rust-igraph 0.6.0

Pure-Rust, high-performance graph & network analysis library — 1200+ APIs, zero unsafe, igraph-compatible
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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
//! Bellman-Ford single-source shortest paths (ALGO-SP-002).
//!
//! Counterpart of `igraph_distances_bellman_ford()` from
//! `references/igraph/src/paths/bellman_ford.c:69`. Returns the
//! shortest-path distance from a single source to every vertex,
//! allowing **negative edge weights** (which Dijkstra forbids).
//! Detects negative cycles reachable from the source.
//!
//! Algorithm: SPFA (Shortest Path Faster Algorithm) — the
//! queue-based Bellman-Ford variant the upstream `bellman_ford.c`
//! uses. Each vertex starts in the queue; popping a vertex marks it
//! "clean" and relaxes its outgoing edges; relaxing an edge marks
//! the target "dirty" and re-queues it if it was clean. A vertex
//! popped more than `vcount` times signals a negative cycle.
//!
//! Time complexity: `O(V · E)` worst case (the SPFA optimisation
//! often beats this in practice).

use std::collections::VecDeque;

use crate::algorithms::paths::dijkstra::DijkstraMode;
use crate::core::graph::EdgeId;
use crate::core::{Graph, IgraphError, IgraphResult, VertexId};

fn validate_weights(graph: &Graph, weights: &[f64]) -> IgraphResult<()> {
    let m = graph.ecount();
    if weights.len() != m {
        return Err(IgraphError::InvalidArgument(format!(
            "weights vector size ({}) differs from edge count ({})",
            weights.len(),
            m
        )));
    }
    for (e, &w) in weights.iter().enumerate() {
        if w.is_nan() {
            return Err(IgraphError::InvalidArgument(format!(
                "weight at edge {e} is NaN"
            )));
        }
    }
    Ok(())
}

fn incident_for_mode(graph: &Graph, v: VertexId, mode: DijkstraMode) -> IgraphResult<Vec<EdgeId>> {
    if !graph.is_directed() {
        return graph.incident(v);
    }
    match mode {
        DijkstraMode::Out => graph.incident(v),
        DijkstraMode::In => graph.incident_in(v),
        DijkstraMode::All => {
            let mut out = graph.incident(v)?;
            out.extend(graph.incident_in(v)?);
            Ok(out)
        }
    }
}

/// Single-source Bellman-Ford shortest distances on `graph` from
/// `source`, following out-edges on directed graphs.
///
/// Returns `distances[v]`: `Some(d)` if `v` is reachable from
/// `source`, `None` otherwise. `distances[source] == Some(0.0)`.
///
/// `weights[e]` is the weight of edge `e`; length must equal
/// `graph.ecount()`. Negative weights are allowed; NaN weights are
/// rejected ([`IgraphError::InvalidArgument`]). If a negative cycle
/// is reachable from the source, returns
/// [`IgraphError::InvalidArgument`] with a "negative cycle"
/// message (matches upstream's `IGRAPH_ENEGCYCLE` semantics).
///
/// Use this instead of [`crate::dijkstra_distances`] when edge
/// weights can be negative. For non-negative weights Dijkstra is
/// asymptotically faster (`O((V+E) log V)` vs Bellman-Ford's
/// `O(V·E)`).
///
/// Counterpart of `igraph_distances_bellman_ford(_, _, vss(source),
/// vss_all(), weights, IGRAPH_OUT)`.
///
/// # Examples
///
/// ```
/// use rust_igraph::{Graph, bellman_ford_distances};
///
/// // Directed graph 0 → 1 → 2 with weights 3, -1 — Bellman-Ford
/// // handles the negative edge that would break Dijkstra's
/// // monotonicity assumption.
/// let mut g = Graph::new(3, true).unwrap();
/// g.add_edge(0, 1).unwrap();  // edge 0, weight 3
/// g.add_edge(1, 2).unwrap();  // edge 1, weight -1
/// let d = bellman_ford_distances(&g, 0, &[3.0, -1.0]).unwrap();
/// assert_eq!(d, vec![Some(0.0), Some(3.0), Some(2.0)]);
/// ```
pub fn bellman_ford_distances(
    graph: &Graph,
    source: VertexId,
    weights: &[f64],
) -> IgraphResult<Vec<Option<f64>>> {
    bellman_ford_distances_with_mode(graph, source, weights, DijkstraMode::Out)
}

