Files
NODEDC_MISSION_CORE/src/k1link/missions/reference_window.py
T
DCCONSTRUCTIONS e515ab1b8c feat(planning): consolidate recorded-route localization and spatial scene
Preserve the completed teach-and-repeat laboratory stage: reference preparation, cascaded acquisition, local tracking and recovery, recording lifecycle, replay qualification, and persistent Rerun scene controls. Document the open grid-picking regression and Rerun upgrade contract. No autonomous driving or loop-closure optimization is claimed.
2026-09-21 08:47:19 +03:00

104 lines
4.3 KiB
Python

"""Bound a numerical target without thinning the route-wide reference map."""
import hashlib
from itertools import product
import numpy as np
from .registration import transform
WINDOW_POLICY = dict(version="local-reference-window/v2", maximum_points=None, margin_m=10.0)
class ReferenceCoverageError(ValueError):
"""No usable local target; this is not a terminal recording failure."""
class ReferenceWindowIndex:
"""One run-owned spatial index; exact source order and density are retained.
The reference is immutable for the lifetime of a planning run. Only source
indices are stored, not another point-cloud copy or a reduced map. This
index must never be reused with a replacement reference array.
"""
def __init__(self, reference, *, cell_m=10.0):
if not np.isfinite(cell_m) or cell_m <= 0:
raise ValueError("Invalid reference index cell size.")
if reference.ndim != 2 or reference.shape[1] != 3 or not np.isfinite(reference).all():
raise ValueError("Invalid reference index geometry.")
self.reference = reference
self.cell_m = cell_m
cells = np.floor(reference / cell_m).astype(np.int64)
keys, inverse, counts = np.unique(cells, axis=0, return_inverse=True, return_counts=True)
self.order = np.argsort(inverse, kind="stable")
boundaries = np.r_[0, np.cumsum(counts)]
self.slices = {
tuple(key): (int(boundaries[i]), int(boundaries[i + 1])) for i, key in enumerate(keys)
}
def crop(self, center, radius):
if not np.isfinite(center).all() or not np.isfinite(radius) or radius <= 0:
raise ValueError("Invalid reference window.")
lower = np.floor((center - radius) / self.cell_m).astype(np.int64)
upper = np.floor((center + radius) / self.cell_m).astype(np.int64)
pieces = []
ranges = tuple(range(int(a), int(b) + 1) for a, b in zip(lower, upper, strict=True))
# Very broad diagnostic crops should not enumerate empty space.
keys = (
product(*ranges)
if np.prod([len(r) for r in ranges]) <= len(self.slices)
else (
key
for key in self.slices
if all(a <= v <= b for v, a, b in zip(key, lower, upper, strict=True))
)
)
for key in keys:
bounds = self.slices.get(key)
if bounds is not None:
pieces.append(self.order[slice(*bounds)])
indices = (
np.sort(np.concatenate(pieces), kind="stable")
if pieces
else np.empty(0, dtype=np.int64)
)
candidates = self.reference[indices]
mask = np.linalg.norm(candidates - center, axis=1) <= radius
selected = candidates[mask]
if len(selected) == len(self.reference):
selected = self.reference
return selected, len(candidates)
def reference_window(reference, sample, hint, *, initializing=False, index=None):
anchor = sample["path"][0 if initializing else -1]
center = transform(np.asarray(anchor)[None, :], hint)[0]
# The local observation footprint bounds work spatially, not by treating
# an arbitrary point count as evidence that localisation was lost.
radius = (
float(np.linalg.norm(sample["points"] - anchor, axis=1).max()) + WINDOW_POLICY["margin_m"]
)
if index is None:
mask = np.linalg.norm(reference - center, axis=1) <= radius
points = reference if mask.all() else reference[mask]
examined = len(reference)
else:
if index.reference is not reference:
raise ValueError("Reference index belongs to another map.")
points, examined = index.crop(center, radius)
if len(points) < 300:
raise ReferenceCoverageError(
"Недостаточное покрытие локальной области эталона для проверки привязки."
)
return points, dict(
policy=WINDOW_POLICY,
map_points=len(reference),
target_points=len(points),
center=center.tolist() if center is not None else None,
radius_m=radius,
lookup="spatial-index/v1" if index is not None else "full-scan",
examined_points=examined,
target_sha256=hashlib.sha256(np.ascontiguousarray(points).tobytes()).hexdigest(),
)