165 lines
5.9 KiB
Python
165 lines
5.9 KiB
Python
from __future__ import annotations
|
|
|
|
from collections import OrderedDict
|
|
from itertools import chain, pairwise
|
|
from math import ceil, floor, hypot
|
|
from time import perf_counter_ns
|
|
from typing import TYPE_CHECKING
|
|
|
|
import numpy
|
|
from scipy.spatial import cKDTree
|
|
from shapely.geometry import box
|
|
|
|
if TYPE_CHECKING:
|
|
from collections.abc import Iterable, Iterator
|
|
|
|
from shapely.geometry import LinearRing, Polygon
|
|
from inire.router._astar_types import AStarMetrics
|
|
|
|
|
|
_COST_CACHE_SIZE = 100000
|
|
|
|
|
|
def _clip_segment(
|
|
start: tuple[float, float],
|
|
end: tuple[float, float],
|
|
bounds: tuple[float, float, float, float],
|
|
) -> tuple[float, float] | None:
|
|
low, high = 0.0, 1.0
|
|
for axis in (0, 1):
|
|
origin = start[axis]
|
|
step = end[axis] - origin
|
|
minimum, maximum = bounds[axis], bounds[axis + 2]
|
|
if not step:
|
|
if not minimum <= origin <= maximum:
|
|
return None
|
|
continue
|
|
enter, leave = sorted(((minimum - origin) / step, (maximum - origin) / step))
|
|
low, high = max(low, enter), min(high, leave)
|
|
return (low, high) if low <= high else None
|
|
|
|
|
|
def _sample_ring(
|
|
ring: LinearRing,
|
|
bounds: tuple[float, float, float, float],
|
|
resolution: float,
|
|
) -> Iterator[tuple[float, float]]:
|
|
distance = 0.0
|
|
next_sample = 0
|
|
last_sample = ceil(ring.length / resolution) - 1
|
|
for start, end in pairwise(ring.coords):
|
|
dx, dy = end[0] - start[0], end[1] - start[1]
|
|
length = hypot(dx, dy)
|
|
clipped = _clip_segment(start, end, bounds)
|
|
if length and clipped is not None:
|
|
low, high = clipped
|
|
first = max(next_sample, ceil((distance + low * length) / resolution))
|
|
last = min(last_sample, floor((distance + high * length) / resolution))
|
|
for index in range(first, last + 1):
|
|
fraction = (index * resolution - distance) / length
|
|
yield (start[0] + fraction * dx, start[1] + fraction * dy)
|
|
if first <= last:
|
|
next_sample = last + 1
|
|
distance += length
|
|
|
|
|
|
class DangerMap:
|
|
"""
|
|
A proximity cost evaluator using a KD-Tree of obstacle boundary points.
|
|
Samples the part of the obstacle perimeter within range of the design.
|
|
"""
|
|
__slots__ = ('minx', 'miny', 'maxx', 'maxy', 'resolution', 'safety_threshold', 'k', 'tree', '_cost_cache', 'metrics')
|
|
|
|
def __init__(
|
|
self,
|
|
bounds: tuple[float, float, float, float],
|
|
resolution: float = 5.0,
|
|
safety_threshold: float = 10.0,
|
|
k: float = 1.0,
|
|
) -> None:
|
|
"""
|
|
Initialize the Danger Map.
|
|
|
|
Args:
|
|
bounds: (minx, miny, maxx, maxy) in um.
|
|
resolution: Sampling resolution for obstacle boundaries (um).
|
|
safety_threshold: Proximity limit (um).
|
|
k: Penalty multiplier.
|
|
"""
|
|
self.minx, self.miny, self.maxx, self.maxy = bounds
|
|
self.resolution = resolution
|
|
self.safety_threshold = safety_threshold
|
|
self.k = k
|
|
self.tree: cKDTree | None = None
|
|
self._cost_cache: OrderedDict[tuple[int, int], float] = OrderedDict()
|
|
self.metrics: AStarMetrics | None = None
|
|
|
|
def precompute(self, obstacles: Iterable[Polygon]) -> None:
|
|
"""
|
|
Pre-compute the proximity tree by sampling obstacle boundaries.
|
|
"""
|
|
reach = self.safety_threshold
|
|
bounds = (self.minx - reach, self.miny - reach, self.maxx + reach, self.maxy + reach)
|
|
window = box(*bounds)
|
|
all_points = []
|
|
for poly in obstacles:
|
|
for ring in chain((poly.exterior,), poly.interiors):
|
|
if window.intersects(ring):
|
|
all_points.extend(_sample_ring(ring, bounds, self.resolution))
|
|
|
|
if all_points:
|
|
self.tree = cKDTree(numpy.array(all_points))
|
|
else:
|
|
self.tree = None
|
|
|
|
self._cost_cache.clear()
|
|
|
|
def is_within_bounds(self, x: float, y: float) -> bool:
|
|
"""
|
|
Check if a coordinate is within the design bounds.
|
|
"""
|
|
return self.minx <= x <= self.maxx and self.miny <= y <= self.maxy
|
|
|
|
def get_cost(self, x: float, y: float) -> float:
|
|
"""
|
|
Get the proximity cost at a specific coordinate using the KD-Tree.
|
|
Coordinates are quantized to 1nm to improve cache performance.
|
|
"""
|
|
metrics = self.metrics
|
|
if metrics is not None:
|
|
metrics.total_danger_map_lookup_calls += 1
|
|
start_ns = perf_counter_ns()
|
|
qx_milli = int(round(x * 1000))
|
|
qy_milli = int(round(y * 1000))
|
|
key = (qx_milli, qy_milli)
|
|
if key in self._cost_cache:
|
|
if metrics is not None:
|
|
metrics.total_danger_map_cache_hits += 1
|
|
metrics.total_danger_map_total_ns += perf_counter_ns() - start_ns
|
|
self._cost_cache.move_to_end(key)
|
|
return self._cost_cache[key]
|
|
|
|
if metrics is not None:
|
|
metrics.total_danger_map_cache_misses += 1
|
|
cost = self._compute_cost_quantized(qx_milli, qy_milli)
|
|
self._cost_cache[key] = cost
|
|
if len(self._cost_cache) > _COST_CACHE_SIZE:
|
|
self._cost_cache.popitem(last=False)
|
|
if metrics is not None:
|
|
metrics.total_danger_map_total_ns += perf_counter_ns() - start_ns
|
|
return cost
|
|
|
|
def _compute_cost_quantized(self, qx_milli: int, qy_milli: int) -> float:
|
|
qx = qx_milli / 1000.0
|
|
qy = qy_milli / 1000.0
|
|
if not self.is_within_bounds(qx, qy):
|
|
return 1e15
|
|
if self.tree is None:
|
|
return 0.0
|
|
if self.metrics is not None:
|
|
self.metrics.total_danger_map_query_calls += 1
|
|
dist, _ = self.tree.query([qx, qy], distance_upper_bound=self.safety_threshold)
|
|
if dist >= self.safety_threshold:
|
|
return 0.0
|
|
safe_dist = max(dist, 0.1)
|
|
return float(self.k / (safe_dist ** 2))
|