tycho-solver
Version:
Evolutionary computation and optimization library
69 lines • 2.6 kB
JavaScript
import { LocalSearch } from '../../search/localSearch';
import { memeticLoop } from './components/LoopOperator';
import { seededRandom } from '../../utils/rng';
// Helper: population initialization
async function initializePopulation(config) {
const population = [];
for (let i = 0; i < config.populationSize; i++) {
const result = config.initializationOperator.initialize({
populationSize: 1,
individualFactory: config.individualFactory
});
const genome = Array.isArray(result) ? result[0] : result;
const resolvedGenome = genome instanceof Promise ? await genome : genome;
const fitness = await config.evaluationOperator.evaluate(resolvedGenome);
population.push({ genome: resolvedGenome, fitness });
}
return population;
}
// Helper: local search application
async function applyLocalSearch(genome, config, localSearcher) {
const { objectiveFunction, neighborhoodFunction, localSearchOptions } = config;
const result = await localSearcher.search(genome, objectiveFunction, neighborhoodFunction, localSearchOptions);
return result.solution;
}
export class MemeticAlgorithm {
population = [];
config;
localSearcher;
bestIndividual = null;
rng;
constructor(config) {
this.config = config;
this.localSearcher = new LocalSearch();
this.rng = seededRandom();
}
async initializePopulation() {
this.population = await initializePopulation(this.config);
this.updateBest();
}
async evolve() {
if (this.population.length === 0) {
await this.initializePopulation();
}
// Use the new LoopOperator for orchestration
this.bestIndividual = await memeticLoop(this.population, this.config, this.localSearcher, (pop) => {
if (!pop.length)
return null;
return pop.reduce((best, ind) => ind.fitness > best.fitness ? ind : best);
}, applyLocalSearch, this.rng);
return this.getBestIndividual();
}
getBestIndividual() {
if (!this.bestIndividual && this.population.length > 0) {
this.updateBest();
}
return this.bestIndividual;
}
updateBest() {
if (this.population.length === 0)
return;
this.bestIndividual = this.population.reduce((best, ind) => ind.fitness > best.fitness ? ind : best);
}
getPopulation() {
return this.population;
}
}
// Export components for advanced usage
export * from './components';
//# sourceMappingURL=index.js.map