Skip to main content

evolutionary_planning/
graph_path.rs

1//! Genetic path planning on graphs and grids: a genome is a simple path from start to goal,
2//! initialised by randomised depth-first search, recombined at shared vertices, mutated by
3//! rerouting a stretch, and repaired by cutting loops.
4//!
5//! ```
6//! use evolutionary_planning::graph_path::{Config, Grid, dijkstra, solve};
7//! use evolutionary_planning::{Limits, SplitMix64};
8//!
9//! // A 10 x 10 grid with a wall that has a gap at the bottom.
10//! let mut grid = Grid::open(10, 10, false);
11//! for y in 0..9 {
12//!     grid.block(5, y);
13//! }
14//! let (start, goal) = (grid.node(0, 0), grid.node(9, 0));
15//! let (path, cost) = solve(&grid, start, goal, &Config::default(), &mut Limits::evaluations(20_000), &mut SplitMix64::new(1)).expect("reachable");
16//! assert_eq!(Some(cost), dijkstra(&grid, start, goal).map(|(_, c)| c));
17//! assert_eq!((path[0], path[path.len() - 1]), (start, goal));
18//! ```
19
20use 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
32/// A directed graph with non-negative edge costs over vertices `0..node_count()`.
33pub trait Graph {
34    /// The number of vertices.
35    fn node_count(&self) -> usize;
36
37    /// Appends the out-edges `(target, cost)` of `node` to `out`; costs are non-negative and
38    /// finite.
39    fn neighbours(&self, node: usize, out: &mut Vec<(usize, f64)>);
40
41    /// The cost of the edge `from -> to`, if it exists (the cheapest of parallel edges).
42    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/// A graph given by adjacency lists.
54#[derive(Debug, Clone, Default, PartialEq)]
55pub struct AdjacencyList {
56    /// `edges[v]` lists the out-edges `(target, cost)` of `v`.
57    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/// A 4- or 8-connected grid with blocked cells; straight moves cost `1`, diagonal moves
79/// `√2` (and may not cut blocked corners). Vertex `y * width + x` is cell `(x, y)`.
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct Grid {
82    /// The number of columns.
83    width: usize,
84    /// The number of rows.
85    height: usize,
86    /// Whether each cell is blocked, row-major.
87    blocked: Vec<bool>,
88    /// Whether diagonal moves are allowed.
89    diagonal: bool,
90}
91
92impl Grid {
93    /// A grid without obstacles.
94    #[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    /// Blocks cell `(x, y)`.
105    ///
106    /// # Panics
107    ///
108    /// Panics if the cell is outside the grid.
109    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    /// The vertex of cell `(x, y)`.
115    #[must_use]
116    pub fn node(&self, x: usize, y: usize) -> usize {
117        y * self.width + x
118    }
119
120    /// Whether cell `(x, y)` is inside the grid and not blocked.
121    #[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    /// The cell `(x, y)` of a vertex.
127    #[must_use]
128    pub fn cell(&self, node: usize) -> (usize, usize) {
129        (node % self.width, node / self.width)
130    }
131
132    /// Whether cell `(x, y)` is free; cells outside the grid are not.
133    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/// The cost of `path` if every consecutive pair is an edge; `None` otherwise (or if empty).
191#[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/// A shortest path by Dijkstra's algorithm, with its cost; `None` if `goal` is unreachable.
201/// The reference for tests and the baseline for benches.
202///
203/// # Panics
204///
205/// Panics if `start` or `goal` is not a vertex of the graph.
206#[must_use]
207pub fn dijkstra<G: Graph + ?Sized>(
208    graph: &G,
209    start: usize,
210    goal: usize,
211) -> Option<(Vec<usize>, f64)> {
212    /// A heap entry ordered by smallest distance first.
213    #[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
266/// A randomised depth-first search from `from` to `to` avoiding `forbidden` vertices,
267/// expanding at most `budget` vertices; returns the path (both ends included).
268fn 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/// Random simple paths from `start` to `goal` by randomised depth-first search. If the goal
324/// is unreachable the genome is just `[start]`, which [`PathLength`] scores `+∞`.
325#[derive(Debug, Clone, Copy)]
326pub struct RandomPath<'g, G: ?Sized> {
327    /// The graph.
328    pub graph: &'g G,
329    /// The first vertex.
330    pub start: usize,
331    /// The last vertex.
332    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/// Crossover at a shared vertex: both parents are cut at a vertex they have in common and
351/// the tails exchanged; loops are cut afterwards. Parents without a shared interior vertex
352/// are returned unchanged.
353#[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/// Replaces the stretch between two path vertices by a random detour (a bounded randomised
390/// depth-first search that avoids the rest of the path).
391#[derive(Debug, Clone, Copy)]
392pub struct Reroute<'g, G: ?Sized> {
393    /// The graph.
394    pub graph: &'g G,
395    /// The largest number of vertices one detour search may expand.
396    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/// Cuts every loop: when a vertex reappears, the stretch between its occurrences goes.
425#[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
434/// Removes loops in place, keeping the first occurrence of each vertex: `O(length)` with a
435/// position table over the vertex range of the path.
436fn 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/// Path length as an objective: the sum of edge costs, `+∞` for paths that are not walks in
460/// the graph or do not run from `start` to `goal`.
461#[derive(Debug, Clone, Copy)]
462pub struct PathLength<'g, G: ?Sized> {
463    /// The graph.
464    pub graph: &'g G,
465    /// The required first vertex.
466    pub start: usize,
467    /// The required last vertex.
468    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/// Parameters of [`solve`].
482#[derive(Debug, Clone, Copy, PartialEq)]
483pub struct Config {
484    /// The GA population size.
485    pub population_size: usize,
486    /// The largest number of vertices a reroute may expand.
487    pub max_expansions: usize,
488}
489
490impl Default for Config {
491    /// 50 paths, reroutes of at most 64 expansions.
492    fn default() -> Self {
493        Self {
494            population_size: 50,
495            max_expansions: 64,
496        }
497    }
498}
499
500/// Searches a short path with a generational GA (elitism two, tournament three, shared-vertex
501/// crossover, reroute mutation, loop removal); returns the best path and its cost, or `None`
502/// if no evaluated path reached the goal.
503pub 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    /// A grid with a few walls, 4- or 8-connected.
550    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    /// The GA finds an optimal path on 4- and 8-connected mazes, and every path it returns
566    /// is a valid simple walk.
567    #[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    /// Operators keep paths valid from start to goal.
596    #[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    /// Loop removal keeps the first occurrence and cuts the cycles in between.
622    #[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    /// An unreachable goal yields no path.
634    #[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}