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

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

gtfs.rs485 lines · 19.8 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::{split_line, RawShapePoint};
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 =
231 |name: &str| header.iter().rposition(|h| h.trim().trim_start_matches('\u{feff}') == name);
232 let (c_trip, c_stop) = (col("trip_id"), col("stop_id"));
233 let (c_seq, c_arr, c_dep) = (col("stop_sequence"), col("arrival_time"), col("departure_time"));
234 let c_dist = col("shape_dist_traveled");
235
236 loop {
237 raw.clear();
238 if reader.read_until(b'\n', &mut raw).ok()? == 0 {
239 break;
240 }
241 // A quoted field may contain a newline, which `read_until` splits in two.
242 // An odd number of quotes means the record is unfinished, so pull in more
243 // lines: `parse_csv` handles this by construction and the two paths have
244 // to agree, or one desyncs and mangles every row after it. (`"` is 0x22,
245 // which never occurs inside a multi-byte UTF-8 sequence.)
246 while raw.iter().filter(|&&b| b == b'"').count() % 2 == 1 {
247 if reader.read_until(b'\n', &mut raw).ok()? == 0 {
248 break;
249 }
250 }
251 let line = String::from_utf8_lossy(&raw);
252 let line = line.trim_end_matches(['\n', '\r']);
253 if line.is_empty() {
254 continue;
255 }
256 // `parse_csv` swallows every `\r` wherever it appears, so a stray one
257 // inside a field would leave the two paths with different ids — and an id
258 // that does not match `trips.txt` silently drops the trip.
259 let line: Cow<str> =
260 if line.contains('\r') { Cow::Owned(line.replace('\r', "")) } else { line.into() };
261 let fields = split_line(&line);
262 // `trip_id` and `stop_stop` are joined to `trips.txt` and `stops.txt`,
263 // whose ids come out of a `Csv` **untrimmed** — so trimming here would
264 // silently fail to match a feed that pads its ids, dropping every trip in
265 // it. Only the numeric fields are trimmed, exactly as the `Csv` path
266 // trims them at the point of parsing.
267 let field =
268 |i: Option<usize>| i.and_then(|i| fields.get(i)).map(|s| s.as_str()).unwrap_or("");
269 let trip_id = field(c_trip);
270 if trip_id.is_empty() {
271 continue;
272 }
273 let Some((arr, dep)) = stop_time_pair(field(c_arr), field(c_dep)) else {
274 continue;
275 };
276 f(StopTimeRow {
277 trip_id,
278 stop_id: field(c_stop),
279 seq: field(c_seq).trim().parse().unwrap_or(0),
280 arr,
281 dep,
282 dist: field(c_dist).trim().parse().unwrap_or(f64::NAN),
283 });
284 }
285 Some(())
286}
287
288/// Stream `dir/shapes.txt` into one polyline per `shape_id`. Returns `None` when
289/// the file is absent (it is optional) or carries no usable columns.
290pub fn read_shapes(dir: &Path) -> Option<HashMap<String, Shape>> {
291 let file = std::fs::File::open(dir.join("shapes.txt")).ok()?;
292 let mut reader = std::io::BufReader::new(file);
293 let mut raw: Vec<u8> = Vec::new();
294
295 reader.read_until(b'\n', &mut raw).ok()?;
296 let header_line = String::from_utf8_lossy(&raw);
297 let header = split_line(header_line.trim_end_matches(['\n', '\r']));
298 let col =
299 |name: &str| header.iter().position(|h| h.trim().trim_start_matches('\u{feff}') == name);
300 let (c_id, c_lat, c_lon, c_seq) =
301 (col("shape_id")?, col("shape_pt_lat")?, col("shape_pt_lon")?, col("shape_pt_sequence")?);
302 let c_dist = col("shape_dist_traveled");
303
304 // (sequence, lat_e7, lon_e7, dist) per shape, sorted once at the end.
305 let mut acc: HashMap<String, Vec<RawShapePoint>> = HashMap::new();
306 loop {
307 raw.clear();
308 if reader.read_until(b'\n', &mut raw).ok()? == 0 {
309 break;
310 }
311 let line = String::from_utf8_lossy(&raw);
312 let line = line.trim_end_matches(['\n', '\r']);
313 if line.is_empty() {
314 continue;
315 }
316 let f = split_line(line);
317 let get = |i: usize| f.get(i).map(|s| s.trim()).unwrap_or("");
318 let id = get(c_id);
319 if id.is_empty() {
320 continue;
321 }
322 let Some((lat, lon)) = parse_lat_lon(get(c_lat), get(c_lon)) else {
323 continue;
324 };
325 let seq: u32 = get(c_seq).parse().unwrap_or(0);
326 let dist = c_dist.map_or(f64::NAN, |i| get(i).parse().unwrap_or(f64::NAN));
327 acc.entry(id.to_string()).or_default().push((
328 seq,
329 (lat * 1e7) as i32,
330 (lon * 1e7) as i32,
331 dist,
332 ));
333 }
334
335 let mut out = HashMap::with_capacity(acc.len());
336 for (id, mut pts) in acc {
337 pts.sort_by_key(|p| p.0);
338 let all_dist = pts.iter().all(|p| !p.3.is_nan());
339 out.insert(
340 id,
341 Shape {
342 lat_e7: pts.iter().map(|p| p.1).collect(),
343 lon_e7: pts.iter().map(|p| p.2).collect(),
344 dist: if all_dist { Some(pts.iter().map(|p| p.3).collect()) } else { None },
345 },
346 );
347 }
348 Some(out)
349}
350
351#[cfg(test)]
352mod tests {
353 use super::*;
354
355 /// A coordinate outside the WGS84 ranges must be rejected, not cast: the cast
356 /// saturates, so one bad row would put `i32::MAX` in the pack's bbox and the
357 /// device's `covers()` would then overflow its margin and match nothing.
358 #[test]
359 fn an_out_of_range_coordinate_is_rejected_rather_than_saturated() {
360 assert_eq!(parse_lat_lon("37.7", "-122.4"), Some((37.7, -122.4)));
361 assert_eq!(parse_lat_lon(" 37.7 ", " -122.4 "), Some((37.7, -122.4)));
362 assert_eq!(parse_lat_lon("-90", "180"), Some((-90.0, 180.0)));
363 for (lat, lon) in [
364 ("500", "0"),
365 ("0", "500"),
366 ("-91", "0"),
367 ("0", "180.5"),
368 ("nan", "0"),
369 ("inf", "0"),
370 ("", "0"),
371 ("abc", "0"),
372 ] {
373 assert_eq!(parse_lat_lon(lat, lon), None, "{lat},{lon} must not be accepted");
374 }
375 // Why rejecting matters: past ~±214 degrees the e7 cast saturates instead
376 // of wrapping, so the bad value lands in the bbox as the largest possible
377 // one. (A value like -91 stays in range for an i32 — still nonsense, but
378 // it is the saturating case that breaks the device.)
379 assert_eq!((500.0f64 * 1e7) as i32, i32::MAX);
380 }
381
382 /// The `shapes.txt` intermediate is one of the two structures a world build
383 /// has billions of, so its size is part of the contract, not an accident.
384 #[test]
385 fn a_raw_shape_point_stays_twentyfour_bytes() {
386 assert_eq!(std::mem::size_of::<RawShapePoint>(), 24);
387 }
388
389 /// The streaming loader must agree with the [`Csv`] path row for row: the
390 /// tests that pin the pack's contents feed it a `Csv`, while the host tool
391 /// streams, and a divergence would mean the two build different packs.
392 #[test]
393 fn streaming_stop_times_matches_parsing_the_whole_table() {
394 // A BOM, a quoted comma, a blank line, each arrival/departure fallback,
395 // an unparseable sequence, a row with no usable time, a row with no trip
396 // id, and a row that simply stops early.
397 // A BOM, a quoted comma, a blank line, each arrival/departure fallback,
398 // an unparseable sequence, a row with no usable time, a row with no trip
399 // id, a row that simply stops early, padded ids, a quoted field with an
400 // embedded newline, and CRLF terminators.
401 let text = "\u{feff}trip_id,stop_id,stop_sequence,arrival_time,departure_time,shape_dist_traveled,stop_headsign\n\
402 T1,S1,1,08:00:00,08:00:05,0,\n\
403 T1,\"S,2\",2,08:10:00,,1.5,\n\
404 \n\
405 T1,S3,3,,08:20:00,,\n\
406 ,S4,4,08:30:00,08:30:00,9,\n\
407 T2,S5,notanumber,25:10:00,25:10:00,,\n\
408 T2,S6,6,,,7,\n\
409 T2,S7\n\
410 T3 , S8 , 1 , 09:00:00 , 09:00:00 , 2 ,\n\
411 T4,S9,1,10:00:00,10:00:00,,\"two\nlines\"\n\
412 T4,S10,2,10:05:00,10:05:00,,plain\r\n";
413
414 let dir = std::env::temp_dir().join(format!("gtfs_ingest_stream_{}", std::process::id()));
415 std::fs::create_dir_all(&dir).expect("temp dir");
416 std::fs::write(dir.join("stop_times.txt"), text).expect("write stop_times.txt");
417
418 // NaN is the "no shape_dist_traveled" sentinel and compares unequal to
419 // itself, so rows are compared by the dist's bits.
420 type Row = (String, String, u32, u32, u32, u64);
421 let mut streamed: Vec<Row> = Vec::new();
422 stream_stop_times(&dir, |r| {
423 streamed.push((
424 r.trip_id.to_string(),
425 r.stop_id.to_string(),
426 r.seq,
427 r.arr,
428 r.dep,
429 r.dist.to_bits(),
430 ));
431 })
432 .expect("stop_times.txt is present");
433 let _ = std::fs::remove_dir_all(&dir);
434
435 let csv = parse_csv(text);
436 let tabled: Vec<Row> = csv
437 .rows
438 .iter()
439 .filter_map(|row| {
440 let trip_id = csv.get(row, "trip_id");
441 if trip_id.is_empty() {
442 return None;
443 }
444 let (arr, dep) =
445 stop_time_pair(csv.get(row, "arrival_time"), csv.get(row, "departure_time"))?;
446 Some((
447 trip_id.to_string(),
448 csv.get(row, "stop_id").to_string(),
449 csv.get(row, "stop_sequence").trim().parse().unwrap_or(0),
450 arr,
451 dep,
452 csv.get(row, "shape_dist_traveled")
453 .trim()
454 .parse()
455 .unwrap_or(f64::NAN)
456 .to_bits(),
457 ))
458 })
459 .collect();
460
461 assert_eq!(streamed, tabled);
462 // Spelled out so the filters themselves are pinned, not just the two
463 // paths' agreement: T1/S1 keeps both times, "S,2" survives the quoted
464 // comma with departure falling back to arrival, S3 arrives at its
465 // departure, S4 has no trip, S5's sequence is unusable and its time is
466 // past midnight, S6/S7 carry no time at all, T3's padded ids stay padded
467 // because that is how `trips.txt` and `stops.txt` will hold them, and T4's
468 // two rows survive a headsign that contains a newline.
469 assert_eq!(streamed.len(), 7, "{streamed:?}");
470 assert_eq!(streamed[0], ("T1".into(), "S1".into(), 1, 28800, 28805, 0f64.to_bits()));
471 assert_eq!(streamed[1], ("T1".into(), "S,2".into(), 2, 29400, 29400, 1.5f64.to_bits()));
472 assert_eq!(streamed[2].3, 30000, "an absent arrival takes the departure");
473 assert_eq!(streamed[3], ("T2".into(), "S5".into(), 0, 90600, 90600, f64::NAN.to_bits()));
474 assert_eq!(
475 streamed[4],
476 ("T3 ".into(), " S8 ".into(), 1, 32400, 32400, 2f64.to_bits()),
477 "ids must not be trimmed, or a feed that pads them loses every trip"
478 );
479 assert_eq!(
480 (streamed[5].1.as_str(), streamed[6].1.as_str()),
481 ("S9", "S10"),
482 "an embedded newline must not desync the rows after it"
483 );
484 }
485}