rustsim-pathfinding 0.0.1

Generic A* and grid-specific pathfinding for rustsim
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! Yen's K-shortest loopless paths algorithm.
//!
//! Finds up to K distinct loopless paths between a source and destination node,
//! ordered by ascending cost. Uses Dijkstra as the inner shortest-path routine.
//!
//! The implementation follows Yen (1971) with standard spur-node iteration.
//!
//! # Example
//!
//! ```
//! use rustsim_pathfinding::yen::{yen_k_shortest, YenPath};
//!
//! // Diamond graph: 0→1 (cost 1), 0→2 (cost 2), 1→3 (cost 2), 2→3 (cost 1)
//! let neighbors = |node: &usize| -> Vec<(usize, f64)> {
//!     match *node {
//!         0 => vec![(1, 1.0), (2, 2.0)],
//!         1 => vec![(3, 2.0)],
//!         2 => vec![(3, 1.0)],
//!         _ => vec![],
//!     }
//! };
//!
//! let paths = yen_k_shortest(0, 3, 3, neighbors);
//! assert_eq!(paths.len(), 2);
//! assert_eq!(paths[0].nodes, vec![0, 1, 3]);
//! assert_eq!(paths[1].nodes, vec![0, 2, 3]);
//! ```
//!
//! # References
//!
//! Yen, J. Y. (1971). "Finding the K Shortest Loopless Paths in a Network."
//! Management Science, 17(11), 712–716.

use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashMap, HashSet};

/// A single path with its node sequence and total cost.
#[derive(Debug, Clone)]
pub struct YenPath<N> {
    /// Ordered node sequence from origin to destination (inclusive).
    pub nodes: Vec<N>,
    /// Total path cost.
    pub cost: f64,
}

#[derive(Clone)]
struct DijkEntry<N> {
    node: N,
    cost: f64,
}

impl<N: PartialEq> PartialEq for DijkEntry<N> {
    fn eq(&self, other: &Self) -> bool {
        self.node == other.node
    }
}

impl<N: Eq> Eq for DijkEntry<N> {}

impl<N: Eq> PartialOrd for DijkEntry<N> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl<N: Eq> Ord for DijkEntry<N> {
    fn cmp(&self, other: &Self) -> Ordering {
        other
            .cost
            .partial_cmp(&self.cost)
            .unwrap_or(Ordering::Equal)
    }
}

/// Dijkstra shortest path from `src` to `dest`, respecting excluded edges and
/// nodes.
fn dijkstra_path<N, FN, I>(
    src: N,
    dest: N,
    neighbors: &mut FN,
    excluded_edges: &HashSet<(N, N)>,
    excluded_nodes: &HashSet<N>,
) -> Option<YenPath<N>>
where
    N: Clone + Eq + std::hash::Hash,
    FN: FnMut(&N) -> I,
    I: IntoIterator<Item = (N, f64)>,
{
    let mut g_scores: HashMap<N, f64> = HashMap::new();
    let mut came_from: HashMap<N, N> = HashMap::new();
    let mut closed: HashSet<N> = HashSet::new();
    let mut heap: BinaryHeap<DijkEntry<N>> = BinaryHeap::new();

    g_scores.insert(src.clone(), 0.0);
    heap.push(DijkEntry {
        node: src.clone(),
        cost: 0.0,
    });

    while let Some(current) = heap.pop() {
        if current.node == dest {
            // Reconstruct path.
            let mut path = Vec::new();
            let mut cur = dest.clone();
            loop {
                path.push(cur.clone());
                match came_from.get(&cur) {
                    Some(prev) => cur = prev.clone(),
                    None => break,
                }
            }
            path.reverse();
            return Some(YenPath {
                nodes: path,
                cost: current.cost,
            });
        }

        if !closed.insert(current.node.clone()) {
            continue;
        }

        let g = current.cost;
        for (nbr, edge_cost) in neighbors(&current.node) {
            if closed.contains(&nbr) {
                continue;
            }
            if excluded_nodes.contains(&nbr) {
                continue;
            }
            if excluded_edges.contains(&(current.node.clone(), nbr.clone())) {
                continue;
            }
            let tentative = g + edge_cost;
            let prev = g_scores.get(&nbr).copied().unwrap_or(f64::INFINITY);
            if tentative < prev {
                g_scores.insert(nbr.clone(), tentative);
                came_from.insert(nbr.clone(), current.node.clone());
                heap.push(DijkEntry {
                    node: nbr,
                    cost: tentative,
                });
            }
        }
    }

    None
}

