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

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

transit_shapes_extra.rs386 lines · 16.2 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::rail::route_color;
9use gtfs_ingest::manifest::FeedSpec;
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 =
189 std::env::temp_dir().join(format!("gtfs_shapes_collapse_{}", std::process::id()));
190 let _ = std::fs::remove_dir_all(&root);
191 std::fs::create_dir_all(&root).unwrap();
192 let w = |file: &str, body: &str| std::fs::write(root.join(file), body).unwrap();
193 w("routes.txt", "route_id,route_short_name,route_type,route_color\nN,N,0,00985F\n");
194 w(
195 "trips.txt",
196 "route_id,trip_id,shape_id\nN,T1,OUT\nN,T2,BACK\nN,T3,BRANCH\n",
197 );
198 // OUT runs 5.5 km north; BACK is the other track, 9 m west, run the other way;
199 // BRANCH follows OUT for 2.7 km and then strikes east for 4 km.
200 w(
201 "shapes.txt",
202 "shape_id,shape_pt_lat,shape_pt_lon,shape_pt_sequence\n\
203 OUT,37.7000,-122.4000,1\n\
204 OUT,37.7250,-122.4000,2\n\
205 OUT,37.7500,-122.4000,3\n\
206 BACK,37.7500,-122.40010,1\n\
207 BACK,37.7250,-122.40010,2\n\
208 BACK,37.7000,-122.40010,3\n\
209 BRANCH,37.7000,-122.4000,1\n\
210 BRANCH,37.7250,-122.4000,2\n\
211 BRANCH,37.7250,-122.3550,3\n",
212 );
213
214 let feed = read_feed(&("solo".to_string(), root.clone(), String::new())).unwrap();
215 assert_eq!(feed.shapes_read, 3, "every shape reaches the cross-feed pass whole");
216
217 let out = root.join("routes.geojsonseq");
218 run(&out, &vec![("solo".to_string(), root.clone(), String::new())]).unwrap();
219 let text = std::fs::read_to_string(&out).unwrap();
220 let emitted: Vec<&str> = text.lines().collect();
221 assert_eq!(emitted.len(), 2, "the trunk once, plus the branch's own leg: {text}");
222 // Nothing of one colour may be parallel to itself, so the second direction is gone
223 // and the branch kept only what it added.
224 assert_eq!(
225 text.matches("\"lanes\":1").count(),
226 2,
227 "one service, no fan: {text}",
228 );
229 assert!(emitted.iter().any(|l| l.contains("-122.355")), "the branch's leg: {text}");
230
231 let _ = std::fs::remove_dir_all(&root);
232}
233
234/// Two services over one track fan out either side of it, and a third route
235/// running elsewhere stays on its own alignment.
236#[test]
237fn routes_sharing_a_corridor_take_lanes_either_side_of_it() {
238 let root = std::env::temp_dir().join(format!("gtfs_shapes_spread_{}", std::process::id()));
239 let _ = std::fs::remove_dir_all(&root);
240 std::fs::create_dir_all(&root).unwrap();
241 let w = |file: &str, body: &str| std::fs::write(root.join(file), body).unwrap();
242 w(
243 "routes.txt",
244 "route_id,route_short_name,route_type,route_color\n\
245 A,A,1,0000FF\n\
246 B,B,1,FF0000\n\
247 C,C,1,00FF00\n",
248 );
249 w("trips.txt", "route_id,trip_id,shape_id\nA,T1,SA\nB,T2,SB\nC,T3,SC\n");
250 // SA and SB are one track 9 m apart; SC is a kilometre east.
251 let mut shapes = String::from("shape_id,shape_pt_lat,shape_pt_lon,shape_pt_sequence\n");
252 for i in 0..21 {
253 let lat = 37.7 + i as f64 * 0.0005;
254 shapes.push_str(&format!("SA,{lat:.4},-122.40000,{}\n", i + 1));
255 shapes.push_str(&format!("SB,{lat:.4},-122.40010,{}\n", i + 1));
256 shapes.push_str(&format!("SC,{lat:.4},-122.38000,{}\n", i + 1));
257 }
258 w("shapes.txt", &shapes);
259
260 let out = root.join("routes.geojsonseq");
261 let specs: Vec<FeedSpec> = vec![("solo".to_string(), root.clone(), String::new())];
262 run(&out, &specs).unwrap();
263 let text = std::fs::read_to_string(&out).unwrap();
264
265 assert_eq!(text.lines().count(), 3, "{text}");
266 // The corridor reports two colours and hands out both ordinals; which side of the
267 // track each lands on is the renderer's arithmetic, not this file's.
268 assert_eq!(text.matches("\"ordinal\":0,\"lanes\":2").count(), 1, "{text}");
269 assert_eq!(text.matches("\"ordinal\":1,\"lanes\":2").count(), 1, "{text}");
270 // And the route with the corridor to itself is not moved off its alignment.
271 assert_eq!(text.matches("\"ordinal\":0,\"lanes\":1").count(), 1, "{text}");
272
273 // Byte-identical between runs, lanes included.
274 let again = root.join("routes.again.geojsonseq");
275 run(&again, &specs).unwrap();
276 assert_eq!(std::fs::read(&out).unwrap(), std::fs::read(&again).unwrap());
277
278 let _ = std::fs::remove_dir_all(&root);
279}
280
281/// The cross-feed pass the exact hash cannot do. Transitous and 511-style regional
282/// feeds republish their member agencies' lines **re-surveyed**, a few metres off, so
283/// the hashes differ — and every city inside such a feed would otherwise draw twice and
284/// pair each line with its own duplicate into a two-route corridor instead of joining the
285/// corridor it really shares.
286#[test]
287fn a_line_another_feed_re_surveyed_collapses_onto_the_first() {
288 let root = std::env::temp_dir().join(format!("gtfs_shapes_resurvey_{}", std::process::id()));
289 let _ = std::fs::remove_dir_all(&root);
290
291 // `city` and `regional` trace one alignment; the regional copy is shifted about 4 m
292 // east and carries an extra intermediate point, so no hash can match them. The
293 // regional feed also has a differently-coloured service over the *same* track,
294 // which must survive: that is what the corridor slots exist to draw.
295 let write_feed = |tag: &str, lon_a: &str, lon_b: &str, extra: &str| -> PathBuf {
296 let dir = root.join(tag);
297 std::fs::create_dir_all(&dir).unwrap();
298 let w = |file: &str, body: String| std::fs::write(dir.join(file), body).unwrap();
299 w(
300 "routes.txt",
301 "route_id,route_short_name,route_type,route_color\nN,N,1,0054A5\n".to_string(),
302 );
303 w("trips.txt", "route_id,trip_id,shape_id\nN,T1,SH\n".to_string());
304 w(
305 "shapes.txt",
306 format!(
307 "shape_id,shape_pt_lat,shape_pt_lon,shape_pt_sequence\n\
308 SH,37.7000,{lon_a},1\n{extra}SH,37.7100,{lon_b},3\n"
309 ),
310 );
311 dir
312 };
313 let city = write_feed("city", "-122.40000", "-122.40000", "");
314 let regional = write_feed(
315 "regional",
316 "-122.400045",
317 "-122.400045",
318 "SH,37.7050,-122.400045,2\n",
319 );
320 // A second service of another colour over the same track, in its own feed.
321 let other = root.join("other");
322 std::fs::create_dir_all(&other).unwrap();
323 std::fs::write(
324 other.join("routes.txt"),
325 "route_id,route_short_name,route_type,route_color\nK,K,1,E31E24\n",
326 )
327 .unwrap();
328 std::fs::write(other.join("trips.txt"), "route_id,trip_id,shape_id\nK,T1,SH\n").unwrap();
329 std::fs::write(
330 other.join("shapes.txt"),
331 "shape_id,shape_pt_lat,shape_pt_lon,shape_pt_sequence\n\
332 SH,37.7000,-122.40000,1\n\
333 SH,37.7100,-122.40000,2\n",
334 )
335 .unwrap();
336
337 let specs: Vec<FeedSpec> = vec![
338 ("city".to_string(), city, String::new()),
339 ("regional".to_string(), regional, String::new()),
340 ("other".to_string(), other, String::new()),
341 ];
342 let out = root.join("routes.geojsonseq");
343 run(&out, &specs).unwrap();
344 let text = std::fs::read_to_string(&out).unwrap();
345
346 assert_eq!(
347 text.matches("\"color\":\"0054A5\"").count(),
348 1,
349 "the re-surveyed republication must collapse onto the first: {text}",
350 );
351 assert_eq!(
352 text.matches("\"color\":\"E31E24\"").count(),
353 1,
354 "a different service over the same track must survive: {text}",
355 );
356 // And the two that survive share the track, so they fan out either side of it
357 // rather than both collapsing to one lane.
358 assert_eq!(text.matches("\"ordinal\":0,\"lanes\":2").count(), 1, "{text}");
359 assert_eq!(text.matches("\"ordinal\":1,\"lanes\":2").count(), 1, "{text}");
360
361 let _ = std::fs::remove_dir_all(&root);
362}
363
364/// A rail route whose trips name a shape the feed does not carry is reported,
365/// not silently emitted as an empty line.
366#[test]
367fn a_route_with_no_usable_shape_is_counted_and_drawn_nothing() {
368 let root = std::env::temp_dir().join(format!("gtfs_shapes_noshape_{}", std::process::id()));
369 let _ = std::fs::remove_dir_all(&root);
370 std::fs::create_dir_all(&root).unwrap();
371 let w = |file: &str, body: &str| std::fs::write(root.join(file), body).unwrap();
372 w("routes.txt", "route_id,route_short_name,route_type,route_color\nR,R,2,\n");
373 w("trips.txt", "route_id,trip_id,shape_id\nR,T1,MISSING\n");
374 // One point is not a line, so even a present shape can be unusable.
375 w(
376 "shapes.txt",
377 "shape_id,shape_pt_lat,shape_pt_lon,shape_pt_sequence\nOTHER,37.7,-122.4,1\n",
378 );
379
380 let feed = read_feed(&("solo".to_string(), root.clone(), String::new())).unwrap();
381 assert_eq!(feed.routes_kept, 1);
382 assert_eq!(feed.routes_without_shape, 1);
383 assert!(feed.lines.is_empty());
384
385 let _ = std::fs::remove_dir_all(&root);
386}