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

Modern-Apps.git / scripts / maps / gtfs_ingest / src / index_part5.rs

index_part5.rs432 lines · 17.7 KiBRaw
1#[cfg(test)]
2mod tests {
3 use super::*;
4 use crate::gtfs::parse_csv;
5 use crate::reader::{
6 Reader, SEC_FEED_MOTIS_PREFIX, SEC_SHAPE_COORDS, SEC_STOP_GTFS_ID,
7 };
8
9 /// 24 bytes per `stop_times.txt` row is the whole point of the streaming
10 /// loader — a world corpus has billions of them, and the old `Csv` +
11 /// `Option<f64>` representation cost ~400 and 40.
12 #[test]
13 fn a_stop_time_stays_twentyfour_bytes() {
14 assert_eq!(std::mem::size_of::<StopTime>(), 24);
15 }
16
17 pub(super) fn agency(tz: &str) -> Csv {
18 parse_csv(&format!("agency_id,agency_name,agency_timezone\nA,Agency,{tz}\n"))
19 }
20
21 /// `(shape_id, points as (lat, lon), optional shape_dist_traveled)`.
22 pub(super) type ShapeSpec<'a> = (&'a str, Vec<(f64, f64)>, Option<Vec<f64>>);
23
24 pub(super) fn shape_map(entries: Vec<ShapeSpec>) -> HashMap<String, Shape> {
25 entries
26 .into_iter()
27 .map(|(id, pts, dist)| {
28 (
29 id.to_string(),
30 Shape {
31 lat_e7: pts.iter().map(|&(la, _)| (la * 1e7) as i32).collect(),
32 lon_e7: pts.iter().map(|&(_, lo)| (lo * 1e7) as i32).collect(),
33 dist,
34 },
35 )
36 })
37 .collect()
38 }
39
40 /// Every route's vertex indices must be non-decreasing and inside its blob,
41 /// or the device's `shape[vertex(board)..=vertex(alight)]` slice is garbage.
42 pub(super) fn assert_shape_invariants(r: &Reader) {
43 for route in 0..r.route_count() {
44 let rec = r.route(route);
45 let (n_stops, first) = (rec.n_stops, rec.first_route_stop);
46 let vertices: Vec<u32> =
47 (0..n_stops).map(|p| r.route_stop_shape(first + p)).collect();
48 match r.route_shape_off(route) {
49 None => assert!(
50 vertices.iter().all(|&v| v == NONE),
51 "route {route} has no shape but carries vertices {vertices:?}"
52 ),
53 Some(off) => {
54 let n = r.shape_points(off).len() as u32;
55 assert!(
56 vertices.windows(2).all(|w| w[1] >= w[0]),
57 "route {route} vertices not monotone: {vertices:?}"
58 );
59 assert!(
60 vertices.iter().all(|&v| v < n),
61 "route {route} vertices {vertices:?} exceed {n} points"
62 );
63 }
64 }
65 }
66 }
67
68 fn feed_a() -> (Csv, Csv, Csv, Csv, Csv) {
69 let stops = parse_csv(
70 "stop_id,stop_name,stop_lat,stop_lon,stop_code\n\
71 S1,Alpha,37.70,-122.40,A1\n\
72 S2,Beta,37.71,-122.41,B2\n\
73 S3,Gamma,37.72,-122.42,C3\n",
74 );
75 let routes = parse_csv(
76 "route_id,route_short_name,route_long_name,route_type,route_color\n\
77 R1,N,Judah,0,0000FF\n",
78 );
79 let trips = parse_csv(
80 "route_id,service_id,trip_id,trip_headsign\n\
81 R1,WK,T1,Downtown\n\
82 R1,WK,T2,Downtown\n",
83 );
84 let stop_times = parse_csv(
85 "trip_id,stop_id,stop_sequence,arrival_time,departure_time\n\
86 T1,S1,1,08:00:00,08:00:00\n\
87 T1,S2,2,08:05:00,08:06:00\n\
88 T1,S3,3,08:10:00,08:10:00\n\
89 T2,S1,1,09:00:00,09:00:00\n\
90 T2,S2,2,09:05:00,09:06:00\n\
91 T2,S3,3,09:10:00,09:10:00\n",
92 );
93 let calendar = parse_csv(
94 "service_id,monday,tuesday,wednesday,thursday,friday,saturday,sunday,start_date,end_date\n\
95 WK,1,1,1,1,1,0,0,20240101,20241231\n",
96 );
97 (stops, routes, trips, stop_times, calendar)
98 }
99
100 fn feed_b() -> (Csv, Csv, Csv, Csv, Csv) {
101 let stops = parse_csv(
102 "stop_id,stop_name,stop_lat,stop_lon,stop_code\n\
103 P1,East1,37.80,-122.27,E1\n\
104 P2,East2,37.81,-122.26,E2\n",
105 );
106 let routes = parse_csv(
107 "route_id,route_short_name,route_long_name,route_type,route_color\n\
108 RB,51,Line 51,3,\n",
109 );
110 let trips = parse_csv(
111 "route_id,service_id,trip_id,trip_headsign\n\
112 RB,WK,TB1,Loop\n",
113 );
114 let stop_times = parse_csv(
115 "trip_id,stop_id,stop_sequence,arrival_time,departure_time\n\
116 TB1,P1,1,07:00:00,07:00:00\n\
117 TB1,P2,2,07:20:00,07:20:00\n",
118 );
119 let calendar = parse_csv(
120 "service_id,monday,tuesday,wednesday,thursday,friday,saturday,sunday,start_date,end_date\n\
121 WK,1,1,1,1,1,0,0,20240101,20241231\n",
122 );
123 (stops, routes, trips, stop_times, calendar)
124 }
125
126 #[test]
127 fn merges_two_feeds_and_roundtrips_profiles() {
128 let (as_, ar, at, ast, ac) = feed_a();
129 let (bs, br, bt, bst, bc) = feed_b();
130 let aa = agency("America/Los_Angeles");
131 let ba = agency("America/New_York");
132 // Two rows for the same (service, date) plus an unsorted extra date, to
133 // exercise the sort + last-row-wins collapse.
134 let acd = parse_csv(
135 "service_id,date,exception_type\n\
136 WK,20240704,1\n\
137 WK,20240101,2\n\
138 WK,20240704,2\n",
139 );
140 let feeds = vec![
141 FeedInput {
142 name: "sfmuni".to_string(),
143 motis_prefix: "us-ca-SFMTA".to_string(),
144 stops: &as_,
145 routes: &ar,
146 trips: &at,
147 stop_times: &ast,
148 calendar: Some(&ac),
149 calendar_dates: Some(&acd),
150 agency: Some(&aa),
151 shapes: None,
152 },
153 FeedInput {
154 name: "actransit".to_string(),
155 // Left empty on purpose: a feed whose MOTIS prefix the build does
156 // not know must still produce a valid pack.
157 motis_prefix: String::new(),
158 stops: &bs,
159 routes: &br,
160 trips: &bt,
161 stop_times: &bst,
162 calendar: Some(&bc),
163 calendar_dates: None,
164 agency: Some(&ba),
165 shapes: None,
166 },
167 ];
168 let (blob, stats) = build_index("world", &feeds).expect("build");
169 let r = Reader::new(blob).expect("read back the pack");
170
171 // Header sanity. `Reader::new` has already checked the magic.
172 assert_eq!(r.version(), VERSION);
173 assert_eq!(r.section_count(), SECTION_COUNT as u32);
174 assert_eq!(r.stop_count(), 5, "stop_count"); // 3 + 2
175 assert_eq!(r.route_count(), 2, "route_count");
176 assert_eq!(r.trip_count(), 3, "trip_count"); // 2 + 1
177 assert_eq!(r.feed_count(), 2, "feed_count");
178 // Feed A's two trips share one shape; feed B has its own -> 2 profiles.
179 assert_eq!(r.profile_count(), 2, "profile_count");
180 assert_eq!(stats.profiles, 2);
181
182 // Feeds table namespacing.
183 assert_eq!(r.feed_name(0), "sfmuni");
184 assert_eq!(r.feed_name(1), "actransit");
185 // v3: per-feed IANA timezone from agency.txt.
186 assert_eq!(r.feed_tz(0), "America/Los_Angeles");
187 assert_eq!(r.feed_tz(1), "America/New_York");
188 // v5: the Transitous prefix and raw stop_ids that compose a MOTIS stop id.
189 assert_eq!(r.feed_motis_prefix(0), "us-ca-SFMTA");
190 assert_eq!(r.feed_motis_prefix(1), "", "a feed with no known prefix writes NONE");
191 // Feed A's stops come first, so 0..3 are its stop_ids. These are the raw
192 // `stop_id` column, NOT `stop_code` ("A1"), which STOPS.code_off holds.
193 assert_eq!(r.stop_gtfs_id(0), "S1");
194 assert_eq!(r.stop_gtfs_id(1), "S2");
195 assert_eq!(r.stop_gtfs_id(2), "S3");
196 assert_ne!(
197 r.sec_bytes(SEC_FEED_MOTIS_PREFIX).len(),
198 0,
199 "FEED_MOTIS_PREFIX must be populated so the manifest proves v5 landed"
200 );
201 assert_eq!(r.sec_bytes(SEC_STOP_GTFS_ID).len(), 5 * 4, "STOP_GTFS_ID is u32[stop_count]");
202
203 // Route 0 = feed A's N-Judah. Decode its trips + profile.
204 let rec0 = r.route(0);
205 assert_eq!(rec0.feed_idx, 0, "route0 feed_idx");
206 assert_eq!(rec0.n_stops, 3, "route0 n_stops");
207 assert_eq!(r.read_str(rec0.name_off), "N");
208 let trips = r.route_trips(&rec0);
209 assert_eq!(trips.len(), 2);
210 // Sorted by start_time: 08:00 then 09:00.
211 assert_eq!(trips[0].start_time, 28800);
212 assert_eq!(trips[1].start_time, 32400);
213 // Both reference the same profile id (dedup).
214 assert_eq!(trips[0].profile_id, trips[1].profile_id);
215
216 // v6's strided table must be the same trips as the varint stream, for every
217 // route. Two views of one thing, written in the same loop, so a disagreement is
218 // a writer bug the device reader would silently inherit.
219 for route_idx in 0..r.route_count() {
220 let rec = r.route(route_idx);
221 let varint = r.route_trips(&rec);
222 let strided = r.route_trips_strided(route_idx);
223 assert_eq!(
224 varint.len(),
225 strided.len(),
226 "route {route_idx} trip count differs between the two views"
227 );
228 for (a, b) in varint.iter().zip(strided.iter()) {
229 assert_eq!(a.start_time, b.start_time, "route {route_idx} start_time");
230 assert_eq!(a.profile_id, b.profile_id, "route {route_idx} profile_id");
231 assert_eq!(a.service_idx, b.service_idx, "route {route_idx} service_idx");
232 assert_eq!(a.headsign_off, b.headsign_off, "route {route_idx} headsign_off");
233 }
234 }
235
236 // Reconstruct absolute arr/dep for trip T2 (start 09:00) and compare.
237 let prof = r.profile(trips[1].profile_id);
238 let start = trips[1].start_time as i64;
239 let abs: Vec<(i64, i64)> =
240 prof.iter().map(|&(a, d)| (start + a, start + d)).collect();
241 assert_eq!(abs[0], (32400, 32400)); // S1 09:00/09:00
242 assert_eq!(abs[1], (32700, 32760)); // S2 09:05/09:06
243 assert_eq!(abs[2], (33000, 33000)); // S3 09:10/09:10
244
245 // Route 1 belongs to feed B.
246 let rec1 = r.route(1);
247 assert_eq!(rec1.feed_idx, 1, "route1 feed_idx");
248 assert_eq!(rec1.n_stops, 2, "route1 n_stops");
249
250 // Route stops of route 0 point at the first three (feed A) stops.
251 for pos in 0..rec0.n_stops {
252 let s = r.route_stop(rec0.first_route_stop + pos);
253 assert!(s < 3, "route0 stop {s} should be a feed-A stop");
254 }
255
256 // Grid nearest lookups.
257 assert_eq!(r.nearest(37.72, -122.42), Some(2), "Gamma");
258 assert_eq!(r.nearest(37.80, -122.27), Some(3), "feed B P1");
259
260 // v3: STOP_ROUTE_POS is parallel to STOP_ROUTES and gives the stop's
261 // position in the pattern, so pos matches a ROUTE_STOPS lookup.
262 for stop in 0..r.stop_count() {
263 for (route, pos) in r.stop_routes(stop) {
264 let rec = r.route(route);
265 assert!(pos < rec.n_stops, "stop {stop} pos {pos} out of route {route}");
266 assert_eq!(
267 r.route_stop(rec.first_route_stop + pos),
268 stop,
269 "stop {stop} route {route}"
270 );
271 }
272 }
273
274 // v3: exceptions are date-sorted per service and collapsed to one row
275 // per (service, date), with the last CSV row winning.
276 let svc = r.route_trips(&rec0)[0].service_idx;
277 assert_eq!(
278 r.service_exceptions(svc),
279 vec![(svc, 20240101, 0), (svc, 20240704, 0)],
280 "sorted, deduped, last-row-wins"
281 );
282 // Feed B contributes no exceptions, so its services have empty ranges.
283 let svc_b = r.route_trips(&rec1)[0].service_idx;
284 assert!(r.service_exceptions(svc_b).is_empty());
285
286 // v4: no shapes.txt anywhere, so every route falls back to stop-to-stop.
287 assert!(r.route_shape_off(0).is_none());
288 assert!(r.route_shape_off(1).is_none());
289 assert_eq!(r.sec_bytes(SEC_SHAPE_COORDS).len(), 0, "SHAPE_COORDS is empty");
290 assert_shape_invariants(&r);
291 }
292
293 // --- v4 shape ingest -----------------------------------------------------
294
295 /// One feed, three collinear stops, one route, `shape_id` on both trips.
296 /// `stop_times_extra` is appended verbatim so a test can add
297 /// `shape_dist_traveled`.
298 pub(super) fn shaped_feed(shape_dist: bool) -> (Csv, Csv, Csv, Csv, Csv) {
299 let stops = parse_csv(
300 "stop_id,stop_name,stop_lat,stop_lon,stop_code\n\
301 S1,Alpha,37.700,-122.400,A1\n\
302 S2,Beta,37.710,-122.400,B2\n\
303 S3,Gamma,37.720,-122.400,C3\n",
304 );
305 let routes = parse_csv(
306 "route_id,route_short_name,route_long_name,route_type,route_color\n\
307 R1,N,Judah,0,0000FF\n",
308 );
309 let trips = parse_csv(
310 "route_id,service_id,trip_id,trip_headsign,shape_id\n\
311 R1,WK,T1,Downtown,SH1\n\
312 R1,WK,T2,Downtown,SH1\n",
313 );
314 let stop_times = if shape_dist {
315 parse_csv(
316 "trip_id,stop_id,stop_sequence,arrival_time,departure_time,shape_dist_traveled\n\
317 T1,S1,1,08:00:00,08:00:00,0.0\n\
318 T1,S2,2,08:05:00,08:06:00,1.3\n\
319 T1,S3,3,08:10:00,08:10:00,2.6\n\
320 T2,S1,1,09:00:00,09:00:00,0.0\n\
321 T2,S2,2,09:05:00,09:06:00,1.3\n\
322 T2,S3,3,09:10:00,09:10:00,2.6\n",
323 )
324 } else {
325 parse_csv(
326 "trip_id,stop_id,stop_sequence,arrival_time,departure_time\n\
327 T1,S1,1,08:00:00,08:00:00\n\
328 T1,S2,2,08:05:00,08:06:00\n\
329 T1,S3,3,08:10:00,08:10:00\n\
330 T2,S1,1,09:00:00,09:00:00\n\
331 T2,S2,2,09:05:00,09:06:00\n\
332 T2,S3,3,09:10:00,09:10:00\n",
333 )
334 };
335 let calendar = parse_csv(
336 "service_id,monday,tuesday,wednesday,thursday,friday,saturday,sunday,start_date,end_date\n\
337 WK,1,1,1,1,1,0,0,20240101,20241231\n",
338 );
339 (stops, routes, trips, stop_times, calendar)
340 }
341
342 /// The route's shape, detouring east between each pair of stops.
343 fn detour_shape(dist: bool) -> HashMap<String, Shape> {
344 shape_map(vec![(
345 "SH1",
346 vec![
347 (37.700, -122.400),
348 (37.705, -122.390),
349 (37.710, -122.400),
350 (37.715, -122.390),
351 (37.720, -122.400),
352 ],
353 // Kilometres, deliberately not metres: units are feed-defined.
354 dist.then(|| vec![0.0, 0.65, 1.3, 1.95, 2.6]),
355 )])
356 }
357
358 pub(super) fn one_feed<'a>(
359 t: &'a (Csv, Csv, Csv, Csv, Csv),
360 ag: &'a Csv,
361 shapes: Option<&'a HashMap<String, Shape>>,
362 ) -> Vec<FeedInput<'a>> {
363 vec![FeedInput {
364 name: "sfmuni".to_string(),
365 motis_prefix: "us-ca-SFMTA".to_string(),
366 stops: &t.0,
367 routes: &t.1,
368 trips: &t.2,
369 stop_times: &t.3,
370 calendar: Some(&t.4),
371 calendar_dates: None,
372 agency: Some(ag),
373 shapes,
374 }]
375 }
376
377 #[test]
378 fn projects_stops_onto_a_shape_without_shape_dist_traveled() {
379 let t = shaped_feed(false);
380 let ag = agency("America/Los_Angeles");
381 let sh = detour_shape(false);
382 let (blob, stats) =
383 build_index("world", &one_feed(&t, &ag, Some(&sh))).expect("build");
384 let r = Reader::new(blob).expect("read back the pack");
385 assert_eq!(stats.shaped_routes, 1);
386 assert_eq!(stats.dropped_shape_routes, 0);
387 assert_eq!(stats.multi_shape_routes, 0);
388 assert_shape_invariants(&r);
389
390 let off = r.route_shape_off(0).expect("route 0 is shaped");
391 let pts = r.shape_points(off);
392 let rec = r.route(0);
393 let vertices: Vec<u32> =
394 (0..rec.n_stops).map(|p| r.route_stop_shape(rec.first_route_stop + p)).collect();
395 // Trimmed to the boarded extent: first stop is vertex 0, last is the end.
396 assert_eq!(vertices[0], 0);
397 assert_eq!(*vertices.last().unwrap() as usize, pts.len() - 1);
398 // Each stop's vertex is the stop's own projection, so a boarded span
399 // starts exactly on the stop.
400 for (p, &v) in vertices.iter().enumerate() {
401 let stop = r.route_stop(rec.first_route_stop + p as u32);
402 let (slat, slon) = r.stop_ll(stop);
403 let (vlat, vlon) = pts[v as usize];
404 assert!(
405 (vlat as f64 * 1e-7 - slat).abs() < 1e-5
406 && (vlon as f64 * 1e-7 - slon).abs() < 1e-5,
407 "vertex {v} at {vlat},{vlon} is not stop {stop} at {slat},{slon}"
408 );
409 }
410 // The detour is kept, so the drawn ride is not straight.
411 assert!(
412 pts.iter().any(|&(_, lon)| lon > -1_223_950_000),
413 "the eastward detour was dropped: {pts:?}"
414 );
415 }
416
417 #[test]
418 fn shape_dist_traveled_on_both_files_is_used() {
419 let t = shaped_feed(true);
420 let ag = agency("America/Los_Angeles");
421 let sh = detour_shape(true);
422 let (blob, stats) =
423 build_index("world", &one_feed(&t, &ag, Some(&sh))).expect("build");
424 let r = Reader::new(blob).expect("read back the pack");
425 assert_eq!(stats.shaped_routes, 1);
426 assert_shape_invariants(&r);
427 let rec = r.route(0);
428 let vertices: Vec<u32> =
429 (0..rec.n_stops).map(|p| r.route_stop_shape(rec.first_route_stop + p)).collect();
430 assert!(vertices.windows(2).all(|w| w[1] > w[0]), "distinct stops, distinct vertices");
431 }
432}