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

Modern-Apps.git / scripts / maps / gtfs_ingest / src / bin / transit_shapes_extra.rs

transit_shapes_extra.rs428 lines · 19.0 KiBRaw
1//! Tests for `transit_shapes`, moved wholesale out of `transit_shapes.rs` to keep
2//! the bin under the file-size limit. Behaviour-identical: same helpers, same
3//! assertions, only the module path changed.
4
5use super::extra2::run;
6use super::*;
7use gtfs_ingest::gtfs::parse_csv;
8use gtfs_ingest::manifest::FeedSpec;
9use gtfs_ingest::rail::route_color;
10use std::path::PathBuf;
11
12#[test]
13fn only_rail_route_types_are_carried() {
14 assert_eq!(mode_of(0), Some("light_rail"));
15 assert_eq!(mode_of(1), Some("subway"));
16 assert_eq!(mode_of(2), Some("train"));
17 assert_eq!(mode_of(5), Some("tram"), "cable tram");
18 assert_eq!(mode_of(7), Some("tram"), "funicular");
19 assert_eq!(mode_of(12), Some("monorail"));
20 assert_eq!(mode_of(3), None, "a bus is not rail");
21 assert_eq!(mode_of(4), None, "nor a ferry");
22 assert_eq!(mode_of(11), None, "nor a trolleybus");
23 // The extended ranges European feeds publish instead of the basic set.
24 assert_eq!(mode_of(109), Some("train"), "suburban railway");
25 assert_eq!(mode_of(117), Some("train"));
26 assert_eq!(mode_of(403), Some("subway"), "metro");
27 assert_eq!(mode_of(405), Some("monorail"));
28 assert_eq!(mode_of(906), Some("tram"));
29 assert_eq!(mode_of(700), None, "bus service");
30 assert_eq!(mode_of(1200), None, "ferry service");
31}
32
33#[test]
34fn a_route_colour_is_bare_hex_and_never_zero() {
35 assert_eq!(route_color("E4002B"), Some(0xE4002B));
36 assert_eq!(route_color(" e4002b "), Some(0xE4002B), "trimmed, case-insensitive");
37 assert_eq!(route_color("#E4002B"), Some(0xE4002B), "a stray hash is tolerated");
38 assert_eq!(route_color(""), None, "absent");
39 assert_eq!(route_color("red"), None, "a name is not a colour");
40 assert_eq!(route_color("F00"), None, "GTFS has no short form");
41 assert_eq!(route_color("GGGGGG"), None, "not hex");
42 // Black is the one legal value that cannot be put on the wire.
43 assert_eq!(route_color("000000"), None);
44}
45
46/// The fallback table is the mode vocabulary, and none of it may be zero:
47/// `Sink::push_transit` refuses a zero colour outright.
48#[test]
49fn every_mode_has_a_nonzero_fallback() {
50 for mode in ["subway", "light_rail", "tram", "train", "monorail"] {
51 assert_ne!(fallback_color(mode), 0, "{mode}");
52 }
53}
54
55#[test]
56fn one_line_per_distinct_shape_not_per_trip() {
57 let routes = parse_csv(
58 "route_id,route_short_name,route_type,route_color\n\
59 SUB,N,1,0054A5\n\
60 BUS,38,3,FFFFFF\n",
61 );
62 let rail = rail_routes(&routes);
63 assert_eq!(rail.len(), 1, "the bus route is dropped");
64 // Four trips over two shapes, plus a bus trip and a trip with no shape.
65 let trips = parse_csv(
66 "route_id,trip_id,shape_id\n\
67 SUB,T1,OUTBOUND\n\
68 SUB,T2,OUTBOUND\n\
69 SUB,T3,INBOUND\n\
70 SUB,T4,INBOUND\n\
71 SUB,T5,\n\
72 BUS,T6,BUSSHAPE\n",
73 );
74 let by_route = shape_ids_by_route(&trips, &rail);
75 assert_eq!(by_route.len(), 1);
76 assert_eq!(
77 by_route["SUB"].iter().cloned().collect::<Vec<String>>(),
78 vec!["INBOUND".to_string(), "OUTBOUND".to_string()],
79 "two distinct shapes for four trips",
80 );
81}
82
83/// The dedup key. Two feeds tracing the same alignment must collapse; two
84/// different alignments must not.
85#[test]
86fn the_polyline_hash_collapses_only_the_same_alignment() {
87 let line: Vec<(i32, i32)> =
88 vec![(37_700_000, -122_400_000), (37_705_000, -122_390_000), (37_710_000, -122_400_000)];
89 assert_eq!(polyline_hash(&line), polyline_hash(&line));
90 // A sub-0.1 m difference in the last digit is the same alignment.
91 let jittered: Vec<(i32, i32)> =
92 vec![(37_700_003, -122_400_000), (37_705_001, -122_390_000), (37_710_000, -122_400_000)];
93 assert_eq!(polyline_hash(&jittered), polyline_hash(&line));
94 // A real difference is not.
95 let elsewhere: Vec<(i32, i32)> =
96 vec![(37_700_000, -122_400_000), (37_705_000, -122_390_000), (37_800_000, -122_400_000)];
97 assert_ne!(polyline_hash(&elsewhere), polyline_hash(&line));
98 // And neither is the same points in the other direction: this pass is exact
99 // after rounding, and the near-match that collapses a route's two directions
100 // is `bundle::same_line`, one layer up.
101 let reversed: Vec<(i32, i32)> = line.iter().rev().copied().collect();
102 assert_ne!(polyline_hash(&reversed), polyline_hash(&line));
103}
104
105/// End to end over two feeds that share one line, which is the case cross-feed
106/// dedup exists for: Transitous ships a merged regional feed *and* its member
107/// agencies, so one alignment is published twice.
108#[test]
109fn two_feeds_sharing_an_alignment_emit_it_once() {
110 let root = std::env::temp_dir().join(format!("gtfs_shapes_{}", std::process::id()));
111 let _ = std::fs::remove_dir_all(&root);
112
113 // `shared` is byte-identical in both feeds; each feed also has one of its
114 // own. The second feed's copy of the shared route is uncoloured, so if the
115 // wrong one survived the colour would change.
116 let write_feed = |tag: &str, color: &str, own: &str| -> PathBuf {
117 let dir = root.join(tag);
118 std::fs::create_dir_all(&dir).unwrap();
119 let w = |file: &str, body: String| std::fs::write(dir.join(file), body).unwrap();
120 w(
121 "routes.txt",
122 format!(
123 "route_id,route_short_name,route_type,route_color\n\
124 SHARED,S,1,{color}\n\
125 OWN,O,0,00FF00\n\
126 BUS,B,3,123456\n"
127 ),
128 );
129 w(
130 "trips.txt",
131 "route_id,trip_id,shape_id\n\
132 SHARED,T1,SH_SHARED\n\
133 SHARED,T2,SH_SHARED\n\
134 OWN,T3,SH_OWN\n\
135 BUS,T4,SH_BUS\n"
136 .to_string(),
137 );
138 w(
139 "shapes.txt",
140 format!(
141 "shape_id,shape_pt_lat,shape_pt_lon,shape_pt_sequence\n\
142 SH_SHARED,37.700,-122.400,1\n\
143 SH_SHARED,37.710,-122.390,2\n\
144 SH_OWN,{own},-122.300,1\n\
145 SH_OWN,{own},-122.290,2\n\
146 SH_BUS,37.600,-122.500,1\n\
147 SH_BUS,37.610,-122.490,2\n"
148 ),
149 );
150 dir
151 };
152
153 let specs: Vec<FeedSpec> = vec![
154 ("a".to_string(), write_feed("a", "0054A5", "37.800"), String::new()),
155 // No colour on `b`'s copy of SHARED, so `a`'s must be the one kept.
156 ("b".to_string(), write_feed("b", "", "37.900"), String::new()),
157 ];
158
159 let out = root.join("routes.geojsonseq");
160 run(&out, &specs).unwrap();
161 let text = std::fs::read_to_string(&out).unwrap();
162 let emitted: Vec<&str> = text.lines().collect();
163
164 assert_eq!(emitted.len(), 3, "one shared line plus one per feed: {text}");
165 assert_eq!(
166 text.matches("\"mode\":\"subway\"").count(),
167 1,
168 "the shared alignment must dedup to one feature: {text}"
169 );
170 assert!(text.contains("\"color\":\"0054A5\""), "the first feed's colour wins: {text}");
171 assert_eq!(text.matches("\"mode\":\"light_rail\"").count(), 2, "one per feed: {text}");
172 assert!(!text.contains("122.5"), "the bus shape must not be emitted: {text}");
173 // Nothing on the wire may carry colour zero, and the uncoloured route took
174 // its mode's fallback rather than black.
175 assert!(!text.contains("\"color\":\"000000\""), "{text}");
176 // Byte-identical between runs.
177 let again = root.join("routes.again.geojsonseq");
178 run(&again, &specs).unwrap();
179 assert_eq!(std::fs::read(&out).unwrap(), std::fs::read(&again).unwrap());
180
181 let _ = std::fs::remove_dir_all(&root);
182}
183
184/// A route's own two directions draw as one line; its branch draws only where it
185/// branches. THE case: a corridor of six services drew twelve lines before this.
186#[test]
187fn a_routes_two_directions_draw_as_one_line() {
188 let root = std::env::temp_dir().join(format!("gtfs_shapes_collapse_{}", std::process::id()));
189 let _ = std::fs::remove_dir_all(&root);
190 std::fs::create_dir_all(&root).unwrap();
191 let w = |file: &str, body: &str| std::fs::write(root.join(file), body).unwrap();
192 w("routes.txt", "route_id,route_short_name,route_type,route_color\nN,N,0,00985F\n");
193 w("trips.txt", "route_id,trip_id,shape_id\nN,T1,OUT\nN,T2,BACK\nN,T3,BRANCH\n");
194 // OUT runs 5.5 km north; BACK is the other track, 9 m west, run the other way;
195 // BRANCH follows OUT for 2.7 km and then strikes east for 4 km.
196 w(
197 "shapes.txt",
198 "shape_id,shape_pt_lat,shape_pt_lon,shape_pt_sequence\n\
199 OUT,37.7000,-122.4000,1\n\
200 OUT,37.7250,-122.4000,2\n\
201 OUT,37.7500,-122.4000,3\n\
202 BACK,37.7500,-122.40010,1\n\
203 BACK,37.7250,-122.40010,2\n\
204 BACK,37.7000,-122.40010,3\n\
205 BRANCH,37.7000,-122.4000,1\n\
206 BRANCH,37.7250,-122.4000,2\n\
207 BRANCH,37.7250,-122.3550,3\n",
208 );
209
210 let feed = read_feed(&("solo".to_string(), root.clone(), String::new())).unwrap();
211 assert_eq!(feed.shapes_read, 3, "every shape reaches the cross-feed pass whole");
212
213 let out = root.join("routes.geojsonseq");
214 run(&out, &[("solo".to_string(), root.clone(), String::new())]).unwrap();
215 let text = std::fs::read_to_string(&out).unwrap();
216 let emitted: Vec<&str> = text.lines().collect();
217 assert_eq!(emitted.len(), 2, "the trunk once, plus the branch's own leg: {text}");
218 // Nothing of one colour may be parallel to itself, so the second direction is gone
219 // and the branch kept only what it added.
220 assert_eq!(text.matches("\"lanes\":1").count(), 2, "one service, no fan: {text}",);
221 assert!(emitted.iter().any(|l| l.contains("-122.355")), "the branch's leg: {text}");
222
223 let _ = std::fs::remove_dir_all(&root);
224}
225
226/// Two services over one track fan out either side of it, and a third route
227/// running elsewhere stays on its own alignment.
228#[test]
229fn routes_sharing_a_corridor_take_lanes_either_side_of_it() {
230 let root = std::env::temp_dir().join(format!("gtfs_shapes_spread_{}", std::process::id()));
231 let _ = std::fs::remove_dir_all(&root);
232 std::fs::create_dir_all(&root).unwrap();
233 let w = |file: &str, body: &str| std::fs::write(root.join(file), body).unwrap();
234 w(
235 "routes.txt",
236 "route_id,route_short_name,route_type,route_color\n\
237 A,A,1,0000FF\n\
238 B,B,1,FF0000\n\
239 C,C,1,00FF00\n",
240 );
241 w("trips.txt", "route_id,trip_id,shape_id\nA,T1,SA\nB,T2,SB\nC,T3,SC\n");
242 // SA and SB are one track 9 m apart; SC is a kilometre east.
243 let mut shapes = String::from("shape_id,shape_pt_lat,shape_pt_lon,shape_pt_sequence\n");
244 for i in 0..21 {
245 let lat = 37.7 + i as f64 * 0.0005;
246 shapes.push_str(&format!("SA,{lat:.4},-122.40000,{}\n", i + 1));
247 shapes.push_str(&format!("SB,{lat:.4},-122.40010,{}\n", i + 1));
248 shapes.push_str(&format!("SC,{lat:.4},-122.38000,{}\n", i + 1));
249 }
250 w("shapes.txt", &shapes);
251
252 let out = root.join("routes.geojsonseq");
253 let specs: Vec<FeedSpec> = vec![("solo".to_string(), root.clone(), String::new())];
254 run(&out, &specs).unwrap();
255 let text = std::fs::read_to_string(&out).unwrap();
256
257 assert_eq!(text.lines().count(), 3, "{text}");
258 // The corridor reports two colours and hands out both ordinals; which side of the
259 // track each lands on is the renderer's arithmetic, not this file's.
260 assert_eq!(text.matches("\"ordinal\":0,\"lanes\":2").count(), 1, "{text}");
261 assert_eq!(text.matches("\"ordinal\":1,\"lanes\":2").count(), 1, "{text}");
262 // And the route with the corridor to itself is not moved off its alignment.
263 assert_eq!(text.matches("\"ordinal\":0,\"lanes\":1").count(), 1, "{text}");
264
265 // Byte-identical between runs, lanes included.
266 let again = root.join("routes.again.geojsonseq");
267 run(&again, &specs).unwrap();
268 assert_eq!(std::fs::read(&out).unwrap(), std::fs::read(&again).unwrap());
269
270 let _ = std::fs::remove_dir_all(&root);
271}
272
273/// The cross-feed pass the exact hash cannot do. Transitous and 511-style regional
274/// feeds republish their member agencies' lines **re-surveyed**, a few metres off, so
275/// the hashes differ — and every city inside such a feed would otherwise draw twice and
276/// pair each line with its own duplicate into a two-route corridor instead of joining the
277/// corridor it really shares.
278#[test]
279fn a_line_another_feed_re_surveyed_collapses_onto_the_first() {
280 let root = std::env::temp_dir().join(format!("gtfs_shapes_resurvey_{}", std::process::id()));
281 let _ = std::fs::remove_dir_all(&root);
282
283 // `city` and `regional` trace one alignment; the regional copy is shifted about 4 m
284 // east and carries an extra intermediate point, so no hash can match them. The
285 // regional feed also has a differently-coloured service over the *same* track,
286 // which must survive: that is what the corridor slots exist to draw.
287 let write_feed = |tag: &str, lon_a: &str, lon_b: &str, extra: &str| -> PathBuf {
288 let dir = root.join(tag);
289 std::fs::create_dir_all(&dir).unwrap();
290 let w = |file: &str, body: String| std::fs::write(dir.join(file), body).unwrap();
291 w(
292 "routes.txt",
293 "route_id,route_short_name,route_type,route_color\nN,N,1,0054A5\n".to_string(),
294 );
295 w("trips.txt", "route_id,trip_id,shape_id\nN,T1,SH\n".to_string());
296 w(
297 "shapes.txt",
298 format!(
299 "shape_id,shape_pt_lat,shape_pt_lon,shape_pt_sequence\n\
300 SH,37.7000,{lon_a},1\n{extra}SH,37.7100,{lon_b},3\n"
301 ),
302 );
303 dir
304 };
305 let city = write_feed("city", "-122.40000", "-122.40000", "");
306 let regional =
307 write_feed("regional", "-122.400045", "-122.400045", "SH,37.7050,-122.400045,2\n");
308 // A second service of another colour over the same track, in its own feed.
309 let other = root.join("other");
310 std::fs::create_dir_all(&other).unwrap();
311 std::fs::write(
312 other.join("routes.txt"),
313 "route_id,route_short_name,route_type,route_color\nK,K,1,E31E24\n",
314 )
315 .unwrap();
316 std::fs::write(other.join("trips.txt"), "route_id,trip_id,shape_id\nK,T1,SH\n").unwrap();
317 std::fs::write(
318 other.join("shapes.txt"),
319 "shape_id,shape_pt_lat,shape_pt_lon,shape_pt_sequence\n\
320 SH,37.7000,-122.40000,1\n\
321 SH,37.7100,-122.40000,2\n",
322 )
323 .unwrap();
324
325 let specs: Vec<FeedSpec> = vec![
326 ("city".to_string(), city, String::new()),
327 ("regional".to_string(), regional, String::new()),
328 ("other".to_string(), other, String::new()),
329 ];
330 let out = root.join("routes.geojsonseq");
331 run(&out, &specs).unwrap();
332 let text = std::fs::read_to_string(&out).unwrap();
333
334 assert_eq!(
335 text.matches("\"color\":\"0054A5\"").count(),
336 1,
337 "the re-surveyed republication must collapse onto the first: {text}",
338 );
339 assert_eq!(
340 text.matches("\"color\":\"E31E24\"").count(),
341 1,
342 "a different service over the same track must survive: {text}",
343 );
344 // And the two that survive share the track, so they fan out either side of it
345 // rather than both collapsing to one lane.
346 assert_eq!(text.matches("\"ordinal\":0,\"lanes\":2").count(), 1, "{text}");
347 assert_eq!(text.matches("\"ordinal\":1,\"lanes\":2").count(), 1, "{text}");
348
349 let _ = std::fs::remove_dir_all(&root);
350}
351
352/// A rail route whose trips name a shape the feed does not carry is reported,
353/// not silently emitted as an empty line.
354#[test]
355fn a_route_with_no_usable_shape_is_counted_and_drawn_nothing() {
356 let root = std::env::temp_dir().join(format!("gtfs_shapes_noshape_{}", std::process::id()));
357 let _ = std::fs::remove_dir_all(&root);
358 std::fs::create_dir_all(&root).unwrap();
359 let w = |file: &str, body: &str| std::fs::write(root.join(file), body).unwrap();
360 w("routes.txt", "route_id,route_short_name,route_type,route_color\nR,R,2,\n");
361 w("trips.txt", "route_id,trip_id,shape_id\nR,T1,MISSING\n");
362 // One point is not a line, so even a present shape can be unusable.
363 w("shapes.txt", "shape_id,shape_pt_lat,shape_pt_lon,shape_pt_sequence\nOTHER,37.7,-122.4,1\n");
364
365 let feed = read_feed(&("solo".to_string(), root.clone(), String::new())).unwrap();
366 assert_eq!(feed.routes_kept, 1);
367 assert_eq!(feed.routes_without_shape, 1);
368 assert!(feed.lines.is_empty());
369
370 let _ = std::fs::remove_dir_all(&root);
371}
372
373/// The cover gates resolve a window of lines speculated in parallel; a window of one line is
374/// the sequential fold exactly, and every other window must reproduce it byte for byte. The
375/// set is built to make the windows disagree if anything were stale: many routes republishing
376/// one track a few metres apart (the colour gate), uncoloured copies (the mode gate), five or
377/// more colours over one stretch (the crowd gate), short-turns, and lines long enough to take
378/// the wide per-line and sharded-add paths.
379#[test]
380fn the_speculative_window_changes_no_byte() {
381 let root = std::env::temp_dir().join(format!("gtfs_shapes_window_{}", std::process::id()));
382 let _ = std::fs::remove_dir_all(&root);
383 std::fs::create_dir_all(&root).unwrap();
384 let colours = ["0054A5", "E31E24", "00A651", "", "FFC20E", "8E44AD", "", "0054A5"];
385 let mut routes = String::from("route_id,route_short_name,route_type,route_color\n");
386 let mut trips = String::from("route_id,trip_id,shape_id\n");
387 let mut shapes = String::from("shape_id,shape_pt_lat,shape_pt_lon,shape_pt_sequence\n");
388 let mut x = 0x2545_F491_4F6C_DD1Du64;
389 let mut next = move || {
390 x ^= x << 13;
391 x ^= x >> 7;
392 x ^= x << 17;
393 x
394 };
395 for r in 0..60u64 {
396 let colour = colours[(next() % colours.len() as u64) as usize];
397 let route_type = [1, 1, 0, 2][(next() % 4) as usize];
398 routes.push_str(&format!("R{r},L{},{route_type},{colour}\n", r % 9));
399 trips.push_str(&format!("R{r},T{r},S{r}\n"));
400 // Up to ~1.1 degrees (~120 km) of one north-south trunk, starting anywhere along its
401 // first half, offset sideways by 0-40 m, with a kink partway.
402 let start = 37.0 + (next() % 500) as f64 * 1e-3;
403 let length = [0.02, 0.1, 0.5, 1.1][(next() % 4) as usize];
404 let lon = -122.0 + (next() % 40) as f64 * 1e-5;
405 let kink = (next() % 3) as f64 * 1e-4;
406 let points = [(start, lon), (start + length * 0.4, lon + kink), (start + length, lon)];
407 for (seq, (lat, lon)) in points.iter().enumerate() {
408 shapes.push_str(&format!("S{r},{lat:.7},{lon:.7},{}\n", seq + 1));
409 }
410 }
411 std::fs::write(root.join("routes.txt"), routes).unwrap();
412 std::fs::write(root.join("trips.txt"), trips).unwrap();
413 std::fs::write(root.join("shapes.txt"), shapes).unwrap();
414 let specs: Vec<FeedSpec> = vec![("trunk".to_string(), root.clone(), String::new())];
415
416 let render = |window: usize| -> String {
417 let out = root.join(format!("w{window}.geojsonseq"));
418 super::extra2::run_windowed(&out, super::extra2::Inputs::Feeds(&specs), None, window)
419 .unwrap();
420 std::fs::read_to_string(&out).unwrap()
421 };
422 let sequential = render(1);
423 assert!(sequential.lines().count() > 3, "the set must keep several lines: {sequential}");
424 for window in [2, 3, 7, 16, 64] {
425 assert_eq!(render(window), sequential, "window {window}");
426 }
427 let _ = std::fs::remove_dir_all(&root);
428}