graphways 0.4.0

Fast OpenStreetMap reachability, routing, and isochrones from Python, powered by Rust -- no routing server required.
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
//! Network-time prisms: "which nodes can I visit between origin and destination
//! within a given time budget, and how much slack remains?"
//!
//! # Concept
//!
//! A node `v` is *feasible* if:
//!
//! ```text
//! inbound_time(origin → v) + outbound_time(v → destination) ≤ available_time
//! ```
//!
//! The leftover is the *slack*:
//!
//! ```text
//! slack = available_time − inbound_time − outbound_time
//! ```
//!
//! Callers control what the slack means at the product level:
//! - Pass `available_time = total_window − activity_duration − buffer` to bake
//!   in an activity and a safety margin before calling.
//! - Use `min_slack` in [`build_feasibility_polygon`] to ask "where can I stop
//!   and still have ≥ N seconds left?"
//!
//! # Design notes
//!
//! - The reverse Dijkstra runs on the *reversed* graph so that
//!   `outbound_time(v → destination)` is computed as a single one-to-many
//!   search from `destination` rather than N individual searches.
//! - `NetworkType` is threaded through so walk / bike / drive travel times are
//!   respected consistently.
//! - [`compute_feasibility`] returns `Err(InfeasibleReason)` when the trip
//!   cannot be completed within the budget at all, giving callers a clear
//!   signal to surface to users rather than an opaque empty result.

use std::collections::HashMap;

use geo::{ConvexHull, MultiPoint, Polygon};
use petgraph::algo::dijkstra;
use petgraph::graph::{DiGraph, NodeIndex};
use petgraph::visit::EdgeRef;

use crate::graph::{node_to_latlon, SpatialGraph, XmlNode, XmlWay};
use crate::overpass::NetworkType;
use crate::reachability::EdgeInfo;

// ---------------------------------------------------------------------------
// Public types
// ---------------------------------------------------------------------------

/// Per-node feasibility data for a single origin → destination query.
#[derive(Debug, Clone)]
pub struct FeasibleNode {
    /// Travel time from origin to this node (seconds).
    pub inbound_time: f64,
    /// Travel time from this node to destination (seconds).
    pub outbound_time: f64,
    /// Remaining time after visiting this node:
    /// `available_time − inbound_time − outbound_time`.
    pub slack: f64,
}

/// Full result of a successful [`compute_feasibility`] call.
#[derive(Debug, Clone)]
pub struct FeasibilityResult {
    /// The origin node used for the forward search.
    pub origin: NodeIndex,
    /// The destination node used for the reverse search.
    pub destination: NodeIndex,
    /// The time budget passed by the caller (seconds).
    pub available_time: f64,
    /// The minimum travel time from origin to destination (seconds).
    /// This is the floor: `available_time` must be ≥ this for any node to be
    /// feasible. Stored here so callers can report headroom to users.
    pub direct_time: f64,
    /// Every node whose `inbound + outbound ≤ available_time`, keyed by
    /// `NodeIndex`. Nodes that are unreachable in either direction are absent.
    pub feasible: HashMap<NodeIndex, FeasibleNode>,
}

/// Reason a feasibility query cannot produce any results.
#[derive(Debug, Clone, PartialEq)]
pub enum InfeasibleReason {
    /// The shortest path from origin to destination already exceeds the budget.
    ///
    /// `direct_time` is the actual travel time; `available_time` is what was
    /// requested. The shortfall is `direct_time − available_time`.
    BudgetTooTight {
        direct_time: f64,
        available_time: f64,
    },
    /// No path exists between origin and destination in the graph.
    NoPathExists,
}

impl std::fmt::Display for InfeasibleReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            InfeasibleReason::BudgetTooTight {
                direct_time,
                available_time,
            } => write!(
                f,
                "budget too tight: direct travel time is {direct_time:.0} s \
                 but available time is only {available_time:.0} s \
                 (shortfall: {:.0} s)",
                direct_time - available_time
            ),
            InfeasibleReason::NoPathExists => {
                write!(f, "no path exists between origin and destination")
            }
        }
    }
}

impl std::error::Error for InfeasibleReason {}

