Retire routing archives and consolidate documentation tooling

Generate the guide, walkthrough, and gallery figures from one command. Keep benchmark fixtures and attribution with the tests and fold the durable findings from completed plans into the guides.
This commit is contained in:
Jan Petykiewicz 2026-12-02 20:33:19 -08:00
commit a05980e8af
16 changed files with 374 additions and 17204 deletions

View file

@ -1,268 +0,0 @@
"""Compare opt-in automatic retry orders on the routing corpus."""
from __future__ import annotations
from argparse import ArgumentParser
from concurrent.futures import ProcessPoolExecutor
from dataclasses import asdict, dataclass, replace
from functools import partial
from json import dumps
from pathlib import Path
from statistics import median
from time import perf_counter
from typing import TYPE_CHECKING
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 (
CASE_GROUPS,
PROFILES,
automatic_options,
benchmark_weighted_length,
native_verified_costs,
profile_options,
route_placement,
select_cases,
)
if TYPE_CHECKING:
from typing import Literal
from inire import _IterationCallback
from inire.model import RoutingOptions, RoutingProblem
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
@dataclass(frozen=True, slots=True)
class _RetryPolicy:
lattice_limit: int | None = None
probe_iterations: int | Literal["configured"] | None = None
residual_limit: int | None = None
residual_after_fallback: bool = False
_POLICIES = {
"baseline": _RetryPolicy(),
**{f"lattice-{limit}": _RetryPolicy(lattice_limit=limit) for limit in (500, 750, 1000, 1500, 2000)},
**{f"probe-iterations-{count}": _RetryPolicy(probe_iterations=count) for count in (1, 2, 3)},
"probe-full-budget": _RetryPolicy(probe_iterations="configured"),
**{f"residual-{limit}": _RetryPolicy(residual_limit=limit) for limit in (1500, 3000)},
"late-residual-3000": _RetryPolicy(residual_limit=3000, residual_after_fallback=True),
}
class _RetryExperiment(_AutomaticRun):
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] = []
def _record_retry(self, policy: str, outcome: str, started: float, first_attempt: int) -> None:
self.retry_attempts.append({
"policy": policy,
"outcome": outcome,
"elapsed_s": perf_counter() - started,
"nodes_expanded": sum(metrics.nodes_expanded for metrics in self.attempts.samples[first_attempt:]),
})
def _search_trials(self, trials: list[Trial], target: int) -> None:
super()._search_trials(trials, target)
limit = self.retry_policy.residual_limit
if (
not self.retry_policy.residual_after_fallback
or limit is None
or limit > self.options.search.node_limit
or target != len(self.problem.nets)
or self.problem.initial_paths
):
return
best = _best_trial(trials)
if target <= 2 or len(best.valid_costs) != target - 1:
return
retained = {net_id: best.run.results_by_net[net_id] for net_id in best.valid_costs}
options = replace(self.options, refinement=replace(self.options.refinement, enabled=False))
trials.extend(self._widen_residual(options, retained, limit, target, policy="late-bounded-residual", check_connectivity=True))
def _direct(self, options: RoutingOptions, policy: str, *, hints: dict[str, PathSeed] | None = None) -> list[Trial]:
cap = self.retry_policy.probe_iterations
if policy == "direct-probe-near-port" and cap is not None:
configured = self.options.congestion.max_iterations
iterations = configured if cap == "configured" else min(configured, cap)
if iterations != options.congestion.max_iterations:
options = replace(options, congestion=replace(options.congestion, max_iterations=iterations))
return super()._direct(options, policy, hints=hints)
def _seed_recovery_trials(self, options: RoutingOptions, trials: list[Trial], target: int) -> None:
limit = self.retry_policy.lattice_limit
if (
limit is not None
and limit <= self.options.search.node_limit
and target == len(self.problem.nets) > 2
and not self.problem.initial_paths
and _near_port_coverage_stalled(trials, target)
):
retry = replace(options, search=replace(options.search, node_limit=limit))
started, first_attempt = perf_counter(), len(self.attempts.samples)
self._lattice_fallback(trials, retry, "Near-port and lookahead searches were one net short", policy="early-bounded-lattice")
complete = len(trials[-1].valid_costs) == target
self._record_retry("bounded-lattice", "complete" if complete else "incomplete", started, first_attempt)
if complete:
return
trials[-1] = replace(trials[-1], selection="incomplete-layout")
super()._seed_recovery_trials(options, trials, target)
def _incumbent_trials(self, options: RoutingOptions, best: Trial, target: int) -> list[Trial]:
trials = super()._incumbent_trials(options, best, target)
limit = self.retry_policy.residual_limit
if (
limit is None
or self.retry_policy.residual_after_fallback
or not options.search.node_limit < limit <= self.options.search.node_limit
or target != len(self.problem.nets)
or len(best.valid_costs) != target - 1
or not trials
or trials[0].stage.kind != "incumbent-residual"
or any(trial.selectable and len(trial.valid_costs) >= target for trial in trials)
):
return trials
retained = {net_id: best.run.results_by_net[net_id] for net_id in best.valid_costs}
return [*trials, *self._widen_residual(options, retained, limit, target, policy="bounded-residual")]
def _widen_residual(
self,
options: RoutingOptions,
retained: dict[str, RoutingResult],
limit: int,
target: int,
*,
policy: str,
check_connectivity: bool = False,
) -> list[Trial]:
started, first_attempt = perf_counter(), len(self.attempts.samples)
if check_connectivity:
with self._time("plan", policy=policy):
blocked = _disconnected_nets(self.problem, self.board, options, retained)
if blocked:
self._record_retry(policy, "disconnected", started, first_attempt)
return []
retry = replace(
options,
search=replace(options.search, node_limit=limit),
topology=replace(options.topology, seed_node_limit=max(limit, options.topology.seed_node_limit)),
congestion=replace(options.congestion, max_iterations=min(2, options.congestion.max_iterations)),
)
run, stage = _route_residual(self.problem, retry, LockPlan(retained), residual_mode="seed", run_route=partial(self._run, policy=policy))
trial = self._trial(run, replace(stage, kind=policy, policy=policy, incumbent_net_ids=tuple(retained)))
trials = [replace(trial, selection="requires-layout-check")]
complete = False
if len(trial.valid_costs) == target:
verified = self._verify_incumbent(trial)
complete = len(verified.valid_costs) == target
trials.append(verified if complete else replace(verified, selection="incomplete-layout"))
self._record_retry(policy, "complete" if complete else "incomplete", started, first_attempt)
return trials
def _near_port_coverage_stalled(trials: list[Trial], target: int) -> bool:
near = [trial for trial in trials if trial.selectable and trial.stage.policy == "direct-probe-near-port"]
wider = [trial for trial in trials if trial.selectable and trial.stage.policy == "direct-lookahead-retry"]
if not near or not wider:
return False
first, second = _best_trial(near), _best_trial(wider)
return len(first.valid_costs) == target - 1 and first.valid_costs.keys() == second.valid_costs.keys()
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] = []
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()
if name == "baseline":
run = route(case.problem, options=options)
else:
run = _route(case.problem, options=options, run_router=run_experiment)
elapsed = perf_counter() - started
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 {
**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,
"timings": [asdict(timing) for timing in report.timings],
}
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, capture_details=capture_details))
return {"case": case.name, "profile": profile, "required": len(case.problem.nets), "samples": samples}
def main() -> None:
parser = ArgumentParser(description=__doc__)
parser.add_argument("--case", choices=tuple(CASE_GROUPS), action="append")
parser.add_argument("--profile", choices=PROFILES, action="append")
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, 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))
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):
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)
if args.json is not None:
args.json.write_text(dumps({"runs": rows}, indent=2) + "\n", encoding="utf-8")
if __name__ == "__main__":
main()

View file

@ -1,177 +0,0 @@
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import json
from dataclasses import asdict
from datetime import datetime
from pathlib import Path
from time import perf_counter
from inire.tests.example_scenarios import _run_example_07_variant
def _parse_csv_ints(raw: str) -> tuple[int, ...]:
return tuple(int(part) for part in raw.split(",") if part.strip())
def _run_case(num_nets: int, seed: int) -> dict[str, object]:
t0 = perf_counter()
run = _run_example_07_variant(
num_nets=num_nets,
seed=seed,
warm_start_enabled=False,
)
duration_s = perf_counter() - t0
return {
"duration_s": duration_s,
"summary": {
"total_results": len(run.results_by_net),
"valid_results": sum(1 for result in run.results_by_net.values() if result.is_valid),
"reached_targets": sum(1 for result in run.results_by_net.values() if result.reached_target),
},
"metrics": asdict(run.metrics),
}
def _is_smoke_candidate(entry: dict[str, object]) -> bool:
summary = entry["summary"]
metrics = entry["metrics"]
return (
summary["valid_results"] == summary["total_results"]
and metrics["pair_local_search_accepts"] >= 1
and entry["duration_s"] <= 1.0
)
def _select_smoke_case(cases: list[dict[str, object]]) -> dict[str, object] | None:
grouped: dict[tuple[int, int], list[dict[str, object]]] = {}
for case in cases:
key = (case["num_nets"], case["seed"])
grouped.setdefault(key, []).append(case)
candidates = []
for (num_nets, seed), repeats in grouped.items():
if repeats and all(_is_smoke_candidate(repeat) for repeat in repeats):
candidates.append({"num_nets": num_nets, "seed": seed})
if not candidates:
return None
candidates.sort(key=lambda item: (item["num_nets"], item["seed"]))
return candidates[0]
def _render_markdown(payload: dict[str, object]) -> str:
lines = [
"# Pair-Local Search Characterization",
"",
f"Generated at {payload['generated_at']} by `{payload['generator']}`.",
"",
f"Grid: `num_nets={payload['grid']['num_nets']}`, `seed={payload['grid']['seeds']}`, repeats={payload['grid']['repeats']}.",
"",
"| Nets | Seed | Repeat | Duration (s) | Valid | Reached | Pair Pairs | Pair Accepts | Pair Nodes | Nodes | Checks |",
"| :-- | :-- | :-- | --: | --: | --: | --: | --: | --: | --: | --: |",
]
for case in payload["cases"]:
summary = case["summary"]
metrics = case["metrics"]
lines.append(
"| "
f"{case['num_nets']} | "
f"{case['seed']} | "
f"{case['repeat']} | "
f"{case['duration_s']:.4f} | "
f"{summary['valid_results']} | "
f"{summary['reached_targets']} | "
f"{metrics['pair_local_search_pairs_considered']} | "
f"{metrics['pair_local_search_accepts']} | "
f"{metrics['pair_local_search_nodes_expanded']} | "
f"{metrics['nodes_expanded']} | "
f"{metrics['congestion_check_calls']} |"
)
lines.extend(["", "## Recommendation", ""])
recommended = payload["recommended_smoke_scenario"]
if recommended is None:
lines.append(
"No smaller stable pair-local smoke scenario satisfied the rule "
"`valid_results == total_results`, `pair_local_search_accepts >= 1`, and `duration_s <= 1.0` across all repeats."
)
else:
lines.append(
f"Recommended smoke scenario: `num_nets={recommended['num_nets']}`, `seed={recommended['seed']}`."
)
return "\n".join(lines)
def main() -> None:
parser = argparse.ArgumentParser(description="Characterize pair-local search across example_07-style no-warm runs.")
parser.add_argument(
"--num-nets",
default="6,8,10",
help="Comma-separated num_nets values to sweep. Default: 6,8,10.",
)
parser.add_argument(
"--seeds",
default="41,42,43",
help="Comma-separated seed values to sweep. Default: 41,42,43.",
)
parser.add_argument(
"--repeats",
type=int,
default=2,
help="Number of repeated runs per (num_nets, seed). Default: 2.",
)
parser.add_argument(
"--output-dir",
type=Path,
default=None,
help="Directory to write pair_local_characterization.json and .md into. Defaults to <repo>/archive/routing.",
)
args = parser.parse_args()
repo_root = Path(__file__).resolve().parents[1]
output_dir = repo_root / "archive" / "routing" if args.output_dir is None else args.output_dir.resolve()
output_dir.mkdir(parents=True, exist_ok=True)
num_nets_values = _parse_csv_ints(args.num_nets)
seed_values = _parse_csv_ints(args.seeds)
cases: list[dict[str, object]] = []
for num_nets in num_nets_values:
for seed in seed_values:
for repeat in range(args.repeats):
case = _run_case(num_nets, seed)
case["num_nets"] = num_nets
case["seed"] = seed
case["repeat"] = repeat
cases.append(case)
payload = {
"generated_at": datetime.now().astimezone().isoformat(timespec="seconds"),
"generator": "scripts/characterize_pair_local_search.py",
"grid": {
"num_nets": list(num_nets_values),
"seeds": list(seed_values),
"repeats": args.repeats,
},
"cases": cases,
"recommended_smoke_scenario": _select_smoke_case(cases),
}
json_path = output_dir / "pair_local_characterization.json"
markdown_path = output_dir / "pair_local_characterization.md"
json_path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n")
markdown_path.write_text(_render_markdown(payload) + "\n")
if json_path.is_relative_to(repo_root):
print(f"Wrote {json_path.relative_to(repo_root)}")
else:
print(f"Wrote {json_path}")
if markdown_path.is_relative_to(repo_root):
print(f"Wrote {markdown_path.relative_to(repo_root)}")
else:
print(f"Wrote {markdown_path}")
if __name__ == "__main__":
main()

