inire/inire/router/refiner.py

448 lines
20 KiB
Python
Raw Normal View History

2026-03-29 18:27:03 -07:00
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
2026-03-29 18:27:03 -07:00
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
2026-03-29 18:27:03 -07:00
if TYPE_CHECKING:
from collections.abc import Iterator, Sequence
2026-03-30 15:32:29 -07:00
from inire.geometry.collision import RoutingWorld
from inire.geometry.components import ComponentResult, MoveKind
2026-03-29 18:27:03 -07:00
from inire.geometry.primitives import Port
2026-03-30 19:51:37 -07:00
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
2026-03-30 19:51:37 -07:00
2026-03-29 18:27:03 -07:00
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:
2026-03-29 18:27:03 -07:00
current = parent_node
between = 0.0
previous_move = parent_node.component_result if parent_node else None
2026-03-29 18:27:03 -07:00
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
2026-03-29 18:27:03 -07:00
current = current.parent
return False
class PathRefiner:
__slots__ = ("context",)
def __init__(self, context: AStarContext) -> None:
self.context = context
@property
2026-03-30 15:32:29 -07:00
def collision_engine(self) -> RoutingWorld:
2026-03-29 18:27:03 -07:00
return self.context.cost_evaluator.collision_engine
2026-03-30 15:32:29 -07:00
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
2026-03-30 19:51:37 -07:00
return self.score_path(actual_start, path)
2026-03-29 18:27:03 -07:00
def score_path(self, start: Port, path: Sequence[ScoreableMove]) -> float:
2026-03-30 19:51:37 -07:00
weights = self.context.options.refinement.objective or self.context.cost_evaluator.default_weights
return self.context.cost_evaluator.path_cost(start, path, weights=weights)
2026-03-30 15:32:29 -07:00
def _path_ports(self, start: Port, path: Sequence[ComponentResult]) -> list[Port]:
2026-03-29 18:27:03 -07:00
ports = [start]
ports.extend(comp.end_port for comp in path)
return ports
2026-03-30 15:32:29 -07:00
def _window_query_bounds(self, start: Port, target: Port, path: Sequence[ComponentResult], pad: float) -> tuple[float, float, float, float]:
2026-03-29 18:27:03 -07:00
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,
2026-03-30 15:32:29 -07:00
window_path: Sequence[ComponentResult],
2026-03-29 18:27:03 -07:00
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:
2026-03-29 18:27:03 -07:00
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)
2026-03-29 18:27:03 -07:00
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
2026-03-29 18:27:03 -07:00
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
2026-03-29 20:35:58 -07:00
for bounds in self.collision_engine.iter_static_obstacle_bounds(query_bounds):
2026-03-31 17:41:15 -07:00
self.context.metrics.total_refinement_static_bounds_checked += 1
2026-03-29 18:27:03 -07:00
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]),
2026-03-29 18:27:03 -07:00
)
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)
2026-03-29 20:35:58 -07:00
for bounds in self.collision_engine.iter_dynamic_path_bounds(query_bounds):
2026-03-31 17:41:15 -07:00
self.context.metrics.total_refinement_dynamic_bounds_checked += 1
2026-03-29 18:27:03 -07:00
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]),
2026-03-29 18:27:03 -07:00
)
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)
2026-03-31 17:41:15 -07:00
self.context.metrics.total_refinement_candidate_side_extents += len(direct_extents)
2026-03-29 18:27:03 -07:00
return sorted(direct_extents, key=lambda value: (abs(value), value))
def _dogleg_moves(
2026-03-29 18:27:03 -07:00
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:
2026-03-29 18:27:03 -07:00
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
2026-03-29 18:27:03 -07:00
if first_straight < -0.01 or second_straight < -0.01:
return None
2026-03-30 15:32:29 -07:00
min_straight = self.context.options.search.min_straight_length
2026-03-29 18:27:03 -07:00
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
2026-03-29 18:27:03 -07:00
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] = []
2026-03-29 18:27:03 -07:00
curr = start
for sign, straight_len in (
(first_sign, first_straight),
(-first_sign, forward_length),
(-first_sign, second_straight),
(first_sign, 0.0),
2026-03-29 18:27:03 -07:00
):
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))
2026-03-29 18:27:03 -07:00
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
2026-03-29 18:27:03 -07:00
def _build_dogleg(self, start: Port, width: float, radius: float, moves: list[_DoglegMove]) -> 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)
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,
)
path.append(component)
port = component.end_port
2026-03-29 18:27:03 -07:00
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]]:
2026-03-29 18:27:03 -07:00
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
2026-03-29 18:27:03 -07:00
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
2026-03-29 18:27:03 -07:00
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,
2026-03-29 18:27:03 -07:00
) -> 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
2026-03-29 18:27:03 -07:00
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
for radius in search.bend_radii:
if circular_bend and not bend_fits_width(radius, net_width):
continue
2026-03-29 18:27:03 -07:00
side_extents = self._candidate_side_extents(window_start, window_end, window_path, net_width, radius)
for side_extent in 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:
2026-03-29 18:27:03 -07:00
continue
try:
replacement = self._build_dogleg(window_start, net_width, radius, moves)
except (ComponentPreparationError, OverflowError):
continue
2026-03-31 17:41:15 -07:00
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
2026-03-31 17:41:15 -07:00
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:
2026-03-29 18:27:03 -07:00
continue
self.context.metrics.total_refinement_candidates_accepted += 1
best_candidate_cost = candidate_cost
best_path = candidate_path
2026-03-29 18:27:03 -07:00
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
2026-03-29 18:27:03 -07:00
def refine_path(
self,
net_id: str,
start: Port,
net_width: float,
2026-03-30 23:54:30 -07:00
path: Sequence[ComponentResult],
2026-03-29 18:27:03 -07:00
) -> list[ComponentResult]:
if not self.has_refinement_bends(path):
2026-03-30 23:54:30 -07:00
return list(path)
2026-03-29 18:27:03 -07:00
best_path = list(path)
2026-03-30 19:51:37 -07:00
best_cost = self.score_path(start, path)
remaining = self.context.options.refinement.max_windows_per_net
incumbent_valid = None
2026-03-29 18:27:03 -07:00
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:
2026-03-29 18:27:03 -07:00
break
return best_path