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

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

transit_dump.rs419 lines · 16.1 KiBRaw
1//! `transit_dump` — a sort-stable, semantic text dump of a `.transit` pack.
2//!
3//! The pack's *bytes* are deliberately non-reproducible: trips are grouped out of
4//! a `HashMap`, so RAPTOR route order, profile ids and service indices all vary
5//! run to run (see the crate README). Byte-diffing two packs therefore proves
6//! nothing. This dump exists so a refactor of the builder can be verified the
7//! only way that is actually valid: dump before, dump after, `diff`, expect
8//! empty.
9//!
10//! Everything whose order is a `HashMap` artefact is either sorted (route blocks,
11//! trip lines) or replaced by a content signature (services, referenced by their
12//! calendar + exceptions rather than by index). Everything whose order *is*
13//! contractual — stop indices, grid cells, a route's stop pattern, a route's
14//! trips by start time — is dumped in that order, so a reordering shows up.
15//!
16//! Usage:
17//! `transit_dump <pack.transit> [out.txt]` full dump (stdout when omitted)
18//! `transit_dump --at <lat>,<lon> <pack>` one stop's departure board
19//!
20//! The full dump is one line per stop and one per trip, so it is much larger than
21//! the pack — meant for the small verification corpora, not `world`. `--at` is the
22//! spot check for a big pack: it answers "does this coordinate resolve to the
23//! right stop, do plausible routes depart it, and does it reach another agency's
24//! stops on foot" without materializing gigabytes of text.
25
26use gtfs_ingest::reader::{Reader, RouteRec};
27use std::collections::{HashMap, HashSet};
28use std::io::{BufWriter, Write};
29use std::process::ExitCode;
30
31enum Cmd<'a> {
32 Dump { pack: &'a str, out: Option<&'a str> },
33 Probe { pack: &'a str, lat: f64, lon: f64 },
34}
35
36fn main() -> ExitCode {
37 let args: Vec<String> = std::env::args().collect();
38 let cmd = match parse_args(&args) {
39 Ok(c) => c,
40 Err(e) => {
41 eprintln!("transit_dump: {e}\n{USAGE}");
42 // 2 for "you invoked it wrong", 1 for "it ran and failed".
43 return ExitCode::from(2);
44 }
45 };
46 let result = match cmd {
47 Cmd::Probe { pack, lat, lon } => Reader::open(std::path::Path::new(pack))
48 .and_then(|r| {
49 let stdout = std::io::stdout();
50 probe(&r, lat, lon, &mut BufWriter::new(stdout.lock()))
51 }),
52 Cmd::Dump { pack, out } => Reader::open(std::path::Path::new(pack)).and_then(|r| {
53 match out {
54 Some(path) => match std::fs::File::create(path) {
55 Ok(f) => dump(&r, &mut BufWriter::new(f)),
56 Err(e) => Err(format!("cannot create {path}: {e}")),
57 },
58 None => {
59 let stdout = std::io::stdout();
60 dump(&r, &mut BufWriter::new(stdout.lock()))
61 }
62 }
63 }),
64 };
65 match result {
66 Ok(()) => ExitCode::SUCCESS,
67 Err(e) => {
68 eprintln!("transit_dump: {e}");
69 ExitCode::FAILURE
70 }
71 }
72}
73
74const USAGE: &str = "usage: transit_dump <pack.transit> [out.txt]\n \
75 transit_dump --at <lat>,<lon> <pack.transit>";
76
77fn parse_args(args: &[String]) -> Result<Cmd<'_>, String> {
78 match args.get(1).map(String::as_str) {
79 Some("--at") => {
80 let (at, pack) = match (args.get(2), args.get(3), args.len()) {
81 (Some(at), Some(pack), 4) => (at.as_str(), pack.as_str()),
82 _ => return Err("--at takes a lat,lon and one pack".to_string()),
83 };
84 let (lat, lon) =
85 at.split_once(',').ok_or_else(|| format!("--at wants lat,lon, got {at:?}"))?;
86 let lat: f64 = lat.trim().parse().map_err(|_| format!("bad latitude {lat:?}"))?;
87 let lon: f64 = lon.trim().parse().map_err(|_| format!("bad longitude {lon:?}"))?;
88 // Checked because the grid lookup clamps rather than rejects, so a
89 // transposed `lon,lat` would otherwise return a confidently wrong
90 // "nearest" stop instead of an error.
91 if !(-90.0..=90.0).contains(&lat) || !(-180.0..=180.0).contains(&lon) {
92 return Err(format!("{lat},{lon} is not a lat,lon — are they the right way round?"));
93 }
94 Ok(Cmd::Probe { pack, lat, lon })
95 }
96 Some(pack) if args.len() <= 3 => {
97 Ok(Cmd::Dump { pack, out: args.get(2).map(String::as_str) })
98 }
99 _ => Err("expected a pack path".to_string()),
100 }
101}
102
103/// Seconds since service midnight as `HH:MM:SS`; hours may exceed 24, which is
104/// legal GTFS and means "after midnight on the service day".
105fn hms(secs: u32) -> String {
106 format!("{:02}:{:02}:{:02}", secs / 3600, (secs / 60) % 60, secs % 60)
107}
108
109/// Approximate ground distance in metres (equirectangular; fine at this range).
110fn metres(lat1: f64, lon1: f64, lat2: f64, lon2: f64) -> f64 {
111 let dlat = (lat2 - lat1) * 111_320.0;
112 let dlon = (lon2 - lon1) * 111_320.0 * ((lat1 + lat2) * 0.5).to_radians().cos();
113 (dlat * dlat + dlon * dlon).sqrt()
114}
115
116/// The nearest stop to `(lat, lon)` with every route that serves it, that route's
117/// departures *from this stop*, and the footpaths leading away from it.
118///
119/// `first`/`last` span every trip on the route regardless of calendar, so `svcs`
120/// reports how many distinct services those trips belong to — a route whose span
121/// looks odd is usually one mixing a weekday and a weekend calendar. At a route's
122/// terminus the profile's departure equals its arrival, which is marked rather
123/// than presented as a departure that never happens.
124fn probe(r: &Reader, lat: f64, lon: f64, out: &mut impl Write) -> Result<(), String> {
125 let stop = r
126 .nearest(lat, lon)
127 .ok_or_else(|| format!("no stop near {lat},{lon}; is it inside the pack's bbox?"))?;
128 let (min_lat, min_lon, max_lat, max_lon) = r.bbox();
129 let (slat, slon) = r.stop_ll(stop);
130 let mut w = |s: String| out.write_all(s.as_bytes()).map_err(|e| format!("write: {e}"));
131
132 w(format!(
133 "pack {:?} bbox {:.6},{:.6} .. {:.6},{:.6}\n",
134 r.pack_name(),
135 min_lat as f64 * 1e-7,
136 min_lon as f64 * 1e-7,
137 max_lat as f64 * 1e-7,
138 max_lon as f64 * 1e-7,
139 ))?;
140 // The distance matters: `nearest` searches only ±1 grid cell, exactly as the
141 // device does, so it answers with whatever it finds there — a coordinate well
142 // outside the transit area still resolves to *something*.
143 w(format!(
144 "nearest stop {stop} name={:?} gtfs={:?} code={:?} at {slat:.6},{slon:.6} ({:.0} m away)\n",
145 r.stop_name(stop),
146 r.stop_gtfs_id(stop),
147 r.stop_code(stop),
148 metres(lat, lon, slat, slon),
149 ))?;
150
151 // Which feed a stop belongs to is not stored; it is whichever feeds' routes
152 // serve it, which is also what makes a footpath between two feeds visible.
153 let feeds_of = |s: u32| -> Vec<String> {
154 let mut names: Vec<String> = r
155 .stop_routes(s)
156 .iter()
157 .map(|&(route, _)| r.feed_name(r.route(route).feed_idx))
158 .collect::<HashSet<_>>()
159 .into_iter()
160 .collect();
161 names.sort();
162 names
163 };
164
165 let mut routes = r.stop_routes(stop);
166 routes.sort_by_key(|&(route, _)| r.read_str(r.route(route).name_off));
167 for (route, pos) in routes {
168 let rec = r.route(route);
169 let trips = r.route_trips(&rec);
170 // The board is the departure at *this* stop, not the trip's start.
171 let mut deps: Vec<u32> = trips
172 .iter()
173 .map(|t| {
174 let prof = r.profile(t.profile_id);
175 (t.start_time as i64 + prof[pos as usize].1) as u32
176 })
177 .collect();
178 deps.sort_unstable();
179 let services: HashSet<u32> = trips.iter().map(|t| t.service_idx).collect();
180 w(format!(
181 " route {:?} type={} feed={:?} pos={pos}/{}{} trips={} svcs={} first={} last={}\n",
182 r.read_str(rec.name_off),
183 rec.route_type,
184 r.feed_name(rec.feed_idx),
185 rec.n_stops,
186 if pos + 1 == rec.n_stops { " terminus" } else { "" },
187 deps.len(),
188 services.len(),
189 deps.first().copied().map_or("-".to_string(), hms),
190 deps.last().copied().map_or("-".to_string(), hms),
191 ))?;
192 }
193
194 let here = feeds_of(stop);
195 for (to, secs) in r.transfers(stop) {
196 let there = feeds_of(to);
197 // "cross-feed", not "cross-agency": one feed may carry several agencies,
198 // and only the feed is recorded per route.
199 let cross = !here.is_empty() && there.iter().any(|f| !here.contains(f));
200 w(format!(
201 " footpath {secs}s -> stop {to} name={:?} feeds={:?}{}\n",
202 r.stop_name(to),
203 there,
204 if cross { " [cross-feed]" } else { "" },
205 ))?;
206 }
207 out.flush().map_err(|e| format!("flush failed: {e}"))
208}
209
210fn dump(r: &Reader, out: &mut impl Write) -> Result<(), String> {
211 let write = |out: &mut dyn Write, s: String| -> Result<(), String> {
212 out.write_all(s.as_bytes()).map_err(|e| format!("write failed: {e}"))
213 };
214
215 write(out, format!("pack {:?}\n", r.pack_name()))?;
216 write(out, format!("version {} sections {}\n", r.version(), r.section_count()))?;
217 write(
218 out,
219 format!(
220 "counts stops={} routes={} trips={} services={} profiles={} feeds={} grid_cells={}\n",
221 r.stop_count(),
222 r.route_count(),
223 r.trip_count(),
224 r.service_count(),
225 r.profile_count(),
226 r.feed_count(),
227 r.grid_cell_count(),
228 ),
229 )?;
230 let (min_lat, min_lon, max_lat, max_lon) = r.bbox();
231 write(out, format!("bbox {min_lat} {min_lon} {max_lat} {max_lon}\n"))?;
232 let g = r.grid();
233 write(
234 out,
235 format!(
236 "grid origin={},{} cell={} cols={} rows={}\n",
237 g.lat0_e7, g.lon0_e7, g.cell_e7, g.cols, g.rows
238 ),
239 )?;
240
241 // Services are referenced by content, not index: a service that only ever
242 // appears on a trip is registered while iterating a `HashMap`, so its index
243 // is one of the things that legitimately moves between runs.
244 let sigs: Vec<String> = (0..r.service_count()).map(|s| service_sig(r, s)).collect();
245
246 // --- Routes, grouped by feed and sorted within it ---
247 let mut per_feed: Vec<Vec<String>> = vec![Vec::new(); r.feed_count() as usize];
248 for ridx in 0..r.route_count() {
249 let rec = r.route(ridx);
250 per_feed[rec.feed_idx as usize].push(route_block(r, ridx, &rec, &sigs));
251 }
252 for feed in 0..r.feed_count() {
253 write(
254 out,
255 format!(
256 "feed {feed} name={:?} tz={:?} motis={:?}\n",
257 r.feed_name(feed),
258 r.feed_tz(feed),
259 r.feed_motis_prefix(feed)
260 ),
261 )?;
262 let blocks = &mut per_feed[feed as usize];
263 blocks.sort();
264 for b in blocks.iter() {
265 write(out, b.clone())?;
266 }
267 }
268
269 // --- Stops, in index order (per-feed contiguous, stops.txt order within) ---
270 for s in 0..r.stop_count() {
271 let (lat, lon) = r.stop_ll_e7(s);
272 // A stop's routes come out of the builder in route order, which moves;
273 // name them and sort.
274 let mut routes: Vec<String> = r
275 .stop_routes(s)
276 .iter()
277 .map(|&(route, pos)| format!("{:?}@{pos}", r.read_str(r.route(route).name_off)))
278 .collect();
279 routes.sort();
280 let transfers: Vec<String> =
281 r.transfers(s).iter().map(|&(to, secs)| format!("{to}:{secs}")).collect();
282 write(
283 out,
284 format!(
285 "stop {s} gtfs={:?} name={:?} code={:?} ll={lat},{lon} routes=[{}] transfers=[{}]\n",
286 r.stop_gtfs_id(s),
287 r.stop_name(s),
288 r.stop_code(s),
289 routes.join(" "),
290 transfers.join(" "),
291 ),
292 )?;
293 }
294
295 // --- Distinct service definitions, sorted, with how many services share one ---
296 let mut sig_counts: HashMap<&str, usize> = HashMap::new();
297 for sig in &sigs {
298 *sig_counts.entry(sig.as_str()).or_insert(0) += 1;
299 }
300 let mut distinct: Vec<(&&str, &usize)> = sig_counts.iter().collect();
301 distinct.sort();
302 for (sig, n) in distinct {
303 write(out, format!("service x{n} {sig}\n"))?;
304 }
305
306 // --- Spatial grid, in file order (the reader binary-searches it ascending) ---
307 let cells = r.grid_cells();
308 assert!(
309 cells.windows(2).all(|w| w[0].0 < w[1].0),
310 "GRID_CELL_IDS must be strictly ascending or the device's binary search breaks"
311 );
312 for (cid, stops) in &cells {
313 let list: Vec<String> = stops.iter().map(|s| s.to_string()).collect();
314 write(out, format!("cell {cid} stops=[{}]\n", list.join(" ")))?;
315 }
316
317 out.flush().map_err(|e| format!("flush failed: {e}"))
318}
319
320/// One service's calendar plus its exceptions, as a content signature.
321fn service_sig(r: &Reader, service_idx: u32) -> String {
322 let svc = r.service(service_idx);
323 let exc = r.service_exceptions(service_idx);
324 assert!(
325 exc.windows(2).all(|w| w[0].1 < w[1].1),
326 "service {service_idx} exceptions must be date-ascending and deduped, got {exc:?}"
327 );
328 let dates: Vec<String> = exc
329 .iter()
330 .map(|&(sidx, date, added)| {
331 assert_eq!(sidx, service_idx, "EXCEPTIONS row outside its CSR range");
332 format!("{}{date}", if added == 1 { '+' } else { '-' })
333 })
334 .collect();
335 format!(
336 "days={:07b} {}..{} exc=[{}]",
337 svc.weekday_mask,
338 svc.start_date,
339 svc.end_date,
340 dates.join(" ")
341 )
342}
343
344/// A whole route: its identity, geometry summary, stop pattern and every trip
345/// with profile-expanded absolute times.
346fn route_block(r: &Reader, ridx: u32, rec: &RouteRec, sigs: &[String]) -> String {
347 let stops = r.route_stops(rec);
348 let pattern: Vec<String> = stops
349 .iter()
350 .enumerate()
351 .map(|(pos, &s)| {
352 let v = r.route_stop_shape(rec.first_route_stop + pos as u32);
353 if v == u32::MAX {
354 format!("{s}")
355 } else {
356 format!("{s}@{v}")
357 }
358 })
359 .collect();
360 let shape = match r.route_shape_off(ridx) {
361 None => "none".to_string(),
362 Some(off) => {
363 let pts = r.shape_points(off);
364 format!("n={},sum={:016x}", pts.len(), fnv1a_points(&pts))
365 }
366 };
367 let mut lines = vec![format!(
368 " route name={:?} type={} color={:06x} shape={shape} stops=[{}]\n",
369 r.read_str(rec.name_off),
370 rec.route_type,
371 rec.color,
372 pattern.join(" "),
373 )];
374
375 // Trips are start-time ordered by construction, but ties are `HashMap`
376 // order, so sort the rendered lines. Zero-padding keeps that a numeric sort.
377 let mut trips: Vec<String> = r
378 .route_trips(rec)
379 .iter()
380 .map(|t| {
381 let start = t.start_time as i64;
382 let times: Vec<String> = r
383 .profile(t.profile_id)
384 .iter()
385 .map(|&(arr, dep)| format!("{}:{}", start + arr, start + dep))
386 .collect();
387 assert_eq!(
388 times.len(),
389 stops.len(),
390 "route {ridx} trip at {start} has {} profile entries for {} stops",
391 times.len(),
392 stops.len()
393 );
394 format!(
395 " trip start={:08} svc={} headsign={:?} times=[{}]\n",
396 t.start_time,
397 sigs[t.service_idx as usize],
398 r.read_str(t.headsign_off),
399 times.join(" "),
400 )
401 })
402 .collect();
403 trips.sort();
404 lines.append(&mut trips);
405 lines.concat()
406}
407
408/// FNV-1a over a polyline's coordinates: a full comparison of the geometry
409/// without printing every vertex of every route.
410fn fnv1a_points(pts: &[(i32, i32)]) -> u64 {
411 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
412 for &(lat, lon) in pts {
413 for b in lat.to_le_bytes().iter().chain(lon.to_le_bytes().iter()) {
414 h ^= *b as u64;
415 h = h.wrapping_mul(0x100_0000_01b3);
416 }
417 }
418 h
419}