/// Single-source Bellman-Ford with directed-mode selection.
///
/// `mode` selects how directed edges are followed:
/// - [`DijkstraMode::Out`] follows out-edges (default for
///   [`bellman_ford_distances`]),
/// - [`DijkstraMode::In`] follows in-edges (i.e. shortest paths
///   *into* `source`),
/// - [`DijkstraMode::All`] ignores edge direction.
///
/// On undirected graphs the mode is ignored.
///
/// Counterpart of `igraph_distances_bellman_ford(_, _, vss(source),
/// vss_all(), weights, mode)`.
///
/// # Examples
///
/// ```
/// use rust_igraph::{Graph, bellman_ford_distances_with_mode, DijkstraMode};
///
/// let mut g = Graph::new(3, true).unwrap();
/// g.add_edge(0, 1).unwrap();
/// g.add_edge(1, 2).unwrap();
/// let d = bellman_ford_distances_with_mode(&g, 2, &[1.0, 1.0], DijkstraMode::In).unwrap();
/// assert!((d[0].unwrap() - 2.0).abs() < 1e-9);
/// ```
pub fn bellman_ford_distances_with_mode(
    graph: &Graph,
    source: VertexId,
    weights: &[f64],
    mode: DijkstraMode,
) -> IgraphResult<Vec<Option<f64>>> {
    let n = graph.vcount();
    if source >= n {
        return Err(IgraphError::VertexOutOfRange { id: source, n });
    }
    validate_weights(graph, weights)?;

    let n_usize = n as usize;
    let mut dist: Vec<f64> = vec![f64::INFINITY; n_usize];
    dist[source as usize] = 0.0;

    // SPFA: queue all vertices initially; pop, relax edges of clean
    // vertices, re-queue targets that get relaxed.
    let mut queue: VecDeque<VertexId> = VecDeque::with_capacity(n_usize);
    let mut in_queue: Vec<bool> = vec![true; n_usize];
    let mut num_queued: Vec<u32> = vec![0; n_usize];
    for v in 0..n {
        queue.push_back(v);
    }

    let n_u32 = n;
    while let Some(j) = queue.pop_front() {
        let j_idx = j as usize;
        in_queue[j_idx] = false;
        num_queued[j_idx] = num_queued[j_idx]
            .checked_add(1)
            .ok_or(IgraphError::Internal("num_queued overflow"))?;
        // A vertex queued more than vcount times indicates a negative
        // cycle (upstream uses the same `> n` threshold).
        if num_queued[j_idx] > n_u32 {
            return Err(IgraphError::InvalidArgument(
                "negative cycle reachable from source while running Bellman-Ford".to_string(),
            ));
        }

        // No point relaxing edges from an unreachable vertex.
        if !dist[j_idx].is_finite() {
            continue;
        }

        let incidents = incident_for_mode(graph, j, mode)?;
        for eid in incidents {
            let w = weights[eid as usize];
            // Positive-infinite weights are ignored (matches upstream).
            if w == f64::INFINITY {
                continue;
            }
            let target = graph.edge_other(eid, j)?;
            let target_idx = target as usize;
            let altdist = dist[j_idx] + w;
            if altdist < dist[target_idx] {
                dist[target_idx] = altdist;
                if !in_queue[target_idx] {
                    in_queue[target_idx] = true;
                    queue.push_back(target);
                }
            }
        }
    }

    Ok(dist
        .into_iter()
        .map(|d| if d.is_finite() { Some(d) } else { None })
        .collect())
}

/// Returns the shortest path from `source` to `target` using
/// Bellman-Ford, following out-edges on directed graphs.
///
/// Returns `Some((vertices, edges))` if a finite-weight path exists,
/// `None` if `target` is unreachable. When `source == target`, returns
/// `Some((vec![source], vec![]))`.
///
/// Supports negative edge weights; detects negative cycles reachable
/// from the source.
///
/// Counterpart of `igraph_get_shortest_path_bellman_ford(_, vertices,
/// edges, from, to, weights, IGRAPH_OUT)`.
///
/// # Examples
///
/// ```
/// use rust_igraph::{Graph, bellman_ford_path_to};
///
/// let mut g = Graph::new(4, true).unwrap();
/// g.add_edge(0, 1).unwrap(); // edge 0, weight 3
/// g.add_edge(1, 2).unwrap(); // edge 1, weight -1
/// g.add_edge(0, 2).unwrap(); // edge 2, weight 5
/// g.add_edge(2, 3).unwrap(); // edge 3, weight 1
/// let (vs, es) = bellman_ford_path_to(&g, 0, 3, &[3.0, -1.0, 5.0, 1.0])
///     .unwrap()
///     .unwrap();
/// assert_eq!(vs, vec![0, 1, 2, 3]);
/// assert_eq!(es, vec![0, 1, 3]);
/// ```
pub fn bellman_ford_path_to(
    graph: &Graph,
    source: VertexId,
    target: VertexId,
    weights: &[f64],
) -> IgraphResult<Option<(Vec<VertexId>, Vec<EdgeId>)>> {
    bellman_ford_path_to_with_mode(graph, source, target, weights, DijkstraMode::Out)
}

