rework structure of everything

This commit is contained in:
Jan Petykiewicz 2026-03-30 15:32:29 -07:00
commit 941d3e01df
12 changed files with 3819 additions and 3559 deletions

View file

@ -3,67 +3,69 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Literal
import numpy
from shapely.geometry import LineString, box
from inire.geometry.collision_query_checker import CollisionQueryChecker
from inire.geometry.dynamic_congestion_checker import DynamicCongestionChecker
from inire.geometry.component_overlap import components_overlap
from inire.geometry.dynamic_path_index import DynamicPathIndex
from inire.geometry.path_verifier import PathVerificationReport, PathVerifier
from inire.geometry.ray_caster import RayCaster
from inire.geometry.index_helpers import grid_cell_span
from inire.geometry.static_obstacle_index import StaticObstacleIndex
from inire.geometry.static_move_checker import StaticMoveChecker
from inire.router.results import RoutingReport
if TYPE_CHECKING:
from collections.abc import Iterable
from collections.abc import 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
class CollisionEngine:
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))
class RoutingWorld:
"""
Manages spatial queries for collision detection with unified dilation logic.
Internal spatial state for collision detection, congestion, and verification.
"""
__slots__ = (
'clearance', 'max_net_width', 'safety_zone_radius',
'metrics', 'grid_cell_size', '_inv_grid_cell_size', '_dynamic_bounds_array',
'_path_verifier', '_dynamic_paths', '_static_obstacles', '_ray_caster', '_static_move_checker',
'_dynamic_congestion_checker', '_collision_query_checker',
"clearance",
"max_net_width",
"safety_zone_radius",
"metrics",
"grid_cell_size",
"_dynamic_paths",
"_static_obstacles",
)
def __init__(
self,
clearance: float,
max_net_width: float = 2.0,
safety_zone_radius: float = 0.0021,
) -> None:
self,
clearance: float,
max_net_width: float = 2.0,
safety_zone_radius: float = 0.0021,
) -> None:
self.clearance = clearance
self.max_net_width = max_net_width
self.safety_zone_radius = safety_zone_radius
self.grid_cell_size = 50.0
self._inv_grid_cell_size = 1.0 / self.grid_cell_size
self._static_obstacles = StaticObstacleIndex(self)
self._dynamic_bounds_array = numpy.array([], dtype=numpy.float64).reshape(0, 4)
self._dynamic_paths = DynamicPathIndex(self)
self.metrics = {
'static_cache_hits': 0,
'static_grid_skips': 0,
'static_tree_queries': 0,
'static_straight_fast': 0,
'congestion_grid_skips': 0,
'congestion_tree_queries': 0,
'safety_zone_checks': 0
"static_cache_hits": 0,
"static_grid_skips": 0,
"static_tree_queries": 0,
"static_straight_fast": 0,
"congestion_grid_skips": 0,
"congestion_tree_queries": 0,
"safety_zone_checks": 0,
}
self._path_verifier = PathVerifier(self)
self._ray_caster = RayCaster(self)
self._static_move_checker = StaticMoveChecker(self)
self._dynamic_congestion_checker = DynamicCongestionChecker(self)
self._collision_query_checker = CollisionQueryChecker(self)
def get_static_version(self) -> int:
return self._static_obstacles.version
@ -89,23 +91,22 @@ class CollisionEngine:
return self._dynamic_paths.geometries.values()
def reset_metrics(self) -> None:
for k in self.metrics:
self.metrics[k] = 0
for key in self.metrics:
self.metrics[key] = 0
def get_metrics_summary(self) -> str:
m = self.metrics
return (f"Collision Performance: \n"
f" Static: {m['static_tree_queries']} checks\n"
f" Congestion: {m['congestion_tree_queries']} checks\n"
f" Safety Zone: {m['safety_zone_checks']} full intersections performed")
metrics = self.metrics
return (
"Collision Performance: \n"
f" Static: {metrics['static_tree_queries']} checks\n"
f" Congestion: {metrics['congestion_tree_queries']} checks\n"
f" Safety Zone: {metrics['safety_zone_checks']} full intersections performed"
)
def add_static_obstacle(self, polygon: Polygon, dilated_geometry: Polygon | None = None) -> int:
return self._static_obstacles.add_obstacle(polygon, dilated_geometry=dilated_geometry)
def remove_static_obstacle(self, obj_id: int) -> None:
"""
Remove a static obstacle by ID.
"""
self._static_obstacles.remove_obstacle(obj_id)
def _invalidate_static_caches(self) -> None:
@ -115,9 +116,6 @@ class CollisionEngine:
self._static_obstacles.ensure_tree()
def _ensure_net_static_tree(self, net_width: float) -> STRtree:
"""
Lazily generate a tree where obstacles are dilated by (net_width/2 + clearance).
"""
return self._static_obstacles.ensure_net_tree(net_width)
def _ensure_static_raw_tree(self) -> None:
@ -125,7 +123,6 @@ class CollisionEngine:
def _ensure_dynamic_tree(self) -> None:
self._dynamic_paths.ensure_tree()
self._dynamic_bounds_array = self._dynamic_paths.bounds_array
def _ensure_dynamic_grid(self) -> None:
self._dynamic_paths.ensure_grid()
@ -134,45 +131,28 @@ class CollisionEngine:
self._dynamic_paths.tree = None
self._ensure_dynamic_tree()
def add_path(self, net_id: str, geometry: list[Polygon], dilated_geometry: list[Polygon] | None = None) -> None:
def add_path(self, net_id: str, geometry: Sequence[Polygon], dilated_geometry: Sequence[Polygon]) -> None:
self._dynamic_paths.add_path(net_id, geometry, dilated_geometry=dilated_geometry)
def remove_path(self, net_id: str) -> None:
self._dynamic_paths.remove_path(net_id)
def lock_net(self, net_id: str) -> None:
""" Convert a routed net into static obstacles. """
self._dynamic_paths.lock_net(net_id)
def unlock_net(self, net_id: str) -> None:
self._dynamic_paths.unlock_net(net_id)
def check_move_straight_static(self, start_port: Port, length: float, net_width: float) -> bool:
return self._static_move_checker.check_move_straight_static(start_port, length, net_width)
self.metrics["static_straight_fast"] += 1
reach = self.ray_cast(start_port, start_port.r, max_dist=length + 0.01, net_width=net_width)
return reach < length - 0.001
def _is_in_safety_zone_fast(self, idx: int, start_port: Port | None, end_port: Port | None) -> bool:
return self._static_move_checker.is_in_safety_zone_fast(idx, start_port, end_port)
def check_move_static(
self,
result: ComponentResult,
start_port: Port | None = None,
end_port: Port | None = None,
net_width: float | None = None,
) -> bool:
return self._static_move_checker.check_move_static(
result,
start_port=start_port,
end_port=end_port,
net_width=net_width,
bounds = self._static_obstacles.bounds_array[idx]
safety_zone = self.safety_zone_radius
if start_port and bounds[0] - safety_zone <= start_port.x <= bounds[2] + safety_zone and bounds[1] - safety_zone <= start_port.y <= bounds[3] + safety_zone:
return True
return bool(
end_port
and bounds[0] - safety_zone <= end_port.x <= bounds[2] + safety_zone
and bounds[1] - safety_zone <= end_port.y <= bounds[3] + safety_zone
)
def check_move_congestion(self, result: ComponentResult, net_id: str) -> int:
return self._dynamic_congestion_checker.check_move_congestion(result, net_id)
def _check_real_congestion(self, result: ComponentResult, net_id: str) -> int:
return self._dynamic_congestion_checker.check_real_congestion(result, net_id)
def _is_in_safety_zone(
self,
geometry: Polygon,
@ -180,7 +160,247 @@ class CollisionEngine:
start_port: Port | None,
end_port: Port | None,
) -> bool:
return self._static_move_checker.is_in_safety_zone(geometry, obj_id, start_port, end_port)
raw_obstacle = self._static_obstacles.geometries[obj_id]
safety_zone = self.safety_zone_radius
obstacle_bounds = raw_obstacle.bounds
near_start = start_port and (
obstacle_bounds[0] - safety_zone <= start_port.x <= obstacle_bounds[2] + safety_zone
and obstacle_bounds[1] - safety_zone <= start_port.y <= obstacle_bounds[3] + safety_zone
)
near_end = end_port and (
obstacle_bounds[0] - safety_zone <= end_port.x <= obstacle_bounds[2] + safety_zone
and obstacle_bounds[1] - safety_zone <= end_port.y <= obstacle_bounds[3] + safety_zone
)
if not near_start and not near_end:
return False
if not geometry.intersects(raw_obstacle):
return False
self.metrics["safety_zone_checks"] += 1
intersection = geometry.intersection(raw_obstacle)
if intersection.is_empty:
return False
ix_bounds = intersection.bounds
if (
start_port
and near_start
and abs(ix_bounds[0] - start_port.x) < safety_zone
and abs(ix_bounds[1] - start_port.y) < safety_zone
and abs(ix_bounds[2] - start_port.x) < safety_zone
and abs(ix_bounds[3] - start_port.y) < safety_zone
):
return True
return bool(
end_port
and near_end
and abs(ix_bounds[0] - end_port.x) < safety_zone
and abs(ix_bounds[1] - end_port.y) < safety_zone
and abs(ix_bounds[2] - end_port.x) < safety_zone
and abs(ix_bounds[3] - end_port.y) < safety_zone
)
def check_move_static(
self,
result: ComponentResult,
start_port: Port | None = None,
end_port: Port | None = None,
net_width: float | None = None,
) -> bool:
del net_width
static_obstacles = self._static_obstacles
if not static_obstacles.dilated:
return False
self.metrics["static_tree_queries"] += 1
self._ensure_static_tree()
hits = static_obstacles.tree.query(box(*result.total_dilated_bounds))
if hits.size == 0:
return False
static_bounds = static_obstacles.bounds_array
move_poly_bounds = result.dilated_bounds
for hit_idx in hits:
obstacle_bounds = static_bounds[hit_idx]
poly_hits_obstacle_aabb = False
for poly_bounds in move_poly_bounds:
if (
poly_bounds[0] < obstacle_bounds[2]
and poly_bounds[2] > obstacle_bounds[0]
and poly_bounds[1] < obstacle_bounds[3]
and poly_bounds[3] > obstacle_bounds[1]
):
poly_hits_obstacle_aabb = True
break
if not poly_hits_obstacle_aabb:
continue
obj_id = static_obstacles.obj_ids[hit_idx]
if self._is_in_safety_zone_fast(hit_idx, start_port, end_port):
collision_found = False
for polygon in result.collision_geometry:
if not self._is_in_safety_zone(polygon, obj_id, start_port, end_port):
collision_found = True
break
if collision_found:
return True
continue
static_obstacle = static_obstacles.dilated[obj_id]
for polygon in result.dilated_collision_geometry:
if polygon.intersects(static_obstacle) and not polygon.touches(static_obstacle):
return True
return False
def _check_real_congestion(self, result: ComponentResult, net_id: str) -> int:
dynamic_paths = self._dynamic_paths
self.metrics["congestion_tree_queries"] += 1
self._ensure_dynamic_tree()
if dynamic_paths.tree is None:
return 0
total_bounds = result.total_dilated_bounds
dynamic_bounds = dynamic_paths.bounds_array
possible_total = (
(total_bounds[0] < dynamic_bounds[:, 2])
& (total_bounds[2] > dynamic_bounds[:, 0])
& (total_bounds[1] < dynamic_bounds[:, 3])
& (total_bounds[3] > dynamic_bounds[:, 1])
)
valid_hits_mask = dynamic_paths.net_ids_array != net_id
if not numpy.any(possible_total & valid_hits_mask):
return 0
geometries_to_test = result.dilated_collision_geometry
res_indices, tree_indices = dynamic_paths.tree.query(geometries_to_test, predicate="intersects")
if tree_indices.size == 0:
return 0
hit_net_ids = numpy.take(dynamic_paths.net_ids_array, tree_indices)
unique_other_nets = numpy.unique(hit_net_ids[hit_net_ids != net_id])
if unique_other_nets.size == 0:
return 0
tree_geometries = dynamic_paths.tree.geometries
real_hits_count = 0
for other_net_id in unique_other_nets:
other_mask = hit_net_ids == other_net_id
sub_tree_indices = tree_indices[other_mask]
sub_res_indices = res_indices[other_mask]
found_real = False
for index in range(len(sub_tree_indices)):
test_geometry = geometries_to_test[sub_res_indices[index]]
tree_geometry = tree_geometries[sub_tree_indices[index]]
if not test_geometry.touches(tree_geometry) and test_geometry.intersection(tree_geometry).area > 1e-7:
found_real = True
break
if found_real:
real_hits_count += 1
return real_hits_count
def check_move_congestion(self, result: ComponentResult, net_id: str) -> int:
dynamic_paths = self._dynamic_paths
if not dynamic_paths.geometries:
return 0
total_bounds = result.total_dilated_bounds
self._ensure_dynamic_grid()
dynamic_grid = dynamic_paths.grid
if not dynamic_grid:
return 0
gx_min, gy_min, gx_max, gy_max = grid_cell_span(total_bounds, self.grid_cell_size)
if gx_min == gx_max and gy_min == gy_max:
cell = (gx_min, gy_min)
if cell in dynamic_grid:
for obj_id in dynamic_grid[cell]:
if dynamic_paths.geometries[obj_id][0] != net_id:
return self._check_real_congestion(result, net_id)
return 0
any_possible = False
for gx in range(gx_min, gx_max + 1):
for gy in range(gy_min, gy_max + 1):
cell = (gx, gy)
if cell in dynamic_grid:
for obj_id in dynamic_grid[cell]:
if dynamic_paths.geometries[obj_id][0] != net_id:
any_possible = True
break
if any_possible:
break
if any_possible:
break
if not any_possible:
return 0
return self._check_real_congestion(result, net_id)
def _check_static_collision(
self,
geometry: Polygon,
start_port: Port | None = None,
end_port: Port | None = None,
dilated_geometry: Polygon | None = None,
) -> bool:
static_obstacles = self._static_obstacles
self._ensure_static_tree()
if static_obstacles.tree is None:
return False
if dilated_geometry is not None:
test_geometry = dilated_geometry
else:
distance = self.clearance / 2.0
test_geometry = geometry.buffer(distance + 1e-7, join_style=2) if distance > 0 else geometry
hits = static_obstacles.tree.query(test_geometry, predicate="intersects")
tree_geometries = static_obstacles.tree.geometries
for hit_idx in hits:
if test_geometry.touches(tree_geometries[hit_idx]):
continue
obj_id = static_obstacles.obj_ids[hit_idx]
if self._is_in_safety_zone(geometry, obj_id, start_port, end_port):
continue
return True
return False
def _check_dynamic_collision(
self,
geometry: Polygon,
net_id: str,
dilated_geometry: Polygon | None = None,
) -> int:
dynamic_paths = self._dynamic_paths
self._ensure_dynamic_tree()
if dynamic_paths.tree is None:
return 0
test_geometry = dilated_geometry if dilated_geometry else geometry.buffer(self.clearance / 2.0)
hits = dynamic_paths.tree.query(test_geometry, predicate="intersects")
tree_geometries = dynamic_paths.tree.geometries
hit_net_ids: list[str] = []
for hit_idx in hits:
if test_geometry.touches(tree_geometries[hit_idx]):
continue
obj_id = dynamic_paths.obj_ids[hit_idx]
other_net_id = dynamic_paths.geometries[obj_id][0]
if other_net_id != net_id:
hit_net_ids.append(other_net_id)
if not hit_net_ids:
return 0
return len(numpy.unique(hit_net_ids))
def check_collision(
self,
@ -193,16 +413,16 @@ class CollisionEngine:
bounds: tuple[float, float, float, float] | None = None,
net_width: float | None = None,
) -> bool | int:
return self._collision_query_checker.check_collision(
geometry,
net_id,
buffer_mode=buffer_mode,
start_port=start_port,
end_port=end_port,
dilated_geometry=dilated_geometry,
bounds=bounds,
net_width=net_width,
)
del bounds, net_width
if buffer_mode == "static":
return self._check_static_collision(
geometry,
start_port=start_port,
end_port=end_port,
dilated_geometry=dilated_geometry,
)
return self._check_dynamic_collision(geometry, net_id, dilated_geometry=dilated_geometry)
def is_collision(
self,
@ -212,7 +432,6 @@ class CollisionEngine:
start_port: Port | None = None,
end_port: Port | None = None,
) -> bool:
""" Unified entry point for static collision checks. """
result = self.check_collision(
geometry,
net_id,
@ -223,12 +442,157 @@ class CollisionEngine:
)
return bool(result)
def verify_path_report(self, net_id: str, components: list[ComponentResult]) -> PathVerificationReport:
return self._path_verifier.verify_path_report(net_id, components)
def verify_path_report(self, net_id: str, components: Sequence[ComponentResult]) -> RoutingReport:
static_collision_count = 0
dynamic_collision_count = 0
self_collision_count = 0
total_length = sum(component.length for component in components)
def verify_path(self, net_id: str, components: list[ComponentResult]) -> tuple[bool, int]:
static_obstacles = self._static_obstacles
dynamic_paths = self._dynamic_paths
self._ensure_static_raw_tree()
if static_obstacles.raw_tree is not None:
raw_geometries = static_obstacles.raw_tree.geometries
for component in components:
for polygon in component.physical_geometry:
buffered = polygon.buffer(self.clearance, join_style=2)
hits = static_obstacles.raw_tree.query(buffered, predicate="intersects")
for hit_idx in hits:
obstacle = raw_geometries[hit_idx]
if buffered.touches(obstacle):
continue
obj_id = static_obstacles.raw_obj_ids[hit_idx]
if not self._is_in_safety_zone(polygon, obj_id, None, None):
static_collision_count += 1
self._ensure_dynamic_tree()
if dynamic_paths.tree is not None:
tree_geometries = dynamic_paths.tree.geometries
for component in components:
test_geometries = component.dilated_physical_geometry
res_indices, tree_indices = dynamic_paths.tree.query(test_geometries, predicate="intersects")
if tree_indices.size == 0:
continue
hit_net_ids = numpy.take(dynamic_paths.net_ids_array, tree_indices)
component_hits = []
for index in range(len(tree_indices)):
if hit_net_ids[index] == str(net_id):
continue
new_geometry = test_geometries[res_indices[index]]
tree_geometry = tree_geometries[tree_indices[index]]
if not new_geometry.touches(tree_geometry) and new_geometry.intersection(tree_geometry).area > 1e-7:
component_hits.append(hit_net_ids[index])
if component_hits:
dynamic_collision_count += len(numpy.unique(component_hits))
for index, component in enumerate(components):
for other_index in range(index + 2, len(components)):
if components_overlap(component, components[other_index], prefer_actual=True):
self_collision_count += 1
return RoutingReport(
static_collision_count=static_collision_count,
dynamic_collision_count=dynamic_collision_count,
self_collision_count=self_collision_count,
total_length=total_length,
)
def verify_path(self, net_id: str, components: Sequence[ComponentResult]) -> tuple[bool, int]:
report = self.verify_path_report(net_id, components)
return report.is_valid, report.collision_count
def ray_cast(self, origin: Port, angle_deg: float, max_dist: float = 2000.0, net_width: float | None = None) -> float:
return self._ray_caster.ray_cast(origin, angle_deg, max_dist=max_dist, net_width=net_width)
def ray_cast(
self,
origin: Port,
angle_deg: float,
max_dist: float = 2000.0,
net_width: float | None = None,
) -> float:
static_obstacles = self._static_obstacles
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 = self._ensure_net_static_tree(net_width)
key = (round(net_width, 4), round(self.clearance, 4))
is_rect_array = static_obstacles.net_specific_is_rect[key]
bounds_array = static_obstacles.net_specific_bounds[key]
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:
return max_dist
candidates = tree.query(box(min_x, min_y, max_x, max_y))
if candidates.size == 0:
return max_dist
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 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

View file

@ -1,97 +0,0 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Literal
import numpy
if TYPE_CHECKING:
from shapely.geometry import Polygon
from inire.geometry.collision import CollisionEngine
from inire.geometry.primitives import Port
class CollisionQueryChecker:
__slots__ = ("engine",)
def __init__(self, engine: CollisionEngine) -> None:
self.engine = engine
def check_collision(
self,
geometry: Polygon,
net_id: str,
buffer_mode: Literal["static", "congestion"] = "static",
start_port: Port | None = None,
end_port: Port | None = None,
dilated_geometry: Polygon | None = None,
bounds: tuple[float, float, float, float] | None = None,
net_width: float | None = None,
) -> bool | int:
del bounds, net_width
if buffer_mode == "static":
return self._check_static_collision(
geometry,
start_port=start_port,
end_port=end_port,
dilated_geometry=dilated_geometry,
)
return self._check_dynamic_collision(geometry, net_id, dilated_geometry=dilated_geometry)
def _check_static_collision(
self,
geometry: Polygon,
start_port: Port | None = None,
end_port: Port | None = None,
dilated_geometry: Polygon | None = None,
) -> bool:
engine = self.engine
static_obstacles = engine._static_obstacles
engine._ensure_static_tree()
if static_obstacles.tree is None:
return False
if dilated_geometry is not None:
test_geometry = dilated_geometry
else:
distance = engine.clearance / 2.0
test_geometry = geometry.buffer(distance + 1e-7, join_style=2) if distance > 0 else geometry
hits = static_obstacles.tree.query(test_geometry, predicate="intersects")
tree_geometries = static_obstacles.tree.geometries
for hit_idx in hits:
if test_geometry.touches(tree_geometries[hit_idx]):
continue
obj_id = static_obstacles.obj_ids[hit_idx]
if engine._is_in_safety_zone(geometry, obj_id, start_port, end_port):
continue
return True
return False
def _check_dynamic_collision(
self,
geometry: Polygon,
net_id: str,
dilated_geometry: Polygon | None = None,
) -> int:
engine = self.engine
dynamic_paths = engine._dynamic_paths
engine._ensure_dynamic_tree()
if dynamic_paths.tree is None:
return 0
test_geometry = dilated_geometry if dilated_geometry else geometry.buffer(engine.clearance / 2.0)
hits = dynamic_paths.tree.query(test_geometry, predicate="intersects")
tree_geometries = dynamic_paths.tree.geometries
hit_net_ids: list[str] = []
for hit_idx in hits:
if test_geometry.touches(tree_geometries[hit_idx]):
continue
obj_id = dynamic_paths.obj_ids[hit_idx]
other_net_id = dynamic_paths.geometries[obj_id][0]
if other_net_id != net_id:
hit_net_ids.append(other_net_id)
if not hit_net_ids:
return 0
return len(numpy.unique(hit_net_ids))

View file

@ -9,9 +9,9 @@ if TYPE_CHECKING:
def component_polygons(component: ComponentResult, prefer_actual: bool = False) -> list[Polygon]:
if prefer_actual and component.actual_geometry is not None:
return component.actual_geometry
return component.geometry
if prefer_actual:
return list(component.physical_geometry)
return list(component.collision_geometry)
def component_bounds(component: ComponentResult, prefer_actual: bool = False) -> tuple[float, float, float, float]:

View file

@ -1,5 +1,6 @@
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Literal
import numpy
@ -12,61 +13,52 @@ from inire.constants import TOLERANCE_ANGULAR
from .primitives import Port, rotation_matrix2
MoveKind = Literal["straight", "bend90", "sbend"]
BendCollisionModelName = Literal["arc", "bbox", "clipped_bbox"]
BendCollisionModel = BendCollisionModelName | Polygon
def _normalize_length(value: float) -> float:
return float(value)
@dataclass(frozen=True, slots=True)
class ComponentResult:
__slots__ = (
"start_port",
"geometry",
"dilated_geometry",
"proxy_geometry",
"actual_geometry",
"dilated_actual_geometry",
"end_port",
"length",
"move_type",
"_bounds",
"_total_bounds",
"_dilated_bounds",
"_total_dilated_bounds",
)
start_port: Port
collision_geometry: tuple[Polygon, ...]
end_port: Port
length: float
move_type: MoveKind
physical_geometry: tuple[Polygon, ...]
dilated_collision_geometry: tuple[Polygon, ...]
dilated_physical_geometry: tuple[Polygon, ...]
_bounds: tuple[tuple[float, float, float, float], ...] = field(init=False, repr=False)
_total_bounds: tuple[float, float, float, float] = field(init=False, repr=False)
_dilated_bounds: tuple[tuple[float, float, float, float], ...] = field(init=False, repr=False)
_total_dilated_bounds: tuple[float, float, float, float] = field(init=False, repr=False)
def __init__(
self,
start_port: Port,
geometry: list[Polygon],
end_port: Port,
length: float,
move_type: str,
dilated_geometry: list[Polygon] | None = None,
proxy_geometry: list[Polygon] | None = None,
actual_geometry: list[Polygon] | None = None,
dilated_actual_geometry: list[Polygon] | None = None,
) -> None:
self.start_port = start_port
self.geometry = geometry
self.dilated_geometry = dilated_geometry
self.proxy_geometry = proxy_geometry
self.actual_geometry = actual_geometry
self.dilated_actual_geometry = dilated_actual_geometry
self.end_port = end_port
self.length = float(length)
self.move_type = move_type
def __post_init__(self) -> None:
collision_geometry = tuple(self.collision_geometry)
physical_geometry = tuple(self.physical_geometry)
dilated_collision_geometry = tuple(self.dilated_collision_geometry)
dilated_physical_geometry = tuple(self.dilated_physical_geometry)
self._bounds = [poly.bounds for poly in self.geometry]
self._total_bounds = _combine_bounds(self._bounds)
object.__setattr__(self, "collision_geometry", collision_geometry)
object.__setattr__(self, "physical_geometry", physical_geometry)
object.__setattr__(self, "dilated_collision_geometry", dilated_collision_geometry)
object.__setattr__(self, "dilated_physical_geometry", dilated_physical_geometry)
object.__setattr__(self, "length", float(self.length))
if self.dilated_geometry is None:
self._dilated_bounds = None
self._total_dilated_bounds = None
else:
self._dilated_bounds = [poly.bounds for poly in self.dilated_geometry]
self._total_dilated_bounds = _combine_bounds(self._dilated_bounds)
bounds = tuple(poly.bounds for poly in collision_geometry)
object.__setattr__(self, "_bounds", bounds)
object.__setattr__(self, "_total_bounds", _combine_bounds(list(bounds)))
dilated_bounds = tuple(poly.bounds for poly in dilated_collision_geometry)
object.__setattr__(self, "_dilated_bounds", dilated_bounds)
object.__setattr__(self, "_total_dilated_bounds", _combine_bounds(list(dilated_bounds)))
@property
def bounds(self) -> list[tuple[float, float, float, float]]:
def bounds(self) -> tuple[tuple[float, float, float, float], ...]:
return self._bounds
@property
@ -74,28 +66,23 @@ class ComponentResult:
return self._total_bounds
@property
def dilated_bounds(self) -> list[tuple[float, float, float, float]] | None:
def dilated_bounds(self) -> tuple[tuple[float, float, float, float], ...]:
return self._dilated_bounds
@property
def total_dilated_bounds(self) -> tuple[float, float, float, float] | None:
def total_dilated_bounds(self) -> tuple[float, float, float, float]:
return self._total_dilated_bounds
def translate(self, dx: int | float, dy: int | float) -> ComponentResult:
return ComponentResult(
start_port=self.start_port + [dx, dy, 0],
geometry=[shapely_translate(poly, dx, dy) for poly in self.geometry],
end_port=self.end_port + [dx, dy, 0],
start_port=self.start_port.translate(dx, dy),
collision_geometry=[shapely_translate(poly, dx, dy) for poly in self.collision_geometry],
end_port=self.end_port.translate(dx, dy),
length=self.length,
move_type=self.move_type,
dilated_geometry=None if self.dilated_geometry is None else [shapely_translate(poly, dx, dy) for poly in self.dilated_geometry],
proxy_geometry=None if self.proxy_geometry is None else [shapely_translate(poly, dx, dy) for poly in self.proxy_geometry],
actual_geometry=None if self.actual_geometry is None else [shapely_translate(poly, dx, dy) for poly in self.actual_geometry],
dilated_actual_geometry=(
None
if self.dilated_actual_geometry is None
else [shapely_translate(poly, dx, dy) for poly in self.dilated_actual_geometry]
),
physical_geometry=[shapely_translate(poly, dx, dy) for poly in self.physical_geometry],
dilated_collision_geometry=[shapely_translate(poly, dx, dy) for poly in self.dilated_collision_geometry],
dilated_physical_geometry=[shapely_translate(poly, dx, dy) for poly in self.dilated_physical_geometry],
)
@ -144,16 +131,13 @@ def _get_arc_polygons(
return [Polygon(numpy.concatenate((inner_points, outer_points), axis=0))]
def _clip_bbox(cxy: tuple[float, float], radius: float, width: float, ts: tuple[float, float], clip_margin: float) -> Polygon:
def _clip_bbox(cxy: tuple[float, float], radius: float, width: float, ts: tuple[float, float]) -> Polygon:
"""Return a conservative 8-point polygonal proxy for the arc.
The polygon uses 4 points along the outer edge and 4 along the inner edge.
The outer edge is a circumscribed polyline and the inner edge is an
inscribed polyline, so the result conservatively contains the true arc.
`clip_margin` is kept for API compatibility but is not used by this proxy.
"""
del clip_margin
cx, cy = cxy
sample_count = 4
angle_span = abs(float(ts[1]) - float(ts[0]))
@ -194,11 +178,10 @@ def _transform_custom_collision_polygon(
def _apply_collision_model(
arc_poly: Polygon,
collision_type: Literal["arc", "bbox", "clipped_bbox"] | Polygon,
collision_type: BendCollisionModel,
radius: float,
width: float,
cxy: tuple[float, float],
clip_margin: float,
ts: tuple[float, float],
rotation_deg: float = 0.0,
mirror_y: bool = False,
@ -208,7 +191,7 @@ def _apply_collision_model(
if collision_type == "arc":
return [arc_poly]
if collision_type == "clipped_bbox":
clipped = _clip_bbox(cxy, radius, width, ts, clip_margin)
clipped = _clip_bbox(cxy, radius, width, ts)
return [clipped if not clipped.is_empty else box(*arc_poly.bounds)]
return [box(*arc_poly.bounds)]
@ -231,7 +214,6 @@ class Straight:
poly_points = (pts @ rot2.T) + numpy.array((start_port.x, start_port.y))
geometry = [Polygon(poly_points)]
dilated_geometry = None
if dilation > 0:
half_w_d = half_w + dilation
pts_d = numpy.array(
@ -244,16 +226,18 @@ class Straight:
)
poly_points_d = (pts_d @ rot2.T) + numpy.array((start_port.x, start_port.y))
dilated_geometry = [Polygon(poly_points_d)]
else:
dilated_geometry = geometry
return ComponentResult(
start_port=start_port,
geometry=geometry,
collision_geometry=geometry,
end_port=end_port,
length=abs(length_f),
move_type="Straight",
dilated_geometry=dilated_geometry,
actual_geometry=geometry,
dilated_actual_geometry=dilated_geometry,
move_type="straight",
physical_geometry=geometry,
dilated_collision_geometry=dilated_geometry,
dilated_physical_geometry=dilated_geometry,
)
@ -265,8 +249,7 @@ class Bend90:
width: float,
direction: Literal["CW", "CCW"],
sagitta: float = 0.01,
collision_type: Literal["arc", "bbox", "clipped_bbox"] | Polygon = "arc",
clip_margin: float = 10.0,
collision_type: BendCollisionModel = "arc",
dilation: float = 0.0,
) -> ComponentResult:
rot2 = rotation_matrix2(start_port.r)
@ -290,32 +273,18 @@ class Bend90:
radius,
width,
(float(center_xy[0]), float(center_xy[1])),
clip_margin,
ts,
rotation_deg=float(start_port.r),
mirror_y=(sign < 0),
)
proxy_geometry = None
if collision_type == "arc":
proxy_geometry = _apply_collision_model(
arc_polys[0],
"clipped_bbox",
radius,
width,
(float(center_xy[0]), float(center_xy[1])),
clip_margin,
ts,
)
dilated_actual_geometry = None
dilated_geometry = None
physical_geometry = collision_polys if uses_custom_geometry else arc_polys
if dilation > 0:
if uses_custom_geometry:
dilated_actual_geometry = [poly.buffer(dilation) for poly in collision_polys]
dilated_geometry = dilated_actual_geometry
dilated_physical_geometry = [poly.buffer(dilation) for poly in collision_polys]
dilated_collision_geometry = dilated_physical_geometry
else:
dilated_actual_geometry = _get_arc_polygons(
dilated_physical_geometry = _get_arc_polygons(
(float(center_xy[0]), float(center_xy[1])),
radius,
width,
@ -323,18 +292,22 @@ class Bend90:
sagitta,
dilation=dilation,
)
dilated_geometry = dilated_actual_geometry if collision_type == "arc" else [poly.buffer(dilation) for poly in collision_polys]
dilated_collision_geometry = (
dilated_physical_geometry if collision_type == "arc" else [poly.buffer(dilation) for poly in collision_polys]
)
else:
dilated_physical_geometry = physical_geometry
dilated_collision_geometry = collision_polys
return ComponentResult(
start_port=start_port,
geometry=collision_polys,
collision_geometry=collision_polys,
end_port=end_port,
length=abs(radius) * numpy.pi / 2.0,
move_type="Bend90",
dilated_geometry=dilated_geometry,
proxy_geometry=proxy_geometry,
actual_geometry=collision_polys if uses_custom_geometry else arc_polys,
dilated_actual_geometry=dilated_actual_geometry,
move_type="bend90",
physical_geometry=physical_geometry,
dilated_collision_geometry=dilated_collision_geometry,
dilated_physical_geometry=dilated_physical_geometry,
)
@ -346,8 +319,7 @@ class SBend:
radius: float,
width: float,
sagitta: float = 0.01,
collision_type: Literal["arc", "bbox", "clipped_bbox"] | Polygon = "arc",
clip_margin: float = 10.0,
collision_type: BendCollisionModel = "arc",
dilation: float = 0.0,
) -> ComponentResult:
if abs(offset) >= 2 * radius:
@ -383,7 +355,6 @@ class SBend:
radius,
width,
(float(c1_xy[0]), float(c1_xy[1])),
clip_margin,
ts1,
rotation_deg=float(start_port.r),
mirror_y=(sign < 0),
@ -394,41 +365,36 @@ class SBend:
radius,
width,
(float(c2_xy[0]), float(c2_xy[1])),
clip_margin,
ts2,
rotation_deg=float(start_port.r),
mirror_y=(sign > 0),
)[0],
]
proxy_geometry = None
if collision_type == "arc":
proxy_geometry = [
_apply_collision_model(arc1, "clipped_bbox", radius, width, (float(c1_xy[0]), float(c1_xy[1])), clip_margin, ts1)[0],
_apply_collision_model(arc2, "clipped_bbox", radius, width, (float(c2_xy[0]), float(c2_xy[1])), clip_margin, ts2)[0],
]
dilated_actual_geometry = None
dilated_geometry = None
physical_geometry = geometry if uses_custom_geometry else actual_geometry
if dilation > 0:
if uses_custom_geometry:
dilated_actual_geometry = [poly.buffer(dilation) for poly in geometry]
dilated_geometry = dilated_actual_geometry
dilated_physical_geometry = [poly.buffer(dilation) for poly in geometry]
dilated_collision_geometry = dilated_physical_geometry
else:
dilated_actual_geometry = [
dilated_physical_geometry = [
_get_arc_polygons((float(c1_xy[0]), float(c1_xy[1])), radius, width, ts1, sagitta, dilation=dilation)[0],
_get_arc_polygons((float(c2_xy[0]), float(c2_xy[1])), radius, width, ts2, sagitta, dilation=dilation)[0],
]
dilated_geometry = dilated_actual_geometry if collision_type == "arc" else [poly.buffer(dilation) for poly in geometry]
dilated_collision_geometry = (
dilated_physical_geometry if collision_type == "arc" else [poly.buffer(dilation) for poly in geometry]
)
else:
dilated_physical_geometry = physical_geometry
dilated_collision_geometry = geometry
return ComponentResult(
start_port=start_port,
geometry=geometry,
collision_geometry=geometry,
end_port=end_port,
length=2.0 * radius * theta,
move_type="SBend",
dilated_geometry=dilated_geometry,
proxy_geometry=proxy_geometry,
actual_geometry=geometry if uses_custom_geometry else actual_geometry,
dilated_actual_geometry=dilated_actual_geometry,
move_type="sbend",
physical_geometry=physical_geometry,
dilated_collision_geometry=dilated_collision_geometry,
dilated_physical_geometry=dilated_physical_geometry,
)

View file

@ -1,117 +0,0 @@
from __future__ import annotations
from typing import TYPE_CHECKING
import numpy
if TYPE_CHECKING:
from inire.geometry.collision import CollisionEngine
from inire.geometry.components import ComponentResult
class DynamicCongestionChecker:
__slots__ = ("engine",)
def __init__(self, engine: CollisionEngine) -> None:
self.engine = engine
def check_move_congestion(self, result: ComponentResult, net_id: str) -> int:
engine = self.engine
dynamic_paths = engine._dynamic_paths
if not dynamic_paths.geometries:
return 0
total_bounds = result.total_dilated_bounds
if total_bounds is None:
return 0
engine._ensure_dynamic_grid()
dynamic_grid = dynamic_paths.grid
if not dynamic_grid:
return 0
cell_size_inv = engine._inv_grid_cell_size
gx_min = int(total_bounds[0] * cell_size_inv)
gy_min = int(total_bounds[1] * cell_size_inv)
gx_max = int(total_bounds[2] * cell_size_inv)
gy_max = int(total_bounds[3] * cell_size_inv)
dynamic_geometries = dynamic_paths.geometries
if gx_min == gx_max and gy_min == gy_max:
cell = (gx_min, gy_min)
if cell in dynamic_grid:
for obj_id in dynamic_grid[cell]:
if dynamic_geometries[obj_id][0] != net_id:
return self.check_real_congestion(result, net_id)
return 0
any_possible = False
for gx in range(gx_min, gx_max + 1):
for gy in range(gy_min, gy_max + 1):
cell = (gx, gy)
if cell in dynamic_grid:
for obj_id in dynamic_grid[cell]:
if dynamic_geometries[obj_id][0] != net_id:
any_possible = True
break
if any_possible:
break
if any_possible:
break
if not any_possible:
return 0
return self.check_real_congestion(result, net_id)
def check_real_congestion(self, result: ComponentResult, net_id: str) -> int:
engine = self.engine
dynamic_paths = engine._dynamic_paths
engine.metrics["congestion_tree_queries"] += 1
engine._ensure_dynamic_tree()
if dynamic_paths.tree is None:
return 0
total_bounds = result.total_dilated_bounds
dynamic_bounds = engine._dynamic_bounds_array
possible_total = (
(total_bounds[0] < dynamic_bounds[:, 2])
& (total_bounds[2] > dynamic_bounds[:, 0])
& (total_bounds[1] < dynamic_bounds[:, 3])
& (total_bounds[3] > dynamic_bounds[:, 1])
)
valid_hits_mask = dynamic_paths.net_ids_array != net_id
if not numpy.any(possible_total & valid_hits_mask):
return 0
geoms_to_test = result.dilated_geometry if result.dilated_geometry else result.geometry
res_indices, tree_indices = dynamic_paths.tree.query(geoms_to_test, predicate="intersects")
if tree_indices.size == 0:
return 0
hit_net_ids = numpy.take(dynamic_paths.net_ids_array, tree_indices)
unique_other_nets = numpy.unique(hit_net_ids[hit_net_ids != net_id])
if unique_other_nets.size == 0:
return 0
tree_geometries = dynamic_paths.tree.geometries
real_hits_count = 0
for other_net_id in unique_other_nets:
other_mask = hit_net_ids == other_net_id
sub_tree_indices = tree_indices[other_mask]
sub_res_indices = res_indices[other_mask]
found_real = False
for index in range(len(sub_tree_indices)):
test_geometry = geoms_to_test[sub_res_indices[index]]
tree_geometry = tree_geometries[sub_tree_indices[index]]
if not test_geometry.touches(tree_geometry) and test_geometry.intersection(tree_geometry).area > 1e-7:
found_real = True
break
if found_real:
real_hits_count += 1
return real_hits_count

View file

@ -6,11 +6,14 @@ import numpy
import rtree
from shapely.strtree import STRtree
if TYPE_CHECKING:
from shapely.geometry import Polygon
from shapely.prepared import PreparedGeometry
from inire.geometry.index_helpers import build_index_payload, iter_grid_cells
from inire.geometry.collision import CollisionEngine
if TYPE_CHECKING:
from collections.abc import Sequence
from shapely.geometry import Polygon
from inire.geometry.collision import RoutingWorld
class DynamicPathIndex:
@ -19,47 +22,38 @@ class DynamicPathIndex:
"index",
"geometries",
"dilated",
"prepared",
"tree",
"obj_ids",
"grid",
"id_counter",
"tree_dirty",
"net_ids_array",
"bounds_array",
"locked_nets",
)
def __init__(self, engine: CollisionEngine) -> None:
def __init__(self, engine: RoutingWorld) -> None:
self.engine = engine
self.index = rtree.index.Index()
self.geometries: dict[int, tuple[str, Polygon]] = {}
self.dilated: dict[int, Polygon] = {}
self.prepared: dict[int, PreparedGeometry] = {}
self.tree: STRtree | None = None
self.obj_ids: numpy.ndarray = numpy.array([], dtype=numpy.int32)
self.grid: dict[tuple[int, int], list[int]] = {}
self.id_counter = 0
self.tree_dirty = True
self.net_ids_array = numpy.array([], dtype="<U32")
self.net_ids_array = numpy.array([], dtype=object)
self.bounds_array = numpy.array([], dtype=numpy.float64).reshape(0, 4)
self.locked_nets: set[str] = set()
def invalidate_queries(self) -> None:
self.tree = None
self.grid = {}
self.tree_dirty = True
def ensure_tree(self) -> None:
if self.tree is None and self.dilated:
ids = sorted(self.dilated.keys())
geometries = [self.dilated[i] for i in ids]
ids, geometries, bounds_array = build_index_payload(self.dilated)
self.tree = STRtree(geometries)
self.obj_ids = numpy.array(ids, dtype=numpy.int32)
self.bounds_array = numpy.array([geometry.bounds for geometry in geometries])
self.bounds_array = bounds_array
net_ids = [self.geometries[obj_id][0] for obj_id in self.obj_ids]
self.net_ids_array = numpy.array(net_ids, dtype="<U32")
self.tree_dirty = False
self.net_ids_array = numpy.array(net_ids, dtype=object)
def ensure_grid(self) -> None:
if self.grid or not self.dilated:
@ -67,27 +61,20 @@ class DynamicPathIndex:
cell_size = self.engine.grid_cell_size
for obj_id, polygon in self.dilated.items():
bounds = polygon.bounds
for gx in range(int(bounds[0] / cell_size), int(bounds[2] / cell_size) + 1):
for gy in range(int(bounds[1] / cell_size), int(bounds[3] / cell_size) + 1):
cell = (gx, gy)
self.grid.setdefault(cell, []).append(obj_id)
for cell in iter_grid_cells(polygon.bounds, cell_size):
self.grid.setdefault(cell, []).append(obj_id)
def add_path(self, net_id: str, geometry: list[Polygon], dilated_geometry: list[Polygon] | None = None) -> None:
def add_path(self, net_id: str, geometry: Sequence[Polygon], dilated_geometry: Sequence[Polygon]) -> None:
self.invalidate_queries()
dilation = self.engine.clearance / 2.0
for index, polygon in enumerate(geometry):
obj_id = self.id_counter
self.id_counter += 1
dilated = dilated_geometry[index] if dilated_geometry else polygon.buffer(dilation)
dilated = dilated_geometry[index]
self.geometries[obj_id] = (net_id, polygon)
self.dilated[obj_id] = dilated
self.index.insert(obj_id, dilated.bounds)
def remove_path(self, net_id: str) -> None:
if net_id in self.locked_nets:
return
to_remove = [obj_id for obj_id, (existing_net_id, _) in self.geometries.items() if existing_net_id == net_id]
self.remove_obj_ids(to_remove)
@ -101,14 +88,7 @@ class DynamicPathIndex:
del self.geometries[obj_id]
del self.dilated[obj_id]
def lock_net(self, net_id: str) -> None:
self.locked_nets.add(net_id)
to_move = [obj_id for obj_id, (existing_net_id, _) in self.geometries.items() if existing_net_id == net_id]
for obj_id in to_move:
polygon = self.geometries[obj_id][1]
dilated = self.dilated[obj_id]
self.engine.add_static_obstacle(polygon, dilated_geometry=dilated)
self.remove_obj_ids(to_move)
def unlock_net(self, net_id: str) -> None:
self.locked_nets.discard(net_id)
def clear_paths(self) -> None:
if not self.geometries:
return
self.remove_obj_ids(list(self.geometries))

View file

@ -0,0 +1,48 @@
from __future__ import annotations
import math
from collections.abc import Iterator, Mapping
from typing import TypeVar
import numpy
GeometryT = TypeVar("GeometryT")
def build_index_payload(
geometries: Mapping[int, GeometryT],
) -> tuple[list[int], list[GeometryT], numpy.ndarray]:
obj_ids = sorted(geometries)
ordered_geometries = [geometries[obj_id] for obj_id in obj_ids]
bounds_array = numpy.array([geometry.bounds for geometry in ordered_geometries], dtype=numpy.float64)
if not ordered_geometries:
bounds_array = bounds_array.reshape(0, 4)
return obj_ids, ordered_geometries, bounds_array
def grid_cell_span(
bounds: tuple[float, float, float, float],
cell_size: float,
) -> tuple[int, int, int, int]:
return (
math.floor(bounds[0] / cell_size),
math.floor(bounds[1] / cell_size),
math.floor(bounds[2] / cell_size),
math.floor(bounds[3] / cell_size),
)
def iter_grid_cells(
bounds: tuple[float, float, float, float],
cell_size: float,
) -> Iterator[tuple[int, int]]:
gx_min, gy_min, gx_max, gy_max = grid_cell_span(bounds, cell_size)
for gx in range(gx_min, gx_max + 1):
for gy in range(gy_min, gy_max + 1):
yield (gx, gy)
def is_axis_aligned_rect(geometry, *, tolerance: float = 1e-4) -> bool:
bounds = geometry.bounds
area = (bounds[2] - bounds[0]) * (bounds[3] - bounds[1])
return abs(geometry.area - area) < tolerance

View file

@ -1,112 +0,0 @@
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
import numpy
from inire.geometry.component_overlap import components_overlap
if TYPE_CHECKING:
from inire.geometry.collision import CollisionEngine
from inire.geometry.components import ComponentResult
@dataclass(frozen=True)
class PathVerificationReport:
static_collision_count: int
dynamic_collision_count: int
self_collision_count: int
total_length: float
@property
def collision_count(self) -> int:
return self.static_collision_count + self.dynamic_collision_count + self.self_collision_count
@property
def is_valid(self) -> bool:
return self.collision_count == 0
class PathVerifier:
__slots__ = ("engine",)
def __init__(self, engine: CollisionEngine) -> None:
self.engine = engine
def verify_path_report(self, net_id: str, components: list[ComponentResult]) -> PathVerificationReport:
"""
Non-approximated, full-polygon intersection check of a path against all
static obstacles, other nets, and itself.
"""
static_collision_count = 0
dynamic_collision_count = 0
self_collision_count = 0
total_length = sum(component.length for component in components)
engine = self.engine
static_obstacles = engine._static_obstacles
dynamic_paths = engine._dynamic_paths
# 1. Check against static obstacles.
engine._ensure_static_raw_tree()
if static_obstacles.raw_tree is not None:
raw_geoms = static_obstacles.raw_tree.geometries
for comp in components:
polygons = comp.actual_geometry if comp.actual_geometry is not None else comp.geometry
for polygon in polygons:
# Physical separation must be >= clearance.
buffered = polygon.buffer(engine.clearance, join_style=2)
hits = static_obstacles.raw_tree.query(buffered, predicate="intersects")
for hit_idx in hits:
obstacle = raw_geoms[hit_idx]
# If they only touch, gap is exactly clearance. Valid.
if buffered.touches(obstacle):
continue
obj_id = static_obstacles.raw_obj_ids[hit_idx]
if not engine._is_in_safety_zone(polygon, obj_id, None, None):
static_collision_count += 1
# 2. Check against other nets.
engine._ensure_dynamic_tree()
if dynamic_paths.tree is not None:
tree_geoms = dynamic_paths.tree.geometries
for comp in components:
# Robust fallback chain to ensure crossings are caught even with zero clearance.
test_geometries = comp.dilated_actual_geometry or comp.dilated_geometry or comp.actual_geometry or comp.geometry
if not test_geometries:
continue
if not isinstance(test_geometries, list | tuple | numpy.ndarray):
test_geometries = [test_geometries]
res_indices, tree_indices = dynamic_paths.tree.query(test_geometries, predicate="intersects")
if tree_indices.size == 0:
continue
hit_net_ids = numpy.take(dynamic_paths.net_ids_array, tree_indices)
comp_hits = []
for i in range(len(tree_indices)):
if hit_net_ids[i] == str(net_id):
continue
p_new = test_geometries[res_indices[i]]
p_tree = tree_geoms[tree_indices[i]]
if not p_new.touches(p_tree) and p_new.intersection(p_tree).area > 1e-7:
comp_hits.append(hit_net_ids[i])
if comp_hits:
dynamic_collision_count += len(numpy.unique(comp_hits))
# 3. Check for self collisions between non-adjacent components.
for i, comp_i in enumerate(components):
for j in range(i + 2, len(components)):
if components_overlap(comp_i, components[j], prefer_actual=True):
self_collision_count += 1
return PathVerificationReport(
static_collision_count=static_collision_count,
dynamic_collision_count=dynamic_collision_count,
self_collision_count=self_collision_count,
total_length=total_length,
)

View file

@ -1,10 +1,10 @@
from __future__ import annotations
from collections.abc import Iterator
from dataclasses import dataclass
from typing import Self
import numpy
from numpy.typing import ArrayLike, NDArray
from numpy.typing import NDArray
def _normalize_angle(angle_deg: int | float) -> int:
@ -13,119 +13,43 @@ def _normalize_angle(angle_deg: int | float) -> int:
raise ValueError(f"Port angle must be Manhattan (multiple of 90), got {angle_deg!r}")
return angle
def _as_int32_triplet(value: ArrayLike) -> NDArray[numpy.int32]:
arr = numpy.asarray(value, dtype=numpy.int32)
if arr.shape != (3,):
raise ValueError(f"Port array must have shape (3,), got {arr.shape}")
arr = arr.copy()
arr[2] = _normalize_angle(int(arr[2]))
return arr
@dataclass(frozen=True, slots=True)
class Port:
"""
Port represented as an ndarray-backed (x, y, r) triple with int32 storage.
Port represented as a normalized integer (x, y, r) triple.
"""
__slots__ = ("_xyr",)
x: int | float
y: int | float
r: int | float
def __init__(self, x: int | float, y: int | float, r: int | float) -> None:
self._xyr = numpy.array(
(int(round(x)), int(round(y)), _normalize_angle(r)),
dtype=numpy.int32,
)
@classmethod
def from_array(cls, xyr: ArrayLike) -> Self:
obj = cls.__new__(cls)
obj._xyr = _as_int32_triplet(xyr)
return obj
@property
def x(self) -> int:
return int(self._xyr[0])
@x.setter
def x(self, val: int | float) -> None:
self._xyr[0] = int(round(val))
@property
def y(self) -> int:
return int(self._xyr[1])
@y.setter
def y(self, val: int | float) -> None:
self._xyr[1] = int(round(val))
@property
def r(self) -> int:
return int(self._xyr[2])
@r.setter
def r(self, val: int | float) -> None:
self._xyr[2] = _normalize_angle(val)
@property
def orientation(self) -> int:
return self.r
@orientation.setter
def orientation(self, val: int | float) -> None:
self.r = val
@property
def xyr(self) -> NDArray[numpy.int32]:
return self._xyr
@xyr.setter
def xyr(self, val: ArrayLike) -> None:
self._xyr = _as_int32_triplet(val)
def __repr__(self) -> str:
return f"Port(x={self.x}, y={self.y}, r={self.r})"
def __iter__(self) -> Iterator[int]:
return iter((self.x, self.y, self.r))
def __len__(self) -> int:
return 3
def __getitem__(self, item: int | slice) -> int | NDArray[numpy.int32]:
return self._xyr[item]
def __array__(self, dtype: numpy.dtype | None = None) -> NDArray[numpy.int32]:
return numpy.asarray(self._xyr, dtype=dtype)
def __eq__(self, other: object) -> bool:
if not isinstance(other, Port):
return False
return bool(numpy.array_equal(self._xyr, other._xyr))
def __hash__(self) -> int:
return hash(self.as_tuple())
def copy(self) -> Self:
return type(self).from_array(self._xyr.copy())
def __post_init__(self) -> None:
object.__setattr__(self, "x", int(round(self.x)))
object.__setattr__(self, "y", int(round(self.y)))
object.__setattr__(self, "r", _normalize_angle(self.r))
def as_tuple(self) -> tuple[int, int, int]:
return (self.x, self.y, self.r)
return (int(self.x), int(self.y), int(self.r))
def translate(self, dxy: ArrayLike) -> Self:
dxy_arr = numpy.asarray(dxy, dtype=numpy.int32)
if dxy_arr.shape == (2,):
return type(self)(self.x + int(dxy_arr[0]), self.y + int(dxy_arr[1]), self.r)
if dxy_arr.shape == (3,):
return type(self)(self.x + int(dxy_arr[0]), self.y + int(dxy_arr[1]), self.r + int(dxy_arr[2]))
raise ValueError(f"Translation must have shape (2,) or (3,), got {dxy_arr.shape}")
def translate(
self,
dx: int | float = 0,
dy: int | float = 0,
rotation: int | float = 0,
) -> Self:
return type(self)(self.x + dx, self.y + dy, self.r + rotation)
def __add__(self, other: ArrayLike) -> Self:
return self.translate(other)
def __sub__(self, other: ArrayLike | Self) -> NDArray[numpy.int32]:
if isinstance(other, Port):
return self._xyr - other._xyr
return self._xyr - numpy.asarray(other, dtype=numpy.int32)
def rotated(
self,
angle: int | float,
origin: tuple[int | float, int | float] = (0, 0),
) -> Self:
angle_i = _normalize_angle(angle)
rot = rotation_matrix2(angle_i)
origin_xy = numpy.array((int(round(origin[0])), int(round(origin[1]))), dtype=numpy.int32)
rel = numpy.array((self.x, self.y), dtype=numpy.int32) - origin_xy
rotated = origin_xy + rot @ rel
return type(self)(int(rotated[0]), int(rotated[1]), self.r + angle_i)
ROT2_0 = numpy.array(((1, 0), (0, 1)), dtype=numpy.int32)
@ -145,16 +69,3 @@ def rotation_matrix3(rotation_deg: int) -> NDArray[numpy.int32]:
rot3[:2, :2] = rot2
rot3[2, 2] = 1
return rot3
def translate_port(port: Port, dx: int | float, dy: int | float) -> Port:
return Port(port.x + dx, port.y + dy, port.r)
def rotate_port(port: Port, angle: int | float, origin: tuple[int | float, int | float] = (0, 0)) -> Port:
angle_i = _normalize_angle(angle)
rot = rotation_matrix2(angle_i)
origin_xy = numpy.array((int(round(origin[0])), int(round(origin[1]))), dtype=numpy.int32)
rel = numpy.array((port.x, port.y), dtype=numpy.int32) - origin_xy
rotated = origin_xy + rot @ rel
return Port(int(rotated[0]), int(rotated[1]), port.r + angle_i)

View file

@ -1,112 +0,0 @@
from __future__ import annotations
from typing import TYPE_CHECKING
import numpy
from shapely.geometry import LineString, box
if TYPE_CHECKING:
from shapely.geometry.base import BaseGeometry
from inire.geometry.collision import CollisionEngine
from inire.geometry.primitives import Port
class RayCaster:
__slots__ = ("engine",)
def __init__(self, engine: CollisionEngine) -> None:
self.engine = engine
def ray_cast(self, origin: Port, angle_deg: float, max_dist: float = 2000.0, net_width: float | None = None) -> float:
engine = self.engine
static_obstacles = engine._static_obstacles
rad = numpy.radians(angle_deg)
cos_v, sin_v = numpy.cos(rad), numpy.sin(rad)
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])
key = None
if net_width is not None:
tree = engine._ensure_net_static_tree(net_width)
key = (round(net_width, 4), round(engine.clearance, 4))
is_rect_arr = static_obstacles.net_specific_is_rect[key]
bounds_arr = static_obstacles.net_specific_bounds[key]
else:
engine._ensure_static_tree()
tree = static_obstacles.tree
is_rect_arr = static_obstacles.is_rect_array
bounds_arr = static_obstacles.bounds_array
if tree is None:
return max_dist
candidates = tree.query(box(min_x, min_y, max_x, max_y))
if candidates.size == 0:
return max_dist
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_geoms = tree.geometries
ray_line = None
# Distance to the AABB min corner is a cheap ordering heuristic.
candidates_bounds = bounds_arr[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_arr[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_arr[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_geoms[candidate_id]
if not obstacle.intersects(ray_line):
continue
intersection = ray_line.intersection(obstacle)
if intersection.is_empty:
continue
distance = self._intersection_distance(origin, intersection)
min_dist = min(min_dist, distance)
return min_dist
def _intersection_distance(self, origin: Port, geometry: BaseGeometry) -> float:
if hasattr(geometry, "geoms"):
return min(self._intersection_distance(origin, sub_geom) for sub_geom in geometry.geoms)
return float(numpy.sqrt((geometry.coords[0][0] - origin.x) ** 2 + (geometry.coords[0][1] - origin.y) ** 2))

View file

@ -1,146 +0,0 @@
from __future__ import annotations
from typing import TYPE_CHECKING
from shapely.geometry import box
if TYPE_CHECKING:
from shapely.geometry import Polygon
from inire.geometry.collision import CollisionEngine
from inire.geometry.components import ComponentResult
from inire.geometry.primitives import Port
class StaticMoveChecker:
__slots__ = ("engine",)
def __init__(self, engine: CollisionEngine) -> None:
self.engine = engine
def check_move_straight_static(self, start_port: Port, length: float, net_width: float) -> bool:
engine = self.engine
engine.metrics["static_straight_fast"] += 1
reach = engine.ray_cast(start_port, start_port.orientation, max_dist=length + 0.01, net_width=net_width)
return reach < length - 0.001
def is_in_safety_zone_fast(self, idx: int, start_port: Port | None, end_port: Port | None) -> bool:
engine = self.engine
sz = engine.safety_zone_radius
bounds = engine._static_obstacles.bounds_array[idx]
if start_port and bounds[0] - sz <= start_port.x <= bounds[2] + sz and bounds[1] - sz <= start_port.y <= bounds[3] + sz:
return True
return bool(
end_port
and bounds[0] - sz <= end_port.x <= bounds[2] + sz
and bounds[1] - sz <= end_port.y <= bounds[3] + sz
)
def check_move_static(
self,
result: ComponentResult,
start_port: Port | None = None,
end_port: Port | None = None,
net_width: float | None = None,
) -> bool:
del net_width
engine = self.engine
static_obstacles = engine._static_obstacles
if not static_obstacles.dilated:
return False
engine.metrics["static_tree_queries"] += 1
engine._ensure_static_tree()
total_bounds = result.total_dilated_bounds if result.total_dilated_bounds else result.total_bounds
hits = static_obstacles.tree.query(box(*total_bounds))
if hits.size == 0:
return False
static_bounds = static_obstacles.bounds_array
move_poly_bounds = result.dilated_bounds if result.dilated_bounds else result.bounds
for hit_idx in hits:
obstacle_bounds = static_bounds[hit_idx]
poly_hits_obstacle_aabb = False
for poly_bounds in move_poly_bounds:
if (
poly_bounds[0] < obstacle_bounds[2]
and poly_bounds[2] > obstacle_bounds[0]
and poly_bounds[1] < obstacle_bounds[3]
and poly_bounds[3] > obstacle_bounds[1]
):
poly_hits_obstacle_aabb = True
break
if not poly_hits_obstacle_aabb:
continue
obj_id = static_obstacles.obj_ids[hit_idx]
if self.is_in_safety_zone_fast(hit_idx, start_port, end_port):
collision_found = False
for polygon in result.geometry:
if not self.is_in_safety_zone(polygon, obj_id, start_port, end_port):
collision_found = True
break
if collision_found:
return True
continue
test_geometries = result.dilated_geometry if result.dilated_geometry else result.geometry
static_obstacle = static_obstacles.dilated[obj_id]
for polygon in test_geometries:
if polygon.intersects(static_obstacle) and not polygon.touches(static_obstacle):
return True
return False
def is_in_safety_zone(
self,
geometry: Polygon,
obj_id: int,
start_port: Port | None,
end_port: Port | None,
) -> bool:
engine = self.engine
raw_obstacle = engine._static_obstacles.geometries[obj_id]
sz = engine.safety_zone_radius
obstacle_bounds = raw_obstacle.bounds
near_start = start_port and (
obstacle_bounds[0] - sz <= start_port.x <= obstacle_bounds[2] + sz
and obstacle_bounds[1] - sz <= start_port.y <= obstacle_bounds[3] + sz
)
near_end = end_port and (
obstacle_bounds[0] - sz <= end_port.x <= obstacle_bounds[2] + sz
and obstacle_bounds[1] - sz <= end_port.y <= obstacle_bounds[3] + sz
)
if not near_start and not near_end:
return False
if not geometry.intersects(raw_obstacle):
return False
engine.metrics["safety_zone_checks"] += 1
intersection = geometry.intersection(raw_obstacle)
if intersection.is_empty:
return False
ix_bounds = intersection.bounds
if (
start_port
and near_start
and abs(ix_bounds[0] - start_port.x) < sz
and abs(ix_bounds[1] - start_port.y) < sz
and abs(ix_bounds[2] - start_port.x) < sz
and abs(ix_bounds[3] - start_port.y) < sz
):
return True
return bool(
end_port
and near_end
and abs(ix_bounds[0] - end_port.x) < sz
and abs(ix_bounds[1] - end_port.y) < sz
and abs(ix_bounds[2] - end_port.x) < sz
and abs(ix_bounds[3] - end_port.y) < sz
)

View file

@ -4,14 +4,14 @@ from typing import TYPE_CHECKING
import numpy
import rtree
from shapely.prepared import prep
from shapely.strtree import STRtree
from inire.geometry.index_helpers import build_index_payload, is_axis_aligned_rect
if TYPE_CHECKING:
from shapely.geometry import Polygon
from shapely.prepared import PreparedGeometry
from inire.geometry.collision import CollisionEngine
from inire.geometry.collision import RoutingWorld
class StaticObstacleIndex:
@ -20,7 +20,6 @@ class StaticObstacleIndex:
"index",
"geometries",
"dilated",
"prepared",
"is_rect",
"tree",
"obj_ids",
@ -31,18 +30,15 @@ class StaticObstacleIndex:
"net_specific_trees",
"net_specific_is_rect",
"net_specific_bounds",
"safe_cache",
"grid",
"id_counter",
"version",
)
def __init__(self, engine: CollisionEngine) -> None:
def __init__(self, engine: RoutingWorld) -> None:
self.engine = engine
self.index = rtree.index.Index()
self.geometries: dict[int, Polygon] = {}
self.dilated: dict[int, Polygon] = {}
self.prepared: dict[int, PreparedGeometry] = {}
self.is_rect: dict[int, bool] = {}
self.tree: STRtree | None = None
self.obj_ids: list[int] = []
@ -53,8 +49,6 @@ class StaticObstacleIndex:
self.net_specific_trees: dict[tuple[float, float], STRtree] = {}
self.net_specific_is_rect: dict[tuple[float, float], numpy.ndarray] = {}
self.net_specific_bounds: dict[tuple[float, float], numpy.ndarray] = {}
self.safe_cache: set[tuple] = set()
self.grid: dict[tuple[int, int], list[int]] = {}
self.id_counter = 0
self.version = 0
@ -69,12 +63,9 @@ class StaticObstacleIndex:
self.geometries[obj_id] = polygon
self.dilated[obj_id] = dilated
self.prepared[obj_id] = prep(dilated)
self.is_rect[obj_id] = is_axis_aligned_rect(dilated)
self.index.insert(obj_id, dilated.bounds)
self.invalidate_caches()
bounds = dilated.bounds
area = (bounds[2] - bounds[0]) * (bounds[3] - bounds[1])
self.is_rect[obj_id] = abs(dilated.area - area) < 1e-4
return obj_id
def remove_obstacle(self, obj_id: int) -> None:
@ -85,7 +76,6 @@ class StaticObstacleIndex:
self.index.delete(obj_id, bounds)
del self.geometries[obj_id]
del self.dilated[obj_id]
del self.prepared[obj_id]
del self.is_rect[obj_id]
self.invalidate_caches()
@ -96,19 +86,15 @@ class StaticObstacleIndex:
self.obj_ids = []
self.raw_tree = None
self.raw_obj_ids = []
self.grid = {}
self.net_specific_trees.clear()
self.net_specific_is_rect.clear()
self.net_specific_bounds.clear()
self.safe_cache.clear()
self.version += 1
def ensure_tree(self) -> None:
if self.tree is None and self.dilated:
self.obj_ids = sorted(self.dilated.keys())
geometries = [self.dilated[i] for i in self.obj_ids]
self.obj_ids, geometries, self.bounds_array = build_index_payload(self.dilated)
self.tree = STRtree(geometries)
self.bounds_array = numpy.array([geometry.bounds for geometry in geometries])
self.is_rect_array = numpy.array([self.is_rect[i] for i in self.obj_ids])
def ensure_net_tree(self, net_width: float) -> STRtree:
@ -125,19 +111,16 @@ class StaticObstacleIndex:
polygon = self.geometries[obj_id]
dilated = polygon.buffer(total_dilation, join_style=2)
geometries.append(dilated)
bounds = dilated.bounds
bounds_list.append(bounds)
area = (bounds[2] - bounds[0]) * (bounds[3] - bounds[1])
is_rect_list.append(abs(dilated.area - area) < 1e-4)
bounds_list.append(dilated.bounds)
is_rect_list.append(is_axis_aligned_rect(dilated))
tree = STRtree(geometries)
self.net_specific_trees[key] = tree
self.net_specific_is_rect[key] = numpy.array(is_rect_list, dtype=bool)
self.net_specific_bounds[key] = numpy.array(bounds_list)
self.net_specific_bounds[key] = numpy.array(bounds_list, dtype=numpy.float64)
return tree
def ensure_raw_tree(self) -> None:
if self.raw_tree is None and self.geometries:
self.raw_obj_ids = sorted(self.geometries.keys())
geometries = [self.geometries[i] for i in self.raw_obj_ids]
self.raw_obj_ids, geometries, _bounds_array = build_index_payload(self.geometries)
self.raw_tree = STRtree(geometries)