graphina 0.4.0-alpha.1

A graph data science library for Rust
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
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
/*!
# Shortest Paths Algorithms

This module provides a collection of shortest‑paths algorithms for the Graphina library.
It supports single‑source and all‑pairs computations via (classical) algorithms including:

- **Dijkstra’s Algorithm:**
  Computes single‑source shortest paths for graphs with nonnegative weights.

- **Bellman–Ford Algorithm:**
  Computes single‑source shortest paths even with negative weights and detects negative cycles.

- **A\* (A-Star) Algorithm:**
  Finds a shortest path from a source to a target using an admissible heuristic.

- **Floyd–Warshall Algorithm:**
  Computes all‑pairs shortest paths using dynamic programming.

- **Johnson’s Algorithm:**
  Computes all‑pairs shortest paths for sparse graphs (even with negative edge weights) by re-weighting the graph and then running Dijkstra’s algorithm from each node.

- **Iterative Deepening A\* (IDA\*):**
  A recursive, depth‑first variant of A\* search specialized for graphs with `f64` weights.
  The f64 is used instead of a generic weight type to simplify the implementation.

## Error Handling

Preconditions for each algorithm are enforced at runtime using `graphina::core::error::GraphinaError`.
For example, algorithms that require nonnegative edge weights will return a `Result` containing a
`GraphinaError::InvalidArgument` if a negative weight is encountered. Users should handle these
`Result` types accordingly.

*/

use crate::core::error::{GraphinaError, Result};
use crate::core::types::{BaseGraph, GraphConstructor, GraphinaGraph, NodeId, NodeMap};
use std::cmp::Reverse;
use std::collections::BinaryHeap;
use std::fmt::Debug;
use std::ops::{Add, Sub};

use ordered_float::NotNan;

/// Result type for pathfinding algorithms: (distances, predecessors).
pub type PathFindResult = (NodeMap<Option<f64>>, NodeMap<Option<NodeId>>);

/// Returns an iterator over outgoing edges from a given node as `(target, weight)`.
fn outgoing_edges<A, W, Ty>(
    graph: &BaseGraph<A, W, Ty>,
    u: NodeId,
) -> impl Iterator<Item = (NodeId, W)> + '_
where
    W: Copy,
    Ty: GraphConstructor<A, W>,
{
    // Delegate to the graph's own incident-edge iterator, which follows petgraph
    // adjacency: outgoing edges for a directed graph, and all incident edges for
    // an undirected graph. Filtering `graph.edges()` by source would miss the
    // undirected edges stored with `u` as the target.
    graph.outgoing_edges(u).map(|(tgt, w)| (tgt, *w))
}

/// Returns an upper bound on node indices, suitable for sizing a dense `Vec`
/// indexed by `NodeId::index()`.
///
/// `BaseGraph` wraps a `StableGraph`, so node indices are stable but not
/// necessarily contiguous after removals. Sizing by this bound (rather than
/// `node_count`) keeps `vec[id.index()]` in range while still allowing dense,
/// hash-free indexing in the inner loops.
fn index_bound<A, W, Ty>(graph: &BaseGraph<A, W, Ty>) -> usize
where
    Ty: GraphConstructor<A, W>,
{
    graph
        .node_ids()
        .map(|n| n.index())
        .max()
        .map_or(0, |m| m + 1)
}

/// Converts a dense, index-keyed slice of per-node values into the `NodeMap`
/// public return type, inserting one entry per existing node.
fn dense_to_nodemap<A, W, Ty, T>(graph: &BaseGraph<A, W, Ty>, dense: &[T]) -> NodeMap<T>
where
    T: Copy,
    Ty: GraphConstructor<A, W>,
{
    let mut map = NodeMap::with_capacity_and_hasher(graph.node_count(), rustc_hash::FxBuildHasher);
    for u in graph.node_ids() {
        map.insert(u, dense[u.index()]);
    }
    map
}

// ============================
// Dijkstra’s Algorithm
// ============================
//