/// Graph-shaped view for a two-ended, time-bounded query.
///
/// A `PrismGraph` represents the nodes that can be reached from an
/// origin and can still reach a destination within the available travel-time
/// budget. It keeps the original graph and the inbound, outbound, and slack
/// labels, and only materializes an induced subgraph when a constrained
/// operation needs one.
#[derive(Clone)]
pub struct PrismGraph {
    /// Parent graph. The prism node set is stored in `result`.
    pub graph: SpatialGraph,
    pub result: FeasibilityResult,
    pub network_type: NetworkType,
}

// ---------------------------------------------------------------------------
// Core computation
// ---------------------------------------------------------------------------

/// Compute which nodes are reachable from `origin` *and* can reach
/// `destination` within `available_time` seconds.
///
/// Returns `Err(InfeasibleReason::NoPathExists)` when origin and destination
/// are disconnected, and `Err(InfeasibleReason::BudgetTooTight)` when the
/// direct travel time already exceeds `available_time`. Both cases carry
/// enough information for callers to produce a meaningful error message.
///
/// # Arguments
///
/// * `graph`          – The road network.
/// * `origin`         – Starting node index.
/// * `destination`    – Ending node index.
/// * `available_time` – Total time budget in seconds. Subtract any activity
///   duration or buffer *before* calling.
/// * `network_type`   – Determines which edge weight (walk / bike / drive) is used.
///
/// Compute two-sided feasibility with a caller-supplied edge cost.
///
/// The closure is invoked once per edge relaxation in *both* the forward and
/// reverse Dijkstra searches. In each invocation the [`EdgeInfo`] reflects the
/// edge's *original* graph orientation — `source` and `target` are not flipped
/// for the reverse search — so cost models keyed by edge identity, density, or
/// node position see a consistent view in both directions.
///
/// Use this when injecting density-based traffic penalties, externally-supplied
/// traffic multipliers, or any custom cost. Costs must be non-negative and
/// finite or Dijkstra's invariants break.
pub fn compute_feasibility_with<F>(
    graph: &DiGraph<XmlNode, XmlWay>,
    origin: NodeIndex,
    destination: NodeIndex,
    available_time: f64,
    mut cost: F,
) -> Result<FeasibilityResult, InfeasibleReason>
where
    F: FnMut(EdgeInfo<'_>) -> f64,
{
    // Forward search: origin → all nodes.
    let forward = dijkstra(graph, origin, None, |e| {
        cost(EdgeInfo {
            id: e.id(),
            source: e.source(),
            target: e.target(),
            weight: e.weight(),
        })
    });

    // Fast-path checks before running the (more expensive) reverse search.
    let direct_time = match forward.get(&destination) {
        Some(&t) => t,
        None => return Err(InfeasibleReason::NoPathExists),
    };

    if direct_time > available_time {
        return Err(InfeasibleReason::BudgetTooTight {
            direct_time,
            available_time,
        });
    }

    // Reverse search: destination → all nodes on the *reversed* graph.
    // petgraph's `Reversed` wrapper flips edge direction without copying the graph.
    // We translate the reversed edge's id back to the original endpoints so the
    // closure always sees the edge in its forward orientation.
    let reversed = petgraph::visit::Reversed(graph);
    let backward = dijkstra(reversed, destination, None, |e| {
        let id = e.id();
        let (source, target) = graph.edge_endpoints(id).unwrap();
        let weight = graph.edge_weight(id).unwrap();
        cost(EdgeInfo {
            id,
            source,
            target,
            weight,
        })
    });

    // Intersect: keep only nodes present in both searches whose combined cost
    // fits within the budget.
    let mut feasible = HashMap::new();
    for (&node, &inbound) in &forward {
        if inbound > available_time {
            continue;
        }
        if let Some(&outbound) = backward.get(&node) {
            let total = inbound + outbound;
            if total <= available_time {
                feasible.insert(
                    node,
                    FeasibleNode {
                        inbound_time: inbound,
                        outbound_time: outbound,
                        slack: available_time - total,
                    },
                );
            }
        }
    }

    Ok(FeasibilityResult {
        origin,
        destination,
        available_time,
        direct_time,
        feasible,
    })
}

/// Compute two-sided feasibility using the precomputed walk/bike/drive travel
/// time on each edge.
///
/// Convenience wrapper around [`compute_feasibility_with`]. For custom cost
/// models (traffic, density penalties), call `compute_feasibility_with` directly.
pub fn compute_feasibility(
    graph: &DiGraph<XmlNode, XmlWay>,
    origin: NodeIndex,
    destination: NodeIndex,
    available_time: f64,
    network_type: NetworkType,
) -> Result<FeasibilityResult, InfeasibleReason> {
    compute_feasibility_with(graph, origin, destination, available_time, |e| {
        e.weight.travel_time(network_type)
    })
}

// ---------------------------------------------------------------------------
// Polygon construction
// ---------------------------------------------------------------------------

/// Build a polygon enclosing all feasible nodes whose slack ≥ `min_slack`.
///
/// # Arguments
///
/// * `graph`     – The road network (needed to look up node coordinates).
/// * `result`    – Output of [`compute_feasibility`].
/// * `min_slack` – Minimum remaining slack (seconds) a node must have to be
///   included. Pass `0.0` to include every feasible node.
///
/// Returns `None` if fewer than three qualifying nodes exist (a polygon cannot
/// be formed).
pub fn build_feasibility_polygon(
    graph: &DiGraph<XmlNode, XmlWay>,
    result: &FeasibilityResult,
    min_slack: f64,
) -> Option<Polygon> {
    let points: MultiPoint<f64> = result
        .feasible
        .iter()
        .filter(|(_, n)| n.slack >= min_slack)
        .map(|(&idx, _)| node_to_latlon(graph, idx))
        .collect::<Vec<_>>()
        .into();

    if points.0.len() < 3 {
        return None;
    }

    Some(points.convex_hull())
}

// ---------------------------------------------------------------------------
// SpatialGraph entry points
// ---------------------------------------------------------------------------

fn prism_subgraph(sg: &SpatialGraph, result: &FeasibilityResult) -> SpatialGraph {
    let mut subgraph = DiGraph::new();
    let mut old_to_new = HashMap::new();

    for &old_idx in result.feasible.keys() {
        let new_idx = subgraph.add_node(sg.graph[old_idx].clone());
        old_to_new.insert(old_idx, new_idx);
    }

    for edge in sg.graph.edge_references() {
        let (Some(&source), Some(&target)) = (
            old_to_new.get(&edge.source()),
            old_to_new.get(&edge.target()),
        ) else {
            continue;
        };
        subgraph.add_edge(source, target, edge.weight().clone());
    }

    SpatialGraph::new(subgraph)
}

impl PrismGraph {
    pub fn node_count(&self) -> usize {
        self.result.feasible.len()
    }

    pub fn edge_count(&self) -> usize {
        self.graph
            .graph
            .edge_references()
            .filter(|edge| {
                self.result.feasible.contains_key(&edge.source())
                    && self.result.feasible.contains_key(&edge.target())
            })
            .count()
    }

    pub fn contains_node_id(&self, node_id: i64) -> bool {
        self.result
            .feasible
            .keys()
            .any(|&idx| self.graph.graph[idx].id == node_id)
    }

    pub fn slack_at_node_id(&self, node_id: i64) -> Option<f64> {
        self.result
            .feasible
            .iter()
            .find_map(|(&idx, node)| (self.graph.graph[idx].id == node_id).then_some(node.slack))
    }

    pub fn materialize(&self) -> SpatialGraph {
        prism_subgraph(&self.graph, &self.result)
    }

    pub fn route(
        &self,
        origin_lat: f64,
        origin_lon: f64,
        dest_lat: f64,
        dest_lon: f64,
        max_snap_m: Option<f64>,
    ) -> Result<crate::routing::Route, crate::error::OsmGraphError> {
        self.materialize().route(
            origin_lat,
            origin_lon,
            dest_lat,
            dest_lon,
            self.network_type,
            max_snap_m,
        )
    }

    pub fn isochrones(
        &self,
        lat: f64,
        lon: f64,
        time_limits: Vec<f64>,
        max_snap_m: Option<f64>,
    ) -> Option<Vec<geo::Polygon>> {
        self.materialize()
            .isochrones(lat, lon, time_limits, self.network_type, max_snap_m)
    }
}

impl SpatialGraph {
    /// Return the network-time prism between two coordinates.
    ///
    /// The result is a lightweight graph view over every node `v` satisfying
    /// `origin -> v -> destination <= available_time`, with each node labeled
    /// by inbound time, outbound time, and slack.
    #[allow(clippy::too_many_arguments)]
    pub fn prism(
        &self,
        origin_lat: f64,
        origin_lon: f64,
        dest_lat: f64,
        dest_lon: f64,
        available_time: f64,
        network_type: NetworkType,
        max_snap_m: Option<f64>,
    ) -> Option<Result<PrismGraph, InfeasibleReason>> {
        let origin = self.nearest_node_within(origin_lat, origin_lon, max_snap_m)?;
        let destination = self.nearest_node_within(dest_lat, dest_lon, max_snap_m)?;
        let result = compute_feasibility(
            &self.graph,
            origin,
            destination,
            available_time,
            network_type,
        );
        Some(result.map(|result| PrismGraph {
            graph: self.clone(),
            result,
            network_type,
        }))
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::{create_graph, XmlNode, XmlNodeRef, XmlTag, XmlWay};
    use crate::overpass::NetworkType;

    // ------------------------------------------------------------------
    // Helpers
    // ------------------------------------------------------------------

    fn node(id: i64, lat: f64, lon: f64) -> XmlNode {
        XmlNode {
            id,
            lat,
            lon,
            tags: vec![],
        }
    }

    fn way(node_ids: Vec<i64>) -> XmlWay {
        XmlWay {
            id: 1,
            nodes: node_ids
                .into_iter()
                .map(|id| XmlNodeRef { node_id: id })
                .collect(),
            tags: vec![XmlTag {
                key: "highway".into(),
                value: "residential".into(),
            }],
            length: 0.0,
            speed_kph: 0.0,
            walk_travel_time: 0.0,
            bike_travel_time: 0.0,
            drive_travel_time: 0.0,
            geometry: Vec::new(),
        }
    }

    /// Linear graph:  A ─── B ─── C ─── D  (~111 m between each node)
    fn linear_graph() -> DiGraph<XmlNode, XmlWay> {
        let nodes = vec![
            node(1, 0.000, 0.0),
            node(2, 0.001, 0.0),
            node(3, 0.002, 0.0),
            node(4, 0.003, 0.0),
        ];
        create_graph(
            nodes,
            vec![way(vec![1, 2, 3, 4])],
            /*retain_all=*/ true,
            false,
        )
    }

    fn find_node(g: &DiGraph<XmlNode, XmlWay>, osm_id: i64) -> NodeIndex {
        g.node_indices().find(|&i| g[i].id == osm_id).unwrap()
    }

    /// Convenience: run with a generous budget and unwrap — used by tests that
    /// only care about the happy path.
    fn feasibility_ok(
        g: &DiGraph<XmlNode, XmlWay>,
        origin: NodeIndex,
        dest: NodeIndex,
        budget: f64,
    ) -> FeasibilityResult {
        compute_feasibility(g, origin, dest, budget, NetworkType::Drive)
            .expect("expected Ok but got Err")
    }

    // ------------------------------------------------------------------
    // Happy-path correctness
    // ------------------------------------------------------------------

    #[test]
    fn feasible_nodes_satisfy_budget() {
        let g = linear_graph();
        let origin = find_node(&g, 1);
        let dest = find_node(&g, 4);
        let result = feasibility_ok(&g, origin, dest, 10_000.0);

        for (_, n) in &result.feasible {
            assert!(
                n.inbound_time + n.outbound_time <= result.available_time + 1e-9,
                "node violates budget: inbound={} outbound={} budget={}",
                n.inbound_time,
                n.outbound_time,
                result.available_time
            );
            assert!(
                n.slack >= -1e-9,
                "slack must be non-negative, got {}",
                n.slack
            );
        }
    }

    #[test]
    fn origin_and_destination_are_feasible() {
        let g = linear_graph();
        let origin = find_node(&g, 1);
        let dest = find_node(&g, 4);
        let result = feasibility_ok(&g, origin, dest, 10_000.0);

        let o = result
            .feasible
            .get(&origin)
            .expect("origin must be feasible");
        assert_eq!(o.inbound_time, 0.0, "origin inbound should be 0");

        let d = result
            .feasible
            .get(&dest)
            .expect("destination must be feasible");
        assert_eq!(d.outbound_time, 0.0, "destination outbound should be 0");
    }

    #[test]
    fn prism_graph_view_exposes_induced_counts_and_slack_labels() {
        let sg = SpatialGraph::new(linear_graph());
        let prism = sg
            .prism(0.0, 0.0, 0.003, 0.0, 10_000.0, NetworkType::Drive, None)
            .expect("origin and destination should snap")
            .expect("budget should be feasible");

        assert_eq!(prism.node_count(), 4);
        assert_eq!(prism.edge_count(), 6);
        assert!(prism.contains_node_id(1));
        assert!(prism.contains_node_id(4));
        assert!(prism.slack_at_node_id(2).is_some());
        assert_eq!(prism.graph.graph.node_count(), 4);
        assert_eq!(
            prism.materialize().graph.node_count(),
            prism.result.feasible.len()
        );
    }

    #[test]
    fn slack_equals_budget_minus_travel_times() {
        let g = linear_graph();
        let origin = find_node(&g, 1);
        let dest = find_node(&g, 4);
        let result = feasibility_ok(&g, origin, dest, 10_000.0);

        for (_, n) in &result.feasible {
            let expected = result.available_time - n.inbound_time - n.outbound_time;
            assert!(
                (n.slack - expected).abs() < 1e-9,
                "slack mismatch: got {} expected {}",
                n.slack,
                expected
            );
        }
    }

    #[test]
    fn direct_time_stored_in_result() {
        let g = linear_graph();
        let origin = find_node(&g, 1);
        let dest = find_node(&g, 4);
        let result = feasibility_ok(&g, origin, dest, 10_000.0);

        // direct_time must equal the destination's inbound_time (shortest path).
        let dest_node = result.feasible.get(&dest).unwrap();
        assert!(
            (result.direct_time - dest_node.inbound_time).abs() < 1e-9,
            "direct_time {} != destination inbound_time {}",
            result.direct_time,
            dest_node.inbound_time
        );
    }

    // ------------------------------------------------------------------
    // InfeasibleReason::BudgetTooTight
    // ------------------------------------------------------------------

    #[test]
    fn budget_too_tight_returns_err() {
        let g = linear_graph();
        let origin = find_node(&g, 1);
        let dest = find_node(&g, 4);

        // First learn the direct time with a generous budget.
        let direct_time = feasibility_ok(&g, origin, dest, 10_000.0).direct_time;

        // Budget just 1 second short of the direct trip.
        let err = compute_feasibility(&g, origin, dest, direct_time - 1.0, NetworkType::Drive)
            .expect_err("expected BudgetTooTight");

        match err {
            InfeasibleReason::BudgetTooTight {
                direct_time: dt,
                available_time: at,
            } => {
                assert!(dt > at, "direct_time should exceed available_time");
                assert!(
                    (dt - direct_time).abs() < 1e-9,
                    "reported direct_time {} doesn't match actual {}",
                    dt,
                    direct_time
                );
            }
            other => panic!("expected BudgetTooTight, got {:?}", other),
        }
    }

    #[test]
    fn budget_too_tight_shortfall_is_correct() {
        let g = linear_graph();
        let origin = find_node(&g, 1);
        let dest = find_node(&g, 4);
        let direct_time = feasibility_ok(&g, origin, dest, 10_000.0).direct_time;

        let shortfall = 42.0;
        let budget = direct_time - shortfall;
        let err = compute_feasibility(&g, origin, dest, budget, NetworkType::Drive)
            .expect_err("expected BudgetTooTight");

        if let InfeasibleReason::BudgetTooTight {
            direct_time: dt,
            available_time: at,
        } = err
        {
            assert!(
                ((dt - at) - shortfall).abs() < 1e-9,
                "shortfall should be {shortfall} but got {}",
                dt - at
            );
        }
    }

    #[test]
    fn budget_exactly_equal_to_direct_time_is_ok() {
        let g = linear_graph();
        let origin = find_node(&g, 1);
        let dest = find_node(&g, 4);
        let direct_time = feasibility_ok(&g, origin, dest, 10_000.0).direct_time;

        // Exactly at the boundary should succeed (≤, not <).
        let result = compute_feasibility(&g, origin, dest, direct_time, NetworkType::Drive)
            .expect("budget == direct_time should be Ok");

        assert!(result.feasible.contains_key(&dest));
        assert!(result.feasible.contains_key(&origin));
    }

    // ------------------------------------------------------------------
    // InfeasibleReason::NoPathExists
    // ------------------------------------------------------------------

    #[test]
    fn disconnected_graph_returns_no_path() {
        // Two isolated nodes with no edges between them.
        let mut g: DiGraph<XmlNode, XmlWay> = DiGraph::new();
        let a = g.add_node(node(1, 0.0, 0.0));
        let b = g.add_node(node(2, 1.0, 1.0));

        let err = compute_feasibility(&g, a, b, 10_000.0, NetworkType::Drive)
            .expect_err("expected NoPathExists");

        assert_eq!(err, InfeasibleReason::NoPathExists);
    }

    // ------------------------------------------------------------------
    // Display / error trait
    // ------------------------------------------------------------------

    #[test]
    fn budget_too_tight_display_mentions_shortfall() {
        let err = InfeasibleReason::BudgetTooTight {
            direct_time: 3600.0,
            available_time: 1800.0,
        };
        let msg = err.to_string();
        assert!(msg.contains("1800"), "should mention available_time: {msg}");
        assert!(msg.contains("3600"), "should mention direct_time: {msg}");
        assert!(
            msg.contains("1800"),
            "should mention shortfall (1800): {msg}"
        );
    }

    #[test]
    fn no_path_display_is_readable() {
        let msg = InfeasibleReason::NoPathExists.to_string();
        assert!(!msg.is_empty());
    }

    // ------------------------------------------------------------------
    // compute_feasibility_with: closure-controlled cost
    // ------------------------------------------------------------------

    /// Doubling every edge cost via the closure must double both inbound and
    /// outbound times for every feasible node, and the slack must update
    /// consistently with the new totals.
    #[test]
    fn closure_doubles_inbound_and_outbound_consistently() {
        let g = linear_graph();
        let origin = find_node(&g, 1);
        let dest = find_node(&g, 4);

        let baseline = compute_feasibility(&g, origin, dest, 10_000.0, NetworkType::Drive)
            .expect("baseline should be Ok");
        let doubled = compute_feasibility_with(&g, origin, dest, 10_000.0, |e| {
            e.weight.travel_time(NetworkType::Drive) * 2.0
        })
        .expect("doubled should be Ok");

        for (node, base) in &baseline.feasible {
            let d = doubled.feasible.get(node).expect("doubled missing a node");
            assert!((d.inbound_time - 2.0 * base.inbound_time).abs() < 1e-9);
            assert!((d.outbound_time - 2.0 * base.outbound_time).abs() < 1e-9);
            // Identity must still hold under the doubled cost.
            assert!(
                (d.inbound_time + d.outbound_time + d.slack - 10_000.0).abs() < 1e-9,
                "doubled identity: in={} out={} slack={}",
                d.inbound_time,
                d.outbound_time,
                d.slack
            );
        }
    }

    /// The closure must see every edge in its *original* orientation regardless
    /// of search direction. We verify by passing a closure whose cost depends on
    /// `source.index() < target.index()` and checking that direction-aware
    /// asymmetry is preserved across both searches.
    #[test]
    fn closure_sees_original_orientation_in_both_searches() {
        let g = linear_graph();
        let origin = find_node(&g, 1);
        let dest = find_node(&g, 4);

        // Charge 10s for "forward" edges (source < target by index) and 100s
        // for "backward" edges. A symmetric cost would give the same in both
        // searches; an oriented cost would differ. Either way, the slack
        // identity must hold.
        let result = compute_feasibility_with(&g, origin, dest, 10_000.0, |e| {
            if e.source.index() < e.target.index() {
                10.0
            } else {
                100.0
            }
        })
        .expect("should be Ok");

        for (_, f) in &result.feasible {
            assert!((f.inbound_time + f.outbound_time + f.slack - 10_000.0).abs() < 1e-9);
            assert!(f.slack >= 0.0);
        }
    }

    /// The convenience `compute_feasibility` must produce identical results to
    /// `compute_feasibility_with` invoked with the equivalent baseline closure.
    #[test]
    fn convenience_wrapper_matches_with_variant() {
        let g = linear_graph();
        let origin = find_node(&g, 1);
        let dest = find_node(&g, 4);

        let a = compute_feasibility(&g, origin, dest, 10_000.0, NetworkType::Drive).unwrap();
        let b = compute_feasibility_with(&g, origin, dest, 10_000.0, |e| {
            e.weight.travel_time(NetworkType::Drive)
        })
        .unwrap();

        assert_eq!(a.feasible.len(), b.feasible.len());
        for (node, fa) in &a.feasible {
            let fb = b.feasible.get(node).expect("node missing in _with result");
            assert!((fa.inbound_time - fb.inbound_time).abs() < 1e-9);
            assert!((fa.outbound_time - fb.outbound_time).abs() < 1e-9);
            assert!((fa.slack - fb.slack).abs() < 1e-9);
        }
    }
}