more perf counters

This commit is contained in:
Jan Petykiewicz 2026-03-31 17:41:15 -07:00
commit e77fd6e69f

View file

@ -1,6 +1,7 @@
from __future__ import annotations
from collections import OrderedDict
from time import perf_counter_ns
from typing import TYPE_CHECKING
import numpy
@ -8,6 +9,7 @@ from scipy.spatial import cKDTree
if TYPE_CHECKING:
from shapely.geometry import Polygon
from inire.router._astar_types import AStarMetrics
_COST_CACHE_SIZE = 100000
@ -18,7 +20,7 @@ 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', '_cost_cache')
__slots__ = ('minx', 'miny', 'maxx', 'maxy', 'resolution', 'safety_threshold', 'k', 'tree', '_cost_cache', 'metrics')
def __init__(
self,
@ -42,6 +44,7 @@ class DangerMap:
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: list[Polygon]) -> None:
"""
@ -82,17 +85,28 @@ class DangerMap:
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:
@ -102,6 +116,8 @@ class DangerMap:
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