View file

@ -1,434 +0,0 @@
"""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
selected_attempt: int | None = None
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] = []
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]]:
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),
selected_attempt=selected_attempt,
)
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()

View file

@ -1,232 +0,0 @@
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import json
from dataclasses import asdict
from datetime import datetime
from pathlib import Path
from inire.results import RouteMetrics
from inire.tests.example_scenarios import capture_scenario_snapshots
SUMMARY_KEYS = (
"duration_s",
"valid_results",
"reached_targets",
"route_iterations",
"nets_routed",
"nodes_expanded",
"ray_cast_calls",
"moves_generated",
"moves_added",
"congestion_check_calls",
"verify_path_report_calls",
)
def _available_metric_names() -> tuple[str, ...]:
return (
"duration_s",
"total_results",
"valid_results",
"reached_targets",
*RouteMetrics.__dataclass_fields__.keys(),
)
def _current_snapshots(
selected_scenarios: tuple[str, ...] | None,
*,
include_performance_only: bool,
baseline: dict[str, dict[str, object]],
) -> dict[str, dict[str, object]]:
snapshots = capture_scenario_snapshots(
selected_scenarios, include_performance_only=include_performance_only, baseline_scenarios=baseline.keys(),
)
return {snapshot.name: asdict(snapshot) for snapshot in snapshots}
def _load_baseline(path: Path, selected_scenarios: tuple[str, ...] | None) -> dict[str, dict[str, object]]:
payload = json.loads(path.read_text())
allowed = None if selected_scenarios is None else set(selected_scenarios)
return {
entry["name"]: entry
for entry in payload["scenarios"]
if allowed is None or entry["name"] in allowed
}
def _metric_value(snapshot: dict[str, object], key: str) -> float | None:
if key in {"duration_s", "total_results", "valid_results", "reached_targets"}:
return float(snapshot[key])
if key not in snapshot["metrics"]:
return None
return float(snapshot["metrics"][key])
def _validate_metrics(metric_names: tuple[str, ...]) -> None:
valid_names = set(_available_metric_names())
unknown = [name for name in metric_names if name not in valid_names]
if unknown:
raise SystemExit(
f"Unknown metric name(s): {', '.join(sorted(unknown))}. "
f"Valid names are: {', '.join(_available_metric_names())}"
)
def _render_report(
baseline: dict[str, dict[str, object]],
current: dict[str, dict[str, object]],
metric_names: tuple[str, ...],
) -> str:
scenario_names = sorted(set(baseline) | set(current))
lines = [
"# Performance Baseline Diff",
"",
"| Scenario | Metric | Baseline | Current | Delta |",
"| :-- | :-- | --: | --: | --: |",
]
for scenario in scenario_names:
base_snapshot = baseline.get(scenario)
curr_snapshot = current.get(scenario)
if base_snapshot is None:
if curr_snapshot is None:
lines.append(f"| {scenario} | added | - | - | - |")
continue
for key in metric_names:
curr_value = _metric_value(curr_snapshot, key)
if curr_value is None:
lines.append(f"| {scenario} | {key} | - | - | - |")
continue
lines.append(f"| {scenario} | {key} | - | {curr_value:.4f} | - |")
continue
if curr_snapshot is None:
lines.append(f"| {scenario} | missing | - | - | - |")
continue
for key in metric_names:
base_value = _metric_value(base_snapshot, key)
curr_value = _metric_value(curr_snapshot, key)
if base_value is None:
lines.append(
f"| {scenario} | {key} | - | {curr_value:.4f} | - |"
)
continue
if curr_value is None:
lines.append(
f"| {scenario} | {key} | {base_value:.4f} | - | - |"
)
continue
lines.append(
f"| {scenario} | {key} | {base_value:.4f} | {curr_value:.4f} | {curr_value - base_value:+.4f} |"
)
return "\n".join(lines) + "\n"
def _render_log_entry(
*,
baseline_path: Path,
label: str,
notes: tuple[str, ...],
report: str,
) -> str:
lines = [
f"## {label}",
"",
f"Measured on {datetime.now().astimezone().isoformat(timespec='seconds')}.",
f"Baseline: `{baseline_path}`.",
"",
]
if notes:
lines.extend(["Findings:", ""])
lines.extend(f"- {note}" for note in notes)
lines.append("")
lines.append(report.rstrip())
lines.append("")
return "\n".join(lines)
def main() -> None:
parser = argparse.ArgumentParser(description="Diff the committed performance baseline against a fresh run.")
parser.add_argument(
"--baseline",
type=Path,
default=Path("archive/routing/performance_baseline.json"),
help="Baseline JSON to compare against. Defaults to archive/routing/performance_baseline.json.",
)
parser.add_argument(
"--output",
type=Path,
default=None,
help="Optional file to write the report to. Defaults to stdout.",
)
parser.add_argument(
"--scenario",
action="append",
dest="scenarios",
default=[],
help="Optional scenario name to include. May be passed more than once.",
)
parser.add_argument(
"--metric",
action="append",
dest="metrics",
default=[],
help="Optional metric to include. May be passed more than once. Defaults to the summary metric set.",
)
parser.add_argument(
"--label",
default="Measurement",
help="Section label to use when appending to a log file.",
)
parser.add_argument(
"--notes",
action="append",
dest="notes",
default=[],
help="Optional short finding to append under the measurement section. May be passed more than once.",
)
parser.add_argument(
"--log",
type=Path,
default=None,
help="Optional Markdown log file to append the rendered report to.",
)
parser.add_argument(
"--include-performance-only",
action="store_true",
help="Include performance-only snapshot scenarios that are excluded from the default baseline corpus.",
)
args = parser.parse_args()
selected = tuple(args.scenarios) if args.scenarios else None
metrics = tuple(args.metrics) if args.metrics else SUMMARY_KEYS
_validate_metrics(metrics)
baseline = _load_baseline(args.baseline, selected)
try:
current = _current_snapshots(selected, include_performance_only=args.include_performance_only, baseline=baseline)
except ValueError as exc:
parser.error(str(exc))
report = _render_report(baseline, current, metrics)
if args.output is not None:
args.output.write_text(report)
print(f"Wrote {args.output}")
elif args.log is None:
print(report, end="")
if args.log is not None:
entry = _render_log_entry(
baseline_path=args.baseline,
label=args.label,
notes=tuple(args.notes),
report=report,
)
with args.log.open("a", encoding="utf-8") as handle:
handle.write(entry)
print(f"Appended {args.log}")
if __name__ == "__main__":
main()

View file

@ -1,52 +0,0 @@
"""Export the advanced example inputs from the canonical benchmark fixtures."""
from argparse import ArgumentParser
from json import dumps
from pathlib import Path
from examples.advanced_layouts import COMPLEX_EXAMPLE, COMPLEX_EXAMPLE_POINTS, INPUTS, build_problem
from inire.tests.routing_corpus import CASE_GROUPS, profile_options
from inire.tests.stress_routing_benchmarks import STRESS_BENCHMARK_CASES
def main() -> None:
parser = ArgumentParser(description=__doc__)
parser.add_argument("--output", type=Path, default=INPUTS)
args = parser.parse_args()
cases = [(case.name, case) for case in STRESS_BENCHMARK_CASES]
for name in (COMPLEX_EXAMPLE, COMPLEX_EXAMPLE_POINTS):
(case,) = CASE_GROUPS[name]
cases.append((name, case))
entries = []
for name, case in cases:
problem = case.problem
options = profile_options(case, "public-defaults")
data = {
"bounds": list(problem.bounds),
"clearance": problem.clearance,
"bend_radii": list(options.search.bend_radii),
"sbend_radii": list(options.search.sbend_radii),
"infer_terminal_headings": options.topology.infer_terminal_headings,
"keepouts": [polygon.wkt for polygon in problem.static_obstacles],
"nets": [(net.net_id, net.start.as_tuple(), net.target.as_tuple(), net.width) for net in problem.nets],
}
rebuilt, settings = build_problem(data)
if problem != rebuilt or options != settings:
raise ValueError(f"The advanced example no longer reproduces fixture {name}")
# Keep ports and each net on one line so the input file is easy to scan.
lines = [f" {dumps(name)}: {{"]
for field in ("bounds", "clearance", "bend_radii", "sbend_radii", "infer_terminal_headings"):
lines.append(f" {dumps(field)}: {dumps(data[field])},")
for field in ("keepouts", "nets"):
values = ",\n".join(f" {dumps(value)}" for value in data[field])
comma = "," if field == "keepouts" else ""
lines.append(f" {dumps(field)}: [\n{values}\n ]{comma}")
entries.append("\n".join((*lines, " }")))
args.output.write_text("{\n" + ",\n".join(entries) + "\n}\n", encoding="utf-8")
if __name__ == "__main__":
main()

View file

@ -1,327 +0,0 @@
"""Convert pinned PIC Routing Benchmark and LiDAR inputs into inire fixtures."""
from __future__ import annotations
from argparse import ArgumentParser
from collections import defaultdict
from csv import DictReader
from dataclasses import dataclass
from hashlib import file_digest
from json import dumps, loads
from math import ceil, floor
from pathlib import Path
from tarfile import TarFile
from typing import TYPE_CHECKING
from zipfile import ZipFile
from shapely import get_parts
from shapely.affinity import scale, translate
from shapely.geometry import Polygon, box
if TYPE_CHECKING:
from collections.abc import Callable, Iterable
from shapely.geometry.base import BaseGeometry
PIC_REVISION = "0c1f445792926d97fae01893c89e96b8a9393800"
LIDAR_REVISION = "4e7004d32b0b80d959553797fb30f0737513de0c"
PIC_DIGEST = "e4a9479a7fcabe64a0083bdab42a615e2200e7245ab5863a7bf109229d7ec588"
LIDAR_DIGEST = "cfd7a43762a9e71435d6d91a488f31ae1527c8752179805bdb4c345cb3089ba3"
UNITS_PER_MICRON = 10
HEADINGS = {"E": 0, "N": 90, "W": 180, "S": 270}
ROTATIONS = ((1, 0), (0, 1), (-1, 0), (0, -1))
OUTPUT = Path(__file__).resolve().parents[1] / "inire/tests/data/external_routing_benchmarks.json"
PIC_DESIGNS = (
"splitter_tree_1x8_ew",
"splitter_ring_mod_ap_combiner_2_ew",
"splitter_mzm_combiner_4_ew",
)
LIDAR_DESIGNS = {
"toy_example/toy_example.gp.yml": (),
"clements_8x8/clements_8x8.yml": tuple(f"n_{n}" for n in range(30, 36)),
"mrr_weight_bank_4x4/mrr_weight_bank_4x4.yml": tuple(f"n_{n}" for n in range(18, 26)),
}
@dataclass(frozen=True, slots=True)
class Pin:
x: float
y: float
heading: int
width: float
@dataclass(frozen=True, slots=True)
class Device:
footprints: tuple[Polygon, ...]
pins: dict[str, Pin]
Connection = tuple[str, tuple[str, str], tuple[str, str]]
def _rotate(x: float, y: float, angle: int) -> tuple[float, float]:
if angle % 90:
raise ValueError(f"Cannot import noncardinal rotation {angle}")
ux, uy = ROTATIONS[int(angle // 90) % 4]
return ux * x - uy * y, uy * x + ux * y
def _footprint(bounds: tuple[float, float, float, float], transform: Callable[[float, float], tuple[float, float]]) -> Polygon:
left, bottom, right, top = bounds
return Polygon([transform(left, bottom), transform(right, bottom), transform(right, top), transform(left, top)])
def _port_cutout(pin: Pin, width: float, clearance: float, extent: Polygon) -> Polygon:
# Carve access only from this port's own device. Allow one lattice unit
# for the snap from fractional source coordinates to inire's Port.
margin = width / 2 + clearance + 1 / UNITS_PER_MICRON
reach = max(extent.bounds[2] - extent.bounds[0], extent.bounds[3] - extent.bounds[1]) + 2 * margin
return _footprint((-margin, -margin, reach, margin), lambda x, y: _pin_frame(pin, x, y))
def _pin_frame(pin: Pin, x: float, y: float) -> tuple[float, float]:
dx, dy = _rotate(x, y, pin.heading)
return pin.x + dx, pin.y + dy
def _polygons(shape: BaseGeometry) -> Iterable[Polygon]:
for part in get_parts(shape):
if isinstance(part, Polygon) and not part.is_empty and part.area > 0:
yield part
def _fixture(
name: str,
source: str,
member: str,
devices: dict[str, Device],
connections: list[Connection],
radius: float,
clearance: float,
*,
die: tuple[float, float, float, float] | None = None,
min_straight: float = 0.5,
expected_routed: int | None = None,
) -> dict:
if not connections:
raise ValueError(f"No compatible connections in {name}")
active = {device for _, start, finish in connections for device, _ in (start, finish)}
if die is None:
bounds = [footprint.bounds for key in active for footprint in devices[key].footprints]
pad = 4 * radius
die = (
floor(min(b[0] for b in bounds) - pad),
floor(min(b[1] for b in bounds) - pad),
ceil(max(b[2] for b in bounds) + pad),
ceil(max(b[3] for b in bounds) + pad),
)
x0, y0, x1, y1 = die
board = box(*die)
cutouts: dict[str, list[Polygon]] = defaultdict(list)
nets = []
for net_id, (a, ap), (b, bp) in connections:
start, finish = devices[a].pins[ap], devices[b].pins[bp]
width = max(start.width, finish.width)
for key, pin in ((a, start), (b, finish)):
for footprint in devices[key].footprints:
cutouts[key].append(_port_cutout(pin, width, clearance, footprint))
nets.append(
{
"id": net_id,
"start": [round((start.x - x0) * UNITS_PER_MICRON), round((start.y - y0) * UNITS_PER_MICRON), start.heading],
"target": [round((finish.x - x0) * UNITS_PER_MICRON), round((finish.y - y0) * UNITS_PER_MICRON), (finish.heading + 180) % 360],
"width": round(width * UNITS_PER_MICRON, 6),
}
)
obstacles = []
for key, device in devices.items():
for footprint in device.footprints:
clipped = footprint.intersection(board)
for access in cutouts.get(key, ()):
clipped = clipped.difference(access)
for part in _polygons(clipped):
local = scale(translate(part, -x0, -y0), xfact=UNITS_PER_MICRON, yfact=UNITS_PER_MICRON, origin=(0, 0))
encoded = [[(round(x, 6), round(y, 6)) for x, y in ring.coords] for ring in (local.exterior, *local.interiors)]
polygon = Polygon(encoded[0], encoded[1:])
if polygon.area > 0:
if not polygon.is_valid:
raise ValueError(f"Invalid device geometry in {name}: {key}")
obstacles.append(encoded)
return {
"name": name,
**({"expected_routed": expected_routed} if expected_routed is not None else {}),
"source": source,
"member": member,
"crop_um": list(die),
"bounds": [0, 0, round((x1 - x0) * UNITS_PER_MICRON), round((y1 - y0) * UNITS_PER_MICRON)],
"bend_radius": radius * UNITS_PER_MICRON,
"clearance": clearance * UNITS_PER_MICRON,
"min_straight": min_straight * UNITS_PER_MICRON,
"obstacles": obstacles,
"nets": nets,
}
def _pic_transform(place: dict, x: float, y: float, *, position: bool = True) -> tuple[float, float]:
dx, dy = _rotate(-x if place["mirror_x"] else x, -y if place["mirror_y"] else y, place["orientation_deg"])
return (dx + place["x_um"], dy + place["y_um"]) if position else (dx, dy)
def _pic_device(cell: dict, place: dict, width: float) -> Device:
w, h = cell["bbox"]["width_um"], cell["bbox"]["height_um"]
outline = _footprint((-w / 2, -h / 2, w / 2, h / 2), lambda x, y: _pic_transform(place, x, y))
pins = {}
for name, port in cell["port_geometry"].items():
x, y = _pic_transform(place, port["x_um"], port["y_um"])
dx, dy = _pic_transform(place, *ROTATIONS[HEADINGS[port["orientation"]] // 90], position=False)
pins[name] = Pin(x, y, ROTATIONS.index((dx, dy)) * 90, width)
return Device((outline,), pins)
def _pic_macro(module: dict, pdk: dict, place: dict) -> Device:
# The selected designs use vertical edge-coupler arrays at the boundary.
# Their constituent boxes remain obstacles, while optical I/O is outside
# the primitive-to-primitive routing subproblem.
children = module["instances"]
attributes = module["attributes"]
if not (attributes["hard_macro"] and attributes["array_axis"] == "V" and all(child["module"] == "EDGE_COUPLER" for child in children)):
raise ValueError("Unsupported PIC macro in the selected design")
box_size = pdk["EDGE_COUPLER"]["bbox"]
w, h = box_size["width_um"], box_size["height_um"]
outlines = []
for i in range(len(children)):
row = (i - (len(children) - 1) / 2) * attributes["pitch"]
outlines.append(_footprint((-w / 2, row - h / 2, w / 2, row + h / 2), lambda x, y: _pic_transform(place, x, y)))
return Device(tuple(outlines), {})
def _pic_cases(archive: ZipFile) -> list[dict]:
root = "pic-benchmark"
pdk = loads(archive.read(f"{root}/pdk/pdk_v2_mzi80.json"))["device_defs"]
rules = loads(archive.read(f"{root}/pdk/design_rules_v2_mzi80.json"))["routing_rules"]
summary = list(DictReader(archive.read(f"{root}/data/_batch_summary.csv").decode().splitlines()))
cases = []
for design in PIC_DESIGNS:
result = next(row for row in summary if row["design"] == design and row["variant"] == "rectilinear")
if result["lvs_ok"] != "True" or result["drc_ok"] != "True" or int(result["n_crossings"]):
raise ValueError(f"Source variant failed the crossing-free LVS and DRC screen: {design}")
folder = f"{root}/data/{design}"
source = loads(archive.read(f"{folder}/{design}_netlist.json"))
member = f"{folder}/rectilinear/{design}_placement.json"
placements = {row["instance"]: row for row in loads(archive.read(member))["placements"]}
modules = source["modules"]
devices = {}
net_ports: dict[str, list[tuple[str, str, str]]] = defaultdict(list)
for inst in modules[source["top_module"]]["instances"]:
key, cell = inst["name"], inst["module"]
module = modules[cell]
if cell not in pdk:
devices[key] = _pic_macro(module, pdk, placements[key])
continue
devices[key] = _pic_device(pdk[cell], placements[key], rules["waveguide_width_um"])
directions = {port["name"]: port["direction"] for port in module["ports"]}
for port, wire in inst["connections"].items():
net_ports[wire].append((directions[port], key, port))
connections = []
for net_id, pins in sorted(net_ports.items()):
if len(pins) != 2:
continue
source_pin, sink_pin = sorted(pins, reverse=True)
if (source_pin[0], sink_pin[0]) != ("output", "input"):
raise ValueError(f"Expected a directed 2-pin net in {design}: {net_id}")
connections.append((net_id, (source_pin[1], source_pin[2]), (sink_pin[1], sink_pin[2])))
cases.append(
_fixture(
f"pic-{design.lower().replace('_', '-')}",
"pic-benchmark",
member,
devices,
connections,
rules["fixed_bend_radius_um"],
rules["min_spacing_um"],
min_straight=rules["min_straight_section_um"],
)
)
return cases
def _lidar_device(inst: dict, macro: dict) -> Device:
_, (x0, y0), orientation, _ = inst["settings"]["placement"]
w, h = macro["size"]
rotations = {"N": 0, "S": 180, "W": 90, "E": 270, "FN": 0, "FS": 0}
angle = rotations[orientation]
sx, sy = (-1 if orientation == "FN" else 1), (-1 if orientation == "FS" else 1)
rotated = [_rotate(sx * x, sy * y, angle) for x, y in ((0, 0), (w, 0), (w, h), (0, h))]
tx, ty = x0 - min(x for x, _ in rotated), y0 - min(y for _, y in rotated)
def transform(x: float, y: float) -> tuple[float, float]:
dx, dy = _rotate(sx * x, sy * y, angle)
return dx + tx, dy + ty
pins = {}
for name, port in (macro.get("pins") or {}).items():
px, py = transform(port["pin_offset_x"], port["pin_offset_y"])
hx, hy = _rotate(1, 0, port["pin_orient"])
heading = ROTATIONS.index(_rotate(sx * hx, sy * hy, angle)) * 90
pins[name] = Pin(px, py, heading, port["pin_width"])
return Device((_footprint((0, 0, w, h), transform),), pins)
def _lidar_cases(archive: TarFile) -> list[dict]:
import yaml # noqa: PLC0415
class BenchmarkLoader(yaml.SafeLoader):
"""Accept LiDAR's tuple-valued parameters as inert YAML sequences."""
BenchmarkLoader.add_constructor("tag:yaml.org,2002:python/tuple", yaml.SafeLoader.construct_sequence)
cases = []
for member, selected in LIDAR_DESIGNS.items():
path = f"LiDAR-{LIDAR_REVISION}/src/picroute/benchmarks/{member}"
source = archive.extractfile(path)
if source is None:
raise ValueError(f"Missing LiDAR input {member}")
with source:
netlist = yaml.load(source, Loader=BenchmarkLoader)
devices = {name: _lidar_device(inst, netlist["library"][inst["settings"]["macro_type"]]) for name, inst in netlist["instances"].items()}
connections = []
for net_id in selected or netlist["nets"]:
start, finish = netlist["nets"][net_id]
a, ap = start.split(",")
b, bp = finish.split(",")
connections.append((net_id, (a, ap), (b, bp)))
settings = netlist["settings"]
die = tuple(value for corner in settings["die_area"] for value in corner) if not selected else None
name = f"lidar-{settings['design'].replace('_', '-')}"
expected_routed = 3 if name == "lidar-clements-8x8" else None
cases.append(_fixture(name, "lidar", member, devices, connections, settings["wg_radius"], 1.0, die=die, expected_routed=expected_routed))
return cases
def _verify_archive(path: Path, expected: str) -> None:
with path.open("rb") as stream:
if file_digest(stream, "sha256").hexdigest() != expected:
raise ValueError(f"Archive does not match the pinned SHA-256: {path}")
def main() -> None:
parser = ArgumentParser(description=__doc__)
parser.add_argument("--pic-archive", type=Path, required=True)
parser.add_argument("--lidar-archive", type=Path, required=True)
parser.add_argument("--output", type=Path, default=OUTPUT)
args = parser.parse_args()
_verify_archive(args.pic_archive, PIC_DIGEST)
_verify_archive(args.lidar_archive, LIDAR_DIGEST)
with ZipFile(args.pic_archive) as pic, TarFile.open(args.lidar_archive) as lidar:
data = {
"units_per_micron": UNITS_PER_MICRON,
"revisions": {"pic-benchmark": PIC_REVISION, "lidar": LIDAR_REVISION},
"cases": [*_pic_cases(pic), *_lidar_cases(lidar)],
}
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(dumps(data, indent=2) + "\n", encoding="utf-8")
if __name__ == "__main__":
main()

