"""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 resolve_bend_geometry from inire.results import RoutingResult, RoutingStage from inire.router._congestion_policy import ordered_nets 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]: if problem.initial_paths: return {} world = RoutingWorld(clearance=problem.clearance, safety_zone_radius=problem.safety_zone_radius) for obstacle in problem.static_obstacles: world.add_static_obstacle(obstacle) 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: 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) if any(not board.covers(shape) for shape in component.physical_geometry): continue 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) world.add_path(net.net_id, component.collision_geometry, dilated_geometry=component.dilated_collision_geometry) 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.static_obstacles + 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) disconnected = set() for width, nets in by_width.items(): # 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) if len(regions) < 2: continue for region in regions: shapely.prepare(region) for net in nets: start, target = Point(net.start.x, net.start.y), Point(net.target.x, net.target.y) 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(shape for result in locks.direct.values() for shape in result.locked_geometry) return replace(problem, nets=residual, static_obstacles=problem.static_obstacles + 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]: direct = locks.direct problem = _residual_problem(problem, locks) 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(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, board: Polygon, *, score: Scorer) -> Trial: outside = tuple( net_id for net_id, result in run.results_by_net.items() if result.report.out_of_bounds or any(not board.covers(shape) for shape in result.locked_geometry) ) if outside: results = dict(run.results_by_net) for net_id in outside: result = results[net_id] if not result.report.out_of_bounds: results[net_id] = replace(result, report=replace(result.report, out_of_bounds=True)) trace = run.conflict_trace if trace and trace[-1].stage == "final": final = trace[-1] checked = replace( final, completed_net_ids=tuple(net_id for net_id in final.completed_net_ids if net_id not in outside), nets=tuple( replace(net, outcome=results[net.net_id].outcome, report=results[net.net_id].report) if net.net_id in outside else net for net in final.nets ), ) trace = (*trace[:-1], checked) run = replace(run, results_by_net=results, conflict_trace=trace) 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