evolutionary-planning 0.1.0

Evolutionary planning for no_std: genetic algorithms, evolution strategies, CMA-ES and multi-objective evolutionary search over plans, paths and trajectories
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//! Variation operators: the genome-agnostic traits ([`Initializer`], [`Mutation`],
//! [`Crossover`], [`Repair`], [`Selection`]), closure adapters, combinators, and ready-made
//! operators per representation in the submodules.
//!
//! Every trait method is generic over the generator, which keeps the hot path monomorphised;
//! closures are accepted through `*_fn` adapters that receive `&mut dyn Rng`.
//!
//! | Module | Genome |
//! |---|---|
//! | [`real`] | `Vec<f64>` within [`Bounds`](real::Bounds) |
//! | [`discrete`] | bit strings `Vec<bool>` and integer strings `Vec<u32>` |
//! | [`permutation`] | permutations `Vec<usize>` of `0..n` |
//! | [`sequence`] | any `Vec<T>`: fixed-length crossovers |
//! | [`chain`] | GLEAM action chains: variable-length `Vec<T>` and parameterised actions |
//! | [`selection`] | parent selection over a cost slice |

pub mod chain;
pub mod discrete;
pub mod permutation;
pub mod real;
pub mod selection;
pub mod sequence;

use alloc::vec::Vec;

use rand_core::Rng;

use crate::rng::{chance, unit_f64};

pub use selection::Selection;

/// Creates random genomes for an initial population.
pub trait Initializer<G> {
    /// Returns a new random genome.
    fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> G;
}

/// Changes one genome in place.
pub trait Mutation<G: ?Sized> {
    /// Mutates `genome`.
    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R);
}

/// Produces two children from two parents.
pub trait Crossover<G> {
    /// Returns two children of `a` and `b`.
    fn crossover<R: Rng + ?Sized>(&mut self, a: &G, b: &G, rng: &mut R) -> [G; 2];
}

/// Makes a genome valid again after variation (genotypic repair).
///
/// Phenotypic repair, which only adjusts the interpretation, belongs in the objective.
pub trait Repair<G: ?Sized> {
    /// Repairs `genome` in place.
    fn repair<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R);
}

impl<G: ?Sized, M: Mutation<G> + ?Sized> Mutation<G> for &mut M {
    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
        (**self).mutate(genome, rng);
    }
}

impl<G, X: Crossover<G> + ?Sized> Crossover<G> for &mut X {
    fn crossover<R: Rng + ?Sized>(&mut self, a: &G, b: &G, rng: &mut R) -> [G; 2] {
        (**self).crossover(a, b, rng)
    }
}

impl<G, I: Initializer<G> + ?Sized> Initializer<G> for &mut I {
    fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> G {
        (**self).initialize(rng)
    }
}

impl<G: ?Sized, P: Repair<G> + ?Sized> Repair<G> for &mut P {
    fn repair<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
        (**self).repair(genome, rng);
    }
}

/// The variation operators of algorithms that bring their own selection (NSGA-II,
/// NSGA-III, MOEA/D, MAP-Elites): initialisation, crossover, mutation and repair.
#[derive(Debug, Clone, PartialEq)]
pub struct Variation<I, X, M, P> {
    /// Creates the initial genomes.
    pub init: I,
    /// Recombines two parents.
    pub crossover: X,
    /// Mutates a child.
    pub mutation: M,
    /// Repairs a child after variation; [`NoRepair`] if none.
    pub repair: P,
}

impl<I, X, M, P> Variation<I, X, M, P> {
    /// Breeds two children of `a` and `b`: crossover with probability `crossover_rate`
    /// (copies otherwise), each child mutated with probability `mutation_rate`, then repaired.
    pub fn breed<G, R>(
        &mut self,
        a: &G,
        b: &G,
        crossover_rate: f64,
        mutation_rate: f64,
        rng: &mut R,
    ) -> [G; 2]
    where
        G: Clone,
        X: Crossover<G>,
        M: Mutation<G>,
        P: Repair<G>,
        R: Rng + ?Sized,
    {
        let mut children = if chance(rng, crossover_rate) {
            self.crossover.crossover(a, b, rng)
        } else {
            [a.clone(), b.clone()]
        };

        for child in &mut children {
            if chance(rng, mutation_rate) {
                self.mutation.mutate(child, rng);
            }

            self.repair.repair(child, rng);
        }

        children
    }
}

/// The repair that changes nothing.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct NoRepair;

impl<G: ?Sized> Repair<G> for NoRepair {
    fn repair<R: Rng + ?Sized>(&mut self, _genome: &mut G, _rng: &mut R) {}
}

/// The mutation that changes nothing, for crossover-only or selection-only runs.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct NoMutation;

