Make retry exports optional and report benchmark placement and selection

This commit is contained in:
Jan Petykiewicz 2026-12-02 00:55:43 -08:00
commit f6e7bac4c5
3 changed files with 78 additions and 20 deletions

View file

@ -22,6 +22,7 @@ from inire.tests.routing_corpus import (
benchmark_weighted_length,
native_verified_costs,
profile_options,
route_placement,
select_cases,
)
@ -184,7 +185,7 @@ def _near_port_coverage_stalled(trials: list[Trial], target: int) -> bool:
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:
def _measure(case: BenchmarkCase, profile: str, name: str, *, capture_details: bool = True) -> dict:
options = automatic_options(profile_options(case, profile), profile)
retry_attempts: list[dict] = []
@ -205,14 +206,17 @@ def _measure(case: BenchmarkCase, profile: str, name: str) -> dict:
report = run.automatic
assert report is not None
verified = sorted(report.verified_net_ids)
summary = {"elapsed_s": elapsed, "verified": verified}
if not capture_details:
return summary
return {
"elapsed_s": elapsed,
"verified": verified,
**summary,
"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},
"placements": {net_id: route_placement(run.results_by_net[net_id]) for net_id in verified},
"stages": [asdict(stage) for stage in report.stages],
"selected_stage": report.selected_stage,
"retry_attempts": retry_attempts,
@ -220,13 +224,13 @@ def _measure(case: BenchmarkCase, profile: str, name: str) -> dict:
}
def _measure_case(job: tuple[BenchmarkCase, str, tuple[str, ...], int]) -> dict:
case, profile, policies, repeats = job
def _measure_case(job: tuple[BenchmarkCase, str, tuple[str, ...], int, bool]) -> dict:
case, profile, policies, repeats, capture_details = 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))
samples[name].append(_measure(case, profile, name, capture_details=capture_details))
return {"case": case.name, "profile": profile, "required": len(case.problem.nets), "samples": samples}
@ -237,24 +241,27 @@ def main() -> None:
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)
parser.add_argument("--json", type=Path, help="Write per-run coverage, placement, costs, and retry details to this file.")
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]
capture_details = args.json is not None
jobs = [(case, profile, policies, args.repeat, capture_details) 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)
if capture_details:
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 args.json is not None:
args.json.write_text(dumps({"runs": rows}, indent=2) + "\n", encoding="utf-8")
if __name__ == "__main__":

View file

@ -61,6 +61,7 @@ class RunSample:
bundle_rejection: str | None = None
bundle_duration_s: float | None = None
selected_stage: int = 0
selected_attempt: int | None = None
capacity_limit: CapacityLimit | None = None
planner_rejections: tuple[str, ...] = ()
port_conflicts: tuple[tuple[str, str], ...] = ()
@ -116,7 +117,17 @@ def _order_trials(problem: RoutingProblem, options: RoutingOptions, strategy: st
def _measure(case: BenchmarkCase, options: RoutingOptions, strategy: str) -> RunSample:
board = box(*case.problem.bounds)
attempt_options: list[RoutingOptions] = []
run_route = partial(_route, run_router=partial(_dispatch_route, attempt_callback=attempt_options.append))
selected_attempt: int | None = None
def select_attempt(index: int) -> None:
nonlocal selected_attempt
selected_attempt = index
dispatch = partial(
_dispatch_route, attempt_callback=attempt_options.append,
selected_attempt_callback=select_attempt if strategy in ("guide", "seed") else None,
)
run_route = partial(_route, run_router=dispatch)
run_worker = partial(route_once, attempt_callback=attempt_options.append)
def measure_direct(problem: RoutingProblem, policy: str) -> tuple[RoutingRunResult, list[Trial]]:
@ -203,6 +214,7 @@ def _measure(case: BenchmarkCase, options: RoutingOptions, strategy: str) -> Run
bundle_rejection=bundle_rejection,
bundle_duration_s=bundle_duration,
selected_stage=next(i for i, trial in enumerate(trials) if trial is best),
selected_attempt=selected_attempt,
)

View file

@ -5,14 +5,11 @@ 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 (
@ -22,6 +19,7 @@ from inire.tests.routing_corpus import (
benchmark_weighted_length,
native_verified_costs,
profile_options,
route_placement,
select_cases,
)
from scripts.compare_topological_routing import _geometry_json
@ -42,8 +40,7 @@ def _paths(results: dict[str, RoutingResult]) -> dict:
"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)],
**route_placement(result),
"report": asdict(result.report),
}
for net_id, result in results.items()