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

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

safety.rs415 lines · 15.5 KiBRaw
1//! The `safety` layer: baked road furniture -- speed cameras, ALPR, generic
2//! surveillance, stop signs and traffic signals.
3//!
4//! A port of `normalize_safety.py`, which is the contract of record. Everything
5//! here is node-based; `osmium export` produced the odd tagged way with these
6//! tags, and the Python dropped anything that was not a `Point`, so we only ever
7//! look at nodes.
8//!
9//! ## The classification order is load-bearing
10//!
11//! It is a chain of early returns, not a set of independent rules:
12//!
13//! 1. `highway=speed_camera`
14//! 2. `enforcement=maxspeed` -- **before** the surveillance branch. A camera
15//! tagged both `man_made=surveillance` and `enforcement=maxspeed` is a speed
16//! camera, not a surveillance camera, and reordering these two silently
17//! reclassifies a whole category.
18//! 3. `man_made=surveillance`, split into `alpr` or `surveillance`
19//! 4. `highway=stop`
20//! 5. `highway=traffic_signals`
21//!
22//! ## The ALPR heuristic is deliberately asymmetric
23//!
24//! DeFlock (deflock.me) tags automated licence-plate readers as
25//! `man_made=surveillance` plus `surveillance:type=ALPR`, and Flock Safety is the
26//! dominant operator and manufacturer. So:
27//!
28//! * `surveillance:type` is matched by **substring**, because real values include
29//! things like `ALPR;camera` and `traffic ANPR`.
30//! * `camera:type` is matched by **exact equality** against `alpr`/`anpr`,
31//! because it is an enumerated field whose other values (`fixed`, `dome`,
32//! `panning`) would be corrupted by a substring rule.
33//! * `operator` and `manufacturer` are matched by substring on `flock`, catching
34//! "Flock Safety", "Flock Safety LLC" and so on.
35//!
36//! That asymmetry is not an oversight in the Python and must survive the port.
37
38use crate::geojson::{osm_ref, Feature, Geometry, Value};
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum Kind {
42 SpeedCamera,
43 Alpr,
44 Surveillance,
45 StopSign,
46 TrafficSignals,
47}
48
49impl Kind {
50 pub fn as_str(self) -> &'static str {
51 match self {
52 Kind::SpeedCamera => "speed_camera",
53 Kind::Alpr => "alpr",
54 Kind::Surveillance => "surveillance",
55 Kind::StopSign => "stop_sign",
56 Kind::TrafficSignals => "traffic_signals",
57 }
58 }
59}
60
61/// The keys `osmium tags-filter` narrowed on, and which therefore have to be in
62/// the PBF pre-filter for this layer.
63pub const FILTERS: [&str; 3] =
64 ["highway=speed_camera,stop,traffic_signals", "man_made=surveillance", "enforcement=maxspeed"];
65
66/// Just the tags this layer reads, in the plain `Option<&str>` shape
67/// [`crate::tags`] uses, so classification is testable with no PBF.
68#[derive(Debug, Default, Clone, Copy)]
69pub struct SafetyTags<'a> {
70 pub highway: Option<&'a str>,
71 pub man_made: Option<&'a str>,
72 pub enforcement: Option<&'a str>,
73 pub surveillance_type: Option<&'a str>,
74 pub camera_type: Option<&'a str>,
75 pub operator: Option<&'a str>,
76 pub manufacturer: Option<&'a str>,
77 pub name: Option<&'a str>,
78 pub direction: Option<&'a str>,
79 pub reference: Option<&'a str>,
80}
81
82/// `normalize_safety.py`'s `_truthy`: absent, empty, and the three "no" spellings
83/// all count as missing, so a `direction=no` never reaches the layer.
84pub fn truthy(v: Option<&str>) -> bool {
85 !matches!(v, None | Some("") | Some("no") | Some("false") | Some("0"))
86}
87
88pub fn classify(t: &SafetyTags) -> Option<Kind> {
89 if t.highway == Some("speed_camera") {
90 return Some(Kind::SpeedCamera);
91 }
92 // A node on an enforcement=maxspeed relation is often tagged directly, and
93 // this must be checked before the surveillance branch below.
94 if t.enforcement == Some("maxspeed") {
95 return Some(Kind::SpeedCamera);
96 }
97
98 if t.man_made == Some("surveillance") {
99 let surv = t.surveillance_type.unwrap_or("").to_lowercase();
100 let cam = t.camera_type.unwrap_or("").to_lowercase();
101 let operator = t.operator.unwrap_or("").to_lowercase();
102 let manufacturer = t.manufacturer.unwrap_or("").to_lowercase();
103 let is_alpr = surv.contains("alpr")
104 || surv.contains("anpr")
105 || cam == "alpr"
106 || cam == "anpr"
107 || operator.contains("flock")
108 || manufacturer.contains("flock");
109 return Some(if is_alpr { Kind::Alpr } else { Kind::Surveillance });
110 }
111
112 if t.highway == Some("stop") {
113 return Some(Kind::StopSign);
114 }
115 if t.highway == Some("traffic_signals") {
116 return Some(Kind::TrafficSignals);
117 }
118 None
119}
120
121/// Build the emitted feature. Property order matches the Python's insertion
122/// order: `kind`, then the carried attributes, then `osm_id`.
123pub fn feature<'a>(
124 kind: Kind,
125 t: &SafetyTags<'a>,
126 lon: f64,
127 lat: f64,
128 node_id: i64,
129) -> Feature<'a> {
130 let mut props: Vec<(&'a str, Value)> = vec![("kind", Value::str(kind.as_str()))];
131 for (key, value) in [
132 ("name", t.name),
133 ("direction", t.direction),
134 ("operator", t.operator),
135 ("ref", t.reference),
136 ("surveillance_type", t.surveillance_type),
137 ] {
138 if truthy(value) {
139 props.push((key, Value::str(value.unwrap())));
140 }
141 }
142 // Always a string, as the Python's `str(osm_id)` made it, and always the
143 // `node/N` form the harness pairs features on.
144 props.push(("osm_id", osm_ref("node", node_id)));
145 Feature { geometry: Geometry::Point((lon, lat)), props }
146}
147
148#[cfg(test)]
149mod tests {
150 use super::*;
151
152 /// The nine features of `scripts/maps/test/fixtures/safety_sample.geojsonseq`,
153 /// transcribed as tag sets.
154 ///
155 /// The fixture is GeoJSON, which this crate has no reader for and does not
156 /// want one -- it reads PBF. What the fixture actually pins is the tag-to-kind
157 /// mapping, so the tags are what gets mirrored, and the assertions below are
158 /// the twelve `test_normalize.py::test_safety` checks one for one.
159 fn fixture() -> Vec<(&'static str, SafetyTags<'static>, bool)> {
160 vec![
161 // node/1001 -- highway=speed_camera with a direction.
162 (
163 "node/1001",
164 SafetyTags {
165 highway: Some("speed_camera"),
166 direction: Some("forward"),
167 ..Default::default()
168 },
169 true,
170 ),
171 // node/1002 -- enforcement=maxspeed, the second route to speed_camera.
172 ("node/1002", SafetyTags { enforcement: Some("maxspeed"), ..Default::default() }, true),
173 // node/1003 -- surveillance:type=ALPR, operator Flock Safety.
174 (
175 "node/1003",
176 SafetyTags {
177 man_made: Some("surveillance"),
178 surveillance_type: Some("ALPR"),
179 operator: Some("Flock Safety"),
180 ..Default::default()
181 },
182 true,
183 ),
184 // node/1004 -- ALPR via camera:type instead.
185 (
186 "node/1004",
187 SafetyTags {
188 man_made: Some("surveillance"),
189 camera_type: Some("alpr"),
190 ..Default::default()
191 },
192 true,
193 ),
194 // node/1005 -- a plain surveillance camera.
195 (
196 "node/1005",
197 SafetyTags {
198 man_made: Some("surveillance"),
199 camera_type: Some("fixed"),
200 ..Default::default()
201 },
202 true,
203 ),
204 // node/1006 -- a stop sign.
205 ("node/1006", SafetyTags { highway: Some("stop"), ..Default::default() }, true),
206 // node/1007 -- traffic signals.
207 (
208 "node/1007",
209 SafetyTags { highway: Some("traffic_signals"), ..Default::default() },
210 true,
211 ),
212 // node/1008 -- a cafe. Not safety furniture.
213 ("node/1008", SafetyTags { name: Some("Corner Cafe"), ..Default::default() }, false),
214 // way/1009 -- highway=stop on a LineString. Classifies, but the
215 // geometry filter drops it, which is why `emitted` is false.
216 ("way/1009", SafetyTags { highway: Some("stop"), ..Default::default() }, false),
217 ]
218 }
219
220 /// The kinds the layer emits for the fixture, i.e. after both the
221 /// classification and the Point-only geometry filter.
222 fn fixture_kinds() -> Vec<Kind> {
223 fixture()
224 .iter()
225 .filter(|(_, _, emitted)| *emitted)
226 .filter_map(|(_, t, _)| classify(t))
227 .collect()
228 }
229
230 fn count(kinds: &[Kind], want: Kind) -> usize {
231 kinds.iter().filter(|k| **k == want).count()
232 }
233
234 #[test]
235 fn emits_seven_features() {
236 assert_eq!(fixture_kinds().len(), 7);
237 }
238
239 #[test]
240 fn speed_camera_from_highway_and_from_enforcement() {
241 let kinds = fixture_kinds();
242 assert!(kinds.contains(&Kind::SpeedCamera));
243 // Two routes to the same kind: the tag and the enforcement relation role.
244 assert_eq!(count(&kinds, Kind::SpeedCamera), 2);
245 }
246
247 #[test]
248 fn alpr_from_surveillance_type_and_from_camera_type() {
249 let kinds = fixture_kinds();
250 assert!(kinds.contains(&Kind::Alpr));
251 assert_eq!(count(&kinds, Kind::Alpr), 2);
252 }
253
254 #[test]
255 fn generic_surveillance_stop_sign_and_traffic_signals() {
256 let kinds = fixture_kinds();
257 assert!(kinds.contains(&Kind::Surveillance));
258 assert!(kinds.contains(&Kind::StopSign));
259 assert!(kinds.contains(&Kind::TrafficSignals));
260 }
261
262 #[test]
263 fn nothing_non_safety_leaks_through() {
264 let cafe = fixture().into_iter().find(|(id, _, _)| *id == "node/1008").unwrap();
265 assert_eq!(classify(&cafe.1), None, "a cafe is not road furniture");
266 }
267
268 #[test]
269 fn alpr_keeps_its_operator() {
270 let (_, tags, _) = fixture().into_iter().find(|(id, _, _)| *id == "node/1003").unwrap();
271 let f = feature(classify(&tags).unwrap(), &tags, -122.417, 37.777, 1003);
272 let operator =
273 f.props.iter().find(|(k, _)| *k == "operator").expect("operator carried through");
274 match &operator.1 {
275 Value::Str(s) => assert_eq!(s, b"Flock Safety"),
276 _ => panic!("operator must be a string"),
277 }
278 }
279
280 #[test]
281 fn every_feature_carries_an_osm_id_and_point_geometry() {
282 for (_, tags, emitted) in fixture() {
283 if !emitted {
284 continue;
285 }
286 let kind = classify(&tags).unwrap();
287 let f = feature(kind, &tags, 0.0, 0.0, 1);
288 assert!(matches!(f.geometry, Geometry::Point(_)));
289 // osm_id is last and always present.
290 assert_eq!(f.props.last().unwrap().0, "osm_id");
291 assert_eq!(f.props.first().unwrap().0, "kind");
292 }
293 }
294
295 // --- the rules the fixture cannot express on its own ---
296
297 #[test]
298 fn enforcement_wins_over_surveillance() {
299 // The ordering trap: a camera tagged both ways is a speed camera. Getting
300 // this backwards reclassifies every enforcement camera as surveillance.
301 let t = SafetyTags {
302 man_made: Some("surveillance"),
303 enforcement: Some("maxspeed"),
304 surveillance_type: Some("ALPR"),
305 ..Default::default()
306 };
307 assert_eq!(classify(&t), Some(Kind::SpeedCamera));
308 }
309
310 #[test]
311 fn surveillance_type_matches_by_substring_but_camera_type_by_equality() {
312 fn surv<'a>(v: &'a str) -> SafetyTags<'a> {
313 SafetyTags {
314 man_made: Some("surveillance"),
315 surveillance_type: Some(v),
316 ..Default::default()
317 }
318 }
319 // Substring, and case-insensitive.
320 assert_eq!(classify(&surv("ALPR")), Some(Kind::Alpr));
321 assert_eq!(classify(&surv("alpr;camera")), Some(Kind::Alpr));
322 assert_eq!(classify(&surv("traffic ANPR")), Some(Kind::Alpr));
323 assert_eq!(classify(&surv("public")), Some(Kind::Surveillance));
324
325 fn cam<'a>(v: &'a str) -> SafetyTags<'a> {
326 SafetyTags {
327 man_made: Some("surveillance"),
328 camera_type: Some(v),
329 ..Default::default()
330 }
331 }
332 assert_eq!(classify(&cam("alpr")), Some(Kind::Alpr));
333 assert_eq!(classify(&cam("ANPR")), Some(Kind::Alpr));
334 // Exact match only: an enumerated field must not be substring-matched, or
335 // every `alpr_capable`-style value would silently become an ALPR.
336 assert_eq!(classify(&cam("alpr;dome")), Some(Kind::Surveillance));
337 assert_eq!(classify(&cam("fixed")), Some(Kind::Surveillance));
338 }
339
340 #[test]
341 fn the_flock_heuristic_hits_operator_and_manufacturer() {
342 let base = SafetyTags { man_made: Some("surveillance"), ..Default::default() };
343 assert_eq!(
344 classify(&SafetyTags { operator: Some("Flock Safety"), ..base }),
345 Some(Kind::Alpr)
346 );
347 assert_eq!(
348 classify(&SafetyTags { manufacturer: Some("Flock Safety LLC"), ..base }),
349 Some(Kind::Alpr)
350 );
351 assert_eq!(
352 classify(&SafetyTags { operator: Some("City of Oakland"), ..base }),
353 Some(Kind::Surveillance)
354 );
355 }
356
357 #[test]
358 fn surveillance_type_is_kept_as_a_property() {
359 // Undocumented in the schema table but emitted by the Python, and the app
360 // may already be reading it. Dropping it would be a silent schema break.
361 let t = SafetyTags {
362 man_made: Some("surveillance"),
363 surveillance_type: Some("ALPR"),
364 ..Default::default()
365 };
366 let f = feature(Kind::Alpr, &t, 0.0, 0.0, 1);
367 assert!(f.props.iter().any(|(k, _)| *k == "surveillance_type"));
368 }
369
370 #[test]
371 fn falsey_attribute_values_are_dropped() {
372 for v in ["", "no", "false", "0"] {
373 let t = SafetyTags {
374 highway: Some("stop"),
375 direction: Some(v),
376 name: Some(v),
377 ..Default::default()
378 };
379 let f = feature(Kind::StopSign, &t, 0.0, 0.0, 1);
380 assert_eq!(f.props.len(), 2, "kind + osm_id only, but {v:?} was carried through");
381 }
382 // Anything else is kept, including values that merely look falsey.
383 let t = SafetyTags { highway: Some("stop"), direction: Some("both"), ..Default::default() };
384 assert_eq!(feature(Kind::StopSign, &t, 0.0, 0.0, 1).props.len(), 3);
385 }
386
387 #[test]
388 fn untagged_and_unrelated_nodes_classify_to_nothing() {
389 assert_eq!(classify(&SafetyTags::default()), None);
390 assert_eq!(
391 classify(&SafetyTags { highway: Some("residential"), ..Default::default() }),
392 None
393 );
394 // `man_made` that is not surveillance falls through to the highway rules.
395 assert_eq!(classify(&SafetyTags { man_made: Some("mast"), ..Default::default() }), None);
396 }
397
398 #[test]
399 fn the_pbf_filters_cover_every_classifying_tag() {
400 let select = crate::select::Select::parse(&FILTERS).unwrap();
401 for (id, tags, _) in fixture() {
402 let get = |k: &str| match k {
403 "highway" => tags.highway,
404 "man_made" => tags.man_made,
405 "enforcement" => tags.enforcement,
406 _ => None,
407 };
408 // The pre-filter must never reject something the classifier accepts,
409 // or the layer loses features for a reason nothing reports.
410 if classify(&tags).is_some() {
411 assert!(select.matches(get), "{id} classifies but is pre-filtered out");
412 }
413 }
414 }
415}