1use alloc::vec::Vec;
34
35use rand_core::Rng;
36
37use crate::operators::{Crossover, Initializer, Mutation};
38use crate::rng::{below, chance};
39
40pub type Symbol = u16;
42
43#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct Grammar {
46 arities: Vec<u8>,
48 terminals: Vec<Symbol>,
50 functions: Vec<Symbol>,
52}
53
54impl Grammar {
55 #[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 #[must_use]
80 pub fn arity(&self, symbol: Symbol) -> usize {
81 usize::from(self.arities[usize::from(symbol)])
82 }
83
84 fn terminal<R: Rng + ?Sized>(&self, rng: &mut R) -> Symbol {
86 self.terminals[below(rng, self.terminals.len())]
87 }
88
89 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#[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#[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#[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#[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
173fn 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#[derive(Debug, Clone, PartialEq, Eq)]
203pub struct RampedHalfAndHalf {
204 pub grammar: Grammar,
206 pub min_depth: usize,
208 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
228fn 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
241fn 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#[derive(Debug, Clone, PartialEq, Eq)]
254pub struct SubtreeCrossover {
255 pub grammar: Grammar,
257 pub max_depth: usize,
259 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#[derive(Debug, Clone, PartialEq, Eq)]
292pub struct SubtreeMutation {
293 pub grammar: Grammar,
295 pub subtree_depth: usize,
297 pub max_depth: usize,
299 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#[derive(Debug, Clone, PartialEq, Eq)]
319pub struct PointMutation {
320 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;