Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / gtfs_ingest / README.md
| 1 | # gtfs_ingest (P11a / world pack) |
| 2 | |
| 3 | Host-side Rust build tool that converts one or more **GTFS** feeds into a single |
| 4 | compact **on-device transit index** (`<pack>.transit`, format **TRX2**) for the |
| 5 | Maps offline packs. It is the ingest half of offline public-transit routing; the |
| 6 | on-device planner that consumes the index is |
| 7 | `maps/src/main/rust/src/transit.rs` (P11b). |
| 8 | |
| 9 | Merging many feeds into one pack is what makes a single global **`world.transit`** |
| 10 | feasible — the app downloads it once on open (mirroring the single global road |
| 11 | graph). 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 |
| 32 | unzip sf_bay_511.zip -d /tmp/sf_bay |
| 33 | unzip ac_transit.zip -d /tmp/ac |
| 34 | |
| 35 | # Build ONE merged index + manifest from several feeds: |
| 36 | cargo 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): |
| 41 | cargo run --release -- /path/to/out world --manifest feeds.manifest |
| 42 | ``` |
| 43 | |
| 44 | Arg order is `gtfs_ingest <out_dir> <pack_name> <feed>...`, where each `<feed>` |
| 45 | is `feed_name=gtfs_dir` (or just `gtfs_dir`, whose base name becomes the feed |
| 46 | name). Feed names are the per-agency provenance stored per route and surfaced on |
| 47 | device (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 | |
| 68 | v1 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 |
| 70 | stop-time ceiling. v2 factors each trip into `{ start_time, profile_id }` and |
| 71 | shares one **profile** (varint hop+dwell offsets) across every trip with the |
| 72 | same run-time shape — killing both the per-trip stop-time table and the ceiling. |
| 73 | Section offsets in the directory are u64 so the file may exceed 4 GB. Expected |
| 74 | world size drops to roughly **~1.5–4 GB** while staying on u32 indices. |
| 75 | |
| 76 | ## What v3 added |
| 77 | |
| 78 | v3 appends three sections after v2's section 16, so sections 0–16 are |
| 79 | byte-identical and only `VERSION` (3) and `SECTION_COUNT` (20) change. All three |
| 80 | exist 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 | |
| 88 | The device reader accepts **v3 and v4**, so an app update and a pack rebuild can |
| 89 | land in either order without offline transit silently degrading to the online |
| 90 | planner 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 |
| 92 | planner rather than misreading the file. |
| 93 | |
| 94 | ## What v4 added |
| 95 | |
| 96 | v4 appends three more sections, so sections 0–19 are byte-identical to v3 and |
| 97 | only `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 |
| 99 | instead of a line through its stops — which also makes its reported distance |
| 100 | truthful, 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 | |
| 108 | Fitting a shape to a pattern (`src/shapes.rs`): |
| 109 | |
| 110 | 1. 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. |
| 113 | 2. **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. |
| 115 | 3. **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]`. |
| 117 | 4. `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. |
| 122 | 5. **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 | |
| 127 | The Douglas–Peucker tolerance is the lever on pack size: shapes dominate a v4 |
| 128 | pack. `shapes.txt` and `stop_times.txt` are the two largest files in a feed, so |
| 129 | both are streamed (`gtfs::read_shapes`, `gtfs::stream_stop_times`) rather than |
| 130 | parsed into a `Csv` of `String`s — see *Build-time memory* below. |
| 131 | |
| 132 | ## What v6 added |
| 133 | |
| 134 | v6 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 |
| 144 | reader's `VERSION_MIN` is still 3: a pack rebuild and an app update can land in |
| 145 | either order, and a reader that finds no table falls back to the varint stream. |
| 146 | The two are written in the same loop, and a test asserts they decode to the same |
| 147 | trips, because a writer emitting two disagreeing views is exactly the failure the |
| 148 | device would inherit silently. |
| 149 | |
| 150 | **What this buys, precisely.** `earliest_trip` scans a route's trips in start-time |
| 151 | order and breaks as soon as `start_time` passes the bound it can still improve on. |
| 152 | Reading 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 |
| 154 | per leg, and again per departure board, over 28.4 M trips in a planetary pack. With |
| 155 | the 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` |
| 158 | is `start_time + dep_rel[p]`, and `dep_rel` grows along the route, so a trip |
| 159 | starting well before the passenger is ready can still depart after them. Only the |
| 160 | upper bound is sound, which is why the reader exposes indexed access and not a |
| 161 | binary search over start times. |
| 162 | |
| 163 | The cost is size: 16 bytes per trip against roughly 11.8 for the varint encoding, |
| 164 | so about +120 MB on a planetary pack that already carries 335 MB of `ROUTE_TRIPS`. |
| 165 | Dropping the varint stream once `VERSION_MIN` moves past 5 recovers all of it. |
| 166 | |
| 167 | ## Build-time memory |
| 168 | |
| 169 | A 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 |
| 171 | each one's `Csv` for the whole run, and a `Csv` row is a `Vec<String>` — roughly |
| 172 | 10x the bytes of the CSV text it came from. Measured at 6.19 GB of RSS per 1 GB of |
| 173 | GTFS, which projects to ~400 GB for 1272 feeds and OOMs at feed 302. |
| 174 | |
| 175 | The builder is incremental instead. `index::IndexBuilder::add_feed_dir` both |
| 176 | ingests a feed and **finalizes** it — routes, trips, profiles, shapes and |
| 177 | stop→route lists all become section bytes before the next feed is read — so the |
| 178 | only things that cross a feed boundary are the sections themselves (which *are* |
| 179 | the pack), the string pool, and `stop_lat`/`stop_lon` (8 B a stop, needed because |
| 180 | the transfer grid, the spatial grid and the bbox are global and `grid_cols` is not |
| 181 | known until the last feed is in). Peak is therefore *pack size + largest single |
| 182 | feed*, 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 | |
| 189 | Four things got it there, all verified with `transit_dump` rather than by |
| 190 | byte-diffing: |
| 191 | |
| 192 | 1. **`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. |
| 199 | 2. **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. |
| 206 | 3. **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. |
| 209 | 4. **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` |
| 214 | looks free — but feeds give it 8+ significant digits, and at that width `f32` |
| 215 | collapses shape points millimetres apart and flips which segment a stop brackets |
| 216 | onto. Measured on 100 feeds it changed the fitted polyline of 0.3% of routes to |
| 217 | save 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 |
| 222 | builds a two-feed index and decodes the blob back, asserting profile encoding |
| 223 | reconstructs the original arr/dep times, feeds/ids are namespaced without |
| 224 | collision, the grid nearest-stop lookup is correct, per-feed timezones survive, |
| 225 | exceptions 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 |
| 228 | mismatched 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 |
| 230 | routes — asserting monotone, in-bounds vertex indices in every case. |
| 231 | |
| 232 | The reader half is tested independently in |
| 233 | `maps/src/main/rust/src/transit.rs`, whose `#[cfg(test)]` module hand-builds TRX2 |
| 234 | blobs and plans over them. The two crates cannot link to each other, so each |
| 235 | codec is exercised by an independent counterpart — which is what catches drift in |
| 236 | a format whose spec lives in a doc comment. |
| 237 | |
| 238 | Because 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 |
| 242 | to each other rather than to a shared assumption. Regenerate it after any format |
| 243 | change, from the repo root: |
| 244 | |
| 245 | ```sh |
| 246 | cargo 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 |
| 249 | rm maps/src/main/rust/test_fixtures/mini.transit.json |
| 250 | ``` |
| 251 | |
| 252 | The bytes are a captured artefact, not a reproducible one — trips are grouped out |
| 253 | of a `HashMap`, so route order, profile ids and service indices all vary between |
| 254 | runs. The device-side assertions are semantic for that reason, and so is |
| 255 | `transit_dump`: |
| 256 | |
| 257 | ```sh |
| 258 | cargo run --release --manifest-path scripts/maps/gtfs_ingest/Cargo.toml \ |
| 259 | --bin transit_dump -- world.transit dump.txt |
| 260 | ``` |
| 261 | |
| 262 | It renders a pack as sort-stable text — header counts, bbox, grid, then per feed |
| 263 | per 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 |
| 265 | calendar rather than their index, and the grid cells. Two builds of the same |
| 266 | corpus produce byte-different packs but identical dumps, so a refactor is verified |
| 267 | by 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 |
| 269 | the device reader, not shared code. |
| 270 | |
| 271 | A world dump would be ~10 GB of text, so a big pack is spot-checked instead: |
| 272 | |
| 273 | ```sh |
| 274 | transit_dump --at 37.7749,-122.4194 world.transit |
| 275 | ``` |
| 276 | |
| 277 | which prints the bbox, the nearest stop to that coordinate (with how far away it |
| 278 | actually is — `nearest` searches ±1 grid cell exactly as the device does, so it |
| 279 | always answers with *something*), every route serving it with its first and last |
| 280 | departure *from that stop*, and the footpaths leading away — flagging the ones |
| 281 | that reach a different feed's stops, since cross-feed transfers working is the |
| 282 | whole 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 |
| 287 | Transitous' own published GTFS directory and merging every zip into one TRIX pack, |
| 288 | then proves the pack's RAIL_LINES reproduce the feeds' transit layer before it |
| 289 | replaces `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 | |
| 299 | It mirrors rather than resolving the Transitous registry feed-by-feed because |
| 300 | the upstreams are third parties in every state of disrepair: 401s, 403s, 404s |
| 301 | from dead rehosts, hostname-mismatched TLS certs, broken pipes. Transitous |
| 302 | already solves that problem — including the API keys we do not have — so the |
| 303 | script 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 |
| 305 | matched to a stop. |
| 306 | |
| 307 | **The app enumerates every `*.transit` file in its external files dir and |
| 308 | concatenates their departure boards without deduplicating**, so ship exactly one |
| 309 | pack. Replace `world.transit` rather than adding a second file beside it; a backup |
| 310 | must 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. |