inire/inire/geometry/collision.py
Jan Petykiewicz 63acb94642 Fix routing correctness and bound optional routing work
Check physical keepout clearance, retain useful partial paths, and account for all pair repair searches. Verify complete seeds early and recover narrower corridors when shared guides are blocked.

Keep frontier diagnostics outside routing decisions and bound their work by the worker deadline. Correct benchmark scaling and scenario validation, and update the guides and release metadata.
2026-12-02 17:16:34 -08:00

980 lines
42 KiB
Python

from __future__ import annotations
from dataclasses import dataclass, replace
from typing import TYPE_CHECKING
import numpy
from shapely import bounds as geometry_bounds
from shapely import box, distance
from shapely.geometry import LineString
from inire.constants import TOLERANCE_LINEAR
from inire.geometry.component_overlap import count_path_self_collisions
from inire.geometry.components import path_within_board
from inire.geometry.dynamic_path_index import DynamicPathIndex
from inire.geometry.index_helpers import floating_polygon, grid_cell_span
from inire.geometry.primitives import rotate_cardinal
from inire.results import RoutingReport
from inire.geometry.static_obstacle_index import StaticObstacleIndex
if TYPE_CHECKING:
from collections.abc import Callable, Iterable, Sequence
from shapely.geometry import Polygon
from shapely.geometry.base import BaseGeometry
from shapely.strtree import STRtree
from inire.geometry.components import ComponentResult
from inire.geometry.primitives import Port
from inire.model import RoutingProblem
_RAY_CAST_CACHE_LIMIT = 8192
def _intersection_distance(origin: Port, geometry: BaseGeometry) -> float:
if hasattr(geometry, "geoms"):
return min(_intersection_distance(origin, sub_geometry) for sub_geometry in geometry.geoms)
return float(numpy.sqrt((geometry.coords[0][0] - origin.x) ** 2 + (geometry.coords[0][1] - origin.y) ** 2))
def _bounds_overlap(
left: tuple[float, float, float, float],
right: tuple[float, float, float, float],
) -> bool:
return (
left[0] < right[2]
and left[2] > right[0]
and left[1] < right[3]
and left[3] > right[1]
)
def _has_non_touching_overlap(left: BaseGeometry, right: BaseGeometry) -> bool:
return left.intersects(right) and not left.touches(right)
def _clearance_limit(clearance: float) -> float:
return clearance - TOLERANCE_LINEAR * min(1.0, clearance)
def _violates_clearance(left: BaseGeometry, right: BaseGeometry, clearance: float) -> bool:
if clearance <= 0:
return _has_non_touching_overlap(left, right)
return left.distance(right) < _clearance_limit(clearance)
def _violates_net_clearance(left: BaseGeometry, right: BaseGeometry, clearance: float) -> bool:
return _violates_clearance(left, right, clearance) if clearance else left.intersects(right)
def _span_to_bounds(
gx_min: int,
gy_min: int,
gx_max: int,
gy_max: int,
cell_size: float,
) -> tuple[float, float, float, float]:
return (
gx_min * cell_size,
gy_min * cell_size,
(gx_max + 1) * cell_size,
(gy_max + 1) * cell_size,
)
@dataclass(frozen=True, slots=True)
class PathVerificationDetail:
report: RoutingReport
conflicting_net_ids: tuple[str, ...] = ()
component_conflicts: tuple[tuple[int, str, int], ...] = ()
@dataclass(frozen=True, slots=True)
class DynamicCongestionDetail:
soft_overlap_count: int = 0
hits_frozen_net: bool = False
class RoutingWorld:
"""
Internal spatial state for collision detection, congestion, and verification.
"""
__slots__ = (
"clearance",
"self_clearance",
"safety_zone_radius",
"_board",
"_board_bounds",
"grid_cell_size",
"metrics",
"_dynamic_paths",
"_static_obstacles",
)
def __init__(
self,
clearance: float,
safety_zone_radius: float = 0.0021,
*,
board: Polygon | None = None,
self_clearance: float = 0.0,
use_dynamic_grid: bool = True,
) -> None:
self.clearance = clearance
self.self_clearance = self_clearance
self.safety_zone_radius = safety_zone_radius
self._board = floating_polygon(board) if board is not None else None
self._board_bounds: tuple[float, float, float, float] | None = None
self.grid_cell_size = 50.0
self.metrics = None
self._static_obstacles = StaticObstacleIndex(self)
self._dynamic_paths = DynamicPathIndex(self, use_grid=use_dynamic_grid)
@classmethod
def from_problem(cls, problem: RoutingProblem, *, board: Polygon | None = None, use_dynamic_grid: bool = True) -> RoutingWorld:
outline = box(*problem.bounds) if board is None else board
world = cls(
clearance=problem.clearance,
safety_zone_radius=problem.safety_zone_radius,
board=outline,
self_clearance=problem.self_clearance,
use_dynamic_grid=use_dynamic_grid,
)
if board is None:
xmin, ymin, xmax, ymax = outline.bounds
if xmin < xmax and ymin < ymax:
world._board_bounds = (xmin, ymin, xmax, ymax)
for obstacle in problem.static_obstacles:
world.add_static_obstacle(obstacle)
for fixed in problem.fixed_routes:
for polygon in fixed.polygons:
world.add_static_obstacle(polygon, owner=fixed.net_id)
return world
@property
def board(self) -> Polygon | None:
return self._board
def board_covers_component(self, component: ComponentResult) -> bool:
bounds = self._board_bounds
if bounds is not None and component.standard_faces:
# For a rectangular board the physical bounds give exact containment.
left, bottom, right, top = component.total_physical_bounds
return bounds[0] <= left and bounds[1] <= bottom and right <= bounds[2] and top <= bounds[3]
return self._board is None or path_within_board((component,), self._board)
def get_static_version(self) -> int:
return self._static_obstacles.version
def iter_static_geometries(self) -> Iterable[Polygon]:
"""Iterate over the current raw obstacles in insertion order."""
return self._static_obstacles.geometries.values()
def iter_static_dilated_geometries(self) -> Iterable[Polygon]:
return self._static_obstacles.dilated.values()
def iter_static_obstacle_bounds(
self,
query_bounds: tuple[float, float, float, float],
) -> Iterable[tuple[float, float, float, float]]:
for obj_id in self._static_obstacles.index.intersection(query_bounds):
yield self._static_obstacles.geometries[obj_id].bounds
def iter_dynamic_path_bounds(
self,
query_bounds: tuple[float, float, float, float],
) -> Iterable[tuple[float, float, float, float]]:
for obj_id in self._dynamic_paths.index.intersection(query_bounds):
yield self._dynamic_paths.geometries[obj_id][1].bounds
def iter_static_entries(self) -> Iterable[tuple[Polygon, str | None]]:
index = self._static_obstacles
return ((polygon, index.owners.get(key)) for key, polygon in index.geometries.items())
def add_static_obstacle(self, polygon: Polygon, dilated_geometry: Polygon | None = None, *, owner: str | None = None) -> int:
return self._static_obstacles.add_obstacle(polygon, dilated_geometry, owner=owner)
def remove_static_obstacle(self, obj_id: int) -> None:
self._static_obstacles.remove_obstacle(obj_id)
def _ensure_static_tree(self) -> None:
self._static_obstacles.ensure_tree()
def corner_segment_visible(self, start: tuple[float, float], end: tuple[float, float]) -> bool:
"""Allow endpoint contact while testing the open segment against keepouts."""
self._ensure_static_tree()
tree = self._static_obstacles.tree
if tree is None:
return True
segment = LineString((start, end))
return all(segment.relate_pattern(tree.geometries[index], "FF*******") for index in tree.query(segment))
def _ensure_static_raw_tree(self) -> None:
self._static_obstacles.ensure_raw_tree()
def terminal_issue(self, port: Port, width: float) -> str | None:
dx, dy = rotate_cardinal(0, width / 2, int(port.r))
bounds = (port.x - abs(dx), port.y - abs(dy), port.x + abs(dx), port.y + abs(dy))
if self.board is not None:
x0, y0, x1, y1 = self.board.bounds
if bounds[0] < x0 or bounds[1] < y0 or bounds[2] > x1 or bounds[3] > y1:
return "face extends outside the routing board"
self._ensure_static_raw_tree()
tree = self._static_obstacles.raw_tree
if tree is None:
return None
clearance = self.clearance
candidates = tree.query(box(bounds[0] - clearance, bounds[1] - clearance, bounds[2] + clearance, bounds[3] + clearance))
if not len(candidates):
return None
face = LineString(((port.x - dx, port.y - dy), (port.x + dx, port.y + dy)))
for index in candidates:
keepout = tree.geometries[index]
if (clearance or self._static_obstacles.raw_owners[index] is not None) and _violates_net_clearance(face, keepout, clearance):
return "face violates keepout clearance"
if not clearance and not face.relate_pattern(keepout, "F**F*****"):
return "face enters a keepout"
return None
def add_path_geometry(
self,
net_id: str,
geometry: Sequence[Polygon],
dilated_geometry: Sequence[Polygon],
component_indexes: Sequence[int] | None = None,
*,
physical_geometry: Sequence[tuple[int, Polygon]] | None = None,
) -> None:
"""Add prepared path polygons and their component indexes."""
self._dynamic_paths.add_path_geometry(
net_id,
geometry,
dilated_geometry=dilated_geometry,
component_indexes=component_indexes,
physical_geometry=physical_geometry,
)
def add_route(self, net_id: str, path: Sequence[ComponentResult]) -> None:
"""Validate and index the polygons of a route's components."""
if any(not component.physical_geometry_valid for component in path):
return
proxies: list[Polygon] = []
dilated_proxies: list[Polygon] = []
physical_geometry: list[tuple[int, Polygon]] = []
for component_index, component in enumerate(path):
proxies.extend(component.collision_geometry)
dilated_proxies.extend(component.dilated_collision_geometry)
physical_geometry.extend((component_index, polygon) for polygon in component.physical_geometry)
self.add_path_geometry(net_id, proxies, dilated_proxies, physical_geometry=physical_geometry)
def remove_path(self, net_id: str) -> None:
self._dynamic_paths.remove_path(net_id)
def has_dynamic_paths(self) -> bool:
return bool(self._dynamic_paths.geometries)
def _proxy_overlap_near_endpoint(self, proxy: Polygon, obstacle: Polygon, result: ComponentResult) -> bool:
radius = self.safety_zone_radius
if radius <= 0:
return False
x0, y0, x1, y1 = obstacle.bounds
nearby = tuple(
port for port in (result.start_port, result.end_port)
if x0 - radius <= port.x <= x1 + radius and y0 - radius <= port.y <= y1 + radius
)
if not nearby:
return False
overlap = proxy.intersection(obstacle)
if overlap.is_empty:
return False
x0, y0, x1, y1 = overlap.bounds
return any(
port.x - radius < x0 <= x1 < port.x + radius and port.y - radius < y0 <= y1 < port.y + radius
for port in nearby
)
def check_move_static(self, result: ComponentResult) -> bool:
self._ensure_static_raw_tree()
tree = self._static_obstacles.raw_tree
if tree is None:
return False
clearance = self.clearance
left, bottom, right, top = result.total_bounds
if self._static_obstacles.owners or result.check_physical_keepout:
x0, y0, x1, y1 = result.total_physical_bounds
left, bottom, right, top = min(left, x0), min(bottom, y0), max(right, x1), max(top, y1)
# The broad phase must include both the keepout proxy and the physical outline.
hits = tree.query(box(left - clearance, bottom - clearance, right + clearance, top + clearance))
obstacles = tree.geometries
physical = result.physical_geometry
for hit_idx in hits:
obstacle = obstacles[hit_idx]
if self._static_obstacles.raw_owners[hit_idx] is not None:
if any(_violates_net_clearance(polygon, obstacle, clearance) for polygon in physical):
return True
continue
if result.check_physical_keepout and any(_violates_clearance(polygon, obstacle, clearance) for polygon in physical):
return True
for polygon in result.collision_geometry:
if not _violates_clearance(polygon, obstacle, clearance):
continue
if (
any(polygon is shape for shape in physical)
or not self._proxy_overlap_near_endpoint(polygon, obstacle, result)
or any(_violates_clearance(shape, obstacle, clearance) for shape in physical)
):
return True
return False
def _check_real_congestion(
self,
result: ComponentResult,
candidates_by_net: dict[str, dict[int, tuple[int, ...]]],
frozen_net_ids: frozenset[str] = frozenset(),
) -> DynamicCongestionDetail:
if not candidates_by_net:
return DynamicCongestionDetail()
dynamic_paths = self._dynamic_paths
geometries_to_test = result.dilated_collision_geometry
real_hits_count = 0
for other_net_id, other_obj_ids in candidates_by_net.items():
found_real = False
for obj_id, test_geometry_indexes in other_obj_ids.items():
tree_geometry = dynamic_paths.dilated[obj_id]
for test_geometry_index in test_geometry_indexes:
test_geometry = geometries_to_test[test_geometry_index]
if self.metrics is not None:
self.metrics.total_congestion_exact_pair_checks += 1
if _has_non_touching_overlap(test_geometry, tree_geometry):
found_real = True
break
if found_real:
break
if found_real:
if other_net_id in frozen_net_ids:
return DynamicCongestionDetail(
soft_overlap_count=real_hits_count,
hits_frozen_net=True,
)
real_hits_count += 1
return DynamicCongestionDetail(soft_overlap_count=real_hits_count)
def check_physical_move_congestion(
self,
result: ComponentResult,
net_id: str,
*,
frozen_net_ids: frozenset[str] = frozenset(),
) -> DynamicCongestionDetail:
"""Use physical clearance when admitting a move with a hard obstacle."""
metrics = self.metrics
if metrics is not None:
metrics.total_congestion_check_calls += 1
hits = set()
for polygon in result.physical_geometry:
candidates = self._physical_candidates(net_id, polygon)
if metrics is not None and candidates:
metrics.total_congestion_candidate_nets += len({other_net_id for other_net_id, _, _ in candidates})
metrics.total_congestion_candidate_ids += len(candidates)
for other_net_id, _index, other in candidates:
if other_net_id in hits:
continue
if metrics is not None:
metrics.total_congestion_exact_pair_checks += 1
if not _violates_net_clearance(polygon, other, self.clearance):
continue
if other_net_id in frozen_net_ids:
return DynamicCongestionDetail(soft_overlap_count=len(hits), hits_frozen_net=True)
hits.add(other_net_id)
return DynamicCongestionDetail(soft_overlap_count=len(hits))
def _physical_candidates(self, net_id: str, polygon: Polygon) -> list[tuple[str, int, Polygon]]:
minx, miny, maxx, maxy = polygon.bounds
clearance = self.clearance
bounds = (minx - clearance, miny - clearance, maxx + clearance, maxy + clearance)
return self._dynamic_paths.physical_candidates(net_id, bounds)
def _collect_congestion_candidates(
self,
result: ComponentResult,
net_id: str,
net_envelope_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]] | None = None,
grid_net_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]] | None = None,
broad_phase_cache: dict[tuple[str, int, int, int, int], dict[str, tuple[int, ...]]] | None = None,
) -> dict[str, dict[int, tuple[int, ...]]]:
dynamic_paths = self._dynamic_paths
if not dynamic_paths.dilated:
return {}
candidates_by_net: dict[str, dict[int, set[int]]] = {}
for test_geometry_index, test_bounds in enumerate(result.dilated_bounds):
if not self._has_possible_congestion_in_grid(test_bounds, net_id):
continue
envelope_net_ids = self._get_net_envelope_candidates(
test_bounds,
net_id,
net_envelope_cache,
)
if not envelope_net_ids:
continue
grid_net_ids = self._get_grid_span_net_candidates(
test_bounds,
net_id,
grid_net_cache,
)
if not grid_net_ids:
continue
candidate_net_ids = tuple(sorted(set(envelope_net_ids) & set(grid_net_ids)))
if not candidate_net_ids:
continue
grid_candidates = self._get_grid_span_candidates(
test_bounds,
net_id,
broad_phase_cache,
)
for other_net_id in candidate_net_ids:
if self.metrics is not None:
self.metrics.total_congestion_candidate_nets += 1
obj_ids = grid_candidates.get(other_net_id)
if not obj_ids:
continue
for obj_id in obj_ids:
if not _bounds_overlap(test_bounds, dynamic_paths.dilated_bounds[obj_id]):
continue
if self.metrics is not None:
self.metrics.total_congestion_candidate_ids += 1
candidate_indexes = candidates_by_net.setdefault(other_net_id, {}).setdefault(obj_id, set())
candidate_indexes.add(test_geometry_index)
return {
other_net_id: {
obj_id: tuple(sorted(test_geometry_indexes))
for obj_id, test_geometry_indexes in sorted(obj_ids.items())
}
for other_net_id, obj_ids in candidates_by_net.items()
}
def _has_possible_congestion_in_grid(
self,
bounds: tuple[float, float, float, float],
net_id: str,
) -> bool:
span = grid_cell_span(bounds, self.grid_cell_size)
dynamic_paths = self._dynamic_paths
if dynamic_paths.uses_tree_for_span(span):
span_bounds = _span_to_bounds(*span, self.grid_cell_size)
return next(dynamic_paths.tree_candidates(net_id, span_bounds), None) is not None
gx_min, gy_min, gx_max, gy_max = span
cells = dynamic_paths.grid_net_obj_ids
if gx_min == gx_max and gy_min == gy_max:
members = cells.get((gx_min, gy_min))
return bool(members and (len(members) > 1 or net_id not in members))
for gx in range(gx_min, gx_max + 1):
for gy in range(gy_min, gy_max + 1):
members = cells.get((gx, gy))
if members and (len(members) > 1 or net_id not in members):
return True
return False
def has_possible_move_congestion(
self,
result: ComponentResult,
net_id: str,
presence_cache: dict[tuple[str, int, int, int, int], bool] | None = None,
) -> bool:
dynamic_paths = self._dynamic_paths
if not dynamic_paths.dilated:
return False
for bounds in result.dilated_bounds:
gx_min, gy_min, gx_max, gy_max = grid_cell_span(bounds, self.grid_cell_size)
cache_key = (net_id, gx_min, gy_min, gx_max, gy_max)
if presence_cache is not None and cache_key in presence_cache:
if self.metrics is not None:
self.metrics.total_congestion_presence_cache_hits += 1
has_possible = presence_cache[cache_key]
else:
if self.metrics is not None:
self.metrics.total_congestion_presence_cache_misses += 1
has_possible = self._has_possible_congestion_in_grid(bounds, net_id)
if presence_cache is not None:
presence_cache[cache_key] = has_possible
if has_possible:
return True
return False
def has_candidate_move_congestion(
self,
result: ComponentResult,
net_id: str,
candidate_precheck_cache: dict[tuple[str, int, int, int, int], bool] | None = None,
net_envelope_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]] | None = None,
grid_net_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]] | None = None,
) -> bool:
dynamic_paths = self._dynamic_paths
if not dynamic_paths.dilated:
return False
for bounds in result.dilated_bounds:
gx_min, gy_min, gx_max, gy_max = grid_cell_span(bounds, self.grid_cell_size)
cache_key = (net_id, gx_min, gy_min, gx_max, gy_max)
if candidate_precheck_cache is not None and cache_key in candidate_precheck_cache:
if self.metrics is not None:
self.metrics.total_congestion_candidate_precheck_hits += 1
has_candidates = candidate_precheck_cache[cache_key]
else:
if self.metrics is not None:
self.metrics.total_congestion_candidate_precheck_misses += 1
span_bounds = _span_to_bounds(gx_min, gy_min, gx_max, gy_max, self.grid_cell_size)
envelope_net_ids = self._get_net_envelope_candidates(
span_bounds,
net_id,
net_envelope_cache,
)
if not envelope_net_ids:
has_candidates = False
else:
grid_net_ids = self._get_grid_span_net_candidates(
span_bounds,
net_id,
grid_net_cache,
)
if not grid_net_ids:
has_candidates = False
else:
has_candidates = bool(set(envelope_net_ids) & set(grid_net_ids))
if candidate_precheck_cache is not None:
candidate_precheck_cache[cache_key] = has_candidates
if has_candidates:
return True
return False
def _get_grid_span_candidates(
self,
bounds: tuple[float, float, float, float],
net_id: str,
broad_phase_cache: dict[tuple[str, int, int, int, int], dict[str, tuple[int, ...]]] | None,
) -> dict[str, tuple[int, ...]]:
span = grid_cell_span(bounds, self.grid_cell_size)
cache_key = (net_id, *span)
if broad_phase_cache is not None and cache_key in broad_phase_cache:
if self.metrics is not None:
self.metrics.total_congestion_grid_span_cache_hits += 1
return broad_phase_cache[cache_key]
if self.metrics is not None:
self.metrics.total_congestion_grid_span_cache_misses += 1
dynamic_paths = self._dynamic_paths
candidates_by_net: dict[str, set[int]] = {}
if dynamic_paths.uses_tree_for_span(span):
span_bounds = _span_to_bounds(*span, self.grid_cell_size)
for other_net_id, obj_id in dynamic_paths.tree_candidates(net_id, span_bounds):
candidates_by_net.setdefault(other_net_id, set()).add(obj_id)
else:
gx_min, gy_min, gx_max, gy_max = span
for gx in range(gx_min, gx_max + 1):
for gy in range(gy_min, gy_max + 1):
for other_net_id, obj_ids in dynamic_paths.grid_net_obj_ids.get((gx, gy), {}).items():
if other_net_id == net_id:
continue
candidates_by_net.setdefault(other_net_id, set()).update(obj_ids)
frozen = {
other_net_id: tuple(sorted(obj_ids))
for other_net_id, obj_ids in sorted(candidates_by_net.items())
}
if broad_phase_cache is not None:
broad_phase_cache[cache_key] = frozen
return frozen
def _get_grid_span_net_candidates(
self,
bounds: tuple[float, float, float, float],
net_id: str,
grid_net_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]] | None,
) -> tuple[str, ...]:
span = grid_cell_span(bounds, self.grid_cell_size)
cache_key = (net_id, *span)
if grid_net_cache is not None and cache_key in grid_net_cache:
if self.metrics is not None:
self.metrics.total_congestion_grid_net_cache_hits += 1
return grid_net_cache[cache_key]
if self.metrics is not None:
self.metrics.total_congestion_grid_net_cache_misses += 1
dynamic_paths = self._dynamic_paths
if dynamic_paths.uses_tree_for_span(span):
span_bounds = _span_to_bounds(*span, self.grid_cell_size)
candidate_net_ids = {other_net_id for other_net_id, _ in dynamic_paths.tree_candidates(net_id, span_bounds)}
else:
gx_min, gy_min, gx_max, gy_max = span
candidate_net_ids = set()
for gx in range(gx_min, gx_max + 1):
for gy in range(gy_min, gy_max + 1):
for other_net_id in dynamic_paths.grid_net_obj_ids.get((gx, gy), {}):
if other_net_id != net_id:
candidate_net_ids.add(other_net_id)
frozen = tuple(sorted(candidate_net_ids))
if grid_net_cache is not None:
grid_net_cache[cache_key] = frozen
return frozen
def _get_net_envelope_candidates(
self,
bounds: tuple[float, float, float, float],
net_id: str,
net_envelope_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]] | None,
) -> tuple[str, ...]:
dynamic_paths = self._dynamic_paths
gx_min, gy_min, gx_max, gy_max = grid_cell_span(bounds, self.grid_cell_size)
cache_key = (net_id, gx_min, gy_min, gx_max, gy_max)
if net_envelope_cache is not None and cache_key in net_envelope_cache:
if self.metrics is not None:
self.metrics.total_congestion_net_envelope_cache_hits += 1
cached_net_ids = net_envelope_cache[cache_key]
else:
if self.metrics is not None:
self.metrics.total_congestion_net_envelope_cache_misses += 1
span_bounds = _span_to_bounds(gx_min, gy_min, gx_max, gy_max, self.grid_cell_size)
cached_net_ids = tuple(
sorted(
dynamic_paths.net_envelope_obj_to_net[obj_id]
for obj_id in dynamic_paths.net_envelope_index.intersection(span_bounds)
if dynamic_paths.net_envelope_obj_to_net[obj_id] != net_id
)
)
if net_envelope_cache is not None:
net_envelope_cache[cache_key] = cached_net_ids
return tuple(
other_net_id
for other_net_id in cached_net_ids
if _bounds_overlap(bounds, dynamic_paths.net_envelopes[other_net_id])
)
def check_move_congestion(
self,
result: ComponentResult,
net_id: str,
net_envelope_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]] | None = None,
grid_net_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]] | None = None,
broad_phase_cache: dict[tuple[str, int, int, int, int], dict[str, tuple[int, ...]]] | None = None,
) -> int:
return self.check_move_congestion_detail(
result,
net_id,
net_envelope_cache=net_envelope_cache,
grid_net_cache=grid_net_cache,
broad_phase_cache=broad_phase_cache,
).soft_overlap_count
def check_move_congestion_detail(
self,
result: ComponentResult,
net_id: str,
*,
frozen_net_ids: frozenset[str] = frozenset(),
net_envelope_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]] | None = None,
grid_net_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]] | None = None,
broad_phase_cache: dict[tuple[str, int, int, int, int], dict[str, tuple[int, ...]]] | None = None,
) -> DynamicCongestionDetail:
if not self.clearance or frozen_net_ids:
return self.check_physical_move_congestion(result, net_id, frozen_net_ids=frozen_net_ids)
if self.metrics is not None:
self.metrics.total_congestion_check_calls += 1
candidates_by_net = self._collect_congestion_candidates(
result,
net_id,
net_envelope_cache,
grid_net_cache,
broad_phase_cache,
)
return self._check_real_congestion(
result,
candidates_by_net,
frozen_net_ids=frozen_net_ids,
)
def _count_static_path_collisions(self, components: Sequence[ComponentResult]) -> int:
static_obstacles = self._static_obstacles
self._ensure_static_raw_tree()
tree = static_obstacles.raw_tree
if tree is None:
return 0
clearance = self.clearance
polygons = [polygon for component in components for polygon in component.physical_geometry]
if clearance > 0 and 4 <= len(polygons) <= 64:
# Use padded bounds for the broad phase, then measure the physical
# polygons. Keepouts and fixed routes use the same positive clearance.
# Stream longer paths below to bound the number of retained pairs.
shapes = numpy.asarray(polygons, dtype=object)
queries = box(*(geometry_bounds(shapes) + (-clearance, -clearance, clearance, clearance)).T)
left, right = tree.query(queries)
if not len(left):
return 0
return int(numpy.count_nonzero(distance(shapes[left], tree.geometries[right]) < _clearance_limit(clearance)))
count = 0
for polygon in polygons:
query = polygon
if clearance > 0:
x0, y0, x1, y1 = polygon.bounds
query = box(x0 - clearance, y0 - clearance, x1 + clearance, y1 + clearance)
for hit in tree.query(query):
violates = _violates_net_clearance if static_obstacles.raw_owners[hit] is not None else _violates_clearance
count += violates(polygon, tree.geometries[hit], clearance)
return count
def verify_path_geometry(self, components: Sequence[ComponentResult]) -> RoutingReport:
"""Check polygon validity, self-spacing, the board, and static obstacles."""
total_length = sum(component.length for component in components)
if any(not component.physical_geometry_valid for component in components):
return RoutingReport(total_length=total_length, invalid_geometry=True)
return RoutingReport(
static_collision_count=self._count_static_path_collisions(components),
self_collision_count=count_path_self_collisions(components, self.self_clearance),
total_length=total_length,
out_of_bounds=self._board is not None and not all(self.board_covers_component(component) for component in components),
)
def verify_path_details(
self,
net_id: str,
components: Sequence[ComponentResult],
*,
capture_component_conflicts: bool = False,
include_invalid_dynamic: bool = True,
geometry_report: RoutingReport | None = None,
diagnostic_expired: Callable[[], bool] | None = None,
) -> PathVerificationDetail:
"""Check a path, or collect component conflicts from an already verified report for diagnostics."""
if diagnostic_expired is not None and geometry_report is None:
raise ValueError("Diagnostic conflict collection needs a verified path report")
if self.metrics is not None:
self.metrics.total_verify_path_report_calls += 1
report = self.verify_path_geometry(components) if geometry_report is None else geometry_report
dynamic_collision_count = 0
conflicting_net_ids: set[str] = set()
component_conflicts: set[tuple[int, str, int]] = set()
if (
not report.invalid_geometry
and (include_invalid_dynamic or not report.intrinsic_collision_count)
and self._dynamic_paths.has_physical_paths()
):
comparisons = 0
for component_index, component in enumerate(components):
if diagnostic_expired is not None and diagnostic_expired():
return PathVerificationDetail(report=report)
component_hits: set[str] = set()
for polygon in component.physical_geometry:
candidates = self._physical_candidates(net_id, polygon)
if self.metrics is not None:
self.metrics.total_verify_dynamic_candidate_nets += len({candidate[0] for candidate in candidates})
polygon_hits: set[str] = set()
for hit_net_id, hit_component_index, other in candidates:
if hit_net_id in polygon_hits and not capture_component_conflicts:
continue
if diagnostic_expired is not None:
comparisons += 1
if comparisons % 32 == 0 and diagnostic_expired():
return PathVerificationDetail(report=report)
if self.metrics is not None:
self.metrics.total_verify_dynamic_exact_pair_checks += 1
if _violates_net_clearance(polygon, other, self.clearance):
polygon_hits.add(hit_net_id)
if capture_component_conflicts:
component_conflicts.add((component_index, hit_net_id, hit_component_index))
component_hits.update(polygon_hits)
dynamic_collision_count += len(component_hits)
conflicting_net_ids.update(component_hits)
if dynamic_collision_count != report.dynamic_collision_count:
report = replace(report, dynamic_collision_count=dynamic_collision_count)
return PathVerificationDetail(
report=report,
conflicting_net_ids=tuple(sorted(conflicting_net_ids)),
component_conflicts=tuple(sorted(component_conflicts)),
)
def verify_path_report(self, net_id: str, components: Sequence[ComponentResult]) -> RoutingReport:
return self.verify_path_details(net_id, components).report
def ray_cast(
self,
origin: Port,
angle_deg: float,
max_dist: float = 2000.0,
net_width: float | None = None,
caller: str = "other",
) -> float:
if self.metrics is not None:
self.metrics.total_ray_cast_calls += 1
if caller == "straight_static":
self.metrics.total_ray_cast_calls_straight_static += 1
elif caller == "expand_snap":
self.metrics.total_ray_cast_calls_expand_snap += 1
elif caller == "expand_forward":
self.metrics.total_ray_cast_calls_expand_forward += 1
elif caller == "visibility_tangent":
self.metrics.total_ray_cast_calls_visibility_tangent += 1
else:
self.metrics.total_ray_cast_calls_other += 1
# Static obstacle changes clear these results along with the trees.
cache = self._static_obstacles.ray_cast_cache
# Equal NumPy and Python scalars can produce different ray geometry.
key = (
origin.x, origin.y, angle_deg, max_dist, net_width, self.clearance,
type(angle_deg), type(max_dist), type(net_width), type(self.clearance),
)
reach = cache.get(key)
if reach is not None:
return reach
reach = self._cast_static_ray(origin, angle_deg, max_dist, net_width)
if len(cache) >= _RAY_CAST_CACHE_LIMIT:
cache.clear()
cache[key] = reach
return reach
def straight_reach(self, origin: Port, max_dist: float, net_width: float) -> float:
"""Find where a fixed-width, flat-ended trace first enters a keepout."""
self._ensure_static_raw_tree()
tree = self._static_obstacles.raw_tree
if tree is None:
return max_dist
dx, dy = rotate_cardinal(max_dist, 0, int(origin.r))
half_x, half_y = (0.0, net_width / 2) if dx else (net_width / 2, 0.0)
left, right = sorted((origin.x, origin.x + dx))
bottom, top = sorted((origin.y, origin.y + dy))
left, bottom, right, top = left - half_x, bottom - half_y, right + half_x, top + half_y
strip = box(left, bottom, right, top)
clearance = self.clearance
padding = clearance - TOLERANCE_LINEAR * min(1.0, clearance)
candidates = tree.query(box(left - padding, bottom - padding, right + padding, top + padding))
axis = 0 if dx else 1
start = origin.x if dx else origin.y
direction = 1 if (dx or dy) > 0 else -1
face = axis if direction > 0 else axis + 2
reach = max_dist
obstacles = tree.geometries
for index in candidates:
obstacle = obstacles[index]
keepout = obstacle.buffer(padding) if padding > 0 else obstacle
overlap = keepout.intersection(strip)
if overlap.area:
reach = min(reach, direction * (overlap.bounds[face] - start))
return reach
def _cast_static_ray(
self,
origin: Port,
angle_deg: float,
max_dist: float,
net_width: float | None,
) -> float:
static_obstacles = self._static_obstacles
tree: STRtree | None
is_rect_array: numpy.ndarray | None
bounds_array: numpy.ndarray | None
radians = numpy.radians(angle_deg)
cos_v, sin_v = numpy.cos(radians), numpy.sin(radians)
dx, dy = max_dist * cos_v, max_dist * sin_v
min_x, max_x = sorted([origin.x, origin.x + dx])
min_y, max_y = sorted([origin.y, origin.y + dy])
if net_width is not None:
tree, is_rect_array, bounds_array = static_obstacles.ensure_net_tree(net_width)
else:
self._ensure_static_tree()
tree = static_obstacles.tree
is_rect_array = static_obstacles.is_rect_array
bounds_array = static_obstacles.bounds_array
if tree is None or is_rect_array is None or bounds_array is None:
return max_dist
candidates = tree.query(box(min_x, min_y, max_x, max_y))
if candidates.size == 0:
return max_dist
if self.metrics is not None:
self.metrics.total_ray_cast_candidate_bounds += int(candidates.size)
min_dist = max_dist
inv_dx = 1.0 / dx if abs(dx) > 1e-12 else 1e30
inv_dy = 1.0 / dy if abs(dy) > 1e-12 else 1e30
tree_geometries = tree.geometries
ray_line = None
candidates_bounds = bounds_array[candidates]
dist_sq = (candidates_bounds[:, 0] - origin.x) ** 2 + (candidates_bounds[:, 1] - origin.y) ** 2
sorted_indices = numpy.argsort(dist_sq)
for idx in sorted_indices:
candidate_id = candidates[idx]
bounds = bounds_array[candidate_id]
if abs(dx) < 1e-12:
if origin.x < bounds[0] or origin.x > bounds[2]:
tx_min, tx_max = 1e30, -1e30
else:
tx_min, tx_max = -1e30, 1e30
else:
t1, t2 = (bounds[0] - origin.x) * inv_dx, (bounds[2] - origin.x) * inv_dx
tx_min, tx_max = min(t1, t2), max(t1, t2)
if abs(dy) < 1e-12:
if origin.y < bounds[1] or origin.y > bounds[3]:
ty_min, ty_max = 1e30, -1e30
else:
ty_min, ty_max = -1e30, 1e30
else:
t1, t2 = (bounds[1] - origin.y) * inv_dy, (bounds[3] - origin.y) * inv_dy
ty_min, ty_max = min(t1, t2), max(t1, t2)
t_min, t_max = max(tx_min, ty_min), min(tx_max, ty_max)
if t_max < 0 or t_min > t_max or t_min > 1.0:
continue
if t_min * max_dist >= min_dist:
continue
if is_rect_array[candidate_id]:
min_dist = max(0.0, t_min * max_dist)
continue
if ray_line is None:
ray_line = LineString([(origin.x, origin.y), (origin.x + dx, origin.y + dy)])
obstacle = tree_geometries[candidate_id]
if self.metrics is not None:
self.metrics.total_ray_cast_exact_geometry_checks += 1
if not obstacle.intersects(ray_line):
continue
intersection = ray_line.intersection(obstacle)
if intersection.is_empty:
continue
distance = _intersection_distance(origin, intersection)
min_dist = min(min_dist, distance)
return min_dist