gryf 0.2.1

Graph data structure library with focus on convenience, versatility, correctness and performance.
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
//! Find [single source shortest paths] and their distances in a graph.
//!
//! See available parameters [here](ShortestPathsBuilder#implementations).
//!
//! Note that more efficient algorithms can be applied if the edges do not have
//! negative weights. If you have a graph where nonnegative weights can be
//! guaranteed at compile time, make sure to use an [unsigned
//! type](crate::core::weight::Weight::is_unsigned) like `u8`, `u32` or
//! [`uf64`](crate::core::weight::uf64).
//!
//! [single source shortest paths]:
//!     https://en.wikipedia.org/wiki/Shortest_path_problem#Single-source_shortest_paths
//!
//! # Examples
//!
//! ```
//! use gryf::{algo::ShortestPaths, Graph};
//!
//! let mut graph = Graph::new_undirected();
//!
//! let prague = graph.add_vertex("Prague");
//! let bratislava = graph.add_vertex("Bratislava");
//! let vienna = graph.add_vertex("Vienna");
//! let munich = graph.add_vertex("Munich");
//! let nuremberg = graph.add_vertex("Nuremberg");
//! let florence = graph.add_vertex("Florence");
//! let rome = graph.add_vertex("Rome");
//!
//! graph.extend_with_edges([
//!     (prague, bratislava, 328u32),
//!     (prague, nuremberg, 297),
//!     (prague, vienna, 293),
//!     (bratislava, vienna, 79),
//!     (nuremberg, munich, 170),
//!     (vienna, munich, 402),
//!     (vienna, florence, 863),
//!     (munich, florence, 646),
//!     (florence, rome, 278),
//! ]);
//!
//! let shortest_paths = ShortestPaths::on(&graph).goal(prague).run(rome).unwrap();
//! let distance = shortest_paths[prague];
//! let path = shortest_paths
//!     .reconstruct(prague)
//!     .map(|v| graph[v])
//!     .collect::<Vec<_>>()
//!     .join(" - ");
//!
//! println!("{distance} km from Prague through {path}");
//! ```

use std::{borrow::Borrow, ops::Index};

use rustc_hash::FxHashMap;
use thiserror::Error;

use crate::core::GraphBase;

mod bellman_ford;
mod bfs;
mod builder;
mod dijkstra;

pub use builder::ShortestPathsBuilder;

/// Shortest paths and their distances from a single source vertex.
///
/// See [module](self) documentation for more details and example.
#[derive(Debug)]
pub struct ShortestPaths<W, G: GraphBase> {
    source: G::VertexId,
    // Using HashMaps because the algorithm supports early termination when
    // reaching given goal. It is likely that reaching goal means visiting a
    // subgraph which is significantly smaller than the original graph.
    dist: FxHashMap<G::VertexId, W>,
    pred: FxHashMap<G::VertexId, G::VertexId>,
}

impl<W, G> ShortestPaths<W, G>
where
    G: GraphBase,
{
    /// Source vertex where the search was started.
    pub fn source(&self) -> &G::VertexId {
        &self.source
    }

    /// Returns the path distance between the source vertex and the given
    /// vertex, or `None` if it's not known.
    ///
    /// There are two causes why the distance between two vertices is not known:
    /// (1) the vertices are not connected, or (2) the
    /// [goal](ShortestPathsBuilder::goal) was reached before visiting the given
    /// vertex.
    pub fn dist<VI>(&self, to: VI) -> Option<&W>
    where
        VI: Borrow<G::VertexId>,
    {
        self.dist.get(to.borrow())
    }

    /// Returns an iterator over vertices on the path between the given vertex
    /// and the source vertex, in this order, or `None` if it wasn't found.
    ///
    /// There are two causes why the distance between two vertices is not known:
    /// (1) the vertices are not connected, or (2) the
    /// [goal](ShortestPathsBuilder::goal) was reached before visiting the given
    /// vertex.
    pub fn reconstruct(&self, to: G::VertexId) -> PathReconstruction<'_, G> {
        PathReconstruction {
            curr: to,
            pred: &self.pred,
        }
    }
}

impl<W, G, VI> Index<VI> for ShortestPaths<W, G>
where
    G: GraphBase,
    VI: Borrow<G::VertexId>,
{
    type Output = W;

    fn index(&self, index: VI) -> &Self::Output {
        self.dist(index).unwrap()
    }
}

