"""Short-term scene memory: per-object Kalman filters in the map frame.
Object positions estimated from single frames are noisy (depth noise grows roughly with range
squared). Each object track is a constant-position Kalman filter. New detections are associated to
tracks with the same label inside a distance gate. The memory lets the robot
answer "where is the cup?" after the cup left the field of view, and gives the language model a list
of recently seen objects.
"""
from __future__ import annotations
import itertools
import threading
import time
from dataclasses import dataclass
import numpy as np
from ..config import TrackingConfig
from .base import label_match
@dataclass
class Track:
track_id: int
label: str
mean: np.ndarray # (3,) map frame
cov: np.ndarray # (3, 3)
score: float
radius_m: float | None
last_seen: float
hits: int = 1
[docs]
class SceneMemory:
def __init__(self, cfg: TrackingConfig, clock=time.monotonic):
self.cfg = cfg
self.clock = clock
self._tracks: list[Track] = []
self._ids = itertools.count(1)
self._lock = threading.Lock()
def measurement_cov(self, range_m: float) -> np.ndarray:
sigma = self.cfg.noise_base_m + self.cfg.noise_per_m2 * range_m**2
return np.eye(3) * sigma**2
def update(
self,
label: str,
position: np.ndarray,
range_m: float,
score: float,
radius_m: float | None = None,
) -> Track:
now = self.clock()
R = self.measurement_cov(range_m)
with self._lock:
self._prune(now)
best, best_d = None, self.cfg.gate_m
for t in self._tracks:
if label_match(label, t.label) < 1.0:
continue
d = float(np.linalg.norm(t.mean[:2] - position[:2]))
if d < best_d:
best, best_d = t, d
if best is None:
best = Track(
next(self._ids),
label,
position.astype(float).copy(),
R.copy(),
score,
radius_m,
now,
)
self._tracks.append(best)
return best
# Predict (constant position, diffusion), then update.
P = best.cov + np.eye(3) * self.cfg.process_noise * (now - best.last_seen)
K = P @ np.linalg.inv(P + R)
best.mean = best.mean + K @ (position - best.mean)
best.cov = (np.eye(3) - K) @ P
best.score = max(score, 0.8 * best.score + 0.2 * score)
if radius_m is not None:
best.radius_m = (
radius_m if best.radius_m is None else 0.7 * best.radius_m + 0.3 * radius_m
)
best.last_seen = now
best.hits += 1
return best
def query(self, label: str | None = None, min_match: float = 0.5) -> list[Track]:
now = self.clock()
with self._lock:
self._prune(now)
tracks = list(self._tracks)
if label is not None:
tracks = [t for t in tracks if label_match(label, t.label) >= min_match]
return sorted(tracks, key=lambda t: (t.last_seen, t.score), reverse=True)
def describe(self, limit: int = 15) -> list[str]:
now = self.clock()
lines = []
for t in self.query()[:limit]:
lines.append(
f"- {t.label} at ({t.mean[0]:.2f}, {t.mean[1]:.2f}), "
f"seen {now - t.last_seen:.0f} s ago"
)
return lines
def _prune(self, now: float) -> None:
self._tracks = [t for t in self._tracks if now - t.last_seen <= self.cfg.ttl_s]