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

Modern-Apps.git / scripts / maps / gtfs_ingest / src / bin / transit_stops.rs

transit_stops.rs445 lines · 15.8 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
27use gtfs_ingest::gtfs::{self, Csv};
28use gtfs_ingest::manifest::{parse_feed_spec, read_manifest, FeedSpec};
29use gtfs_ingest::par;
30use std::collections::HashMap;
31use std::io::{BufWriter, Write};
32use std::path::{Path, PathBuf};
33use std::process::ExitCode;
34
35fn 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
109fn 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.
116struct 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.
126struct 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.
134fn 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!(
153 "feed '{name}' ({}) missing required GTFS file: stop_times.txt",
154 dir.display()
155 )
156 })?;
157
158 let mut out = FeedStops {
159 candidates: Vec::new(),
160 rows: 0,
161 };
162 for row in &stops_csv.rows {
163 out.rows += 1;
164 let id = stops_csv.get(row, "stop_id");
165 if id.is_empty() {
166 continue;
167 }
168 // A stop no trip ever calls at is not boardable, and includes the
169 // unserved parent stations GTFS feeds carry alongside their platforms.
170 let Some(&route_type) = stop_route_type.get(id) else { continue };
171 let Some((lat, lon)) =
172 gtfs::parse_lat_lon(stops_csv.get(row, "stop_lat"), stops_csv.get(row, "stop_lon"))
173 else {
174 continue;
175 };
176 let stop_name = stops_csv.get(row, "stop_name").trim();
177 let motis_id = if motis_prefix.is_empty() {
178 String::new()
179 } else {
180 format!("{motis_prefix}_{id}")
181 };
182
183 // Dedup key: Transitous ships merged regional feeds (`SF-bayarea`) *and* the
184 // member agencies (`SFMTA`), so one physical platform appears several times.
185 // Keying on a coarsened position plus the name collapses those without
186 // merging genuinely distinct stops: 1e-4 deg is ~11 m, well under the gap
187 // between the two sides of a street.
188 let key = (
189 (lat * 1e4).round() as i32,
190 (lon * 1e4).round() as i32,
191 stop_name.to_lowercase(),
192 );
193 out.candidates.push((
194 key,
195 Stop {
196 lat_e7: (lat * 1e7).round() as i32,
197 lon_e7: (lon * 1e7).round() as i32,
198 name: stop_name.to_string(),
199 motis_id,
200 route_type,
201 },
202 ));
203 }
204 Ok(out)
205}
206
207pub(crate) fn run(geojson: &Path, specs: &[FeedSpec]) -> Result<(), String> {
208 let mut seen: HashMap<(i32, i32, String), usize> = HashMap::new();
209 let mut stops: Vec<Stop> = Vec::new();
210 let mut total_rows = 0usize;
211
212 // Feeds are read concurrently, in batches, and merged serially in SPEC ORDER.
213 //
214 // Per-feed reading is the cost — parsing stops/routes/trips and streaming
215 // stop_times — and it touches no cross-feed state. The merge is the opposite: the
216 // first-wins-then-upgrade rule below is order-dependent, so replaying it in spec
217 // order is what keeps the output byte-identical however the reads interleave.
218 //
219 // A batch at a time rather than all feeds at once, because a batch is what bounds
220 // live memory: a world build has hundreds of feeds and holding every feed's
221 // candidates would trade the peak this change exists to protect.
222 let batch = par::threads().max(1);
223 for chunk in specs.chunks(batch) {
224 let read: Vec<Result<FeedStops, String>> = if chunk.len() == 1 {
225 vec![read_feed(&chunk[0])]
226 } else {
227 std::thread::scope(|scope| {
228 let handles: Vec<_> = chunk
229 .iter()
230 .map(|spec| scope.spawn(|| read_feed(spec)))
231 .collect();
232 handles
233 .into_iter()
234 .map(|h| {
235 h.join()
236 .unwrap_or_else(|_| Err("a feed reader panicked".to_string()))
237 })
238 .collect()
239 })
240 };
241
242 for (spec, feed) in chunk.iter().zip(read) {
243 let feed = feed?;
244 total_rows += feed.rows;
245 let mut emitted = 0usize;
246 for (key, candidate) in feed.candidates {
247 match seen.get(&key) {
248 // Prefer the duplicate we can name in MOTIS's id space, so the
249 // surviving pin is the one that can fetch live departures.
250 Some(&existing) => {
251 let keep = stops[existing].motis_id.is_empty()
252 && !candidate.motis_id.is_empty();
253 if keep {
254 stops[existing] = candidate;
255 }
256 }
257 None => {
258 seen.insert(key, stops.len());
259 stops.push(candidate);
260 emitted += 1;
261 }
262 }
263 }
264 eprintln!("transit_stops: feed '{}': {emitted} new stop(s)", spec.0);
265 }
266 }
267
268 // Deterministic output, so a rebuild produces a byte-identical layer and the
269 // tile diff is empty when nothing changed.
270 stops.sort_by(|a, b| {
271 a.lat_e7
272 .cmp(&b.lat_e7)
273 .then(a.lon_e7.cmp(&b.lon_e7))
274 .then_with(|| a.name.cmp(&b.name))
275 });
276
277 let file = std::fs::File::create(geojson)
278 .map_err(|e| format!("cannot write {}: {e}", geojson.display()))?;
279 let mut out = BufWriter::new(file);
280 let mut line: Vec<u8> = Vec::new();
281 let mut with_id = 0usize;
282 for s in &stops {
283 line.clear();
284 write!(
285 line,
286 "{{\"type\":\"Feature\",\"geometry\":{{\"type\":\"Point\",\"coordinates\":[{:.7},{:.7}]}},\"properties\":{{\"name\":\"",
287 s.lon_e7 as f64 * 1e-7,
288 s.lat_e7 as f64 * 1e-7
289 )
290 .map_err(io_err)?;
291 json_escape(s.name.as_bytes(), &mut line);
292 line.extend_from_slice(b"\"");
293 if !s.motis_id.is_empty() {
294 with_id += 1;
295 line.extend_from_slice(b",\"motis_id\":\"");
296 json_escape(s.motis_id.as_bytes(), &mut line);
297 line.extend_from_slice(b"\"");
298 }
299 writeln!(line, ",\"route_type\":{}}}}}", s.route_type).map_err(io_err)?;
300 out.write_all(&line).map_err(io_err)?;
301 }
302 out.flush().map_err(io_err)?;
303
304 eprintln!(
305 "transit_stops: wrote {} ({} stop(s) from {} rows, {with_id} with a motis_id)",
306 geojson.display(),
307 stops.len(),
308 total_rows,
309 );
310 Ok(())
311}
312
313/// `stop_id` -> the GTFS route type of the most prominent mode calling there.
314///
315/// GTFS has no stop->route table, so it is recovered through
316/// `stop_times` -> `trips` -> `routes`.
317///
318/// `stop_times.txt` is **streamed**, not read into a `Csv`. It is the largest file
319/// in almost every feed — 5.8 GB for `great_britain`, and 52 GB once materialised as
320/// `Vec<Vec<String>>` — while all this needs from a row is two borrowed strs. Doing
321/// it the other way was what made sharding feeds across threads impossible: peak
322/// memory would have multiplied by the thread count.
323///
324/// `None` only when `stop_times.txt` is absent, which the caller reports as a
325/// missing required file.
326fn derive_stop_modes(routes: &Csv, trips: &Csv, dir: &Path) -> Option<HashMap<String, u32>> {
327 let trip_type = trip_modes(routes, trips);
328 let mut out: HashMap<String, u32> = HashMap::new();
329 gtfs::stream_stop_times(dir, |r| {
330 fold_stop_mode(&mut out, &trip_type, r.trip_id, r.stop_id);
331 })?;
332 Some(out)
333}
334
335/// `trip_id` -> normalized route type, for every trip whose route is known.
336pub(crate) fn trip_modes<'a>(routes: &'a Csv, trips: &'a Csv) -> HashMap<&'a str, u32> {
337 let mut route_type: HashMap<&str, u32> = HashMap::new();
338 for row in &routes.rows {
339 let id = routes.get(row, "route_id");
340 if id.is_empty() {
341 continue;
342 }
343 let rt: u32 = routes.get(row, "route_type").trim().parse().unwrap_or(3);
344 route_type.insert(id, normalize_route_type(rt));
345 }
346
347 let mut trip_type: HashMap<&str, u32> = HashMap::new();
348 for row in &trips.rows {
349 let id = trips.get(row, "trip_id");
350 if id.is_empty() {
351 continue;
352 }
353 if let Some(&rt) = route_type.get(trips.get(row, "route_id")) {
354 trip_type.insert(id, rt);
355 }
356 }
357 trip_type
358}
359
360/// Fold one `stop_times` row into the per-stop mode map, keeping the most prominent
361/// mode. Order-independent: [`mode_rank`] decides, not arrival order.
362pub(crate) fn fold_stop_mode(
363 out: &mut HashMap<String, u32>,
364 trip_type: &HashMap<&str, u32>,
365 trip_id: &str,
366 stop_id: &str,
367) {
368 if stop_id.is_empty() {
369 return;
370 }
371 let Some(&rt) = trip_type.get(trip_id) else { return };
372 match out.get(stop_id) {
373 Some(&existing) if mode_rank(existing) <= mode_rank(rt) => {}
374 _ => {
375 out.insert(stop_id.to_string(), rt);
376 }
377 }
378}
379
380/// Fold GTFS's extended route types (the 100-1799 ranges) onto the basic set, so
381/// the layer only ever has to style a handful of values.
382pub(crate) fn normalize_route_type(rt: u32) -> u32 {
383 match rt {
384 0..=7 | 11 | 12 => rt,
385 100..=199 => 2, // railway service
386 200..=299 => 3, // coach service
387 300..=399 => 2, // suburban / regional rail
388 400..=499 => 1, // urban railway / metro
389 500..=599 => 1, // metro
390 600..=699 => 1, // underground
391 700..=799 => 3, // bus service
392 800..=899 => 11, // trolleybus service
393 900..=999 => 0, // tram service
394 1000..=1099 => 4, // water transport
395 1200..=1299 => 4, // ferry service
396 1300..=1399 => 6, // aerial lift
397 1400..=1499 => 7, // funicular
398 _ => 3,
399 }
400}
401
402/// Styling priority when several modes call at one stop: rail-like modes outrank
403/// buses, so a subway entrance that also has a bus stop still reads as a subway.
404/// Lower is more prominent.
405fn mode_rank(rt: u32) -> u8 {
406 match rt {
407 1 => 0, // subway / metro
408 2 => 1, // rail
409 0 => 2, // tram / light rail
410 12 => 3, // monorail
411 4 => 4, // ferry
412 6 => 5, // aerial lift
413 7 => 6, // funicular
414 5 => 7, // cable tram
415 3 | 11 => 8, // bus / trolleybus
416 _ => 9,
417 }
418}
419
420fn io_err(e: impl std::fmt::Display) -> String {
421 format!("write failed: {e}")
422}
423
424/// Escape a name for a JSON string. UTF-8 bytes pass through verbatim; only the
425/// JSON-mandatory escapes and C0 controls are rewritten. Mirrors
426/// `osm_ingest::poi_build`'s escaper so both layers quote identically.
427pub(crate) fn json_escape(s: &[u8], out: &mut Vec<u8>) {
428 for &b in s {
429 match b {
430 b'"' => out.extend_from_slice(b"\\\""),
431 b'\\' => out.extend_from_slice(b"\\\\"),
432 b'\n' => out.extend_from_slice(b"\\n"),
433 b'\r' => out.extend_from_slice(b"\\r"),
434 b'\t' => out.extend_from_slice(b"\\t"),
435 0x00..=0x1f => {
436 out.extend_from_slice(format!("\\u{:04x}", b).as_bytes());
437 }
438 _ => out.push(b),
439 }
440 }
441}
442
443#[path = "transit_stops_extra.rs"]
444#[cfg(test)]
445mod extra;