impl<G: ?Sized> Mutation<G> for NoMutation {
    fn mutate<R: Rng + ?Sized>(&mut self, _genome: &mut G, _rng: &mut R) {}
}

/// The crossover that returns copies of the parents, for mutation-only runs.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct NoCrossover;

impl<G: Clone> Crossover<G> for NoCrossover {
    fn crossover<R: Rng + ?Sized>(&mut self, a: &G, b: &G, _rng: &mut R) -> [G; 2] {
        [a.clone(), b.clone()]
    }
}

/// Calls `f` with a generator behind `&mut dyn Rng`, for the closure adapters.
fn with_dyn<R: Rng + ?Sized, T>(rng: &mut R, f: impl FnOnce(&mut dyn Rng) -> T) -> T {
    let mut rng = rng;

    f(&mut rng)
}

/// Turns a closure `FnMut(&mut dyn Rng) -> G` into an [`Initializer`].
///
/// ```
/// use evolutionary_planning::operators::{Initializer, initializer_fn};
/// use evolutionary_planning::{SplitMix64, below};
///
/// let mut init = initializer_fn(|rng| below(rng, 10));
/// assert!(init.initialize(&mut SplitMix64::new(1)) < 10);
/// ```
pub fn initializer_fn<G, F: FnMut(&mut dyn Rng) -> G>(f: F) -> InitializerFn<F> {
    InitializerFn(f)
}

/// A closure used as an [`Initializer`]; created by [`initializer_fn`].
#[derive(Debug, Clone, Copy)]
pub struct InitializerFn<F>(F);

impl<G, F: FnMut(&mut dyn Rng) -> G> Initializer<G> for InitializerFn<F> {
    fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> G {
        with_dyn(rng, |rng| (self.0)(rng))
    }
}

/// Turns a closure `FnMut(&mut G, &mut dyn Rng)` into a [`Mutation`].
pub fn mutation_fn<G: ?Sized, F: FnMut(&mut G, &mut dyn Rng)>(f: F) -> MutationFn<F> {
    MutationFn(f)
}

/// A closure used as a [`Mutation`]; created by [`mutation_fn`].
#[derive(Debug, Clone, Copy)]
pub struct MutationFn<F>(F);

impl<G: ?Sized, F: FnMut(&mut G, &mut dyn Rng)> Mutation<G> for MutationFn<F> {
    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
        with_dyn(rng, |rng| (self.0)(genome, rng));
    }
}

/// Turns a closure `FnMut(&G, &G, &mut dyn Rng) -> [G; 2]` into a [`Crossover`].
pub fn crossover_fn<G, F: FnMut(&G, &G, &mut dyn Rng) -> [G; 2]>(f: F) -> CrossoverFn<F> {
    CrossoverFn(f)
}

/// A closure used as a [`Crossover`]; created by [`crossover_fn`].
#[derive(Debug, Clone, Copy)]
pub struct CrossoverFn<F>(F);

impl<G, F: FnMut(&G, &G, &mut dyn Rng) -> [G; 2]> Crossover<G> for CrossoverFn<F> {
    fn crossover<R: Rng + ?Sized>(&mut self, a: &G, b: &G, rng: &mut R) -> [G; 2] {
        with_dyn(rng, |rng| (self.0)(a, b, rng))
    }
}

/// Turns a closure `FnMut(&mut G, &mut dyn Rng)` into a [`Repair`].
pub fn repair_fn<G: ?Sized, F: FnMut(&mut G, &mut dyn Rng)>(f: F) -> RepairFn<F> {
    RepairFn(f)
}

/// A closure used as a [`Repair`]; created by [`repair_fn`].
#[derive(Debug, Clone, Copy)]
pub struct RepairFn<F>(F);

impl<G: ?Sized, F: FnMut(&mut G, &mut dyn Rng)> Repair<G> for RepairFn<F> {
    fn repair<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
        with_dyn(rng, |rng| (self.0)(genome, rng));
    }
}

/// Applies `a` with probability `weight_a / (weight_a + weight_b)`, otherwise `b`; the
/// building block of GLEAM-style operator mixes. Nest it for more than two operators, or
/// use [`mix`].
///
/// ```
/// use evolutionary_planning::operators::{mix, permutation::{Inversion, Swap}};
///
/// // Inversions twice as often as swaps.
/// let _mutation = mix(Inversion, 2.0, Swap, 1.0);
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Mix<A, B> {
    /// The first operator.
    pub a: A,
    /// The second operator.
    pub b: B,
    /// The probability of choosing `a`, in `[0, 1]`.
    pub probability_a: f64,
}

