Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / scripts / maps / osm_ingest / src / maxspeed.rs

maxspeed.rs217 lines · 8.6 KiBRaw
1//! The `maxspeed` layer: posted speed limits, for the app's `MaxspeedSource`.
2//!
3//! **Superseded by [`crate::roads`], and no longer in any build pipeline.** That
4//! layer carries the same geometry with the same raw `maxspeed` string beside the
5//! lane, width and class attributes the app needs to draw the road, so a second
6//! copy of every road in the world is not worth one property. Kept only so the
7//! retired layer can still be built and diffed against `roads`; delete it, and
8//! `build_maxspeed_layer.sh` and `normalize_maxspeed.py` with it, once that
9//! comparison is done.
10//!
11//! A port of `normalize_maxspeed.py`, which is the contract of record.
12//!
13//! ## The value is a RAW STRING and must stay one
14//!
15//! The emitted `maxspeed` property is the OSM tag verbatim: `"25 mph"`,
16//! `"100 km/h"`, `"50"`, `"none"`, `"walk"`, `"signals"`. The app parses it itself,
17//! in `OsmMaxspeed.kt::parseMaxspeed`, because the distinctions matter to it --
18//! `none` on an autobahn is not the same as an absent limit, and `walk` is not a
19//! number at all.
20//!
21//! **Do not route this through [`crate::tags::parse_maxspeed`].** That function
22//! exists for the routing graph, where a speed has to become a `u8` of km/h to go
23//! in an edge record, so it normalises units and collapses everything
24//! non-numeric to `0`. Sending the layer through it would turn `"25 mph"` into
25//! `40`, `"none"` into `0`, and `"walk"` into `0` -- three different facts about a
26//! road becoming the same one, with nothing in the pipeline to notice.
27//!
28//! ## Tag precedence
29//!
30//! First non-empty of `maxspeed`, `maxspeed:forward`, `maxspeed:backward`. The
31//! direction-agnostic tag wins; the directional ones are a fallback, and the layer
32//! does not record which one it used. That is a known simplification -- a road with
33//! different limits each way is rendered with one of them -- and it is what the
34//! Python did.
35
36use crate::geojson::{osm_ref, Feature, Geometry, Value};
37
38/// The keys `osmium tags-filter` narrowed on for this layer.
39pub const FILTERS: [&str; 3] = ["maxspeed", "maxspeed:forward", "maxspeed:backward"];
40
41#[derive(Debug, Default, Clone, Copy)]
42pub struct MaxspeedTags<'a> {
43 pub maxspeed: Option<&'a str>,
44 pub maxspeed_forward: Option<&'a str>,
45 pub maxspeed_backward: Option<&'a str>,
46 pub highway: Option<&'a str>,
47 pub name: Option<&'a str>,
48}
49
50/// The raw tag value to emit, or `None` when the way has no usable limit.
51pub fn extract<'a>(t: &MaxspeedTags<'a>) -> Option<&'a str> {
52 [t.maxspeed, t.maxspeed_forward, t.maxspeed_backward]
53 .into_iter()
54 .flatten()
55 .find(|v| !v.is_empty())
56}
57
58/// Build the emitted feature. Property order matches the Python's insertion order:
59/// `maxspeed`, then `highway`, then `name`, then `osm_id`.
60///
61/// `highway` and `name` are kept on plain emptiness, **not** on the `_truthy` test
62/// the safety layer uses: `normalize_maxspeed.py` has no `_truthy` at all, so
63/// `highway=no` survives here where `direction=no` would not survive there. An
64/// inconsistency in the original, reproduced deliberately rather than tidied, since
65/// tidying it would change what the layer contains.
66pub fn feature<'a>(
67 maxspeed: &'a str,
68 t: &MaxspeedTags<'a>,
69 geometry: Geometry,
70 way_id: i64,
71) -> Feature<'a> {
72 let mut props: Vec<(&'a str, Value)> = vec![("maxspeed", Value::str(maxspeed))];
73 if let Some(v) = t.highway.filter(|v| !v.is_empty()) {
74 props.push(("highway", Value::str(v)));
75 }
76 if let Some(v) = t.name.filter(|v| !v.is_empty()) {
77 props.push(("name", Value::str(v)));
78 }
79 props.push(("osm_id", osm_ref("way", way_id)));
80 Feature { geometry, props }
81}
82
83#[cfg(test)]
84mod tests {
85 use super::*;
86
87 fn tags<'a>(
88 ms: Option<&'a str>,
89 fwd: Option<&'a str>,
90 bwd: Option<&'a str>,
91 ) -> MaxspeedTags<'a> {
92 MaxspeedTags {
93 maxspeed: ms,
94 maxspeed_forward: fwd,
95 maxspeed_backward: bwd,
96 ..Default::default()
97 }
98 }
99
100 /// The seven emitted features of
101 /// `scripts/maps/test/fixtures/maxspeed_sample.geojsonseq`, as tag sets. The
102 /// fixture also holds a way with no maxspeed and a Point that has one; both are
103 /// dropped, the first by [`extract`] and the second by the geometry filter.
104 fn fixture_values() -> Vec<&'static str> {
105 [
106 tags(Some("25 mph"), None, None),
107 tags(Some("50"), None, None),
108 tags(Some("100 km/h"), None, None),
109 tags(None, Some("30 mph"), None),
110 tags(Some("none"), None, None),
111 tags(Some("walk"), None, None),
112 tags(Some("signals"), None, None),
113 ]
114 .iter()
115 .filter_map(extract)
116 .collect()
117 }
118
119 #[test]
120 fn emits_seven_values() {
121 assert_eq!(fixture_values().len(), 7);
122 }
123
124 #[test]
125 fn every_raw_form_survives_verbatim() {
126 // This is the whole point of the layer: the app parses these itself.
127 let values = fixture_values();
128 for want in ["25 mph", "50", "100 km/h", "30 mph", "none", "walk", "signals"] {
129 assert!(values.contains(&want), "{want:?} was lost: {values:?}");
130 }
131 }
132
133 #[test]
134 fn tags_rs_parse_maxspeed_would_destroy_every_one_of_them() {
135 // Not a test of this module so much as a guard on the wiring: if anyone
136 // routes the layer through the graph's parser, these are the answers they
137 // get instead. "25 mph" becomes 40, and the three non-numeric forms all
138 // become the same 0.
139 assert_eq!(crate::tags::parse_maxspeed(Some("25 mph")), 40);
140 assert_eq!(crate::tags::parse_maxspeed(Some("100 km/h")), 100);
141 for lossy in ["none", "walk", "signals"] {
142 assert_eq!(crate::tags::parse_maxspeed(Some(lossy)), 0, "{lossy}");
143 }
144 }
145
146 #[test]
147 fn precedence_is_maxspeed_then_forward_then_backward() {
148 assert_eq!(extract(&tags(Some("50"), Some("30"), Some("20"))), Some("50"));
149 assert_eq!(extract(&tags(None, Some("30"), Some("20"))), Some("30"));
150 assert_eq!(extract(&tags(None, None, Some("20"))), Some("20"));
151 assert_eq!(extract(&tags(None, None, None)), None);
152 }
153
154 #[test]
155 fn an_empty_tag_falls_through_to_the_next() {
156 // A present-but-empty tag is not a speed limit.
157 assert_eq!(extract(&tags(Some(""), Some("30"), None)), Some("30"));
158 assert_eq!(extract(&tags(Some(""), Some(""), Some(""))), None);
159 }
160
161 #[test]
162 fn the_emitted_schema_is_maxspeed_highway_name_osm_id() {
163 let t = MaxspeedTags {
164 maxspeed: Some("25 mph"),
165 highway: Some("residential"),
166 name: Some("Main St"),
167 ..Default::default()
168 };
169 let f = feature("25 mph", &t, Geometry::LineString(vec![(0.0, 0.0), (1.0, 1.0)]), 3001);
170 let keys: Vec<&str> = f.props.iter().map(|(k, _)| *k).collect();
171 assert_eq!(keys, ["maxspeed", "highway", "name", "osm_id"]);
172 match &f.props[3].1 {
173 Value::Str(s) => assert_eq!(s, b"way/3001"),
174 _ => panic!("osm_id must be the way/N string form"),
175 }
176 }
177
178 #[test]
179 fn highway_and_name_are_omitted_only_when_empty() {
180 let bare = MaxspeedTags { maxspeed: Some("50"), ..Default::default() };
181 assert_eq!(
182 feature("50", &bare, Geometry::LineString(vec![]), 1).props.len(),
183 2,
184 "maxspeed + osm_id only"
185 );
186 let empty = MaxspeedTags {
187 maxspeed: Some("50"),
188 highway: Some(""),
189 name: Some(""),
190 ..Default::default()
191 };
192 assert_eq!(feature("50", &empty, Geometry::LineString(vec![]), 1).props.len(), 2);
193
194 // `highway=no` IS kept: normalize_maxspeed.py used plain truthiness, not
195 // its own `_truthy`, unlike the safety layer.
196 let no = MaxspeedTags { maxspeed: Some("50"), highway: Some("no"), ..Default::default() };
197 assert_eq!(feature("50", &no, Geometry::LineString(vec![]), 1).props.len(), 3);
198 }
199
200 #[test]
201 fn the_pbf_filters_cover_every_tag_extract_reads() {
202 let select = crate::select::Select::parse(&FILTERS).unwrap();
203 for (ms, fwd, bwd) in
204 [(Some("50"), None, None), (None, Some("30 mph"), None), (None, None, Some("20"))]
205 {
206 let t = tags(ms, fwd, bwd);
207 let get = |k: &str| match k {
208 "maxspeed" => t.maxspeed,
209 "maxspeed:forward" => t.maxspeed_forward,
210 "maxspeed:backward" => t.maxspeed_backward,
211 _ => None,
212 };
213 assert!(extract(&t).is_some());
214 assert!(select.matches(get), "extract accepts what the filter rejects");
215 }
216 }
217}