/// Generic, Full implementationof Dijkstra's algorithm for finding shortest paths in a graph
/// with non-negative weights.
///
/// # Arguments
///
/// * `graph`: the target graph.
/// * `source`: the source of path finding.
/// * `cutoff`: the maximum total cost before stopping search.
/// * `eval_cost`: callback to evaluate the cost of possible edges in the graph, returning
///     - `Some(f64)` for cost,
///     - `None` for not passable edge.
///
/// # Returns
///
/// - `Vec<Option<f64>>` in which `None` for unreachable, and `Some(cost)` for the total path cost.
/// - `Vec<Option<NodeID>>` in which `None` for no traceback (i.e. is source or unreachable),
///   and `Some(NodeId)` for the previous node visited in the path.
///
/// # Error
///
/// return error, if encounter negative cost, or encounter `NaN` weight.
///
/// # Example
/// ```rust
/// use graphina::core::types::Digraph;
///
/// use graphina::core::paths::dijkstra_path_impl;
///
/// let mut graph: Digraph<String, (f64, String)> = Digraph::new();
/// //                             ^^^^^^^^^^^^^
/// //                                         L arbitrary type as edge
///
/// let cities = ["ATL", "PEK", "LHR", "HND", "CDG", "FRA", "HKG"];
///
/// let ids = cities
///     .iter()
///     .map(|s| graph.add_node(s.to_string()))
///     .collect::<Vec<_>>();
///
/// let edges = [
///     //
///     ("ATL", "PEK", (900.0, "boeing")),
///     ("ATL", "LHR", (500.0, "airbus")),
///     ("ATL", "HND", (700.0, "airbus")),
///     //
///     ("PEK", "LHR", (800.0, "boeing")),
///     ("PEK", "HND", (100.0, "airbus")),
///     ("PEK", "HKG", (100.0, "airbus")),
///     //
///     ("LHR", "CDG", (100.0, "airbus")),
///     ("LHR", "FRA", (200.0, "boeing")),
///     ("LHR", "HND", (600.0, "airbus")),
///     //
///     ("HND", "ATL", (700.0, "airbus")),
///     ("HND", "FRA", (600.0, "airbus")),
///     ("HND", "HKG", (100.0, "airbus")),
///     //
/// ];
///
/// for (s, d, w) in edges {
///     let depart = cities.iter().position(|city| s == *city).unwrap();
///     let destin = cities.iter().position(|city| d == *city).unwrap();
///     graph.add_edge(ids[depart], ids[destin], (w.0, w.1.to_string()));
/// }
///
/// // function for evaluating possible cost for the edge
/// // Some(f64) for cost
/// // None for impassable
/// let eval_cost = |(price, manufactuer): &(f64, String)| match manufactuer.as_str() {
///     "boeing" => None,  // avoid boeing plane
///     _ => Some(*price), // return price as the cost
/// };
///
/// let (cost, trace) = dijkstra_path_impl(&graph, ids[0], Some(1000.0), eval_cost).unwrap();
/// println!("cost : {:?}", cost);
/// println!("trace: {:?}", trace);
///
/// let expected_cost = [
///     Some(0.0),
///     None,
///     Some(500.0),
///     Some(700.0),
///     Some(600.0),
///     None,
///     Some(800.0),
/// ];
/// let expected_trace = [
///     None,
///     None,
///     Some(ids[0]),
///     Some(ids[0]),
///     Some(ids[2]),
///     None,
///     Some(ids[3]),
/// ];
///
/// for id in ids {
///     assert_eq!(cost[&id], expected_cost[id.index()]);
///     assert_eq!(trace[&id], expected_trace[id.index()]);
/// }
/// ```
pub fn dijkstra_path_impl<A, W, Ty>(
    graph: &BaseGraph<A, W, Ty>,
    source: NodeId,
    cutoff: Option<f64>,
    eval_cost: impl Fn(&W) -> Option<f64>,
) -> Result<PathFindResult>
where
    W: Debug,
    A: Debug,
    Ty: GraphConstructor<A, W>,
    NodeId: Ord,
    BaseGraph<A, W, Ty>: GraphinaGraph<A, W>,
{
    // Dense, index-keyed buffers (see `dijkstra`). A cutoff or impassable-edge
    // search may touch few nodes, but the return contract is a complete map (one
    // entry per node, `None` when unreachable), so we fill from the dense buffers
    // at the end rather than building two full maps up front.
    let bound = index_bound(graph);
    let mut dist: Vec<Option<f64>> = vec![None; bound];
    let mut trace: Vec<Option<NodeId>> = vec![None; bound];
    let mut heap = BinaryHeap::new();

    dist[source.index()] = Some(0.0);

    heap.push(Reverse((
        NotNan::new(0.0).unwrap_or_else(|_| NotNan::new(1.0).unwrap_or(NotNan::from(1))),
        source,
    )));

    while let Some(Reverse((d, u))) = heap.pop() {
        if let Some(current) = dist[u.index()] {
            if *d > current {
                continue;
            }
        }
        for (v, edge) in graph.outgoing_edges(u) {
            let Some(w) = eval_cost(edge) else {
                continue;
            };
            if w.is_sign_negative() {
                return Err(GraphinaError::invalid_argument(format!(
                    "Dijkstra requires nonnegative costs, but found cost: {:?}, src: {:?}, dst: {:?}, edge: {:?}",
                    w, u, v, edge
                )));
            }
            let Ok(w) = NotNan::new(w) else {
                return Err(GraphinaError::invalid_argument(format!(
                    "Dijkstra requires not NaN costs, but found cost: {:?}, src: {:?}, dst: {:?}, edge: {:?}",
                    w, u, v, edge
                )));
            };
            let next = d + w;
            if let Some(cutoff) = cutoff {
                if *next > cutoff {
                    continue;
                }
            }
            let vi = v.index();
            if dist[vi].is_none() || Some(*next) < dist[vi] {
                dist[vi] = Some(*next);
                trace[vi] = Some(u);
                heap.push(Reverse((next, v)));
            }
        }
    }
    Ok((
        dense_to_nodemap(graph, &dist),
        dense_to_nodemap(graph, &trace),
    ))
}