View file

@ -1,139 +0,0 @@
#!/usr/bin/env python3
from __future__ import annotations
from collections import Counter
from dataclasses import asdict
from typing import TYPE_CHECKING
from inire.tests.trace_recording import NO_WARM_START_SCENARIOS, record_trace, result_summary
if TYPE_CHECKING:
from inire.results import RoutingRunResult
def _scenario_payload(result: RoutingRunResult) -> dict[str, object]:
return {
"summary": {
**result_summary(result),
"results_by_net": {
net_id: {"outcome": entry.outcome, "reached_target": entry.reached_target, "report": asdict(entry.report)}
for net_id, entry in result.results_by_net.items()
},
},
"conflict_trace": [asdict(entry) for entry in result.conflict_trace],
}
def _count_stage_nets(entry: dict[str, object]) -> int:
return sum(
1
for net in entry["nets"]
if net["report"]["dynamic_collision_count"] > 0
)
def _canonical_component_pair(
net_id: str,
self_component_index: int,
other_net_id: str,
other_component_index: int,
) -> tuple[tuple[str, int], tuple[str, int]]:
left = (net_id, self_component_index)
right = (other_net_id, other_component_index)
if left <= right:
return (left, right)
return (right, left)
def _render_markdown(payload: dict[str, object]) -> str:
lines = [
"# Conflict Trace",
"",
f"Generated at {payload['generated_at']} by `{payload['generator']}`.",
"",
]
for scenario in payload["scenarios"]:
lines.extend(
[
f"## {scenario['name']}",
"",
f"Results: {scenario['summary']['valid_results']} valid / "
f"{scenario['summary']['reached_targets']} reached / "
f"{scenario['summary']['total_results']} total.",
"",
"| Stage | Iteration | Conflicting Nets | Conflict Edges | Completed Nets |",
"| :-- | --: | --: | --: | --: |",
]
)
net_stage_counts: Counter[str] = Counter()
edge_counts: Counter[tuple[str, str]] = Counter()
component_pair_counts: Counter[tuple[tuple[str, int], tuple[str, int]]] = Counter()
trace_entries = scenario["conflict_trace"]
for entry in trace_entries:
lines.append(
"| "
f"{entry['stage']} | "
f"{'' if entry['iteration'] is None else entry['iteration']} | "
f"{_count_stage_nets(entry)} | "
f"{len(entry['conflict_edges'])} | "
f"{len(entry['completed_net_ids'])} |"
)
seen_component_pairs: set[tuple[tuple[str, int], tuple[str, int]]] = set()
for edge in entry["conflict_edges"]:
edge_counts[tuple(edge)] += 1
for net in entry["nets"]:
if net["report"]["dynamic_collision_count"] > 0:
net_stage_counts[net["net_id"]] += 1
for component_conflict in net["component_conflicts"]:
pair = _canonical_component_pair(
net["net_id"],
component_conflict["self_component_index"],
component_conflict["other_net_id"],
component_conflict["other_component_index"],
)
seen_component_pairs.add(pair)
for pair in seen_component_pairs:
component_pair_counts[pair] += 1
lines.extend(["", "Top nets by traced dynamic-collision stages:", ""])
if net_stage_counts:
for net_id, count in net_stage_counts.most_common(10):
lines.append(f"- `{net_id}`: {count}")
else:
lines.append("- None")
lines.extend(["", "Top net pairs by frequency:", ""])
if edge_counts:
for (left, right), count in edge_counts.most_common(10):
lines.append(f"- `{left}` <-> `{right}`: {count}")
else:
lines.append("- None")
lines.extend(["", "Top component pairs by frequency:", ""])
if component_pair_counts:
for pair, count in component_pair_counts.most_common(10):
(left_net, left_index), (right_net, right_index) = pair
lines.append(f"- `{left_net}[{left_index}]` <-> `{right_net}[{right_index}]`: {count}")
else:
lines.append("- None")
lines.append("")
return "\n".join(lines)
def main() -> None:
record_trace(
__file__,
"conflict_trace",
scenario_label="trace",
default_scenarios=NO_WARM_START_SCENARIOS[:1],
scenario_payload=_scenario_payload,
render_markdown=_render_markdown,
)
if __name__ == "__main__":
main()

