inire/inire/router/danger_map.py

201 lines
7.7 KiB
Python

from __future__ import annotations
from collections import OrderedDict
from itertools import chain, islice, pairwise
from math import ceil, floor, hypot, isfinite
from time import perf_counter_ns
from typing import TYPE_CHECKING
import numpy
import shapely
from scipy.spatial import cKDTree
from shapely.geometry import Point, box
from shapely.strtree import STRtree
if TYPE_CHECKING:
from collections.abc import Iterable, Iterator
from shapely.geometry import LinearRing, Polygon
from numpy.typing import NDArray
from inire.router._astar_types import AStarMetrics
_COST_CACHE_SIZE = 100000
_MAX_SAMPLES = 20000
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",
"_boundary_tree", "_cost_distance_range", "_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,
*,
cost_distance_range: float = 10.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._boundary_tree: STRtree | None = None
self._cost_distance_range = cost_distance_range
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)
rings = [
ring for poly in obstacles for ring in chain((poly.exterior,), poly.interiors)
if window.intersects(ring)
]
if any(not isfinite(ring.length / self.resolution) for ring in rings):
self.tree = None
self._boundary_tree = STRtree(rings)
self._cost_cache.clear()
return
points = list(islice(chain.from_iterable(_sample_ring(ring, bounds, self.resolution) for ring in rings), _MAX_SAMPLES + 1))
self.tree = cKDTree(numpy.array(points)) if 0 < len(points) <= _MAX_SAMPLES else None
self._boundary_tree = STRtree(rings) if len(points) > _MAX_SAMPLES else None
self._cost_cache.clear()
@property
def has_data(self) -> bool:
return self.tree is not None or self._boundary_tree is not None
def costs_at_points(self, coordinates: NDArray[numpy.float64]) -> NDArray[numpy.float64]:
distances = numpy.full(len(coordinates), numpy.inf)
if self.tree is not None:
distances, _ = self.tree.query(coordinates, distance_upper_bound=self.safety_threshold)
elif self._boundary_tree is not None:
indices, measured = self._boundary_tree.query_nearest(
shapely.points(coordinates), max_distance=self.safety_threshold, return_distance=True, all_matches=False,
)
distances[indices[0]] = measured
safe = numpy.maximum(0.1, 10 * (distances / self._cost_distance_range))
return numpy.where(distances < self.safety_threshold, self.k / safe ** 2, 0.0)
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 not self.has_data:
return 0.0
if self.metrics is not None:
self.metrics.total_danger_map_query_calls += 1
if self.tree is not None:
dist, _ = self.tree.query([qx, qy], distance_upper_bound=self.safety_threshold)
else:
assert self._boundary_tree is not None
_, distances = self._boundary_tree.query_nearest(
Point(qx, qy), max_distance=self.safety_threshold, return_distance=True, all_matches=False,
)
dist = distances[0] if len(distances) else numpy.inf
if dist >= self.safety_threshold:
return 0.0
safe_dist = max(10 * (dist / self._cost_distance_range), 0.1)
return float(self.k / (safe_dist ** 2))