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

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

maxspeed.rs219 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>(ms: Option<&'a str>, fwd: Option<&'a str>, bwd: Option<&'a str>) -> MaxspeedTags<'a> {
88 MaxspeedTags {
89 maxspeed: ms,
90 maxspeed_forward: fwd,
91 maxspeed_backward: bwd,
92 ..Default::default()
93 }
94 }
95
96 /// The seven emitted features of
97 /// `scripts/maps/test/fixtures/maxspeed_sample.geojsonseq`, as tag sets. The
98 /// fixture also holds a way with no maxspeed and a Point that has one; both are
99 /// dropped, the first by [`extract`] and the second by the geometry filter.
100 fn fixture_values() -> Vec<&'static str> {
101 [
102 tags(Some("25 mph"), None, None),
103 tags(Some("50"), None, None),
104 tags(Some("100 km/h"), None, None),
105 tags(None, Some("30 mph"), None),
106 tags(Some("none"), None, None),
107 tags(Some("walk"), None, None),
108 tags(Some("signals"), None, None),
109 ]
110 .iter()
111 .filter_map(extract)
112 .collect()
113 }
114
115 #[test]
116 fn emits_seven_values() {
117 assert_eq!(fixture_values().len(), 7);
118 }
119
120 #[test]
121 fn every_raw_form_survives_verbatim() {
122 // This is the whole point of the layer: the app parses these itself.
123 let values = fixture_values();
124 for want in ["25 mph", "50", "100 km/h", "30 mph", "none", "walk", "signals"] {
125 assert!(values.contains(&want), "{want:?} was lost: {values:?}");
126 }
127 }
128
129 #[test]
130 fn tags_rs_parse_maxspeed_would_destroy_every_one_of_them() {
131 // Not a test of this module so much as a guard on the wiring: if anyone
132 // routes the layer through the graph's parser, these are the answers they
133 // get instead. "25 mph" becomes 40, and the three non-numeric forms all
134 // become the same 0.
135 assert_eq!(crate::tags::parse_maxspeed(Some("25 mph")), 40);
136 assert_eq!(crate::tags::parse_maxspeed(Some("100 km/h")), 100);
137 for lossy in ["none", "walk", "signals"] {
138 assert_eq!(crate::tags::parse_maxspeed(Some(lossy)), 0, "{lossy}");
139 }
140 }
141
142 #[test]
143 fn precedence_is_maxspeed_then_forward_then_backward() {
144 assert_eq!(extract(&tags(Some("50"), Some("30"), Some("20"))), Some("50"));
145 assert_eq!(extract(&tags(None, Some("30"), Some("20"))), Some("30"));
146 assert_eq!(extract(&tags(None, None, Some("20"))), Some("20"));
147 assert_eq!(extract(&tags(None, None, None)), None);
148 }
149
150 #[test]
151 fn an_empty_tag_falls_through_to_the_next() {
152 // A present-but-empty tag is not a speed limit.
153 assert_eq!(extract(&tags(Some(""), Some("30"), None)), Some("30"));
154 assert_eq!(extract(&tags(Some(""), Some(""), Some(""))), None);
155 }
156
157 #[test]
158 fn the_emitted_schema_is_maxspeed_highway_name_osm_id() {
159 let t = MaxspeedTags {
160 maxspeed: Some("25 mph"),
161 highway: Some("residential"),
162 name: Some("Main St"),
163 ..Default::default()
164 };
165 let f = feature("25 mph", &t, Geometry::LineString(vec![(0.0, 0.0), (1.0, 1.0)]), 3001);
166 let keys: Vec<&str> = f.props.iter().map(|(k, _)| *k).collect();
167 assert_eq!(keys, ["maxspeed", "highway", "name", "osm_id"]);
168 match &f.props[3].1 {
169 Value::Str(s) => assert_eq!(s, b"way/3001"),
170 _ => panic!("osm_id must be the way/N string form"),
171 }
172 }
173
174 #[test]
175 fn highway_and_name_are_omitted_only_when_empty() {
176 let bare = MaxspeedTags { maxspeed: Some("50"), ..Default::default() };
177 assert_eq!(
178 feature("50", &bare, Geometry::LineString(vec![]), 1).props.len(),
179 2,
180 "maxspeed + osm_id only"
181 );
182 let empty = MaxspeedTags {
183 maxspeed: Some("50"),
184 highway: Some(""),
185 name: Some(""),
186 ..Default::default()
187 };
188 assert_eq!(feature("50", &empty, Geometry::LineString(vec![]), 1).props.len(), 2);
189
190 // `highway=no` IS kept: normalize_maxspeed.py used plain truthiness, not
191 // its own `_truthy`, unlike the safety layer.
192 let no = MaxspeedTags {
193 maxspeed: Some("50"),
194 highway: Some("no"),
195 ..Default::default()
196 };
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),
205 (None, Some("30 mph"), None),
206 (None, None, Some("20")),
207 ] {
208 let t = tags(ms, fwd, bwd);
209 let get = |k: &str| match k {
210 "maxspeed" => t.maxspeed,
211 "maxspeed:forward" => t.maxspeed_forward,
212 "maxspeed:backward" => t.maxspeed_backward,
213 _ => None,
214 };
215 assert!(extract(&t).is_some());
216 assert!(select.matches(get), "extract accepts what the filter rejects");
217 }
218 }
219}