Skip to main content

evolutionary_planning/
programmer.rs

1//! An evolutionary programmer after Lou, Ding and Wu (2022): a meta-GA evolves bit strings
2//! that encode complete path-planning GAs (operators and their parameters, drawn from an
3//! operator library), scored by how well the decoded planner solves a set of training
4//! instances within a fixed evaluation budget.
5//!
6//! The genome has 18 bits (the paper's has 64 over a larger library):
7//!
8//! | Bits | Gene | Values |
9//! |---|---|---|
10//! | 0–1 | selection operator | tournament, truncation, roulette, linear ranking with SUS |
11//! | 2–3 | selection parameter | size 2/3/4/6; fraction 0.2/0.3/0.5/0.7; pressure 1.2/1.4/1.7/2 |
12//! | 4–5 | elitism | 0, 1, 2, 4 |
13//! | 6–7 | crossover rate | 0, 0.4, 0.7, 0.95 |
14//! | 8–9 | mutation rate | 0.2, 0.5, 0.8, 1 |
15//! | 10–12 | population size | 10, 16, 24, 32, 48, 64, 96, 128 |
16//! | 13–14 | reroute expansions | 8, 32, 128, 512 |
17//! | 15 | scheme | generational, steady state |
18//! | 16–17 | steady-state replacement | always (codes 0, 1), only if better (codes 2, 3) |
19//!
20//! The meta-GA uses linear ranking with selective pressure `1.2`, the paper's scores from
21//! 0.8 (worst) to 1.2 (best).
22//!
23//! ```
24//! use evolutionary_planning::graph_path::Grid;
25//! use evolutionary_planning::programmer::{Instance, MetaConfig, Programmer};
26//! use evolutionary_planning::SplitMix64;
27//!
28//! let mut grid = Grid::open(8, 8, false);
29//! for y in 0..6 {
30//!     grid.block(4, y);
31//! }
32//! let instances = vec![Instance::new(&grid, grid.node(0, 0), grid.node(7, 0))];
33//! let mut programmer = Programmer::new(instances, 400);
34//! let (planner, score) = programmer.evolve(&MetaConfig { population_size: 10, evaluations: 60 }, &mut SplitMix64::new(1));
35//! assert!(score.is_finite() && planner.population_size >= 10);
36//! ```
37
38use alloc::vec::Vec;
39
40use rand_core::Rng;
41
42use crate::ga::{Config as GaConfig, Ga, Operators, Scheme};
43use crate::graph_path::{
44    CommonVertex, Graph, PathLength, RandomPath, RemoveLoops, Reroute, dijkstra,
45};
46use crate::operators::discrete::{BitFlip, RandomBits};
47use crate::operators::selection::{
48    LinearRanking, Proportional, Sampling, Selection, Tournament, Truncation,
49};
50use crate::operators::sequence::UniformCrossover;
51use crate::{Limits, Objective, SplitMix64};
52
53/// The number of bits of a planner genome.
54pub const GENOME_BITS: usize = 18;
55
56/// A selection operator chosen by the genome.
57#[derive(Debug, Clone, Copy, PartialEq)]
58pub enum SelectionChoice {
59    /// A tournament of the given size.
60    Tournament(usize),
61    /// Truncation to the given fraction.
62    Truncation(f64),
63    /// Fitness-proportional roulette.
64    Roulette,
65    /// Linear ranking with the given pressure, sampled universally.
66    Ranking(f64),
67}
68
69impl Selection for SelectionChoice {
70    fn select<R: Rng + ?Sized>(
71        &mut self,
72        costs: &[f64],
73        count: usize,
74        rng: &mut R,
75        out: &mut Vec<usize>,
76    ) {
77        match *self {
78            Self::Tournament(size) => Tournament { size }.select(costs, count, rng, out),
79            Self::Truncation(fraction) => Truncation { fraction }.select(costs, count, rng, out),
80            Self::Roulette => Proportional {
81                sampling: Sampling::Roulette,
82            }
83            .select(costs, count, rng, out),
84            Self::Ranking(pressure) => LinearRanking {
85                pressure,
86                sampling: Sampling::Universal,
87            }
88            .select(costs, count, rng, out),
89        }
90    }
91}
92
93/// A decoded path-planning GA.
94#[derive(Debug, Clone, Copy, PartialEq)]
95pub struct PlannerConfig {
96    /// The parent selection.
97    pub selection: SelectionChoice,
98    /// Elites kept per generation.
99    pub elitism: usize,
100    /// The crossover probability.
101    pub crossover_rate: f64,
102    /// The mutation probability.
103    pub mutation_rate: f64,
104    /// The population size.
105    pub population_size: usize,
106    /// The largest detour search of the reroute mutation.
107    pub max_expansions: usize,
108    /// Generational or steady state.
109    pub scheme: Scheme,
110}
111
112impl PlannerConfig {
113    /// Decodes a [`GENOME_BITS`]-bit genome (missing bits read as `false`).
114    #[must_use]
115    pub fn decode(bits: &[bool]) -> Self {
116        let field = |start: usize, len: usize| {
117            (start..start + len).fold(0usize, |acc, i| {
118                acc << 1 | usize::from(bits.get(i).copied().unwrap_or(false))
119            })
120        };
121        let parameter = field(2, 2);
122        let selection = match field(0, 2) {
123            0 => SelectionChoice::Tournament([2, 3, 4, 6][parameter]),
124            1 => SelectionChoice::Truncation([0.2, 0.3, 0.5, 0.7][parameter]),
125            2 => SelectionChoice::Roulette,
126            _ => SelectionChoice::Ranking([1.2, 1.4, 1.7, 2.0][parameter]),
127        };
128        let scheme = if field(15, 1) == 0 {
129            Scheme::Generational
130        } else {
131            Scheme::SteadyState {
132                only_if_better: field(16, 2) >= 2,
133            }
134        };
135
136        Self {
137            selection,
138            elitism: [0, 1, 2, 4][field(4, 2)],
139            crossover_rate: [0.0, 0.4, 0.7, 0.95][field(6, 2)],
140            mutation_rate: [0.2, 0.5, 0.8, 1.0][field(8, 2)],
141            population_size: [10, 16, 24, 32, 48, 64, 96, 128][field(10, 3)],
142            max_expansions: [8, 32, 128, 512][field(13, 2)],
143            scheme,
144        }
145    }
146
147    /// Runs the decoded planner on one instance; returns the best path length found.
148    pub fn solve<G: Graph + ?Sized, R: Rng + ?Sized>(
149        &self,
150        graph: &G,
151        start: usize,
152        goal: usize,
153        evaluations: u64,
154        rng: &mut R,
155    ) -> f64 {
156        let mut ga = Ga::new(
157            GaConfig {
158                population_size: self.population_size,
159                elitism: self.elitism,
160                crossover_rate: self.crossover_rate,
161                mutation_rate: self.mutation_rate,
162                scheme: self.scheme,
163            },
164            Operators {
165                init: RandomPath { graph, start, goal },
166                selection: self.selection,
167                crossover: CommonVertex,
168                mutation: Reroute {
169                    graph,
170                    max_expansions: self.max_expansions,
171                },
172                repair: RemoveLoops,
173            },
174        );
175        let mut objective = PathLength { graph, start, goal };
176
177        ga.run(
178            &mut objective,
179            &mut Limits::evaluations(evaluations),
180            &mut (),
181            rng,
182        )
183        .best_cost()
184    }
185}
186
187/// A training instance: a graph, a start, a goal and the optimal length (from Dijkstra).
188#[derive(Debug, Clone, Copy)]
189pub struct Instance<'g, G: ?Sized> {
190    /// The graph.
191    pub graph: &'g G,
192    /// The start vertex.
193    pub start: usize,
194    /// The goal vertex.
195    pub goal: usize,
196    /// The shortest path length, `+∞` if unreachable.
197    pub optimum: f64,
198}
199
200impl<'g, G: Graph + ?Sized> Instance<'g, G> {
201    /// An instance with its optimum computed by Dijkstra.
202    #[must_use]
203    pub fn new(graph: &'g G, start: usize, goal: usize) -> Self {
204        let optimum = dijkstra(graph, start, goal).map_or(f64::INFINITY, |(_, c)| c);
205
206        Self {
207            graph,
208            start,
209            goal,
210            optimum,
211        }
212    }
213}
214
215/// Parameters of the meta-GA.
216#[derive(Debug, Clone, Copy, PartialEq, Eq)]
217pub struct MetaConfig {
218    /// The number of planner genomes per generation.
219    pub population_size: usize,
220    /// The number of planner genomes evaluated in total.
221    pub evaluations: u64,
222}
223
224/// The planner-programming objective: the mean relative excess `cost / optimum - 1` of the
225/// decoded planner over the training instances (a failed run counts `10`), each run with a
226/// fixed seed so a genome's score is deterministic.
227#[derive(Debug, Clone)]
228pub struct Programmer<'g, G: ?Sized> {
229    /// The training instances (reachable ones only contribute).
230    pub instances: Vec<Instance<'g, G>>,
231    /// The evaluation budget of every planner run.
232    pub evaluations: u64,
233}
234
235impl<'g, G: Graph + ?Sized> Programmer<'g, G> {
236    /// A programmer for `instances` with a per-run budget.
237    #[must_use]
238    pub fn new(instances: Vec<Instance<'g, G>>, evaluations: u64) -> Self {
239        Self {
240            instances,
241            evaluations,
242        }
243    }
244
245    /// The score of a decoded planner (smaller is better).
246    #[must_use]
247    pub fn score(&self, planner: &PlannerConfig) -> f64 {
248        let reachable: Vec<&Instance<'g, G>> = self
249            .instances
250            .iter()
251            .filter(|i| i.optimum.is_finite())
252            .collect();
253        let total: f64 = reachable
254            .iter()
255            .enumerate()
256            .map(|(k, instance)| {
257                let mut rng = SplitMix64::new(0x5EED ^ k as u64);
258                let cost = planner.solve(
259                    instance.graph,
260                    instance.start,
261                    instance.goal,
262                    self.evaluations,
263                    &mut rng,
264                );
265                if cost.is_finite() {
266                    cost / instance.optimum.max(f64::MIN_POSITIVE) - 1.0
267                } else {
268                    10.0
269                }
270            })
271            .sum();
272
273        #[expect(clippy::cast_precision_loss, reason = "instance counts are small")]
274        let mean = total / reachable.len().max(1) as f64;
275
276        mean
277    }
278
279    /// Runs the meta-GA and returns the best planner with its score.
280    pub fn evolve<R: Rng + ?Sized>(
281        &mut self,
282        meta: &MetaConfig,
283        rng: &mut R,
284    ) -> (PlannerConfig, f64) {
285        let mut ga = Ga::new(
286            GaConfig {
287                population_size: meta.population_size.max(2),
288                elitism: 1,
289                crossover_rate: 0.8,
290                mutation_rate: 1.0,
291                scheme: Scheme::Generational,
292            },
293            Operators {
294                init: RandomBits { len: GENOME_BITS },
295                selection: LinearRanking {
296                    pressure: 1.2,
297                    sampling: Sampling::Roulette,
298                },
299                crossover: UniformCrossover::default(),
300                mutation: BitFlip::default(),
301                repair: crate::operators::NoRepair,
302            },
303        );
304        let outcome = ga.run(
305            self,
306            &mut Limits::evaluations(meta.evaluations),
307            &mut (),
308            rng,
309        );
310        let bits = outcome
311            .best_genome()
312            .cloned()
313            .unwrap_or_else(|| alloc::vec![false; GENOME_BITS]);
314
315        (PlannerConfig::decode(&bits), outcome.best_cost())
316    }
317}
318
319impl<G: Graph + ?Sized> Objective<Vec<bool>> for Programmer<'_, G> {
320    fn evaluate(&mut self, genome: &Vec<bool>) -> f64 {
321        self.score(&PlannerConfig::decode(genome))
322    }
323}
324
325#[cfg(test)]
326mod tests {
327    use super::*;
328    use crate::graph_path::Grid;
329    use crate::operators::Initializer;
330
331    /// Three mazes as training instances.
332    fn mazes() -> Vec<Grid> {
333        (0..3)
334            .map(|k| {
335                let mut grid = Grid::open(14, 10, k == 2);
336                for y in 0..8 {
337                    grid.block(3 + k, y);
338                }
339                for y in 2..10 {
340                    grid.block(8 + k, y);
341                }
342                grid
343            })
344            .collect()
345    }
346
347    /// Every bit string decodes to a valid planner, and decoding is a pure function.
348    #[test]
349    fn decoding_is_total() {
350        let mut rng = SplitMix64::new(1);
351        let mut init = RandomBits { len: GENOME_BITS };
352        for _ in 0..200 {
353            let bits = init.initialize(&mut rng);
354            let config = PlannerConfig::decode(&bits);
355            assert_eq!(config, PlannerConfig::decode(&bits));
356            assert!(config.population_size >= 10 && config.elitism <= 4);
357        }
358    }
359
360    /// The evolved planner scores at least as well as the median of 40 random planners.
361    #[test]
362    fn evolved_planner_beats_random_ones() {
363        let grids = mazes();
364        let instances: Vec<Instance<'_, Grid>> = grids
365            .iter()
366            .map(|g| Instance::new(g, g.node(0, 0), g.node(13, 9)))
367            .collect();
368        let mut programmer = Programmer::new(instances, 300);
369        let (_, evolved) = programmer.evolve(
370            &MetaConfig {
371                population_size: 12,
372                evaluations: 120,
373            },
374            &mut SplitMix64::new(2),
375        );
376
377        let mut rng = SplitMix64::new(7);
378        let mut init = RandomBits { len: GENOME_BITS };
379        let mut random: Vec<f64> = (0..40)
380            .map(|_| programmer.evaluate(&init.initialize(&mut rng)))
381            .collect();
382        random.sort_by(f64::total_cmp);
383
384        assert!(
385            evolved <= random[20],
386            "evolved {evolved}, random median {}",
387            random[20]
388        );
389    }
390}