1use 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
53pub const GENOME_BITS: usize = 18;
55
56#[derive(Debug, Clone, Copy, PartialEq)]
58pub enum SelectionChoice {
59 Tournament(usize),
61 Truncation(f64),
63 Roulette,
65 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#[derive(Debug, Clone, Copy, PartialEq)]
95pub struct PlannerConfig {
96 pub selection: SelectionChoice,
98 pub elitism: usize,
100 pub crossover_rate: f64,
102 pub mutation_rate: f64,
104 pub population_size: usize,
106 pub max_expansions: usize,
108 pub scheme: Scheme,
110}
111
112impl PlannerConfig {
113 #[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 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#[derive(Debug, Clone, Copy)]
189pub struct Instance<'g, G: ?Sized> {
190 pub graph: &'g G,
192 pub start: usize,
194 pub goal: usize,
196 pub optimum: f64,
198}
199
200impl<'g, G: Graph + ?Sized> Instance<'g, G> {
201 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
217pub struct MetaConfig {
218 pub population_size: usize,
220 pub evaluations: u64,
222}
223
224#[derive(Debug, Clone)]
228pub struct Programmer<'g, G: ?Sized> {
229 pub instances: Vec<Instance<'g, G>>,
231 pub evaluations: u64,
233}
234
235impl<'g, G: Graph + ?Sized> Programmer<'g, G> {
236 #[must_use]
238 pub fn new(instances: Vec<Instance<'g, G>>, evaluations: u64) -> Self {
239 Self {
240 instances,
241 evaluations,
242 }
243 }
244
245 #[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 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 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 #[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 #[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}