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

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

safety.rs484 lines · 16.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",
65 "man_made=surveillance",
66 "enforcement=maxspeed",
67];
68
69/// Just the tags this layer reads, in the plain `Option<&str>` shape
70/// [`crate::tags`] uses, so classification is testable with no PBF.
71#[derive(Debug, Default, Clone, Copy)]
72pub struct SafetyTags<'a> {
73 pub highway: Option<&'a str>,
74 pub man_made: Option<&'a str>,
75 pub enforcement: Option<&'a str>,
76 pub surveillance_type: Option<&'a str>,
77 pub camera_type: Option<&'a str>,
78 pub operator: Option<&'a str>,
79 pub manufacturer: Option<&'a str>,
80 pub name: Option<&'a str>,
81 pub direction: Option<&'a str>,
82 pub reference: Option<&'a str>,
83}
84
85/// `normalize_safety.py`'s `_truthy`: absent, empty, and the three "no" spellings
86/// all count as missing, so a `direction=no` never reaches the layer.
87pub fn truthy(v: Option<&str>) -> bool {
88 !matches!(v, None | Some("") | Some("no") | Some("false") | Some("0"))
89}
90
91pub fn classify(t: &SafetyTags) -> Option<Kind> {
92 if t.highway == Some("speed_camera") {
93 return Some(Kind::SpeedCamera);
94 }
95 // A node on an enforcement=maxspeed relation is often tagged directly, and
96 // this must be checked before the surveillance branch below.
97 if t.enforcement == Some("maxspeed") {
98 return Some(Kind::SpeedCamera);
99 }
100
101 if t.man_made == Some("surveillance") {
102 let surv = t.surveillance_type.unwrap_or("").to_lowercase();
103 let cam = t.camera_type.unwrap_or("").to_lowercase();
104 let operator = t.operator.unwrap_or("").to_lowercase();
105 let manufacturer = t.manufacturer.unwrap_or("").to_lowercase();
106 let is_alpr = surv.contains("alpr")
107 || surv.contains("anpr")
108 || cam == "alpr"
109 || cam == "anpr"
110 || operator.contains("flock")
111 || manufacturer.contains("flock");
112 return Some(if is_alpr { Kind::Alpr } else { Kind::Surveillance });
113 }
114
115 if t.highway == Some("stop") {
116 return Some(Kind::StopSign);
117 }
118 if t.highway == Some("traffic_signals") {
119 return Some(Kind::TrafficSignals);
120 }
121 None
122}
123
124/// Build the emitted feature. Property order matches the Python's insertion
125/// order: `kind`, then the carried attributes, then `osm_id`.
126pub fn feature<'a>(kind: Kind, t: &SafetyTags<'a>, lon: f64, lat: f64, node_id: i64) -> Feature<'a> {
127 let mut props: Vec<(&'a str, Value)> = vec![("kind", Value::str(kind.as_str()))];
128 for (key, value) in [
129 ("name", t.name),
130 ("direction", t.direction),
131 ("operator", t.operator),
132 ("ref", t.reference),
133 ("surveillance_type", t.surveillance_type),
134 ] {
135 if truthy(value) {
136 props.push((key, Value::str(value.unwrap())));
137 }
138 }
139 // Always a string, as the Python's `str(osm_id)` made it, and always the
140 // `node/N` form the harness pairs features on.
141 props.push(("osm_id", osm_ref("node", node_id)));
142 Feature {
143 geometry: Geometry::Point((lon, lat)),
144 props,
145 }
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 (
173 "node/1002",
174 SafetyTags {
175 enforcement: Some("maxspeed"),
176 ..Default::default()
177 },
178 true,
179 ),
180 // node/1003 -- surveillance:type=ALPR, operator Flock Safety.
181 (
182 "node/1003",
183 SafetyTags {
184 man_made: Some("surveillance"),
185 surveillance_type: Some("ALPR"),
186 operator: Some("Flock Safety"),
187 ..Default::default()
188 },
189 true,
190 ),
191 // node/1004 -- ALPR via camera:type instead.
192 (
193 "node/1004",
194 SafetyTags {
195 man_made: Some("surveillance"),
196 camera_type: Some("alpr"),
197 ..Default::default()
198 },
199 true,
200 ),
201 // node/1005 -- a plain surveillance camera.
202 (
203 "node/1005",
204 SafetyTags {
205 man_made: Some("surveillance"),
206 camera_type: Some("fixed"),
207 ..Default::default()
208 },
209 true,
210 ),
211 // node/1006 -- a stop sign.
212 (
213 "node/1006",
214 SafetyTags {
215 highway: Some("stop"),
216 ..Default::default()
217 },
218 true,
219 ),
220 // node/1007 -- traffic signals.
221 (
222 "node/1007",
223 SafetyTags {
224 highway: Some("traffic_signals"),
225 ..Default::default()
226 },
227 true,
228 ),
229 // node/1008 -- a cafe. Not safety furniture.
230 (
231 "node/1008",
232 SafetyTags {
233 name: Some("Corner Cafe"),
234 ..Default::default()
235 },
236 false,
237 ),
238 // way/1009 -- highway=stop on a LineString. Classifies, but the
239 // geometry filter drops it, which is why `emitted` is false.
240 (
241 "way/1009",
242 SafetyTags {
243 highway: Some("stop"),
244 ..Default::default()
245 },
246 false,
247 ),
248 ]
249 }
250
251 /// The kinds the layer emits for the fixture, i.e. after both the
252 /// classification and the Point-only geometry filter.
253 fn fixture_kinds() -> Vec<Kind> {
254 fixture()
255 .iter()
256 .filter(|(_, _, emitted)| *emitted)
257 .filter_map(|(_, t, _)| classify(t))
258 .collect()
259 }
260
261 fn count(kinds: &[Kind], want: Kind) -> usize {
262 kinds.iter().filter(|k| **k == want).count()
263 }
264
265 #[test]
266 fn emits_seven_features() {
267 assert_eq!(fixture_kinds().len(), 7);
268 }
269
270 #[test]
271 fn speed_camera_from_highway_and_from_enforcement() {
272 let kinds = fixture_kinds();
273 assert!(kinds.contains(&Kind::SpeedCamera));
274 // Two routes to the same kind: the tag and the enforcement relation role.
275 assert_eq!(count(&kinds, Kind::SpeedCamera), 2);
276 }
277
278 #[test]
279 fn alpr_from_surveillance_type_and_from_camera_type() {
280 let kinds = fixture_kinds();
281 assert!(kinds.contains(&Kind::Alpr));
282 assert_eq!(count(&kinds, Kind::Alpr), 2);
283 }
284
285 #[test]
286 fn generic_surveillance_stop_sign_and_traffic_signals() {
287 let kinds = fixture_kinds();
288 assert!(kinds.contains(&Kind::Surveillance));
289 assert!(kinds.contains(&Kind::StopSign));
290 assert!(kinds.contains(&Kind::TrafficSignals));
291 }
292
293 #[test]
294 fn nothing_non_safety_leaks_through() {
295 let cafe = fixture()
296 .into_iter()
297 .find(|(id, _, _)| *id == "node/1008")
298 .unwrap();
299 assert_eq!(classify(&cafe.1), None, "a cafe is not road furniture");
300 }
301
302 #[test]
303 fn alpr_keeps_its_operator() {
304 let (_, tags, _) = fixture()
305 .into_iter()
306 .find(|(id, _, _)| *id == "node/1003")
307 .unwrap();
308 let f = feature(classify(&tags).unwrap(), &tags, -122.417, 37.777, 1003);
309 let operator = f
310 .props
311 .iter()
312 .find(|(k, _)| *k == "operator")
313 .expect("operator carried through");
314 match &operator.1 {
315 Value::Str(s) => assert_eq!(s, b"Flock Safety"),
316 _ => panic!("operator must be a string"),
317 }
318 }
319
320 #[test]
321 fn every_feature_carries_an_osm_id_and_point_geometry() {
322 for (_, tags, emitted) in fixture() {
323 if !emitted {
324 continue;
325 }
326 let kind = classify(&tags).unwrap();
327 let f = feature(kind, &tags, 0.0, 0.0, 1);
328 assert!(matches!(f.geometry, Geometry::Point(_)));
329 // osm_id is last and always present.
330 assert_eq!(f.props.last().unwrap().0, "osm_id");
331 assert_eq!(f.props.first().unwrap().0, "kind");
332 }
333 }
334
335 // --- the rules the fixture cannot express on its own ---
336
337 #[test]
338 fn enforcement_wins_over_surveillance() {
339 // The ordering trap: a camera tagged both ways is a speed camera. Getting
340 // this backwards reclassifies every enforcement camera as surveillance.
341 let t = SafetyTags {
342 man_made: Some("surveillance"),
343 enforcement: Some("maxspeed"),
344 surveillance_type: Some("ALPR"),
345 ..Default::default()
346 };
347 assert_eq!(classify(&t), Some(Kind::SpeedCamera));
348 }
349
350 #[test]
351 fn surveillance_type_matches_by_substring_but_camera_type_by_equality() {
352 fn surv<'a>(v: &'a str) -> SafetyTags<'a> {
353 SafetyTags {
354 man_made: Some("surveillance"),
355 surveillance_type: Some(v),
356 ..Default::default()
357 }
358 }
359 // Substring, and case-insensitive.
360 assert_eq!(classify(&surv("ALPR")), Some(Kind::Alpr));
361 assert_eq!(classify(&surv("alpr;camera")), Some(Kind::Alpr));
362 assert_eq!(classify(&surv("traffic ANPR")), Some(Kind::Alpr));
363 assert_eq!(classify(&surv("public")), Some(Kind::Surveillance));
364
365 fn cam<'a>(v: &'a str) -> SafetyTags<'a> {
366 SafetyTags {
367 man_made: Some("surveillance"),
368 camera_type: Some(v),
369 ..Default::default()
370 }
371 }
372 assert_eq!(classify(&cam("alpr")), Some(Kind::Alpr));
373 assert_eq!(classify(&cam("ANPR")), Some(Kind::Alpr));
374 // Exact match only: an enumerated field must not be substring-matched, or
375 // every `alpr_capable`-style value would silently become an ALPR.
376 assert_eq!(classify(&cam("alpr;dome")), Some(Kind::Surveillance));
377 assert_eq!(classify(&cam("fixed")), Some(Kind::Surveillance));
378 }
379
380 #[test]
381 fn the_flock_heuristic_hits_operator_and_manufacturer() {
382 let base = SafetyTags {
383 man_made: Some("surveillance"),
384 ..Default::default()
385 };
386 assert_eq!(
387 classify(&SafetyTags {
388 operator: Some("Flock Safety"),
389 ..base
390 }),
391 Some(Kind::Alpr)
392 );
393 assert_eq!(
394 classify(&SafetyTags {
395 manufacturer: Some("Flock Safety LLC"),
396 ..base
397 }),
398 Some(Kind::Alpr)
399 );
400 assert_eq!(
401 classify(&SafetyTags {
402 operator: Some("City of Oakland"),
403 ..base
404 }),
405 Some(Kind::Surveillance)
406 );
407 }
408
409 #[test]
410 fn surveillance_type_is_kept_as_a_property() {
411 // Undocumented in the schema table but emitted by the Python, and the app
412 // may already be reading it. Dropping it would be a silent schema break.
413 let t = SafetyTags {
414 man_made: Some("surveillance"),
415 surveillance_type: Some("ALPR"),
416 ..Default::default()
417 };
418 let f = feature(Kind::Alpr, &t, 0.0, 0.0, 1);
419 assert!(f.props.iter().any(|(k, _)| *k == "surveillance_type"));
420 }
421
422 #[test]
423 fn falsey_attribute_values_are_dropped() {
424 for v in ["", "no", "false", "0"] {
425 let t = SafetyTags {
426 highway: Some("stop"),
427 direction: Some(v),
428 name: Some(v),
429 ..Default::default()
430 };
431 let f = feature(Kind::StopSign, &t, 0.0, 0.0, 1);
432 assert_eq!(
433 f.props.len(),
434 2,
435 "kind + osm_id only, but {v:?} was carried through"
436 );
437 }
438 // Anything else is kept, including values that merely look falsey.
439 let t = SafetyTags {
440 highway: Some("stop"),
441 direction: Some("both"),
442 ..Default::default()
443 };
444 assert_eq!(feature(Kind::StopSign, &t, 0.0, 0.0, 1).props.len(), 3);
445 }
446
447 #[test]
448 fn untagged_and_unrelated_nodes_classify_to_nothing() {
449 assert_eq!(classify(&SafetyTags::default()), None);
450 assert_eq!(
451 classify(&SafetyTags {
452 highway: Some("residential"),
453 ..Default::default()
454 }),
455 None
456 );
457 // `man_made` that is not surveillance falls through to the highway rules.
458 assert_eq!(
459 classify(&SafetyTags {
460 man_made: Some("mast"),
461 ..Default::default()
462 }),
463 None
464 );
465 }
466
467 #[test]
468 fn the_pbf_filters_cover_every_classifying_tag() {
469 let select = crate::select::Select::parse(&FILTERS).unwrap();
470 for (id, tags, _) in fixture() {
471 let get = |k: &str| match k {
472 "highway" => tags.highway,
473 "man_made" => tags.man_made,
474 "enforcement" => tags.enforcement,
475 _ => None,
476 };
477 // The pre-filter must never reject something the classifier accepts,
478 // or the layer loses features for a reason nothing reports.
479 if classify(&tags).is_some() {
480 assert!(select.matches(get), "{id} classifies but is pre-filtered out");
481 }
482 }
483 }
484}