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

Modern-Apps.git / maps / src / main / rust / tests / real_archive / pack.rs

pack.rs482 lines · 16.7 KiBRaw
1//! A minimal TRIX pack writer for the synthetic-archive tests.
2//!
3//! Mirrors the test writer in `src/transit_part6.rs` (which cannot be
4//! linked from an integration test): if the two drift, these tests
5//! fail, which is the point. Builds the same three-stop pack the unit
6//! tests plan over, at raw v7 (planet4's layout).
7
8use std::collections::HashMap;
9
10const NONE: u32 = 0xFFFF_FFFF;
11const HEADER_LEN: usize = 80;
12const MAGIC: u32 = tilecodec::mamaps::archive::TRANSIT_MAGIC;
13const GRID_CELL_E7: u32 = 200_000;
14const MAX_TRANSFER_M: f64 = 400.0;
15const WALK_SPEED_M_S: f64 = 4.5 / 3.6;
16
17fn dist_m(lat1: f64, lon1: f64, lat2: f64, lon2: f64) -> f64 {
18 let dlat = (lat2 - lat1) * 111_320.0;
19 let mean = ((lat1 + lat2) * 0.5).to_radians();
20 let dlon = (lon2 - lon1) * 111_320.0 * mean.cos();
21 (dlat * dlat + dlon * dlon).sqrt()
22}
23
24struct Stop {
25 lat: f64,
26 lon: f64,
27 name: &'static str,
28 code: &'static str,
29 gtfs_id: &'static str,
30}
31
32struct Trip {
33 start: u32,
34 stoptimes: Vec<(u32, u32)>,
35 service: u32,
36 headsign: &'static str,
37}
38
39struct Shape {
40 points: Vec<(f64, f64)>,
41 stop_vertices: Vec<u32>,
42}
43
44struct Route {
45 name: &'static str,
46 color: u32,
47 route_type: u32,
48 feed: u32,
49 pattern: Vec<u32>,
50 trips: Vec<Trip>,
51 shape: Option<Shape>,
52}
53
54struct Service {
55 mask: u8,
56 start: u32,
57 end: u32,
58}
59
60struct Pack {
61 stops: Vec<Stop>,
62 routes: Vec<Route>,
63 services: Vec<Service>,
64 exceptions: Vec<(u32, u32, u32)>,
65 feeds: Vec<(&'static str, &'static str, &'static str)>,
66}
67
68#[derive(Default)]
69struct Pool {
70 bytes: Vec<u8>,
71 map: HashMap<String, u32>,
72}
73
74impl Pool {
75 fn new() -> Pool {
76 Pool { bytes: vec![0], map: HashMap::new() }
77 }
78 fn intern(&mut self, s: &str) -> u32 {
79 if s.is_empty() {
80 return NONE;
81 }
82 if let Some(&o) = self.map.get(s) {
83 return o;
84 }
85 let off = self.bytes.len() as u32;
86 self.bytes.extend_from_slice(s.as_bytes());
87 self.bytes.push(0);
88 self.map.insert(s.to_string(), off);
89 off
90 }
91}
92
93fn u32b(v: &mut Vec<u8>, x: u32) {
94 v.extend_from_slice(&x.to_le_bytes());
95}
96fn i32b(v: &mut Vec<u8>, x: i32) {
97 v.extend_from_slice(&x.to_le_bytes());
98}
99fn uvarint(v: &mut Vec<u8>, mut x: u64) {
100 loop {
101 let b = (x & 0x7f) as u8;
102 x >>= 7;
103 if x != 0 {
104 v.push(b | 0x80);
105 } else {
106 v.push(b);
107 break;
108 }
109 }
110}
111fn zigzag_varint(v: &mut Vec<u8>, x: i64) {
112 uvarint(v, ((x << 1) ^ (x >> 63)) as u64);
113}
114
115impl Pack {
116 fn build_with_version(&self, version: u32) -> Vec<u8> {
117 let mut pool = Pool::new();
118 let pack_name_off = pool.intern("testpack");
119
120 let n_stops = self.stops.len();
121 let mut sec_stops = Vec::new();
122 let mut sec_stop_gtfs_id = Vec::new();
123 let mut sec_route_trip_recs = Vec::new();
124 let mut sec_route_trip_off = Vec::new();
125 let (mut min_lat, mut min_lon) = (i32::MAX, i32::MAX);
126 let (mut max_lat, mut max_lon) = (i32::MIN, i32::MIN);
127 let lat_e7: Vec<i32> = self.stops.iter().map(|s| (s.lat * 1e7) as i32).collect();
128 let lon_e7: Vec<i32> = self.stops.iter().map(|s| (s.lon * 1e7) as i32).collect();
129 for i in 0..n_stops {
130 min_lat = min_lat.min(lat_e7[i]);
131 min_lon = min_lon.min(lon_e7[i]);
132 max_lat = max_lat.max(lat_e7[i]);
133 max_lon = max_lon.max(lon_e7[i]);
134 }
135 for (i, s) in self.stops.iter().enumerate() {
136 i32b(&mut sec_stops, lat_e7[i]);
137 i32b(&mut sec_stops, lon_e7[i]);
138 let n = pool.intern(s.name);
139 let c = pool.intern(s.code);
140 u32b(&mut sec_stops, n);
141 u32b(&mut sec_stops, c);
142 let g = pool.intern(s.gtfs_id);
143 u32b(&mut sec_stop_gtfs_id, g);
144 }
145
146 let mut profile_bytes: Vec<u8> = Vec::new();
147 let mut profile_offsets: Vec<u32> = Vec::new();
148 let mut profile_ids: HashMap<Vec<u8>, u32> = HashMap::new();
149 let mut intern_profile = |sts: &[(u32, u32)]| -> u32 {
150 let mut body = Vec::new();
151 uvarint(&mut body, sts.len() as u64);
152 let (arr0, dep0) = sts[0];
153 uvarint(&mut body, dep0.saturating_sub(arr0) as u64);
154 let mut prev_dep = dep0;
155 for &(arr, dep) in &sts[1..] {
156 uvarint(&mut body, arr.saturating_sub(prev_dep) as u64);
157 uvarint(&mut body, dep.saturating_sub(arr) as u64);
158 prev_dep = dep;
159 }
160 if let Some(&id) = profile_ids.get(&body) {
161 return id;
162 }
163 let id = profile_offsets.len() as u32;
164 profile_offsets.push(profile_bytes.len() as u32);
165 profile_bytes.extend_from_slice(&body);
166 profile_ids.insert(body, id);
167 id
168 };
169
170 let mut sec_routes = Vec::new();
171 let mut sec_route_stops = Vec::new();
172 let mut sec_route_trips = Vec::new();
173 let mut sec_route_stop_shape = Vec::new();
174 let mut sec_route_shape_idx = Vec::new();
175 let mut shape_bytes: Vec<u8> = Vec::new();
176 let mut shape_offsets: HashMap<Vec<u8>, u32> = HashMap::new();
177 let mut stop_routes: Vec<Vec<(u32, u32)>> = vec![Vec::new(); n_stops];
178 let mut trip_total = 0usize;
179
180 for (ridx, r) in self.routes.iter().enumerate() {
181 let first_route_stop = (sec_route_stops.len() / 4) as u32;
182 for (pos, &s) in r.pattern.iter().enumerate() {
183 u32b(&mut sec_route_stops, s);
184 let vertex = r
185 .shape
186 .as_ref()
187 .and_then(|sh| sh.stop_vertices.get(pos).copied())
188 .unwrap_or(NONE);
189 u32b(&mut sec_route_stop_shape, vertex);
190 let sr = &mut stop_routes[s as usize];
191 if !sr.iter().any(|&(rr, _)| rr == ridx as u32) {
192 sr.push((ridx as u32, pos as u32));
193 }
194 }
195 let shape_off = match &r.shape {
196 None => NONE,
197 Some(sh) => {
198 let mut body = Vec::new();
199 u32b(&mut body, sh.points.len() as u32);
200 let (mut plat, mut plon) = (0i64, 0i64);
201 for &(lat, lon) in &sh.points {
202 let lat_e7 = (lat * 1e7).round() as i64;
203 let lon_e7 = (lon * 1e7).round() as i64;
204 zigzag_varint(&mut body, lat_e7 - plat);
205 zigzag_varint(&mut body, lon_e7 - plon);
206 plat = lat_e7;
207 plon = lon_e7;
208 }
209 match shape_offsets.get(&body) {
210 Some(&off) => off,
211 None => {
212 let off = shape_bytes.len() as u32;
213 shape_bytes.extend_from_slice(&body);
214 shape_offsets.insert(body, off);
215 off
216 }
217 }
218 }
219 };
220 u32b(&mut sec_route_shape_idx, shape_off);
221 let trips_off = sec_route_trips.len() as u32;
222 let mut ordered: Vec<&Trip> = r.trips.iter().collect();
223 ordered.sort_by_key(|t| t.start);
224 u32b(&mut sec_route_trip_off, trip_total as u32);
225 let mut prev_start = 0u32;
226 for t in &ordered {
227 let pid = intern_profile(&t.stoptimes);
228 uvarint(&mut sec_route_trips, t.start.saturating_sub(prev_start) as u64);
229 uvarint(&mut sec_route_trips, pid as u64);
230 uvarint(&mut sec_route_trips, t.service as u64);
231 let h = pool.intern(t.headsign);
232 uvarint(&mut sec_route_trips, h as u64);
233 u32b(&mut sec_route_trip_recs, t.start);
234 u32b(&mut sec_route_trip_recs, pid);
235 u32b(&mut sec_route_trip_recs, t.service);
236 u32b(&mut sec_route_trip_recs, h);
237 prev_start = t.start;
238 trip_total += 1;
239 }
240 let name_off = pool.intern(r.name);
241 u32b(&mut sec_routes, name_off);
242 u32b(&mut sec_routes, r.color);
243 u32b(&mut sec_routes, r.route_type);
244 u32b(&mut sec_routes, r.feed);
245 u32b(&mut sec_routes, r.pattern.len() as u32);
246 u32b(&mut sec_routes, first_route_stop);
247 u32b(&mut sec_routes, ordered.len() as u32);
248 u32b(&mut sec_routes, trips_off);
249 }
250
251 let mut sec_profiles_idx = Vec::new();
252 for &o in &profile_offsets {
253 u32b(&mut sec_profiles_idx, o);
254 }
255 u32b(&mut sec_profiles_idx, profile_bytes.len() as u32);
256
257 let mut sec_stop_routes = Vec::new();
258 let mut sec_stop_routes_idx = Vec::new();
259 let mut sec_stop_route_pos = Vec::new();
260 let mut acc = 0u32;
261 for sr in &stop_routes {
262 u32b(&mut sec_stop_routes_idx, acc);
263 for &(r, pos) in sr {
264 u32b(&mut sec_stop_routes, r);
265 u32b(&mut sec_stop_route_pos, pos);
266 }
267 acc += sr.len() as u32;
268 }
269 u32b(&mut sec_stop_routes_idx, acc);
270
271 let mut sec_transfers = Vec::new();
272 let mut sec_transfers_idx = Vec::new();
273 let mut tacc = 0u32;
274 for i in 0..n_stops {
275 u32b(&mut sec_transfers_idx, tacc);
276 for j in 0..n_stops {
277 if i == j {
278 continue;
279 }
280 let d = dist_m(
281 self.stops[i].lat,
282 self.stops[i].lon,
283 self.stops[j].lat,
284 self.stops[j].lon,
285 );
286 if d <= MAX_TRANSFER_M {
287 u32b(&mut sec_transfers, j as u32);
288 u32b(&mut sec_transfers, (d / WALK_SPEED_M_S).ceil() as u32);
289 tacc += 1;
290 }
291 }
292 }
293 u32b(&mut sec_transfers_idx, tacc);
294
295 let mut sec_services = Vec::new();
296 for s in &self.services {
297 sec_services.push(s.mask);
298 sec_services.extend_from_slice(&[0u8, 0, 0]);
299 u32b(&mut sec_services, s.start);
300 u32b(&mut sec_services, s.end);
301 }
302
303 let mut exc = self.exceptions.clone();
304 exc.sort_by_key(|&(s, d, _)| (s, d));
305 let mut sec_exceptions = Vec::new();
306 let mut sec_exceptions_idx = Vec::new();
307 let mut eacc = 0u32;
308 let mut ei = 0usize;
309 for s in 0..self.services.len() as u32 {
310 u32b(&mut sec_exceptions_idx, eacc);
311 while exc.get(ei).is_some_and(|&(sidx, _, _)| sidx == s) {
312 let (sidx, date, added) = exc[ei];
313 u32b(&mut sec_exceptions, sidx);
314 u32b(&mut sec_exceptions, date);
315 u32b(&mut sec_exceptions, added);
316 eacc += 1;
317 ei += 1;
318 }
319 }
320 u32b(&mut sec_exceptions_idx, eacc);
321
322 let cell_col = |lon: i32| ((lon as i64 - min_lon as i64) / GRID_CELL_E7 as i64).max(0);
323 let cell_row = |lat: i32| ((lat as i64 - min_lat as i64) / GRID_CELL_E7 as i64).max(0);
324 let grid_cols = (cell_col(max_lon) + 1) as u32;
325 let grid_rows = (cell_row(max_lat) + 1) as u32;
326 let mut grid: HashMap<u32, Vec<u32>> = HashMap::new();
327 for i in 0..n_stops {
328 let cid = cell_row(lat_e7[i]) as u32 * grid_cols + cell_col(lon_e7[i]) as u32;
329 grid.entry(cid).or_default().push(i as u32);
330 }
331 let mut cell_ids: Vec<u32> = grid.keys().copied().collect();
332 cell_ids.sort_unstable();
333 let mut sec_grid_cell_ids = Vec::new();
334 let mut sec_grid_cell_off = Vec::new();
335 let mut sec_grid_stops = Vec::new();
336 let mut gacc = 0u32;
337 for &cid in &cell_ids {
338 u32b(&mut sec_grid_cell_ids, cid);
339 u32b(&mut sec_grid_cell_off, gacc);
340 for &s in &grid[&cid] {
341 u32b(&mut sec_grid_stops, s);
342 }
343 gacc += grid[&cid].len() as u32;
344 }
345 u32b(&mut sec_grid_cell_off, gacc);
346
347 let mut sec_feeds = Vec::new();
348 let mut sec_feed_tz = Vec::new();
349 let mut sec_feed_motis_prefix = Vec::new();
350 for &(name, tz, motis) in &self.feeds {
351 let n = pool.intern(name);
352 let t = pool.intern(tz);
353 let m = pool.intern(motis);
354 u32b(&mut sec_feeds, n);
355 u32b(&mut sec_feed_tz, t);
356 u32b(&mut sec_feed_motis_prefix, m);
357 }
358
359 let mut sections: Vec<&[u8]> = vec![
360 &pool.bytes,
361 &sec_stops,
362 &sec_routes,
363 &sec_route_stops,
364 &sec_route_trips,
365 &profile_bytes,
366 &sec_profiles_idx,
367 &sec_stop_routes,
368 &sec_stop_routes_idx,
369 &sec_transfers,
370 &sec_transfers_idx,
371 &sec_services,
372 &sec_exceptions,
373 &sec_grid_cell_ids,
374 &sec_grid_cell_off,
375 &sec_grid_stops,
376 &sec_feeds,
377 &sec_feed_tz,
378 &sec_exceptions_idx,
379 &sec_stop_route_pos,
380 ];
381 if version >= 4 {
382 u32b(&mut sec_route_shape_idx, shape_bytes.len() as u32);
383 sections.push(&shape_bytes);
384 sections.push(&sec_route_shape_idx);
385 sections.push(&sec_route_stop_shape);
386 }
387 if version >= 5 {
388 sections.push(&sec_feed_motis_prefix);
389 sections.push(&sec_stop_gtfs_id);
390 }
391 if version >= 6 {
392 u32b(&mut sec_route_trip_off, trip_total as u32);
393 sections.push(&sec_route_trip_recs);
394 sections.push(&sec_route_trip_off);
395 }
396 let section_count = sections.len();
397
398 let align = |o: usize| (o + 7) & !7;
399 let mut data_off = HEADER_LEN + section_count * 16;
400 let mut dir: Vec<(u64, u64)> = Vec::new();
401 for s in sections.iter() {
402 data_off = align(data_off);
403 dir.push((data_off as u64, s.len() as u64));
404 data_off += s.len();
405 }
406
407 let mut out = Vec::with_capacity(data_off);
408 u32b(&mut out, MAGIC);
409 u32b(&mut out, version);
410 u32b(&mut out, section_count as u32);
411 u32b(&mut out, n_stops as u32);
412 u32b(&mut out, self.routes.len() as u32);
413 u32b(&mut out, trip_total as u32);
414 u32b(&mut out, self.services.len() as u32);
415 u32b(&mut out, profile_offsets.len() as u32);
416 u32b(&mut out, self.feeds.len() as u32);
417 u32b(&mut out, cell_ids.len() as u32);
418 u32b(&mut out, pack_name_off);
419 i32b(&mut out, min_lat);
420 i32b(&mut out, min_lon);
421 i32b(&mut out, max_lat);
422 i32b(&mut out, max_lon);
423 i32b(&mut out, min_lat);
424 i32b(&mut out, min_lon);
425 u32b(&mut out, GRID_CELL_E7);
426 u32b(&mut out, grid_cols);
427 u32b(&mut out, grid_rows);
428 assert_eq!(out.len(), HEADER_LEN);
429 for (off, len) in &dir {
430 out.extend_from_slice(&off.to_le_bytes());
431 out.extend_from_slice(&len.to_le_bytes());
432 }
433 for s in sections.iter() {
434 out.resize(align(out.len()), 0);
435 out.extend_from_slice(s);
436 }
437 out
438 }
439}
440
441pub fn synthetic_pack() -> Vec<u8> {
442 one_route_pack().build_with_version(7)
443}
444
445fn weekdays() -> Service {
446 Service { mask: 0b0011_1111 & 0b0001_1111, start: 20_240_101, end: 20_241_231 }
447}
448
449fn one_route_pack() -> Pack {
450 Pack {
451 stops: vec![
452 Stop { lat: 37.700, lon: -122.400, name: "Alpha", code: "A1", gtfs_id: "901201" },
453 Stop { lat: 37.710, lon: -122.400, name: "Beta", code: "B2", gtfs_id: "901202" },
454 Stop { lat: 37.720, lon: -122.400, name: "Gamma", code: "C3", gtfs_id: "901203" },
455 ],
456 routes: vec![Route {
457 name: "N",
458 color: 0x0000FF,
459 route_type: 0,
460 feed: 0,
461 pattern: vec![0, 1, 2],
462 trips: vec![
463 Trip {
464 start: 28_800,
465 stoptimes: vec![(28_800, 28_800), (29_100, 29_160), (29_400, 29_400)],
466 service: 0,
467 headsign: "Downtown",
468 },
469 Trip {
470 start: 32_400,
471 stoptimes: vec![(32_400, 32_400), (32_700, 32_760), (33_000, 33_000)],
472 service: 0,
473 headsign: "Downtown",
474 },
475 ],
476 shape: None,
477 }],
478 services: vec![weekdays()],
479 exceptions: Vec::new(),
480 feeds: vec![("sfmuni", "America/Los_Angeles", "us-ca-SFMTA")],
481 }
482}