View file

@ -1,119 +0,0 @@
#!/usr/bin/env python3
from __future__ import annotations
from collections import Counter
from dataclasses import asdict
from typing import TYPE_CHECKING
from inire.tests.trace_recording import NO_WARM_START_SCENARIOS, record_trace
if TYPE_CHECKING:
from inire.results import RoutingRunResult
def _scenario_payload(result: RoutingRunResult) -> dict[str, object]:
return {"frontier_trace": [asdict(entry) for entry in result.frontier_trace]}
def _render_markdown(payload: dict[str, object]) -> str:
lines = [
"# Frontier Trace",
"",
f"Generated at {payload['generated_at']} by `{payload['generator']}`.",
"",
]
for scenario in payload["scenarios"]:
lines.extend(
[
f"## {scenario['name']}",
"",
f"Results: {scenario['summary']['valid_results']} valid / "
f"{scenario['summary']['reached_targets']} reached / "
f"{scenario['summary']['total_results']} total.",
"",
"| Net | Hotspots | Closed-Set | Hard Collision | Self Collision | Cost | Samples |",
"| :-- | --: | --: | --: | --: | --: | --: |",
]
)
reason_counts: Counter[str] = Counter()
hotspot_counts: Counter[tuple[str, int]] = Counter()
for net_trace in scenario["frontier_trace"]:
sample_count = len(net_trace["samples"])
lines.append(
"| "
f"{net_trace['net_id']} | "
f"{len(net_trace['hotspot_bounds'])} | "
f"{net_trace['pruned_closed_set']} | "
f"{net_trace['pruned_hard_collision']} | "
f"{net_trace['pruned_self_collision']} | "
f"{net_trace['pruned_cost']} | "
f"{sample_count} |"
)
reason_counts["closed_set"] += net_trace["pruned_closed_set"]
reason_counts["hard_collision"] += net_trace["pruned_hard_collision"]
reason_counts["self_collision"] += net_trace["pruned_self_collision"]
reason_counts["cost"] += net_trace["pruned_cost"]
for sample in net_trace["samples"]:
hotspot_counts[(net_trace["net_id"], sample["hotspot_index"])] += 1
lines.extend(["", "Prune totals by reason:", ""])
if reason_counts:
for reason, count in reason_counts.most_common():
lines.append(f"- `{reason}`: {count}")
else:
lines.append("- None")
lines.extend(["", "Top traced hotspots by sample count:", ""])
if hotspot_counts:
for (net_id, hotspot_index), count in hotspot_counts.most_common(10):
lines.append(f"- `{net_id}` hotspot `{hotspot_index}`: {count}")
else:
lines.append("- None")
lines.extend(["", "Per-net sampled reason/move breakdown:", ""])
if scenario["frontier_trace"]:
for net_trace in scenario["frontier_trace"]:
reason_move_counts: Counter[tuple[str, str]] = Counter()
hotspot_sample_counts: Counter[int] = Counter()
for sample in net_trace["samples"]:
reason_move_counts[(sample["reason"], sample["move_type"])] += 1
hotspot_sample_counts[sample["hotspot_index"]] += 1
lines.append(f"- `{net_trace['net_id']}`")
if reason_move_counts:
top_pairs = ", ".join(
f"`{reason}` x `{move}` = {count}"
for (reason, move), count in reason_move_counts.most_common(3)
)
lines.append(f" sampled reasons: {top_pairs}")
else:
lines.append(" sampled reasons: none")
if hotspot_sample_counts:
top_hotspots = ", ".join(
f"`{hotspot}` = {count}" for hotspot, count in hotspot_sample_counts.most_common(3)
)
lines.append(f" hotspot samples: {top_hotspots}")
else:
lines.append(" hotspot samples: none")
else:
lines.append("- None")
lines.append("")
return "\n".join(lines)
def main() -> None:
record_trace(
__file__,
"frontier_trace",
scenario_label="trace",
default_scenarios=NO_WARM_START_SCENARIOS[:1],
scenario_payload=_scenario_payload,
render_markdown=_render_markdown,
)
if __name__ == "__main__":
main()

View file

@ -1,92 +0,0 @@
#!/usr/bin/env python3
from __future__ import annotations
from collections import Counter
from dataclasses import asdict
from typing import TYPE_CHECKING
from inire.tests.trace_recording import NO_WARM_START_SCENARIOS, record_trace
if TYPE_CHECKING:
from inire.results import RoutingRunResult
def _scenario_payload(result: RoutingRunResult) -> dict[str, object]:
return {"iteration_trace": [asdict(entry) for entry in result.iteration_trace]}
def _render_markdown(payload: dict[str, object]) -> str:
lines = [
"# Iteration Trace",
"",
f"Generated at {payload['generated_at']} by `{payload['generator']}`.",
"",
]
for scenario in payload["scenarios"]:
lines.extend(
[
f"## {scenario['name']}",
"",
f"Results: {scenario['summary']['valid_results']} valid / "
f"{scenario['summary']['reached_targets']} reached / "
f"{scenario['summary']['total_results']} total.",
"",
"| Iteration | Penalty | Routed Nets | Completed | Conflict Edges | Dynamic Collisions | "
"Nodes | Congestion Checks | Candidate Ids | Exact Pairs |",
"| --: | --: | --: | --: | --: | --: | --: | --: | --: | --: |",
]
)
net_node_counts: Counter[str] = Counter()
net_check_counts: Counter[str] = Counter()
for entry in scenario["iteration_trace"]:
lines.append(
"| "
f"{entry['iteration']} | "
f"{entry['congestion_penalty']:.1f} | "
f"{len(entry['routed_net_ids'])} | "
f"{entry['completed_nets']} | "
f"{entry['conflict_edges']} | "
f"{entry['total_dynamic_collisions']} | "
f"{entry['nodes_expanded']} | "
f"{entry['congestion_check_calls']} | "
f"{entry['congestion_candidate_ids']} | "
f"{entry['congestion_exact_pair_checks']} |"
)
for attempt in entry["net_attempts"]:
net_node_counts[attempt["net_id"]] += attempt["nodes_expanded"]
net_check_counts[attempt["net_id"]] += attempt["congestion_check_calls"]
lines.extend(["", "Top nets by iteration-attributed nodes expanded:", ""])
if net_node_counts:
for net_id, count in net_node_counts.most_common(10):
lines.append(f"- `{net_id}`: {count}")
else:
lines.append("- None")
lines.extend(["", "Top nets by iteration-attributed congestion checks:", ""])
if net_check_counts:
for net_id, count in net_check_counts.most_common(10):
lines.append(f"- `{net_id}`: {count}")
else:
lines.append("- None")
lines.append("")
return "\n".join(lines)
def main() -> None:
record_trace(
__file__,
"iteration_trace",
scenario_label="iteration-trace",
default_scenarios=NO_WARM_START_SCENARIOS,
scenario_payload=_scenario_payload,
render_markdown=_render_markdown,
)
if __name__ == "__main__":
main()

View file

