trim down

This commit is contained in:
Jan Petykiewicz 2026-03-29 01:26:22 -07:00
commit 4c2d5051cd

View file

@ -3,6 +3,8 @@ from __future__ import annotations
from typing import TYPE_CHECKING
import numpy
import shapely
from scipy.spatial import cKDTree
from functools import lru_cache
if TYPE_CHECKING:
from shapely.geometry import Polygon
@ -10,36 +12,15 @@ if TYPE_CHECKING:
class DangerMap:
"""
A pre-computed grid for heuristic proximity costs, vectorized for performance.
A proximity cost evaluator using a KD-Tree of obstacle boundary points.
Scales with obstacle perimeter rather than design area.
"""
__slots__ = ('minx', 'miny', 'maxx', 'maxy', 'resolution', 'safety_threshold', 'k', 'width_cells', 'height_cells', 'grid')
minx: float
miny: float
maxx: float
maxy: float
""" Boundary coordinates of the map """
resolution: float
""" Grid cell size in micrometers """
safety_threshold: float
""" Distance below which proximity costs are applied """
k: float
""" Cost multiplier constant """
width_cells: int
height_cells: int
""" Grid dimensions in cells """
grid: numpy.ndarray
""" 2D array of pre-computed costs """
__slots__ = ('minx', 'miny', 'maxx', 'maxy', 'resolution', 'safety_threshold', 'k', 'tree')
def __init__(
self,
bounds: tuple[float, float, float, float],
resolution: float = 1.0,
resolution: float = 5.0,
safety_threshold: float = 10.0,
k: float = 1.0,
) -> None:
@ -48,7 +29,7 @@ class DangerMap:
Args:
bounds: (minx, miny, maxx, maxy) in um.
resolution: Cell size (um).
resolution: Sampling resolution for obstacle boundaries (um).
safety_threshold: Proximity limit (um).
k: Penalty multiplier.
"""
@ -56,79 +37,62 @@ class DangerMap:
self.resolution = resolution
self.safety_threshold = safety_threshold
self.k = k
# Grid dimensions
self.width_cells = int(numpy.ceil((self.maxx - self.minx) / self.resolution))
self.height_cells = int(numpy.ceil((self.maxy - self.miny) / self.resolution))
self.grid = numpy.zeros((self.width_cells, self.height_cells), dtype=numpy.float32)
self.tree: cKDTree | None = None
def precompute(self, obstacles: list[Polygon]) -> None:
"""
Pre-compute the proximity costs for the entire grid using vectorized operations.
Args:
obstacles: List of static obstacle geometries.
Pre-compute the proximity tree by sampling obstacle boundaries.
"""
from scipy.ndimage import distance_transform_edt
# 1. Create a binary mask of obstacles
mask = numpy.ones((self.width_cells, self.height_cells), dtype=bool)
# Create coordinate grids
x_coords = numpy.linspace(self.minx + self.resolution/2, self.maxx - self.resolution/2, self.width_cells)
y_coords = numpy.linspace(self.miny + self.resolution/2, self.maxy - self.resolution/2, self.height_cells)
xv, yv = numpy.meshgrid(x_coords, y_coords, indexing='ij')
all_points = []
for poly in obstacles:
# Use shapely.contains_xy for fast vectorized point-in-polygon check
in_poly = shapely.contains_xy(poly, xv, yv)
mask[in_poly] = False
# Sample exterior
exterior = poly.exterior
dist = 0
while dist < exterior.length:
pt = exterior.interpolate(dist)
all_points.append((pt.x, pt.y))
dist += self.resolution
# Sample interiors (holes)
for interior in poly.interiors:
dist = 0
while dist < interior.length:
pt = interior.interpolate(dist)
all_points.append((pt.x, pt.y))
dist += self.resolution
# 2. Distance transform (mask=True for empty space)
distances = distance_transform_edt(mask) * self.resolution
# 3. Proximity cost: k / d^2 if d < threshold, else 0
# Cap distances at a small epsilon (e.g. 0.1um) to avoid division by zero
safe_distances = numpy.maximum(distances, 0.1)
self.grid = numpy.where(
distances < self.safety_threshold,
self.k / (safe_distances**2),
0.0
).astype(numpy.float32)
if all_points:
self.tree = cKDTree(numpy.array(all_points))
else:
self.tree = None
# Clear cache when tree changes
self._get_cost_quantized.cache_clear()
def is_within_bounds(self, x: float, y: float) -> bool:
"""
Check if a coordinate is within the design bounds.
Args:
x, y: Coordinate to check.
Returns:
True if within [min, max] for both axes.
"""
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.
Args:
x, y: Coordinate to look up.
Returns:
Pre-computed cost, or 1e15 if out of bounds.
Get the proximity cost at a specific coordinate using the KD-Tree.
Coordinates are quantized to 1nm to improve cache performance.
"""
# Clamp to grid range to handle upper boundary exactly
ix = int((x - self.minx) / self.resolution)
iy = int((y - self.miny) / self.resolution)
# Handle exact upper boundary
if ix == self.width_cells and abs(x - self.maxx) < 1e-9:
ix = self.width_cells - 1
if iy == self.height_cells and abs(y - self.maxy) < 1e-9:
iy = self.height_cells - 1
qx_milli = int(round(x * 1000))
qy_milli = int(round(y * 1000))
return self._get_cost_quantized(qx_milli, qy_milli)
if 0 <= ix < self.width_cells and 0 <= iy < self.height_cells:
return float(self.grid[ix, iy])
return 1e15 # Outside bounds
@lru_cache(maxsize=100000)
def _get_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
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))