/// Full implementation of Dijkstra's algorithm for finding shortest paths in a graph
/// for graph with edge type `f64`
/// with non-negative weights.
///
/// # Arguments
///
/// * `graph`: the target graph.
/// * `source`: the source of path finding.
/// * `cutoff`: the maximum total cost before stopping search.
///
/// # Returns
///
/// - `Vec<Option<f64>>` in which `None` for unreachable, and `Some(cost)` for the total path cost.
/// - `Vec<Option<NodeID>>` in which `None` for no traceback (i.e. is source or unreachable),
///   and `Some(NodeId)` for the previous node visited in the path.
///
/// # Error
///
/// return error, if encounter negative cost, or encounter `NaN` weight.
///
/// # Example
/// ```rust
/// use graphina::core::types::Graph;
///
/// use graphina::core::paths::dijkstra_path_f64;
///
/// let mut graph = Graph::new();
/// let ids = (0..5).map(|i| graph.add_node(i)).collect::<Vec<_>>();
/// let edges = [(0, 1, 1.0), (1, 2, 1.0), (2, 3, 2.0), (3, 4, 1.0)];
/// for (s, d, w) in edges {
///     graph.add_edge(ids[s], ids[d], w);
/// }
///
/// let (cost, trace) = dijkstra_path_f64(&graph, ids[0], None).unwrap();
///
/// println!("cost : {:?}", cost);
/// println!("trace: {:?}", trace);
/// let expected_cost = [Some(0.0), Some(1.0), Some(2.0), Some(4.0), Some(5.0)];
/// let expected_trace = [None, Some(ids[0]), Some(ids[1]), Some(ids[2]), Some(ids[3])];
///
/// for id in ids {
///     assert_eq!(cost[&id], expected_cost[id.index()]);
///     assert_eq!(trace[&id], expected_trace[id.index()]);
/// }
/// ```
pub fn dijkstra_path_f64<A, Ty>(
    graph: &BaseGraph<A, f64, Ty>,
    source: NodeId,
    cutoff: Option<f64>,
) -> Result<PathFindResult>
where
    A: Debug,
    Ty: GraphConstructor<A, f64>,
    BaseGraph<A, f64, Ty>: GraphinaGraph<A, f64>,
{
    dijkstra_path_impl(graph, source, cutoff, |f| Some(*f))
}

/// Computes single‑source shortest paths for graphs with nonnegative weights.
///
/// # Returns
///
/// A `Result` containing a NodeMap keyed by node IDs, where each value is:
/// - `Some(cost)` if the node is reachable from the source, or
/// - `None` if it is unreachable.
///
/// Returns an `Err(GraphinaException)` if a negative edge weight is found.
///
/// # Complexity
///
/// - Time: O(E log V)
/// - Space: O(V)
pub fn dijkstra<A, W, Ty>(graph: &BaseGraph<A, W, Ty>, source: NodeId) -> Result<NodeMap<Option<W>>>
where
    W: Copy + PartialOrd + Add<Output = W> + Sub<Output = W> + From<u8> + Ord + Debug,
    Ty: GraphConstructor<A, W>,
    NodeId: Ord,
{
    // Dense, index-keyed distance buffer: `vec[id.index()]` is hash-free in the
    // inner loop. Converted to the `NodeMap` return type once at the end.
    let mut dist: Vec<Option<W>> = vec![None; index_bound(graph)];
    let mut heap = BinaryHeap::new();

    dist[source.index()] = Some(W::from(0u8));
    heap.push(Reverse((W::from(0u8), source)));

    while let Some(Reverse((d, u))) = heap.pop() {
        if let Some(current) = dist[u.index()] {
            if d > current {
                continue;
            }
        }
        for (v, w) in outgoing_edges(graph, u) {
            if w < W::from(0u8) {
                return Err(GraphinaError::invalid_argument(format!(
                    "Dijkstra requires nonnegative weights, but found weight: {:?}",
                    w
                )));
            }
            let next = d + w;
            let vi = v.index();
            if dist[vi].is_none() || Some(next) < dist[vi] {
                dist[vi] = Some(next);
                heap.push(Reverse((next, v)));
            }
        }
    }
    Ok(dense_to_nodemap(graph, &dist))
}

