Skip to main content

Module gp

Module gp 

Source
Expand description

Tree-based genetic programming over a small operator language, for evolving planning programs such as reactive navigation policies (the idea of Lou, Ding and Wu 2022 taken to program trees; see also Koza 1992).

A program is a tree in prefix order, Vec<Symbol>; a Grammar gives each symbol its arity (0 for terminals such as actions, more for functions such as conditionals). The caller interprets programs (see children); this module supplies ramped half-and-half initialisation, subtree crossover, subtree mutation and point mutation, all respecting a depth and length limit.

use evolutionary_planning::gp::{Grammar, RampedHalfAndHalf, children, is_valid};
use evolutionary_planning::operators::Initializer;
use evolutionary_planning::SplitMix64;

// Symbols: 0 = add(a, b), 1 = neg(a), 2 = x, 3 = one.
let grammar = Grammar::new(vec![2, 1, 0, 0]);
let program = RampedHalfAndHalf { grammar: grammar.clone(), min_depth: 1, max_depth: 4 }.initialize(&mut SplitMix64::new(1));
assert!(is_valid(&grammar, &program));

fn eval(grammar: &Grammar, p: &[u16], at: usize, x: f64) -> f64 {
    let kids = children(grammar, p, at);
    match p[at] {
        0 => eval(grammar, p, kids[0], x) + eval(grammar, p, kids[1], x),
        1 => -eval(grammar, p, kids[0], x),
        2 => x,
        _ => 1.0,
    }
}
assert_eq!(eval(&grammar, &[0, 2, 1, 3], 0, 5.0), 4.0);

Structs§

Grammar
The arities of the symbols 0..n.
PointMutation
Point mutation: replace one node’s symbol by another of the same arity.
RampedHalfAndHalf
Ramped half-and-half initialisation (Koza): a uniform depth in min_depth..=max_depth, and the full or grow method with equal probability.
SubtreeCrossover
Subtree crossover: swap a random subtree of each parent; a child over the limits is replaced by a copy of its parent.
SubtreeMutation
Subtree mutation: replace a random subtree by a grown tree of at most subtree_depth levels, unless that breaks the limits.

Functions§

children
The start indices of the children of the node at at, in order.
depth
The depth of the tree (a single terminal has depth 0).
is_valid
Whether program is exactly one complete prefix tree.
subtree_end
The index one past the subtree rooted at start.

Type Aliases§

Symbol
A symbol of the language: an index into the grammar.