"""Compare the public routing modes on selected routing benchmarks.""" from __future__ import annotations from argparse import ArgumentParser from dataclasses import asdict, dataclass, replace from functools import partial from json import dumps from math import ceil, isfinite from pathlib import Path from platform import python_version from statistics import median from time import perf_counter from typing import TYPE_CHECKING import shapely from shapely.geometry import box, mapping 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 ( AUTOMATIC_POLICIES, CASE_GROUPS, EXAMPLE_NAMES, PROFILES, automatic_options, benchmark_weighted_length, native_verified_costs, profile_options, select_cases, ) if TYPE_CHECKING: from inire import CapacityLimit, RoutingProblem, RoutingRunResult, RoutingTiming, TopologyReport, _IterationCallback from inire.router._routing_policy import RouteCall, Trial 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") POLICIES = (*DIRECT_POLICIES, *ORDER_POLICIES, *BUNDLE_POLICIES, *AUTOMATIC_POLICIES) @dataclass(frozen=True, slots=True) 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 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 capacity_limit: CapacityLimit | None = None planner_rejections: tuple[str, ...] = () port_conflicts: tuple[tuple[str, str], ...] = () max_routed: int | None = None cost_pass_performed: bool = False timings: tuple[RoutingTiming, ...] = () _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) if strategy in POLICIES: return options return replace(options, topology=replace(options.topology, mode=strategy)) 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 = 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] second_order = "shortest" if first_order == "longest" else "longest" second_limit = limit - first_limit second_options = replace( first_options, search=replace(options.search, node_limit=second_limit), congestion=replace(options.congestion, net_order=second_order), ) incumbents = {net_id: run.results_by_net[net_id] for net_id in first.valid_costs} if strategy != "seed-order-restart" else {} if strategy == "seed-order-initial": seeds = {net_id: result.as_seed() for net_id, result in incumbents.items()} second_problem = replace(problem, initial_paths={**seeds, **problem.initial_paths}) elif strategy == "seed-order-locked" and incumbents: second_problem = _residual_problem(problem, LockPlan(incumbents)) else: second_problem = problem 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)) return [first, _trial(run, stage)] 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) def measure_direct(problem: RoutingProblem, policy: str) -> tuple[RoutingRunResult, list[Trial]]: trials: list[Trial] = [] def run_direct( prepared_problem: RoutingProblem, worker_options: RoutingOptions, _iteration_callback: _IterationCallback | None, ) -> RoutingRunResult: trials.extend(_direct_trials(prepared_problem, board, worker_options, policy, run_route=run_worker)) return _best_trial(trials).run run = _route(problem, options=options, run_router=run_direct) return run, trials started = perf_counter() bundle_rejection = None bundle_duration = None if strategy in AUTOMATIC_POLICIES: run = run_route(case.problem, options=options) report = run.automatic assert report is not None selected = report.stages[report.selected_stage] 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, 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, port_conflicts=report.port_conflicts, max_routed=report.max_routed, cost_pass_performed=report.cost_pass_performed, timings=report.timings, ) if strategy in BUNDLE_POLICIES: bundle_options = replace( options, topology=replace(options.topology, mode="bundle", infer_terminal_headings=case.options.topology.infer_terminal_headings), congestion=replace(options.congestion, max_iterations=1), refinement=replace(options.refinement, enabled=strategy == "bundle-first-refine"), ) try: run = run_route(case.problem, options=bundle_options) except ValueError as exc: bundle_rejection = str(exc) bundle_duration = perf_counter() - started run, trials = measure_direct(case.fixed_headings_problem(), "direct-probe-near-port") 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: run, trials = measure_direct(case.fixed_headings_problem(), strategy) elif strategy in ORDER_POLICIES: problem = case.fixed_headings_problem() trials = _order_trials(problem, options, strategy, run_route=run_route) run = _best_trial(trials).run else: 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 return RunSample( 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), 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), ) def _print_summary(mode: str, samples: list[RunSample]) -> None: run = samples[0] print( f" {mode}: {median(len(sample.valid_costs) for sample in samples):g}/{len(run.net_outcomes)} valid, " f"{median(len(sample.reached_net_ids) for sample in samples):g} reached, " f"{median(sample.nodes_expanded for sample in samples):g} A* nodes, " f"{median(sample.duration_s for sample in samples):.3f} s median", flush=True, ) if run.valid_costs: 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: print(f" bundle rejected; using direct-probe-near-port. {run.bundle_rejection}", flush=True) if mode in AUTOMATIC_POLICIES: selected = run.stages[run.selected_stage] policy = f", policy {selected.policy}" if selected.policy else "" print(f" selected {selected.planner}, mode {selected.mode}, operation {selected.operation}{policy}", flush=True) elapsed = { operation: median(sum(timing.duration_s for timing in sample.timings if timing.operation == operation) for sample in samples) for operation in ("plan", "verify", "search", "refine") } print(" median stage time " + ", ".join(f"{operation} {seconds:.3f} s" for operation, seconds in elapsed.items()), flush=True) if run.capacity_limit: limit = run.capacity_limit print( f" capacity {limit.tracks}/{limit.crossing_nets} across x={limit.cut_x:g}, at most {limit.max_routed} on the board", flush=True, ) if run.port_conflicts: print(f" port spacing limits board to {len(run.net_outcomes) - len(run.port_conflicts)} nets", flush=True) return if mode in POLICIES: for stage in run.stages: if stage.kind == "bundle": continue if stage.kind == "lattice-probe": print(f" unlocked lattice probe at {stage.node_limit} nodes per attempt", flush=True) continue if stage.net_order is not None: incumbents = f", carried {', '.join(stage.incumbent_net_ids)}" if stage.incumbent_net_ids else "" print(f" {stage.mode} at {stage.node_limit} nodes per attempt, order {stage.net_order}{incumbents}", flush=True) continue skipped = f", skipped {', '.join(stage.skipped_net_ids)}" if stage.skipped_net_ids else "" print( f" {stage.mode} at {stage.node_limit} nodes per attempt after locking {len(stage.direct_net_ids)} direct routes{skipped}", flush=True, ) if run.topology is not None: corridors = sum(count for _, count in run.topology.corridor_counts) seeds = ", ".join(run.topology.seeded_net_ids) or "none" print( f" {corridors} corridors across {len(run.topology.corridor_counts)} nets, " f"seeds {seeds}, {run.topology.seed_nodes_expanded} seed expansions", flush=True, ) def _geometry_json(value: object) -> dict: if isinstance(value, shapely.Polygon): return mapping(value) raise TypeError(f"Cannot serialize {type(value).__name__}") def main() -> None: parser = ArgumentParser(description=__doc__) 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(name for name in CASE_GROUPS if name not in EXAMPLE_NAMES), type=lambda name: EXAMPLE_NAMES.get(name, name), action="append", help="Select a case or suite. Use 'corpus' to select all boards.", ) parser.add_argument("--list", action="store_true", help="List the available cases.") parser.add_argument( "--mode", choices=("off", "guide", "seed", "automatic"), action="append", help="Repeat to compare modes. The public-defaults profile selects the shipped mode by default.", ) parser.add_argument("--policy", choices=POLICIES, action="append", help="Include a routing policy. Repeat to compare policies.") parser.add_argument("--nodes", type=int, action="append", help="Repeat to compare node budgets. The matched-budget profile defaults to 500.") 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) 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")) 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.") args = parser.parse_args() if args.list: print("All boards (--case corpus)") for group, title in ( ("all", "Core corpus"), ("holdout", "Held-out boards"), ("fallback", "Fallback cases"), ("external", "External cases"), ("crossings", "Preplaced crossings"), ("stress", "Stress cases"), ("geometry-corners", "Tight geometry"), ("complex-layouts", "Complex layouts"), ("search-challenges", "Search challenges"), ("scaling", "Large net and keepout counts"), ("retry-holdout", "Retry-policy holdouts"), ): print(f"{title} (--case {group})") for case in CASE_GROUPS[group]: name = EXAMPLE_NAMES.get(case.name, case.name) print(f" {name:40} {case.description}") return 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") refinement_overrides: dict[str, bool | int | None] = {} if args.refinement is not None: refinement_overrides["enabled"] = args.refinement == "on" if args.refinement_windows is not None: limit_error = "--refinement-windows must be a positive integer or 'unlimited'" try: limit = None if args.refinement_windows == "unlimited" else int(args.refinement_windows) except ValueError: parser.error(limit_error) if limit is not None and limit < 1: parser.error(limit_error) refinement_overrides["max_windows_per_net"] = limit topology_overrides = { name: value for name, value in ( ("max_corridors", args.max_corridors), ("guide_strength", args.guide_strength), ("seed_node_limit", args.seed_nodes), ) 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 = ("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 = 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: name = EXAMPLE_NAMES.get(case.name, case.name) print(f"{name} | {budget} nodes per attempt", flush=True) options = replace( base, topology=topology, search=replace( base.search, node_limit=budget, sbend_offsets=sbend_offsets if sbend_offsets is not None else base.search.sbend_offsets ), refinement=replace(base.refinement, **refinement_overrides), congestion=replace( base.congestion, max_iterations=iterations, 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} samples: dict[str, list[RunSample]] = {mode: [] for mode in modes} for repeat in range(args.repeat): offset = repeat % len(modes) for mode in modes[offset:] + modes[:offset]: 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": requested_mode, "grid_nm": case.grid_nm, "reference_net_ids": [net_id for net_id, _ in case.reference_paths], "options": asdict(mode_options[mode]), "samples": [asdict(sample) for sample in samples[mode]], "duration_s_median": median(sample.duration_s for sample in samples[mode]), "duration_s_p95": sorted(sample.duration_s for sample in samples[mode])[ceil(0.95 * len(samples[mode])) - 1], } ) if args.json is not None: payload = { "profile": args.profile, "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") if __name__ == "__main__": main()