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

457 lines
20 KiB
Python

from __future__ import annotations
from bisect import bisect_left
from dataclasses import dataclass
from heapq import merge
from itertools import accumulate, chain
from math import inf
from typing import TYPE_CHECKING, Any
from shapely.geometry import Polygon
from inire.constants import TOLERANCE_LINEAR
from inire.geometry.component_overlap import components_overlap
from inire.geometry.components import (
_bend90_length, bend_fits_width, bend90_grid_span, bend90_uses_circular_geometry, build_component, component_endpoint,
ComponentPreparationError,
)
from inire.geometry.primitives import port_local_coordinates
from inire.model import resolve_bend_geometry
if TYPE_CHECKING:
from collections.abc import Iterator, Sequence
from inire.geometry.collision import RoutingWorld
from inire.geometry.components import ComponentResult, MoveKind
from inire.geometry.primitives import Port
from inire.router._astar_types import AStarContext
from inire.router.cost import ScoreableMove
from inire.seeds import BendDirection
@dataclass(frozen=True, slots=True)
class _DoglegMove:
end_port: Port
length: float
move_type: MoveKind
direction: BendDirection | None = None
bend_radius: float | None = None
def _forward_position(port: Port) -> float:
axis = port.y if port.r % 180 else port.x
return axis if port.r < 180 else -axis
class _WindowEnds:
"""Find the last sufficiently forward endpoint in a prefix of the path."""
def __init__(self, indices: list[int], ports: Sequence[Port]) -> None:
self.indices = indices
self._size = 1 << (len(indices) - 1).bit_length()
self._maxima = [-inf] * (2 * self._size)
self._maxima[self._size : self._size + len(indices)] = [_forward_position(ports[index]) for index in indices]
for node in range(self._size - 1, 0, -1):
self._maxima[node] = max(self._maxima[2 * node], self._maxima[2 * node + 1])
def rightmost(self, stop: int, minimum: float) -> int | None:
if not stop:
return None
node = self._size + stop - 1
if self._maxima[node] >= minimum:
return stop - 1
# Earlier leaves lie in left siblings of the path back to the root.
while node > 1:
if node % 2 and self._maxima[node - 1] >= minimum:
node -= 1
while node < self._size:
right = 2 * node + 1
node = right if self._maxima[right] >= minimum else right - 1
return node - self._size
node //= 2
return None
def component_hits_ancestor_chain(component: ComponentResult, parent_node: Any, clearance: float = 0.0) -> bool:
current = parent_node
between = 0.0
previous_move = parent_node.component_result if parent_node else None
while current and current.parent:
ancestor_component = current.component_result
if ancestor_component:
if current is parent_node:
if components_overlap(ancestor_component, component, prefer_actual=True, at_join=True):
return True
else:
single_bend = current is parent_node.parent and previous_move is not None and previous_move.move_type != "straight"
spacing = clearance if not single_bend and between >= clearance - TOLERANCE_LINEAR else 0.0
if components_overlap(ancestor_component, component, prefer_actual=True, clearance=spacing):
return True
between += ancestor_component.length
current = current.parent
return False
class PathRefiner:
__slots__ = ("context",)
def __init__(self, context: AStarContext) -> None:
self.context = context
@property
def collision_engine(self) -> RoutingWorld:
return self.context.cost_evaluator.collision_engine
def path_cost(
self,
path: Sequence[ComponentResult],
*,
start: Port | None = None,
) -> float:
if not path:
return 0.0
actual_start = path[0].start_port if start is None else start
return self.score_path(actual_start, path)
def score_path(self, start: Port, path: Sequence[ScoreableMove]) -> float:
weights = self.context.options.refinement.objective or self.context.cost_evaluator.default_weights
return self.context.cost_evaluator.path_cost(start, path, weights=weights)
def _path_ports(self, start: Port, path: Sequence[ComponentResult]) -> list[Port]:
ports = [start]
ports.extend(comp.end_port for comp in path)
return ports
def _window_query_bounds(self, start: Port, target: Port, path: Sequence[ComponentResult], pad: float) -> tuple[float, float, float, float]:
min_x = float(min(start.x, target.x))
min_y = float(min(start.y, target.y))
max_x = float(max(start.x, target.x))
max_y = float(max(start.y, target.y))
for comp in path:
bounds = comp.total_bounds
min_x = min(min_x, bounds[0])
min_y = min(min_y, bounds[1])
max_x = max(max_x, bounds[2])
max_y = max(max_y, bounds[3])
return (min_x - pad, min_y - pad, max_x + pad, max_y + pad)
def _candidate_side_extents(
self,
start: Port,
target: Port,
window_path: Sequence[ComponentResult],
net_width: float,
radius: float,
) -> list[float]:
local_dx, local_dy = port_local_coordinates(start, target.x, target.y)
span = bend90_grid_span(radius)
if local_dx < 4 * span:
return []
local_points = [port_local_coordinates(start, start.x, start.y)]
local_points.extend(port_local_coordinates(start, comp.end_port.x, comp.end_port.y) for comp in window_path)
min_side = float(min(point[1] for point in local_points))
max_side = float(max(point[1] for point in local_points))
positive_anchors: set[float] = set()
negative_anchors: set[float] = set()
direct_extents: set[float] = set()
if max_side > 0.01:
positive_anchors.add(max_side)
direct_extents.add(max_side)
if min_side < -0.01:
negative_anchors.add(min_side)
direct_extents.add(min_side)
if local_dy > 0:
positive_anchors.add(float(local_dy))
elif local_dy < 0:
negative_anchors.add(float(local_dy))
pad = 2 * span + self.collision_engine.clearance + net_width
query_bounds = self._window_query_bounds(start, target, window_path, pad)
x_min = min(0.0, float(local_dx)) - 0.01
x_max = max(0.0, float(local_dx)) + 0.01
for bounds in self.collision_engine.iter_static_obstacle_bounds(query_bounds):
self.context.metrics.total_refinement_static_bounds_checked += 1
local_corners = (
port_local_coordinates(start, bounds[0], bounds[1]),
port_local_coordinates(start, bounds[0], bounds[3]),
port_local_coordinates(start, bounds[2], bounds[1]),
port_local_coordinates(start, bounds[2], bounds[3]),
)
obs_min_x = min(pt[0] for pt in local_corners)
obs_max_x = max(pt[0] for pt in local_corners)
if obs_max_x < x_min or obs_min_x > x_max:
continue
obs_min_y = min(pt[1] for pt in local_corners)
obs_max_y = max(pt[1] for pt in local_corners)
positive_anchors.add(obs_max_y)
negative_anchors.add(obs_min_y)
for bounds in self.collision_engine.iter_dynamic_path_bounds(query_bounds):
self.context.metrics.total_refinement_dynamic_bounds_checked += 1
local_corners = (
port_local_coordinates(start, bounds[0], bounds[1]),
port_local_coordinates(start, bounds[0], bounds[3]),
port_local_coordinates(start, bounds[2], bounds[1]),
port_local_coordinates(start, bounds[2], bounds[3]),
)
obs_min_x = min(pt[0] for pt in local_corners)
obs_max_x = max(pt[0] for pt in local_corners)
if obs_max_x < x_min or obs_min_x > x_max:
continue
obs_min_y = min(pt[1] for pt in local_corners)
obs_max_y = max(pt[1] for pt in local_corners)
positive_anchors.add(obs_max_y)
negative_anchors.add(obs_min_y)
for anchor in tuple(positive_anchors):
if anchor > max(0.0, float(local_dy)) - 0.01:
direct_extents.add(anchor + pad)
for anchor in tuple(negative_anchors):
if anchor < min(0.0, float(local_dy)) + 0.01:
direct_extents.add(anchor - pad)
self.context.metrics.total_refinement_candidate_side_extents += len(direct_extents)
return sorted(direct_extents, key=lambda value: (abs(value), value))
def _dogleg_moves(
self,
start: Port,
target: Port,
radius: float,
side_extent: float,
) -> list[_DoglegMove] | None:
local_dx, local_dy = port_local_coordinates(start, target.x, target.y)
span = bend90_grid_span(radius)
if local_dx < 4 * span or abs(side_extent) < 0.01:
return None
first_sign = 1 if side_extent > 0 else -1
first_straight = round(abs(side_extent)) - 2 * span
second_straight = first_straight - first_sign * local_dy
if first_straight < -0.01 or second_straight < -0.01:
return None
min_straight = self.context.options.search.min_straight_length
if 0.01 < first_straight < min_straight - 0.01:
return None
if 0.01 < second_straight < min_straight - 0.01:
return None
forward_length = local_dx - 4 * span
if 0.01 < forward_length < min_straight - 0.01:
return None
bend_length = self.context.options.search.bend_physical_length or _bend90_length(radius)
moves: list[_DoglegMove] = []
curr = start
for sign, straight_len in (
(first_sign, first_straight),
(-first_sign, forward_length),
(-first_sign, second_straight),
(first_sign, 0.0),
):
direction = "CCW" if sign > 0 else "CW"
curr = component_endpoint(curr, "bend90", (radius, direction))
moves.append(_DoglegMove(curr, bend_length, "bend90", direction, bend_radius=radius))
if straight_len > 0.01:
length = float(straight_len)
curr = component_endpoint(curr, "straight", (length,))
moves.append(_DoglegMove(curr, length, "straight"))
return moves if curr == target else None
def _build_dogleg(
self, start: Port, width: float, radius: float, moves: list[_DoglegMove],
components: dict[tuple[Port, MoveKind, tuple], ComponentResult],
) -> list[ComponentResult]:
search = self.context.options.search
proxy, physical = resolve_bend_geometry(search)
dilation = self.collision_engine.clearance / 2.0
path = []
port = start
board = self.collision_engine.board
bounds = None if board is None else board.bounds
for move in moves:
parameters = (move.length,) if move.direction is None else (radius, move.direction)
key = (port, move.move_type, parameters)
component = components.get(key)
if component is None:
component = build_component(
port, width, move.move_type, parameters,
collision_type=proxy, physical_geometry_type=physical, clip_margin=search.bend_clip_margin, dilation=dilation,
physical_length=search.bend_physical_length if move.move_type == "bend90" else None, bounds=bounds,
)
if len(components) < 256:
components[key] = component
path.append(component)
port = component.end_port
return path
def _verify_changed_window(
self,
net_id: str,
replacement: list[ComponentResult],
prefix: list[ComponentResult],
suffix: list[ComponentResult],
) -> bool:
if self.collision_engine.self_clearance:
return self.collision_engine.verify_path_report(net_id, (*prefix, *replacement, *suffix)).is_valid
if not self.collision_engine.verify_path_report(net_id, replacement).is_valid:
return False
if prefix and components_overlap(prefix[-1], replacement[0], prefer_actual=True, at_join=True):
return False
if suffix and components_overlap(replacement[-1], suffix[0], prefer_actual=True, at_join=True):
return False
# The verified incumbent's prefix and suffix remain separated by
# several components. Only pairs involving a replacement can change.
for i, component in enumerate(replacement):
before = prefix if i > 0 else prefix[:-1]
after = suffix if i < len(replacement) - 1 else suffix[1:]
if any(components_overlap(component, other, prefer_actual=True) for other in chain(before, after)):
return False
return True
def _iter_refinement_windows(self, start: Port, path: Sequence[ComponentResult]) -> Iterator[tuple[int, int]]:
ports = self._path_ports(start, path)
min_forward = 4 * bend90_grid_span(min(self.context.options.search.bend_radii, default=0.0))
bends = [component.move_type == "bend90" for component in path]
bend_counts = tuple(accumulate(bends, initial=0))
limit = self.context.options.refinement.max_windows_per_net
# Keep the original order for a single attempt and for unlimited refinement.
prioritize_bend_edges = limit is not None and limit > 1
edge_counts = (2, 1, 0) if prioritize_bend_edges else (None,)
by_heading: dict[tuple[int | float, int | None], list[int]] = {}
for end, port in enumerate(ports[1:], start=1):
if bend_counts[end] >= 4:
edge = int(bends[end - 1]) if prioritize_bend_edges else None
by_heading.setdefault((port.r, edge), []).append(end)
candidates = {key: _WindowEnds(indices, ports) for key, indices in by_heading.items()}
def from_start(index: int, edge_count: int | None) -> Iterator[tuple[int, int, int]]:
end_edge = edge_count - int(bends[index]) if edge_count is not None else None
ends = candidates.get((ports[index].r, end_edge))
if ends is None:
return
minimum_end = bisect_left(bend_counts, bend_counts[index] + 4)
minimum_position = _forward_position(ports[index]) + min_forward
stop = len(ends.indices)
while (slot := ends.rightmost(stop, minimum_position)) is not None:
end = ends.indices[slot]
if end < minimum_end:
break
yield index - end, index, end
stop = slot
for edge_count in edge_counts:
windows = (from_start(index, edge_count) for index, count in enumerate(bend_counts[:-1]) if count <= bend_counts[-1] - 4)
# Each stream is longest-first, so the merge only needs one pending window per start.
for _, start_idx, end_idx in merge(*windows):
yield start_idx, end_idx
def _try_refine_window(
self,
net_id: str,
start: Port,
net_width: float,
path: list[ComponentResult],
start_idx: int,
end_idx: int,
best_cost: float,
incumbent_valid: bool,
) -> tuple[list[ComponentResult], float] | None:
ports = self._path_ports(start, path)
window_start = ports[start_idx]
window_end = ports[end_idx]
window_path = path[start_idx:end_idx]
prefix, suffix = path[:start_idx], path[end_idx:]
scoring_start = prefix[0].start_port if prefix else window_start
best_path: list[ComponentResult] | None = None
best_candidate_cost = best_cost
search = self.context.options.search
proxy, physical = resolve_bend_geometry(search)
circular_bend = bend90_uses_circular_geometry(proxy, physical)
custom_danger_map = self.context.cost_evaluator.danger_map if isinstance(physical, Polygon) else None
components: dict[tuple[Port, MoveKind, tuple], ComponentResult] = {}
for radius in search.bend_radii:
if circular_bend and not bend_fits_width(radius, net_width):
continue
side_extents = self._candidate_side_extents(window_start, window_end, window_path, net_width, radius)
for side_extent in dict.fromkeys(map(round, side_extents)):
moves = self._dogleg_moves(window_start, window_end, radius, side_extent)
if moves is None:
continue
# With an outlying declared port, score the placed custom outline.
outside = custom_danger_map is not None and any(
not custom_danger_map.is_within_bounds(port.x, port.y)
for port in chain((window_start,), (move.end_port for move in moves))
)
if not outside and not self.score_path(scoring_start, [*prefix, *moves, *suffix]) + 1e-6 < best_candidate_cost:
continue
try:
replacement = self._build_dogleg(window_start, net_width, radius, moves, components)
except (ComponentPreparationError, OverflowError):
continue
self.context.metrics.total_refinement_candidates_built += 1
candidate_path = [*prefix, *replacement, *suffix]
candidate_cost = self.score_path(scoring_start, candidate_path)
if not candidate_cost + 1e-6 < best_candidate_cost:
continue
self.context.metrics.total_refinement_candidates_verified += 1
valid = (
self._verify_changed_window(net_id, replacement, prefix, suffix)
if incumbent_valid
else self.collision_engine.verify_path_report(net_id, candidate_path).is_valid
)
if not valid:
continue
self.context.metrics.total_refinement_candidates_accepted += 1
best_candidate_cost = candidate_cost
best_path = candidate_path
if best_path is None:
return None
return best_path, best_candidate_cost
@staticmethod
def has_refinement_bends(path: Sequence[ComponentResult]) -> bool:
return len(path) >= 4 and sum(component.move_type == "bend90" for component in path) >= 4
def refine_path(
self,
net_id: str,
start: Port,
net_width: float,
path: Sequence[ComponentResult],
) -> list[ComponentResult]:
if not self.has_refinement_bends(path):
return list(path)
best_path = list(path)
best_cost = self.score_path(start, path)
remaining = self.context.options.refinement.max_windows_per_net
incumbent_valid = None
for _ in range(3):
improved = False
for start_idx, end_idx in self._iter_refinement_windows(start, best_path):
if incumbent_valid is None:
incumbent_valid = self.collision_engine.verify_path_report(net_id, best_path).is_valid
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, incumbent_valid)
if refined is not None:
best_path, best_cost = refined
incumbent_valid = True
improved = True
break
if remaining == 0:
break
if not improved or remaining == 0:
break
return best_path