rework structure of everything

This commit is contained in:
Jan Petykiewicz 2026-03-30 15:32:29 -07:00
commit 941d3e01df

View file

@ -1,21 +1,24 @@
from __future__ import annotations
from collections import OrderedDict
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
_COST_CACHE_SIZE = 100000
class DangerMap:
"""
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', 'tree')
__slots__ = ('minx', 'miny', 'maxx', 'maxy', 'resolution', 'safety_threshold', 'k', 'tree', '_cost_cache')
def __init__(
self,
@ -38,6 +41,7 @@ class DangerMap:
self.safety_threshold = safety_threshold
self.k = k
self.tree: cKDTree | None = None
self._cost_cache: OrderedDict[tuple[int, int], float] = OrderedDict()
def precompute(self, obstacles: list[Polygon]) -> None:
"""
@ -64,9 +68,8 @@ class DangerMap:
self.tree = cKDTree(numpy.array(all_points))
else:
self.tree = None
# Clear cache when tree changes
self._get_cost_quantized.cache_clear()
self._cost_cache.clear()
def is_within_bounds(self, x: float, y: float) -> bool:
"""
@ -81,10 +84,18 @@ class DangerMap:
"""
qx_milli = int(round(x * 1000))
qy_milli = int(round(y * 1000))
return self._get_cost_quantized(qx_milli, qy_milli)
key = (qx_milli, qy_milli)
if key in self._cost_cache:
self._cost_cache.move_to_end(key)
return self._cost_cache[key]
@lru_cache(maxsize=100000)
def _get_cost_quantized(self, qx_milli: int, qy_milli: int) -> float:
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)
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):