/// Algorithm for [`ShortestPaths`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Algo {
    /// [Dijkstra's
    /// algorithm](https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm)
    ///
    /// Dijkstra's algorithm is a popular method on a graph with non-negative
    /// edge weights. It operates by iteratively selecting the vertex with the
    /// smallest known distance from the source and updating the distances of
    /// its neighbors.
    ///
    /// # Use cases
    ///
    /// * Finding the shortest path in road networks.
    /// * Optimizing routing in communication networks.
    /// * Navigation and GPS systems.
    Dijkstra,

    /// [Bellman–Ford
    /// algorithm](https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm).
    ///
    /// The Bellman-Ford algorithm can handle graphs with negative edge weights
    /// and can detect negative weight cycles in a graph. However, it is
    /// generally slower than Dijkstra's algorithm.
    ///
    /// # Use cases
    ///
    /// * Finding shortest paths in graphs that may contain negative weight
    ///   edges.
    /// * Detecting negative weight cycles in financial models.
    /// * Network routing protocols like RIP (Routing Information Protocol).
    BellmanFord,
}

mod algo {
    use super::Algo;

    #[derive(Debug)]
    pub struct AnyAlgo;

    #[derive(Debug)]
    pub struct SpecificAlgo(pub Option<Algo>);

    #[derive(Debug)]
    pub struct Dijkstra;

    #[derive(Debug)]
    pub struct BellmanFord;

    #[derive(Debug)]
    pub struct Bfs;
}

/// The error encountered during a [`ShortestPaths`] run.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
pub enum Error {
    /// An edge with negative weight encountered.
    #[error("edge with negative weight encountered")]
    NegativeWeight,

    /// A negative cycle encountered.
    #[error("negative cycle encountered")]
    NegativeCycle,

    /// The specified goal not reached.
    #[error("specified goal not reached")]
    GoalNotReached,

    /// An edge not available.
    ///
    /// This error should not happen in normal circumstances. If it does, it
    /// indicates a bad implementation of the graph.
    #[error("edge not available")]
    EdgeNotAvailable,
}

/// Iterator over the vertices on the path from a vertex to the source vertex.
///
/// Returned by [`ShortestPaths::reconstruct`].
pub struct PathReconstruction<'a, G: GraphBase> {
    curr: G::VertexId,
    pred: &'a FxHashMap<G::VertexId, G::VertexId>,
}

impl<'a, G: GraphBase> Iterator for PathReconstruction<'a, G> {
    type Item = G::VertexId;

    fn next(&mut self) -> Option<Self::Item> {
        self.curr = self.pred.get(&self.curr).cloned()?;
        Some(self.curr.clone())
    }
}

#[cfg(test)]
mod tests {
    use assert_matches::assert_matches;
    use proptest::prelude::*;

    use crate::{
        core::{
            GraphAdd, GraphMut, VertexSet,
            id::{DefaultId, EdgeId, IdType, VertexId},
            marker::{Directed, Undirected},
        },
        infra::proptest::{graph_directed, graph_undirected},
        storage::AdjList,
    };

    use super::*;

    fn create_basic_graph() -> AdjList<(), i32, Undirected, DefaultId> {
        let mut graph = AdjList::default();

        let v0 = graph.add_vertex(());
        let v1 = graph.add_vertex(());
        let v2 = graph.add_vertex(());
        let v3 = graph.add_vertex(());
        let v4 = graph.add_vertex(());
        let v5 = graph.add_vertex(());

        graph.add_edge(&v0, &v1, 3);
        graph.add_edge(&v0, &v2, 2);
        graph.add_edge(&v1, &v2, 2);
        graph.add_edge(&v1, &v3, 2);
        graph.add_edge(&v1, &v4, 7);
        graph.add_edge(&v2, &v3, 5);
        graph.add_edge(&v3, &v4, 3);
        graph.add_edge(&v4, &v5, 10);

        graph
    }

    fn create_graph_with_isolated_vertex() -> (AdjList<(), i32, Undirected, DefaultId>, VertexId) {
        let mut graph = AdjList::default();

        let v0 = graph.add_vertex(());
        let v1 = graph.add_vertex(());
        let v2 = graph.add_vertex(());
        let v3 = graph.add_vertex(());

        graph.add_edge(&v0, &v1, 3);
        graph.add_edge(&v0, &v2, 2);
        graph.add_edge(&v1, &v2, 2);

        (graph, v3)
    }

