inire/inire/router/cost.py
Jan Petykiewicz eac083a37d Refine routing geometry checks and streamline documentation
Report coincident terminals and unusable seeds per net, update custom bend handling and verification, and cover the revised behavior with regression tests.

Shorten the user and developer guides around reader tasks and keep the illustrated routing walkthrough and reference links easy to find.
2026-11-29 23:12:28 -08:00

286 lines
11 KiB
Python

from __future__ import annotations
from time import perf_counter_ns
from typing import TYPE_CHECKING
import numpy
from shapely.geometry import Point
from shapely.ops import nearest_points
from inire.constants import TOLERANCE_LINEAR
from inire.geometry.collision import RoutingWorld
from inire.geometry.components import ComponentResult
from inire.geometry.primitives import rotate_cardinal
from inire.model import ObjectiveWeights
from inire.router.danger_map import DangerMap
if TYPE_CHECKING:
from collections.abc import Iterable, Mapping, Sequence
from typing import Protocol
from inire.geometry.components import MoveKind
from inire.geometry.primitives import Port
from inire.model import RoutingProblem
class ScoreableMove(Protocol):
@property
def end_port(self) -> Port: ...
@property
def length(self) -> float: ...
@property
def move_type(self) -> MoveKind: ...
@property
def bend_radius(self) -> float | None: ...
def weighted_path_length(path: Iterable[ScoreableMove], weights: Mapping[MoveKind, float]) -> float:
return sum(component.length * weights[component.move_type] for component in path)
def _boundary_proximity(danger_map: DangerMap, component: ComponentResult, start_port: Port | None) -> float:
def sample(port: Port) -> tuple[float, float]:
if danger_map.is_within_bounds(port.x, port.y):
return port.x, port.y
point = Point(port.x, port.y)
polygon = min(component.physical_geometry, key=point.distance)
nearest, _ = nearest_points(polygon, point)
return nearest.x, nearest.y
end = sample(component.end_port)
points = [end]
if start_port is not None:
start = sample(start_port)
midpoint = ((start[0] + end[0]) / 2, (start[1] + end[1]) / 2)
points.extend((start, midpoint))
# Exact coordinates keep a boundary sample inside even on fractional board bounds.
return float(danger_map.costs_at_points(numpy.asarray(points, dtype=float)).mean())
class CostEvaluator:
__slots__ = (
"collision_engine",
"danger_map",
"_search_weights",
"_greedy_h_weight",
"distance_heuristic_weight",
"_target_x",
"_target_y",
"_target_r",
"_target_cos",
"_target_sin",
)
def __init__(
self,
collision_engine: RoutingWorld,
danger_map: DangerMap | None = None,
unit_length_cost: float = 1.0,
greedy_h_weight: float = 1.5,
bend_penalty: float = 250.0,
sbend_penalty: float | None = None,
danger_weight: float = 1.0,
distance_heuristic_weight: float = 1.0,
) -> None:
actual_sbend_penalty = 2.0 * bend_penalty if sbend_penalty is None else sbend_penalty
self.collision_engine = collision_engine
self.danger_map = danger_map
self._search_weights = ObjectiveWeights(
unit_length_cost=unit_length_cost,
bend_penalty=bend_penalty,
sbend_penalty=actual_sbend_penalty,
danger_weight=danger_weight,
)
self._greedy_h_weight = float(greedy_h_weight)
self.distance_heuristic_weight = distance_heuristic_weight
self._target_x = 0.0
self._target_y = 0.0
self._target_r = 0
self._target_cos = 1.0
self._target_sin = 0.0
@classmethod
def from_objective(
cls,
world: RoutingWorld,
danger_map: DangerMap | None,
objective: ObjectiveWeights,
*,
greedy_h_weight: float = 1.5,
distance_heuristic_weight: float = 1.0,
) -> CostEvaluator:
return cls(
world,
danger_map,
unit_length_cost=objective.unit_length_cost,
greedy_h_weight=greedy_h_weight,
bend_penalty=objective.bend_penalty,
sbend_penalty=objective.sbend_penalty,
danger_weight=objective.danger_weight,
distance_heuristic_weight=distance_heuristic_weight,
)
@property
def default_weights(self) -> ObjectiveWeights:
return self._search_weights
@property
def greedy_h_weight(self) -> float:
return self._greedy_h_weight
@greedy_h_weight.setter
def greedy_h_weight(self, value: float) -> None:
self._greedy_h_weight = float(value)
def _resolve_weights(self, weights: ObjectiveWeights | None) -> ObjectiveWeights:
return self._search_weights if weights is None else weights
def set_target(self, target: Port) -> None:
self._target_x = target.x
self._target_y = target.y
self._target_r = int(target.r)
self._target_cos, self._target_sin = rotate_cardinal(1.0, 0.0, int(target.r))
def h_manhattan(
self,
current: Port,
target: Port,
*,
min_bend_radius: float = 50.0,
) -> float:
tx, ty = target.x, target.y
if abs(tx - self._target_x) > TOLERANCE_LINEAR or abs(ty - self._target_y) > TOLERANCE_LINEAR or target.r != self._target_r:
self.set_target(target)
dx = abs(current.x - tx)
dy = abs(current.y - ty)
dist = dx + dy
bp = self._search_weights.bend_penalty
penalty = 0.0
curr_r = current.r
diff = abs(curr_r - self._target_r) % 360
if diff > 0:
penalty += 2 * bp if diff == 180 else bp
v_dx = tx - current.x
v_dy = ty - current.y
side_proj = v_dx * self._target_cos + v_dy * self._target_sin
perp_dist = abs(v_dx * self._target_sin - v_dy * self._target_cos)
if side_proj < 0 or (side_proj < min_bend_radius and perp_dist > 0):
penalty += 2 * bp
c_cos, c_sin = rotate_cardinal(1.0, 0.0, int(curr_r))
move_proj = v_dx * c_cos + v_dy * c_sin
if move_proj < 0:
penalty += 2 * bp
if diff == 0 and perp_dist > 0:
penalty += 2 * bp
distance_cost = dist * (self._search_weights.unit_length_cost * self.distance_heuristic_weight)
return self._greedy_h_weight * (distance_cost + penalty)
def score_component(
self,
component: ScoreableMove,
*,
start_port: Port | None = None,
weights: ObjectiveWeights | None = None,
) -> float:
metrics = self.collision_engine.metrics
if metrics is not None:
metrics.total_score_component_calls += 1
start_ns = perf_counter_ns()
active_weights = self._resolve_weights(weights)
danger_map = self.danger_map
end_port = component.end_port
custom = (
component if isinstance(component, ComponentResult) and not component.standard_faces and component.physical_geometry else None
)
port_outside = False
if danger_map is not None:
port_outside = not danger_map.is_within_bounds(end_port.x, end_port.y) or (
custom is not None and start_port is not None and not danger_map.is_within_bounds(start_port.x, start_port.y)
)
if port_outside and (custom is None or not danger_map.covers_bounds(custom.total_physical_bounds)):
if metrics is not None:
metrics.total_score_component_total_ns += perf_counter_ns() - start_ns
return 1e15
total_cost = component.length * active_weights.unit_length_cost + self.component_penalty(
component.move_type,
move_radius=component.bend_radius,
weights=active_weights,
)
# Skip danger sampling entirely when there are no static obstacles in the KD-tree.
if danger_map is not None and active_weights.danger_weight and danger_map.has_data:
if port_outside and custom is not None:
total_cost += component.length * active_weights.danger_weight * _boundary_proximity(danger_map, custom, start_port)
elif start_port:
cost_s = danger_map.get_cost(start_port.x, start_port.y)
cost_e = danger_map.get_cost(end_port.x, end_port.y)
mid_x = (start_port.x + end_port.x) / 2.0
mid_y = (start_port.y + end_port.y) / 2.0
cost_m = danger_map.get_cost(mid_x, mid_y)
total_cost += component.length * active_weights.danger_weight * (cost_s + cost_m + cost_e) / 3.0
else:
total_cost += component.length * active_weights.danger_weight * danger_map.get_cost(end_port.x, end_port.y)
if metrics is not None:
metrics.total_score_component_total_ns += perf_counter_ns() - start_ns
return total_cost
def component_penalty(
self,
move_type: MoveKind,
*,
move_radius: float | None = None,
weights: ObjectiveWeights | None = None,
) -> float:
active_weights = self._resolve_weights(weights)
penalty = 0.0
if move_type == "sbend":
penalty = active_weights.sbend_penalty
elif move_type == "bend90":
penalty = active_weights.bend_penalty
if move_radius is not None and move_radius > TOLERANCE_LINEAR and penalty > 0:
penalty *= (10.0 / move_radius) ** 0.5
return penalty
def path_cost(
self,
start_port: Port,
path: Sequence[ScoreableMove],
*,
weights: ObjectiveWeights | None = None,
) -> float:
metrics = self.collision_engine.metrics
if metrics is not None:
metrics.total_path_cost_calls += 1
active_weights = self._resolve_weights(weights)
total = 0.0
current_port = start_port
for component in path:
total += self.score_component(
component,
start_port=current_port,
weights=active_weights,
)
current_port = component.end_port
return total
def proximity_map(problem: RoutingProblem, proximity_range: float) -> DangerMap:
return DangerMap(
bounds=problem.bounds, resolution=proximity_range / 2 or proximity_range, safety_threshold=proximity_range,
cost_distance_range=proximity_range,
)
def build_native_cost_evaluator(problem: RoutingProblem, objective: ObjectiveWeights, *, proximity_range: float = 10.0) -> CostEvaluator:
"""Score candidate paths using the original layout's obstacles and objective."""
danger = None
if objective.danger_weight and problem._blocking_polygons:
danger = proximity_map(problem, proximity_range)
danger.precompute(problem._blocking_polygons)
return CostEvaluator.from_objective(RoutingWorld(clearance=problem.clearance), danger, objective)