inire/inire/router/refiner.py

356 lines
15 KiB
Python

from __future__ import annotations
import math
from dataclasses import dataclass
from itertools import accumulate, chain
from typing import TYPE_CHECKING, Any
from inire.geometry.component_overlap import components_overlap
from inire.geometry.components import Bend90, Straight, _advance_port, _bend90_length
from inire.geometry.primitives import port_local_coordinates, rotation_matrix2
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
def component_hits_ancestor_chain(component: ComponentResult, parent_node: Any) -> bool:
current = parent_node
while current and current.parent:
ancestor_component = current.component_result
if ancestor_component and components_overlap(component, ancestor_component):
return True
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)
if local_dx < 4.0 * radius - 0.01:
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.0 * radius + 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)
if local_dx < 4.0 * radius - 0.01 or abs(side_extent) < 0.01:
return None
side_abs = abs(side_extent)
first_straight = side_abs - 2.0 * radius
second_straight = side_abs - 2.0 * radius - math.copysign(float(local_dy), side_extent)
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.0 * radius
if forward_length < -0.01:
return None
if 0.01 < forward_length < min_straight - 0.01:
return None
first_sign = 1 if side_extent > 0 else -1
bend_length = _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),
):
curr = _advance_port(curr, rotation_matrix2(curr.r), radius, sign * radius, sign * 90)
moves.append(_DoglegMove(curr, bend_length, "bend90", "CCW" if sign > 0 else "CW"))
if straight_len > 0.01:
length = float(straight_len)
curr = _advance_port(curr, rotation_matrix2(curr.r), 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]) -> list[ComponentResult]:
dilation = self.collision_engine.clearance / 2.0
path = []
port = start
for move in moves:
if move.direction is None:
component = Straight.generate(port, move.length, width, dilation=dilation)
else:
component = Bend90.generate(port, radius, width, move.direction, dilation=dilation)
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 not self.collision_engine.verify_path_report(net_id, replacement).is_valid:
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_radius = 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.
edge_counts = (2, 1, 0) if limit is not None and limit > 1 else (None,)
for edge_count in edge_counts:
for window_size in range(len(path), 3, -1):
for start_idx in range(len(path) - window_size + 1):
end_idx = start_idx + window_size
if bend_counts[end_idx] - bend_counts[start_idx] < 4:
continue
if edge_count is not None and bends[start_idx] + bends[end_idx - 1] != edge_count:
continue
window_start = ports[start_idx]
window_end = ports[end_idx]
if window_start.r != window_end.r:
continue
local_dx, _ = port_local_coordinates(window_start, window_end.x, window_end.y)
if local_dx >= 4.0 * min_radius - 0.01:
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
for radius in self.context.options.search.bend_radii:
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 or not self.score_path(scoring_start, [*prefix, *moves, *suffix]) + 1e-6 < best_candidate_cost:
continue
replacement = self._build_dogleg(window_start, net_width, radius, moves)
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
def refine_path(
self,
net_id: str,
start: Port,
net_width: float,
path: Sequence[ComponentResult],
) -> list[ComponentResult]:
if not path:
return list(path)
path = list(path)
bend_count = sum(1 for comp in path if comp.move_type == "bend90")
if bend_count < 4:
return path
best_path = 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