Select and verify topological and constructive routing plans
This commit is contained in:
parent
d741456d6b
commit
be3222e5ae
1 changed files with 2868 additions and 68 deletions
567
inire/router/_automatic.py
Normal file
567
inire/router/_automatic.py
Normal file
|
|
@ -0,0 +1,567 @@
|
|||
"""Automatic planner selection and verified residual routing."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import contextmanager, suppress
|
||||
from dataclasses import fields, replace
|
||||
from functools import partial
|
||||
from itertools import chain, combinations, islice, pairwise, product
|
||||
from math import floor, isfinite
|
||||
from time import perf_counter
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import shapely
|
||||
from shapely.geometry import box
|
||||
|
||||
from inire.constants import TOLERANCE_LINEAR
|
||||
from inire.geometry.collision import RoutingWorld
|
||||
from inire.model import resolve_bend_geometry
|
||||
from inire.results import AutomaticRoutingReport, CapacityLimit, RouteMetrics, RoutingStage, RoutingTiming, _planner_for_mode
|
||||
from inire.router._bundle import ordered_bundle_terminal_headings, plan_ordered_bundle
|
||||
from inire.router._columns import column_seed_candidates, open_intervals, rectangular_obstacle_bounds
|
||||
from inire.router._compact import compact_port_seed_set
|
||||
from inire.router._perimeter import bundle_turnaround_candidates, perimeter_detour_candidates, terminal_link_seed
|
||||
from inire.router._routing_policy import LockPlan, _best_trial, _direct_trials, _disconnected_nets, _is_short_shift, _route_residual, _trial
|
||||
from inire.router._seed_materialization import materialize_path_seed
|
||||
from inire.router._stack import route_once
|
||||
from inire.router.cost import CostEvaluator
|
||||
from inire.router.danger_map import DangerMap
|
||||
from inire.seeds import SBendSeed
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable, Iterable, Iterator
|
||||
|
||||
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.seeds import PathSeed
|
||||
|
||||
|
||||
_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
|
||||
# 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:
|
||||
self.raw_problem = problem
|
||||
self.problem = problem
|
||||
self.options = options
|
||||
self.board = box(*problem.bounds)
|
||||
self.metrics: list[RouteMetrics] = []
|
||||
self.timings: list[RoutingTiming] = []
|
||||
self.iteration_callback = iteration_callback
|
||||
self.callback_index = 0
|
||||
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,
|
||||
) -> RoutingRunResult:
|
||||
def notify(_iteration: int, results: dict[str, RoutingResult]) -> None:
|
||||
assert self.iteration_callback is not None
|
||||
self.iteration_callback(self.callback_index, results)
|
||||
self.callback_index += 1
|
||||
|
||||
mode = options.topology.mode
|
||||
time_operation = partial(self._time, planner=planner or _planner_for_mode(mode), mode=mode, policy=policy)
|
||||
with time_operation(operation):
|
||||
run = route_once(
|
||||
problem,
|
||||
options=options,
|
||||
iteration_callback=notify if self.iteration_callback else None,
|
||||
phase_timer=time_operation,
|
||||
)
|
||||
self.metrics.append(run.metrics)
|
||||
return run
|
||||
|
||||
def _score(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)
|
||||
if self.evaluator is None:
|
||||
objective = self.options.objective
|
||||
danger = None
|
||||
if objective.danger_weight and self.problem.static_obstacles:
|
||||
danger = DangerMap(bounds=self.problem.bounds)
|
||||
danger.precompute(list(self.problem.static_obstacles))
|
||||
self.evaluator = CostEvaluator(
|
||||
RoutingWorld(clearance=self.problem.clearance),
|
||||
danger,
|
||||
unit_length_cost=objective.unit_length_cost,
|
||||
bend_penalty=objective.bend_penalty,
|
||||
sbend_penalty=objective.sbend_penalty,
|
||||
danger_weight=objective.danger_weight,
|
||||
)
|
||||
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, self.board, score=self._score)
|
||||
|
||||
def _verify(self, problem: RoutingProblem, planner: str, *, kind: str | None = None, policy: str | None = None) -> Trial:
|
||||
options = self.options
|
||||
check = 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),
|
||||
)
|
||||
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)
|
||||
return self._trial(run, stage)
|
||||
|
||||
def _constructive_trials(self) -> tuple[list[Trial], tuple[str, ...]]:
|
||||
problem, options = self.problem, self.options
|
||||
trials: list[Trial] = []
|
||||
rejections = []
|
||||
try:
|
||||
with self._time("plan", planner="bundle"):
|
||||
bundle = plan_ordered_bundle(self.raw_problem, options.search, infer_terminal_headings=True)
|
||||
except ValueError as exc:
|
||||
rejections.append(str(exc))
|
||||
else:
|
||||
if bundle.nets == problem.nets:
|
||||
trials.append(self._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(self._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(self._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)
|
||||
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) is None:
|
||||
rejections.append("Cost scoring found no verified column layout")
|
||||
return trials, tuple(rejections)
|
||||
|
||||
def _column_trial(self, weighted: bool, trials: list[Trial]) -> 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(self.problem, self.options.search, weights, weighted=weighted, sbend_penalty=penalty)
|
||||
for seeds in islice(candidates, 8):
|
||||
trial = self._verify(replace(self.problem, initial_paths=seeds), "column", kind=kind, policy=policy)
|
||||
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(clearance=problem.clearance, safety_zone_radius=problem.safety_zone_radius)
|
||||
for obstacle in problem.static_obstacles:
|
||||
world.add_static_obstacle(obstacle)
|
||||
|
||||
def footprints(net: NetSpec, seeds: Iterable[PathSeed]) -> list[tuple[PathSeed, BaseGeometry]]:
|
||||
choices = []
|
||||
for seed in seeds:
|
||||
path = materialize_path_seed(seed, start=net.start, net_width=net.width, search=options.search, clearance=problem.clearance)
|
||||
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])
|
||||
if self.board.covers(footprint):
|
||||
choices.append((seed, footprint))
|
||||
return choices
|
||||
|
||||
candidates: list[list[tuple[PathSeed, BaseGeometry]]] = []
|
||||
links: list[list[tuple[PathSeed, BaseGeometry]]] = []
|
||||
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(footprints(net, (simple,)) if simple is not None else [])
|
||||
single = replace(problem, nets=(net,), initial_paths={})
|
||||
detours = (seed for _, seed in islice(perimeter_detour_candidates(single, options.search), 32))
|
||||
candidates.append(links[-1] if supplied is not None else [*links[-1], *footprints(net, detours)])
|
||||
|
||||
pairs: Iterable[tuple[tuple[PathSeed, BaseGeometry], tuple[PathSeed, BaseGeometry]]] = product(*candidates)
|
||||
first, second = problem.nets
|
||||
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]
|
||||
obstacles = problem.static_obstacles + tuple(shapely.get_parts(peer_link[1]))
|
||||
reserved = replace(problem, nets=(net,), initial_paths={}, static_obstacles=obstacles)
|
||||
detours = footprints(net, (seed for _, seed in islice(perimeter_detour_candidates(reserved, options.search), 16)))
|
||||
reserved_pairs = product(detours, (peer_link,)) if index == 0 else product((peer_link,), detours)
|
||||
pairs = chain(pairs, reserved_pairs)
|
||||
|
||||
for (first_seed, first_shape), (second_seed, second_shape) in pairs:
|
||||
if first_shape.distance(second_shape) < problem.clearance - TOLERANCE_LINEAR:
|
||||
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, selectable=False)
|
||||
|
||||
def _perimeter_trials(self, options: RoutingOptions) -> list[Trial]:
|
||||
problem = self.problem
|
||||
trials = []
|
||||
if 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, selectable=False))
|
||||
if not candidate.valid_costs:
|
||||
continue
|
||||
chosen = candidate.run.results_by_net[net.net_id]
|
||||
residual = replace(
|
||||
problem,
|
||||
nets=tuple(other for other in problem.nets if other != net),
|
||||
static_obstacles=problem.static_obstacles + chosen.locked_geometry,
|
||||
)
|
||||
guide = replace(options, topology=replace(options.topology, mode="guide"), congestion=replace(options.congestion, max_iterations=1))
|
||||
run = self._run(residual, options=guide, policy="perimeter-residual")
|
||||
combined = {net.net_id: chosen, **run.results_by_net}
|
||||
stage = RoutingStage(
|
||||
"guide",
|
||||
(net.net_id,),
|
||||
run.metrics.nodes_expanded,
|
||||
options.search.node_limit,
|
||||
kind="perimeter-residual",
|
||||
policy="perimeter-residual",
|
||||
planner="perimeter",
|
||||
)
|
||||
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)
|
||||
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) -> 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"
|
||||
run, stage = _route_residual(problem, options, "direct-seed", LockPlan(retained), 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 [trial]
|
||||
seeds = {net_id: result.as_seed() for net_id, result in run.results_by_net.items()}
|
||||
verified = self._verify(replace(problem, initial_paths=seeds), stage.planner, kind="incumbent-verified", policy=policy)
|
||||
return [replace(trial, selectable=False), verified]
|
||||
|
||||
def _direct(self, options: RoutingOptions, policy: str) -> list[Trial]:
|
||||
with self._time("plan", planner="direct", policy=policy):
|
||||
return _direct_trials(
|
||||
self.problem,
|
||||
self.board,
|
||||
options,
|
||||
policy,
|
||||
run_route=partial(self._run, policy=policy),
|
||||
check_trial=self._trial,
|
||||
)
|
||||
|
||||
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 self.iteration_callback is not None
|
||||
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 _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(
|
||||
self.options,
|
||||
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
|
||||
|
||||
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 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))
|
||||
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))
|
||||
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 _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]) -> None:
|
||||
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},
|
||||
)
|
||||
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")
|
||||
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()))
|
||||
|
||||
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] = []
|
||||
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":
|
||||
self._lattice_fallback(trials, options, "Custom bend geometry uses lattice routing")
|
||||
elif not hasattr(shapely, "constrained_delaunay_triangles") or shapely.geos_version < (3, 10):
|
||||
self._lattice_fallback(trials, options, "Constrained triangulation is unavailable")
|
||||
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 trials or len(_best_trial(trials).valid_costs) < target:
|
||||
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)})
|
||||
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,
|
||||
)
|
||||
return replace(best.run, 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()
|
||||
Loading…
Reference in a new issue