refactor(lab): restore canonical RAV004 replay

This commit is contained in:
DCCONSTRUCTIONS
2026-08-30 01:22:44 +03:00
parent 74da6437e9
commit f1cbe0061a
21 changed files with 1181 additions and 719 deletions
+207 -36
View File
@@ -5,7 +5,7 @@ transport. This adapter reads the immutable recording once, indexes the
recorded source cloud and sensor pose, estimates the session sensor height from
the initial stationary cloud, and returns both the current increment and a
bounded accumulated local-SLAM cloud in a ground-rebased body frame. Camera,
spatial layers and the common timeline can therefore be driven by one host
spatial layers and the common timeline can therefore be driven by one media
clock without a per-LAB coordinate adapter.
"""
@@ -21,7 +21,7 @@ from typing import Any, Final
import numpy as np
import rerun_bindings as rr_bindings
CANONICAL_LAB_SPATIAL_PROFILE: Final = "source-paced-ground-v2"
CANONICAL_LAB_SPATIAL_PROFILE: Final = "source-paced-ground-v3"
_POINT_ENTITY: Final = "/world/points"
_POSE_ENTITY: Final = "/world/sensor_pose"
_TRAJECTORY_ENTITY: Final = "/world/trajectory"
@@ -35,11 +35,15 @@ _HEIGHT_CALIBRATION_MAX_FRAMES: Final = 120
_HEIGHT_NEAR_MIN_RADIUS_M: Final = 1.0
_HEIGHT_NEAR_MAX_RADIUS_M: Final = 6.0
_HEIGHT_LOWER_QUANTILE: Final = 0.025
_LOCAL_HEIGHT_QUANTILE: Final = 0.10
_LOCAL_HEIGHT_HALF_WINDOW_SECONDS: Final = 1.0
_LOCAL_SLAM_HISTORY_SECONDS: Final = 5.0
_LOCAL_SLAM_RADIUS_M: Final = 30.0
_LOCAL_SLAM_VERTICAL_LIMIT_M: Final = 6.0
_LOCAL_SLAM_VOXEL_SIZE_M: Final = 0.12
_LOCAL_SLAM_POINT_LIMIT: Final = 27_000
_FORWARD_HALF_WINDOW_SECONDS: Final = 1.0
_FORWARD_MINIMUM_DISPLACEMENT_M: Final = 0.15
@dataclass(frozen=True)
@@ -233,6 +237,67 @@ def _map_points_to_body(
return body.astype(np.float32)
def _gravity_stable_basis_map_from_body(
poses: _TimedPoses,
target_time_ns: int,
) -> tuple[np.ndarray, str]:
"""Return a right-handed forward/left/up base frame in the RFU map.
Rerun declares this recording map as RFU, while the metric LAB scene
consumes points as forward/left/up. The LiDAR quaternion columns are sensor
right/forward/up and also contain rover or handheld roll/pitch, so they are
not a body basis. Route displacement owns yaw when available; the sensor's
local +Y (Rerun Forward) projected onto map gravity is the stationary
fallback. Map +Z always owns up.
"""
center = _latest_index(poses.times_ns, target_time_ns)
half_window_ns = round(_FORWARD_HALF_WINDOW_SECONDS * 1_000_000_000)
first = _latest_index(poses.times_ns, max(0, target_time_ns - half_window_ns))
last = min(
len(poses.times_ns) - 1,
max(0, bisect_right(poses.times_ns, target_time_ns + half_window_ns) - 1),
)
route = poses.translations[last] - poses.translations[first]
route_xy = np.asarray([route[0], route[1], 0.0], dtype=np.float64)
route_norm = float(np.linalg.norm(route_xy))
sensor_rotation = _rotation_map_from_body(poses.quaternions_xyzw[center])
sensor_forward = np.asarray(
[sensor_rotation[0, 1], sensor_rotation[1, 1], 0.0],
dtype=np.float64,
)
sensor_forward_norm = float(np.linalg.norm(sensor_forward))
if sensor_forward_norm <= 1e-9:
raise ValueError("Recorded LAB sensor forward axis is invalid")
sensor_forward /= sensor_forward_norm
if route_norm >= _FORWARD_MINIMUM_DISPLACEMENT_M:
forward = route_xy / route_norm
if float(np.dot(forward, sensor_forward)) < 0.0:
forward = -forward
forward_source = "smoothed-pose-trajectory-tangent"
else:
forward = sensor_forward
forward_source = "rerun-rfu-sensor-forward-fallback"
up = np.asarray([0.0, 0.0, 1.0], dtype=np.float64)
left = np.cross(up, forward)
left_norm = float(np.linalg.norm(left))
if left_norm <= 1e-9:
raise ValueError("Recorded LAB body left axis is invalid")
left /= left_norm
forward = np.cross(left, up)
forward /= float(np.linalg.norm(forward))
basis = np.column_stack((forward, left, up))
if (
not np.allclose(basis.T @ basis, np.eye(3), atol=1e-7)
or np.linalg.det(basis) < 0.999999
):
raise ValueError("Recorded LAB gravity-stable body basis is invalid")
return basis, forward_source
def _estimate_sensor_height(points: _TimedPoints, poses: _TimedPoses) -> tuple[float, int, float]:
"""Estimate one session mount height from the initial qualified cloud.
@@ -253,17 +318,13 @@ def _estimate_sensor_height(points: _TimedPoints, poses: _TimedPoses) -> tuple[f
estimates: list[float] = []
for point_index in candidates:
pose_index = _latest_index(poses.times_ns, points.times_ns[point_index])
body = _map_points_to_body(
points.values[point_index],
poses.translations[pose_index],
poses.quaternions_xyzw[pose_index],
)
radius = np.linalg.norm(body[:, :2], axis=1)
eligible = body[
delta = points.values[point_index].astype(np.float64) - poses.translations[pose_index]
radius = np.linalg.norm(delta[:, :2], axis=1)
eligible = delta[
(radius >= _HEIGHT_NEAR_MIN_RADIUS_M)
& (radius <= _HEIGHT_NEAR_MAX_RADIUS_M)
& (body[:, 2] >= -2.0)
& (body[:, 2] <= 0.5)
& (delta[:, 2] >= -2.0)
& (delta[:, 2] <= 0.5)
]
if eligible.shape[0] < 100:
continue
@@ -278,12 +339,55 @@ def _estimate_sensor_height(points: _TimedPoints, poses: _TimedPoses) -> tuple[f
return height, len(estimates), mad
def _estimate_local_sensor_height(
points: _TimedPoints,
poses: _TimedPoses,
target_time_ns: int,
fallback_height_m: float,
) -> tuple[float, int, float, str]:
"""Estimate the current gravity-axis height without a fixed camera mount.
RAVNOVES004TREE changes sensor height during the route. A session-wide
constant therefore moves the scene vertically whenever the operator raises
or lowers K1. Use a short source-time window and a conservative near-field
ground quantile; fall back to the sealed session calibration only when the
current cloud has insufficient support.
"""
half_window_ns = round(_LOCAL_HEIGHT_HALF_WINDOW_SECONDS * 1_000_000_000)
first = bisect_right(points.times_ns, max(0, target_time_ns - half_window_ns) - 1)
last = bisect_right(points.times_ns, target_time_ns + half_window_ns)
estimates: list[float] = []
for point_index in range(first, last):
pose_index = _latest_index(poses.times_ns, points.times_ns[point_index])
delta = points.values[point_index].astype(np.float64) - poses.translations[pose_index]
radius = np.linalg.norm(delta[:, :2], axis=1)
eligible = delta[
(radius >= _HEIGHT_NEAR_MIN_RADIUS_M)
& (radius <= _HEIGHT_NEAR_MAX_RADIUS_M)
& (delta[:, 2] >= -2.5)
& (delta[:, 2] <= 0.5)
]
if eligible.shape[0] < 100:
continue
estimate = -float(np.quantile(eligible[:, 2], _LOCAL_HEIGHT_QUANTILE))
if 0.03 <= estimate <= 2.5:
estimates.append(estimate)
if not estimates:
return fallback_height_m, 0, 0.0, "session-source-cloud-fallback"
values = np.asarray(estimates, dtype=np.float64)
height = float(np.median(values))
mad = float(np.median(np.abs(values - height)))
return height, len(estimates), mad, "local-source-cloud-ground-quantile-median"
def _ground_origin_map(
sensor_origin_map: np.ndarray,
basis_map_from_body: np.ndarray,
sensor_height_m: float,
) -> np.ndarray:
return sensor_origin_map - basis_map_from_body[:, 2] * sensor_height_m
# The calibrated height belongs to the map gravity axis. Sensor roll/pitch
# must never tilt the ground origin or the accumulated world cloud.
return sensor_origin_map - np.asarray([0.0, 0.0, sensor_height_m])
def _map_points_to_ground_body(
@@ -329,32 +433,29 @@ def _bounded_local_slam(
return np.ascontiguousarray(local, dtype=np.float32), len(selected), source_count
def canonical_lab_spatial_frame(
recording_path: Path,
generation_sha256: str,
def _canonical_lab_spatial_frame_from_index(
index: _CanonicalSpatialIndex,
target_time_ns: int,
) -> dict[str, object]:
"""Return the current source cloud and bounded Local SLAM on one host time."""
if target_time_ns < 0:
raise ValueError("Recorded LAB target time is invalid")
stat = recording_path.stat()
index = _load_index(
str(recording_path),
stat.st_size,
stat.st_mtime_ns,
generation_sha256,
)
point_index = _latest_index(index.points.times_ns, target_time_ns)
pose_index = _latest_index(index.poses.times_ns, index.points.times_ns[point_index])
trajectory_index = _latest_index(index.trajectories.times_ns, target_time_ns)
translation = index.poses.translations[pose_index]
quaternion = index.poses.quaternions_xyzw[pose_index]
basis_map_from_body = _rotation_map_from_body(quaternion)
sensor_height_m, sensor_height_sample_count, sensor_height_mad_m, height_source = (
_estimate_local_sensor_height(
index.points,
index.poses,
index.points.times_ns[point_index],
index.sensor_height_m,
)
)
basis_map_from_body, forward_source = _gravity_stable_basis_map_from_body(
index.poses,
index.points.times_ns[point_index],
)
ground_origin = _ground_origin_map(
translation,
basis_map_from_body,
index.sensor_height_m,
sensor_height_m,
)
points_body = _map_points_to_ground_body(
index.points.values[point_index],
@@ -368,17 +469,18 @@ def canonical_lab_spatial_frame(
basis_map_from_body,
)
return {
"schema_version": "missioncore.canonical-recorded-lab-spatial-frame/v2",
"schema_version": "missioncore.canonical-recorded-lab-spatial-frame/v3",
"target_time_ns": target_time_ns,
"source_time_ns": index.points.times_ns[point_index],
"pose_time_ns": index.poses.times_ns[pose_index],
"trajectory_time_ns": index.trajectories.times_ns[trajectory_index],
"coordinate_frame": "body-ground",
"sensor_height": {
"meters": index.sensor_height_m,
"source": "initial-source-cloud-lower-quantile-median",
"sample_count": index.sensor_height_sample_count,
"mad_m": index.sensor_height_mad_m,
"meters": sensor_height_m,
"source": height_source,
"sample_count": sensor_height_sample_count,
"mad_m": sensor_height_mad_m,
"session_fallback_meters": index.sensor_height_m,
"authority": "visual-derived",
},
"spatial_profile": {
@@ -392,6 +494,8 @@ def canonical_lab_spatial_frame(
"origin_map_xyz_m": ground_origin.tolist(),
"sensor_origin_map_xyz_m": translation.tolist(),
"basis_map_from_body": basis_map_from_body.tolist(),
"up_source": "rerun-rfu-map-gravity-axis",
"forward_source": forward_source,
},
"source_point_count": int(points_body.shape[0]),
"source_points_body_xyz_m": points_body.tolist(),
@@ -400,3 +504,70 @@ def canonical_lab_spatial_frame(
"local_slam_point_count": int(local_slam.shape[0]),
"local_slam_body_xyz_m": local_slam.tolist(),
}
def canonical_lab_spatial_frame(
recording_path: Path,
generation_sha256: str,
target_time_ns: int,
) -> dict[str, object]:
"""Return the current source cloud and bounded Local SLAM on one media time."""
if target_time_ns < 0:
raise ValueError("Recorded LAB target time is invalid")
stat = recording_path.stat()
index = _load_index(
str(recording_path),
stat.st_size,
stat.st_mtime_ns,
generation_sha256,
)
return _canonical_lab_spatial_frame_from_index(index, target_time_ns)
def canonical_lab_spatial_timeline_samples(
recording_path: Path,
generation_sha256: str,
frame_times_ns: tuple[int, ...],
start_sequence: int,
frame_count: int,
) -> tuple[dict[str, object] | None, ...]:
"""Project only new source increments onto a denser camera timeline.
Camera is roughly 10 Hz in RAVNOVES004TREE while the sealed source cloud is
roughly 2 Hz. Returning the same JSON point array for every camera frame
multiplies transfer and parse cost and makes the viewer chase itself. A row
is populated only when its nearest causal source increment changes; the
canonical viewer retains that spatial frame until the next increment.
"""
if (
start_sequence < 0
or frame_count < 1
or start_sequence >= len(frame_times_ns)
or any(current <= previous for previous, current in zip(frame_times_ns, frame_times_ns[1:]))
):
raise ValueError("Recorded LAB timeline sample request is invalid")
stat = recording_path.stat()
index = _load_index(
str(recording_path),
stat.st_size,
stat.st_mtime_ns,
generation_sha256,
)
stop = min(len(frame_times_ns), start_sequence + frame_count)
samples: list[dict[str, object] | None] = []
for sequence in range(start_sequence, stop):
target_time_ns = frame_times_ns[sequence]
point_index = _latest_index(index.points.times_ns, target_time_ns)
previous_point_index = (
-1
if sequence == 0
else _latest_index(index.points.times_ns, frame_times_ns[sequence - 1])
)
samples.append(
_canonical_lab_spatial_frame_from_index(index, target_time_ns)
if point_index != previous_point_index
else None
)
return tuple(samples)