/// ============================
/// Bellman–Ford Algorithm
/// ============================
///
/// Computes single‑source shortest paths for graphs with negative weights.
/// Returns `Some(distances)` if no negative cycle is detected, or `None` otherwise.
///
/// # Complexity
///
/// - **Time:** O(VE)
/// - **Space:** O(V)
pub fn bellman_ford<A, W, Ty>(
    graph: &BaseGraph<A, W, Ty>,
    source: NodeId,
) -> Option<NodeMap<Option<W>>>
where
    W: Copy + PartialOrd + Add<Output = W> + From<u8>,
    Ty: GraphConstructor<A, W>,
{
    let n = graph.node_count();
    // Dense, index-keyed distance buffer (see `dijkstra`).
    let mut dist: Vec<Option<W>> = vec![None; index_bound(graph)];
    dist[source.index()] = Some(W::from(0u8));

    for _ in 0..n.saturating_sub(1) {
        let mut updated = false;
        // Relax via the per-node incident-edge iterator, which follows undirected
        // edges in both directions (iterating `graph.edges()` would relax each
        // stored edge in one direction only, leaving most nodes unreachable on an
        // undirected graph). This matches dijkstra.
        for u in graph.node_ids() {
            if let Some(du) = dist[u.index()] {
                for (v, w) in outgoing_edges(graph, u) {
                    let candidate = du + w;
                    let vi = v.index();
                    if dist[vi].is_none() || Some(candidate) < dist[vi] {
                        dist[vi] = Some(candidate);
                        updated = true;
                    }
                }
            }
        }
        if !updated {
            break;
        }
    }
    // Check for negative cycles.
    for u in graph.node_ids() {
        if let Some(du) = dist[u.index()] {
            for (v, w) in outgoing_edges(graph, u) {
                if let Some(dv) = dist[v.index()] {
                    if du + w < dv {
                        return None;
                    }
                }
            }
        }
    }
    Some(dense_to_nodemap(graph, &dist))
}

/// ============================
/// A* (A-Star) Algorithm
/// ============================
///
/// Finds a shortest path from `source` to `target` using an admissible heuristic.
///
/// # Preconditions
///
/// - The heuristic must be admissible (i.e., it never overestimates the true cost).
///
/// # Returns
///
/// A `Result` which is `Ok(Some((total_cost, path)))` if a path is found, `Ok(None)` if no path exists,
/// or an `Err(GraphinaException)` if a negative edge weight is found.
///
/// # Complexity
///
/// - **Time:** Worst-case \(O(E \log V)\)
/// - **Space:** \(O(V)\)
pub fn a_star<A, W, Ty, F>(
    graph: &BaseGraph<A, W, Ty>,
    source: NodeId,
    target: NodeId,
    heuristic: F,
) -> Result<Option<(W, Vec<NodeId>)>>
where
    W: Copy + PartialOrd + Add<Output = W> + Sub<Output = W> + From<u8> + Ord + Debug,
    Ty: GraphConstructor<A, W>,
    F: Fn(NodeId) -> W,
    NodeId: Ord,
{
    // Buffers are keyed by `NodeId::index()`, which stays stable across node
    // removal, so they must span the index bound (max live index + 1), not the
    // node count. Sizing by `node_count()` panics once a node has been removed.
    let n = index_bound(graph);
    let mut dist = vec![None; n];
    let mut prev = vec![None; n];
    let mut heap = BinaryHeap::new();

    dist[source.index()] = Some(W::from(0u8));
    heap.push(Reverse((W::from(0u8) + heuristic(source), source)));

    while let Some(Reverse((f, u))) = heap.pop() {
        if u == target {
            break;
        }
        if let Some(current) = dist[u.index()] {
            if f - heuristic(u) > current {
                continue;
            }
        }
        for (v, w) in outgoing_edges(graph, u) {
            if w < W::from(0u8) {
                return Err(GraphinaError::invalid_argument(format!(
                    "A* requires nonnegative weights, but found weight: {:?}",
                    w
                )));
            }
            let Some(u_dist) = dist[u.index()] else {
                continue;
            };
            let tentative = u_dist + w;
            if dist[v.index()].is_none() || Some(tentative) < dist[v.index()] {
                dist[v.index()] = Some(tentative);
                prev[v.index()] = Some(u);
                let priority = tentative + heuristic(v);
                heap.push(Reverse((priority, v)));
            }
        }
    }

    if let Some(goal_cost) = dist[target.index()] {
        let mut path = Vec::new();
        let mut cur = target;
        while cur != source {
            path.push(cur);
            cur = prev[cur.index()].ok_or_else(|| {
                GraphinaError::algorithm_error("Path reconstruction failed unexpectedly.")
            })?;
        }
        path.push(source);
        path.reverse();
        Ok(Some((goal_cost, path)))
    } else {
        Ok(None)
    }
}

