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

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

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