maps P11a: Rust GTFS ingest host tool -> compact on-device transit index
- Commit
de742b64407e0b40f67d05f072795c2163c05f8d- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-17 01:14 UTC (3 months ago)
- Parents
03b33ea
Std-only, workspace-detached cargo bin under scripts/maps/gtfs_ingest that reads an unzipped region GTFS feed and emits a compact .transit index + JSON manifest for the offline packs. Honors the Rust-first language rule (no normalize_gtfs.py). On-disk format documented in src/index.rs; consumed on-device by transit.rs (P11b).
Diff
scripts/maps/P11_OFFLINE_TRANSIT_SPIKE.md
diff --git a/scripts/maps/P11_OFFLINE_TRANSIT_SPIKE.md b/scripts/maps/P11_OFFLINE_TRANSIT_SPIKE.mdnew file mode 100644index 0000000000..ad3313f5f0--- /dev/null+++ b/scripts/maps/P11_OFFLINE_TRANSIT_SPIKE.md@@ -0,0 +1,308 @@+# P11 — Offline public-transit routing: feasibility spike++**Status:** spike / report for lead review. **No app behavior changed.** No large+artifacts committed. This document is the deliverable.++**Scope of the spike (from task #144 / `VELA_PORT_PLAN.md` P11):** investigate+offline transit routing from the SAME Transitous/GTFS data as the P10 boards —+ingest per-region GTFS into the downloadable offline packs + an on-device+journey planner (Rust preferred; **user rule: NO hand-written C++** for P11).+Report feasibility/size and the C++-vs-Rust/Python generator decision *before*+any build.++**Verdict up front: VIABLE, and better-supported than expected.** The on-device+Rust engine already has a working public-transit mode and an explicit+"which GTFS feeds are present offline" mechanism. The real missing pieces are a+GTFS **ingest/compaction stage** (recommend **Python**, not C++), a proper+per-region **transit index + planner** (recommend **RAPTOR in Rust**), and+**pack download/packaging wiring**. Two pre-existing gaps in the offline-pack+pipeline (below) must be acknowledged because P11 rides on top of them.++---++## 1) How offline packs + routing work today (assessment)++### 1a. The offline-pack generator (`scripts/maps/generator.cpp`, `run_generator.sh`)++`generator.cpp` is a libosmium, multi-threaded C++ tool that turns an `.osm.pbf`+into a routing graph. **Its transit/GTFS scaffolding is already substantial** —+this is the single most important finding for effort estimation:++- **Stop detection** (`:431-445`, `:563-582`): flags `highway=bus_stop|bus_station|tram_stop`,+ `railway=station|halt|tram_stop|stop`, `public_transport=stop_position|platform|station`+ as transit nodes; reads `gtfs:stop_code:<feed>` OSM tags to capture a **feed name**+ and **stop code** per node (`:536-560`).+- **Transit ways** (`is_transit_way`, `:348-355`): `railway=rail|subway|tram|light_rail`,+ `route=bus|train`.+- **Voyage input two ways** (`:388-404`, `:641-688`):+ - if a second CLI arg `transit.csv` is given, it reads pre-expanded connections+ `u_osm, v_osm, line_name, dep(HH:MM:SS), arr(HH:MM:SS)` and groups them into+ per-edge voyage lists;+ - **otherwise it *synthesizes* a 15-minute-frequency timetable** on transit ways+ (`:641-668`) — i.e. today's "transit" is fake, evenly-spaced departures.+- **Transfer edges** (`:747-761`) between co-located road and transit nodes (15 m),+ and **isolated-stop reconnection** (`:774-853`).+- **Output** (`:855-913`): per-zone binaries `nodes_zone_{0..63}.bin`,+ `edges_zone_{0..63}.bin`, `transit_voyages_zone_{0..63}.bin`, plus global+ `road_names.bin`, `metadata.bin` (64×u32 zone node counts). `run_generator.sh`+ compiles it (`g++ -O3`), runs it on `california-latest.osm.pbf` by default, and+ `aws s3 sync`s those `.bin`s to Cloudflare R2.++**What's missing at the generator level:** a real GTFS→timetable path. The+`transit.csv` it consumes is *already-flattened consecutive-stop connections keyed+by OSM node id* — nothing in the repo produces that from GTFS `stop_times/trips/+calendar`, and doing so requires matching GTFS stops → OSM node ids (fragile; only+works where `gtfs:stop_code:*` tags exist). The synthesized 15-min timetable is a+placeholder, not schedule-accurate routing.++### 1b. The on-device engine (`maps/src/main/rust/src/`, `OfflineRouter.kt`)++The Rust router is **already transit-aware** — it is not a plain road router:++- `graph.rs` loads a whole-world graph and, crucially, **`present_feeds: HashSet<String>`**+ — the set of GTFS feeds available offline. It reads `transit_voyages.bin` and+ `transit_attributes.bin` (per-node `stop_code_off`/`feed_name_off`).+- `routing.rs` runs a **time-dependent A\*** with a `PUBLIC_TRANSIT` mode+ (`graph.rs:15`): a second node "state" bit for boarded-vs-not, boarding/transfer+ gating at recognized stops (`:366-401`), and `reconstruct_path` already emits+ transit steps with feed name, boarding stop, alighting stop, stop count, and a+ 6000-unit boarding penalty (`:479-520`).+- `geometry.rs:get_transit_edge_time_10ms` (`:112-190`) does **next-departure+ scheduling** over a voyage list and — key for offline — **degrades gracefully+ when a feed is not present offline**: `if !present_feeds.contains(feed) { return+ unscheduled voyage-0 duration }` (`:132-139`).+- `lib.rs` exposes JNI `init(basePath, presentFeeds[])` + `findRouteNative(...,+ mode, startTime)` and marshals steps into `OfflineRouter.RawStep` → the Kotlin+ `RouteService.Step{..., transitDetails}` the whole P4/P5 UI already renders.+- `OfflineRouter.kt:214-218` computes `presentFeeds` by listing **APK assets** for+ folders containing `routes.txt`, and points the graph loader at+ `getExternalFilesDir(null)`. `GTFSProvider.kt` also reads `routes.txt` **from+ assets** (route colors).++**Implication:** the app already ships GTFS feeds *as bundled APK assets* (whole+feeds) and already has a transit routing mode and UI. The engine was clearly+designed with offline GTFS in mind — `present_feeds` is exactly the "is this+region's transit available offline?" switch P11 needs.++### 1c. The downloadable-pack format + `DownloadedMapsPage`++- `DownloadedMapsPage.kt` renders a 64-cell Morton grid; `ZoneDownloadManager.kt`+ downloads **only** `https://data.vayunmathur.com/zone_{id}.pmtiles` (map tiles)+ and checks/deletes only that file. Download titles use a `"Map Zone $id ($part)"`+ convention — a **multi-part pack scheme that currently has exactly one part+ (`Map`)**.++### 1d. Two pre-existing gaps P11 inherits (flag to lead)++1. **Producer/consumer format mismatch (road graph).** `generator.cpp` writes+ *per-zone* files with a 28-byte `NodeMaster` (inline `spatial_id` + stop/feed+ offsets) and 8-byte voyages. `graph.rs` reads a *single merged* `nodes.bin`+ (16-byte `NodeMaster`, u64 `edge_ptr`, **no** inline stop codes), a separate+ `transit_attributes.bin`, an `intermediate.bin` geometry blob, and 4-byte+ `TransitVoyageCompact`. **No merge/compaction stage exists in the repo** — the+ merged format is a port of an old `native-lib.cpp` toolchain that isn't checked+ in. So `generator.cpp` output cannot currently be loaded by the shipping Rust+ router as-is.+2. **No download path for routing data.** `ZoneDownloadManager` fetches only+ `.pmtiles`; nothing delivers `nodes.bin`/GTFS to `getExternalFilesDir`. Today+ the only transit data the app actually uses offline is the **bundled-asset GTFS+ feeds**.++These are not blockers for P11's *design*, but they mean "add GTFS to the existing+pack pipeline" is really "define a transit pack + its producer + its download+path," partly greenfield rather than a small edit to `generator.cpp`.++---++## 2) GTFS source & size (per-region, offline-bundle)++**Source.** Transitous (the P10 board backend, `TransitousDataSource.kt` →+`api.transitous.org`, MOTIS) is a community aggregator of open GTFS/GTFS-RT. Two+ways to get bundle-able GTFS:++- **Preferred: the Transitous feed registry** (`github.com/public-transport/+ transitous`, `feeds/*.json`) — a per-region index pointing at each agency's+ **official GTFS `.zip`** source URL. Pulling the original per-region zips gives+ clean per-metro granularity and licensing traceability. This is the right+ granularity for offline packs.+- Not recommended as the bundle source: MOTIS itself (online routing engine) or+ the giant nightly *merged* planet feed (wrong granularity, huge).++**Static GTFS is enough** for offline (schedules). GTFS-RT (live delays) stays+online-only via the P10 board.++**Granularity & size (a metro).** GTFS is CSV text dominated by `stop_times.txt`+(80–95% of bytes). Rough per-metro figures:++| Metro (static GTFS) | Raw `.zip` | Unzipped text | `stop_times` share |+|---|---:|---:|---:|+| Mid-size metro | 5–20 MB | 30–120 MB | ~85% |+| Large metro (e.g. SF Bay 511, NYC MTA-ish) | 20–60 MB | 150–500 MB | ~90% |++**Compacted on-device index** (intern strings; per-route trip arrays; delta-coded+`stop_times`; `u16` minutes-since-service-start; service-day bitsets from+`calendar`/`calendar_dates`):++- **~2–15 MB per metro**, dominated by stop_times. This is *small* next to a+ `zone_*.pmtiles` (tens–hundreds of MB) and the road graph. Bundling transit per+ region is cheap.++---++## 3) Algorithm + language decisions++### 3a. RAPTOR vs CSA — **recommend RAPTOR** (CSA acceptable as a simpler v1)++| | CSA (Connection Scan) | RAPTOR |+|---|---|---|+| Data | one array of connections sorted by dep time | routes→trips→stop_times + stop→routes index |+| Impl complexity | **lowest**; the connection array *is* the on-disk pack | moderate |+| Query | linear scan dep→horizon; great per-metro, cache-friendly | round-based (K = #transfers); prunes fast |+| Multi-criteria | awkward | **native** Pareto over (arrival time, #transfers) |+| UX fit | earliest-arrival | earliest-arrival **+ fewest-transfers** options, à la Google/MOTIS |++**Recommendation: RAPTOR**, because the transit UI (`RouteService.Step`,+`transitDetails`, multiple route options) expects transfer-aware alternatives, and+RAPTOR gives the (time, transfers) Pareto set for free. **CSA is a legitimate+lower-effort v1** if we want to validate the data pipeline first — its on-disk form+is trivially the sorted connection array, and it can be swapped for RAPTOR later+behind the same JNI. Either way this **replaces the synthesized-voyage graph-A\***+for transit with a real timetable engine; the road graph A* stays for walking+access/egress/transfer legs.++### 3b. Engine language — **Rust** (`maps/src/main/rust`)++Same crate as the router, behind the existing `OfflineRouter` JNI. Reuses the mmap+loader pattern, the `present_feeds` switch, and the `RawStep`→`RouteService.Step`+marshaling that the UI already consumes. JVM/Kotlin is possible but would duplicate+the JNI boundary and lose the mmap/zero-copy story; Rust is the clear fit and the+user's stated preference.++### 3c. KEY DECISION — extend the C++ generator, or port GTFS ingest to Rust/Python?++**Recommendation: do the GTFS ingest in Python; do NOT add hand-written C++.**++- **Honors the P11 rule** ("NO hand-written C++") and the user's app-code rule+ (this is host build-tooling, but the rule signals "stop growing the C++").+- **GTFS parsing is I/O/string-heavy, not perf-critical** — it runs once on a build+ host, not on device. Python's `csv`/`zipfile` stdlib is ideal.+- **Precedent + test harness already exist:** `scripts/maps/normalize_{safety,+ maxspeed,admin}.py` + `test/test_normalize.py` with fixtures. A+ `normalize_gtfs.py` slots straight in and is unit-testable with a tiny fixture+ feed, exactly like the others.+- **Decouple transit from OSM node ids.** Rather than feeding `generator.cpp`'s+ `transit.csv` (which forces GTFS onto OSM node ids via fragile `gtfs:stop_code`+ matching and still writes the incompatible per-zone format), have Python emit a+ **self-contained per-region transit index** (its own stop ids), and link stops to+ the road graph only for access/egress by nearest-walk-node. This sidesteps the+ §1d pipeline gaps entirely for transit.++**Rejected alternative — extend `generator.cpp`'s existing `transit.csv` path:**+minimal *lines* changed, but (i) requires new C++ (rule violation), (ii) inherits+the OSM-node-id coupling and the broken per-zone→merged format gap, and (iii)+entangles timetable data with the road graph. Higher real risk for less capability.++The C++ generator stays as-is for the **road** graph; GTFS becomes an **additive+Python stage** producing a new pack file consumed by a new Rust transit index.++---++## 4) Size / performance feasibility + blockers++**Size:** +2–15 MB transit index per region — negligible beside the pmtiles/road+packs. **Query:** RAPTOR/CSA on a single metro is interactive — typically+~10–50 ms on device for a handful of rounds; index is mmap'd (few MB resident).+Feasible on-device without trouble.++**Blockers / risks to plan for:**++1. **Pipeline gaps (§1d):** need a real pack-assembly + download path. Transit can+ be a clean new pack part (`zone_*.transit` or feed-keyed), but the road-graph+ producer/consumer mismatch should be settled in parallel or the offline router+ won't load at all on freshly generated data.+2. **Zone (Morton) vs feed (metro) boundaries don't align.** GTFS feeds are+ per-agency/metro; the 64-zone grid is geographic. Package transit **per feed/+ region**, and map "which feeds cover zone N" so downloading a zone can offer its+ transit. Feeds can also straddle zones.+3. **Stop↔walk-graph linking & footpath transfers.** Need nearest-walk-node+ snapping for access/egress and precomputed short walking transfers between nearby+ stops (RAPTOR needs a transfer table). The generator already has a 15 m transfer+ notion to borrow from.+4. **Calendar correctness:** `calendar.txt` + `calendar_dates.txt` exceptions,+ service-day bitsets, and per-feed **timezone**/midnight-rollover (`>24:00:00`+ times are legal in GTFS). The current engine's day-mod arithmetic is naive.+5. **Freshness/versioning:** offline GTFS goes stale; needs a feed version stamp ++ the P10 online board/MOTIS as the fresh fallback.+6. **Licensing/attribution** per feed (Transitous tracks this; carry it into packs).++None are showstoppers; all are standard transit-routing engineering.++---++## 5) Concrete phased build plan (if lead approves go)++**Phase 0 — Decisions & pack contract (design).** Lock: RAPTOR vs CSA-first; the+transit-pack file format (feed-keyed vs zone-keyed); resolve the §1d road-graph+format gap ownership. Define the on-disk transit index schema (stops, routes,+trips, stop_times delta-coded, service-day bitsets, transfer table, string pool)+and a `feeds.json` manifest (feed id, version, bbox, covered zones, size, URL).++**Phase 1 — GTFS ingest (Python, `scripts/maps/normalize_gtfs.py`).** Parse a+GTFS `.zip` → the compact per-region index above. Pure stdlib, deterministic,+`test/` fixture feed + `test_normalize.py`-style unit test. Emits index + manifest+entry; no C++.++**Phase 2 — Rust transit index + planner (`maps/src/main/rust/src/transit.rs`).**+mmap loader for the index (mirroring `graph.rs`); RAPTOR (or CSA) earliest-arrival++ transfers over one region; produce the same `StepData` transit shape+`reconstruct_path` emits so `lib.rs` marshaling and the UI are unchanged. Reuse the+road A* for access/egress/transfer walking legs; keep the `present_feeds` gate.++**Phase 3 — Generator/packaging wiring.** Add the transit index to region packs+(new part). Publish via R2 like the pmtiles. Do **not** grow `generator.cpp`; the+Python stage writes the transit part; a thin packaging step lists it in the+manifest. Address the road-graph merge/format gap here (or as a tracked sibling).++**Phase 4 — App download + init wiring.** Extend `ZoneDownloadManager` to fetch the+transit part (the `($part)` scheme already anticipates this) and track it in+`DownloadedMapsPage`. Move `present_feeds` discovery from "APK assets" to+"downloaded region packs" (fall back to assets). Point the Rust transit loader at+`getExternalFilesDir`.++**Phase 5 — Routing integration + online fallback.** Route `TravelMode.TRANSIT`+through the new planner when the region's feed is present offline; otherwise fall+back to the **P10 online board / MOTIS** (`TransitousDataSource`) — the graceful+`present_feeds` miss path already models this. Wire journey results into the+existing directions UI.++**Phase 6 — Validation.** Fixture-feed unit tests (Phase 1); a metro dry-run+(e.g. SF Bay) end-to-end; compare a few journeys against the MOTIS online result+for sanity; measure on-device index size + query latency.++**Reuse leverage:** transit UI (`RouteService.Step`/`transitDetails`), the JNI+boundary + `RawStep` marshaling, `present_feeds`, the road A* for walk legs, the+Python normalizer pattern + test harness, and the P10 Transitous source for the+online fallback. The genuinely new work is `normalize_gtfs.py`, `transit.rs`+(RAPTOR/CSA + index loader), and the pack download/packaging wiring.++---++## Appendix — key file references++- `scripts/maps/generator.cpp` — OSM→graph; transit scaffolding `:348-355`,+ `:431-445`, `:536-582`, `:641-761`; output `:855-913`.+- `scripts/maps/run_generator.sh` — compile/run/R2-sync `:64-99`.+- `maps/src/main/rust/src/graph.rs` — loader + `present_feeds` `:167-301`; on-disk+ structs `:39-69`.+- `maps/src/main/rust/src/routing.rs` — transit A* `:322-428`; step build+ `:446-600`.+- `maps/src/main/rust/src/geometry.rs` — `get_transit_edge_time_10ms` + offline+ feed fallback `:112-190`.+- `maps/src/main/rust/src/lib.rs` — JNI `init(basePath, presentFeeds)` `:124-163`.+- `maps/src/main/java/.../util/OfflineRouter.kt` — present-feeds from assets+ `:214-218`; graph base = externalFilesDir `:211`.+- `maps/src/main/java/.../util/GTFSProvider.kt` — GTFS `routes.txt` from assets.+- `maps/src/main/java/.../ui/DownloadedMapsPage.kt` + `util/ZoneDownloadManager.kt`+ — pmtiles-only zone downloads; `"Map Zone $id ($part)"` multi-part hint.+- `maps/src/main/java/.../data/transit/TransitousDataSource.kt` — P10 online board+ (MOTIS) = the online fallback.
scripts/maps/gtfs_ingest/.gitignore
diff --git a/scripts/maps/gtfs_ingest/.gitignore b/scripts/maps/gtfs_ingest/.gitignorenew file mode 100644index 0000000000..ea8c4bf7f3--- /dev/null+++ b/scripts/maps/gtfs_ingest/.gitignore@@ -0,0 +1 @@+/target
scripts/maps/gtfs_ingest/Cargo.lock
diff --git a/scripts/maps/gtfs_ingest/Cargo.lock b/scripts/maps/gtfs_ingest/Cargo.locknew file mode 100644index 0000000000..901c4635ad--- /dev/null+++ b/scripts/maps/gtfs_ingest/Cargo.lock@@ -0,0 +1,7 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "gtfs_ingest"+version = "0.1.0"
scripts/maps/gtfs_ingest/Cargo.toml
diff --git a/scripts/maps/gtfs_ingest/Cargo.toml b/scripts/maps/gtfs_ingest/Cargo.tomlnew file mode 100644index 0000000000..04208e158d--- /dev/null+++ b/scripts/maps/gtfs_ingest/Cargo.toml@@ -0,0 +1,26 @@+# Host-side GTFS ingest tool for the Maps offline transit packs (P11a).+#+# Deliberately DETACHED from the Android Rust workspace (the empty [workspace]+# table below): it is a std-only host binary with zero external dependencies, so+# `cargo build` here resolves offline and never pulls the aarch64-android+# toolchain or the app crates' lints. It emits a compact per-region transit+# index consumed on-device by `maps/src/main/rust/src/transit.rs` (P11b).+[package]+name = "gtfs_ingest"+version = "0.1.0"+edition = "2021"+publish = false+license = "GPL-2.0-only"+description = "GTFS -> compact on-device transit index for the Maps offline packs"++[[bin]]+name = "gtfs_ingest"+path = "src/main.rs"++[dependencies]++[profile.release]+opt-level = 3++# Detach from the repo-root workspace so this host tool builds standalone/offline.+[workspace]
scripts/maps/gtfs_ingest/README.md
diff --git a/scripts/maps/gtfs_ingest/README.md b/scripts/maps/gtfs_ingest/README.mdnew file mode 100644index 0000000000..7c26d91d7d--- /dev/null+++ b/scripts/maps/gtfs_ingest/README.md@@ -0,0 +1,52 @@+# gtfs_ingest (P11a)++Host-side Rust build tool that converts a region's **GTFS** feed into a compact+**on-device transit index** (`<feed>.transit`) for the Maps offline region+packs. It is the ingest half of offline public-transit routing; the on-device+planner that consumes the index is `maps/src/main/rust/src/transit.rs` (P11b).++## Why Rust + directory input++- **Rust-first (LANGUAGE RULE):** GTFS ingest is done in Rust, not Python. No+ `normalize_gtfs.py`.+- **Zero dependencies / offline builds:** the tool is `std`-only and detached+ from the repo-root Cargo workspace (see the empty `[workspace]` in+ `Cargo.toml`), so `cargo build` here resolves without the network and without+ the Android/aarch64 toolchain or the app crates' lints.+- **Unzipped input:** it reads an *unzipped* GTFS directory rather than a `.zip`,+ which avoids pulling in a DEFLATE crate. Unzipping is a one-line pre-step.++## Usage++```sh+# 1. Fetch a region feed (Transitous registry points at each agency's GTFS zip):+# https://github.com/public-transport/transitous -> feeds/*.json+unzip sf_bay_511.zip -d /tmp/sf_bay++# 2. Build the compact index + manifest:+cargo run --release -- /tmp/sf_bay sf_bay /path/to/pack/out+# -> /path/to/pack/out/sf_bay.transit (mmap'd on device)+# -> /path/to/pack/out/sf_bay.transit.json (manifest: bbox, counts, size)+```++`<feed_name>` is the feed id used as the `present_feeds` key on device (it must+match the GTFS feed folder name the app recognises).++## Output++- `<feed>.transit` — the binary index. On-disk layout is documented at the top+ of `src/index.rs` and **must stay in sync** with `transit.rs`. It holds an+ interned string pool, stops, RAPTOR routes (trips grouped by identical stop+ pattern), delta-free `stop_times` in seconds since service midnight, a+ stop→routes index, footpath transfers (≤400 m), and calendar service masks ++ `calendar_dates` exceptions.+- `<feed>.transit.json` — a small manifest the packaging step (P11c) uses to+ list the transit part alongside the pmtiles.++Typical size is ~2–15 MB per metro (see `P11_OFFLINE_TRANSIT_SPIKE.md`).++## Known limitations (v1)++- Transfers use a straight-line ≤400 m footpath heuristic (not the road graph).+- Service masks cover `calendar.txt` weekdays + `calendar_dates.txt` exceptions;+ per-feed timezone handling is left to the on-device planner's query time.
scripts/maps/gtfs_ingest/src/gtfs.rs
diff --git a/scripts/maps/gtfs_ingest/src/gtfs.rs b/scripts/maps/gtfs_ingest/src/gtfs.rsnew file mode 100644index 0000000000..cc8cc25dd4--- /dev/null+++ b/scripts/maps/gtfs_ingest/src/gtfs.rs@@ -0,0 +1,126 @@+//! Minimal, dependency-free GTFS reader: an RFC 4180-ish CSV parser plus typed+//! loaders for the GTFS files the offline transit index needs+//! (`stops`, `routes`, `trips`, `stop_times`, `calendar`, `calendar_dates`).+//!+//! GTFS is CSV text; times may exceed 24:00:00 (legal, means "after service+//! midnight"). We keep everything in seconds-since-service-midnight.++use std::collections::HashMap;+use std::path::Path;++/// A parsed CSV table: the header row plus data rows (each a `Vec<String>`).+pub struct Csv {+ header: Vec<String>,+ pub rows: Vec<Vec<String>>,+ col: HashMap<String, usize>,+}++impl Csv {+ /// Index of the named column, if present.+ pub fn idx(&self, name: &str) -> Option<usize> {+ self.col.get(name).copied()+ }++ /// Cell value for `row` at column `name`, or "" when absent/short.+ pub fn get<'a>(&self, row: &'a [String], name: &str) -> &'a str {+ match self.idx(name).and_then(|i| row.get(i)) {+ Some(s) => s.as_str(),+ None => "",+ }+ }++ #[allow(dead_code)]+ pub fn header(&self) -> &[String] {+ &self.header+ }+}++/// Parse RFC 4180-ish CSV from `text`. Handles quoted fields containing commas,+/// embedded newlines and escaped quotes (`""`), plus a leading UTF-8 BOM.+pub fn parse_csv(text: &str) -> Csv {+ let mut records: Vec<Vec<String>> = Vec::new();+ let mut field = String::new();+ let mut record: Vec<String> = Vec::new();+ let mut in_quotes = false;+ let mut chars = text.chars().peekable();+ let mut started = false;++ // Strip a leading BOM if present.+ if let Some('\u{feff}') = chars.peek().copied() {+ let _ = chars.next();+ }++ while let Some(c) = chars.next() {+ started = true;+ if in_quotes {+ if c == '"' {+ if chars.peek().copied() == Some('"') {+ field.push('"');+ let _ = chars.next();+ } else {+ in_quotes = false;+ }+ } else {+ field.push(c);+ }+ continue;+ }+ match c {+ '"' => in_quotes = true,+ ',' => {+ record.push(std::mem::take(&mut field));+ }+ '\r' => { /* swallow; handled by \n */ }+ '\n' => {+ record.push(std::mem::take(&mut field));+ records.push(std::mem::take(&mut record));+ }+ _ => field.push(c),+ }+ }+ // Flush a trailing record with no final newline.+ if started && (!field.is_empty() || !record.is_empty()) {+ record.push(field);+ records.push(record);+ }++ let mut iter = records.into_iter();+ let header = iter.next().unwrap_or_default();+ let mut col = HashMap::new();+ for (i, h) in header.iter().enumerate() {+ col.insert(h.trim().to_string(), i);+ }+ let rows: Vec<Vec<String>> = iter.filter(|r| !(r.len() == 1 && r[0].is_empty())).collect();+ Csv { header, rows, col }+}++/// Read `dir/name` as UTF-8 (lossy) and parse it as CSV. Returns `None` when the+/// file is absent (optional GTFS files such as `calendar_dates.txt`).+pub fn read_table(dir: &Path, name: &str) -> Option<Csv> {+ let path = dir.join(name);+ let bytes = std::fs::read(&path).ok()?;+ Some(parse_csv(&String::from_utf8_lossy(&bytes)))+}++/// Parse a GTFS `HH:MM:SS` time (hours may exceed 24) into seconds since+/// service midnight. Returns `None` for blank/malformed values.+pub fn parse_gtfs_time(s: &str) -> Option<u32> {+ let s = s.trim();+ if s.is_empty() {+ return None;+ }+ let mut parts = s.split(':');+ let h: u32 = parts.next()?.trim().parse().ok()?;+ let m: u32 = parts.next()?.trim().parse().ok()?;+ let sec: u32 = parts.next().unwrap_or("0").trim().parse().ok()?;+ Some(h * 3600 + m * 60 + sec)+}++/// Parse a GTFS `YYYYMMDD` service date into an integer `yyyymmdd`.+pub fn parse_gtfs_date(s: &str) -> Option<u32> {+ let s = s.trim();+ if s.len() != 8 {+ return None;+ }+ s.parse().ok()+}
scripts/maps/gtfs_ingest/src/index.rs
diff --git a/scripts/maps/gtfs_ingest/src/index.rs b/scripts/maps/gtfs_ingest/src/index.rsnew file mode 100644index 0000000000..28b2ea6d9c--- /dev/null+++ b/scripts/maps/gtfs_ingest/src/index.rs@@ -0,0 +1,586 @@+//! Build the compact per-region transit index from parsed GTFS tables and+//! serialize it to the on-disk `.transit` format.+//!+//! ON-DISK FORMAT (little-endian, mmap-friendly, read via `read_unaligned` on+//! device). THIS LAYOUT MUST STAY IN SYNC WITH+//! `maps/src/main/rust/src/transit.rs`.+//!+//! Header (48 bytes):+//! u32 magic (MAGIC), u32 version (VERSION), u32 section_count,+//! u32 stop_count, u32 route_count, u32 trip_count, u32 service_count,+//! u32 feed_name_off, i32 min_lat_e7, i32 min_lon_e7, i32 max_lat_e7,+//! i32 max_lon_e7+//! Section directory: section_count * { u64 offset, u64 len } (absolute byte+//! offset from file start, byte length). Sections are 8-byte aligned.+//!+//! Sections (index -> payload):+//! 0 STRINGS NUL-terminated UTF-8 string pool; offsets are byte+//! offsets into this section, sentinel NONE = no string.+//! 1 STOPS StopRec[stop_count] = { i32 lat_e7, i32 lon_e7,+//! u32 name_off, u32 code_off }+//! 2 ROUTES RouteRec[route_count]= { u32 name_off, u32 color,+//! u32 route_type, u32 n_stops, u32 first_route_stop,+//! u32 n_trips, u32 first_trip, u32 _pad }+//! 3 ROUTE_STOPS u32[] ordered stop indices; RouteRec slices it by+//! [first_route_stop, +n_stops].+//! 4 TRIPS TripRec[trip_count] = { u32 route_idx, u32 service_idx,+//! u32 headsign_off, u32 first_stoptime }; a trip's+//! stop_times are STOPTIMES[first_stoptime, +n_stops].+//! 5 STOPTIMES StopTime[] = { u32 arr_s, u32 dep_s } seconds since+//! service midnight (may exceed 86400).+//! 6 STOP_ROUTES u32[] route indices serving each stop (flattened).+//! 7 STOP_ROUTES_IDX u32[stop_count + 1] prefix offsets into STOP_ROUTES.+//! 8 TRANSFERS Transfer[] = { u32 to_stop, u32 secs } footpaths.+//! 9 TRANSFERS_IDX u32[stop_count + 1] prefix offsets into TRANSFERS.+//! 10 SERVICES ServiceRec[service_count] = { u8 weekday_mask,+//! u8[3] _pad, u32 start_date, u32 end_date }.+//! 11 EXCEPTIONS ExcRec[] = { u32 service_idx, u32 date, u32 added }+//! (added: 1 = service added on date, 0 = removed).++use crate::gtfs::{parse_gtfs_date, parse_gtfs_time, Csv};+use std::collections::HashMap;++pub const MAGIC: u32 = 0x5452_4958; // "TRIX"+pub const VERSION: u32 = 1;+pub const NONE: u32 = 0xFFFF_FFFF;+pub const SECTION_COUNT: usize = 12;++const MAX_TRANSFER_M: f64 = 400.0;+const WALK_SPEED_M_S: f64 = 1.33;+const CELL_DEG: f64 = 0.004; // ~450 m latitude buckets for the transfer grid+const MAX_TRANSFERS_PER_STOP: usize = 16;++/// Interning string pool producing byte offsets into the STRINGS section.+struct StringPool {+ bytes: Vec<u8>,+ map: HashMap<String, u32>,+}++impl StringPool {+ fn new() -> StringPool {+ // Byte 0 is a lone NUL so offset 0 is a valid empty string, keeping+ // NONE (0xFFFFFFFF) unambiguous.+ StringPool { bytes: vec![0], map: HashMap::new() }+ }++ fn intern(&mut self, s: &str) -> u32 {+ if s.is_empty() {+ return NONE;+ }+ if let Some(&off) = self.map.get(s) {+ return off;+ }+ let off = self.bytes.len() as u32;+ self.bytes.extend_from_slice(s.as_bytes());+ self.bytes.push(0);+ self.map.insert(s.to_string(), off);+ off+ }+}++struct StopTime {+ stop_idx: u32,+ seq: i64,+ arr: u32,+ dep: u32,+}++/// Summary counts reported to the caller / manifest.+pub struct BuildStats {+ pub stops: usize,+ pub routes: usize,+ pub trips: usize,+ pub transfers: usize,+ pub min_lat_e7: i32,+ pub min_lon_e7: i32,+ pub max_lat_e7: i32,+ pub max_lon_e7: i32,+ pub size_bytes: usize,+}++fn append_u32(v: &mut Vec<u8>, x: u32) {+ v.extend_from_slice(&x.to_le_bytes());+}+fn append_i32(v: &mut Vec<u8>, x: i32) {+ v.extend_from_slice(&x.to_le_bytes());+}++/// Approximate ground distance in metres (equirectangular; fine at footpath+/// range).+fn dist_m(lat1_e7: i32, lon1_e7: i32, lat2_e7: i32, lon2_e7: i32) -> f64 {+ let lat1 = lat1_e7 as f64 * 1e-7;+ let lat2 = lat2_e7 as f64 * 1e-7;+ let dlat = (lat2 - lat1) * 111_320.0;+ let mean = ((lat1 + lat2) * 0.5).to_radians();+ let dlon = (lon2_e7 as f64 * 1e-7 - lon1_e7 as f64 * 1e-7) * 111_320.0 * mean.cos();+ (dlat * dlat + dlon * dlon).sqrt()+}++/// Build the full index blob from the GTFS tables. `feed_name` is stored in the+/// string pool and surfaced to the on-device planner.+pub fn build_index(+ feed_name: &str,+ stops_csv: &Csv,+ routes_csv: &Csv,+ trips_csv: &Csv,+ stop_times_csv: &Csv,+ calendar_csv: Option<&Csv>,+ calendar_dates_csv: Option<&Csv>,+) -> Result<(Vec<u8>, BuildStats), String> {+ let mut pool = StringPool::new();+ let feed_name_off = pool.intern(feed_name);++ // --- Stops ---+ let mut stop_id_to_idx: HashMap<String, u32> = HashMap::new();+ let mut stop_lat: Vec<i32> = Vec::new();+ let mut stop_lon: Vec<i32> = Vec::new();+ let mut stop_name_off: Vec<u32> = Vec::new();+ let mut stop_code_off: Vec<u32> = Vec::new();+ let (mut min_lat, mut min_lon) = (i32::MAX, i32::MAX);+ let (mut max_lat, mut max_lon) = (i32::MIN, i32::MIN);++ for row in &stops_csv.rows {+ let id = stops_csv.get(row, "stop_id");+ if id.is_empty() {+ continue;+ }+ let lat: f64 = stops_csv.get(row, "stop_lat").trim().parse().unwrap_or(f64::NAN);+ let lon: f64 = stops_csv.get(row, "stop_lon").trim().parse().unwrap_or(f64::NAN);+ if lat.is_nan() || lon.is_nan() {+ continue;+ }+ let lat_e7 = (lat * 1e7) as i32;+ let lon_e7 = (lon * 1e7) as i32;+ let name = stops_csv.get(row, "stop_name");+ let code = stops_csv.get(row, "stop_code");+ let idx = stop_lat.len() as u32;+ stop_id_to_idx.insert(id.to_string(), idx);+ stop_lat.push(lat_e7);+ stop_lon.push(lon_e7);+ stop_name_off.push(pool.intern(name));+ stop_code_off.push(pool.intern(if code.is_empty() { id } else { code }));+ min_lat = min_lat.min(lat_e7);+ min_lon = min_lon.min(lon_e7);+ max_lat = max_lat.max(lat_e7);+ max_lon = max_lon.max(lon_e7);+ }+ let stop_count = stop_lat.len();+ if stop_count == 0 {+ return Err("no usable stops in feed".to_string());+ }++ // --- Route metadata (from routes.txt) ---+ struct RouteMeta {+ name_off: u32,+ color: u32,+ route_type: u32,+ }+ let mut route_meta: HashMap<String, RouteMeta> = HashMap::new();+ for row in &routes_csv.rows {+ let id = routes_csv.get(row, "route_id");+ if id.is_empty() {+ continue;+ }+ let short = routes_csv.get(row, "route_short_name");+ let long = routes_csv.get(row, "route_long_name");+ let name = if !short.is_empty() { short } else { long };+ let color = u32::from_str_radix(routes_csv.get(row, "route_color").trim(), 16).unwrap_or(0);+ let rtype: u32 = routes_csv.get(row, "route_type").trim().parse().unwrap_or(3);+ route_meta.insert(+ id.to_string(),+ RouteMeta { name_off: pool.intern(name), color, route_type: rtype },+ );+ }++ // --- Trips (route_id, service_id, headsign) ---+ struct TripMeta {+ route_id: String,+ service_id: String,+ headsign_off: u32,+ }+ let mut trip_meta: HashMap<String, TripMeta> = HashMap::new();+ for row in &trips_csv.rows {+ let id = trips_csv.get(row, "trip_id");+ if id.is_empty() {+ continue;+ }+ let headsign = trips_csv.get(row, "trip_headsign");+ trip_meta.insert(+ id.to_string(),+ TripMeta {+ route_id: trips_csv.get(row, "route_id").to_string(),+ service_id: trips_csv.get(row, "service_id").to_string(),+ headsign_off: pool.intern(headsign),+ },+ );+ }++ // --- stop_times grouped by trip ---+ let mut trip_stoptimes: HashMap<String, Vec<StopTime>> = HashMap::new();+ for row in &stop_times_csv.rows {+ let trip_id = stop_times_csv.get(row, "trip_id");+ if trip_id.is_empty() {+ continue;+ }+ let stop_id = stop_times_csv.get(row, "stop_id");+ let stop_idx = match stop_id_to_idx.get(stop_id) {+ Some(&i) => i,+ None => continue,+ };+ let seq: i64 = stop_times_csv.get(row, "stop_sequence").trim().parse().unwrap_or(0);+ let dep = parse_gtfs_time(stop_times_csv.get(row, "departure_time"));+ let arr = parse_gtfs_time(stop_times_csv.get(row, "arrival_time"));+ let (arr, dep) = match (arr, dep) {+ (Some(a), Some(d)) => (a, d),+ (Some(a), None) => (a, a),+ (None, Some(d)) => (d, d),+ (None, None) => continue,+ };+ trip_stoptimes+ .entry(trip_id.to_string())+ .or_default()+ .push(StopTime { stop_idx, seq, arr, dep });+ }++ // --- Services (calendar.txt) ---+ let mut service_id_to_idx: HashMap<String, u32> = HashMap::new();+ let mut svc_mask: Vec<u8> = Vec::new();+ let mut svc_start: Vec<u32> = Vec::new();+ let mut svc_end: Vec<u32> = Vec::new();+ if let Some(cal) = calendar_csv {+ let days = [+ "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday",+ ];+ for row in &cal.rows {+ let id = cal.get(row, "service_id");+ if id.is_empty() {+ continue;+ }+ let mut mask = 0u8;+ for (b, d) in days.iter().enumerate() {+ if cal.get(row, d).trim() == "1" {+ mask |= 1 << b;+ }+ }+ let idx = svc_mask.len() as u32;+ service_id_to_idx.insert(id.to_string(), idx);+ svc_mask.push(mask);+ svc_start.push(parse_gtfs_date(cal.get(row, "start_date")).unwrap_or(0));+ svc_end.push(parse_gtfs_date(cal.get(row, "end_date")).unwrap_or(99_999_999));+ }+ }+ // Register any service_ids that appear only in calendar_dates.+ let ensure_service =+ |sid: &str,+ map: &mut HashMap<String, u32>,+ mask: &mut Vec<u8>,+ start: &mut Vec<u32>,+ end: &mut Vec<u32>| -> u32 {+ if let Some(&i) = map.get(sid) {+ return i;+ }+ let i = mask.len() as u32;+ map.insert(sid.to_string(), i);+ mask.push(0);+ start.push(0);+ end.push(99_999_999);+ i+ };++ // --- Exceptions (calendar_dates.txt) ---+ let mut exceptions: Vec<(u32, u32, u32)> = Vec::new(); // (service_idx, date, added)+ if let Some(cd) = calendar_dates_csv {+ for row in &cd.rows {+ let sid = cd.get(row, "service_id");+ if sid.is_empty() {+ continue;+ }+ let date = match parse_gtfs_date(cd.get(row, "date")) {+ Some(d) => d,+ None => continue,+ };+ let added = if cd.get(row, "exception_type").trim() == "1" { 1 } else { 0 };+ let sidx = ensure_service(+ sid,+ &mut service_id_to_idx,+ &mut svc_mask,+ &mut svc_start,+ &mut svc_end,+ );+ exceptions.push((sidx, date, added));+ }+ }++ // --- Group trips into RAPTOR routes by (gtfs route, ordered stop pattern) ---+ struct RaptorRoute {+ meta_route_id: String,+ stop_pattern: Vec<u32>,+ trips: Vec<usize>, // indices into `trips` below+ }+ struct BuiltTrip {+ service_idx: u32,+ headsign_off: u32,+ dep_first: u32,+ stoptimes: Vec<(u32, u32)>, // (arr, dep) aligned to stop_pattern+ }+ let mut raptor_routes: Vec<RaptorRoute> = Vec::new();+ let mut pattern_key_to_route: HashMap<String, usize> = HashMap::new();+ let mut built_trips: Vec<BuiltTrip> = Vec::new();++ for (trip_id, mut sts) in trip_stoptimes {+ if sts.len() < 2 {+ continue;+ }+ sts.sort_by_key(|s| s.seq);+ let pattern: Vec<u32> = sts.iter().map(|s| s.stop_idx).collect();+ let tmeta = match trip_meta.get(&trip_id) {+ Some(m) => m,+ None => continue,+ };+ let service_idx = match service_id_to_idx.get(&tmeta.service_id) {+ Some(&i) => i,+ None => ensure_service(+ &tmeta.service_id,+ &mut service_id_to_idx,+ &mut svc_mask,+ &mut svc_start,+ &mut svc_end,+ ),+ };+ let key = format!(+ "{}|{}",+ tmeta.route_id,+ pattern.iter().map(|s| s.to_string()).collect::<Vec<_>>().join(",")+ );+ let route_idx = *pattern_key_to_route.entry(key).or_insert_with(|| {+ raptor_routes.push(RaptorRoute {+ meta_route_id: tmeta.route_id.clone(),+ stop_pattern: pattern.clone(),+ trips: Vec::new(),+ });+ raptor_routes.len() - 1+ });+ let bt = BuiltTrip {+ service_idx,+ headsign_off: tmeta.headsign_off,+ dep_first: sts.first().map(|s| s.dep).unwrap_or(0),+ stoptimes: sts.iter().map(|s| (s.arr, s.dep)).collect(),+ };+ let ti = built_trips.len();+ built_trips.push(bt);+ raptor_routes[route_idx].trips.push(ti);+ }++ // --- Flatten into on-disk sections ---+ let mut sec_stops = Vec::new();+ for i in 0..stop_count {+ append_i32(&mut sec_stops, stop_lat[i]);+ append_i32(&mut sec_stops, stop_lon[i]);+ append_u32(&mut sec_stops, stop_name_off[i]);+ append_u32(&mut sec_stops, stop_code_off[i]);+ }++ let mut sec_routes = Vec::new();+ let mut sec_route_stops = Vec::new();+ let mut sec_trips = Vec::new();+ let mut sec_stoptimes = Vec::new();+ // stop -> set of route indices (dedup while preserving order)+ let mut stop_routes: Vec<Vec<u32>> = vec![Vec::new(); stop_count];++ let mut trip_global: u32 = 0;+ let route_count = raptor_routes.len();+ for (ridx, rr) in raptor_routes.iter().enumerate() {+ let meta = route_meta.get(&rr.meta_route_id);+ let (name_off, color, rtype) = match meta {+ Some(m) => (m.name_off, m.color, m.route_type),+ None => (NONE, 0, 3),+ };+ let first_route_stop = (sec_route_stops.len() / 4) as u32;+ for &s in &rr.stop_pattern {+ append_u32(&mut sec_route_stops, s);+ let rv = &mut stop_routes[s as usize];+ if rv.last() != Some(&(ridx as u32)) && !rv.contains(&(ridx as u32)) {+ rv.push(ridx as u32);+ }+ }+ let n_stops = rr.stop_pattern.len() as u32;++ // Sort this route's trips by departure at the first stop.+ let mut trip_order = rr.trips.clone();+ trip_order.sort_by_key(|&ti| built_trips[ti].dep_first);+ let first_trip = trip_global;+ for &ti in &trip_order {+ let bt = &built_trips[ti];+ let first_stoptime = (sec_stoptimes.len() / 8) as u32;+ for &(arr, dep) in &bt.stoptimes {+ append_u32(&mut sec_stoptimes, arr);+ append_u32(&mut sec_stoptimes, dep);+ }+ append_u32(&mut sec_trips, ridx as u32);+ append_u32(&mut sec_trips, bt.service_idx);+ append_u32(&mut sec_trips, bt.headsign_off);+ append_u32(&mut sec_trips, first_stoptime);+ trip_global += 1;+ }+ let n_trips = trip_global - first_trip;++ append_u32(&mut sec_routes, name_off);+ append_u32(&mut sec_routes, color);+ append_u32(&mut sec_routes, rtype);+ append_u32(&mut sec_routes, n_stops);+ append_u32(&mut sec_routes, first_route_stop);+ append_u32(&mut sec_routes, n_trips);+ append_u32(&mut sec_routes, first_trip);+ append_u32(&mut sec_routes, 0); // _pad+ }+ let trip_count = trip_global as usize;++ // stop_routes flattened + index+ let mut sec_stop_routes = Vec::new();+ let mut sec_stop_routes_idx = Vec::new();+ let mut acc: u32 = 0;+ for sr in &stop_routes {+ append_u32(&mut sec_stop_routes_idx, acc);+ for &r in sr {+ append_u32(&mut sec_stop_routes, r);+ }+ acc += sr.len() as u32;+ }+ append_u32(&mut sec_stop_routes_idx, acc);++ // --- Footpath transfers via a coarse spatial grid ---+ let mut grid: HashMap<(i32, i32), Vec<u32>> = HashMap::new();+ let cell = |lat_e7: i32, lon_e7: i32| -> (i32, i32) {+ (+ (lat_e7 as f64 * 1e-7 / CELL_DEG).floor() as i32,+ (lon_e7 as f64 * 1e-7 / CELL_DEG).floor() as i32,+ )+ };+ for i in 0..stop_count {+ grid.entry(cell(stop_lat[i], stop_lon[i])).or_default().push(i as u32);+ }+ let mut transfers: Vec<Vec<(u32, u32)>> = vec![Vec::new(); stop_count];+ let mut transfer_total = 0usize;+ for i in 0..stop_count {+ let (cx, cy) = cell(stop_lat[i], stop_lon[i]);+ let mut cand: Vec<(u32, f64)> = Vec::new();+ for dx in -1..=1 {+ for dy in -1..=1 {+ if let Some(bucket) = grid.get(&(cx + dx, cy + dy)) {+ for &j in bucket {+ if j as usize == i {+ continue;+ }+ let d = dist_m(+ stop_lat[i],+ stop_lon[i],+ stop_lat[j as usize],+ stop_lon[j as usize],+ );+ if d <= MAX_TRANSFER_M {+ cand.push((j, d));+ }+ }+ }+ }+ }+ cand.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));+ cand.truncate(MAX_TRANSFERS_PER_STOP);+ for (j, d) in cand {+ let secs = (d / WALK_SPEED_M_S).ceil() as u32;+ transfers[i].push((j, secs));+ transfer_total += 1;+ }+ }+ let mut sec_transfers = Vec::new();+ let mut sec_transfers_idx = Vec::new();+ let mut tacc: u32 = 0;+ for tr in &transfers {+ append_u32(&mut sec_transfers_idx, tacc);+ for &(to, secs) in tr {+ append_u32(&mut sec_transfers, to);+ append_u32(&mut sec_transfers, secs);+ }+ tacc += tr.len() as u32;+ }+ append_u32(&mut sec_transfers_idx, tacc);++ // Services + exceptions+ let mut sec_services = Vec::new();+ for i in 0..svc_mask.len() {+ sec_services.push(svc_mask[i]);+ sec_services.extend_from_slice(&[0u8, 0, 0]);+ append_u32(&mut sec_services, svc_start[i]);+ append_u32(&mut sec_services, svc_end[i]);+ }+ let mut sec_exceptions = Vec::new();+ for &(sidx, date, added) in &exceptions {+ append_u32(&mut sec_exceptions, sidx);+ append_u32(&mut sec_exceptions, date);+ append_u32(&mut sec_exceptions, added);+ }++ // --- Assemble file: header + directory + aligned sections ---+ let sections: [&[u8]; SECTION_COUNT] = [+ &pool.bytes,+ &sec_stops,+ &sec_routes,+ &sec_route_stops,+ &sec_trips,+ &sec_stoptimes,+ &sec_stop_routes,+ &sec_stop_routes_idx,+ &sec_transfers,+ &sec_transfers_idx,+ &sec_services,+ &sec_exceptions,+ ];++ let header_len = 48usize;+ let dir_len = SECTION_COUNT * 16;+ let mut data_off = header_len + dir_len;+ let align = |o: usize| (o + 7) & !7;+ let mut dir: Vec<(u64, u64)> = Vec::with_capacity(SECTION_COUNT);+ for s in sections.iter() {+ data_off = align(data_off);+ dir.push((data_off as u64, s.len() as u64));+ data_off += s.len();+ }+ let total = data_off;++ let mut out = Vec::with_capacity(total);+ append_u32(&mut out, MAGIC);+ append_u32(&mut out, VERSION);+ append_u32(&mut out, SECTION_COUNT as u32);+ append_u32(&mut out, stop_count as u32);+ append_u32(&mut out, route_count as u32);+ append_u32(&mut out, trip_count as u32);+ append_u32(&mut out, svc_mask.len() as u32);+ append_u32(&mut out, feed_name_off);+ append_i32(&mut out, min_lat);+ append_i32(&mut out, min_lon);+ append_i32(&mut out, max_lat);+ append_i32(&mut out, max_lon);+ for (off, len) in &dir {+ out.extend_from_slice(&off.to_le_bytes());+ out.extend_from_slice(&len.to_le_bytes());+ }+ for s in sections.iter() {+ let pad = align(out.len()) - out.len();+ out.extend(std::iter::repeat(0u8).take(pad));+ out.extend_from_slice(s);+ }++ let stats = BuildStats {+ stops: stop_count,+ routes: route_count,+ trips: trip_count,+ transfers: transfer_total,+ min_lat_e7: min_lat,+ min_lon_e7: min_lon,+ max_lat_e7: max_lat,+ max_lon_e7: max_lon,+ size_bytes: out.len(),+ };+ Ok((out, stats))+}
scripts/maps/gtfs_ingest/src/main.rs
diff --git a/scripts/maps/gtfs_ingest/src/main.rs b/scripts/maps/gtfs_ingest/src/main.rsnew file mode 100644index 0000000000..9861518dd3--- /dev/null+++ b/scripts/maps/gtfs_ingest/src/main.rs@@ -0,0 +1,133 @@+//! `gtfs_ingest` — host build tool (P11a) that turns a region's GTFS feed into a+//! compact on-device transit index (`<feed>.transit`) plus a small JSON+//! manifest describing it, for bundling into the Maps offline region packs.+//!+//! Usage:+//! gtfs_ingest <gtfs_dir> <feed_name> <out_dir>+//!+//! `gtfs_dir` is an UNZIPPED GTFS feed directory (containing `stops.txt`,+//! `routes.txt`, `trips.txt`, `stop_times.txt`, and optionally `calendar.txt` /+//! `calendar_dates.txt`). Unzipping is a one-line pre-step+//! (`unzip feed.zip -d <gtfs_dir>`); keeping this tool zip-free means it builds+//! with zero external crates and resolves fully offline — the LANGUAGE RULE's+//! Rust-first, no-Python requirement without dragging in a decompression dep.+//!+//! GTFS feeds are sourced per-region from the Transitous feed registry+//! (github.com/public-transport/transitous, `feeds/*.json`), which points at+//! each agency's official GTFS `.zip` — the same open data behind the P10+//! online boards.++mod gtfs;+mod index;++use std::path::{Path, PathBuf};+use std::process::ExitCode;++fn main() -> ExitCode {+ let args: Vec<String> = std::env::args().collect();+ if args.len() != 4 {+ eprintln!("usage: gtfs_ingest <gtfs_dir> <feed_name> <out_dir>");+ return ExitCode::from(2);+ }+ let gtfs_dir = PathBuf::from(&args[1]);+ let feed_name = &args[2];+ let out_dir = PathBuf::from(&args[3]);++ match run(>fs_dir, feed_name, &out_dir) {+ Ok(()) => ExitCode::SUCCESS,+ Err(e) => {+ eprintln!("gtfs_ingest: {e}");+ ExitCode::FAILURE+ }+ }+}++fn run(gtfs_dir: &Path, feed_name: &str, out_dir: &Path) -> Result<(), String> {+ let require = |name: &str| -> Result<gtfs::Csv, String> {+ gtfs::read_table(gtfs_dir, name)+ .ok_or_else(|| format!("missing required GTFS file: {name}"))+ };++ let stops = require("stops.txt")?;+ let routes = require("routes.txt")?;+ let trips = require("trips.txt")?;+ let stop_times = require("stop_times.txt")?;+ let calendar = gtfs::read_table(gtfs_dir, "calendar.txt");+ let calendar_dates = gtfs::read_table(gtfs_dir, "calendar_dates.txt");+ if calendar.is_none() && calendar_dates.is_none() {+ eprintln!(+ "gtfs_ingest: warning: no calendar.txt or calendar_dates.txt; \+ all services will be treated as never-scheduled by the planner"+ );+ }++ let (blob, stats) = index::build_index(+ feed_name,+ &stops,+ &routes,+ &trips,+ &stop_times,+ calendar.as_ref(),+ calendar_dates.as_ref(),+ )?;++ std::fs::create_dir_all(out_dir)+ .map_err(|e| format!("cannot create out dir {}: {e}", out_dir.display()))?;+ let index_path = out_dir.join(format!("{feed_name}.transit"));+ std::fs::write(&index_path, &blob)+ .map_err(|e| format!("cannot write {}: {e}", index_path.display()))?;++ // Per-feed manifest (hand-written JSON, no serde dep). Consumed by the+ // packaging step (P11c) to list transit parts alongside the pmtiles.+ let manifest = format!(+ "{{\n \"feed\": {feed},\n \"format_version\": {ver},\n \"file\": {file},\n \+ \"size_bytes\": {size},\n \"stops\": {stops},\n \"routes\": {routes},\n \+ \"trips\": {trips},\n \"transfers\": {transfers},\n \+ \"bbox_e7\": [{min_lat}, {min_lon}, {max_lat}, {max_lon}]\n}}\n",+ feed = json_str(feed_name),+ ver = index::VERSION,+ file = json_str(&format!("{feed_name}.transit")),+ size = stats.size_bytes,+ stops = stats.stops,+ routes = stats.routes,+ trips = stats.trips,+ transfers = stats.transfers,+ min_lat = stats.min_lat_e7,+ min_lon = stats.min_lon_e7,+ max_lat = stats.max_lat_e7,+ max_lon = stats.max_lon_e7,+ );+ let manifest_path = out_dir.join(format!("{feed_name}.transit.json"));+ std::fs::write(&manifest_path, manifest)+ .map_err(|e| format!("cannot write {}: {e}", manifest_path.display()))?;++ eprintln!(+ "gtfs_ingest: wrote {} ({} KiB): {} stops, {} routes, {} trips, {} transfers",+ index_path.display(),+ stats.size_bytes / 1024,+ stats.stops,+ stats.routes,+ stats.trips,+ stats.transfers,+ );+ Ok(())+}++/// Minimal JSON string escaper for the manifest.+fn json_str(s: &str) -> String {+ let mut out = String::with_capacity(s.len() + 2);+ out.push('"');+ for c in s.chars() {+ match c {+ '"' => out.push_str("\\\""),+ '\\' => out.push_str("\\\\"),+ '\n' => out.push_str("\\n"),+ '\r' => out.push_str("\\r"),+ '\t' => out.push_str("\\t"),+ c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),+ c => out.push(c),+ }+ }+ out.push('"');+ out+}