use alloc::vec::Vec;
use rand_core::Rng;
use crate::operators::{Crossover, Initializer, Mutation};
use crate::rng::{below, chance};
pub type Symbol = u16;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Grammar {
arities: Vec<u8>,
terminals: Vec<Symbol>,
functions: Vec<Symbol>,
}
impl Grammar {
#[must_use]
pub fn new(arities: Vec<u8>) -> Self {
let symbols = |terminal: bool| -> Vec<Symbol> {
(0..arities.len())
.filter(|&s| (arities[s] == 0) == terminal)
.map(|s| Symbol::try_from(s).expect("at most u16::MAX symbols"))
.collect()
};
let (terminals, functions) = (symbols(true), symbols(false));
assert!(!terminals.is_empty(), "a grammar needs a terminal");
Self {
arities,
terminals,
functions,
}
}
#[must_use]
pub fn arity(&self, symbol: Symbol) -> usize {
usize::from(self.arities[usize::from(symbol)])
}
fn terminal<R: Rng + ?Sized>(&self, rng: &mut R) -> Symbol {
self.terminals[below(rng, self.terminals.len())]
}
fn function<R: Rng + ?Sized>(&self, rng: &mut R) -> Symbol {
if self.functions.is_empty() {
return self.terminal(rng);
}
self.functions[below(rng, self.functions.len())]
}
}
#[must_use]
pub fn subtree_end(grammar: &Grammar, program: &[Symbol], start: usize) -> usize {
let mut open = 1usize;
for (i, &symbol) in program.iter().enumerate().skip(start) {
open = open + grammar.arity(symbol) - 1;
if open == 0 {
return i + 1;
}
}
panic!("truncated program");
}
#[must_use]
pub fn children(grammar: &Grammar, program: &[Symbol], at: usize) -> Vec<usize> {
let mut out = Vec::with_capacity(grammar.arity(program[at]));
let mut next = at + 1;
for _ in 0..grammar.arity(program[at]) {
out.push(next);
next = subtree_end(grammar, program, next);
}
out
}
#[must_use]
pub fn is_valid(grammar: &Grammar, program: &[Symbol]) -> bool {
let mut open = 1isize;
for (i, &symbol) in program.iter().enumerate() {
if usize::from(symbol) >= grammar.arities.len() {
return false;
}
open += isize::from(grammar.arities[usize::from(symbol)]) - 1;
if open == 0 {
return i + 1 == program.len();
}
}
false
}
#[must_use]
pub fn depth(grammar: &Grammar, program: &[Symbol]) -> usize {
let mut stack: Vec<usize> = Vec::new();
let mut deepest = 0;
for &symbol in program {
let level = stack.len();
deepest = deepest.max(level);
if let Some(top) = stack.last_mut() {
*top -= 1;
}
let arity = grammar.arity(symbol);
if arity > 0 {
stack.push(arity);
}
while stack.last() == Some(&0) {
stack.pop();
}
}
deepest
}
fn generate<R: Rng + ?Sized>(
grammar: &Grammar,
depth: usize,
full: bool,
rng: &mut R,
out: &mut Vec<Symbol>,
) {
let terminal_chance = if full || depth == 0 {
if depth == 0 { 1.0 } else { 0.0 }
} else {
#[expect(clippy::cast_precision_loss, reason = "grammars are tiny")]
let share = grammar.terminals.len() as f64 / grammar.arities.len() as f64;
share
};
let symbol = if chance(rng, terminal_chance) || grammar.functions.is_empty() {
grammar.terminal(rng)
} else {
grammar.function(rng)
};
out.push(symbol);
for _ in 0..grammar.arity(symbol) {
generate(grammar, depth.saturating_sub(1), full, rng, out);
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RampedHalfAndHalf {
pub grammar: Grammar,
pub min_depth: usize,
pub max_depth: usize,
}
impl Initializer<Vec<Symbol>> for RampedHalfAndHalf {
fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Vec<Symbol> {
let depth = self.min_depth + below(rng, self.max_depth.saturating_sub(self.min_depth) + 1);
let mut program = Vec::new();
generate(
&self.grammar,
depth,
rng.next_u32() & 1 == 0,
rng,
&mut program,
);
program
}
}
fn pick_point<R: Rng + ?Sized>(grammar: &Grammar, program: &[Symbol], rng: &mut R) -> usize {
let internal: Vec<usize> = (0..program.len())
.filter(|&i| grammar.arity(program[i]) > 0)
.collect();
if !internal.is_empty() && chance(rng, 0.9) {
return internal[below(rng, internal.len())];
}
below(rng, program.len())
}
fn splice(program: &[Symbol], start: usize, end: usize, replacement: &[Symbol]) -> Vec<Symbol> {
let mut out = Vec::with_capacity(program.len() - (end - start) + replacement.len());
out.extend_from_slice(&program[..start]);
out.extend_from_slice(replacement);
out.extend_from_slice(&program[end..]);
out
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SubtreeCrossover {
pub grammar: Grammar,
pub max_depth: usize,
pub max_len: usize,
}
impl Crossover<Vec<Symbol>> for SubtreeCrossover {
fn crossover<R: Rng + ?Sized>(
&mut self,
a: &Vec<Symbol>,
b: &Vec<Symbol>,
rng: &mut R,
) -> [Vec<Symbol>; 2] {
let grammar = &self.grammar;
let (start_a, start_b) = (pick_point(grammar, a, rng), pick_point(grammar, b, rng));
let (end_a, end_b) = (
subtree_end(grammar, a, start_a),
subtree_end(grammar, b, start_b),
);
let within = |child: &Vec<Symbol>| {
child.len() <= self.max_len && depth(grammar, child) <= self.max_depth
};
let c1 = splice(a, start_a, end_a, &b[start_b..end_b]);
let c2 = splice(b, start_b, end_b, &a[start_a..end_a]);
[
if within(&c1) { c1 } else { a.clone() },
if within(&c2) { c2 } else { b.clone() },
]
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SubtreeMutation {
pub grammar: Grammar,
pub subtree_depth: usize,
pub max_depth: usize,
pub max_len: usize,
}
impl Mutation<Vec<Symbol>> for SubtreeMutation {
fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<Symbol>, rng: &mut R) {
let g = &self.grammar;
let at = pick_point(g, genome, rng);
let end = subtree_end(g, genome, at);
let mut fresh = Vec::new();
generate(g, self.subtree_depth, false, rng, &mut fresh);
let candidate = splice(genome, at, end, &fresh);
if candidate.len() <= self.max_len && depth(g, &candidate) <= self.max_depth {
*genome = candidate;
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PointMutation {
pub grammar: Grammar,
}
impl Mutation<Vec<Symbol>> for PointMutation {
fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<Symbol>, rng: &mut R) {
if genome.is_empty() {
return;
}
let at = below(rng, genome.len());
let arity = self.grammar.arity(genome[at]);
let same: Vec<Symbol> = (0..self.grammar.arities.len())
.filter(|&s| usize::from(self.grammar.arities[s]) == arity)
.map(|s| Symbol::try_from(s).expect("checked at construction"))
.collect();
genome[at] = same[below(rng, same.len())];
}
}
#[cfg(test)]
mod tests;