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

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

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