Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / gtfs_ingest / src / index_part2.rs
index_part2.rs387 lines · 16.4 KiBRaw
| 1 | impl IndexBuilder { |
| 2 | /// `pack_name` is stored in the string pool and surfaced to the on-device |
| 3 | /// planner as a fallback. |
| 4 | pub fn new(pack_name: &str) -> IndexBuilder { |
| 5 | let mut pool = StringPool::new(); |
| 6 | let pack_name_off = pool.intern(pack_name); |
| 7 | IndexBuilder { |
| 8 | pool, |
| 9 | pack_name_off, |
| 10 | stop_lat: Vec::new(), |
| 11 | stop_lon: Vec::new(), |
| 12 | min_lat: i32::MAX, |
| 13 | min_lon: i32::MAX, |
| 14 | max_lat: i32::MIN, |
| 15 | max_lon: i32::MIN, |
| 16 | service_key_to_idx: HashMap::new(), |
| 17 | svc_mask: Vec::new(), |
| 18 | svc_start: Vec::new(), |
| 19 | svc_end: Vec::new(), |
| 20 | exceptions: Vec::new(), |
| 21 | feed_name_offs: Vec::new(), |
| 22 | feed_tz_offs: Vec::new(), |
| 23 | feed_motis_prefix_offs: Vec::new(), |
| 24 | sec_stops: Vec::new(), |
| 25 | sec_stop_gtfs_id: Vec::new(), |
| 26 | sec_routes: Vec::new(), |
| 27 | sec_route_stops: Vec::new(), |
| 28 | sec_route_trips: Vec::new(), |
| 29 | sec_route_trip_recs: Vec::new(), |
| 30 | sec_route_trip_off: Vec::new(), |
| 31 | sec_route_shape_idx: Vec::new(), |
| 32 | sec_route_stop_shape: Vec::new(), |
| 33 | sec_stop_routes: Vec::new(), |
| 34 | sec_stop_routes_idx: Vec::new(), |
| 35 | sec_stop_route_pos: Vec::new(), |
| 36 | profiles: ProfileTable::new(), |
| 37 | shape_blobs: ShapeBlobs::new(), |
| 38 | rail_lines: RailLines::new(), |
| 39 | stop_routes_total: 0, |
| 40 | route_count: 0, |
| 41 | trip_total: 0, |
| 42 | shaped_routes: 0, |
| 43 | multi_shape_routes: 0, |
| 44 | dropped_shape_routes: 0, |
| 45 | dropped_stops_bad_coord: 0, |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | /// Register a feed-namespaced service id, returning its global index. |
| 50 | fn ensure_service(&mut self, key: &str) -> u32 { |
| 51 | if let Some(&i) = self.service_key_to_idx.get(key) { |
| 52 | return i; |
| 53 | } |
| 54 | let i = self.svc_mask.len() as u32; |
| 55 | self.service_key_to_idx.insert(key.to_string(), i); |
| 56 | self.svc_mask.push(0); |
| 57 | self.svc_start.push(0); |
| 58 | self.svc_end.push(99_999_999); |
| 59 | i |
| 60 | } |
| 61 | |
| 62 | /// Ingest and finalize one feed whose tables are all already parsed. |
| 63 | pub fn add_feed(&mut self, feed: &FeedInput) -> Result<(), String> { |
| 64 | self.add(&feed.into()) |
| 65 | } |
| 66 | |
| 67 | /// Ingest and finalize one feed, streaming its `stop_times.txt` off disk. |
| 68 | pub fn add_feed_dir(&mut self, feed: &FeedDir) -> Result<(), String> { |
| 69 | self.add(&feed.into()) |
| 70 | } |
| 71 | |
| 72 | /// Bytes currently held in the sections, for progress reporting: this is |
| 73 | /// what the finished pack will be, so it is the number to watch. |
| 74 | pub fn section_bytes(&self) -> usize { |
| 75 | self.pool.bytes.len() |
| 76 | + self.profiles.bytes.len() |
| 77 | + self.shape_blobs.bytes.len() |
| 78 | + self.sec_stops.len() |
| 79 | + self.sec_stop_gtfs_id.len() |
| 80 | + self.sec_routes.len() |
| 81 | + self.sec_route_stops.len() |
| 82 | + self.sec_route_trips.len() |
| 83 | + self.sec_route_trip_recs.len() |
| 84 | + self.sec_route_trip_off.len() |
| 85 | + self.sec_route_shape_idx.len() |
| 86 | + self.sec_route_stop_shape.len() |
| 87 | + self.sec_stop_routes.len() |
| 88 | + self.sec_stop_routes_idx.len() |
| 89 | + self.sec_stop_route_pos.len() |
| 90 | } |
| 91 | |
| 92 | /// `(stops, routes, trips)` accumulated so far. |
| 93 | pub fn counts(&self) -> (usize, usize, usize) { |
| 94 | (self.stop_lat.len(), self.route_count, self.trip_total) |
| 95 | } |
| 96 | |
| 97 | fn add(&mut self, feed: &FeedView) -> Result<(), String> { |
| 98 | let feed_idx = self.feed_name_offs.len() as u32; |
| 99 | let feed_stop_start = self.stop_lat.len() as u32; |
| 100 | let feed_exc_start = self.exceptions.len(); |
| 101 | self.feed_name_offs.push(self.pool.intern(feed.name)); |
| 102 | // Per-feed IANA timezone. Dedup in the pool means one shared |
| 103 | // "America/Los_Angeles" no matter how many feeds use it. |
| 104 | let tz = feed |
| 105 | .agency |
| 106 | .and_then(|a| a.rows.first().map(|row| a.get(row, "agency_timezone").trim())) |
| 107 | .unwrap_or(""); |
| 108 | self.feed_tz_offs.push(self.pool.intern(tz)); |
| 109 | // Interned once per feed, so every stop's MOTIS id shares this entry. |
| 110 | self.feed_motis_prefix_offs.push(self.pool.intern(feed.motis_prefix.trim())); |
| 111 | |
| 112 | // --- Stops (this feed) -> global indices --- |
| 113 | let mut stop_id_to_idx: HashMap<String, u32> = HashMap::new(); |
| 114 | for row in &feed.stops.rows { |
| 115 | let id = feed.stops.get(row, "stop_id"); |
| 116 | if id.is_empty() { |
| 117 | continue; |
| 118 | } |
| 119 | // Out-of-range coordinates are dropped, not clamped: see |
| 120 | // `gtfs::parse_lat_lon` for what one bad row does to the bbox. |
| 121 | let Some((lat, lon)) = |
| 122 | gtfs::parse_lat_lon(feed.stops.get(row, "stop_lat"), feed.stops.get(row, "stop_lon")) |
| 123 | else { |
| 124 | self.dropped_stops_bad_coord += 1; |
| 125 | continue; |
| 126 | }; |
| 127 | let lat_e7 = (lat * 1e7) as i32; |
| 128 | let lon_e7 = (lon * 1e7) as i32; |
| 129 | let name = feed.stops.get(row, "stop_name"); |
| 130 | let code = feed.stops.get(row, "stop_code"); |
| 131 | let idx = self.stop_lat.len() as u32; |
| 132 | stop_id_to_idx.insert(id.to_string(), idx); |
| 133 | self.stop_lat.push(lat_e7); |
| 134 | self.stop_lon.push(lon_e7); |
| 135 | // StopRec goes straight into the section: keeping the name/code/id |
| 136 | // offsets in parallel `Vec<u32>`s only to flatten them at the end was |
| 137 | // a second copy of STOPS plus a third of STOP_GTFS_ID. |
| 138 | append_i32(&mut self.sec_stops, lat_e7); |
| 139 | append_i32(&mut self.sec_stops, lon_e7); |
| 140 | let name_off = self.pool.intern(name); |
| 141 | append_u32(&mut self.sec_stops, name_off); |
| 142 | let code_off = self.pool.intern(if code.is_empty() { id } else { code }); |
| 143 | append_u32(&mut self.sec_stops, code_off); |
| 144 | // Interned explicitly: `code_off` above falls back to `stop_id` only |
| 145 | // when `stop_code` is blank, so it cannot stand in for the real id. |
| 146 | let gtfs_off = self.pool.intern(id); |
| 147 | append_u32(&mut self.sec_stop_gtfs_id, gtfs_off); |
| 148 | self.min_lat = self.min_lat.min(lat_e7); |
| 149 | self.min_lon = self.min_lon.min(lon_e7); |
| 150 | self.max_lat = self.max_lat.max(lat_e7); |
| 151 | self.max_lon = self.max_lon.max(lon_e7); |
| 152 | } |
| 153 | |
| 154 | // --- Route metadata (this feed) --- |
| 155 | let mut route_meta: HashMap<String, RouteMeta> = HashMap::new(); |
| 156 | for row in &feed.routes.rows { |
| 157 | let id = feed.routes.get(row, "route_id"); |
| 158 | if id.is_empty() { |
| 159 | continue; |
| 160 | } |
| 161 | let short = feed.routes.get(row, "route_short_name"); |
| 162 | let long = feed.routes.get(row, "route_long_name"); |
| 163 | let name = if !short.is_empty() { short } else { long }; |
| 164 | let color = |
| 165 | u32::from_str_radix(feed.routes.get(row, "route_color").trim(), 16).unwrap_or(0); |
| 166 | let rtype: u32 = feed.routes.get(row, "route_type").trim().parse().unwrap_or(3); |
| 167 | let name_off = self.pool.intern(name); |
| 168 | route_meta |
| 169 | .insert(id.to_string(), RouteMeta { name_off, color, route_type: rtype }); |
| 170 | } |
| 171 | |
| 172 | // --- Trips (this feed) --- |
| 173 | let mut trip_meta: HashMap<String, TripMeta> = HashMap::new(); |
| 174 | for row in &feed.trips.rows { |
| 175 | let id = feed.trips.get(row, "trip_id"); |
| 176 | if id.is_empty() { |
| 177 | continue; |
| 178 | } |
| 179 | let headsign_off = self.pool.intern(feed.trips.get(row, "trip_headsign")); |
| 180 | trip_meta.insert( |
| 181 | id.to_string(), |
| 182 | TripMeta { |
| 183 | route_id: feed.trips.get(row, "route_id").to_string(), |
| 184 | service_id: feed.trips.get(row, "service_id").to_string(), |
| 185 | headsign_off, |
| 186 | shape_id: feed.trips.get(row, "shape_id").trim().to_string(), |
| 187 | }, |
| 188 | ); |
| 189 | } |
| 190 | |
| 191 | // --- stop_times grouped by trip (this feed) --- |
| 192 | let mut trip_stoptimes: HashMap<String, Vec<StopTime>> = HashMap::new(); |
| 193 | let mut collect = |row: gtfs::StopTimeRow| { |
| 194 | let stop_idx = match stop_id_to_idx.get(row.stop_id) { |
| 195 | Some(&i) => i, |
| 196 | None => return, |
| 197 | }; |
| 198 | trip_stoptimes.entry(row.trip_id.to_string()).or_default().push(StopTime { |
| 199 | seq: row.seq, |
| 200 | stop_idx, |
| 201 | arr: row.arr, |
| 202 | dep: row.dep, |
| 203 | dist: row.dist, |
| 204 | }); |
| 205 | }; |
| 206 | match feed.stop_times { |
| 207 | StopTimesSource::Table(csv) => { |
| 208 | for row in &csv.rows { |
| 209 | let trip_id = csv.get(row, "trip_id"); |
| 210 | if trip_id.is_empty() { |
| 211 | continue; |
| 212 | } |
| 213 | let Some((arr, dep)) = gtfs::stop_time_pair( |
| 214 | csv.get(row, "arrival_time"), |
| 215 | csv.get(row, "departure_time"), |
| 216 | ) else { |
| 217 | continue; |
| 218 | }; |
| 219 | collect(gtfs::StopTimeRow { |
| 220 | trip_id, |
| 221 | stop_id: csv.get(row, "stop_id"), |
| 222 | seq: csv.get(row, "stop_sequence").trim().parse().unwrap_or(0), |
| 223 | arr, |
| 224 | dep, |
| 225 | dist: csv |
| 226 | .get(row, "shape_dist_traveled") |
| 227 | .trim() |
| 228 | .parse() |
| 229 | .unwrap_or(f64::NAN), |
| 230 | }); |
| 231 | } |
| 232 | } |
| 233 | StopTimesSource::Dir(dir) => { |
| 234 | gtfs::stream_stop_times(dir, collect).ok_or_else(|| { |
| 235 | format!( |
| 236 | "feed '{}' ({}) missing required GTFS file: stop_times.txt", |
| 237 | feed.name, |
| 238 | dir.display() |
| 239 | ) |
| 240 | })?; |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | // --- Services (calendar.txt) namespaced by feed --- |
| 245 | let feed_key = |id: &str| format!("{}|{}", feed.name, id); |
| 246 | if let Some(cal) = feed.calendar { |
| 247 | let days = [ |
| 248 | "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", |
| 249 | ]; |
| 250 | for row in &cal.rows { |
| 251 | let id = cal.get(row, "service_id"); |
| 252 | if id.is_empty() { |
| 253 | continue; |
| 254 | } |
| 255 | let key = feed_key(id); |
| 256 | if self.service_key_to_idx.contains_key(&key) { |
| 257 | continue; |
| 258 | } |
| 259 | let mut mask = 0u8; |
| 260 | for (b, d) in days.iter().enumerate() { |
| 261 | if cal.get(row, d).trim() == "1" { |
| 262 | mask |= 1 << b; |
| 263 | } |
| 264 | } |
| 265 | let idx = self.svc_mask.len() as u32; |
| 266 | self.service_key_to_idx.insert(key, idx); |
| 267 | self.svc_mask.push(mask); |
| 268 | self.svc_start.push(parse_gtfs_date(cal.get(row, "start_date")).unwrap_or(0)); |
| 269 | self.svc_end |
| 270 | .push(parse_gtfs_date(cal.get(row, "end_date")).unwrap_or(99_999_999)); |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | // --- Exceptions (calendar_dates.txt) --- |
| 275 | if let Some(cd) = feed.calendar_dates { |
| 276 | for row in &cd.rows { |
| 277 | let sid = cd.get(row, "service_id"); |
| 278 | if sid.is_empty() { |
| 279 | continue; |
| 280 | } |
| 281 | let date = match parse_gtfs_date(cd.get(row, "date")) { |
| 282 | Some(d) => d, |
| 283 | None => continue, |
| 284 | }; |
| 285 | let added = if cd.get(row, "exception_type").trim() == "1" { 1 } else { 0 }; |
| 286 | let sidx = self.ensure_service(&feed_key(sid)); |
| 287 | self.exceptions.push((sidx, date, added)); |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | // --- Group this feed's trips into RAPTOR routes --- |
| 292 | // Every one of these is a feed-local: `finalize_feed` below turns them |
| 293 | // into section bytes before `add_feed` returns, which is what stops them |
| 294 | // accumulating across 1272 feeds. |
| 295 | let mut raptor_routes: Vec<RaptorRoute> = Vec::new(); |
| 296 | let mut built_trips: Vec<BuiltTrip> = Vec::new(); |
| 297 | // Referenced `shapes.txt` polylines, interned so a trip names its shape |
| 298 | // by index instead of carrying a `String`. |
| 299 | let mut shapes: Vec<(&str, &Shape)> = Vec::new(); |
| 300 | let mut shape_id_to_idx: HashMap<&str, u32> = HashMap::new(); |
| 301 | // Keyed by a hash of `(route_id, stop_pattern)`, with every candidate |
| 302 | // compared in full. Unlike the other dedup tables a false match here |
| 303 | // would fuse two distinct patterns into one route — wrong departures |
| 304 | // rather than wasted bytes — so a hash alone is not enough. Comparing |
| 305 | // against the pattern the route already stores also removes the ~240-byte |
| 306 | // key string this used to allocate per trip. |
| 307 | let mut pattern_index: HashMap<u64, Vec<usize>> = HashMap::new(); |
| 308 | for (trip_id, mut sts) in trip_stoptimes { |
| 309 | if sts.len() < 2 { |
| 310 | continue; |
| 311 | } |
| 312 | sts.sort_by_key(|s| s.seq); |
| 313 | let pattern: Vec<u32> = sts.iter().map(|s| s.stop_idx).collect(); |
| 314 | let tmeta = match trip_meta.get(&trip_id) { |
| 315 | Some(m) => m, |
| 316 | None => continue, |
| 317 | }; |
| 318 | let service_idx = self.ensure_service(&feed_key(&tmeta.service_id)); |
| 319 | let mut hash = fnv1a(tmeta.route_id.as_bytes()); |
| 320 | for &s in &pattern { |
| 321 | hash = fnv1a_mix(hash, &s.to_le_bytes()); |
| 322 | } |
| 323 | let slot = pattern_index.entry(hash).or_default(); |
| 324 | let route_idx = match slot.iter().copied().find(|&i| { |
| 325 | raptor_routes[i].route_id == tmeta.route_id |
| 326 | && raptor_routes[i].stop_pattern == pattern |
| 327 | }) { |
| 328 | Some(i) => i, |
| 329 | None => { |
| 330 | let (name_off, color, rtype) = match route_meta.get(&tmeta.route_id) { |
| 331 | Some(m) => (m.name_off, m.color, m.route_type), |
| 332 | None => (NONE, 0, 3), |
| 333 | }; |
| 334 | raptor_routes.push(RaptorRoute { |
| 335 | feed_idx, |
| 336 | route_id: tmeta.route_id.clone(), |
| 337 | name_off, |
| 338 | color, |
| 339 | route_type: rtype, |
| 340 | stop_pattern: pattern, |
| 341 | trips: Vec::new(), |
| 342 | }); |
| 343 | let i = raptor_routes.len() - 1; |
| 344 | slot.push(i); |
| 345 | i |
| 346 | } |
| 347 | }; |
| 348 | let shape_key = match feed |
| 349 | .shapes |
| 350 | .filter(|_| !tmeta.shape_id.is_empty()) |
| 351 | .and_then(|m| m.get_key_value(&tmeta.shape_id)) |
| 352 | { |
| 353 | Some((id, sh)) => *shape_id_to_idx.entry(id.as_str()).or_insert_with(|| { |
| 354 | shapes.push((id.as_str(), sh)); |
| 355 | shapes.len() as u32 - 1 |
| 356 | }), |
| 357 | None => NONE, |
| 358 | }; |
| 359 | built_trips.push(BuiltTrip { |
| 360 | service_idx, |
| 361 | headsign_off: tmeta.headsign_off, |
| 362 | start_time: sts.first().map(|s| s.dep).unwrap_or(0), |
| 363 | stoptimes: sts.iter().map(|s| (s.arr, s.dep)).collect(), |
| 364 | shape_key, |
| 365 | // Present only when every stop in the pattern carries one, which |
| 366 | // is what `shapes::fit` requires before it trusts the key. |
| 367 | stop_dists: sts |
| 368 | .iter() |
| 369 | .map(|s| (!s.dist.is_nan()).then_some(s.dist)) |
| 370 | .collect::<Option<Vec<f64>>>(), |
| 371 | }); |
| 372 | raptor_routes[route_idx].trips.push(built_trips.len() - 1); |
| 373 | } |
| 374 | |
| 375 | self.finalize_feed(&raptor_routes, &built_trips, &shapes, feed_stop_start)?; |
| 376 | self.rail_lines.add_feed(feed_idx, feed)?; |
| 377 | |
| 378 | // A feed's services are allocated contiguously while it is being added, |
| 379 | // and its exceptions only ever reference them, so sorting this feed's |
| 380 | // slice leaves the whole array sorted by (service, date) once every feed |
| 381 | // is in. The sort must stay **stable**: `finish_to` collapses duplicate |
| 382 | // (service, date) rows by keeping the last, which is CSV order. |
| 383 | self.exceptions[feed_exc_start..].sort_by_key(|&(sidx, date, _)| (sidx, date)); |
| 384 | Ok(()) |
| 385 | } |
| 386 | |
| 387 | } |