    fn v(index: usize) -> VertexId {
        index.into()
    }

    fn e(index: usize) -> EdgeId {
        index.into()
    }

    #[test]
    fn dijkstra_basic() {
        let graph = create_basic_graph();
        let shortest_paths = ShortestPaths::on(&graph)
            .using(Algo::Dijkstra)
            .run(v(0))
            .unwrap();

        assert_eq!(shortest_paths.dist(v(4)), Some(&8));
        assert_eq!(
            shortest_paths.reconstruct(v(4)).collect::<Vec<_>>(),
            vec![v(3), v(1), v(0)]
        );

        assert_eq!(shortest_paths.dist(v(2)), Some(&2));
    }

    #[test]
    fn dijkstra_early_termination() {
        let graph = create_basic_graph();
        let shortest_paths = ShortestPaths::on(&graph)
            .goal(v(4))
            .using(Algo::Dijkstra)
            .run(v(0))
            .unwrap();

        assert!(shortest_paths.dist(v(5)).is_none());
    }

    #[test]
    fn dijkstra_negative_edge() {
        let mut graph = create_basic_graph();
        graph.replace_edge(&e(2), -1);

        let shortest_paths = ShortestPaths::on(&graph)
            .goal(v(4))
            .using(Algo::Dijkstra)
            .run(v(0));

        assert_matches!(shortest_paths, Err(Error::NegativeWeight));
    }

    #[test]
    fn dijkstra_goal_not_reached() {
        let (graph, u) = create_graph_with_isolated_vertex();

        let shortest_paths = ShortestPaths::on(&graph)
            .goal(u)
            .using(Algo::Dijkstra)
            .run(v(0));

        assert_matches!(shortest_paths, Err(Error::GoalNotReached));
    }

    #[test]
    fn bellman_ford_basic() {
        let graph = create_basic_graph();
        let shortest_paths = ShortestPaths::on(&graph)
            .using(Algo::BellmanFord)
            .run(v(0))
            .unwrap();

        assert_eq!(shortest_paths.dist(v(4)), Some(&8));
        assert_eq!(
            shortest_paths.reconstruct(v(4)).collect::<Vec<_>>(),
            vec![v(3), v(1), v(0)]
        );

        assert_eq!(shortest_paths.dist(v(2)), Some(&2));
    }

    #[test]
    fn bellman_ford_negative_edge() {
        let mut graph = AdjList::<_, _, Directed, _>::default();

        let v0 = graph.add_vertex(());
        let v1 = graph.add_vertex(());
        let v2 = graph.add_vertex(());
        let v3 = graph.add_vertex(());
        let v4 = graph.add_vertex(());
        let v5 = graph.add_vertex(());

        graph.add_edge(&v0, &v1, 3);
        graph.add_edge(&v0, &v2, 2);
        graph.add_edge(&v1, &v2, -1);
        graph.add_edge(&v1, &v3, 2);
        graph.add_edge(&v1, &v4, 7);
        graph.add_edge(&v2, &v3, 5);
        graph.add_edge(&v3, &v4, 3);
        graph.add_edge(&v4, &v5, 10);

        let shortest_paths = ShortestPaths::on(&graph)
            .using(Algo::BellmanFord)
            .run(v(0))
            .unwrap();

        assert_eq!(shortest_paths.dist(v(4)), Some(&8));
        assert_eq!(
            shortest_paths.reconstruct(v(4)).collect::<Vec<_>>(),
            vec![v(3), v(1), v(0)]
        );

        assert_eq!(shortest_paths.dist(v(2)), Some(&2));
    }

    #[test]
    fn bellman_ford_negative_cycle() {
        let mut graph = AdjList::<(), i32, Directed, DefaultId>::new();

        let v0 = graph.add_vertex(());
        let v1 = graph.add_vertex(());
        let v2 = graph.add_vertex(());
        let v3 = graph.add_vertex(());
        let v4 = graph.add_vertex(());

        graph.add_edge(&v0, &v1, 3);
        graph.add_edge(&v1, &v2, -2);
        graph.add_edge(&v2, &v3, 2);
        graph.add_edge(&v2, &v1, -2);
        graph.add_edge(&v2, &v4, 3);

        let shortest_paths = ShortestPaths::on(&graph).using(Algo::BellmanFord).run(v(0));

        assert_matches!(shortest_paths, Err(Error::NegativeCycle));
    }