@ -1,125 +0,0 @@
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import json
from dataclasses import asdict
from datetime import date
from pathlib import Path
from inire.tests.example_scenarios import capture_scenario_snapshots
def _build_payload(
selected_scenarios: tuple[str, ...] | None = None,
*,
include_performance_only: bool = False,
) -> dict[str, object]:
snapshots = capture_scenario_snapshots(selected_scenarios, include_performance_only=include_performance_only)
return {
"generated_on": date.today().isoformat(),
"generator": "scripts/record_performance_baseline.py",
"scenarios": [asdict(snapshot) for snapshot in snapshots],
}
def _render_markdown(payload: dict[str, object]) -> str:
rows = payload["scenarios"]
lines = [
"# Performance Baseline",
"",
f"Generated on {payload['generated_on']} by `{payload['generator']}`.",
"",
"The full machine-readable snapshot is in [performance_baseline.json](performance_baseline.json).",
"Use `scripts/diff_performance_baseline.py` to compare a fresh run against that snapshot.",
"",
"| Scenario | Duration (s) | Total | Valid | Reached | Iter | Nets Routed | Nodes | Ray Casts | "
"Moves Gen | Moves Added | Dyn Tree | Corner Index Builds | Congestion Checks | Verify Calls |",
"| :-- | --: | --: | --: | --: | --: | --: | --: | --: | --: | --: | --: | --: | --: | --: |",
]
for row in rows:
metrics = row["metrics"]
lines.append(
"| "
f"{row['name']} | "
f"{row['duration_s']:.4f} | "
f"{row['total_results']} | "
f"{row['valid_results']} | "
f"{row['reached_targets']} | "
f"{metrics['route_iterations']} | "
f"{metrics['nets_routed']} | "
f"{metrics['nodes_expanded']} | "
f"{metrics['ray_cast_calls']} | "
f"{metrics['moves_generated']} | "
f"{metrics['moves_added']} | "
f"{metrics['dynamic_tree_rebuilds']} | "
f"{metrics['visibility_corner_index_builds']} | "
f"{metrics['congestion_check_calls']} | "
f"{metrics['verify_path_report_calls']} |"
)
lines.extend(
[
"",
"## Full Counter Set",
"",
"Each scenario entry in the JSON records the full `RouteMetrics` snapshot, "
"including cache, index, congestion, and verification counters.",
"These counters are currently observational only and are not enforced as CI regression gates.",
"",
"Tracked metric keys:",
"",
", ".join(rows[0]["metrics"].keys()) if rows else "",
]
)
return "\n".join(lines) + "\n"
def main() -> None:
parser = argparse.ArgumentParser(description="Record the example-scenario performance baseline.")
parser.add_argument(
"--output-dir",
type=Path,
default=None,
help="Directory to write performance_baseline.json and performance.md into. Defaults to <repo>/archive/routing.",
)
parser.add_argument(
"--scenario",
action="append",
dest="scenarios",
default=[],
help="Optional scenario name to include. May be passed more than once.",
)
parser.add_argument(
"--include-performance-only",
action="store_true",
help="Include performance-only snapshot scenarios that are excluded from the default baseline corpus.",
)
args = parser.parse_args()
repo_root = Path(__file__).resolve().parents[1]
output_dir = repo_root / "archive" / "routing" if args.output_dir is None else args.output_dir.resolve()
selected = tuple(args.scenarios) if args.scenarios else None
try:
payload = _build_payload(selected, include_performance_only=args.include_performance_only)
except ValueError as exc:
parser.error(str(exc))
output_dir.mkdir(parents=True, exist_ok=True)
json_path = output_dir / "performance_baseline.json"
markdown_path = output_dir / "performance.md"
json_path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n")
markdown_path.write_text(_render_markdown(payload))
if json_path.is_relative_to(repo_root):
print(f"Wrote {json_path.relative_to(repo_root)}")
else:
print(f"Wrote {json_path}")
if markdown_path.is_relative_to(repo_root):
print(f"Wrote {markdown_path.relative_to(repo_root)}")
else:
print(f"Wrote {markdown_path}")
if __name__ == "__main__":
main()

View file

@ -1,95 +0,0 @@
#!/usr/bin/env python3
from __future__ import annotations
from collections import Counter
from dataclasses import asdict
from typing import TYPE_CHECKING
from inire.tests.trace_recording import NO_WARM_START_SCENARIOS, record_trace
if TYPE_CHECKING:
from inire.results import RoutingRunResult
def _scenario_payload(result: RoutingRunResult) -> dict[str, object]:
trace = result.pre_pair_frontier_trace
return {"pre_pair_frontier_trace": asdict(trace) if trace is not None else None}
def _render_markdown(payload: dict[str, object]) -> str:
lines = [
"# Pre-Pair Frontier Trace",
"",
f"Generated at {payload['generated_at']} by `{payload['generator']}`.",
"",
]
for scenario in payload["scenarios"]:
lines.extend(
[
f"## {scenario['name']}",
"",
f"Results: {scenario['summary']['valid_results']} valid / "
f"{scenario['summary']['reached_targets']} reached / "
f"{scenario['summary']['total_results']} total.",
"",
]
)
trace = scenario["pre_pair_frontier_trace"]
if trace is None:
lines.extend(["No pre-pair frontier trace captured.", ""])
continue
lines.extend(
[
f"Captured iteration: `{trace['iteration']}`",
"",
f"Conflict edges: `{trace['conflict_edges']}`",
"",
"| Net | Nodes | Checks | Closed-Set | Cost | Hard Collision | Guidance Seed | Frontier Samples |",
"| :-- | --: | --: | --: | --: | --: | :--: | --: |",
]
)
reason_counts: Counter[str] = Counter()
for net_trace in trace["nets"]:
frontier = net_trace["frontier"]
lines.append(
"| "
f"{net_trace['net_id']} | "
f"{net_trace['nodes_expanded']} | "
f"{net_trace['congestion_check_calls']} | "
f"{net_trace['pruned_closed_set']} | "
f"{net_trace['pruned_cost']} | "
f"{net_trace['pruned_hard_collision']} | "
f"{'yes' if net_trace['guidance_seed_present'] else 'no'} | "
f"{len(frontier['samples'])} |"
)
reason_counts["closed_set"] += frontier["pruned_closed_set"]
reason_counts["hard_collision"] += frontier["pruned_hard_collision"]
reason_counts["self_collision"] += frontier["pruned_self_collision"]
reason_counts["cost"] += frontier["pruned_cost"]
lines.extend(["", "Frontier prune totals by reason:", ""])
if reason_counts:
for reason, count in reason_counts.most_common():
lines.append(f"- `{reason}`: {count}")
else:
lines.append("- None")
lines.append("")
return "\n".join(lines)
def main() -> None:
record_trace(
__file__,
"pre_pair_frontier_trace",
scenario_label="pre-pair frontier-trace",
default_scenarios=NO_WARM_START_SCENARIOS,
scenario_payload=_scenario_payload,
render_markdown=_render_markdown,
)
if __name__ == "__main__":
main()

View file