/// ============================
/// Floyd–Warshall Algorithm
/// ============================
///
/// Computes all‑pairs shortest paths using dynamic programming.
/// Returns `Some(map)` where `map[u][v]` is:
///     - `Some(cost)` if a path from node `u` to `v` exists, or
///     - `None` if `v` is unreachable from `u`.
/// Returns `None` if a negative cycle is detected.
///
/// # Complexity
///
/// - **Time:** O(V^3)
/// - **Space:** O(V^2)
pub fn floyd_warshall<A, W, Ty>(graph: &BaseGraph<A, W, Ty>) -> Option<NodeMap<NodeMap<Option<W>>>>
where
    W: Copy + PartialOrd + Add<Output = W> + From<u8>,
    Ty: GraphConstructor<A, W>,
{
    let n = graph.node_count();
    let nodes: Vec<NodeId> = graph.node_ids().collect();
    // Map each NodeId to its position in `nodes`. NodeId indices are not guaranteed
    // to be contiguous (a StableGraph never recycles indices), so positions, not
    // raw indices, address the matrix.
    let pos: NodeMap<usize> = nodes.iter().enumerate().map(|(i, u)| (*u, i)).collect();

    let mut dist = vec![vec![None; n]; n];
    for (i, row) in dist.iter_mut().enumerate().take(n) {
        row[i] = Some(W::from(0u8));
    }
    // Populate via outgoing_edges so undirected edges (stored once) are recorded in
    // both directions, matching dijkstra and bellman_ford.
    for (i, &u) in nodes.iter().enumerate() {
        for (v, w) in outgoing_edges(graph, u) {
            let Some(&j) = pos.get(&v) else { continue };
            match dist[i][j] {
                Some(current) if w < current => dist[i][j] = Some(w),
                None => dist[i][j] = Some(w),
                _ => {}
            }
        }
    }
    for k in 0..n {
        for i in 0..n {
            for j in 0..n {
                if let (Some(dik), Some(dkj)) = (dist[i][k], dist[k][j]) {
                    let candidate = dik + dkj;
                    match dist[i][j] {
                        Some(dij) if candidate < dij => dist[i][j] = Some(candidate),
                        None => dist[i][j] = Some(candidate),
                        _ => {}
                    }
                }
            }
        }
    }
    for (i, row) in dist.iter_mut().enumerate().take(n) {
        row[i] = Some(W::from(0u8));
    }
    // Convert to NodeMap form
    let mut outer: NodeMap<NodeMap<Option<W>>> = NodeMap::default();
    for (i, u) in nodes.iter().enumerate() {
        let mut inner: NodeMap<Option<W>> = NodeMap::default();
        for (j, v) in nodes.iter().enumerate() {
            inner.insert(*v, dist[i][j]);
        }
        outer.insert(*u, inner);
    }
    Some(outer)
}

