Refactor routing internals and archive retry benchmarks

This commit is contained in:
Jan Petykiewicz 2026-11-26 19:58:46 -08:00
commit ea5cfe7f31
10 changed files with 3481 additions and 2583 deletions

View file

@ -0,0 +1,285 @@
"""Compare opt-in automatic retry orders on the routing corpus."""
from __future__ import annotations
from argparse import ArgumentParser
from concurrent.futures import ProcessPoolExecutor
from dataclasses import asdict, dataclass, replace
from functools import partial
from json import dumps
from pathlib import Path
from statistics import median
from time import perf_counter
from typing import TYPE_CHECKING
from inire import route
from inire.router._automatic import _AutomaticRun, _INITIAL_NODE_LIMIT
from inire.router._routing_policy import LockPlan, _best_trial, _direct_trials, _disconnected_nets, _route_residual
from inire.tests.routing_corpus import (
CASE_GROUPS,
PROFILES,
automatic_options,
benchmark_weighted_length,
native_verified_costs,
profile_options,
select_cases,
)
if TYPE_CHECKING:
from inire.model import RoutingOptions, RoutingProblem
from inire.results import RoutingResult
from inire.router._routing_policy import Trial
from inire.tests.routing_benchmark_case import BenchmarkCase
@dataclass(frozen=True, slots=True)
class _RetryPolicy:
lattice_limit: int | None = None
recovery_stage: str | None = None
recovery_remaining: int = 1
probe_iterations: int | None = None
residual_limit: int | None = None
residual_after_fallback: bool = False
_POLICIES = {
"baseline": _RetryPolicy(),
**{f"lattice-{limit}": _RetryPolicy(lattice_limit=limit) for limit in (500, 750, 1000, 1500, 2000)},
"recover-lookahead": _RetryPolicy(recovery_stage="direct-lookahead-retry"),
"recover-near-port": _RetryPolicy(recovery_stage="direct-probe-near-port", recovery_remaining=2),
"lattice-1500-and-recover-near-port": _RetryPolicy(
lattice_limit=1500, recovery_stage="direct-probe-near-port", recovery_remaining=2
),
**{f"probe-iterations-{count}": _RetryPolicy(probe_iterations=count) for count in (1, 2, 3)},
**{f"residual-{limit}": _RetryPolicy(residual_limit=limit) for limit in (1500, 3000)},
"late-residual-3000": _RetryPolicy(residual_limit=3000, residual_after_fallback=True),
}
class _RetryExperiment(_AutomaticRun):
def __init__(self, problem: RoutingProblem, options: RoutingOptions, policy: _RetryPolicy) -> None:
super().__init__(problem, options, None)
self.retry_policy = policy
self.retry_attempts: list[dict] = []
def _record_retry(self, policy: str, outcome: str, started: float, first_run: int) -> None:
self.retry_attempts.append({
"policy": policy,
"outcome": outcome,
"elapsed_s": perf_counter() - started,
"nodes_expanded": sum(metrics.nodes_expanded for metrics in self.metrics[first_run:]),
})
def _search_trials(self, trials: list[Trial], target: int) -> None:
self.routing_bound = target
super()._search_trials(trials, target)
limit = self.retry_policy.residual_limit
if (
not self.retry_policy.residual_after_fallback
or limit is None
or limit > self.options.search.node_limit
or target != len(self.problem.nets)
or self.problem.initial_paths
):
return
best = _best_trial(trials)
if target <= 2 or len(best.valid_costs) != target - 1:
return
retained = {net_id: best.run.results_by_net[net_id] for net_id in best.valid_costs}
options = replace(self.options, refinement=replace(self.options.refinement, enabled=False))
trials.extend(self._widen_residual(options, retained, limit, target, policy="late-bounded-residual", check_connectivity=True))
def _recover_before_direct_retry(self, attempt: Trial, options: RoutingOptions) -> list[Trial]:
target = len(self.problem.nets)
verified = len(attempt.valid_costs)
if (
self.routing_bound < target
or target <= 2
or self.problem.initial_paths
or not 0 < target - verified <= self.retry_policy.recovery_remaining
or 3 * verified < 2 * target
):
return []
seeded = replace(
options,
search=replace(options.search, node_limit=min(_INITIAL_NODE_LIMIT, self.options.search.node_limit)),
congestion=replace(options.congestion, max_iterations=min(2, options.congestion.max_iterations)),
topology=replace(options.topology, mode="seed"),
)
started, first_run = perf_counter(), len(self.metrics)
recovered = self._incumbent_trials(seeded, attempt, target, retry_disconnected=False)
complete = any(candidate.selectable and len(candidate.valid_costs) == target for candidate in recovered)
outcome = "incomplete" if recovered else "disconnected"
self._record_retry("incumbent-recovery", "complete" if complete else outcome, started, first_run)
if complete:
return recovered
# Keep failed experimental work visible without changing the fallback incumbent.
return [replace(candidate, selection="incomplete-layout") for candidate in recovered]
def _direct(self, options: RoutingOptions, policy: str) -> list[Trial]:
if policy == "direct-probe-near-port" and self.retry_policy.probe_iterations is not None:
iterations = min(options.congestion.max_iterations, self.retry_policy.probe_iterations)
options = replace(options, congestion=replace(options.congestion, max_iterations=iterations))
if policy != self.retry_policy.recovery_stage:
return super()._direct(options, policy)
with self._time("plan", planner="direct", policy=policy):
return _direct_trials(
self.problem,
self.board,
options,
policy,
run_route=partial(self._run, policy=policy),
check_trial=self._trial,
recover_before_retry=partial(self._recover_before_direct_retry, options=options),
)
def _seed_recovery_trials(self, options: RoutingOptions, trials: list[Trial], target: int) -> None:
limit = self.retry_policy.lattice_limit
if (
limit is not None
and limit <= self.options.search.node_limit
and target == len(self.problem.nets) > 2
and not self.problem.initial_paths
and _near_port_coverage_stalled(trials, target)
):
retry = replace(options, search=replace(options.search, node_limit=limit))
started, first_run = perf_counter(), len(self.metrics)
self._lattice_fallback(trials, retry, "Near-port and lookahead searches were one net short", policy="early-bounded-lattice")
complete = len(trials[-1].valid_costs) == target
self._record_retry("bounded-lattice", "complete" if complete else "incomplete", started, first_run)
if complete:
return
trials[-1] = replace(trials[-1], selection="incomplete-layout")
super()._seed_recovery_trials(options, trials, target)
def _incumbent_trials(self, options: RoutingOptions, best: Trial, target: int, *, retry_disconnected: bool = True) -> list[Trial]:
trials = super()._incumbent_trials(options, best, target, retry_disconnected=retry_disconnected)
limit = self.retry_policy.residual_limit
if (
limit is None
or self.retry_policy.residual_after_fallback
or not options.search.node_limit < limit <= self.options.search.node_limit
or target != len(self.problem.nets)
or len(best.valid_costs) != target - 1
or not trials
or trials[0].stage.kind != "incumbent-residual"
or any(trial.selectable and len(trial.valid_costs) >= target for trial in trials)
):
return trials
retained = {net_id: best.run.results_by_net[net_id] for net_id in best.valid_costs}
return [*trials, *self._widen_residual(options, retained, limit, target, policy="bounded-residual")]
def _widen_residual(
self,
options: RoutingOptions,
retained: dict[str, RoutingResult],
limit: int,
target: int,
*,
policy: str,
check_connectivity: bool = False,
) -> list[Trial]:
started, first_run = perf_counter(), len(self.metrics)
if check_connectivity:
with self._time("plan", policy=policy):
blocked = _disconnected_nets(self.problem, self.board, options, retained)
if blocked:
self._record_retry(policy, "disconnected", started, first_run)
return []
retry = replace(
options,
search=replace(options.search, node_limit=limit),
topology=replace(options.topology, seed_node_limit=max(limit, options.topology.seed_node_limit)),
congestion=replace(options.congestion, max_iterations=min(2, options.congestion.max_iterations)),
)
run, stage = _route_residual(self.problem, retry, "direct-seed", LockPlan(retained), run_route=partial(self._run, policy=policy))
trial = self._trial(run, replace(stage, kind=policy, policy=policy, incumbent_net_ids=tuple(retained)))
trials = [replace(trial, selection="requires-layout-check")]
complete = False
if len(trial.valid_costs) == target:
verified = self._verify_incumbent(trial)
complete = len(verified.valid_costs) == target
trials.append(verified if complete else replace(verified, selection="incomplete-layout"))
self._record_retry(policy, "complete" if complete else "incomplete", started, first_run)
return trials
def _near_port_coverage_stalled(trials: list[Trial], target: int) -> bool:
near = [trial for trial in trials if trial.selectable and trial.stage.policy == "direct-probe-near-port"]
wider = [trial for trial in trials if trial.selectable and trial.stage.policy == "direct-lookahead-retry"]
if not near or not wider:
return False
first, second = _best_trial(near), _best_trial(wider)
return len(first.valid_costs) == target - 1 and first.valid_costs.keys() == second.valid_costs.keys()
def _measure(case: BenchmarkCase, profile: str, name: str) -> dict:
options = automatic_options(profile_options(case, profile), profile)
started = perf_counter()
experiment = None if name == "baseline" else _RetryExperiment(case.problem, options, _POLICIES[name])
if experiment is None:
run = route(case.problem, options=options)
else:
run = experiment.execute()
elapsed = perf_counter() - started
report = run.automatic
assert report is not None
verified = sorted(report.verified_net_ids)
return {
"elapsed_s": elapsed,
"verified": verified,
"routing_bound": report.max_routed,
"nodes_expanded": run.metrics.nodes_expanded,
"weighted_cost": {net_id: benchmark_weighted_length(run.results_by_net[net_id]) for net_id in verified},
"native_cost": native_verified_costs(case, options, run.results_by_net, verified),
"seeds": {net_id: repr(run.results_by_net[net_id].as_seed()) for net_id in verified},
"stages": [asdict(stage) for stage in report.stages],
"selected_stage": report.selected_stage,
"retry_attempts": [] if experiment is None else experiment.retry_attempts,
"timings": [asdict(timing) for timing in report.timings],
}
def _measure_case(job: tuple[BenchmarkCase, str, tuple[str, ...], int]) -> dict:
case, profile, policies, repeats = job
samples = {name: [] for name in policies}
for index in range(repeats):
offset = index % len(policies)
for name in policies[offset:] + policies[:offset]:
samples[name].append(_measure(case, profile, name))
return {"case": case.name, "profile": profile, "required": len(case.problem.nets), "samples": samples}
def main() -> None:
parser = ArgumentParser(description=__doc__)
parser.add_argument("--case", choices=tuple(CASE_GROUPS), action="append")
parser.add_argument("--profile", choices=PROFILES, action="append")
parser.add_argument("--policy", choices=tuple(_POLICIES), action="append")
parser.add_argument("--repeat", type=int, default=1)
parser.add_argument("--jobs", type=int, default=1)
parser.add_argument("--json", type=Path, required=True)
args = parser.parse_args()
if args.repeat < 1 or args.jobs < 1:
parser.error("--repeat and --jobs must be positive")
cases = select_cases(args.case or ["corpus"])
profiles = tuple(dict.fromkeys(args.profile or ("public-defaults", "corpus-regression")))
policies = tuple(dict.fromkeys(args.policy or _POLICIES))
jobs = [(case, profile, policies, args.repeat) for case in cases for profile in profiles]
rows = []
with ProcessPoolExecutor(max_workers=args.jobs) as pool:
for result in pool.map(_measure_case, jobs):
rows.append(result)
summary = " ".join(
f"{name}={len(samples[0]['verified'])}/{result['required']}@{median(s['elapsed_s'] for s in samples):.3f}s"
for name, samples in result["samples"].items()
)
print(result["case"], result["profile"], summary, flush=True)
args.json.write_text(dumps({"runs": rows}, indent=2) + "\n", encoding="utf-8")
if __name__ == "__main__":
main()

