Skip to main content

solverforge_maps/routing/
config.rs

1//! Configuration for road network operations.
2
3use std::path::PathBuf;
4use std::time::Duration;
5
6use serde::{Deserialize, Serialize};
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum ConnectivityPolicy {
10    KeepAll,
11    LargestStronglyConnectedComponent,
12}
13
14/// The class of road an edge belongs to, from its OpenStreetMap `highway` tag.
15/// A link (`motorway_link`) belongs to the class of the road it serves.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
17#[serde(rename_all = "snake_case")]
18pub enum RoadClass {
19    Motorway,
20    Trunk,
21    Primary,
22    Secondary,
23    Tertiary,
24    Residential,
25    Unclassified,
26    Service,
27    LivingStreet,
28    /// Any other `highway` value, and edges built without one.
29    Other,
30}
31
32impl RoadClass {
33    /// Every class, in order from the fastest roads down.
34    pub const ALL: [RoadClass; 10] = [
35        RoadClass::Motorway,
36        RoadClass::Trunk,
37        RoadClass::Primary,
38        RoadClass::Secondary,
39        RoadClass::Tertiary,
40        RoadClass::Residential,
41        RoadClass::Unclassified,
42        RoadClass::Service,
43        RoadClass::LivingStreet,
44        RoadClass::Other,
45    ];
46
47    /// The class of an OpenStreetMap `highway` value.
48    pub fn from_highway(highway: &str) -> Self {
49        match highway {
50            "motorway" | "motorway_link" => RoadClass::Motorway,
51            "trunk" | "trunk_link" => RoadClass::Trunk,
52            "primary" | "primary_link" => RoadClass::Primary,
53            "secondary" | "secondary_link" => RoadClass::Secondary,
54            "tertiary" | "tertiary_link" => RoadClass::Tertiary,
55            "residential" => RoadClass::Residential,
56            "unclassified" => RoadClass::Unclassified,
57            "service" => RoadClass::Service,
58            "living_street" => RoadClass::LivingStreet,
59            _ => RoadClass::Other,
60        }
61    }
62
63    /// The class's name as written in configuration: `motorway`, `living_street`, `other`.
64    pub fn as_str(self) -> &'static str {
65        match self {
66            RoadClass::Motorway => "motorway",
67            RoadClass::Trunk => "trunk",
68            RoadClass::Primary => "primary",
69            RoadClass::Secondary => "secondary",
70            RoadClass::Tertiary => "tertiary",
71            RoadClass::Residential => "residential",
72            RoadClass::Unclassified => "unclassified",
73            RoadClass::Service => "service",
74            RoadClass::LivingStreet => "living_street",
75            RoadClass::Other => "other",
76        }
77    }
78
79    /// The class named `name` ([`RoadClass::as_str`]), if any.
80    pub fn parse(name: &str) -> Option<Self> {
81        RoadClass::ALL
82            .into_iter()
83            .find(|class| class.as_str() == name)
84    }
85}
86
87/// How a network is travelled: by car (the default), by bicycle or on foot.
88/// Each mode reads its own roads and paths from OpenStreetMap, follows its
89/// own access and one-way rules, and is cached on its own.
90#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
91#[serde(rename_all = "snake_case")]
92pub enum TravelMode {
93    #[default]
94    Car,
95    Bicycle,
96    Foot,
97}
98
99impl TravelMode {
100    /// Every mode.
101    pub const ALL: [TravelMode; 3] = [TravelMode::Car, TravelMode::Bicycle, TravelMode::Foot];
102
103    /// The mode's name as written in configuration: `car`, `bicycle`, `foot`.
104    pub fn as_str(self) -> &'static str {
105        match self {
106            TravelMode::Car => "car",
107            TravelMode::Bicycle => "bicycle",
108            TravelMode::Foot => "foot",
109        }
110    }
111
112    /// The mode named `name` ([`TravelMode::as_str`]), if any.
113    pub fn parse(name: &str) -> Option<Self> {
114        TravelMode::ALL
115            .into_iter()
116            .find(|mode| mode.as_str() == name)
117    }
118
119    /// The `highway` values a bicycle or a walker may use. A car uses
120    /// [`NetworkConfig::highway_types`].
121    pub fn highway_types(self) -> Option<Vec<&'static str>> {
122        let streets = [
123            "primary",
124            "primary_link",
125            "secondary",
126            "secondary_link",
127            "tertiary",
128            "tertiary_link",
129            "residential",
130            "unclassified",
131            "service",
132            "living_street",
133            "track",
134            "path",
135            "cycleway",
136            "pedestrian",
137            "footway",
138        ];
139        match self {
140            TravelMode::Car => None,
141            TravelMode::Bicycle => Some(streets.to_vec()),
142            TravelMode::Foot => Some(streets.into_iter().chain(["steps"]).collect()),
143        }
144    }
145
146    /// Travel speed in m/s off a car: 15 km/h by bicycle, 5 km/h on foot.
147    pub fn speed_mps(self) -> Option<f64> {
148        match self {
149            TravelMode::Car => None,
150            TravelMode::Bicycle => Some(15.0 / 3.6),
151            TravelMode::Foot => Some(5.0 / 3.6),
152        }
153    }
154}
155
156#[derive(Debug, Clone)]
157pub struct SpeedProfile {
158    pub motorway: f64,
159    pub trunk: f64,
160    pub primary: f64,
161    pub secondary: f64,
162    pub tertiary: f64,
163    pub residential: f64,
164    pub unclassified: f64,
165    pub service: f64,
166    pub living_street: f64,
167    pub default: f64,
168}
169
170impl Default for SpeedProfile {
171    fn default() -> Self {
172        Self {
173            motorway: 100.0,
174            trunk: 80.0,
175            primary: 60.0,
176            secondary: 50.0,
177            tertiary: 40.0,
178            residential: 30.0,
179            unclassified: 30.0,
180            service: 20.0,
181            living_street: 10.0,
182            default: 30.0,
183        }
184    }
185}
186
187impl SpeedProfile {
188    pub fn speed_mps(&self, maxspeed: Option<&str>, highway: &str) -> f64 {
189        let kmh = maxspeed
190            .and_then(|v| self.parse_maxspeed(v))
191            .unwrap_or_else(|| self.highway_speed(highway));
192        kmh * 1000.0 / 3600.0
193    }
194
195    fn highway_speed(&self, highway: &str) -> f64 {
196        match highway {
197            "motorway" | "motorway_link" => self.motorway,
198            "trunk" | "trunk_link" => self.trunk,
199            "primary" | "primary_link" => self.primary,
200            "secondary" | "secondary_link" => self.secondary,
201            "tertiary" | "tertiary_link" => self.tertiary,
202            "residential" => self.residential,
203            "unclassified" => self.unclassified,
204            "service" => self.service,
205            "living_street" => self.living_street,
206            _ => self.default,
207        }
208    }
209
210    fn parse_maxspeed(&self, value: &str) -> Option<f64> {
211        let value = value.trim();
212
213        match value.to_lowercase().as_str() {
214            "walk" => return Some(5.0),
215            "none" | "unlimited" => return None,
216            _ => {}
217        }
218
219        let (num_str, is_mph) = if let Some(s) = value.strip_suffix("mph") {
220            (s.trim(), true)
221        } else if let Some(s) = value.strip_suffix("km/h") {
222            (s.trim(), false)
223        } else if let Some(s) = value.strip_suffix("kmh") {
224            (s.trim(), false)
225        } else {
226            (value, false)
227        };
228
229        let kmh: f64 = num_str.parse().ok()?;
230        if kmh <= 0.0 || kmh > 300.0 {
231            return None;
232        }
233
234        Some(if is_mph { kmh * 1.60934 } else { kmh })
235    }
236}
237
238#[derive(Debug, Clone)]
239pub struct NetworkConfig {
240    pub overpass_url: String,
241    pub overpass_endpoints: Vec<String>,
242    pub overpass_max_retries: usize,
243    pub overpass_retry_backoff: Duration,
244    pub cache_dir: PathBuf,
245    pub connect_timeout: Duration,
246    pub read_timeout: Duration,
247    pub speed_profile: SpeedProfile,
248    pub connectivity_policy: ConnectivityPolicy,
249    pub highway_types: Vec<&'static str>,
250}
251
252impl Default for NetworkConfig {
253    fn default() -> Self {
254        let default_overpass = "https://overpass-api.de/api/interpreter".to_string();
255        Self {
256            overpass_url: default_overpass.clone(),
257            overpass_endpoints: vec![default_overpass],
258            overpass_max_retries: 2,
259            overpass_retry_backoff: Duration::from_secs(2),
260            cache_dir: PathBuf::from(".osm_cache"),
261            connect_timeout: Duration::from_secs(30),
262            read_timeout: Duration::from_secs(180),
263            speed_profile: SpeedProfile::default(),
264            connectivity_policy: ConnectivityPolicy::KeepAll,
265            // Motorways and trunk roads are entered and left through their links.
266            highway_types: vec![
267                "motorway",
268                "motorway_link",
269                "trunk",
270                "trunk_link",
271                "primary",
272                "primary_link",
273                "secondary",
274                "secondary_link",
275                "tertiary",
276                "tertiary_link",
277                "residential",
278                "unclassified",
279                "service",
280                "living_street",
281            ],
282        }
283    }
284}
285
286impl NetworkConfig {
287    pub fn new() -> Self {
288        Self::default()
289    }
290
291    pub fn overpass_url(mut self, url: impl Into<String>) -> Self {
292        let url = url.into();
293        self.overpass_url = url.clone();
294        self.overpass_endpoints = vec![url];
295        self
296    }
297
298    pub fn overpass_endpoints(mut self, urls: Vec<String>) -> Self {
299        if let Some(primary) = urls.first().cloned() {
300            self.overpass_url = primary;
301            self.overpass_endpoints = urls;
302        }
303        self
304    }
305
306    pub fn overpass_max_retries(mut self, retries: usize) -> Self {
307        self.overpass_max_retries = retries;
308        self
309    }
310
311    pub fn overpass_retry_backoff(mut self, backoff: Duration) -> Self {
312        self.overpass_retry_backoff = backoff;
313        self
314    }
315
316    pub fn cache_dir(mut self, path: impl Into<PathBuf>) -> Self {
317        self.cache_dir = path.into();
318        self
319    }
320
321    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
322        self.connect_timeout = timeout;
323        self
324    }
325
326    pub fn read_timeout(mut self, timeout: Duration) -> Self {
327        self.read_timeout = timeout;
328        self
329    }
330
331    pub fn speed_profile(mut self, profile: SpeedProfile) -> Self {
332        self.speed_profile = profile;
333        self
334    }
335
336    pub fn connectivity_policy(mut self, policy: ConnectivityPolicy) -> Self {
337        self.connectivity_policy = policy;
338        self
339    }
340
341    pub fn highway_types(mut self, types: Vec<&'static str>) -> Self {
342        self.highway_types = types;
343        self
344    }
345
346    pub(crate) fn highway_regex(&self) -> String {
347        format!("^({})$", self.highway_types.join("|"))
348    }
349}