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

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

index_part1.rs197 lines · 7.0 KiBRaw
1impl<'a> From<&'a FeedDir<'a>> for FeedView<'a> {
2 fn from(f: &'a FeedDir<'a>) -> FeedView<'a> {
3 FeedView {
4 name: &f.name,
5 motis_prefix: &f.motis_prefix,
6 stops: f.stops,
7 routes: f.routes,
8 trips: f.trips,
9 calendar: f.calendar,
10 calendar_dates: f.calendar_dates,
11 agency: f.agency,
12 shapes: f.shapes,
13 stop_times: StopTimesSource::Dir(f.dir),
14 }
15 }
16}
17
18/// Summary counts reported to the caller / manifest.
19pub struct BuildStats {
20 pub stops: usize,
21 pub routes: usize,
22 pub trips: usize,
23 pub profiles: usize,
24 pub feeds: usize,
25 pub transfers: usize,
26 pub min_lat_e7: i32,
27 pub min_lon_e7: i32,
28 pub max_lat_e7: i32,
29 pub max_lon_e7: i32,
30 pub size_bytes: usize,
31 /// (section name, byte length) for the size-breakdown report.
32 pub section_sizes: Vec<(&'static str, usize)>,
33 /// Routes that got `shapes.txt` ride geometry.
34 pub shaped_routes: usize,
35 /// Routes whose trips disagreed on `shape_id`; the modal one was used.
36 pub multi_shape_routes: usize,
37 /// Routes whose shape failed validation and fell back to stop-to-stop.
38 pub dropped_shape_routes: usize,
39 /// Stops dropped because `stop_lat`/`stop_lon` was missing, unparseable or
40 /// outside the WGS84 ranges. A non-zero count is a data-quality signal, not
41 /// a build error.
42 pub dropped_stops_bad_coord: usize,
43}
44
45fn append_u32(v: &mut Vec<u8>, x: u32) {
46 v.extend_from_slice(&x.to_le_bytes());
47}
48fn append_i32(v: &mut Vec<u8>, x: i32) {
49 v.extend_from_slice(&x.to_le_bytes());
50}
51
52/// Approximate ground distance in metres (equirectangular; fine at footpath
53/// range).
54fn dist_m(lat1_e7: i32, lon1_e7: i32, lat2_e7: i32, lon2_e7: i32) -> f64 {
55 let lat1 = lat1_e7 as f64 * 1e-7;
56 let lat2 = lat2_e7 as f64 * 1e-7;
57 let dlat = (lat2 - lat1) * 111_320.0;
58 let mean = ((lat1 + lat2) * 0.5).to_radians();
59 let dlon = (lon2_e7 as f64 * 1e-7 - lon1_e7 as f64 * 1e-7) * 111_320.0 * mean.cos();
60 (dlat * dlat + dlon * dlon).sqrt()
61}
62
63/// A RAPTOR route: trips grouped by identical (feed, gtfs route, stop pattern).
64struct RaptorRoute {
65 feed_idx: u32,
66 /// The feed's own `route_id`. Kept because grouping is by
67 /// `(route_id, stop_pattern)`: two GTFS routes over the same stops are two
68 /// RAPTOR routes, and `pattern_index` confirms a candidate against this.
69 route_id: String,
70 name_off: u32,
71 color: u32,
72 route_type: u32,
73 stop_pattern: Vec<u32>,
74 trips: Vec<usize>, // indices into `built_trips`
75}
76
77/// A trip reduced to its start time + run-time shape, ready for profile dedup.
78struct BuiltTrip {
79 service_idx: u32,
80 headsign_off: u32,
81 start_time: u32, // departure at the first stop
82 stoptimes: Vec<(u32, u32)>, // (arr, dep) aligned to the route's stop_pattern
83 /// Index into the feed's interned shape list, or [`NONE`] when the trip
84 /// references no usable shape.
85 shape_key: u32,
86 /// `shape_dist_traveled` per pattern stop, when every stop has one.
87 stop_dists: Option<Vec<f64>>,
88}
89
90/// Build the whole pack in memory from feeds whose tables are already parsed.
91/// `pack_name` is stored in the string pool and surfaced to the on-device planner
92/// as a fallback.
93///
94/// Convenience for tests and small corpora. The host tool drives
95/// [`IndexBuilder`] directly instead, one feed at a time, so it never holds more
96/// than one feed's tables — or a second copy of the pack.
97pub fn build_index(
98 pack_name: &str,
99 feeds: &[FeedInput],
100) -> Result<(Vec<u8>, BuildStats), String> {
101 let mut builder = IndexBuilder::new(pack_name);
102 for feed in feeds {
103 builder.add_feed(feed)?;
104 }
105 let mut blob = Vec::new();
106 let stats = builder.finish_to(&mut blob)?;
107 Ok((blob, stats))
108}
109
110/// One GTFS route's own fields, before its trips are grouped into patterns.
111struct RouteMeta {
112 name_off: u32,
113 color: u32,
114 route_type: u32,
115}
116
117/// One GTFS trip's own fields, before its `stop_times` are attached.
118struct TripMeta {
119 route_id: String,
120 service_id: String,
121 headsign_off: u32,
122 shape_id: String,
123}
124
125/// Accumulates GTFS feeds into one merged pack.
126///
127/// Feeds go in one at a time through [`IndexBuilder::add_feed`] (or
128/// [`IndexBuilder::add_feed_dir`], which streams `stop_times.txt`), and each call
129/// both ingests a feed **and finalizes it**: its routes, trips, profiles, shapes
130/// and stop→route lists are serialized before the next feed is touched, so
131/// nothing per-feed survives the feed boundary. That is legal because a route
132/// never references a stop outside its own feed (`stop_id_to_idx` is per-feed),
133/// which `add` asserts.
134///
135/// What crosses a boundary is only the pack itself — the section buffers, the
136/// string pool, the profile and shape tables — plus `stop_lat`/`stop_lon`,
137/// services and exceptions, which the transfers, both grids and the bbox need
138/// once every feed is in.
139pub struct IndexBuilder {
140 pool: StringPool,
141 /// STRINGS offset of the pack name, for the header.
142 pack_name_off: u32,
143
144 // Merged stop coordinates, in feed order; a feed's stops are one contiguous
145 // run. Kept (unlike the name/code offsets, which go straight into STOPS)
146 // because transfers, the transfer grid, the spatial grid and the bbox all
147 // need them, and `grid_cols` is only known once the last feed is in. 8 bytes
148 // a stop is ~80-160 MB on a world pack.
149 stop_lat: Vec<i32>,
150 stop_lon: Vec<i32>,
151 min_lat: i32,
152 min_lon: i32,
153 max_lat: i32,
154 max_lon: i32,
155
156 // Services, namespaced by feed, plus exceptions against the global index.
157 service_key_to_idx: HashMap<String, u32>,
158 svc_mask: Vec<u8>,
159 svc_start: Vec<u32>,
160 svc_end: Vec<u32>,
161 exceptions: Vec<(u32, u32, u32)>,
162
163 feed_name_offs: Vec<u32>,
164 feed_tz_offs: Vec<u32>,
165 feed_motis_prefix_offs: Vec<u32>,
166
167 // Sections, appended feed by feed.
168 sec_stops: Vec<u8>,
169 sec_stop_gtfs_id: Vec<u8>,
170 sec_routes: Vec<u8>,
171 sec_route_stops: Vec<u8>,
172 sec_route_trips: Vec<u8>,
173 /// v6: fixed-stride `u32 start_time, profile_id, service_idx, headsign_off` per
174 /// trip, per route contiguous, so a trip is addressable by index. Written
175 /// alongside ROUTE_TRIPS rather than replacing it, because the device reader's
176 /// version window still accepts packs that only have the varint stream.
177 sec_route_trip_recs: Vec<u8>,
178 /// v6: `u32[route_count + 1]` CSR prefix into [`Self::sec_route_trip_recs`].
179 sec_route_trip_off: Vec<u8>,
180 sec_route_shape_idx: Vec<u8>,
181 sec_route_stop_shape: Vec<u8>,
182 sec_stop_routes: Vec<u8>,
183 sec_stop_routes_idx: Vec<u8>,
184 sec_stop_route_pos: Vec<u8>,
185 profiles: ProfileTable,
186 shape_blobs: ShapeBlobs,
187 rail_lines: RailLines,
188 /// Running STOP_ROUTES entry count, i.e. the next STOP_ROUTES_IDX value.
189 stop_routes_total: u32,
190
191 route_count: usize,
192 trip_total: usize,
193 shaped_routes: usize,
194 multi_shape_routes: usize,
195 dropped_shape_routes: usize,
196 dropped_stops_bad_coord: usize,
197}