sim-lib-discrete-graph 0.2.0

Discrete graph algorithms.
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
412
413
414
415
416
//! Shortest paths: single-source Dijkstra and Bellman-Ford, checked all-pairs
//! shortest paths, and reachability over the algebra spine's semiring closure.

use crate::certificate::{ShortestPathCertificate, verify_shortest_paths};
use crate::error::GraphError;
use crate::graph::Graph;
use core::cmp::Reverse;
use sim_lib_discrete_algebra::{AlgebraLimits, BoolRing, Matrix, MinPlus};
use std::collections::BinaryHeap;

/// Single-source distances and predecessor forest.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PathResult<W> {
    /// `distances[v]` is the shortest distance to `v`, or `None` if unreachable.
    pub distances: Vec<Option<W>>,
    /// `predecessors[v]` is the node `v` was reached from on a shortest path.
    pub predecessors: Vec<Option<usize>>,
}

/// One shortest path between two nodes, with a verifiable predecessor-tree
/// certificate for the source.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ShortestPath<N> {
    /// Source node.
    pub source: usize,
    /// Goal node.
    pub goal: usize,
    /// Node labels along the selected shortest path, including endpoints.
    pub nodes: Vec<N>,
    /// Total path weight, or `None` when the goal is unreachable.
    pub distance: Option<i64>,
    /// The shortest-path tree certificate produced by Bellman-Ford.
    pub certificate: ShortestPathCertificate,
}

/// Directed out-arcs `(target, weight)` of `node`, honoring directedness.
fn out_arcs<N, W: Clone>(graph: &Graph<N, W>, node: usize) -> Vec<(usize, W)> {
    let undirected = !graph.is_directed();
    let mut arcs = Vec::new();
    for e in &graph.edges {
        if e.source == node {
            arcs.push((e.target, e.weight.clone()));
        } else if undirected && e.target == node {
            arcs.push((e.source, e.weight.clone()));
        }
    }
    arcs
}

/// Dijkstra's algorithm over non-negative `u64` weights.
///
/// # Examples
///
/// On a directed graph where the two-hop route `0 -> 1 -> 2` (1 + 2 = 3) beats
/// the direct edge `0 -> 2` (5), the shortest distance to node `2` is `3`:
///
/// ```
/// use sim_lib_discrete_graph::{dijkstra, Directedness, Graph};
///
/// let mut g: Graph<(), u64> = Graph::with_nodes(vec![(), (), ()], Directedness::Directed);
/// g.add_edge(0, 1, 1).unwrap();
/// g.add_edge(1, 2, 2).unwrap();
/// g.add_edge(0, 2, 5).unwrap();
///
/// let r = dijkstra(&g, 0).unwrap();
/// assert_eq!(r.distances, vec![Some(0), Some(1), Some(3)]);
/// assert_eq!(r.predecessors[2], Some(1)); // reached via node 1
/// ```
pub fn dijkstra<N>(graph: &Graph<N, u64>, source: usize) -> Result<PathResult<u64>, GraphError> {
    graph.validate()?;
    let n = graph.node_count();
    if source >= n {
        return Err(GraphError::NodeOutOfRange {
            node: source,
            count: n,
        });
    }
    let mut dist = vec![None; n];
    let mut pred = vec![None; n];
    let mut heap: BinaryHeap<Reverse<(u64, usize)>> = BinaryHeap::new();
    dist[source] = Some(0);
    heap.push(Reverse((0, source)));
    while let Some(Reverse((d, u))) = heap.pop() {
        if dist[u].is_some_and(|best| d > best) {
            continue;
        }
        for (v, w) in out_arcs(graph, u) {
            // Saturating adversarial weights must not wrap into a spuriously
            // short distance; an overflowing relaxation is simply no shorter path.
            let Some(nd) = d.checked_add(w) else {
                continue;
            };
            if dist[v].is_none_or(|best| nd < best) {
                dist[v] = Some(nd);
                pred[v] = Some(u);
                heap.push(Reverse((nd, v)));
            }
        }
    }
    Ok(PathResult {
        distances: dist,
        predecessors: pred,
    })
}

