tycho-solver
Version:
Evolutionary computation and optimization library
39 lines (38 loc) • 2.37 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReplacementOperatorImpl = void 0;
// Generational replacement: replace entire population with offspring, insert elites if provided
class ReplacementOperatorImpl {
constructor(options) {
this.elitismOperator = options === null || options === void 0 ? void 0 : options.elitismOperator;
this.eliteCount = (options === null || options === void 0 ? void 0 : options.eliteCount) || 0;
this.fitnessFunction = options === null || options === void 0 ? void 0 : options.fitnessFunction;
}
// If elites are provided, insert them into the new population (replace worst)
replace(oldPopulation, offspring, fitnesses) {
return __awaiter(this, void 0, void 0, function* () {
let newPop = offspring.slice(0, oldPopulation.length);
if (this.elitismOperator && this.eliteCount > 0 && this.fitnessFunction) {
// Evaluate fitness for newPop
const popWithFitness = yield Promise.all(newPop.map((ind, idx) => __awaiter(this, void 0, void 0, function* () { return ({ ind, fit: yield this.fitnessFunction(ind), idx }); })));
popWithFitness.sort((a, b) => a.fit - b.fit); // ascending, worst first
// Get elites from old population
const elites = this.elitismOperator.apply(oldPopulation, fitnesses, this.eliteCount);
for (let i = 0; i < elites.length; ++i) {
newPop[popWithFitness[i].idx] = elites[i];
}
}
return newPop;
});
}
}
exports.ReplacementOperatorImpl = ReplacementOperatorImpl;