/// Returns the shortest path from `source` to `target` using
/// Bellman-Ford with directed-mode selection.
///
/// `mode` selects how directed edges are followed:
/// - [`DijkstraMode::Out`] follows out-edges,
/// - [`DijkstraMode::In`] follows in-edges,
/// - [`DijkstraMode::All`] ignores edge direction.
///
/// Returns `Some((vertices, edges))` if a finite-weight path exists,
/// `None` if `target` is unreachable.
///
/// # Examples
///
/// ```
/// use rust_igraph::{Graph, bellman_ford_path_to_with_mode, DijkstraMode};
///
/// let mut g = Graph::new(3, true).unwrap();
/// g.add_edge(0, 1).unwrap();
/// g.add_edge(1, 2).unwrap();
/// let p = bellman_ford_path_to_with_mode(&g, 2, 0, &[1.0, 1.0], DijkstraMode::In)
///     .unwrap().unwrap();
/// assert_eq!(p.0, vec![2, 1, 0]);
/// ```
pub fn bellman_ford_path_to_with_mode(
    graph: &Graph,
    source: VertexId,
    target: VertexId,
    weights: &[f64],
    mode: DijkstraMode,
) -> IgraphResult<Option<(Vec<VertexId>, Vec<EdgeId>)>> {
    let n = graph.vcount();
    if source >= n {
        return Err(IgraphError::VertexOutOfRange { id: source, n });
    }
    if target >= n {
        return Err(IgraphError::VertexOutOfRange { id: target, n });
    }
    validate_weights(graph, weights)?;

    if source == target {
        return Ok(Some((vec![source], vec![])));
    }

    let n_usize = n as usize;
    let mut dist: Vec<f64> = vec![f64::INFINITY; n_usize];
    dist[source as usize] = 0.0;

    // Parent edge for reconstructing the path.
    let mut parent_edge: Vec<Option<EdgeId>> = vec![None; n_usize];

    let mut queue: VecDeque<VertexId> = VecDeque::with_capacity(n_usize);
    let mut in_queue: Vec<bool> = vec![true; n_usize];
    let mut num_queued: Vec<u32> = vec![0; n_usize];
    for v in 0..n {
        queue.push_back(v);
    }

    while let Some(j) = queue.pop_front() {
        let j_idx = j as usize;
        in_queue[j_idx] = false;
        num_queued[j_idx] = num_queued[j_idx]
            .checked_add(1)
            .ok_or(IgraphError::Internal("num_queued overflow"))?;
        if num_queued[j_idx] > n {
            return Err(IgraphError::InvalidArgument(
                "negative cycle reachable from source while running Bellman-Ford".to_string(),
            ));
        }

        if !dist[j_idx].is_finite() {
            continue;
        }

        let incidents = incident_for_mode(graph, j, mode)?;
        for eid in incidents {
            let w = weights[eid as usize];
            if w == f64::INFINITY {
                continue;
            }
            let neighbor = graph.edge_other(eid, j)?;
            let neighbor_idx = neighbor as usize;
            let altdist = dist[j_idx] + w;
            if altdist < dist[neighbor_idx] {
                dist[neighbor_idx] = altdist;
                parent_edge[neighbor_idx] = Some(eid);
                if !in_queue[neighbor_idx] {
                    in_queue[neighbor_idx] = true;
                    queue.push_back(neighbor);
                }
            }
        }
    }

    // If target is unreachable, return None.
    if !dist[target as usize].is_finite() {
        return Ok(None);
    }

    // Reconstruct path from target back to source.
    let mut edges_rev: Vec<EdgeId> = Vec::new();
    let mut vertices_rev: Vec<VertexId> = Vec::new();
    let mut cur = target;
    vertices_rev.push(cur);
    while cur != source {
        let eid = parent_edge[cur as usize].ok_or(IgraphError::Internal(
            "bellman_ford_path_to: missing parent edge in path reconstruction",
        ))?;
        edges_rev.push(eid);
        cur = graph.edge_other(eid, cur)?;
        vertices_rev.push(cur);
    }

    vertices_rev.reverse();
    edges_rev.reverse();
    Ok(Some((vertices_rev, edges_rev)))
}

