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

Modern-Apps.git / scripts / maps / gtfs_ingest / src / gtfs.rs

gtfs.rs496 lines · 19.9 KiBRaw
1//! Minimal, dependency-free GTFS reader: an RFC 4180-ish CSV parser plus typed
2//! loaders for the GTFS files the offline transit index needs
3//! (`stops`, `routes`, `trips`, `stop_times`, `calendar`, `calendar_dates`,
4//! `shapes`).
5//!
6//! GTFS is CSV text; times may exceed 24:00:00 (legal, means "after service
7//! midnight"). We keep everything in seconds-since-service-midnight.
8//!
9//! `stop_times.txt` and `shapes.txt` get streaming loaders rather than a [`Csv`]:
10//! they are the two largest files in a feed, and a `Csv` would hold every
11//! coordinate and every time as a `String`.
12
13use std::borrow::Cow;
14use std::collections::HashMap;
15use std::io::BufRead;
16use std::path::Path;
17
18pub(crate) use crate::gtfs_extra::{RawShapePoint, split_line};
19
20/// A parsed CSV table: the header row plus data rows (each a `Vec<String>`).
21pub struct Csv {
22 header: Vec<String>,
23 pub rows: Vec<Vec<String>>,
24 col: HashMap<String, usize>,
25}
26
27impl Csv {
28 /// Index of the named column, if present.
29 pub fn idx(&self, name: &str) -> Option<usize> {
30 self.col.get(name).copied()
31 }
32
33 /// Cell value for `row` at column `name`, or "" when absent/short.
34 pub fn get<'a>(&self, row: &'a [String], name: &str) -> &'a str {
35 match self.idx(name).and_then(|i| row.get(i)) {
36 Some(s) => s.as_str(),
37 None => "",
38 }
39 }
40
41 #[allow(dead_code)]
42 pub fn header(&self) -> &[String] {
43 &self.header
44 }
45}
46
47/// Parse RFC 4180-ish CSV from `text`. Handles quoted fields containing commas,
48/// embedded newlines and escaped quotes (`""`), plus a leading UTF-8 BOM.
49pub fn parse_csv(text: &str) -> Csv {
50 let mut records: Vec<Vec<String>> = Vec::new();
51 let mut field = String::new();
52 let mut record: Vec<String> = Vec::new();
53 let mut in_quotes = false;
54 let mut chars = text.chars().peekable();
55 let mut started = false;
56
57 // Strip a leading BOM if present.
58 if let Some('\u{feff}') = chars.peek().copied() {
59 let _ = chars.next();
60 }
61
62 while let Some(c) = chars.next() {
63 started = true;
64 if in_quotes {
65 if c == '"' {
66 if chars.peek().copied() == Some('"') {
67 field.push('"');
68 let _ = chars.next();
69 } else {
70 in_quotes = false;
71 }
72 } else {
73 field.push(c);
74 }
75 continue;
76 }
77 match c {
78 '"' => in_quotes = true,
79 ',' => {
80 record.push(std::mem::take(&mut field));
81 }
82 '\r' => { /* swallow; handled by \n */ }
83 '\n' => {
84 record.push(std::mem::take(&mut field));
85 records.push(std::mem::take(&mut record));
86 }
87 _ => field.push(c),
88 }
89 }
90 // Flush a trailing record with no final newline.
91 if started && (!field.is_empty() || !record.is_empty()) {
92 record.push(field);
93 records.push(record);
94 }
95
96 let mut iter = records.into_iter();
97 let header = iter.next().unwrap_or_default();
98 let mut col = HashMap::new();
99 for (i, h) in header.iter().enumerate() {
100 col.insert(h.trim().to_string(), i);
101 }
102 let rows: Vec<Vec<String>> = iter.filter(|r| !(r.len() == 1 && r[0].is_empty())).collect();
103 Csv { header, rows, col }
104}
105
106/// Read `dir/name` as UTF-8 (lossy) and parse it as CSV. Returns `None` when the
107/// file is absent (optional GTFS files such as `calendar_dates.txt`).
108pub fn read_table(dir: &Path, name: &str) -> Option<Csv> {
109 let path = dir.join(name);
110 let bytes = std::fs::read(&path).ok()?;
111 Some(parse_csv(&String::from_utf8_lossy(&bytes)))
112}
113
114/// Parse a GTFS `HH:MM:SS` time (hours may exceed 24) into seconds since
115/// service midnight. Returns `None` for blank/malformed values.
116pub fn parse_gtfs_time(s: &str) -> Option<u32> {
117 let s = s.trim();
118 if s.is_empty() {
119 return None;
120 }
121 let mut parts = s.split(':');
122 let h: u32 = parts.next()?.trim().parse().ok()?;
123 let m: u32 = parts.next()?.trim().parse().ok()?;
124 let sec: u32 = parts.next().unwrap_or("0").trim().parse().ok()?;
125 Some(h * 3600 + m * 60 + sec)
126}
127
128/// Parse a GTFS `YYYYMMDD` service date into an integer `yyyymmdd`.
129pub fn parse_gtfs_date(s: &str) -> Option<u32> {
130 let s = s.trim();
131 if s.len() != 8 {
132 return None;
133 }
134 s.parse().ok()
135}
136
137/// Parse a `stop_lat`/`stop_lon` pair, rejecting anything that is not a finite
138/// coordinate inside the WGS84 ranges.
139///
140/// The range check is not pedantry: `(lat * 1e7) as i32` **saturates**, so a feed
141/// with `stop_lat = 500` yields `i32::MAX` rather than an error. One such row sets
142/// a whole pack's bbox to `i32::MAX`, at which point the device's `covers()` adds
143/// its 5.5 km margin to that, overflows, and concludes the pack covers *nothing*.
144/// A single bad stop in one of 1272 feeds could therefore disable transit routing
145/// for the entire pack.
146///
147/// Returns degrees, not `e7`, because callers disagree on rounding — the index
148/// truncates and `transit_stops` rounds — and neither may change.
149pub fn parse_lat_lon(lat: &str, lon: &str) -> Option<(f64, f64)> {
150 let lat: f64 = lat.trim().parse().ok()?;
151 let lon: f64 = lon.trim().parse().ok()?;
152 // A range `contains` is false for NaN and for both infinities, so this
153 // subsumes the finiteness check.
154 if !(-90.0..=90.0).contains(&lat) || !(-180.0..=180.0).contains(&lon) {
155 return None;
156 }
157 Some((lat, lon))
158}
159
160/// GTFS lets a `stop_times.txt` row give only one of arrival/departure; the
161/// missing one means "no dwell here". A row with neither is unusable.
162pub fn stop_time_pair(arrival: &str, departure: &str) -> Option<(u32, u32)> {
163 match (parse_gtfs_time(arrival), parse_gtfs_time(departure)) {
164 (Some(a), Some(d)) => Some((a, d)),
165 (Some(a), None) => Some((a, a)),
166 (None, Some(d)) => Some((d, d)),
167 (None, None) => None,
168 }
169}
170
171/// One `shapes.txt` polyline, in `shape_pt_sequence` order.
172pub struct Shape {
173 pub lat_e7: Vec<i32>,
174 pub lon_e7: Vec<i32>,
175 /// `shape_dist_traveled`, present only when *every* point carries one.
176 /// Feed-defined units (km, mi, ft, ...): only ever compared, never converted.
177 ///
178 /// Kept `f64` deliberately. It is only an ordering key, so `f32` looks safe —
179 /// but real feeds give it 8+ significant digits (`advance_transit` has metres
180 /// to 8 decimal places), and at that width `f32` collapses points a few
181 /// millimetres apart, flipping which segment a stop brackets onto. Measured on
182 /// 100 feeds that moved the fitted polyline of 0.3% of routes for a 4-byte
183 /// saving per row.
184 pub dist: Option<Vec<f64>>,
185}
186
187/// One usable `stop_times.txt` row, already typed. Borrowed from the reader's
188/// line buffer, so it must be consumed before the next row is read.
189pub struct StopTimeRow<'a> {
190 pub trip_id: &'a str,
191 pub stop_id: &'a str,
192 /// `stop_sequence`. GTFS defines it as a non-negative integer; a value that
193 /// will not parse becomes 0, which sorts first and, the sort being stable,
194 /// leaves such rows in file order.
195 pub seq: u32,
196 pub arr: u32,
197 pub dep: u32,
198 /// `shape_dist_traveled` in the feed's own units, an ordering key only, or
199 /// NaN when the row carries none. A sentinel rather than an `Option` because
200 /// this is the field that decides how big a `stop_times` row is, and there
201 /// are billions of them: `Option<f64>` would cost 16 bytes and push the row
202 /// from 24 to 32. See [`Shape::dist`] for why it is not an `f32`.
203 pub dist: f64,
204}
205
206/// Stream `dir/stop_times.txt`, calling `f` once per row that carries a trip id
207/// and a usable time. Returns `None` only when the file is absent.
208///
209/// `stop_times.txt` is the largest file in almost every feed — 52 GB of `Csv` for
210/// `great_britain` alone — and every row is reduced to a handful of bytes
211/// immediately, so materializing it as `Vec<Vec<String>>` first is pure waste.
212/// Like [`read_shapes`] this is `BufReader` + `read_until` + an immediate typed
213/// parse.
214///
215/// Rows arrive in **file order**, which callers depend on: the `stop_sequence`
216/// sort downstream is stable, so feeds that repeat a `stop_sequence` within a
217/// trip are resolved by their file order.
218pub fn stream_stop_times(dir: &Path, mut f: impl FnMut(StopTimeRow)) -> Option<()> {
219 let file = std::fs::File::open(dir.join("stop_times.txt")).ok()?;
220 let mut reader = std::io::BufReader::new(file);
221 let mut raw: Vec<u8> = Vec::new();
222
223 reader.read_until(b'\n', &mut raw).ok()?;
224 let header_line = String::from_utf8_lossy(&raw);
225 let header = split_line(header_line.trim_end_matches(['\n', '\r']));
226 // Every column is optional, exactly as [`Csv::get`] treats a missing one: a
227 // feed with no `stop_id` column yields no usable rows rather than an error.
228 // `rposition`, because `parse_csv` builds a map and so a repeated column name
229 // resolves to its last occurrence.
230 let col = |name: &str| {
231 header.iter().rposition(|h| h.trim().trim_start_matches('\u{feff}') == name)
232 };
233 let (c_trip, c_stop) = (col("trip_id"), col("stop_id"));
234 let (c_seq, c_arr, c_dep) =
235 (col("stop_sequence"), col("arrival_time"), col("departure_time"));
236 let c_dist = col("shape_dist_traveled");
237
238 loop {
239 raw.clear();
240 if reader.read_until(b'\n', &mut raw).ok()? == 0 {
241 break;
242 }
243 // A quoted field may contain a newline, which `read_until` splits in two.
244 // An odd number of quotes means the record is unfinished, so pull in more
245 // lines: `parse_csv` handles this by construction and the two paths have
246 // to agree, or one desyncs and mangles every row after it. (`"` is 0x22,
247 // which never occurs inside a multi-byte UTF-8 sequence.)
248 while raw.iter().filter(|&&b| b == b'"').count() % 2 == 1 {
249 if reader.read_until(b'\n', &mut raw).ok()? == 0 {
250 break;
251 }
252 }
253 let line = String::from_utf8_lossy(&raw);
254 let line = line.trim_end_matches(['\n', '\r']);
255 if line.is_empty() {
256 continue;
257 }
258 // `parse_csv` swallows every `\r` wherever it appears, so a stray one
259 // inside a field would leave the two paths with different ids — and an id
260 // that does not match `trips.txt` silently drops the trip.
261 let line: Cow<str> =
262 if line.contains('\r') { Cow::Owned(line.replace('\r', "")) } else { line.into() };
263 let fields = split_line(&line);
264 // `trip_id` and `stop_stop` are joined to `trips.txt` and `stops.txt`,
265 // whose ids come out of a `Csv` **untrimmed** — so trimming here would
266 // silently fail to match a feed that pads its ids, dropping every trip in
267 // it. Only the numeric fields are trimmed, exactly as the `Csv` path
268 // trims them at the point of parsing.
269 let field = |i: Option<usize>| {
270 i.and_then(|i| fields.get(i)).map(|s| s.as_str()).unwrap_or("")
271 };
272 let trip_id = field(c_trip);
273 if trip_id.is_empty() {
274 continue;
275 }
276 let Some((arr, dep)) = stop_time_pair(field(c_arr), field(c_dep)) else {
277 continue;
278 };
279 f(StopTimeRow {
280 trip_id,
281 stop_id: field(c_stop),
282 seq: field(c_seq).trim().parse().unwrap_or(0),
283 arr,
284 dep,
285 dist: field(c_dist).trim().parse().unwrap_or(f64::NAN),
286 });
287 }
288 Some(())
289}
290
291/// Stream `dir/shapes.txt` into one polyline per `shape_id`. Returns `None` when
292/// the file is absent (it is optional) or carries no usable columns.
293pub fn read_shapes(dir: &Path) -> Option<HashMap<String, Shape>> {
294 let file = std::fs::File::open(dir.join("shapes.txt")).ok()?;
295 let mut reader = std::io::BufReader::new(file);
296 let mut raw: Vec<u8> = Vec::new();
297
298 reader.read_until(b'\n', &mut raw).ok()?;
299 let header_line = String::from_utf8_lossy(&raw);
300 let header = split_line(header_line.trim_end_matches(['\n', '\r']));
301 let col = |name: &str| {
302 header.iter().position(|h| h.trim().trim_start_matches('\u{feff}') == name)
303 };
304 let (c_id, c_lat, c_lon, c_seq) =
305 (col("shape_id")?, col("shape_pt_lat")?, col("shape_pt_lon")?, col("shape_pt_sequence")?);
306 let c_dist = col("shape_dist_traveled");
307
308 // (sequence, lat_e7, lon_e7, dist) per shape, sorted once at the end.
309 let mut acc: HashMap<String, Vec<RawShapePoint>> = HashMap::new();
310 loop {
311 raw.clear();
312 if reader.read_until(b'\n', &mut raw).ok()? == 0 {
313 break;
314 }
315 let line = String::from_utf8_lossy(&raw);
316 let line = line.trim_end_matches(['\n', '\r']);
317 if line.is_empty() {
318 continue;
319 }
320 let f = split_line(line);
321 let get = |i: usize| f.get(i).map(|s| s.trim()).unwrap_or("");
322 let id = get(c_id);
323 if id.is_empty() {
324 continue;
325 }
326 let Some((lat, lon)) = parse_lat_lon(get(c_lat), get(c_lon)) else {
327 continue;
328 };
329 let seq: u32 = get(c_seq).parse().unwrap_or(0);
330 let dist = c_dist.map_or(f64::NAN, |i| get(i).parse().unwrap_or(f64::NAN));
331 acc.entry(id.to_string()).or_default().push((
332 seq,
333 (lat * 1e7) as i32,
334 (lon * 1e7) as i32,
335 dist,
336 ));
337 }
338
339 let mut out = HashMap::with_capacity(acc.len());
340 for (id, mut pts) in acc {
341 pts.sort_by_key(|p| p.0);
342 let all_dist = pts.iter().all(|p| !p.3.is_nan());
343 out.insert(
344 id,
345 Shape {
346 lat_e7: pts.iter().map(|p| p.1).collect(),
347 lon_e7: pts.iter().map(|p| p.2).collect(),
348 dist: if all_dist {
349 Some(pts.iter().map(|p| p.3).collect())
350 } else {
351 None
352 },
353 },
354 );
355 }
356 Some(out)
357}
358
359#[cfg(test)]
360mod tests {
361 use super::*;
362
363 /// A coordinate outside the WGS84 ranges must be rejected, not cast: the cast
364 /// saturates, so one bad row would put `i32::MAX` in the pack's bbox and the
365 /// device's `covers()` would then overflow its margin and match nothing.
366 #[test]
367 fn an_out_of_range_coordinate_is_rejected_rather_than_saturated() {
368 assert_eq!(parse_lat_lon("37.7", "-122.4"), Some((37.7, -122.4)));
369 assert_eq!(parse_lat_lon(" 37.7 ", " -122.4 "), Some((37.7, -122.4)));
370 assert_eq!(parse_lat_lon("-90", "180"), Some((-90.0, 180.0)));
371 for (lat, lon) in [
372 ("500", "0"),
373 ("0", "500"),
374 ("-91", "0"),
375 ("0", "180.5"),
376 ("nan", "0"),
377 ("inf", "0"),
378 ("", "0"),
379 ("abc", "0"),
380 ] {
381 assert_eq!(parse_lat_lon(lat, lon), None, "{lat},{lon} must not be accepted");
382 }
383 // Why rejecting matters: past ~±214 degrees the e7 cast saturates instead
384 // of wrapping, so the bad value lands in the bbox as the largest possible
385 // one. (A value like -91 stays in range for an i32 — still nonsense, but
386 // it is the saturating case that breaks the device.)
387 assert_eq!((500.0f64 * 1e7) as i32, i32::MAX);
388 }
389
390 /// The `shapes.txt` intermediate is one of the two structures a world build
391 /// has billions of, so its size is part of the contract, not an accident.
392 #[test]
393 fn a_raw_shape_point_stays_twentyfour_bytes() {
394 assert_eq!(std::mem::size_of::<RawShapePoint>(), 24);
395 }
396
397 /// The streaming loader must agree with the [`Csv`] path row for row: the
398 /// tests that pin the pack's contents feed it a `Csv`, while the host tool
399 /// streams, and a divergence would mean the two build different packs.
400 #[test]
401 fn streaming_stop_times_matches_parsing_the_whole_table() {
402 // A BOM, a quoted comma, a blank line, each arrival/departure fallback,
403 // an unparseable sequence, a row with no usable time, a row with no trip
404 // id, and a row that simply stops early.
405 // A BOM, a quoted comma, a blank line, each arrival/departure fallback,
406 // an unparseable sequence, a row with no usable time, a row with no trip
407 // id, a row that simply stops early, padded ids, a quoted field with an
408 // embedded newline, and CRLF terminators.
409 let text = "\u{feff}trip_id,stop_id,stop_sequence,arrival_time,departure_time,shape_dist_traveled,stop_headsign\n\
410 T1,S1,1,08:00:00,08:00:05,0,\n\
411 T1,\"S,2\",2,08:10:00,,1.5,\n\
412 \n\
413 T1,S3,3,,08:20:00,,\n\
414 ,S4,4,08:30:00,08:30:00,9,\n\
415 T2,S5,notanumber,25:10:00,25:10:00,,\n\
416 T2,S6,6,,,7,\n\
417 T2,S7\n\
418 T3 , S8 , 1 , 09:00:00 , 09:00:00 , 2 ,\n\
419 T4,S9,1,10:00:00,10:00:00,,\"two\nlines\"\n\
420 T4,S10,2,10:05:00,10:05:00,,plain\r\n";
421
422 let dir = std::env::temp_dir()
423 .join(format!("gtfs_ingest_stream_{}", std::process::id()));
424 std::fs::create_dir_all(&dir).expect("temp dir");
425 std::fs::write(dir.join("stop_times.txt"), text).expect("write stop_times.txt");
426
427 // NaN is the "no shape_dist_traveled" sentinel and compares unequal to
428 // itself, so rows are compared by the dist's bits.
429 type Row = (String, String, u32, u32, u32, u64);
430 let mut streamed: Vec<Row> = Vec::new();
431 stream_stop_times(&dir, |r| {
432 streamed.push((
433 r.trip_id.to_string(),
434 r.stop_id.to_string(),
435 r.seq,
436 r.arr,
437 r.dep,
438 r.dist.to_bits(),
439 ));
440 })
441 .expect("stop_times.txt is present");
442 let _ = std::fs::remove_dir_all(&dir);
443
444 let csv = parse_csv(text);
445 let tabled: Vec<Row> = csv
446 .rows
447 .iter()
448 .filter_map(|row| {
449 let trip_id = csv.get(row, "trip_id");
450 if trip_id.is_empty() {
451 return None;
452 }
453 let (arr, dep) = stop_time_pair(
454 csv.get(row, "arrival_time"),
455 csv.get(row, "departure_time"),
456 )?;
457 Some((
458 trip_id.to_string(),
459 csv.get(row, "stop_id").to_string(),
460 csv.get(row, "stop_sequence").trim().parse().unwrap_or(0),
461 arr,
462 dep,
463 csv.get(row, "shape_dist_traveled")
464 .trim()
465 .parse()
466 .unwrap_or(f64::NAN)
467 .to_bits(),
468 ))
469 })
470 .collect();
471
472 assert_eq!(streamed, tabled);
473 // Spelled out so the filters themselves are pinned, not just the two
474 // paths' agreement: T1/S1 keeps both times, "S,2" survives the quoted
475 // comma with departure falling back to arrival, S3 arrives at its
476 // departure, S4 has no trip, S5's sequence is unusable and its time is
477 // past midnight, S6/S7 carry no time at all, T3's padded ids stay padded
478 // because that is how `trips.txt` and `stops.txt` will hold them, and T4's
479 // two rows survive a headsign that contains a newline.
480 assert_eq!(streamed.len(), 7, "{streamed:?}");
481 assert_eq!(streamed[0], ("T1".into(), "S1".into(), 1, 28800, 28805, 0f64.to_bits()));
482 assert_eq!(streamed[1], ("T1".into(), "S,2".into(), 2, 29400, 29400, 1.5f64.to_bits()));
483 assert_eq!(streamed[2].3, 30000, "an absent arrival takes the departure");
484 assert_eq!(streamed[3], ("T2".into(), "S5".into(), 0, 90600, 90600, f64::NAN.to_bits()));
485 assert_eq!(
486 streamed[4],
487 ("T3 ".into(), " S8 ".into(), 1, 32400, 32400, 2f64.to_bits()),
488 "ids must not be trimmed, or a feed that pads them loses every trip"
489 );
490 assert_eq!(
491 (streamed[5].1.as_str(), streamed[6].1.as_str()),
492 ("S9", "S10"),
493 "an embedded newline must not desync the rows after it"
494 );
495 }
496}