diff --git a/docs/benchmarks.md b/docs/benchmarks.md index 59bc866..ab474e1 100644 --- a/docs/benchmarks.md +++ b/docs/benchmarks.md @@ -45,6 +45,8 @@ Both budget profiles use benchmark weights when selecting an automatic candidate Benchmark JSON records the configured options for each strategy. Each sample's `attempt_options` lists the effective options passed to routing workers in execution order, including rejected bundle attempts and any fallback workers. `requested_mode` is null for policies that choose their own mode for each attempt. +For explicit `guide` and `seed` runs, `selected_attempt` is the zero-based index into `attempt_options` of the worker whose routes were returned. + ### Run the full benchmark corpus ```sh @@ -83,7 +85,7 @@ python -m scripts.benchmark_retry_order \ --json /tmp/inire-residual.json ``` -Compare verified IDs, unchanged incumbents, and time spent on failed attempts. +Omit `--json` for a console summary. The optional JSON includes effective ports and polygon hashes for verified nets, so you can compare incumbent placement as well as coverage and time spent on failed attempts. - [Earlier retry results](benchmark-results.md#early-and-late-retries) diff --git a/inire/__init__.py b/inire/__init__.py index df4163e..2911e17 100644 --- a/inire/__init__.py +++ b/inire/__init__.py @@ -88,6 +88,7 @@ def _dispatch_route( iteration_callback: _IterationCallback | None, *, attempt_callback: Callable[[RoutingOptions], None] | None = None, + selected_attempt_callback: Callable[[int], None] | None = None, ) -> RoutingRunResult: if options.topology.mode == "automatic": from .router._automatic import route_automatic # noqa: PLC0415 @@ -96,7 +97,10 @@ def _dispatch_route( from .router._stack import route_explicit # noqa: PLC0415 - return route_explicit(problem, options=options, iteration_callback=iteration_callback, attempt_callback=attempt_callback) + return route_explicit( + problem, options=options, iteration_callback=iteration_callback, attempt_callback=attempt_callback, + selected_attempt_callback=selected_attempt_callback, + ) def route( diff --git a/inire/router/_stack.py b/inire/router/_stack.py index 1972238..e5ec67b 100644 --- a/inire/router/_stack.py +++ b/inire/router/_stack.py @@ -155,6 +155,7 @@ def route_explicit( options: RoutingOptions, iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None, attempt_callback: Callable[[RoutingOptions], None] | None = None, + selected_attempt_callback: Callable[[int], None] | None = None, ) -> RoutingRunResult: attempts = RoutingAttempts(iteration_callback, attempt_callback=attempt_callback) with_guidance = attempts.run(problem, options=options) @@ -165,6 +166,8 @@ def route_explicit( or with_guidance.metrics.timeout_events or not with_guidance.topology or not with_guidance.topology.corridor_counts or all(result.is_valid for result in with_guidance.results_by_net.values()) ): + if selected_attempt_callback is not None: + selected_attempt_callback(0) return with_guidance retry = replace( @@ -174,5 +177,8 @@ def route_explicit( without_guidance = attempts.run(problem, options=retry) old_count = sum(result.is_valid for result in with_guidance.results_by_net.values()) new_count = sum(result.is_valid for result in without_guidance.results_by_net.values()) - selected = without_guidance if new_count > old_count else with_guidance + retry_won = new_count > old_count + if selected_attempt_callback is not None: + selected_attempt_callback(int(retry_won)) + selected = without_guidance if retry_won else with_guidance return replace(selected, metrics=attempts.metrics()) diff --git a/inire/tests/routing_corpus.py b/inire/tests/routing_corpus.py index 14cbd21..a31f1fa 100644 --- a/inire/tests/routing_corpus.py +++ b/inire/tests/routing_corpus.py @@ -2,9 +2,12 @@ from __future__ import annotations -from dataclasses import replace +from dataclasses import asdict, replace +from hashlib import sha256 from typing import TYPE_CHECKING +from shapely import to_wkb + from inire import RoutingOptions from inire.router.cost import build_native_cost_evaluator, weighted_path_length from inire.tests.retry_holdout_benchmarks import RETRY_HOLDOUT_CASES @@ -134,6 +137,13 @@ def benchmark_weighted_length(result: RoutingResult) -> float: return weighted_path_length(result.path, LENGTH_COST) +def route_placement(result: RoutingResult) -> dict: + return { + "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)], + } + + def native_verified_costs( case: BenchmarkCase, options: RoutingOptions, diff --git a/inire/tests/test_routing_benchmarks.py b/inire/tests/test_routing_benchmarks.py index 4feeee2..e515565 100644 --- a/inire/tests/test_routing_benchmarks.py +++ b/inire/tests/test_routing_benchmarks.py @@ -192,6 +192,17 @@ def test_retry_experiment_preserves_public_input_handling() -> None: assert baseline["routing_bound"] == experiment["routing_bound"] == 1 assert baseline["nodes_expanded"] == experiment["nodes_expanded"] == 0 assert baseline["stages"] == experiment["stages"] + assert baseline["placements"] == experiment["placements"] + + coincident, straight = problem.nets + moved = replace(straight, start=straight.start.translate(dy=5), target=straight.target.translate(dy=5)) + moved_case = replace(case, problem=replace(problem, nets=(coincident, moved))) + shifted = _measure_retry(moved_case, "matched-budget", "baseline") + assert shifted["seeds"] == baseline["seeds"] + original_placement = baseline["placements"]["straight"] + moved_placement = shifted["placements"]["straight"] + assert moved_placement["effective_net"]["start"]["y"] == 20 + assert moved_placement["physical_polygon_hashes"] != original_placement["physical_polygon_hashes"] def test_direct_benchmarks_validate_inputs_before_locking_routes() -> None: diff --git a/inire/tests/test_topology.py b/inire/tests/test_topology.py index bb82252..37521d0 100644 --- a/inire/tests/test_topology.py +++ b/inire/tests/test_topology.py @@ -9,7 +9,9 @@ from inire import ( ) from inire.router._stack import build_routing_stack from inire.router._topology import _Assignment, _endpoint_access, _Mesh, _plan_lane_assignments, plan_corridors +from inire.tests.routing_benchmark_case import BenchmarkCase from inire.tests.routing_benchmarks import DETOUR +from scripts.compare_topological_routing import _measure def test_seed_mode_recovers_a_corridor_after_an_invalid_hint() -> None: @@ -135,6 +137,13 @@ def test_guidance_retry_can_change_an_incumbent_in_an_offset_gate() -> None: assert [entry.iteration for entry in run.conflict_trace if entry.stage == "iteration"] == [2] assert run.conflict_trace[-1].iteration is None + case = BenchmarkCase("guidance-retry", "Two offset gates", problem, options) + sample = _measure(case, options, mode) + + assert sample.valid_costs.keys() == {"a", "b"} + assert [attempt.topology.guide_strength for attempt in sample.attempt_options] == [0.75, 0.0] + assert sample.selected_attempt == 1 + def test_lane_assignment_keeps_mesh_path_order_on_equal_costs(monkeypatch: pytest.MonkeyPatch) -> None: problem = DETOUR.problem diff --git a/scripts/benchmark_retry_order.py b/scripts/benchmark_retry_order.py index 5645c3a..a761abc 100644 --- a/scripts/benchmark_retry_order.py +++ b/scripts/benchmark_retry_order.py @@ -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__": diff --git a/scripts/compare_topological_routing.py b/scripts/compare_topological_routing.py index ba035ff..128e3ec 100644 --- a/scripts/compare_topological_routing.py +++ b/scripts/compare_topological_routing.py @@ -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, ) diff --git a/scripts/routing_benchmark_parity.py b/scripts/routing_benchmark_parity.py index 8c152c0..ed060d7 100644 --- a/scripts/routing_benchmark_parity.py +++ b/scripts/routing_benchmark_parity.py @@ -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()