/// Creates a [`Mix`] choosing `a` and `b` in proportion to their (non-negative) weights.
///
/// # Panics
///
/// Panics if a weight is negative or both are zero.
#[must_use]
pub fn mix<A, B>(a: A, weight_a: f64, b: B, weight_b: f64) -> Mix<A, B> {
    assert!(
        weight_a >= 0.0 && weight_b >= 0.0 && weight_a + weight_b > 0.0,
        "mix weights must be non-negative and not both zero"
    );

    Mix {
        a,
        b,
        probability_a: weight_a / (weight_a + weight_b),
    }
}

impl<G: ?Sized, A: Mutation<G>, B: Mutation<G>> Mutation<G> for Mix<A, B> {
    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
        if unit_f64(rng) < self.probability_a {
            self.a.mutate(genome, rng);
        } else {
            self.b.mutate(genome, rng);
        }
    }
}

impl<G, A: Crossover<G>, B: Crossover<G>> Crossover<G> for Mix<A, B> {
    fn crossover<R: Rng + ?Sized>(&mut self, a: &G, b: &G, rng: &mut R) -> [G; 2] {
        if unit_f64(rng) < self.probability_a {
            self.a.crossover(a, b, rng)
        } else {
            self.b.crossover(a, b, rng)
        }
    }
}

/// Applies `first`, then `second`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Then<A, B> {
    /// Applied first.
    pub first: A,
    /// Applied to the result of `first`.
    pub second: B,
}

impl<G: ?Sized, A: Mutation<G>, B: Mutation<G>> Mutation<G> for Then<A, B> {
    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
        self.first.mutate(genome, rng);
        self.second.mutate(genome, rng);
    }
}

impl<G: ?Sized, A: Repair<G>, B: Repair<G>> Repair<G> for Then<A, B> {
    fn repair<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
        self.first.repair(genome, rng);
        self.second.repair(genome, rng);
    }
}

/// Applies `inner` with probability `probability`, otherwise leaves the genome unchanged.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Sometimes<M> {
    /// The wrapped mutation.
    pub inner: M,
    /// The probability of applying it, in `[0, 1]`.
    pub probability: f64,
}

impl<G: ?Sized, M: Mutation<G>> Mutation<G> for Sometimes<M> {
    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut G, rng: &mut R) {
        if chance(rng, self.probability) {
            self.inner.mutate(genome, rng);
        }
    }
}

/// An initialiser that yields caller-supplied seed genomes first (for example previous plans
/// or heuristic solutions), then falls back to `inner`.
///
/// Jakob (2021) advises seeding at most about 20 % of the initial population so it still
/// covers the search space; [`Seeded::new`] keeps at most `max_fraction` of
/// `population_size` seeds.
#[derive(Debug, Clone, PartialEq)]
pub struct Seeded<G, I> {
    /// The remaining seeds, yielded from the back (stored reversed).
    seeds: Vec<G>,
    /// The initialiser used once the seeds run out.
    inner: I,
}

impl<G, I> Seeded<G, I> {
    /// Keeps the first `floor(max_fraction * population_size)` (at least one, if any) of
    /// `seeds`, in order.
    #[must_use]
    pub fn new(mut seeds: Vec<G>, inner: I, population_size: usize, max_fraction: f64) -> Self {
        #[expect(
            clippy::cast_possible_truncation,
            clippy::cast_sign_loss,
            clippy::cast_precision_loss,
            reason = "a population fraction, clamped to [0, population_size]"
        )]
        let cap = ((max_fraction.clamp(0.0, 1.0) * population_size as f64) as usize).max(1);
        seeds.truncate(cap);
        seeds.reverse();

        Self { seeds, inner }
    }
}

impl<G, I: Initializer<G>> Initializer<G> for Seeded<G, I> {
    fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> G {
        match self.seeds.pop() {
            Some(seed) => seed,
            None => self.inner.initialize(rng),
        }
    }
}

#[cfg(test)]
mod tests {
    use alloc::vec;

    use super::*;
    use crate::SplitMix64;

    /// A mix with weight zero on one side always picks the other.
    #[test]
    fn mix_respects_weights() {
        let mut rng = SplitMix64::new(1);
        let mut m = mix(
            mutation_fn(|x: &mut u32, _| *x += 1),
            1.0,
            mutation_fn(|x: &mut u32, _| *x += 100),
            0.0,
        );
        let mut value = 0;
        for _ in 0..10 {
            m.mutate(&mut value, &mut rng);
        }

        assert_eq!(value, 10);
    }

    /// Seeds come first and are capped.
    #[test]
    fn seeded_caps_and_orders() {
        let mut rng = SplitMix64::new(1);
        let mut init = Seeded::new(vec![1, 2, 3], initializer_fn(|_| 0), 10, 0.2);
        let got: Vec<i32> = (0..4).map(|_| init.initialize(&mut rng)).collect();

        assert_eq!(got, [1, 2, 0, 0]);
    }
}