Skip to main content

solverforge_maps/routing/
traffic.rs

1//! Slower roads for a period of the day: the same network with some edges
2//! taking longer to drive.
3
4use std::fmt;
5
6use super::bbox::BoundingBox;
7use super::config::RoadClass;
8use super::coord::Coord;
9use super::network::{EdgeData, RoadNetwork};
10
11/// Roads that take `factor` times as long to drive: every road of the listed
12/// classes (every road when none is listed), only where they lie in `area`
13/// when one is given. An edge lies in an area when its midpoint does.
14#[derive(Debug, Clone, PartialEq)]
15pub struct Slowdown {
16    factor: f64,
17    roads: Vec<RoadClass>,
18    area: Option<BoundingBox>,
19}
20
21/// A slowdown factor that is not a finite number above zero.
22#[derive(Debug, Clone, Copy, PartialEq)]
23pub struct SlowdownError {
24    pub factor: f64,
25}
26
27impl fmt::Display for SlowdownError {
28    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29        write!(
30            f,
31            "slowdown factor {} is not a finite number above zero",
32            self.factor
33        )
34    }
35}
36
37impl std::error::Error for SlowdownError {}
38
39impl Slowdown {
40    /// Every road taking `factor` times as long: 1.5 is half as long again,
41    /// 0.8 is faster than usual.
42    pub fn new(factor: f64) -> Result<Self, SlowdownError> {
43        if !factor.is_finite() || factor <= 0.0 {
44            return Err(SlowdownError { factor });
45        }
46        Ok(Self {
47            factor,
48            roads: Vec::new(),
49            area: None,
50        })
51    }
52
53    /// Only roads of these classes.
54    pub fn roads(mut self, roads: impl IntoIterator<Item = RoadClass>) -> Self {
55        self.roads = roads.into_iter().collect();
56        self
57    }
58
59    /// Only roads inside `area`.
60    pub fn area(mut self, area: BoundingBox) -> Self {
61        self.area = Some(area);
62        self
63    }
64
65    pub fn factor(&self) -> f64 {
66        self.factor
67    }
68
69    /// Whether an edge of `class` with its midpoint at `midpoint` is slowed.
70    pub fn applies(&self, class: RoadClass, midpoint: Coord) -> bool {
71        (self.roads.is_empty() || self.roads.contains(&class))
72            && self.area.is_none_or(|area| area.contains(midpoint))
73    }
74}
75
76impl RoadNetwork {
77    /// This network with every edge's travel time multiplied by the factors of
78    /// the slowdowns that apply to it; slowdowns that overlap multiply. Nodes,
79    /// distances, names, classes and connectivity stay the same, so places snap
80    /// where they do on this network and every route still exists.
81    pub fn slowed(&self, slowdowns: &[Slowdown]) -> RoadNetwork {
82        let mut slowed = RoadNetwork::new();
83        for idx in self.graph.node_indices() {
84            if let Some(node) = self.graph.node_weight(idx) {
85                slowed.add_node_at(node.lat, node.lng);
86            }
87        }
88        for idx in self.graph.edge_indices() {
89            let (Some((from, to)), Some(edge)) =
90                (self.graph.edge_endpoints(idx), self.graph.edge_weight(idx))
91            else {
92                continue;
93            };
94            let (Some(a), Some(b)) = (self.graph.node_weight(from), self.graph.node_weight(to))
95            else {
96                continue;
97            };
98            let midpoint = Coord::new((a.lat + b.lat) / 2.0, (a.lng + b.lng) / 2.0);
99            let factor: f64 = slowdowns
100                .iter()
101                .filter(|s| s.applies(edge.road_class, midpoint))
102                .map(Slowdown::factor)
103                .product();
104            slowed.add_edge(
105                from,
106                to,
107                EdgeData {
108                    travel_time_s: edge.travel_time_s * factor,
109                    distance_m: edge.distance_m,
110                    name: edge.name.clone(),
111                    road_class: edge.road_class,
112                },
113            );
114        }
115        slowed.build_spatial_index();
116        slowed
117    }
118}
119
120#[cfg(test)]
121#[path = "traffic_tests.rs"]
122mod tests;