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

Modern-Apps.git / maps / src / main / rust / examples / graph_thin.rs

graph_thin.rs418 lines · 17.5 KiBRaw
1//! `graph_thin` — planet-size prototype: error-bounded shape-point thinning of a routing graph's
2//! `intermediate.bin`, keeping the on-disk layout (no reader change).
3//!
4//! ```text
5//! cargo run --release --example graph_thin -- IN_GRAPH_DIR OUT_GRAPH_DIR TOL_CM
6//! ```
7//!
8//! Every stored polyline (source node + interior points + target node) is Douglas-Peucker
9//! simplified with tolerance `TOL_CM` (perpendicular distance in centimetres on a local
10//! equirectangular projection), endpoints always kept — so straight runs collapse to their
11//! endpoints and bends keep exactly the vertices that carry them. Interior points are re-added
12//! wherever a gap would overflow the format's `i16` e7 delta (~365 m), so the result is always
13//! encodable. `edges.bin` distances and times are untouched (route length / ETA cannot move);
14//! only the decoded polyline does, by at most `TOL_CM` from the original.
15//!
16//! The presence bitmap and its rank index are copied verbatim (an edge whose interior empties
17//! keeps an empty blob), so `G` and every edge's geometry rank are unchanged; only the blob and
18//! the two-level offset table are rebuilt. Every other graph file is copied. Also reports the
19//! size the thinned polylines would take under two candidate *format changes*: zigzag-varint
20//! deltas, and the same at a 1e-6 degree (~11 cm) grid.
21//!
22//! Experiment tooling (examples/): never in the cdylib.
23
24use offlinerouter::graph::{Graph, LatLon, INTERMEDIATE_BLOCK, INTERMEDIATE_BLOCK_V8};
25
26fn read_u64(b: &[u8], at: usize) -> u64 {
27 u64::from_le_bytes(b[at..at + 8].try_into().unwrap())
28}
29
30fn seg_dist_sq(p: (f64, f64), a: (f64, f64), b: (f64, f64)) -> f64 {
31 let (dx, dy) = (b.0 - a.0, b.1 - a.1);
32 let l2 = dx * dx + dy * dy;
33 if l2 == 0.0 {
34 return (p.0 - a.0).powi(2) + (p.1 - a.1).powi(2);
35 }
36 let t = (((p.0 - a.0) * dx + (p.1 - a.1) * dy) / l2).clamp(0.0, 1.0);
37 let (qx, qy) = (a.0 + t * dx, a.1 + t * dy);
38 (p.0 - qx).powi(2) + (p.1 - qy).powi(2)
39}
40
41fn dp(pts: &[(f64, f64)], tol_sq: f64, keep: &mut [bool]) {
42 let mut stack = vec![(0usize, pts.len() - 1)];
43 while let Some((a, b)) = stack.pop() {
44 if b <= a + 1 {
45 continue;
46 }
47 let (mut worst, mut wi) = (0.0, a);
48 for i in a + 1..b {
49 let d = seg_dist_sq(pts[i], pts[a], pts[b]);
50 if d > worst {
51 worst = d;
52 wi = i;
53 }
54 }
55 if worst > tol_sq {
56 keep[wi] = true;
57 stack.push((a, wi));
58 stack.push((wi, b));
59 }
60 }
61}
62
63fn push_uvarint(out: &mut usize, mut v: u64) {
64 loop {
65 *out += 1;
66 v >>= 7;
67 if v == 0 {
68 break;
69 }
70 }
71}
72
73fn zz(v: i64) -> u64 {
74 ((v << 1) ^ (v >> 63)) as u64
75}
76
77/// A ZBLK section (plus any trailing tables) with column-transformed blocks; unchanged when its
78/// blocks already are.
79fn columns_blocked(raw: &[u8]) -> Vec<u8> {
80 let v = tilecodec::blocked::Blocked::parse(raw).expect("a ZBLK section");
81 if v.flags() & tilecodec::blocked::BLOCKED_FLAG_COLUMNS != 0 {
82 return raw.to_vec();
83 }
84 let end = v.block_offset(v.block_count()).expect("end") as usize;
85 let mut records = Vec::with_capacity(v.unpacked_len() as usize);
86 for b in 0..v.block_count() {
87 records.extend_from_slice(&v.block(b).expect("block"));
88 }
89 let mut out = tilecodec::blocked::write_blocked_columns(&records, v.record_len());
90 // Trailing tables (edges.bin's escapes and names) start at the next 8-byte boundary after
91 // the records, in the old file and in the new one alike.
92 let tail = end.div_ceil(8) * 8;
93 if tail < raw.len() {
94 out.resize(out.len().div_ceil(8) * 8, 0);
95 out.extend_from_slice(&raw[tail..]);
96 }
97 out
98}
99
100fn main() -> std::process::ExitCode {
101 let all: Vec<String> = std::env::args().skip(1).collect();
102 // `--v8`: write the planet5 layout (graph v8: zigzag-varint deltas on a 1e-6 degree grid,
103 // INTERMEDIATE_BLOCK_V8 per coarse entry, no i16 bridging needed). Without it the v7 layout.
104 // `--v9`: v8's encoding, then graph v9's block compression: the intermediate blob and
105 // road_names.bin become ZSEC sections (64 KiB zstd-19 blocks) and nodes.bin/edges.bin ZBLK
106 // blocks are column-transformed when the input still has row blocks.
107 let v9 = all.iter().any(|x| x == "--v9");
108 let v8 = v9 || all.iter().any(|x| x == "--v8");
109 let a: Vec<String> = all.into_iter().filter(|x| x != "--v8" && x != "--v9").collect();
110 if a.len() < 3 {
111 eprintln!("usage: graph_thin IN_GRAPH_DIR OUT_GRAPH_DIR TOL_CM");
112 return std::process::ExitCode::from(2);
113 }
114 let (inp, outp) = (a[0].trim_end_matches('/'), a[1].trim_end_matches('/'));
115 let tol_cm: f64 = a[2].parse().expect("TOL_CM");
116 // Optional: keep every shape point within KEEP_END_M (along the line) of either node, so
117 // the approach/exit bearings guidance derives maneuvers from are untouched ("full detail
118 // at junctions").
119 let keep_end_m: f64 = a.get(3).map(|v| v.parse().expect("KEEP_END_M")).unwrap_or(0.0);
120 let g = Graph::load(&format!("{inp}/")).expect("load graph");
121 let inter = std::fs::read(format!("{inp}/intermediate.bin")).expect("read intermediate");
122 let e = g.edge_count;
123 let gcount = read_u64(&inter, inter.len() - 8);
124 let bitmap_bytes = (e.div_ceil(512) + 1) * 8 + e.div_ceil(8);
125 let meta = std::fs::read(format!("{inp}/metadata.bin")).expect("read metadata");
126 let in_version = u32::from_le_bytes(meta[4..8].try_into().unwrap());
127 let in_block = if in_version >= 8 { INTERMEDIATE_BLOCK_V8 } else { INTERMEDIATE_BLOCK };
128 let out_block = if v8 { INTERMEDIATE_BLOCK_V8 } else { INTERMEDIATE_BLOCK };
129 let coarse_bytes = (gcount.div_ceil(in_block) + 1) * 8;
130 let out_coarse_bytes = (gcount.div_ceil(out_block) + 1) * 8;
131 let within_bytes = (gcount + 1) * 2;
132 let trailer = bitmap_bytes + coarse_bytes + within_bytes + 8;
133 let blob_len = inter.len() as u64 - trailer;
134 let bitmap = &inter[blob_len as usize..(blob_len + bitmap_bytes) as usize];
135 let present_off = ((e.div_ceil(512) + 1) * 8) as usize;
136 let present = &bitmap[present_off..];
137
138 let tol_m = tol_cm / 100.0;
139 let mut blob: Vec<u8> = Vec::with_capacity(blob_len as usize);
140 let mut coarse: Vec<u64> = Vec::with_capacity(out_coarse_bytes as usize / 8);
141 let mut within: Vec<u16> = Vec::with_capacity(gcount as usize + 1);
142 let mut buf = vec![LatLon { lat_e7: 0, lon_e7: 0 }; 256];
143 let (mut pts_in, mut pts_out, mut readded) = (0u64, 0u64, 0u64);
144 let (mut var_e7, mut var_e6) = (0usize, 0usize);
145 let mut max_dev_m = 0.0f64;
146 let mut rank = 0u64;
147 let mut block_start = 0u64;
148 for idx in 0..e {
149 if present[(idx / 8) as usize] & (1 << (idx % 8)) == 0 {
150 continue;
151 }
152 if rank % out_block == 0 {
153 block_start = blob.len() as u64;
154 coarse.push(block_start);
155 }
156 within.push(
157 u16::try_from(blob.len() as u64 - block_start)
158 .expect("a coarse block spans more than 64 KiB"),
159 );
160 rank += 1;
161 let src = g.find_node_idx_for_edge(idx);
162 let Some((cnt, rev)) = g.get_edge_coordinates_from(src, idx, &mut buf) else {
163 panic!("edge {idx} present in the bitmap but not decodable");
164 };
165 assert!(!rev, "a stored polyline decoded reversed");
166 let cnt = cnt as usize;
167 if cnt < 3 {
168 continue;
169 }
170 let poly = &buf[..cnt];
171 pts_in += (cnt - 2) as u64;
172 // Local metres: equirectangular about the source.
173 let lat0 = poly[0].lat_e7 as f64 * 1e-7;
174 let kx = 0.011_131_949 * lat0.to_radians().cos(); // m per e7 unit of lon (×1e-7 deg × 111319.49 m)
175 let ky = 0.011_131_949;
176 let xy: Vec<(f64, f64)> = poly
177 .iter()
178 .map(|p| {
179 ((p.lon_e7 - poly[0].lon_e7) as f64 * kx, (p.lat_e7 - poly[0].lat_e7) as f64 * ky)
180 })
181 .collect();
182 let mut keep = vec![false; cnt];
183 keep[0] = true;
184 keep[cnt - 1] = true;
185 if tol_m > 0.0 {
186 dp(&xy, tol_m * tol_m, &mut keep);
187 if keep_end_m > 0.0 {
188 let mut acc = vec![0.0f64; cnt];
189 for k in 1..cnt {
190 acc[k] = acc[k - 1]
191 + ((xy[k].0 - xy[k - 1].0).powi(2) + (xy[k].1 - xy[k - 1].1).powi(2))
192 .sqrt();
193 }
194 let total = acc[cnt - 1];
195 for k in 1..cnt - 1 {
196 if acc[k] <= keep_end_m || total - acc[k] <= keep_end_m {
197 keep[k] = true;
198 }
199 }
200 }
201 } else {
202 keep.iter_mut().for_each(|k| *k = true);
203 }
204 // i16 delta bridging: walk kept points, re-adding the farthest in-range original point
205 // whenever the next kept point is out of delta range of the previous one.
206 let fits = |a: &LatLon, b: &LatLon| {
207 (b.lat_e7 - a.lat_e7).abs() <= i16::MAX as i32
208 && (b.lon_e7 - a.lon_e7).abs() <= i16::MAX as i32
209 };
210 let mut out_idx: Vec<usize> = vec![0];
211 let mut i = if v8 { cnt - 1 } else { 1 };
212 if v8 {
213 // No delta range to bridge: varints take any step.
214 out_idx.extend((1..cnt - 1).filter(|&k| keep[k]));
215 }
216 while i < cnt - 1 {
217 if !keep[i] {
218 i += 1;
219 continue;
220 }
221 let prev = *out_idx.last().unwrap();
222 if fits(&poly[prev], &poly[i]) {
223 out_idx.push(i);
224 i += 1;
225 } else {
226 // Farthest original point after prev that still fits (always prev+1 at worst,
227 // since the original encoded every consecutive pair).
228 let mut j = prev + 1;
229 while j + 1 < i && fits(&poly[prev], &poly[j + 1]) {
230 j += 1;
231 }
232 out_idx.push(j);
233 readded += 1;
234 }
235 }
236 // Bridging re-adds split DP's chords, which can leave a dropped vertex farther than the
237 // tolerance from the new, shorter chord: restore the bound by re-inserting the worst
238 // vertex of any span that breaks it, until none does (only ever adds points, so the
239 // i16 fit established above still holds).
240 let mut kept: Vec<usize> =
241 out_idx.iter().copied().chain(std::iter::once(cnt - 1)).collect();
242 if tol_m > 0.0 {
243 loop {
244 let mut changed = false;
245 let mut next = Vec::with_capacity(kept.len() + 4);
246 for w in kept.windows(2) {
247 next.push(w[0]);
248 let (mut worst, mut wi) = (tol_m * tol_m, usize::MAX);
249 for k in w[0] + 1..w[1] {
250 let d = seg_dist_sq(xy[k], xy[w[0]], xy[w[1]]);
251 if d > worst {
252 worst = d;
253 wi = k;
254 }
255 }
256 if wi != usize::MAX {
257 next.push(wi);
258 changed = true;
259 }
260 }
261 next.push(cnt - 1);
262 kept = next;
263 if !changed {
264 break;
265 }
266 }
267 out_idx = kept[..kept.len() - 1].to_vec();
268 }
269 // Deviation of the thinned polyline from every dropped original vertex: the exact
270 // max over the original vertices (straight original segments between them cannot
271 // stray farther than their endpoints from a chord).
272
273 for w in kept.windows(2) {
274 for k in w[0] + 1..w[1] {
275 max_dev_m = max_dev_m.max(seg_dist_sq(xy[k], xy[w[0]], xy[w[1]]).sqrt());
276 }
277 }
278 if v8 {
279 let q = |v: i32| (v as i64).div_euclid(10) + i64::from((v as i64).rem_euclid(10) >= 5);
280 let (mut pl, mut pn) = (q(poly[0].lat_e7), q(poly[0].lon_e7));
281 for &k in &out_idx[1..] {
282 let (ql, qn) = (q(poly[k].lat_e7), q(poly[k].lon_e7));
283 let mut put = |v: i64| {
284 let mut u = ((v << 1) ^ (v >> 63)) as u64;
285 loop {
286 let b = (u & 0x7f) as u8;
287 u >>= 7;
288 if u == 0 {
289 blob.push(b);
290 break;
291 }
292 blob.push(b | 0x80);
293 }
294 };
295 put(ql - pl);
296 put(qn - pn);
297 (pl, pn) = (ql, qn);
298 pts_out += 1;
299 }
300 continue;
301 }
302 // Encode interior points (out_idx[1..]) as i16 deltas, first from the source.
303 let mut prev = poly[0];
304 let mut prev6 = (poly[0].lat_e7 / 10, poly[0].lon_e7 / 10);
305 for &k in &out_idx[1..] {
306 let p = poly[k];
307 let dl = (p.lat_e7 - prev.lat_e7) as i16;
308 let dn = (p.lon_e7 - prev.lon_e7) as i16;
309 blob.extend_from_slice(&dl.to_le_bytes());
310 blob.extend_from_slice(&dn.to_le_bytes());
311 push_uvarint(&mut var_e7, zz((p.lat_e7 - prev.lat_e7) as i64));
312 push_uvarint(&mut var_e7, zz((p.lon_e7 - prev.lon_e7) as i64));
313 let q =
314 ((p.lat_e7 as f64 / 10.0).round() as i32, (p.lon_e7 as f64 / 10.0).round() as i32);
315 push_uvarint(&mut var_e6, zz((q.0 - prev6.0) as i64));
316 push_uvarint(&mut var_e6, zz((q.1 - prev6.1) as i64));
317 prev = p;
318 prev6 = q;
319 pts_out += 1;
320 }
321 }
322 assert_eq!(rank, gcount, "geometry rank count");
323 // Sentinel: the blob length, in the final block's slot.
324 if rank % out_block == 0 {
325 coarse.push(blob.len() as u64);
326 block_start = blob.len() as u64;
327 }
328 within.push(
329 u16::try_from(blob.len() as u64 - block_start)
330 .expect("a coarse block spans more than 64 KiB"),
331 );
332 // The table always carries div_ceil(G, 32) + 1 entries; the generator's trailing slot is
333 // the blob length.
334 while (coarse.len() as u64) * 8 < out_coarse_bytes {
335 coarse.push(blob.len() as u64);
336 }
337 assert_eq!(coarse.len() as u64 * 8, out_coarse_bytes, "coarse table size");
338 assert_eq!(within.len() as u64 * 2, within_bytes, "within table size");
339
340 std::fs::create_dir_all(outp).expect("mkdir");
341 for f in std::fs::read_dir(inp).expect("readdir") {
342 let f = f.unwrap();
343 let name = f.file_name().into_string().unwrap();
344 if name == "intermediate.bin" || !f.file_type().unwrap().is_file() {
345 continue;
346 }
347 if v9 && name == "road_names.bin" {
348 let raw = std::fs::read(f.path()).expect("read road_names");
349 let z = if raw.is_empty() {
350 raw
351 } else {
352 tilecodec::zsec::write_zsec(&raw, tilecodec::zsec::ZSEC_BLOCK, 19)
353 };
354 std::fs::write(format!("{outp}/{name}"), &z).expect("write road_names");
355 continue;
356 }
357 if v9 && (name == "nodes.bin" || name == "edges.bin") {
358 let raw = std::fs::read(f.path()).expect("read blocked");
359 let mut out = columns_blocked(&raw);
360 if name == "edges.bin" {
361 // The name-offset table (u32 per named edge, the file's tail) becomes a ZSEC
362 // section: 1.1 GB raw on the planet, read only to word instructions.
363 let named = read_u64(&meta, 32) as usize;
364 if named > 0 {
365 let at = out.len() - named * 4;
366 let table = out.split_off(at);
367 out.extend_from_slice(&tilecodec::zsec::write_zsec(
368 &table,
369 tilecodec::zsec::ZSEC_BLOCK,
370 19,
371 ));
372 }
373 }
374 std::fs::write(format!("{outp}/{name}"), out).expect("write blocked");
375 continue;
376 }
377 std::fs::copy(f.path(), format!("{outp}/{name}")).expect("copy");
378 }
379 let new_blob = blob.len();
380 let mut out =
381 if v9 { tilecodec::zsec::write_zsec(&blob, tilecodec::zsec::ZSEC_BLOCK, 19) } else { blob };
382 out.extend_from_slice(bitmap);
383 for c in &coarse {
384 out.extend_from_slice(&c.to_le_bytes());
385 }
386 for w in &within {
387 out.extend_from_slice(&w.to_le_bytes());
388 }
389 out.extend_from_slice(&gcount.to_le_bytes());
390 std::fs::write(format!("{outp}/intermediate.bin"), &out).expect("write");
391 let mut meta_out = meta.clone();
392 let out_version: u32 = if v9 {
393 9
394 } else if v8 {
395 8
396 } else {
397 in_version.min(7)
398 };
399 meta_out[4..8].copy_from_slice(&out_version.to_le_bytes());
400 std::fs::write(format!("{outp}/metadata.bin"), &meta_out).expect("write metadata");
401 // Validate by loading the result with the real reader.
402 let g2 = Graph::load(&format!("{outp}/")).expect("thinned graph must load");
403 assert_eq!(g2.edge_count, e);
404 println!(
405 "graph_thin v8={v8} tol_cm={tol_cm} keep_end_m={keep_end_m} interior_points {pts_in} -> {pts_out} ({:.1}%), readded_for_i16 {readded}, \
406 max_dev_m {max_dev_m:.3}\n intermediate.bin {} -> {} bytes (blob {} -> {}; trailer {})\n \
407 format-change estimates for the thinned blob: zigzag-varint e7 {} B, varint at 1e-6 deg {} B",
408 100.0 * pts_out as f64 / pts_in.max(1) as f64,
409 inter.len(),
410 out.len(),
411 blob_len,
412 new_blob,
413 trailer,
414 var_e7,
415 var_e6
416 );
417 std::process::ExitCode::SUCCESS
418}