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

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

transit_lines.rs409 lines · 15.1 KiBRaw
1//! The `transit_lines` layer: OSM rail/subway/tram/… geometry for the app's
2//! transit-line highlight.
3//!
4//! A port of `normalize_transit_lines.py`. Two sources feed it, and each can only
5//! produce some of the kinds:
6//!
7//! * **railway ways** -- `railway=rail|subway|light_rail|tram|monorail|narrow_gauge`
8//! * **route relations** -- `type=route` with `route=subway|tram|light_rail|train|monorail`
9//!
10//! The asymmetry is deliberate and encoded in the two maps. `rail` is only
11//! reachable from a way, because `route=rail` is not a tagging convention; `train`
12//! is only reachable from a relation, because that is how national rail services
13//! are tagged; `narrow_gauge` folds into `rail`; and `route=bus` is in neither map,
14//! so bus routes are dropped -- this layer is for the rail-like modes the highlight
15//! styles.
16//!
17//! `railway` wins over `route`: a way carrying both is a physical piece of track,
18//! and the route is a service running over it.
19//!
20//! ## The HSTORE parsing is gone, and why that is not a regression
21//!
22//! The Python spent a third of its length on `parse_hstore` and `merged_tags`,
23//! unpacking a `"route"=>"subway","colour"=>"#DA291C"` string back into tags. That
24//! existed for exactly one reason: relation geometry came from
25//! `ogr2ogr -f GeoJSONSeq … multilinestrings`, and GDAL's OSM driver exposes a few
26//! named fields and folds every other tag into an `other_tags` HSTORE. Reading
27//! relations out of the PBF directly gives their tags as tags, so there is nothing
28//! to unpack. The GDAL dependency goes with it.
29//!
30//! ## Relation geometry is an unordered MultiLineString
31//!
32//! A route relation's member ways are emitted as separate parts, in member order,
33//! with no attempt to stitch them into a single continuous line. The layer's
34//! contract allows it -- `MultiLineString` is what the Python emitted too, since
35//! that is what GDAL produced -- and it is the right answer for a route: branches,
36//! loops and split platforms mean the ways often do not form one path at all.
37//!
38//! ## One deliberate schema change
39//!
40//! `osm_id` for a relation is now `relation/9001`, where the GDAL path emitted a
41//! bare `9001` (its `osm_id` field) while ways came through as `way/5001`. The two
42//! sources disagreeing was an artefact of the toolchain, not a decision, so the
43//! port uses the `<kind>/<id>` form throughout. The differential harness will show
44//! this as a property difference on relation features; that is expected.
45
46use crate::geojson::{osm_ref, Feature, Geometry, Value};
47
48/// `railway=<value>` on a way -> the layer's `kind`.
49pub const RAILWAY_KIND: [(&str, &str); 6] = [
50 ("rail", "rail"),
51 ("subway", "subway"),
52 ("light_rail", "light_rail"),
53 ("tram", "tram"),
54 ("monorail", "monorail"),
55 // Folded in: the highlight styles gauge-agnostic heavy rail the same way.
56 ("narrow_gauge", "rail"),
57];
58
59/// `route=<value>` on a `type=route` relation -> the layer's `kind`.
60pub const ROUTE_KIND: [(&str, &str); 5] = [
61 ("subway", "subway"),
62 ("tram", "tram"),
63 ("light_rail", "light_rail"),
64 ("train", "train"),
65 ("monorail", "monorail"),
66];
67
68/// The `osmium tags-filter` expression for the way half of the layer.
69pub const WAY_FILTERS: [&str; 1] = ["railway=rail,subway,light_rail,tram,monorail,narrow_gauge"];
70
71/// The `osmium tags-filter` expression for the relation half.
72pub const RELATION_FILTERS: [&str; 1] = ["route=subway,tram,light_rail,train,monorail"];
73
74#[derive(Debug, Default, Clone, Copy)]
75pub struct TransitTags<'a> {
76 pub railway: Option<&'a str>,
77 /// The relation's `type`. Absent is accepted, matching the Python's
78 /// `tags.get("type") in (None, "route")`.
79 pub type_: Option<&'a str>,
80 pub route: Option<&'a str>,
81 pub name: Option<&'a str>,
82 pub reference: Option<&'a str>,
83 pub colour: Option<&'a str>,
84 /// The American spelling, accepted as a fallback.
85 pub color: Option<&'a str>,
86}
87
88fn lookup(map: &[(&str, &'static str)], v: Option<&str>) -> Option<&'static str> {
89 let v = v?;
90 map.iter().find(|(k, _)| *k == v).map(|(_, kind)| *kind)
91}
92
93pub fn railway_kind(v: Option<&str>) -> Option<&'static str> {
94 lookup(&RAILWAY_KIND, v)
95}
96
97pub fn route_kind(v: Option<&str>) -> Option<&'static str> {
98 lookup(&ROUTE_KIND, v)
99}
100
101pub fn classify(t: &TransitTags) -> Option<&'static str> {
102 // A way carrying both tags is track, not a service.
103 if let Some(kind) = railway_kind(t.railway) {
104 return Some(kind);
105 }
106 if matches!(t.type_, None | Some("route")) {
107 return route_kind(t.route);
108 }
109 None
110}
111
112/// `normalize_transit_lines.py`'s `_truthy`.
113pub fn truthy(v: Option<&str>) -> bool {
114 !matches!(v, None | Some("") | Some("no") | Some("false") | Some("0"))
115}
116
117/// Whether a route relation's way member with this `role` is part of the line.
118///
119/// A PTv2 route relation carries more than its path: `platform` and `stop` members
120/// describe where passengers board, and a platform is very often a **closed way**.
121/// Including those drew every platform's outline as if it were track, which is what
122/// put station-shaped boxes all over the transit layer.
123///
124/// Unroled members are the path, and `forward`/`backward` are as much of it — only
125/// boarding infrastructure is excluded, by prefix, because PTv2 spells it
126/// `platform_entry_only`, `stop_exit_only` and so on.
127pub fn member_is_path(role: &[u8]) -> bool {
128 !role.starts_with(b"platform") && !role.starts_with(b"stop")
129}
130
131/// British spelling first, then American.
132pub fn colour<'a>(t: &TransitTags<'a>) -> Option<&'a str> {
133 [t.colour, t.color].into_iter().find(|v| truthy(*v)).flatten()
134}
135
136/// Build the emitted feature. Property order matches the Python's insertion order:
137/// `kind`, `name`, `ref`, `colour`, `osm_id`.
138pub fn feature<'a>(
139 kind: &'a str,
140 t: &TransitTags<'a>,
141 geometry: Geometry,
142 element: &'a str,
143 id: i64,
144) -> Feature<'a> {
145 let mut props: Vec<(&'a str, Value)> = vec![("kind", Value::str(kind))];
146 if truthy(t.name) {
147 props.push(("name", Value::str(t.name.unwrap())));
148 }
149 if truthy(t.reference) {
150 props.push(("ref", Value::str(t.reference.unwrap())));
151 }
152 if let Some(c) = colour(t) {
153 props.push(("colour", Value::str(c)));
154 }
155 props.push(("osm_id", osm_ref(element, id)));
156 Feature { geometry, props }
157}
158
159#[cfg(test)]
160mod tests {
161 use super::*;
162
163 fn way(railway: &str) -> TransitTags<'_> {
164 TransitTags { railway: Some(railway), ..Default::default() }
165 }
166
167 fn relation<'a>(route: &'a str) -> TransitTags<'a> {
168 TransitTags {
169 type_: Some("route"),
170 route: Some(route),
171 ..Default::default()
172 }
173 }
174
175 /// The eight emitted features of
176 /// `scripts/maps/test/fixtures/transit_lines_sample.geojsonseq`: six railway
177 /// ways and two route relations. The fixture's platform way, highway way, bus
178 /// route relation and station point are all dropped.
179 fn fixture_kinds() -> Vec<&'static str> {
180 [
181 way("subway"), // way/5001 Market St Subway
182 way("light_rail"), // way/5002
183 way("tram"), // way/5003
184 way("monorail"), // way/5004
185 way("rail"), // way/5005
186 way("narrow_gauge"), // way/5006 -> rail
187 relation("subway"), // relation 9001 Red Line
188 relation("tram"), // relation 9002 N Judah
189 ]
190 .iter()
191 .filter_map(classify)
192 .collect()
193 }
194
195 fn count(kinds: &[&str], want: &str) -> usize {
196 kinds.iter().filter(|k| **k == want).count()
197 }
198
199 #[test]
200 fn emits_eight_features() {
201 assert_eq!(fixture_kinds().len(), 8);
202 }
203
204 #[test]
205 fn a_way_and_a_relation_can_both_produce_the_same_kind() {
206 let kinds = fixture_kinds();
207 assert_eq!(count(&kinds, "subway"), 2, "railway=subway and route=subway");
208 assert_eq!(count(&kinds, "tram"), 2, "railway=tram and route=tram");
209 }
210
211 #[test]
212 fn light_rail_and_monorail_come_through() {
213 let kinds = fixture_kinds();
214 assert!(kinds.contains(&"light_rail"));
215 assert!(kinds.contains(&"monorail"));
216 }
217
218 #[test]
219 fn narrow_gauge_folds_into_rail() {
220 // Two rail features from one railway=rail and one railway=narrow_gauge.
221 assert_eq!(count(&fixture_kinds(), "rail"), 2);
222 assert_eq!(classify(&way("narrow_gauge")), Some("rail"));
223 }
224
225 #[test]
226 fn platforms_highways_and_bus_routes_are_dropped() {
227 assert_eq!(classify(&way("platform")), None);
228 assert_eq!(classify(&TransitTags::default()), None);
229 // A highway way carries no railway tag at all.
230 assert_eq!(
231 classify(&TransitTags { route: None, ..Default::default() }),
232 None
233 );
234 // route=bus is in neither map: this layer is the rail-like modes.
235 assert_eq!(classify(&relation("bus")), None);
236 assert_eq!(classify(&relation("ferry")), None);
237 }
238
239 #[test]
240 fn train_is_only_reachable_from_a_relation_and_rail_only_from_a_way() {
241 assert_eq!(classify(&relation("train")), Some("train"));
242 // There is no railway=train convention, so a way cannot make one.
243 assert_eq!(classify(&way("train")), None);
244 assert_eq!(classify(&way("rail")), Some("rail"));
245 // And route=rail is not a convention either.
246 assert_eq!(classify(&relation("rail")), None);
247 }
248
249 #[test]
250 fn railway_wins_over_route() {
251 // Track carrying a service is track.
252 let both = TransitTags {
253 railway: Some("rail"),
254 type_: Some("route"),
255 route: Some("subway"),
256 ..Default::default()
257 };
258 assert_eq!(classify(&both), Some("rail"));
259 }
260
261 #[test]
262 fn an_absent_type_is_accepted_but_a_wrong_one_is_not() {
263 // The Python tested `type in (None, "route")`.
264 assert_eq!(
265 classify(&TransitTags { route: Some("subway"), ..Default::default() }),
266 Some("subway")
267 );
268 assert_eq!(
269 classify(&TransitTags {
270 type_: Some("multipolygon"),
271 route: Some("subway"),
272 ..Default::default()
273 }),
274 None
275 );
276 }
277
278 #[test]
279 fn the_relations_colour_and_ref_come_through() {
280 // The Red Line fixture: colour "#DA291C", ref "Red", kind subway. These
281 // arrived via GDAL's HSTORE before; now they are just tags.
282 let t = TransitTags {
283 type_: Some("route"),
284 route: Some("subway"),
285 name: Some("Red Line"),
286 reference: Some("Red"),
287 colour: Some("#DA291C"),
288 ..Default::default()
289 };
290 assert_eq!(classify(&t), Some("subway"));
291 let f = feature("subway", &t, Geometry::MultiLineString(vec![]), "relation", 9001);
292 let keys: Vec<&str> = f.props.iter().map(|(k, _)| *k).collect();
293 assert_eq!(keys, ["kind", "name", "ref", "colour", "osm_id"]);
294 match &f.props[3].1 {
295 Value::Str(s) => assert_eq!(s, b"#DA291C"),
296 _ => panic!("colour must be a string"),
297 }
298 }
299
300 #[test]
301 fn the_american_colour_spelling_is_accepted() {
302 // The N Judah fixture uses `color`.
303 let t = TransitTags { color: Some("blue"), ..Default::default() };
304 assert_eq!(colour(&t), Some("blue"));
305 // British wins when both are set.
306 let t = TransitTags {
307 colour: Some("#DA291C"),
308 color: Some("blue"),
309 ..Default::default()
310 };
311 assert_eq!(colour(&t), Some("#DA291C"));
312 // A falsey British value falls through to the American one.
313 let t = TransitTags {
314 colour: Some("no"),
315 color: Some("blue"),
316 ..Default::default()
317 };
318 assert_eq!(colour(&t), Some("blue"));
319 assert_eq!(colour(&TransitTags::default()), None);
320 }
321
322 #[test]
323 fn a_ways_ref_comes_through_too() {
324 // The fixture has a way with ref "F".
325 let t = TransitTags {
326 railway: Some("tram"),
327 reference: Some("F"),
328 ..Default::default()
329 };
330 let f = feature("tram", &t, Geometry::LineString(vec![]), "way", 5003);
331 assert!(f.props.iter().any(|(k, v)| *k == "ref"
332 && matches!(v, Value::Str(s) if s == b"F")));
333 }
334
335 #[test]
336 fn osm_id_uses_the_element_kind_for_both_sources() {
337 // The one deliberate schema change: GDAL emitted a bare number for
338 // relations, so the two sources disagreed. See the module docs.
339 let t = way("rail");
340 let f = feature("rail", &t, Geometry::LineString(vec![]), "way", 5005);
341 match &f.props.last().unwrap().1 {
342 Value::Str(s) => assert_eq!(s, b"way/5005"),
343 _ => panic!(),
344 }
345 let t = relation("train");
346 let f = feature("train", &t, Geometry::MultiLineString(vec![]), "relation", 9003);
347 match &f.props.last().unwrap().1 {
348 Value::Str(s) => assert_eq!(s, b"relation/9003"),
349 _ => panic!(),
350 }
351 }
352
353 #[test]
354 fn falsey_names_and_refs_are_dropped() {
355 for v in ["", "no", "false", "0"] {
356 let t = TransitTags {
357 railway: Some("rail"),
358 name: Some(v),
359 reference: Some(v),
360 colour: Some(v),
361 ..Default::default()
362 };
363 let f = feature("rail", &t, Geometry::LineString(vec![]), "way", 1);
364 assert_eq!(f.props.len(), 2, "kind + osm_id only, but {v:?} survived");
365 }
366 }
367
368 #[test]
369 fn only_boarding_infrastructure_roles_are_excluded_from_the_path() {
370 // The PTv2 role table. `platform*` and `stop*` describe where passengers
371 // board; a platform is usually a closed way, and including it drew a box
372 // around every station.
373 for role in [
374 "platform",
375 "platform_entry_only",
376 "platform_exit_only",
377 "stop",
378 "stop_entry_only",
379 "stop_exit_only",
380 ] {
381 assert!(!member_is_path(role.as_bytes()), "{role} is not the path");
382 }
383 // Unroled members are the path, and a direction is still the path.
384 for role in ["", "forward", "backward"] {
385 assert!(member_is_path(role.as_bytes()), "{role} is the path");
386 }
387 }
388
389 #[test]
390 fn the_pbf_filters_cover_both_halves_of_the_layer() {
391 let ways = crate::select::Select::parse(&WAY_FILTERS).unwrap();
392 for (_, kind) in RAILWAY_KIND {
393 let value = RAILWAY_KIND.iter().find(|(_, k)| *k == kind).unwrap().0;
394 assert!(
395 ways.matches(|k| if k == "railway" { Some(value) } else { None }),
396 "railway={value} classifies but is pre-filtered out"
397 );
398 }
399 let rels = crate::select::Select::parse(&RELATION_FILTERS).unwrap();
400 for (value, _) in ROUTE_KIND {
401 assert!(
402 rels.matches(|k| if k == "route" { Some(value) } else { None }),
403 "route={value} classifies but is pre-filtered out"
404 );
405 }
406 // And the filters do not let bus through.
407 assert!(!rels.matches(|k| if k == "route" { Some("bus") } else { None }));
408 }
409}