Skip to main content

evolutionary_planning/
ga.rs

1//! Genetic algorithms: generational with elitism, and steady state.
2//!
3//! ```mermaid
4//! graph LR
5//!     init[initialise and evaluate] --> select[select parents]
6//!     select --> cross[crossover with rate]
7//!     cross --> mutate[mutate with rate]
8//!     mutate --> repair[repair]
9//!     repair --> eval[evaluate]
10//!     eval --> refine[optional local search]
11//!     refine --> replace[replace: generational with elites, or steady state]
12//!     replace --> select
13//! ```
14//!
15//! # Examples
16//!
17//! OneMax on 32 bits:
18//!
19//! ```
20//! use evolutionary_planning::ga::{Config, Ga, Operators};
21//! use evolutionary_planning::operators::{discrete::{BitFlip, RandomBits}, selection::Tournament, sequence::UniformCrossover, NoRepair};
22//! use evolutionary_planning::{Limits, SplitMix64};
23//!
24//! let mut ga = Ga::new(Config::default(), Operators {
25//!     init: RandomBits { len: 32 },
26//!     selection: Tournament { size: 2 },
27//!     crossover: UniformCrossover::default(),
28//!     mutation: BitFlip::default(),
29//!     repair: NoRepair,
30//! });
31//! let mut zeros = |bits: &Vec<bool>| bits.iter().filter(|&&b| !b).count() as f64;
32//! let outcome = ga.run(&mut zeros, &mut Limits::evaluations(20_000).with_target(0.0), &mut (), &mut SplitMix64::new(1));
33//! assert_eq!(outcome.best_cost(), 0.0);
34//! ```
35
36use 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/// How offspring enter the population.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum Scheme {
48    /// Each generation replaces the whole population except the
49    /// [`Config::elitism`] best, which are copied unchanged.
50    Generational,
51    /// Each step breeds two offspring; each replaces the current worst individual. With
52    /// `only_if_better`, only if it is strictly cheaper. One generation is counted per
53    /// `population_size` offspring.
54    SteadyState {
55        /// Replace only when the offspring is strictly cheaper than the worst.
56        only_if_better: bool,
57    },
58}
59
60/// Parameters of a [`Ga`] run.
61#[derive(Debug, Clone, Copy, PartialEq)]
62pub struct Config {
63    /// The number of individuals, at least `2`.
64    pub population_size: usize,
65    /// Generational scheme: the number of best individuals copied unchanged into the next
66    /// generation (clamped to `population_size - 1`, so every generation breeds). Ignored by
67    /// the steady-state scheme, which is elitist by construction.
68    pub elitism: usize,
69    /// The probability that a pair of parents is recombined; otherwise the children are
70    /// copies.
71    pub crossover_rate: f64,
72    /// The probability that a child is mutated at all; the mutation operator decides how
73    /// much (for example a per-gene rate).
74    pub mutation_rate: f64,
75    /// Generational or steady state.
76    pub scheme: Scheme,
77}
78
79impl Default for Config {
80    /// 100 individuals, one elite, crossover rate 0.9, every child mutated, generational.
81    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/// The operators a [`Ga`] breeds with.
93#[derive(Debug, Clone, PartialEq)]
94pub struct Operators<I, S, X, M, P> {
95    /// Creates the initial population.
96    pub init: I,
97    /// Picks parents.
98    pub selection: S,
99    /// Recombines two parents.
100    pub crossover: X,
101    /// Mutates a child.
102    pub mutation: M,
103    /// Repairs a child after variation; [`NoRepair`](crate::operators::NoRepair) if none.
104    pub repair: P,
105}
106
107/// A genetic algorithm over any genome type.
108#[derive(Debug, Clone, PartialEq)]
109pub struct Ga<I, S, X, M, P> {
110    /// The run parameters.
111    pub config: Config,
112    /// The breeding operators.
113    pub operators: Operators<I, S, X, M, P>,
114}
115
116/// Something applied to every freshly evaluated offspring: nothing for a plain GA, a local
117/// search for the memetic variant.
118pub(crate) trait Refine<G> {
119    /// Returns the (possibly improved) offspring; evaluations go through `evaluator`.
120    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
134/// The refinement that changes nothing.
135pub(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    /// Creates a GA.
157    #[must_use]
158    pub fn new(config: Config, operators: Operators<I, S, X, M, P>) -> Self {
159        Self { config, operators }
160    }
161
162    /// Runs the GA from a random initial population until the budget stops it.
163    ///
164    /// The returned [`Outcome::best`] is the best genome ever evaluated; the population is the
165    /// last complete one.
166    ///
167    /// # Panics
168    ///
169    /// Panics if [`Config::population_size`] is below `2`.
170    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    /// Like [`Ga::run`], but the initial population starts with `seeds` (truncated to the
193    /// population size) and is filled up by the initialiser.
194    ///
195    /// # Panics
196    ///
197    /// Panics if [`Config::population_size`] is below `2`.
198    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    /// Runs the GA as a memetic algorithm: every evaluated offspring (and initial member)
224    /// goes through `memetic`'s local search according to its schedule. Local search
225    /// evaluations count against the same budget.
226    ///
227    /// # Panics
228    ///
229    /// Panics if [`Config::population_size`] is below `2`.
230    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    /// The shared driver of the plain and the memetic GA.
257    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    /// Creates and evaluates the initial population; `None` if the budget ran out first.
298    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    /// Runs generations until the budget is exhausted.
331    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    /// Runs steady-state steps until the budget is exhausted.
383    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    /// Produces two children of `a` and `b`: crossover, mutation and repair.
432    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
458/// Replaces the worst individual (the last among equals) by `newcomer`, if allowed.
459fn 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
475/// The cheapest cost in a population.
476pub(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
483/// Ends a run stopped by the budget.
484fn 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;