1use alloc::collections::BinaryHeap;
21use alloc::vec::Vec;
22use core::cmp::Ordering;
23
24use rand_core::Rng;
25
26use crate::ga::{Config as GaConfig, Ga, Operators, Scheme};
27use crate::operators::selection::Tournament;
28use crate::operators::{Crossover, Initializer, Mutation, Repair};
29use crate::rng::{below, shuffle, two_sorted_indices};
30use crate::{Budget, Objective, Stats};
31
32pub trait Graph {
34 fn node_count(&self) -> usize;
36
37 fn neighbours(&self, node: usize, out: &mut Vec<(usize, f64)>);
40
41 fn edge_cost(&self, from: usize, to: usize) -> Option<f64> {
43 let mut out = Vec::new();
44 self.neighbours(from, &mut out);
45
46 out.into_iter()
47 .filter(|&(v, _)| v == to)
48 .map(|(_, c)| c)
49 .min_by(f64::total_cmp)
50 }
51}
52
53#[derive(Debug, Clone, Default, PartialEq)]
55pub struct AdjacencyList {
56 pub edges: Vec<Vec<(usize, f64)>>,
58}
59
60impl Graph for AdjacencyList {
61 fn node_count(&self) -> usize {
62 self.edges.len()
63 }
64
65 fn neighbours(&self, node: usize, out: &mut Vec<(usize, f64)>) {
66 out.extend_from_slice(&self.edges[node]);
67 }
68
69 fn edge_cost(&self, from: usize, to: usize) -> Option<f64> {
70 self.edges[from]
71 .iter()
72 .filter(|&&(v, _)| v == to)
73 .map(|&(_, c)| c)
74 .min_by(f64::total_cmp)
75 }
76}
77
78#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct Grid {
82 width: usize,
84 height: usize,
86 blocked: Vec<bool>,
88 diagonal: bool,
90}
91
92impl Grid {
93 #[must_use]
95 pub fn open(width: usize, height: usize, diagonal: bool) -> Self {
96 Self {
97 width,
98 height,
99 blocked: alloc::vec![false; width * height],
100 diagonal,
101 }
102 }
103
104 pub fn block(&mut self, x: usize, y: usize) {
110 assert!(x < self.width && y < self.height, "cell outside the grid");
111 self.blocked[y * self.width + x] = true;
112 }
113
114 #[must_use]
116 pub fn node(&self, x: usize, y: usize) -> usize {
117 y * self.width + x
118 }
119
120 #[must_use]
122 pub fn is_free(&self, x: usize, y: usize) -> bool {
123 x < self.width && y < self.height && !self.blocked[y * self.width + x]
124 }
125
126 #[must_use]
128 pub fn cell(&self, node: usize) -> (usize, usize) {
129 (node % self.width, node / self.width)
130 }
131
132 fn free(&self, x: isize, y: isize) -> bool {
134 let (Ok(x), Ok(y)) = (usize::try_from(x), usize::try_from(y)) else {
135 return false;
136 };
137
138 x < self.width && y < self.height && !self.blocked[y * self.width + x]
139 }
140}
141
142impl Graph for Grid {
143 fn node_count(&self) -> usize {
144 self.width * self.height
145 }
146
147 fn neighbours(&self, node: usize, out: &mut Vec<(usize, f64)>) {
148 let (x, y) = self.cell(node);
149 let (Ok(x), Ok(y)) = (isize::try_from(x), isize::try_from(y)) else {
150 return;
151 };
152
153 if !self.free(x, y) {
154 return;
155 }
156
157 for (dx, dy) in [
158 (1, 0),
159 (-1, 0),
160 (0, 1),
161 (0, -1),
162 (1, 1),
163 (1, -1),
164 (-1, 1),
165 (-1, -1),
166 ] {
167 let diagonal = dx != 0 && dy != 0;
168 if diagonal && !(self.diagonal && self.free(x + dx, y) && self.free(x, y + dy)) {
169 continue;
170 }
171
172 if self.free(x + dx, y + dy) {
173 let target = usize::try_from(
174 (y + dy) * isize::try_from(self.width).unwrap_or(isize::MAX) + x + dx,
175 )
176 .expect("a free cell has a valid index");
177 out.push((
178 target,
179 if diagonal {
180 core::f64::consts::SQRT_2
181 } else {
182 1.0
183 },
184 ));
185 }
186 }
187 }
188}
189
190#[must_use]
192pub fn path_cost<G: Graph + ?Sized>(graph: &G, path: &[usize]) -> Option<f64> {
193 if path.is_empty() {
194 return None;
195 }
196
197 path.windows(2).map(|w| graph.edge_cost(w[0], w[1])).sum()
198}
199
200#[must_use]
207pub fn dijkstra<G: Graph + ?Sized>(
208 graph: &G,
209 start: usize,
210 goal: usize,
211) -> Option<(Vec<usize>, f64)> {
212 #[derive(PartialEq)]
214 struct Entry(f64, usize);
215 impl Eq for Entry {}
216 impl PartialOrd for Entry {
217 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
218 Some(self.cmp(other))
219 }
220 }
221 impl Ord for Entry {
222 fn cmp(&self, other: &Self) -> Ordering {
223 other.0.total_cmp(&self.0).then(other.1.cmp(&self.1))
224 }
225 }
226
227 let n = graph.node_count();
228 let mut distance = alloc::vec![f64::INFINITY; n];
229 let mut parent = alloc::vec![usize::MAX; n];
230 let mut heap = BinaryHeap::new();
231 let mut edges = Vec::new();
232 distance[start] = 0.0;
233 heap.push(Entry(0.0, start));
234 while let Some(Entry(d, v)) = heap.pop() {
235 if v == goal {
236 break;
237 }
238 if d > distance[v] {
239 continue;
240 }
241
242 edges.clear();
243 graph.neighbours(v, &mut edges);
244 for &(w, c) in &edges {
245 if d + c < distance[w] {
246 distance[w] = d + c;
247 parent[w] = v;
248 heap.push(Entry(d + c, w));
249 }
250 }
251 }
252
253 if !distance[goal].is_finite() {
254 return None;
255 }
256
257 let mut path = alloc::vec![goal];
258 while *path.last().expect("non-empty") != start {
259 path.push(parent[*path.last().expect("non-empty")]);
260 }
261 path.reverse();
262
263 Some((path, distance[goal]))
264}
265
266fn random_dfs<G: Graph + ?Sized, R: Rng + ?Sized>(
269 graph: &G,
270 from: usize,
271 to: usize,
272 forbidden: &[bool],
273 budget: usize,
274 rng: &mut R,
275) -> Option<Vec<usize>> {
276 let mut visited = forbidden.to_vec();
277 let mut stack: Vec<(usize, Vec<usize>)> = Vec::new();
278 let mut edges = Vec::new();
279 let mut path = alloc::vec![from];
280 visited[from] = true;
281 let mut expansions = 0;
282 let frontier = |v: usize, visited: &[bool], rng: &mut R, edges: &mut Vec<(usize, f64)>| {
283 edges.clear();
284 graph.neighbours(v, edges);
285 let mut next: Vec<usize> = edges
286 .iter()
287 .map(|e| e.0)
288 .filter(|&w| w == to || !visited[w])
289 .collect();
290 shuffle(rng, &mut next);
291 next
292 };
293 stack.push((from, frontier(from, &visited, rng, &mut edges)));
294 while let Some((_, options)) = stack.last_mut() {
295 let Some(next) = options.pop() else {
296 stack.pop();
297 path.pop();
298 continue;
299 };
300
301 if next == to {
302 path.push(to);
303 return Some(path);
304 }
305 if visited[next] {
306 continue;
307 }
308
309 expansions += 1;
310 if expansions > budget {
311 return None;
312 }
313
314 visited[next] = true;
315 path.push(next);
316 let options = frontier(next, &visited, rng, &mut edges);
317 stack.push((next, options));
318 }
319
320 None
321}
322
323#[derive(Debug, Clone, Copy)]
326pub struct RandomPath<'g, G: ?Sized> {
327 pub graph: &'g G,
329 pub start: usize,
331 pub goal: usize,
333}
334
335impl<G: Graph + ?Sized> Initializer<Vec<usize>> for RandomPath<'_, G> {
336 fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Vec<usize> {
337 let forbidden = alloc::vec![false; self.graph.node_count()];
338 random_dfs(
339 self.graph,
340 self.start,
341 self.goal,
342 &forbidden,
343 usize::MAX,
344 rng,
345 )
346 .unwrap_or_else(|| alloc::vec![self.start])
347 }
348}
349
350#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
354pub struct CommonVertex;
355
356impl Crossover<Vec<usize>> for CommonVertex {
357 fn crossover<R: Rng + ?Sized>(
358 &mut self,
359 a: &Vec<usize>,
360 b: &Vec<usize>,
361 rng: &mut R,
362 ) -> [Vec<usize>; 2] {
363 let shared: Vec<(usize, usize)> = a
364 .iter()
365 .enumerate()
366 .skip(1)
367 .take(a.len().saturating_sub(2))
368 .filter_map(|(i, v)| {
369 b.iter()
370 .position(|w| w == v)
371 .filter(|&j| j > 0 && j + 1 < b.len())
372 .map(|j| (i, j))
373 })
374 .collect();
375 if shared.is_empty() {
376 return [a.clone(), b.clone()];
377 }
378
379 let (i, j) = shared[below(rng, shared.len())];
380 let mut c1: Vec<usize> = a[..=i].iter().chain(&b[j + 1..]).copied().collect();
381 let mut c2: Vec<usize> = b[..=j].iter().chain(&a[i + 1..]).copied().collect();
382 remove_loops(&mut c1);
383 remove_loops(&mut c2);
384
385 [c1, c2]
386 }
387}
388
389#[derive(Debug, Clone, Copy)]
392pub struct Reroute<'g, G: ?Sized> {
393 pub graph: &'g G,
395 pub max_expansions: usize,
397}
398
399impl<G: Graph + ?Sized> Mutation<Vec<usize>> for Reroute<'_, G> {
400 fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<usize>, rng: &mut R) {
401 if genome.len() < 2 {
402 return;
403 }
404
405 let (i, j) = two_sorted_indices(rng, genome.len());
406 let mut forbidden = alloc::vec![false; self.graph.node_count()];
407 for &v in genome[..i].iter().chain(&genome[j + 1..]) {
408 forbidden[v] = true;
409 }
410
411 if let Some(detour) = random_dfs(
412 self.graph,
413 genome[i],
414 genome[j],
415 &forbidden,
416 self.max_expansions,
417 rng,
418 ) {
419 genome.splice(i..=j, detour);
420 }
421 }
422}
423
424#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
426pub struct RemoveLoops;
427
428impl Repair<Vec<usize>> for RemoveLoops {
429 fn repair<R: Rng + ?Sized>(&mut self, genome: &mut Vec<usize>, _rng: &mut R) {
430 remove_loops(genome);
431 }
432}
433
434fn remove_loops(path: &mut Vec<usize>) {
437 let Some(&largest) = path.iter().max() else {
438 return;
439 };
440
441 let mut position = alloc::vec![usize::MAX; largest + 1];
442 let mut out: Vec<usize> = Vec::with_capacity(path.len());
443 for &v in path.iter() {
444 let at = position[v];
445 if at < out.len() && out[at] == v {
446 for &dropped in &out[at + 1..] {
447 position[dropped] = usize::MAX;
448 }
449 out.truncate(at + 1);
450 } else {
451 position[v] = out.len();
452 out.push(v);
453 }
454 }
455
456 *path = out;
457}
458
459#[derive(Debug, Clone, Copy)]
462pub struct PathLength<'g, G: ?Sized> {
463 pub graph: &'g G,
465 pub start: usize,
467 pub goal: usize,
469}
470
471impl<G: Graph + ?Sized> Objective<Vec<usize>> for PathLength<'_, G> {
472 fn evaluate(&mut self, genome: &Vec<usize>) -> f64 {
473 if genome.first() != Some(&self.start) || genome.last() != Some(&self.goal) {
474 return f64::INFINITY;
475 }
476
477 path_cost(self.graph, genome).unwrap_or(f64::INFINITY)
478 }
479}
480
481#[derive(Debug, Clone, Copy, PartialEq)]
483pub struct Config {
484 pub population_size: usize,
486 pub max_expansions: usize,
488}
489
490impl Default for Config {
491 fn default() -> Self {
493 Self {
494 population_size: 50,
495 max_expansions: 64,
496 }
497 }
498}
499
500pub fn solve<G, B, R>(
504 graph: &G,
505 start: usize,
506 goal: usize,
507 config: &Config,
508 budget: &mut B,
509 rng: &mut R,
510) -> Option<(Vec<usize>, f64)>
511where
512 G: Graph + ?Sized,
513 B: Budget<Stats> + ?Sized,
514 R: Rng + ?Sized,
515{
516 let mut ga = Ga::new(
517 GaConfig {
518 population_size: config.population_size,
519 elitism: 2,
520 crossover_rate: 0.7,
521 mutation_rate: 0.8,
522 scheme: Scheme::Generational,
523 },
524 Operators {
525 init: RandomPath { graph, start, goal },
526 selection: Tournament { size: 3 },
527 crossover: CommonVertex,
528 mutation: Reroute {
529 graph,
530 max_expansions: config.max_expansions,
531 },
532 repair: RemoveLoops,
533 },
534 );
535 let mut objective = PathLength { graph, start, goal };
536 let outcome = ga.run(&mut objective, budget, &mut (), rng);
537
538 outcome
539 .best
540 .filter(|b| b.cost.is_finite())
541 .map(|b| (b.genome, b.cost))
542}
543
544#[cfg(test)]
545mod tests {
546 use super::*;
547 use crate::{Limits, SplitMix64};
548
549 fn maze(diagonal: bool) -> Grid {
551 let mut grid = Grid::open(16, 12, diagonal);
552 for y in 0..9 {
553 grid.block(4, y);
554 }
555 for y in 3..12 {
556 grid.block(9, y);
557 }
558 for x in 11..15 {
559 grid.block(x, 6);
560 }
561
562 grid
563 }
564
565 #[test]
568 fn matches_dijkstra() {
569 for diagonal in [false, true] {
570 let grid = maze(diagonal);
571 let (start, goal) = (grid.node(0, 0), grid.node(15, 11));
572 let (_, optimum) = dijkstra(&grid, start, goal).expect("reachable");
573 let (path, cost) = solve(
574 &grid,
575 start,
576 goal,
577 &Config::default(),
578 &mut Limits::evaluations(30_000),
579 &mut SplitMix64::new(2),
580 )
581 .expect("found");
582
583 assert_eq!(path_cost(&grid, &path), Some(cost));
584 assert!(
585 (cost - optimum).abs() < 1e-9,
586 "diagonal {diagonal}: {cost} vs {optimum}"
587 );
588 let mut sorted = path.clone();
589 sorted.sort_unstable();
590 sorted.dedup();
591 assert_eq!(sorted.len(), path.len(), "the path is simple");
592 }
593 }
594
595 #[test]
597 fn operators_keep_paths_valid() {
598 let grid = maze(true);
599 let (start, goal) = (grid.node(0, 0), grid.node(15, 11));
600 let mut rng = SplitMix64::new(5);
601 let mut init = RandomPath {
602 graph: &grid,
603 start,
604 goal,
605 };
606 let mut reroute = Reroute {
607 graph: &grid,
608 max_expansions: 50,
609 };
610 for _ in 0..100 {
611 let a = init.initialize(&mut rng);
612 let b = init.initialize(&mut rng);
613 for mut child in CommonVertex.crossover(&a, &b, &mut rng) {
614 reroute.mutate(&mut child, &mut rng);
615 assert_eq!((child[0], child[child.len() - 1]), (start, goal));
616 assert!(path_cost(&grid, &child).is_some());
617 }
618 }
619 }
620
621 #[test]
623 fn loops_are_cut() {
624 let mut path = alloc::vec![0, 1, 2, 1, 3, 4, 3, 5, 0, 6];
625 remove_loops(&mut path);
626
627 assert_eq!(path, [0, 6]);
628 let mut path = alloc::vec![0, 1, 2, 3, 2, 4];
629 remove_loops(&mut path);
630 assert_eq!(path, [0, 1, 2, 4]);
631 }
632
633 #[test]
635 fn unreachable_goal() {
636 let mut grid = Grid::open(5, 5, false);
637 for y in 0..5 {
638 grid.block(2, y);
639 }
640
641 assert!(dijkstra(&grid, 0, 4).is_none());
642 assert!(
643 solve(
644 &grid,
645 0,
646 4,
647 &Config::default(),
648 &mut Limits::evaluations(500),
649 &mut SplitMix64::new(1)
650 )
651 .is_none()
652 );
653 }
654}