/// Find up to `k` shortest loopless paths from `src` to `dest`.
///
/// Uses Yen's algorithm with Dijkstra as the inner shortest-path routine.
///
/// # Arguments
///
/// - `src` - source node
/// - `dest` - destination node
/// - `k` - maximum number of paths to find
/// - `neighbors` - closure returning (neighbor, edge_cost) pairs for a node
///
/// Returns paths sorted by ascending cost. May return fewer than `k` paths
/// if fewer distinct loopless paths exist.
pub fn yen_k_shortest<N, FN, I>(src: N, dest: N, k: usize, mut neighbors: FN) -> Vec<YenPath<N>>
where
    N: Clone + Eq + std::hash::Hash,
    FN: FnMut(&N) -> I,
    I: IntoIterator<Item = (N, f64)>,
{
    if k == 0 {
        return Vec::new();
    }

    // Find the shortest path first.
    let first = dijkstra_path(
        src.clone(),
        dest.clone(),
        &mut neighbors,
        &HashSet::new(),
        &HashSet::new(),
    );
    let Some(first) = first else {
        return Vec::new();
    };

    let mut accepted: Vec<YenPath<N>> = vec![first];

    // Candidate heap: (cost, path_nodes).
    // We wrap in a struct for ordering.
    let mut candidates: BinaryHeap<CandidateEntry<N>> = BinaryHeap::new();
    let mut candidate_set: HashSet<Vec<N>> = HashSet::new();

    for ki in 1..k {
        let prev_path = &accepted[ki - 1].nodes;

        // Spur from each node along the previous path (except dest).
        for spur_idx in 0..prev_path.len().saturating_sub(1) {
            let spur_node = prev_path[spur_idx].clone();
            let root_path: Vec<N> = prev_path[..=spur_idx].to_vec();

            // Exclude edges at spur_node that share the same root prefix.
            let mut excluded_edges: HashSet<(N, N)> = HashSet::new();
            for accepted_path in &accepted {
                if accepted_path.nodes.len() > spur_idx
                    && accepted_path.nodes[..=spur_idx] == root_path[..]
                {
                    excluded_edges.insert((
                        accepted_path.nodes[spur_idx].clone(),
                        accepted_path.nodes[spur_idx + 1].clone(),
                    ));
                }
            }

            // Exclude nodes in root (except spur node) to guarantee loopless.
            let mut excluded_nodes: HashSet<N> = HashSet::new();
            for node in &root_path[..spur_idx] {
                excluded_nodes.insert(node.clone());
            }

            if let Some(spur_path) = dijkstra_path(
                spur_node,
                dest.clone(),
                &mut neighbors,
                &excluded_edges,
                &excluded_nodes,
            ) {
                // Concatenate root + spur (spur starts at spur_node).
                let mut full_nodes = root_path.clone();
                full_nodes.extend_from_slice(&spur_path.nodes[1..]);

                // Check for loops.
                let mut seen = HashSet::new();
                if full_nodes.iter().any(|n| !seen.insert(n.clone())) {
                    continue;
                }

                if !candidate_set.contains(&full_nodes) {
                    // Compute total cost.
                    let cost = path_cost(&full_nodes, &mut neighbors);
                    candidate_set.insert(full_nodes.clone());
                    candidates.push(CandidateEntry {
                        cost,
                        nodes: full_nodes,
                    });
                }
            }
        }

        // Pop the cheapest candidate.
        if let Some(best) = candidates.pop() {
            accepted.push(YenPath {
                nodes: best.nodes,
                cost: best.cost,
            });
        } else {
            break;
        }
    }

    accepted
}

/// Compute the total cost of a path by summing edge costs from the neighbor
/// function.
fn path_cost<N, FN, I>(nodes: &[N], neighbors: &mut FN) -> f64
where
    N: Clone + Eq + std::hash::Hash,
    FN: FnMut(&N) -> I,
    I: IntoIterator<Item = (N, f64)>,
{
    let mut total = 0.0;
    for pair in nodes.windows(2) {
        let from = &pair[0];
        let to = &pair[1];
        // Find the edge cost from `from` to `to`.
        let edge_cost = neighbors(from)
            .into_iter()
            .find(|(n, _)| n == to)
            .map(|(_, c)| c)
            .unwrap_or(0.0);
        total += edge_cost;
    }
    total
}

