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