    #[test]
    fn bellman_ford_goal_not_reached() {
        let (graph, u) = create_graph_with_isolated_vertex();

        let shortest_paths = ShortestPaths::on(&graph)
            .goal(u)
            .using(Algo::BellmanFord)
            .run(v(0));

        assert_matches!(shortest_paths, Err(Error::GoalNotReached));
    }

    #[test]
    fn bellman_ford_undirected_support() {
        let mut graph = AdjList::<_, _, Undirected, _>::default();

        let v0 = graph.add_vertex(());
        let v1 = graph.add_vertex(());

        graph.add_edge(&v0, &v1, 1);

        let shortest_paths = ShortestPaths::on(&graph)
            .using(Algo::BellmanFord)
            .run(v1)
            .unwrap();

        // Assuming that the AdjList reports the edge with endpoints (v0, v1),
        // Bellman-Ford algorithm needs a special support for undirected graphs
        // to report the distance below correctly.
        assert_eq!(shortest_paths.dist(v0), Some(&1));
    }

    #[test]
    fn bfs_basic() {
        let graph = create_basic_graph();
        let shortest_paths = ShortestPaths::on(&graph)
            .unit_weight()
            .bfs()
            .run(v(0))
            .unwrap();

        assert_eq!(shortest_paths.dist(v(4)), Some(&2));
        assert_eq!(
            shortest_paths.reconstruct(v(4)).collect::<Vec<_>>(),
            vec![v(1), v(0)]
        );

        assert_eq!(shortest_paths.dist(v(2)), Some(&1));
    }

    #[test]
    fn bfs_early_termination() {
        let graph = create_basic_graph();
        let shortest_paths = ShortestPaths::on(&graph)
            .goal(v(4))
            .unit_weight()
            .bfs()
            .run(v(0))
            .unwrap();

        assert!(shortest_paths.dist(v(5)).is_none());
    }

    #[test]
    fn bfs_goal_not_reached() {
        let (graph, u) = create_graph_with_isolated_vertex();

        let shortest_paths = ShortestPaths::on(&graph)
            .goal(u)
            .unit_weight()
            .bfs()
            .run(v(0));

        assert_matches!(shortest_paths, Err(Error::GoalNotReached));
    }

    #[test]
    fn prefer_dijkstra_for_undirected() {
        let mut graph = AdjList::<_, _, Undirected, _>::default();

        let v0 = graph.add_vertex(());
        let v1 = graph.add_vertex(());

        graph.add_edge(&v0, &v1, -1);

        // Setting the goal vertex to be the same as the starting vertex makes
        // Dijkstra's algorithm finish immediately with success where the
        // Bellman-Ford would report "negative cycle" error because it doesn't
        // consider the goal vertex.
        let shortest_paths = ShortestPaths::on(&graph).goal(v1).run(v1).unwrap();

        assert_eq!(shortest_paths.dist(v1), Some(&0));
    }

