Skip to main content

solverforge_maps/routing/
network.rs

1//! Road network graph core types and routing.
2
3use serde::{Deserialize, Serialize};
4use std::collections::HashSet;
5
6use super::algo::{astar, kosaraju_scc};
7use super::coord::Coord;
8use super::error::RoutingError;
9use super::geo::haversine_distance;
10use super::graph::{DiGraph, EdgeIdx, NodeIdx};
11use super::spatial::{KdTree, Point2D, Segment, SegmentIndex};
12
13#[derive(Debug, Clone)]
14pub struct NodeData {
15    pub lat: f64,
16    pub lng: f64,
17}
18
19impl NodeData {
20    #[inline]
21    pub fn coord(&self) -> Coord {
22        Coord::new(self.lat, self.lng)
23    }
24}
25
26#[derive(Debug, Clone)]
27pub struct EdgeData {
28    pub travel_time_s: f64,
29    pub distance_m: f64,
30}
31
32#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
33pub struct RouteResult {
34    pub duration_seconds: i64,
35    pub distance_meters: f64,
36    pub geometry: Vec<Coord>,
37}
38
39impl RouteResult {
40    /// Simplify the route geometry using Douglas-Peucker algorithm.
41    ///
42    /// # Arguments
43    /// * `tolerance_m` - Tolerance in meters; points within this distance of
44    ///   the simplified line are removed.
45    pub fn simplify(mut self, tolerance_m: f64) -> Self {
46        if self.geometry.len() <= 2 {
47            return self;
48        }
49
50        self.geometry = douglas_peucker(&self.geometry, tolerance_m);
51        self
52    }
53}
54
55#[derive(Debug, Clone, Copy, Default)]
56pub struct SnappedCoord {
57    pub original: Coord,
58    pub snapped: Coord,
59    pub snap_distance_m: f64,
60    pub(crate) node_index: NodeIdx,
61}
62
63/// Data stored in the point spatial index.
64#[derive(Debug, Clone, Copy)]
65struct SpatialPoint {
66    node_index: NodeIdx,
67}
68
69/// Data stored in the segment spatial index.
70#[derive(Debug, Clone, Copy)]
71struct SpatialSegment {
72    from_node: NodeIdx,
73    to_node: NodeIdx,
74    edge_index: EdgeIdx,
75}
76
77#[derive(Debug, Clone, Copy)]
78pub struct EdgeSnappedLocation {
79    pub original: Coord,
80    pub snapped: Coord,
81    pub snap_distance_m: f64,
82    pub(crate) edge_index: EdgeIdx,
83    pub(crate) position: f64,
84    pub(crate) from_node: NodeIdx,
85    pub(crate) to_node: NodeIdx,
86}
87
88#[derive(Debug, Clone, Copy)]
89struct EdgeTraversal {
90    node: NodeIdx,
91    time_s: f64,
92    distance_m: f64,
93}
94
95pub struct RoadNetwork {
96    pub(super) graph: DiGraph<NodeData, EdgeData>,
97    spatial_index: Option<KdTree<SpatialPoint>>,
98    edge_spatial_index: Option<SegmentIndex<SpatialSegment>>,
99    max_speed_mps: f64,
100}
101
102impl RoadNetwork {
103    pub fn new() -> Self {
104        Self {
105            graph: DiGraph::new(),
106            spatial_index: None,
107            edge_spatial_index: None,
108            max_speed_mps: 0.0,
109        }
110    }
111
112    pub(super) fn add_node_at(&mut self, lat: f64, lng: f64) -> NodeIdx {
113        self.graph.add_node(NodeData { lat, lng })
114    }
115
116    pub(super) fn add_edge(&mut self, from: NodeIdx, to: NodeIdx, data: EdgeData) {
117        self.record_edge_speed(&data);
118        self.graph.add_edge(from, to, data);
119    }
120
121    pub(super) fn add_edge_by_index(
122        &mut self,
123        from: usize,
124        to: usize,
125        travel_time_s: f64,
126        distance_m: f64,
127    ) {
128        let from_idx = NodeIdx::new(from);
129        let to_idx = NodeIdx::new(to);
130        let data = EdgeData {
131            travel_time_s,
132            distance_m,
133        };
134        self.record_edge_speed(&data);
135        self.graph.add_edge(from_idx, to_idx, data);
136    }
137
138    pub(super) fn build_spatial_index(&mut self) {
139        // Build point index for nodes
140        let points: Vec<(Point2D, SpatialPoint)> = self
141            .graph
142            .node_indices()
143            .filter_map(|node_idx| {
144                let node = self.graph.node_weight(node_idx)?;
145                Some((
146                    Point2D::new(node.lat, node.lng),
147                    SpatialPoint {
148                        node_index: node_idx,
149                    },
150                ))
151            })
152            .collect();
153
154        self.spatial_index = Some(KdTree::from_items(points));
155
156        // Build segment index for edges
157        let segments: Vec<(Segment, SpatialSegment)> = self
158            .graph
159            .edge_indices()
160            .filter_map(|edge_idx| {
161                let (from_node, to_node) = self.graph.edge_endpoints(edge_idx)?;
162                let from_data = self.graph.node_weight(from_node)?;
163                let to_data = self.graph.node_weight(to_node)?;
164                Some((
165                    Segment::new(
166                        Point2D::new(from_data.lat, from_data.lng),
167                        Point2D::new(to_data.lat, to_data.lng),
168                    ),
169                    SpatialSegment {
170                        from_node,
171                        to_node,
172                        edge_index: edge_idx,
173                    },
174                ))
175            })
176            .collect();
177
178        self.edge_spatial_index = Some(SegmentIndex::bulk_load(segments));
179    }
180
181    fn record_edge_speed(&mut self, edge: &EdgeData) {
182        if edge.travel_time_s <= 0.0 || edge.distance_m <= 0.0 {
183            return;
184        }
185
186        let speed_mps = edge.distance_m / edge.travel_time_s;
187        if speed_mps.is_finite() {
188            self.max_speed_mps = self.max_speed_mps.max(speed_mps);
189        }
190    }
191
192    fn distance_lower_bound_between(&self, from: NodeIdx, to: NodeIdx) -> f64 {
193        let Some(from_node) = self.graph.node_weight(from) else {
194            return 0.0;
195        };
196        let Some(to_node) = self.graph.node_weight(to) else {
197            return 0.0;
198        };
199        haversine_distance(from_node.coord(), to_node.coord())
200    }
201
202    fn time_lower_bound_between(&self, from: NodeIdx, to: NodeIdx) -> f64 {
203        if !self.max_speed_mps.is_finite() || self.max_speed_mps <= 0.0 {
204            return 0.0;
205        }
206
207        self.distance_lower_bound_between(from, to) / self.max_speed_mps
208    }
209
210    fn node_path_geometry(&self, path: &[NodeIdx]) -> Vec<Coord> {
211        path.iter()
212            .filter_map(|&idx| self.graph.node_weight(idx).map(|n| n.coord()))
213            .collect()
214    }
215
216    fn node_path_metrics(&self, path: &[NodeIdx]) -> (f64, f64) {
217        let mut distance = 0.0;
218        let mut time = 0.0;
219
220        for window in path.windows(2) {
221            if let Some(edge) = self.graph.find_edge(window[0], window[1]) {
222                if let Some(weight) = self.graph.edge_weight(edge) {
223                    distance += weight.distance_m;
224                    time += weight.travel_time_s;
225                }
226            }
227        }
228
229        (distance, time)
230    }
231
232    fn route_result_from_node_path(&self, path: &[NodeIdx], duration_seconds: i64) -> RouteResult {
233        let geometry = self.node_path_geometry(path);
234        let (distance, _) = self.node_path_metrics(path);
235
236        RouteResult {
237            duration_seconds,
238            distance_meters: distance,
239            geometry,
240        }
241    }
242
243    /// Iterate over all nodes as (lat, lng) pairs.
244    pub fn nodes_iter(&self) -> impl Iterator<Item = (f64, f64)> + '_ {
245        self.graph
246            .node_indices()
247            .filter_map(|idx| self.graph.node_weight(idx).map(|n| (n.lat, n.lng)))
248    }
249
250    /// Iterate over all edges as (from_idx, to_idx, travel_time_s, distance_m) tuples.
251    pub fn edges_iter(&self) -> impl Iterator<Item = (usize, usize, f64, f64)> + '_ {
252        self.graph.edge_indices().filter_map(|idx| {
253            let (from, to) = self.graph.edge_endpoints(idx)?;
254            let weight = self.graph.edge_weight(idx)?;
255            Some((
256                from.index(),
257                to.index(),
258                weight.travel_time_s,
259                weight.distance_m,
260            ))
261        })
262    }
263
264    /// Snap a coordinate to the nearest node in the road network.
265    ///
266    /// Returns `None` if the network is empty.
267    pub fn snap_to_road(&self, coord: Coord) -> Option<NodeIdx> {
268        self.spatial_index
269            .as_ref()?
270            .nearest_neighbor(&Point2D::new(coord.lat, coord.lng))
271            .map(|p| p.node_index)
272    }
273
274    /// Snap a coordinate to the road network with detailed information.
275    ///
276    /// Returns a `SnappedCoord` containing both original and snapped coordinates,
277    /// the snap distance, and an internal node index for routing.
278    pub fn snap_to_road_detailed(&self, coord: Coord) -> Result<SnappedCoord, RoutingError> {
279        let tree = self
280            .spatial_index
281            .as_ref()
282            .ok_or(RoutingError::SnapFailed {
283                coord,
284                nearest_distance_m: None,
285            })?;
286
287        let query = Point2D::new(coord.lat, coord.lng);
288        let (nearest, _dist_sq) =
289            tree.nearest_neighbor_with_distance(&query)
290                .ok_or(RoutingError::SnapFailed {
291                    coord,
292                    nearest_distance_m: None,
293                })?;
294
295        // Get the actual coordinates from the graph node
296        let node_data =
297            self.graph
298                .node_weight(nearest.node_index)
299                .ok_or(RoutingError::SnapFailed {
300                    coord,
301                    nearest_distance_m: None,
302                })?;
303
304        let snapped = Coord::new(node_data.lat, node_data.lng);
305        let snap_distance_m = haversine_distance(coord, snapped);
306
307        Ok(SnappedCoord {
308            original: coord,
309            snapped,
310            snap_distance_m,
311            node_index: nearest.node_index,
312        })
313    }
314
315    /// Snap a coordinate to the nearest road segment (edge-based snapping).
316    ///
317    /// This is production-grade snapping that projects the coordinate onto the
318    /// nearest road segment rather than snapping to the nearest intersection.
319    pub fn snap_to_edge(&self, coord: Coord) -> Result<EdgeSnappedLocation, RoutingError> {
320        let index = self
321            .edge_spatial_index
322            .as_ref()
323            .ok_or(RoutingError::SnapFailed {
324                coord,
325                nearest_distance_m: None,
326            })?;
327
328        let query = Point2D::new(coord.lat, coord.lng);
329        let (segment, seg_data, proj_point, _dist_sq) =
330            index
331                .nearest_segment(&query)
332                .ok_or(RoutingError::SnapFailed {
333                    coord,
334                    nearest_distance_m: None,
335                })?;
336
337        // Compute position along segment
338        let (_, position) = segment.project_point(&query);
339        let snapped = Coord::new(proj_point.x, proj_point.y);
340        let snap_distance_m = haversine_distance(coord, snapped);
341
342        Ok(EdgeSnappedLocation {
343            original: coord,
344            snapped,
345            snap_distance_m,
346            edge_index: seg_data.edge_index,
347            position,
348            from_node: seg_data.from_node,
349            to_node: seg_data.to_node,
350        })
351    }
352
353    /// Find a route between two coordinates.
354    ///
355    /// This method snaps both coordinates to the nearest road-network nodes,
356    /// then runs the public travel-time search over those snapped nodes.
357    /// The current implementation passes a zero heuristic to `astar`, so its
358    /// behavior is equivalent to Dijkstra's algorithm.
359    pub fn route(&self, from: Coord, to: Coord) -> Result<RouteResult, RoutingError> {
360        let start_snap = self.snap_to_road_detailed(from)?;
361        let end_snap = self.snap_to_road_detailed(to)?;
362
363        self.route_snapped(&start_snap, &end_snap)
364    }
365
366    /// Find a route between two edge-snapped locations.
367    ///
368    /// Use this when start and end should stay on their containing road
369    /// segments instead of being snapped all the way to graph nodes.
370    pub fn route_edge_snapped(
371        &self,
372        from: &EdgeSnappedLocation,
373        to: &EdgeSnappedLocation,
374    ) -> Result<RouteResult, RoutingError> {
375        let from_edge = self
376            .graph
377            .edge_weight(from.edge_index)
378            .ok_or(RoutingError::NoPath {
379                from: from.original,
380                to: to.original,
381            })?;
382        let to_edge = self
383            .graph
384            .edge_weight(to.edge_index)
385            .ok_or(RoutingError::NoPath {
386                from: from.original,
387                to: to.original,
388            })?;
389
390        // Same-edge travel is only valid in the edge's forward direction.
391        if from.edge_index == to.edge_index {
392            if to.position < from.position {
393                return Err(RoutingError::NoPath {
394                    from: from.original,
395                    to: to.original,
396                });
397            }
398
399            let segment_time = from_edge.travel_time_s;
400            let segment_dist = from_edge.distance_m;
401            let travel_fraction = to.position - from.position;
402            return Ok(RouteResult {
403                duration_seconds: (segment_time * travel_fraction).round() as i64,
404                distance_meters: segment_dist * travel_fraction,
405                geometry: vec![from.snapped, to.snapped],
406            });
407        }
408
409        let start_exit = EdgeTraversal {
410            node: from.to_node,
411            time_s: from_edge.travel_time_s * (1.0 - from.position),
412            distance_m: from_edge.distance_m * (1.0 - from.position),
413        };
414        let end_entry = EdgeTraversal {
415            node: to.from_node,
416            time_s: to_edge.travel_time_s * to.position,
417            distance_m: to_edge.distance_m * to.position,
418        };
419
420        let best_result = if start_exit.node == end_entry.node {
421            Some((start_exit.time_s + end_entry.time_s, vec![start_exit.node]))
422        } else {
423            astar(
424                &self.graph,
425                start_exit.node,
426                |n| n == end_entry.node,
427                |e| e.travel_time_s,
428                |n| self.time_lower_bound_between(n, end_entry.node),
429            )
430            .map(|(path_cost, path)| (start_exit.time_s + path_cost + end_entry.time_s, path))
431        };
432
433        match best_result {
434            Some((total_cost, path)) => {
435                let mut geometry = vec![from.snapped];
436                for coord in self.node_path_geometry(&path) {
437                    if geometry.last().copied() != Some(coord) {
438                        geometry.push(coord);
439                    }
440                }
441                if geometry.last().copied() != Some(to.snapped) {
442                    geometry.push(to.snapped);
443                }
444
445                let (path_distance, _) = self.node_path_metrics(&path);
446                let distance = start_exit.distance_m + path_distance + end_entry.distance_m;
447
448                Ok(RouteResult {
449                    duration_seconds: total_cost.round() as i64,
450                    distance_meters: distance,
451                    geometry,
452                })
453            }
454            None => Err(RoutingError::NoPath {
455                from: from.original,
456                to: to.original,
457            }),
458        }
459    }
460
461    /// Find a route between two node-snapped coordinates.
462    ///
463    /// This expects `SnappedCoord` values produced by `snap_to_road_detailed`
464    /// and returns geometry along graph nodes, not projected edge endpoints.
465    pub fn route_snapped(
466        &self,
467        from: &SnappedCoord,
468        to: &SnappedCoord,
469    ) -> Result<RouteResult, RoutingError> {
470        if from.node_index == to.node_index {
471            // Stay on the network: a line between the raw points may cross land or water.
472            return Ok(RouteResult {
473                duration_seconds: 0,
474                distance_meters: 0.0,
475                geometry: vec![from.snapped, to.snapped],
476            });
477        }
478
479        let result = astar(
480            &self.graph,
481            from.node_index,
482            |n| n == to.node_index,
483            |e| e.travel_time_s,
484            |n| self.time_lower_bound_between(n, to.node_index),
485        );
486
487        match result {
488            Some((cost, path)) => Ok(self.route_result_from_node_path(&path, cost.round() as i64)),
489            None => Err(RoutingError::NoPath {
490                from: from.original,
491                to: to.original,
492            }),
493        }
494    }
495
496    /// Find a route between two coordinates with an explicit optimization objective.
497    ///
498    /// Like `route`, this method snaps to the nearest graph nodes first and
499    /// uses admissible straight-line lower bounds for both objectives.
500    pub fn route_with(
501        &self,
502        from: Coord,
503        to: Coord,
504        objective: Objective,
505    ) -> Result<RouteResult, RoutingError> {
506        let start_snap = self.snap_to_road_detailed(from)?;
507        let end_snap = self.snap_to_road_detailed(to)?;
508
509        if start_snap.node_index == end_snap.node_index {
510            return Ok(RouteResult {
511                duration_seconds: 0,
512                distance_meters: 0.0,
513                geometry: vec![start_snap.snapped, end_snap.snapped],
514            });
515        }
516
517        let result = match objective {
518            Objective::Time => astar(
519                &self.graph,
520                start_snap.node_index,
521                |n| n == end_snap.node_index,
522                |e| e.travel_time_s,
523                |n| self.time_lower_bound_between(n, end_snap.node_index),
524            ),
525            Objective::Distance => astar(
526                &self.graph,
527                start_snap.node_index,
528                |n| n == end_snap.node_index,
529                |e| e.distance_m,
530                |n| self.distance_lower_bound_between(n, end_snap.node_index),
531            ),
532        };
533
534        match result {
535            Some((_, path)) => {
536                let (distance, time) = self.node_path_metrics(&path);
537                Ok(RouteResult {
538                    duration_seconds: time.round() as i64,
539                    distance_meters: distance,
540                    geometry: self.node_path_geometry(&path),
541                })
542            }
543            None => Err(RoutingError::NoPath { from, to }),
544        }
545    }
546
547    pub fn node_count(&self) -> usize {
548        self.graph.node_count()
549    }
550
551    pub fn edge_count(&self) -> usize {
552        self.graph.edge_count()
553    }
554
555    pub fn strongly_connected_components(&self) -> usize {
556        kosaraju_scc(&self.graph).len()
557    }
558
559    pub fn largest_component_fraction(&self) -> f64 {
560        let sccs = kosaraju_scc(&self.graph);
561        if sccs.is_empty() {
562            return 0.0;
563        }
564        let largest = sccs.iter().map(|c| c.len()).max().unwrap_or(0);
565        let total = self.graph.node_count();
566        if total == 0 {
567            0.0
568        } else {
569            largest as f64 / total as f64
570        }
571    }
572
573    pub fn is_strongly_connected(&self) -> bool {
574        self.strongly_connected_components() == 1
575    }
576
577    /// Filter the network to keep only the largest strongly connected component.
578    pub fn filter_to_largest_scc(&mut self) {
579        let sccs = kosaraju_scc(&self.graph);
580        if sccs.len() <= 1 {
581            return; // Already connected or empty
582        }
583
584        // Find the largest SCC
585        let largest_scc: HashSet<NodeIdx> = sccs
586            .into_iter()
587            .max_by_key(|scc| scc.len())
588            .unwrap_or_default()
589            .into_iter()
590            .collect();
591
592        // Retain only nodes in the largest SCC
593        self.graph.retain_nodes(|n, _| largest_scc.contains(&n));
594
595        self.build_spatial_index();
596    }
597}
598
599impl Default for RoadNetwork {
600    fn default() -> Self {
601        Self::new()
602    }
603}
604
605impl RoadNetwork {
606    /// Build a network from raw node/edge data (for testing).
607    ///
608    /// # Arguments
609    /// * `nodes` - Slice of (lat, lng) tuples for each node
610    /// * `edges` - Slice of (from_idx, to_idx, time_s, dist_m) tuples
611    ///
612    /// # Example
613    /// ```
614    /// use solverforge_maps::RoadNetwork;
615    ///
616    /// let nodes = &[(40.0, -75.0), (39.8, -75.2)];
617    /// let edges = &[(0, 1, 60.0, 1000.0), (1, 0, 60.0, 1000.0)];
618    /// let network = RoadNetwork::from_test_data(nodes, edges);
619    ///
620    /// assert_eq!(network.node_count(), 2);
621    /// assert_eq!(network.edge_count(), 2);
622    /// ```
623    pub fn from_test_data(nodes: &[(f64, f64)], edges: &[(usize, usize, f64, f64)]) -> Self {
624        let mut network = Self::new();
625
626        // Add all nodes
627        for &(lat, lng) in nodes {
628            network.add_node_at(lat, lng);
629        }
630
631        // Add all edges
632        for &(from, to, time_s, dist_m) in edges {
633            network.add_edge_by_index(from, to, time_s, dist_m);
634        }
635
636        // Build spatial index for snapping
637        network.build_spatial_index();
638
639        network
640    }
641}
642
643#[cfg(test)]
644#[path = "network_tests.rs"]
645mod tests;
646
647#[derive(Debug, Clone, Copy, PartialEq, Eq)]
648pub enum Objective {
649    Time,
650    Distance,
651}
652
653/// Douglas-Peucker line simplification algorithm.
654fn douglas_peucker(points: &[Coord], tolerance_m: f64) -> Vec<Coord> {
655    if points.len() <= 2 {
656        return points.to_vec();
657    }
658
659    let first = points[0];
660    let last = points[points.len() - 1];
661    let mut max_dist = 0.0;
662    let mut max_idx = 0;
663
664    for (i, point) in points.iter().enumerate().skip(1).take(points.len() - 2) {
665        let dist = perpendicular_distance(*point, first, last);
666        if dist > max_dist {
667            max_dist = dist;
668            max_idx = i;
669        }
670    }
671
672    if max_dist > tolerance_m {
673        let mut left = douglas_peucker(&points[..=max_idx], tolerance_m);
674        let right = douglas_peucker(&points[max_idx..], tolerance_m);
675
676        left.pop();
677        left.extend(right);
678        left
679    } else {
680        vec![first, last]
681    }
682}
683
684fn perpendicular_distance(point: Coord, line_start: Coord, line_end: Coord) -> f64 {
685    let dx = line_end.lng - line_start.lng;
686    let dy = line_end.lat - line_start.lat;
687
688    let line_length_sq = dx * dx + dy * dy;
689    if line_length_sq < f64::EPSILON {
690        return haversine_distance(point, line_start);
691    }
692
693    let t =
694        ((point.lng - line_start.lng) * dx + (point.lat - line_start.lat) * dy) / line_length_sq;
695    let t = t.clamp(0.0, 1.0);
696
697    let projected = Coord::new(line_start.lat + t * dy, line_start.lng + t * dx);
698
699    haversine_distance(point, projected)
700}