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

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

transit_lines.rs392 lines · 14.9 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 { type_: Some("route"), route: Some(route), ..Default::default() }
169 }
170
171 /// The eight emitted features of
172 /// `scripts/maps/test/fixtures/transit_lines_sample.geojsonseq`: six railway
173 /// ways and two route relations. The fixture's platform way, highway way, bus
174 /// route relation and station point are all dropped.
175 fn fixture_kinds() -> Vec<&'static str> {
176 [
177 way("subway"), // way/5001 Market St Subway
178 way("light_rail"), // way/5002
179 way("tram"), // way/5003
180 way("monorail"), // way/5004
181 way("rail"), // way/5005
182 way("narrow_gauge"), // way/5006 -> rail
183 relation("subway"), // relation 9001 Red Line
184 relation("tram"), // relation 9002 N Judah
185 ]
186 .iter()
187 .filter_map(classify)
188 .collect()
189 }
190
191 fn count(kinds: &[&str], want: &str) -> usize {
192 kinds.iter().filter(|k| **k == want).count()
193 }
194
195 #[test]
196 fn emits_eight_features() {
197 assert_eq!(fixture_kinds().len(), 8);
198 }
199
200 #[test]
201 fn a_way_and_a_relation_can_both_produce_the_same_kind() {
202 let kinds = fixture_kinds();
203 assert_eq!(count(&kinds, "subway"), 2, "railway=subway and route=subway");
204 assert_eq!(count(&kinds, "tram"), 2, "railway=tram and route=tram");
205 }
206
207 #[test]
208 fn light_rail_and_monorail_come_through() {
209 let kinds = fixture_kinds();
210 assert!(kinds.contains(&"light_rail"));
211 assert!(kinds.contains(&"monorail"));
212 }
213
214 #[test]
215 fn narrow_gauge_folds_into_rail() {
216 // Two rail features from one railway=rail and one railway=narrow_gauge.
217 assert_eq!(count(&fixture_kinds(), "rail"), 2);
218 assert_eq!(classify(&way("narrow_gauge")), Some("rail"));
219 }
220
221 #[test]
222 fn platforms_highways_and_bus_routes_are_dropped() {
223 assert_eq!(classify(&way("platform")), None);
224 assert_eq!(classify(&TransitTags::default()), None);
225 // A highway way carries no railway tag at all.
226 assert_eq!(classify(&TransitTags { route: None, ..Default::default() }), None);
227 // route=bus is in neither map: this layer is the rail-like modes.
228 assert_eq!(classify(&relation("bus")), None);
229 assert_eq!(classify(&relation("ferry")), None);
230 }
231
232 #[test]
233 fn train_is_only_reachable_from_a_relation_and_rail_only_from_a_way() {
234 assert_eq!(classify(&relation("train")), Some("train"));
235 // There is no railway=train convention, so a way cannot make one.
236 assert_eq!(classify(&way("train")), None);
237 assert_eq!(classify(&way("rail")), Some("rail"));
238 // And route=rail is not a convention either.
239 assert_eq!(classify(&relation("rail")), None);
240 }
241
242 #[test]
243 fn railway_wins_over_route() {
244 // Track carrying a service is track.
245 let both = TransitTags {
246 railway: Some("rail"),
247 type_: Some("route"),
248 route: Some("subway"),
249 ..Default::default()
250 };
251 assert_eq!(classify(&both), Some("rail"));
252 }
253
254 #[test]
255 fn an_absent_type_is_accepted_but_a_wrong_one_is_not() {
256 // The Python tested `type in (None, "route")`.
257 assert_eq!(
258 classify(&TransitTags { route: Some("subway"), ..Default::default() }),
259 Some("subway")
260 );
261 assert_eq!(
262 classify(&TransitTags {
263 type_: Some("multipolygon"),
264 route: Some("subway"),
265 ..Default::default()
266 }),
267 None
268 );
269 }
270
271 #[test]
272 fn the_relations_colour_and_ref_come_through() {
273 // The Red Line fixture: colour "#DA291C", ref "Red", kind subway. These
274 // arrived via GDAL's HSTORE before; now they are just tags.
275 let t = TransitTags {
276 type_: Some("route"),
277 route: Some("subway"),
278 name: Some("Red Line"),
279 reference: Some("Red"),
280 colour: Some("#DA291C"),
281 ..Default::default()
282 };
283 assert_eq!(classify(&t), Some("subway"));
284 let f = feature("subway", &t, Geometry::MultiLineString(vec![]), "relation", 9001);
285 let keys: Vec<&str> = f.props.iter().map(|(k, _)| *k).collect();
286 assert_eq!(keys, ["kind", "name", "ref", "colour", "osm_id"]);
287 match &f.props[3].1 {
288 Value::Str(s) => assert_eq!(s, b"#DA291C"),
289 _ => panic!("colour must be a string"),
290 }
291 }
292
293 #[test]
294 fn the_american_colour_spelling_is_accepted() {
295 // The N Judah fixture uses `color`.
296 let t = TransitTags { color: Some("blue"), ..Default::default() };
297 assert_eq!(colour(&t), Some("blue"));
298 // British wins when both are set.
299 let t = TransitTags { colour: Some("#DA291C"), color: Some("blue"), ..Default::default() };
300 assert_eq!(colour(&t), Some("#DA291C"));
301 // A falsey British value falls through to the American one.
302 let t = TransitTags { colour: Some("no"), color: Some("blue"), ..Default::default() };
303 assert_eq!(colour(&t), Some("blue"));
304 assert_eq!(colour(&TransitTags::default()), None);
305 }
306
307 #[test]
308 fn a_ways_ref_comes_through_too() {
309 // The fixture has a way with ref "F".
310 let t = TransitTags { railway: Some("tram"), reference: Some("F"), ..Default::default() };
311 let f = feature("tram", &t, Geometry::LineString(vec![]), "way", 5003);
312 assert!(f
313 .props
314 .iter()
315 .any(|(k, v)| *k == "ref" && matches!(v, Value::Str(s) if s == b"F")));
316 }
317
318 #[test]
319 fn osm_id_uses_the_element_kind_for_both_sources() {
320 // The one deliberate schema change: GDAL emitted a bare number for
321 // relations, so the two sources disagreed. See the module docs.
322 let t = way("rail");
323 let f = feature("rail", &t, Geometry::LineString(vec![]), "way", 5005);
324 match &f.props.last().unwrap().1 {
325 Value::Str(s) => assert_eq!(s, b"way/5005"),
326 _ => panic!(),
327 }
328 let t = relation("train");
329 let f = feature("train", &t, Geometry::MultiLineString(vec![]), "relation", 9003);
330 match &f.props.last().unwrap().1 {
331 Value::Str(s) => assert_eq!(s, b"relation/9003"),
332 _ => panic!(),
333 }
334 }
335
336 #[test]
337 fn falsey_names_and_refs_are_dropped() {
338 for v in ["", "no", "false", "0"] {
339 let t = TransitTags {
340 railway: Some("rail"),
341 name: Some(v),
342 reference: Some(v),
343 colour: Some(v),
344 ..Default::default()
345 };
346 let f = feature("rail", &t, Geometry::LineString(vec![]), "way", 1);
347 assert_eq!(f.props.len(), 2, "kind + osm_id only, but {v:?} survived");
348 }
349 }
350
351 #[test]
352 fn only_boarding_infrastructure_roles_are_excluded_from_the_path() {
353 // The PTv2 role table. `platform*` and `stop*` describe where passengers
354 // board; a platform is usually a closed way, and including it drew a box
355 // around every station.
356 for role in [
357 "platform",
358 "platform_entry_only",
359 "platform_exit_only",
360 "stop",
361 "stop_entry_only",
362 "stop_exit_only",
363 ] {
364 assert!(!member_is_path(role.as_bytes()), "{role} is not the path");
365 }
366 // Unroled members are the path, and a direction is still the path.
367 for role in ["", "forward", "backward"] {
368 assert!(member_is_path(role.as_bytes()), "{role} is the path");
369 }
370 }
371
372 #[test]
373 fn the_pbf_filters_cover_both_halves_of_the_layer() {
374 let ways = crate::select::Select::parse(&WAY_FILTERS).unwrap();
375 for (_, kind) in RAILWAY_KIND {
376 let value = RAILWAY_KIND.iter().find(|(_, k)| *k == kind).unwrap().0;
377 assert!(
378 ways.matches(|k| if k == "railway" { Some(value) } else { None }),
379 "railway={value} classifies but is pre-filtered out"
380 );
381 }
382 let rels = crate::select::Select::parse(&RELATION_FILTERS).unwrap();
383 for (value, _) in ROUTE_KIND {
384 assert!(
385 rels.matches(|k| if k == "route" { Some(value) } else { None }),
386 "route={value} classifies but is pre-filtered out"
387 );
388 }
389 // And the filters do not let bus through.
390 assert!(!rels.matches(|k| if k == "route" { Some("bus") } else { None }));
391 }
392}