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

Modern-Apps.git / scripts / maps / gtfs_ingest / README.md

README.md18.5 KiBRenderedCodeRaw
1# gtfs_ingest (P11a / world pack)
2
3Host-side Rust build tool that converts one or more **GTFS** feeds into a single
4compact **on-device transit index** (`<pack>.transit`, format **TRX2**) for the
5Maps offline packs. It is the ingest half of offline public-transit routing; the
6on-device planner that consumes the index is
7`maps/src/main/rust/src/transit.rs` (P11b).
8
9Merging many feeds into one pack is what makes a single global **`world.transit`**
10feasible — the app downloads it once on open (mirroring the single global road
11graph). See `scripts/maps/build_world_transit.ps1` for the world pipeline.
12
13## Why Rust + directory input
14
15- **Rust-first (LANGUAGE RULE):** GTFS ingest is done in Rust, not Python. No
16 `normalize_gtfs.py`. Its sibling host tool, `scripts/maps/osm_ingest`, follows
17 the same rule for the OSM side — it replaced the libosmium `generator.cpp` /
18 `poi_extract.cpp`, so no hand-written C++ is left in the Maps pipeline and both
19 tools run on Windows.
20- **Zero dependencies / offline builds:** the tool is `std`-only and detached
21 from the repo-root Cargo workspace (see the empty `[workspace]` in
22 `Cargo.toml`), so `cargo build` here resolves without the network and without
23 the Android/aarch64 toolchain or the app crates' lints.
24- **Unzipped input:** it reads *unzipped* GTFS directories rather than `.zip`s,
25 which avoids pulling in a DEFLATE crate. Unzipping is a one-line pre-step.
26
27## Usage
28
29```sh
30# Fetch region feeds (Transitous registry points at each agency's GTFS zip):
31# https://github.com/public-transport/transitous -> feeds/*.json
32unzip sf_bay_511.zip -d /tmp/sf_bay
33unzip ac_transit.zip -d /tmp/ac
34
35# Build ONE merged index + manifest from several feeds:
36cargo run --release -- /path/to/out world sf_bay=/tmp/sf_bay actransit=/tmp/ac
37# -> /path/to/out/world.transit (mmap'd on device)
38# -> /path/to/out/world.transit.json (manifest: counts, bbox, section sizes)
39
40# …or list feeds in a manifest file (one `feed_name=dir` per line):
41cargo run --release -- /path/to/out world --manifest feeds.manifest
42```
43
44Arg order is `gtfs_ingest <out_dir> <pack_name> <feed>...`, where each `<feed>`
45is `feed_name=gtfs_dir` (or just `gtfs_dir`, whose base name becomes the feed
46name). Feed names are the per-agency provenance stored per route and surfaced on
47device (used for route colours via `GTFSProvider`).
48
49## Output
50
51- `<pack>.transit` — the binary TRX2 index. On-disk layout is documented at the
52 top of `src/index.rs` and **must stay in sync** with `transit.rs`. It holds an
53 interned string pool, stops, a FEEDS table (with each feed's IANA timezone from
54 `agency.txt`), RAPTOR routes (trips grouped by identical stop pattern) with
55 **varint-packed per-route trip arrays**, **deduplicated timetable profiles**
56 (per-stop run-time shape, varint-delta encoded), a stop→routes index (with each
57 stop's position in the pattern), footpath transfers (≤400 m, cross-feed), a
58 **sparse spatial grid** (CSR by cell for O(cell) nearest/bbox), and calendar
59 service masks + a CSR-indexed, date-sorted `calendar_dates` exception table, and
60 **`shapes.txt` ride geometry** fitted to each route's stop pattern.
61- `<pack>.transit.json` — a small manifest with counts, bbox and a **per-section
62 byte breakdown** so the compression win (profiles vs the old per-trip
63 stop-times) is visible, plus how many routes got ride geometry.
64 `format_version` is 6.
65
66## Why TRX2 (v2)
67
68v1 stored `(arr,dep)` u32 per stop *per trip* (8 B) and referenced them via a
69`u32 first_stoptime`, so a worldwide pack was ~10–20 GB and near the 4.29 B
70stop-time ceiling. v2 factors each trip into `{ start_time, profile_id }` and
71shares one **profile** (varint hop+dwell offsets) across every trip with the
72same run-time shape — killing both the per-trip stop-time table and the ceiling.
73Section offsets in the directory are u64 so the file may exceed 4 GB. Expected
74world size drops to roughly **~1.5–4 GB** while staying on u32 indices.
75
76## What v3 added
77
78v3 appends three sections after v2's section 16, so sections 0–16 are
79byte-identical and only `VERSION` (3) and `SECTION_COUNT` (20) change. All three
80exist so the on-device planner can be *correct* and *fast* on a world pack:
81
82| Section | Payload | Why |
83|---|---|---|
84| 17 `FEED_TZ` | `u32[feed_count]` string offsets | Each feed's `agency_timezone`. The planner routes in the **feed's** local time; without this a world-merged pack is queried in the device's zone and picks trips hours off. |
85| 18 `EXCEPTIONS_IDX` | `u32[service_count + 1]` CSR offsets | `EXCEPTIONS` is now sorted by `(service, date)` with one row per pair, so a `calendar_dates` lookup is a range + binary search instead of a full scan of the pack **per trip**. |
86| 19 `STOP_ROUTE_POS` | `u32[]` parallel to `STOP_ROUTES` | A stop's position in each serving route's pattern, replacing a linear scan of the pattern in the RAPTOR hot loop. |
87
88The device reader accepts **v3 and v4**, so an app update and a pack rebuild can
89land in either order without offline transit silently degrading to the online
90planner in between. A version it does not know is cleanly rejected
91(`TransitIndex::load` returns `None`) and the app falls back to the online MOTIS
92planner rather than misreading the file.
93
94## What v4 added
95
96v4 appends three more sections, so sections 0–19 are byte-identical to v3 and
97only `VERSION` (4) and `SECTION_COUNT` (23) change. They carry GTFS
98`shapes.txt` geometry, so a ride leg draws the path the vehicle actually takes
99instead of a line through its stops — which also makes its reported distance
100truthful, where stop-to-stop under-reports every ride.
101
102| Section | Payload | Why |
103|---|---|---|
104| 20 `SHAPE_COORDS` | Concatenated blobs: `u32 point_count` then zigzag-varint delta lat/lon | The polylines. Zigzag varints, **not** the `i16` deltas `graph.rs` uses for road geometry: consecutive `shapes.txt` points are routinely far enough apart (highway running) to overflow an `i16` at 1e-7°. |
105| 21 `ROUTE_SHAPE_IDX` | `u32[route_count + 1]` byte offsets | Route → blob. `NONE` means "no shape", and the last entry bounds the section. **Not** a prefix sum: routes producing identical geometry share one blob. |
106| 22 `ROUTE_STOP_SHAPE` | `u32[]` parallel to `ROUTE_STOPS` | Each pattern stop's vertex index in its route's shape, non-decreasing, so the device slices `shape[vertex(board)..=vertex(alight)]`. |
107
108Fitting a shape to a pattern (`src/shapes.rs`):
109
1101. Take the **modal `shape_id`** across the pattern's trips. Direction
111 differences already form distinct patterns, so what lands here is versioned
112 shapes or rare express variants; the modal one keeps the common case exact.
1132. **Project each stop onto the shape and insert that projection as a vertex**,
114 so a boarded span begins and ends exactly on its stop.
1153. **Simplify (Douglas–Peucker, ~2.5 m) only between those pinned vertices**, so
116 it can never move or drop one, and trim to `[first stop, last stop]`.
1174. `shape_dist_traveled` is used when present on **both** `shapes.txt` and
118 `stop_times.txt`, strictly as a monotone *ordering* key — it disambiguates a
119 route that passes one stop twice. Its units are feed-defined (km, mi, ft) and
120 are never read as metres. Otherwise stops are projected by nearest point,
121 forced monotonically non-decreasing.
1225. **Validate, then fall back.** A stop further than ~150 m from the shape drops
123 the whole fit, and the route stores `NONE` so the device draws stop-to-stop as
124 before. The tool reports per-run counts of shaped routes, validation drops,
125 and routes whose trips disagreed on `shape_id`.
126
127The Douglas–Peucker tolerance is the lever on pack size: shapes dominate a v4
128pack. `shapes.txt` and `stop_times.txt` are the two largest files in a feed, so
129both are streamed (`gtfs::read_shapes`, `gtfs::stream_stop_times`) rather than
130parsed into a `Csv` of `String`s — see *Build-time memory* below.
131
132## What v6 added
133
134v6 appends two more sections, so sections 0-24 are byte-identical to v5 and only
135`VERSION` (6) and `SECTION_COUNT` (27) change. They make a route's trips
136**randomly addressable**.
137
138| Section | Payload | Why |
139|---|---|---|
140| 25 `ROUTE_TRIP_RECS` | Fixed-stride `TripRec[trip_count]` = `{ u32 start_time, profile_id, service_idx, headsign_off }`, each route's trips contiguous and start-time ordered | A trip is an index, so a scan reads only the trips it looks at. |
141| 26 `ROUTE_TRIP_OFF` | `u32[route_count + 1]` CSR prefix | Route *i*'s trips are `ROUTE_TRIP_RECS[off[i]..off[i+1]]`. |
142
143`ROUTE_TRIPS` is still written, unchanged. Both views ship because the device
144reader's `VERSION_MIN` is still 3: a pack rebuild and an app update can land in
145either order, and a reader that finds no table falls back to the varint stream.
146The two are written in the same loop, and a test asserts they decode to the same
147trips, because a writer emitting two disagreeing views is exactly the failure the
148device would inherit silently.
149
150**What this buys, precisely.** `earliest_trip` scans a route's trips in start-time
151order and breaks as soon as `start_time` passes the bound it can still improve on.
152Reading the varint stream defeated that: `route_trips` decoded and heap-allocated
153*every* trip of the route before the scan began - per route per RAPTOR round, again
154per leg, and again per departure board, over 28.4 M trips in a planetary pack. With
155the table the break actually saves the work it was written to save.
156
157**What it does not buy: a lower bound.** A trip's departure from stop position `p`
158is `start_time + dep_rel[p]`, and `dep_rel` grows along the route, so a trip
159starting well before the passenger is ready can still depart after them. Only the
160upper bound is sound, which is why the reader exposes indexed access and not a
161binary search over start times.
162
163The cost is size: 16 bytes per trip against roughly 11.8 for the varint encoding,
164so about +120 MB on a planetary pack that already carries 335 MB of `ROUTE_TRIPS`.
165Dropping the varint stream once `VERSION_MIN` moves past 5 recovers all of it.
166
167## Build-time memory
168
169A world build is bound by RAM, not by pack size. The pack is ~1.5–4 GB, but the
170*input* representation used to cost far more: parsing every feed up front held
171each one's `Csv` for the whole run, and a `Csv` row is a `Vec<String>` — roughly
17210x the bytes of the CSV text it came from. Measured at 6.19 GB of RSS per 1 GB of
173GTFS, which projects to ~400 GB for 1272 feeds and OOMs at feed 302.
174
175The builder is incremental instead. `index::IndexBuilder::add_feed_dir` both
176ingests a feed and **finalizes** it — routes, trips, profiles, shapes and
177stop→route lists all become section bytes before the next feed is read — so the
178only things that cross a feed boundary are the sections themselves (which *are*
179the pack), the string pool, and `stop_lat`/`stop_lon` (8 B a stop, needed because
180the transfer grid, the spatial grid and the bbox are global and `grid_cols` is not
181known until the last feed is in). Peak is therefore *pack size + largest single
182feed*, not the sum of all feeds:
183
184| | before | after |
185|---|---|---|
186| 100 feeds (346k stops, 1.24 M trips) | 1.85 GB, 147 s | **0.66 GB, 128 s** |
187| `great_britain` alone (9.5 GB of GTFS, 5.8 GB of it `stop_times.txt`) | ~60 GB (projected) | **1.93 GB, 250 s** |
188
189Four things got it there, all verified with `transit_dump` rather than by
190byte-diffing:
191
1921. **`stop_times.txt` is streamed**, not parsed into a `Csv` — it is 5.8 GB of the
193 9.5 GB `great_britain` feed and every row reduces to a 24-byte `StopTime`. The
194 streaming path has to agree with the `Csv` path *exactly*, which is subtler
195 than it looks: ids are joined against `trips.txt`/`stops.txt` untrimmed, `\r`
196 is swallowed anywhere, a repeated column name resolves to its last occurrence,
197 and a quoted field may contain a newline. `gtfs.rs`'s tests pin all four —
198 trimming ids alone silently dropped 1562 trips from one feed.
1992. **Dedup maps hold no second copy.** `StringPool`, the profile table and the
200 shape-blob table are keyed by hash and confirm each candidate against the
201 append-only buffer that already holds the bytes. A collision can only fail to
202 dedup, never merge two different values. `pattern_key_to_route` is the
203 exception and compares `(route_id, stop_pattern)` in full — a false match there
204 would fuse two patterns into one route, which is wrong departures rather than
205 wasted bytes.
2063. **Both grids are flat sorted vectors**, looked up by `partition_point`, instead
207 of `HashMap`s holding millions of tiny `Vec`s. Sorting the spatial grid by
208 `(cell_id, stop)` is also exactly the order the device's binary search needs.
2094. **The pack streams out** through a `BufWriter`: every section length is known
210 by `finish_to`, so the directory is computed up front and the pack is never
211 concatenated into one giant `Vec` first.
212
213`shape_dist_traveled` stays `f64` throughout. It is only an ordering key, so `f32`
214looks free — but feeds give it 8+ significant digits, and at that width `f32`
215collapses shape points millimetres apart and flips which segment a stop brackets
216onto. Measured on 100 feeds it changed the fitted polyline of 0.3% of routes to
217save 4 bytes a row, which is the wrong trade.
218
219## Testing
220
221`cargo test` runs a round-trip harness (`src/index.rs` `#[cfg(test)]`) that
222builds a two-feed index and decodes the blob back, asserting profile encoding
223reconstructs the original arr/dep times, feeds/ids are namespaced without
224collision, the grid nearest-stop lookup is correct, per-feed timezones survive,
225exceptions are date-sorted and collapsed to one row per `(service, date)`, and
226`STOP_ROUTE_POS` agrees with `ROUTE_STOPS`. The v4 cases cover
227`shape_dist_traveled` on both files, shapes without it, no `shapes.txt` at all, a
228mismatched shape that must fail validation, a pattern whose trips carry two
229`shape_id`s, deltas that would overflow an `i16`, and a shape shared by two
230routes — asserting monotone, in-bounds vertex indices in every case.
231
232The reader half is tested independently in
233`maps/src/main/rust/src/transit.rs`, whose `#[cfg(test)]` module hand-builds TRX2
234blobs and plans over them. The two crates cannot link to each other, so each
235codec is exercised by an independent counterpart — which is what catches drift in
236a format whose spec lives in a doc comment.
237
238Because both halves are *reimplementations*, they could also drift together. So
239`test_fixtures/mini_feed/` (a three-stop feed with a shape) is ingested into
240`maps/src/main/rust/test_fixtures/mini.transit`, committed, and read back by
241`transit.rs::reads_a_pack_written_by_the_real_ingester`. That pins the two crates
242to each other rather than to a shared assumption. Regenerate it after any format
243change, from the repo root:
244
245```sh
246cargo run --release --manifest-path scripts/maps/gtfs_ingest/Cargo.toml -- \
247 maps/src/main/rust/test_fixtures mini \
248 mini=scripts/maps/gtfs_ingest/test_fixtures/mini_feed
249rm maps/src/main/rust/test_fixtures/mini.transit.json
250```
251
252The bytes are a captured artefact, not a reproducible one — trips are grouped out
253of a `HashMap`, so route order, profile ids and service indices all vary between
254runs. The device-side assertions are semantic for that reason, and so is
255`transit_dump`:
256
257```sh
258cargo run --release --manifest-path scripts/maps/gtfs_ingest/Cargo.toml \
259 --bin transit_dump -- world.transit dump.txt
260```
261
262It renders a pack as sort-stable text — header counts, bbox, grid, then per feed
263per route (sorted) every trip with its profile expanded back to absolute
264`(arr, dep)`, then stops with their routes and footpaths, services keyed by their
265calendar rather than their index, and the grid cells. Two builds of the same
266corpus produce byte-different packs but identical dumps, so a refactor is verified
267by dumping before, dumping after, and diffing. **Do not byte-diff packs.**
268`src/reader.rs` is the decoder it uses — deliberately a second implementation of
269the device reader, not shared code.
270
271A world dump would be ~10 GB of text, so a big pack is spot-checked instead:
272
273```sh
274transit_dump --at 37.7749,-122.4194 world.transit
275```
276
277which prints the bbox, the nearest stop to that coordinate (with how far away it
278actually is — `nearest` searches ±1 grid cell exactly as the device does, so it
279always answers with *something*), every route serving it with its first and last
280departure *from that stop*, and the footpaths leading away — flagging the ones
281that reach a different feed's stops, since cross-feed transfers working is the
282whole point of merging feeds into one pack.
283
284## Building the world pack
285
286`scripts/maps/build_world_transit.ps1` builds the single global pack by mirroring
287Transitous' own published GTFS directory and merging every zip into one TRIX pack,
288then proves the pack's RAIL_LINES reproduce the feeds' transit layer before it
289replaces `inputs/world.transit`:
290
291```powershell
292.\scripts\maps\build_world_transit.ps1 # mirror, unzip, merge, verify, install
293.\scripts\maps\build_world_transit.ps1 -SkipMirror # reuse the zips already on disk
294```
295
296`build_graph.ps1` reads only the pack, so the work dir this leaves behind
297(`scripts/maps/world_transit_work`, ~80 GB) can be deleted afterwards.
298
299It mirrors rather than resolving the Transitous registry feed-by-feed because
300the upstreams are third parties in every state of disrepair: 401s, 403s, 404s
301from dead rehosts, hostname-mismatched TLS certs, broken pipes. Transitous
302already solves that problem — including the API keys we do not have — so the
303script takes its output instead of repeating its work badly. Each zip's feed id
304(`<region>-<Source>`) becomes the MOTIS id namespace, so live delays can be
305matched to a stop.
306
307**The app enumerates every `*.transit` file in its external files dir and
308concatenates their departure boards without deduplicating**, so ship exactly one
309pack. Replace `world.transit` rather than adding a second file beside it; a backup
310must not end in `.transit` or it will be loaded too.
311
312## Known limitations
313
314- Transfers use a straight-line ≤400 m footpath heuristic (not the road graph);
315 merging feeds makes these cross-agency for free. The *drawn* walk legs are
316 re-routed along the road graph on device, but their timings stay as RAPTOR
317 planned them, so a shown ETA is slightly optimistic.
318- A route whose trips genuinely use different roads draws whichever the modal
319 `shape_id` describes. Stops, timings and transfers stay correct.
320- A feed with no `shapes.txt`, or a route whose shape fails validation, draws its
321 ride legs stop-to-stop as before.
322- GTFS permits several agencies per feed; `FEED_TZ` takes row 0 of `agency.txt`
323 and assumes one timezone per feed. A feed with no `agency.txt` gets no
324 timezone, and the device falls back to its own zone (the tool warns).
325- A journey spanning two timezones is planned entirely in the origin feed's zone.