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

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

admin.rs215 lines · 8.2 KiBRaw
1//! The `admin_city` layer: OSM `admin_level=8` boundaries, for the app's border
2//! masks and labels.
3//!
4//! A port of `normalize_admin.py --level city`. Only the city level comes from OSM;
5//! `admin_country` and `admin_region` come from Natural Earth, which is not
6//! derivable from OSM and is handled elsewhere. See the README's caveats.
7//!
8//! ## `name_en` has no fallback to plain `name` here
9//!
10//! The three levels disagree, and the disagreement is in the Python:
11//!
12//! | level | `name` from | `name_en` from |
13//! |---|---|---|
14//! | country | `NAME_EN, name:en, NAME, name` | `NAME_EN, name:en` |
15//! | region | `name_en, NAME_EN, name, NAME` | `name_en, NAME_EN, name:en` |
16//! | **city** | `name:en, name, NAME_EN, NAME` | **`name:en, NAME_EN`** |
17//!
18//! So a city tagged only `name=Oakland` gets `name` and **no** `name_en`, where a
19//! region tagged only `name=California` would get both. Adding the fallback would
20//! be a defensible schema decision and a silent change to what the layer contains,
21//! so it is not made here.
22//!
23//! ## The level filter
24//!
25//! `boundary=administrative` (absent counts as administrative) **and**
26//! `admin_level=8`. A relation with neither key is accepted -- that branch existed
27//! for Natural Earth rows, which carry no OSM admin tagging -- but a PBF relation
28//! always has both, so in practice both must match.
29
30use crate::geojson::{osm_ref, Feature, Geometry, Value};
31
32/// The admin level this layer takes.
33pub const CITY_LEVEL: i64 = 8;
34
35/// The `osmium tags-filter` expression for the layer.
36pub const FILTERS: [&str; 1] = ["boundary=administrative"];
37
38#[derive(Debug, Default, Clone, Copy)]
39pub struct AdminTags<'a> {
40 pub boundary: Option<&'a str>,
41 pub admin_level: Option<&'a str>,
42 pub name_en_tag: Option<&'a str>,
43 pub name: Option<&'a str>,
44 /// The relation `type`, which must be `boundary` for a boundary relation.
45 pub type_: Option<&'a str>,
46}
47
48/// `normalize_admin.py`'s `_get`: the first key whose value is neither absent nor
49/// empty.
50fn first<const N: usize>(values: [Option<&str>; N]) -> Option<&str> {
51 values.into_iter().flatten().find(|v| !v.is_empty())
52}
53
54/// `is_admin_level(tags, 8)`.
55pub fn is_city(t: &AdminTags) -> bool {
56 if t.admin_level.is_none() && t.boundary.is_none() {
57 // Natural Earth rows have no OSM admin tagging. A PBF relation always has
58 // both, so this branch is unreachable from a PBF.
59 return true;
60 }
61 if t.boundary.unwrap_or("administrative") != "administrative" {
62 return false;
63 }
64 match t.admin_level {
65 None => true,
66 // A non-numeric admin_level is a tagging error, not level 8.
67 Some(v) => v.trim().parse::<i64>() == Ok(CITY_LEVEL),
68 }
69}
70
71/// `build_city`, plus the `"name" not in props` drop the Python applied afterwards:
72/// `None` when the boundary is unnamed, since an unnamed border is useless for both
73/// the mask and the labels.
74pub fn feature<'a>(t: &AdminTags<'a>, geometry: Geometry, relation_id: i64) -> Option<Feature<'a>> {
75 let name = first([t.name_en_tag, t.name])?;
76 // No fallback to plain `name` -- see the module docs.
77 let name_en = first([t.name_en_tag]);
78
79 let mut props: Vec<(&'a str, Value)> =
80 vec![("admin_level", Value::num(CITY_LEVEL)), ("name", Value::str(name))];
81 if let Some(v) = name_en {
82 props.push(("name_en", Value::str(v)));
83 }
84 props.push(("osm_id", osm_ref("relation", relation_id)));
85 Some(Feature { geometry, props })
86}
87
88#[cfg(test)]
89mod tests {
90 use super::*;
91
92 fn city<'a>(name: Option<&'a str>, name_en: Option<&'a str>) -> AdminTags<'a> {
93 AdminTags {
94 boundary: Some("administrative"),
95 admin_level: Some("8"),
96 name,
97 name_en_tag: name_en,
98 type_: Some("boundary"),
99 }
100 }
101
102 fn poly() -> Geometry {
103 Geometry::Polygon(vec![vec![(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (0.0, 0.0)]])
104 }
105
106 fn props_of(t: &AdminTags) -> Vec<(String, String)> {
107 feature(t, poly(), 1)
108 .expect("a named city")
109 .props
110 .iter()
111 .map(|(k, v)| {
112 let rendered = match v {
113 Value::Str(s) => String::from_utf8_lossy(s).to_string(),
114 Value::Raw(r) => r.clone(),
115 };
116 (k.to_string(), rendered)
117 })
118 .collect()
119 }
120
121 /// `scripts/maps/test/fixtures/admin_city_sample.geojsonseq` holds San
122 /// Francisco and Oakland at `admin_level=8`, plus a county at `admin_level=6`
123 /// that must be dropped.
124 #[test]
125 fn only_admin_level_8_is_kept() {
126 assert!(is_city(&city(Some("San Francisco"), None)));
127 assert!(is_city(&city(Some("Oakland"), None)));
128 let county = AdminTags { admin_level: Some("6"), ..city(Some("Alameda County"), None) };
129 assert!(!is_city(&county), "a county is not a city");
130 }
131
132 #[test]
133 fn admin_level_is_emitted_as_the_number_8() {
134 let p = props_of(&city(Some("Oakland"), None));
135 assert_eq!(p[0], ("admin_level".to_string(), "8".to_string()));
136 // A number, not a string: the app's mask code reads it as one.
137 match &feature(&city(Some("Oakland"), None), poly(), 1).unwrap().props[0].1 {
138 Value::Raw(r) => assert_eq!(r, "8"),
139 _ => panic!("admin_level must be a JSON number"),
140 }
141 }
142
143 #[test]
144 fn name_prefers_the_english_tag_then_falls_back() {
145 // name:en wins.
146 let p = props_of(&city(Some("Ciudad de México"), Some("Mexico City")));
147 assert_eq!(p[1].1, "Mexico City");
148 // Only `name`: that is the name.
149 let p = props_of(&city(Some("Oakland"), None));
150 assert_eq!(p[1].1, "Oakland");
151 }
152
153 #[test]
154 fn name_en_has_no_fallback_to_plain_name() {
155 // The city level's one asymmetry, and the trap: a region tagged only `name`
156 // gets a `name_en` too, a city does not. Adding the fallback would be a
157 // silent change to what the layer contains.
158 let keys: Vec<String> =
159 props_of(&city(Some("Oakland"), None)).into_iter().map(|(k, _)| k).collect();
160 assert_eq!(keys, ["admin_level", "name", "osm_id"]);
161 assert!(!keys.contains(&"name_en".to_string()));
162
163 // With name:en, both appear.
164 let keys: Vec<String> = props_of(&city(Some("Ciudad de México"), Some("Mexico City")))
165 .into_iter()
166 .map(|(k, _)| k)
167 .collect();
168 assert_eq!(keys, ["admin_level", "name", "name_en", "osm_id"]);
169 }
170
171 #[test]
172 fn an_unnamed_boundary_is_dropped() {
173 assert!(feature(&city(None, None), poly(), 1).is_none());
174 assert!(feature(&city(Some(""), None), poly(), 1).is_none());
175 // An empty name:en falls through to `name`.
176 let f = feature(&city(Some("Oakland"), Some("")), poly(), 1).unwrap();
177 assert_eq!(f.props.len(), 3, "name from `name`, and no name_en");
178 }
179
180 #[test]
181 fn a_non_administrative_boundary_is_rejected() {
182 for b in ["postal_code", "political", "maritime"] {
183 let t = AdminTags { boundary: Some(b), ..city(Some("X"), None) };
184 assert!(!is_city(&t), "boundary={b}");
185 }
186 // An absent boundary key defaults to administrative.
187 let t = AdminTags { boundary: None, ..city(Some("X"), None) };
188 assert!(is_city(&t));
189 }
190
191 #[test]
192 fn a_malformed_admin_level_is_not_level_eight() {
193 for v in ["", "eight", "8a", "8.0", "-8"] {
194 let t = AdminTags { admin_level: Some(v), ..city(Some("X"), None) };
195 assert!(!is_city(&t), "admin_level={v:?}");
196 }
197 // Whitespace around a good value is tolerated.
198 let t = AdminTags { admin_level: Some(" 8 "), ..city(Some("X"), None) };
199 assert!(is_city(&t));
200 }
201
202 #[test]
203 fn osm_id_is_the_relation_form() {
204 let p = props_of(&city(Some("Oakland"), None));
205 assert_eq!(p.last().unwrap(), &("osm_id".to_string(), "relation/1".to_string()));
206 }
207
208 #[test]
209 fn the_pbf_filter_covers_what_the_level_test_accepts() {
210 let select = crate::select::Select::parse(&FILTERS).unwrap();
211 let t = city(Some("Oakland"), None);
212 assert!(is_city(&t));
213 assert!(select.matches(|k| if k == "boundary" { t.boundary } else { None }));
214 }
215}