/// One entry in the result of [`bellman_ford_paths`]: `Some((vertices,
/// edges))` if the target is reachable, `None` otherwise.
pub type BellmanFordPathEntry = Option<(Vec<VertexId>, Vec<EdgeId>)>;

/// Shortest paths from `source` to each vertex in `targets` using
/// Bellman-Ford (handles negative edge weights).
///
/// Counterpart of `igraph_get_shortest_paths_bellman_ford` in
/// `references/igraph/src/paths/bellman_ford.c:296`. Runs the
/// SSSP computation once and reconstructs a path for each target.
///
/// Returns a `Vec` with one entry per target. Each entry is
/// `Some((vertices, edges))` if the target is reachable from `source`,
/// or `None` if it is not.
///
/// # Errors
///
/// * [`IgraphError::VertexOutOfRange`] if `source` or any target is
///   outside `[0, vcount())`.
/// * [`IgraphError::InvalidArgument`] if a negative cycle is reachable
///   from `source`, or `weights.len() != ecount()`, or any weight is NaN.
///
/// # Examples
///
/// ```
/// use rust_igraph::{Graph, bellman_ford_paths};
///
/// let mut g = Graph::new(4, true).unwrap();
/// g.add_edge(0, 1).unwrap(); // edge 0, weight 3
/// g.add_edge(1, 2).unwrap(); // edge 1, weight -1
/// g.add_edge(0, 2).unwrap(); // edge 2, weight 5
/// g.add_edge(2, 3).unwrap(); // edge 3, weight 1
/// let results = bellman_ford_paths(&g, 0, &[2, 3], &[3.0, -1.0, 5.0, 1.0]).unwrap();
/// // Path to vertex 2: 0→1→2 (cost 2, via negative edge)
/// let (vs, es) = results[0].as_ref().unwrap();
/// assert_eq!(*vs, vec![0, 1, 2]);
/// assert_eq!(*es, vec![0, 1]);
/// // Path to vertex 3: 0→1→2→3 (cost 3)
/// let (vs, es) = results[1].as_ref().unwrap();
/// assert_eq!(*vs, vec![0, 1, 2, 3]);
/// assert_eq!(*es, vec![0, 1, 3]);
/// ```
pub fn bellman_ford_paths(
    graph: &Graph,
    source: VertexId,
    targets: &[VertexId],
    weights: &[f64],
) -> IgraphResult<Vec<BellmanFordPathEntry>> {
    bellman_ford_paths_with_mode(graph, source, targets, weights, DijkstraMode::Out)
}

