inire/inire/router/_automatic.py
Jan Petykiewicz ed52ea6ffd Improve automatic routing retries and reuse component geometry
Try verified perimeter construction early and reuse probe routes as movable hints during lookahead. Batch collision checks and cache component generation for repeated placement and refinement candidates.
2026-11-30 19:29:51 -08:00

858 lines
43 KiB
Python

"""Automatic planner selection and verified residual routing."""
from __future__ import annotations
from contextlib import contextmanager, suppress
from dataclasses import replace
from functools import partial
from itertools import chain, islice, pairwise
from time import perf_counter
from typing import TYPE_CHECKING
import shapely
from shapely.geometry import box
from inire.geometry.collision import RoutingWorld, _violates_net_clearance
from inire.model import FixedRoute, resolve_bend_geometry
from inire.results import AutomaticRoutingReport, RoutingStage, RoutingTiming, _planner_for_mode
from inire.router._bundle import ordered_bundle_terminal_headings, plan_ordered_bundle
from inire.router._capacity import cut_capacity, port_conflicts
from inire.router._columns import (
column_jog_candidates, column_partition_budget_exceeded, column_recovery_candidates, column_recovery_subproblems, column_seed_candidates,
)
from inire.router._compact import compact_port_seed_set, short_shift_seed_set
from inire.router._congestion_policy import ordered_nets
from inire.router._perimeter import (
bundle_turnaround_candidates,
perimeter_detour_candidates,
residual_dogleg_candidates,
terminal_link_seed,
)
from inire.router._route_traces import complete_final_conflict_trace
from inire.router._routing_policy import (
LockPlan,
_best_trial,
_direct_trials,
_disconnected_nets,
_is_short_shift,
_residual_problem,
_route_prepared_residual,
_route_residual,
_trial,
)
from inire.router._seed_materialization import materialize_path_seed, seed_preparation_error
from inire.router._stack import RoutingAttempts
from inire.router._topology import constrained_triangulation_available, plan_corridors
from inire.router.cost import build_native_cost_evaluator, weighted_path_length
from inire.router.refiner import PathRefiner
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.router._routing_policy import Trial
from inire.router._topology import Corridor
from inire.router.cost import CostEvaluator
from inire.seeds import PathSeed
_Footprint = tuple[PathSeed, BaseGeometry]
_PerimeterPair = tuple[_Footprint, _Footprint]
_INITIAL_NODE_LIMIT = 500
_NEAR_PORT_NODE_LIMIT = 100
_NEAR_PORT_ITERATION_LIMIT = 2
def _has_fragmented_shifts(trial: Trial) -> bool:
for net_id in trial.valid_costs:
path = trial.run.results_by_net[net_id].path
# A chain of S-bends with a short offset is a sign that the span
# planner is piecing together a shift across a single window.
for a, b in pairwise(path):
if a.move_type == b.move_type == "sbend" and any(
isinstance(move.move_spec, SBendSeed) and abs(move.move_spec.offset) <= move.move_spec.radius / 2 for move in (a, b)
):
return True
return False
class _AutomaticRun:
def __init__(
self,
problem: RoutingProblem,
options: RoutingOptions,
iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None,
) -> None:
if any(not seed.segments for seed in problem.initial_paths.values()):
problem = replace(problem, initial_paths={net_id: seed for net_id, seed in problem.initial_paths.items() if seed.segments})
self.raw_problem = problem
self.problem = problem
self.options = options
self.board = box(*problem.bounds)
self.attempts = RoutingAttempts(iteration_callback)
self.timings: list[RoutingTiming] = []
self.cost_pass_performed = False
self.evaluator: CostEvaluator | None = None
weights = options.topology.automatic_length_weights
self.length_weights = dict(zip(("straight", "bend90", "sbend"), weights, strict=True)) if weights is not None else None
@contextmanager
def _time(
self,
operation: RoutingOperation,
*,
planner: str | None = None,
mode: str | None = None,
policy: str | None = None,
) -> Iterator[None]:
index = len(self.timings)
timing = RoutingTiming(operation, 0.0, planner, mode, policy)
self.timings.append(timing)
started = perf_counter()
try:
yield
finally:
elapsed = perf_counter() - started
# Nested verification and search are labeled independently of candidate generation.
child_time = sum(child.duration_s for child in self.timings[index + 1 :])
self.timings[index] = replace(timing, duration_s=max(0.0, elapsed - child_time))
def _run(
self,
problem: RoutingProblem,
*,
options: RoutingOptions,
operation: RoutingOperation = "search",
planner: str | None = None,
policy: str | None = None,
corridors: dict[str, tuple[Corridor, ...]] | None = None,
) -> RoutingRunResult:
mode = options.topology.mode
time_operation = partial(self._time, planner=planner or _planner_for_mode(mode), mode=mode, policy=policy)
with time_operation(operation):
return self.attempts.run(
problem,
options=options,
phase_timer=time_operation,
corridors=corridors,
)
def _selection_cost(self, result: RoutingResult) -> float:
if not self.options.search.node_limit:
# Verification-only runs have a single candidate to report.
return 0.0
if self.length_weights is not None:
return weighted_path_length(result.path, self.length_weights)
if self.evaluator is None:
self.evaluator = build_native_cost_evaluator(
self.problem, self.options.objective, proximity_range=self.options.search.proximity_range,
)
return self.evaluator.path_cost(result.path[0].start_port, result.path)
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, score=self._selection_cost)
def _seeded_problem(self, trial: Trial, *, include_unresolved: bool = False) -> RoutingProblem:
seeds = {
net_id: result.as_seed() for net_id, result in trial.run.results_by_net.items()
if result.path and (include_unresolved or net_id in trial.valid_costs)
}
nets = []
for net in self.problem.nets:
if net.net_id not in seeds:
continue
result = trial.run.results_by_net[net.net_id]
nets.append(replace(
net, start=result.path[0].start_port,
target=result.path[-1].end_port if result.reached_target else net.target,
))
return replace(self.problem, nets=tuple(nets), initial_paths=seeds)
def _seeded_attempt(
self,
problem: RoutingProblem,
planner: str,
*,
kind: str,
policy: str | None,
operation: Literal["verify", "refine"],
node_limit: int = 1,
) -> tuple[RoutingRunResult, RoutingStage]:
options = self.options
refinement = options.refinement
if operation == "verify":
refinement = replace(refinement, enabled=False)
node_limit = 0
worker = replace(
options,
search=replace(options.search, node_limit=node_limit),
topology=replace(options.topology, mode="off"),
congestion=replace(options.congestion, max_iterations=1),
refinement=refinement,
)
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, preserve_hints: bool = False,
) -> Trial:
def verify(candidate: RoutingProblem) -> Trial:
run, stage = self._seeded_attempt(candidate, planner, kind=kind or planner, policy=policy, operation="verify")
return self._trial(run, stage)
if preserve_hints and self.problem.initial_paths:
active_ids = {net.net_id for net in problem.nets}
hints = {net_id: seed for net_id, seed in self.problem.initial_paths.items() if net_id in active_ids}
merged = {**problem.initial_paths, **hints}
if merged != problem.initial_paths:
incumbent = verify(replace(problem, initial_paths=merged))
if len(incumbent.valid_costs) == len(problem.nets):
return incumbent
candidate = verify(problem)
return candidate if candidate.improves_on(incumbent) else incumbent
return verify(problem)
def _constructive_trials(self) -> tuple[list[Trial], tuple[str, ...]]:
options = self.options
problem = replace(self.problem, initial_paths={}) if self.problem.initial_paths else self.problem
verify = partial(self._verify, preserve_hints=True)
trials: list[Trial] = []
rejections = []
try:
with self._time("plan", planner="bundle"):
raw = replace(self.raw_problem, initial_paths={}) if self.raw_problem.initial_paths else self.raw_problem
bundle = plan_ordered_bundle(raw, options.search, infer_terminal_headings=True)
except ValueError as exc:
rejections.append(str(exc))
else:
if bundle.nets == problem.nets:
trials.append(verify(bundle, "bundle"))
if len(trials[-1].valid_costs) == len(problem.nets):
return trials, ()
rejections.append("Bundle candidate failed geometric verification")
elif not options.topology.infer_terminal_headings:
with self._time("plan", planner="bundle-turnaround"):
for candidate in bundle_turnaround_candidates(problem, bundle, options.search):
trials.append(verify(candidate, "bundle-turnaround"))
if len(trials[-1].valid_costs) == len(problem.nets):
return trials, ()
rejections.append("No geometrically verified turnaround matched the terminal headings")
with self._time("plan", planner="compact-port-jogs"):
compact = compact_port_seed_set(problem, options.search)
if compact is not None:
trials.append(verify(replace(problem, initial_paths=compact), "compact-port-jogs"))
if len(trials[-1].valid_costs) == len(problem.nets):
return trials, tuple(rejections)
span_trial = self._column_trial(False, trials, problem=problem)
if span_trial is None:
rejections.append("Span scoring found no verified column layout")
policy = options.topology.automatic_cost
if policy == "always" or (policy == "selective" and span_trial is not None and _has_fragmented_shifts(span_trial)):
self.cost_pass_performed = True
if self._column_trial(True, trials, problem=problem) is None:
rejections.append("Cost scoring found no verified column layout")
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._selection_cost,
defer_blocker=not self.problem.initial_paths, length_weights=self.length_weights,
)
if shifts is not None:
trial = verify(replace(problem, initial_paths=shifts), planner)
complete = len(trial.valid_costs) == len(problem.nets)
trials.append(trial if complete else replace(trial, selection="incomplete-layout"))
if len(shifts) == len(problem.nets) - 1:
detour = self._residual_constructive_trial(options, trial, limit_per_pass=16)
if detour is not None:
trials.append(detour)
return trials, tuple(rejections)
if not complete:
rejections.append("Local S-bend layout failed full verification")
return trials, tuple(rejections)
def _column_trial(self, weighted: bool, trials: list[Trial], *, problem: RoutingProblem) -> Trial | None:
objective = self.options.objective
weights = self.length_weights or dict.fromkeys(("straight", "bend90", "sbend"), objective.unit_length_cost)
penalty = 0.0 if self.length_weights is not None else objective.sbend_penalty
policy = "weighted" if weighted else "span"
kind = "column-cost" if weighted else "column-span"
with self._time("plan", planner="column", policy=policy):
candidates = column_seed_candidates(problem, self.options.search, weights, weighted=weighted, sbend_penalty=penalty)
for seeds in islice(candidates, 8):
trial = self._verify(replace(problem, initial_paths=seeds), "column", kind=kind, policy=policy, preserve_hints=True)
trials.append(trial)
if len(trial.valid_costs) == len(self.problem.nets):
return trial
return None
def _paired_perimeter(self, trials: list[Trial]) -> None:
problem, options = self.problem, self.options
if len(problem.nets) != 2:
return
world = RoutingWorld.from_problem(problem, board=self.board)
def footprints(net: NetSpec, seeds: Iterable[PathSeed]) -> Iterator[_Footprint]:
for seed in seeds:
path = materialize_path_seed(
seed, start=net.start, net_width=net.width, search=options.search, clearance=problem.clearance, bounds=problem.bounds,
)
if not path or path[-1].end_port != net.target or not world.verify_path_report(net.net_id, path).is_valid:
continue
footprint = shapely.union_all([shape for component in path for shape in component.physical_geometry])
yield seed, footprint
candidates: list[Iterator[_Footprint]] = []
links: list[list[_Footprint]] = []
for net in problem.nets:
supplied = problem.initial_paths.get(net.net_id)
simple = supplied if supplied is not None else terminal_link_seed(net, options.search)
links.append(list(footprints(net, (simple,))) if simple is not None else [])
if supplied is not None:
candidates.append(iter(links[-1]))
continue
single = replace(problem, nets=(net,), initial_paths={})
detours = (seed for _, seed in islice(perimeter_detour_candidates(single, options.search), 32))
candidates.append(chain(links[-1], footprints(net, detours)))
first, second = problem.nets
def ordinary_pairs() -> Iterator[_PerimeterPair]:
left, right = candidates
checked_right: list[_Footprint] = []
for left_candidate in left:
for right_candidate in checked_right:
yield left_candidate, right_candidate
for right_candidate in right:
checked_right.append(right_candidate)
yield left_candidate, right_candidate
if not checked_right:
return
def reserved_pairs() -> Iterator[_PerimeterPair]:
for index, net in enumerate(problem.nets):
if net.net_id in problem.initial_paths or not links[1 - index]:
continue
peer_link = links[1 - index][0]
peer = problem.nets[1 - index]
fixed = FixedRoute(peer.net_id, tuple(shapely.get_parts(peer_link[1])))
reserved = replace(problem, nets=(net,), initial_paths={}, fixed_routes=(*problem.fixed_routes, fixed))
detours = footprints(net, (seed for _, seed in islice(perimeter_detour_candidates(reserved, options.search), 16)))
for detour in detours:
yield (detour, peer_link) if index == 0 else (peer_link, detour)
for (first_seed, first_shape), (second_seed, second_shape) in chain(ordinary_pairs(), reserved_pairs()):
if _violates_net_clearance(first_shape, second_shape, problem.clearance):
continue
plan = replace(problem, initial_paths={first.net_id: first_seed, second.net_id: second_seed})
trial = self._verify(plan, "paired-perimeter")
trials.append(trial)
if len(trial.valid_costs) == len(problem.nets):
return
trials[-1] = replace(trial, selection="incomplete-layout")
def _perimeter_trials(self, options: RoutingOptions, *, try_pair: bool = True) -> list[Trial]:
problem = self.problem
trials = []
if try_pair and len(problem.nets) == 2:
with self._time("plan", planner="paired-perimeter"):
self._paired_perimeter(trials)
if trials and len(trials[-1].valid_costs) == len(problem.nets):
return trials
for net, seed in islice(perimeter_detour_candidates(problem, options.search), 32):
detour_problem = replace(problem, nets=(net,), initial_paths={net.net_id: seed})
candidate = self._verify(detour_problem, "perimeter", kind="perimeter-check")
if len(problem.nets) == 1 and candidate.valid_costs:
trials.append(replace(candidate, stage=replace(candidate.stage, kind="perimeter")))
break
trials.append(replace(candidate, selection="local-only"))
if not candidate.valid_costs:
continue
chosen = candidate.run.results_by_net[net.net_id]
policy = "perimeter-residual"
guide = replace(options, congestion=replace(options.congestion, max_iterations=1))
run, stage = _route_residual(
problem,
guide,
LockPlan({net.net_id: chosen}),
residual_mode="guide",
run_route=partial(self._run, policy=policy),
)
stage = replace(stage, kind=policy, policy=policy, planner="perimeter")
trials.append(self._trial(run, stage))
if len(trials[-1].valid_costs) == len(problem.nets):
trials[-1] = replace(trials[-1], selection="requires-layout-check")
seeds = {net_id: result.as_seed() for net_id, result in run.results_by_net.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]:
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:
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(
"seed",
(),
run.metrics.nodes_expanded,
options.search.node_limit,
kind="incumbent-retry",
policy="incumbent-retry",
incumbent_net_ids=tuple(retained),
retry_reason=f"Incumbents disconnect {', '.join(sorted(blocked))} when locked",
)
return [self._trial(run, stage)]
policy = "incumbent-residual"
locks = LockPlan(retained)
residual = _residual_problem(problem, locks)
run, stage = _route_prepared_residual(residual, options, locks, residual_mode="seed", run_route=partial(self._run, policy=policy))
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, selection="requires-layout-check"), self._verify_incumbent(trial)]
trials = [trial]
if len(trial.valid_costs) < target:
construction = self._residual_constructive_trial(options, _best_trial([best, trial]))
if construction is not None:
return [trial, construction]
joint = self._joint_lane_trial(residual, options, locks, trial)
if joint is not None:
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:
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.as_replacement_for(trial), run=replace(verified.run, results_by_net=results))
def _residual_constructive_trial(self, options: RoutingOptions, incumbent: Trial, *, limit_per_pass: int = 8) -> Trial | None:
problem = self.problem
if len(incumbent.valid_costs) != len(problem.nets) - 1:
return None
retained = {net_id: incumbent.run.results_by_net[net_id] for net_id in incumbent.valid_costs}
residual = _residual_problem(problem, LockPlan(retained))
(net,) = residual.nets
seeds = {net_id: result.as_seed() for net_id, result in retained.items()}
if net.start.r == net.target.r == 0 and net.start.x > net.target.x:
planner = "residual-perimeter"
candidates = (seed for _, seed in islice(perimeter_detour_candidates(residual, options.search), 32))
else:
planner = "residual-dogleg"
candidates = residual_dogleg_candidates(residual, options.search, limit_per_pass=limit_per_pass)
with self._time("plan", planner=planner, policy=planner):
world = None
for seed in candidates:
path = materialize_path_seed(
seed, start=net.start, net_width=net.width, search=options.search, clearance=residual.clearance, bounds=residual.bounds,
)
if not path or path[-1].end_port != net.target:
continue
if world is None:
world = RoutingWorld.from_problem(residual, board=self.board)
if not world.verify_path_report(net.net_id, path).is_valid:
continue
candidate = replace(problem, initial_paths={**seeds, net.net_id: seed})
trial = self._verify(candidate, planner, policy=planner)
if len(trial.valid_costs) == len(problem.nets):
return trial
return None
def _direct(self, options: RoutingOptions, policy: str, *, hints: dict[str, PathSeed] | None = None) -> list[Trial]:
def run(problem: RoutingProblem, *, options: RoutingOptions) -> RoutingRunResult:
if hints:
# Add internal hints after direct locks are chosen so search can move them.
active_hints = {net.net_id: hints[net.net_id] for net in problem.nets if net.net_id in hints}
if active_hints:
problem = replace(problem, initial_paths={**active_hints, **problem.initial_paths})
options = replace(options, congestion=replace(options.congestion, warm_start_enabled=False))
return self._run(problem, options=options, policy=policy)
with self._time("plan", planner="direct", policy=policy):
return _direct_trials(
self.problem,
self.board,
options,
policy,
run_route=run,
check_trial=self._trial,
)
def _try_hinted_lookahead(self, options: RoutingOptions, trials: list[Trial], incumbent: Trial, target: int) -> bool:
if (
self.problem.initial_paths or target != len(self.problem.nets)
or not 2 <= len(incumbent.valid_costs) < target - 1
or options.search.node_limit <= _NEAR_PORT_NODE_LIMIT
or options.congestion.max_iterations <= 1 or options.congestion.shuffle_nets or not options.congestion.warm_start_enabled
):
return False
retained = [incumbent.run.results_by_net[net_id] for net_id in incumbent.valid_costs]
if all(len(result.path) == 1 and result.path[0].move_type == "straight" for result in retained):
return False
hints = {result.net_id: result.as_seed() for result in retained}
attempts = self._direct(options, "direct-lookahead-hinted", hints=hints)
best = _best_trial(attempts)
if len(incumbent.valid_costs) < len(best.valid_costs) < target:
seeded = replace(options, topology=replace(options.topology, mode="seed"))
attempts.extend(self._incumbent_trials(seeded, best, target))
if len(_best_trial(attempts).valid_costs) >= target:
trials.extend(attempts)
return True
# The ordinary retry starts from its original incumbents if hints fall short.
trials.extend(replace(trial, selection="incomplete-layout") for trial in attempts)
return False
def _early_guide(self, options: RoutingOptions) -> Trial | None:
problem = self.problem
if (
len(problem.nets) <= 2
or problem.initial_paths
or options.search.node_limit <= _NEAR_PORT_NODE_LIMIT
or options.congestion.shuffle_nets
):
return None
max_offset = 2 * max(options.search.sbend_radii, default=0)
if not all(_is_short_shift(net, max_offset) for net in problem.nets) or len({net.start.r % 180 for net in problem.nets}) < 2:
return None
policy = "early-guide"
guide = replace(options, topology=replace(options.topology, mode="guide"))
run = self._run(problem, options=guide, policy=policy)
return self._trial(run, RoutingStage("guide", (), run.metrics.nodes_expanded, guide.search.node_limit, policy=policy))
def _try_column_jogs(self, options: RoutingOptions, trials: list[Trial], target: int) -> bool:
problem = self.problem
if target != len(problem.nets) or problem.initial_paths:
return False
with self._time("plan", planner="column-jogs"):
for seeds in column_jog_candidates(problem, options.search, limit_per_pass=8):
trial = self._verify(replace(problem, initial_paths=seeds), "column-jogs")
if len(trial.valid_costs) == target:
trials.append(trial)
return True
return False
def _try_column_recovery(self, options: RoutingOptions, trials: list[Trial], groups: tuple[RoutingProblem, ...]) -> bool:
problem = self.problem
planner = "column-recovery"
with self._time("plan", planner=planner):
combined = {}
for group in groups:
for seeds in column_recovery_candidates(group, options.search):
trial = self._verify(replace(group, initial_paths=seeds), planner)
if len(trial.valid_costs) == len(group.nets):
if group is problem:
trials.append(trial)
return True
combined.update(seeds)
break
else:
return False
trial = self._verify(replace(problem, initial_paths=combined), planner)
if len(trial.valid_costs) == len(problem.nets):
trials.append(trial)
return True
return False
def _search_trials(self, trials: list[Trial], target: int) -> None:
configured_search = self.options.search
first_limit = min(_INITIAL_NODE_LIMIT, configured_search.node_limit)
options = replace(
self.options,
search=replace(configured_search, node_limit=first_limit),
refinement=replace(self.options.refinement, enabled=False),
)
if self._initial_search_trials(options, trials, target):
return
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:
self._lattice_fallback(
trials,
replace(options, search=configured_search),
"Initial pass fell short of the routing bound",
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 = not options.congestion.shuffle_nets
if try_construction_early and self._try_column_jogs(options, trials, target):
return True
groups = ()
if (
try_construction_early and target == len(problem.nets) and not problem.initial_paths
and options.search.bend_radii and problem._blocking_polygons
):
with self._time("plan", planner="column-recovery"):
groups = column_recovery_subproblems(problem)
try_recovery_early = len(groups) > 1 or (len(groups) == 1 and column_partition_budget_exceeded(problem))
# Independent channels and dense aperture fields can be cheaper to route
# by construction. Try their bypass before spending search budget.
if try_recovery_early:
if self._try_column_recovery(options, trials, groups):
return True
groups = ()
max_shift = 2 * max(options.search.sbend_radii, default=0)
early_perimeter = (
try_construction_early and target == len(problem.nets) <= 2 and not problem.initial_paths
and options.search.node_limit > 1 and options.search.bend_radii and problem._blocking_polygons
and all(net.start.r == net.target.r == 0 and not _is_short_shift(net, max_shift) for net in problem.nets)
and (target == 2 or problem.nets[0].start.x > problem.nets[0].target.x)
)
if early_perimeter:
# For a small, fixed-heading layout, try verified construction
# before searching. Defer the perimeter's residual A* to its usual turn.
with self._time("plan", planner="perimeter"):
perimeter = []
if target == 2:
with self._time("plan", planner="paired-perimeter"):
self._paired_perimeter(perimeter)
else:
perimeter = self._perimeter_trials(options)
trials.extend(perimeter)
if perimeter and len(perimeter[-1].valid_costs) == target:
return True
probe_iterations = options.congestion.max_iterations
proxy, _ = resolve_bend_geometry(options.search)
# Clipped proxies can find cheaper routes in later probe iterations than in the wider retry.
if proxy == "arc":
probe_iterations = min(_NEAR_PORT_ITERATION_LIMIT, probe_iterations)
probe_options = replace(
options,
search=replace(options.search, node_limit=min(_NEAR_PORT_NODE_LIMIT, options.search.node_limit)),
congestion=replace(options.congestion, max_iterations=probe_iterations),
)
probe = self._direct(probe_options, "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:
construction = self._residual_constructive_trial(options, _best_trial(probe))
if construction is not None:
trials.append(construction)
return True
if len(problem.nets) <= 2 and (not early_perimeter or target == 2):
with self._time("plan", planner="perimeter"):
trials.extend(self._perimeter_trials(options, try_pair=not early_perimeter))
if len(_best_trial(trials).valid_costs) >= target:
return True
if len(groups) == 1 and self._try_column_recovery(options, trials, groups):
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:
if self._try_hinted_lookahead(options, trials, _best_trial(probe), target):
return True
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")
candidate = self._trial(run, stage)
trials.append(candidate)
if not problem.initial_paths and len(candidate.valid_costs) == target - 1 and _best_trial(trials) is candidate:
# The seed fallback can leave a better set of incumbents for a final detour.
construction = self._residual_constructive_trial(options, candidate, limit_per_pass=16)
if construction is not None:
trials.append(construction)
def _joint_lane_trial(self, residual: RoutingProblem, options: RoutingOptions, locks: LockPlan, previous: Trial) -> Trial | None:
if len(residual.nets) < 2:
return None
policy = "joint-portal-lanes"
unresolved = frozenset(net.net_id for net in residual.nets if net.net_id not in previous.valid_costs)
nets = ordered_nets(residual.nets, options.congestion.net_order)
with self._time("plan", planner="corridor-seed", mode="seed", policy=policy):
corridors = plan_corridors(
residual.bounds,
residual._blocking_polygons,
nets,
clearance=residual.clearance,
bend_radius=min(options.search.bend_radii, default=0.0),
limit=options.topology.max_corridors,
joint_net_ids=unresolved,
)
if not corridors:
return None
retry = replace(options, congestion=replace(options.congestion, max_iterations=min(3, options.congestion.max_iterations)))
run, stage = _route_prepared_residual(
residual, retry, locks, residual_mode="seed", run_route=partial(self._run, policy=policy, corridors=corridors)
)
stage = replace(
stage,
policy=policy,
incumbent_net_ids=tuple(locks.direct),
retry_reason="Unresolved nets share a portal with alternative lane assignments",
)
return self._trial(run, stage)
def _lattice_fallback(self, trials: list[Trial], options: RoutingOptions, reason: str, *, policy: str | None = None) -> None:
run = self._run(self.problem, options=replace(options, topology=replace(options.topology, mode="off")), policy=policy)
stage = RoutingStage(
"off",
(),
run.metrics.nodes_expanded,
options.search.node_limit,
kind="lattice-fallback",
policy=policy,
retry_reason=reason,
)
trials.append(self._trial(run, stage))
def _refine(self, trials: list[Trial]) -> Trial | None:
best = _best_trial(trials)
if not self.options.refinement.enabled or not any(
PathRefiner.has_refinement_bends(best.run.results_by_net[net_id].path) for net_id in best.valid_costs
):
return None
has_unresolved_paths = any(result.path and not result.is_valid for result in best.run.results_by_net.values())
run, stage = self._seeded_attempt(
self._seeded_problem(best, include_unresolved=has_unresolved_paths),
best.stage.planner,
kind="refinement",
policy=best.stage.policy,
operation="refine",
node_limit=0 if has_unresolved_paths else 1,
)
# Any carried-over result without a replayed seed has no path to recheck.
results = {**best.run.results_by_net, **run.results_by_net}
refined = self._trial(replace(run, results_by_net=results), stage).as_replacement_for(best)
# Only a whole verified replacement of the incumbent can win.
trials.append(refined)
objective = self.options.refinement.objective
if objective is None:
return None
if not refined.selectable:
return best
evaluator = build_native_cost_evaluator(self.problem, objective, proximity_range=self.options.search.proximity_range)
def cost(trial: Trial) -> float:
paths = (trial.run.results_by_net[net_id].path for net_id in trial.valid_costs)
return sum(evaluator.path_cost(path[0].start_port, path) for path in paths)
return refined if cost(refined) < cost(best) else best
def execute(self) -> RoutingRunResult:
started = perf_counter()
options = self.options
proxy, physical = resolve_bend_geometry(options.search)
cut = None
conflicts = ()
rejections = ()
target = len(self.problem.nets)
trials: list[Trial] = []
refinement_choice = None
if not self.problem.nets or options.search.node_limit <= 0 or options.congestion.max_iterations <= 0:
self._lattice_fallback(trials, options, "No automatic search requested")
elif (
isinstance(proxy, shapely.Polygon) or physical != "arc"
or options.search.has_applicable_sbend_outline(net.width for net in self.problem.nets)
):
self._lattice_fallback(trials, options, "Custom bend geometry uses lattice routing")
else:
with self._time("plan"):
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)
target -= len(conflicts)
if cut:
target = min(target, cut.max_routed)
if not cut and not conflicts:
trials, rejections = self._constructive_trials()
if not any(trial.selectable for trial in trials) or len(_best_trial(trials).valid_costs) < target:
if constrained_triangulation_available():
self._search_trials(trials, target)
else:
worker = replace(options, refinement=replace(options.refinement, enabled=False))
self._lattice_fallback(trials, worker, "Constrained triangulation is unavailable")
refinement_choice = self._refine(trials)
best = refinement_choice or _best_trial(trials)
metrics = self.attempts.metrics()
report = AutomaticRoutingReport(
tuple(trial.stage for trial in trials),
next(i for i, trial in enumerate(trials) if trial is best),
target,
capacity_limit=cut,
port_conflicts=conflicts,
planner_rejections=rejections,
cost_pass_performed=self.cost_pass_performed,
timings=tuple(self.timings),
duration_s=perf_counter() - started,
)
results = best.run.results_by_net
if options.congestion.max_iterations and self.raw_problem.initial_paths:
results = dict(results)
for net in self.raw_problem.nets:
seed = self.raw_problem.initial_paths.get(net.net_id)
result = results[net.net_id]
if seed is None or result.report.seed_error is not None:
continue
error = seed_preparation_error(
seed, start=net.start, net_width=net.width, search=options.search, clearance=self.raw_problem.clearance,
)
if error:
report_with_error = replace(result.report, seed_error=f"Initial path for {net.net_id!r} {error}")
results[net.net_id] = replace(result, report=report_with_error)
return replace(complete_final_conflict_trace(replace(best.run, results_by_net=results)), metrics=metrics, automatic=report)
def route_automatic(
problem: RoutingProblem,
options: RoutingOptions,
iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None,
) -> RoutingRunResult:
return _AutomaticRun(problem, options, iteration_callback).execute()