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

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

index_part3.rs383 lines · 15.4 KiBRaw
1impl IndexBuilder {
2 /// Serialize one feed's routes, trips, profiles, shapes and stop→route lists.
3 ///
4 /// `stop_first` is the first stop index this feed contributed. Because a
5 /// route only ever references its own feed's stops, this feed's STOP_ROUTES
6 /// entries cover exactly `stop_first..` and append onto a globally
7 /// stop-ascending array.
8 fn finalize_feed(
9 &mut self,
10 raptor_routes: &[RaptorRoute],
11 built_trips: &[BuiltTrip],
12 shapes: &[(&str, &Shape)],
13 stop_first: u32,
14 ) -> Result<(), String> {
15 // (stop, route, position in the route's pattern), sorted into
16 // stop-ascending order below. Replaces the old `vec![Vec::new(); stops]`
17 // pair — 48 bytes of empty headers per stop, worldwide — and the
18 // `contains` scan that went with it, which was quadratic on the routes
19 // through a major interchange.
20 let mut stop_routes: Vec<(u32, u32, u32)> = Vec::new();
21
22 for (local_idx, rr) in raptor_routes.iter().enumerate() {
23 let ridx = (self.route_count + local_idx) as u32;
24 // Trips of one pattern normally share a `shape_id`. Where they do not
25 // (versioned shapes, rare express variants) the modal one keeps the
26 // common case exact; direction differences already form distinct
27 // patterns, so they never land here.
28 let mut votes: HashMap<u32, usize> = HashMap::new();
29 for &ti in &rr.trips {
30 let k = built_trips[ti].shape_key;
31 if k != NONE {
32 *votes.entry(k).or_insert(0) += 1;
33 }
34 }
35 if votes.len() > 1 {
36 self.multi_shape_routes += 1;
37 }
38 let mut ranked: Vec<(u32, usize)> = votes.into_iter().collect();
39 // Ties break on the `shape_id` itself, not on its interned index, so
40 // the winner does not depend on the order trips were seen in.
41 ranked.sort_by(|a, b| {
42 b.1.cmp(&a.1).then(shapes[a.0 as usize].0.cmp(shapes[b.0 as usize].0))
43 });
44 let modal = ranked.first().map(|&(k, _)| k);
45 let fitted = modal.and_then(|key| {
46 let shape = shapes[key as usize].1;
47 let stop_ll: Vec<(i32, i32)> = rr
48 .stop_pattern
49 .iter()
50 .map(|&s| (self.stop_lat[s as usize], self.stop_lon[s as usize]))
51 .collect();
52 // `shape_dist_traveled` only helps when both files carry it, so
53 // take it from a trip that actually uses the modal shape.
54 let dists = rr
55 .trips
56 .iter()
57 .filter(|&&ti| built_trips[ti].shape_key == key)
58 .find_map(|&ti| built_trips[ti].stop_dists.as_ref())
59 .filter(|d| d.len() == rr.stop_pattern.len());
60 shapes::fit(shape, &stop_ll, dists.map(|d| d.as_slice()))
61 });
62 if modal.is_some() {
63 if fitted.is_some() {
64 self.shaped_routes += 1;
65 } else {
66 self.dropped_shape_routes += 1;
67 }
68 }
69 let shape_off = match &fitted {
70 None => NONE,
71 Some(f) => self.shape_blobs.intern(&shapes::encode(&f.points))?,
72 };
73 append_u32(&mut self.sec_route_shape_idx, shape_off);
74
75 let first_route_stop = (self.sec_route_stops.len() / 4) as u32;
76 for (pos, &s) in rr.stop_pattern.iter().enumerate() {
77 debug_assert!(
78 s >= stop_first,
79 "route {ridx} references stop {s} from an earlier feed; per-feed \
80 finalization depends on patterns staying inside their own feed"
81 );
82 append_u32(&mut self.sec_route_stops, s);
83 let vertex = fitted
84 .as_ref()
85 .and_then(|f| f.stop_vertices.get(pos).copied())
86 .unwrap_or(NONE);
87 append_u32(&mut self.sec_route_stop_shape, vertex);
88 stop_routes.push((s, ridx, pos as u32));
89 }
90 let n_stops = rr.stop_pattern.len() as u32;
91
92 // Sort this route's trips by first-stop departure, then varint-pack.
93 let mut trip_order: Vec<usize> = rr.trips.clone();
94 trip_order.sort_by_key(|&ti| built_trips[ti].start_time);
95 // RouteRec.trips_off is a u32 byte offset into ROUTE_TRIPS.
96 let trips_off = u32::try_from(self.sec_route_trips.len()).map_err(|_| {
97 "ROUTE_TRIPS exceeded 4 GiB, which a u32 RouteRec.trips_off cannot address"
98 .to_string()
99 })?;
100 let mut prev_start: u32 = 0;
101 // The CSR prefix: this route's first trip in the strided table.
102 append_u32(&mut self.sec_route_trip_off, self.trip_total as u32);
103 for &ti in &trip_order {
104 let bt = &built_trips[ti];
105 let profile_id = self.profiles.intern(&bt.stoptimes)?;
106 let start_delta = bt.start_time.saturating_sub(prev_start);
107 write_uvarint(&mut self.sec_route_trips, start_delta as u64);
108 write_uvarint(&mut self.sec_route_trips, profile_id as u64);
109 write_uvarint(&mut self.sec_route_trips, bt.service_idx as u64);
110 write_uvarint(&mut self.sec_route_trips, bt.headsign_off as u64);
111 append_u32(&mut self.sec_route_trip_recs, bt.start_time);
112 append_u32(&mut self.sec_route_trip_recs, profile_id);
113 append_u32(&mut self.sec_route_trip_recs, bt.service_idx);
114 append_u32(&mut self.sec_route_trip_recs, bt.headsign_off);
115 prev_start = bt.start_time;
116 self.trip_total += 1;
117 }
118
119 append_u32(&mut self.sec_routes, rr.name_off);
120 append_u32(&mut self.sec_routes, rr.color);
121 append_u32(&mut self.sec_routes, rr.route_type);
122 append_u32(&mut self.sec_routes, rr.feed_idx);
123 append_u32(&mut self.sec_routes, n_stops);
124 append_u32(&mut self.sec_routes, first_route_stop);
125 append_u32(&mut self.sec_routes, trip_order.len() as u32);
126 append_u32(&mut self.sec_routes, trips_off);
127 }
128 self.route_count += raptor_routes.len();
129
130 // Stable, so within a stop the routes stay in ascending route order and
131 // the surviving position is the pattern's first occurrence of that stop —
132 // matching the reader's `break`-on-match scan that STOP_ROUTE_POS
133 // replaces.
134 stop_routes.sort_by_key(|&(s, _, _)| s);
135 stop_routes.dedup_by(|a, b| a.0 == b.0 && a.1 == b.1);
136 let mut k = 0usize;
137 for s in stop_first..self.stop_lat.len() as u32 {
138 append_u32(&mut self.sec_stop_routes_idx, self.stop_routes_total);
139 while let Some(&(stop, route, pos)) = stop_routes.get(k) {
140 if stop != s {
141 break;
142 }
143 append_u32(&mut self.sec_stop_routes, route);
144 append_u32(&mut self.sec_stop_route_pos, pos);
145 self.stop_routes_total += 1;
146 k += 1;
147 }
148 }
149 debug_assert_eq!(k, stop_routes.len(), "a stop→route entry fell outside this feed");
150 Ok(())
151 }
152
153 /// Serialize the sections that need every feed, and write the pack to `out`.
154 pub fn finish_to(self, out: &mut impl Write) -> Result<BuildStats, String> {
155 let IndexBuilder {
156 pool,
157 pack_name_off,
158 stop_lat,
159 stop_lon,
160 min_lat,
161 min_lon,
162 max_lat,
163 max_lon,
164 service_key_to_idx: _,
165 svc_mask,
166 svc_start,
167 svc_end,
168 exceptions,
169 feed_name_offs,
170 feed_tz_offs,
171 feed_motis_prefix_offs,
172 sec_stops,
173 sec_stop_gtfs_id,
174 sec_routes,
175 sec_route_stops,
176 sec_route_trips,
177 sec_route_trip_recs,
178 mut sec_route_trip_off,
179 mut sec_route_shape_idx,
180 sec_route_stop_shape,
181 sec_stop_routes,
182 mut sec_stop_routes_idx,
183 sec_stop_route_pos,
184 profiles,
185 shape_blobs,
186 rail_lines,
187 stop_routes_total,
188 route_count,
189 trip_total,
190 shaped_routes,
191 multi_shape_routes,
192 dropped_shape_routes,
193 dropped_stops_bad_coord,
194 } = self;
195 let stop_count = stop_lat.len();
196 if stop_count == 0 {
197 return Err("no usable stops in any feed".to_string());
198 }
199
200 // Everything that depends on one feed alone is already serialized; what
201 // is left needs the whole merged stop set.
202
203 // Terminating bound the reader validates shape offsets against.
204 append_u32(&mut sec_route_shape_idx, shape_blobs.bytes.len() as u32);
205 // Terminating total, so the last stop's STOP_ROUTES range closes.
206 append_u32(&mut sec_stop_routes_idx, stop_routes_total);
207
208 // Profiles index (byte offset per id, plus terminating length).
209 let mut sec_profiles_idx = Vec::new();
210 for &off in &profiles.offsets {
211 append_u32(&mut sec_profiles_idx, off);
212 }
213 append_u32(&mut sec_profiles_idx, profiles.bytes.len() as u32);
214 let profile_count = profiles.offsets.len();
215
216 // A wrapped STRINGS offset would name the wrong stop rather than fail, so
217 // this is checked before anything is written.
218 if pool.overflowed {
219 return Err(
220 "STRINGS exceeded the 4 GiB a u32 string offset can address; the pack cannot \
221 represent this many feeds"
222 .to_string(),
223 );
224 }
225
226 let (sec_transfers, sec_transfers_idx, transfer_total) =
227 build_transfers(&stop_lat, &stop_lon);
228
229 let (sec_services, sec_exceptions, sec_exceptions_idx) =
230 build_services_and_exceptions(&svc_mask, &svc_start, &svc_end, exceptions);
231
232 // --- Spatial grid (sparse CSR keyed by cell id) ---
233 let grid_lat0 = min_lat;
234 let grid_lon0 = min_lon;
235 let (
236 sec_grid_cell_ids,
237 sec_grid_cell_off,
238 sec_grid_stops,
239 grid_cols,
240 grid_rows,
241 grid_cell_e7,
242 grid_cell_count,
243 ) = build_spatial_grid(&stop_lat, &stop_lon, grid_lat0, grid_lon0, max_lat, max_lon);
244
245 // --- Feeds ---
246 let mut sec_feeds = Vec::with_capacity(feed_name_offs.len() * 4);
247 for &off in &feed_name_offs {
248 append_u32(&mut sec_feeds, off);
249 }
250 let mut sec_feed_tz = Vec::with_capacity(feed_tz_offs.len() * 4);
251 for &off in &feed_tz_offs {
252 append_u32(&mut sec_feed_tz, off);
253 }
254 let mut sec_feed_motis_prefix = Vec::with_capacity(feed_motis_prefix_offs.len() * 4);
255 for &off in &feed_motis_prefix_offs {
256 append_u32(&mut sec_feed_motis_prefix, off);
257 }
258
259 // --- Assemble file: header + directory + aligned sections ---
260 let section_names: [&'static str; SECTION_COUNT] = [
261 "STRINGS",
262 "STOPS",
263 "ROUTES",
264 "ROUTE_STOPS",
265 "ROUTE_TRIPS",
266 "PROFILES",
267 "PROFILES_IDX",
268 "STOP_ROUTES",
269 "STOP_ROUTES_IDX",
270 "TRANSFERS",
271 "TRANSFERS_IDX",
272 "SERVICES",
273 "EXCEPTIONS",
274 "GRID_CELL_IDS",
275 "GRID_CELL_OFF",
276 "GRID_STOPS",
277 "FEEDS",
278 "FEED_TZ",
279 "EXCEPTIONS_IDX",
280 "STOP_ROUTE_POS",
281 "SHAPE_COORDS",
282 "ROUTE_SHAPE_IDX",
283 "ROUTE_STOP_SHAPE",
284 "FEED_MOTIS_PREFIX",
285 "STOP_GTFS_ID",
286 "ROUTE_TRIP_RECS",
287 "ROUTE_TRIP_OFF",
288 "RAIL_LINES",
289 ];
290 // Close the CSR prefix: one past the last route's trips, i.e. the total. Done
291 // here because it is only known once every feed's routes have been written.
292 append_u32(&mut sec_route_trip_off, trip_total as u32);
293 let sec_rail_lines = rail_lines.into_section();
294 let sections: [&[u8]; SECTION_COUNT] = [
295 &pool.bytes,
296 &sec_stops,
297 &sec_routes,
298 &sec_route_stops,
299 &sec_route_trips,
300 &profiles.bytes,
301 &sec_profiles_idx,
302 &sec_stop_routes,
303 &sec_stop_routes_idx,
304 &sec_transfers,
305 &sec_transfers_idx,
306 &sec_services,
307 &sec_exceptions,
308 &sec_grid_cell_ids,
309 &sec_grid_cell_off,
310 &sec_grid_stops,
311 &sec_feeds,
312 &sec_feed_tz,
313 &sec_exceptions_idx,
314 &sec_stop_route_pos,
315 &shape_blobs.bytes,
316 &sec_route_shape_idx,
317 &sec_route_stop_shape,
318 &sec_feed_motis_prefix,
319 &sec_stop_gtfs_id,
320 &sec_route_trip_recs,
321 &sec_route_trip_off,
322 &sec_rail_lines,
323 ];
324
325 let dir_len = SECTION_COUNT * 16;
326 let mut data_off = HEADER_LEN + dir_len;
327 let align = |o: usize| (o + 7) & !7;
328 for s in sections.iter() {
329 data_off = align(data_off) + s.len();
330 }
331 let total = data_off;
332
333 let mut header: Vec<u8> = Vec::with_capacity(HEADER_LEN);
334 append_u32(&mut header, MAGIC);
335 append_u32(&mut header, VERSION);
336 append_u32(&mut header, SECTION_COUNT as u32);
337 append_u32(&mut header, stop_count as u32);
338 append_u32(&mut header, route_count as u32);
339 append_u32(&mut header, trip_total as u32);
340 append_u32(&mut header, svc_mask.len() as u32);
341 append_u32(&mut header, profile_count as u32);
342 append_u32(&mut header, feed_name_offs.len() as u32);
343 append_u32(&mut header, grid_cell_count as u32);
344 append_u32(&mut header, pack_name_off);
345 append_i32(&mut header, min_lat);
346 append_i32(&mut header, min_lon);
347 append_i32(&mut header, max_lat);
348 append_i32(&mut header, max_lon);
349 append_i32(&mut header, grid_lat0);
350 append_i32(&mut header, grid_lon0);
351 append_u32(&mut header, grid_cell_e7);
352 append_u32(&mut header, grid_cols);
353 append_u32(&mut header, grid_rows);
354 debug_assert_eq!(header.len(), HEADER_LEN);
355
356 let written =
357 write_pack(out, &header, &sections).map_err(|e| format!("cannot write the pack: {e}"))?;
358 debug_assert_eq!(written, total);
359
360 let section_sizes: Vec<(&'static str, usize)> =
361 section_names.iter().zip(sections.iter()).map(|(&n, s)| (n, s.len())).collect();
362
363 Ok(BuildStats {
364 stops: stop_count,
365 routes: route_count,
366 trips: trip_total,
367 profiles: profile_count,
368 feeds: feed_name_offs.len(),
369 transfers: transfer_total,
370 min_lat_e7: min_lat,
371 min_lon_e7: min_lon,
372 max_lat_e7: max_lat,
373 max_lon_e7: max_lon,
374 size_bytes: written,
375 section_sizes,
376 shaped_routes,
377 multi_shape_routes,
378 dropped_shape_routes,
379 dropped_stops_bad_coord,
380 })
381 }
382
383}