Check physical keepout clearance, retain useful partial paths, and account for all pair repair searches. Verify complete seeds early and recover narrower corridors when shared guides are blocked. Keep frontier diagnostics outside routing decisions and bound their work by the worker deadline. Correct benchmark scaling and scenario validation, and update the guides and release metadata.
330 lines
13 KiB
Python
330 lines
13 KiB
Python
"""Shared direct-route and residual search policies."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass, replace
|
|
from typing import TYPE_CHECKING, Protocol
|
|
|
|
import shapely
|
|
from shapely.geometry import Point
|
|
|
|
from inire.constants import TOLERANCE_LINEAR
|
|
from inire.geometry.collision import RoutingWorld
|
|
from inire.geometry.components import Straight
|
|
from inire.geometry.primitives import port_local_coordinates
|
|
from inire.model import FixedRoute, resolve_bend_geometry
|
|
from inire.results import RoutingResult, RoutingStage
|
|
from inire.router._congestion_policy import ordered_nets
|
|
from inire.router._seed_materialization import materialize_path_seed
|
|
from inire.router._stack import route_once
|
|
|
|
if TYPE_CHECKING:
|
|
from collections.abc import Callable
|
|
from typing import Literal
|
|
|
|
from shapely.geometry import Polygon
|
|
|
|
from inire.model import NetSpec, RoutingOptions, RoutingProblem
|
|
from inire.results import RoutingRunResult
|
|
|
|
Scorer = Callable[[RoutingResult], float]
|
|
CheckTrial = Callable[[RoutingRunResult, RoutingStage], "Trial"]
|
|
|
|
|
|
class RouteCall(Protocol):
|
|
def __call__(self, problem: RoutingProblem, *, options: RoutingOptions) -> RoutingRunResult: ...
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class LockPlan:
|
|
direct: dict[str, RoutingResult]
|
|
disconnected: frozenset[str] = frozenset()
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class Trial:
|
|
"""A checked result and its eligibility for automatic selection.
|
|
|
|
A local check or residual search can establish coverage worth verifying
|
|
on the whole layout. Only eligible trials may win final selection.
|
|
"""
|
|
|
|
run: RoutingRunResult
|
|
stage: RoutingStage
|
|
valid_costs: dict[str, float]
|
|
selection: Literal["eligible", "local-only", "requires-layout-check", "incomplete-layout", "changed-net-set"] = "eligible"
|
|
|
|
@property
|
|
def selectable(self) -> bool:
|
|
return self.selection == "eligible"
|
|
|
|
def as_replacement_for(self, incumbent: Trial) -> Trial:
|
|
if self.valid_costs.keys() == incumbent.valid_costs.keys():
|
|
return self
|
|
return replace(self, selection="changed-net-set")
|
|
|
|
def improves_on(self, other: Trial) -> bool:
|
|
"""Prefer greater coverage, then lower cost within the same net set."""
|
|
return len(self.valid_costs) > len(other.valid_costs) or (
|
|
self.valid_costs.keys() == other.valid_costs.keys() and sum(self.valid_costs.values()) < sum(other.valid_costs.values())
|
|
)
|
|
|
|
|
|
def _is_short_shift(net: NetSpec, max_offset: float) -> bool:
|
|
forward, lateral = port_local_coordinates(net.start, net.target.x, net.target.y)
|
|
return net.start.r == net.target.r and forward > 0 and 0 < abs(lateral) < max_offset
|
|
|
|
|
|
def _direct_paths(
|
|
problem: RoutingProblem,
|
|
board: Polygon,
|
|
options: RoutingOptions,
|
|
*,
|
|
priority: frozenset[str] = frozenset(),
|
|
) -> dict[str, RoutingResult]:
|
|
world = RoutingWorld.from_problem(problem, board=board, use_dynamic_grid=False)
|
|
ordered = ordered_nets(problem.nets, options.congestion.net_order)
|
|
if priority:
|
|
ordered.sort(key=lambda net: net.net_id not in priority)
|
|
|
|
paths = {}
|
|
for net in ordered:
|
|
seed = problem.initial_paths.get(net.net_id)
|
|
if seed is None or options.search.seed_geometry_error(seed):
|
|
continue
|
|
path = materialize_path_seed(
|
|
seed, start=net.start, net_width=net.width, search=options.search, clearance=problem.clearance, bounds=problem.bounds,
|
|
)
|
|
if path and path[-1].end_port == net.target:
|
|
report = world.verify_path_report(net.net_id, path)
|
|
if report.is_valid:
|
|
paths[net.net_id] = RoutingResult(net.net_id, path, reached_target=True, report=report, effective_net=net)
|
|
world.add_route(net.net_id, path)
|
|
for net in ordered:
|
|
if net.net_id in problem.initial_paths:
|
|
continue
|
|
forward, lateral = port_local_coordinates(net.start, net.target.x, net.target.y)
|
|
if net.start.r != net.target.r or forward <= 0 or lateral:
|
|
continue
|
|
component = Straight.generate(net.start, forward, net.width, dilation=problem.clearance / 2)
|
|
report = world.verify_path_report(net.net_id, (component,))
|
|
if report.is_valid:
|
|
paths[net.net_id] = RoutingResult(net.net_id, (component,), reached_target=True, report=report, effective_net=net)
|
|
world.add_route(net.net_id, (component,))
|
|
return paths
|
|
|
|
|
|
def _disconnected_nets(
|
|
problem: RoutingProblem,
|
|
board: Polygon,
|
|
options: RoutingOptions,
|
|
direct: dict[str, RoutingResult],
|
|
) -> frozenset[str]:
|
|
_, physical_bends = resolve_bend_geometry(options.search)
|
|
if physical_bends != "arc":
|
|
return frozenset()
|
|
|
|
residual = [net for net in problem.nets if net.net_id not in direct]
|
|
if not residual:
|
|
return frozenset()
|
|
obstacles = problem._blocking_polygons + tuple(shape for result in direct.values() for shape in result.locked_geometry)
|
|
by_width: dict[float, list[NetSpec]] = {}
|
|
for net in residual:
|
|
by_width.setdefault(net.width, []).append(net)
|
|
|
|
def free_regions(width: float) -> tuple[Polygon, ...]:
|
|
# Allow the whole board to centerlines, including flush ports. Rounded
|
|
# buffers and a small under-dilation keep this test optimistic.
|
|
padding = max(0.0, problem.clearance + width / 2 - max(problem.safety_zone_radius, TOLERANCE_LINEAR))
|
|
forbidden = shapely.union_all([shape.buffer(padding) for shape in obstacles])
|
|
regions = tuple(region for region in shapely.get_parts(board.difference(forbidden)) if region.area > 0)
|
|
for region in regions:
|
|
shapely.prepare(region)
|
|
return regions
|
|
|
|
widest = max(by_width)
|
|
shared_regions = free_regions(widest)
|
|
disconnected = set()
|
|
for width, nets in by_width.items():
|
|
if width == widest and len(shared_regions) < 2:
|
|
continue
|
|
regions = shared_regions if width == widest else None
|
|
for net in nets:
|
|
start, target = Point(net.start.x, net.start.y), Point(net.target.x, net.target.y)
|
|
if width != widest and any(region.covers(start) and region.covers(target) for region in shared_regions):
|
|
continue
|
|
if regions is None:
|
|
regions = free_regions(width)
|
|
if len(regions) < 2:
|
|
break
|
|
start_regions = {idx for idx, region in enumerate(regions) if region.covers(start)}
|
|
target_regions = {idx for idx, region in enumerate(regions) if region.covers(target)}
|
|
if start_regions and target_regions and start_regions.isdisjoint(target_regions):
|
|
disconnected.add(net.net_id)
|
|
return frozenset(disconnected)
|
|
|
|
|
|
def _plan_locks(
|
|
problem: RoutingProblem,
|
|
board: Polygon,
|
|
options: RoutingOptions,
|
|
*,
|
|
check_connectivity: bool = True,
|
|
priority: frozenset[str] = frozenset(),
|
|
) -> LockPlan:
|
|
direct = _direct_paths(problem, board, options, priority=priority)
|
|
disconnected = _disconnected_nets(problem, board, options, direct) if direct and check_connectivity else frozenset()
|
|
return LockPlan(direct, disconnected)
|
|
|
|
|
|
def _prefer_connected_locks(problem: RoutingProblem, board: Polygon, options: RoutingOptions, locks: LockPlan) -> LockPlan:
|
|
if not locks.disconnected:
|
|
return locks
|
|
candidate = _plan_locks(problem, board, options, priority=locks.disconnected)
|
|
return candidate if len(candidate.disconnected) < len(locks.disconnected) else locks
|
|
|
|
|
|
def _alternate_locks(
|
|
problem: RoutingProblem,
|
|
board: Polygon,
|
|
options: RoutingOptions,
|
|
locks: LockPlan,
|
|
*,
|
|
check_connectivity: bool = True,
|
|
) -> LockPlan | None:
|
|
if not 0 < len(locks.direct) < len(problem.nets) or options.search.node_limit <= 1:
|
|
return None
|
|
priority = frozenset(net.net_id for net in problem.nets if net.net_id not in locks.direct)
|
|
candidate = _plan_locks(problem, board, options, check_connectivity=check_connectivity, priority=priority)
|
|
if candidate.direct.keys() != locks.direct.keys() and len(candidate.disconnected) <= len(locks.disconnected):
|
|
return candidate
|
|
return None
|
|
|
|
|
|
def _split_search_budget(options: RoutingOptions, probe_limit: int) -> tuple[RoutingOptions, RoutingOptions]:
|
|
remaining = options.search.node_limit - probe_limit
|
|
first_limit = remaining // 2
|
|
return (
|
|
replace(options, search=replace(options.search, node_limit=first_limit)),
|
|
replace(options, search=replace(options.search, node_limit=remaining - first_limit)),
|
|
)
|
|
|
|
|
|
def _residual_problem(problem: RoutingProblem, locks: LockPlan) -> RoutingProblem:
|
|
if not locks.direct and not locks.disconnected:
|
|
return problem
|
|
residual = tuple(net for net in problem.nets if net.net_id not in locks.direct and net.net_id not in locks.disconnected)
|
|
locked = tuple(FixedRoute.from_result(result) for result in locks.direct.values())
|
|
initial_paths = {net.net_id: problem.initial_paths[net.net_id] for net in residual if net.net_id in problem.initial_paths}
|
|
return replace(
|
|
problem, nets=residual, initial_paths=initial_paths, fixed_routes=problem.fixed_routes + locked,
|
|
)
|
|
|
|
|
|
def _route_residual(
|
|
problem: RoutingProblem,
|
|
options: RoutingOptions,
|
|
locks: LockPlan,
|
|
*,
|
|
residual_mode: Literal["guide", "seed"] | None = None,
|
|
run_route: RouteCall = route_once,
|
|
) -> tuple[RoutingRunResult, RoutingStage]:
|
|
residual_problem = _residual_problem(problem, locks)
|
|
direct = locks.direct
|
|
residual = residual_problem.nets
|
|
if not residual:
|
|
mode = "off"
|
|
elif residual_mode is not None:
|
|
mode = residual_mode
|
|
else:
|
|
max_offset = 2 * max(options.search.sbend_radii, default=0)
|
|
mode = "guide" if any(_is_short_shift(net, max_offset) for net in residual) else "seed"
|
|
run = run_route(residual_problem, options=replace(options, topology=replace(options.topology, mode=mode)))
|
|
skipped = tuple(sorted(locks.disconnected))
|
|
return (
|
|
replace(run, results_by_net={**direct, **run.results_by_net, **{net_id: RoutingResult(net_id, ()) for net_id in skipped}}),
|
|
RoutingStage(
|
|
mode,
|
|
tuple(direct),
|
|
run.metrics.nodes_expanded,
|
|
options.search.node_limit,
|
|
skipped,
|
|
planner="direct" if direct and not residual else "",
|
|
),
|
|
)
|
|
|
|
|
|
def _trial(run: RoutingRunResult, stage: RoutingStage, *, score: Scorer) -> Trial:
|
|
outside = tuple(net_id for net_id, result in run.results_by_net.items() if result.report.out_of_bounds)
|
|
valid_costs = {net_id: score(result) for net_id, result in run.results_by_net.items() if result.is_valid}
|
|
stage = replace(stage, valid_net_ids=tuple(valid_costs), out_of_bounds_net_ids=outside)
|
|
return Trial(run, stage, valid_costs)
|
|
|
|
|
|
def _lattice_probe(problem: RoutingProblem, options: RoutingOptions, limit: int, *, run_route: RouteCall, check_trial: CheckTrial) -> Trial:
|
|
probe_options = replace(
|
|
options,
|
|
search=replace(options.search, node_limit=limit),
|
|
congestion=replace(options.congestion, max_iterations=min(1, options.congestion.max_iterations)),
|
|
topology=replace(options.topology, mode="off"),
|
|
)
|
|
run = run_route(problem, options=probe_options)
|
|
return check_trial(run, RoutingStage("off", (), run.metrics.nodes_expanded, limit, kind="lattice-probe"))
|
|
|
|
|
|
def _lock_near_new_port(problem: RoutingProblem, options: RoutingOptions, first: LockPlan, retry: LockPlan) -> bool:
|
|
bend_radius = min(options.search.bend_radii, default=0.0)
|
|
removed = tuple(shape for net_id in first.direct.keys() - retry.direct.keys() for shape in first.direct[net_id].locked_geometry)
|
|
added = retry.direct.keys() - first.direct.keys()
|
|
return any(
|
|
shape.distance(Point(port.x, port.y)) < bend_radius
|
|
for net in problem.nets
|
|
if net.net_id in added
|
|
for port in (net.start, net.target)
|
|
for shape in removed
|
|
)
|
|
|
|
|
|
def _direct_trials(
|
|
problem: RoutingProblem,
|
|
board: Polygon,
|
|
options: RoutingOptions,
|
|
strategy: str,
|
|
*,
|
|
check_trial: CheckTrial,
|
|
run_route: RouteCall = route_once,
|
|
) -> list[Trial]:
|
|
def check(run: RoutingRunResult, stage: RoutingStage) -> Trial:
|
|
return check_trial(run, replace(stage, policy=strategy))
|
|
|
|
locks = _prefer_connected_locks(problem, board, options, _plan_locks(problem, board, options))
|
|
retry_locks = _alternate_locks(problem, board, options, locks)
|
|
first_options = options
|
|
retry_options = options
|
|
probe_limit = 0
|
|
if retry_locks is not None:
|
|
if strategy == "direct-probe-near-port" and _lock_near_new_port(problem, options, locks, retry_locks):
|
|
probe_limit = min(32, options.search.node_limit // 3)
|
|
first_options, retry_options = _split_search_budget(options, probe_limit)
|
|
|
|
trials = []
|
|
if probe_limit:
|
|
probe = _lattice_probe(problem, options, probe_limit, run_route=run_route, check_trial=check)
|
|
trials.append(probe)
|
|
if len(probe.valid_costs) == len(problem.nets):
|
|
return trials
|
|
|
|
first = check(*_route_residual(problem, first_options, locks, run_route=run_route))
|
|
trials.append(first)
|
|
if retry_locks is not None and len(first.valid_costs) < len(problem.nets):
|
|
trials.append(check(*_route_residual(problem, retry_options, retry_locks, run_route=run_route)))
|
|
return trials
|
|
|
|
|
|
def _best_trial(trials: list[Trial]) -> Trial:
|
|
candidates = (trial for trial in trials if trial.selectable)
|
|
best = next(candidates)
|
|
for trial in candidates:
|
|
if trial.improves_on(best):
|
|
best = trial
|
|
return best
|