/// Bellman-Ford over `i64` weights. Returns the result and whether a
/// negative-weight cycle is reachable from the source.
pub fn bellman_ford<N>(
    graph: &Graph<N, i64>,
    source: usize,
) -> Result<(PathResult<i64>, bool), GraphError> {
    graph.validate()?;
    let n = graph.node_count();
    if source >= n {
        return Err(GraphError::NodeOutOfRange {
            node: source,
            count: n,
        });
    }
    let undirected = !graph.is_directed();
    // Collect all directed arcs once.
    let mut arcs: Vec<(usize, usize, i64)> = Vec::new();
    for e in &graph.edges {
        arcs.push((e.source, e.target, e.weight));
        if undirected {
            arcs.push((e.target, e.source, e.weight));
        }
    }
    let mut dist: Vec<Option<i64>> = vec![None; n];
    let mut pred = vec![None; n];
    dist[source] = Some(0);
    for _ in 0..n.saturating_sub(1) {
        let mut changed = false;
        for &(a, b, w) in &arcs {
            if let Some(da) = dist[a] {
                let nd = da.checked_add(w).ok_or_else(|| {
                    GraphError::WeightOverflow("Bellman-Ford relaxation".to_string())
                })?;
                if dist[b].is_none_or(|best| nd < best) {
                    dist[b] = Some(nd);
                    pred[b] = Some(a);
                    changed = true;
                }
            }
        }
        if !changed {
            break;
        }
    }
    let mut negative_cycle = false;
    for &(a, b, w) in &arcs {
        if let Some(da) = dist[a] {
            let nd = da.checked_add(w).ok_or_else(|| {
                GraphError::WeightOverflow("Bellman-Ford cycle check".to_string())
            })?;
            if dist[b].is_none_or(|best| nd < best) {
                negative_cycle = true;
                break;
            }
        }
    }
    Ok((
        PathResult {
            distances: dist,
            predecessors: pred,
        },
        negative_cycle,
    ))
}

/// Return one shortest path and its reusable certificate.
///
/// The helper delegates search to Bellman-Ford and verifies the produced
/// [`ShortestPathCertificate`] before returning. The graph may be directed or
/// undirected and may contain negative edges, but negative cycles are rejected.
///
/// ```
/// use sim_lib_discrete_graph::{Directedness, Graph, shortest_path};
///
/// let mut g = Graph::with_nodes(vec!["start", "via", "goal"], Directedness::Directed);
/// g.add_edge(0, 1, 1).unwrap();
/// g.add_edge(1, 2, 1).unwrap();
/// g.add_edge(0, 2, 5).unwrap();
///
/// let path = shortest_path(&g, 0, 2).unwrap();
/// assert_eq!(path.nodes, vec!["start", "via", "goal"]);
/// assert_eq!(path.distance, Some(2));
/// assert_eq!(path.certificate.predecessors[2], Some(1));
/// ```
pub fn shortest_path<N: Clone>(
    graph: &Graph<N, i64>,
    source: usize,
    goal: usize,
) -> Result<ShortestPath<N>, GraphError> {
    graph.validate()?;
    let n = graph.node_count();
    for node in [source, goal] {
        if node >= n {
            return Err(GraphError::NodeOutOfRange { node, count: n });
        }
    }

    let (paths, negative_cycle) = bellman_ford(graph, source)?;
    if negative_cycle {
        return Err(GraphError::NegativeCycle);
    }
    let certificate = ShortestPathCertificate {
        source,
        predecessors: paths.predecessors,
    };
    verify_shortest_paths(graph, &certificate)?;

    let nodes = if paths.distances[goal].is_some() {
        let mut reversed = Vec::new();
        let mut current = goal;
        loop {
            reversed.push(graph.nodes[current].clone());
            if current == source {
                break;
            }
            current = certificate.predecessors[current].ok_or_else(|| {
                GraphError::CertificateInvalid("path predecessor gap".to_string())
            })?;
        }
        reversed.reverse();
        reversed
    } else {
        Vec::new()
    };

    Ok(ShortestPath {
        source,
        goal,
        nodes,
        distance: paths.distances[goal],
        certificate,
    })
}