struct CandidateEntry<N> {
    cost: f64,
    nodes: Vec<N>,
}

impl<N: PartialEq> PartialEq for CandidateEntry<N> {
    fn eq(&self, other: &Self) -> bool {
        self.cost == other.cost && self.nodes == other.nodes
    }
}

impl<N: Eq> Eq for CandidateEntry<N> {}

impl<N: Eq> PartialOrd for CandidateEntry<N> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl<N: Eq> Ord for CandidateEntry<N> {
    fn cmp(&self, other: &Self) -> Ordering {
        // Min-heap: reverse the cost comparison.
        other
            .cost
            .partial_cmp(&self.cost)
            .unwrap_or(Ordering::Equal)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn diamond_neighbors(node: &usize) -> Vec<(usize, f64)> {
        match *node {
            0 => vec![(1, 1.0), (2, 2.0)],
            1 => vec![(3, 2.0)],
            2 => vec![(3, 1.0)],
            _ => vec![],
        }
    }

    #[test]
    fn finds_two_paths_on_diamond() {
        let paths = yen_k_shortest(0, 3, 3, diamond_neighbors);
        assert_eq!(paths.len(), 2);
        assert_eq!(paths[0].nodes, vec![0, 1, 3]);
        assert!((paths[0].cost - 3.0).abs() < 1e-6);
        assert_eq!(paths[1].nodes, vec![0, 2, 3]);
        assert!((paths[1].cost - 3.0).abs() < 1e-6);
    }

    #[test]
    fn single_path_on_line() {
        let neighbors = |node: &usize| -> Vec<(usize, f64)> {
            match *node {
                0 => vec![(1, 1.0)],
                1 => vec![(2, 1.0)],
                _ => vec![],
            }
        };
        let paths = yen_k_shortest(0, 2, 5, neighbors);
        assert_eq!(paths.len(), 1);
        assert_eq!(paths[0].nodes, vec![0, 1, 2]);
        assert!((paths[0].cost - 2.0).abs() < 1e-6);
    }

    #[test]
    fn no_path_returns_empty() {
        let neighbors = |_: &usize| -> Vec<(usize, f64)> { vec![] };
        let paths = yen_k_shortest(0, 5, 3, neighbors);
        assert!(paths.is_empty());
    }

    #[test]
    fn k_zero_returns_empty() {
        let paths = yen_k_shortest(0, 3, 0, diamond_neighbors);
        assert!(paths.is_empty());
    }

    #[test]
    fn paths_are_loopless() {
        // Graph with potential loops: 0→1→2→3, 0→2→3, 0→1→0 (loop edge)
        let neighbors = |node: &usize| -> Vec<(usize, f64)> {
            match *node {
                0 => vec![(1, 1.0), (2, 3.0)],
                1 => vec![(0, 1.0), (2, 1.0)],
                2 => vec![(3, 1.0)],
                _ => vec![],
            }
        };
        let paths = yen_k_shortest(0, 3, 5, neighbors);
        for path in &paths {
            let mut seen = HashSet::new();
            assert!(
                path.nodes.iter().all(|n| seen.insert(n)),
                "Path contains loop: {:?}",
                path.nodes
            );
        }
    }

    #[test]
    fn paths_sorted_by_cost() {
        // Grid-like graph with multiple paths
        let neighbors = |node: &usize| -> Vec<(usize, f64)> {
            match *node {
                0 => vec![(1, 1.0), (2, 2.0), (3, 5.0)],
                1 => vec![(4, 1.0)],
                2 => vec![(4, 1.0)],
                3 => vec![(4, 1.0)],
                _ => vec![],
            }
        };
        let paths = yen_k_shortest(0, 4, 5, neighbors);
        for i in 1..paths.len() {
            assert!(
                paths[i].cost >= paths[i - 1].cost - 1e-12,
                "Paths not sorted: cost[{}]={} < cost[{}]={}",
                i,
                paths[i].cost,
                i - 1,
                paths[i - 1].cost
            );
        }
    }
}