@ -1,291 +0,0 @@
"""Render intermediate router states for complex-routing example 1."""
from __future__ import annotations
from argparse import ArgumentParser
from dataclasses import replace
from json import loads
from math import floor
from pathlib import Path
from typing import TYPE_CHECKING
from matplotlib.lines import Line2D
from shapely import get_parts, union_all
from shapely.geometry import box
from examples.advanced_layouts import COMPLEX_EXAMPLE, INPUTS, _draw_ports, build_problem
from inire import DiagnosticsOptions, route
from inire.constants import TOLERANCE_LINEAR
from inire.geometry.intervals import open_intervals
from inire.router._bundle import _identify_layout, plan_ordered_bundle
from inire.router._seed_materialization import materialize_path_seed
from inire.router._stack import route_once
from inire.router._topology import _build_corridors, _endpoint_access, _Mesh, _plan_lane_assignments
from inire.router._waypoints import export_waypoints
from scripts.render_documentation_figures import EDGE, INK, MUTED, _board, _polygon, _save, plt
if TYPE_CHECKING:
from collections.abc import Mapping, Sequence
from matplotlib.axes import Axes
from inire import RoutingOptions, RoutingProblem, RoutingRunResult, SearchOptions
from inire.geometry.components import ComponentResult
PathMap = Mapping[str, Sequence[ComponentResult]]
LOWER = "#326a9b"
UPPER = "#26785e"
SHORT = "#725197"
RETURN = "#b34331"
def _seed_paths(problem: RoutingProblem, search: SearchOptions) -> PathMap:
paths = {}
for net in problem.nets:
path = materialize_path_seed(
problem.initial_paths[net.net_id], start=net.start, net_width=net.width, search=search, clearance=problem.clearance,
)
assert path
paths[net.net_id] = path
return paths
def _result_paths(run: RoutingRunResult) -> PathMap:
return {net_id: result.path for net_id, result in run.results_by_net.items()}
def _footprint(ax: Axes, path: Sequence[ComponentResult], color: str, *, dashed: bool = False) -> None:
for shape in get_parts(union_all([polygon for move in path for polygon in move.physical_geometry])):
_polygon(ax, shape, fill="none" if dashed else color, edge=color, linewidth=0.9, linestyle="--" if dashed else "-", zorder=4)
def _waypoints(ax: Axes, path: Sequence[ComponentResult], color: str, *, marker: str | None = None) -> None:
x, y = zip(*export_waypoints(path), strict=True)
ax.plot(x, y, color=color, marker=marker, markersize=2.6, linewidth=1.35, zorder=4)
def _input_figure(directory: Path, problem: RoutingProblem) -> None:
first, last = sorted({x for shape in problem.static_obstacles for x in (shape.bounds[0], shape.bounds[2])})[:2]
cut = (first + last) / 2
_, bottom, _, top = problem.bounds
solid = [(y0, y1) for x0, y0, x1, y1 in (shape.bounds for shape in problem.static_obstacles) if x0 < cut < x1]
openings = open_intervals(solid, bottom, top)
width = min(net.width for net in problem.nets)
pitch = width + problem.clearance - TOLERANCE_LINEAR
fig, (board, section) = plt.subplots(1, 2, figsize=(10, 3.6), width_ratios=(4.5, 1), layout="constrained")
_board(board, problem, grid=True)
board.set_title("Input ports, headings, and keepouts", loc="left", color=INK)
board.set_xlabel("x in layout units", color=MUTED)
for net in problem.nets:
_draw_ports(board, net.start, net.target, RETURN if net.net_id == "net_08" else INK, arrow_length=55)
board.axvline(cut, color=SHORT, linestyle="--", linewidth=1.4, zorder=3)
board.text(cut + 33, 260, f"Cut at x = {cut:g}", rotation=90, color=SHORT, fontsize=9)
section.set(title="Openings on the cut", xlim=(0, 1), ylim=(bottom, top), xticks=[])
section.tick_params(axis="y", labelsize=8, colors=MUTED)
for low, high in solid:
section.axhspan(low, high, color="#d9e1e4")
track_count = 0
for low, high in openings:
first_track = low + width / 2 + (problem.clearance if low != bottom else 0)
last_track = high - width / 2 - (problem.clearance if high != top else 0)
count = max(0, 1 + floor((last_track - first_track + 2 * TOLERANCE_LINEAR) / pitch))
track_count += count
section.plot([0.15, 0.15], [low, high], color=SHORT, linewidth=2)
section.scatter([0.27] * count, [first_track + i * pitch for i in range(count)], s=4, color=SHORT)
section.text(0.40, (low + high) / 2, f"{low:g}–{high:g}", va="center", color=INK, fontsize=9)
section.set_xlabel(f"{track_count} available tracks", color=MUTED, fontsize=9)
_save(fig, directory, f"{COMPLEX_EXAMPLE}-input.png")
def _lane_figure(directory: Path, problem: RoutingProblem, paths: PathMap, colors: Mapping[str, str]) -> None:
fig, (board, detail) = plt.subplots(2, 1, figsize=(9.5, 5.4), height_ratios=(3, 1), layout="constrained")
fig.suptitle("Ordered bundle waypoints", x=0.01, ha="left", color=INK, fontsize=13)
_board(board, problem)
for net_id, path in paths.items():
_waypoints(board, path, colors[net_id], marker="o")
groups = (("Lower group", LOWER), ("Upper group", UPPER), ("Short connection", SHORT), ("Outer return", RETURN))
handles = [Line2D([], [], color=color, label=label) for label, color in groups]
board.legend(handles=handles, loc="lower center", bbox_to_anchor=(0.5, 1), ncols=4, frameon=False, fontsize=9)
_board(detail, problem, grid=True)
detail.set(xlim=(1270, 1615), ylim=(-5, 64), yticks=(1, 10, 18, 45), xticks=(1350, 1450, 1537))
detail.set_title("Two continuous lanes below the tower", loc="left", color=INK, fontsize=10)
detail.tick_params(labelsize=8, colors=MUTED)
for net_id in ("net_00", "net_08"):
_waypoints(detail, paths[net_id], colors[net_id])
detail.text(1450, 33, "Tower", color=MUTED, fontsize=9, ha="center")
detail.text(1292, 10, "net_00", color=LOWER, fontsize=8, va="bottom")
detail.text(1550, 1, "net_08", color=RETURN, fontsize=8, va="bottom")
_save(fig, directory, f"{COMPLEX_EXAMPLE}-lanes.png")
def _turnaround_figure(directory: Path, problem: RoutingProblem, proposal: PathMap, verified: PathMap) -> None:
fig, panels = plt.subplots(2, 1, figsize=(9.5, 4.0), layout="constrained")
for ax, paths, title in zip(panels, (proposal, verified), ("Inferred westbound arrival", "Candidate with eastbound arrival"), strict=True):
_board(ax, problem, grid=True)
ax.set(xlim=(995, 2500), ylim=(785, 1028), xticks=(1112, 1500, 2000, 2412), yticks=(850, 991))
ax.tick_params(labelsize=8, colors=MUTED)
ax.set_title(title, loc="left", color=INK, fontsize=11)
for net_id, color in (("net_07", UPPER), ("net_08", RETURN)):
_footprint(ax, paths[net_id], color)
port = paths["net_08"][-1].end_port
dx = 25 if port.r == 0 else -25
ax.annotate(
"", xy=(port.x + dx, port.y + 21), xytext=(port.x - dx, port.y + 21),
arrowprops={"arrowstyle": "-|>", "color": RETURN, "lw": 1.5}, zorder=6,
)
ax.scatter(port.x, port.y, marker="s", s=22, facecolor="white", edgecolor=RETURN, zorder=7)
ax.text(1950, 902, "net_07 · shelf", color=UPPER, fontsize=9)
ax.text(1250, 1004 if paths is proposal else 844, "net_08 · return", color=RETURN, fontsize=9)
_save(fig, directory, f"{COMPLEX_EXAMPLE}-turnaround.png")
def _verify_figure(directory: Path, problem: RoutingProblem, paths: PathMap, colors: Mapping[str, str]) -> None:
fig, panels = plt.subplots(2, 1, figsize=(8.5, 6.4), layout="constrained")
prefix = tuple(net.net_id for net in problem.nets[:4])
for ax, ids, title in zip(
panels, (prefix, paths), ("First four seeds in install order", "Installed layout after verification · 9/9"), strict=True,
):
_board(ax, problem)
ax.set_title(title, loc="left", color=INK, fontsize=11)
for net in problem.nets:
_draw_ports(ax, net.start, net.target, colors[net.net_id] if net.net_id in ids else EDGE, arrow_length=0)
for net_id in ids:
_footprint(ax, paths[net_id], colors[net_id])
_save(fig, directory, f"{COMPLEX_EXAMPLE}-verification.png")
def _refine_figure(directory: Path, problem: RoutingProblem, before: PathMap, after: PathMap) -> None:
fig, ax = plt.subplots(figsize=(9.5, 2.5), layout="constrained")
_board(ax, problem, grid=True)
ax.set(xlim=(990, 2500), ylim=(793, 1022), xticks=(1100, 1500, 2000, 2412), yticks=(850, 890, 999))
ax.tick_params(labelsize=8, colors=MUTED)
ax.set_title("Selected refinement of the shelf route · net_07", loc="left", color=INK, fontsize=11)
_footprint(ax, before["net_07"], SHORT, dashed=True)
_footprint(ax, after["net_07"], UPPER)
_footprint(ax, after["net_08"], RETURN)
ax.text(1520, 1005, "Selected shelf", color=UPPER, fontsize=9)
ax.text(1510, 895, "Previous shelf (dashed)", color=SHORT, fontsize=9)
ax.text(1460, 845, "Outer return", color=RETURN, fontsize=9)
_save(fig, directory, f"{COMPLEX_EXAMPLE}-refinement.png")
def _guide_figure(directory: Path, problem: RoutingProblem, options: RoutingOptions) -> None:
net = next(net for net in problem.nets if net.net_id == "net_08")
single = replace(problem, nets=(net,))
radius = min(options.search.bend_radii)
board = box(*single.bounds)
mesh = _Mesh(board, single.static_obstacles, net.width / 2, single.clearance)
endpoints, leads = _endpoint_access(mesh, single.nets, radius)
assignments = _plan_lane_assignments(
mesh, single.nets, endpoints, leads, bend_radius=radius, limit=options.topology.max_corridors,
)
corridors = _build_corridors(mesh, board, single.nets, assignments, radius)
config = replace(
options,
search=replace(options.search, node_limit=12),
topology=replace(options.topology, mode="guide"),
congestion=replace(options.congestion, max_iterations=1, warm_start_enabled=False),
diagnostics=DiagnosticsOptions(capture_expanded=True),
)
run = route_once(single, options=config, corridors=corridors)
result = run.results_by_net[net.net_id]
assert result.outcome == "partial"
assert run.metrics.nodes_expanded == config.search.node_limit
assignment = assignments[net.net_id][0]
guide = corridors[net.net_id][0]
fig, (overview, search) = plt.subplots(1, 2, figsize=(10, 4.3), width_ratios=(2, 1), layout="constrained")
for ax in (overview, search):
_board(ax, single, grid=True)
ax.tick_params(labelsize=8, colors=MUTED)
for i, cell in enumerate(mesh.cells):
_polygon(ax, cell, fill="#dfeee7" if i in assignment.cells else "#f2f6f9", edge="#a4b5bd", linewidth=0.7, zorder=1)
ax.plot(*guide.centerline.xy, color=UPPER, linewidth=1.4, linestyle="--", zorder=3)
_draw_ports(ax, net.start, net.target, INK, arrow_length=0)
overview.set_title(f"Guide mesh · {len(mesh.cells)} triangles", loc="left", color=INK, fontsize=11)
search.set_title("Partial path after 12 expansions", loc="left", color=INK, fontsize=11)
search.set(xlim=(0, 410), ylim=(395, 945), xticks=(0, 100, 200, 300, 400))
x, y, _ = zip(*run.expanded_nodes, strict=True)
search.scatter(x, y, color=SHORT, s=12, alpha=0.8, zorder=3, label="Expanded position")
_footprint(search, result.path, RETURN)
port = result.path[-1].end_port
search.annotate(
"Partial end port", xy=(port.x, port.y), xytext=(90, 905), color=RETURN, fontsize=8,
arrowprops={"arrowstyle": "->", "color": RETURN}, zorder=5,
)
search.legend(loc="lower right", fontsize=8)
_save(fig, directory, f"{COMPLEX_EXAMPLE}-guide.png")
def _modes_figure(directory: Path, problem: RoutingProblem, options: RoutingOptions) -> None:
config = replace(
options,
search=replace(options.search, node_limit=100),
congestion=replace(options.congestion, max_iterations=1, warm_start_enabled=False),
refinement=replace(options.refinement, enabled=False),
)
modes = ("automatic", "off", "guide", "seed", "bundle")
fig, panels = plt.subplots(3, 2, figsize=(10, 7), layout="constrained")
fig.suptitle("One congestion iteration · 100 nodes per search", color=INK, fontsize=13)
for ax, mode in zip(panels.ravel()[:-1], modes, strict=True):
settings = replace(config, topology=replace(config.topology, mode=mode, infer_terminal_headings=mode == "bundle"))
run = route(problem, options=settings)
verified = sum(result.is_valid for result in run.results_by_net.values())
label = "bundle with heading inference" if mode == "bundle" else mode
_board(ax, problem)
ax.set_title(f"{label} · {verified}/{len(problem.nets)} verified", loc="left", color=INK, fontsize=11)
for net in problem.nets:
_draw_ports(ax, net.start, net.target, EDGE, arrow_length=0)
result = run.results_by_net[net.net_id]
if result.path:
_footprint(ax, result.path, UPPER if result.is_valid else RETURN, dashed=not result.is_valid)
legend = panels.flat[-1]
legend.set_axis_off()
handles = [
Line2D([], [], color=UPPER, label="Verified path"),
Line2D([], [], color=RETURN, linestyle="--", label="Unverified or partial path"),
]
legend.legend(handles=handles, loc="center left", frameon=False, fontsize=10)
_save(fig, directory, f"{COMPLEX_EXAMPLE}-modes.png")
def main() -> None:
parser = ArgumentParser(description=__doc__)
parser.add_argument("--output-dir", type=Path, default=Path(__file__).resolve().parents[1] / "docs" / "figures")
directory = parser.parse_args().output_dir
directory.mkdir(parents=True, exist_ok=True)
problem, options = build_problem(loads(INPUTS.read_text(encoding="utf-8"))[COMPLEX_EXAMPLE])
proposal = plan_ordered_bundle(problem, options.search, infer_terminal_headings=True)
verified = route(problem, options=replace(options, refinement=replace(options.refinement, enabled=False)))
refined = route(problem, options=options)
assert verified.automatic is not None
assert refined.automatic is not None
assert [stage.planner for stage in verified.automatic.stages] == ["bundle-turnaround"]
assert [stage.operation for stage in refined.automatic.stages] == ["verify", "refine"]
assert refined.automatic.selected_stage == 1
assert len(refined.automatic.verified_net_ids) == len(verified.automatic.verified_net_ids) == len(problem.nets)
assert refined.metrics.nodes_expanded == 0
layout = _identify_layout(problem, problem.nets[0].width / 2 + problem.clearance)
colors = {net.net_id: color for group, color in ((layout.lower, LOWER), (layout.upper, UPPER)) for net in group}
colors.update({layout.short.net_id: SHORT, layout.outer_return.net_id: RETURN})
proposed_paths = _seed_paths(proposal, options.search)
paths = _result_paths(verified)
_input_figure(directory, problem)
_lane_figure(directory, problem, proposed_paths, colors)
_turnaround_figure(directory, problem, proposed_paths, paths)
_verify_figure(directory, problem, paths, colors)
_refine_figure(directory, problem, paths, _result_paths(refined))
_guide_figure(directory, problem, options)
_modes_figure(directory, problem, options)
print(f"{COMPLEX_EXAMPLE}: {len(problem.nets)}/{len(problem.nets)} verified, {refined.metrics.nodes_expanded} A* expansions")
if __name__ == "__main__":
main()

View file

