"""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, 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.terminal_bench_scenario import LENGTH_COST if TYPE_CHECKING: from shapely.geometry import Polygon from inire import CapacityLimit, RoutingProblem, RoutingResult, RoutingTiming, TopologyReport from inire.router._routing_policy import Trial from inire.tests.routing_benchmarks 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) class RunSample: duration_s: float net_outcomes: dict[str, str] 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, ...] 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, ...] = () 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) 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), ) def _order_trials(problem: RoutingProblem, board: Polygon, options: RoutingOptions, strategy: str) -> 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) first = _trial(run, RoutingStage("seed", (), run.metrics.nodes_expanded, first_limit, net_order=first_order), board) 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: locked = tuple(shape for result in incumbents.values() for shape in result.locked_geometry) second_problem = replace( problem, nets=tuple(net for net in problem.nets if net.net_id not in incumbents), static_obstacles=problem.static_obstacles + locked, initial_paths={net_id: seed for net_id, seed in problem.initial_paths.items() if net_id not in incumbents}, ) else: second_problem = problem 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, board)] def _measure(case: BenchmarkCase, options: RoutingOptions, strategy: str) -> RunSample: board = box(*case.problem.bounds) started = perf_counter() bundle_rejection = None bundle_duration = None if strategy in AUTOMATIC_POLICIES: 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_score(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, 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, 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 = 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") else: bundle_duration = perf_counter() - started stage = RoutingStage("bundle", (), run.metrics.nodes_expanded, options.search.node_limit, kind="bundle") trials = [_trial(run, stage, board)] elif strategy in DIRECT_POLICIES: problem = case.fixed_headings_problem() trials = _direct_trials(problem, board, options, strategy) elif strategy in ORDER_POLICIES: problem = case.fixed_headings_problem() trials = _order_trials(problem, board, options, strategy) else: run = route(case.fixed_headings_problem(), options=options) trials = [_trial(run, RoutingStage(strategy, (), run.metrics.nodes_expanded, options.search.node_limit), board)] best = _best_trial(trials) duration = perf_counter() - started run = best.run 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, 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), 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" valid-net cost {sum(run.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: broader = (*VALIDATION_BENCHMARK_CASES, *FALLBACK_BENCHMARK_CASES, *EXTERNAL_BENCHMARK_CASES) case_groups = {case.name: (case,) for case in (*BENCHMARK_CASES, *broader, *CROSSING_BENCHMARK_CASES)} 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, } ) 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( "--case", choices=tuple(case_groups), action="append", help="Select a case or suite. The broad suite includes the holdout, fallback, and external suites.", ) 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, 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("--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("--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: for group, title in ( ("all", "Core corpus"), ("holdout", "Held-out boards"), ("fallback", "Fallback cases"), ("external", "External cases"), ("crossings", "Preplaced crossings"), ): print(f"{title} (--case {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: 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 try: topology = replace( defaults.topology, 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() 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") modes = tuple(dict.fromkeys(requested or default_modes)) for case in cases: base = _public_defaults(case, defaults) if use_public_defaults else case.options 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), 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, warm_start_enabled=not args.no_warm_start and defaults.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]) records.append( { "case": case.name, "strategy": mode, "requested_mode": mode_options[mode].topology.mode, "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, "runs": records, } args.json.write_text(dumps(payload, indent=2, default=_geometry_json) + "\n") if __name__ == "__main__": main()