Skip to main content

evolutionary_planning/
operators.rs

1//! Variation operators: the genome-agnostic traits ([`Initializer`], [`Mutation`],
2//! [`Crossover`], [`Repair`], [`Selection`]), closure adapters, combinators, and ready-made
3//! operators per representation in the submodules.
4//!
5//! Every trait method is generic over the generator, which keeps the hot path monomorphised;
6//! closures are accepted through `*_fn` adapters that receive `&mut dyn Rng`.
7//!
8//! | Module | Genome |
9//! |---|---|
10//! | [`real`] | `Vec<f64>` within [`Bounds`](real::Bounds) |
11//! | [`discrete`] | bit strings `Vec<bool>` and integer strings `Vec<u32>` |
12//! | [`permutation`] | permutations `Vec<usize>` of `0..n` |
13//! | [`sequence`] | any `Vec<T>`: fixed-length crossovers |
14//! | [`chain`] | GLEAM action chains: variable-length `Vec<T>` and parameterised actions |
15//! | [`selection`] | parent selection over a cost slice |
16
17pub mod chain;
18pub mod discrete;
19pub mod permutation;
20pub mod real;
21pub mod selection;
22pub mod sequence;
23
24use alloc::vec::Vec;
25
26use rand_core::Rng;
27
28use crate::rng::{chance, unit_f64};
29
30pub use selection::Selection;
31
32/// Creates random genomes for an initial population.
33pub trait Initializer<G> {
34    /// Returns a new random genome.
35    fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> G;
36}
37
38/// Changes one genome in place.
39pub trait Mutation<G: ?Sized> {
40    /// Mutates `genome`.
41    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R);
42}
43
44/// Produces two children from two parents.
45pub trait Crossover<G> {
46    /// Returns two children of `a` and `b`.
47    fn crossover<R: Rng + ?Sized>(&mut self, a: &G, b: &G, rng: &mut R) -> [G; 2];
48}
49
50/// Makes a genome valid again after variation (genotypic repair).
51///
52/// Phenotypic repair, which only adjusts the interpretation, belongs in the objective.
53pub trait Repair<G: ?Sized> {
54    /// Repairs `genome` in place.
55    fn repair<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R);
56}
57
58impl<G: ?Sized, M: Mutation<G> + ?Sized> Mutation<G> for &mut M {
59    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
60        (**self).mutate(genome, rng);
61    }
62}
63
64impl<G, X: Crossover<G> + ?Sized> Crossover<G> for &mut X {
65    fn crossover<R: Rng + ?Sized>(&mut self, a: &G, b: &G, rng: &mut R) -> [G; 2] {
66        (**self).crossover(a, b, rng)
67    }
68}
69
70impl<G, I: Initializer<G> + ?Sized> Initializer<G> for &mut I {
71    fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> G {
72        (**self).initialize(rng)
73    }
74}
75
76impl<G: ?Sized, P: Repair<G> + ?Sized> Repair<G> for &mut P {
77    fn repair<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
78        (**self).repair(genome, rng);
79    }
80}
81
82/// The variation operators of algorithms that bring their own selection (NSGA-II,
83/// NSGA-III, MOEA/D, MAP-Elites): initialisation, crossover, mutation and repair.
84#[derive(Debug, Clone, PartialEq)]
85pub struct Variation<I, X, M, P> {
86    /// Creates the initial genomes.
87    pub init: I,
88    /// Recombines two parents.
89    pub crossover: X,
90    /// Mutates a child.
91    pub mutation: M,
92    /// Repairs a child after variation; [`NoRepair`] if none.
93    pub repair: P,
94}
95
96impl<I, X, M, P> Variation<I, X, M, P> {
97    /// Breeds two children of `a` and `b`: crossover with probability `crossover_rate`
98    /// (copies otherwise), each child mutated with probability `mutation_rate`, then repaired.
99    pub fn breed<G, R>(
100        &mut self,
101        a: &G,
102        b: &G,
103        crossover_rate: f64,
104        mutation_rate: f64,
105        rng: &mut R,
106    ) -> [G; 2]
107    where
108        G: Clone,
109        X: Crossover<G>,
110        M: Mutation<G>,
111        P: Repair<G>,
112        R: Rng + ?Sized,
113    {
114        let mut children = if chance(rng, crossover_rate) {
115            self.crossover.crossover(a, b, rng)
116        } else {
117            [a.clone(), b.clone()]
118        };
119
120        for child in &mut children {
121            if chance(rng, mutation_rate) {
122                self.mutation.mutate(child, rng);
123            }
124
125            self.repair.repair(child, rng);
126        }
127
128        children
129    }
130}
131
132/// The repair that changes nothing.
133#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
134pub struct NoRepair;
135
136impl<G: ?Sized> Repair<G> for NoRepair {
137    fn repair<R: Rng + ?Sized>(&mut self, _genome: &mut G, _rng: &mut R) {}
138}
139
140/// The mutation that changes nothing, for crossover-only or selection-only runs.
141#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
142pub struct NoMutation;
143
144impl<G: ?Sized> Mutation<G> for NoMutation {
145    fn mutate<R: Rng + ?Sized>(&mut self, _genome: &mut G, _rng: &mut R) {}
146}
147
148/// The crossover that returns copies of the parents, for mutation-only runs.
149#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
150pub struct NoCrossover;
151
152impl<G: Clone> Crossover<G> for NoCrossover {
153    fn crossover<R: Rng + ?Sized>(&mut self, a: &G, b: &G, _rng: &mut R) -> [G; 2] {
154        [a.clone(), b.clone()]
155    }
156}
157
158/// Calls `f` with a generator behind `&mut dyn Rng`, for the closure adapters.
159fn with_dyn<R: Rng + ?Sized, T>(rng: &mut R, f: impl FnOnce(&mut dyn Rng) -> T) -> T {
160    let mut rng = rng;
161
162    f(&mut rng)
163}
164
165/// Turns a closure `FnMut(&mut dyn Rng) -> G` into an [`Initializer`].
166///
167/// ```
168/// use evolutionary_planning::operators::{Initializer, initializer_fn};
169/// use evolutionary_planning::{SplitMix64, below};
170///
171/// let mut init = initializer_fn(|rng| below(rng, 10));
172/// assert!(init.initialize(&mut SplitMix64::new(1)) < 10);
173/// ```
174pub fn initializer_fn<G, F: FnMut(&mut dyn Rng) -> G>(f: F) -> InitializerFn<F> {
175    InitializerFn(f)
176}
177
178/// A closure used as an [`Initializer`]; created by [`initializer_fn`].
179#[derive(Debug, Clone, Copy)]
180pub struct InitializerFn<F>(F);
181
182impl<G, F: FnMut(&mut dyn Rng) -> G> Initializer<G> for InitializerFn<F> {
183    fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> G {
184        with_dyn(rng, |rng| (self.0)(rng))
185    }
186}
187
188/// Turns a closure `FnMut(&mut G, &mut dyn Rng)` into a [`Mutation`].
189pub fn mutation_fn<G: ?Sized, F: FnMut(&mut G, &mut dyn Rng)>(f: F) -> MutationFn<F> {
190    MutationFn(f)
191}
192
193/// A closure used as a [`Mutation`]; created by [`mutation_fn`].
194#[derive(Debug, Clone, Copy)]
195pub struct MutationFn<F>(F);
196
197impl<G: ?Sized, F: FnMut(&mut G, &mut dyn Rng)> Mutation<G> for MutationFn<F> {
198    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
199        with_dyn(rng, |rng| (self.0)(genome, rng));
200    }
201}
202
203/// Turns a closure `FnMut(&G, &G, &mut dyn Rng) -> [G; 2]` into a [`Crossover`].
204pub fn crossover_fn<G, F: FnMut(&G, &G, &mut dyn Rng) -> [G; 2]>(f: F) -> CrossoverFn<F> {
205    CrossoverFn(f)
206}
207
208/// A closure used as a [`Crossover`]; created by [`crossover_fn`].
209#[derive(Debug, Clone, Copy)]
210pub struct CrossoverFn<F>(F);
211
212impl<G, F: FnMut(&G, &G, &mut dyn Rng) -> [G; 2]> Crossover<G> for CrossoverFn<F> {
213    fn crossover<R: Rng + ?Sized>(&mut self, a: &G, b: &G, rng: &mut R) -> [G; 2] {
214        with_dyn(rng, |rng| (self.0)(a, b, rng))
215    }
216}
217
218/// Turns a closure `FnMut(&mut G, &mut dyn Rng)` into a [`Repair`].
219pub fn repair_fn<G: ?Sized, F: FnMut(&mut G, &mut dyn Rng)>(f: F) -> RepairFn<F> {
220    RepairFn(f)
221}
222
223/// A closure used as a [`Repair`]; created by [`repair_fn`].
224#[derive(Debug, Clone, Copy)]
225pub struct RepairFn<F>(F);
226
227impl<G: ?Sized, F: FnMut(&mut G, &mut dyn Rng)> Repair<G> for RepairFn<F> {
228    fn repair<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
229        with_dyn(rng, |rng| (self.0)(genome, rng));
230    }
231}
232
233/// Applies `a` with probability `weight_a / (weight_a + weight_b)`, otherwise `b`; the
234/// building block of GLEAM-style operator mixes. Nest it for more than two operators, or
235/// use [`mix`].
236///
237/// ```
238/// use evolutionary_planning::operators::{mix, permutation::{Inversion, Swap}};
239///
240/// // Inversions twice as often as swaps.
241/// let _mutation = mix(Inversion, 2.0, Swap, 1.0);
242/// ```
243#[derive(Debug, Clone, Copy, PartialEq)]
244pub struct Mix<A, B> {
245    /// The first operator.
246    pub a: A,
247    /// The second operator.
248    pub b: B,
249    /// The probability of choosing `a`, in `[0, 1]`.
250    pub probability_a: f64,
251}
252
253/// Creates a [`Mix`] choosing `a` and `b` in proportion to their (non-negative) weights.
254///
255/// # Panics
256///
257/// Panics if a weight is negative or both are zero.
258#[must_use]
259pub fn mix<A, B>(a: A, weight_a: f64, b: B, weight_b: f64) -> Mix<A, B> {
260    assert!(
261        weight_a >= 0.0 && weight_b >= 0.0 && weight_a + weight_b > 0.0,
262        "mix weights must be non-negative and not both zero"
263    );
264
265    Mix {
266        a,
267        b,
268        probability_a: weight_a / (weight_a + weight_b),
269    }
270}
271
272impl<G: ?Sized, A: Mutation<G>, B: Mutation<G>> Mutation<G> for Mix<A, B> {
273    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
274        if unit_f64(rng) < self.probability_a {
275            self.a.mutate(genome, rng);
276        } else {
277            self.b.mutate(genome, rng);
278        }
279    }
280}
281
282impl<G, A: Crossover<G>, B: Crossover<G>> Crossover<G> for Mix<A, B> {
283    fn crossover<R: Rng + ?Sized>(&mut self, a: &G, b: &G, rng: &mut R) -> [G; 2] {
284        if unit_f64(rng) < self.probability_a {
285            self.a.crossover(a, b, rng)
286        } else {
287            self.b.crossover(a, b, rng)
288        }
289    }
290}
291
292/// Applies `first`, then `second`.
293#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
294pub struct Then<A, B> {
295    /// Applied first.
296    pub first: A,
297    /// Applied to the result of `first`.
298    pub second: B,
299}
300
301impl<G: ?Sized, A: Mutation<G>, B: Mutation<G>> Mutation<G> for Then<A, B> {
302    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
303        self.first.mutate(genome, rng);
304        self.second.mutate(genome, rng);
305    }
306}
307
308impl<G: ?Sized, A: Repair<G>, B: Repair<G>> Repair<G> for Then<A, B> {
309    fn repair<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
310        self.first.repair(genome, rng);
311        self.second.repair(genome, rng);
312    }
313}
314
315/// Applies `inner` with probability `probability`, otherwise leaves the genome unchanged.
316#[derive(Debug, Clone, Copy, PartialEq)]
317pub struct Sometimes<M> {
318    /// The wrapped mutation.
319    pub inner: M,
320    /// The probability of applying it, in `[0, 1]`.
321    pub probability: f64,
322}
323
324impl<G: ?Sized, M: Mutation<G>> Mutation<G> for Sometimes<M> {
325    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
326        if chance(rng, self.probability) {
327            self.inner.mutate(genome, rng);
328        }
329    }
330}
331
332/// An initialiser that yields caller-supplied seed genomes first (for example previous plans
333/// or heuristic solutions), then falls back to `inner`.
334///
335/// Jakob (2021) advises seeding at most about 20 % of the initial population so it still
336/// covers the search space; [`Seeded::new`] keeps at most `max_fraction` of
337/// `population_size` seeds.
338#[derive(Debug, Clone, PartialEq)]
339pub struct Seeded<G, I> {
340    /// The remaining seeds, yielded from the back (stored reversed).
341    seeds: Vec<G>,
342    /// The initialiser used once the seeds run out.
343    inner: I,
344}
345
346impl<G, I> Seeded<G, I> {
347    /// Keeps the first `floor(max_fraction * population_size)` (at least one, if any) of
348    /// `seeds`, in order.
349    #[must_use]
350    pub fn new(mut seeds: Vec<G>, inner: I, population_size: usize, max_fraction: f64) -> Self {
351        #[expect(
352            clippy::cast_possible_truncation,
353            clippy::cast_sign_loss,
354            clippy::cast_precision_loss,
355            reason = "a population fraction, clamped to [0, population_size]"
356        )]
357        let cap = ((max_fraction.clamp(0.0, 1.0) * population_size as f64) as usize).max(1);
358        seeds.truncate(cap);
359        seeds.reverse();
360
361        Self { seeds, inner }
362    }
363}
364
365impl<G, I: Initializer<G>> Initializer<G> for Seeded<G, I> {
366    fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> G {
367        match self.seeds.pop() {
368            Some(seed) => seed,
369            None => self.inner.initialize(rng),
370        }
371    }
372}
373
374#[cfg(test)]
375mod tests {
376    use alloc::vec;
377
378    use super::*;
379    use crate::SplitMix64;
380
381    /// A mix with weight zero on one side always picks the other.
382    #[test]
383    fn mix_respects_weights() {
384        let mut rng = SplitMix64::new(1);
385        let mut m = mix(
386            mutation_fn(|x: &mut u32, _| *x += 1),
387            1.0,
388            mutation_fn(|x: &mut u32, _| *x += 100),
389            0.0,
390        );
391        let mut value = 0;
392        for _ in 0..10 {
393            m.mutate(&mut value, &mut rng);
394        }
395
396        assert_eq!(value, 10);
397    }
398
399    /// Seeds come first and are capped.
400    #[test]
401    fn seeded_caps_and_orders() {
402        let mut rng = SplitMix64::new(1);
403        let mut init = Seeded::new(vec![1, 2, 3], initializer_fn(|_| 0), 10, 0.2);
404        let got: Vec<i32> = (0..4).map(|_| init.initialize(&mut rng)).collect();
405
406        assert_eq!(got, [1, 2, 0, 0]);
407    }
408}