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

Modern-Apps.git / scripts / maps / tile_build / src / bin / transit_planet5.rs

transit_planet5.rs337 lines · 13.3 KiBRaw
1//! `transit_planet5` — rewrite a TRIX v7 transit pack as planet5 TRIX v8.
2//!
3//! ```text
4//! transit_planet5 IN.transit OUT.transit [--shape-tol-m 1.0]
5//! ```
6//!
7//! * drops the host-only sections (27.., RAIL_LINES), as `mamaps_pack` already did;
8//! * empties ROUTE_TRIPS (the varint trip stream): readers since TRX v6 take trips from
9//! ROUTE_TRIP_RECS/ROUTE_TRIP_OFF and fall back to the stream only for a route whose table
10//! disagrees with its `n_trips` — checked here for every route, and the stream is kept if any
11//! route would need it;
12//! * thins SHAPE_COORDS with Douglas-Peucker at `--shape-tol-m` metres between protected
13//! vertices (every stop's vertex of every route sharing the blob, and both ends), remapping
14//! ROUTE_STOP_SHAPE to the kept vertices and rebuilding ROUTE_SHAPE_IDX; a ride leg still
15//! slices `shape[vertex(board)..=vertex(alight)]` exactly at its stops;
16//! * stores the sections the planner only reads to describe a result (names, feed metadata,
17//! polylines, MOTIS ids) as 64 KiB zstd-19 ZSEC sections (`--zsec` overrides; see
18//! COLD_SECTIONS for the measured trade-off), flagged by bit 63 of their directory length,
19//! and stamps version 8.
20//!
21//! The device reader (maps `transit.rs`) reads v3..=v8; a v7-only reader refuses v8 cleanly.
22use std::fs::File;
23use std::process::ExitCode;
24
25const HEADER_LEN: usize = 80;
26const DEVICE_SECTIONS: usize = 27;
27const SEC_ROUTES: usize = 2;
28const SEC_ROUTE_TRIPS: usize = 4;
29const SEC_SHAPE_COORDS: usize = 20;
30const SEC_ROUTE_SHAPE_IDX: usize = 21;
31const SEC_ROUTE_STOP_SHAPE: usize = 22;
32const SEC_ROUTE_TRIP_RECS: usize = 25;
33const SEC_ROUTE_TRIP_OFF: usize = 26;
34const ROUTE_REC: usize = 32;
35/// Sections stored as ZSEC by default: the ones the planner reads only to describe a finished
36/// journey or a stop (names 0, feed metadata 16/17/23, polylines and their indexes 20-22, MOTIS
37/// ids 24). The RAPTOR tables stay raw. Plan time against raw v7 on the planet pack (block cache
38/// 16 MiB/thread):
39/// cold only 2.94 GB 1.01x (60 queries) <- default
40/// cold + exceptions 2.45 GB 1.30x (12 queries), 5.5x (60: long searches thrash the cache)
41/// + stop routes 2.3x | + transfers 2.6x | + profiles 5.2x (12 queries)
42/// everything 1.19 GB ~35x
43const COLD_SECTIONS: [usize; 8] = [0, 16, 17, 20, 21, 22, 23, 24];
44const NONE: u32 = u32::MAX;
45
46fn u32_at(b: &[u8], o: usize) -> u32 {
47 u32::from_le_bytes(b[o..o + 4].try_into().unwrap())
48}
49
50fn uvar(b: &[u8], pos: &mut usize) -> u64 {
51 let (mut r, mut s) = (0u64, 0);
52 loop {
53 let c = b[*pos];
54 *pos += 1;
55 r |= ((c & 0x7f) as u64) << s;
56 if c < 0x80 {
57 return r;
58 }
59 s += 7;
60 }
61}
62
63fn put_uvar(out: &mut Vec<u8>, mut v: u64) {
64 loop {
65 let b = (v & 0x7f) as u8;
66 v >>= 7;
67 if v == 0 {
68 out.push(b);
69 return;
70 }
71 out.push(b | 0x80);
72 }
73}
74
75fn seg_dist_sq(p: (f64, f64), a: (f64, f64), b: (f64, f64)) -> f64 {
76 let (dx, dy) = (b.0 - a.0, b.1 - a.1);
77 let l2 = dx * dx + dy * dy;
78 let t =
79 if l2 == 0.0 { 0.0 } else { (((p.0 - a.0) * dx + (p.1 - a.1) * dy) / l2).clamp(0.0, 1.0) };
80 (p.0 - a.0 - t * dx).powi(2) + (p.1 - a.1 - t * dy).powi(2)
81}
82
83fn main() -> ExitCode {
84 let args: Vec<String> = std::env::args().collect();
85 let mut tol = 1.0f64;
86 let mut zsec: Vec<usize> = COLD_SECTIONS.to_vec();
87 let mut block = tilecodec::zsec::ZSEC_BLOCK;
88 let mut pos = Vec::new();
89 let mut i = 1;
90 while i < args.len() {
91 if args[i] == "--shape-tol-m" {
92 tol = args[i + 1].parse().expect("--shape-tol-m M");
93 i += 2;
94 continue;
95 }
96 if args[i] == "--zsec-block" {
97 block = args[i + 1].parse().expect("--zsec-block BYTES");
98 i += 2;
99 continue;
100 }
101 if args[i] == "--zsec" {
102 zsec = match args[i + 1].as_str() {
103 "all" => (0..DEVICE_SECTIONS).collect(),
104 "cold" => COLD_SECTIONS.to_vec(),
105 "none" => Vec::new(),
106 list => list.split(',').map(|v| v.parse().expect("--zsec section list")).collect(),
107 };
108 i += 2;
109 continue;
110 }
111 pos.push(args[i].clone());
112 i += 1;
113 }
114 if pos.len() != 2 {
115 eprintln!("usage: transit_planet5 IN.transit OUT.transit [--shape-tol-m M] [--zsec cold|all|none|i,j,..]");
116 return ExitCode::from(2);
117 }
118 match run(&pos[0], &pos[1], tol, &zsec, block) {
119 Ok(()) => ExitCode::SUCCESS,
120 Err(e) => {
121 eprintln!("transit_planet5: {e}");
122 ExitCode::FAILURE
123 }
124 }
125}
126
127fn run(input: &str, output: &str, tol: f64, zsec: &[usize], block: usize) -> Result<(), String> {
128 let f = File::open(input).map_err(|e| format!("open {input}: {e}"))?;
129 let m = unsafe { memmap2::Mmap::map(&f) }.map_err(|e| e.to_string())?;
130 if m.len() < HEADER_LEN || u32_at(&m, 0) != tilecodec::mamaps::archive::TRANSIT_MAGIC {
131 return Err("not a TRIX pack".into());
132 }
133 let version = u32_at(&m, 4);
134 if version != 7 {
135 return Err(format!("expected a v7 pack, got v{version}"));
136 }
137 let count = u32_at(&m, 8) as usize;
138 let route_count = u32_at(&m, 16) as usize;
139 let sec = |i: usize| -> &[u8] {
140 if i >= count {
141 return &[];
142 }
143 let at = HEADER_LEN + i * 16;
144 let off = u64::from_le_bytes(m[at..at + 8].try_into().unwrap()) as usize;
145 let len = u64::from_le_bytes(m[at + 8..at + 16].try_into().unwrap()) as usize;
146 &m[off..off + len]
147 };
148 let mut sections: Vec<Vec<u8>> = (0..DEVICE_SECTIONS).map(|i| sec(i).to_vec()).collect();
149 let routes = sec(SEC_ROUTES);
150
151 // ROUTE_TRIPS: drop only when every route's strided table agrees with its record.
152 let trip_off = sec(SEC_ROUTE_TRIP_OFF);
153 let recs_len = sec(SEC_ROUTE_TRIP_RECS).len();
154 let table_ok = trip_off.len() >= (route_count + 1) * 4
155 && (0..route_count).all(|r| {
156 let n_trips = u32_at(routes, r * ROUTE_REC + 24);
157 let (b, e) = (u32_at(trip_off, r * 4), u32_at(trip_off, r * 4 + 4));
158 e >= b && e - b == n_trips && (e as usize) * 16 <= recs_len
159 });
160 let dropped_trips =
161 if table_ok { std::mem::take(&mut sections[SEC_ROUTE_TRIPS]).len() } else { 0 };
162
163 // SHAPE_COORDS thinning with stop vertices protected.
164 let shapes = sec(SEC_SHAPE_COORDS);
165 let shape_idx = sec(SEC_ROUTE_SHAPE_IDX);
166 let rss = sec(SEC_ROUTE_STOP_SHAPE);
167 let (mut pts_in, mut pts_out) = (0u64, 0u64);
168 if !shapes.is_empty() && shape_idx.len() >= (route_count + 1) * 4 && tol > 0.0 {
169 let mut prot: std::collections::BTreeMap<u32, Vec<u32>> = Default::default();
170 for r in 0..route_count {
171 let off = u32_at(shape_idx, r * 4);
172 if off == NONE {
173 continue;
174 }
175 let n_stops = u32_at(routes, r * ROUTE_REC + 16) as usize;
176 let first = u32_at(routes, r * ROUTE_REC + 20) as usize;
177 let e = prot.entry(off).or_default();
178 for k in 0..n_stops {
179 if (first + k + 1) * 4 <= rss.len() {
180 let v = u32_at(rss, (first + k) * 4);
181 if v != NONE {
182 e.push(v);
183 }
184 }
185 }
186 }
187 let mut new_shapes = Vec::with_capacity(shapes.len() / 2);
188 let mut new_off: std::collections::HashMap<u32, u32> = Default::default();
189 let mut remap: std::collections::HashMap<u32, Vec<u32>> = Default::default();
190 for (&off, protected) in &prot {
191 let mut p = off as usize;
192 let n = u32_at(shapes, p) as usize;
193 p += 4;
194 let (mut la, mut lo) = (0i64, 0i64);
195 let mut pts = Vec::with_capacity(n);
196 for _ in 0..n {
197 let a = uvar(shapes, &mut p);
198 let b = uvar(shapes, &mut p);
199 la += ((a >> 1) as i64) ^ -((a & 1) as i64);
200 lo += ((b >> 1) as i64) ^ -((b & 1) as i64);
201 pts.push((la, lo));
202 }
203 pts_in += n as u64;
204 let mut keep = vec![false; n];
205 if n > 0 {
206 keep[0] = true;
207 keep[n - 1] = true;
208 }
209 for &v in protected {
210 if (v as usize) < n {
211 keep[v as usize] = true;
212 }
213 }
214 let lat0 = if n > 0 { pts[0].0 as f64 * 1e-7 } else { 0.0 };
215 let kx = 0.011_131_949 * lat0.to_radians().cos();
216 let xy: Vec<(f64, f64)> =
217 pts.iter().map(|q| (q.1 as f64 * kx, q.0 as f64 * 0.011_131_949)).collect();
218 let anchors: Vec<usize> = (0..n).filter(|&i| keep[i]).collect();
219 for w in anchors.windows(2) {
220 let mut stack = vec![(w[0], w[1])];
221 while let Some((a, b)) = stack.pop() {
222 if b <= a + 1 {
223 continue;
224 }
225 let (mut worst, mut wi) = (tol * tol, usize::MAX);
226 for i in a + 1..b {
227 let d = seg_dist_sq(xy[i], xy[a], xy[b]);
228 if d > worst {
229 worst = d;
230 wi = i;
231 }
232 }
233 if wi != usize::MAX {
234 keep[wi] = true;
235 stack.push((a, wi));
236 stack.push((wi, b));
237 }
238 }
239 }
240 let mut map = vec![NONE; n];
241 let mut kept = 0u32;
242 for i in 0..n {
243 if keep[i] {
244 map[i] = kept;
245 kept += 1;
246 }
247 }
248 new_off.insert(off, new_shapes.len() as u32);
249 new_shapes.extend_from_slice(&kept.to_le_bytes());
250 let (mut pl, mut pn) = (0i64, 0i64);
251 for i in 0..n {
252 if keep[i] {
253 let (a, b) = pts[i];
254 put_uvar(&mut new_shapes, (((a - pl) << 1) ^ ((a - pl) >> 63)) as u64);
255 put_uvar(&mut new_shapes, (((b - pn) << 1) ^ ((b - pn) >> 63)) as u64);
256 (pl, pn) = (a, b);
257 }
258 }
259 pts_out += kept as u64;
260 remap.insert(off, map);
261 }
262 let mut new_idx = Vec::with_capacity(shape_idx.len());
263 let mut new_rss = rss.to_vec();
264 for r in 0..route_count {
265 let off = u32_at(shape_idx, r * 4);
266 if off == NONE {
267 new_idx.extend_from_slice(&NONE.to_le_bytes());
268 continue;
269 }
270 new_idx.extend_from_slice(&new_off[&off].to_le_bytes());
271 let map = &remap[&off];
272 let n_stops = u32_at(routes, r * ROUTE_REC + 16) as usize;
273 let first = u32_at(routes, r * ROUTE_REC + 20) as usize;
274 for k in 0..n_stops {
275 let at = (first + k) * 4;
276 if at + 4 > new_rss.len() {
277 continue;
278 }
279 let v = u32_at(rss, at);
280 if v != NONE {
281 let nv = map.get(v as usize).copied().unwrap_or(NONE);
282 if nv == NONE {
283 return Err(format!("route {r}: stop vertex {v} was not kept"));
284 }
285 new_rss[at..at + 4].copy_from_slice(&nv.to_le_bytes());
286 }
287 }
288 }
289 new_idx.extend_from_slice(&(new_shapes.len() as u32).to_le_bytes());
290 sections[SEC_SHAPE_COORDS] = new_shapes;
291 sections[SEC_ROUTE_SHAPE_IDX] = new_idx;
292 sections[SEC_ROUTE_STOP_SHAPE] = new_rss;
293 }
294
295 // ZSEC the chosen non-empty sections (flagged in the directory); v8 header and directory.
296 let raw_total: usize = sections.iter().map(|s| s.len()).sum();
297 let stored: Vec<(Vec<u8>, bool)> = sections
298 .iter()
299 .enumerate()
300 .map(|(i, s)| {
301 if s.is_empty() || !zsec.contains(&i) {
302 (s.clone(), false)
303 } else {
304 (tilecodec::zsec::write_zsec(s, block, 19), true)
305 }
306 })
307 .collect();
308 let mut out = m[..HEADER_LEN].to_vec();
309 out[4..8].copy_from_slice(&tilecodec::mamaps::archive::TRANSIT_VERSION_ZSEC.to_le_bytes());
310 out[8..12].copy_from_slice(&(DEVICE_SECTIONS as u32).to_le_bytes());
311 let dir_at = out.len();
312 out.resize(dir_at + DEVICE_SECTIONS * 16, 0);
313 for (i, (s, z)) in stored.iter().enumerate() {
314 while out.len() % 8 != 0 {
315 out.push(0);
316 }
317 let off = out.len() as u64;
318 out.extend_from_slice(s);
319 let at = dir_at + i * 16;
320 let flag = if *z { tilecodec::mamaps::archive::TRANSIT_ZSEC_FLAG } else { 0 };
321 out[at..at + 8].copy_from_slice(&off.to_le_bytes());
322 out[at + 8..at + 16].copy_from_slice(&(s.len() as u64 | flag).to_le_bytes());
323 }
324 std::fs::write(output, &out).map_err(|e| format!("write {output}: {e}"))?;
325 println!(
326 "transit_planet5: {} -> {} bytes (device sections raw {} B after thinning); ROUTE_TRIPS dropped {} B{}; shape points {} -> {} at {} m",
327 m.len(),
328 out.len(),
329 raw_total,
330 dropped_trips,
331 if table_ok { "" } else { " (kept: a route's trip table disagrees)" },
332 pts_in,
333 pts_out,
334 tol
335 );
336 Ok(())
337}