/// ============================
/// Johnson’s Algorithm
/// ============================
///
/// Computes all‑pairs shortest paths for sparse graphs (even with negative edge weights)
/// by reweighting the graph to eliminate negatives and then running Dijkstra’s algorithm from each node.
/// Returns `Some(map)` if no negative cycle is detected, or `None` otherwise.
///
/// # Complexity
///
/// - **Time:** O(VE \log V) (implementation uses a binary heap)
/// - **Space:** O(V^2)
pub fn johnson<A, W, Ty>(graph: &BaseGraph<A, W, Ty>) -> Option<NodeMap<NodeMap<Option<W>>>>
where
    W: Copy + PartialOrd + Add<Output = W> + Sub<Output = W> + From<u8> + Ord,
    Ty: GraphConstructor<A, W>,
{
    // Potentials `h` and per-source distances `d` are keyed by `NodeId::index()`,
    // which is stable across node removal, so they span the index bound rather
    // than the node count. The output matrix `dist[i][j]` stays contiguous, keyed
    // by position in `nodes`. Mixing the two index spaces (as the previous version
    // did) is wrong whenever a node has been removed.
    let bound = index_bound(graph);
    let node_count = graph.node_count();
    let mut h = vec![W::from(0u8); bound];

    // Relax edges for node_count - 1 iterations.
    for _ in 0..node_count.saturating_sub(1) {
        let mut updated = false;
        for (u, v, &w) in graph.edges() {
            let ui = u.index();
            let vi = v.index();
            if h[ui] + w < h[vi] {
                h[vi] = h[ui] + w;
                updated = true;
            }
        }
        if !updated {
            break;
        }
    }
    // Check for negative cycles.
    for (u, v, &w) in graph.edges() {
        let ui = u.index();
        let vi = v.index();
        if h[ui] + w < h[vi] {
            return None;
        }
    }

    // Contiguous list of nodes; `dist[i][j]` is keyed by position here.
    let nodes: Vec<NodeId> = graph.nodes().map(|(node, _)| node).collect();
    let n = nodes.len();

    let mut dist = vec![vec![None; n]; n];
    for (i, &start) in nodes.iter().enumerate() {
        let mut d = vec![None; bound];
        d[start.index()] = Some(W::from(0u8));
        let mut heap = BinaryHeap::new();
        heap.push(Reverse((W::from(0u8), start)));
        while let Some(Reverse((du, current))) = heap.pop() {
            let ci = current.index();
            if let Some(cur) = d[ci] {
                if du > cur {
                    continue;
                }
            }
            for (v, w) in outgoing_edges(graph, current) {
                let vi = v.index();
                let new_w = w + h[current.index()] - h[vi];
                let nd = du + new_w;
                if d[vi].is_none() || Some(nd) < d[vi] {
                    d[vi] = Some(nd);
                    heap.push(Reverse((nd, v)));
                }
            }
        }
        for (j, &v) in nodes.iter().enumerate() {
            if let Some(dprime) = d[v.index()] {
                dist[i][j] = Some(dprime - h[start.index()] + h[v.index()]);
            }
        }
    }
    // Convert to NodeMap form
    let mut outer: NodeMap<NodeMap<Option<W>>> = NodeMap::default();
    for (i, u) in nodes.iter().enumerate() {
        let mut inner: NodeMap<Option<W>> = NodeMap::default();
        for (j, v) in nodes.iter().enumerate() {
            inner.insert(*v, dist[i][j]);
        }
        outer.insert(*u, inner);
    }
    Some(outer)
}

#[cfg(test)]
mod tests {

    #[test]
    fn test_dijkstra_negative_weights() {
        use crate::core::paths::dijkstra_path_f64;
        use crate::core::types::Graph;

        let mut g = Graph::<i32, f64>::new();
        let n1 = g.add_node(1);
        let n2 = g.add_node(2);

        g.add_edge(n1, n2, -5.0);

        let result = dijkstra_path_f64(&g, n1, None);
        assert!(result.is_err());
    }

    // Regression: the generic Dijkstra followed only the stored edge orientation,
    // so on an undirected graph a node reached via an edge stored as (other, node)
    // could not reach back. Here the edges are stored as (0,1) and (1,2); from node
    // 2, Dijkstra must still reach node 0 at distance 2.
    #[test]
    fn test_dijkstra_undirected_follows_both_directions() {
        use crate::core::paths::dijkstra;
        use crate::core::types::Graph;

        let mut g = Graph::<i32, i32>::new();
        let n0 = g.add_node(0);
        let n1 = g.add_node(1);
        let n2 = g.add_node(2);
        g.add_edge(n0, n1, 1);
        g.add_edge(n1, n2, 1);

        let dist = dijkstra(&g, n2).expect("dijkstra should succeed");
        assert_eq!(dist[&n2], Some(0));
        assert_eq!(dist[&n1], Some(1));
        assert_eq!(dist[&n0], Some(2), "node 0 must be reachable from node 2");
    }

