Select and verify topological and constructive routing plans

This commit is contained in:
Jan Petykiewicz 2026-11-26 11:57:43 -08:00
commit be3222e5ae
21 changed files with 2868 additions and 68 deletions

View file

@ -13,8 +13,11 @@ from .model import (
RoutingOptions as RoutingOptions, RoutingOptions as RoutingOptions,
RoutingProblem as RoutingProblem, RoutingProblem as RoutingProblem,
SearchOptions as SearchOptions, SearchOptions as SearchOptions,
TopologyOptions as TopologyOptions,
) # noqa: PLC0414 ) # noqa: PLC0414
from .results import ( # noqa: PLC0414 from .results import ( # noqa: PLC0414
AutomaticRoutingReport as AutomaticRoutingReport,
CapacityLimit as CapacityLimit,
ComponentConflictTrace as ComponentConflictTrace, ComponentConflictTrace as ComponentConflictTrace,
ConflictTraceEntry as ConflictTraceEntry, ConflictTraceEntry as ConflictTraceEntry,
FrontierPruneSample as FrontierPruneSample, FrontierPruneSample as FrontierPruneSample,
@ -26,6 +29,9 @@ from .results import ( # noqa: PLC0414
PrePairNetTrace as PrePairNetTrace, PrePairNetTrace as PrePairNetTrace,
RoutingResult as RoutingResult, RoutingResult as RoutingResult,
RoutingRunResult as RoutingRunResult, RoutingRunResult as RoutingRunResult,
RoutingStage as RoutingStage,
RoutingTiming as RoutingTiming,
TopologyReport as TopologyReport,
) )
from .seeds import Bend90Seed as Bend90Seed, PathSeed as PathSeed, SBendSeed as SBendSeed, StraightSeed as StraightSeed # noqa: PLC0414 from .seeds import Bend90Seed as Bend90Seed, PathSeed as PathSeed, SBendSeed as SBendSeed, StraightSeed as StraightSeed # noqa: PLC0414
@ -39,24 +45,20 @@ def route(
options: RoutingOptions | None = None, options: RoutingOptions | None = None,
iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None, iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None,
) -> RoutingRunResult: ) -> RoutingRunResult:
from .router._stack import build_routing_stack
resolved_options = RoutingOptions() if options is None else options resolved_options = RoutingOptions() if options is None else options
stack = build_routing_stack(problem, resolved_options) if resolved_options.topology.mode == "automatic":
finder = stack.finder from .router._automatic import route_automatic # noqa: PLC0415
results = finder.route_all(iteration_callback=iteration_callback)
return RoutingRunResult( return route_automatic(problem, resolved_options, iteration_callback)
results_by_net=results,
metrics=finder.metrics.snapshot(), from .router._stack import route_once # noqa: PLC0415
expanded_nodes=tuple(finder.accumulated_expanded_nodes),
conflict_trace=tuple(finder.conflict_trace), return route_once(problem, options=resolved_options, iteration_callback=iteration_callback)
frontier_trace=tuple(finder.frontier_trace),
pre_pair_frontier_trace=finder.pre_pair_frontier_trace,
iteration_trace=tuple(finder.iteration_trace),
)
__all__ = [ __all__ = [
"AutomaticRoutingReport",
"Bend90Seed", "Bend90Seed",
"CapacityLimit",
"CongestionOptions", "CongestionOptions",
"ComponentConflictTrace", "ComponentConflictTrace",
"ConflictTraceEntry", "ConflictTraceEntry",
@ -77,8 +79,12 @@ __all__ = [
"RoutingProblem", "RoutingProblem",
"RoutingResult", "RoutingResult",
"RoutingRunResult", "RoutingRunResult",
"RoutingStage",
"RoutingTiming",
"SBendSeed", "SBendSeed",
"SearchOptions", "SearchOptions",
"StraightSeed", "StraightSeed",
"TopologyOptions",
"TopologyReport",
"route", "route",
] ]

View file

@ -2,6 +2,7 @@ from __future__ import annotations
import warnings import warnings
from dataclasses import dataclass, field from dataclasses import dataclass, field
from math import isfinite
from typing import TYPE_CHECKING, Literal from typing import TYPE_CHECKING, Literal
from shapely.geometry import Polygon from shapely.geometry import Polygon
@ -100,6 +101,12 @@ class CongestionOptions:
class RefinementOptions: class RefinementOptions:
enabled: bool = True enabled: bool = True
objective: ObjectiveWeights | None = None objective: ObjectiveWeights | None = None
max_windows_per_net: int | None = 24
def __post_init__(self) -> None:
limit = self.max_windows_per_net
if limit is not None and (isinstance(limit, bool) or not isinstance(limit, int) or limit < 1):
raise ValueError("max_windows_per_net must be a positive integer or None")
@dataclass(frozen=True, slots=True) @dataclass(frozen=True, slots=True)
@ -111,6 +118,34 @@ class DiagnosticsOptions:
capture_pre_pair_frontier_trace: bool = False capture_pre_pair_frontier_trace: bool = False
@dataclass(frozen=True, slots=True)
class TopologyOptions:
mode: Literal["off", "guide", "seed", "bundle", "automatic"] = "automatic"
max_corridors: int = 3
guide_strength: float = 0.75
seed_node_limit: int = 600
infer_terminal_headings: bool = False
automatic_cost: Literal["selective", "always", "never"] = "selective"
automatic_length_weights: tuple[float, float, float] | None = None
def __post_init__(self) -> None:
if self.mode not in ("off", "guide", "seed", "bundle", "automatic"):
raise ValueError(f"Unknown topology mode: {self.mode!r}")
if not isinstance(self.max_corridors, int) or self.max_corridors < 1:
raise ValueError("max_corridors must be a positive integer")
if not isfinite(self.guide_strength) or self.guide_strength < 0:
raise ValueError("guide_strength must be finite and nonnegative")
if not isinstance(self.seed_node_limit, int) or self.seed_node_limit < 1:
raise ValueError("seed_node_limit must be a positive integer")
if self.automatic_cost not in ("selective", "always", "never"):
raise ValueError(f"Unknown automatic cost policy: {self.automatic_cost!r}")
if self.automatic_length_weights is not None:
weights = tuple(self.automatic_length_weights)
if len(weights) != 3 or any(not isfinite(weight) or weight < 0 for weight in weights):
raise ValueError("automatic_length_weights must contain three finite, nonnegative weights")
object.__setattr__(self, "automatic_length_weights", weights)
@dataclass(frozen=True, slots=True) @dataclass(frozen=True, slots=True)
class RoutingOptions: class RoutingOptions:
search: SearchOptions = field(default_factory=SearchOptions) search: SearchOptions = field(default_factory=SearchOptions)
@ -118,6 +153,7 @@ class RoutingOptions:
congestion: CongestionOptions = field(default_factory=CongestionOptions) congestion: CongestionOptions = field(default_factory=CongestionOptions)
refinement: RefinementOptions = field(default_factory=RefinementOptions) refinement: RefinementOptions = field(default_factory=RefinementOptions)
diagnostics: DiagnosticsOptions = field(default_factory=DiagnosticsOptions) diagnostics: DiagnosticsOptions = field(default_factory=DiagnosticsOptions)
topology: TopologyOptions = field(default_factory=TopologyOptions)
@dataclass(frozen=True, slots=True) @dataclass(frozen=True, slots=True)

View file

@ -22,10 +22,11 @@ class RoutingReport:
dynamic_collision_count: int = 0 dynamic_collision_count: int = 0
self_collision_count: int = 0 self_collision_count: int = 0
total_length: float = 0.0 total_length: float = 0.0
out_of_bounds: bool = False
@property @property
def collision_count(self) -> int: def collision_count(self) -> int:
return self.static_collision_count + self.dynamic_collision_count + self.self_collision_count return self.static_collision_count + self.dynamic_collision_count + self.self_collision_count + int(self.out_of_bounds)
@property @property
def is_valid(self) -> bool: def is_valid(self) -> bool:
@ -273,6 +274,88 @@ class RoutingResult:
return PathSeed(tuple(component.move_spec for component in self.path)) return PathSeed(tuple(component.move_spec for component in self.path))
@dataclass(frozen=True, slots=True)
class TopologyReport:
corridor_counts: tuple[tuple[str, int], ...] = ()
seeded_net_ids: tuple[str, ...] = ()
seed_nodes_expanded: int = 0
RoutingOperation = Literal["plan", "verify", "search", "refine"]
def _planner_for_mode(mode: str) -> str:
return {"off": "lattice", "guide": "portal-guide", "seed": "corridor-seed"}.get(mode, mode)
@dataclass(frozen=True, slots=True)
class RoutingTiming:
"""Exclusive elapsed time for an operation, including unsuccessful work."""
operation: RoutingOperation
duration_s: float
planner: str | None = None
mode: str | None = None
policy: str | None = None
@dataclass(frozen=True, slots=True)
class RoutingStage:
"""One routing or verification attempt in an automatic run."""
mode: str
direct_net_ids: tuple[str, ...]
nodes_expanded: int
node_limit: int
skipped_net_ids: tuple[str, ...] = ()
kind: str = "route"
net_order: str | None = None
incumbent_net_ids: tuple[str, ...] = ()
valid_net_ids: tuple[str, ...] = ()
policy: str | None = None
retry_reason: str | None = None
out_of_bounds_net_ids: tuple[str, ...] = ()
planner: str = ""
operation: RoutingOperation = "search"
def __post_init__(self) -> None:
if not self.planner:
object.__setattr__(self, "planner", _planner_for_mode(self.mode))
@dataclass(frozen=True, slots=True)
class CapacityLimit:
"""A vertical cut that bounds the number of routes through the board."""
cut_x: float
crossing_nets: int
tracks: int
max_routed: int
@dataclass(frozen=True, slots=True)
class AutomaticRoutingReport:
"""Planner selection, verified coverage, and geometry-based upper bounds."""
stages: tuple[RoutingStage, ...]
selected_stage: int
max_routed: int
capacity_limit: CapacityLimit | None = None
port_conflicts: tuple[tuple[str, str], ...] = ()
planner_rejections: tuple[str, ...] = ()
cost_pass_performed: bool = False
timings: tuple[RoutingTiming, ...] = ()
duration_s: float = 0.0
@property
def selected_planner(self) -> str:
return self.stages[self.selected_stage].planner
@property
def verified_net_ids(self) -> tuple[str, ...]:
return self.stages[self.selected_stage].valid_net_ids
@dataclass(frozen=True, slots=True) @dataclass(frozen=True, slots=True)
class RoutingRunResult: class RoutingRunResult:
results_by_net: dict[str, RoutingResult] results_by_net: dict[str, RoutingResult]
@ -282,3 +365,5 @@ class RoutingRunResult:
frontier_trace: tuple[NetFrontierTrace, ...] = () frontier_trace: tuple[NetFrontierTrace, ...] = ()
pre_pair_frontier_trace: PrePairFrontierTraceEntry | None = None pre_pair_frontier_trace: PrePairFrontierTraceEntry | None = None
iteration_trace: tuple[IterationTraceEntry, ...] = () iteration_trace: tuple[IterationTraceEntry, ...] = ()
topology: TopologyReport | None = None
automatic: AutomaticRoutingReport | None = None

View file

@ -159,6 +159,13 @@ def add_node(
parent_p = parent.port parent_p = parent.port
end_p = result.end_port end_p = result.end_port
corridor = config.corridor
if (
corridor is not None
and config.restrict_to_corridor
and any(not corridor.footprint.covers(shape) for shape in result.physical_geometry)
):
return
if cache_key in context.hard_collision_set: if cache_key in context.hard_collision_set:
if frontier_trace is not None: if frontier_trace is not None:
@ -219,6 +226,9 @@ def add_node(
move_cost = max(0.001, move_cost - applied_bonus) move_cost = max(0.001, move_cost - applied_bonus)
next_seed_index = parent.seed_index + 1 next_seed_index = parent.seed_index + 1
if corridor is not None and config.corridor_strength:
move_cost += result.length * config.corridor_strength * (corridor.distance(parent_p) + corridor.distance(end_p)) / 2
if config.max_cost is not None and parent.g_cost + move_cost > config.max_cost: if config.max_cost is not None and parent.g_cost + move_cost > config.max_cost:
if frontier_trace is not None: if frontier_trace is not None:
frontier_trace.record("cost", move_type, parent.port.as_tuple(), state, result.total_dilated_bounds) frontier_trace.record("cost", move_type, parent.port.as_tuple(), state, result.total_dilated_bounds)
@ -267,6 +277,8 @@ def add_node(
context.metrics.total_congestion_candidate_precheck_skips += 1 context.metrics.total_congestion_candidate_precheck_skips += 1
else: else:
context.metrics.total_congestion_presence_skips += 1 context.metrics.total_congestion_presence_skips += 1
if total_overlaps and config.hard_congestion:
return
move_cost += total_overlaps * context.congestion_penalty move_cost += total_overlaps * context.congestion_penalty
g_cost = parent.g_cost + move_cost g_cost = parent.g_cost + move_cost
@ -277,11 +289,7 @@ def add_node(
metrics.total_pruned_closed_set += 1 metrics.total_pruned_closed_set += 1
return return
h_cost = context.cost_evaluator.h_manhattan( h_cost = config.estimate_remaining_cost(result.end_port, target, context)
result.end_port,
target,
min_bend_radius=context.min_bend_radius,
)
heapq.heappush( heapq.heappush(
open_set, open_set,
AStarNode( AStarNode(

View file

@ -264,6 +264,20 @@ def expand_moves(
continue continue
candidate_lengths.extend((dx_local - sbend_span, dx_local - 2.0 * sbend_span)) candidate_lengths.extend((dx_local - sbend_span, dx_local - 2.0 * sbend_span))
guide_offsets: set[int] = set()
if config.corridor is not None:
max_radius = max((*search_options.bend_radii, *search_options.sbend_radii), default=0.0)
for forward, lateral in config.corridor.nearby_anchors(cp, max_reach + 2 * max_radius):
candidate_lengths.append(forward)
candidate_lengths.extend(forward - radius for radius in search_options.bend_radii)
if search_options.sbend_offsets is None and abs(lateral) >= 1 and search_options.sbend_radii:
for radius in search_options.sbend_radii:
span = _sbend_forward_span(lateral, radius)
if span is not None:
candidate_lengths.append(forward - span)
if forward <= span + max_radius:
guide_offsets.add(round(lateral))
for length in _quantized_lengths(candidate_lengths, max_reach): for length in _quantized_lengths(candidate_lengths, max_reach):
if length < search_options.min_straight_length: if length < search_options.min_straight_length:
continue continue
@ -292,7 +306,7 @@ def expand_moves(
angle_to_target = 0.0 angle_to_target = 0.0
if dx_t != 0 or dy_t != 0: if dx_t != 0 or dy_t != 0:
angle_to_target = float((round((180.0 / math.pi) * math.atan2(dy_t, dx_t)) + 360.0) % 360.0) angle_to_target = float((round((180.0 / math.pi) * math.atan2(dy_t, dx_t)) + 360.0) % 360.0)
allow_backwards = dist_sq < 150 * 150 allow_backwards = config.restrict_to_corridor or dist_sq < 150 * 150
for radius in search_options.bend_radii: for radius in search_options.bend_radii:
for direction in ("CW", "CCW"): for direction in ("CW", "CCW"):
@ -328,6 +342,7 @@ def expand_moves(
explicit_offsets = search_options.sbend_offsets explicit_offsets = search_options.sbend_offsets
offsets: set[int] = {int(round(v)) for v in explicit_offsets or []} offsets: set[int] = {int(round(v)) for v in explicit_offsets or []}
offsets.update(guide_offsets)
if target.r == cp.r and 0 < dx_local <= 4 * max_sbend_r and 0 < abs(dy_local) < 2 * max_sbend_r: if target.r == cp.r and 0 < dx_local <= 4 * max_sbend_r and 0 < abs(dy_local) < 2 * max_sbend_r:
offsets.add(int(round(dy_local))) offsets.add(int(round(dy_local)))

View file

@ -11,6 +11,7 @@ if TYPE_CHECKING:
from inire.geometry.components import BendCollisionModel, BendPhysicalGeometry, ComponentResult from inire.geometry.components import BendCollisionModel, BendPhysicalGeometry, ComponentResult
from inire.geometry.primitives import Port from inire.geometry.primitives import Port
from inire.model import RoutingOptions, RoutingProblem from inire.model import RoutingOptions, RoutingProblem
from inire.router._topology import Corridor
from inire.router.cost import CostEvaluator from inire.router.cost import CostEvaluator
from inire.seeds import PathSegmentSeed from inire.seeds import PathSegmentSeed
@ -73,6 +74,17 @@ class SearchRunConfig:
skip_congestion: bool = False skip_congestion: bool = False
max_cost: float | None = None max_cost: float | None = None
self_collision_check: bool = False self_collision_check: bool = False
corridor: Corridor | None = None
corridor_strength: float = 0.0
restrict_to_corridor: bool = False
hard_congestion: bool = False
def estimate_remaining_cost(self, current: Port, target: Port, context: AStarContext) -> float:
evaluator = context.cost_evaluator
cost = evaluator.h_manhattan(current, target, min_bend_radius=context.min_bend_radius)
if self.restrict_to_corridor and self.corridor is not None and current != target:
return 0.4 * cost + 0.6 * evaluator.greedy_h_weight * self.corridor.remaining(current)
return cost
@classmethod @classmethod
def from_options( def from_options(
@ -89,6 +101,10 @@ class SearchRunConfig:
skip_congestion: bool = False, skip_congestion: bool = False,
max_cost: float | None = None, max_cost: float | None = None,
self_collision_check: bool = False, self_collision_check: bool = False,
corridor: Corridor | None = None,
corridor_strength: float = 0.0,
restrict_to_corridor: bool = False,
hard_congestion: bool = False,
) -> SearchRunConfig: ) -> SearchRunConfig:
search = options.search search = options.search
bend_collision_type, bend_physical_geometry = resolve_bend_geometry( bend_collision_type, bend_physical_geometry = resolve_bend_geometry(
@ -108,6 +124,10 @@ class SearchRunConfig:
skip_congestion=skip_congestion, skip_congestion=skip_congestion,
max_cost=max_cost, max_cost=max_cost,
self_collision_check=self_collision_check, self_collision_check=self_collision_check,
corridor=corridor,
corridor_strength=corridor_strength,
restrict_to_corridor=restrict_to_corridor,
hard_congestion=hard_congestion,
) )

567
inire/router/_automatic.py Normal file
View 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()

260
inire/router/_bundle.py Normal file
View file

@ -0,0 +1,260 @@
"""Constructive routing for ordered bundles with an outer return and paired barriers."""
from __future__ import annotations
from collections import defaultdict
from dataclasses import dataclass, replace
from itertools import pairwise
from math import ceil, floor, isfinite, isqrt, sqrt
from typing import TYPE_CHECKING
from shapely.geometry import box
from inire.geometry.primitives import Port
from inire.model import resolve_bend_geometry
from inire.router._waypoints import XY, compile_waypoints
if TYPE_CHECKING:
from inire.model import NetSpec, RoutingProblem, SearchOptions
Bounds = tuple[float, float, float, float]
@dataclass(frozen=True, slots=True)
class _Layout:
first: tuple[Bounds, Bounds]
last: tuple[Bounds, Bounds]
north: Bounds
south: Bounds
tower: Bounds
outer_return: NetSpec
short: NetSpec
lower: tuple[NetSpec, ...]
upper: tuple[NetSpec, ...]
@dataclass(frozen=True, slots=True)
class _Shift:
x: int
y: int
sbend: bool = False
def _identify_layout(problem: RoutingProblem, margin: float) -> _Layout:
columns: dict[tuple[float, float], list[Bounds]] = defaultdict(list)
for obstacle in problem.static_obstacles:
if not obstacle.equals(box(*obstacle.bounds)):
raise ValueError("Bundle routing requires axis-aligned rectangular obstacles")
x0, y0, x1, y1 = obstacle.bounds
columns[x0, x1].append((x0, y0, x1, y1))
paired = [tuple(sorted(column, key=lambda b: b[1])) for _, column in sorted(columns.items()) if len(column) == 2]
singles = [column[0] for column in columns.values() if len(column) == 1]
if len(paired) != 2 or len(singles) != 3 or len(columns) != 5:
raise ValueError("Bundle routing requires two paired barriers and three interior obstacles")
first, last = paired
tower = min(singles, key=lambda b: b[1])
north = max(singles, key=lambda b: b[3])
if tower == north:
raise ValueError("An ordered bundle needs separate north and tower obstacles")
(south,) = (b for b in singles if b not in (tower, north))
if not first[0][2] < min(north[0], south[0]) < max(north[2], south[2]) < tower[0] < last[0][0]:
raise ValueError("The paired barriers must enclose the north and south obstacles followed by the tower")
nets = sorted(problem.nets, key=lambda net: net.start.y)
if (
not nets
or len({(net.start.x, net.start.r, net.width) for net in nets}) != 1
or len({net.start.y for net in nets}) != len(nets)
or nets[0].start.r != 0
):
raise ValueError("Bundle routing requires equally wide eastbound launches on a common x coordinate")
if nets[0].start.x >= first[0][0] or any(net.target.x <= net.start.x for net in nets):
raise ValueError("Bundle routing requires launches before the first barrier and destinations to the east")
right = max(net.target.x for net in nets)
outer_return = nets[0]
interior = [net for net in nets[1:] if net.target.x < right]
if len(interior) != 1 or not north[2] < outer_return.target.x < tower[0]:
raise ValueError("Bundle routing requires a short route and an outer return to the north shelf")
short = interior[0]
if not (first[0][3] + margin <= short.start.y <= first[1][1] - margin and short.target.x < north[0]):
raise ValueError("The short route must leave through the first gap and end before the north obstacle")
lower = tuple(net for net in nets[1:] if net.start.y < short.start.y)
upper = tuple(net for net in nets if net.start.y > short.start.y)
through = (*lower, *upper)
if (
len(lower) < 2
or len(upper) < 3
or any(a.target.y >= b.target.y for a, b in pairwise(through))
or outer_return.target.y <= max(net.target.y for net in through)
):
raise ValueError("The through nets must retain their launch order below the return")
if not last[0][3] + margin <= upper[0].target.y <= last[1][1] - margin:
raise ValueError("The lowest upper net must terminate opposite the second gap")
return _Layout(first, last, north, south, tower, outer_return, short, lower, upper)
def _eastbound_launches(problem: RoutingProblem) -> RoutingProblem:
nets = tuple(replace(net, start=Port(net.start.x, net.start.y, 0)) for net in problem.nets)
return replace(problem, nets=nets)
def ordered_bundle_terminal_headings(problem: RoutingProblem) -> RoutingProblem:
"""Resolve terminal headings from the layout without assigning tracks."""
if not problem.nets:
return problem
problem = _eastbound_launches(problem)
layout = _identify_layout(problem, problem.nets[0].width / 2 + problem.clearance)
nets = tuple(replace(net, target=Port(net.target.x, net.target.y, 180 if net == layout.outer_return else 0)) for net in problem.nets)
return replace(problem, nets=nets)
def _exact_offsets(radius: int) -> tuple[int, ...]:
return tuple(d for d in range(1, 2 * radius) if isqrt(d * (4 * radius - d)) ** 2 == d * (4 * radius - d))
def _assign_shifts(
layout: _Layout,
radius: int,
margin: float,
pitch: int,
floor_lane: int,
) -> tuple[dict[str, list[_Shift]], int]:
short, lower, upper = layout.short, layout.lower, layout.upper
middle, *ascending, shelf = upper
north, south, tower = layout.north, layout.south, layout.tower
last_lower, last_upper = layout.last
stagger = max(pitch, radius // 2)
launch = ceil(short.start.x) + 2 * radius
shifts: dict[str, list[_Shift]] = {net.net_id: [] for net in (short, *lower, *upper)}
# Account for the perimeter return first, then fill the remaining bottom tracks.
bottom_capacity = 1 + floor((tower[1] - margin - 1 - floor_lane) / pitch)
if bottom_capacity < 1:
raise ValueError("The tower blocks the perimeter return")
above_tower = lower[bottom_capacity - 1 :]
for index, net in enumerate(lower, start=1):
shifts[net.net_id].append(_Shift(launch + index * stagger, floor_lane + index * pitch))
upper_base = ceil(max(layout.first[1][3] + margin + 1, short.target.y + radius))
for index, net in enumerate(upper[:-1]):
shifts[net.net_id].append(_Shift(launch + (len(upper) - 1 - index) * stagger, upper_base + index * pitch))
shelf_launch = ceil(max(north[3] + margin + 1, upper_base + (len(upper) - 1) * pitch))
shifts[shelf.net_id].append(_Shift(launch, shelf_launch))
shifts[short.net_id].append(_Shift(int(short.target.x) - 2 * radius, int(short.target.y)))
# Pack descending tracks beside the short terminal. The limiting turn must
# already be below the obstacle keepout when its arc reaches the left wall.
drop = ceil(short.target.x + pitch)
available = north[0] - margin - drop - (len(upper) - 2) * pitch
if available <= 0:
raise ValueError("The side of the north obstacle has insufficient track capacity")
run = min(radius, available)
max_y = floor(north[1] - margin - radius + sqrt(run * (2 * radius - run)) - 1)
for index, net in enumerate(upper[:-1]):
y = max_y - (len(upper) - 2 - index) * pitch
shifts[net.net_id].append(_Shift(drop + index * pitch, y))
# The outermost eastbound track traverses above the north obstacle. Pick a
# final shelf that can reach its destination with an exact lattice S-bend.
first_top = ceil(last_upper[3] + margin + 0.1)
top_lanes = [first_top + i * pitch for i in range(len(ascending))]
offsets = _exact_offsets(radius)
shelf_options = [
int(shelf.target.y) + offset for offset in offsets if top_lanes[-1] + pitch <= shelf.target.y + offset <= shelf_launch - 2 * radius
]
if not shelf_options:
raise ValueError("The north shelf has no exact S-bend to the outer eastbound target")
shifts[shelf.net_id].append(_Shift(ceil(north[2] + margin + radius + 1), min(shelf_options)))
side_rise = ceil(north[2] + margin + radius + pitch)
for index, (net, y) in enumerate(zip(reversed(ascending), reversed(top_lanes), strict=True)):
shifts[net.net_id].append(_Shift(side_rise + index * stagger, y))
tower_floor = ceil(tower[3] + margin + 1)
tower_lanes = [tower_floor + i * pitch for i in range(len(above_tower))]
middle_y = shifts[middle.net_id][-1].y
middle_rise = side_rise + (len(ascending) - 1) * stagger
middle_floor = tower_lanes[-1] + pitch if tower_lanes else tower_floor
if middle_y < middle_floor:
shift = next((d for d in offsets if middle_y + d >= middle_floor), None)
if shift is None:
raise ValueError("The middle track cannot rise above the tower with a lattice S-bend")
shifts[middle.net_id].append(_Shift(middle_rise, middle_y + shift, sbend=True))
middle_rise += isqrt(shift * (4 * radius - shift))
lower_rise = max(ceil(south[2] + margin + radius + 1), middle_rise)
for index, (net, y) in enumerate(zip(reversed(above_tower), reversed(tower_lanes), strict=True)):
shifts[net.net_id].append(_Shift(lower_rise + index * stagger, y))
lower_drop = ceil(tower[2] + margin + radius + 1)
highest_lane = floor(last_lower[1] - margin - 1)
lower_lanes = []
for net in reversed(above_tower):
target_y = int(net.target.y)
y = highest_lane
# Align with the target if it fits below the barrier, or leave
# two radii for the quarter turns on the final rise.
if 0 < abs(target_y - y) < 2 * radius:
y = target_y if target_y < y else target_y - 2 * radius
if y < floor_lane + bottom_capacity * pitch:
raise ValueError("The bottom lanes cannot leave room for the final turns")
lower_lanes.append(y)
highest_lane = y - pitch
for index, (net, y) in enumerate(zip(above_tower, reversed(lower_lanes), strict=True)):
shifts[net.net_id].append(_Shift(lower_drop + index * stagger, y))
shifts[middle.net_id].append(_Shift(lower_drop + len(above_tower) * stagger, int(middle.target.y)))
finish = ceil(last_lower[2] + margin + radius + 1)
for group in (reversed(lower), iter(ascending)):
for index, net in enumerate(group):
shifts[net.net_id].append(_Shift(finish + index * stagger, int(net.target.y)))
shifts[shelf.net_id].append(_Shift(finish + len(ascending) * stagger, int(shelf.target.y), sbend=True))
return shifts, launch
def plan_ordered_bundle(problem: RoutingProblem, search: SearchOptions, *, infer_terminal_headings: bool) -> RoutingProblem:
"""Generate path seeds from an ordered bundle layout for router verification."""
if problem.initial_paths:
raise ValueError("Bundle routing requires an unseeded problem")
if not problem.nets:
return problem
_, physical_geometry = resolve_bend_geometry(search)
bend = min(search.bend_radii, default=0.0)
if not isfinite(bend) or bend <= 0 or bend != int(bend) or bend not in search.sbend_radii or physical_geometry != "arc":
raise ValueError("Bundle routing needs a common integer radius for circular bends and S-bends")
radius = int(bend)
width = problem.nets[0].width
if not isfinite(width) or width <= 0:
raise ValueError("Bundle routing requires a positive waveguide width")
margin = width / 2 + problem.clearance
pitch = ceil(width + problem.clearance) + 1
floor_lane = ceil(problem.bounds[1] + width / 2)
if infer_terminal_headings:
# The supported arrangement puts every launch to the left of its
# destination and of the first barrier, so the bundle launches east.
problem = _eastbound_launches(problem)
layout = _identify_layout(problem, margin)
shifts, launch = _assign_shifts(layout, radius, margin, pitch, floor_lane)
seeds = {}
updated_nets = []
for net in problem.nets:
start = int(net.start.x), int(net.start.y)
target = int(net.target.x), int(net.target.y)
if net == layout.outer_return:
right_turn = ceil(max(n.target.x for n in problem.nets) + radius + pitch)
points = [start, (launch, start[1]), (launch, floor_lane), (right_turn, floor_lane), (right_turn, target[1]), target]
else:
points: list[XY] = [start]
y = start[1]
for shift in shifts[net.net_id]:
span = abs(shift.y - y)
if not span:
continue
advance = isqrt(span * (4 * radius - span)) if shift.sbend else 0
points.extend(((shift.x, y), (shift.x + advance, shift.y)))
y = shift.y
points.append(target)
seed, arrival = compile_waypoints(tuple(points), net.start, radius)
if not infer_terminal_headings and arrival.r != net.target.r:
raise ValueError(f"Bundle routing needs arrival heading {arrival.r} for {net.net_id}. Enable point-terminal inference to allow it.")
seeds[net.net_id] = seed
updated_nets.append(replace(net, target=arrival))
return replace(problem, nets=tuple(updated_nets), initial_paths=seeds)

465
inire/router/_columns.py Normal file
View file

@ -0,0 +1,465 @@
"""Construct ordered routes through nonoverlapping columns of rectangles."""
from __future__ import annotations
from collections import defaultdict
from dataclasses import dataclass
from functools import lru_cache
from itertools import combinations_with_replacement, pairwise, product
from math import acos, ceil, cos, floor, gcd, isfinite, isqrt, sin
from typing import TYPE_CHECKING
from shapely.geometry import LineString, box
from inire.model import resolve_bend_geometry
from inire.seeds import PathSeed, SBendSeed, StraightSeed
if TYPE_CHECKING:
from collections.abc import Callable, Iterator, Mapping
from inire.geometry.primitives import Port
from inire.model import NetSpec, RoutingProblem, SearchOptions
from inire.seeds import PathSegmentSeed
Profile = tuple[int, ...]
Gap = tuple[float, float]
Window = tuple[int, int]
@dataclass(frozen=True, slots=True)
class _Track:
net: NetSpec
left: Port
right: Port
westbound: bool
@dataclass(frozen=True, slots=True)
class _Column:
span: Window
openings: tuple[Gap, ...]
@dataclass(frozen=True, slots=True)
class _BendSequence:
offsets: tuple[int, ...]
span: int
cost: float
def rectangular_obstacle_bounds(problem: RoutingProblem) -> tuple[tuple[float, float, float, float], ...] | None:
bounds = tuple(tuple(shape.bounds) for shape in problem.static_obstacles)
if any(shape.is_empty or not shape.equals(box(*extent)) for shape, extent in zip(problem.static_obstacles, bounds, strict=True)):
return None
return bounds
def open_intervals(solid: list[Gap], ymin: float, ymax: float) -> tuple[Gap, ...]:
openings = []
cursor = ymin
for bottom, top in sorted(solid):
if top <= ymin or bottom >= ymax:
continue
if cursor < bottom:
openings.append((cursor, bottom))
cursor = max(cursor, top)
if cursor < ymax:
openings.append((cursor, ymax))
return tuple(openings)
def _columns(problem: RoutingProblem, start: int, finish: int) -> tuple[_Column, ...]:
# A bounding rectangle only reserves extra space in this candidate
# planner. Capacity proofs still require the actual rectangular obstacles.
extents: dict[Window, list[Gap]] = defaultdict(list)
for obstacle in problem.static_obstacles:
if obstacle.is_empty:
continue
left, bottom, right, top = obstacle.bounds
lo, hi = floor(left), ceil(right)
if lo < start or hi > finish:
return ()
extents[lo, hi].append((bottom, top))
columns = []
previous = start
for (left, right), solid in sorted(extents.items()):
if left <= previous:
return ()
openings = open_intervals(solid, problem.bounds[1], problem.bounds[3])
if not openings:
return ()
columns.append(_Column((left, right), openings))
previous = right
return tuple(columns)
def _ordered_tracks(problem: RoutingProblem) -> tuple[_Track, ...]:
tracks = []
for net in problem.nets:
if net.start.r == net.target.r == 0 and net.start.x < net.target.x:
tracks.append(_Track(net, net.start, net.target, False))
elif net.start.r == net.target.r == 180 and net.start.x > net.target.x:
tracks.append(_Track(net, net.target, net.start, True))
else:
return ()
tracks.sort(key=lambda track: track.left.y)
if any(a.left.y >= b.left.y or a.right.y >= b.right.y for a, b in pairwise(tracks)):
return ()
return tuple(tracks)
def _round_up(y: float, residue: int, modulus: int) -> int:
return ceil((y - residue) / modulus) * modulus + residue
def _round_down(y: float, residue: int, modulus: int) -> int:
return floor((y - residue) / modulus) * modulus + residue
def _pack_forward(
lower: list[int],
upper: list[int],
spacing: list[float],
residues: Profile,
desired: tuple[float, ...],
modulus: int,
reachable: tuple[Profile, ...] = (),
) -> Profile:
row = []
for i, (band_bottom, high, residue, y) in enumerate(zip(lower, upper, residues, desired, strict=True)):
low = band_bottom
if row:
low = max(low, _round_up(row[-1] + spacing[i - 1], residue, modulus))
choice = min(high, max(low, round((y - residue) / modulus) * modulus + residue))
if reachable:
choice = min((v for v in reachable[i] if low <= v <= high), key=lambda v: (abs(v - y), v), default=choice)
row.append(choice)
return tuple(row)
def _band_profiles(
problem: RoutingProblem,
opening: Gap,
widths: tuple[float, ...],
residues: Profile,
desired: tuple[float, ...],
spacing_slack: int,
wall_slack: int,
modulus: int,
reachability: tuple[tuple[Profile, ...], ...],
) -> tuple[Profile, ...]:
if not widths:
return ((),)
bottom, top = opening
bottom_wall = bottom != problem.bounds[1]
top_wall = top != problem.bounds[3]
margin = problem.clearance + wall_slack
lower = [_round_up(bottom + w / 2 + (margin if bottom_wall else 0), m, modulus) for w, m in zip(widths, residues, strict=True)]
upper = [_round_down(top - w / 2 - (margin if top_wall else 0), m, modulus) for w, m in zip(widths, residues, strict=True)]
spacing = [(a + b) / 2 + problem.clearance + spacing_slack for a, b in pairwise(widths)]
for i in range(1, len(lower)):
lower[i] = max(lower[i], _round_up(lower[i - 1] + spacing[i - 1], residues[i], modulus))
for i in range(len(upper) - 2, -1, -1):
upper[i] = min(upper[i], _round_down(upper[i + 1] - spacing[i], residues[i], modulus))
if any(low > high for low, high in zip(lower, upper, strict=True)):
return ()
profiles = {_pack_forward(lower, upper, spacing, residues, desired, modulus)}
# Reflect the band to project preferences from its upper boundary as well.
reflected = _pack_forward(
[-y for y in reversed(upper)],
[-y for y in reversed(lower)],
spacing[::-1],
tuple(-m for m in reversed(residues)),
tuple(-y for y in reversed(desired)),
modulus,
)
profiles.add(tuple(-y for y in reversed(reflected)))
if bottom_wall:
profiles.add(tuple(lower))
if top_wall:
profiles.add(tuple(upper))
if bottom_wall and top_wall:
n = len(lower)
spread = tuple(lower[0] + (upper[-1] - lower[0]) * i / max(1, n - 1) for i in range(n))
if n == 1:
spread = ((lower[0] + upper[0]) / 2,)
profiles.add(_pack_forward(lower, upper, spacing, residues, spread, modulus))
for reachable in reachability:
profiles.add(_pack_forward(lower, upper, spacing, residues, desired, modulus, reachable))
return tuple(sorted(profiles))
def _column_profiles(
problem: RoutingProblem,
column: _Column,
widths: tuple[float, ...],
residues: Profile,
desired: tuple[float, ...],
spacing_slack: int,
wall_slack: int,
modulus: int,
reachability: tuple[tuple[Profile, ...], ...] = (),
) -> list[Profile]:
profiles = set()
n = len(widths)
band_cache = {}
for cuts in combinations_with_replacement(range(n + 1), len(column.openings) - 1):
groups = []
for opening, (left, right) in zip(column.openings, pairwise((0, *cuts, n)), strict=True):
key = opening, left, right
if key not in band_cache:
band_cache[key] = _band_profiles(
problem,
opening,
widths[left:right],
residues[left:right],
desired[left:right],
spacing_slack,
wall_slack,
modulus,
tuple(candidate[left:right] for candidate in reachability),
)
groups.append(band_cache[key])
profiles.update(tuple(y for group in chosen for y in group) for chosen in product(*groups))
return sorted(profiles, key=lambda row: (sum(abs(a - b) for a, b in zip(row, desired, strict=True)), row))[:140]
def _exact_spans(radius: int) -> dict[int, int]:
spans = {}
for offset in range(1, 2 * radius):
squared = offset * (4 * radius - offset)
span = isqrt(squared)
if span * span == squared:
spans[offset] = span
return spans
def _bend_sequences(
spans: dict[int, int],
radius: int,
weights: Mapping[str, float],
*,
weighted: bool,
sbend_penalty: float,
) -> Callable[[int, int], _BendSequence | None]:
# Each S-bend replaces a straight of its forward span in this window.
bend_costs = {
d: sbend_penalty + weights["sbend"] * 2 * radius * acos(1 - d / (2 * radius)) - weights["straight"] * span for d, span in spans.items()
}
sequences: list[tuple[_BendSequence, ...]] = [(_BendSequence((), 0, 0.0),)]
@lru_cache(maxsize=4096)
def choose(delta: int, usable: int) -> _BendSequence | None:
magnitude = abs(delta)
while len(sequences) <= magnitude:
height = len(sequences)
candidates = [
_BendSequence((offset, *prefix.offsets), span + prefix.span, bend_costs[offset] + prefix.cost)
for offset, span in spans.items()
if offset <= height
for prefix in sequences[height - offset]
]
candidates.sort(
key=lambda candidate: (
candidate.span,
candidate.cost if weighted else len(candidate.offsets),
tuple(-d for d in candidate.offsets),
)
)
frontier = []
for candidate in candidates:
if not frontier or (weighted and candidate.cost < frontier[-1].cost - 1e-9):
frontier.append(candidate)
sequences.append(tuple(frontier))
viable = [candidate for candidate in sequences[magnitude] if candidate.span <= usable]
if not viable:
return None
best = viable[-1]
if delta < 0:
return _BendSequence(tuple(-offset for offset in best.offsets), best.span, best.cost)
return best
return choose
def _positions(radius: int, spans: dict[int, int], sequence: _BendSequence, window: int, y: int) -> LineString:
x = (window - sequence.span) // 2
points = [(0, y), (x, y)]
for shift in sequence.offsets:
theta = acos(1 - abs(shift) / (2 * radius))
direction = 1 if shift > 0 else -1
advance = spans[abs(shift)]
for i in range(1, 13):
angle = theta * i / 12
points.append((x + radius * sin(angle), y + direction * radius * (1 - cos(angle))))
for i in range(11, -1, -1):
angle = theta * i / 12
points.append((x + advance - radius * sin(angle), y + shift - direction * radius * (1 - cos(angle))))
x += advance
y += shift
points.append((window, y))
return LineString(points)
def _schedules(
windows: tuple[Window, ...],
profiles: list[list[Profile]],
widths: tuple[float, ...],
clearance: float,
radius: int,
spans: dict[int, int],
weights: Mapping[str, float],
*,
weighted: bool,
sbend_penalty: float,
) -> Iterator[tuple[tuple[Profile, ...], tuple[tuple[_BendSequence, ...], ...]]]:
choose = _bend_sequences(spans, radius, weights, weighted=weighted, sbend_penalty=sbend_penalty)
needs = tuple((a + b) / 2 + clearance for a, b in pairwise(widths))
# The track order allows a local check of each neighboring pair. The
# final router still verifies the exact arcs and every pair of routes.
@lru_cache(maxsize=65536)
def pair_clear(window: int, gap: int, da: int, db: int, need: float) -> bool:
if min(gap, gap + db - da) < need:
return False
if min(gap, gap + db) - max(0, da) >= need:
return True
lower, upper = choose(da, window - 4), choose(db, window - 4)
assert lower is not None
assert upper is not None
# Cache the shapes via the local wrapper. The span map is fixed.
return positions(lower, window, 0).distance(positions(upper, window, gap)) >= need + 0.025
@lru_cache(maxsize=8192)
def positions(sequence: _BendSequence, window: int, y: int) -> LineString:
return _positions(radius, spans, sequence, window, y)
start = profiles[0][0]
approaches = {start: [(0.0, (start,))]}
for ((_, after), (before, _)), rows in zip(pairwise(windows), profiles[1:], strict=True):
window = before - after
next_approaches = {}
for row in rows:
scores = []
for previous, histories in approaches.items():
offsets = tuple(b - a for a, b in zip(previous, row, strict=True))
sequences = [choose(d, window - 4) for d in offsets]
if any(sequence is None for sequence in sequences):
continue
if any(
not pair_clear(window, b - a, da, db, need)
for (a, b), (da, db), need in zip(pairwise(previous), pairwise(offsets), needs, strict=True)
):
continue
if weighted:
cost = sum(sequence.cost for sequence in sequences if sequence is not None)
else:
cost = sum(abs(d) for d in offsets) + 1.5 * max(abs(d) for d in offsets)
cost += 0.02 * sum(sequence.span for sequence in sequences if sequence is not None)
scores.extend((score + cost, (*history, row)) for score, history in histories)
if scores:
next_approaches[row] = sorted(scores)[:2]
approaches = next_approaches
if not approaches:
return
for _, rows in approaches.get(profiles[-1][0], ()):
moves = []
for ((_, after), (before, _)), (a, b) in zip(pairwise(windows), pairwise(rows), strict=True):
sequences = tuple(choose(y1 - y0, before - after - 4) for y0, y1 in zip(a, b, strict=True))
assert all(sequence is not None for sequence in sequences)
moves.append(tuple(sequence for sequence in sequences if sequence is not None))
yield rows, tuple(moves)
def _seeds(
tracks: tuple[_Track, ...],
windows: tuple[Window, ...],
moves: tuple[tuple[_BendSequence, ...], ...],
radius: int,
) -> dict[str, PathSeed]:
seeds = {}
for i, track in enumerate(tracks):
x = track.left.x
segments: list[PathSegmentSeed] = []
for ((_, after), (before, _)), sequences in zip(pairwise(windows), moves, strict=True):
sequence = sequences[i]
if not sequence.offsets:
continue
entrance = (after + before - sequence.span) // 2
segments.append(StraightSeed(entrance - x))
segments.extend(SBendSeed(offset, radius) for offset in sequence.offsets)
x = entrance + sequence.span
segments.append(StraightSeed(track.right.x - x))
seeds[track.net.net_id] = PathSeed(tuple(reversed(segments) if track.westbound else segments))
return seeds
def column_seed_candidates(
problem: RoutingProblem,
search: SearchOptions,
weights: Mapping[str, float],
*,
weighted: bool,
sbend_penalty: float = 0.0,
) -> Iterator[dict[str, PathSeed]]:
"""Yield candidate routes from configured circular bends and problem geometry."""
_, physical_geometry = resolve_bend_geometry(search)
bend = min(search.sbend_radii, default=0.0)
if problem.initial_paths or physical_geometry != "arc" or not isfinite(bend) or bend <= 0 or bend != int(bend):
return
tracks = _ordered_tracks(problem)
if len(tracks) < 3 or any(not isfinite(track.net.width) or track.net.width <= 0 for track in tracks):
return
start, finish = max(track.left.x for track in tracks), min(track.right.x for track in tracks)
columns = _columns(problem, start, finish)
if not columns:
return
radius = int(bend)
spans = _exact_spans(radius)
if not spans:
return
modulus = gcd(*spans)
launch, arrival = tuple(track.left.y for track in tracks), tuple(track.right.y for track in tracks)
residues = tuple(y % modulus for y in launch)
if tuple(y % modulus for y in arrival) != residues:
return
widths = tuple(track.net.width for track in tracks)
windows = ((start, start), *(column.span for column in columns), (finish, finish))
preferences = []
for column in columns:
share = (sum(column.span) / 2 - start) / (finish - start)
preferences.append(tuple(a + share * (b - a) for a, b in zip(launch, arrival, strict=True)))
# The first pass uses moderate lateral shifts. Later passes relax the
# spacing or try smaller or larger bends if a transition will not fit.
limits = tuple(dict.fromkeys(min(2 * radius - 1, ceil(radius * frac)) for frac in (0.8, 0.4, 1.44)))
seen = set()
for spacing_slack, wall_slack, maximum in product((5, 3, 2, 1, 0, 7), (1, 0), limits):
active_spans = {d: span for d, span in spans.items() if d <= maximum}
if not active_spans:
continue
interior = [
_column_profiles(problem, column, widths, residues, preference, spacing_slack, wall_slack, modulus)
for column, preference in zip(columns, preferences, strict=True)
]
if weighted:
adjacent = [[launch], *interior, [arrival]]
reachable_offsets = (0, *(d for offset in active_spans for d in (-offset, offset)))
for i, (column, preference) in enumerate(zip(columns, preferences, strict=True)):
anchors = (*adjacent[i][:2], *adjacent[i + 2][:2])
reachable = tuple(tuple(tuple(y + d for d in reachable_offsets) for y in anchor) for anchor in anchors)
seeded = _column_profiles(problem, column, widths, residues, preference, spacing_slack, wall_slack, modulus, reachable)
interior[i] = sorted(set(interior[i] + seeded))
for i, (column, preference) in enumerate(zip(columns, preferences, strict=True)):
if column.openings[0][0] == problem.bounds[1] or column.openings[-1][1] == problem.bounds[3]:
roomier = _column_profiles(problem, column, widths, residues, preference, spacing_slack + 5, wall_slack, modulus)
interior[i] = sorted(set(interior[i] + roomier[:45]))
profiles = [[launch], *interior, [arrival]]
for rows, moves in _schedules(
windows, profiles, widths, problem.clearance, radius, active_spans, weights, weighted=weighted, sbend_penalty=sbend_penalty
):
signature = rows, moves
if signature not in seen:
seen.add(signature)
yield _seeds(tracks, windows, moves, radius)

154
inire/router/_compact.py Normal file
View file

@ -0,0 +1,154 @@
"""Fit perpendicular jogs between nearby, parallel terminal columns."""
from __future__ import annotations
from itertools import islice
from math import isfinite
from typing import TYPE_CHECKING
from shapely import union_all
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.router._columns import _exact_spans
from inire.router._seed_materialization import materialize_path_seed
from inire.seeds import Bend90Seed, PathSeed, SBendSeed, StraightSeed
if TYPE_CHECKING:
from collections.abc import Iterator
from shapely.geometry.base import BaseGeometry
from inire.model import NetSpec, RoutingProblem, SearchOptions
from inire.seeds import PathSegmentSeed
def _path(*moves: int | PathSegmentSeed) -> PathSeed:
return PathSeed(tuple(StraightSeed(move) if isinstance(move, int) else move for move in moves if move != 0))
def _lanes(first: int, last: int) -> tuple[int, ...]:
return tuple(dict.fromkeys((*range(last, max(first - 1, last - 8), -1), *range(min(last, first + 7), first - 1, -1))))
def _shift_positions(
problem: RoutingProblem,
origin: int,
sign: int,
radius: int,
run: int,
available: int,
) -> list[int]:
positions = {i * available // 8 for i in range(9)}
for obstacle in problem.static_obstacles:
if obstacle.is_empty:
continue
low, high = sorted(sign * (y - origin) - radius for y in (obstacle.bounds[1], obstacle.bounds[3]))
positions.update((round(low - problem.clearance - run), round(high + problem.clearance), round((low + high - run) / 2)))
return sorted((y for y in positions if 0 <= y <= available), key=lambda y: (abs(2 * y - available), y))
def _candidate_jogs(
net: NetSpec,
problem: RoutingProblem,
search: SearchOptions,
radii: tuple[int, ...],
) -> Iterator[PathSeed]:
start, target = net.start, net.target
dx, dy = target.x - start.x, target.y - start.y
if dy == 0:
yield _path(dx)
return
direction = 1 if dy > 0 else -1
for radius in radii:
reach = abs(dy) - 2 * radius
if reach < 0 or dx < 2 * radius:
continue
first = Bend90Seed(radius, "CCW" if direction > 0 else "CW")
last = Bend90Seed(radius, "CW" if direction > 0 else "CCW")
turns = _lanes(start.x + radius, target.x - radius)
for x in turns:
yield _path(x - start.x - radius, first, reach, last, target.x - x - radius)
if radius not in search.sbend_radii:
continue
# Move the middle of the jog between two independently positioned
# turn lanes. The S-bend stays away from the terminal access cutouts.
for offset, span in reversed(tuple(_exact_spans(radius).items())):
if span > reach:
continue
available = reach - span
for before in _shift_positions(problem, start.y, direction, radius, span, available):
for exit_x in turns:
for lateral in (offset, -offset):
lead = exit_x + lateral - start.x - radius
if lead < 0:
continue
yield _path(
lead,
first,
before,
SBendSeed(direction * lateral, radius),
available - before,
last,
target.x - exit_x - radius,
)
def _pack_routes(
candidates: dict[str, list[tuple[PathSeed, BaseGeometry]]],
clearance: float,
) -> dict[str, PathSeed] | None:
order = sorted(candidates, key=lambda net_id: len(candidates[net_id]))
chosen: dict[str, tuple[PathSeed, BaseGeometry]] = {}
remaining = 4096
def add(index: int) -> bool:
nonlocal remaining
if index == len(order):
return True
net_id = order[index]
for seed, footprint in candidates[net_id]:
if remaining <= 0:
break
remaining -= 1
if any(footprint.distance(other) < clearance - TOLERANCE_LINEAR for _, other in chosen.values()):
continue
chosen[net_id] = (seed, footprint)
if add(index + 1):
return True
del chosen[net_id]
return False
return {net_id: value[0] for net_id, value in chosen.items()} if add(0) else None
def compact_port_seed_set(problem: RoutingProblem, search: SearchOptions) -> dict[str, PathSeed] | None:
"""Verify candidates individually and find mutually clear routes for a bank."""
_, physical_geometry = resolve_bend_geometry(search)
radii = tuple(sorted({int(r) for r in search.bend_radii if isfinite(r) and r > 0 and r == int(r)}))
if problem.initial_paths or not radii or not problem.nets or physical_geometry != "arc":
return None
if any(net.start.r != 0 or net.target.r != 0 or not 0 < net.target.x - net.start.x <= 4 * radii[-1] for net in problem.nets):
return None
world = RoutingWorld(clearance=problem.clearance, safety_zone_radius=problem.safety_zone_radius)
for obstacle in problem.static_obstacles:
world.add_static_obstacle(obstacle)
board = box(*problem.bounds)
candidates = {}
for net in problem.nets:
choices = []
for seed in islice(_candidate_jogs(net, problem, search, radii), 512):
path = materialize_path_seed(seed, start=net.start, net_width=net.width, search=search, clearance=problem.clearance)
if path[-1].end_port != net.target or not world.verify_path_report(net.net_id, path).is_valid:
continue
footprint = union_all([polygon for component in path for polygon in component.physical_geometry])
if board.covers(footprint):
choices.append((seed, footprint))
if len(choices) == 20:
break
if not choices:
return None
candidates[net.net_id] = choices
return _pack_routes(candidates, problem.clearance)

201
inire/router/_perimeter.py Normal file
View file

@ -0,0 +1,201 @@
"""Perimeter detours and fixed-heading returns for ordered bundles."""
from __future__ import annotations
from dataclasses import replace
from itertools import combinations, pairwise, product
from math import ceil, floor, isfinite
from typing import TYPE_CHECKING
from inire.model import resolve_bend_geometry
from inire.router._seed_materialization import materialize_path_seed
from inire.router._waypoints import _direction, compile_waypoints, export_waypoints
from inire.seeds import PathSeed, StraightSeed
if TYPE_CHECKING:
from collections.abc import Iterator
from inire.model import NetSpec, RoutingProblem, SearchOptions
from inire.router._waypoints import XY
def bundle_turnaround_candidates(
problem: RoutingProblem,
proposal: RoutingProblem,
search: SearchOptions,
) -> Iterator[RoutingProblem]:
"""Fit a final turnaround below the shelf without changing terminal headings."""
if len(problem.nets) != len(proposal.nets) or not problem.nets:
return
mismatches = [
(fixed, inferred)
for fixed, inferred in zip(problem.nets, proposal.nets, strict=True)
if (fixed.start, fixed.target) != (inferred.start, inferred.target)
]
if len(mismatches) != 1:
return
returning, inferred = mismatches[0]
if returning.start != inferred.start or returning.target.r != 0 or inferred.target.r != 180:
return
radius = int(min(search.bend_radii))
farthest = max(net.target.x for net in problem.nets)
shelf = max((net for net in problem.nets if net.target.x == farthest), key=lambda net: net.target.y)
if shelf == returning:
return
def points_for(net: NetSpec) -> tuple[XY, ...]:
path = materialize_path_seed(
proposal.initial_paths[net.net_id], start=net.start, net_width=net.width, search=search, clearance=problem.clearance
)
return tuple((round(x), round(y)) for x, y in export_waypoints(path))
shelf_points, return_points = points_for(shelf), points_for(returning)
horizontals = [i for i, (a, b) in enumerate(pairwise(shelf_points)) if a[1] == b[1]]
if len(return_points) != 6 or not horizontals:
return
launch = max(horizontals, key=lambda i: shelf_points[i][1])
drop = launch + 1
bends = [(a, b) for a, b in pairwise(shelf_points[drop:]) if a[0] != b[0] and a[1] != b[1]]
if len(bends) != 1 or drop + 1 >= len(shelf_points):
return
(left_x, left_y), (right_x, right_y) = bends[0]
drop_offset = left_y - right_y
if not 0 < drop_offset < 2 * radius:
return
min_gap = problem.clearance + (returning.width + shelf.width) / 2
# Parallel S-bends approach each other most at their largest tangent angle.
inner_gap = ceil(min_gap / (1 - drop_offset / (2 * radius)))
top = floor(problem.bounds[3] - shelf.width / 2)
first_drop = max(shelf_points[drop][0], ceil(returning.target.x + radius + min_gap))
for descent_x, gap, lead in product(
(first_drop, first_drop + radius // 2, first_drop + radius),
range(inner_gap, inner_gap + 5),
(0, 2, 4, 8),
):
shelf_candidate = list(shelf_points)
shelf_candidate[launch] = (shelf_points[launch][0], top)
shelf_candidate[drop] = (descent_x, top)
shelf_candidate[drop + 1] = (descent_x, shelf_points[drop + 1][1])
x_turn = returning.target.x - radius - lead
turn_points = (
*return_points[:4],
(return_points[4][0], right_y - gap),
(right_x, right_y - gap),
(left_x, left_y - gap),
(x_turn, left_y - gap),
(x_turn, returning.target.y),
(returning.target.x, returning.target.y),
)
try:
shelf_seed, shelf_end = compile_waypoints(tuple(shelf_candidate), shelf.start, radius)
return_seed, return_end = compile_waypoints(turn_points, returning.start, radius)
except ValueError:
continue
if shelf_end == shelf.target and return_end == returning.target:
seeds = {**proposal.initial_paths, shelf.net_id: shelf_seed, returning.net_id: return_seed}
yield replace(problem, initial_paths=seeds)
def terminal_link_seed(net: NetSpec, search: SearchOptions) -> PathSeed | None:
"""Connect aligned terminals with a straight or a single tangent bend."""
start, target = net.start, net.target
a, b = (start.x, start.y), (target.x, target.y)
if a == b:
return None
if start.r == target.r == _direction(a, b):
return PathSeed((StraightSeed(abs(b[0] - a[0]) + abs(b[1] - a[1])),))
if start.r % 180 == target.r % 180:
return None
corner = (b[0], a[1]) if start.r % 180 == 0 else (a[0], b[1])
radius = min(search.bend_radii, default=0.0)
if (
not isfinite(radius)
or radius <= 0
or corner in (a, b)
or _direction(a, corner) != start.r
or _direction(corner, b) != target.r
or min(abs(b[0] - a[0]), abs(b[1] - a[1])) < radius
):
return None
seed, end = compile_waypoints((a, corner, b), start, radius)
return seed if end == target else None
def _return_detours(
problem: RoutingProblem,
net: NetSpec,
obstacles: tuple[tuple[float, float, float, float], ...],
radius: int,
) -> Iterator[PathSeed]:
xmin, ymin, xmax, ymax = problem.bounds
half_width = net.width / 2
margin = ceil(problem.clearance + half_width + 1)
start, target = net.start, net.target
low = min(start.y, target.y) - 2 * radius
high = max(start.y, target.y) + 2 * radius
bottom = min(low, min((floor(bottom - margin) for _, bottom, _, _ in obstacles), default=low))
top = max(high, max((ceil(top + margin) for _, _, _, top in obstacles), default=high))
pivots = {xmin + half_width, xmax - half_width, start.x + radius + 1, target.x - radius - 1}
for left, _, right, _ in obstacles:
pivots.update((floor(left - margin), ceil(right + margin)))
departures = sorted(x for x in pivots if start.x + radius <= x <= xmax - half_width)
arrivals = sorted((x for x in pivots if xmin + half_width <= x <= target.x - radius), reverse=True)
for y in (bottom, top):
if not ymin + half_width <= y <= ymax - half_width:
continue
for first, last in product(departures, arrivals):
points = ((start.x, start.y), (first, start.y), (first, y), (last, y), (last, target.y), (target.x, target.y))
seed, end = compile_waypoints(points, start, radius)
if end == target:
yield seed
def perimeter_detour_candidates(problem: RoutingProblem, search: SearchOptions) -> Iterator[tuple[NetSpec, PathSeed]]:
"""Try four-turn detours around obstacles or behind east-facing ports."""
_, physical_geometry = resolve_bend_geometry(search)
bend = min(search.bend_radii, default=0.0)
if problem.initial_paths or physical_geometry != "arc" or not isfinite(bend) or bend <= 0 or bend != int(bend):
return
obstacles = tuple(shape.bounds for shape in problem.static_obstacles if not shape.is_empty)
radius = int(bend)
for net in problem.nets:
if net.start.r != 0 or net.target.r != 0:
continue
if net.start.x > net.target.x:
yield from ((net, seed) for seed in _return_detours(problem, net, obstacles, radius))
continue
if net.start.x == net.target.x or not obstacles:
continue
low, high = sorted((net.start.y, net.target.y))
if all(bottom > high or top < low or right < net.start.x or left > net.target.x for left, bottom, right, top in obstacles):
continue
margin = ceil(problem.clearance + net.width / 2 + 1)
lanes = (max(ceil(top + margin) for _, _, _, top in obstacles), min(floor(bottom - margin) for _, bottom, _, _ in obstacles))
pivots = {net.start.x + radius + 1, net.target.x - radius - 1}
pivots.update(
x
for left, _, right, _ in obstacles
for x in (floor(left - radius - margin), ceil(right + radius + margin))
if net.start.x + radius <= x <= net.target.x - radius
)
for y in lanes:
if (
abs(y - net.start.y) < 2 * radius
or abs(y - net.target.y) < 2 * radius
or not problem.bounds[1] + net.width / 2 <= y <= problem.bounds[3] - net.width / 2
):
continue
for first, last in combinations(sorted(pivots), 2):
if last - first < 2 * radius:
continue
points = (
(net.start.x, net.start.y),
(first, net.start.y),
(first, y),
(last, y),
(last, net.target.y),
(net.target.x, net.target.y),
)
seed, end = compile_waypoints(points, net.start, radius)
if end == net.target:
yield net, seed

View file

@ -2,7 +2,8 @@ from __future__ import annotations
import random import random
import time import time
from dataclasses import dataclass from contextlib import nullcontext
from dataclasses import dataclass, field
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from inire.geometry.collision import RoutingWorld from inire.geometry.collision import RoutingWorld
@ -20,6 +21,7 @@ from inire.results import (
RoutingOutcome, RoutingOutcome,
RoutingReport, RoutingReport,
RoutingResult, RoutingResult,
TopologyReport,
) )
from inire.router._astar_types import AStarContext, AStarMetrics, FrontierTraceCollector, SearchRunConfig from inire.router._astar_types import AStarContext, AStarMetrics, FrontierTraceCollector, SearchRunConfig
from inire.router._search import route_astar from inire.router._search import route_astar
@ -30,11 +32,16 @@ from inire.router.refiner import PathRefiner
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Callable, Sequence from collections.abc import Callable, Sequence
from contextlib import AbstractContextManager
from shapely.geometry import Polygon from shapely.geometry import Polygon
from inire.geometry.collision import PathVerificationDetail from inire.geometry.collision import PathVerificationDetail
from inire.geometry.components import ComponentResult from inire.geometry.components import ComponentResult
from inire.results import RoutingOperation
from inire.router._topology import Corridor
PhaseTimer = Callable[[RoutingOperation], AbstractContextManager[None]]
@dataclass(slots=True) @dataclass(slots=True)
@ -57,6 +64,7 @@ class _RoutingState:
pair_local_plateau_count: int pair_local_plateau_count: int
recent_attempt_work: dict[str, int] recent_attempt_work: dict[str, int]
pre_pair_candidate: _PrePairCandidate | None pre_pair_candidate: _PrePairCandidate | None
corridors: dict[str, tuple[Corridor, ...]] = field(default_factory=dict)
@dataclass(slots=True) @dataclass(slots=True)
@ -106,6 +114,7 @@ class PathFinder:
"frontier_trace", "frontier_trace",
"pre_pair_frontier_trace", "pre_pair_frontier_trace",
"iteration_trace", "iteration_trace",
"topology_report",
) )
def __init__( def __init__(
@ -125,6 +134,7 @@ class PathFinder:
self.frontier_trace: list[NetFrontierTrace] = [] self.frontier_trace: list[NetFrontierTrace] = []
self.pre_pair_frontier_trace: PrePairFrontierTraceEntry | None = None self.pre_pair_frontier_trace: PrePairFrontierTraceEntry | None = None
self.iteration_trace: list[IterationTraceEntry] = [] self.iteration_trace: list[IterationTraceEntry] = []
self.topology_report: TopologyReport | None = None
def _metric_total(self, metric_name: str) -> int: def _metric_total(self, metric_name: str) -> int:
return int(getattr(self.metrics, f"total_{metric_name}")) return int(getattr(self.metrics, f"total_{metric_name}"))
@ -200,6 +210,7 @@ class PathFinder:
self, self,
net_specs: dict[str, NetSpec], net_specs: dict[str, NetSpec],
order: NetOrder, order: NetOrder,
corridors: dict[str, tuple[Corridor, ...]],
) -> dict[str, tuple[ComponentResult, ...]]: ) -> dict[str, tuple[ComponentResult, ...]]:
greedy_paths: dict[str, tuple[ComponentResult, ...]] = {} greedy_paths: dict[str, tuple[ComponentResult, ...]] = {}
temp_obj_ids: list[int] = [] temp_obj_ids: list[int] = []
@ -212,12 +223,15 @@ class PathFinder:
min_bend_radius=self.context.min_bend_radius, min_bend_radius=self.context.min_bend_radius,
) )
max_cost_limit = max(h_start * 3.0, 2000.0) max_cost_limit = max(h_start * 3.0, 2000.0)
candidates = corridors.get(net_id, ())
run_config = SearchRunConfig.from_options( run_config = SearchRunConfig.from_options(
self.context.options, self.context.options,
skip_congestion=True, skip_congestion=True,
max_cost=max_cost_limit, max_cost=max_cost_limit,
self_collision_check=True, self_collision_check=True,
node_limit=greedy_node_limit, node_limit=greedy_node_limit,
corridor=candidates[0] if candidates else None,
corridor_strength=self.context.options.topology.guide_strength,
) )
path = route_astar( path = route_astar(
net.start, net.start,
@ -241,6 +255,87 @@ class PathFinder:
self.context.cost_evaluator.collision_engine.remove_static_obstacle(obj_id) self.context.cost_evaluator.collision_engine.remove_static_obstacle(obj_id)
return greedy_paths return greedy_paths
def _build_corridor_seeds(self, state: _RoutingState) -> dict[str, tuple[ComponentResult, ...]]:
topology = self.context.options.topology
world = self.context.cost_evaluator.collision_engine
existing = state.initial_paths or {}
seeds: dict[str, tuple[ComponentResult, ...]] = {}
temporary: list[int] = []
def reserve(path: Sequence[ComponentResult]) -> None:
for component in path:
for shape in component.physical_geometry:
temporary.append(world.add_static_obstacle(shape))
try:
for net_id, path in existing.items():
if path and path[-1].end_port == state.net_specs[net_id].target and world.verify_path_report(net_id, path).is_valid:
reserve(path)
for net_id in state.ordered_net_ids:
if net_id in existing:
continue
net = state.net_specs[net_id]
candidates = state.corridors.get(net_id, ())
remaining = min(topology.seed_node_limit, self.context.options.search.node_limit)
for index, corridor in enumerate(candidates):
if remaining <= 0:
break
searches_left = len(candidates) - index
budget = max(1, remaining // searches_left)
if index == 0 and searches_left > 1:
budget = max(budget, (remaining + 1) // 2)
config = SearchRunConfig.from_options(
self.context.options,
node_limit=budget,
skip_congestion=True,
self_collision_check=True,
corridor=corridor,
restrict_to_corridor=True,
)
path = route_astar(net.start, net.target, net.width, self.context, metrics=self.metrics, net_id=net_id, config=config)
remaining -= self.metrics.nodes_expanded
if path and path[-1].end_port == net.target and world.verify_path_report(net_id, path).is_valid:
seeds[net_id] = tuple(path)
self.metrics.total_warm_start_paths_built += 1
reserve(path)
break
finally:
for obstacle in temporary:
world.remove_static_obstacle(obstacle)
self.context.clear_static_caches()
return seeds
def _prepare_topology(self, state: _RoutingState) -> None:
topology = self.context.options.topology
if topology.mode == "bundle":
self.topology_report = TopologyReport(seeded_net_ids=tuple(self.context.problem.initial_paths))
return
if topology.mode not in ("guide", "seed"):
return
from inire.router._topology import plan_corridors # noqa: PLC0415
world = self.context.cost_evaluator.collision_engine
for net_id in state.ordered_net_ids:
world.remove_path(net_id)
state.corridors = plan_corridors(
self.context.problem.bounds,
world._static_obstacles.geometries.values(),
[state.net_specs[net_id] for net_id in state.ordered_net_ids],
clearance=world.clearance,
bend_radius=min(self.context.options.search.bend_radii, default=0.0),
limit=topology.max_corridors,
)
before = self.metrics.total_nodes_expanded
seeds = self._build_corridor_seeds(state) if topology.mode == "seed" and state.corridors else {}
if seeds:
state.initial_paths = {**(state.initial_paths or {}), **seeds}
self.topology_report = TopologyReport(
corridor_counts=tuple((net_id, len(candidates)) for net_id, candidates in state.corridors.items()),
seeded_net_ids=tuple(seeds),
seed_nodes_expanded=self.metrics.total_nodes_expanded - before,
)
def _prepare_state(self) -> _RoutingState: def _prepare_state(self) -> _RoutingState:
problem = self.context.problem problem = self.context.problem
congestion = self.context.options.congestion congestion = self.context.options.congestion
@ -249,7 +344,7 @@ class PathFinder:
num_nets = len(net_specs) num_nets = len(net_specs)
state = _RoutingState( state = _RoutingState(
net_specs=net_specs, net_specs=net_specs,
ordered_net_ids=list(net_specs.keys()), ordered_net_ids=self._routing_order(net_specs, congestion.net_order),
results={}, results={},
needs_self_collision_check=set(), needs_self_collision_check=set(),
start_time=time.monotonic(), start_time=time.monotonic(),
@ -267,12 +362,19 @@ class PathFinder:
recent_attempt_work={}, recent_attempt_work={},
pre_pair_candidate=None, pre_pair_candidate=None,
) )
self._prepare_topology(state)
if state.initial_paths is None and congestion.warm_start_enabled: if state.initial_paths is None and congestion.warm_start_enabled:
state.initial_paths = self._build_greedy_warm_start_paths(net_specs, congestion.net_order) state.initial_paths = self._build_greedy_warm_start_paths(net_specs, congestion.net_order, state.corridors)
self.context.clear_static_caches() self.context.clear_static_caches()
if state.corridors and state.initial_paths and congestion.max_iterations > 0:
if congestion.net_order != "user": world = self.context.cost_evaluator.collision_engine
state.ordered_net_ids = self._routing_order(net_specs, congestion.net_order) for net_id, path in state.initial_paths.items():
if not path or path[-1].end_port != net_specs[net_id].target:
continue
report = world.verify_path_report(net_id, path)
if report.is_valid:
self._install_path(net_id, path)
state.results[net_id] = RoutingResult(net_id, path, reached_target=True, report=report)
return state return state
def _materialize_problem_initial_paths(self) -> dict[str, tuple[ComponentResult, ...]] | None: def _materialize_problem_initial_paths(self) -> dict[str, tuple[ComponentResult, ...]] | None:
@ -300,7 +402,7 @@ class PathFinder:
self.context.cost_evaluator.collision_engine.remove_path(net_id) self.context.cost_evaluator.collision_engine.remove_path(net_id)
for net_id in state.ordered_net_ids: for net_id in state.ordered_net_ids:
result = results.get(net_id) result = results.get(net_id)
if result and result.path: if result and result.path and (result.reached_target or not state.corridors):
self._install_path(net_id, result.path) self._install_path(net_id, result.path)
def _analyze_restored_best( def _analyze_restored_best(
@ -748,7 +850,7 @@ class PathFinder:
if net_id in pair_net_ids: if net_id in pair_net_ids:
continue continue
result = incumbent_results.get(net_id) result = incumbent_results.get(net_id)
if result is None or not result.path: if result is None or not result.path or (state.corridors and not result.reached_target):
continue continue
for component in result.path: for component in result.path:
for polygon in component.physical_geometry: for polygon in component.physical_geometry:
@ -875,6 +977,8 @@ class PathFinder:
) -> set[str]: ) -> set[str]:
if self._results_all_reached_target(state) and 0 < len(review.conflict_edges) <= 3: if self._results_all_reached_target(state) and 0 < len(review.conflict_edges) <= 3:
return set(review.conflicting_nets) return set(review.conflicting_nets)
if state.corridors:
return set(state.ordered_net_ids).difference(review.completed_net_ids)
return set(state.ordered_net_ids) return set(state.ordered_net_ids)
def _should_stop_for_pair_local_plateau( def _should_stop_for_pair_local_plateau(
@ -1059,7 +1163,7 @@ class PathFinder:
coll_model, _ = resolve_bend_geometry(search) coll_model, _ = resolve_bend_geometry(search)
skip_congestion = False skip_congestion = False
guidance_seed, guidance_bonus, guidance_seed_present = (None, 0.0, False) guidance_seed, guidance_bonus, guidance_seed_present = (None, 0.0, False)
if congestion.use_tiered_strategy and iteration == 0: if congestion.use_tiered_strategy and iteration == 0 and not state.corridors:
skip_congestion = True skip_congestion = True
if coll_model == "arc": if coll_model == "arc":
coll_model = "clipped_bbox" coll_model = "clipped_bbox"
@ -1071,6 +1175,7 @@ class PathFinder:
if node_limit_override is not None and self._has_incumbent_fallback(incumbent_fallback): if node_limit_override is not None and self._has_incumbent_fallback(incumbent_fallback):
return self._restore_incumbent_fallback(net_id, incumbent_fallback, guidance_seed_present) return self._restore_incumbent_fallback(net_id, incumbent_fallback, guidance_seed_present)
corridors = state.corridors.get(net_id, ())
run_config = SearchRunConfig.from_options( run_config = SearchRunConfig.from_options(
self.context.options, self.context.options,
bend_collision_type=coll_model, bend_collision_type=coll_model,
@ -1081,6 +1186,9 @@ class PathFinder:
skip_congestion=skip_congestion, skip_congestion=skip_congestion,
self_collision_check=(net_id in state.needs_self_collision_check), self_collision_check=(net_id in state.needs_self_collision_check),
node_limit=search.node_limit if node_limit_override is None else node_limit_override, node_limit=search.node_limit if node_limit_override is None else node_limit_override,
corridor=corridors[iteration] if iteration < len(corridors) else None,
corridor_strength=self.context.options.topology.guide_strength / (iteration + 1),
hard_congestion=bool(state.corridors) and iteration == 0,
) )
path = route_astar( path = route_astar(
net.start, net.start,
@ -1106,7 +1214,8 @@ class PathFinder:
if reached_target: if reached_target:
self.metrics.total_nets_reached_target += 1 self.metrics.total_nets_reached_target += 1
report = None report = None
self._install_path(net_id, path) if reached_target or not state.corridors:
self._install_path(net_id, path)
if reached_target: if reached_target:
report = self.context.cost_evaluator.collision_engine.verify_path_report(net_id, path) report = self.context.cost_evaluator.collision_engine.verify_path_report(net_id, path)
if report.self_collision_count > 0: if report.self_collision_count > 0:
@ -1326,6 +1435,7 @@ class PathFinder:
self, self,
*, *,
iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None, iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None,
phase_timer: PhaseTimer | None = None,
) -> dict[str, RoutingResult]: ) -> dict[str, RoutingResult]:
self.context.congestion_penalty = self.context.options.congestion.base_penalty self.context.congestion_penalty = self.context.options.congestion.base_penalty
self.accumulated_expanded_nodes = [] self.accumulated_expanded_nodes = []
@ -1333,6 +1443,7 @@ class PathFinder:
self.frontier_trace = [] self.frontier_trace = []
self.pre_pair_frontier_trace = None self.pre_pair_frontier_trace = None
self.iteration_trace = [] self.iteration_trace = []
self.topology_report = None
self.metrics.reset_totals() self.metrics.reset_totals()
self.metrics.reset_per_route() self.metrics.reset_per_route()
@ -1342,13 +1453,11 @@ class PathFinder:
self._restore_best_iteration(state) self._restore_best_iteration(state)
self._analyze_restored_best(state) self._analyze_restored_best(state)
if timed_out: if not timed_out:
self._run_pair_local_search(state)
with phase_timer("refine") if phase_timer is not None and self.context.options.refinement.enabled else nullcontext():
self._refine_results(state)
with phase_timer("verify") if phase_timer is not None else nullcontext():
final_results = self._verify_results(state) final_results = self._verify_results(state)
self._capture_frontier_trace(state, final_results) self._capture_frontier_trace(state, final_results)
return final_results
self._run_pair_local_search(state)
self._refine_results(state)
final_results = self._verify_results(state)
self._capture_frontier_trace(state, final_results)
return final_results return final_results

View file

@ -0,0 +1,334 @@
"""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.model import resolve_bend_geometry
from inire.results import RoutingResult, RoutingStage
from inire.router._stack import route_once
if TYPE_CHECKING:
from collections.abc import Callable
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: ...
PROBE_FIRST_POLICIES = ("direct-probe-first", "direct-probe-near-port")
PROBE_POLICIES = (*PROBE_FIRST_POLICIES, "direct-probe-after")
DIRECT_POLICIES = (
"direct-guide",
"direct-seed",
"direct-adaptive",
"direct-adaptive-retry",
"direct-cull",
"direct-lookahead",
"direct-budgeted-retry",
"direct-lookahead-retry",
*PROBE_POLICIES,
)
LOOKAHEAD_POLICIES = ("direct-lookahead", "direct-lookahead-retry", *PROBE_POLICIES)
CONNECTIVITY_POLICIES = ("direct-cull", *LOOKAHEAD_POLICIES)
BUDGETED_POLICIES = ("direct-budgeted-retry", "direct-lookahead-retry", *PROBE_POLICIES)
@dataclass(frozen=True, slots=True)
class LockPlan:
direct: dict[str, RoutingResult]
disconnected: frozenset[str] = frozenset()
@dataclass(frozen=True, slots=True)
class Trial:
run: RoutingRunResult
stage: RoutingStage
valid_costs: dict[str, float]
selectable: bool = True
def improves_on(self, other: Trial) -> bool:
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 _local_delta(net: NetSpec) -> tuple[float, float]:
heading = ((1, 0), (0, 1), (-1, 0), (0, -1))[int(net.start.r) // 90]
dx, dy = net.target.x - net.start.x, net.target.y - net.start.y
return dx * heading[0] + dy * heading[1], dy * heading[0] - dx * heading[1]
def _is_short_shift(net: NetSpec, max_offset: float) -> bool:
forward, lateral = _local_delta(net)
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 = list(problem.nets)
order = options.congestion.net_order
if order != "user":
ordered.sort(key=lambda net: sum(map(abs, _local_delta(net))), reverse=order == "longest")
if priority:
ordered.sort(key=lambda net: net.net_id not in priority)
paths = {}
for net in ordered:
forward, lateral = _local_delta(net)
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,
strategy: str,
*,
priority: frozenset[str] = frozenset(),
) -> LockPlan:
direct = _direct_paths(problem, board, options, priority=priority)
disconnected = _disconnected_nets(problem, board, options, direct) if direct and strategy in CONNECTIVITY_POLICIES else frozenset()
return LockPlan(direct, disconnected)
def _route_residual(
problem: RoutingProblem,
options: RoutingOptions,
policy: str,
locks: LockPlan,
*,
run_route: RouteCall = route_once,
) -> tuple[RoutingRunResult, RoutingStage]:
direct = locks.direct
residual = tuple(net for net in problem.nets if net.net_id not in direct and net.net_id not in locks.disconnected)
if not residual:
mode = "off"
elif policy in ("direct-guide", "direct-seed"):
mode = "guide" if policy == "direct-guide" else "seed"
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"
if direct:
locked = tuple(shape for result in direct.values() for shape in result.locked_geometry)
problem = replace(problem, nets=residual, static_obstacles=problem.static_obstacles + locked)
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 _length(result: RoutingResult) -> float:
return sum(component.length for component in result.path)
def _trial(run: RoutingRunResult, stage: RoutingStage, board: Polygon, *, score: Scorer = _length) -> 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,
*,
run_route: RouteCall = route_once,
score: Scorer = _length,
check_trial: CheckTrial | None = None,
) -> list[Trial]:
def check(run: RoutingRunResult, stage: RoutingStage) -> Trial:
stage = replace(stage, policy=strategy)
return _trial(run, stage, board, score=score) if check_trial is None else check_trial(run, stage)
locks = _plan_locks(problem, board, options, strategy)
if locks.disconnected and strategy in LOOKAHEAD_POLICIES:
candidate = _plan_locks(problem, board, options, strategy, priority=locks.disconnected)
if len(candidate.disconnected) < len(locks.disconnected):
locks = candidate
first_options = retry_options = options
retry_locks = None
probe_limit = 0
can_reorder = 0 < len(locks.direct) < len(problem.nets)
if can_reorder and strategy in BUDGETED_POLICIES and options.search.node_limit > 1:
priority = frozenset(net.net_id for net in problem.nets if net.net_id not in locks.direct)
candidate = _plan_locks(problem, board, options, strategy, priority=priority)
if candidate.direct.keys() != locks.direct.keys() and len(candidate.disconnected) <= len(locks.disconnected):
retry_locks = candidate
limit = options.search.node_limit
if strategy in PROBE_POLICIES and (
strategy != "direct-probe-near-port" or _lock_near_new_port(problem, options, locks, retry_locks)
):
probe_limit = min(32, limit // 3)
remaining = limit - probe_limit
first_limit = remaining // 2
first_options = replace(options, search=replace(options.search, node_limit=first_limit))
retry_options = replace(options, search=replace(options.search, node_limit=remaining - first_limit))
trials = []
if probe_limit and strategy in PROBE_FIRST_POLICIES:
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, strategy, locks, run_route=run_route))
trials.append(first)
if len(first.valid_costs) == len(problem.nets):
return trials
if probe_limit and strategy == "direct-probe-after":
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
if strategy == "direct-adaptive-retry" and can_reorder:
unresolved = frozenset(first.run.results_by_net.keys() - first.valid_costs.keys())
candidate = _plan_locks(problem, board, options, strategy, priority=unresolved)
if candidate.direct.keys() != locks.direct.keys():
retry_locks = candidate
if retry_locks is not None:
trials.append(check(*_route_residual(problem, retry_options, strategy, 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

View file

@ -50,7 +50,7 @@ def route_astar(
start_node = _AStarNode( start_node = _AStarNode(
start, start,
0.0, 0.0,
context.cost_evaluator.h_manhattan(start, target, min_bend_radius=context.min_bend_radius), config.estimate_remaining_cost(start, target, context),
seed_index=0 if config.guidance_seed else None, seed_index=0 if config.guidance_seed else None,
) )
heapq.heappush(open_set, start_node) heapq.heappush(open_set, start_node)

View file

@ -3,13 +3,21 @@ from __future__ import annotations
from dataclasses import dataclass from dataclasses import dataclass
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from shapely.geometry import box
from inire.geometry.collision import RoutingWorld
from inire.results import RoutingRunResult
from inire.router._astar_types import AStarContext
from inire.router._router import PathFinder
from inire.router.cost import CostEvaluator
from inire.router.danger_map import DangerMap
if TYPE_CHECKING: if TYPE_CHECKING:
from inire.geometry.collision import RoutingWorld from collections.abc import Callable
from inire.model import RoutingOptions, RoutingProblem from inire.model import RoutingOptions, RoutingProblem
from inire.router._astar_types import AStarContext from inire.results import RoutingResult
from inire.router._router import PathFinder from inire.router._router import PhaseTimer
from inire.router.cost import CostEvaluator
from inire.router.danger_map import DangerMap
@dataclass(frozen=True, slots=True) @dataclass(frozen=True, slots=True)
@ -22,11 +30,10 @@ class RoutingStack:
def build_routing_stack(problem: RoutingProblem, options: RoutingOptions) -> RoutingStack: def build_routing_stack(problem: RoutingProblem, options: RoutingOptions) -> RoutingStack:
from inire.geometry.collision import RoutingWorld if options.topology.mode == "bundle":
from inire.router._astar_types import AStarContext from inire.router._bundle import plan_ordered_bundle # noqa: PLC0415
from inire.router._router import PathFinder
from inire.router.cost import CostEvaluator problem = plan_ordered_bundle(problem, options.search, infer_terminal_headings=options.topology.infer_terminal_headings)
from inire.router.danger_map import DangerMap
world = RoutingWorld( world = RoutingWorld(
clearance=problem.clearance, clearance=problem.clearance,
@ -57,3 +64,34 @@ def build_routing_stack(problem: RoutingProblem, options: RoutingOptions) -> Rou
context=context, context=context,
finder=finder, finder=finder,
) )
def route_once(
problem: RoutingProblem,
*,
options: RoutingOptions,
iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None,
phase_timer: PhaseTimer | None = None,
) -> RoutingRunResult:
"""Run one explicitly selected routing mode and capture its diagnostics."""
if options.topology.mode == "automatic":
raise ValueError("A single routing attempt requires an explicit planner mode")
finder = build_routing_stack(problem, options).finder
results = finder.route_all(iteration_callback=iteration_callback, phase_timer=phase_timer)
if options.topology.mode == "bundle":
board = box(*problem.bounds)
for result in results.values():
if not result.is_valid or any(not board.covers(shape) for shape in result.locked_geometry):
raise ValueError(f"Bundle schedule failed geometric verification for {result.net_id}")
return RoutingRunResult(
results_by_net=results,
metrics=finder.metrics.snapshot(),
expanded_nodes=tuple(finder.accumulated_expanded_nodes),
conflict_trace=tuple(finder.conflict_trace),
frontier_trace=tuple(finder.frontier_trace),
pre_pair_frontier_trace=finder.pre_pair_frontier_trace,
iteration_trace=tuple(finder.iteration_trace),
topology=finder.topology_report,
)

313
inire/router/_topology.py Normal file
View file

@ -0,0 +1,313 @@
"""Capacity-aware corridor planning in the triangulated centerline free space."""
from __future__ import annotations
from dataclasses import dataclass, field
from heapq import heappop, heappush
from itertools import pairwise
from math import hypot, inf
from typing import TYPE_CHECKING
import shapely
from shapely.geometry import LineString, Point, box
if TYPE_CHECKING:
from collections.abc import Iterable, Sequence
from shapely.geometry import Polygon
from shapely.geometry.base import BaseGeometry
from inire.geometry.primitives import Port
from inire.model import NetSpec
XY = tuple[float, float]
Edge = tuple[int, int]
HEADINGS = ((1, 0), (0, 1), (-1, 0), (0, -1))
@dataclass(slots=True)
class Corridor:
centerline: LineString
footprint: BaseGeometry
scale: float
_distances: dict[tuple[float, float], float] = field(default_factory=dict)
_remaining: dict[tuple[float, float], float] = field(default_factory=dict)
_anchors: tuple[XY, ...] = field(init=False)
_length: float = field(init=False)
def __post_init__(self) -> None:
self._anchors = tuple(dict.fromkeys(self.centerline.coords))
self._length = self.centerline.length
def distance(self, port: Port) -> float:
xy = (port.x, port.y)
if xy not in self._distances:
self._distances[xy] = min(1.0, self.centerline.distance(Point(xy)) / self.scale)
return self._distances[xy]
def remaining(self, port: Port) -> float:
xy = (port.x, port.y)
if xy not in self._remaining:
point = Point(xy)
self._remaining[xy] = self._length - self.centerline.project(point) + self.centerline.distance(point)
return self._remaining[xy]
def nearby_anchors(self, port: Port, forward_limit: float) -> list[tuple[float, float]]:
"""Return nearby waypoints in the current port's forward/lateral frame."""
dx, dy = HEADINGS[int(port.r) // 90]
candidates = []
for x, y in self._anchors:
px, py = x - port.x, y - port.y
forward, lateral = px * dx + py * dy, py * dx - px * dy
if 0 < forward <= forward_limit:
candidates.append((forward, lateral))
return sorted(candidates, key=lambda xy: xy[0] + abs(xy[1]))[:4]
@dataclass(frozen=True, slots=True)
class _Portal:
lanes: tuple[XY, ...]
midpoint: XY
@dataclass(frozen=True, slots=True)
class _Endpoint:
port: XY
lead: XY
cell: int
@dataclass(frozen=True, slots=True)
class _Assignment:
cells: tuple[int, ...]
points: tuple[XY, ...]
cost: float
def _edge(a: int, b: int) -> Edge:
return (a, b) if a < b else (b, a)
class _Mesh:
def __init__(self, board: Polygon, obstacles: Iterable[Polygon], margin: float, clearance: float) -> None:
triangulate = getattr(shapely, "constrained_delaunay_triangles", None)
if triangulate is None:
raise RuntimeError("Topological routing requires Shapely 2.1 and GEOS 3.10 or newer")
self.pitch = max(1.0, 2 * margin + clearance)
obstacles = shapely.union_all([shape.buffer(margin + clearance, join_style="mitre") for shape in obstacles])
self.free = board.buffer(-margin).difference(obstacles)
self.boundary = self.free.boundary
self.cells: tuple[Polygon, ...] = tuple(triangulate(self.free).geoms)
self.index = shapely.STRtree(self.cells)
self.portals: dict[Edge, _Portal] = {}
self.neighbors: list[list[int]] = [[] for _ in self.cells]
self.room: dict[XY, float] = {}
edges: dict[tuple[XY, XY], int] = {}
for cell_id, cell in enumerate(self.cells):
for a, b in pairwise(cell.exterior.coords):
segment = (a, b) if a < b else (b, a)
other = edges.get(segment)
if other is None:
edges[segment] = cell_id
continue
ax, ay = segment[0]
bx, by = segment[1]
length = hypot(bx - ax, by - ay)
# Leave a small offset at wall vertices. Narrow passages keep a middle lane.
usable = max(0.0, length - 0.2)
count = min(9, 1 + int(usable / self.pitch))
spacing = usable / max(1, count - 1)
fractions = [0.5 + (i - (count - 1) / 2) * spacing / length for i in range(count)]
lanes = tuple((ax + (bx - ax) * f, ay + (by - ay) * f) for f in fractions)
self.portals[other, cell_id] = _Portal(lanes, ((ax + bx) / 2, (ay + by) / 2))
self.neighbors[other].append(cell_id)
self.neighbors[cell_id].append(other)
def endpoint(self, port: Port, direction: int, lead_length: float) -> _Endpoint | None:
x, y, rotation = port.as_tuple()
dx, dy = HEADINGS[rotation // 90]
for length in (lead_length, lead_length / 2, 1.0, 0.0):
lead = (x + dx * length * direction, y + dy * length * direction)
if length and not self.free.covers(LineString(((x, y), lead))):
continue
cells = self.index.query(Point(lead), predicate="covered_by")
if len(cells):
return _Endpoint((x, y), lead, int(min(cells)))
return None
def _crossing_cost(self, edge: Edge, demand: dict[Edge, int]) -> float:
count = len(self.portals[edge].lanes)
load = demand.get(edge, 0)
return self.pitch * (load / count + 12 * max(0, load + 1 - count))
def shortest(
self,
start: _Endpoint,
target: _Endpoint,
demand: dict[Edge, int],
prefix: tuple[int, ...],
blocked: set[Edge],
) -> tuple[float, tuple[int, ...]]:
location = start.lead
prefix_cost = 0.0
for a, b in pairwise(prefix):
edge = _edge(a, b)
midpoint = self.portals[edge].midpoint
prefix_cost += hypot(midpoint[0] - location[0], midpoint[1] - location[1]) + self._crossing_cost(edge, demand)
location = midpoint
# In a triangle the straight line between two portal points stays in free space.
# The entry portal is part of the state because it changes each exit cost.
queue = [(prefix_cost + hypot(target.lead[0] - location[0], target.lead[1] - location[1]), prefix_cost, prefix, location)]
cost_by_entry: dict[tuple[int, int], float] = {}
while queue:
estimate, cost, path, location = heappop(queue)
cell = path[-1]
if cell == target.cell:
return estimate, path
for neighbor in self.neighbors[cell]:
edge = _edge(cell, neighbor)
if neighbor in path or edge in blocked:
continue
midpoint = self.portals[edge].midpoint
next_cost = cost + hypot(midpoint[0] - location[0], midpoint[1] - location[1]) + self._crossing_cost(edge, demand)
if next_cost < cost_by_entry.get((cell, neighbor), inf):
cost_by_entry[cell, neighbor] = next_cost
remaining = hypot(target.lead[0] - midpoint[0], target.lead[1] - midpoint[1])
heappush(queue, (next_cost + remaining, next_cost, (*path, neighbor), midpoint))
return inf, ()
def alternatives(self, start: _Endpoint, target: _Endpoint, demand: dict[Edge, int], limit: int) -> list[tuple[int, ...]]:
_, first = self.shortest(start, target, demand, (start.cell,), set())
if not first:
return []
paths = [first]
frontier: list[tuple[float, tuple[int, ...]]] = []
seen = {first}
while len(paths) < limit:
for end in range(1, len(paths[-1])):
prefix = paths[-1][:end]
blocked = {_edge(path[end - 1], path[end]) for path in paths if path[:end] == prefix and len(path) > end}
cost, candidate = self.shortest(start, target, demand, prefix, blocked)
if candidate and candidate not in seen:
seen.add(candidate)
heappush(frontier, (cost, candidate))
if not frontier:
break
paths.append(heappop(frontier)[1])
return paths
def turn_cost(self, a: XY, b: XY, c: XY, radius: float) -> float:
dx, dy = b[0] - a[0], b[1] - a[1]
ex, ey = c[0] - b[0], c[1] - b[1]
scale = hypot(dx, dy) * hypot(ex, ey)
if not scale or not radius:
return 0.0
if b not in self.room:
self.room[b] = self.boundary.distance(Point(b))
angle_cost = 1 - max(-1.0, min(1.0, (dx * ex + dy * ey) / scale))
return angle_cost * (radius / 2 + 3 * max(0, radius - self.room[b]))
def assign_lanes(
self,
cells: tuple[int, ...],
start: _Endpoint,
target: _Endpoint,
reservations: dict[int, BaseGeometry],
radius: float,
) -> _Assignment:
gates = [self.portals[_edge(a, b)].lanes for a, b in pairwise(cells)]
gates.append((target.lead,))
choices = [(0.0, (start.port, start.lead))]
for cell, gate in zip(cells, gates, strict=True):
next_choices = []
for point in gate:
best = (inf, ())
for previous_cost, points in choices:
a, b = points[-2:]
distance = hypot(point[0] - b[0], point[1] - b[1])
cost = previous_cost + distance + self.turn_cost(a, b, point, radius)
buffered_routes = reservations.get(cell)
if buffered_routes is not None and distance and buffered_routes.intersects(LineString((b, point))):
cost += 12 * self.pitch + 4 * radius
if cell == target.cell:
cost += self.turn_cost(b, point, target.port, radius)
if cost < best[0]:
best = (cost, (*points, point))
next_choices.append(best)
choices = next_choices
cost, points = choices[0]
return _Assignment(cells, (*points, target.port), cost)
def plan_corridors(
bounds: tuple[float, float, float, float],
obstacles: Iterable[Polygon],
nets: Sequence[NetSpec],
*,
clearance: float,
bend_radius: float,
limit: int,
) -> dict[str, tuple[Corridor, ...]]:
if not nets:
return {}
mesh = _Mesh(box(*bounds), obstacles, max(net.width for net in nets) / 2, clearance)
board = box(*bounds)
endpoints = {}
leads: dict[int, list[tuple[str, BaseGeometry]]] = {}
for net in nets:
span = hypot(net.target.x - net.start.x, net.target.y - net.start.y)
lead_length = min(max(bend_radius / 2, mesh.pitch), span / 4)
start = mesh.endpoint(net.start, 1, lead_length)
target = mesh.endpoint(net.target, -1, lead_length)
if start is not None and target is not None and start.port != target.port:
endpoints[net.net_id] = start, target
for end in (start, target):
if end.port == end.lead:
continue
shape = LineString((end.port, end.lead)).buffer(mesh.pitch - 0.01)
for cell in mesh.index.query(shape, predicate="intersects"):
leads.setdefault(cell, []).append((net.net_id, shape))
occupied: dict[int, list[BaseGeometry]] = {}
demand: dict[Edge, int] = {}
guides: dict[str, tuple[Corridor, ...]] = {}
for net in nets:
if net.net_id not in endpoints:
continue
start, target = endpoints[net.net_id]
candidates = mesh.alternatives(start, target, demand, limit)
candidate_cells = {cell for candidate in candidates for cell in candidate}
overlapping = {
cell: occupied.get(cell, []) + [shape for net_id, shape in leads.get(cell, ()) if net_id != net.net_id] for cell in candidate_cells
}
reservations = {cell: shapely.union_all(shapes) for cell, shapes in overlapping.items() if shapes}
for reservation in reservations.values():
shapely.prepare(reservation)
assignments = sorted(
(mesh.assign_lanes(cells, start, target, reservations, bend_radius) for cells in candidates),
key=lambda assignment: assignment.cost,
)
if not assignments:
continue
best = assignments[0]
for a, b in pairwise(best.cells):
edge = _edge(a, b)
demand[edge] = demand.get(edge, 0) + 1
reservation = LineString(best.points).buffer(mesh.pitch - 0.01)
for cell in mesh.index.query(reservation, predicate="intersects"):
occupied.setdefault(cell, []).append(reservation)
corridors = []
for assignment in assignments:
line = LineString(assignment.points)
region = shapely.union_all([mesh.cells[i] for i in assignment.cells] + [line])
footprint = region.buffer(mesh.pitch + net.width / 2, join_style="mitre").intersection(board)
shapely.prepare(footprint)
corridors.append(Corridor(line, footprint, max(bend_radius, mesh.pitch)))
guides[net.net_id] = tuple(corridors)
return guides

View file

@ -0,0 +1,92 @@
from __future__ import annotations
from itertools import pairwise
from math import isclose
from typing import TYPE_CHECKING
from inire.geometry.primitives import Port
from inire.seeds import Bend90Seed, PathSeed, SBendSeed, StraightSeed
if TYPE_CHECKING:
from collections.abc import Sequence
from inire.geometry.components import ComponentResult
from inire.seeds import PathSegmentSeed
XY = tuple[int, int]
_HEADINGS = ((1, 0), (0, 1), (-1, 0), (0, -1))
def _direction(a: XY, b: XY) -> int | None:
dx, dy = b[0] - a[0], b[1] - a[1]
if not dx and not dy:
raise ValueError("Consecutive waypoints must be distinct")
if not dy:
return 0 if dx > 0 else 180
if not dx:
return 90 if dy > 0 else 270
return None
def compile_waypoints(points: tuple[XY, ...], start: Port, radius: float) -> tuple[PathSeed, Port]:
"""Replace sharp Manhattan intersections with tangential arc components."""
if len(points) < 2 or points[0] != (start.x, start.y):
raise ValueError("The waypoint path must start at the port and have at least two points")
directions = [_direction(a, b) for a, b in pairwise(points)]
corners = tuple(a is not None and b is not None and a != b for a, b in pairwise(directions))
segments: list[PathSegmentSeed] = []
heading = int(start.r)
for index, (a, b) in enumerate(pairwise(points)):
direction = directions[index]
dx, dy = b[0] - a[0], b[1] - a[1]
if direction is None:
ux, uy = _HEADINGS[heading // 90]
offset = dy * ux - dx * uy
span = dx * ux + dy * uy
if not 0 < abs(offset) < 2 * radius or not isclose(span**2, abs(offset) * (4 * radius - abs(offset))) or span <= 0:
raise ValueError(f"Invalid S-bend from {a} to {b}")
segments.append(SBendSeed(offset, radius))
continue
if direction != heading:
raise ValueError(f"Inconsistent segment heading from {a} to {b}")
entry = index > 0 and corners[index - 1]
exit_corner = index < len(corners) and corners[index]
length = abs(dx) + abs(dy) - radius * (entry + exit_corner)
if length < 0:
raise ValueError(f"Overlapping bend tangencies from {a} to {b}")
if length:
segments.append(StraightSeed(length))
if exit_corner:
next_heading = directions[index + 1]
assert next_heading is not None
sweep = (next_heading - heading) % 360
if sweep not in (90, 270):
raise ValueError(f"Unsupported turn at {b}")
segments.append(Bend90Seed(radius, "CCW" if sweep == 90 else "CW"))
heading = next_heading
return PathSeed(tuple(segments)), Port(*points[-1], heading)
def export_waypoints(path: Sequence[ComponentResult]) -> tuple[tuple[float, float], ...]:
"""Export bend intersections and S-bend tangencies from a realized path."""
points: list[tuple[float, float]] = []
def append(x: float, y: float) -> None:
if not points or points[-1] != (x, y):
points.append((x, y))
if not path:
return ()
append(path[0].start_port.x, path[0].start_port.y)
for component in path:
start = component.start_port
move = component.move_spec
if isinstance(move, Bend90Seed):
ux, uy = _HEADINGS[int(start.r) // 90]
append(start.x + ux * move.radius, start.y + uy * move.radius)
elif isinstance(move, SBendSeed):
append(start.x, start.y)
append(component.end_port.x, component.end_port.y)
append(path[-1].end_port.x, path[-1].end_port.y)
return tuple(points)

View file

@ -7,7 +7,7 @@ from inire.geometry.component_overlap import components_overlap
from inire.geometry.components import Bend90, Straight from inire.geometry.components import Bend90, Straight
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Sequence from collections.abc import Iterator, Sequence
from inire.geometry.collision import RoutingWorld from inire.geometry.collision import RoutingWorld
from inire.geometry.components import ComponentResult from inire.geometry.components import ComponentResult
@ -227,9 +227,8 @@ class PathRefiner:
return None return None
return path return path
def _iter_refinement_windows(self, start: Port, path: Sequence[ComponentResult]) -> list[tuple[int, int]]: def _iter_refinement_windows(self, start: Port, path: Sequence[ComponentResult]) -> Iterator[tuple[int, int]]:
ports = self._path_ports(start, path) ports = self._path_ports(start, path)
windows: list[tuple[int, int]] = []
min_radius = min(self.context.options.search.bend_radii, default=0.0) min_radius = min(self.context.options.search.bend_radii, default=0.0)
for window_size in range(len(path), 0, -1): for window_size in range(len(path), 0, -1):
@ -246,9 +245,7 @@ class PathRefiner:
local_dx, _ = self._to_local(window_start, window_end) local_dx, _ = self._to_local(window_start, window_end)
if local_dx < 4.0 * min_radius - 0.01: if local_dx < 4.0 * min_radius - 0.01:
continue continue
self.context.metrics.total_refinement_windows_considered += 1 yield start_idx, end_idx
windows.append((start_idx, end_idx))
return windows
def _try_refine_window( def _try_refine_window(
self, self,
@ -276,15 +273,17 @@ class PathRefiner:
continue continue
self.context.metrics.total_refinement_candidates_built += 1 self.context.metrics.total_refinement_candidates_built += 1
candidate_path = path[:start_idx] + replacement + path[end_idx:] candidate_path = path[:start_idx] + replacement + path[end_idx:]
# Only an improving candidate can replace the incumbent.
candidate_cost = self.path_cost(candidate_path)
if not candidate_cost + 1e-6 < best_candidate_cost:
continue
self.context.metrics.total_refinement_candidates_verified += 1 self.context.metrics.total_refinement_candidates_verified += 1
report = self.collision_engine.verify_path_report(net_id, candidate_path) report = self.collision_engine.verify_path_report(net_id, candidate_path)
if not report.is_valid: if not report.is_valid:
continue continue
candidate_cost = self.path_cost(candidate_path) self.context.metrics.total_refinement_candidates_accepted += 1
if candidate_cost + 1e-6 < best_candidate_cost: best_candidate_cost = candidate_cost
self.context.metrics.total_refinement_candidates_accepted += 1 best_path = candidate_path
best_candidate_cost = candidate_cost
best_path = candidate_path
if best_path is None: if best_path is None:
return None return None
@ -308,17 +307,22 @@ class PathRefiner:
best_path = path best_path = path
best_cost = self.score_path(start, path) best_cost = self.score_path(start, path)
remaining = self.context.options.refinement.max_windows_per_net
for _ in range(3): for _ in range(3):
improved = False improved = False
for start_idx, end_idx in self._iter_refinement_windows(start, best_path): for start_idx, end_idx in self._iter_refinement_windows(start, best_path):
if remaining is not None:
remaining -= 1
self.context.metrics.total_refinement_windows_considered += 1
refined = self._try_refine_window(net_id, start, net_width, best_path, start_idx, end_idx, best_cost) refined = self._try_refine_window(net_id, start, net_width, best_path, start_idx, end_idx, best_cost)
if refined is None: if refined is not None:
continue best_path, best_cost = refined
best_path, best_cost = refined improved = True
improved = True break
break if remaining == 0:
if not improved: break
if not improved or remaining == 0:
break break
return best_path return best_path

View file

@ -1,6 +1,7 @@
import importlib import importlib
import pytest import pytest
import shapely
from shapely.geometry import box from shapely.geometry import box
import inire.router._router as router_module import inire.router._router as router_module
@ -14,6 +15,7 @@ from inire import (
RoutingOptions, RoutingOptions,
RoutingProblem, RoutingProblem,
SearchOptions, SearchOptions,
TopologyOptions,
route, route,
) )
from inire.geometry.components import Straight from inire.geometry.components import Straight
@ -53,12 +55,86 @@ def test_route_problem_smoke() -> None:
assert set(run.results_by_net) == {"net1"} assert set(run.results_by_net) == {"net1"}
assert run.results_by_net["net1"].is_valid assert run.results_by_net["net1"].is_valid
assert run.automatic is not None
assert run.automatic.verified_net_ids == ("net1",)
assert all(stage.node_limit <= 500 for stage in run.automatic.stages)
assert run.conflict_trace == () assert run.conflict_trace == ()
assert run.frontier_trace == () assert run.frontier_trace == ()
assert run.pre_pair_frontier_trace is None assert run.pre_pair_frontier_trace is None
assert run.iteration_trace == () assert run.iteration_trace == ()
def test_automatic_routes_report_boundary_violations_in_results_and_diagnostics() -> None:
problem = RoutingProblem(
bounds=(0, 0, 100, 100),
nets=(
NetSpec("edge", Port(10, 0, 0), Port(90, 0, 0)),
NetSpec("flush", Port(0, 50, 0), Port(100, 50, 0)),
),
)
options = RoutingOptions(search=SearchOptions(node_limit=100), diagnostics=DiagnosticsOptions(capture_conflict_trace=True))
run = route(problem, options=options)
assert run.automatic is not None
valid_ids = tuple(net_id for net_id, result in run.results_by_net.items() if result.is_valid)
assert valid_ids == run.automatic.verified_net_ids == ("flush",)
selected = run.automatic.stages[run.automatic.selected_stage]
assert selected.out_of_bounds_net_ids == ("edge",)
edge = run.results_by_net["edge"]
assert edge.reached_target
assert edge.outcome == "colliding"
assert edge.report.out_of_bounds
assert edge.collisions == 1
assert not edge.report.is_valid
final = run.conflict_trace[-1]
assert final.stage == "final"
assert "edge" not in final.completed_net_ids
traced_edge = next(net for net in final.nets if net.net_id == "edge")
assert traced_edge.outcome == edge.outcome
assert traced_edge.report == edge.report
@pytest.mark.parametrize("node_limit", [40, 500, 700, None], ids=["tight", "initial", "higher", "default"])
def test_default_router_escalates_only_within_the_configured_node_limit(monkeypatch, node_limit) -> None:
problem = RoutingProblem((0, 0, 200, 200), (NetSpec("turn", Port(20, 20, 0), Port(180, 160, 90)),))
route_astar = router_module.route_astar
attempted_limits = []
def route_with_budget(*args, config, **kwargs):
attempted_limits.append(config.node_limit)
if config.node_limit <= 500:
return None
return route_astar(*args, config=config, **kwargs)
monkeypatch.setattr(router_module, "route_astar", route_with_budget)
options = None if node_limit is None else RoutingOptions(search=SearchOptions(node_limit=node_limit))
run = route(problem, options=options)
assert run.automatic is not None
ceiling = SearchOptions().node_limit if node_limit is None else node_limit
assert attempted_limits
assert max(attempted_limits) <= ceiling
limits = [stage.node_limit for stage in run.automatic.stages]
assert min(500, ceiling) in limits
assert [limit for limit in limits if limit > 500] == ([ceiling] if ceiling > 500 else [])
assert run.results_by_net["turn"].is_valid == (ceiling > 500)
def test_default_router_uses_lattice_when_triangulation_is_unavailable(monkeypatch) -> None:
problem = RoutingProblem((0, 0, 200, 200), (NetSpec("turn", Port(20, 20, 0), Port(180, 160, 90)),))
monkeypatch.delattr(shapely, "constrained_delaunay_triangles", raising=False)
run = route(problem)
assert run.automatic is not None
assert run.automatic.selected_planner == "lattice"
assert run.automatic.stages[run.automatic.selected_stage].kind == "lattice-fallback"
assert run.automatic.verified_net_ids == ("turn",)
def test_route_problem_supports_configs_and_debug_data() -> None: def test_route_problem_supports_configs_and_debug_data() -> None:
problem = RoutingProblem( problem = RoutingProblem(
bounds=(0, 0, 100, 100), bounds=(0, 0, 100, 100),
@ -78,6 +154,7 @@ def test_route_problem_supports_configs_and_debug_data() -> None:
congestion=CongestionOptions(warm_start_enabled=False), congestion=CongestionOptions(warm_start_enabled=False),
refinement=RefinementOptions(enabled=True), refinement=RefinementOptions(enabled=True),
diagnostics=DiagnosticsOptions(capture_expanded=True), diagnostics=DiagnosticsOptions(capture_expanded=True),
topology=TopologyOptions(mode="off"),
) )
run = route(problem, options=options) run = route(problem, options=options)
@ -230,6 +307,7 @@ def test_capture_iteration_trace_records_iteration_and_attempt_deltas() -> None:
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False),
refinement=RefinementOptions(enabled=False), refinement=RefinementOptions(enabled=False),
diagnostics=DiagnosticsOptions(capture_iteration_trace=True), diagnostics=DiagnosticsOptions(capture_iteration_trace=True),
topology=TopologyOptions(mode="off"),
), ),
) )
@ -265,6 +343,7 @@ def test_capture_conflict_trace_records_component_pairs() -> None:
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False),
refinement=RefinementOptions(enabled=False), refinement=RefinementOptions(enabled=False),
diagnostics=DiagnosticsOptions(capture_conflict_trace=True), diagnostics=DiagnosticsOptions(capture_conflict_trace=True),
topology=TopologyOptions(mode="off"),
) )
run = route(problem, options=options) run = route(problem, options=options)
@ -292,6 +371,7 @@ def test_capture_frontier_trace_preserves_route_outputs() -> None:
base_options = RoutingOptions( base_options = RoutingOptions(
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False),
refinement=RefinementOptions(enabled=False), refinement=RefinementOptions(enabled=False),
topology=TopologyOptions(mode="off"),
) )
run_without_trace = route(problem, options=base_options) run_without_trace = route(problem, options=base_options)
@ -301,6 +381,7 @@ def test_capture_frontier_trace_preserves_route_outputs() -> None:
congestion=base_options.congestion, congestion=base_options.congestion,
refinement=base_options.refinement, refinement=base_options.refinement,
diagnostics=DiagnosticsOptions(capture_frontier_trace=True), diagnostics=DiagnosticsOptions(capture_frontier_trace=True),
topology=base_options.topology,
), ),
) )
@ -353,6 +434,7 @@ def test_capture_frontier_trace_records_prune_reasons() -> None:
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False),
refinement=RefinementOptions(enabled=False), refinement=RefinementOptions(enabled=False),
diagnostics=DiagnosticsOptions(capture_frontier_trace=True), diagnostics=DiagnosticsOptions(capture_frontier_trace=True),
topology=TopologyOptions(mode="off"),
), ),
) )
@ -378,6 +460,7 @@ def test_reverify_iterations_stop_early_on_stalled_conflict_graph() -> None:
options = RoutingOptions( options = RoutingOptions(
congestion=CongestionOptions(max_iterations=10, warm_start_enabled=False), congestion=CongestionOptions(max_iterations=10, warm_start_enabled=False),
refinement=RefinementOptions(enabled=False), refinement=RefinementOptions(enabled=False),
topology=TopologyOptions(mode="off"),
) )
run = route(problem, options=options) run = route(problem, options=options)
@ -795,7 +878,7 @@ def test_route_results_metrics_are_snapshots() -> None:
bounds=(0, 0, 100, 100), bounds=(0, 0, 100, 100),
nets=(NetSpec("net1", Port(10, 50, 0), Port(90, 50, 0), width=2.0),), nets=(NetSpec("net1", Port(10, 50, 0), Port(90, 50, 0), width=2.0),),
) )
options = RoutingOptions() options = RoutingOptions(topology=TopologyOptions(mode="off"))
run1 = route(problem, options=options) run1 = route(problem, options=options)
first_metrics = run1.metrics first_metrics = run1.metrics
run2 = route(problem, options=options) run2 = route(problem, options=options)

View file

@ -1,3 +1,4 @@
import pytest
from shapely.geometry import box from shapely.geometry import box
from inire import ( from inire import (
@ -139,7 +140,8 @@ def test_route_all_refreshes_static_caches_after_static_topology_changes() -> No
assert [(comp.move_type, comp.start_port.as_tuple(), comp.end_port.as_tuple()) for comp in auto_result.path] == [ assert [(comp.move_type, comp.start_port.as_tuple(), comp.end_port.as_tuple()) for comp in auto_result.path] == [
(comp.move_type, comp.start_port.as_tuple(), comp.end_port.as_tuple()) for comp in manual_result.path (comp.move_type, comp.start_port.as_tuple(), comp.end_port.as_tuple()) for comp in manual_result.path
] ]
def test_refine_path_handles_same_orientation_lateral_offset() -> None: @pytest.mark.parametrize("max_windows", [1, None])
def test_refine_path_handles_same_orientation_lateral_offset(max_windows: int | None) -> None:
engine = RoutingWorld(clearance=2.0) engine = RoutingWorld(clearance=2.0)
danger_map = DangerMap(bounds=(-20, -20, 120, 120)) danger_map = DangerMap(bounds=(-20, -20, 120, 120))
danger_map.precompute([]) danger_map.precompute([])
@ -151,6 +153,7 @@ def test_refine_path_handles_same_orientation_lateral_offset() -> None:
bounds=(-20, -20, 120, 120), bounds=(-20, -20, 120, 120),
bend_radii=[5.0, 10.0], bend_radii=[5.0, 10.0],
enabled=True, enabled=True,
max_windows_per_net=max_windows,
) )
start = Port(0, 0, 0) start = Port(0, 0, 0)
@ -182,6 +185,11 @@ def test_refine_path_handles_same_orientation_lateral_offset() -> None:
assert sum(1 for comp in refined if comp.move_type == "bend90") == 4 assert sum(1 for comp in refined if comp.move_type == "bend90") == 4
assert refined[-1].end_port == target assert refined[-1].end_port == target
assert pf.refiner.path_cost(refined) < pf.refiner.path_cost(path) assert pf.refiner.path_cost(refined) < pf.refiner.path_cost(path)
windows = pf.context.metrics.total_refinement_windows_considered
if max_windows == 1:
assert windows == 1
else:
assert windows > 1
def test_refine_path_can_simplify_subpath_with_different_global_orientation() -> None: def test_refine_path_can_simplify_subpath_with_different_global_orientation() -> None:

Some files were not shown because too many files have changed in this diff Show more