Local preservation snapshot, not a new deployment or simulation acceptance.
134 lines
5.6 KiB
Python
134 lines
5.6 KiB
Python
"""Bounded causal semantic barriers from observed calibrated range returns.
|
|
|
|
Applied AFTER geometric normalisation, so a smooth lawn cannot turn into a
|
|
permitted park path. Unknown cells retain geometry costs; no hidden scan/map
|
|
semantics are consulted. A reset destroys the entire memory with its ROS node.
|
|
"""
|
|
|
|
from collections import OrderedDict
|
|
import math
|
|
|
|
import numpy as np
|
|
|
|
|
|
class SemanticSurface:
|
|
# Preserve height: a wall/overhang must not relabel the floor beneath it.
|
|
# XY keeps the existing map resolution; Z matches the range voxel scale.
|
|
cell_size = np.array([0.2, 0.2, 0.06])
|
|
|
|
@classmethod
|
|
def cell_keys(cls, points):
|
|
return np.floor(np.asarray(points)[:, :3] / cls.cell_size).astype(int)
|
|
|
|
def __init__(self, *, retain_near=False, fuse_observations=False):
|
|
self.cells = OrderedDict()
|
|
self.retain_near = retain_near
|
|
self.position = None
|
|
self.fuse_observations = fuse_observations
|
|
self.evidence = {}
|
|
|
|
def retained(self, key, stamp, now):
|
|
return stamp >= now - 30 or (
|
|
self.retain_near
|
|
and self.position is not None
|
|
and math.hypot((key[0] + 0.5) * 0.2 - self.position[0],
|
|
(key[1] + 0.5) * 0.2 - self.position[1]) < 4.0
|
|
)
|
|
|
|
def observe(self, samples, now, pose=None, *, evidence_id=None):
|
|
evidence_id = now if evidence_id is None else evidence_id
|
|
if pose is not None:
|
|
position = np.asarray(pose, dtype=float)
|
|
if position.shape != (7,) or not np.isfinite(position).all():
|
|
raise ValueError("Invalid semantic memory pose")
|
|
self.position = position[:2].copy()
|
|
samples = np.asarray(samples, dtype=float)
|
|
if not samples.size:
|
|
return
|
|
if (
|
|
samples.ndim != 2
|
|
or samples.shape[1] != 4
|
|
or len(samples) > 30000
|
|
or not np.isfinite(samples).all()
|
|
or not np.isin(samples[:, 3], [0, 1]).all()
|
|
):
|
|
raise ValueError("Invalid observed semantic surface")
|
|
# Preserve measurement support inside each map cell. One excluded
|
|
# return still blocks a newly observed mixed cell, but is weaker
|
|
# contradictory evidence than an entire excluded surface patch.
|
|
cells = self.cell_keys(samples)
|
|
current = {}
|
|
for cell, permitted in zip(cells, samples[:, 3], strict=True):
|
|
key = tuple(cell)
|
|
count, excluded = current.get(key, (0, 0))
|
|
current[key] = (count + 1, excluded + int(not permitted))
|
|
for key, (count, excluded) in current.items():
|
|
permitted = int(excluded == 0)
|
|
if self.fuse_observations:
|
|
# Bounded binary evidence for the static surface layer. One
|
|
# misclassified pixel cannot erase repeated road observations.
|
|
# Range hazards remain immediate and independent. No calibrated
|
|
# probability is claimed for the model's binary confidence mask.
|
|
vote = -excluded / count if excluded else 1.0
|
|
previous = self.evidence.get(key)
|
|
if previous is None or not self.retained(key, self.cells[key][1], now):
|
|
base = 0
|
|
elif previous[1] == evidence_id:
|
|
base, vote = previous[2], min(previous[3], vote)
|
|
else:
|
|
base = previous[0]
|
|
score = max(-3, min(3, base + vote))
|
|
self.evidence[key] = (score, evidence_id, base, vote)
|
|
# Ties and first observations of exclusions are blocked.
|
|
permitted = int(score > 0)
|
|
self.cells[key] = (permitted, now)
|
|
self.cells.move_to_end(key)
|
|
for key, (_, stamp) in list(self.cells.items()):
|
|
if not self.retained(key, stamp, now):
|
|
del self.cells[key]
|
|
self.evidence.pop(key, None)
|
|
if len(self.cells) > 30000:
|
|
raise RuntimeError("Semantic memory capacity exceeded")
|
|
|
|
def apply(self, terrain, now):
|
|
result = terrain.copy()
|
|
cells = self.cell_keys(terrain)
|
|
# Nearby returns can share a voxel. Resolve its exact
|
|
# permission once, then map it back without changing expiry semantics.
|
|
unique, inverse = np.unique(cells, axis=0, return_inverse=True)
|
|
forbidden = np.array(
|
|
[
|
|
self.cells.get(tuple(c), (1, now))[0] == 0
|
|
and self.retained(tuple(c), self.cells[tuple(c)][1], now)
|
|
for c in unique
|
|
],
|
|
dtype=bool,
|
|
)[inverse]
|
|
result[forbidden, 3] = np.maximum(result[forbidden, 3], 1.0)
|
|
return result, int(forbidden.sum())
|
|
|
|
def permitted_terrain(self, terrain, now):
|
|
"""Positive surface evidence for a body-sized destination.
|
|
|
|
Obstacle absence is insufficient here: unknown and expired cells cannot
|
|
supply arrival support. Geometric obstacle costs remain intact.
|
|
"""
|
|
cells = self.cell_keys(terrain)
|
|
unique, inverse = np.unique(cells, axis=0, return_inverse=True)
|
|
allowed = np.array(
|
|
[
|
|
self.cells.get(tuple(c), (0, now))[0] == 1
|
|
and self.retained(tuple(c), self.cells[tuple(c)][1], now)
|
|
for c in unique
|
|
],
|
|
dtype=bool,
|
|
)[inverse]
|
|
return terrain[allowed]
|
|
|
|
def snapshot(self, now):
|
|
"""JSON-safe diagnostic evidence; does not refresh observation ages."""
|
|
return [
|
|
[int(key[0]), int(key[1]), int(key[2]), int(permitted), float(now - stamp)]
|
|
for key, (permitted, stamp) in self.cells.items()
|
|
]
|