/// Checked all-pairs shortest paths.
///
/// The algebra crate's tropical semiring is a bounded saturating model. This
/// graph-facing API instead shares Bellman-Ford's fail-closed `i64` overflow
/// policy so single-source and all-pairs shortest paths agree at numeric
/// extremes.
pub fn all_pairs_shortest_paths<N>(graph: &Graph<N, i64>) -> Result<Matrix<MinPlus>, GraphError> {
    graph.validate()?;
    let n = graph.node_count();
    let mut m = Matrix::try_filled_with_limits(n, n, MinPlus::Inf, AlgebraLimits::default())?;
    for source in 0..n {
        let (paths, negative_cycle) = bellman_ford(graph, source)?;
        if negative_cycle {
            return Err(GraphError::NegativeCycle);
        }
        for (target, distance) in paths.distances.into_iter().enumerate() {
            if let Some(distance) = distance {
                m.set(source, target, MinPlus::Fin(distance))?;
            }
        }
    }
    Ok(m)
}

/// Reachability as the boolean closure of the adjacency matrix. Thin wrapper.
pub fn reachability<N, W>(graph: &Graph<N, W>) -> Result<Matrix<BoolRing>, GraphError> {
    graph.validate()?;
    let n = graph.node_count();
    let undirected = !graph.is_directed();
    let mut m = Matrix::try_filled_with_limits(n, n, BoolRing(false), AlgebraLimits::default())?;
    for e in &graph.edges {
        m.data[e.source * n + e.target] = BoolRing(true);
        if undirected {
            m.data[e.target * n + e.source] = BoolRing(true);
        }
    }
    Ok(m.closure(AlgebraLimits::default())?)
}

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

    #[test]
    fn dijkstra_row_equals_all_pairs_row() {
        // Same structure over u64 (Dijkstra) and i64 (all-pairs closure).
        let edges = [(0usize, 1usize, 1u64), (1, 2, 2), (0, 2, 5), (2, 3, 1)];
        let mut gu: Graph<u8, u64> = Graph::with_nodes(vec![0, 1, 2, 3], Directedness::Directed);
        let mut gi: Graph<u8, i64> = Graph::with_nodes(vec![0, 1, 2, 3], Directedness::Directed);
        for &(s, t, w) in &edges {
            gu.add_edge(s, t, w).unwrap();
            gi.add_edge(s, t, w as i64).unwrap();
        }
        let dj = dijkstra(&gu, 0).unwrap();
        let ap = all_pairs_shortest_paths(&gi).unwrap();
        for j in 0..4 {
            let from_closure = match ap.data[j] {
                MinPlus::Fin(d) => Some(d as u64),
                MinPlus::Inf => None,
            };
            assert_eq!(dj.distances[j], from_closure, "node {j}");
        }
    }

    #[test]
    fn bellman_ford_handles_negative_edge_without_cycle() {
        let mut g: Graph<u8, i64> = Graph::with_nodes(vec![0, 1, 2], Directedness::Directed);
        g.add_edge(0, 1, 4).unwrap();
        g.add_edge(0, 2, 5).unwrap();
        g.add_edge(2, 1, -3).unwrap(); // 0->2->1 = 2 beats direct 4
        let (res, neg) = bellman_ford(&g, 0).unwrap();
        assert!(!neg);
        assert_eq!(res.distances[1], Some(2));
    }

    #[test]
    fn bellman_ford_detects_negative_cycle() {
        let mut g: Graph<u8, i64> = Graph::with_nodes(vec![0, 1], Directedness::Directed);
        g.add_edge(0, 1, 1).unwrap();
        g.add_edge(1, 0, -2).unwrap(); // cycle weight -1
        let (_res, neg) = bellman_ford(&g, 0).unwrap();
        assert!(neg);
    }

    #[test]
    fn near_max_weights_do_not_wrap_distance() {
        // Dijkstra: two near-u64::MAX hops must not wrap to a tiny distance.
        let mut gu: Graph<u8, u64> = Graph::with_nodes(vec![0, 1, 2], Directedness::Directed);
        gu.add_edge(0, 1, u64::MAX - 1).unwrap();
        gu.add_edge(1, 2, u64::MAX - 1).unwrap();
        let dj = dijkstra(&gu, 0).unwrap();
        assert_eq!(dj.distances[1], Some(u64::MAX - 1));
        // 2 is only reachable via an overflowing relaxation, so it stays unreached.
        assert_eq!(dj.distances[2], None);

        // Bellman-Ford: two near-i64::MAX hops fail closed instead of wrapping
        // or silently dropping the overflowing reachable relaxation.
        let mut gi: Graph<u8, i64> = Graph::with_nodes(vec![0, 1, 2], Directedness::Directed);
        gi.add_edge(0, 1, i64::MAX - 1).unwrap();
        gi.add_edge(1, 2, i64::MAX - 1).unwrap();
        assert!(matches!(
            bellman_ford(&gi, 0),
            Err(GraphError::WeightOverflow(_))
        ));
    }

    #[test]
    fn all_pairs_shortest_paths_rejects_overflow() {
        let mut g: Graph<u8, i64> = Graph::with_nodes(vec![0, 1, 2], Directedness::Directed);
        g.add_edge(0, 1, i64::MAX - 1).unwrap();
        g.add_edge(1, 2, i64::MAX - 1).unwrap();

        assert!(matches!(
            all_pairs_shortest_paths(&g),
            Err(GraphError::WeightOverflow(_))
        ));
    }

    #[test]
    fn all_pairs_shortest_paths_rejects_negative_cycle() {
        let mut g: Graph<u8, i64> = Graph::with_nodes(vec![0, 1], Directedness::Directed);
        g.add_edge(0, 1, 1).unwrap();
        g.add_edge(1, 0, -2).unwrap();

        assert_eq!(all_pairs_shortest_paths(&g), Err(GraphError::NegativeCycle));
    }

    #[test]
    fn bellman_ford_rejects_negative_overflow() {
        let mut g: Graph<u8, i64> = Graph::with_nodes(vec![0, 1, 2], Directedness::Directed);
        g.add_edge(0, 1, i64::MIN + 1).unwrap();
        g.add_edge(1, 2, -2).unwrap();

        assert!(matches!(
            bellman_ford(&g, 0),
            Err(GraphError::WeightOverflow(_))
        ));
    }

    #[test]
    fn reachability_is_transitive() {
        let mut g: Graph<u8, u64> = Graph::with_nodes(vec![0, 1, 2], Directedness::Directed);
        g.add_edge(0, 1, 1).unwrap();
        g.add_edge(1, 2, 1).unwrap();
        let r = reachability(&g).unwrap();
        assert_eq!(r.data[2], BoolRing(true)); // 0 reaches 2
        assert_eq!(r.data[6], BoolRing(false)); // 2 does not reach 0
    }

    #[test]
    fn shortest_path_returns_verified_certificate() {
        let mut g = Graph::with_nodes(vec!["start", "via", "goal"], Directedness::Directed);
        g.add_edge(0, 1, 1).unwrap();
        g.add_edge(1, 2, 1).unwrap();
        g.add_edge(0, 2, 5).unwrap();

        let path = shortest_path(&g, 0, 2).unwrap();

        assert_eq!(path.nodes, vec!["start", "via", "goal"]);
        assert_eq!(path.distance, Some(2));
        assert_eq!(path.certificate.predecessors, vec![None, Some(0), Some(1)]);
        verify_shortest_paths(&g, &path.certificate).unwrap();
    }

    #[test]
    fn shortest_path_reports_unreachable_goal_with_certificate() {
        let g = Graph::with_nodes(vec![0, 1], Directedness::Directed);

        let path = shortest_path(&g, 0, 1).unwrap();

        assert_eq!(path.nodes, Vec::<i32>::new());
        assert_eq!(path.distance, None);
        assert_eq!(path.certificate.predecessors, vec![None, None]);
        verify_shortest_paths(&g, &path.certificate).unwrap();
    }
}