/// Multi-target Bellman-Ford shortest paths with directed-mode selection.
///
/// Like [`bellman_ford_paths`] but allows choosing how directed edges
/// are followed:
/// - [`DijkstraMode::Out`] follows out-edges (default),
/// - [`DijkstraMode::In`] follows in-edges,
/// - [`DijkstraMode::All`] ignores edge direction.
///
/// # Examples
///
/// ```
/// use rust_igraph::{Graph, bellman_ford_paths_with_mode, DijkstraMode};
///
/// let mut g = Graph::with_vertices(3);
/// g.add_edge(0, 1).unwrap();
/// g.add_edge(1, 2).unwrap();
/// let res = bellman_ford_paths_with_mode(&g, 0, &[2], &[1.0, 1.0], DijkstraMode::All).unwrap();
/// assert!(res[0].is_some());
/// ```
pub fn bellman_ford_paths_with_mode(
    graph: &Graph,
    source: VertexId,
    targets: &[VertexId],
    weights: &[f64],
    mode: DijkstraMode,
) -> IgraphResult<Vec<BellmanFordPathEntry>> {
    let n = graph.vcount();
    if source >= n {
        return Err(IgraphError::VertexOutOfRange { id: source, n });
    }
    for &t in targets {
        if t >= n {
            return Err(IgraphError::VertexOutOfRange { id: t, n });
        }
    }
    validate_weights(graph, weights)?;

    let n_usize = n as usize;

    // Run SSSP once from source.
    let mut dist: Vec<f64> = vec![f64::INFINITY; n_usize];
    dist[source as usize] = 0.0;

    let mut parent_edge: Vec<Option<EdgeId>> = vec![None; n_usize];

    let mut queue: VecDeque<VertexId> = VecDeque::with_capacity(n_usize);
    let mut in_queue: Vec<bool> = vec![true; n_usize];
    let mut num_queued: Vec<u32> = vec![0; n_usize];
    for v in 0..n {
        queue.push_back(v);
    }

    while let Some(j) = queue.pop_front() {
        let j_idx = j as usize;
        in_queue[j_idx] = false;
        num_queued[j_idx] = num_queued[j_idx]
            .checked_add(1)
            .ok_or(IgraphError::Internal("num_queued overflow"))?;
        if num_queued[j_idx] > n {
            return Err(IgraphError::InvalidArgument(
                "negative cycle reachable from source while running Bellman-Ford".to_string(),
            ));
        }

        if !dist[j_idx].is_finite() {
            continue;
        }

        let incidents = incident_for_mode(graph, j, mode)?;
        for eid in incidents {
            let w = weights[eid as usize];
            if w == f64::INFINITY {
                continue;
            }
            let neighbor = graph.edge_other(eid, j)?;
            let neighbor_idx = neighbor as usize;
            let altdist = dist[j_idx] + w;
            if altdist < dist[neighbor_idx] {
                dist[neighbor_idx] = altdist;
                parent_edge[neighbor_idx] = Some(eid);
                if !in_queue[neighbor_idx] {
                    in_queue[neighbor_idx] = true;
                    queue.push_back(neighbor);
                }
            }
        }
    }

    // Reconstruct paths for each target.
    let mut results: Vec<Option<(Vec<VertexId>, Vec<EdgeId>)>> = Vec::with_capacity(targets.len());
    for &target in targets {
        if target == source {
            results.push(Some((vec![source], vec![])));
            continue;
        }
        if !dist[target as usize].is_finite() {
            results.push(None);
            continue;
        }
        let mut edges_rev: Vec<EdgeId> = Vec::new();
        let mut vertices_rev: Vec<VertexId> = Vec::new();
        let mut cur = target;
        vertices_rev.push(cur);
        while cur != source {
            let eid = parent_edge[cur as usize].ok_or(IgraphError::Internal(
                "bellman_ford_paths: missing parent edge in path reconstruction",
            ))?;
            edges_rev.push(eid);
            cur = graph.edge_other(eid, cur)?;
            vertices_rev.push(cur);
        }
        vertices_rev.reverse();
        edges_rev.reverse();
        results.push(Some((vertices_rev, edges_rev)));
    }

    Ok(results)
}

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

    #[test]
    fn positive_weights_match_dijkstra_triangle() {
        // Triangle 0-1-2 with positive weights — Bellman-Ford and
        // Dijkstra must agree.
        let mut g = Graph::with_vertices(3);
        g.add_edge(0, 1).unwrap();
        g.add_edge(0, 2).unwrap();
        g.add_edge(1, 2).unwrap();
        let weights = [1.0, 4.0, 2.0];
        let bf = bellman_ford_distances(&g, 0, &weights).unwrap();
        assert_eq!(bf, vec![Some(0.0), Some(1.0), Some(3.0)]);
    }

    #[test]
    fn negative_edge_directed_no_cycle() {
        // Directed 0 → 1 → 2 with weights 3, -1.
        let mut g = Graph::new(3, true).unwrap();
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();
        let d = bellman_ford_distances(&g, 0, &[3.0, -1.0]).unwrap();
        assert_eq!(d, vec![Some(0.0), Some(3.0), Some(2.0)]);
    }

    #[test]
    fn unreachable_vertex_is_none() {
        // Two components, source in the first.
        let mut g = Graph::with_vertices(4);
        g.add_edge(0, 1).unwrap();
        g.add_edge(2, 3).unwrap();
        let d = bellman_ford_distances(&g, 0, &[1.0, 1.0]).unwrap();
        assert_eq!(d, vec![Some(0.0), Some(1.0), None, None]);
    }

    #[test]
    fn negative_cycle_directed_errors() {
        // 0 → 1 → 2 → 0 with weights summing to -1 (negative cycle).
        let mut g = Graph::new(3, true).unwrap();
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();
        g.add_edge(2, 0).unwrap();
        let err = bellman_ford_distances(&g, 0, &[1.0, 1.0, -3.0]).unwrap_err();
        assert!(matches!(err, IgraphError::InvalidArgument(_)));
    }

    #[test]
    fn negative_cycle_unreachable_does_not_error() {
        // Negative cycle 2 → 3 → 2 unreachable from source 0.
        // Although SPFA initially queues every vertex, vertex 2's
        // distance stays at infinity, so relaxation is skipped and
        // the cycle never gets explored. Distances for the
        // unreachable component come back as None.
        let mut g = Graph::new(4, true).unwrap();
        g.add_edge(0, 1).unwrap();
        g.add_edge(2, 3).unwrap();
        g.add_edge(3, 2).unwrap();
        let d = bellman_ford_distances(&g, 0, &[1.0, -1.0, -1.0]).unwrap();
        assert_eq!(d, vec![Some(0.0), Some(1.0), None, None]);
    }

    #[test]
    fn zero_weights_ok() {
        let mut g = Graph::with_vertices(3);
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();
        let d = bellman_ford_distances(&g, 0, &[0.0, 0.0]).unwrap();
        assert_eq!(d, vec![Some(0.0), Some(0.0), Some(0.0)]);
    }

    #[test]
    fn source_out_of_range_errors() {
        let g = Graph::with_vertices(3);
        let err = bellman_ford_distances(&g, 99, &[]).unwrap_err();
        assert!(matches!(
            err,
            IgraphError::VertexOutOfRange { id: 99, n: 3 }
        ));
    }

    #[test]
    fn weights_size_mismatch_errors() {
        let mut g = Graph::with_vertices(2);
        g.add_edge(0, 1).unwrap();
        let err = bellman_ford_distances(&g, 0, &[1.0, 2.0]).unwrap_err();
        assert!(matches!(err, IgraphError::InvalidArgument(_)));
    }

    #[test]
    fn nan_weight_errors() {
        let mut g = Graph::with_vertices(2);
        g.add_edge(0, 1).unwrap();
        let err = bellman_ford_distances(&g, 0, &[f64::NAN]).unwrap_err();
        assert!(matches!(err, IgraphError::InvalidArgument(_)));
    }

    #[test]
    fn in_mode_walks_reverse_edges() {
        // Directed 0 → 1 → 2: from 2 with IN mode, paths reach 1 then 0.
        let mut g = Graph::new(3, true).unwrap();
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();
        let d = bellman_ford_distances_with_mode(&g, 2, &[3.0, -1.0], DijkstraMode::In).unwrap();
        // dist(2→2)=0, dist(2→1)=-1, dist(2→0)=-1+3=2
        assert_eq!(d, vec![Some(2.0), Some(-1.0), Some(0.0)]);
    }

    #[test]
    fn all_mode_ignores_direction() {
        // Directed 0 → 1, asking ALL from 1 reaches 0 via the reverse.
        let mut g = Graph::new(2, true).unwrap();
        g.add_edge(0, 1).unwrap();
        let d = bellman_ford_distances_with_mode(&g, 1, &[5.0], DijkstraMode::All).unwrap();
        assert_eq!(d, vec![Some(5.0), Some(0.0)]);
    }

    #[test]
    fn infinity_weight_ignored() {
        // Edge with positive-infinite weight should be skipped (upstream behaviour).
        let mut g = Graph::with_vertices(3);
        g.add_edge(0, 1).unwrap();
        g.add_edge(0, 2).unwrap();
        let d = bellman_ford_distances(&g, 0, &[1.0, f64::INFINITY]).unwrap();
        assert_eq!(d, vec![Some(0.0), Some(1.0), None]);
    }

    // --- bellman_ford_path_to tests ---

    #[test]
    fn path_to_simple_directed() {
        let mut g = Graph::new(4, true).unwrap();
        g.add_edge(0, 1).unwrap(); // 0
        g.add_edge(1, 2).unwrap(); // 1
        g.add_edge(0, 2).unwrap(); // 2, w=5
        g.add_edge(2, 3).unwrap(); // 3
        let w = [3.0, -1.0, 5.0, 1.0];
        let (vs, es) = bellman_ford_path_to(&g, 0, 3, &w).unwrap().unwrap();
        assert_eq!(vs, vec![0, 1, 2, 3]);
        assert_eq!(es, vec![0, 1, 3]);
    }

    #[test]
    fn path_to_source_equals_target() {
        let mut g = Graph::with_vertices(3);
        g.add_edge(0, 1).unwrap();
        let (vs, es) = bellman_ford_path_to(&g, 0, 0, &[1.0]).unwrap().unwrap();
        assert_eq!(vs, vec![0]);
        assert!(es.is_empty());
    }

    #[test]
    fn path_to_unreachable() {
        let mut g = Graph::new(3, true).unwrap();
        g.add_edge(0, 1).unwrap();
        let result = bellman_ford_path_to(&g, 0, 2, &[1.0]).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn path_to_negative_cycle_errors() {
        let mut g = Graph::new(3, true).unwrap();
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();
        g.add_edge(2, 0).unwrap();
        let err = bellman_ford_path_to(&g, 0, 2, &[1.0, 1.0, -3.0]).unwrap_err();
        assert!(matches!(err, IgraphError::InvalidArgument(_)));
    }

    #[test]
    fn path_to_prefers_negative_shortcut() {
        // 0→1→2 (w=1,1) and 0→2 (w=5); via negative: 0→1→2 is 2 < 5
        let mut g = Graph::new(3, true).unwrap();
        g.add_edge(0, 1).unwrap(); // 0, w=1
        g.add_edge(1, 2).unwrap(); // 1, w=-1
        g.add_edge(0, 2).unwrap(); // 2, w=5
        let (vs, es) = bellman_ford_path_to(&g, 0, 2, &[1.0, -1.0, 5.0])
            .unwrap()
            .unwrap();
        assert_eq!(vs, vec![0, 1, 2]);
        assert_eq!(es, vec![0, 1]);
    }

    #[test]
    fn path_to_with_in_mode() {
        // Directed 0→1→2; from 2 in IN mode finds path 2←1←0
        let mut g = Graph::new(3, true).unwrap();
        g.add_edge(0, 1).unwrap(); // 0
        g.add_edge(1, 2).unwrap(); // 1
        let (vs, es) = bellman_ford_path_to_with_mode(&g, 2, 0, &[3.0, -1.0], DijkstraMode::In)
            .unwrap()
            .unwrap();
        assert_eq!(vs, vec![2, 1, 0]);
        assert_eq!(es, vec![1, 0]);
    }

    #[test]
    fn path_to_undirected_negative_cycle() {
        // Undirected graph with a negative edge creates a negative cycle
        // (traverse edge back-and-forth indefinitely), so BF reports it.
        let mut g = Graph::with_vertices(3);
        g.add_edge(0, 1).unwrap(); // 0, w=2
        g.add_edge(1, 2).unwrap(); // 1, w=-1
        g.add_edge(0, 2).unwrap(); // 2, w=5
        let err = bellman_ford_path_to(&g, 0, 2, &[2.0, -1.0, 5.0]).unwrap_err();
        assert!(matches!(err, IgraphError::InvalidArgument(_)));
    }

    #[test]
    fn path_to_multiple_hops() {
        // 0→1→2→3 all weight 1, direct 0→3 weight 10
        let mut g = Graph::new(4, true).unwrap();
        g.add_edge(0, 1).unwrap(); // 0
        g.add_edge(1, 2).unwrap(); // 1
        g.add_edge(2, 3).unwrap(); // 2
        g.add_edge(0, 3).unwrap(); // 3, w=10
        let (vs, es) = bellman_ford_path_to(&g, 0, 3, &[1.0, 1.0, 1.0, 10.0])
            .unwrap()
            .unwrap();
        assert_eq!(vs, vec![0, 1, 2, 3]);
        assert_eq!(es, vec![0, 1, 2]);
    }

    // --- bellman_ford_paths (multi-target) tests ---

    #[test]
    fn paths_multi_target_directed() {
        let mut g = Graph::new(4, true).unwrap();
        g.add_edge(0, 1).unwrap(); // 0, w=3
        g.add_edge(1, 2).unwrap(); // 1, w=-1
        g.add_edge(0, 2).unwrap(); // 2, w=5
        g.add_edge(2, 3).unwrap(); // 3, w=1
        let w = [3.0, -1.0, 5.0, 1.0];
        let results = bellman_ford_paths(&g, 0, &[1, 2, 3], &w).unwrap();
        assert_eq!(results.len(), 3);
        // path to 1: 0→1
        let (vs, es) = results[0].as_ref().unwrap();
        assert_eq!(*vs, vec![0, 1]);
        assert_eq!(*es, vec![0]);
        // path to 2: 0→1→2 (cost 2) < 0→2 (cost 5)
        let (vs, es) = results[1].as_ref().unwrap();
        assert_eq!(*vs, vec![0, 1, 2]);
        assert_eq!(*es, vec![0, 1]);
        // path to 3: 0→1→2→3 (cost 3)
        let (vs, es) = results[2].as_ref().unwrap();
        assert_eq!(*vs, vec![0, 1, 2, 3]);
        assert_eq!(*es, vec![0, 1, 3]);
    }

    #[test]
    fn paths_source_in_targets() {
        let mut g = Graph::new(3, true).unwrap();
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();
        let results = bellman_ford_paths(&g, 0, &[0, 2], &[1.0, 1.0]).unwrap();
        // source to self
        let (vs, es) = results[0].as_ref().unwrap();
        assert_eq!(*vs, vec![0]);
        assert!(es.is_empty());
        // source to 2
        let (vs, es) = results[1].as_ref().unwrap();
        assert_eq!(*vs, vec![0, 1, 2]);
        assert_eq!(*es, vec![0, 1]);
    }

    #[test]
    fn paths_unreachable_target() {
        let mut g = Graph::new(4, true).unwrap();
        g.add_edge(0, 1).unwrap();
        // vertex 2 and 3 unreachable from 0
        let results = bellman_ford_paths(&g, 0, &[1, 2, 3], &[1.0]).unwrap();
        assert!(results[0].is_some());
        assert!(results[1].is_none());
        assert!(results[2].is_none());
    }

    #[test]
    fn paths_empty_targets() {
        let g = Graph::with_vertices(3);
        let results = bellman_ford_paths(&g, 0, &[], &[]).unwrap();
        assert!(results.is_empty());
    }

    #[test]
    fn paths_negative_cycle_errors() {
        let mut g = Graph::new(3, true).unwrap();
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();
        g.add_edge(2, 0).unwrap();
        let err = bellman_ford_paths(&g, 0, &[2], &[1.0, 1.0, -3.0]).unwrap_err();
        assert!(matches!(err, IgraphError::InvalidArgument(_)));
    }

    #[test]
    fn paths_duplicate_target() {
        let mut g = Graph::new(3, true).unwrap();
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();
        let results = bellman_ford_paths(&g, 0, &[2, 2], &[1.0, 1.0]).unwrap();
        assert_eq!(results.len(), 2);
        assert_eq!(results[0], results[1]);
    }

    #[test]
    fn paths_with_in_mode() {
        let mut g = Graph::new(3, true).unwrap();
        g.add_edge(0, 1).unwrap(); // 0
        g.add_edge(1, 2).unwrap(); // 1
        let results =
            bellman_ford_paths_with_mode(&g, 2, &[0, 1], &[3.0, -1.0], DijkstraMode::In).unwrap();
        // 2←1: edge 1
        let (vs, es) = results[1].as_ref().unwrap();
        assert_eq!(*vs, vec![2, 1]);
        assert_eq!(*es, vec![1]);
        // 2←1←0: edges 1, 0
        let (vs, es) = results[0].as_ref().unwrap();
        assert_eq!(*vs, vec![2, 1, 0]);
        assert_eq!(*es, vec![1, 0]);
    }

    #[test]
    fn paths_agrees_with_path_to() {
        let mut g = Graph::new(5, true).unwrap();
        g.add_edge(0, 1).unwrap(); // 0
        g.add_edge(1, 2).unwrap(); // 1
        g.add_edge(0, 3).unwrap(); // 2
        g.add_edge(3, 4).unwrap(); // 3
        g.add_edge(2, 4).unwrap(); // 4
        let w = [2.0, -1.0, 3.0, 1.0, 1.0];
        let multi = bellman_ford_paths(&g, 0, &[1, 2, 3, 4], &w).unwrap();
        for (i, &target) in [1u32, 2, 3, 4].iter().enumerate() {
            let single = bellman_ford_path_to(&g, 0, target, &w).unwrap();
            assert_eq!(multi[i], single, "mismatch for target {target}");
        }
    }

    #[test]
    fn paths_target_out_of_range() {
        let g = Graph::with_vertices(3);
        let err = bellman_ford_paths(&g, 0, &[99], &[]).unwrap_err();
        assert!(matches!(
            err,
            IgraphError::VertexOutOfRange { id: 99, n: 3 }
        ));
    }
}