"""Capture and compare exact automatic-routing benchmark results.""" from __future__ import annotations from argparse import ArgumentParser from concurrent.futures import ProcessPoolExecutor from dataclasses import asdict, replace from hashlib import sha256 from json import dumps, loads from pathlib import Path from time import perf_counter from typing import TYPE_CHECKING from shapely import to_wkb from inire import DiagnosticsOptions, route from inire.results import RouteMetrics from inire.tests.routing_corpus import ( CASE_GROUPS, PROFILES, automatic_options, benchmark_weighted_length, native_verified_costs, profile_options, select_cases, ) from scripts.compare_topological_routing import _geometry_json if TYPE_CHECKING: from inire import RoutingResult SCHEMA_VERSION = 2 STABLE_COUNTERS = tuple(name for name in RouteMetrics.__dataclass_fields__ if not name.endswith("_ns")) def _paths(results: dict[str, RoutingResult]) -> dict: return { "net_order": list(results), "nets": { net_id: { "outcome": result.outcome, "reached_target": result.reached_target, "seed": [{"kind": type(move).__name__, **asdict(move)} for move in result.as_seed().segments], "effective_net": asdict(result.effective_net) if result.effective_net is not None else None, "physical_polygon_hashes": [sha256(wkb).hexdigest() for wkb in to_wkb(result.locked_geometry, byte_order=1)], "report": asdict(result.report), } for net_id, result in results.items() }, } def _capture(job: tuple[str, str, bool, bool]) -> dict: name, profile, with_callback, with_diagnostics = job (case,) = CASE_GROUPS[name] options = automatic_options(profile_options(case, profile), profile) if with_diagnostics: options = replace( options, diagnostics=DiagnosticsOptions( capture_conflict_trace=True, capture_iteration_trace=True, capture_frontier_trace=True, capture_pre_pair_frontier_trace=True, ), ) callbacks = [] def notify(index: int, results: dict[str, RoutingResult]) -> None: callbacks.append({"index": index, **_paths(results)}) started = perf_counter() run = route(case.problem, options=options, iteration_callback=notify if with_callback else None) elapsed = perf_counter() - started report = run.automatic assert report is not None native_costs = native_verified_costs(case, options, run.results_by_net, report.verified_net_ids) costs = { net_id: {"native": cost, "benchmark_weighted_length": benchmark_weighted_length(run.results_by_net[net_id])} for net_id, cost in native_costs.items() } return { "case": name, "profile": profile, "with_callback": with_callback, "with_diagnostics": with_diagnostics, "elapsed_s": elapsed, "stable": { "options": asdict(options), **_paths(run.results_by_net), "costs": costs, "verified_net_ids": report.verified_net_ids, "automatic": asdict(replace(report, duration_s=0.0, timings=())), "timing_labels": [(item.operation, item.planner, item.mode, item.policy) for item in report.timings], "metrics": {field: getattr(run.metrics, field) for field in STABLE_COUNTERS}, "topology": asdict(run.topology) if run.topology is not None else None, "conflict_trace": [asdict(item) for item in run.conflict_trace], "frontier_trace": [asdict(item) for item in run.frontier_trace], "pre_pair_frontier_trace": asdict(run.pre_pair_frontier_trace) if run.pre_pair_frontier_trace is not None else None, "iteration_trace": [asdict(item) for item in run.iteration_trace], "callbacks": callbacks, }, } def _first_difference(expected: object, actual: object, field: str = "") -> str | None: if expected == actual: return None if isinstance(expected, dict) and isinstance(actual, dict): for key in dict.fromkeys((*expected, *actual)): path = f"{field}.{key}" if field else str(key) if key not in expected or key not in actual: return f"{path} exists on only one side" difference = _first_difference(expected[key], actual[key], path) if difference is not None: return difference if isinstance(expected, list) and isinstance(actual, list): for index, (left, right) in enumerate(zip(expected, actual, strict=False)): difference = _first_difference(left, right, f"{field}[{index}]") if difference is not None: return difference return f"{field} length is {len(expected)} before and {len(actual)} after" return f"{field} is {expected!r} before and {actual!r} after" def _read(path: Path) -> tuple[int, dict]: payload = loads(path.read_text(encoding="utf-8")) version = payload["schema_version"] if version not in (1, SCHEMA_VERSION): raise ValueError(f"Unsupported parity schema in {path}") rows = payload["runs"] by_key = {(row["case"], row["profile"], row["with_callback"], row["with_diagnostics"]): row for row in rows} if len(by_key) != len(rows): raise ValueError(f"Duplicate parity run in {path}") return version, by_key def _compare(before: Path, after: Path, allowed_counters: list[str]) -> int: before_version, baseline = _read(before) after_version, current = _read(after) if before_version != after_version: print(f"Parity schema mismatch ({before_version} and {after_version}). Capture both revisions with the same script version.") return 1 for key in sorted(baseline.keys() | current.keys()): label = f"{key[0]} / {key[1]} (callback={key[2]}, diagnostics={key[3]})" if key not in baseline or key not in current: print(f"{label}: run exists on only one side") return 1 expected, actual = baseline[key]["stable"], current[key]["stable"] for counter in allowed_counters: old, new = expected["metrics"].pop(counter), actual["metrics"].pop(counter) if old != new: print(f"{label}: allowed counter change {counter} from {old} to {new}") difference = _first_difference(expected, actual) if difference is not None: print(f"{label}: {difference}") return 1 print(f"{len(current)} runs match.") baseline_elapsed = sum(row["elapsed_s"] for row in baseline.values()) current_elapsed = sum(row["elapsed_s"] for row in current.values()) print(f"Sum of measured routing times: {baseline_elapsed:.3f}s before and {current_elapsed:.3f}s after.") return 0 def main() -> int: parser = ArgumentParser(description=__doc__) commands = parser.add_subparsers(dest="command", required=True) capture = commands.add_parser("capture") capture.add_argument("output", type=Path) capture.add_argument("--case", choices=tuple(CASE_GROUPS), action="append") capture.add_argument("--profile", choices=PROFILES, action="append") capture.add_argument("--callbacks", action="store_true", help="Also capture routing with an iteration callback.") capture.add_argument("--diagnostics", action="store_true", help="Enable conflict, frontier, and iteration traces.") capture.add_argument("--jobs", type=int, default=1) compare = commands.add_parser("compare") compare.add_argument("before", type=Path) compare.add_argument("after", type=Path) compare.add_argument("--allow-counter-change", choices=STABLE_COUNTERS, action="append", default=[]) args = parser.parse_args() if args.command == "compare": return _compare(args.before, args.after, list(dict.fromkeys(args.allow_counter_change))) if args.jobs < 1: parser.error("--jobs must be positive") cases = select_cases(args.case or ("corpus",)) profiles = dict.fromkeys(args.profile or ("corpus-regression", "public-defaults")) callback_modes = (False, True) if args.callbacks else (False,) jobs = [(case.name, profile, callback, args.diagnostics) for case in cases for profile in profiles for callback in callback_modes] if args.jobs == 1: rows = list(map(_capture, jobs)) else: with ProcessPoolExecutor(max_workers=args.jobs) as pool: rows = list(pool.map(_capture, jobs)) payload = {"schema_version": SCHEMA_VERSION, "runs": rows} args.output.write_text(dumps(payload, indent=2, default=_geometry_json) + "\n", encoding="utf-8") print(f"Captured {len(rows)} runs in {args.output}") return 0 if __name__ == "__main__": raise SystemExit(main())