Refactor routing internals and archive retry benchmarks

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

View file

@ -3,10 +3,9 @@
from __future__ import annotations
from contextlib import contextmanager, suppress
from dataclasses import fields, replace
from dataclasses import replace
from functools import partial
from itertools import chain, combinations, islice, pairwise, product
from math import floor, isfinite
from itertools import chain, islice, pairwise, product
from time import perf_counter
from typing import TYPE_CHECKING
@ -15,10 +14,12 @@ from shapely.geometry import box
from inire.constants import TOLERANCE_LINEAR
from inire.geometry.collision import RoutingWorld
from inire.geometry.primitives import port_local_coordinates
from inire.model import resolve_bend_geometry
from inire.results import AutomaticRoutingReport, CapacityLimit, RouteMetrics, RoutingStage, RoutingTiming, _planner_for_mode
from inire.results import AutomaticRoutingReport, RoutingStage, RoutingTiming, _planner_for_mode, _sum_route_metrics
from inire.router._bundle import ordered_bundle_terminal_headings, plan_ordered_bundle
from inire.router._columns import column_jog_candidates, column_seed_candidates, open_intervals, rectangular_obstacle_bounds
from inire.router._capacity import cut_capacity, port_conflicts
from inire.router._columns import column_jog_candidates, column_seed_candidates
from inire.router._compact import compact_port_seed_set, short_shift_seed_set
from inire.router._perimeter import (
bundle_turnaround_candidates,
@ -32,7 +33,6 @@ from inire.router._routing_policy import (
_direct_trials,
_disconnected_nets,
_is_short_shift,
_local_delta,
_residual_problem,
_route_residual,
_trial,
@ -40,17 +40,18 @@ from inire.router._routing_policy import (
from inire.router._seed_materialization import materialize_path_seed
from inire.router._stack import route_once
from inire.router._topology import plan_corridors
from inire.router.cost import CostEvaluator
from inire.router.cost import CostEvaluator, weighted_path_length
from inire.router.danger_map import DangerMap
from inire.seeds import SBendSeed
if TYPE_CHECKING:
from collections.abc import Callable, Iterable, Iterator
from typing import Literal
from shapely.geometry.base import BaseGeometry
from inire.model import NetSpec, RoutingOptions, RoutingProblem
from inire.results import RoutingOperation, RoutingResult, RoutingRunResult
from inire.results import RouteMetrics, RoutingOperation, RoutingResult, RoutingRunResult
from inire.router._routing_policy import Trial
from inire.router._topology import Corridor
from inire.seeds import PathSeed
@ -60,65 +61,6 @@ _INITIAL_NODE_LIMIT = 500
_NEAR_PORT_NODE_LIMIT = 100
def _cut_capacity(problem: RoutingProblem, options: RoutingOptions) -> CapacityLimit | None:
_, physical_geometry = resolve_bend_geometry(options.search)
obstacles = rectangular_obstacle_bounds(problem)
if physical_geometry != "arc" or not obstacles or not problem.nets:
return None
# The narrowest guide gives an optimistic upper bound for mixed widths.
width = min(net.width for net in problem.nets)
if not isfinite(width) or width <= 0 or problem.clearance < 0:
return None
pitch = width + problem.clearance
limit = None
edges = sorted({x for left, _, right, _ in obstacles for x in (left, right)})
for left, right in pairwise(edges):
x = (left + right) / 2
crossing = sum(min(net.start.x, net.target.x) + width / 2 < x < max(net.start.x, net.target.x) - width / 2 for net in problem.nets)
if not crossing:
continue
solid = [(bottom, top) for start, bottom, end, top in obstacles if start < x < end]
if not solid:
continue
ymin, ymax = problem.bounds[1], problem.bounds[3]
tracks = 0
for low, high in open_intervals(solid, ymin, ymax):
bottom = low + width / 2 + (problem.clearance if low != ymin else 0)
top = high - width / 2 - (problem.clearance if high != ymax else 0)
room = top - bottom + 2 * TOLERANCE_LINEAR
if room >= 0:
tracks += 1 + floor(room / max(TOLERANCE_LINEAR, pitch - TOLERANCE_LINEAR))
max_routed = len(problem.nets) - crossing + tracks
if tracks < crossing and (limit is None or max_routed < limit.max_routed):
limit = CapacityLimit(x, crossing, tracks, max_routed)
return limit
def _port_conflicts(problem: RoutingProblem, options: RoutingOptions) -> tuple[tuple[str, str], ...]:
_, physical_geometry = resolve_bend_geometry(options.search)
if physical_geometry != "arc" or problem.clearance <= TOLERANCE_LINEAR:
return ()
aligned: dict[tuple[int, int], list[tuple[str, float, float]]] = {}
for net in problem.nets:
for port in (net.start, net.target):
axis = port.r % 180
longitudinal, lateral = (port.x, port.y) if axis == 0 else (port.y, port.x)
aligned.setdefault((axis, longitudinal), []).append((net.net_id, lateral, net.width))
# Each disjoint conflict pair forces at least one route to be omitted.
# A terminal's physical cross-section is fixed by its heading and width.
pairs = []
matched = set()
for ports in aligned.values():
for (a, y1, w1), (b, y2, w2) in combinations(ports, 2):
if a == b or a in matched or b in matched:
continue
gap = abs(y1 - y2) - (w1 + w2) / 2
if gap < problem.clearance - TOLERANCE_LINEAR:
pairs.append((a, b))
matched.update((a, b))
return tuple(pairs)
def _has_fragmented_shifts(trial: Trial) -> bool:
for net_id in trial.valid_costs:
path = trial.run.results_by_net[net_id].path
@ -201,9 +143,9 @@ class _AutomaticRun:
self.metrics.append(run.metrics)
return run
def _score(self, result: RoutingResult) -> float:
def _selection_cost(self, result: RoutingResult) -> float:
if self.length_weights is not None:
return sum(component.length * self.length_weights[component.move_type] for component in result.path)
return weighted_path_length(result.path, self.length_weights)
if self.evaluator is None:
objective = self.options.objective
danger = None
@ -222,19 +164,48 @@ class _AutomaticRun:
def _trial(self, run: RoutingRunResult, stage: RoutingStage) -> Trial:
with self._time("verify", planner=stage.planner, mode=stage.mode, policy=stage.policy):
return _trial(run, stage, self.board, score=self._score)
return _trial(run, stage, self.board, score=self._selection_cost)
def _verify(self, problem: RoutingProblem, planner: str, *, kind: str | None = None, policy: str | None = None) -> Trial:
def _seeded_problem(self, trial: Trial) -> RoutingProblem:
seeds = {net_id: trial.run.results_by_net[net_id].as_seed() for net_id in trial.valid_costs}
nets = tuple(net for net in self.problem.nets if net.net_id in seeds)
return replace(self.problem, nets=nets, initial_paths=seeds)
def _seeded_attempt(
self,
problem: RoutingProblem,
planner: str,
*,
kind: str,
policy: str | None,
operation: Literal["verify", "refine"],
) -> tuple[RoutingRunResult, RoutingStage]:
options = self.options
check = replace(
refinement = options.refinement
if operation == "verify":
refinement = replace(refinement, enabled=False)
worker = replace(
options,
search=replace(options.search, node_limit=1),
topology=replace(options.topology, mode="off"),
congestion=replace(options.congestion, max_iterations=1),
refinement=replace(options.refinement, enabled=False),
refinement=refinement,
)
run = self._run(problem, options=check, operation="verify", planner=planner, policy=policy)
stage = RoutingStage("off", (), run.metrics.nodes_expanded, 1, kind=kind or planner, planner=planner, operation="verify", policy=policy)
run = self._run(problem, options=worker, operation=operation, planner=planner, policy=policy)
stage = RoutingStage(
worker.topology.mode,
(),
run.metrics.nodes_expanded,
worker.search.node_limit,
kind=kind,
planner=planner,
operation=operation,
policy=policy,
)
return run, stage
def _verify(self, problem: RoutingProblem, planner: str, *, kind: str | None = None, policy: str | None = None) -> Trial:
run, stage = self._seeded_attempt(problem, planner, kind=kind or planner, policy=policy, operation="verify")
return self._trial(run, stage)
def _constructive_trials(self) -> tuple[list[Trial], tuple[str, ...]]:
@ -278,11 +249,11 @@ class _AutomaticRun:
if not trials or len(_best_trial(trials).valid_costs) < len(problem.nets):
planner = "local-sbend"
with self._time("plan", planner=planner):
shifts = short_shift_seed_set(problem, options.search, self._score)
shifts = short_shift_seed_set(problem, options.search, self._selection_cost)
if shifts is not None:
trial = self._verify(replace(problem, initial_paths=shifts), planner)
complete = len(trial.valid_costs) == len(problem.nets)
trials.append(replace(trial, selectable=complete))
trials.append(trial if complete else replace(trial, selection="incomplete-layout"))
if not complete:
rejections.append("Local S-bend layout failed full verification")
return trials, tuple(rejections)
@ -351,7 +322,7 @@ class _AutomaticRun:
trials.append(trial)
if len(trial.valid_costs) == len(problem.nets):
return
trials[-1] = replace(trial, selectable=False)
trials[-1] = replace(trial, selection="incomplete-layout")
def _perimeter_trials(self, options: RoutingOptions) -> list[Trial]:
problem = self.problem
@ -367,7 +338,7 @@ class _AutomaticRun:
if len(problem.nets) == 1 and candidate.valid_costs:
trials.append(replace(candidate, stage=replace(candidate.stage, kind="perimeter")))
break
trials.append(replace(candidate, selectable=False))
trials.append(replace(candidate, selection="local-only"))
if not candidate.valid_costs:
continue
chosen = candidate.run.results_by_net[net.net_id]
@ -390,19 +361,21 @@ class _AutomaticRun:
)
trials.append(self._trial(replace(run, results_by_net=combined), stage))
if len(trials[-1].valid_costs) == len(problem.nets):
trials[-1] = replace(trials[-1], selectable=False)
trials[-1] = replace(trials[-1], selection="requires-layout-check")
seeds = {net_id: result.as_seed() for net_id, result in combined.items()}
trials.append(self._verify(replace(problem, initial_paths=seeds), "perimeter"))
if len(trials[-1].valid_costs) == len(problem.nets):
break
return trials
def _incumbent_trials(self, options: RoutingOptions, best: Trial, target: int) -> list[Trial]:
def _incumbent_trials(self, options: RoutingOptions, best: Trial, target: int, *, retry_disconnected: bool = True) -> list[Trial]:
problem = self.problem
retained = {net_id: best.run.results_by_net[net_id] for net_id in best.valid_costs}
with self._time("plan", policy="incumbent-retry"):
blocked = _disconnected_nets(problem, self.board, options, retained)
if blocked:
if not retry_disconnected:
return []
seeds = {net_id: result.as_seed() for net_id, result in retained.items()}
run = self._run(replace(problem, initial_paths=seeds), options=options, policy="incumbent-retry")
stage = RoutingStage(
@ -423,7 +396,7 @@ class _AutomaticRun:
stage = replace(stage, kind=policy, policy=policy, retry_reason="Residual terminals remain connected with the incumbents locked")
trial = self._trial(run, stage)
if len(trial.valid_costs) == len(problem.nets):
return [replace(trial, selectable=False), self._verify_incumbent(trial)]
return [replace(trial, selection="requires-layout-check"), self._verify_incumbent(trial)]
trials = [trial]
if len(trial.valid_costs) < target:
dogleg = self._residual_dogleg_trial(options, _best_trial([best, trial]))
@ -431,17 +404,17 @@ class _AutomaticRun:
return [trial, dogleg]
joint = self._joint_lane_trial(options, locks, trial)
if joint is not None:
trials.append(replace(joint, selectable=False))
trials.append(replace(joint, selection="requires-layout-check"))
if joint.improves_on(_best_trial([best, trial])):
trials.append(self._verify_incumbent(joint))
return trials
def _verify_incumbent(self, trial: Trial) -> Trial:
seeds = {net_id: trial.run.results_by_net[net_id].as_seed() for net_id in trial.valid_costs}
problem = replace(self.problem, nets=tuple(net for net in self.problem.nets if net.net_id in seeds), initial_paths=seeds)
problem = self._seeded_problem(trial)
# Check the seeded subproblem before restoring the unresolved results.
verified = self._verify(problem, trial.stage.planner, kind="incumbent-verified", policy=trial.stage.policy)
results = {**trial.run.results_by_net, **verified.run.results_by_net}
return replace(verified, run=replace(verified.run, results_by_net=results), selectable=verified.valid_costs.keys() == seeds.keys())
return replace(verified.as_replacement_for(trial), run=replace(verified.run, results_by_net=results))
def _residual_dogleg_trial(self, options: RoutingOptions, incumbent: Trial) -> Trial | None:
problem = self.problem
@ -502,7 +475,6 @@ class _AutomaticRun:
return False
def _search_trials(self, trials: list[Trial], target: int) -> None:
problem = self.problem
configured_search = self.options.search
first_limit = min(_INITIAL_NODE_LIMIT, configured_search.node_limit)
options = replace(
@ -510,43 +482,9 @@ class _AutomaticRun:
search=replace(configured_search, node_limit=first_limit),
refinement=replace(self.options.refinement, enabled=False),
)
early = self._early_guide(options)
if early is not None:
trials.append(early)
if len(_best_trial(trials).valid_costs) >= target:
return
early_jogs = self.iteration_callback is None and not options.congestion.shuffle_nets
if early_jogs and self._try_column_jogs(options, trials, target):
if self._initial_search_trials(options, trials, target):
return
small = replace(options, search=replace(options.search, node_limit=min(_NEAR_PORT_NODE_LIMIT, options.search.node_limit)))
trials.extend(self._direct(small, "direct-probe-near-port"))
if len(_best_trial(trials).valid_costs) >= target:
return
if not early_jogs and self._try_column_jogs(options, trials, target):
return
if len(problem.nets) <= 2:
with self._time("plan", planner="perimeter"):
trials.extend(self._perimeter_trials(options))
if len(_best_trial(trials).valid_costs) >= target:
return
# Every short shift has lateral displacement, so the direct retry cannot lock
# any straight paths. It would run the same guide with the same budget.
if early is None or early.run.metrics.timeout_events:
trials.extend(self._direct(options, "direct-lookahead-retry"))
best = _best_trial(trials)
if len(best.valid_costs) >= target:
return
seeded = replace(options, topology=replace(options.topology, mode="seed"))
if best.valid_costs and len(problem.nets) > 2 and not problem.initial_paths:
trials.extend(self._incumbent_trials(seeded, best, target))
if len(_best_trial(trials).valid_costs) < target:
run = self._run(problem, options=seeded, policy="seed-fallback")
stage = RoutingStage("seed", (), run.metrics.nodes_expanded, options.search.node_limit, policy="seed-fallback")
trials.append(self._trial(run, stage))
self._seed_recovery_trials(options, trials, target)
if len(_best_trial(trials).valid_costs) < target:
self._lattice_fallback(trials, options, "Automatic planners left unresolved nets")
if first_limit < configured_search.node_limit and len(_best_trial(trials).valid_costs) < target:
@ -557,6 +495,55 @@ class _AutomaticRun:
policy="budget-escalation",
)
def _initial_search_trials(self, options: RoutingOptions, trials: list[Trial], target: int) -> bool:
problem = self.problem
early = self._early_guide(options)
if early is not None:
trials.append(early)
if len(_best_trial(trials).valid_costs) >= target:
return True
try_construction_early = self.iteration_callback is None and not options.congestion.shuffle_nets
if try_construction_early and self._try_column_jogs(options, trials, target):
return True
small = replace(options, search=replace(options.search, node_limit=min(_NEAR_PORT_NODE_LIMIT, options.search.node_limit)))
probe = self._direct(small, "direct-probe-near-port")
trials.extend(probe)
if len(_best_trial(trials).valid_costs) >= target:
return True
if not try_construction_early and self._try_column_jogs(options, trials, target):
return True
if try_construction_early and target == len(problem.nets) and target > 2 and not problem.initial_paths:
dogleg = self._residual_dogleg_trial(options, _best_trial(probe))
if dogleg is not None:
trials.append(dogleg)
return True
if len(problem.nets) <= 2:
with self._time("plan", planner="perimeter"):
trials.extend(self._perimeter_trials(options))
if len(_best_trial(trials).valid_costs) >= target:
return True
# Every short shift has lateral displacement, so the direct retry cannot lock
# any straight paths. It would run the same guide with the same budget.
if early is None or early.run.metrics.timeout_events:
trials.extend(self._direct(options, "direct-lookahead-retry"))
return len(_best_trial(trials).valid_costs) >= target
def _seed_recovery_trials(self, options: RoutingOptions, trials: list[Trial], target: int) -> None:
problem = self.problem
best = _best_trial(trials)
seeded = replace(options, topology=replace(options.topology, mode="seed"))
if best.valid_costs and len(problem.nets) > 2 and not problem.initial_paths:
trials.extend(self._incumbent_trials(seeded, best, target))
if len(_best_trial(trials).valid_costs) < target:
run = self._run(problem, options=seeded, policy="seed-fallback")
stage = RoutingStage("seed", (), run.metrics.nodes_expanded, options.search.node_limit, policy="seed-fallback")
trials.append(self._trial(run, stage))
def _joint_lane_trial(self, options: RoutingOptions, locks: LockPlan, previous: Trial) -> Trial | None:
residual = _residual_problem(self.problem, locks)
if len(residual.nets) < 2:
@ -566,7 +553,11 @@ class _AutomaticRun:
order = options.congestion.net_order
nets = residual.nets
if order != "user":
nets = tuple(sorted(nets, key=lambda net: sum(map(abs, _local_delta(net))), reverse=order == "longest"))
nets = tuple(sorted(
nets,
key=lambda net: sum(map(abs, port_local_coordinates(net.start, net.target.x, net.target.y))),
reverse=order == "longest",
))
with self._time("plan", planner="corridor-seed", mode="seed", policy=policy):
corridors = plan_corridors(
residual.bounds,
@ -608,24 +599,18 @@ class _AutomaticRun:
best = _best_trial(trials)
if not self.options.refinement.enabled or not best.valid_costs:
return
problem = replace(
self.problem,
nets=tuple(net for net in self.problem.nets if net.net_id in best.valid_costs),
initial_paths={net_id: best.run.results_by_net[net_id].as_seed() for net_id in best.valid_costs},
run, stage = self._seeded_attempt(
self._seeded_problem(best),
best.stage.planner,
kind="refinement",
policy=best.stage.policy,
operation="refine",
)
options = replace(
self.options,
search=replace(self.options.search, node_limit=1),
topology=replace(self.options.topology, mode="off"),
congestion=replace(self.options.congestion, max_iterations=1),
)
planner, policy = best.stage.planner, best.stage.policy
run = self._run(problem, options=options, operation="refine", planner=planner, policy=policy)
stage = RoutingStage("off", (), run.metrics.nodes_expanded, 1, kind="refinement", policy=policy, planner=planner, operation="refine")
# Audit the merged result so the stage still reports unresolved routes outside the board.
results = {**best.run.results_by_net, **run.results_by_net}
refined = self._trial(replace(run, results_by_net=results), stage)
# Only a whole verified replacement of the incumbent can win.
trials.append(replace(refined, selectable=refined.valid_costs.keys() == best.valid_costs.keys()))
trials.append(refined.as_replacement_for(best))
def execute(self) -> RoutingRunResult:
started = perf_counter()
@ -647,8 +632,8 @@ class _AutomaticRun:
if options.topology.infer_terminal_headings and not self.problem.initial_paths:
with suppress(ValueError):
self.problem = ordered_bundle_terminal_headings(self.raw_problem)
cut = _cut_capacity(self.problem, options)
conflicts = _port_conflicts(self.problem, options)
cut = cut_capacity(self.problem, options)
conflicts = port_conflicts(self.problem, options)
target -= len(conflicts)
if cut:
target = min(target, cut.max_routed)
@ -658,7 +643,7 @@ class _AutomaticRun:
self._search_trials(trials, target)
self._refine(trials)
best = _best_trial(trials)
metrics = replace(best.run.metrics, **{field.name: sum(getattr(m, field.name) for m in self.metrics) for field in fields(RouteMetrics)})
metrics = _sum_route_metrics(self.metrics)
report = AutomaticRoutingReport(
tuple(trial.stage for trial in trials),
next(i for i, trial in enumerate(trials) if trial is best),