@ -1,32 +1,48 @@
"""Render the routing figures embedded in the user and developer guides."""
"""Render the guide, walkthrough, and advanced example figures."""
from __future__ import annotations
from argparse import ArgumentParser
from dataclasses import replace
from itertools import pairwise
from json import loads
from math import floor
from pathlib import Path
from typing import TYPE_CHECKING
import matplotlib
import shapely
from shapely import get_parts, union_all
from shapely.geometry import box
from inire import CongestionOptions, NetSpec, ObjectiveWeights, Port, RoutingOptions, RoutingProblem, SearchOptions, route
from inire.router._topology import HEADINGS, _endpoint_access, _Mesh, _plan_lane_assignments
from inire import CongestionOptions, DiagnosticsOptions, NetSpec, ObjectiveWeights, Port, RoutingOptions, RoutingProblem, SearchOptions, route
from inire.constants import TOLERANCE_LINEAR
from inire.geometry.intervals import open_intervals
from inire.router._bundle import _identify_layout, plan_ordered_bundle
from inire.router._seed_materialization import materialize_path_seed
from inire.router._stack import route_once
from inire.router._topology import HEADINGS, _build_corridors, _endpoint_access, _Mesh, _plan_lane_assignments
from inire.router._waypoints import export_waypoints
from inire.tests.routing_corpus import CASE_GROUPS, profile_options
matplotlib.use("Agg")
from matplotlib import pyplot as plt # noqa: E402
from matplotlib.lines import Line2D # noqa: E402
from matplotlib.patches import FancyBboxPatch # noqa: E402
from examples.advanced_layouts import COMPLEX_EXAMPLE, INPUTS, _draw_ports, build_problem, render_layouts # noqa: E402
from inire.utils.visualization import draw_polygon # noqa: E402
if TYPE_CHECKING:
from collections.abc import Mapping, Sequence
from matplotlib.axes import Axes
from matplotlib.figure import Figure
from shapely.geometry import Polygon
from inire import RoutingResult
from inire import RoutingResult, RoutingRunResult
from inire.geometry.components import ComponentResult
PathMap = Mapping[str, Sequence[ComponentResult]]
INK = "#193447"
@ -36,6 +52,10 @@ PARTIAL = "#a43a33"
PORTAL = "#a05221"
OBSTACLE = "#d9e1e4"
EDGE = "#738692"
LOWER = "#326a9b"
UPPER = "#26785e"
SHORT = "#725197"
RETURN = "#b34331"
def _save(fig: Figure, directory: Path, name: str) -> None:
@ -241,14 +261,259 @@ def _automatic_stages(directory: Path) -> None:
_save(fig, directory, "automatic-stages.png")
def main() -> None:
def _seed_paths(problem: RoutingProblem, search: SearchOptions) -> PathMap:
paths = {}
for net in problem.nets:
path = materialize_path_seed(
problem.initial_paths[net.net_id], start=net.start, net_width=net.width, search=search, clearance=problem.clearance,
)
assert path
paths[net.net_id] = path
return paths
def _result_paths(run: RoutingRunResult) -> PathMap:
return {net_id: result.path for net_id, result in run.results_by_net.items()}
def _footprint(ax: Axes, path: Sequence[ComponentResult], color: str, *, dashed: bool = False) -> None:
for shape in get_parts(union_all([polygon for move in path for polygon in move.physical_geometry])):
_polygon(ax, shape, fill="none" if dashed else color, edge=color, linewidth=0.9, linestyle="--" if dashed else "-", zorder=4)
def _waypoints(ax: Axes, path: Sequence[ComponentResult], color: str, *, marker: str | None = None) -> None:
x, y = zip(*export_waypoints(path), strict=True)
ax.plot(x, y, color=color, marker=marker, markersize=2.6, linewidth=1.35, zorder=4)
def _input_figure(directory: Path, problem: RoutingProblem) -> None:
first, last = sorted({x for shape in problem.static_obstacles for x in (shape.bounds[0], shape.bounds[2])})[:2]
cut = (first + last) / 2
_, bottom, _, top = problem.bounds
solid = [(y0, y1) for x0, y0, x1, y1 in (shape.bounds for shape in problem.static_obstacles) if x0 < cut < x1]
openings = open_intervals(solid, bottom, top)
width = min(net.width for net in problem.nets)
pitch = width + problem.clearance - TOLERANCE_LINEAR
fig, (board, section) = plt.subplots(1, 2, figsize=(10, 3.6), width_ratios=(4.5, 1), layout="constrained")
_board(board, problem, grid=True)
board.set_title("Input ports, headings, and keepouts", loc="left", color=INK)
board.set_xlabel("x in layout units", color=MUTED)
for net in problem.nets:
_draw_ports(board, net.start, net.target, RETURN if net.net_id == "net_08" else INK, arrow_length=55)
board.axvline(cut, color=SHORT, linestyle="--", linewidth=1.4, zorder=3)
board.text(cut + 33, 260, f"Cut at x = {cut:g}", rotation=90, color=SHORT, fontsize=9)
section.set(title="Openings on the cut", xlim=(0, 1), ylim=(bottom, top), xticks=[])
section.tick_params(axis="y", labelsize=8, colors=MUTED)
for low, high in solid:
section.axhspan(low, high, color="#d9e1e4")
track_count = 0
for low, high in openings:
first_track = low + width / 2 + (problem.clearance if low != bottom else 0)
last_track = high - width / 2 - (problem.clearance if high != top else 0)
count = max(0, 1 + floor((last_track - first_track + 2 * TOLERANCE_LINEAR) / pitch))
track_count += count
section.plot([0.15, 0.15], [low, high], color=SHORT, linewidth=2)
section.scatter([0.27] * count, [first_track + i * pitch for i in range(count)], s=4, color=SHORT)
section.text(0.40, (low + high) / 2, f"{low:g}–{high:g}", va="center", color=INK, fontsize=9)
section.set_xlabel(f"{track_count} available tracks", color=MUTED, fontsize=9)
_save(fig, directory, f"{COMPLEX_EXAMPLE}-input.png")
def _lane_figure(directory: Path, problem: RoutingProblem, paths: PathMap, colors: Mapping[str, str]) -> None:
fig, (board, detail) = plt.subplots(2, 1, figsize=(9.5, 5.4), height_ratios=(3, 1), layout="constrained")
fig.suptitle("Ordered bundle waypoints", x=0.01, ha="left", color=INK, fontsize=13)
_board(board, problem)
for net_id, path in paths.items():
_waypoints(board, path, colors[net_id], marker="o")
groups = (("Lower group", LOWER), ("Upper group", UPPER), ("Short connection", SHORT), ("Outer return", RETURN))
handles = [Line2D([], [], color=color, label=label) for label, color in groups]
board.legend(handles=handles, loc="lower center", bbox_to_anchor=(0.5, 1), ncols=4, frameon=False, fontsize=9)
_board(detail, problem, grid=True)
detail.set(xlim=(1270, 1615), ylim=(-5, 64), yticks=(1, 10, 18, 45), xticks=(1350, 1450, 1537))
detail.set_title("Two continuous lanes below the tower", loc="left", color=INK, fontsize=10)
detail.tick_params(labelsize=8, colors=MUTED)
for net_id in ("net_00", "net_08"):
_waypoints(detail, paths[net_id], colors[net_id])
detail.text(1450, 33, "Tower", color=MUTED, fontsize=9, ha="center")
detail.text(1292, 10, "net_00", color=LOWER, fontsize=8, va="bottom")
detail.text(1550, 1, "net_08", color=RETURN, fontsize=8, va="bottom")
_save(fig, directory, f"{COMPLEX_EXAMPLE}-lanes.png")
def _turnaround_figure(directory: Path, problem: RoutingProblem, proposal: PathMap, verified: PathMap) -> None:
fig, panels = plt.subplots(2, 1, figsize=(9.5, 4.0), layout="constrained")
for ax, paths, title in zip(panels, (proposal, verified), ("Inferred westbound arrival", "Candidate with eastbound arrival"), strict=True):
_board(ax, problem, grid=True)
ax.set(xlim=(995, 2500), ylim=(785, 1028), xticks=(1112, 1500, 2000, 2412), yticks=(850, 991))
ax.tick_params(labelsize=8, colors=MUTED)
ax.set_title(title, loc="left", color=INK, fontsize=11)
for net_id, color in (("net_07", UPPER), ("net_08", RETURN)):
_footprint(ax, paths[net_id], color)
port = paths["net_08"][-1].end_port
dx = 25 if port.r == 0 else -25
ax.annotate(
"", xy=(port.x + dx, port.y + 21), xytext=(port.x - dx, port.y + 21),
arrowprops={"arrowstyle": "-|>", "color": RETURN, "lw": 1.5}, zorder=6,
)
ax.scatter(port.x, port.y, marker="s", s=22, facecolor="white", edgecolor=RETURN, zorder=7)
ax.text(1950, 902, "net_07 · shelf", color=UPPER, fontsize=9)
ax.text(1250, 1004 if paths is proposal else 844, "net_08 · return", color=RETURN, fontsize=9)
_save(fig, directory, f"{COMPLEX_EXAMPLE}-turnaround.png")
def _verify_figure(directory: Path, problem: RoutingProblem, paths: PathMap, colors: Mapping[str, str]) -> None:
fig, panels = plt.subplots(2, 1, figsize=(8.5, 6.4), layout="constrained")
prefix = tuple(net.net_id for net in problem.nets[:4])
for ax, ids, title in zip(
panels, (prefix, paths), ("First four seeds in install order", "Installed layout after verification · 9/9"), strict=True,
):
_board(ax, problem)
ax.set_title(title, loc="left", color=INK, fontsize=11)
for net in problem.nets:
_draw_ports(ax, net.start, net.target, colors[net.net_id] if net.net_id in ids else EDGE, arrow_length=0)
for net_id in ids:
_footprint(ax, paths[net_id], colors[net_id])
_save(fig, directory, f"{COMPLEX_EXAMPLE}-verification.png")
def _refine_figure(directory: Path, problem: RoutingProblem, before: PathMap, after: PathMap) -> None:
fig, ax = plt.subplots(figsize=(9.5, 2.5), layout="constrained")
_board(ax, problem, grid=True)
ax.set(xlim=(990, 2500), ylim=(793, 1022), xticks=(1100, 1500, 2000, 2412), yticks=(850, 890, 999))
ax.tick_params(labelsize=8, colors=MUTED)
ax.set_title("Selected refinement of the shelf route · net_07", loc="left", color=INK, fontsize=11)
_footprint(ax, before["net_07"], SHORT, dashed=True)
_footprint(ax, after["net_07"], UPPER)
_footprint(ax, after["net_08"], RETURN)
ax.text(1520, 1005, "Selected shelf", color=UPPER, fontsize=9)
ax.text(1510, 895, "Previous shelf (dashed)", color=SHORT, fontsize=9)
ax.text(1460, 845, "Outer return", color=RETURN, fontsize=9)
_save(fig, directory, f"{COMPLEX_EXAMPLE}-refinement.png")
def _guide_figure(directory: Path, problem: RoutingProblem, options: RoutingOptions) -> None:
net = next(net for net in problem.nets if net.net_id == "net_08")
single = replace(problem, nets=(net,))
radius = min(options.search.bend_radii)
board = box(*single.bounds)
mesh = _Mesh(board, single.static_obstacles, net.width / 2, single.clearance)
endpoints, leads = _endpoint_access(mesh, single.nets, radius)
assignments = _plan_lane_assignments(
mesh, single.nets, endpoints, leads, bend_radius=radius, limit=options.topology.max_corridors,
)
corridors = _build_corridors(mesh, board, single.nets, assignments, radius)
config = replace(
options,
search=replace(options.search, node_limit=12),
topology=replace(options.topology, mode="guide"),
congestion=replace(options.congestion, max_iterations=1, warm_start_enabled=False),
diagnostics=DiagnosticsOptions(capture_expanded=True),
)
run = route_once(single, options=config, corridors=corridors)
result = run.results_by_net[net.net_id]
assert result.outcome == "partial"
assert run.metrics.nodes_expanded == config.search.node_limit
assignment = assignments[net.net_id][0]
guide = corridors[net.net_id][0]
fig, (overview, search) = plt.subplots(1, 2, figsize=(10, 4.3), width_ratios=(2, 1), layout="constrained")
for ax in (overview, search):
_board(ax, single, grid=True)
ax.tick_params(labelsize=8, colors=MUTED)
for i, cell in enumerate(mesh.cells):
_polygon(ax, cell, fill="#dfeee7" if i in assignment.cells else "#f2f6f9", edge="#a4b5bd", linewidth=0.7, zorder=1)
ax.plot(*guide.centerline.xy, color=UPPER, linewidth=1.4, linestyle="--", zorder=3)
_draw_ports(ax, net.start, net.target, INK, arrow_length=0)
overview.set_title(f"Guide mesh · {len(mesh.cells)} triangles", loc="left", color=INK, fontsize=11)
search.set_title("Partial path after 12 expansions", loc="left", color=INK, fontsize=11)
search.set(xlim=(0, 410), ylim=(395, 945), xticks=(0, 100, 200, 300, 400))
x, y, _ = zip(*run.expanded_nodes, strict=True)
search.scatter(x, y, color=SHORT, s=12, alpha=0.8, zorder=3, label="Expanded position")
_footprint(search, result.path, RETURN)
port = result.path[-1].end_port
search.annotate(
"Partial end port", xy=(port.x, port.y), xytext=(90, 905), color=RETURN, fontsize=8,
arrowprops={"arrowstyle": "->", "color": RETURN}, zorder=5,
)
search.legend(loc="lower right", fontsize=8)
_save(fig, directory, f"{COMPLEX_EXAMPLE}-guide.png")
def _modes_figure(directory: Path, problem: RoutingProblem, options: RoutingOptions) -> None:
config = replace(
options,
search=replace(options.search, node_limit=100),
congestion=replace(options.congestion, max_iterations=1, warm_start_enabled=False),
refinement=replace(options.refinement, enabled=False),
)
modes = ("automatic", "off", "guide", "seed", "bundle")
fig, panels = plt.subplots(3, 2, figsize=(10, 7), layout="constrained")
fig.suptitle("One congestion iteration · 100 nodes per search", color=INK, fontsize=13)
for ax, mode in zip(panels.ravel()[:-1], modes, strict=True):
settings = replace(config, topology=replace(config.topology, mode=mode, infer_terminal_headings=mode == "bundle"))
run = route(problem, options=settings)
verified = sum(result.is_valid for result in run.results_by_net.values())
label = "bundle with heading inference" if mode == "bundle" else mode
_board(ax, problem)
ax.set_title(f"{label} · {verified}/{len(problem.nets)} verified", loc="left", color=INK, fontsize=11)
for net in problem.nets:
_draw_ports(ax, net.start, net.target, EDGE, arrow_length=0)
result = run.results_by_net[net.net_id]
if result.path:
_footprint(ax, result.path, UPPER if result.is_valid else RETURN, dashed=not result.is_valid)
legend = panels.flat[-1]
legend.set_axis_off()
handles = [
Line2D([], [], color=UPPER, label="Verified path"),
Line2D([], [], color=RETURN, linestyle="--", label="Unverified or partial path"),
]
legend.legend(handles=handles, loc="center left", frameon=False, fontsize=10)
_save(fig, directory, f"{COMPLEX_EXAMPLE}-modes.png")
def _render_walkthrough(directory: Path, layout: dict) -> None:
problem, options = build_problem(layout)
proposal = plan_ordered_bundle(problem, options.search, infer_terminal_headings=True)
verified = route(problem, options=replace(options, refinement=replace(options.refinement, enabled=False)))
refined = route(problem, options=options)
assert verified.automatic is not None
assert refined.automatic is not None
assert [stage.planner for stage in verified.automatic.stages] == ["bundle-turnaround"]
assert [stage.operation for stage in refined.automatic.stages] == ["verify", "refine"]
assert refined.automatic.selected_stage == 1
assert len(refined.automatic.verified_net_ids) == len(verified.automatic.verified_net_ids) == len(problem.nets)
assert refined.metrics.nodes_expanded == 0
layout = _identify_layout(problem, problem.nets[0].width / 2 + problem.clearance)
colors = {net.net_id: color for group, color in ((layout.lower, LOWER), (layout.upper, UPPER)) for net in group}
colors.update({layout.short.net_id: SHORT, layout.outer_return.net_id: RETURN})
proposed_paths = _seed_paths(proposal, options.search)
paths = _result_paths(verified)
_input_figure(directory, problem)
_lane_figure(directory, problem, proposed_paths, colors)
_turnaround_figure(directory, problem, proposed_paths, paths)
_verify_figure(directory, problem, paths, colors)
_refine_figure(directory, problem, paths, _result_paths(refined))
_guide_figure(directory, problem, options)
_modes_figure(directory, problem, options)
print(f"{COMPLEX_EXAMPLE}: {len(problem.nets)}/{len(problem.nets)} verified, {refined.metrics.nodes_expanded} A* expansions")
def main() -> int:
parser = ArgumentParser(description=__doc__)
parser.add_argument("--output-dir", type=Path, default=Path(__file__).resolve().parents[1] / "docs" / "figures")
directory = parser.parse_args().output_dir
directory.mkdir(parents=True, exist_ok=True)
for render in (_first_route, _placed_crossing, _search_limits, _automatic_stages, _corridor):
render(directory)
layouts = loads(INPUTS.read_text(encoding="utf-8"))
_render_walkthrough(directory, layouts[COMPLEX_EXAMPLE])
return render_layouts(layouts, directory)
if __name__ == "__main__":
main()
raise SystemExit(main())

