Share routing preparation and report benchmark worker options

This commit is contained in:
Jan Petykiewicz 2026-12-01 22:58:43 -08:00
commit 8c8cbe569b
8 changed files with 152 additions and 43 deletions

View file

@ -43,6 +43,8 @@ List cases with `python -m scripts.compare_topological_routing --list`. Start wi
Both budget profiles use benchmark weights when selecting an automatic candidate. A stage can use a smaller budget, and a net can be searched more than once. Match the profile, options, and worker count when measuring a change.
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.
### Run the full benchmark corpus
```sh

View file

@ -54,6 +54,9 @@ if _shapely.geos_version < (3, 10, 0):
__author__ = 'Jan Petykiewicz'
__version__ = '0.1'
_IterationCallback = Callable[[int, dict[str, RoutingResult]], None]
_Router = Callable[[RoutingProblem, RoutingOptions, _IterationCallback | None], RoutingRunResult]
def _warn_bend_port_mismatches(results: dict[str, RoutingResult], nets: dict[str, NetSpec]) -> None:
checked = set()
@ -75,10 +78,27 @@ def _warn_bend_port_mismatches(results: dict[str, RoutingResult], nets: dict[str
warnings.warn(
f"Custom 90-degree bend of radius {move.radius:g} does not match the declared port faces "
f"of width {width:g} on net {net_id!r}",
stacklevel=3,
stacklevel=4,
)
def _dispatch_route(
problem: RoutingProblem,
options: RoutingOptions,
iteration_callback: _IterationCallback | None,
*,
attempt_callback: Callable[[RoutingOptions], None] | None = None,
) -> RoutingRunResult:
if options.topology.mode == "automatic":
from .router._automatic import route_automatic # noqa: PLC0415
return route_automatic(problem, options, iteration_callback, attempt_callback=attempt_callback)
from .router._stack import route_explicit # noqa: PLC0415
return route_explicit(problem, options=options, iteration_callback=iteration_callback, attempt_callback=attempt_callback)
def route(
problem: RoutingProblem,
*,
@ -86,7 +106,18 @@ def route(
iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None,
) -> RoutingRunResult:
resolved_options = RoutingOptions() if options is None else options
search = resolved_options.search
return _route(problem, options=resolved_options, iteration_callback=iteration_callback)
def _route(
problem: RoutingProblem,
*,
options: RoutingOptions,
iteration_callback: _IterationCallback | None = None,
run_router: _Router = _dispatch_route,
) -> RoutingRunResult:
"""Prepare inputs and attach diagnostics around a routing implementation."""
search = options.search
requested = {net.net_id: net for net in problem.nets}
coincident = {
net.net_id: RoutingResult(
@ -142,14 +173,7 @@ def route(
iteration_callback(iteration, attach_requested(results))
callback = notify if iteration_callback is not None else None
if resolved_options.topology.mode == "automatic":
from .router._automatic import route_automatic # noqa: PLC0415
run = route_automatic(problem, resolved_options, callback)
else:
from .router._stack import route_explicit # noqa: PLC0415
run = route_explicit(problem, options=resolved_options, iteration_callback=callback)
run = run_router(problem, options, callback)
results = attach_requested(run.results_by_net)
if coincident:
results = {net_id: results[net_id] for net_id in requested}

View file

@ -84,6 +84,8 @@ class _AutomaticRun:
problem: RoutingProblem,
options: RoutingOptions,
iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None,
*,
attempt_callback: Callable[[RoutingOptions], None] | None = None,
) -> None:
if any(not seed.segments for seed in problem.initial_paths.values()):
problem = replace(problem, initial_paths={net_id: seed for net_id, seed in problem.initial_paths.items() if seed.segments})
@ -91,7 +93,7 @@ class _AutomaticRun:
self.problem = problem
self.options = options
self.board = box(*problem.bounds)
self.attempts = RoutingAttempts(iteration_callback)
self.attempts = RoutingAttempts(iteration_callback, attempt_callback=attempt_callback)
self.timings: list[RoutingTiming] = []
self.cost_pass_performed = False
self.evaluator: CostEvaluator | None = None
@ -804,5 +806,7 @@ def route_automatic(
problem: RoutingProblem,
options: RoutingOptions,
iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None,
*,
attempt_callback: Callable[[RoutingOptions], None] | None = None,
) -> RoutingRunResult:
return _AutomaticRun(problem, options, iteration_callback).execute()
return _AutomaticRun(problem, options, iteration_callback, attempt_callback=attempt_callback).execute()

View file

@ -71,11 +71,14 @@ def route_once(
phase_timer: PhaseTimer | None = None,
corridors: dict[str, tuple[Corridor, ...]] | None = None,
iteration_offset: int = 0,
attempt_callback: Callable[[RoutingOptions], None] | None = None,
) -> RoutingRunResult:
"""Run one explicitly selected routing mode and capture its diagnostics."""
if options.topology.mode == "automatic":
raise ValueError("A single routing attempt requires an explicit planner mode")
if attempt_callback is not None:
attempt_callback(options)
started_at = time.monotonic()
finder = build_routing_stack(problem, options).finder
effective = {net.net_id: net for net in finder.context.problem.nets}
@ -116,8 +119,14 @@ def collect_worker_result(finder: PathFinder, results: dict[str, RoutingResult])
class RoutingAttempts:
"""Coordinate workers without retaining diagnostic data from discarded runs."""
def __init__(self, callback: Callable[[int, dict[str, RoutingResult]], None] | None) -> None:
def __init__(
self,
callback: Callable[[int, dict[str, RoutingResult]], None] | None,
*,
attempt_callback: Callable[[RoutingOptions], None] | None = None,
) -> None:
self.callback = callback
self.attempt_callback = attempt_callback
self.iterations = 0
self.samples: list[RouteMetrics] = []
@ -130,7 +139,7 @@ class RoutingAttempts:
) -> RoutingRunResult:
result = route_once(
problem, options=options, iteration_callback=self.callback, phase_timer=phase_timer,
iteration_offset=self.iterations,
iteration_offset=self.iterations, attempt_callback=self.attempt_callback,
)
self.iterations += result.metrics.route_iterations
self.samples.append(result.metrics)
@ -145,8 +154,9 @@ def route_explicit(
*,
options: RoutingOptions,
iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None,
attempt_callback: Callable[[RoutingOptions], None] | None = None,
) -> RoutingRunResult:
attempts = RoutingAttempts(iteration_callback)
attempts = RoutingAttempts(iteration_callback, attempt_callback=attempt_callback)
with_guidance = attempts.run(problem, options=options)
topology = options.topology
if (

View file

@ -25,7 +25,7 @@ if TYPE_CHECKING:
from shapely.geometry import Polygon
from inire import RoutingOptions, RoutingProblem, RoutingRunResult, RoutingStage
from inire.router._routing_policy import LockPlan, Trial
from inire.router._routing_policy import LockPlan, RouteCall, Trial
@dataclass(frozen=True, slots=True)
@ -56,17 +56,19 @@ _EXPERIMENTS = {
DIRECT_POLICIES = tuple(_EXPERIMENTS)
def direct_trials(problem: RoutingProblem, board: Polygon, options: RoutingOptions, strategy: str) -> list[Trial]:
def direct_trials(
problem: RoutingProblem, board: Polygon, options: RoutingOptions, strategy: str, *, run_route: RouteCall = route_once,
) -> list[Trial]:
experiment = _EXPERIMENTS[strategy]
summarize = partial(_trial, score=benchmark_weighted_length)
if experiment is None:
return _direct_trials(problem, board, options, strategy, check_trial=summarize)
return _direct_trials(problem, board, options, strategy, check_trial=summarize, run_route=run_route)
def check(run: RoutingRunResult, stage: RoutingStage) -> Trial:
return summarize(run, replace(stage, policy=strategy))
def run_residual(worker: RoutingOptions, locks: LockPlan) -> Trial:
return check(*_route_residual(problem, worker, locks, residual_mode=experiment.residual_mode))
return check(*_route_residual(problem, worker, locks, residual_mode=experiment.residual_mode, run_route=run_route))
plan = partial(_plan_locks, problem, board, options, check_connectivity=experiment.check_connectivity)
locks = plan()
@ -85,7 +87,7 @@ def direct_trials(problem: RoutingProblem, board: Polygon, options: RoutingOptio
trials = []
if probe_limit and experiment.probe == "first":
trials.append(_lattice_probe(problem, options, probe_limit, run_route=route_once, check_trial=check))
trials.append(_lattice_probe(problem, options, probe_limit, run_route=run_route, check_trial=check))
if len(trials[-1].valid_costs) == len(problem.nets):
return trials
@ -95,7 +97,7 @@ def direct_trials(problem: RoutingProblem, board: Polygon, options: RoutingOptio
return trials
if probe_limit and experiment.probe == "after":
trials.append(_lattice_probe(problem, options, probe_limit, run_route=route_once, check_trial=check))
trials.append(_lattice_probe(problem, options, probe_limit, run_route=run_route, check_trial=check))
if len(trials[-1].valid_costs) == len(problem.nets):
return trials

View file

@ -161,6 +161,8 @@ def test_benchmark_profile_records_effective_options(tmp_path, monkeypatch) -> N
assert options["objective"] == asdict(defaults.objective)
assert options["congestion"] == asdict(defaults.congestion)
assert options["topology"]["automatic_length_weights"] is None
[attempt] = sample["attempt_options"]
assert attempt == {**options, "topology": {**options["topology"], "mode": "off"}}
def test_retry_experiment_records_worker_expansions() -> None:
@ -175,6 +177,23 @@ def test_retry_experiment_records_worker_expansions() -> None:
assert len(sample["verified"]) == case.routing_bound
def test_retry_experiment_preserves_public_input_handling() -> None:
port = Port(10, 5, 0)
problem = RoutingProblem(
bounds=(0, 0, 100, 40),
nets=(NetSpec("coincident", port, port), NetSpec("straight", Port(10, 15, 0), Port(90, 15, 0))),
)
case = BenchmarkCase("coincident-control", "Coincident ports beside a straight route", problem, RoutingOptions())
baseline = _measure_retry(case, "matched-budget", "baseline")
experiment = _measure_retry(case, "matched-budget", "probe-iterations-2")
assert baseline["verified"] == experiment["verified"] == ["straight"]
assert baseline["routing_bound"] == experiment["routing_bound"] == 1
assert baseline["nodes_expanded"] == experiment["nodes_expanded"] == 0
assert baseline["stages"] == experiment["stages"]
def test_seed_order_locked_rejects_touching_routes_at_zero_clearance() -> None:
problem = RoutingProblem(
bounds=(0, 0, 100, 40),
@ -194,6 +213,9 @@ def test_seed_order_locked_rejects_touching_routes_at_zero_clearance() -> None:
assert retry.incumbent_net_ids == first.valid_net_ids
assert retry.valid_net_ids == first.valid_net_ids
assert sample.valid_costs.keys() == {"a"}
assert [(attempt.topology.mode, attempt.search.node_limit, attempt.congestion.net_order) for attempt in sample.attempt_options] == [
("seed", 30, "user"), ("seed", 30, "longest"),
]
def test_benchmark_native_cost_uses_configured_proximity_range() -> None:
@ -278,8 +300,25 @@ def test_point_terminal_replay_preserves_the_selected_port_headings() -> None:
assert all(result.is_valid and result.locked_geometry == paths[net_id].locked_geometry for net_id, result in replay.results_by_net.items())
def test_bundle_first_reports_capacity_failure_and_uses_the_generic_fallback() -> None:
def test_bundle_first_reports_effective_settings_and_capacity_fallback(tmp_path, monkeypatch) -> None:
original = next(case for case in BENCHMARK_CASES if case.name == "terminal-bench-point-terminals")
output = tmp_path / "benchmark.json"
monkeypatch.setattr(sys, "argv", [
"bench", "--case", original.name, "--policy", "bundle-first", "--iterations", "4", "--refinement", "on", "--json", str(output),
])
run_benchmarks()
[record] = loads(output.read_text())["runs"]
[success] = record["samples"]
[bundle] = success["attempt_options"]
assert record["requested_mode"] is None
assert record["options"]["congestion"]["max_iterations"] == 4
assert record["options"]["refinement"]["enabled"]
assert bundle["topology"]["mode"] == "bundle"
assert bundle["congestion"]["max_iterations"] == 1
assert not bundle["refinement"]["enabled"]
assert len(success["valid_costs"]) == len(original.problem.nets)
case = replace(original, problem=replace(original.problem, clearance=7))
options = replace(case.options, search=replace(case.options.search, node_limit=20))
@ -292,6 +331,8 @@ def test_bundle_first_reports_capacity_failure_and_uses_the_generic_fallback() -
assert sample.stages == fallback.stages
assert sample.net_outcomes == fallback.net_outcomes
assert sample.valid_costs == fallback.valid_costs
assert sample.attempt_options[0].topology.mode == "bundle"
assert sample.attempt_options[1:] == fallback.attempt_options
def test_automatic_retry_releases_a_lock_that_disconnects_the_remaining_net() -> None:

View file

@ -12,7 +12,7 @@ from statistics import median
from time import perf_counter
from typing import TYPE_CHECKING
from inire import route
from inire import _route, route
from inire.router._automatic import _AutomaticRun
from inire.router._routing_policy import LockPlan, _best_trial, _disconnected_nets, _route_residual
from inire.tests.routing_corpus import (
@ -28,8 +28,9 @@ from inire.tests.routing_corpus import (
if TYPE_CHECKING:
from typing import Literal
from inire import _IterationCallback
from inire.model import RoutingOptions, RoutingProblem
from inire.results import RoutingResult
from inire.results import RoutingResult, RoutingRunResult
from inire.router._routing_policy import Trial
from inire.seeds import PathSeed
from inire.tests.routing_benchmark_case import BenchmarkCase
@ -54,8 +55,14 @@ _POLICIES = {
class _RetryExperiment(_AutomaticRun):
def __init__(self, problem: RoutingProblem, options: RoutingOptions, policy: _RetryPolicy) -> None:
super().__init__(problem, options, None)
def __init__(
self,
problem: RoutingProblem,
options: RoutingOptions,
iteration_callback: _IterationCallback | None,
policy: _RetryPolicy,
) -> None:
super().__init__(problem, options, iteration_callback)
self.retry_policy = policy
self.retry_attempts: list[dict] = []
@ -179,12 +186,21 @@ def _near_port_coverage_stalled(trials: list[Trial], target: int) -> bool:
def _measure(case: BenchmarkCase, profile: str, name: str) -> dict:
options = automatic_options(profile_options(case, profile), profile)
retry_attempts: list[dict] = []
def run_experiment(
problem: RoutingProblem, options: RoutingOptions, iteration_callback: _IterationCallback | None,
) -> RoutingRunResult:
experiment = _RetryExperiment(problem, options, iteration_callback, _POLICIES[name])
run = experiment.execute()
retry_attempts.extend(experiment.retry_attempts)
return run
started = perf_counter()
experiment = None if name == "baseline" else _RetryExperiment(case.problem, options, _POLICIES[name])
if experiment is None:
if name == "baseline":
run = route(case.problem, options=options)
else:
run = experiment.execute()
run = _route(case.problem, options=options, run_router=run_experiment)
elapsed = perf_counter() - started
report = run.automatic
assert report is not None
@ -199,7 +215,7 @@ def _measure(case: BenchmarkCase, profile: str, name: str) -> dict:
"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,
"retry_attempts": retry_attempts,
"timings": [asdict(timing) for timing in report.timings],
}

View file

@ -16,9 +16,10 @@ from typing import TYPE_CHECKING
import shapely
from shapely.geometry import box, mapping
from inire import RoutingOptions, RoutingStage, route
from inire import RoutingOptions, RoutingStage, _dispatch_route, _route, route
from inire.router._routing_policy import LockPlan, _best_trial, _residual_problem
from inire.router._routing_policy import _trial as _summarize_trial
from inire.router._stack import route_once
from inire.tests.direct_routing_policies import DIRECT_POLICIES
from inire.tests.direct_routing_policies import direct_trials as _direct_trials
from inire.tests.routing_corpus import (
@ -35,7 +36,7 @@ from inire.tests.routing_corpus import (
if TYPE_CHECKING:
from inire import CapacityLimit, RoutingProblem, RoutingTiming, TopologyReport
from inire.router._routing_policy import Trial
from inire.router._routing_policy import RouteCall, Trial
from inire.tests.routing_benchmark_case import BenchmarkCase
@ -56,6 +57,7 @@ class RunSample:
route_iterations: int
topology: TopologyReport | None
stages: tuple[RoutingStage, ...]
attempt_options: tuple[RoutingOptions, ...]
bundle_rejection: str | None = None
bundle_duration_s: float | None = None
selected_stage: int = 0
@ -73,15 +75,17 @@ _trial = partial(_summarize_trial, score=benchmark_weighted_length)
def _mode_options(options: RoutingOptions, strategy: str, profile: str = "matched-budget") -> RoutingOptions:
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))
if strategy in POLICIES:
return options
return replace(options, topology=replace(options.topology, mode=strategy))
def _order_trials(problem: RoutingProblem, options: RoutingOptions, strategy: str) -> list[Trial]:
def _order_trials(problem: RoutingProblem, options: RoutingOptions, strategy: str, *, run_route: RouteCall = route) -> list[Trial]:
limit = options.search.node_limit
first_limit = max(1, limit // 2)
first_order = options.congestion.net_order
first_options = replace(options, search=replace(options.search, node_limit=first_limit), topology=replace(options.topology, mode="seed"))
run = route(problem, options=first_options)
run = run_route(problem, options=first_options)
first = _trial(run, RoutingStage("seed", (), run.metrics.nodes_expanded, first_limit, net_order=first_order))
if len(first.valid_costs) == len(problem.nets) or limit == 1:
return [first]
@ -102,7 +106,7 @@ def _order_trials(problem: RoutingProblem, options: RoutingOptions, strategy: st
else:
second_problem = problem
run = route(second_problem, options=second_options)
run = run_route(second_problem, options=second_options)
if strategy == "seed-order-locked":
run = replace(run, results_by_net={**incumbents, **run.results_by_net})
stage = RoutingStage("seed", (), run.metrics.nodes_expanded, second_limit, net_order=second_order, incumbent_net_ids=tuple(incumbents))
@ -111,11 +115,14 @@ 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))
run_worker = partial(route_once, attempt_callback=attempt_options.append)
started = perf_counter()
bundle_rejection = None
bundle_duration = None
if strategy in AUTOMATIC_POLICIES:
run = route(case.problem, options=options)
run = run_route(case.problem, options=options)
report = run.automatic
assert report is not None
selected = report.stages[report.selected_stage]
@ -131,6 +138,7 @@ def _measure(case: BenchmarkCase, options: RoutingOptions, strategy: str) -> Run
route_iterations=run.metrics.route_iterations,
topology=run.topology,
stages=report.stages,
attempt_options=tuple(attempt_options),
selected_stage=report.selected_stage,
capacity_limit=report.capacity_limit,
planner_rejections=report.planner_rejections,
@ -147,23 +155,23 @@ def _measure(case: BenchmarkCase, options: RoutingOptions, strategy: str) -> Run
refinement=replace(options.refinement, enabled=strategy == "bundle-first-refine"),
)
try:
run = route(case.problem, options=bundle_options)
run = run_route(case.problem, options=bundle_options)
except ValueError as exc:
bundle_rejection = str(exc)
bundle_duration = perf_counter() - started
trials = _direct_trials(case.fixed_headings_problem(), board, options, "direct-probe-near-port")
trials = _direct_trials(case.fixed_headings_problem(), board, options, "direct-probe-near-port", run_route=run_worker)
else:
bundle_duration = perf_counter() - started
stage = RoutingStage("bundle", (), run.metrics.nodes_expanded, options.search.node_limit, kind="bundle")
trials = [_trial(run, stage)]
elif strategy in DIRECT_POLICIES:
problem = case.fixed_headings_problem()
trials = _direct_trials(problem, board, options, strategy)
trials = _direct_trials(problem, board, options, strategy, run_route=run_worker)
elif strategy in ORDER_POLICIES:
problem = case.fixed_headings_problem()
trials = _order_trials(problem, options, strategy)
trials = _order_trials(problem, options, strategy, run_route=run_route)
else:
run = route(case.fixed_headings_problem(), options=options)
run = run_route(case.fixed_headings_problem(), options=options)
trials = [_trial(run, RoutingStage(strategy, (), run.metrics.nodes_expanded, options.search.node_limit))]
best = _best_trial(trials)
duration = perf_counter() - started
@ -179,6 +187,7 @@ def _measure(case: BenchmarkCase, options: RoutingOptions, strategy: str) -> Run
route_iterations=sum(trial.run.metrics.route_iterations for trial in trials),
topology=run.topology,
stages=tuple(trial.stage for trial in trials),
attempt_options=tuple(attempt_options),
bundle_rejection=bundle_rejection,
bundle_duration_s=bundle_duration,
selected_stage=next(i for i, trial in enumerate(trials) if trial is best),
@ -371,11 +380,12 @@ def main() -> None:
samples[mode].append(_measure(case, mode_options[mode], mode))
for mode in modes:
_print_summary(mode, samples[mode])
requested_mode = mode_options[mode].topology.mode if mode not in POLICIES or mode in AUTOMATIC_POLICIES else None
records.append(
{
"case": case.name,
"strategy": mode,
"requested_mode": mode_options[mode].topology.mode,
"requested_mode": requested_mode,
"grid_nm": case.grid_nm,
"reference_net_ids": [net_id for net_id, _ in case.reference_paths],
"options": asdict(mode_options[mode]),