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

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

route_diff.rs1363 lines · 52.7 KiBRaw
1//! Route-level differential oracle for road-graph changes.
2//!
3//! Compaction renumbers nodes and edges and changes their counts, so no output
4//! file of two graphs built from the same region is comparable byte-wise. What
5//! *is* comparable is what the router does with them: for a fixed list of
6//! origin/destination coordinates, the total distance, the total time, the turn
7//! sequence and the decoded polyline.
8//!
9//! This lives in the engine crate, and drives `Graph::load` +
10//! `prepare_routing` + `perform_search_loop` + `reconstruct_path` directly,
11//! because the point is to exercise the real reader — including
12//! `decode_edge_coords` and the `REVERSE_GEOMETRY_FLAG` twin lookup — rather
13//! than a host reimplementation of it.
14//!
15//! It is an `examples/` target, not `src/bin/`, so `cargo build` for the
16//! Android lib never picks it up.
17//!
18//! ```text
19//! cargo run --release --example route_diff -- gen-pairs --graph DIR --out pairs.txt [--count N]
20//! cargo run --release --example route_diff -- report --graph DIR --pairs pairs.txt --out report.txt
21//! cargo run --release --example route_diff -- compare --baseline a.txt --candidate b.txt [--tol-mm N]
22//! cargo run --release --example route_diff -- bench --graph DIR --pairs pairs.txt [--passes N] [--cold]
23//! cargo run --release --example route_diff -- dump --graph DIR --out dump.bin
24//! cargo run --release --example route_diff -- dump-compare --baseline a.bin --candidate b.bin
25//! ```
26//!
27//! `Graph::load` mmaps, and `MmapRegion::map` is `#[cfg(unix)]`, so this must
28//! run on Linux (WSL is fine).
29
30use std::collections::{HashMap, HashSet};
31use std::fmt::Write as _;
32use std::io::Write as _;
33
34use offlinerouter::geometry::{accurate_dist_mm, TrafficSpeeds};
35use offlinerouter::graph::{archive_path, get_pt_at, Graph, LatLon, BICYCLE, DRIVING, NO_NAME, WALK};
36use offlinerouter::routing::{perform_search_loop, prepare_routing, reconstruct_path};
37use offlinerouter::state::{RadixHeap, RoutingScratchpad};
38
39/// One origin/destination probe. Coordinates, not node ids: ids move when the
40/// graph is rebuilt, coordinates do not, which is the whole point.
41struct Pair {
42 kind: String,
43 mode: i32,
44 s_lat: f64,
45 s_lon: f64,
46 e_lat: f64,
47 e_lon: f64,
48}
49
50fn main() -> std::process::ExitCode {
51 let args: Vec<String> = std::env::args().skip(1).collect();
52 let r = match args.first().map(String::as_str) {
53 Some("gen-pairs") => gen_pairs(&args[1..]),
54 Some("report") => report(&args[1..]),
55 Some("compare") => compare(&args[1..]),
56 Some("geometry") => geometry(&args[1..]),
57 Some("bench") => bench(&args[1..]),
58 Some("dump") => dump(&args[1..]),
59 Some("dump-compare") => dump_compare(&args[1..]),
60 Some("sections") => sections(&args[1..]),
61 Some("transit") => transit(&args[1..]),
62 _ => Err(USAGE.to_string()),
63 };
64 match r {
65 Ok(true) => std::process::ExitCode::SUCCESS,
66 Ok(false) => std::process::ExitCode::FAILURE,
67 Err(e) => {
68 eprintln!("error: {e}");
69 std::process::ExitCode::FAILURE
70 }
71 }
72}
73
74const USAGE: &str = "\
75usage:
76 route_diff gen-pairs --graph DIR --out FILE [--count N]
77 route_diff report --graph DIR --pairs FILE --out FILE [--overlay FILE | --no-overlay]
78 route_diff compare --baseline FILE --candidate FILE [--tol-mm N] [--tol-10ms N]
79 route_diff geometry --baseline DIR --candidate DIR
80 route_diff bench --graph DIR --pairs FILE [--passes N] [--cold] [--verbose] [--overlay FILE | --no-overlay]
81 route_diff dump
82 route_diff dump --graph DIR --out FILE
83 route_diff dump-compare --baseline FILE --candidate FILE [--limit N]
84 route_diff sections --archive FILE [--dump KIND]
85 route_diff transit --graph DIR --from LAT,LON --to LAT,LON --dep SECS --date YYYYMMDD --weekday N";
86
87fn flag(args: &[String], name: &str) -> Option<String> {
88 args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned()
89}
90
91fn need(args: &[String], name: &str) -> Result<String, String> {
92 flag(args, name).ok_or_else(|| format!("missing {name}\n{USAGE}"))
93}
94
95/// Plan one transit journey from an archive's transit section and print its
96/// legs, the time the first plan took (which includes classifying the
97/// intercity routes), and a second, warm plan.
98fn transit(args: &[String]) -> Result<bool, String> {
99 use offlinerouter::transit::{plan, LegKind, QueryDay, Schedule, TransitIndex};
100 let dir = need(args, "--graph")?;
101 let point = |name: &str| -> Result<(f64, f64), String> {
102 let v = need(args, name)?;
103 let (a, b) = v.split_once(',').ok_or_else(|| format!("{name} wants LAT,LON"))?;
104 Ok((a.trim().parse().map_err(|e| format!("{name}: {e}"))?, b.trim().parse().map_err(|e| format!("{name}: {e}"))?))
105 };
106 let num = |name: &str| -> Result<u32, String> { need(args, name)?.parse().map_err(|e| format!("{name}: {e}")) };
107 let (from, to) = (point("--from")?, point("--to")?);
108 let (dep, date, weekday) = (num("--dep")?, num("--date")?, num("--weekday")?);
109 let started = std::time::Instant::now();
110 let idx = TransitIndex::load_archive(&archive_path(&dir)).ok_or("no transit section in the archive")?;
111 println!(" load {:>10.1} ms", started.elapsed().as_secs_f64() * 1e3);
112 let sched = Schedule { day: QueryDay::for_date(weekday, date), overlay: None };
113 let hhmm = |s: u32| {
114 let (d, r) = (s / 86_400, s % 86_400);
115 format!("{:02}:{:02}{}", r / 3600, r % 3600 / 60, if d > 0 { format!(" +{d}d") } else { String::new() })
116 };
117 let mut first = None;
118 for pass in ["cold", "warm"] {
119 let t = std::time::Instant::now();
120 let legs = plan(&idx, from.0, from.1, to.0, to.1, dep, sched);
121 println!(" plan ({pass}) {:>10.1} ms", t.elapsed().as_secs_f64() * 1e3);
122 if first.is_none() {
123 first = Some(legs);
124 }
125 }
126 let Some(legs) = first.flatten() else {
127 println!(" no journey");
128 return Ok(false);
129 };
130 for l in &legs {
131 let kind = match l.kind {
132 LegKind::Walk => "walk",
133 LegKind::Wait => "wait",
134 LegKind::Ride => "ride",
135 };
136 println!(
137 " {kind:<4} {:>9} -> {:<9} {:<28} {} -> {} ({} stops, {:.0} km)",
138 hhmm(l.dep_secs),
139 hhmm(l.arr_secs),
140 l.name,
141 l.from_stop,
142 l.to_stop,
143 l.stop_count,
144 l.dist_m / 1000.0
145 );
146 }
147 let total = legs.last().map_or(0, |l| l.arr_secs).saturating_sub(dep);
148 println!(" total {:.1} h, {} rides", f64::from(total) / 3600.0, legs.iter().filter(|l| l.kind == LegKind::Ride).count());
149 Ok(true)
150}
151
152/// Print `kind offset len` for every sidecar section of a `.mamaps`, reading
153/// only the footer and directory, so sections can be cut out with `dd`.
154fn sections(args: &[String]) -> Result<bool, String> {
155 use std::io::{Read as _, Seek as _, SeekFrom};
156 use tilecodec::mamaps::archive::{ArchiveEntry, ArchiveFooter};
157 let path = need(args, "--archive")?;
158 let mut f = std::fs::File::open(&path).map_err(|e| format!("{path}: {e}"))?;
159 let mut read_at = |at: SeekFrom, len: usize| -> Result<Vec<u8>, String> {
160 let mut buf = vec![0u8; len];
161 f.seek(at).and_then(|_| f.read_exact(&mut buf)).map_err(|e| format!("{path}: {e}"))?;
162 Ok(buf)
163 };
164 let footer = ArchiveFooter::parse(&read_at(SeekFrom::End(-32), 32)?).map_err(|e| e.0)?;
165 let dir = read_at(SeekFrom::Start(footer.dir_offset), footer.dir_len as usize)?;
166 let count = u32::from_le_bytes(dir[0..4].try_into().expect("4 bytes")) as usize;
167 let dump: Option<u8> = flag(args, "--dump").map(|k| k.parse().map_err(|e| format!("--dump: {e}"))).transpose()?;
168 for i in 0..count {
169 let e = ArchiveEntry::parse(&dir[4 + i * 32..]).map_err(|e| e.0)?;
170 match dump {
171 None => println!("{} {} {}", e.kind, e.offset, e.len),
172 Some(k) if k == e.kind => {
173 f.seek(SeekFrom::Start(e.offset)).map_err(|e| e.to_string())?;
174 let mut out = std::io::stdout().lock();
175 std::io::copy(&mut (&mut f).take(e.len), &mut out).map_err(|e| e.to_string())?;
176 return Ok(true);
177 }
178 Some(_) => {}
179 }
180 }
181 Ok(dump.is_none())
182}
183
184fn load(dir: &str) -> Result<Graph, String> {
185 Graph::load(dir).or_else(|| Graph::load_archive(&archive_path(dir))).ok_or_else(|| {
186 format!("cannot load a graph from {dir} (missing/short files, or a bad metadata.bin header)")
187 })
188}
189
190/// [`load`], then attach `--overlay FILE` when given, or drop the archive's own
191/// overlay with `--no-overlay`.
192fn load_with_overlay(dir: &str, args: &[String]) -> Result<Graph, String> {
193 let mut g = load(dir)?;
194 if args.iter().any(|a| a == "--no-overlay") {
195 g.detach_overlay();
196 }
197 if let Some(path) = flag(args, "--overlay") {
198 if !g.attach_overlay_file(&path) {
199 return Err(format!("{path}: not an overlay for this graph"));
200 }
201 }
202 Ok(g)
203}
204
205// ---------------------------------------------------------------------------
206// gen-pairs
207// ---------------------------------------------------------------------------
208
209/// Sample probe pairs from a graph's node array and write them as coordinates.
210///
211/// Three length classes, because they stress different things. `long` pairs
212/// exercise the search itself; `mid` pairs exercise turn-by-turn output; and
213/// `near` pairs put both endpoints within a few nodes of each other, which
214/// after compaction is very often the *same* collapsed edge — the case where a
215/// straight-chord graph and a collapsed graph can disagree most.
216fn gen_pairs(args: &[String]) -> Result<bool, String> {
217 let dir = need(args, "--graph")?;
218 let out = need(args, "--out")?;
219 let count: u32 = flag(args, "--count")
220 .as_deref()
221 .unwrap_or("300")
222 .parse()
223 .map_err(|e| format!("--count: {e}"))?;
224
225 let g = load(&dir)?;
226 if g.node_count < 16 {
227 return Err(format!("graph has only {} node(s)", g.node_count));
228 }
229 let n = u64::from(g.node_count);
230
231 // Deterministic sampling: a fixed odd multiplier walked over the node
232 // array. No RNG, so the pair file is reproducible from any graph of the
233 // same region without carrying a seed.
234 let mut buf = String::new();
235 buf.push_str("# route_diff pairs: kind mode s_lat s_lon e_lat e_lon\n");
236 buf.push_str(&format!("# generated from {dir} ({} nodes)\n", g.node_count));
237 let mut emitted = 0u32;
238 let mut k = 0u64;
239 while emitted < count {
240 let i = (k.wrapping_mul(2_654_435_761) % n) as u32;
241 let (kind, mode, j) = match emitted % 5 {
242 0 => ("long", DRIVING, (k.wrapping_mul(40_503) % n) as u32),
243 1 => ("mid", DRIVING, ((u64::from(i) + 4_000) % n) as u32),
244 2 => ("near", DRIVING, ((u64::from(i) + 3) % n) as u32),
245 3 => ("near", WALK, ((u64::from(i) + 2) % n) as u32),
246 _ => ("mid", BICYCLE, ((u64::from(i) + 500) % n) as u32),
247 };
248 k += 1;
249 if i == j {
250 continue;
251 }
252 let a = g.node(i);
253 let b = g.node(j);
254 // A node at (0, 0) means the graph has a hole where a coordinate should
255 // be; probing it tests nothing.
256 if (a.lat_e7 == 0 && a.lon_e7 == 0) || (b.lat_e7 == 0 && b.lon_e7 == 0) {
257 continue;
258 }
259 // Nudge off the node itself so the probe exercises mid-edge snapping
260 // rather than landing exactly on a vertex.
261 buf.push_str(&format!(
262 "{} {} {:.7} {:.7} {:.7} {:.7}\n",
263 kind,
264 mode,
265 f64::from(a.lat_e7) * 1e-7 + 1e-6,
266 f64::from(a.lon_e7) * 1e-7 - 1e-6,
267 f64::from(b.lat_e7) * 1e-7 - 1e-6,
268 f64::from(b.lon_e7) * 1e-7 + 1e-6,
269 ));
270 emitted += 1;
271 }
272 write_file(&out, buf.as_bytes())?;
273 println!("wrote {emitted} pair(s) to {out}");
274 Ok(true)
275}
276
277fn read_pairs(path: &str) -> Result<Vec<Pair>, String> {
278 let text = std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?;
279 let mut out = Vec::new();
280 for (ln, line) in text.lines().enumerate() {
281 if line.starts_with('#') || line.trim().is_empty() {
282 continue;
283 }
284 let f: Vec<&str> = line.split_whitespace().collect();
285 if f.len() != 6 {
286 return Err(format!("{path}:{}: want 6 fields, got {}", ln + 1, f.len()));
287 }
288 let num = |s: &str| s.parse::<f64>().map_err(|e| format!("{path}:{}: {e}", ln + 1));
289 out.push(Pair {
290 kind: f[0].to_string(),
291 mode: f[1].parse::<i32>().map_err(|e| format!("{path}:{}: {e}", ln + 1))?,
292 s_lat: num(f[2])?,
293 s_lon: num(f[3])?,
294 e_lat: num(f[4])?,
295 e_lon: num(f[5])?,
296 });
297 }
298 Ok(out)
299}
300
301// ---------------------------------------------------------------------------
302// report
303// ---------------------------------------------------------------------------
304
305/// Route every pair and write a line-oriented report.
306///
307/// The format is deliberately flat text: one `PAIR` line per probe carrying the
308/// totals, then one `STEP` line per turn, then one `GEOM` line holding the
309/// whole polyline. `compare` reads it back field by field, so totals can carry
310/// a tolerance while the turn sequence and geometry are matched exactly.
311fn report(args: &[String]) -> Result<bool, String> {
312 let dir = need(args, "--graph")?;
313 let pairs_path = need(args, "--pairs")?;
314 let out = need(args, "--out")?;
315
316 let g = load_with_overlay(&dir, args)?;
317 let pairs = read_pairs(&pairs_path)?;
318 let speeds = TrafficSpeeds::default();
319 let mut scratch = RoutingScratchpad::new();
320 let mut heap = RadixHeap::new();
321
322 let mut buf = String::new();
323 let _ = writeln!(buf, "# route_diff report");
324 let _ = writeln!(buf, "GRAPH nodes={} edges={}", g.node_count, g.edge_count);
325 let _ = writeln!(buf, "PAIRS {}", pairs.len());
326
327 let mut routed = 0usize;
328 for (i, p) in pairs.iter().enumerate() {
329 // No traffic on a host report: live speeds are a device-side input and
330 // would make the differential depend on when it ran.
331 let mut ensure = |_lat_e7: i32, _lon_e7: i32| {};
332 let ctx = prepare_routing(
333 &g, &speeds, &mut ensure, p.s_lat, p.s_lon, p.e_lat, p.e_lon, p.mode, &mut scratch,
334 &mut heap,
335 );
336 let mut ctx = match ctx {
337 Some(c) => c,
338 None => {
339 let _ = writeln!(buf, "PAIR {i} {} mode={} no_snap", p.kind, p.mode);
340 continue;
341 }
342 };
343 perform_search_loop(&g, &speeds, &mut ensure, p.mode, &mut ctx, &mut scratch, &mut heap);
344 // Where the query points landed on the network, and on which edges.
345 // Emitted before the routability check because a pair that stops routing
346 // is usually a pair that snapped somewhere else, and that is only
347 // visible if the snap is reported either way.
348 //
349 // Reported separately from the route because a rebuild that moves the
350 // node set changes how far `find_nearest_edge`'s fixed 800-node window
351 // reaches: a route that starts somewhere else is not the same question as
352 // a route that takes a different path from the same place.
353 let _ = writeln!(
354 buf,
355 "SNAP {i} s={:.7},{:.7} e={:.7},{:.7} s_off={:.1} e_off={:.1} s_road={} e_road={} direct={}",
356 f64::from(ctx.start.proj_lat) * 1e-7,
357 f64::from(ctx.start.proj_lon) * 1e-7,
358 f64::from(ctx.end.proj_lat) * 1e-7,
359 f64::from(ctx.end.proj_lon) * 1e-7,
360 // How far the query point had to move to reach the network. This is
361 // the measure of snap *quality*: the pairs were sampled from node
362 // coordinates, so a good snap lands within centimetres.
363 crow_m(p.s_lat, p.s_lon, f64::from(ctx.start.proj_lat) * 1e-7, f64::from(ctx.start.proj_lon) * 1e-7),
364 crow_m(p.e_lat, p.e_lon, f64::from(ctx.end.proj_lat) * 1e-7, f64::from(ctx.end.proj_lon) * 1e-7),
365 g.road_name(ctx.start.name_offset).unwrap_or_default(),
366 g.road_name(ctx.end.name_offset).unwrap_or_default(),
367 u8::from(ctx.direct.is_some())
368 );
369 let _ = writeln!(
370 buf,
371 "EDGE {i} s_edge={} s_ab={},{} e_edge={} e_ab={},{} twin={}",
372 ctx.start.edge_idx,
373 ctx.start.node_a,
374 ctx.start.node_b,
375 ctx.end.edge_idx,
376 ctx.end.node_a,
377 ctx.end.node_b,
378 // Whether the road can be travelled the other way at all. When both
379 // ends snap to one edge but in the wrong order, this is what decides
380 // between "stay on the road" and "go around the block".
381 twin_of(&g, ctx.start.node_a, ctx.start.node_b)
382 .map_or(-1i64, |k| i64::try_from(k).unwrap_or(-2))
383 );
384 // A route that never leaves its snapped edge reaches no node, so
385 // `target_node` stays unset and `ctx.direct` carries the route instead.
386 if ctx.target_node == 0xFFFF_FFFF && ctx.direct.is_none() {
387 let _ = writeln!(buf, "PAIR {i} {} mode={} no_route", p.kind, p.mode);
388 continue;
389 }
390 let steps = reconstruct_path(&g, &speeds, p.mode, &ctx, &mut scratch);
391 let dist: u64 = steps.iter().map(|s| s.dist_mm).sum();
392 let time: u64 = steps.iter().map(|s| s.time_10ms).sum();
393 routed += 1;
394 let _ = writeln!(
395 buf,
396 "PAIR {i} {} mode={} ok dist_mm={dist} time_10ms={time} steps={}",
397 p.kind,
398 p.mode,
399 steps.len()
400 );
401 for (k, s) in steps.iter().enumerate() {
402 let name = g.road_name(s.name_off).unwrap_or_default();
403 let _ = writeln!(
404 buf,
405 "STEP {i} {k} maneuver={} dist_mm={} time_10ms={} pts={} name={name}",
406 s.maneuver,
407 s.dist_mm,
408 s.time_10ms,
409 s.coords.len() / 2
410 );
411 }
412 // The polyline is the claim that compaction is geometry-preserving, so
413 // it is compared exactly. `coords` is flat [lon, lat, ...] from
414 // `StepData`; 7 decimals is the graph's own resolution.
415 let _ = write!(buf, "GEOM {i}");
416 for s in &steps {
417 for c in s.coords.chunks_exact(2) {
418 let _ = write!(buf, " {:.7},{:.7}", c[1], c[0]);
419 }
420 }
421 buf.push('\n');
422 }
423 let _ = writeln!(buf, "ROUTED {routed}/{}", pairs.len());
424 write_file(&out, buf.as_bytes())?;
425 println!("{out}: routed {routed}/{} pair(s)", pairs.len());
426 Ok(true)
427}
428
429// ---------------------------------------------------------------------------
430// dump / dump-compare
431// ---------------------------------------------------------------------------
432
433/// Magic and version of the dump format itself, so two dumps of different
434/// vintages cannot be compared as if they were the same thing.
435const DUMP_MAGIC: u32 = 0x5044_4752; // "RGDP"
436const DUMP_VERSION: u32 = 1;
437const DUMP_HEADER: usize = 24;
438/// `u32 source, u32 target, u32 dist_mm, u32 name_offset, u8 type_, u8 speed_limit`.
439const DUMP_EDGE: usize = 18;
440/// `i32 lat_e7, i32 lon_e7, u64 edge_ptr`.
441const DUMP_NODE: usize = 16;
442
443/// Every field of every edge and every node, in one linear pass.
444///
445/// This is the strongest check available on a pack-format change, and the cheapest.
446/// `report`/`compare` exercise whatever ~35 K vertices 999 sampled routes happen to
447/// touch; this exercises all E edges and all N+1 nodes, so a record that decodes
448/// wrongly one time in a million cannot hide. When it fails it names an edge index
449/// rather than a route, which is the difference between an afternoon and five
450/// minutes.
451///
452/// It reads through the *public* accessors — `edge_range`, `edge`,
453/// `edge_name_offset` — precisely so that the widened view, the delta decode and
454/// the sparse name table are all in the path being tested.
455///
456/// Fixed-width binary rather than text: California is 405 MB this way and 840 MB as
457/// text, and `dump_compare` decodes it back into field names anyway.
458fn dump(args: &[String]) -> Result<bool, String> {
459 let dir = need(args, "--graph")?;
460 let out = need(args, "--out")?;
461 let g = load(&dir)?;
462
463 let mut f = std::io::BufWriter::with_capacity(
464 1 << 20,
465 std::fs::File::create(&out).map_err(|e| format!("{out}: {e}"))?,
466 );
467 let mut w = |bytes: &[u8]| -> Result<(), String> {
468 f.write_all(bytes).map_err(|e| format!("{out}: {e}"))
469 };
470 w(&DUMP_MAGIC.to_le_bytes())?;
471 w(&DUMP_VERSION.to_le_bytes())?;
472 w(&u64::from(g.node_count).to_le_bytes())?;
473 w(&g.edge_count.to_le_bytes())?;
474
475 // Edges in index order, which is also source order, so `source` comes from the
476 // walk rather than from a search. Writing it down is the point: it is the one
477 // field no `edges.bin` record has ever stored, and getting it wrong is exactly
478 // how a delta-coded `target` fails.
479 let mut written = 0u64;
480 for u in 0..g.node_count {
481 let (start, end) = g.edge_range(u);
482 for idx in start..end {
483 let e = g.edge(u, idx);
484 w(&u.to_le_bytes())?;
485 w(&e.target.to_le_bytes())?;
486 w(&e.dist_mm.to_le_bytes())?;
487 w(&g.edge_name_offset(idx).unwrap_or(NO_NAME).to_le_bytes())?;
488 w(&[e.type_, e.speed_limit])?;
489 written += 1;
490 }
491 }
492 // Every edge must be reachable from exactly one node's range. If the ranges do
493 // not tile `0..edge_count` the dump is short, and no field comparison would say
494 // so.
495 if written != g.edge_count {
496 return Err(format!(
497 "the node ranges cover {written} edge(s), not the {} in the pack",
498 g.edge_count
499 ));
500 }
501
502 // N + 1, because the sentinel record is read by every `edge_range` call and so
503 // is as much a part of the contract as any real node.
504 for v in 0..=g.node_count {
505 let n = g.node(v);
506 w(&n.lat_e7.to_le_bytes())?;
507 w(&n.lon_e7.to_le_bytes())?;
508 w(&n.edge_ptr.to_le_bytes())?;
509 }
510 f.flush().map_err(|e| format!("{out}: {e}"))?;
511 // The escape and named counts are reported but deliberately *not* written into
512 // the dump. The dump has to stay byte-identical across every phase, and which
513 // fields a record could not hold is a property of the encoding rather than of the
514 // graph.
515 println!(
516 "{out}: {} edge(s) and {} node record(s), {} escaped ({:.4}%), {} named ({:.2}%)",
517 g.edge_count,
518 u64::from(g.node_count) + 1,
519 g.escape_count,
520 g.escape_count as f64 / g.edge_count.max(1) as f64 * 100.0,
521 g.named_edges,
522 g.named_edges as f64 / g.edge_count.max(1) as f64 * 100.0
523 );
524 Ok(true)
525}
526
527/// Compare two dumps element by element, naming the first few that differ.
528///
529/// Streams both files, because a Europe dump is 6.3 GB and holding two of them
530/// would be the only reason this tool needed a big machine.
531fn dump_compare(args: &[String]) -> Result<bool, String> {
532 let base_path = need(args, "--baseline")?;
533 let cand_path = need(args, "--candidate")?;
534 let limit: usize = flag(args, "--limit")
535 .as_deref()
536 .unwrap_or("10")
537 .parse()
538 .map_err(|e| format!("--limit: {e}"))?;
539
540 let mut b = DumpReader::open(&base_path)?;
541 let mut c = DumpReader::open(&cand_path)?;
542 let mut ok = true;
543 if (b.node_count, b.edge_count) != (c.node_count, c.edge_count) {
544 println!(
545 "FAIL counts differ: baseline {} node(s) {} edge(s), candidate {} / {}",
546 b.node_count, b.edge_count, c.node_count, c.edge_count
547 );
548 return Ok(false);
549 }
550 println!(
551 "DUMP {} edge(s), {} node record(s)",
552 b.edge_count,
553 b.node_count + 1
554 );
555
556 let mut shown = 0usize;
557 let mut edge_diffs = 0u64;
558 for idx in 0..b.edge_count {
559 let (x, y) = (b.next(DUMP_EDGE)?, c.next(DUMP_EDGE)?);
560 if x == y {
561 continue;
562 }
563 edge_diffs += 1;
564 ok = false;
565 if shown < limit {
566 shown += 1;
567 println!(" edge {idx}\n baseline {}\n candidate {}", fmt_edge(&x), fmt_edge(&y));
568 }
569 }
570
571 let mut node_diffs = 0u64;
572 shown = 0;
573 for idx in 0..=b.node_count {
574 let (x, y) = (b.next(DUMP_NODE)?, c.next(DUMP_NODE)?);
575 if x == y {
576 continue;
577 }
578 node_diffs += 1;
579 ok = false;
580 if shown < limit {
581 shown += 1;
582 let sentinel = if idx == b.node_count { " (sentinel)" } else { "" };
583 println!(
584 " node {idx}{sentinel}\n baseline {}\n candidate {}",
585 fmt_node(&x),
586 fmt_node(&y)
587 );
588 }
589 }
590
591 println!(
592 " {edge_diffs} edge(s) and {node_diffs} node record(s) differ\n{}",
593 if ok { "DUMPS IDENTICAL" } else { "DUMPS DIFFER" }
594 );
595 Ok(ok)
596}
597
598/// Fixed-width record reader over a dump file.
599struct DumpReader {
600 inner: std::io::BufReader<std::fs::File>,
601 path: String,
602 node_count: u64,
603 edge_count: u64,
604 buf: Vec<u8>,
605}
606
607impl DumpReader {
608 fn open(path: &str) -> Result<DumpReader, String> {
609 let f = std::fs::File::open(path).map_err(|e| format!("{path}: {e}"))?;
610 let mut r = DumpReader {
611 inner: std::io::BufReader::with_capacity(1 << 20, f),
612 path: path.to_string(),
613 node_count: 0,
614 edge_count: 0,
615 buf: Vec::new(),
616 };
617 let h = r.next(DUMP_HEADER)?;
618 if u32::from_le_bytes(h[0..4].try_into().unwrap()) != DUMP_MAGIC
619 || u32::from_le_bytes(h[4..8].try_into().unwrap()) != DUMP_VERSION
620 {
621 return Err(format!("{path} is not a v{DUMP_VERSION} dump"));
622 }
623 r.node_count = u64::from_le_bytes(h[8..16].try_into().unwrap());
624 r.edge_count = u64::from_le_bytes(h[16..24].try_into().unwrap());
625 Ok(r)
626 }
627
628 fn next(&mut self, n: usize) -> Result<Vec<u8>, String> {
629 self.buf.resize(n, 0);
630 std::io::Read::read_exact(&mut self.inner, &mut self.buf)
631 .map_err(|e| format!("{}: {e}", self.path))?;
632 Ok(self.buf.clone())
633 }
634}
635
636fn fmt_edge(r: &[u8]) -> String {
637 let u32_at = |i: usize| u32::from_le_bytes(r[i..i + 4].try_into().unwrap());
638 format!(
639 "source={} target={} dist_mm={} name_offset={} type={} speed_limit={}",
640 u32_at(0),
641 u32_at(4),
642 u32_at(8),
643 u32_at(12),
644 r[16],
645 r[17]
646 )
647}
648
649fn fmt_node(r: &[u8]) -> String {
650 format!(
651 "lat_e7={} lon_e7={} edge_ptr={}",
652 i32::from_le_bytes(r[0..4].try_into().unwrap()),
653 i32::from_le_bytes(r[4..8].try_into().unwrap()),
654 u64::from_le_bytes(r[8..16].try_into().unwrap())
655 )
656}
657
658// ---------------------------------------------------------------------------
659// bench
660// ---------------------------------------------------------------------------
661
662/// Time the real reader against a fixed pair set.
663///
664/// Every pack-format phase is measured against this and one of them is *gated* on
665/// it, so the cold pass is reported apart from the warm ones. On a pack far larger
666/// than RAM the first pass is almost entirely major page faults, and that is the
667/// number that decides whether splitting one record across two arrays is
668/// affordable; the warm passes measure the instruction path instead. Dropping the
669/// page cache is the caller's job, so "cold" means whatever state it left the cache
670/// in.
671///
672/// The route checksum is not decoration. A format change that broke routing would
673/// otherwise show up here as a *speedup*, so the bench refuses to report a number
674/// without also reporting what was computed.
675fn bench(args: &[String]) -> Result<bool, String> {
676 let dir = need(args, "--graph")?;
677 let pairs_path = need(args, "--pairs")?;
678 let passes: u32 = flag(args, "--passes")
679 .as_deref()
680 .unwrap_or("3")
681 .parse()
682 .map_err(|e| format!("--passes: {e}"))?;
683 if passes == 0 {
684 return Err("--passes wants at least one".to_string());
685 }
686 let cold = args.iter().any(|a| a == "--cold");
687 let verbose = args.iter().any(|a| a == "--verbose");
688 if cold {
689 let evicted = evict(&dir)?;
690 println!("evicted {evicted} pack file(s) from the page cache");
691 }
692
693 let load_started = std::time::Instant::now();
694 let g = load_with_overlay(&dir, args)?;
695 let load_ms = load_started.elapsed().as_secs_f64() * 1e3;
696
697 let pairs = read_pairs(&pairs_path)?;
698 let speeds = TrafficSpeeds::default();
699 let mut scratch = RoutingScratchpad::new();
700 let mut heap = RadixHeap::new();
701
702 println!("BENCH graph={dir} pairs={} passes={passes}", pairs.len());
703 println!(" Graph::load {load_ms:>10.1} ms");
704
705 let mut first: Option<Pass> = None;
706 let mut last = Pass::default();
707 for pass in 0..passes {
708 let mut p = Pass::default();
709 let started = std::time::Instant::now();
710 for pair in &pairs {
711 let one = std::time::Instant::now();
712 let mut ensure = |_lat_e7: i32, _lon_e7: i32| {};
713 let ctx = prepare_routing(
714 &g, &speeds, &mut ensure, pair.s_lat, pair.s_lon, pair.e_lat, pair.e_lon,
715 pair.mode, &mut scratch, &mut heap,
716 );
717 if let Some(mut ctx) = ctx {
718 let hierarchical = ctx.hierarchy;
719 perform_search_loop(
720 &g, &speeds, &mut ensure, pair.mode, &mut ctx, &mut scratch, &mut heap,
721 );
722 if verbose {
723 println!(
724 " {} mode={} {:.0} ms iterations={} hierarchy={} fell_back={} routed={}",
725 pair.kind,
726 pair.mode,
727 one.elapsed().as_secs_f64() * 1e3,
728 ctx.iterations,
729 hierarchical,
730 hierarchical && !ctx.hierarchy,
731 ctx.target_node != 0xFFFF_FFFF || ctx.direct.is_some(),
732 );
733 }
734 if ctx.target_node != 0xFFFF_FFFF || ctx.direct.is_some() {
735 let steps = reconstruct_path(&g, &speeds, pair.mode, &ctx, &mut scratch);
736 p.routed += 1;
737 for s in &steps {
738 // A cheap order-dependent mix, so a route that changes
739 // length, timing or turn order changes the digest.
740 p.checksum = p
741 .checksum
742 .rotate_left(7)
743 .wrapping_add(u64::from(s.dist_mm))
744 .wrapping_mul(0x1000_0000_1B3)
745 ^ u64::from(s.time_10ms);
746 }
747 }
748 }
749 p.latency_ns.push(one.elapsed().as_nanos() as u64);
750 }
751 p.wall_s = started.elapsed().as_secs_f64();
752 p.latency_ns.sort_unstable();
753 let label = if pass == 0 { "cold" } else { "warm" };
754 println!(
755 " pass {:<2} ({label}) {:>9.1} routes/s p50 {:>7.2} p90 {:>7.2} \
756 p99 {:>7.2} max {:>8.2} ms",
757 pass + 1,
758 pairs.len() as f64 / p.wall_s,
759 p.pct_ms(50),
760 p.pct_ms(90),
761 p.pct_ms(99),
762 p.pct_ms(100),
763 );
764 if first.is_none() {
765 first = Some(p);
766 } else {
767 last = p;
768 }
769 }
770 let first = first.expect("at least one pass");
771 let warm = if last.latency_ns.is_empty() { &first } else { &last };
772 println!(
773 " routed {}/{} pair(s), checksum {:016x}",
774 warm.routed,
775 pairs.len(),
776 warm.checksum
777 );
778 if first.checksum != warm.checksum || first.routed != warm.routed {
779 println!(" FAIL the passes disagree on what they routed");
780 return Ok(false);
781 }
782 println!(" peak RSS {:>10} kB", peak_rss_kb());
783 // One line per pass is what a script diffs, but the summary line is what a
784 // human reads, and the plan's tolerances are stated against these three.
785 println!(
786 "SUMMARY load_ms={load_ms:.1} cold_routes_s={:.1} warm_routes_s={:.1} \
787 cold_p50_ms={:.3} cold_p99_ms={:.3} warm_p50_ms={:.3} warm_p99_ms={:.3} \
788 peak_rss_kb={} checksum={:016x}",
789 pairs.len() as f64 / first.wall_s,
790 pairs.len() as f64 / warm.wall_s,
791 first.pct_ms(50),
792 first.pct_ms(99),
793 warm.pct_ms(50),
794 warm.pct_ms(99),
795 peak_rss_kb(),
796 warm.checksum
797 );
798 Ok(true)
799}
800
801#[derive(Default)]
802struct Pass {
803 latency_ns: Vec<u64>,
804 wall_s: f64,
805 routed: usize,
806 checksum: u64,
807}
808
809impl Pass {
810 /// The `p`-th percentile in milliseconds; `p = 100` is the maximum.
811 fn pct_ms(&self, p: usize) -> f64 {
812 if self.latency_ns.is_empty() {
813 return 0.0;
814 }
815 let last = self.latency_ns.len() - 1;
816 let i = (p * last / 100).min(last);
817 self.latency_ns[i] as f64 / 1e6
818 }
819}
820
821/// High-water mark of the process's resident set, in kB, or 0 where the kernel
822/// does not report it.
823fn peak_rss_kb() -> u64 {
824 std::fs::read_to_string("/proc/self/status")
825 .ok()
826 .and_then(|s| {
827 s.lines()
828 .find(|l| l.starts_with("VmHWM:"))
829 .and_then(|l| l.split_whitespace().nth(1)?.parse().ok())
830 })
831 .unwrap_or(0)
832}
833
834/// Evict a pack directory's files from the page cache, so the pass that follows
835/// measures major faults rather than a warm cache. Returns how many files were hit.
836///
837/// `POSIX_FADV_DONTNEED` rather than `/proc/sys/vm/drop_caches`, which needs root.
838/// It is advisory and best-effort — pages that are dirty or still mapped elsewhere
839/// stay resident — so what it produces is a *lower bound* on how cold a real first
840/// run is. Which is the right direction: a phase that looks affordable here might
841/// still not be on a pack larger than RAM, and one that regresses here certainly is
842/// not.
843fn evict(dir: &str) -> Result<usize, String> {
844 const FILES: [&str; 6] = [
845 "metadata.bin",
846 "nodes.bin",
847 "edges.bin",
848 "lanes.bin",
849 "intermediate.bin",
850 "road_names.bin",
851 ];
852 let mut hit = 0;
853 for name in FILES {
854 let path = format!("{}/{name}", dir.trim_end_matches('/'));
855 let Ok(f) = std::fs::File::open(&path) else { continue };
856 // Offset 0, length 0 means "the whole file".
857 let rc = unsafe {
858 libc::posix_fadvise(
859 std::os::unix::io::AsRawFd::as_raw_fd(&f),
860 0,
861 0,
862 libc::POSIX_FADV_DONTNEED,
863 )
864 };
865 if rc != 0 {
866 return Err(format!("posix_fadvise({path}): {rc}"));
867 }
868 hit += 1;
869 }
870 Ok(hit)
871}
872
873// ---------------------------------------------------------------------------
874// compare
875// ---------------------------------------------------------------------------
876
877/// Compare two reports.
878///
879/// The pass criterion has to account for the fact that a rebuild which changes
880/// the node set also changes *snapping*: `find_nearest_edge` scans a fixed
881/// window of 800 nodes in Morton order, so with fewer, longer edges it reaches
882/// further and legitimately finds a different — often nearer — road. A route from
883/// a different starting edge is not a regression, it is a different question.
884///
885/// So pairs are split by whether both ends snapped to the same place:
886///
887/// * **Same snap, same distance** is the strict case: the turn sequence and the
888/// polyline must match exactly. This is where a geometry or bookkeeping bug
889/// would show, and it is the only class treated as a failure.
890/// * **Same snap, different distance** is an alternative optimum. Reported.
891/// * **Moved snap** is reported and counted, not failed.
892///
893/// A pair that stops being routable is always a failure; one that becomes
894/// routable is not.
895fn compare(args: &[String]) -> Result<bool, String> {
896 let base_path = need(args, "--baseline")?;
897 let cand_path = need(args, "--candidate")?;
898 let tol_mm: u64 = flag(args, "--tol-mm")
899 .as_deref()
900 .unwrap_or("1000")
901 .parse()
902 .map_err(|e| format!("--tol-mm: {e}"))?;
903 let tol_time: u64 = flag(args, "--tol-10ms")
904 .as_deref()
905 .unwrap_or("100")
906 .parse()
907 .map_err(|e| format!("--tol-10ms: {e}"))?;
908 // How far a snap may move before the pair is no longer "the same question".
909 let snap_tol_m: f64 = flag(args, "--tol-snap-m")
910 .as_deref()
911 .unwrap_or("1.0")
912 .parse()
913 .map_err(|e| format!("--tol-snap-m: {e}"))?;
914
915 let base = std::fs::read_to_string(&base_path).map_err(|e| format!("{base_path}: {e}"))?;
916 let cand = std::fs::read_to_string(&cand_path).map_err(|e| format!("{cand_path}: {e}"))?;
917
918 let bp = index_by_key(&base, "PAIR");
919 let cp = index_by_key(&cand, "PAIR");
920 let bs_snap = index_by_key(&base, "SNAP");
921 let cs_snap = index_by_key(&cand, "SNAP");
922 let bg = index_by_key(&base, "GEOM");
923 let cg = index_by_key(&cand, "GEOM");
924 let bs = index_steps(&base);
925 let cs = index_steps(&cand);
926
927 let mut fails: Vec<String> = Vec::new();
928 let mut lost = 0usize;
929 let mut gained = 0usize;
930 let mut moved_snap = 0usize;
931 let mut strict = 0usize;
932 let mut alt_optimum = 0usize;
933 let mut worst_dist = 0i64;
934 let mut worst_time = 0i64;
935
936 let mut keys: Vec<&String> = bp.keys().collect();
937 keys.sort_by_key(|k| k.parse::<u64>().unwrap_or(u64::MAX));
938
939 for k in &keys {
940 let b = &bp[*k];
941 let c = match cp.get(*k) {
942 Some(c) => c,
943 None => {
944 fails.push(format!("pair {k}: missing from the candidate report"));
945 continue;
946 }
947 };
948 let b_ok = b.contains(&"ok".to_string());
949 let c_ok = c.contains(&"ok".to_string());
950 // Snap movement is checked first, and outranks routability. A query point
951 // that is a kilometre from any road can snap onto a nearer but
952 // disconnected one after a rebuild, and calling that a lost route blames
953 // the graph for an unreasonable question.
954 let shift = snap_shift_m(bs_snap.get(*k), cs_snap.get(*k));
955 if shift > snap_tol_m {
956 moved_snap += 1;
957 continue;
958 }
959 if b_ok && !c_ok {
960 lost += 1;
961 fails.push(format!("pair {k}: snapped to the same place but is no longer routable"));
962 continue;
963 }
964 if !b_ok {
965 if c_ok {
966 gained += 1;
967 }
968 continue;
969 }
970
971 let dd = kv(c, "dist_mm").unwrap_or(0) as i64 - kv(b, "dist_mm").unwrap_or(0) as i64;
972 let dt = kv(c, "time_10ms").unwrap_or(0) as i64 - kv(b, "time_10ms").unwrap_or(0) as i64;
973 if dd.abs() > worst_dist.abs() {
974 worst_dist = dd;
975 }
976 if dt.abs() > worst_time.abs() {
977 worst_time = dt;
978 }
979
980 if dd.unsigned_abs() > tol_mm || dt.unsigned_abs() > tol_time {
981 alt_optimum += 1;
982 continue;
983 }
984
985 // Same snap, same length: the roads travelled and the path drawn must
986 // match.
987 strict += 1;
988 let b_roads = bs.get(*k).map(road_seq).unwrap_or_default();
989 let c_roads = cs.get(*k).map(road_seq).unwrap_or_default();
990 if b_roads != c_roads {
991 fails.push(format!(
992 "pair {k}: same snap and same length, but the roads travelled differ \
993 ({} vs {}, first at {:?})",
994 b_roads.len(),
995 c_roads.len(),
996 first_mismatch(&b_roads, &c_roads)
997 ));
998 }
999 let b_line = polyline_points(bg.get(*k));
1000 let c_line = polyline_points(cg.get(*k));
1001 if !same_path(&b_line, &c_line) {
1002 fails.push(format!(
1003 "pair {k}: same snap and same length, but the path differs \
1004 ({} vs {} distinct point(s))",
1005 b_line.len(),
1006 c_line.len()
1007 ));
1008 }
1009 }
1010
1011 for k in cp.keys() {
1012 if !bp.contains_key(k) {
1013 fails.push(format!("pair {k}: only in the candidate report"));
1014 }
1015 }
1016
1017 println!("{} pair(s) compared", keys.len());
1018 println!(" {strict:>5} same snap, same length (compared strictly)");
1019 println!(" {alt_optimum:>5} same snap, different length (alternative optimum)");
1020 println!(" {moved_snap:>5} snapped somewhere else (>{snap_tol_m} m)");
1021 println!(" {gained:>5} became routable");
1022 println!(" {lost:>5} stopped being routable");
1023 println!("worst dist delta {worst_dist} mm, worst time delta {worst_time} (10 ms units)");
1024 for f in fails.iter().take(20) {
1025 println!(" {f}");
1026 }
1027 if fails.len() > 20 {
1028 println!(" ({} further finding(s) suppressed)", fails.len() - 20);
1029 }
1030 println!(
1031 "{}",
1032 if fails.is_empty() { "DIFFERENTIAL CLEAN" } else { "DIFFERENTIAL FAILED" }
1033 );
1034 Ok(fails.is_empty())
1035}
1036
1037/// The larger of the two ends' snap movements, in metres.
1038fn snap_shift_m(b: Option<&Vec<String>>, c: Option<&Vec<String>>) -> f64 {
1039 let point = |t: &Vec<String>, key: &str| -> Option<(f64, f64)> {
1040 let v = t.iter().find_map(|s| s.strip_prefix(key)?.strip_prefix('='))?;
1041 let (a, b) = v.split_once(',')?;
1042 Some((a.parse().ok()?, b.parse().ok()?))
1043 };
1044 let (b, c) = match (b, c) {
1045 (Some(b), Some(c)) => (b, c),
1046 // No SNAP line means an older report; treat it as "unknown", which is
1047 // safer read as moved than as identical.
1048 _ => return f64::INFINITY,
1049 };
1050 let mut worst = 0.0f64;
1051 for key in ["s", "e"] {
1052 match (point(b, key), point(c, key)) {
1053 (Some(p), Some(q)) => worst = worst.max(crow_m(p.0, p.1, q.0, q.1)),
1054 _ => return f64::INFINITY,
1055 }
1056 }
1057 worst
1058}
1059
1060/// Collect `KIND <id> rest...` lines into id -> tokens.
1061fn index_by_key(text: &str, kind: &str) -> HashMap<String, Vec<String>> {
1062 let mut out = HashMap::new();
1063 for line in text.lines() {
1064 let mut it = line.split_whitespace();
1065 if it.next() != Some(kind) {
1066 continue;
1067 }
1068 if let Some(id) = it.next() {
1069 let _ = out.insert(id.to_string(), it.map(str::to_string).collect());
1070 }
1071 }
1072 out
1073}
1074
1075/// `STEP <pair> <k> ...` grouped by pair, in file order.
1076fn index_steps(text: &str) -> HashMap<String, Vec<String>> {
1077 let mut out: HashMap<String, Vec<String>> = HashMap::new();
1078 for line in text.lines() {
1079 let mut it = line.split_whitespace();
1080 if it.next() != Some("STEP") {
1081 continue;
1082 }
1083 if let Some(id) = it.next() {
1084 out.entry(id.to_string()).or_default().push(line.to_string());
1085 }
1086 }
1087 out
1088}
1089
1090fn kv(tokens: &[String], key: &str) -> Option<u64> {
1091 tokens
1092 .iter()
1093 .find_map(|t| t.strip_prefix(key).and_then(|r| r.strip_prefix('=')))
1094 .and_then(|v| v.parse().ok())
1095}
1096
1097/// The roads a route actually travels, in order, with repeats folded together.
1098///
1099/// Deliberately not the raw step list. Steps are split on bearing change, and two
1100/// graphs of one region split them differently for reasons that are not route
1101/// changes: an uncompacted graph's reconstruction emits a spurious zero-length
1102/// U-turn step where the route doubles back to a node, and a compacted one does
1103/// not. The sequence of named roads is what a driver would recognise, and it is
1104/// invariant to that.
1105fn road_seq(lines: &Vec<String>) -> Vec<String> {
1106 let mut out: Vec<String> = Vec::new();
1107 for l in lines {
1108 // Zero-length steps are reconstruction artefacts, not roads.
1109 if kv(&l.split_whitespace().map(str::to_string).collect::<Vec<_>>(), "dist_mm")
1110 == Some(0)
1111 {
1112 continue;
1113 }
1114 let name = match l.find(" name=") {
1115 Some(i) => l[i + 6..].to_string(),
1116 None => String::new(),
1117 };
1118 if out.last() != Some(&name) {
1119 out.push(name);
1120 }
1121 }
1122 out
1123}
1124
1125/// A polyline's points, with consecutive repeats folded together.
1126///
1127/// Repeats are artefacts, not shape: a route that doubles back to a node emits it
1128/// twice, and the reconstruction's start and end stubs repeat their joint vertex.
1129fn polyline_points(tokens: Option<&Vec<String>>) -> Vec<(i64, i64)> {
1130 let tokens = match tokens {
1131 Some(t) => t,
1132 None => return Vec::new(),
1133 };
1134 let mut pts: Vec<(i64, i64)> = Vec::with_capacity(tokens.len());
1135 for t in tokens {
1136 if let Some((a, b)) = t.split_once(',') {
1137 if let (Ok(lat), Ok(lon)) = (a.parse::<f64>(), b.parse::<f64>()) {
1138 let p = ((lat * 1e7).round() as i64, (lon * 1e7).round() as i64);
1139 if pts.last() != Some(&p) {
1140 pts.push(p);
1141 }
1142 }
1143 }
1144 }
1145 pts
1146}
1147
1148/// Whether two polylines trace the same path, allowing one to be a finer
1149/// subdivision of the other.
1150///
1151/// The geometry encoder inserts collinear points wherever a gap exceeds the `i16`
1152/// delta range, so a compacted graph's polyline legitimately carries vertices an
1153/// uncompacted one never needed. Those extra points lie *between* the originals,
1154/// so the coarser polyline must appear in the finer one as an in-order
1155/// subsequence — which is an exact test, unlike trying to detect and drop the
1156/// inserted points, since collinearity is not stable under subdivision (adding a
1157/// point between A and P changes P's neighbours, and so changes whether P looks
1158/// collinear).
1159fn same_path(a: &[(i64, i64)], b: &[(i64, i64)]) -> bool {
1160 if a == b {
1161 return true;
1162 }
1163 is_subsequence(a, b) || is_subsequence(b, a)
1164}
1165
1166fn is_subsequence(needle: &[(i64, i64)], haystack: &[(i64, i64)]) -> bool {
1167 if needle.len() > haystack.len() {
1168 return false;
1169 }
1170 let mut it = haystack.iter();
1171 needle.iter().all(|p| it.any(|q| q == p))
1172}
1173
1174fn first_mismatch(a: &[String], b: &[String]) -> Option<usize> {
1175 (0..a.len().max(b.len())).find(|&i| a.get(i) != b.get(i))
1176}
1177
1178// ---------------------------------------------------------------------------
1179// geometry
1180// ---------------------------------------------------------------------------
1181
1182/// Check directly that a rebuild describes the same roads, independent of
1183/// routing.
1184///
1185/// This is sharper than the route differential, and it has to be: collapsing
1186/// nodes changes how far `find_nearest_edge`'s fixed 800-node window reaches, so
1187/// two graphs of one region legitimately snap to different edges and produce
1188/// different routes. What must not change is the road network itself.
1189///
1190/// Two invariants are checked, both chosen to be insensitive to how the geometry
1191/// is *divided* into points, because the encoder inserts collinear points
1192/// wherever a gap exceeds the `i16` delta range:
1193///
1194/// * **No vertex is lost.** Every point in the baseline's geometry must still
1195/// appear in the candidate's. Interpolation only ever adds points, so the
1196/// candidate's vertex set must be a superset. A collapsed node whose
1197/// coordinate vanished would mean a corner had been cut.
1198/// * **Total length is preserved.** Summed over every hop of every edge.
1199/// Subdividing a straight hop does not change its length beyond the
1200/// sub-centimetre rounding of the inserted points.
1201fn geometry(args: &[String]) -> Result<bool, String> {
1202 let base_dir = need(args, "--baseline")?;
1203 let cand_dir = need(args, "--candidate")?;
1204 let base = load(&base_dir)?;
1205 let cand = load(&cand_dir)?;
1206
1207 let b = scan_geometry(&base);
1208 println!(
1209 "baseline nodes={:<10} edges={:<10} hops={:<10} vertices={:<10} length={} mm",
1210 base.node_count,
1211 base.edge_count,
1212 b.hops,
1213 b.vertices.len(),
1214 b.length_mm
1215 );
1216 let c = scan_geometry(&cand);
1217 println!(
1218 "candidate nodes={:<10} edges={:<10} hops={:<10} vertices={:<10} length={} mm",
1219 cand.node_count,
1220 cand.edge_count,
1221 c.hops,
1222 c.vertices.len(),
1223 c.length_mm
1224 );
1225 println!(
1226 "candidate stored geometry on {} edge(s), {} of them by reference to a twin",
1227 c.with_geometry, c.reversed
1228 );
1229 print!("candidate points per edge (log2 buckets):");
1230 for (i, n) in c.pt_hist.iter().enumerate() {
1231 if *n > 0 {
1232 print!(" 2^{i}={n}");
1233 }
1234 }
1235 println!();
1236
1237 // Sorted, because the sample below is the only thing a human has to go on and a
1238 // `HashSet`'s iteration order is randomised per process — so an unsorted sample
1239 // changes on every run of the same pack, which makes it useless for both
1240 // diagnosis and for diffing two runs against each other.
1241 let mut missing: Vec<&(i32, i32)> = b.vertices.difference(&c.vertices).collect();
1242 missing.sort_unstable();
1243 let mut ok = true;
1244 if missing.is_empty() {
1245 println!("PASS every baseline vertex survives in the candidate");
1246 } else {
1247 ok = false;
1248 println!(
1249 "FAIL {} of {} baseline vertices are missing from the candidate",
1250 missing.len(),
1251 b.vertices.len()
1252 );
1253 for v in missing.iter().take(10) {
1254 println!(" {:.7},{:.7}", f64::from(v.0) * 1e-7, f64::from(v.1) * 1e-7);
1255 }
1256 }
1257
1258 // A tenth of a percent covers the reconnection edges, which legitimately
1259 // pick different anchors once the node set changes, plus integer rounding on
1260 // interpolated points.
1261 let delta = c.length_mm as i128 - b.length_mm as i128;
1262 let tol = (b.length_mm / 1000).max(1_000_000) as i128;
1263 if delta.abs() <= tol {
1264 println!(
1265 "PASS total road length within tolerance (delta {delta} mm of {} mm, tol {tol})",
1266 b.length_mm
1267 );
1268 } else {
1269 ok = false;
1270 println!("FAIL total road length moved by {delta} mm (tol {tol})");
1271 }
1272 println!("{}", if ok { "GEOMETRY PRESERVED" } else { "GEOMETRY CHANGED" });
1273 Ok(ok)
1274}
1275
1276struct GeomScan {
1277 hops: u64,
1278 length_mm: u128,
1279 vertices: HashSet<(i32, i32)>,
1280 with_geometry: u64,
1281 reversed: u64,
1282 pt_hist: [u64; 9],
1283}
1284
1285/// Walk every edge and collect the geometry the device would draw: the stored
1286/// polyline where there is one, the straight chord otherwise.
1287fn scan_geometry(g: &Graph) -> GeomScan {
1288 let mut coords = [LatLon { lat_e7: 0, lon_e7: 0 }; 256];
1289 let mut out = GeomScan {
1290 hops: 0,
1291 length_mm: 0,
1292 vertices: HashSet::new(),
1293 with_geometry: 0,
1294 reversed: 0,
1295 pt_hist: [0u64; 9],
1296 };
1297 let mut pts: Vec<LatLon> = Vec::with_capacity(256);
1298
1299 for u in 0..g.node_count {
1300 let node_u = g.node(u);
1301 let (start, end) = g.edge_range(u);
1302 for j in start..end {
1303 let e = g.edge(u, j);
1304 if e.target >= g.node_count {
1305 continue;
1306 }
1307 pts.clear();
1308 match g.get_edge_coordinates_from(u, j, &mut coords) {
1309 Some((count, is_reversed)) if count >= 2 => {
1310 out.with_geometry += 1;
1311 if is_reversed {
1312 out.reversed += 1;
1313 }
1314 pts.extend((0..count).map(|p| get_pt_at(&coords, count, is_reversed, p)));
1315 }
1316 _ => {
1317 let node_v = g.node(e.target);
1318 pts.push(LatLon { lat_e7: node_u.lat_e7, lon_e7: node_u.lon_e7 });
1319 pts.push(LatLon { lat_e7: node_v.lat_e7, lon_e7: node_v.lon_e7 });
1320 }
1321 }
1322 let bucket = (pts.len() as f64).log2() as usize;
1323 out.pt_hist[bucket.min(8)] += 1;
1324 for p in &pts {
1325 let _ = out.vertices.insert((p.lat_e7, p.lon_e7));
1326 }
1327 for w in pts.windows(2) {
1328 if (w[0].lat_e7, w[0].lon_e7) == (w[1].lat_e7, w[1].lon_e7) {
1329 continue;
1330 }
1331 out.hops += 1;
1332 out.length_mm += u128::from(accurate_dist_mm(
1333 w[0].lat_e7, w[0].lon_e7, w[1].lat_e7, w[1].lon_e7,
1334 ));
1335 }
1336 }
1337 }
1338 out
1339}
1340
1341/// The other direction of the same road: the first edge from `target` back to
1342/// `source`. Mirrors `graph.rs`'s reverse-geometry lookup and `routing.rs`'s
1343/// `twin_edge`, so the tool and the engine agree on what "the twin" means.
1344fn twin_of(g: &Graph, source: u32, target: u32) -> Option<u64> {
1345 if target >= g.node_count {
1346 return None;
1347 }
1348 let (s, e) = g.edge_range(target);
1349 (s..e).find(|k| g.edge_targets(*k, target, source))
1350}
1351
1352/// Approximate ground distance in metres (equirectangular). Only used to report
1353/// how far a snap moved, so an approximation is fine.
1354fn crow_m(lat1: f64, lon1: f64, lat2: f64, lon2: f64) -> f64 {
1355 let dlat = (lat2 - lat1) * 111_320.0;
1356 let dlon = (lon2 - lon1) * 111_320.0 * ((lat1 + lat2) * 0.5).to_radians().cos();
1357 (dlat * dlat + dlon * dlon).sqrt()
1358}
1359
1360fn write_file(path: &str, bytes: &[u8]) -> Result<(), String> {
1361 let mut f = std::fs::File::create(path).map_err(|e| format!("{path}: {e}"))?;
1362 f.write_all(bytes).map_err(|e| format!("{path}: {e}"))
1363}