    proptest! {
        #[test]
        #[ignore = "run property-based tests with `cargo test proptest_ -- --ignored`"]
        fn proptest_dijkstra_connected_all_reachable(graph in graph_undirected(any::<()>(), any::<u16>().prop_map(|e| e as u32)).connected(), source: u64) {
            let n = graph.vertex_count() as u64;
            prop_assume!(n > 0);

            let source = VertexId::from_bits(source % n);
            let paths = ShortestPaths::on(&graph).using(Algo::Dijkstra).run(source).unwrap();

            for v in graph.vertices_by_id() {
                prop_assert_ne!(paths.dist(v), None);

                let u = paths.reconstruct(v).last();
                if v != source {
                    prop_assert_eq!(u, Some(source));
                } else {
                    prop_assert_eq!(u, None);
                }
            }
        }

        #[test]
        #[ignore = "run property-based tests with `cargo test proptest_ -- --ignored`"]
        fn proptest_bellman_ford_any_directed_negative_weight_no_panic(graph in graph_directed(any::<()>(), any::<i16>().prop_map(|e| e as i32)).max_size(128), source: u64) {
            let n = graph.vertex_count() as u64;
            prop_assume!(n > 0);

            let source = VertexId::from_bits(source % n);
            let _ = ShortestPaths::on(&graph).using(Algo::BellmanFord).run(source);
        }

        #[test]
        #[ignore = "run property-based tests with `cargo test proptest_ -- --ignored`"]
        fn proptest_bellman_ford_all_reachable(graph in graph_undirected(any::<()>(), any::<u16>().prop_map(|e| e as u32)).max_size(128).connected(), source: u64) {
            let n = graph.vertex_count() as u64;
            prop_assume!(n > 0);

            let source = VertexId::from_bits(source % n);
            let paths = ShortestPaths::on(&graph).using(Algo::BellmanFord).run(source).unwrap();

            for v in graph.vertices_by_id() {
                prop_assert_ne!(paths.dist(v), None);

                let u = paths.reconstruct(v).last();
                if v != source {
                    prop_assert_eq!(u, Some(source));
                } else {
                    prop_assert_eq!(u, None);
                }
            }
        }

        #[test]
        #[ignore = "run property-based tests with `cargo test proptest_ -- --ignored`"]
        fn proptest_dijkstra_bellman_ford_agree_any_directed(graph in graph_directed(any::<()>(), any::<u16>().prop_map(|e| e as u32)).max_size(128), source: u64) {
            let n = graph.vertex_count() as u64;
            prop_assume!(n > 0);

            let source = VertexId::from_bits(source % n);
            let paths_d = ShortestPaths::on(&graph).using(Algo::Dijkstra).run(source).unwrap();
            let paths_bf = ShortestPaths::on(&graph).using(Algo::BellmanFord).run(source).unwrap();

            for v in graph.vertices_by_id() {
                prop_assert_eq!(paths_d.dist(v), paths_bf.dist(v));
                // Check only the distances. Paths as found by the two
                // algorithms can be different in general.
            }
        }

        #[test]
        #[ignore = "run property-based tests with `cargo test proptest_ -- --ignored`"]
        fn proptest_dijkstra_bellman_ford_agree_any_undirected(graph in graph_undirected(any::<()>(), any::<u16>().prop_map(|e| e as u32)).max_size(128), source: u64) {
            let n = graph.vertex_count() as u64;
            prop_assume!(n > 0);

            let source = VertexId::from_bits(source % n);
            let paths_d = ShortestPaths::on(&graph).using(Algo::Dijkstra).run(source).unwrap();
            let paths_bf = ShortestPaths::on(&graph).using(Algo::BellmanFord).run(source).unwrap();

            for v in graph.vertices_by_id() {
                prop_assert_eq!(paths_d.dist(v), paths_bf.dist(v));
                // Check only the distances. Paths as found by the two
                // algorithms can be different in general.
            }
        }

        #[test]
        #[ignore = "run property-based tests with `cargo test proptest_ -- --ignored`"]
        fn proptest_dijkstra_bfs_agree_any_directed(graph in graph_directed(any::<()>(), any::<()>()).max_size(128), source: u64) {
            let n = graph.vertex_count() as u64;
            prop_assume!(n > 0);

            let source = VertexId::from_bits(source % n);
            let paths_d = ShortestPaths::on(&graph).unit_weight().dijkstra().run(source).unwrap();
            let paths_bfs = ShortestPaths::on(&graph).unit_weight().bfs().run(source).unwrap();

            for v in graph.vertices_by_id() {
                prop_assert_eq!(paths_d.dist(v), paths_bfs.dist(v));
                // Check only the distances. Paths as found by the two
                // algorithms can be different in general.
            }
        }

        #[test]
        #[ignore = "run property-based tests with `cargo test proptest_ -- --ignored`"]
        fn proptest_dijkstra_bfs_agree_any_undirected(graph in graph_undirected(any::<()>(), any::<()>()).max_size(128), source: u64) {
            let n = graph.vertex_count() as u64;
            prop_assume!(n > 0);

            let source = VertexId::from_bits(source % n);
            let paths_d = ShortestPaths::on(&graph).unit_weight().dijkstra().run(source).unwrap();
            let paths_bfs = ShortestPaths::on(&graph).unit_weight().bfs().run(source).unwrap();

            for v in graph.vertices_by_id() {
                prop_assert_eq!(paths_d.dist(v), paths_bfs.dist(v));
                // Check only the distances. Paths as found by the two
                // algorithms can be different in general.
            }
        }
    }
}