inire/inire/geometry/collision.py

509 lines
20 KiB
Python
Raw Normal View History

2026-03-07 08:26:29 -08:00
from __future__ import annotations
2026-03-30 19:51:37 -07:00
from typing import TYPE_CHECKING
2026-03-29 20:35:58 -07:00
import numpy
2026-03-30 15:32:29 -07:00
from shapely.geometry import LineString, box
2026-03-29 20:35:58 -07:00
2026-03-30 15:32:29 -07:00
from inire.geometry.component_overlap import components_overlap
2026-03-29 20:35:58 -07:00
from inire.geometry.dynamic_path_index import DynamicPathIndex
2026-03-30 15:32:29 -07:00
from inire.geometry.index_helpers import grid_cell_span
2026-03-30 19:51:37 -07:00
from inire.results import RoutingReport
2026-03-29 20:35:58 -07:00
from inire.geometry.static_obstacle_index import StaticObstacleIndex
2026-03-07 08:26:29 -08:00
if TYPE_CHECKING:
2026-03-30 15:32:29 -07:00
from collections.abc import Iterable, Sequence
2026-03-29 20:35:58 -07:00
2026-03-09 03:19:01 -07:00
from shapely.geometry import Polygon
2026-03-30 15:32:29 -07:00
from shapely.geometry.base import BaseGeometry
2026-03-29 20:35:58 -07:00
from shapely.strtree import STRtree
from inire.geometry.components import ComponentResult
2026-03-29 20:35:58 -07:00
from inire.geometry.primitives import Port
2026-03-07 08:26:29 -08:00
2026-03-30 15:32:29 -07:00
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:
2026-03-09 03:19:01 -07:00
"""
2026-03-30 15:32:29 -07:00
Internal spatial state for collision detection, congestion, and verification.
2026-03-09 03:19:01 -07:00
"""
2026-03-30 15:32:29 -07:00
2026-03-09 03:19:01 -07:00
__slots__ = (
2026-03-30 15:32:29 -07:00
"clearance",
"safety_zone_radius",
"grid_cell_size",
2026-03-31 17:26:00 -07:00
"metrics",
2026-03-30 15:32:29 -07:00
"_dynamic_paths",
"_static_obstacles",
2026-03-09 03:19:01 -07:00
)
2026-03-07 08:26:29 -08:00
2026-03-09 03:19:01 -07:00
def __init__(
2026-03-30 15:32:29 -07:00
self,
clearance: float,
safety_zone_radius: float = 0.0021,
) -> None:
2026-03-07 08:26:29 -08:00
self.clearance = clearance
2026-03-08 20:18:53 -07:00
self.safety_zone_radius = safety_zone_radius
2026-03-09 03:19:01 -07:00
2026-03-19 15:03:29 -07:00
self.grid_cell_size = 50.0
2026-03-31 17:26:00 -07:00
self.metrics = None
2026-03-29 20:35:58 -07:00
self._static_obstacles = StaticObstacleIndex(self)
self._dynamic_paths = DynamicPathIndex(self)
def get_static_version(self) -> int:
return self._static_obstacles.version
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
2026-03-29 01:26:22 -07:00
def add_static_obstacle(self, polygon: Polygon, dilated_geometry: Polygon | None = None) -> int:
2026-03-29 20:35:58 -07:00
return self._static_obstacles.add_obstacle(polygon, dilated_geometry=dilated_geometry)
2026-03-20 16:59:36 -07:00
def remove_static_obstacle(self, obj_id: int) -> None:
2026-03-29 20:35:58 -07:00
self._static_obstacles.remove_obstacle(obj_id)
2026-03-29 01:26:22 -07:00
def _ensure_static_tree(self) -> None:
2026-03-29 20:35:58 -07:00
self._static_obstacles.ensure_tree()
2026-03-29 01:26:22 -07:00
def _ensure_net_static_tree(self, net_width: float) -> STRtree:
2026-03-29 20:35:58 -07:00
return self._static_obstacles.ensure_net_tree(net_width)
2026-03-29 01:26:22 -07:00
2026-03-19 15:03:29 -07:00
def _ensure_static_raw_tree(self) -> None:
2026-03-29 20:35:58 -07:00
self._static_obstacles.ensure_raw_tree()
def _ensure_dynamic_tree(self) -> None:
2026-03-29 20:35:58 -07:00
self._dynamic_paths.ensure_tree()
def _ensure_dynamic_grid(self) -> None:
2026-03-29 20:35:58 -07:00
self._dynamic_paths.ensure_grid()
2026-03-30 15:32:29 -07:00
def add_path(self, net_id: str, geometry: Sequence[Polygon], dilated_geometry: Sequence[Polygon]) -> None:
2026-03-29 20:35:58 -07:00
self._dynamic_paths.add_path(net_id, geometry, dilated_geometry=dilated_geometry)
2026-03-09 03:19:01 -07:00
2026-03-19 15:03:29 -07:00
def remove_path(self, net_id: str) -> None:
2026-03-29 20:35:58 -07:00
self._dynamic_paths.remove_path(net_id)
2026-03-07 08:26:29 -08:00
2026-03-29 01:26:22 -07:00
def check_move_straight_static(self, start_port: Port, length: float, net_width: float) -> bool:
2026-03-31 17:41:15 -07:00
reach = self.ray_cast(
start_port,
start_port.r,
max_dist=length + 0.01,
net_width=net_width,
caller="straight_static",
)
2026-03-30 15:32:29 -07:00
return reach < length - 0.001
def _is_in_safety_zone_fast(self, idx: int, start_port: Port | None, end_port: Port | None) -> bool:
2026-03-30 23:54:30 -07:00
bounds_array = self._static_obstacles.bounds_array
if bounds_array is None:
return False
bounds = bounds_array[idx]
2026-03-30 15:32:29 -07:00
safety_zone = self.safety_zone_radius
2026-03-30 23:54:30 -07:00
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
):
2026-03-30 15:32:29 -07:00
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
2026-03-29 20:35:58 -07:00
)
2026-03-29 20:35:58 -07:00
def _is_in_safety_zone(
self,
geometry: Polygon,
obj_id: int,
start_port: Port | None,
end_port: Port | None,
) -> bool:
2026-03-30 15:32:29 -07:00
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
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,
) -> bool:
2026-03-30 19:51:37 -07:00
# TODO: If static buffering becomes net-width-specific, add dedicated
# width-aware geometry/index handling instead of reviving dead args here.
2026-03-30 15:32:29 -07:00
static_obstacles = self._static_obstacles
if not static_obstacles.dilated:
return False
self._ensure_static_tree()
2026-03-30 23:54:30 -07:00
tree = static_obstacles.tree
bounds_array = static_obstacles.bounds_array
if tree is None or bounds_array is None:
return False
2026-03-30 15:32:29 -07:00
2026-03-30 23:54:30 -07:00
hits = tree.query(box(*result.total_dilated_bounds))
2026-03-30 15:32:29 -07:00
if hits.size == 0:
return False
move_poly_bounds = result.dilated_bounds
for hit_idx in hits:
2026-03-30 23:54:30 -07:00
obstacle_bounds = bounds_array[hit_idx]
2026-03-30 15:32:29 -07:00
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._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)):
2026-03-31 17:26:00 -07:00
if self.metrics is not None:
self.metrics.total_congestion_exact_pair_checks += 1
2026-03-30 15:32:29 -07:00
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:
2026-03-31 17:26:00 -07:00
if self.metrics is not None:
self.metrics.total_congestion_check_calls += 1
2026-03-30 15:32:29 -07:00
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 verify_path_report(self, net_id: str, components: Sequence[ComponentResult]) -> RoutingReport:
2026-03-31 17:26:00 -07:00
if self.metrics is not None:
self.metrics.total_verify_path_report_calls += 1
2026-03-30 15:32:29 -07:00
static_collision_count = 0
dynamic_collision_count = 0
self_collision_count = 0
total_length = sum(component.length for component in components)
2026-03-29 20:35:58 -07:00
2026-03-30 15:32:29 -07:00
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:
2026-03-31 17:26:00 -07:00
if self.metrics is not None:
self.metrics.total_verify_static_buffer_ops += 1
2026-03-30 23:54:30 -07:00
buffered = polygon.buffer(self.clearance, join_style="mitre")
2026-03-30 15:32:29 -07:00
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
2026-03-31 17:26:00 -07:00
if self.metrics is not None:
self.metrics.total_verify_dynamic_exact_pair_checks += 1
2026-03-30 15:32:29 -07:00
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 ray_cast(
self,
origin: Port,
angle_deg: float,
max_dist: float = 2000.0,
net_width: float | None = None,
2026-03-31 17:41:15 -07:00
caller: str = "other",
2026-03-30 15:32:29 -07:00
) -> float:
2026-03-31 17:26:00 -07:00
if self.metrics is not None:
self.metrics.total_ray_cast_calls += 1
2026-03-31 17:41:15 -07:00
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_build":
self.metrics.total_ray_cast_calls_visibility_build += 1
elif caller == "visibility_query":
self.metrics.total_ray_cast_calls_visibility_query += 1
elif caller == "visibility_tangent":
self.metrics.total_ray_cast_calls_visibility_tangent += 1
else:
self.metrics.total_ray_cast_calls_other += 1
2026-03-30 15:32:29 -07:00
static_obstacles = self._static_obstacles
2026-03-30 23:54:30 -07:00
tree: STRtree | None
is_rect_array: numpy.ndarray | None
bounds_array: numpy.ndarray | None
2026-03-30 15:32:29 -07:00
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
2026-03-30 23:54:30 -07:00
if tree is None or is_rect_array is None or bounds_array is None:
2026-03-30 15:32:29 -07:00
return max_dist
candidates = tree.query(box(min_x, min_y, max_x, max_y))
if candidates.size == 0:
return max_dist
2026-03-31 17:26:00 -07:00
if self.metrics is not None:
self.metrics.total_ray_cast_candidate_bounds += int(candidates.size)
2026-03-30 15:32:29 -07:00
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]
2026-03-31 17:26:00 -07:00
if self.metrics is not None:
self.metrics.total_ray_cast_exact_geometry_checks += 1
2026-03-30 15:32:29 -07:00
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