Skip to main content

evolutionary_planning/
gp.rs

1//! Tree-based genetic programming over a small operator language, for evolving planning
2//! programs such as reactive navigation policies (the idea of Lou, Ding and Wu 2022 taken to
3//! program trees; see also Koza 1992).
4//!
5//! A program is a tree in prefix order, `Vec<Symbol>`; a [`Grammar`] gives each symbol its
6//! arity (`0` for terminals such as actions, more for functions such as conditionals). The
7//! caller interprets programs (see [`children`]); this module supplies ramped half-and-half
8//! initialisation, subtree crossover, subtree mutation and point mutation, all respecting a
9//! depth and length limit.
10//!
11//! ```
12//! use evolutionary_planning::gp::{Grammar, RampedHalfAndHalf, children, is_valid};
13//! use evolutionary_planning::operators::Initializer;
14//! use evolutionary_planning::SplitMix64;
15//!
16//! // Symbols: 0 = add(a, b), 1 = neg(a), 2 = x, 3 = one.
17//! let grammar = Grammar::new(vec![2, 1, 0, 0]);
18//! let program = RampedHalfAndHalf { grammar: grammar.clone(), min_depth: 1, max_depth: 4 }.initialize(&mut SplitMix64::new(1));
19//! assert!(is_valid(&grammar, &program));
20//!
21//! fn eval(grammar: &Grammar, p: &[u16], at: usize, x: f64) -> f64 {
22//!     let kids = children(grammar, p, at);
23//!     match p[at] {
24//!         0 => eval(grammar, p, kids[0], x) + eval(grammar, p, kids[1], x),
25//!         1 => -eval(grammar, p, kids[0], x),
26//!         2 => x,
27//!         _ => 1.0,
28//!     }
29//! }
30//! assert_eq!(eval(&grammar, &[0, 2, 1, 3], 0, 5.0), 4.0);
31//! ```
32
33use alloc::vec::Vec;
34
35use rand_core::Rng;
36
37use crate::operators::{Crossover, Initializer, Mutation};
38use crate::rng::{below, chance};
39
40/// A symbol of the language: an index into the grammar.
41pub type Symbol = u16;
42
43/// The arities of the symbols `0..n`.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct Grammar {
46    /// The arity of each symbol.
47    arities: Vec<u8>,
48    /// The terminals (arity `0`); never empty.
49    terminals: Vec<Symbol>,
50    /// The functions (arity above `0`).
51    functions: Vec<Symbol>,
52}
53
54impl Grammar {
55    /// A grammar from the arity of every symbol.
56    ///
57    /// # Panics
58    ///
59    /// Panics if there is no terminal or more than `u16::MAX` symbols.
60    #[must_use]
61    pub fn new(arities: Vec<u8>) -> Self {
62        let symbols = |terminal: bool| -> Vec<Symbol> {
63            (0..arities.len())
64                .filter(|&s| (arities[s] == 0) == terminal)
65                .map(|s| Symbol::try_from(s).expect("at most u16::MAX symbols"))
66                .collect()
67        };
68        let (terminals, functions) = (symbols(true), symbols(false));
69        assert!(!terminals.is_empty(), "a grammar needs a terminal");
70
71        Self {
72            arities,
73            terminals,
74            functions,
75        }
76    }
77
78    /// The arity of `symbol`.
79    #[must_use]
80    pub fn arity(&self, symbol: Symbol) -> usize {
81        usize::from(self.arities[usize::from(symbol)])
82    }
83
84    /// A uniform terminal.
85    fn terminal<R: Rng + ?Sized>(&self, rng: &mut R) -> Symbol {
86        self.terminals[below(rng, self.terminals.len())]
87    }
88
89    /// A uniform function, or a terminal if there is none.
90    fn function<R: Rng + ?Sized>(&self, rng: &mut R) -> Symbol {
91        if self.functions.is_empty() {
92            return self.terminal(rng);
93        }
94
95        self.functions[below(rng, self.functions.len())]
96    }
97}
98
99/// The index one past the subtree rooted at `start`.
100///
101/// # Panics
102///
103/// Panics if the program is not a valid prefix tree from `start`.
104#[must_use]
105pub fn subtree_end(grammar: &Grammar, program: &[Symbol], start: usize) -> usize {
106    let mut open = 1usize;
107    for (i, &symbol) in program.iter().enumerate().skip(start) {
108        open = open + grammar.arity(symbol) - 1;
109        if open == 0 {
110            return i + 1;
111        }
112    }
113
114    panic!("truncated program");
115}
116
117/// The start indices of the children of the node at `at`, in order.
118#[must_use]
119pub fn children(grammar: &Grammar, program: &[Symbol], at: usize) -> Vec<usize> {
120    let mut out = Vec::with_capacity(grammar.arity(program[at]));
121    let mut next = at + 1;
122    for _ in 0..grammar.arity(program[at]) {
123        out.push(next);
124        next = subtree_end(grammar, program, next);
125    }
126
127    out
128}
129
130/// Whether `program` is exactly one complete prefix tree.
131#[must_use]
132pub fn is_valid(grammar: &Grammar, program: &[Symbol]) -> bool {
133    let mut open = 1isize;
134    for (i, &symbol) in program.iter().enumerate() {
135        if usize::from(symbol) >= grammar.arities.len() {
136            return false;
137        }
138
139        open += isize::from(grammar.arities[usize::from(symbol)]) - 1;
140        if open == 0 {
141            return i + 1 == program.len();
142        }
143    }
144
145    false
146}
147
148/// The depth of the tree (a single terminal has depth `0`).
149#[must_use]
150pub fn depth(grammar: &Grammar, program: &[Symbol]) -> usize {
151    let mut stack: Vec<usize> = Vec::new();
152    let mut deepest = 0;
153    for &symbol in program {
154        let level = stack.len();
155        deepest = deepest.max(level);
156        if let Some(top) = stack.last_mut() {
157            *top -= 1;
158        }
159
160        let arity = grammar.arity(symbol);
161        if arity > 0 {
162            stack.push(arity);
163        }
164
165        while stack.last() == Some(&0) {
166            stack.pop();
167        }
168    }
169
170    deepest
171}
172
173/// Appends a random tree of at most `depth` levels: the *full* method always picks functions
174/// above the last level, the *grow* method any symbol.
175fn generate<R: Rng + ?Sized>(
176    grammar: &Grammar,
177    depth: usize,
178    full: bool,
179    rng: &mut R,
180    out: &mut Vec<Symbol>,
181) {
182    let terminal_chance = if full || depth == 0 {
183        if depth == 0 { 1.0 } else { 0.0 }
184    } else {
185        #[expect(clippy::cast_precision_loss, reason = "grammars are tiny")]
186        let share = grammar.terminals.len() as f64 / grammar.arities.len() as f64;
187        share
188    };
189    let symbol = if chance(rng, terminal_chance) || grammar.functions.is_empty() {
190        grammar.terminal(rng)
191    } else {
192        grammar.function(rng)
193    };
194    out.push(symbol);
195    for _ in 0..grammar.arity(symbol) {
196        generate(grammar, depth.saturating_sub(1), full, rng, out);
197    }
198}
199
200/// Ramped half-and-half initialisation (Koza): a uniform depth in `min_depth..=max_depth`,
201/// and the full or grow method with equal probability.
202#[derive(Debug, Clone, PartialEq, Eq)]
203pub struct RampedHalfAndHalf {
204    /// The language.
205    pub grammar: Grammar,
206    /// The smallest depth.
207    pub min_depth: usize,
208    /// The largest depth, `>= min_depth`.
209    pub max_depth: usize,
210}
211
212impl Initializer<Vec<Symbol>> for RampedHalfAndHalf {
213    fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Vec<Symbol> {
214        let depth = self.min_depth + below(rng, self.max_depth.saturating_sub(self.min_depth) + 1);
215        let mut program = Vec::new();
216        generate(
217            &self.grammar,
218            depth,
219            rng.next_u32() & 1 == 0,
220            rng,
221            &mut program,
222        );
223
224        program
225    }
226}
227
228/// Picks a crossover or mutation point: a function node with probability `0.9` if there is
229/// one (Koza's bias against swapping leaves), otherwise a uniform node.
230fn pick_point<R: Rng + ?Sized>(grammar: &Grammar, program: &[Symbol], rng: &mut R) -> usize {
231    let internal: Vec<usize> = (0..program.len())
232        .filter(|&i| grammar.arity(program[i]) > 0)
233        .collect();
234    if !internal.is_empty() && chance(rng, 0.9) {
235        return internal[below(rng, internal.len())];
236    }
237
238    below(rng, program.len())
239}
240
241/// Replaces `program[start..end]` by `replacement`.
242fn splice(program: &[Symbol], start: usize, end: usize, replacement: &[Symbol]) -> Vec<Symbol> {
243    let mut out = Vec::with_capacity(program.len() - (end - start) + replacement.len());
244    out.extend_from_slice(&program[..start]);
245    out.extend_from_slice(replacement);
246    out.extend_from_slice(&program[end..]);
247
248    out
249}
250
251/// Subtree crossover: swap a random subtree of each parent; a child over the limits is
252/// replaced by a copy of its parent.
253#[derive(Debug, Clone, PartialEq, Eq)]
254pub struct SubtreeCrossover {
255    /// The language.
256    pub grammar: Grammar,
257    /// The largest depth of a child.
258    pub max_depth: usize,
259    /// The largest number of nodes of a child.
260    pub max_len: usize,
261}
262
263impl Crossover<Vec<Symbol>> for SubtreeCrossover {
264    fn crossover<R: Rng + ?Sized>(
265        &mut self,
266        a: &Vec<Symbol>,
267        b: &Vec<Symbol>,
268        rng: &mut R,
269    ) -> [Vec<Symbol>; 2] {
270        let grammar = &self.grammar;
271        let (start_a, start_b) = (pick_point(grammar, a, rng), pick_point(grammar, b, rng));
272        let (end_a, end_b) = (
273            subtree_end(grammar, a, start_a),
274            subtree_end(grammar, b, start_b),
275        );
276        let within = |child: &Vec<Symbol>| {
277            child.len() <= self.max_len && depth(grammar, child) <= self.max_depth
278        };
279        let c1 = splice(a, start_a, end_a, &b[start_b..end_b]);
280        let c2 = splice(b, start_b, end_b, &a[start_a..end_a]);
281
282        [
283            if within(&c1) { c1 } else { a.clone() },
284            if within(&c2) { c2 } else { b.clone() },
285        ]
286    }
287}
288
289/// Subtree mutation: replace a random subtree by a grown tree of at most `subtree_depth`
290/// levels, unless that breaks the limits.
291#[derive(Debug, Clone, PartialEq, Eq)]
292pub struct SubtreeMutation {
293    /// The language.
294    pub grammar: Grammar,
295    /// The depth of the new subtree.
296    pub subtree_depth: usize,
297    /// The largest depth of the result.
298    pub max_depth: usize,
299    /// The largest number of nodes of the result.
300    pub max_len: usize,
301}
302
303impl Mutation<Vec<Symbol>> for SubtreeMutation {
304    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<Symbol>, rng: &mut R) {
305        let g = &self.grammar;
306        let at = pick_point(g, genome, rng);
307        let end = subtree_end(g, genome, at);
308        let mut fresh = Vec::new();
309        generate(g, self.subtree_depth, false, rng, &mut fresh);
310        let candidate = splice(genome, at, end, &fresh);
311        if candidate.len() <= self.max_len && depth(g, &candidate) <= self.max_depth {
312            *genome = candidate;
313        }
314    }
315}
316
317/// Point mutation: replace one node's symbol by another of the same arity.
318#[derive(Debug, Clone, PartialEq, Eq)]
319pub struct PointMutation {
320    /// The language.
321    pub grammar: Grammar,
322}
323
324impl Mutation<Vec<Symbol>> for PointMutation {
325    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<Symbol>, rng: &mut R) {
326        if genome.is_empty() {
327            return;
328        }
329
330        let at = below(rng, genome.len());
331        let arity = self.grammar.arity(genome[at]);
332        let same: Vec<Symbol> = (0..self.grammar.arities.len())
333            .filter(|&s| usize::from(self.grammar.arities[s]) == arity)
334            .map(|s| Symbol::try_from(s).expect("checked at construction"))
335            .collect();
336        genome[at] = same[below(rng, same.len())];
337    }
338}
339
340#[cfg(test)]
341mod tests;