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

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

index.rs449 lines · 20.3 KiBRaw
1//! Build the compact **world** transit index from parsed GTFS tables (possibly
2//! merged from many feeds) and serialize it to the on-disk `.transit` format.
3//!
4//! ON-DISK FORMAT v5 ("TRX2", little-endian, mmap-friendly, read via
5//! `read_unaligned` on device). THIS LAYOUT MUST STAY IN SYNC WITH
6//! `maps/src/main/rust/src/transit.rs`.
7//!
8//! v5 is v4 plus two purely additive sections (23-24) that let the device name a
9//! stop in Transitous/MOTIS's own id space without a network round-trip, which is
10//! what keeps the realtime `/stoptimes` overlay working now that the
11//! `/map/stops` coordinate-to-id lookup is gone. A MOTIS stop id is
12//! `<registry-file>-<source name>_<gtfs stop_id>`, so it is composed on device
13//! from a per-feed prefix and the raw `stop_id`. They are parallel `u32` STRINGS
14//! offsets rather than new `StopRec` fields because `StopRec` is a packed 16-byte
15//! stride indexed by arithmetic — widening it would invalidate every older pack.
16//!
17//! v4 is v3 plus three purely additive sections (20-22) carrying GTFS
18//! `shapes.txt` geometry, so a ride leg draws the path the vehicle actually
19//! takes — and reports a truthful distance — instead of a line through its
20//! stops. The device reader accepts v3 and v4, so a pack rebuild and an app
21//! update can land in either order.
22//!
23//! v3 is v2 plus three purely additive sections (17-19); sections 0-16 are
24//! byte-identical. They exist so the on-device planner can be correct and fast
25//! on a world pack: `FEED_TZ` lets it route in the *feed's* timezone rather than
26//! the device's, `EXCEPTIONS_IDX` turns the `calendar_dates` lookup from a full
27//! scan per trip into a CSR range + binary search, and `STOP_ROUTE_POS` removes
28//! the per-stop linear scan over a route's stop pattern.
29//!
30//! The v2 redesign exists to make a single global (world) pack feasible. v1
31//! stored `(arr,dep)` u32 per stop *per trip* (8 B) and referenced them via a
32//! `u32 first_stoptime`, so a worldwide pack was ~10–20 GB and bumped the 4.29 B
33//! stop-time ceiling. v2 instead:
34//! * factors each trip into `{ start_time, profile_id }` where a **profile** is
35//! the varint-delta-encoded run-time *shape* (per-stop hop + dwell offsets),
36//! deduplicated across all trips sharing that shape — this removes both the
37//! per-trip stop-time table and the u32 ceiling;
38//! * packs each RAPTOR route's trips as varints (start-time deltas + ids);
39//! * adds a **spatial grid** (sparse CSR) so nearest-stop / bbox queries are
40//! cell-local instead of O(all stops);
41//! * adds a **FEEDS** table + per-route `feed_idx` so many agencies merge into
42//! one pack without id collisions (ids are namespaced per feed at build).
43//!
44//! Header (80 bytes; all u32/i32 little-endian):
45//! u32 magic (MAGIC), u32 version (VERSION=7), u32 section_count,
46//! u32 stop_count, u32 route_count, u32 trip_count, u32 service_count,
47//! u32 profile_count, u32 feed_count, u32 grid_cell_count, u32 feed_name_off,
48//! i32 min_lat_e7, i32 min_lon_e7, i32 max_lat_e7, i32 max_lon_e7,
49//! i32 grid_lat0_e7, i32 grid_lon0_e7, u32 grid_cell_e7, u32 grid_cols,
50//! u32 grid_rows
51//! Section directory: section_count * { u64 offset, u64 len } (absolute byte
52//! offset from file start, byte length; 8-byte aligned, may exceed 4 GB).
53//!
54//! Sections (index -> payload):
55//! 0 STRINGS NUL-terminated UTF-8 string pool; offsets are byte
56//! offsets into this section, sentinel NONE = no string.
57//! 1 STOPS StopRec[stop_count] = { i32 lat_e7, i32 lon_e7,
58//! u32 name_off, u32 code_off }.
59//! 2 ROUTES RouteRec[route_count] = { u32 name_off, u32 color,
60//! u32 route_type, u32 feed_idx, u32 n_stops,
61//! u32 first_route_stop, u32 n_trips, u32 trips_off };
62//! `trips_off` is a byte offset into ROUTE_TRIPS.
63//! 3 ROUTE_STOPS u32[] ordered stop indices; RouteRec slices it by
64//! [first_route_stop, +n_stops].
65//! 4 ROUTE_TRIPS varint stream. Each route's block (at RouteRec.trips_off,
66//! n_trips entries) is, per trip in start-time order:
67//! uvarint start_delta (Δ from previous trip's start_time,
68//! first = absolute), uvarint profile_id,
69//! uvarint service_idx, uvarint headsign_off.
70//! 5 PROFILES varint stream. Each profile (at PROFILES_IDX[id]) is:
71//! uvarint n, uvarint dwell0, then for k in 1..n
72//! uvarint hop[k], uvarint dwell[k]. Given a trip start
73//! time T: dep[0]=T, arr[0]=T-dwell0, and for k>=1
74//! arr[k]=dep[k-1]+hop[k], dep[k]=arr[k]+dwell[k].
75//! 6 PROFILES_IDX u32[profile_count + 1] byte offsets into PROFILES.
76//! 7 STOP_ROUTES u32[] route indices serving each stop (flattened).
77//! 8 STOP_ROUTES_IDX u32[stop_count + 1] prefix offsets into STOP_ROUTES.
78//! 9 TRANSFERS Transfer[] = { u32 to_stop, u32 secs } footpaths.
79//! 10 TRANSFERS_IDX u32[stop_count + 1] prefix offsets into TRANSFERS.
80//! 11 SERVICES ServiceRec[service_count] = { u8 weekday_mask,
81//! u8[3] _pad, u32 start_date, u32 end_date }.
82//! 12 EXCEPTIONS ExcRec[] = { u32 service_idx, u32 date, u32 added }
83//! (added: 1 = service added on date, 0 = removed).
84//! Sorted by (service_idx, date), one row per pair.
85//! 13 GRID_CELL_IDS u32[grid_cell_count] non-empty cell ids, ascending.
86//! cell_id = row*grid_cols + col, row/col from the header
87//! grid origin + grid_cell_e7.
88//! 14 GRID_CELL_OFF u32[grid_cell_count + 1] prefix offsets into GRID_STOPS.
89//! 15 GRID_STOPS u32[stop_count] stop indices grouped by cell (in the
90//! GRID_CELL_IDS order).
91//! 16 FEEDS FeedRec[feed_count] = { u32 name_off }.
92//! 17 FEED_TZ u32[feed_count] STRINGS offsets holding each feed's IANA
93//! timezone from `agency.txt` (`agency_timezone`, row 0),
94//! or NONE when the feed has no `agency.txt`.
95//! 18 EXCEPTIONS_IDX u32[service_count + 1] prefix offsets into EXCEPTIONS,
96//! so one service's exceptions are a contiguous,
97//! date-ascending range.
98//! 19 STOP_ROUTE_POS u32[] parallel to STOP_ROUTES: the position of that stop
99//! within that route's stop pattern (first occurrence).
100//! 20 SHAPE_COORDS Concatenated polyline blobs. Each blob is `u32
101//! point_count` then, per point, a zigzag-varint lat
102//! delta and lon delta (1e-7 deg, cumulative from zero).
103//! Blobs are self-delimiting and deduplicated, so routes
104//! producing identical geometry share one.
105//! 21 ROUTE_SHAPE_IDX u32[route_count + 1]. For route i, the byte offset of
106//! its blob in SHAPE_COORDS, or NONE when the feed had no
107//! usable shape for it. NOT a prefix sum: offsets repeat
108//! where routes share a blob. The final entry is
109//! SHAPE_COORDS' byte length, which the reader uses as a
110//! bound.
111//! 22 ROUTE_STOP_SHAPE u32[] parallel to ROUTE_STOPS: that pattern stop's
112//! vertex index within its route's shape (NONE when the
113//! route has none). Non-decreasing within a route, so the
114//! device can slice `shape[vertex(board)..=vertex(alight)]`.
115//! 23 FEED_MOTIS_PREFIX u32[feed_count] STRINGS offsets holding each feed's
116//! Transitous id prefix (`us-ca-SF-bayarea`), or NONE when
117//! the build did not know it. Interned, so the prefix costs
118//! one pool entry shared by every stop in that feed.
119//! 24 STOP_GTFS_ID u32[stop_count] STRINGS offsets holding each stop's raw
120//! GTFS `stop_id`. Joined to the prefix with `_` to form a
121//! MOTIS stop id. Kept separate from `StopRec.code_off`,
122//! which falls back to `stop_id` only when `stop_code` is
123//! blank and so cannot be relied on.
124//! 25 ROUTE_TRIP_RECS v6. Fixed-stride TripRec[trip_count] = { u32 start_time,
125//! u32 profile_id, u32 service_idx, u32 headsign_off },
126//! each route's trips contiguous and in start-time order.
127//! The same trips as ROUTE_TRIPS, which is still written:
128//! the device reader's version window accepts packs that
129//! only have the varint stream, so both views ship.
130//! A trip is addressable by index here, which is the point -
131//! the varint stream has to be decoded from a route's first
132//! trip, so a scan that breaks early still paid to decode
133//! every trip of the route before it started.
134//! 26 ROUTE_TRIP_OFF v6. u32[route_count + 1] CSR prefix: route i's trips are
135//! ROUTE_TRIP_RECS[off[i]..off[i+1]]. Disagreeing with
136//! RouteRec.n_trips makes the reader fall back to the
137//! varint stream rather than index past the table.
138//! 27 RAIL_LINES v7. Host-only: every whole, unsimplified rail shape the
139//! basemap's transit layer is drawn from, so `transit_shapes`
140//! can rebuild it from the pack alone. Written last and
141//! dropped from the app archive by `mamaps_pack`. See
142//! [`RailLines`].
143
144use crate::gtfs;
145use crate::gtfs::{parse_gtfs_date, Csv, Shape};
146use crate::shapes;
147use std::collections::HashMap;
148use std::io::Write;
149use std::path::Path;
150
151pub const MAGIC: u32 = 0x5452_4958; // "TRIX"
152pub const VERSION: u32 = 7;
153/// Oldest version the device reader still accepts, mirrored from
154/// `maps/src/main/rust/src/transit.rs` so the host reader agrees on the range.
155pub const VERSION_MIN: u32 = 3;
156pub const NONE: u32 = 0xFFFF_FFFF;
157pub const SECTION_COUNT: usize = 28;
158/// Sections in a v6 pack, which has no RAIL_LINES. The host reader still opens one.
159pub const SECTION_COUNT_V6: usize = 27;
160pub const HEADER_LEN: usize = 80;
161
162const MAX_TRANSFER_M: f64 = 400.0;
163const WALK_SPEED_M_S: f64 = 1.33;
164const CELL_DEG: f64 = 0.004; // ~450 m latitude buckets for the transfer grid
165const MAX_TRANSFERS_PER_STOP: usize = 16;
166
167/// Spatial-grid cell size for the on-device nearest/bbox index (degrees).
168/// ~2.2 km at the equator; access/egress (≤1 km) searches ±1 cell.
169const GRID_CELL_DEG: f64 = 0.02;
170
171// --- varint (unsigned LEB128) ---
172
173fn write_uvarint(v: &mut Vec<u8>, mut x: u64) {
174 loop {
175 let b = (x & 0x7f) as u8;
176 x >>= 7;
177 if x != 0 {
178 v.push(b | 0x80);
179 } else {
180 v.push(b);
181 break;
182 }
183 }
184}
185
186/// FNV-1a, 64-bit. Only ever used to *find* dedup candidates, which are then
187/// confirmed byte-for-byte against the buffer that already holds them — so a
188/// collision costs a few duplicated bytes and never a wrong merge.
189fn fnv1a(bytes: &[u8]) -> u64 {
190 fnv1a_mix(0xcbf2_9ce4_8422_2325, bytes)
191}
192
193/// Continue an FNV-1a hash, for keys built from more than one piece.
194fn fnv1a_mix(mut h: u64, bytes: &[u8]) -> u64 {
195 for &b in bytes {
196 h ^= b as u64;
197 h = h.wrapping_mul(0x100_0000_01b3);
198 }
199 h
200}
201
202/// Interning string pool producing byte offsets into the STRINGS section.
203///
204/// The pool does **not** keep a copy of what it interns: `bytes` is the only
205/// copy, and the index is `hash -> offsets`, each candidate confirmed by
206/// comparing it against `bytes`. On a world pack the second copy cost several
207/// gigabytes on its own.
208struct StringPool {
209 bytes: Vec<u8>,
210 by_hash: HashMap<u64, Vec<u32>>,
211 /// Set when the pool would pass the 4 GiB that a u32 STRINGS offset can
212 /// address. Checked once before the pack is assembled: silently wrapping
213 /// here produces a pack the device will happily mmap and mis-read.
214 overflowed: bool,
215}
216
217impl StringPool {
218 fn new() -> StringPool {
219 // Byte 0 is a lone NUL so offset 0 is a valid empty string, keeping
220 // NONE (0xFFFFFFFF) unambiguous.
221 StringPool { bytes: vec![0], by_hash: HashMap::new(), overflowed: false }
222 }
223
224 fn intern(&mut self, s: &str) -> u32 {
225 if s.is_empty() {
226 return NONE;
227 }
228 let h = fnv1a(s.as_bytes());
229 if let Some(off) = self
230 .by_hash
231 .get(&h)
232 .and_then(|offs| offs.iter().copied().find(|&off| self.matches_at(off, s)))
233 {
234 return off;
235 }
236 // `+ 1` for the terminating NUL; the last valid offset must still be a
237 // u32, and NONE is reserved.
238 if self.bytes.len() + s.len() + 1 >= NONE as usize {
239 self.overflowed = true;
240 return NONE;
241 }
242 let off = self.bytes.len() as u32;
243 self.bytes.extend_from_slice(s.as_bytes());
244 self.bytes.push(0);
245 self.by_hash.entry(h).or_default().push(off);
246 off
247 }
248
249 /// Whether the interned string at `off` is exactly `s`. The NUL check is
250 /// what stops `s` matching a prefix of a longer entry.
251 fn matches_at(&self, off: u32, s: &str) -> bool {
252 let start = off as usize;
253 let end = start + s.len();
254 end < self.bytes.len() && self.bytes[end] == 0 && &self.bytes[start..end] == s.as_bytes()
255 }
256}
257
258/// The PROFILES section plus its dedup index: run-time shapes are shared by
259/// every trip that runs them, which is what removed v1's per-trip stop-time
260/// table. Like [`StringPool`], the index is `hash -> ids` and holds no second
261/// copy of the bodies.
262struct ProfileTable {
263 bytes: Vec<u8>,
264 /// Byte offset into `bytes` per profile id.
265 offsets: Vec<u32>,
266 by_hash: HashMap<u64, Vec<u32>>,
267 /// Reused across trips so encoding one does not allocate.
268 scratch: Vec<u8>,
269}
270
271impl ProfileTable {
272 fn new() -> ProfileTable {
273 ProfileTable {
274 bytes: Vec::new(),
275 offsets: Vec::new(),
276 by_hash: HashMap::new(),
277 scratch: Vec::new(),
278 }
279 }
280
281 /// Encode a trip's `(arr, dep)` sequence as a profile body and return its id,
282 /// reusing an identical existing profile.
283 fn intern(&mut self, sts: &[(u32, u32)]) -> Result<u32, String> {
284 let n = sts.len();
285 self.scratch.clear();
286 write_uvarint(&mut self.scratch, n as u64);
287 let (arr0, dep0) = sts[0];
288 write_uvarint(&mut self.scratch, dep0.saturating_sub(arr0) as u64);
289 let mut prev_dep = dep0;
290 for &(arr, dep) in &sts[1..] {
291 write_uvarint(&mut self.scratch, arr.saturating_sub(prev_dep) as u64);
292 write_uvarint(&mut self.scratch, dep.saturating_sub(arr) as u64);
293 prev_dep = dep;
294 }
295 let h = fnv1a(&self.scratch);
296 if let Some(id) = self.by_hash.get(&h).and_then(|ids| {
297 ids.iter().copied().find(|&id| {
298 let start = self.offsets[id as usize] as usize;
299 self.bytes[start..].starts_with(&self.scratch)
300 })
301 }) {
302 return Ok(id);
303 }
304 // PROFILES_IDX entries are u32 byte offsets into PROFILES.
305 let off = u32::try_from(self.bytes.len()).map_err(|_| {
306 "PROFILES exceeded 4 GiB, which a u32 PROFILES_IDX offset cannot address".to_string()
307 })?;
308 let id = self.offsets.len() as u32;
309 self.offsets.push(off);
310 self.bytes.extend_from_slice(&self.scratch);
311 self.by_hash.entry(h).or_default().push(id);
312 Ok(id)
313 }
314}
315
316/// The SHAPE_COORDS section plus its dedup index, so routes producing identical
317/// geometry share one blob. Blobs are self-delimiting, so a candidate is
318/// confirmed by a prefix comparison at its offset.
319struct ShapeBlobs {
320 bytes: Vec<u8>,
321 by_hash: HashMap<u64, Vec<u32>>,
322}
323
324impl ShapeBlobs {
325 fn new() -> ShapeBlobs {
326 ShapeBlobs { bytes: Vec::new(), by_hash: HashMap::new() }
327 }
328
329 fn intern(&mut self, blob: &[u8]) -> Result<u32, String> {
330 let h = fnv1a(blob);
331 if let Some(off) = self.by_hash.get(&h).and_then(|offs| {
332 offs.iter().copied().find(|&off| self.bytes[off as usize..].starts_with(blob))
333 }) {
334 return Ok(off);
335 }
336 // ROUTE_SHAPE_IDX holds u32 byte offsets and reserves NONE, so the
337 // section itself has to stay below that.
338 if self.bytes.len() >= NONE as usize {
339 return Err("SHAPE_COORDS exceeded the 4 GiB a u32 ROUTE_SHAPE_IDX offset can address"
340 .to_string());
341 }
342 let off = self.bytes.len() as u32;
343 self.bytes.extend_from_slice(blob);
344 self.by_hash.entry(h).or_default().push(off);
345 Ok(off)
346 }
347}
348
349/// One `stop_times.txt` row reduced to what the index needs: 24 bytes, against
350/// the ~400 a `Csv` row costs and the 40 an `Option<f64>` dist and `i64`
351/// sequence used to. This is the hot struct — a world corpus has billions.
352struct StopTime {
353 seq: u32,
354 stop_idx: u32,
355 arr: u32,
356 dep: u32,
357 /// `shape_dist_traveled` in the feed's own units, or NaN when absent. An
358 /// ordering key only; see [`Shape::dist`] for why it is still `f64`.
359 dist: f64,
360}
361
362/// One input GTFS feed (already parsed). Multiple feeds merge into one pack;
363/// their GTFS ids are namespaced by feed so they never collide.
364///
365/// Holding `stop_times.txt` as a [`Csv`] costs roughly 10x the bytes of the file,
366/// so the host tool uses [`FeedDir`] instead and lets the builder stream it.
367pub struct FeedInput<'a> {
368 pub name: String,
369 /// Transitous id prefix for this feed (`us-ca-SF-bayarea`), used to compose
370 /// MOTIS stop ids on device. Empty when the caller does not know it (the
371 /// world build mangles feed names), which writes NONE and makes the device
372 /// accessor return `None`.
373 pub motis_prefix: String,
374 pub stops: &'a Csv,
375 pub routes: &'a Csv,
376 pub trips: &'a Csv,
377 pub stop_times: &'a Csv,
378 pub calendar: Option<&'a Csv>,
379 pub calendar_dates: Option<&'a Csv>,
380 /// `agency.txt`, read only for `agency_timezone`. GTFS permits several
381 /// agencies per feed; we take row 0 and assume one timezone per feed.
382 pub agency: Option<&'a Csv>,
383 /// `shapes.txt` keyed by `shape_id`. Optional: without it every route in this
384 /// feed falls back to stop-to-stop ride geometry on device.
385 pub shapes: Option<&'a HashMap<String, Shape>>,
386}
387
388/// The same feed, but with `stop_times.txt` left on disk to be streamed out of
389/// `dir` rather than parsed into a [`Csv`] first. Everything else is small enough
390/// to hold.
391pub struct FeedDir<'a> {
392 pub name: String,
393 pub motis_prefix: String,
394 /// The unzipped GTFS directory holding `stop_times.txt`.
395 pub dir: &'a Path,
396 pub stops: &'a Csv,
397 pub routes: &'a Csv,
398 pub trips: &'a Csv,
399 pub calendar: Option<&'a Csv>,
400 pub calendar_dates: Option<&'a Csv>,
401 pub agency: Option<&'a Csv>,
402 pub shapes: Option<&'a HashMap<String, Shape>>,
403}
404
405/// Where a feed's `stop_times.txt` comes from.
406enum StopTimesSource<'a> {
407 Table(&'a Csv),
408 Dir(&'a Path),
409}
410
411/// The parts of a feed [`IndexBuilder::add`] needs, from either input form.
412struct FeedView<'a> {
413 name: &'a str,
414 motis_prefix: &'a str,
415 stops: &'a Csv,
416 routes: &'a Csv,
417 trips: &'a Csv,
418 calendar: Option<&'a Csv>,
419 calendar_dates: Option<&'a Csv>,
420 agency: Option<&'a Csv>,
421 shapes: Option<&'a HashMap<String, Shape>>,
422 stop_times: StopTimesSource<'a>,
423}
424
425impl<'a> From<&'a FeedInput<'a>> for FeedView<'a> {
426 fn from(f: &'a FeedInput<'a>) -> FeedView<'a> {
427 FeedView {
428 name: &f.name,
429 motis_prefix: &f.motis_prefix,
430 stops: f.stops,
431 routes: f.routes,
432 trips: f.trips,
433 calendar: f.calendar,
434 calendar_dates: f.calendar_dates,
435 agency: f.agency,
436 shapes: f.shapes,
437 stop_times: StopTimesSource::Table(f.stop_times),
438 }
439 }
440}
441
442include!("index_part1.rs");
443include!("index_part2.rs");
444include!("index_part3.rs");
445include!("index_part3_s1.rs");
446include!("index_part4.rs");
447include!("index_part5.rs");
448include!("index_part6.rs");
449include!("index_part7.rs");