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