1use serde::{Deserialize, Serialize};
4use std::collections::HashSet;
5
6use super::algo::{astar, kosaraju_scc};
7use super::config::RoadClass;
8use super::coord::Coord;
9use super::error::RoutingError;
10use super::geo::haversine_distance;
11use super::graph::{DiGraph, EdgeIdx, NodeIdx};
12use super::spatial::{KdTree, Point2D, Segment, SegmentIndex};
13
14fn component_root(parent: &mut [usize], mut root: usize) -> usize {
16 let mut probe = root;
17 while parent[probe] != probe {
18 probe = parent[probe];
19 }
20 while parent[root] != probe {
21 let next = parent[root];
22 parent[root] = probe;
23 root = next;
24 }
25 probe
26}
27
28#[derive(Debug, Clone)]
29pub struct NodeData {
30 pub lat: f64,
31 pub lng: f64,
32}
33
34impl NodeData {
35 #[inline]
36 pub fn coord(&self) -> Coord {
37 Coord::new(self.lat, self.lng)
38 }
39}
40
41#[derive(Debug, Clone)]
42pub struct EdgeData {
43 pub travel_time_s: f64,
44 pub distance_m: f64,
45 pub name: Option<String>,
46 pub road_class: RoadClass,
47}
48
49#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
51pub struct StreetRun {
52 pub name: String,
53 pub distance_m: f64,
54}
55
56#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
57pub struct RouteResult {
58 pub duration_seconds: i64,
59 pub distance_meters: f64,
60 pub geometry: Vec<Coord>,
61 pub streets: Vec<StreetRun>,
65}
66
67pub(crate) fn merge_street_runs(
70 pieces: impl IntoIterator<Item = (Option<String>, f64)>,
71) -> Vec<StreetRun> {
72 let mut runs: Vec<StreetRun> = Vec::new();
73 for (name, distance) in pieces {
74 let Some(name) = name else { continue };
75 if distance <= 0.0 {
76 continue;
77 }
78 match runs.last_mut() {
79 Some(last) if last.name == name => last.distance_m += distance,
80 _ => runs.push(StreetRun {
81 name,
82 distance_m: distance,
83 }),
84 }
85 }
86 runs
87}
88
89impl RouteResult {
90 pub fn simplify(mut self, tolerance_m: f64) -> Self {
96 if self.geometry.len() <= 2 {
97 return self;
98 }
99
100 self.geometry = douglas_peucker(&self.geometry, tolerance_m);
101 self
102 }
103}
104
105#[derive(Debug, Clone, Copy, Default)]
106pub struct SnappedCoord {
107 pub original: Coord,
108 pub snapped: Coord,
109 pub snap_distance_m: f64,
110 pub(crate) node_index: NodeIdx,
111}
112
113#[derive(Debug, Clone, Copy)]
115struct SpatialPoint {
116 node_index: NodeIdx,
117}
118
119#[derive(Debug, Clone, Copy)]
121struct SpatialSegment {
122 from_node: NodeIdx,
123 to_node: NodeIdx,
124 edge_index: EdgeIdx,
125}
126
127#[derive(Debug, Clone, Copy)]
128pub struct EdgeSnappedLocation {
129 pub original: Coord,
130 pub snapped: Coord,
131 pub snap_distance_m: f64,
132 pub(crate) edge_index: EdgeIdx,
133 pub(crate) position: f64,
134 pub(crate) from_node: NodeIdx,
135 pub(crate) to_node: NodeIdx,
136}
137
138#[derive(Debug, Clone, Copy)]
139struct EdgeTraversal {
140 node: NodeIdx,
141 time_s: f64,
142 distance_m: f64,
143}
144
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
152pub enum SnapAccess {
153 Incoming,
154 Outgoing,
155 Both,
156}
157
158impl SnapAccess {
159 fn allows(&self, incoming: bool, outgoing: bool) -> bool {
160 match self {
161 SnapAccess::Incoming => incoming,
162 SnapAccess::Outgoing => outgoing,
163 SnapAccess::Both => incoming && outgoing,
164 }
165 }
166}
167
168pub struct RoadNetwork {
169 pub(super) graph: DiGraph<NodeData, EdgeData>,
170 spatial_index: Option<KdTree<SpatialPoint>>,
171 edge_spatial_index: Option<SegmentIndex<SpatialSegment>>,
172 node_access: Option<(Vec<bool>, Vec<bool>)>,
175 node_component_size: Option<Vec<u32>>,
180 max_speed_mps: f64,
181}
182
183impl RoadNetwork {
184 pub fn new() -> Self {
185 Self {
186 graph: DiGraph::new(),
187 spatial_index: None,
188 edge_spatial_index: None,
189 node_access: None,
190 node_component_size: None,
191 max_speed_mps: 0.0,
192 }
193 }
194
195 pub(super) fn add_node_at(&mut self, lat: f64, lng: f64) -> NodeIdx {
196 self.graph.add_node(NodeData { lat, lng })
197 }
198
199 pub(super) fn add_edge(&mut self, from: NodeIdx, to: NodeIdx, data: EdgeData) {
200 self.record_edge_speed(&data);
201 self.graph.add_edge(from, to, data);
202 }
203
204 pub fn add_edge_by_index(
205 &mut self,
206 from: usize,
207 to: usize,
208 travel_time_s: f64,
209 distance_m: f64,
210 ) {
211 self.add_edge_named_by_index(from, to, travel_time_s, distance_m, None, RoadClass::Other);
212 }
213
214 pub(super) fn add_edge_named_by_index(
215 &mut self,
216 from: usize,
217 to: usize,
218 travel_time_s: f64,
219 distance_m: f64,
220 name: Option<String>,
221 road_class: RoadClass,
222 ) {
223 let from_idx = NodeIdx::new(from);
224 let to_idx = NodeIdx::new(to);
225 let data = EdgeData {
226 travel_time_s,
227 distance_m,
228 name,
229 road_class,
230 };
231 self.record_edge_speed(&data);
232 self.graph.add_edge(from_idx, to_idx, data);
233 }
234
235 pub(super) fn build_spatial_index(&mut self) {
236 let points: Vec<(Point2D, SpatialPoint)> = self
238 .graph
239 .node_indices()
240 .filter_map(|node_idx| {
241 let node = self.graph.node_weight(node_idx)?;
242 Some((
243 Point2D::new(node.lat, node.lng),
244 SpatialPoint {
245 node_index: node_idx,
246 },
247 ))
248 })
249 .collect();
250
251 self.spatial_index = Some(KdTree::from_items(points));
252
253 let segments: Vec<(Segment, SpatialSegment)> = self
255 .graph
256 .edge_indices()
257 .filter_map(|edge_idx| {
258 let (from_node, to_node) = self.graph.edge_endpoints(edge_idx)?;
259 let from_data = self.graph.node_weight(from_node)?;
260 let to_data = self.graph.node_weight(to_node)?;
261 Some((
262 Segment::new(
263 Point2D::new(from_data.lat, from_data.lng),
264 Point2D::new(to_data.lat, to_data.lng),
265 ),
266 SpatialSegment {
267 from_node,
268 to_node,
269 edge_index: edge_idx,
270 },
271 ))
272 })
273 .collect();
274
275 self.edge_spatial_index = Some(SegmentIndex::bulk_load(segments));
276
277 let node_count = self.graph.node_count();
281 if node_count > 0 {
282 let mut incoming = vec![false; node_count];
283 let mut outgoing = vec![false; node_count];
284 for (from, to) in self
285 .graph
286 .edge_indices()
287 .filter_map(|edge| self.graph.edge_endpoints(edge))
288 {
289 outgoing[from.index()] = true;
290 incoming[to.index()] = true;
291 }
292 self.node_access = Some((incoming, outgoing));
293
294 let mut parent: Vec<usize> = (0..node_count).collect();
298 let mut sizes: Vec<usize> = vec![1; node_count];
299 for (from, to) in self
300 .graph
301 .edge_indices()
302 .filter_map(|edge| self.graph.edge_endpoints(edge))
303 {
304 let from_root = component_root(&mut parent, from.index());
305 let to_root = component_root(&mut parent, to.index());
306 if from_root == to_root {
307 continue;
308 }
309 if sizes[from_root] < sizes[to_root] {
311 sizes[to_root] += sizes[from_root];
312 sizes[from_root] = 0;
313 parent[from_root] = to_root;
314 } else {
315 sizes[from_root] += sizes[to_root];
316 sizes[to_root] = 0;
317 parent[to_root] = from_root;
318 }
319 }
320 let per_node: Vec<u32> = (0..node_count)
321 .map(|node_index| {
322 let root = component_root(&mut parent, node_index);
323 u32::try_from(sizes[root]).unwrap_or(u32::MAX)
324 })
325 .collect();
326 self.node_component_size = Some(per_node);
327 }
328 }
329
330 fn allows_access(&self, node_index: NodeIdx, access: SnapAccess) -> bool {
335 match self.node_access.as_ref() {
336 Some((incoming, outgoing)) => {
337 let index = node_index.index();
338 access.allows(
339 incoming.get(index).copied().unwrap_or(false),
340 outgoing.get(index).copied().unwrap_or(false),
341 )
342 }
343 None => true,
344 }
345 }
346
347 fn component_size(&self, node_index: NodeIdx) -> u32 {
349 match self.node_component_size.as_ref() {
350 Some(per_node) => per_node.get(node_index.index()).copied().unwrap_or(0),
351 None => u32::MAX,
352 }
353 }
354
355 pub fn snap_road_index_with_access(
361 &self,
362 coord: Coord,
363 access: SnapAccess,
364 ) -> Result<SnappedCoord, RoutingError> {
365 let tree = self
366 .spatial_index
367 .as_ref()
368 .ok_or(RoutingError::SnapFailed {
369 coord,
370 nearest_distance_m: None,
371 })?;
372
373 let query = Point2D::new(coord.lat, coord.lng);
374 const SNAP_CANDIDATES: usize = 64;
375 let candidates = tree.nearest_n_neighbors(&query, SNAP_CANDIDATES);
376 let mut chosen: Option<(NodeIdx, u32)> = None;
379 for (candidate, _dist) in &candidates {
380 if !self.allows_access(candidate.node_index, access) {
381 continue;
382 }
383 let size = self.component_size(candidate.node_index);
384 if chosen.is_none_or(|(_, best)| size > best) {
385 chosen = Some((candidate.node_index, size));
386 }
387 }
388 let chosen_node = match chosen {
389 Some((node, _)) => node,
390 None => candidates
391 .first()
392 .map(|(candidate, _)| candidate.node_index)
393 .ok_or(RoutingError::SnapFailed {
394 coord,
395 nearest_distance_m: None,
396 })?,
397 };
398
399 let node_data = self
400 .graph
401 .node_weight(chosen_node)
402 .ok_or(RoutingError::SnapFailed {
403 coord,
404 nearest_distance_m: None,
405 })?;
406
407 let snapped = Coord::new(node_data.lat, node_data.lng);
408 let snap_distance_m = haversine_distance(coord, snapped);
409
410 Ok(SnappedCoord {
411 original: coord,
412 snapped,
413 snap_distance_m,
414 node_index: chosen_node,
415 })
416 }
417
418 fn record_edge_speed(&mut self, edge: &EdgeData) {
419 if edge.travel_time_s <= 0.0 || edge.distance_m <= 0.0 {
420 return;
421 }
422
423 let speed_mps = edge.distance_m / edge.travel_time_s;
424 if speed_mps.is_finite() {
425 self.max_speed_mps = self.max_speed_mps.max(speed_mps);
426 }
427 }
428
429 fn distance_lower_bound_between(&self, from: NodeIdx, to: NodeIdx) -> f64 {
430 let Some(from_node) = self.graph.node_weight(from) else {
431 return 0.0;
432 };
433 let Some(to_node) = self.graph.node_weight(to) else {
434 return 0.0;
435 };
436 haversine_distance(from_node.coord(), to_node.coord())
437 }
438
439 fn time_lower_bound_between(&self, from: NodeIdx, to: NodeIdx) -> f64 {
440 if !self.max_speed_mps.is_finite() || self.max_speed_mps <= 0.0 {
441 return 0.0;
442 }
443
444 self.distance_lower_bound_between(from, to) / self.max_speed_mps
445 }
446
447 fn node_path_geometry(&self, path: &[NodeIdx]) -> Vec<Coord> {
448 path.iter()
449 .filter_map(|&idx| self.graph.node_weight(idx).map(|n| n.coord()))
450 .collect()
451 }
452
453 fn node_path_metrics(&self, path: &[NodeIdx]) -> (f64, f64) {
454 let mut distance = 0.0;
455 let mut time = 0.0;
456
457 for window in path.windows(2) {
458 if let Some(edge) = self.graph.find_edge(window[0], window[1]) {
459 if let Some(weight) = self.graph.edge_weight(edge) {
460 distance += weight.distance_m;
461 time += weight.travel_time_s;
462 }
463 }
464 }
465
466 (distance, time)
467 }
468
469 fn route_result_from_node_path(&self, path: &[NodeIdx], duration_seconds: i64) -> RouteResult {
470 let geometry = self.node_path_geometry(path);
471 let (distance, _) = self.node_path_metrics(path);
472 let pieces = path.windows(2).map(|window| {
473 self.graph
474 .find_edge(window[0], window[1])
475 .and_then(|edge| self.graph.edge_weight(edge))
476 .map(|weight| (weight.name.clone(), weight.distance_m))
477 .unwrap_or((None, 0.0))
478 });
479
480 RouteResult {
481 duration_seconds,
482 distance_meters: distance,
483 geometry,
484 streets: merge_street_runs(pieces),
485 }
486 }
487
488 pub fn nodes_iter(&self) -> impl Iterator<Item = (f64, f64)> + '_ {
490 self.graph
491 .node_indices()
492 .filter_map(|idx| self.graph.node_weight(idx).map(|n| (n.lat, n.lng)))
493 }
494
495 pub fn edges_iter(&self) -> impl Iterator<Item = (usize, usize, f64, f64)> + '_ {
498 self.graph.edge_indices().filter_map(|idx| {
499 let (from, to) = self.graph.edge_endpoints(idx)?;
500 let weight = self.graph.edge_weight(idx)?;
501 Some((
502 from.index(),
503 to.index(),
504 weight.travel_time_s,
505 weight.distance_m,
506 ))
507 })
508 }
509
510 pub fn edges_with_names_iter(
513 &self,
514 ) -> impl Iterator<Item = (usize, usize, f64, f64, Option<String>)> + '_ {
515 self.graph.edge_indices().filter_map(|idx| {
516 let (from, to) = self.graph.edge_endpoints(idx)?;
517 let weight = self.graph.edge_weight(idx)?;
518 Some((
519 from.index(),
520 to.index(),
521 weight.travel_time_s,
522 weight.distance_m,
523 weight.name.clone(),
524 ))
525 })
526 }
527
528 pub fn snap_to_road(&self, coord: Coord) -> Option<NodeIdx> {
532 self.spatial_index
533 .as_ref()?
534 .nearest_neighbor(&Point2D::new(coord.lat, coord.lng))
535 .map(|p| p.node_index)
536 }
537
538 pub fn snap_to_road_detailed(&self, coord: Coord) -> Result<SnappedCoord, RoutingError> {
543 let tree = self
544 .spatial_index
545 .as_ref()
546 .ok_or(RoutingError::SnapFailed {
547 coord,
548 nearest_distance_m: None,
549 })?;
550
551 let query = Point2D::new(coord.lat, coord.lng);
552 let (nearest, _dist_sq) =
553 tree.nearest_neighbor_with_distance(&query)
554 .ok_or(RoutingError::SnapFailed {
555 coord,
556 nearest_distance_m: None,
557 })?;
558
559 let node_data =
561 self.graph
562 .node_weight(nearest.node_index)
563 .ok_or(RoutingError::SnapFailed {
564 coord,
565 nearest_distance_m: None,
566 })?;
567
568 let snapped = Coord::new(node_data.lat, node_data.lng);
569 let snap_distance_m = haversine_distance(coord, snapped);
570
571 Ok(SnappedCoord {
572 original: coord,
573 snapped,
574 snap_distance_m,
575 node_index: nearest.node_index,
576 })
577 }
578
579 pub fn snap_to_edge(&self, coord: Coord) -> Result<EdgeSnappedLocation, RoutingError> {
584 let index = self
585 .edge_spatial_index
586 .as_ref()
587 .ok_or(RoutingError::SnapFailed {
588 coord,
589 nearest_distance_m: None,
590 })?;
591
592 let query = Point2D::new(coord.lat, coord.lng);
593 let (segment, seg_data, proj_point, _dist_sq) =
594 index
595 .nearest_segment(&query)
596 .ok_or(RoutingError::SnapFailed {
597 coord,
598 nearest_distance_m: None,
599 })?;
600
601 let (_, position) = segment.project_point(&query);
603 let snapped = Coord::new(proj_point.x, proj_point.y);
604 let snap_distance_m = haversine_distance(coord, snapped);
605
606 Ok(EdgeSnappedLocation {
607 original: coord,
608 snapped,
609 snap_distance_m,
610 edge_index: seg_data.edge_index,
611 position,
612 from_node: seg_data.from_node,
613 to_node: seg_data.to_node,
614 })
615 }
616
617 pub fn route(&self, from: Coord, to: Coord) -> Result<RouteResult, RoutingError> {
624 let start_snap = self.snap_road_index_with_access(from, SnapAccess::Outgoing)?;
625 let end_snap = self.snap_road_index_with_access(to, SnapAccess::Incoming)?;
626
627 self.route_snapped(&start_snap, &end_snap)
628 }
629
630 pub fn route_edge_snapped(
635 &self,
636 from: &EdgeSnappedLocation,
637 to: &EdgeSnappedLocation,
638 ) -> Result<RouteResult, RoutingError> {
639 let from_edge = self
640 .graph
641 .edge_weight(from.edge_index)
642 .ok_or(RoutingError::NoPath {
643 from: from.original,
644 to: to.original,
645 })?;
646 let to_edge = self
647 .graph
648 .edge_weight(to.edge_index)
649 .ok_or(RoutingError::NoPath {
650 from: from.original,
651 to: to.original,
652 })?;
653
654 if from.edge_index == to.edge_index {
656 if to.position < from.position {
657 return Err(RoutingError::NoPath {
658 from: from.original,
659 to: to.original,
660 });
661 }
662
663 let segment_time = from_edge.travel_time_s;
664 let segment_dist = from_edge.distance_m;
665 let travel_fraction = to.position - from.position;
666 return Ok(RouteResult {
667 duration_seconds: (segment_time * travel_fraction).round() as i64,
668 distance_meters: segment_dist * travel_fraction,
669 geometry: vec![from.snapped, to.snapped],
670 streets: merge_street_runs([(
671 from_edge.name.clone(),
672 segment_dist * travel_fraction,
673 )]),
674 });
675 }
676
677 let start_exit = EdgeTraversal {
678 node: from.to_node,
679 time_s: from_edge.travel_time_s * (1.0 - from.position),
680 distance_m: from_edge.distance_m * (1.0 - from.position),
681 };
682 let end_entry = EdgeTraversal {
683 node: to.from_node,
684 time_s: to_edge.travel_time_s * to.position,
685 distance_m: to_edge.distance_m * to.position,
686 };
687
688 let best_result = if start_exit.node == end_entry.node {
689 Some((start_exit.time_s + end_entry.time_s, vec![start_exit.node]))
690 } else {
691 astar(
692 &self.graph,
693 start_exit.node,
694 |n| n == end_entry.node,
695 |e| e.travel_time_s,
696 |n| self.time_lower_bound_between(n, end_entry.node),
697 )
698 .map(|(path_cost, path)| (start_exit.time_s + path_cost + end_entry.time_s, path))
699 };
700
701 match best_result {
702 Some((total_cost, path)) => {
703 let mut geometry = vec![from.snapped];
704 for coord in self.node_path_geometry(&path) {
705 if geometry.last().copied() != Some(coord) {
706 geometry.push(coord);
707 }
708 }
709 if geometry.last().copied() != Some(to.snapped) {
710 geometry.push(to.snapped);
711 }
712
713 let (path_distance, _) = self.node_path_metrics(&path);
714 let distance = start_exit.distance_m + path_distance + end_entry.distance_m;
715 let mut pieces = Vec::new();
716 pieces.push((from_edge.name.clone(), start_exit.distance_m));
717 for window in path.windows(2) {
718 if let Some(edge) = self.graph.find_edge(window[0], window[1]) {
719 if let Some(weight) = self.graph.edge_weight(edge) {
720 pieces.push((weight.name.clone(), weight.distance_m));
721 }
722 }
723 }
724 pieces.push((to_edge.name.clone(), end_entry.distance_m));
725
726 Ok(RouteResult {
727 duration_seconds: total_cost.round() as i64,
728 distance_meters: distance,
729 geometry,
730 streets: merge_street_runs(pieces),
731 })
732 }
733 None => Err(RoutingError::NoPath {
734 from: from.original,
735 to: to.original,
736 }),
737 }
738 }
739
740 pub fn route_snapped(
745 &self,
746 from: &SnappedCoord,
747 to: &SnappedCoord,
748 ) -> Result<RouteResult, RoutingError> {
749 if from.node_index == to.node_index {
750 return Ok(RouteResult {
752 duration_seconds: 0,
753 distance_meters: 0.0,
754 geometry: vec![from.snapped, to.snapped],
755 streets: Vec::new(),
756 });
757 }
758
759 let result = astar(
760 &self.graph,
761 from.node_index,
762 |n| n == to.node_index,
763 |e| e.travel_time_s,
764 |n| self.time_lower_bound_between(n, to.node_index),
765 );
766
767 match result {
768 Some((cost, path)) => Ok(self.route_result_from_node_path(&path, cost.round() as i64)),
769 None => Err(RoutingError::NoPath {
770 from: from.original,
771 to: to.original,
772 }),
773 }
774 }
775
776 pub fn route_with(
781 &self,
782 from: Coord,
783 to: Coord,
784 objective: Objective,
785 ) -> Result<RouteResult, RoutingError> {
786 let start_snap = self.snap_to_road_detailed(from)?;
787 let end_snap = self.snap_to_road_detailed(to)?;
788
789 if start_snap.node_index == end_snap.node_index {
790 return Ok(RouteResult {
791 duration_seconds: 0,
792 distance_meters: 0.0,
793 geometry: vec![start_snap.snapped, end_snap.snapped],
794 streets: Vec::new(),
795 });
796 }
797
798 let result = match objective {
799 Objective::Time => astar(
800 &self.graph,
801 start_snap.node_index,
802 |n| n == end_snap.node_index,
803 |e| e.travel_time_s,
804 |n| self.time_lower_bound_between(n, end_snap.node_index),
805 ),
806 Objective::Distance => astar(
807 &self.graph,
808 start_snap.node_index,
809 |n| n == end_snap.node_index,
810 |e| e.distance_m,
811 |n| self.distance_lower_bound_between(n, end_snap.node_index),
812 ),
813 };
814
815 match result {
816 Some((_, path)) => {
817 let (distance, time) = self.node_path_metrics(&path);
818 Ok(RouteResult {
819 duration_seconds: time.round() as i64,
820 distance_meters: distance,
821 geometry: self.node_path_geometry(&path),
822 streets: merge_street_runs(path.windows(2).map(|window| {
823 self.graph
824 .find_edge(window[0], window[1])
825 .and_then(|edge| self.graph.edge_weight(edge))
826 .map(|weight| (weight.name.clone(), weight.distance_m))
827 .unwrap_or((None, 0.0))
828 })),
829 })
830 }
831 None => Err(RoutingError::NoPath { from, to }),
832 }
833 }
834
835 pub fn node_count(&self) -> usize {
836 self.graph.node_count()
837 }
838
839 pub fn edge_count(&self) -> usize {
840 self.graph.edge_count()
841 }
842
843 pub fn strongly_connected_components(&self) -> usize {
844 kosaraju_scc(&self.graph).len()
845 }
846
847 pub fn largest_component_fraction(&self) -> f64 {
848 let sccs = kosaraju_scc(&self.graph);
849 if sccs.is_empty() {
850 return 0.0;
851 }
852 let largest = sccs.iter().map(|c| c.len()).max().unwrap_or(0);
853 let total = self.graph.node_count();
854 if total == 0 {
855 0.0
856 } else {
857 largest as f64 / total as f64
858 }
859 }
860
861 pub fn is_strongly_connected(&self) -> bool {
862 self.strongly_connected_components() == 1
863 }
864
865 pub fn filter_to_largest_scc(&mut self) {
867 let sccs = kosaraju_scc(&self.graph);
868 if sccs.len() <= 1 {
869 return; }
871
872 let largest_scc: HashSet<NodeIdx> = sccs
874 .into_iter()
875 .max_by_key(|scc| scc.len())
876 .unwrap_or_default()
877 .into_iter()
878 .collect();
879
880 self.graph.retain_nodes(|n, _| largest_scc.contains(&n));
882
883 self.build_spatial_index();
884 }
885}
886
887impl Default for RoadNetwork {
888 fn default() -> Self {
889 Self::new()
890 }
891}
892
893impl RoadNetwork {
894 pub fn from_test_data(nodes: &[(f64, f64)], edges: &[(usize, usize, f64, f64)]) -> Self {
914 let mut network = Self::new();
915
916 for &(lat, lng) in nodes {
918 network.add_node_at(lat, lng);
919 }
920
921 for &(from, to, time_s, dist_m) in edges {
923 network.add_edge_by_index(from, to, time_s, dist_m);
924 }
925
926 network.build_spatial_index();
928
929 network
930 }
931
932 pub fn from_test_data_named(
949 nodes: &[(f64, f64)],
950 edges: &[(usize, usize, f64, f64, &str)],
951 ) -> Self {
952 let mut network = Self::new();
953
954 for &(lat, lng) in nodes {
955 network.add_node_at(lat, lng);
956 }
957
958 for &(from, to, time_s, dist_m, name) in edges {
959 network.add_edge_named_by_index(
960 from,
961 to,
962 time_s,
963 dist_m,
964 Some(name.to_string()),
965 RoadClass::Other,
966 );
967 }
968
969 network.build_spatial_index();
970
971 network
972 }
973
974 pub fn from_test_data_classed(
991 nodes: &[(f64, f64)],
992 edges: &[(usize, usize, f64, f64, RoadClass)],
993 ) -> Self {
994 let mut network = Self::new();
995
996 for &(lat, lng) in nodes {
997 network.add_node_at(lat, lng);
998 }
999
1000 for &(from, to, time_s, dist_m, class) in edges {
1001 network.add_edge_named_by_index(from, to, time_s, dist_m, None, class);
1002 }
1003
1004 network.build_spatial_index();
1005
1006 network
1007 }
1008}
1009
1010#[cfg(test)]
1011#[path = "network_tests.rs"]
1012mod tests;
1013
1014#[cfg(test)]
1015#[path = "network_name_tests.rs"]
1016mod name_tests;
1017
1018#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1019pub enum Objective {
1020 Time,
1021 Distance,
1022}
1023
1024fn douglas_peucker(points: &[Coord], tolerance_m: f64) -> Vec<Coord> {
1026 if points.len() <= 2 {
1027 return points.to_vec();
1028 }
1029
1030 let first = points[0];
1031 let last = points[points.len() - 1];
1032 let mut max_dist = 0.0;
1033 let mut max_idx = 0;
1034
1035 for (i, point) in points.iter().enumerate().skip(1).take(points.len() - 2) {
1036 let dist = perpendicular_distance(*point, first, last);
1037 if dist > max_dist {
1038 max_dist = dist;
1039 max_idx = i;
1040 }
1041 }
1042
1043 if max_dist > tolerance_m {
1044 let mut left = douglas_peucker(&points[..=max_idx], tolerance_m);
1045 let right = douglas_peucker(&points[max_idx..], tolerance_m);
1046
1047 left.pop();
1048 left.extend(right);
1049 left
1050 } else {
1051 vec![first, last]
1052 }
1053}
1054
1055fn perpendicular_distance(point: Coord, line_start: Coord, line_end: Coord) -> f64 {
1056 let dx = line_end.lng - line_start.lng;
1057 let dy = line_end.lat - line_start.lat;
1058
1059 let line_length_sq = dx * dx + dy * dy;
1060 if line_length_sq < f64::EPSILON {
1061 return haversine_distance(point, line_start);
1062 }
1063
1064 let t =
1065 ((point.lng - line_start.lng) * dx + (point.lat - line_start.lat) * dy) / line_length_sq;
1066 let t = t.clamp(0.0, 1.0);
1067
1068 let projected = Coord::new(line_start.lat + t * dy, line_start.lng + t * dx);
1069
1070 haversine_distance(point, projected)
1071}