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

Modern-Apps.git / scripts / maps / test / diff_mamaps.py

diff_mamaps.py380 lines · 14.8 KiBRaw
1#!/usr/bin/env python3
2"""diff_mamaps.py — is this archive the same PICTURE as that one?
3
4Compares two `.mamaps` archives by decoding both with `tile_build`'s `mamaps_dump`
5and diffing the decoded model, tile by tile and layer by layer.
6
7WHY THIS EXISTS. Every earlier change to the tile pipeline was gated on a
8byte-identical archive, which is the strongest check there is and needs no
9judgement. `tile_build::subdivide` gave that up: it clips a feature down the tile
10quadtree instead of once per tile, and Sutherland-Hodgman keeps its input's
11rotation, so a ring comes out starting at a different vertex. Same edges, same
12winding, same area, different bytes. A byte diff on such an archive reports
13everything and means nothing, so this compares the measures instead.
14
15WHAT IS HELD EXACT, per (tile, layer):
16 * The set of (tile, layer) pairs. A tile in one archive and not the other is a
17 hole in the map or a tile invented from nothing, and either is a failure.
18 * Feature count.
19 * Geometry-type mix -- a line layer must not start emitting polygons.
20
21WHAT IS HELD TO A TOLERANCE, per (tile, layer):
22 * Total absolute ring area, and total line length, relatively. This is the
23 check that says the shape did not move. The tolerance is there for the
24 last-bit drift a composed clip introduces when it interpolates a crossing off
25 an already-interpolated vertex, which is around 1e-12 of a coordinate.
26 * Point count, which may differ by a little: a concave ring's zero-area run
27 along a clip boundary is shorter when the clip happens in stages. The budget
28 is a percentage OR a small absolute slack, whichever is larger, because the
29 effect is a couple of vertices per ring and not a proportion -- one vertex on
30 an eleven-point tile is 9%, which a percentage-only budget would call a
31 catastrophe. The SIGN of the net change is printed in the summary; a net
32 increase means the archive is growing and is worth explaining.
33
34Usage:
35 ./diff_mamaps.py before.mamaps after.mamaps
36 ./diff_mamaps.py a.mamaps b.mamaps --layer water
37 ./diff_mamaps.py a.mamaps b.mamaps --max-measure-delta 1e-6 --max-point-delta 1.0
38
39Exit code 0 when they hold the same picture within the stated budget, 1 otherwise.
40"""
41
42from __future__ import annotations
43
44import argparse
45import subprocess
46import sys
47from pathlib import Path
48
49ROOT = Path(__file__).resolve().parent.parent
50CRATE = ROOT / "tile_build"
51
52
53def dump_command(explicit: Path | None) -> list[str]:
54 if explicit:
55 return [str(explicit)]
56 for name in ("mamaps_dump", "mamaps_dump.exe"):
57 built = CRATE / "target" / "release" / name
58 if built.exists():
59 return [str(built)]
60 # Falling back to `cargo run` keeps this usable on a clean checkout, at the
61 # cost of a build on first use.
62 return [
63 "cargo",
64 "run",
65 "--release",
66 "--quiet",
67 "--manifest-path",
68 str(CRATE / "Cargo.toml"),
69 "--bin",
70 "mamaps_dump",
71 "--",
72 ]
73
74
75def run_churn(before: Path, after: Path, budget_gb: float | None) -> bool:
76 """Print the byte-level overlay budget; True when the budget gate fails."""
77 cmd = churn_command(None)
78 proc = subprocess.run(cmd + [str(before), str(after)], capture_output=True, text=True)
79 if proc.returncode != 0:
80 sys.stderr.write(proc.stderr)
81 raise SystemExit(f"mamaps_churn failed on {before} vs {after}")
82 overlay_bytes = None
83 for line in proc.stdout.splitlines():
84 print(f"churn: {line}")
85 if line.startswith("OVERLAY_BYTES="):
86 overlay_bytes = int(line.split("=", 1)[1])
87 if budget_gb is not None:
88 if overlay_bytes is None:
89 raise SystemExit("mamaps_churn printed no OVERLAY_BYTES line")
90 budget_bytes = int(budget_gb * 1024**3)
91 if overlay_bytes > budget_bytes:
92 print(
93 f"churn: OVERLAY {overlay_bytes / 1024**3:.2f} GiB "
94 f"exceeds budget {budget_gb:.2f} GiB"
95 )
96 return True
97 print(
98 f"churn: OVERLAY {overlay_bytes / 1024**3:.2f} GiB "
99 f"within budget {budget_gb:.2f} GiB"
100 )
101 return False
102
103
104def churn_command(explicit: Path | None) -> list[str]:
105 if explicit:
106 return [str(explicit)]
107 for name in ("mamaps_churn", "mamaps_churn.exe"):
108 built = CRATE / "target" / "release" / name
109 if built.exists():
110 return [str(built)]
111 # Falling back to `cargo run` keeps this usable on a clean checkout, at the
112 # cost of a build on first use.
113 return [
114 "cargo",
115 "run",
116 "--release",
117 "--quiet",
118 "--manifest-path",
119 str(CRATE / "Cargo.toml"),
120 "--bin",
121 "mamaps_churn",
122 "--",
123 ]
124
125
126class Row:
127 """One (tile, layer)'s measures, as `mamaps_dump --mode geometry` prints them."""
128
129 __slots__ = ("features", "points", "rings", "geom", "area", "net", "length")
130
131 def __init__(self, fields: dict[str, str]) -> None:
132 self.features = int(fields.get("features", 0))
133 self.points = int(fields.get("points", 0))
134 self.rings = int(fields.get("rings", 0))
135 # Type mix as a dict, so "polygon:3" and "line:1" compare as a mapping
136 # rather than as a string whose order might drift.
137 self.geom = {}
138 for p in filter(None, fields.get("geom", "").split(",")):
139 k, _, v = p.partition(":")
140 self.geom[k] = int(v or 0)
141 self.area = float(fields.get("area", 0.0))
142 self.net = float(fields.get("net", 0.0))
143 self.length = float(fields.get("length", 0.0))
144
145
146def run_dump(cmd: list[str], archive: Path, layer: str | None) -> dict[tuple[str, str], Row]:
147 argv = cmd + [str(archive), "--mode", "geometry"]
148 if layer:
149 argv += ["--layer", layer]
150 proc = subprocess.run(argv, capture_output=True, text=True)
151 if proc.returncode != 0:
152 sys.stderr.write(proc.stderr)
153 raise SystemExit(f"mamaps_dump failed on {archive}")
154 if proc.stderr.strip():
155 sys.stderr.write(proc.stderr)
156
157 out: dict[tuple[str, str], Row] = {}
158 for line in proc.stdout.splitlines():
159 parts = line.split("\t")
160 if len(parts) < 3:
161 continue
162 tile, layer_name = parts[0], parts[1]
163 fields = {}
164 for p in parts[2:]:
165 k, _, v = p.partition("=")
166 fields[k] = v
167 # A tile id can repeat across layers but never within one, so the pair is
168 # the key. A duplicate would mean the dump itself is wrong.
169 key = (tile, layer_name)
170 if key in out:
171 raise SystemExit(f"{archive}: {tile} {layer_name} appears twice in the dump")
172 out[key] = Row(fields)
173 return out
174
175
176def tile_sort_key(tile: str) -> tuple[int, int, int]:
177 z, x, y = tile.split("/")
178 return int(z), int(x), int(y)
179
180
181def relative_delta(a: float, b: float) -> float:
182 """How far apart two measures are, scaled so a zero measure is comparable."""
183 scale = max(abs(a), abs(b), 1.0)
184 return abs(a - b) / scale
185
186
187def main() -> int:
188 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
189 ap.add_argument("before", type=Path, help="the archive to compare against")
190 ap.add_argument("after", type=Path, help="the archive under test")
191 ap.add_argument("--layer", help="restrict the comparison to one layer")
192 ap.add_argument(
193 "--max-measure-delta",
194 type=float,
195 default=1e-6,
196 help="permitted relative difference in ring area and line length per "
197 "(tile, layer) (default 1e-6). Composed clipping drifts by about 1e-12, "
198 "so this is six orders of margin and still far below one extent unit.",
199 )
200 ap.add_argument(
201 "--max-point-delta",
202 type=float,
203 default=1.0,
204 help="permitted per-(tile, layer) point-count difference, in percent of "
205 "the `before` count (default 1). Zero-area collinear runs along a clip "
206 "boundary are the only thing that should move this.",
207 )
208 ap.add_argument(
209 "--point-slack",
210 type=int,
211 default=2,
212 help="point-count difference always permitted regardless of percentage "
213 "(default 2). A tile holding eleven points is 9%% different at one "
214 "vertex, and one vertex is the size of the effect being tolerated.",
215 )
216 ap.add_argument(
217 "--dump",
218 type=Path,
219 help="path to a mamaps_dump binary (default: the crate's release build, "
220 "else `cargo run`)",
221 )
222 ap.add_argument(
223 "--max-report",
224 type=int,
225 default=20,
226 help="how many failures to print before summarising (default 20)",
227 )
228 ap.add_argument(
229 "--churn",
230 action="store_true",
231 help="also report the byte-level overlay budget via mamaps_churn "
232 "(stored-body churn, per-zoom split, sidecar moves). The picture "
233 "check above still gates; this is the Phase 0 sizing signal.",
234 )
235 ap.add_argument(
236 "--churn-budget-gb",
237 type=float,
238 default=None,
239 help="fail when the mamaps_churn OVERLAY_BYTES estimate exceeds this "
240 "many GiB (requires --churn). The increment fails closed when a "
241 "monthly overlay would not fit the budget.",
242 )
243 args = ap.parse_args()
244
245 churn_failed = False
246 if args.churn or args.churn_budget_gb is not None:
247 churn_failed = run_churn(args.before, args.after, args.churn_budget_gb)
248
249 cmd = dump_command(args.dump)
250 before = run_dump(cmd, args.before, args.layer)
251 after = run_dump(cmd, args.after, args.layer)
252
253 print(f"before: {len(before):>9,} (tile, layer) pair(s) {args.before}")
254 print(f"after : {len(after):>9,} (tile, layer) pair(s) {args.after}")
255
256 failures: list[str] = []
257 only_before = sorted(set(before) - set(after), key=lambda p: (tile_sort_key(p[0]), p[1]))
258 only_after = sorted(set(after) - set(before), key=lambda p: (tile_sort_key(p[0]), p[1]))
259 for tile, layer in only_before:
260 failures.append(f"{tile} {layer}: in before, absent from after -- a hole in the map")
261 for tile, layer in only_after:
262 failures.append(f"{tile} {layer}: in after, absent from before -- a tile from nothing")
263
264 # Totals, so the summary says something even when every pair agrees.
265 shared = sorted(set(before) & set(after), key=lambda p: (tile_sort_key(p[0]), p[1]))
266 totals = {
267 "area": [0.0, 0.0],
268 "net": [0.0, 0.0],
269 "length": [0.0, 0.0],
270 "points": [0, 0],
271 "features": [0, 0],
272 "rings": [0, 0],
273 }
274 worst = {"area": 0.0, "net": 0.0, "length": 0.0}
275 offenders: dict[str, list[tuple[float, str, float, float]]] = {
276 "area": [],
277 "net": [],
278 "length": [],
279 }
280 moved_points = 0
281 lost_rings = 0
282
283 for key in shared:
284 a, b = before[key], after[key]
285 label = f"{key[0]} {key[1]}"
286
287 totals["features"][0] += a.features
288 totals["features"][1] += b.features
289 totals["rings"][0] += a.rings
290 totals["rings"][1] += b.rings
291 totals["points"][0] += a.points
292 totals["points"][1] += b.points
293 totals["area"][0] += a.area
294 totals["area"][1] += b.area
295 totals["net"][0] += a.net
296 totals["net"][1] += b.net
297 totals["length"][0] += a.length
298 totals["length"][1] += b.length
299
300 if a.features != b.features:
301 failures.append(f"{label}: features {a.features} vs {b.features}")
302 if a.geom != b.geom:
303 failures.append(f"{label}: geometry mix {a.geom} vs {b.geom}")
304 # Exact, and never budgeted. A lost ring is a lost hole, and a hole that
305 # disappears renders as a lake filled in solid -- the one failure mode this
306 # pipeline has always gated on. `geom=` counts features by TYPE and cannot
307 # see it, which is why this column exists.
308 if a.rings != b.rings:
309 lost_rings += 1
310 failures.append(
311 f"{label}: rings {a.rings} vs {b.rings} "
312 f"(net area {a.net:.2f} vs {b.net:.2f})"
313 )
314
315 for what, x, y in (
316 ("area", a.area, b.area),
317 ("net", a.net, b.net),
318 ("length", a.length, b.length),
319 ):
320 d = relative_delta(x, y)
321 worst[what] = max(worst[what], d)
322 # Kept with its identity, not just its size: "the worst area delta is
323 # 20%" is not actionable, and "it is this tile" is.
324 offenders[what].append((d, label, x, y))
325 if d > args.max_measure_delta:
326 failures.append(
327 f"{label}: {what} {x:.2f} vs {y:.2f} "
328 f"(relative {d:.3e} > {args.max_measure_delta:.0e})"
329 )
330
331 if a.points != b.points:
332 moved_points += 1
333 off = abs(b.points - a.points)
334 pct = off / max(a.points, 1) * 100.0
335 if off > args.point_slack and pct > args.max_point_delta:
336 failures.append(
337 f"{label}: points {a.points} vs {b.points} "
338 f"({pct:.2f}% > {args.max_point_delta:.2f}% budget, "
339 f"{off} > {args.point_slack} slack)"
340 )
341
342 print()
343 print(f"shared pairs : {len(shared):>9,}")
344 print(f"features : {totals['features'][0]:>9,} vs {totals['features'][1]:,}")
345 print(f"rings : {totals['rings'][0]:>9,} vs {totals['rings'][1]:,}")
346 print(f" pairs that lost or gained a ring: {lost_rings:,}")
347 print(f"points : {totals['points'][0]:>9,} vs {totals['points'][1]:,}")
348 point_delta = totals["points"][1] - totals["points"][0]
349 print(f" net point change : {point_delta:+,}")
350 print(f" pairs whose count moved: {moved_points:,}")
351 print(f"ring area (total) : {totals['area'][0]:.2f} vs {totals['area'][1]:.2f}")
352 print(f"net area (total) : {totals['net'][0]:.2f} vs {totals['net'][1]:.2f}")
353 print(f"line length (total) : {totals['length'][0]:.2f} vs {totals['length'][1]:.2f}")
354 print(f"worst relative area delta : {worst['area']:.3e}")
355 print(f"worst relative net delta : {worst['net']:.3e}")
356 print(f"worst relative length delta : {worst['length']:.3e}")
357
358 for what in ("area", "net", "length"):
359 top = sorted(offenders[what], reverse=True)[:5]
360 if top and top[0][0] > 0.0:
361 print(f"\nlargest {what} differences:")
362 for d, label, x, y in top:
363 if d == 0.0:
364 break
365 print(f" {label}: {x:.2f} vs {y:.2f} (relative {d:.3e})")
366
367 print()
368 if not failures:
369 print(f"OK: {len(shared):,} (tile, layer) pair(s) hold the same picture")
370 return 1 if churn_failed else 0
371 print(f"FAIL ({len(failures):,}):")
372 for f in failures[: args.max_report]:
373 print(f" {f}")
374 if len(failures) > args.max_report:
375 print(f" ... and {len(failures) - args.max_report:,} more")
376 return 1
377
378
379if __name__ == "__main__":
380 sys.exit(main())