View file

@ -20,30 +20,27 @@ from inire import RoutingOptions, RoutingStage, route
from inire.router._routing_policy import DIRECT_POLICIES, _best_trial
from inire.router._routing_policy import _direct_trials as _run_direct_trials
from inire.router._routing_policy import _trial as _summarize_trial
from inire.tests.routing_benchmarks import (
BENCHMARK_CASES,
COMPLEX_BENCHMARK_CASES,
CROSSING_BENCHMARK_CASES,
EXTERNAL_BENCHMARK_CASES,
FALLBACK_BENCHMARK_CASES,
VALIDATION_BENCHMARK_CASES,
from inire.tests.routing_corpus import (
AUTOMATIC_POLICIES,
CASE_GROUPS,
PROFILES,
automatic_options,
benchmark_weighted_length,
native_verified_costs,
profile_options,
select_cases,
)
from inire.tests.stress_routing_benchmarks import STRESS_BENCHMARK_CASES
from inire.tests.terminal_bench_scenario import LENGTH_COST
if TYPE_CHECKING:
from shapely.geometry import Polygon
from inire import CapacityLimit, RoutingProblem, RoutingResult, RoutingTiming, TopologyReport
from inire import CapacityLimit, RoutingProblem, RoutingTiming, TopologyReport
from inire.router._routing_policy import Trial
from inire.tests.routing_benchmarks import BenchmarkCase
from inire.tests.routing_benchmark_case import BenchmarkCase
ORDER_POLICIES = ("seed-order-restart", "seed-order-initial", "seed-order-locked")
BUNDLE_POLICIES = ("bundle-first", "bundle-first-refine")
AUTOMATIC_COST_MODES = {"automatic": "selective", "automatic-span": "never", "automatic-weighted": "always"}
AUTOMATIC_POLICIES = tuple(AUTOMATIC_COST_MODES)
POLICIES = (*DIRECT_POLICIES, *ORDER_POLICIES, *BUNDLE_POLICIES, *AUTOMATIC_POLICIES)
PROFILES = ("matched-budget", "public-defaults")
@dataclass(frozen=True, slots=True)
@ -51,6 +48,7 @@ class RunSample:
duration_s: float
net_outcomes: dict[str, str]
valid_costs: dict[str, float]
native_valid_costs: dict[str, float]
reached_net_ids: tuple[str, ...]
out_of_bounds_net_ids: tuple[str, ...]
nodes_expanded: int
@ -68,51 +66,14 @@ class RunSample:
timings: tuple[RoutingTiming, ...] = ()
def _benchmark_score(result: RoutingResult) -> float:
return sum(component.length * LENGTH_COST[component.move_type] for component in result.path)
_trial = partial(_summarize_trial, score=_benchmark_score)
_direct_trials = partial(_run_direct_trials, score=_benchmark_score)
_trial = partial(_summarize_trial, score=benchmark_weighted_length)
_direct_trials = partial(_run_direct_trials, score=benchmark_weighted_length)
def _mode_options(options: RoutingOptions, strategy: str, profile: str = "matched-budget") -> RoutingOptions:
if strategy not in AUTOMATIC_POLICIES:
return replace(options, topology=replace(options.topology, mode="off" if strategy in POLICIES else strategy))
weights = options.topology.automatic_length_weights
if profile == "matched-budget":
weights = (LENGTH_COST["straight"], LENGTH_COST["bend90"], LENGTH_COST["sbend"])
cost_policy = options.topology.automatic_cost if profile == "public-defaults" and strategy == "automatic" else AUTOMATIC_COST_MODES[strategy]
return replace(
options,
topology=replace(
options.topology,
mode="automatic",
automatic_cost=cost_policy,
automatic_length_weights=weights,
),
)
def _public_defaults(case: BenchmarkCase, defaults: RoutingOptions) -> RoutingOptions:
geometry = case.options.search
return replace(
defaults,
search=replace(
defaults.search,
bend_radii=geometry.bend_radii,
sbend_radii=geometry.sbend_radii,
sbend_offsets=geometry.sbend_offsets,
bend_collision_type=geometry.bend_collision_type,
bend_proxy_geometry=geometry.bend_proxy_geometry,
bend_physical_geometry=geometry.bend_physical_geometry,
bend_clip_margin=geometry.bend_clip_margin,
min_straight_length=geometry.min_straight_length,
max_straight_length=geometry.max_straight_length,
),
topology=replace(defaults.topology, infer_terminal_headings=case.options.topology.infer_terminal_headings),
)
if strategy in AUTOMATIC_POLICIES:
return automatic_options(options, profile, strategy)
return replace(options, topology=replace(options.topology, mode="off" if strategy in POLICIES else strategy))
def _order_trials(problem: RoutingProblem, board: Polygon, options: RoutingOptions, strategy: str) -> list[Trial]:
@ -164,11 +125,12 @@ def _measure(case: BenchmarkCase, options: RoutingOptions, strategy: str) -> Run
report = run.automatic
assert report is not None
selected = report.stages[report.selected_stage]
valid_costs = {net_id: _benchmark_score(run.results_by_net[net_id]) for net_id in report.verified_net_ids}
valid_costs = {net_id: benchmark_weighted_length(run.results_by_net[net_id]) for net_id in report.verified_net_ids}
return RunSample(
duration_s=perf_counter() - started,
net_outcomes={net_id: result.outcome for net_id, result in run.results_by_net.items()},
valid_costs=valid_costs,
native_valid_costs=native_verified_costs(case, options, run.results_by_net, report.verified_net_ids),
reached_net_ids=tuple(net_id for net_id, result in run.results_by_net.items() if result.reached_target),
out_of_bounds_net_ids=selected.out_of_bounds_net_ids,
nodes_expanded=run.metrics.nodes_expanded,
@ -216,6 +178,7 @@ def _measure(case: BenchmarkCase, options: RoutingOptions, strategy: str) -> Run
duration_s=duration,
net_outcomes={net_id: result.outcome for net_id, result in run.results_by_net.items()},
valid_costs=best.valid_costs,
native_valid_costs=native_verified_costs(case, options, run.results_by_net, best.valid_costs),
reached_net_ids=tuple(net_id for net_id, result in run.results_by_net.items() if result.reached_target),
out_of_bounds_net_ids=best.stage.out_of_bounds_net_ids,
nodes_expanded=sum(trial.stage.nodes_expanded for trial in trials),
@ -238,7 +201,11 @@ def _print_summary(mode: str, samples: list[RunSample]) -> None:
flush=True,
)
if run.valid_costs:
print(f" valid-net cost {sum(run.valid_costs.values()):.2f}, nets {', '.join(run.valid_costs)}", flush=True)
print(
f" benchmark-weighted length {sum(run.valid_costs.values()):.2f}, "
f"native objective cost {sum(run.native_valid_costs.values()):.2f}, nets {', '.join(run.valid_costs)}",
flush=True,
)
if run.out_of_bounds_net_ids:
print(f" outside board {', '.join(run.out_of_bounds_net_ids)}", flush=True)
if run.bundle_rejection is not None:
@ -294,28 +261,13 @@ def _geometry_json(value: object) -> dict:
def main() -> None:
broader = (*VALIDATION_BENCHMARK_CASES, *FALLBACK_BENCHMARK_CASES, *EXTERNAL_BENCHMARK_CASES)
corpus = (*BENCHMARK_CASES, *broader, *CROSSING_BENCHMARK_CASES, *STRESS_BENCHMARK_CASES)
case_groups = {case.name: (case,) for case in corpus}
case_groups.update(
{
"all": BENCHMARK_CASES,
"complex": COMPLEX_BENCHMARK_CASES,
"holdout": VALIDATION_BENCHMARK_CASES,
"fallback": FALLBACK_BENCHMARK_CASES,
"external": EXTERNAL_BENCHMARK_CASES,
"broad": broader,
"crossings": CROSSING_BENCHMARK_CASES,
"stress": STRESS_BENCHMARK_CASES,
"corpus": corpus,
}
)
defaults = RoutingOptions()
parser = ArgumentParser(description=__doc__)
parser.add_argument("--profile", choices=PROFILES, default="matched-budget", help="Use controlled budgets or the public API defaults.")
parser.add_argument(
"--profile", choices=PROFILES, default="matched-budget", help="Use CLI budgets, API defaults, or pytest corpus settings."
)
parser.add_argument(
"--case",
choices=tuple(case_groups),
choices=tuple(CASE_GROUPS),
action="append",
help="Select a case or suite. Use 'corpus' to select all boards.",
)
@ -331,11 +283,11 @@ def main() -> None:
parser.add_argument("--iterations", type=int)
parser.add_argument("--refinement", choices=("on", "off"), help="Override refinement for public routing modes.")
parser.add_argument("--refinement-windows", metavar="N", help="Limit attempted windows per net, or use 'unlimited'.")
parser.add_argument("--max-corridors", type=int, default=defaults.topology.max_corridors)
parser.add_argument("--guide-strength", type=float, default=defaults.topology.guide_strength)
parser.add_argument("--seed-nodes", type=int, default=defaults.topology.seed_node_limit)
parser.add_argument("--max-corridors", type=int)
parser.add_argument("--guide-strength", type=float)
parser.add_argument("--seed-nodes", type=int)
parser.add_argument("--sbend-offset", type=float, action="append", help="Override search S-bend offsets. Repeat for multiple offsets.")
parser.add_argument("--net-order", choices=("user", "shortest", "longest"), default=defaults.congestion.net_order)
parser.add_argument("--net-order", choices=("user", "shortest", "longest"))
parser.add_argument("--no-warm-start", action="store_true")
parser.add_argument("--repeat", type=int, default=1, help="Run each configuration this many times and report median runtime.")
parser.add_argument("--json", type=Path, help="Write options and individual runs to this file.")
@ -349,16 +301,13 @@ def main() -> None:
("external", "External cases"),
("crossings", "Preplaced crossings"),
("stress", "Stress cases"),
("retry-holdout", "Retry-policy holdouts"),
):
print(f"{title} (--case {group})")
for case in case_groups[group]:
for case in CASE_GROUPS[group]:
print(f" {case.name:40} {case.description}")
return
use_public_defaults = args.profile == "public-defaults"
default_budget = defaults.search.node_limit if use_public_defaults else 500
budgets = tuple(dict.fromkeys(args.nodes or (default_budget,)))
iterations = args.iterations if args.iterations is not None else (defaults.congestion.max_iterations if use_public_defaults else 2)
if min(budgets) < 1 or iterations < 1 or args.repeat < 1:
if (args.nodes and min(args.nodes) < 1) or (args.iterations is not None and args.iterations < 1) or args.repeat < 1:
parser.error("--nodes, --iterations and --repeat must be positive")
if args.sbend_offset is not None and not all(isfinite(offset) for offset in args.sbend_offset):
parser.error("--sbend-offset must be finite")
@ -374,30 +323,34 @@ def main() -> None:
if limit is not None and limit < 1:
parser.error(limit_error)
refinement_overrides["max_windows_per_net"] = limit
try:
topology = replace(
defaults.topology,
max_corridors=args.max_corridors,
guide_strength=args.guide_strength,
seed_node_limit=args.seed_nodes,
topology_overrides = {
name: value
for name, value in (
("max_corridors", args.max_corridors),
("guide_strength", args.guide_strength),
("seed_node_limit", args.seed_nodes),
)
except ValueError as exc:
parser.error(str(exc))
groups = args.case or ["terminal-bench"]
cases = {case.name: case for group in groups for case in case_groups[group]}.values()
if value is not None
}
cases = select_cases(args.case or ["terminal-bench"])
sbend_offsets = tuple(args.sbend_offset) if args.sbend_offset is not None else None
records = []
requested = [*(args.mode or ()), *(args.policy or ())]
default_modes = (defaults.topology.mode,) if use_public_defaults else ("off", "guide", "seed")
default_modes = ("off", "guide", "seed") if args.profile == "matched-budget" else (RoutingOptions().topology.mode,)
modes = tuple(dict.fromkeys(requested or default_modes))
for case in cases:
base = _public_defaults(case, defaults) if use_public_defaults else case.options
base = profile_options(case, args.profile)
try:
topology = replace(base.topology, **topology_overrides)
except ValueError as exc:
parser.error(str(exc))
budgets = tuple(dict.fromkeys(args.nodes or (base.search.node_limit,)))
iterations = base.congestion.max_iterations if args.iterations is None else args.iterations
for budget in budgets:
print(f"{case.name} | {budget} nodes per attempt", flush=True)
options = replace(
base,
topology=replace(topology, infer_terminal_headings=base.topology.infer_terminal_headings),
topology=topology,
search=replace(
base.search, node_limit=budget, sbend_offsets=sbend_offsets if sbend_offsets is not None else base.search.sbend_offsets
),
@ -405,8 +358,8 @@ def main() -> None:
congestion=replace(
base.congestion,
max_iterations=iterations,
net_order=args.net_order,
warm_start_enabled=not args.no_warm_start and defaults.congestion.warm_start_enabled,
net_order=args.net_order or base.congestion.net_order,
warm_start_enabled=not args.no_warm_start and base.congestion.warm_start_enabled,
),
)
mode_options = {mode: _mode_options(options, mode, args.profile) for mode in modes}
@ -435,6 +388,7 @@ def main() -> None:
"python": python_version(),
"shapely": shapely.__version__,
"geos": shapely.geos_version_string,
"cost_metrics": {"valid_costs": "benchmark_weighted_length", "native_valid_costs": "native_objective"},
"runs": records,
}
args.json.write_text(dumps(payload, indent=2, default=_geometry_json) + "\n")

