Refactor routing internals and archive retry benchmarks

This commit is contained in:
Jan Petykiewicz 2026-11-26 19:58:46 -08:00
commit ea5cfe7f31

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")