    // Regression: bellman_ford relaxed each stored edge in one direction only, so on
    // an undirected graph it left nodes reachable only against the stored edge
    // orientation unreachable, disagreeing with dijkstra. It must follow undirected
    // edges in both directions.
    #[test]
    fn test_bellman_ford_undirected_follows_both_directions() {
        use crate::core::paths::bellman_ford;
        use crate::core::types::Graph;

        let mut g = Graph::<i32, i32>::new();
        let n0 = g.add_node(0);
        let n1 = g.add_node(1);
        let n2 = g.add_node(2);
        g.add_edge(n0, n1, 1);
        g.add_edge(n1, n2, 1);

        let dist = bellman_ford(&g, n2).expect("bellman_ford should succeed");
        assert_eq!(dist[&n2], Some(0));
        assert_eq!(dist[&n1], Some(1));
        assert_eq!(dist[&n0], Some(2), "node 0 must be reachable from node 2");
    }

    // Regression: floyd_warshall initialized its distance matrix by iterating
    // graph.edges() and writing only dist[u][v], never dist[v][u]. On an undirected
    // graph (edges stored once) the all-pairs matrix came out asymmetric and most
    // pairs unreachable, inconsistent with dijkstra and bellman_ford.
    #[test]
    fn test_floyd_warshall_undirected_follows_both_directions() {
        use crate::core::paths::floyd_warshall;
        use crate::core::types::Graph;

        let mut g = Graph::<i32, i32>::new();
        let n0 = g.add_node(0);
        let n1 = g.add_node(1);
        let n2 = g.add_node(2);
        g.add_edge(n0, n1, 1);
        g.add_edge(n1, n2, 1);

        let matrix = floyd_warshall(&g).expect("floyd_warshall should succeed");
        assert_eq!(
            matrix[&n2][&n0],
            Some(2),
            "node 0 must be reachable from node 2"
        );
        assert_eq!(matrix[&n0][&n2], Some(2), "matrix must be symmetric");
        assert_eq!(matrix[&n1][&n0], Some(1));
        assert_eq!(matrix[&n0][&n1], Some(1));
    }

    #[test]
    fn test_a_star_after_node_removal_no_panic() {
        use crate::core::types::Digraph;
        // `a_star` sized its dense buffers by `node_count()` and indexed them by
        // `NodeId::index()`. Because `NodeId`s are stable across removal, removing a
        // node leaves a live index above `node_count()`, so the buffer access panicked
        // out of bounds. It must size by the index bound instead, like `dijkstra`.
        use crate::core::paths::a_star;

        let mut g: Digraph<i32, i32> = Digraph::new();
        let a = g.add_node(0);
        let b = g.add_node(1);
        let c = g.add_node(2);
        let d = g.add_node(3);
        g.remove_node(b); // index 3 (d) is now live while node_count() is 3
        g.add_edge(a, c, 1);
        g.add_edge(c, d, 1);

        let result = a_star(&g, a, d, |_| 0).unwrap();
        assert_eq!(result.map(|(cost, _)| cost), Some(2));
    }

