Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / gtfs_ingest / src / bin / transit_stops.rs
transit_stops.rs425 lines · 15.4 KiBRaw
| 1 | //! `transit_stops` — host build tool emitting the basemap's `transit_stops` layer |
| 2 | //! as newline-delimited GeoJSON (geojsonseq), one `Point` per served GTFS stop. |
| 3 | //! |
| 4 | //! Usage: |
| 5 | //! transit_stops --geojson OUT.geojsonseq <feed>... [--threads N] |
| 6 | //! transit_stops --geojson OUT.geojsonseq --manifest FILE [--threads N] |
| 7 | //! |
| 8 | //! `<feed>` is `feed_name=gtfs_dir[=motis_prefix]` or a bare `gtfs_dir`, exactly |
| 9 | //! as `gtfs_ingest` takes them, so the same `feeds.manifest` |
| 10 | //! `build_world_transit.ps1` writes drives both tools. |
| 11 | //! |
| 12 | //! This replaces the per-viewport `GET /api/v1/map/stops` fetch: stops are static |
| 13 | //! data, so they belong in the basemap rather than behind a network round-trip on |
| 14 | //! every camera idle. Each feature carries |
| 15 | //! |
| 16 | //! * `motis_id` — `<motis_prefix>_<gtfs stop_id>`, the id the realtime |
| 17 | //! `/stoptimes` overlay needs. Omitted when the feed's prefix |
| 18 | //! is unknown, in which case a tap can still open the offline |
| 19 | //! board but gets no live delays. |
| 20 | //! * `name` — `stop_name`. |
| 21 | //! * `route_type` — the GTFS route type of the most prominent mode serving the |
| 22 | //! stop, so the layer can be styled per mode. |
| 23 | //! |
| 24 | //! Mirrors `build_pois_layer.sh`'s shape: a Rust binary writes the geojsonseq |
| 25 | //! directly, with no osmium or python stage. |
| 26 | |
| 27 | use gtfs_ingest::gtfs::{self, Csv}; |
| 28 | use gtfs_ingest::manifest::{parse_feed_spec, read_manifest, FeedSpec}; |
| 29 | use gtfs_ingest::par; |
| 30 | use std::collections::HashMap; |
| 31 | use std::io::{BufWriter, Write}; |
| 32 | use std::path::{Path, PathBuf}; |
| 33 | use std::process::ExitCode; |
| 34 | |
| 35 | fn main() -> ExitCode { |
| 36 | let args: Vec<String> = std::env::args().collect(); |
| 37 | let mut geojson: Option<PathBuf> = None; |
| 38 | let mut manifest: Option<PathBuf> = None; |
| 39 | let mut inline: Vec<String> = Vec::new(); |
| 40 | |
| 41 | let mut i = 1; |
| 42 | while i < args.len() { |
| 43 | match args[i].as_str() { |
| 44 | "--geojson" => { |
| 45 | geojson = args.get(i + 1).map(PathBuf::from); |
| 46 | i += 2; |
| 47 | } |
| 48 | "--manifest" => { |
| 49 | manifest = args.get(i + 1).map(PathBuf::from); |
| 50 | i += 2; |
| 51 | } |
| 52 | "--threads" => { |
| 53 | let Some(raw) = args.get(i + 1) else { |
| 54 | eprintln!("transit_stops: --threads needs a value"); |
| 55 | return ExitCode::from(2); |
| 56 | }; |
| 57 | match par::parse_threads(raw) { |
| 58 | Ok(n) => par::set_threads(n), |
| 59 | Err(e) => { |
| 60 | eprintln!("transit_stops: {e}"); |
| 61 | return ExitCode::from(2); |
| 62 | } |
| 63 | } |
| 64 | i += 2; |
| 65 | } |
| 66 | "-h" | "--help" => { |
| 67 | usage(); |
| 68 | return ExitCode::SUCCESS; |
| 69 | } |
| 70 | other => { |
| 71 | inline.push(other.to_string()); |
| 72 | i += 1; |
| 73 | } |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | let Some(geojson) = geojson else { |
| 78 | eprintln!("transit_stops: --geojson is required"); |
| 79 | usage(); |
| 80 | return ExitCode::from(2); |
| 81 | }; |
| 82 | |
| 83 | let specs: Vec<FeedSpec> = match &manifest { |
| 84 | Some(m) => match read_manifest(m) { |
| 85 | Ok(v) => v, |
| 86 | Err(e) => { |
| 87 | eprintln!("transit_stops: {e}"); |
| 88 | return ExitCode::FAILURE; |
| 89 | } |
| 90 | }, |
| 91 | None => inline.iter().map(|s| parse_feed_spec(s)).collect(), |
| 92 | }; |
| 93 | |
| 94 | if specs.is_empty() { |
| 95 | eprintln!("transit_stops: no feeds given"); |
| 96 | usage(); |
| 97 | return ExitCode::from(2); |
| 98 | } |
| 99 | |
| 100 | match run(&geojson, &specs) { |
| 101 | Ok(()) => ExitCode::SUCCESS, |
| 102 | Err(e) => { |
| 103 | eprintln!("transit_stops: {e}"); |
| 104 | ExitCode::FAILURE |
| 105 | } |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | fn usage() { |
| 110 | eprintln!("usage: transit_stops --geojson OUT.geojsonseq <feed>... [--threads N]"); |
| 111 | eprintln!(" transit_stops --geojson OUT.geojsonseq --manifest FILE [--threads N]"); |
| 112 | eprintln!(" <feed> = feed_name=gtfs_dir[=motis_prefix] | gtfs_dir"); |
| 113 | } |
| 114 | |
| 115 | /// One emitted stop. |
| 116 | struct Stop { |
| 117 | lat_e7: i32, |
| 118 | lon_e7: i32, |
| 119 | name: String, |
| 120 | /// Empty when the feed carried no MOTIS prefix. |
| 121 | motis_id: String, |
| 122 | route_type: u32, |
| 123 | } |
| 124 | |
| 125 | /// What one feed contributes, before any cross-feed dedup. |
| 126 | struct FeedStops { |
| 127 | /// Candidates in `stops.txt` order, each with the dedup key already computed. |
| 128 | candidates: Vec<((i32, i32, String), Stop)>, |
| 129 | rows: usize, |
| 130 | } |
| 131 | |
| 132 | /// Read one feed and reduce it to candidates. Pure with respect to every other |
| 133 | /// feed, which is what lets these run concurrently. |
| 134 | fn read_feed(spec: &FeedSpec) -> Result<FeedStops, String> { |
| 135 | let (name, dir, motis_prefix) = spec; |
| 136 | let require = |file: &str| -> Result<Csv, String> { |
| 137 | gtfs::read_table(dir, file).ok_or_else(|| { |
| 138 | format!("feed '{name}' ({}) missing required GTFS file: {file}", dir.display()) |
| 139 | }) |
| 140 | }; |
| 141 | let stops_csv = require("stops.txt")?; |
| 142 | let routes_csv = require("routes.txt")?; |
| 143 | let trips_csv = require("trips.txt")?; |
| 144 | if motis_prefix.is_empty() { |
| 145 | eprintln!( |
| 146 | "transit_stops: warning: feed '{name}' has no MOTIS prefix; its stops \ |
| 147 | will carry no motis_id and get no realtime delays" |
| 148 | ); |
| 149 | } |
| 150 | |
| 151 | let stop_route_type = derive_stop_modes(&routes_csv, &trips_csv, dir).ok_or_else(|| { |
| 152 | format!("feed '{name}' ({}) missing required GTFS file: stop_times.txt", dir.display()) |
| 153 | })?; |
| 154 | |
| 155 | let mut out = FeedStops { candidates: Vec::new(), rows: 0 }; |
| 156 | for row in &stops_csv.rows { |
| 157 | out.rows += 1; |
| 158 | let id = stops_csv.get(row, "stop_id"); |
| 159 | if id.is_empty() { |
| 160 | continue; |
| 161 | } |
| 162 | // A stop no trip ever calls at is not boardable, and includes the |
| 163 | // unserved parent stations GTFS feeds carry alongside their platforms. |
| 164 | let Some(&route_type) = stop_route_type.get(id) else { continue }; |
| 165 | let Some((lat, lon)) = |
| 166 | gtfs::parse_lat_lon(stops_csv.get(row, "stop_lat"), stops_csv.get(row, "stop_lon")) |
| 167 | else { |
| 168 | continue; |
| 169 | }; |
| 170 | let stop_name = stops_csv.get(row, "stop_name").trim(); |
| 171 | let motis_id = |
| 172 | if motis_prefix.is_empty() { String::new() } else { format!("{motis_prefix}_{id}") }; |
| 173 | |
| 174 | // Dedup key: Transitous ships merged regional feeds (`SF-bayarea`) *and* the |
| 175 | // member agencies (`SFMTA`), so one physical platform appears several times. |
| 176 | // Keying on a coarsened position plus the name collapses those without |
| 177 | // merging genuinely distinct stops: 1e-4 deg is ~11 m, well under the gap |
| 178 | // between the two sides of a street. |
| 179 | let key = |
| 180 | ((lat * 1e4).round() as i32, (lon * 1e4).round() as i32, stop_name.to_lowercase()); |
| 181 | out.candidates.push(( |
| 182 | key, |
| 183 | Stop { |
| 184 | lat_e7: (lat * 1e7).round() as i32, |
| 185 | lon_e7: (lon * 1e7).round() as i32, |
| 186 | name: stop_name.to_string(), |
| 187 | motis_id, |
| 188 | route_type, |
| 189 | }, |
| 190 | )); |
| 191 | } |
| 192 | Ok(out) |
| 193 | } |
| 194 | |
| 195 | pub(crate) fn run(geojson: &Path, specs: &[FeedSpec]) -> Result<(), String> { |
| 196 | let mut seen: HashMap<(i32, i32, String), usize> = HashMap::new(); |
| 197 | let mut stops: Vec<Stop> = Vec::new(); |
| 198 | let mut total_rows = 0usize; |
| 199 | |
| 200 | // Feeds are read concurrently, in batches, and merged serially in SPEC ORDER. |
| 201 | // |
| 202 | // Per-feed reading is the cost — parsing stops/routes/trips and streaming |
| 203 | // stop_times — and it touches no cross-feed state. The merge is the opposite: the |
| 204 | // first-wins-then-upgrade rule below is order-dependent, so replaying it in spec |
| 205 | // order is what keeps the output byte-identical however the reads interleave. |
| 206 | // |
| 207 | // A batch at a time rather than all feeds at once, because a batch is what bounds |
| 208 | // live memory: a world build has hundreds of feeds and holding every feed's |
| 209 | // candidates would trade the peak this change exists to protect. |
| 210 | let batch = par::threads().max(1); |
| 211 | for chunk in specs.chunks(batch) { |
| 212 | let read: Vec<Result<FeedStops, String>> = if chunk.len() == 1 { |
| 213 | vec![read_feed(&chunk[0])] |
| 214 | } else { |
| 215 | std::thread::scope(|scope| { |
| 216 | let handles: Vec<_> = |
| 217 | chunk.iter().map(|spec| scope.spawn(|| read_feed(spec))).collect(); |
| 218 | handles |
| 219 | .into_iter() |
| 220 | .map(|h| h.join().unwrap_or_else(|_| Err("a feed reader panicked".to_string()))) |
| 221 | .collect() |
| 222 | }) |
| 223 | }; |
| 224 | |
| 225 | for (spec, feed) in chunk.iter().zip(read) { |
| 226 | let feed = feed?; |
| 227 | total_rows += feed.rows; |
| 228 | let mut emitted = 0usize; |
| 229 | for (key, candidate) in feed.candidates { |
| 230 | match seen.get(&key) { |
| 231 | // Prefer the duplicate we can name in MOTIS's id space, so the |
| 232 | // surviving pin is the one that can fetch live departures. |
| 233 | Some(&existing) => { |
| 234 | let keep = |
| 235 | stops[existing].motis_id.is_empty() && !candidate.motis_id.is_empty(); |
| 236 | if keep { |
| 237 | stops[existing] = candidate; |
| 238 | } |
| 239 | } |
| 240 | None => { |
| 241 | seen.insert(key, stops.len()); |
| 242 | stops.push(candidate); |
| 243 | emitted += 1; |
| 244 | } |
| 245 | } |
| 246 | } |
| 247 | eprintln!("transit_stops: feed '{}': {emitted} new stop(s)", spec.0); |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | // Deterministic output, so a rebuild produces a byte-identical layer and the |
| 252 | // tile diff is empty when nothing changed. |
| 253 | stops.sort_by(|a, b| { |
| 254 | a.lat_e7.cmp(&b.lat_e7).then(a.lon_e7.cmp(&b.lon_e7)).then_with(|| a.name.cmp(&b.name)) |
| 255 | }); |
| 256 | |
| 257 | let file = std::fs::File::create(geojson) |
| 258 | .map_err(|e| format!("cannot write {}: {e}", geojson.display()))?; |
| 259 | let mut out = BufWriter::new(file); |
| 260 | let mut line: Vec<u8> = Vec::new(); |
| 261 | let mut with_id = 0usize; |
| 262 | for s in &stops { |
| 263 | line.clear(); |
| 264 | write!( |
| 265 | line, |
| 266 | "{{\"type\":\"Feature\",\"geometry\":{{\"type\":\"Point\",\"coordinates\":[{:.7},{:.7}]}},\"properties\":{{\"name\":\"", |
| 267 | s.lon_e7 as f64 * 1e-7, |
| 268 | s.lat_e7 as f64 * 1e-7 |
| 269 | ) |
| 270 | .map_err(io_err)?; |
| 271 | json_escape(s.name.as_bytes(), &mut line); |
| 272 | line.extend_from_slice(b"\""); |
| 273 | if !s.motis_id.is_empty() { |
| 274 | with_id += 1; |
| 275 | line.extend_from_slice(b",\"motis_id\":\""); |
| 276 | json_escape(s.motis_id.as_bytes(), &mut line); |
| 277 | line.extend_from_slice(b"\""); |
| 278 | } |
| 279 | writeln!(line, ",\"route_type\":{}}}}}", s.route_type).map_err(io_err)?; |
| 280 | out.write_all(&line).map_err(io_err)?; |
| 281 | } |
| 282 | out.flush().map_err(io_err)?; |
| 283 | |
| 284 | eprintln!( |
| 285 | "transit_stops: wrote {} ({} stop(s) from {} rows, {with_id} with a motis_id)", |
| 286 | geojson.display(), |
| 287 | stops.len(), |
| 288 | total_rows, |
| 289 | ); |
| 290 | Ok(()) |
| 291 | } |
| 292 | |
| 293 | /// `stop_id` -> the GTFS route type of the most prominent mode calling there. |
| 294 | /// |
| 295 | /// GTFS has no stop->route table, so it is recovered through |
| 296 | /// `stop_times` -> `trips` -> `routes`. |
| 297 | /// |
| 298 | /// `stop_times.txt` is **streamed**, not read into a `Csv`. It is the largest file |
| 299 | /// in almost every feed — 5.8 GB for `great_britain`, and 52 GB once materialised as |
| 300 | /// `Vec<Vec<String>>` — while all this needs from a row is two borrowed strs. Doing |
| 301 | /// it the other way was what made sharding feeds across threads impossible: peak |
| 302 | /// memory would have multiplied by the thread count. |
| 303 | /// |
| 304 | /// `None` only when `stop_times.txt` is absent, which the caller reports as a |
| 305 | /// missing required file. |
| 306 | fn derive_stop_modes(routes: &Csv, trips: &Csv, dir: &Path) -> Option<HashMap<String, u32>> { |
| 307 | let trip_type = trip_modes(routes, trips); |
| 308 | let mut out: HashMap<String, u32> = HashMap::new(); |
| 309 | gtfs::stream_stop_times(dir, |r| { |
| 310 | fold_stop_mode(&mut out, &trip_type, r.trip_id, r.stop_id); |
| 311 | })?; |
| 312 | Some(out) |
| 313 | } |
| 314 | |
| 315 | /// `trip_id` -> normalized route type, for every trip whose route is known. |
| 316 | pub(crate) fn trip_modes<'a>(routes: &'a Csv, trips: &'a Csv) -> HashMap<&'a str, u32> { |
| 317 | let mut route_type: HashMap<&str, u32> = HashMap::new(); |
| 318 | for row in &routes.rows { |
| 319 | let id = routes.get(row, "route_id"); |
| 320 | if id.is_empty() { |
| 321 | continue; |
| 322 | } |
| 323 | let rt: u32 = routes.get(row, "route_type").trim().parse().unwrap_or(3); |
| 324 | route_type.insert(id, normalize_route_type(rt)); |
| 325 | } |
| 326 | |
| 327 | let mut trip_type: HashMap<&str, u32> = HashMap::new(); |
| 328 | for row in &trips.rows { |
| 329 | let id = trips.get(row, "trip_id"); |
| 330 | if id.is_empty() { |
| 331 | continue; |
| 332 | } |
| 333 | if let Some(&rt) = route_type.get(trips.get(row, "route_id")) { |
| 334 | trip_type.insert(id, rt); |
| 335 | } |
| 336 | } |
| 337 | trip_type |
| 338 | } |
| 339 | |
| 340 | /// Fold one `stop_times` row into the per-stop mode map, keeping the most prominent |
| 341 | /// mode. Order-independent: [`mode_rank`] decides, not arrival order. |
| 342 | pub(crate) fn fold_stop_mode( |
| 343 | out: &mut HashMap<String, u32>, |
| 344 | trip_type: &HashMap<&str, u32>, |
| 345 | trip_id: &str, |
| 346 | stop_id: &str, |
| 347 | ) { |
| 348 | if stop_id.is_empty() { |
| 349 | return; |
| 350 | } |
| 351 | let Some(&rt) = trip_type.get(trip_id) else { return }; |
| 352 | match out.get(stop_id) { |
| 353 | Some(&existing) if mode_rank(existing) <= mode_rank(rt) => {} |
| 354 | _ => { |
| 355 | out.insert(stop_id.to_string(), rt); |
| 356 | } |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | /// Fold GTFS's extended route types (the 100-1799 ranges) onto the basic set, so |
| 361 | /// the layer only ever has to style a handful of values. |
| 362 | pub(crate) fn normalize_route_type(rt: u32) -> u32 { |
| 363 | match rt { |
| 364 | 0..=7 | 11 | 12 => rt, |
| 365 | 100..=199 => 2, // railway service |
| 366 | 200..=299 => 3, // coach service |
| 367 | 300..=399 => 2, // suburban / regional rail |
| 368 | 400..=499 => 1, // urban railway / metro |
| 369 | 500..=599 => 1, // metro |
| 370 | 600..=699 => 1, // underground |
| 371 | 700..=799 => 3, // bus service |
| 372 | 800..=899 => 11, // trolleybus service |
| 373 | 900..=999 => 0, // tram service |
| 374 | 1000..=1099 => 4, // water transport |
| 375 | 1200..=1299 => 4, // ferry service |
| 376 | 1300..=1399 => 6, // aerial lift |
| 377 | 1400..=1499 => 7, // funicular |
| 378 | _ => 3, |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | /// Styling priority when several modes call at one stop: rail-like modes outrank |
| 383 | /// buses, so a subway entrance that also has a bus stop still reads as a subway. |
| 384 | /// Lower is more prominent. |
| 385 | fn mode_rank(rt: u32) -> u8 { |
| 386 | match rt { |
| 387 | 1 => 0, // subway / metro |
| 388 | 2 => 1, // rail |
| 389 | 0 => 2, // tram / light rail |
| 390 | 12 => 3, // monorail |
| 391 | 4 => 4, // ferry |
| 392 | 6 => 5, // aerial lift |
| 393 | 7 => 6, // funicular |
| 394 | 5 => 7, // cable tram |
| 395 | 3 | 11 => 8, // bus / trolleybus |
| 396 | _ => 9, |
| 397 | } |
| 398 | } |
| 399 | |
| 400 | fn io_err(e: impl std::fmt::Display) -> String { |
| 401 | format!("write failed: {e}") |
| 402 | } |
| 403 | |
| 404 | /// Escape a name for a JSON string. UTF-8 bytes pass through verbatim; only the |
| 405 | /// JSON-mandatory escapes and C0 controls are rewritten. Mirrors |
| 406 | /// `osm_ingest::poi_build`'s escaper so both layers quote identically. |
| 407 | pub(crate) fn json_escape(s: &[u8], out: &mut Vec<u8>) { |
| 408 | for &b in s { |
| 409 | match b { |
| 410 | b'"' => out.extend_from_slice(b"\\\""), |
| 411 | b'\\' => out.extend_from_slice(b"\\\\"), |
| 412 | b'\n' => out.extend_from_slice(b"\\n"), |
| 413 | b'\r' => out.extend_from_slice(b"\\r"), |
| 414 | b'\t' => out.extend_from_slice(b"\\t"), |
| 415 | 0x00..=0x1f => { |
| 416 | out.extend_from_slice(format!("\\u{:04x}", b).as_bytes()); |
| 417 | } |
| 418 | _ => out.push(b), |
| 419 | } |
| 420 | } |
| 421 | } |
| 422 | |
| 423 | #[path = "transit_stops_extra.rs"] |
| 424 | #[cfg(test)] |
| 425 | mod extra; |