1use alloc::vec::Vec;
37
38use rand_core::Rng;
39
40use crate::evaluator::Evaluator;
41use crate::operators::{Crossover, Initializer, Mutation, Repair, Selection};
42use crate::rng::chance;
43use crate::{Budget, Individual, Objective, Observer, Outcome, Stats, Stop};
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum Scheme {
48 Generational,
51 SteadyState {
55 only_if_better: bool,
57 },
58}
59
60#[derive(Debug, Clone, Copy, PartialEq)]
62pub struct Config {
63 pub population_size: usize,
65 pub elitism: usize,
69 pub crossover_rate: f64,
72 pub mutation_rate: f64,
75 pub scheme: Scheme,
77}
78
79impl Default for Config {
80 fn default() -> Self {
82 Self {
83 population_size: 100,
84 elitism: 1,
85 crossover_rate: 0.9,
86 mutation_rate: 1.0,
87 scheme: Scheme::Generational,
88 }
89 }
90}
91
92#[derive(Debug, Clone, PartialEq)]
94pub struct Operators<I, S, X, M, P> {
95 pub init: I,
97 pub selection: S,
99 pub crossover: X,
101 pub mutation: M,
103 pub repair: P,
105}
106
107#[derive(Debug, Clone, PartialEq)]
109pub struct Ga<I, S, X, M, P> {
110 pub config: Config,
112 pub operators: Operators<I, S, X, M, P>,
114}
115
116pub(crate) trait Refine<G> {
119 fn refine<O, B, Obs, R>(
121 &mut self,
122 child: Individual<G>,
123 evaluator: &mut Evaluator<'_, G, O, B, Obs>,
124 rng: &mut R,
125 ) -> Individual<G>
126 where
127 G: Clone,
128 O: Objective<G> + ?Sized,
129 B: Budget<Stats> + ?Sized,
130 Obs: Observer + ?Sized,
131 R: Rng + ?Sized;
132}
133
134pub(crate) struct NoRefine;
136
137impl<G> Refine<G> for NoRefine {
138 fn refine<O, B, Obs, R>(
139 &mut self,
140 child: Individual<G>,
141 _evaluator: &mut Evaluator<'_, G, O, B, Obs>,
142 _rng: &mut R,
143 ) -> Individual<G>
144 where
145 G: Clone,
146 O: Objective<G> + ?Sized,
147 B: Budget<Stats> + ?Sized,
148 Obs: Observer + ?Sized,
149 R: Rng + ?Sized,
150 {
151 child
152 }
153}
154
155impl<I, S, X, M, P> Ga<I, S, X, M, P> {
156 #[must_use]
158 pub fn new(config: Config, operators: Operators<I, S, X, M, P>) -> Self {
159 Self { config, operators }
160 }
161
162 pub fn run<G, O, B, Obs, R>(
171 &mut self,
172 objective: &mut O,
173 budget: &mut B,
174 observer: &mut Obs,
175 rng: &mut R,
176 ) -> Outcome<G>
177 where
178 G: Clone,
179 I: Initializer<G>,
180 S: Selection,
181 X: Crossover<G>,
182 M: Mutation<G>,
183 P: Repair<G>,
184 O: Objective<G> + ?Sized,
185 B: Budget<Stats> + ?Sized,
186 Obs: Observer + ?Sized,
187 R: Rng + ?Sized,
188 {
189 self.run_from(Vec::new(), objective, budget, observer, rng)
190 }
191
192 pub fn run_from<G, O, B, Obs, R>(
199 &mut self,
200 seeds: Vec<G>,
201 objective: &mut O,
202 budget: &mut B,
203 observer: &mut Obs,
204 rng: &mut R,
205 ) -> Outcome<G>
206 where
207 G: Clone,
208 I: Initializer<G>,
209 S: Selection,
210 X: Crossover<G>,
211 M: Mutation<G>,
212 P: Repair<G>,
213 O: Objective<G> + ?Sized,
214 B: Budget<Stats> + ?Sized,
215 Obs: Observer + ?Sized,
216 R: Rng + ?Sized,
217 {
218 let mut evaluator = Evaluator::new(objective, budget, observer);
219
220 self.evolve(seeds, &mut evaluator, &mut NoRefine, rng)
221 }
222
223 pub fn run_memetic<G, L, O, B, Obs, R>(
231 &mut self,
232 memetic: &mut crate::memetic::Memetic<L>,
233 objective: &mut O,
234 budget: &mut B,
235 observer: &mut Obs,
236 rng: &mut R,
237 ) -> Outcome<G>
238 where
239 G: Clone,
240 I: Initializer<G>,
241 S: Selection,
242 X: Crossover<G>,
243 M: Mutation<G>,
244 P: Repair<G>,
245 L: crate::memetic::LocalSearch<G>,
246 O: Objective<G> + ?Sized,
247 B: Budget<Stats> + ?Sized,
248 Obs: Observer + ?Sized,
249 R: Rng + ?Sized,
250 {
251 let mut evaluator = Evaluator::new(objective, budget, observer);
252
253 self.evolve(Vec::new(), &mut evaluator, memetic, rng)
254 }
255
256 pub(crate) fn evolve<G, O, B, Obs, F, R>(
258 &mut self,
259 seeds: Vec<G>,
260 evaluator: &mut Evaluator<'_, G, O, B, Obs>,
261 refine: &mut F,
262 rng: &mut R,
263 ) -> Outcome<G>
264 where
265 G: Clone,
266 I: Initializer<G>,
267 S: Selection,
268 X: Crossover<G>,
269 M: Mutation<G>,
270 P: Repair<G>,
271 O: Objective<G> + ?Sized,
272 B: Budget<Stats> + ?Sized,
273 Obs: Observer + ?Sized,
274 F: Refine<G>,
275 R: Rng + ?Sized,
276 {
277 assert!(
278 self.config.population_size >= 2,
279 "a GA needs at least two individuals"
280 );
281
282 let Some(mut population) = self.initial_population(seeds, evaluator, refine, rng) else {
283 return finish(evaluator, Vec::new());
284 };
285
286 evaluator.end_generation(population_best(&population));
287 match self.config.scheme {
288 Scheme::Generational => self.generational(&mut population, evaluator, refine, rng),
289 Scheme::SteadyState { only_if_better } => {
290 self.steady_state(&mut population, only_if_better, evaluator, refine, rng);
291 }
292 }
293
294 finish(evaluator, population)
295 }
296
297 fn initial_population<G, O, B, Obs, F, R>(
299 &mut self,
300 seeds: Vec<G>,
301 evaluator: &mut Evaluator<'_, G, O, B, Obs>,
302 refine: &mut F,
303 rng: &mut R,
304 ) -> Option<Vec<Individual<G>>>
305 where
306 G: Clone,
307 I: Initializer<G>,
308 O: Objective<G> + ?Sized,
309 B: Budget<Stats> + ?Sized,
310 Obs: Observer + ?Sized,
311 F: Refine<G>,
312 R: Rng + ?Sized,
313 {
314 let size = self.config.population_size;
315 let mut genomes = seeds;
316 genomes.truncate(size);
317 while genomes.len() < size {
318 genomes.push(self.operators.init.initialize(rng));
319 }
320
321 let mut population = Vec::with_capacity(size);
322 for genome in genomes {
323 let individual = evaluator.individual(genome)?;
324 population.push(refine.refine(individual, evaluator, rng));
325 }
326
327 Some(population)
328 }
329
330 fn generational<G, O, B, Obs, F, R>(
332 &mut self,
333 population: &mut Vec<Individual<G>>,
334 evaluator: &mut Evaluator<'_, G, O, B, Obs>,
335 refine: &mut F,
336 rng: &mut R,
337 ) where
338 G: Clone,
339 S: Selection,
340 X: Crossover<G>,
341 M: Mutation<G>,
342 P: Repair<G>,
343 O: Objective<G> + ?Sized,
344 B: Budget<Stats> + ?Sized,
345 Obs: Observer + ?Sized,
346 F: Refine<G>,
347 R: Rng + ?Sized,
348 {
349 let size = self.config.population_size;
350 let mut parents = Vec::with_capacity(2);
351 loop {
352 crate::cost::sort_population(population);
353 let costs: Vec<f64> = population.iter().map(|i| i.cost).collect();
354 let mut next: Vec<Individual<G>> =
355 population[..self.config.elitism.min(size - 1)].to_vec();
356 while next.len() < size {
357 parents.clear();
358 self.operators
359 .selection
360 .select(&costs, 2, rng, &mut parents);
361 for child in self.breed(
362 &population[parents[0]].genome,
363 &population[parents[1]].genome,
364 rng,
365 ) {
366 if next.len() == size {
367 break;
368 }
369
370 let Some(individual) = evaluator.individual(child) else {
371 return;
372 };
373 next.push(refine.refine(individual, evaluator, rng));
374 }
375 }
376
377 *population = next;
378 evaluator.end_generation(population_best(population));
379 }
380 }
381
382 fn steady_state<G, O, B, Obs, F, R>(
384 &mut self,
385 population: &mut [Individual<G>],
386 only_if_better: bool,
387 evaluator: &mut Evaluator<'_, G, O, B, Obs>,
388 refine: &mut F,
389 rng: &mut R,
390 ) where
391 G: Clone,
392 S: Selection,
393 X: Crossover<G>,
394 M: Mutation<G>,
395 P: Repair<G>,
396 O: Objective<G> + ?Sized,
397 B: Budget<Stats> + ?Sized,
398 Obs: Observer + ?Sized,
399 F: Refine<G>,
400 R: Rng + ?Sized,
401 {
402 let mut parents = Vec::with_capacity(2);
403 let mut offspring_in_generation = 0;
404 loop {
405 let costs: Vec<f64> = population.iter().map(|i| i.cost).collect();
406 parents.clear();
407 self.operators
408 .selection
409 .select(&costs, 2, rng, &mut parents);
410 let children = self.breed(
411 &population[parents[0]].genome,
412 &population[parents[1]].genome,
413 rng,
414 );
415 for child in children {
416 let Some(individual) = evaluator.individual(child) else {
417 return;
418 };
419
420 let individual = refine.refine(individual, evaluator, rng);
421 replace_worst(population, individual, only_if_better);
422 offspring_in_generation += 1;
423 if offspring_in_generation == population.len() {
424 offspring_in_generation = 0;
425 evaluator.end_generation(population_best(population));
426 }
427 }
428 }
429 }
430
431 fn breed<G, R>(&mut self, a: &G, b: &G, rng: &mut R) -> [G; 2]
433 where
434 G: Clone,
435 X: Crossover<G>,
436 M: Mutation<G>,
437 P: Repair<G>,
438 R: Rng + ?Sized,
439 {
440 let mut children = if chance(rng, self.config.crossover_rate) {
441 self.operators.crossover.crossover(a, b, rng)
442 } else {
443 [a.clone(), b.clone()]
444 };
445
446 for child in &mut children {
447 if chance(rng, self.config.mutation_rate) {
448 self.operators.mutation.mutate(child, rng);
449 }
450
451 self.operators.repair.repair(child, rng);
452 }
453
454 children
455 }
456}
457
458fn replace_worst<G>(
460 population: &mut [Individual<G>],
461 newcomer: Individual<G>,
462 only_if_better: bool,
463) {
464 let worst = population
465 .iter()
466 .enumerate()
467 .max_by(|a, b| a.1.cost.total_cmp(&b.1.cost).then(a.0.cmp(&b.0)))
468 .map_or(0, |(index, _)| index);
469
470 if !only_if_better || newcomer.cost < population[worst].cost {
471 population[worst] = newcomer;
472 }
473}
474
475pub(crate) fn population_best<G>(population: &[Individual<G>]) -> f64 {
477 population
478 .iter()
479 .map(|i| i.cost)
480 .fold(f64::INFINITY, f64::min)
481}
482
483fn finish<G: Clone, O, B, Obs>(
485 evaluator: &mut Evaluator<'_, G, O, B, Obs>,
486 population: Vec<Individual<G>>,
487) -> Outcome<G>
488where
489 O: Objective<G> + ?Sized,
490 B: Budget<Stats> + ?Sized,
491 Obs: Observer + ?Sized,
492{
493 evaluator.outcome(population, Stop::Budget)
494}
495
496#[cfg(test)]
497mod tests;