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

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

index_part3.rs503 lines · 21.0 KiBRaw
1impl IndexBuilder {
2 /// Serialize one feed's routes, trips, profiles, shapes and stop→route lists.
3 ///
4 /// `stop_first` is the first stop index this feed contributed. Because a
5 /// route only ever references its own feed's stops, this feed's STOP_ROUTES
6 /// entries cover exactly `stop_first..` and append onto a globally
7 /// stop-ascending array.
8 fn finalize_feed(
9 &mut self,
10 raptor_routes: &[RaptorRoute],
11 built_trips: &[BuiltTrip],
12 shapes: &[(&str, &Shape)],
13 stop_first: u32,
14 ) -> Result<(), String> {
15 // (stop, route, position in the route's pattern), sorted into
16 // stop-ascending order below. Replaces the old `vec![Vec::new(); stops]`
17 // pair — 48 bytes of empty headers per stop, worldwide — and the
18 // `contains` scan that went with it, which was quadratic on the routes
19 // through a major interchange.
20 let mut stop_routes: Vec<(u32, u32, u32)> = Vec::new();
21
22 for (local_idx, rr) in raptor_routes.iter().enumerate() {
23 let ridx = (self.route_count + local_idx) as u32;
24 // Trips of one pattern normally share a `shape_id`. Where they do not
25 // (versioned shapes, rare express variants) the modal one keeps the
26 // common case exact; direction differences already form distinct
27 // patterns, so they never land here.
28 let mut votes: HashMap<u32, usize> = HashMap::new();
29 for &ti in &rr.trips {
30 let k = built_trips[ti].shape_key;
31 if k != NONE {
32 *votes.entry(k).or_insert(0) += 1;
33 }
34 }
35 if votes.len() > 1 {
36 self.multi_shape_routes += 1;
37 }
38 let mut ranked: Vec<(u32, usize)> = votes.into_iter().collect();
39 // Ties break on the `shape_id` itself, not on its interned index, so
40 // the winner does not depend on the order trips were seen in.
41 ranked.sort_by(|a, b| {
42 b.1.cmp(&a.1).then(shapes[a.0 as usize].0.cmp(shapes[b.0 as usize].0))
43 });
44 let modal = ranked.first().map(|&(k, _)| k);
45 let fitted = modal.and_then(|key| {
46 let shape = shapes[key as usize].1;
47 let stop_ll: Vec<(i32, i32)> = rr
48 .stop_pattern
49 .iter()
50 .map(|&s| (self.stop_lat[s as usize], self.stop_lon[s as usize]))
51 .collect();
52 // `shape_dist_traveled` only helps when both files carry it, so
53 // take it from a trip that actually uses the modal shape.
54 let dists = rr
55 .trips
56 .iter()
57 .filter(|&&ti| built_trips[ti].shape_key == key)
58 .find_map(|&ti| built_trips[ti].stop_dists.as_ref())
59 .filter(|d| d.len() == rr.stop_pattern.len());
60 shapes::fit(shape, &stop_ll, dists.map(|d| d.as_slice()))
61 });
62 if modal.is_some() {
63 if fitted.is_some() {
64 self.shaped_routes += 1;
65 } else {
66 self.dropped_shape_routes += 1;
67 }
68 }
69 let shape_off = match &fitted {
70 None => NONE,
71 Some(f) => self.shape_blobs.intern(&shapes::encode(&f.points))?,
72 };
73 append_u32(&mut self.sec_route_shape_idx, shape_off);
74
75 let first_route_stop = (self.sec_route_stops.len() / 4) as u32;
76 for (pos, &s) in rr.stop_pattern.iter().enumerate() {
77 debug_assert!(
78 s >= stop_first,
79 "route {ridx} references stop {s} from an earlier feed; per-feed \
80 finalization depends on patterns staying inside their own feed"
81 );
82 append_u32(&mut self.sec_route_stops, s);
83 let vertex = fitted
84 .as_ref()
85 .and_then(|f| f.stop_vertices.get(pos).copied())
86 .unwrap_or(NONE);
87 append_u32(&mut self.sec_route_stop_shape, vertex);
88 stop_routes.push((s, ridx, pos as u32));
89 }
90 let n_stops = rr.stop_pattern.len() as u32;
91
92 // Sort this route's trips by first-stop departure, then varint-pack.
93 let mut trip_order: Vec<usize> = rr.trips.clone();
94 trip_order.sort_by_key(|&ti| built_trips[ti].start_time);
95 // RouteRec.trips_off is a u32 byte offset into ROUTE_TRIPS.
96 let trips_off = u32::try_from(self.sec_route_trips.len()).map_err(|_| {
97 "ROUTE_TRIPS exceeded 4 GiB, which a u32 RouteRec.trips_off cannot address"
98 .to_string()
99 })?;
100 let mut prev_start: u32 = 0;
101 // The CSR prefix: this route's first trip in the strided table.
102 append_u32(&mut self.sec_route_trip_off, self.trip_total as u32);
103 for &ti in &trip_order {
104 let bt = &built_trips[ti];
105 let profile_id = self.profiles.intern(&bt.stoptimes)?;
106 let start_delta = bt.start_time.saturating_sub(prev_start);
107 write_uvarint(&mut self.sec_route_trips, start_delta as u64);
108 write_uvarint(&mut self.sec_route_trips, profile_id as u64);
109 write_uvarint(&mut self.sec_route_trips, bt.service_idx as u64);
110 write_uvarint(&mut self.sec_route_trips, bt.headsign_off as u64);
111 append_u32(&mut self.sec_route_trip_recs, bt.start_time);
112 append_u32(&mut self.sec_route_trip_recs, profile_id);
113 append_u32(&mut self.sec_route_trip_recs, bt.service_idx);
114 append_u32(&mut self.sec_route_trip_recs, bt.headsign_off);
115 prev_start = bt.start_time;
116 self.trip_total += 1;
117 }
118
119 append_u32(&mut self.sec_routes, rr.name_off);
120 append_u32(&mut self.sec_routes, rr.color);
121 append_u32(&mut self.sec_routes, rr.route_type);
122 append_u32(&mut self.sec_routes, rr.feed_idx);
123 append_u32(&mut self.sec_routes, n_stops);
124 append_u32(&mut self.sec_routes, first_route_stop);
125 append_u32(&mut self.sec_routes, trip_order.len() as u32);
126 append_u32(&mut self.sec_routes, trips_off);
127 }
128 self.route_count += raptor_routes.len();
129
130 // Stable, so within a stop the routes stay in ascending route order and
131 // the surviving position is the pattern's first occurrence of that stop —
132 // matching the reader's `break`-on-match scan that STOP_ROUTE_POS
133 // replaces.
134 stop_routes.sort_by_key(|&(s, _, _)| s);
135 stop_routes.dedup_by(|a, b| a.0 == b.0 && a.1 == b.1);
136 let mut k = 0usize;
137 for s in stop_first..self.stop_lat.len() as u32 {
138 append_u32(&mut self.sec_stop_routes_idx, self.stop_routes_total);
139 while let Some(&(stop, route, pos)) = stop_routes.get(k) {
140 if stop != s {
141 break;
142 }
143 append_u32(&mut self.sec_stop_routes, route);
144 append_u32(&mut self.sec_stop_route_pos, pos);
145 self.stop_routes_total += 1;
146 k += 1;
147 }
148 }
149 debug_assert_eq!(k, stop_routes.len(), "a stop→route entry fell outside this feed");
150 Ok(())
151 }
152
153 /// Serialize the sections that need every feed, and write the pack to `out`.
154 pub fn finish_to(self, out: &mut impl Write) -> Result<BuildStats, String> {
155 let IndexBuilder {
156 pool,
157 pack_name_off,
158 stop_lat,
159 stop_lon,
160 min_lat,
161 min_lon,
162 max_lat,
163 max_lon,
164 service_key_to_idx: _,
165 svc_mask,
166 svc_start,
167 svc_end,
168 exceptions,
169 feed_name_offs,
170 feed_tz_offs,
171 feed_motis_prefix_offs,
172 sec_stops,
173 sec_stop_gtfs_id,
174 sec_routes,
175 sec_route_stops,
176 sec_route_trips,
177 sec_route_trip_recs,
178 mut sec_route_trip_off,
179 mut sec_route_shape_idx,
180 sec_route_stop_shape,
181 sec_stop_routes,
182 mut sec_stop_routes_idx,
183 sec_stop_route_pos,
184 profiles,
185 shape_blobs,
186 rail_lines,
187 stop_routes_total,
188 route_count,
189 trip_total,
190 shaped_routes,
191 multi_shape_routes,
192 dropped_shape_routes,
193 dropped_stops_bad_coord,
194 } = self;
195 let stop_count = stop_lat.len();
196 if stop_count == 0 {
197 return Err("no usable stops in any feed".to_string());
198 }
199
200 // Everything that depends on one feed alone is already serialized; what
201 // is left needs the whole merged stop set.
202
203 // Terminating bound the reader validates shape offsets against.
204 append_u32(&mut sec_route_shape_idx, shape_blobs.bytes.len() as u32);
205 // Terminating total, so the last stop's STOP_ROUTES range closes.
206 append_u32(&mut sec_stop_routes_idx, stop_routes_total);
207
208 // Profiles index (byte offset per id, plus terminating length).
209 let mut sec_profiles_idx = Vec::new();
210 for &off in &profiles.offsets {
211 append_u32(&mut sec_profiles_idx, off);
212 }
213 append_u32(&mut sec_profiles_idx, profiles.bytes.len() as u32);
214 let profile_count = profiles.offsets.len();
215
216 // A wrapped STRINGS offset would name the wrong stop rather than fail, so
217 // this is checked before anything is written.
218 if pool.overflowed {
219 return Err(
220 "STRINGS exceeded the 4 GiB a u32 string offset can address; the pack cannot \
221 represent this many feeds"
222 .to_string(),
223 );
224 }
225
226 // --- Footpath transfers via a coarse spatial grid (cross-feed for free) ---
227 // A flat `(cell, stop)` vector sorted once, not a `HashMap` of buckets: on a
228 // world pack the map is millions of cells each holding a tiny `Vec`, whose
229 // headers and allocations cost far more than the stop ids in them. Sorting
230 // by `(cell, stop)` keeps each cell's stops ascending, which is the order the
231 // old bucket pushes produced and which the distance sort below tie-breaks on.
232 let xcell = |lat_e7: i32, lon_e7: i32| -> (i32, i32) {
233 (
234 (lat_e7 as f64 * 1e-7 / CELL_DEG).floor() as i32,
235 (lon_e7 as f64 * 1e-7 / CELL_DEG).floor() as i32,
236 )
237 };
238 let mut xgrid: Vec<((i32, i32), u32)> = (0..stop_count)
239 .map(|i| (xcell(stop_lat[i], stop_lon[i]), i as u32))
240 .collect();
241 xgrid.sort_unstable();
242 let xbucket = |key: (i32, i32)| -> &[((i32, i32), u32)] {
243 let lo = xgrid.partition_point(|&(k, _)| k < key);
244 let hi = xgrid.partition_point(|&(k, _)| k <= key);
245 &xgrid[lo..hi]
246 };
247 let mut transfer_total = 0usize;
248 let mut sec_transfers = Vec::new();
249 let mut sec_transfers_idx = Vec::new();
250 let mut tacc: u32 = 0;
251 for i in 0..stop_count {
252 append_u32(&mut sec_transfers_idx, tacc);
253 let (cx, cy) = xcell(stop_lat[i], stop_lon[i]);
254 let mut cand: Vec<(u32, f64)> = Vec::new();
255 for dx in -1..=1 {
256 for dy in -1..=1 {
257 for &(_, j) in xbucket((cx + dx, cy + dy)) {
258 if j as usize == i {
259 continue;
260 }
261 let d =
262 dist_m(stop_lat[i], stop_lon[i], stop_lat[j as usize], stop_lon[j as usize]);
263 if d <= MAX_TRANSFER_M {
264 cand.push((j, d));
265 }
266 }
267 }
268 }
269 // Stable, so equidistant candidates keep the dx/dy/stop order above and
270 // `truncate` drops a deterministic tail.
271 cand.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
272 cand.truncate(MAX_TRANSFERS_PER_STOP);
273 for (j, d) in cand {
274 let secs = (d / WALK_SPEED_M_S).ceil() as u32;
275 append_u32(&mut sec_transfers, j);
276 append_u32(&mut sec_transfers, secs);
277 tacc += 1;
278 transfer_total += 1;
279 }
280 }
281 append_u32(&mut sec_transfers_idx, tacc);
282
283 // --- Services + exceptions ---
284 let mut sec_services = Vec::new();
285 for i in 0..svc_mask.len() {
286 sec_services.push(svc_mask[i]);
287 sec_services.extend_from_slice(&[0u8, 0, 0]);
288 append_u32(&mut sec_services, svc_start[i]);
289 append_u32(&mut sec_services, svc_end[i]);
290 }
291 // --- Exceptions: sorted by (service_idx, date), one row per pair, with a
292 // CSR index so the device does a range lookup + binary search instead of a
293 // full scan per trip. `add_feed` already stable-sorted each feed's slice
294 // and a feed's services are a contiguous index range, so the whole array
295 // is sorted; for duplicate (service, date) rows the last in CSV order
296 // wins — matching the old reader, which scanned every exception without
297 // breaking out. ---
298 debug_assert!(
299 exceptions.windows(2).all(|w| (w[0].0, w[0].1) <= (w[1].0, w[1].1)),
300 "per-feed exception slices did not concatenate into a sorted array"
301 );
302 let mut exc_unique: Vec<(u32, u32, u32)> = Vec::with_capacity(exceptions.len());
303 for e in exceptions {
304 match exc_unique.last_mut() {
305 Some(last) if last.0 == e.0 && last.1 == e.1 => *last = e,
306 _ => exc_unique.push(e),
307 }
308 }
309 let mut sec_exceptions = Vec::new();
310 let mut sec_exceptions_idx = Vec::new();
311 let mut eacc: u32 = 0;
312 let mut ei = 0usize;
313 for s in 0..svc_mask.len() as u32 {
314 append_u32(&mut sec_exceptions_idx, eacc);
315 while let Some(&(sidx, date, added)) = exc_unique.get(ei) {
316 if sidx != s {
317 break;
318 }
319 append_u32(&mut sec_exceptions, sidx);
320 append_u32(&mut sec_exceptions, date);
321 append_u32(&mut sec_exceptions, added);
322 eacc += 1;
323 ei += 1;
324 }
325 }
326 append_u32(&mut sec_exceptions_idx, eacc);
327
328 // --- Spatial grid (sparse CSR keyed by cell id) ---
329 let grid_lat0 = min_lat;
330 let grid_lon0 = min_lon;
331 let grid_cell_e7 = (GRID_CELL_DEG * 1e7) as u32;
332 let cell_col = |lon_e7: i32| -> i64 {
333 ((lon_e7 as i64 - grid_lon0 as i64) / grid_cell_e7 as i64).max(0)
334 };
335 let cell_row = |lat_e7: i32| -> i64 {
336 ((lat_e7 as i64 - grid_lat0 as i64) / grid_cell_e7 as i64).max(0)
337 };
338 let grid_cols = (cell_col(max_lon) + 1) as u32;
339 let grid_rows = (cell_row(max_lat) + 1) as u32;
340 // Sorted by `(cell_id, stop)`, which is exactly the two orderings the device
341 // requires: GRID_CELL_IDS ascending, because the reader binary-searches it,
342 // and each cell's GRID_STOPS run stop-ascending.
343 let mut grid: Vec<(u32, u32)> = (0..stop_count)
344 .map(|i| {
345 let row = cell_row(stop_lat[i]) as u32;
346 let col = cell_col(stop_lon[i]) as u32;
347 (row * grid_cols + col, i as u32)
348 })
349 .collect();
350 grid.sort_unstable();
351 let mut sec_grid_cell_ids = Vec::new();
352 let mut sec_grid_cell_off = Vec::new();
353 let mut sec_grid_stops = Vec::with_capacity(stop_count * 4);
354 let mut grid_cell_count = 0usize;
355 for (k, &(cid, stop)) in grid.iter().enumerate() {
356 if k == 0 || cid != grid[k - 1].0 {
357 append_u32(&mut sec_grid_cell_ids, cid);
358 append_u32(&mut sec_grid_cell_off, k as u32);
359 grid_cell_count += 1;
360 }
361 append_u32(&mut sec_grid_stops, stop);
362 }
363 append_u32(&mut sec_grid_cell_off, grid.len() as u32);
364
365 // --- Feeds ---
366 let mut sec_feeds = Vec::with_capacity(feed_name_offs.len() * 4);
367 for &off in &feed_name_offs {
368 append_u32(&mut sec_feeds, off);
369 }
370 let mut sec_feed_tz = Vec::with_capacity(feed_tz_offs.len() * 4);
371 for &off in &feed_tz_offs {
372 append_u32(&mut sec_feed_tz, off);
373 }
374 let mut sec_feed_motis_prefix = Vec::with_capacity(feed_motis_prefix_offs.len() * 4);
375 for &off in &feed_motis_prefix_offs {
376 append_u32(&mut sec_feed_motis_prefix, off);
377 }
378
379 // --- Assemble file: header + directory + aligned sections ---
380 let section_names: [&'static str; SECTION_COUNT] = [
381 "STRINGS",
382 "STOPS",
383 "ROUTES",
384 "ROUTE_STOPS",
385 "ROUTE_TRIPS",
386 "PROFILES",
387 "PROFILES_IDX",
388 "STOP_ROUTES",
389 "STOP_ROUTES_IDX",
390 "TRANSFERS",
391 "TRANSFERS_IDX",
392 "SERVICES",
393 "EXCEPTIONS",
394 "GRID_CELL_IDS",
395 "GRID_CELL_OFF",
396 "GRID_STOPS",
397 "FEEDS",
398 "FEED_TZ",
399 "EXCEPTIONS_IDX",
400 "STOP_ROUTE_POS",
401 "SHAPE_COORDS",
402 "ROUTE_SHAPE_IDX",
403 "ROUTE_STOP_SHAPE",
404 "FEED_MOTIS_PREFIX",
405 "STOP_GTFS_ID",
406 "ROUTE_TRIP_RECS",
407 "ROUTE_TRIP_OFF",
408 "RAIL_LINES",
409 ];
410 // Close the CSR prefix: one past the last route's trips, i.e. the total. Done
411 // here because it is only known once every feed's routes have been written.
412 append_u32(&mut sec_route_trip_off, trip_total as u32);
413 let sec_rail_lines = rail_lines.into_section();
414 let sections: [&[u8]; SECTION_COUNT] = [
415 &pool.bytes,
416 &sec_stops,
417 &sec_routes,
418 &sec_route_stops,
419 &sec_route_trips,
420 &profiles.bytes,
421 &sec_profiles_idx,
422 &sec_stop_routes,
423 &sec_stop_routes_idx,
424 &sec_transfers,
425 &sec_transfers_idx,
426 &sec_services,
427 &sec_exceptions,
428 &sec_grid_cell_ids,
429 &sec_grid_cell_off,
430 &sec_grid_stops,
431 &sec_feeds,
432 &sec_feed_tz,
433 &sec_exceptions_idx,
434 &sec_stop_route_pos,
435 &shape_blobs.bytes,
436 &sec_route_shape_idx,
437 &sec_route_stop_shape,
438 &sec_feed_motis_prefix,
439 &sec_stop_gtfs_id,
440 &sec_route_trip_recs,
441 &sec_route_trip_off,
442 &sec_rail_lines,
443 ];
444
445 let dir_len = SECTION_COUNT * 16;
446 let mut data_off = HEADER_LEN + dir_len;
447 let align = |o: usize| (o + 7) & !7;
448 for s in sections.iter() {
449 data_off = align(data_off) + s.len();
450 }
451 let total = data_off;
452
453 let mut header: Vec<u8> = Vec::with_capacity(HEADER_LEN);
454 append_u32(&mut header, MAGIC);
455 append_u32(&mut header, VERSION);
456 append_u32(&mut header, SECTION_COUNT as u32);
457 append_u32(&mut header, stop_count as u32);
458 append_u32(&mut header, route_count as u32);
459 append_u32(&mut header, trip_total as u32);
460 append_u32(&mut header, svc_mask.len() as u32);
461 append_u32(&mut header, profile_count as u32);
462 append_u32(&mut header, feed_name_offs.len() as u32);
463 append_u32(&mut header, grid_cell_count as u32);
464 append_u32(&mut header, pack_name_off);
465 append_i32(&mut header, min_lat);
466 append_i32(&mut header, min_lon);
467 append_i32(&mut header, max_lat);
468 append_i32(&mut header, max_lon);
469 append_i32(&mut header, grid_lat0);
470 append_i32(&mut header, grid_lon0);
471 append_u32(&mut header, grid_cell_e7);
472 append_u32(&mut header, grid_cols);
473 append_u32(&mut header, grid_rows);
474 debug_assert_eq!(header.len(), HEADER_LEN);
475
476 let written =
477 write_pack(out, &header, &sections).map_err(|e| format!("cannot write the pack: {e}"))?;
478 debug_assert_eq!(written, total);
479
480 let section_sizes: Vec<(&'static str, usize)> =
481 section_names.iter().zip(sections.iter()).map(|(&n, s)| (n, s.len())).collect();
482
483 Ok(BuildStats {
484 stops: stop_count,
485 routes: route_count,
486 trips: trip_total,
487 profiles: profile_count,
488 feeds: feed_name_offs.len(),
489 transfers: transfer_total,
490 min_lat_e7: min_lat,
491 min_lon_e7: min_lon,
492 max_lat_e7: max_lat,
493 max_lon_e7: max_lon,
494 size_bytes: written,
495 section_sizes,
496 shaped_routes,
497 multi_shape_routes,
498 dropped_shape_routes,
499 dropped_stops_bad_coord,
500 })
501 }
502
503}