View file

@ -103,6 +103,7 @@ def _fixture(
*,
die: tuple[float, float, float, float] | None = None,
min_straight: float = 0.5,
expected_routed: int | None = None,
) -> dict:
if not connections:
raise ValueError(f"No compatible connections in {name}")
@ -150,6 +151,7 @@ def _fixture(
obstacles.append(encoded)
return {
"name": name,
**({"expected_routed": expected_routed} if expected_routed is not None else {}),
"source": source,
"member": member,
"crop_um": list(die),
@ -292,7 +294,8 @@ def _lidar_cases(archive: TarFile) -> list[dict]:
settings = netlist["settings"]
die = tuple(value for corner in settings["die_area"] for value in corner) if not selected else None
name = f"lidar-{settings['design'].replace('_', '-')}"
cases.append(_fixture(name, "lidar", member, devices, connections, settings["wg_radius"], 1.0, die=die))
expected_routed = 3 if name == "lidar-clements-8x8" else None
cases.append(_fixture(name, "lidar", member, devices, connections, settings["wg_radius"], 1.0, die=die, expected_routed=expected_routed))
return cases

View file

@ -1,82 +1,26 @@
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import json
from collections import Counter
from dataclasses import asdict
from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING
from inire.results import RoutingRunResult
from inire.tests.example_scenarios import TRACE_PERFORMANCE_SCENARIO_RUNS, TRACE_SCENARIO_RUNS
from inire.tests.trace_recording import NO_WARM_START_SCENARIOS, record_trace, result_summary
if TYPE_CHECKING:
from inire.results import RoutingRunResult
def _trace_registry(include_performance_only: bool) -> tuple[tuple[str, object], ...]:
if include_performance_only:
return TRACE_SCENARIO_RUNS + TRACE_PERFORMANCE_SCENARIO_RUNS
return TRACE_SCENARIO_RUNS
def _selected_runs(
selected_scenarios: tuple[str, ...] | None,
*,
include_performance_only: bool,
) -> tuple[tuple[str, object], ...]:
if selected_scenarios is None:
return (("example_07_large_scale_routing_no_warm_start", dict(TRACE_PERFORMANCE_SCENARIO_RUNS)["example_07_large_scale_routing_no_warm_start"]),)
registry = dict(TRACE_SCENARIO_RUNS + TRACE_PERFORMANCE_SCENARIO_RUNS)
allowed_standard = dict(_trace_registry(include_performance_only))
runs = []
for name in selected_scenarios:
if name in allowed_standard:
runs.append((name, allowed_standard[name]))
continue
if name in registry:
runs.append((name, registry[name]))
continue
valid = ", ".join(sorted(registry))
raise SystemExit(f"Unknown trace scenario: {name}. Valid scenarios: {valid}")
return tuple(runs)
def _result_summary(run: RoutingRunResult) -> dict[str, object]:
def _scenario_payload(result: RoutingRunResult) -> dict[str, object]:
return {
"total_results": len(run.results_by_net),
"valid_results": sum(1 for result in run.results_by_net.values() if result.is_valid),
"reached_targets": sum(1 for result in run.results_by_net.values() if result.reached_target),
"results_by_net": {
net_id: {
"outcome": result.outcome,
"reached_target": result.reached_target,
"report": asdict(result.report),
}
for net_id, result in run.results_by_net.items()
"summary": {
**result_summary(result),
"results_by_net": {
net_id: {"outcome": entry.outcome, "reached_target": entry.reached_target, "report": asdict(entry.report)}
for net_id, entry in result.results_by_net.items()
},
},
}
def _build_payload(
selected_scenarios: tuple[str, ...] | None,
*,
include_performance_only: bool,
) -> dict[str, object]:
scenarios = []
for name, run in _selected_runs(selected_scenarios, include_performance_only=include_performance_only):
result = run()
scenarios.append(
{
"name": name,
"summary": _result_summary(result),
"metrics": asdict(result.metrics),
"conflict_trace": [asdict(entry) for entry in result.conflict_trace],
}
)
return {
"generated_at": datetime.now().astimezone().isoformat(timespec="seconds"),
"generator": "scripts/record_conflict_trace.py",
"scenarios": scenarios,
"conflict_trace": [asdict(entry) for entry in result.conflict_trace],
}
@ -181,47 +125,14 @@ def _render_markdown(payload: dict[str, object]) -> str:
def main() -> None:
parser = argparse.ArgumentParser(description="Record conflict-trace artifacts for selected trace scenarios.")
parser.add_argument(
"--scenario",
action="append",
dest="scenarios",
default=[],
help="Optional trace scenario name to include. May be passed more than once.",
record_trace(
__file__,
"conflict_trace",
scenario_label="trace",
default_scenarios=NO_WARM_START_SCENARIOS[:1],
scenario_payload=_scenario_payload,
render_markdown=_render_markdown,
)
parser.add_argument(
"--include-performance-only",
action="store_true",
help="Include performance-only trace scenarios when selecting from the standard registry.",
)
parser.add_argument(
"--output-dir",
type=Path,
default=None,
help="Directory to write conflict_trace.json and conflict_trace.md into. Defaults to <repo>/docs.",
)
args = parser.parse_args()
repo_root = Path(__file__).resolve().parents[1]
output_dir = repo_root / "docs" if args.output_dir is None else args.output_dir.resolve()
output_dir.mkdir(exist_ok=True)
selected = tuple(args.scenarios) if args.scenarios else None
payload = _build_payload(selected, include_performance_only=args.include_performance_only)
json_path = output_dir / "conflict_trace.json"
markdown_path = output_dir / "conflict_trace.md"
json_path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n")
markdown_path.write_text(_render_markdown(payload) + "\n")
if json_path.is_relative_to(repo_root):
print(f"Wrote {json_path.relative_to(repo_root)}")
else:
print(f"Wrote {json_path}")
if markdown_path.is_relative_to(repo_root):
print(f"Wrote {markdown_path.relative_to(repo_root)}")
else:
print(f"Wrote {markdown_path}")
if __name__ == "__main__":

View file

@ -1,71 +1,18 @@
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import json
from collections import Counter
from dataclasses import asdict
from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING
from inire.tests.example_scenarios import TRACE_PERFORMANCE_SCENARIO_RUNS, TRACE_SCENARIO_RUNS
from inire.tests.trace_recording import NO_WARM_START_SCENARIOS, record_trace
if TYPE_CHECKING:
from inire.results import RoutingRunResult
def _trace_registry(include_performance_only: bool) -> tuple[tuple[str, object], ...]:
if include_performance_only:
return TRACE_SCENARIO_RUNS + TRACE_PERFORMANCE_SCENARIO_RUNS
return TRACE_SCENARIO_RUNS
def _selected_runs(
selected_scenarios: tuple[str, ...] | None,
*,
include_performance_only: bool,
) -> tuple[tuple[str, object], ...]:
if selected_scenarios is None:
default_registry = dict(TRACE_PERFORMANCE_SCENARIO_RUNS)
return (("example_07_large_scale_routing_no_warm_start", default_registry["example_07_large_scale_routing_no_warm_start"]),)
registry = dict(TRACE_SCENARIO_RUNS + TRACE_PERFORMANCE_SCENARIO_RUNS)
allowed_standard = dict(_trace_registry(include_performance_only))
runs = []
for name in selected_scenarios:
if name in allowed_standard:
runs.append((name, allowed_standard[name]))
continue
if name in registry:
runs.append((name, registry[name]))
continue
valid = ", ".join(sorted(registry))
raise SystemExit(f"Unknown trace scenario: {name}. Valid scenarios: {valid}")
return tuple(runs)
def _build_payload(
selected_scenarios: tuple[str, ...] | None,
*,
include_performance_only: bool,
) -> dict[str, object]:
scenarios = []
for name, run in _selected_runs(selected_scenarios, include_performance_only=include_performance_only):
result = run()
scenarios.append(
{
"name": name,
"summary": {
"total_results": len(result.results_by_net),
"valid_results": sum(1 for entry in result.results_by_net.values() if entry.is_valid),
"reached_targets": sum(1 for entry in result.results_by_net.values() if entry.reached_target),
},
"metrics": asdict(result.metrics),
"frontier_trace": [asdict(entry) for entry in result.frontier_trace],
}
)
return {
"generated_at": datetime.now().astimezone().isoformat(timespec="seconds"),
"generator": "scripts/record_frontier_trace.py",
"scenarios": scenarios,
}
def _scenario_payload(result: RoutingRunResult) -> dict[str, object]:
return {"frontier_trace": [asdict(entry) for entry in result.frontier_trace]}
def _render_markdown(payload: dict[str, object]) -> str:
@ -158,47 +105,14 @@ def _render_markdown(payload: dict[str, object]) -> str:
def main() -> None:
parser = argparse.ArgumentParser(description="Record frontier-trace artifacts for selected trace scenarios.")
parser.add_argument(
"--scenario",
action="append",
dest="scenarios",
default=[],
help="Optional trace scenario name to include. May be passed more than once.",
record_trace(
__file__,
"frontier_trace",
scenario_label="trace",
default_scenarios=NO_WARM_START_SCENARIOS[:1],
scenario_payload=_scenario_payload,
render_markdown=_render_markdown,
)
parser.add_argument(
"--include-performance-only",
action="store_true",
help="Include performance-only trace scenarios when selecting from the standard registry.",
)
parser.add_argument(
"--output-dir",
type=Path,
default=None,
help="Directory to write frontier_trace.json and frontier_trace.md into. Defaults to <repo>/docs.",
)
args = parser.parse_args()
repo_root = Path(__file__).resolve().parents[1]
output_dir = repo_root / "docs" if args.output_dir is None else args.output_dir.resolve()
output_dir.mkdir(exist_ok=True)
selected = tuple(args.scenarios) if args.scenarios else None
payload = _build_payload(selected, include_performance_only=args.include_performance_only)
json_path = output_dir / "frontier_trace.json"
markdown_path = output_dir / "frontier_trace.md"
json_path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n")
markdown_path.write_text(_render_markdown(payload) + "\n")
if json_path.is_relative_to(repo_root):
print(f"Wrote {json_path.relative_to(repo_root)}")
else:
print(f"Wrote {json_path}")
if markdown_path.is_relative_to(repo_root):
print(f"Wrote {markdown_path.relative_to(repo_root)}")
else:
print(f"Wrote {markdown_path}")
if __name__ == "__main__":

View file

@ -1,80 +1,18 @@
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import json
from collections import Counter
from dataclasses import asdict
from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING
from inire.tests.example_scenarios import TRACE_PERFORMANCE_SCENARIO_RUNS, TRACE_SCENARIO_RUNS
from inire.tests.trace_recording import NO_WARM_START_SCENARIOS, record_trace
if TYPE_CHECKING:
from inire.results import RoutingRunResult
def _trace_registry(include_performance_only: bool) -> tuple[tuple[str, object], ...]:
if include_performance_only:
return TRACE_SCENARIO_RUNS + TRACE_PERFORMANCE_SCENARIO_RUNS
return TRACE_SCENARIO_RUNS
def _selected_runs(
selected_scenarios: tuple[str, ...] | None,
*,
include_performance_only: bool,
) -> tuple[tuple[str, object], ...]:
if selected_scenarios is None:
perf_registry = dict(TRACE_PERFORMANCE_SCENARIO_RUNS)
return (
(
"example_07_large_scale_routing_no_warm_start",
perf_registry["example_07_large_scale_routing_no_warm_start"],
),
(
"example_07_large_scale_routing_no_warm_start_seed43",
perf_registry["example_07_large_scale_routing_no_warm_start_seed43"],
),
)
registry = dict(TRACE_SCENARIO_RUNS + TRACE_PERFORMANCE_SCENARIO_RUNS)
allowed_standard = dict(_trace_registry(include_performance_only))
runs = []
for name in selected_scenarios:
if name in allowed_standard:
runs.append((name, allowed_standard[name]))
continue
if name in registry:
runs.append((name, registry[name]))
continue
valid = ", ".join(sorted(registry))
raise SystemExit(f"Unknown iteration-trace scenario: {name}. Valid scenarios: {valid}")
return tuple(runs)
def _build_payload(
selected_scenarios: tuple[str, ...] | None,
*,
include_performance_only: bool,
) -> dict[str, object]:
scenarios = []
for name, run in _selected_runs(selected_scenarios, include_performance_only=include_performance_only):
result = run()
scenarios.append(
{
"name": name,
"summary": {
"total_results": len(result.results_by_net),
"valid_results": sum(1 for entry in result.results_by_net.values() if entry.is_valid),
"reached_targets": sum(1 for entry in result.results_by_net.values() if entry.reached_target),
},
"metrics": asdict(result.metrics),
"iteration_trace": [asdict(entry) for entry in result.iteration_trace],
}
)
return {
"generated_at": datetime.now().astimezone().isoformat(timespec="seconds"),
"generator": "scripts/record_iteration_trace.py",
"scenarios": scenarios,
}
def _scenario_payload(result: RoutingRunResult) -> dict[str, object]:
return {"iteration_trace": [asdict(entry) for entry in result.iteration_trace]}
def _render_markdown(payload: dict[str, object]) -> str:
@ -94,7 +32,8 @@ def _render_markdown(payload: dict[str, object]) -> str:
f"{scenario['summary']['reached_targets']} reached / "
f"{scenario['summary']['total_results']} total.",
"",
"| Iteration | Penalty | Routed Nets | Completed | Conflict Edges | Dynamic Collisions | Nodes | Congestion Checks | Candidate Ids | Exact Pairs |",
"| Iteration | Penalty | Routed Nets | Completed | Conflict Edges | Dynamic Collisions | "
"Nodes | Congestion Checks | Candidate Ids | Exact Pairs |",
"| --: | --: | --: | --: | --: | --: | --: | --: | --: | --: |",
]
)
@ -139,47 +78,14 @@ def _render_markdown(payload: dict[str, object]) -> str:
def main() -> None:
parser = argparse.ArgumentParser(description="Record iteration-trace artifacts for selected trace scenarios.")
parser.add_argument(
"--scenario",
action="append",
dest="scenarios",
default=[],
help="Optional trace scenario name to include. May be passed more than once.",
record_trace(
__file__,
"iteration_trace",
scenario_label="iteration-trace",
default_scenarios=NO_WARM_START_SCENARIOS,
scenario_payload=_scenario_payload,
render_markdown=_render_markdown,
)
parser.add_argument(
"--include-performance-only",
action="store_true",
help="Include performance-only trace scenarios when selecting from the standard registry.",
)
parser.add_argument(
"--output-dir",
type=Path,
default=None,
help="Directory to write iteration_trace.json and iteration_trace.md into. Defaults to <repo>/docs.",
)
args = parser.parse_args()
repo_root = Path(__file__).resolve().parents[1]
output_dir = repo_root / "docs" if args.output_dir is None else args.output_dir.resolve()
output_dir.mkdir(exist_ok=True)
selected = tuple(args.scenarios) if args.scenarios else None
payload = _build_payload(selected, include_performance_only=args.include_performance_only)
json_path = output_dir / "iteration_trace.json"
markdown_path = output_dir / "iteration_trace.md"
json_path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n")
markdown_path.write_text(_render_markdown(payload) + "\n")
if json_path.is_relative_to(repo_root):
print(f"Wrote {json_path.relative_to(repo_root)}")
else:
print(f"Wrote {json_path}")
if markdown_path.is_relative_to(repo_root):
print(f"Wrote {markdown_path.relative_to(repo_root)}")
else:
print(f"Wrote {markdown_path}")
if __name__ == "__main__":

View file

@ -58,7 +58,8 @@ def _render_markdown(payload: dict[str, object]) -> str:
"The full machine-readable snapshot lives in `docs/performance_baseline.json`.",
"Use `scripts/diff_performance_baseline.py` to compare a fresh run against that snapshot.",
"",
"| Scenario | Duration (s) | Total | Valid | Reached | Iter | Nets Routed | Nodes | Ray Casts | Moves Gen | Moves Added | Dyn Tree | Visibility Builds | Congestion Checks | Verify Calls |",
"| Scenario | Duration (s) | Total | Valid | Reached | Iter | Nets Routed | Nodes | Ray Casts | "
"Moves Gen | Moves Added | Dyn Tree | Visibility Builds | Congestion Checks | Verify Calls |",
"| :-- | --: | --: | --: | --: | --: | --: | --: | --: | --: | --: | --: | --: | --: | --: |",
]
for row in rows:
@ -87,7 +88,8 @@ def _render_markdown(payload: dict[str, object]) -> str:
"",
"## Full Counter Set",
"",
"Each scenario entry in `docs/performance_baseline.json` records the full `RouteMetrics` snapshot, including cache, index, congestion, and verification counters.",
"Each scenario entry in `docs/performance_baseline.json` records the full `RouteMetrics` snapshot, "
"including cache, index, congestion, and verification counters.",
"These counters are currently observational only and are not enforced as CI regression gates.",
"",
"Tracked metric keys:",

View file

@ -1,82 +1,19 @@
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import json
from collections import Counter
from dataclasses import asdict
from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING
from inire.tests.example_scenarios import TRACE_PERFORMANCE_SCENARIO_RUNS, TRACE_SCENARIO_RUNS
from inire.tests.trace_recording import NO_WARM_START_SCENARIOS, record_trace
if TYPE_CHECKING:
from inire.results import RoutingRunResult
def _trace_registry(include_performance_only: bool) -> tuple[tuple[str, object], ...]:
if include_performance_only:
return TRACE_SCENARIO_RUNS + TRACE_PERFORMANCE_SCENARIO_RUNS
return TRACE_SCENARIO_RUNS
def _selected_runs(
selected_scenarios: tuple[str, ...] | None,
*,
include_performance_only: bool,
) -> tuple[tuple[str, object], ...]:
if selected_scenarios is None:
perf_registry = dict(TRACE_PERFORMANCE_SCENARIO_RUNS)
return (
(
"example_07_large_scale_routing_no_warm_start",
perf_registry["example_07_large_scale_routing_no_warm_start"],
),
(
"example_07_large_scale_routing_no_warm_start_seed43",
perf_registry["example_07_large_scale_routing_no_warm_start_seed43"],
),
)
registry = dict(TRACE_SCENARIO_RUNS + TRACE_PERFORMANCE_SCENARIO_RUNS)
allowed_standard = dict(_trace_registry(include_performance_only))
runs = []
for name in selected_scenarios:
if name in allowed_standard:
runs.append((name, allowed_standard[name]))
continue
if name in registry:
runs.append((name, registry[name]))
continue
valid = ", ".join(sorted(registry))
raise SystemExit(f"Unknown pre-pair frontier-trace scenario: {name}. Valid scenarios: {valid}")
return tuple(runs)
def _build_payload(
selected_scenarios: tuple[str, ...] | None,
*,
include_performance_only: bool,
) -> dict[str, object]:
scenarios = []
for name, run in _selected_runs(selected_scenarios, include_performance_only=include_performance_only):
result = run()
scenarios.append(
{
"name": name,
"summary": {
"total_results": len(result.results_by_net),
"valid_results": sum(1 for entry in result.results_by_net.values() if entry.is_valid),
"reached_targets": sum(1 for entry in result.results_by_net.values() if entry.reached_target),
},
"metrics": asdict(result.metrics),
"pre_pair_frontier_trace": None
if result.pre_pair_frontier_trace is None
else asdict(result.pre_pair_frontier_trace),
}
)
return {
"generated_at": datetime.now().astimezone().isoformat(timespec="seconds"),
"generator": "scripts/record_pre_pair_frontier_trace.py",
"scenarios": scenarios,
}
def _scenario_payload(result: RoutingRunResult) -> dict[str, object]:
trace = result.pre_pair_frontier_trace
return {"pre_pair_frontier_trace": asdict(trace) if trace is not None else None}
def _render_markdown(payload: dict[str, object]) -> str:
@ -144,47 +81,14 @@ def _render_markdown(payload: dict[str, object]) -> str:
def main() -> None:
parser = argparse.ArgumentParser(description="Record pre-pair frontier-trace artifacts for selected trace scenarios.")
parser.add_argument(
"--scenario",
action="append",
dest="scenarios",
default=[],
help="Optional trace scenario name to include. May be passed more than once.",
record_trace(
__file__,
"pre_pair_frontier_trace",
scenario_label="pre-pair frontier-trace",
default_scenarios=NO_WARM_START_SCENARIOS,
scenario_payload=_scenario_payload,
render_markdown=_render_markdown,
)
parser.add_argument(
"--include-performance-only",
action="store_true",
help="Include performance-only trace scenarios when selecting from the standard registry.",
)
parser.add_argument(
"--output-dir",
type=Path,
default=None,
help="Directory to write pre_pair_frontier_trace.json and .md into. Defaults to <repo>/docs.",
)
args = parser.parse_args()
repo_root = Path(__file__).resolve().parents[1]
output_dir = repo_root / "docs" if args.output_dir is None else args.output_dir.resolve()
output_dir.mkdir(exist_ok=True)
selected = tuple(args.scenarios) if args.scenarios else None
payload = _build_payload(selected, include_performance_only=args.include_performance_only)
json_path = output_dir / "pre_pair_frontier_trace.json"
markdown_path = output_dir / "pre_pair_frontier_trace.md"
json_path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n")
markdown_path.write_text(_render_markdown(payload) + "\n")
if json_path.is_relative_to(repo_root):
print(f"Wrote {json_path.relative_to(repo_root)}")
else:
print(f"Wrote {json_path}")
if markdown_path.is_relative_to(repo_root):
print(f"Wrote {markdown_path.relative_to(repo_root)}")
else:
print(f"Wrote {markdown_path}")
if __name__ == "__main__":

View file

@ -10,6 +10,7 @@ from shapely.geometry import box
from inire import TopologyOptions, route
from inire.router._waypoints import export_waypoints
from inire.router.cost import weighted_path_length
from inire.tests.terminal_bench_scenario import LENGTH_COST, terminal_bench_options, terminal_bench_problem
@ -39,9 +40,9 @@ def main() -> None:
if not result.is_valid or any(not board.covers(shape) for shape in result.locked_geometry):
parser.exit(1, f"Lane plan failed inire verification for {net_id}\n")
cost = sum(component.length * LENGTH_COST[component.move_type] for result in run.results_by_net.values() for component in result.path)
cost = weighted_path_length((component for result in run.results_by_net.values() for component in result.path), LENGTH_COST)
total = len(problem.nets)
print(f"{total}/{total} verified, weighted cost {cost:.2f}, {run.metrics.nodes_expanded} A* expansions, {elapsed:.3f} s")
print(f"{total}/{total} verified, benchmark-weighted length {cost:.2f}, {run.metrics.nodes_expanded} A* expansions, {elapsed:.3f} s")
if args.output is not None:
waypoints = {net_id: export_waypoints(result.path) for net_id, result in run.results_by_net.items()}
args.output.write_text(dumps({"nets": {net_id: {"waypoints": path} for net_id, path in waypoints.items()}}, indent=2) + "\n")

View file

@ -0,0 +1,192 @@
"""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 json import dumps, loads
from pathlib import Path
from time import perf_counter
from typing import TYPE_CHECKING
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 = 1
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],
"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) -> dict:
payload = loads(path.read_text(encoding="utf-8"))
if payload["schema_version"] != 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 by_key
def _compare(before: Path, after: Path, allowed_counters: list[str]) -> int:
baseline, current = _read(before), _read(after)
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())