    #[test]
    fn test_johnson_after_node_removal_no_panic() {
        use crate::core::types::Digraph;
        // Same stable-index defect as `a_star`, compounded by `johnson` mixing
        // contiguous `0..n` indices with `NodeId::index()`.
        use crate::core::paths::johnson;

        let mut g: Digraph<i32, i32> = Digraph::new();
        let a = g.add_node(0);
        let b = g.add_node(1);
        let c = g.add_node(2);
        let d = g.add_node(3);
        g.remove_node(b);
        g.add_edge(a, c, 1);
        g.add_edge(c, d, 1);

        let all_pairs = johnson(&g).unwrap();
        assert_eq!(all_pairs[&a][&d], Some(2));
        assert_eq!(all_pairs[&a][&c], Some(1));
        assert_eq!(all_pairs[&d][&a], None);
    }
    use super::*;
    use crate::core::types::{Digraph, NodeId};
    use ordered_float::OrderedFloat;
    use std::collections::HashMap;
    fn build_test_graph_ordered() -> (Digraph<i32, OrderedFloat<f64>>, HashMap<i32, NodeId>) {
        let mut graph: Digraph<i32, OrderedFloat<f64>> = Digraph::default();
        let mut nodes = HashMap::new();
        nodes.insert(0, graph.add_node(0));
        nodes.insert(1, graph.add_node(1));
        nodes.insert(2, graph.add_node(2));
        nodes.insert(3, graph.add_node(3));
        graph.add_edge(nodes[&0], nodes[&1], OrderedFloat(1.0));
        graph.add_edge(nodes[&0], nodes[&2], OrderedFloat(4.0));
        graph.add_edge(nodes[&1], nodes[&2], OrderedFloat(2.0));
        graph.add_edge(nodes[&1], nodes[&3], OrderedFloat(6.0));
        graph.add_edge(nodes[&2], nodes[&3], OrderedFloat(3.0));
        (graph, nodes)
    }
    #[test]
    fn test_dijkstra_directed() {
        let (graph, nodes) = build_test_graph_ordered();
        let n0 = nodes[&0];
        let n3 = nodes[&3];
        let dist = dijkstra(&graph, n0).unwrap();
        assert_eq!(dist[&n3], Some(OrderedFloat(6.0)));
    }
    #[test]
    fn test_bellman_ford_directed() {
        let (graph, nodes) = build_test_graph_ordered();
        let n0 = nodes[&0];
        let n3 = nodes[&3];
        let dist = bellman_ford(&graph, n0).expect("No negative cycle");
        assert_eq!(dist[&n3], Some(OrderedFloat(6.0)));
    }
    #[test]
    fn test_bellman_ford_undirected() {
        // Path 0-1-2-3 on an undirected graph, with each edge stored in the
        // reverse orientation (higher index as source). Bellman-Ford must follow
        // undirected edges in both directions, matching dijkstra, so every node
        // is reachable from node 0.
        use crate::core::types::Graph;
        let mut graph: Graph<i32, OrderedFloat<f64>> = Graph::default();
        let n0 = graph.add_node(0);
        let n1 = graph.add_node(1);
        let n2 = graph.add_node(2);
        let n3 = graph.add_node(3);
        graph.add_edge(n1, n0, OrderedFloat(1.0));
        graph.add_edge(n2, n1, OrderedFloat(2.0));
        graph.add_edge(n3, n2, OrderedFloat(3.0));
        let dist = bellman_ford(&graph, n0).expect("No negative cycle");
        assert_eq!(dist[&n1], Some(OrderedFloat(1.0)));
        assert_eq!(dist[&n2], Some(OrderedFloat(3.0)));
        assert_eq!(dist[&n3], Some(OrderedFloat(6.0)));
    }
    #[test]
    fn test_a_star_directed() {
        let (graph, nodes) = build_test_graph_ordered();
        let n0 = nodes[&0];
        let n1 = nodes[&1];
        let n2 = nodes[&2];
        let n3 = nodes[&3];
        let result = a_star(&graph, n0, n3, |_| OrderedFloat(0.0));
        assert!(result.is_ok());
        let path_opt = result.unwrap();
        assert!(path_opt.is_some());
        let (cost, path) = path_opt.unwrap();
        assert_eq!(cost, OrderedFloat(6.0));
        assert_eq!(path, vec![n0, n1, n2, n3]);
    }
    #[test]
    fn test_floyd_warshall_directed() {
        let (graph, nodes) = build_test_graph_ordered();
        let n0 = nodes[&0];
        let n3 = nodes[&3];
        let matrix = floyd_warshall(&graph).expect("No negative cycle");
        assert_eq!(matrix[&n0][&n3], Some(OrderedFloat(6.0)));
    }
    #[test]
    fn test_floyd_warshall_undirected() {
        // Path 0-1-2-3 on an undirected graph, with each edge stored in the
        // reverse orientation. Floyd-Warshall must record undirected edges in both
        // directions, so the all-pairs matrix is symmetric and every pair reachable.
        use crate::core::types::Graph;
        let mut graph: Graph<i32, OrderedFloat<f64>> = Graph::default();
        let n0 = graph.add_node(0);
        let n1 = graph.add_node(1);
        let n2 = graph.add_node(2);
        let n3 = graph.add_node(3);
        graph.add_edge(n1, n0, OrderedFloat(1.0));
        graph.add_edge(n2, n1, OrderedFloat(2.0));
        graph.add_edge(n3, n2, OrderedFloat(3.0));
        let matrix = floyd_warshall(&graph).expect("No negative cycle");
        assert_eq!(matrix[&n0][&n3], Some(OrderedFloat(6.0)));
        assert_eq!(matrix[&n3][&n0], Some(OrderedFloat(6.0)));
        assert_eq!(matrix[&n0][&n2], Some(OrderedFloat(3.0)));
        assert_eq!(matrix[&n1][&n3], Some(OrderedFloat(5.0)));
    }
}