View file

@ -1,52 +0,0 @@
"""Route complex-routing example 1 and export verified waypoints."""
from argparse import ArgumentParser
from dataclasses import replace
from json import dumps
from pathlib import Path
from time import perf_counter
from shapely.geometry import box
from inire import TopologyOptions, route
from inire.router._waypoints import export_waypoints
from inire.router.cost import weighted_path_length
from inire.tests.terminal_bench_scenario import LENGTH_COST, terminal_bench_options, terminal_bench_problem
def main() -> None:
parser = ArgumentParser(description=__doc__)
parser.add_argument("--output", type=Path, help="Write the verified waypoint plan to this JSON file.")
parser.add_argument("--reference-lane-plan", action="store_true", help="Replay the manually supplied reference for comparison.")
parser.add_argument("--single-bottom-track", action="store_true", help="Replay the manual reference with one bottom track.")
args = parser.parse_args()
options = terminal_bench_options(max_iterations=1)
options = replace(options, refinement=replace(options.refinement, enabled=False))
started = perf_counter()
if args.reference_lane_plan or args.single_bottom_track:
from inire.tests.terminal_bench_lane_plan import terminal_bench_lane_problem # noqa: PLC0415
problem = terminal_bench_lane_problem(share_bottom_passage=not args.single_bottom_track)
else:
problem = terminal_bench_problem()
options = replace(options, topology=TopologyOptions(mode="bundle", infer_terminal_headings=True))
run = route(problem, options=options)
elapsed = perf_counter() - started
board = box(*problem.bounds)
if run.results_by_net.keys() != {net.net_id for net in problem.nets}:
parser.exit(1, "The route results do not cover the full waypoint plan\n")
for net_id, result in run.results_by_net.items():
if not result.is_valid or any(not board.covers(shape) for shape in result.locked_geometry):
parser.exit(1, f"Lane plan failed inire verification for {net_id}\n")
cost = weighted_path_length((component for result in run.results_by_net.values() for component in result.path), LENGTH_COST)
total = len(problem.nets)
print(f"{total}/{total} verified, benchmark-weighted length {cost:.2f}, {run.metrics.nodes_expanded} A* expansions, {elapsed:.3f} s")
if args.output is not None:
waypoints = {net_id: export_waypoints(result.path) for net_id, result in run.results_by_net.items()}
args.output.write_text(dumps({"nets": {net_id: {"waypoints": path} for net_id, path in waypoints.items()}}, indent=2) + "\n")
if __name__ == "__main__":
main()

View file

@ -1,7 +0,0 @@
"""Compatibility entry point for the nine-net waypoint exporter."""
from scripts.route_complex_routing_example import main
if __name__ == "__main__":
main()

View file

@ -1,199 +0,0 @@
"""Capture and compare exact automatic-routing benchmark results."""
from __future__ import annotations
from argparse import ArgumentParser
from concurrent.futures import ProcessPoolExecutor
from dataclasses import asdict, replace
from json import dumps, loads
from pathlib import Path
from time import perf_counter
from typing import TYPE_CHECKING
from inire import DiagnosticsOptions, route
from inire.results import RouteMetrics
from inire.tests.routing_corpus import (
CASE_GROUPS,
PROFILES,
automatic_options,
benchmark_weighted_length,
native_verified_costs,
profile_options,
route_placement,
select_cases,
)
from scripts.compare_topological_routing import _geometry_json
if TYPE_CHECKING:
from inire import RoutingResult
SCHEMA_VERSION = 2
STABLE_COUNTERS = tuple(name for name in RouteMetrics.__dataclass_fields__ if not name.endswith("_ns"))
def _paths(results: dict[str, RoutingResult]) -> dict:
return {
"net_order": list(results),
"nets": {
net_id: {
"outcome": result.outcome,
"reached_target": result.reached_target,
"seed": [{"kind": type(move).__name__, **asdict(move)} for move in result.as_seed().segments],
**route_placement(result),
"report": asdict(result.report),
}
for net_id, result in results.items()
},
}
def _capture(job: tuple[str, str, bool, bool]) -> dict:
name, profile, with_callback, with_diagnostics = job
(case,) = CASE_GROUPS[name]
options = automatic_options(profile_options(case, profile), profile)
if with_diagnostics:
options = replace(
options,
diagnostics=DiagnosticsOptions(
capture_conflict_trace=True,
capture_iteration_trace=True,
capture_frontier_trace=True,
capture_pre_pair_frontier_trace=True,
),
)
callbacks = []
def notify(index: int, results: dict[str, RoutingResult]) -> None:
callbacks.append({"index": index, **_paths(results)})
started = perf_counter()
run = route(case.problem, options=options, iteration_callback=notify if with_callback else None)
elapsed = perf_counter() - started
report = run.automatic
assert report is not None
native_costs = native_verified_costs(case, options, run.results_by_net, report.verified_net_ids)
costs = {
net_id: {"native": cost, "benchmark_weighted_length": benchmark_weighted_length(run.results_by_net[net_id])}
for net_id, cost in native_costs.items()
}
return {
"case": name,
"profile": profile,
"with_callback": with_callback,
"with_diagnostics": with_diagnostics,
"elapsed_s": elapsed,
"stable": {
"options": asdict(options),
**_paths(run.results_by_net),
"costs": costs,
"verified_net_ids": report.verified_net_ids,
"automatic": asdict(replace(report, duration_s=0.0, timings=())),
"timing_labels": [(item.operation, item.planner, item.mode, item.policy) for item in report.timings],
"metrics": {field: getattr(run.metrics, field) for field in STABLE_COUNTERS},
"topology": asdict(run.topology) if run.topology is not None else None,
"conflict_trace": [asdict(item) for item in run.conflict_trace],
"frontier_trace": [asdict(item) for item in run.frontier_trace],
"pre_pair_frontier_trace": asdict(run.pre_pair_frontier_trace) if run.pre_pair_frontier_trace is not None else None,
"iteration_trace": [asdict(item) for item in run.iteration_trace],
"callbacks": callbacks,
},
}
def _first_difference(expected: object, actual: object, field: str = "") -> str | None:
if expected == actual:
return None
if isinstance(expected, dict) and isinstance(actual, dict):
for key in dict.fromkeys((*expected, *actual)):
path = f"{field}.{key}" if field else str(key)
if key not in expected or key not in actual:
return f"{path} exists on only one side"
difference = _first_difference(expected[key], actual[key], path)
if difference is not None:
return difference
if isinstance(expected, list) and isinstance(actual, list):
for index, (left, right) in enumerate(zip(expected, actual, strict=False)):
difference = _first_difference(left, right, f"{field}[{index}]")
if difference is not None:
return difference
return f"{field} length is {len(expected)} before and {len(actual)} after"
return f"{field} is {expected!r} before and {actual!r} after"
def _read(path: Path) -> tuple[int, dict]:
payload = loads(path.read_text(encoding="utf-8"))
version = payload["schema_version"]
if version not in (1, SCHEMA_VERSION):
raise ValueError(f"Unsupported parity schema in {path}")
rows = payload["runs"]
by_key = {(row["case"], row["profile"], row["with_callback"], row["with_diagnostics"]): row for row in rows}
if len(by_key) != len(rows):
raise ValueError(f"Duplicate parity run in {path}")
return version, by_key
def _compare(before: Path, after: Path, allowed_counters: list[str]) -> int:
before_version, baseline = _read(before)
after_version, current = _read(after)
if before_version != after_version:
print(f"Parity schema mismatch ({before_version} and {after_version}). Capture both revisions with the same script version.")
return 1
for key in sorted(baseline.keys() | current.keys()):
label = f"{key[0]} / {key[1]} (callback={key[2]}, diagnostics={key[3]})"
if key not in baseline or key not in current:
print(f"{label}: run exists on only one side")
return 1
expected, actual = baseline[key]["stable"], current[key]["stable"]
for counter in allowed_counters:
old, new = expected["metrics"].pop(counter), actual["metrics"].pop(counter)
if old != new:
print(f"{label}: allowed counter change {counter} from {old} to {new}")
difference = _first_difference(expected, actual)
if difference is not None:
print(f"{label}: {difference}")
return 1
print(f"{len(current)} runs match.")
baseline_elapsed = sum(row["elapsed_s"] for row in baseline.values())
current_elapsed = sum(row["elapsed_s"] for row in current.values())
print(f"Sum of measured routing times: {baseline_elapsed:.3f}s before and {current_elapsed:.3f}s after.")
return 0
def main() -> int:
parser = ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest="command", required=True)
capture = commands.add_parser("capture")
capture.add_argument("output", type=Path)
capture.add_argument("--case", choices=tuple(CASE_GROUPS), action="append")
capture.add_argument("--profile", choices=PROFILES, action="append")
capture.add_argument("--callbacks", action="store_true", help="Also capture routing with an iteration callback.")
capture.add_argument("--diagnostics", action="store_true", help="Enable conflict, frontier, and iteration traces.")
capture.add_argument("--jobs", type=int, default=1)
compare = commands.add_parser("compare")
compare.add_argument("before", type=Path)
compare.add_argument("after", type=Path)
compare.add_argument("--allow-counter-change", choices=STABLE_COUNTERS, action="append", default=[])
args = parser.parse_args()
if args.command == "compare":
return _compare(args.before, args.after, list(dict.fromkeys(args.allow_counter_change)))
if args.jobs < 1:
parser.error("--jobs must be positive")
cases = select_cases(args.case or ("corpus",))
profiles = dict.fromkeys(args.profile or ("corpus-regression", "public-defaults"))
callback_modes = (False, True) if args.callbacks else (False,)
jobs = [(case.name, profile, callback, args.diagnostics) for case in cases for profile in profiles for callback in callback_modes]
if args.jobs == 1:
rows = list(map(_capture, jobs))
else:
with ProcessPoolExecutor(max_workers=args.jobs) as pool:
rows = list(pool.map(_capture, jobs))
payload = {"schema_version": SCHEMA_VERSION, "runs": rows}
args.output.write_text(dumps(payload, indent=2, default=_geometry_json) + "\n", encoding="utf-8")
print(f"Captured {len(rows)} runs in {args.output}")
return 0
if __name__ == "__main__":
raise SystemExit(main())