Files
RC2027_BR_code/minco_ws/docs/diagnostics/analyze_self_boundary.py
T

1919 lines
88 KiB
Python
Raw Normal View History

#!/usr/bin/python3
"""Offline diagnosis of self-body returns that survived the self filter.
Read-only by construction: this opens a recorded bag and parses it. It never
starts a node, never plays the bag back, and never publishes a topic. Nothing
here influences the running filter, the collision margin, or any parameter.
EVIDENCE GRADE (revised 2026-11-02 after architecture review)
------------------------------------------------------------
This tool does not confirm a cause. It separates three kinds of observation and
reports how far each one can carry you. Two earlier claims were withdrawn:
1. It used to call the observed pose spread a "motion bound" and treat a
residual below it as explained. That is wrong: the pose spread of the
*recorded* odometry cannot bound the prediction error of the *unpublished*
anchor that Point-LIO actually used. The quantity is now named
observed_motion_scale, and it only brackets the motion that was observed --
it is not an upper bound on anything. A residual below it is therefore
"inconclusive", and a residual above it is an "anomaly candidate", never a
confirmed transform defect.
2. It used to emit `unique` when one raw point was decisively nearest, which
reads as "same-source correspondence confirmed". It is not. Because a
published frame can draw points from several original scans, a competing
return in another candidate scan is not excluded by distance alone. The
value is now `heuristic_nearest`, and the nearest distance, the runner-up
distance, and their gap are all reported so a reviewer can judge for
themselves.
A high ambiguity rate is a property of the data, not a defect in the tool, and
it is not a reason to relax the evidence requirement.
Why the inverse transform cannot be exact
-----------------------------------------
Point-LIO publishes /cloud_registered_full through transformFullPointForward()
(laserMapping.cpp), which moves every point with a *predicted* anchor state:
p_world = R_pred * (R_L_I * p_lidar + T_L_I) + p_pred
R_pred = anchor.rot * Exp(anchor.omg, dt)
p_pred = anchor.pos + anchor.vel*dt + 0.5*anchor.acc*dt*dt
The anchor (rot/pos/vel/acc/omg) is an internal prediction snapshot and is NOT
published. Only /aft_mapped_to_init (the filtered IMU pose) is recorded. An
inverse built from recorded odometry is therefore an approximation whose error
is unknown, not merely small.
ImuProcess::Process() (IMU_Processing.cpp) currently copies the cloud unchanged,
so feats_undistort is a raw single-frame cloud in the optical frame; the motion
compensation happens only inside transformFullPointForward(). That also means
the per-point `curvature` field (offset_time / 1e6, milliseconds) survives into
the world cloud -- but since one published frame may hold points from several
original scans, a curvature value maps to a *set* of instants, never one.
"""
from __future__ import annotations
import argparse
import csv
import json
import math
import sqlite3
import sys
import traceback
from pathlib import Path
import numpy as np
TOOL_VERSION = "1.1.0"
SCHEMA_VERSION = 2
# Baseline measurement from the acceptance document. The config file is the
# actual input; a mismatch is reported, never silently accepted.
BASELINE = {
"self_front": 0.385,
"self_rear": 0.425,
"self_left": 0.400,
"self_right": 0.400,
"self_z_min": -0.48,
"self_z_max": 0.0,
"lidar_to_imu_translation": (-0.011, -0.02329, 0.04412),
}
# Screening threshold for the raw<->world residual, PROVISIONAL.
#
# This is NOT an acceptance tolerance and NOT a verified noise bound. It exists
# only to suppress residual screening below a level where the comparison cannot
# be trusted, and it is reported so it can be challenged or varied afterwards on
# the same bag.
#
# What it is NOT allowed to stand in for:
# * the motion observed in a frame -- that is reported separately and exactly;
# * a measured sensor noise figure -- a raw return and its world-frame copy
# come from the SAME measurement, so they share that noise and it cancels.
# Repeated-measurement spread only enters when two DIFFERENT returns (from
# different scans) are associated.
# * storage resolution -- curvature is a float32 holding milliseconds, so its
# resolution near a 50 ms offset is a few nanoseconds, not one millisecond.
COMPARISON_SCREENING_M = 0.02
DEFAULT_POSE_TIME_TOL = 0.03 # matches node.py's accepted cloud/pose gap
DEFAULT_POSE_GAP_WARN = 0.15 # node.py treats >0.15 s as a mismatch
DEFAULT_POSE_STALE = 0.25 # node.py's absolute age limit
DEFAULT_ASSOC_TIME_TOL = 0.002 # 2 ms; curvature is stored in ms as float32
DEFAULT_ASSOC_XYZ_TOL = 0.12 # search radius: raw/world are different pipelines
DEFAULT_ASSOC_TIE_MARGIN = 0.02 # nearest must beat the runner-up by this much
CANDIDATE_FRAME_RADIUS = 2 # scans either side that may contribute points
# Diagnostic region of interest around the measured bodywork. Environment
# returns (walls, steps, furniture) are trivially outside a 0.81x0.80 m box, so
# counting them would make "outside the envelope" meaningless. Only returns this
# close to the box are evidence about the body.
BODY_ROI_MARGIN_M = 0.30
DEFAULT_SHELL_MARGIN = 0.05 # keep raw points this far inside the box too
MAX_CSV_ROWS = 5000
MAX_SAMPLE_ROWS = 20
TOPIC_RAW = "/livox/lidar"
TOPIC_WORLD = "/cloud_registered_full"
TOPIC_POSE = "/aft_mapped_to_init"
REQUIRED_TOPICS = (TOPIC_RAW, TOPIC_WORLD, TOPIC_POSE)
EXIT_OK = 0
EXIT_MISSING = 2
EXIT_INCOMPATIBLE = 3
class PathProblem(Exception):
"""Unusable path or configuration; maps to exit code 2."""
class BagProblem(Exception):
"""Corrupt bag, unsupported storage, or incompatible message type.
Maps to exit code 3.
"""
class MissingTopic(Exception):
"""A required topic is absent; a partial report is still written."""
# --------------------------------------------------------------------------
# geometry
# --------------------------------------------------------------------------
def rotation_from_quaternion(quaternion):
"""Rotation matrix from a quaternion, rejecting degenerate input.
Mirrors obstacle_cloud.core.rotation_from_quaternion exactly so that a
point classified here matches what the live filter would have classified.
An all-zero quaternion is a missing orientation, not "identity": guessing
would hide the defect this tool is meant to find.
"""
q = np.asarray(quaternion, dtype=np.float64)
if q.shape != (4,) or not np.isfinite(q).all() or np.linalg.norm(q) < 1e-6:
raise ValueError("invalid IMU orientation for self filter")
x, y, z, w = q / np.linalg.norm(q)
return np.array([
[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
[2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
[2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)],
])
def load_geometry(config_path: Path) -> dict:
"""Read the measured envelope and extrinsic from the runtime config.
The config is the single source of truth. Anything that disagrees with the
acceptance document's baseline is surfaced in the returned dict under
'baseline_differences' instead of being rejected.
"""
config_path = Path(config_path)
if not config_path.is_file():
raise PathProblem(f"config not found: {config_path}")
try:
import yaml
except ImportError as exc: # pragma: no cover
raise PathProblem(f"PyYAML unavailable: {exc}") from exc
try:
raw = yaml.safe_load(config_path.read_text(encoding="utf-8"))
except Exception as exc:
raise PathProblem(f"cannot parse config {config_path}: {exc}") from exc
if not isinstance(raw, dict):
raise PathProblem(f"config {config_path} is not a mapping")
# Accept either the ROS parameter file shape or a flat mapping.
params = raw
for key in ("obstacle_cloud", "ros__parameters"):
if isinstance(params.get(key), dict):
params = params[key]
if isinstance(params.get("ros__parameters"), dict):
params = params["ros__parameters"]
missing = [k for k in BASELINE if k not in params]
if missing:
raise PathProblem(
f"config {config_path} is missing keys: {', '.join(sorted(missing))}")
geometry = {
"config_path": str(config_path.resolve()),
"self_front": float(params["self_front"]),
"self_rear": float(params["self_rear"]),
"self_left": float(params["self_left"]),
"self_right": float(params["self_right"]),
"self_z_min": float(params["self_z_min"]),
"self_z_max": float(params["self_z_max"]),
"boundary_guard": float(params.get("self_boundary_guard", 0.02)),
"lidar_to_imu_translation": np.asarray(
params["lidar_to_imu_translation"], dtype=np.float64),
}
if not np.isfinite([
geometry["self_front"], geometry["self_rear"],
geometry["self_left"], geometry["self_right"],
geometry["self_z_min"], geometry["self_z_max"]]).all():
raise PathProblem(f"config {config_path} has non-finite envelope values")
for key in ("self_front", "self_rear", "self_left", "self_right"):
if geometry[key] <= 0:
raise PathProblem(f"config {config_path}: {key} must be positive")
if geometry["self_z_min"] >= geometry["self_z_max"]:
raise PathProblem(
f"config {config_path}: self_z_min must be below self_z_max")
if geometry["lidar_to_imu_translation"].shape != (3,) or \
not np.isfinite(geometry["lidar_to_imu_translation"]).all():
raise PathProblem(
f"config {config_path}: lidar_to_imu_translation must be 3 finite values")
differences = []
for key, expected in BASELINE.items():
actual = geometry[key]
if key == "lidar_to_imu_translation":
if not np.allclose(actual, np.asarray(expected), atol=1e-9):
differences.append({
"key": key, "config": actual.tolist(),
"baseline": list(expected)})
continue
if not math.isclose(float(actual), float(expected), abs_tol=1e-9):
differences.append({
"key": key, "config": float(actual), "baseline": float(expected)})
geometry["baseline_differences"] = differences
geometry["baseline_as_documented"] = {
k: (list(v) if isinstance(v, tuple) else v) for k, v in BASELINE.items()}
return geometry
def envelope_bounds(geometry: dict):
"""Return (lo, hi, guard) in the optical lidar frame.
Axis convention comes from obstacle_cloud.core: x forward, y left, z up.
Hence front is +x, rear is -x, left is +y, right is -y.
The guard is lateral only, matching core.classify_self_returns: extending
it downward would reclassify ordinary ground returns as bodywork.
"""
lo = np.array([-geometry["self_rear"], -geometry["self_right"],
geometry["self_z_min"]], dtype=np.float64)
hi = np.array([geometry["self_front"], geometry["self_left"],
geometry["self_z_max"]], dtype=np.float64)
guard = np.array([geometry["boundary_guard"],
geometry["boundary_guard"], 0.0], dtype=np.float64)
return lo, hi, guard
def _direction_label(axis: int, positive: bool) -> str:
return {
(0, True): "front", (0, False): "rear",
(1, True): "left", (1, False): "right",
(2, True): "up", (2, False): "down",
}[(axis, positive)]
def classify_envelope(points, geometry: dict) -> dict:
"""Split points into inside / boundary band / outside.
Semantics follow obstacle_cloud.core.classify_self_returns exactly:
inside within the measured box
boundary outside the box but inside the per-axis guard band
outside beyond the guarded box
'excess' is measured from the *physical* box faces, not from the guarded
ones, so a boundary-band point still reports how far it is outside the real
bodywork. The guard only decides which band a point falls in; the vertical
guard is zero, so a return below the floor is outside immediately.
"""
pts = np.asarray(points, dtype=np.float64).reshape((-1, 3))
lo, hi, guard = envelope_bounds(geometry)
if len(pts) == 0:
return {
"inside": np.zeros(0, dtype=bool),
"boundary": np.zeros(0, dtype=bool),
"outside": np.zeros(0, dtype=bool),
"excess": np.zeros(0), "axis": np.zeros(0, dtype=int),
"positive": np.zeros(0, dtype=bool),
"distance_to_box": np.zeros(0),
}
exceed_hi = pts - hi # >0 means beyond the +side face
exceed_lo = lo - pts # >0 means beyond the -side face
exceed = np.maximum(exceed_hi, exceed_lo)
excess = exceed.max(axis=1)
axis = np.argmax(exceed, axis=1)
rows = np.arange(len(pts))
positive = exceed_hi[rows, axis] >= exceed_lo[rows, axis]
inside = ((pts >= lo) & (pts <= hi)).all(axis=1)
within_guard = ((pts >= lo - guard) & (pts <= hi + guard)).all(axis=1)
boundary = within_guard & ~inside
outside = ~within_guard
# L2 distance to the physical box surface, for readability only.
clipped = np.clip(pts, lo, hi)
distance_to_box = np.linalg.norm(pts - clipped, axis=1)
return {
"inside": inside, "boundary": boundary, "outside": outside,
"excess": excess, "axis": axis, "positive": positive,
"distance_to_box": distance_to_box,
}
def body_shell_mask(classified: dict,
inner_margin: float = DEFAULT_SHELL_MARGIN,
outer_margin: float = BODY_ROI_MARGIN_M) -> np.ndarray:
"""Which points are worth carrying into the association stage.
Only a thin band around the envelope qualifies: a little inside (so a raw
return just inside a face can still be matched) and out to the body ROI.
Both bounds are required -- `excess` is the distance from the box faces, so
an unbounded lower test would accept every distant wall as well.
"""
excess = classified["excess"]
return (excess >= -abs(inner_margin)) & (excess <= outer_margin)
def envelope_label(classified: dict) -> np.ndarray:
"""Per-point class label: 'inside' / 'boundary' / 'outside'.
A *label* change is a stronger observation than an `outside` flag change,
because a point can move between inside and the boundary band without ever
becoming outside. Both are recorded, but neither selects a verdict.
"""
count = len(classified["inside"])
labels = np.full(count, "outside", dtype=object)
labels[classified["boundary"]] = "boundary"
labels[classified["inside"]] = "inside"
return labels
# --------------------------------------------------------------------------
# time
# --------------------------------------------------------------------------
def point_time_ns(timebase_ns: int, offset_ns: int) -> int:
"""Absolute integer-nanosecond stamp of one Livox point.
Verified against livox_ros_driver2: InitCustomMsg sets
timebase = pkg.base_time (uint64, ns)
header.stamp = rclcpp::Time(timestamp) (same instant)
and FillPointsToCustomMsg sets
offset_time = point.offset_time - pkg.base_time (uint32, ns)
so the per-point instant is timebase + offset_time, in the same clock as
the message header. Integer arithmetic only: float seconds lose ~100 ns of
resolution near a modern epoch, which is the same order as the offsets we
are trying to resolve.
"""
base = int(timebase_ns)
offset = int(offset_ns)
if base < 0 or offset < 0:
raise ValueError(f"negative timestamp components: {timebase_ns}, {offset_ns}")
if offset > 4_000_000_000:
raise ValueError(f"implausible offset_time {offset} ns for a Livox frame")
return base + offset
class PoseIndex:
"""Nearest-neighbour lookup over recorded IMU poses.
Deliberately nearest rather than interpolated: interpolation would invent a
pose that was never recorded and blur exactly the timing error we want to
measure. The returned dt lets callers reject a match instead.
"""
def __init__(self, times_ns, positions, quaternions):
self.times = np.asarray(times_ns, dtype=np.int64)
self.positions = np.asarray(positions, dtype=np.float64).reshape((-1, 3))
self.quaternions = np.asarray(quaternions, dtype=np.float64).reshape((-1, 4))
if not (len(self.times) == len(self.positions) == len(self.quaternions)):
raise ValueError("pose arrays have inconsistent lengths")
self.regressions = int(np.sum(np.diff(self.times) <= 0))
if len(self.times) > 1:
gaps = np.diff(self.times) / 1e9
self.max_gap = float(gaps.max())
else:
self.max_gap = 0.0
self.valid = np.zeros(len(self.times), dtype=bool)
for i, q in enumerate(self.quaternions):
try:
rotation_from_quaternion(q)
except ValueError:
continue
if np.isfinite(self.positions[i]).all():
self.valid[i] = True
def __len__(self):
return len(self.times)
def nearest(self, query_ns: int):
"""Return (dt_seconds, index) or (inf, None) when unusable."""
if len(self.times) == 0:
return math.inf, None
pos = int(np.searchsorted(self.times, query_ns))
best = None
for idx in (pos - 1, pos, pos + 1):
if 0 <= idx < len(self.times) and self.valid[idx]:
delta = abs(int(self.times[idx]) - int(query_ns))
if best is None or delta < best[0]:
best = (delta, idx)
if best is None:
return math.inf, None
return best[0] / 1e9, best[1]
# --------------------------------------------------------------------------
# transforms and observed motion
# --------------------------------------------------------------------------
def inverse_transform(points_world, pose_position, pose_quaternion,
translation, rotation_fn=None) -> np.ndarray:
"""World -> IMU -> optical lidar, using the full quaternion.
p_IMU = p_lidar + T_L_I and p_world = R_world * p_IMU + pos
therefore p_lidar = R_world^T (p_world - pos) - T_L_I.
This is the inverse of Point-LIO's forward map with the *recorded* pose
substituted for the unpublished anchor prediction. The substitution error
is unknown; it is not bounded by anything this tool can measure.
"""
fn = rotation_fn or rotation_from_quaternion
rotation = fn(pose_quaternion)
pts = np.asarray(points_world, dtype=np.float64).reshape((-1, 3))
translation = np.asarray(translation, dtype=np.float64).reshape(3)
return (pts - np.asarray(pose_position, dtype=np.float64).reshape(3)) @ rotation \
- translation
def observed_motion_scale(pose_positions, pose_quaternions, points_world,
rotation_fn=None) -> float:
"""How much motion the recorded odometry actually spans during the frame.
scale = translational extent + rotational extent * lever arm
THIS IS NOT AN UPPER BOUND. It describes the observed motion of the robot.
It says nothing about the error of the unpublished anchor prediction, which
is the quantity that actually contaminates the world cloud. A residual above
this scale is therefore only an *anomaly candidate*: it exceeds the motion
that was observed, and no further attribution is supported.
Returned unmodified, including the exact zero of a perfectly static frame.
Any floor belongs to the screening threshold, not here: mixing the two would
let an assumption masquerade as measured motion.
"""
fn = rotation_fn or rotation_from_quaternion
pos = np.asarray(pose_positions, dtype=np.float64).reshape((-1, 3))
pts = np.asarray(points_world, dtype=np.float64).reshape((-1, 3))
if len(pos) == 0 or len(pts) == 0:
return math.inf
translational = float(np.linalg.norm(np.ptp(pos, axis=0))) if len(pos) > 1 else 0.0
rotational = 0.0
quats = np.asarray(pose_quaternions, dtype=np.float64).reshape((-1, 4))
if len(quats) > 1:
reference = None
for q in quats:
try:
reference = fn(q)
break
except ValueError:
continue
if reference is not None:
for q in quats:
try:
current = fn(q)
except ValueError:
continue
cosine = (np.trace(reference.T @ current) - 1.0) / 2.0
rotational = max(rotational,
math.acos(max(-1.0, min(1.0, cosine))))
origin = pos.mean(axis=0)
lever = float(np.linalg.norm(pts - origin, axis=1).max()) if len(pts) else 0.0
return translational + rotational * lever
def comparison_threshold(observed_scale_m: float) -> float:
"""Residual screening threshold for a frame: the larger of the two.
The residual is screened against the frame's own observed motion, but never
below the provisional floor, because a static frame has zero motion and a
zero threshold would flag floating-point dust.
Being below this threshold means only that no screening was triggered. It
does not mean the residual was explained by motion -- that stronger reading
is reserved for residuals within observed_scale_m itself.
"""
if observed_scale_m is None or not math.isfinite(observed_scale_m):
return COMPARISON_SCREENING_M
return max(float(observed_scale_m), COMPARISON_SCREENING_M)
# --------------------------------------------------------------------------
# association
# --------------------------------------------------------------------------
def candidate_frame_indices(frames, index: int) -> list:
"""Scans that could have supplied a point to the published frame.
The full-cloud path drains a cross-scan queue, so a published frame may
contain points whose original scan is not the one nearest in time. Every
plausible scan must be searched for competing returns -- searching only the
nearest frame can hide a competitor and manufacture a false `heuristic_nearest`.
"""
lo = max(0, index - CANDIDATE_FRAME_RADIUS)
hi = min(len(frames), index + CANDIDATE_FRAME_RADIUS + 1)
return list(range(lo, hi))
def estimate_scan_window_ns(frames) -> int:
"""How far back a point in a published frame can have been sampled.
One scan duration plus one scan spacing: the queue can hold a full previous
scan, and the frame header sits at that scan's end. Using only the spacing
would exclude every point of the previous scan, which is exactly the case
the cross-scan search exists for.
"""
if not frames:
return 0
duration = max((f["duration_ns"] for f in frames), default=0)
if len(frames) < 2:
return duration
bases = np.array([f["timebase_ns"] for f in frames], dtype=np.int64)
gaps = np.abs(np.diff(bases))
gaps = gaps[gaps > 0]
spacing = int(np.median(gaps)) if len(gaps) else 0
return duration + spacing
def candidate_time_window_ns(published_stamp_ns: int, scan_window_ns: int,
time_tolerance_s: float) -> tuple:
"""The instants that can physically belong to one published frame.
One-sided and bounded: a point cannot be sampled after the frame header, and
can be at most a scan duration plus a scan spacing earlier (queued points
that arrived late). A future scan is never admissible.
"""
tolerance_ns = int(round(time_tolerance_s * 1e9))
published = int(published_stamp_ns)
return (published - max(int(scan_window_ns), 0) - tolerance_ns,
published + tolerance_ns)
def candidate_times_ns(frames, indices, curvature_ms: float,
published_stamp_ns: int, scan_window_ns: int,
time_tolerance_s: float) -> list:
"""Every instant a world point could have been sampled at.
curvature is the offset from the *original scan's* base time, and the
original scan is not identified by the published frame. Each candidate scan
therefore contributes its own instant, typically one scan period apart.
Returning a set, rather than picking the most convenient one, keeps the
unresolved assumption visible.
"""
curvature_ns = int(round(float(curvature_ms) * 1e6))
earliest, latest = candidate_time_window_ns(
published_stamp_ns, scan_window_ns, time_tolerance_s)
out = []
for i in indices:
candidate = int(frames[i]["timebase_ns"]) + curvature_ns
if earliest <= candidate <= latest:
out.append(candidate)
return sorted(set(out))
def association_pool(frames, indices) -> dict:
"""Merge the raw shell of every candidate scan into one searchable pool.
Searching only frames[index] was a defect: a competitor point living in a
neighbouring scan never entered the comparison, so a distant runner-up could
be missed and a false nearest reported.
"""
times, points, outside, owners, labels = [], [], [], [], []
for i in indices:
frame = frames[i]
count = len(frame["times_ns"])
if count == 0:
continue
times.append(frame["times_ns"])
points.append(frame["points"])
outside.append(frame["outside"])
labels.append(frame["labels"])
owners.append(np.full(count, i, dtype=np.int64))
if not times:
return {
"times": np.zeros(0, dtype=np.int64),
"points": np.zeros((0, 3)), "outside": np.zeros(0, dtype=bool),
"labels": np.zeros(0, dtype=object),
"owner": np.zeros(0, dtype=np.int64),
}
return {
"times": np.concatenate(times),
"points": np.vstack(points),
"outside": np.concatenate(outside),
"labels": np.concatenate(labels),
"owner": np.concatenate(owners),
}
def resolve_association(candidate_times, point_lidar, pool, time_tol_s,
xyz_tol, tie_margin=DEFAULT_ASSOC_TIE_MARGIN) -> tuple:
"""Single-assumption association; delegates to the multi-assumption form.
The position is broadcast across every candidate time on purpose: with one
position and several instants, zip() would silently evaluate only the first
instant and drop the rest.
"""
point = np.asarray(point_lidar, dtype=np.float64).reshape(3)
times = list(candidate_times)
return resolve_association_multi(times, [point] * len(times), pool,
time_tol_s, xyz_tol, tie_margin)
def resolve_association_multi(option_times, option_points, pool, time_tol_s,
xyz_tol,
tie_margin=DEFAULT_ASSOC_TIE_MARGIN) -> tuple:
"""Rank raw returns while keeping each assumption's own candidate.
Every admissible assumption searches its own instant and reports at most one
raw return. The per-assumption residuals are kept separately and summarised
as a RANGE:
residual_min the most favourable admissible reading
residual_max the least favourable one
A large residual_max must NOT be used to reject the reading that produced a
small residual_min: that would discard the best admissible account of the
observation. Two assumptions with residuals of 1 mm and 50 mm do not
contradict each other -- the 50 mm one simply says that reading fits worse.
Symmetrically, claiming that the residual exceeds a threshold requires
residual_MIN to exceed it, i.e. every admissible reading fails. That is the
only form of the claim the data can support.
Quality:
heuristic_nearest one raw return is decisively nearer than the runner-up
ambiguous several are similarly near
unmatched no assumption reached any raw return
'heuristic_nearest' ranks candidates by distance. It does not confirm that
the raw and world points are the same measurement.
"""
time_tol_ns = int(round(time_tol_s * 1e9))
times = pool["times"]
points = pool["points"]
per_assumption_best = [] # each assumption's nearest admissible return
all_hits = {} # every raw index reached, with its best distance
for candidate, position in zip(option_times, option_points):
position = np.asarray(position, dtype=np.float64).reshape(3)
best = None
if np.isfinite(position).all():
window = np.abs(times - int(candidate)) <= time_tol_ns
if window.any():
inside = np.where(window)[0]
distance = np.linalg.norm(points[inside] - position, axis=1)
for local, value in enumerate(distance):
if float(value) <= xyz_tol:
index = int(inside[local])
all_hits[index] = min(float(value),
all_hits.get(index, math.inf))
if best is None or value < best[1]:
best = (index, float(value))
per_assumption_best.append(best)
reached = [item for item in per_assumption_best if item is not None]
# Two different counts matter: how many assumptions reached something, and
# how many distinct raw returns were reached at all.
diagnostics = {
"assumption_count": len(option_times),
"assumptions_reaching_a_candidate": len(reached),
"candidate_scans": int(len(np.unique(pool["owner"]))) if len(pool["owner"]) else 0,
"hits": len(all_hits),
"nearest_dist": math.nan, "second_dist": math.nan, "margin": math.nan,
"residual_min": math.nan, "residual_max": math.nan,
}
if not reached:
return "unmatched", None, diagnostics
# Per-assumption residuals: each assumption is summarised by its own best
# account, and the pair is described by the range. Never by the worst alone.
distances = [distance for _, distance in reached]
diagnostics["residual_min"] = float(min(distances))
diagnostics["residual_max"] = float(max(distances))
ordered = sorted(all_hits.items(), key=lambda item: item[1])
nearest_index, nearest_distance = ordered[0]
diagnostics["nearest_dist"] = nearest_distance
if len(ordered) == 1:
diagnostics["margin"] = math.inf
return "heuristic_nearest", nearest_index, diagnostics
diagnostics["second_dist"] = ordered[1][1]
diagnostics["margin"] = ordered[1][1] - nearest_distance
if ordered[1][1] - nearest_distance >= tie_margin:
return "heuristic_nearest", nearest_index, diagnostics
return "ambiguous", None, diagnostics
def candidate_pose_options(pose_times, pose_valid, frame_bases, offset_ns,
indices, pose_time_tol_s, published_stamp_ns,
scan_window_ns) -> list:
"""One pose resolution per admissible sampling assumption.
The sampling instant is a set, not a value. Picking the assumption whose
odometry happens to be closest would turn a guess into a fact, and would
systematically prefer the time that makes the residual look smallest. Every
assumption is resolved and returned; nothing is collapsed, and no agreement
between assumptions is required.
An assumption is admissible only when its instant lies inside the published
frame's physical time window. Enforcing that here -- not only when listing
candidate times -- is what keeps future or out-of-window scans out of the
enumeration.
Each option is a dict:
frame_index, time_ns, pose_index (-1 where none), dt_s,
usable, in_window, pose_valid
"""
options = []
if len(offset_ns) == 0 or not indices or len(pose_times) == 0:
return options
earliest, latest = candidate_time_window_ns(
published_stamp_ns, scan_window_ns, 0.0)
last = len(pose_times) - 1
for frame_index in indices:
candidate = np.int64(frame_bases[frame_index]) + offset_ns
in_window = (candidate >= earliest) & (candidate <= latest)
upper = np.clip(np.searchsorted(pose_times, candidate), 0, last)
lower = np.clip(upper - 1, 0, last)
distance_upper = np.abs(pose_times[upper] - candidate)
distance_lower = np.abs(pose_times[lower] - candidate)
take_lower = distance_lower < distance_upper
pose_index = np.where(take_lower, lower, upper)
distance = np.where(take_lower, distance_lower, distance_upper)
dt = distance / 1e9
valid = pose_valid[pose_index]
usable = valid & in_window & (dt <= pose_time_tol_s)
options.append({
"frame_index": int(frame_index),
"time_ns": candidate,
# -1 whenever the assumption cannot be used, so a caller that
# forgets to test `usable` still cannot index a wrong pose.
"pose_index": np.where(usable, pose_index, -1),
"dt_s": dt,
"in_window": in_window,
"pose_valid": valid,
"usable": usable,
})
return options
# --------------------------------------------------------------------------
# bag access
# --------------------------------------------------------------------------
def read_metadata(bag_dir: Path) -> dict:
"""Parse metadata.yaml: storage kind, shard list, topic type map."""
bag_dir = Path(bag_dir)
if not bag_dir.exists():
raise PathProblem(f"bag directory not found: {bag_dir}")
if bag_dir.is_file():
if bag_dir.suffix == ".db3":
return {
"storage_identifier": "sqlite3",
"files": [bag_dir.parent / bag_dir.name],
"topics": {}, "metadata_present": False,
"shard_note": "single .db3 passed directly; topic types read from sqlite",
}
raise PathProblem(f"--bag expects a directory, got file: {bag_dir}")
metadata = bag_dir / "metadata.yaml"
if not metadata.is_file():
raise PathProblem(f"metadata.yaml not found in {bag_dir}")
try:
import yaml
except ImportError as exc: # pragma: no cover
raise PathProblem(f"PyYAML unavailable: {exc}") from exc
try:
doc = yaml.safe_load(metadata.read_text(encoding="utf-8"))
except Exception as exc:
raise BagProblem(f"cannot parse {metadata}: {exc}") from exc
info = (doc or {}).get("rosbag2_bagfile_information")
if not isinstance(info, dict):
raise BagProblem(f"{metadata} has no rosbag2_bagfile_information")
storage = info.get("storage_identifier", "")
relative = info.get("relative_file_paths") or [
entry.get("path") for entry in info.get("files", []) if entry.get("path")]
if not relative:
raise BagProblem(f"{metadata} lists no shard files")
files = [bag_dir / name for name in relative]
missing = [str(f) for f in files if not f.is_file()]
if missing:
raise BagProblem(f"shard files listed in metadata are absent: {missing}")
topics = {}
for entry in info.get("topics_with_message_count", []) or []:
meta = entry.get("topic_metadata", {})
name, kind = meta.get("name"), meta.get("type")
if name and kind:
topics[name] = kind
return {
"storage_identifier": storage,
"files": files,
"topics": topics,
"metadata_present": True,
"version": info.get("version"),
"duration_ns": info.get("duration", {}).get("nanoseconds")
if isinstance(info.get("duration"), dict) else None,
}
def _open_shard(path: Path):
if not Path(path).is_file():
raise BagProblem(f"shard not found: {path}")
try:
conn = sqlite3.connect(f"file:{Path(path).resolve()}?mode=ro", uri=True)
conn.execute("SELECT count(*) FROM sqlite_master").fetchone()
except sqlite3.DatabaseError as exc:
raise BagProblem(f"cannot open {path} as sqlite: {exc}") from exc
return conn
def _topic_ids(conn, path: Path) -> dict:
try:
rows = conn.execute("SELECT id, name, type FROM topics").fetchall()
except sqlite3.DatabaseError as exc:
raise BagProblem(f"{path} is not a rosbag2 sqlite shard: {exc}") from exc
return {name: (tid, kind) for tid, name, kind in rows}
def _load_ros_bindings():
try:
from rclpy.serialization import deserialize_message # noqa: WPS433
from rosidl_runtime_py.utilities import get_message # noqa: WPS433
except ImportError as exc:
raise BagProblem(
"ROS 2 Python bindings unavailable "
f"({exc}); source /opt/ros/humble/setup.bash and install/setup.bash")
return deserialize_message, get_message
def _stamp_ns(stamp) -> int:
return int(stamp.sec) * 1_000_000_000 + int(stamp.nanosec)
_PC2_DTYPES = {
1: np.int8, 2: np.uint8, 3: np.int16, 4: np.uint16,
5: np.int32, 6: np.uint32, 7: np.float32, 8: np.float64,
}
def cloud_fields(msg) -> dict:
"""Extract named float columns from a PointCloud2 without read_points().
read_points() returns a structured array whose dtype varies with the
message; indexing it column-wise is fragile. Reading the raw buffer with
explicit field offsets keeps the arithmetic predictable and avoids one
Python object per point.
"""
count = int(msg.width) * int(msg.height)
if count == 0 or msg.point_step == 0:
return {}
buffer = np.frombuffer(msg.data, dtype=np.uint8)
if buffer.size < count * msg.point_step:
raise BagProblem(
f"PointCloud2 data is {buffer.size} bytes, expected "
f"{count * msg.point_step}")
view = buffer.reshape(count, msg.point_step)
order = ">" if getattr(msg, "is_bigendian", False) else "<"
columns = {}
for field in msg.fields:
dtype = _PC2_DTYPES.get(int(field.datatype))
if dtype is None:
continue
width = np.dtype(dtype).itemsize
if field.offset + width > msg.point_step:
continue
chunk = np.ascontiguousarray(
view[:, field.offset:field.offset + width]).copy()
columns[field.name] = chunk.view(
np.dtype(f"{order}{np.dtype(dtype).str[1:]}")).reshape(count)
return columns
# --------------------------------------------------------------------------
# analysis
# --------------------------------------------------------------------------
def _collect_poses(paths, topic_type, deserialize_message, get_message):
times, positions, quaternions = [], [], []
frames = 0
invalid_quaternion = 0
for path in paths:
conn = _open_shard(path)
try:
ids = _topic_ids(conn, path)
if TOPIC_POSE not in ids:
continue
tid, kind = ids[TOPIC_POSE]
for (blob,) in conn.execute(
"SELECT data FROM messages WHERE topic_id=? ORDER BY timestamp", (tid,)):
msg = deserialize_message(blob, get_message(kind or topic_type))
pose = msg.pose.pose
frames += 1
quaternion = [pose.orientation.x, pose.orientation.y,
pose.orientation.z, pose.orientation.w]
try:
rotation_from_quaternion(quaternion)
except ValueError:
invalid_quaternion += 1
continue
if not all(math.isfinite(v) for v in
(pose.position.x, pose.position.y, pose.position.z)):
continue
times.append(_stamp_ns(msg.header.stamp))
positions.append([pose.position.x, pose.position.y, pose.position.z])
quaternions.append(quaternion)
finally:
conn.close()
order = np.argsort(np.asarray(times, dtype=np.int64), kind="stable")
return (
np.asarray(times, dtype=np.int64)[order],
np.asarray(positions, dtype=np.float64).reshape((-1, 3))[order],
np.asarray(quaternions, dtype=np.float64).reshape((-1, 4))[order],
{"messages": frames, "invalid_quaternion_skipped": invalid_quaternion},
)
def _scan_raw(paths, geometry, deserialize_message, get_message, topic_type,
shell_margin):
"""First pass: classify raw points in the optical frame, keep a shell.
Only points at or near the envelope are retained. A whole bag of
full-resolution scans does not fit in memory, and the outside/boundary
points are the only ones this diagnostic needs to associate later.
"""
cls = get_message(topic_type)
frames = []
total_points = 0
invalid_points = 0
counts = {"inside": 0, "boundary": 0, "outside": 0}
roi_counts = {"points": 0, "beyond_solid_envelope": 0,
"within_guard_band": 0, "beyond_guard_band": 0}
for path in paths:
conn = _open_shard(path)
try:
ids = _topic_ids(conn, path)
if TOPIC_RAW not in ids:
continue
tid, kind = ids[TOPIC_RAW]
for (blob,) in conn.execute(
"SELECT data FROM messages WHERE topic_id=? ORDER BY timestamp", (tid,)):
msg = deserialize_message(blob, get_message(kind or topic_type))
timebase = int(msg.timebase) if msg.timebase else _stamp_ns(msg.header.stamp)
if not msg.points:
continue
xyz = np.array([[p.x, p.y, p.z] for p in msg.points], dtype=np.float64)
offsets = np.array([int(p.offset_time) for p in msg.points], dtype=np.int64)
finite = np.isfinite(xyz).all(axis=1)
invalid_points += int((~finite).sum())
if not finite.any():
continue
xyz, offsets = xyz[finite], offsets[finite]
classified = classify_envelope(xyz, geometry)
counts["inside"] += int(classified["inside"].sum())
counts["boundary"] += int(classified["boundary"].sum())
counts["outside"] += int(classified["outside"].sum())
total_points += len(xyz)
# Whole-scene counts are dominated by walls and steps, which are
# outside any 0.81x0.80 m box. Only the body ROI is evidence, and
# it is split into "beyond the solid envelope" (which includes the
# 2 cm guard band) and "beyond the guard band as well".
roi = classified["distance_to_box"] <= BODY_ROI_MARGIN_M
roi_counts["points"] += int(roi.sum())
roi_counts["beyond_solid_envelope"] += int(
(roi & (classified["boundary"] | classified["outside"])).sum())
roi_counts["within_guard_band"] += int(
(roi & classified["boundary"]).sum())
roi_counts["beyond_guard_band"] += int(
(roi & classified["outside"]).sum())
keep = body_shell_mask(classified, inner_margin=shell_margin)
duration = int(offsets.max()) if len(offsets) else 0
labels = envelope_label(classified)
if not keep.any():
frames.append({
"timebase_ns": timebase,
"times_ns": np.zeros(0, dtype=np.int64),
"points": np.zeros((0, 3)),
"inside": np.zeros(0, dtype=bool),
"boundary": np.zeros(0, dtype=bool),
"outside": np.zeros(0, dtype=bool),
"labels": np.zeros(0, dtype=object),
"excess": np.zeros(0),
"axis": np.zeros(0, dtype=int),
"positive": np.zeros(0, dtype=bool),
"distance_to_box": np.zeros(0),
"duration_ns": duration,
})
continue
times = np.array(
[point_time_ns(timebase, off) for off in offsets[keep]],
dtype=np.int64)
frames.append({
"timebase_ns": timebase,
"times_ns": times,
"points": xyz[keep],
"inside": classified["inside"][keep],
"boundary": classified["boundary"][keep],
"outside": classified["outside"][keep],
"labels": labels[keep],
"excess": classified["excess"][keep],
"axis": classified["axis"][keep],
"positive": classified["positive"][keep],
"distance_to_box": classified["distance_to_box"][keep],
"duration_ns": duration,
})
finally:
conn.close()
return frames, {
"scans": len(frames), "points": total_points,
"invalid_points_skipped": invalid_points,
"raw_classified": counts,
"raw_body_roi": {**roi_counts, "roi_margin_m": BODY_ROI_MARGIN_M},
}
def _decide(quality, residual_min, observed_scale, threshold, world_outside,
evidence_complete) -> str:
"""Decide what a single associated pair supports, in this order.
Two deliberate omissions:
* classification_changed is not a parameter here. A raw point and its
inverse-transformed counterpart landing on different sides of the envelope
is an observation, not a cause: a millimetre near a face flips it, and the
inverse transform's unknown error can produce that flip just as easily as
a real defect. It is recorded in the CSV only.
* the anomaly branch tests residual_MIN, not residual_max. Claiming that the
residual exceeds a threshold means every admissible reading fails. Using a
large worst-case residual while a favourable reading exists would discard
the best account of the observation.
An anomaly is still only a candidate: observed_motion_scale does not bound
the unpublished anchor prediction error, so no cause follows from it.
"""
if quality == "ambiguous":
return "inconclusive_ambiguous"
if quality == "unmatched":
return "world_outside_no_raw_counterpart" if world_outside \
else "inconclusive_unmatched"
if not evidence_complete:
return "inconclusive_incomplete_evidence"
if residual_min is None or not math.isfinite(residual_min):
return "inconclusive_unmatched"
if observed_scale is None or not math.isfinite(observed_scale):
return "inconclusive_no_observed_motion_scale"
# Only a residual inside the frame's own observed motion is *explained* by
# motion. Between that and the screening threshold nothing was triggered,
# which is a weaker statement and must not borrow the stronger wording.
if residual_min <= observed_scale:
return "inconclusive_within_observed_motion"
if residual_min <= threshold:
return "inconclusive_below_screening_threshold"
return "anomaly_candidate_unattributed"
def _reason(decision, diagnostics) -> str:
base = {
"inconclusive_ambiguous": (
"candidates similarly close; the nearest is not separable"),
"inconclusive_unmatched": "no raw point within tolerance",
"inconclusive_incomplete_evidence": (
"at least one admissible sampling assumption had no usable pose, so "
"the candidate set was not fully evaluated"),
"inconclusive_no_observed_motion_scale": (
"observed motion scale could not be computed"),
"inconclusive_within_observed_motion": (
"the most favourable admissible reading is no larger than the motion "
"observed in this frame"),
"inconclusive_below_screening_threshold": (
"the most favourable admissible reading exceeds the observed motion "
"but stays below the provisional screening threshold; no screen was "
"triggered, and the residual is NOT explained"),
"anomaly_candidate_unattributed": (
"every admissible reading exceeds the observed motion scale, but "
"that scale does not bound the unpublished anchor prediction error; "
"cause not established"),
"world_outside_no_raw_counterpart": (
"world point is outside but no raw return matches it in time and "
"space; it may be a compensation artefact or an unrecorded raw point"),
}.get(decision, decision)
return base
def _conclude(report) -> tuple:
"""Return (conclusion, reason) without overstating the evidence.
The basis is the body-region ROI, not the whole scene: walls, steps and
furniture are trivially outside a 0.81x0.80 m box, so a whole-scene count
would make "outside the envelope" meaningless.
'undetermined' is a first-class outcome, and so is
'raw_outside_measured_unlinked': it states that measured raw coordinates lie
outside the configured envelope near the bodywork, and nothing more. It does
not establish body protrusion, a real obstacle, or a compensation error.
"""
stats = report["statistics"]
decisions = stats.get("decisions", {})
association = stats.get("association", {})
roi = stats.get("raw_body_roi", {})
beyond_solid = int(roi.get("beyond_solid_envelope", 0))
beyond_band = int(roi.get("beyond_guard_band", 0))
nearest = association.get("heuristic_nearest", 0)
ambiguous = association.get("ambiguous", 0)
anomalies = decisions.get("anomaly_candidate_unattributed", 0)
within = decisions.get("inconclusive_within_observed_motion", 0)
below_screen = decisions.get("inconclusive_below_screening_threshold", 0)
incomplete = decisions.get("inconclusive_incomplete_evidence", 0)
no_counterpart = decisions.get("world_outside_no_raw_counterpart", 0)
if beyond_solid == 0:
return "no_raw_outside_returns", (
"no raw return inside the body diagnostic region lies outside the "
"measured envelope, so there is no measured out-of-envelope return "
"to explain")
if nearest == 0:
return "raw_outside_measured_unlinked", (
f"{beyond_solid} raw return(s) inside the body diagnostic region lie "
f"outside the measured envelope ({beyond_band} of them beyond the "
"2 cm guard band as well). This is a statement about the measured "
"raw coordinates relative to the configured envelope, with no "
"reliable association to the world cloud established. It does not "
"establish body protrusion, a real obstacle, or a compensation "
"error")
if anomalies > 0:
return "anomaly_candidates_unattributed", (
f"{anomalies} pair(s) leave every admissible reading larger than the "
f"motion observed in their frame ({within} did not). That scale does "
"not bound the unpublished anchor prediction error, so no cause is "
"attributed; this is a lead to investigate, not a finding")
if incomplete > 0 and within == 0 and below_screen == 0:
return "undetermined", (
f"{incomplete} pair(s) could not be fully evaluated because an "
"admissible sampling assumption had no usable pose; the evidence is "
"incomplete rather than negative")
if within > 0 or below_screen > 0:
return "undetermined", (
f"{within} pair(s) stay within the motion observed in their frame and "
f"{below_screen} exceed that motion but fall below the provisional "
"screening threshold, so no screen was triggered for them. Neither "
"outcome is evidence about the cause: the inverse transform cannot be "
"separated from the anchor error "
f"(ambiguous candidates: {ambiguous}, no counterpart: {no_counterpart})")
return "undetermined", (
f"body-region outside returns={beyond_solid}, heuristic nearest={nearest}, "
f"ambiguous={ambiguous}, no counterpart={no_counterpart}; "
"not enough separable evidence to attribute a cause")
def _limits(report) -> list:
limits = [
"observed_motion_scale describes the motion spanned by the recorded "
"odometry in a frame, measured and reported without any floor. It is NOT "
"an upper bound on the error of the unpublished anchor used by Point-LIO, "
"so a residual above it is only an anomaly candidate and never a "
"confirmed transform defect.",
"The comparison threshold is max(observed motion, provisional screening "
"floor). It is a screening level only: NOT an acceptance tolerance, and "
"NOT a verified noise bound. A raw return and its world-frame copy come "
"from the same measurement, so sensor noise cancels between them; "
"repeated-measurement spread enters only when two different scans are "
"associated. A residual below the threshold was not screened, which is "
"weaker than being explained by motion.",
"World points whose residual never triggered screening are still written "
"to the CSV with their excess distance and classification, and the "
"summary reports the excess distribution regardless of the threshold, so "
"small excursions stay visible and thresholds can be compared later on "
"the same bag.",
"Each admissible sampling assumption is evaluated separately. The "
"reported residual is a range: residual_min is the most favourable "
"reading, residual_max the least favourable. A large residual_max does "
"not invalidate a small residual_min.",
"heuristic_nearest ranks a candidate by distance among the scanned "
"returns. It does not establish that the raw point and the world point "
"came from the same measurement; nearest distance, runner-up distance "
"and their gap are reported for that judgement.",
"The inverse transform substitutes the recorded /aft_mapped_to_init "
"pose for Point-LIO's unpublished anchor prediction, so it is an "
"approximation with unknown error, not an exact inverse.",
"A published /cloud_registered_full frame may contain points from more "
"than one original Livox scan (cross-scan queue). Per-point stamps are "
"therefore a candidate set, enumerated without preference.",
"curvature is the per-point offset in milliseconds. It brackets the "
"sampling instant but does not identify which raw return produced a "
"world point.",
"A classification change across the envelope is recorded as an "
"observation. It is not used to select a verdict, because a millimetre "
"near a face is enough to flip it.",
"Raw-frame classification involves no transform at all, so it is immune "
"to the inverse-transform error. On a static bag the same bodywork is "
"re-measured every scan, so cross-scan association is expected to be "
"largely ambiguous; that limits linking, not the raw measurement.",
"raw_body_roi restricts 'outside the envelope' to returns within "
"BODY_ROI_MARGIN_M of the bodywork. Whole-scene counts include walls and "
"steps and are reported for completeness only, never as evidence.",
"This tool only reports geometry. It does not decide whether any crop "
"should be widened, and it does not modify the running filter.",
]
if report["geometry"]["baseline_differences"]:
limits.append(
"The config differs from the documented baseline "
f"({len(report['geometry']['baseline_differences'])} key(s)); "
"numbers above use the config, not the document.")
return limits
def _percentiles(values) -> dict:
if not values:
return {"count": 0}
arr = np.asarray(values, dtype=np.float64)
return {
"count": int(arr.size),
"p50": float(np.quantile(arr, 0.5)),
"p95": float(np.quantile(arr, 0.95)),
"max": float(arr.max()),
}
def analyze_bag(bag_dir: Path, geometry: dict) -> dict:
"""Read the bag and produce the full report dict.
Streaming on purpose: scans are classified one at a time and only a thin
shell near the envelope is retained, so memory stays bounded by the number
of scans rather than by the number of points.
"""
bag_dir = Path(bag_dir)
meta = read_metadata(bag_dir)
if meta["storage_identifier"] not in ("sqlite3", ""):
raise BagProblem(
f"unsupported storage '{meta['storage_identifier']}' in {bag_dir}; "
"only rosbag2 sqlite3 is supported")
types = dict(meta["topics"])
# A shard passed directly has no metadata, so read the type from sqlite.
# This needs only sqlite, not the ROS Python bindings.
if not types:
conn = _open_shard(meta["files"][0])
try:
types = {name: kind for name, (_, kind) in
_topic_ids(conn, meta["files"][0]).items()}
finally:
conn.close()
missing_topics = [t for t in REQUIRED_TOPICS if t not in types]
report = {
"schema_version": SCHEMA_VERSION,
"tool": {"name": "analyze_self_boundary", "version": TOOL_VERSION},
"evidence_grade": {
"verdicts": ["undetermined", "no_raw_outside_returns",
"raw_outside_measured_unlinked",
"anomaly_candidates_unattributed"],
"confirmed_causes": [],
"note": "this tool reports observations; it does not confirm causes. "
"raw_outside_measured_unlinked is a direct measurement of "
"the raw cloud (no transform applied) with the cause left "
"open. See limits for what observed_motion_scale and "
"heuristic_nearest do and do not support.",
},
"geometry": {
"config_path": geometry["config_path"],
"envelope_optical_frame": {
"x_front": geometry["self_front"], "x_rear": geometry["self_rear"],
"y_left": geometry["self_left"], "y_right": geometry["self_right"],
"z_min": geometry["self_z_min"], "z_max": geometry["self_z_max"],
},
"boundary_guard": geometry["boundary_guard"],
"lidar_to_imu_translation": geometry["lidar_to_imu_translation"].tolist(),
"baseline_differences": geometry["baseline_differences"],
"note": "guard is lateral only, matching core.classify_self_returns",
},
"bag": {
"path": str(bag_dir.resolve()),
"storage": meta["storage_identifier"],
"shards": [str(Path(f).name) for f in meta["files"]],
"topics": types,
"metadata_present": meta["metadata_present"],
},
"time_tolerances": {
"pose_match_s": DEFAULT_POSE_TIME_TOL,
"pose_gap_warn_s": DEFAULT_POSE_GAP_WARN,
"pose_stale_s": DEFAULT_POSE_STALE,
"association_time_s": DEFAULT_ASSOC_TIME_TOL,
"association_xyz_m": DEFAULT_ASSOC_XYZ_TOL,
"association_tie_margin_m": DEFAULT_ASSOC_TIE_MARGIN,
"candidate_frame_radius": CANDIDATE_FRAME_RADIUS,
"comparison_screening_floor_m": COMPARISON_SCREENING_M,
"comparison_screening_note": (
"provisional floor for residual screening only. NOT an "
"acceptance tolerance and NOT a verified noise bound; a raw "
"return and its world copy share the same measurement, so "
"sensor noise cancels between them. Reported separately from "
"the per-frame observed motion scale."),
},
}
if missing_topics:
report["status"] = "incomplete"
report["missing_topics"] = missing_topics
report["conclusion"] = "undetermined"
report["conclusion_reason"] = (
"required topic(s) absent: " + ", ".join(missing_topics) +
". Without the raw Livox topic the raw-frame out-of-envelope "
"returns cannot be separated from world-cloud compensation "
"residuals.")
report["limits"] = [
"No raw classification was possible, so evidence class 'raw' is empty.",
"World-cloud points alone cannot distinguish a real out-of-envelope "
"return from a motion-compensation residual.",
]
raise MissingTopic(report)
# Only now are the ROS bindings required: up to this point everything was
# metadata and sqlite, which keeps the failure modes separable.
deserialize_message, get_message = _load_ros_bindings()
# ---- poses -----------------------------------------------------------
pose_times, pose_pos, pose_quat, pose_meta = _collect_poses(
meta["files"], types[TOPIC_POSE], deserialize_message, get_message)
if len(pose_times) == 0:
raise MissingTopic({**report, "status": "incomplete",
"missing_topics": [TOPIC_POSE],
"conclusion": "undetermined",
"conclusion_reason": f"{TOPIC_POSE} present but yielded no valid pose"})
poses = PoseIndex(pose_times, pose_pos, pose_quat)
report["data_integrity"] = {
"pose_messages": pose_meta["messages"],
"usable_poses": len(poses),
"invalid_quaternion_skipped": pose_meta["invalid_quaternion_skipped"],
"pose_time_regressions": poses.regressions,
"pose_max_gap_s": poses.max_gap,
"pose_time_range_ns": [int(pose_times.min()), int(pose_times.max())],
}
# ---- raw -------------------------------------------------------------
frames, raw_meta = _scan_raw(
meta["files"], geometry, deserialize_message, get_message,
types[TOPIC_RAW], DEFAULT_SHELL_MARGIN)
if not frames:
raise MissingTopic({**report, "status": "incomplete",
"missing_topics": [TOPIC_RAW],
"conclusion": "undetermined",
"conclusion_reason": f"{TOPIC_RAW} present but contained no frames"})
frame_bases = np.array([f["timebase_ns"] for f in frames], dtype=np.int64)
report["data_integrity"].update({
"raw_scans": raw_meta["scans"],
"raw_points": raw_meta["points"],
"raw_invalid_points_skipped": raw_meta["invalid_points_skipped"],
"raw_scan_time_range_ns": [int(frame_bases.min()), int(frame_bases.max())],
})
report["statistics"] = {
"raw_whole_scene_classification": raw_meta["raw_classified"],
"raw_whole_scene_note": (
"classified directly in the optical frame, no transform applied; "
"this count includes walls, steps and furniture and is NOT the "
"diagnostic basis"),
"raw_body_roi": raw_meta["raw_body_roi"],
"raw_body_roi_note": (
"only returns within BODY_ROI_MARGIN_M of the bodywork; "
"beyond_solid_envelope includes the 2 cm guard band, "
"beyond_guard_band is the stricter subset"),
# kept for backwards compatibility with earlier reports/tests
"raw_frame_classification": raw_meta["raw_classified"],
}
# ---- world -----------------------------------------------------------
world = {
"scans": 0, "points": 0,
"out_of_envelope": 0, "in_boundary_band": 0, "inside": 0,
"pose_undetermined": 0, "classification_samples": 0,
"association": {"heuristic_nearest": 0, "ambiguous": 0, "unmatched": 0},
"decisions": {},
"pose_dt_s": [], "residual_m": [], "residual_max_m": [], "scale_m": [],
"threshold_m": [], "world_excess_m": [],
"nearest_margin_m": [], "candidate_scans": [], "candidate_times": [],
"classification_changed": 0, "incomplete_evidence": 0,
"classification_inconsistent": 0,
}
csv_rows = []
samples = []
translation = geometry["lidar_to_imu_translation"]
curvature_present = True
pool_cache = {}
scan_window_ns = estimate_scan_window_ns(frames)
for path in meta["files"]:
conn = _open_shard(path)
try:
ids = _topic_ids(conn, path)
if TOPIC_WORLD not in ids:
continue
tid, kind = ids[TOPIC_WORLD]
cls = get_message(kind or types[TOPIC_WORLD])
for (blob,) in conn.execute(
"SELECT data FROM messages WHERE topic_id=? ORDER BY timestamp", (tid,)):
msg = deserialize_message(blob, cls)
columns = cloud_fields(msg)
if not all(k in columns for k in ("x", "y", "z")):
raise BagProblem(
f"{TOPIC_WORLD} lacks x/y/z fields; got {sorted(columns)}")
xyz_all = np.column_stack(
[columns["x"], columns["y"], columns["z"]]).astype(np.float64)
finite = np.isfinite(xyz_all).all(axis=1)
if not finite.any():
continue
xyz = xyz_all[finite]
world["scans"] += 1
world["points"] += len(xyz)
stamp_ns = _stamp_ns(msg.header.stamp)
index = int(np.argmin(np.abs(frame_bases - stamp_ns)))
indices = candidate_frame_indices(frames, index)
if "curvature" in columns:
curvature = columns["curvature"][finite].astype(np.float64)
else:
curvature_present = False
curvature = np.zeros(len(xyz), dtype=np.float64)
offset_ns = np.rint(curvature * 1e6).astype(np.int64)
# Enumerate every admissible sampling assumption. No single
# assumption is preferred; each yields its own pose and its own
# optical-frame position for the same world point.
options = candidate_pose_options(
pose_times, poses.valid, frame_bases, offset_ns, indices,
DEFAULT_POSE_TIME_TOL, stamp_ns, scan_window_ns)
usable_any = np.zeros(len(xyz), dtype=bool)
for option in options:
usable_any |= option["usable"]
world["pose_undetermined"] += int((~usable_any).sum())
if not usable_any.any():
continue
# Invert under every assumption and take the union of the
# classifications: a point counts as interesting if it is at or
# beyond the envelope under ANY admissible reading. Erring
# towards keeping evidence, never towards dropping it.
local_by_option = []
outside_any = np.zeros(len(xyz), dtype=bool)
boundary_any = np.zeros(len(xyz), dtype=bool)
first_position = np.full_like(xyz, np.nan)
excess_best = np.full(len(xyz), -np.inf)
axis_best = np.zeros(len(xyz), dtype=int)
positive_best = np.zeros(len(xyz), dtype=bool)
distance_best = np.full(len(xyz), np.inf)
for option in options:
local = np.full_like(xyz, np.nan)
members_index = np.where(option["usable"])[0]
for pi in np.unique(option["pose_index"][members_index]):
if int(pi) < 0:
continue
members = members_index[
option["pose_index"][members_index] == int(pi)]
rotation = rotation_from_quaternion(pose_quat[int(pi)])
local[members] = (xyz[members] - pose_pos[int(pi)]) \
@ rotation - translation
local_by_option.append(local)
if len(members_index) == 0:
continue
unseen = np.isnan(first_position[members_index, 0])
first_position[members_index[unseen]] = \
local[members_index[unseen]]
classified = classify_envelope(local[members_index], geometry)
outside_any[members_index] |= classified["outside"]
boundary_any[members_index] |= classified["boundary"]
world["classification_samples"] += int(len(members_index))
# Keep the largest excess seen under any assumption, with
# its direction. This is the conservative description of
# how far out the point could be.
better = classified["excess"] > excess_best[members_index]
rows = members_index[better]
excess_best[rows] = classified["excess"][better]
axis_best[rows] = classified["axis"][better]
positive_best[rows] = classified["positive"][better]
distance_best[rows] = classified["distance_to_box"][better]
# Counted per point on the union, not per assumption: the same
# point outside under three readings is still one point.
world["out_of_envelope"] += int(outside_any.sum())
world["in_boundary_band"] += int(
(boundary_any & ~outside_any).sum())
world["inside"] += int((~outside_any & ~boundary_any).sum())
world_labels = np.full(len(xyz), "inside", dtype=object)
world_labels[boundary_any] = "boundary"
world_labels[outside_any] = "outside"
lo_ns = int(frame_bases[index] - frames[index]["duration_ns"])
hi_ns = int(frame_bases[index] + frames[index]["duration_ns"])
window = np.where((pose_times >= lo_ns) & (pose_times <= hi_ns))[0]
if len(window) == 0:
window = np.array([int(np.argmin(np.abs(pose_times - stamp_ns)))])
motion_scale = observed_motion_scale(
pose_pos[window], pose_quat[window], xyz)
threshold = comparison_threshold(motion_scale)
# Same ROI rule as the raw side: a wall metres away is trivially
# outside a 0.81x0.80 m box and is not evidence about the body.
near_body = distance_best <= BODY_ROI_MARGIN_M
interesting = np.where((outside_any | boundary_any) & near_body)[0]
if len(interesting) == 0:
continue
key = (indices[0], indices[-1])
if key not in pool_cache:
pool_cache.clear()
pool_cache[key] = association_pool(frames, indices)
pool = pool_cache[key]
for i in interesting:
option_times = []
option_points = []
valid_assumptions = 0
invalid_assumptions = 0
labels_seen = []
excess_seen = []
for slot, option in enumerate(options):
# A scan outside the frame's time window is not a
# candidate at all; it must not be counted as evidence
# that failed to resolve.
if not option["in_window"][i]:
continue
if not option["usable"][i]:
invalid_assumptions += 1
continue
position = local_by_option[slot][i]
valid_assumptions += 1
option_times.append(int(option["time_ns"][i]))
option_points.append(position)
single = classify_envelope(position.reshape(1, 3), geometry)
labels_seen.append(str(envelope_label(single)[0]))
excess_seen.append(float(single["excess"][0]))
# Evidence is incomplete whenever an admissible assumption
# could not be evaluated: the candidate set was not fully
# searched, so no claim may be stronger than "inconclusive".
evidence_complete = (invalid_assumptions == 0
and valid_assumptions > 0)
classification_consistent = len(set(labels_seen)) <= 1
quality, hit, diag = resolve_association_multi(
option_times, option_points, pool,
DEFAULT_ASSOC_TIME_TOL, DEFAULT_ASSOC_XYZ_TOL)
world["association"][quality] += 1
world["pose_dt_s"].append(
float(max(option["dt_s"][i] for option in options)))
world["scale_m"].append(float(motion_scale))
world["threshold_m"].append(float(threshold))
world["world_excess_m"].append(float(excess_best[i]))
world["candidate_times"].append(len(option_times))
if math.isfinite(diag["margin"]):
world["nearest_margin_m"].append(float(diag["margin"]))
world["candidate_scans"].append(diag["candidate_scans"])
if not evidence_complete:
world["incomplete_evidence"] += 1
if not classification_consistent:
world["classification_inconsistent"] += 1
raw_outside = None
residual_min = diag["residual_min"]
changed = False
if hit is not None:
raw_outside = bool(pool["outside"][hit])
world["residual_m"].append(float(diag["residual_min"]))
world["residual_max_m"].append(float(diag["residual_max"]))
# A label change is a recorded observation only. It is
# never used to select the decision.
changed = str(pool["labels"][hit]) != str(world_labels[i])
if changed:
world["classification_changed"] += 1
decision = _decide(quality=quality, residual_min=residual_min,
observed_scale=motion_scale,
threshold=threshold,
world_outside=bool(outside_any[i]),
evidence_complete=evidence_complete)
world["decisions"][decision] = \
world["decisions"].get(decision, 0) + 1
times = option_times
span_ms = ""
if len(times) > 1:
span_ms = f"{(max(times) - min(times)) / 1e6:.6f}"
row = {
"source": "world",
"point_time_ns": "",
"candidate_time_count": str(len(option_times)),
"candidate_time_span_ms": span_ms,
"assumptions_valid": str(valid_assumptions),
"assumptions_invalid": str(invalid_assumptions),
"evidence_complete": "yes" if evidence_complete else "no",
"curvature_ms": f"{curvature[i]:.6f}",
"x_m": f"{first_position[i][0]:.6f}",
"y_m": f"{first_position[i][1]:.6f}",
"z_m": f"{first_position[i][2]:.6f}",
"outside_axis": _direction_label(
int(axis_best[i]), bool(positive_best[i])),
"excess_min_m": _fmt(min(excess_seen)) if excess_seen else "",
"excess_max_m": _fmt(max(excess_seen)) if excess_seen else "",
"classification_consistent": "yes" if classification_consistent else "no",
"distance_to_box_m": _fmt(distance_best[i]),
"match_quality": quality,
"residual_min_m": _fmt(diag["residual_min"]),
"residual_max_m": _fmt(diag["residual_max"]),
"nearest_dist_m": _fmt(diag["nearest_dist"]),
"second_dist_m": _fmt(diag["second_dist"]),
"nearest_margin_m": _fmt(diag["margin"]),
"candidate_scans": str(diag["candidate_scans"]),
"pose_dt_s": f"{float(max(option['dt_s'][i] for option in options)):.6f}",
"observed_motion_scale_m": f"{float(motion_scale):.6f}",
"comparison_threshold_m": f"{float(threshold):.6f}",
"classification_changed": "yes" if changed else "no",
"decision": decision,
"reason": _reason(decision, diag),
}
if len(csv_rows) < MAX_CSV_ROWS:
csv_rows.append(row)
elif len(samples) < MAX_SAMPLE_ROWS:
samples.append(row)
finally:
conn.close()
# ---- raw boundary rows (evidence class 1) ----------------------------
raw_rows = 0
for frame in frames:
selected = np.where(frame["boundary"] | frame["outside"])[0]
if len(selected) == 0:
continue
for i in selected:
if len(csv_rows) >= MAX_CSV_ROWS:
break
csv_rows.append({
"source": "raw",
"point_time_ns": str(int(frame["times_ns"][i])),
"candidate_time_count": "1",
"candidate_time_span_ms": "",
"curvature_ms": "",
"x_m": f"{frame['points'][i][0]:.6f}",
"y_m": f"{frame['points'][i][1]:.6f}",
"z_m": f"{frame['points'][i][2]:.6f}",
"outside_axis": _direction_label(
int(frame["axis"][i]), bool(frame["positive"][i])),
"outside_dist_m": f"{float(frame['excess'][i]):.6f}",
"distance_to_box_m": f"{float(frame['distance_to_box'][i]):.6f}",
"assumptions_valid": "", "assumptions_invalid": "",
"evidence_complete": "",
"match_quality": "n/a",
"excess_min_m": f"{float(frame['excess'][i]):.6f}",
"excess_max_m": f"{float(frame['excess'][i]):.6f}",
"classification_consistent": "",
"residual_min_m": "", "residual_max_m": "",
"nearest_dist_m": "", "second_dist_m": "",
"nearest_margin_m": "", "candidate_scans": "",
"pose_dt_s": "", "observed_motion_scale_m": "",
"comparison_threshold_m": "",
"classification_changed": "",
"decision": "raw_only_in_boundary_band"
if frame["boundary"][i] else "raw_outside_envelope",
"reason": "classified directly in the optical frame; no transform",
})
raw_rows += 1
report["statistics"]["world_inverse_classification"] = {
"points": world["points"], "inside": world["inside"],
"in_boundary_band": world["in_boundary_band"],
"out_of_envelope": world["out_of_envelope"],
"curvature_field_present": curvature_present,
"note": "inverse transform uses the recorded pose at each point's own instant",
}
report["statistics"]["pose_assignment"] = {
"points_with_no_usable_assumption": world["pose_undetermined"],
"classification_samples": world["classification_samples"],
"pairs_with_incomplete_evidence": world["incomplete_evidence"],
"pairs_with_inconsistent_classification": world["classification_inconsistent"],
"note": "every admissible sampling assumption is enumerated separately "
"and none is preferred; no agreement between assumptions is "
"required. Evidence is marked incomplete when any admissible "
"assumption lacked a usable pose.",
}
report["statistics"]["association"] = {
**world["association"],
"note": "heuristic_nearest ranks by distance inside the candidate set; "
"it does not confirm same-source correspondence",
}
report["statistics"]["association_quality"] = {
"candidate_scans": _percentiles(world["candidate_scans"]),
"candidate_times": _percentiles(world["candidate_times"]),
"nearest_margin_m": _percentiles(world["nearest_margin_m"]),
}
report["statistics"]["decisions"] = world["decisions"]
report["statistics"]["classification_changed_pairs"] = \
world["classification_changed"]
report["statistics"]["observation_note"] = (
"classification_changed counts pairs that fall on different sides of "
"the envelope in the raw and inverse-transformed clouds. It is an "
"observation and is never used to select a decision.")
report["statistics"]["csv_rows"] = len(csv_rows)
report["statistics"]["raw_rows_written"] = raw_rows
if world["pose_dt_s"]:
report["statistics"]["pose_dt_summary"] = _percentiles(world["pose_dt_s"])
if world["residual_m"]:
report["statistics"]["residual_summary"] = {
"residual_min": _percentiles(world["residual_m"]),
"residual_max": _percentiles(world["residual_max_m"]),
"note": "residual_min is the most favourable admissible reading and "
"is the only one used to test the observed motion scale",
}
if world["scale_m"]:
# Reported apart on purpose: one is measured motion, the other is a
# provisional assumption. Merging them would hide which one decided.
report["statistics"]["observed_motion_scale_summary"] = {
**_percentiles(world["scale_m"]),
"note": "measured motion in the frame; no floor applied",
}
report["statistics"]["comparison_threshold_summary"] = {
**_percentiles(world["threshold_m"]),
"screening_floor_m": COMPARISON_SCREENING_M,
"note": "max(observed motion, provisional screening floor); a "
"residual below this was not screened, which is not the "
"same as being explained by motion",
}
if world["world_excess_m"]:
excess = np.asarray(world["world_excess_m"], dtype=np.float64)
report["statistics"]["world_excess_summary"] = {
"count": int(excess.size),
"p50_m": float(np.quantile(excess, 0.5)),
"p95_m": float(np.quantile(excess, 0.95)),
"max_m": float(excess.max()),
"count_over_5mm": int(np.sum(excess > 0.005)),
"count_over_10mm": int(np.sum(excess > 0.010)),
"count_over_13mm": int(np.sum(excess > 0.013)),
"count_over_20mm": int(np.sum(excess > 0.020)),
"note": "how far world points sit outside the envelope, independent "
"of the residual screening threshold; this keeps small "
"excursions visible when screening does not trigger",
}
report["samples"] = samples or csv_rows[:MAX_SAMPLE_ROWS]
report["conclusion"], report["conclusion_reason"] = _conclude(report)
report["limits"] = _limits(report)
report["status"] = "complete"
return {**report, "_csv_rows": csv_rows}
def _fmt(value) -> str:
if value is None:
return ""
if isinstance(value, float) and not math.isfinite(value):
return "inf" if value > 0 else "-inf"
return f"{float(value):.6f}"
# --------------------------------------------------------------------------
# output
# --------------------------------------------------------------------------
CSV_FIELDS = [
"source", "point_time_ns", "candidate_time_count", "candidate_time_span_ms",
"assumptions_valid", "assumptions_invalid", "evidence_complete",
"curvature_ms", "x_m", "y_m", "z_m",
"outside_axis", "excess_min_m", "excess_max_m",
"classification_consistent", "distance_to_box_m",
"match_quality", "residual_min_m", "residual_max_m",
"nearest_dist_m", "second_dist_m", "nearest_margin_m",
"candidate_scans", "pose_dt_s", "observed_motion_scale_m",
"comparison_threshold_m", "classification_changed", "decision", "reason",
]
def write_report(report: dict, output_dir: Path) -> None:
"""Write summary.json and boundary_points.csv.
Callers must have already refused to overwrite; this function assumes the
directory is safe to write into. Existing files are never touched here.
"""
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
rows = report.get("_csv_rows", [])
payload = {k: v for k, v in report.items() if not k.startswith("_")}
summary_path = output_dir / "summary.json"
csv_path = output_dir / "boundary_points.csv"
for target in (summary_path, csv_path):
if target.exists():
raise PathProblem(
f"refusing to overwrite existing {target}; "
"pass --overwrite or choose another --output")
summary_path.write_text(
json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8")
with csv_path.open("w", newline="", encoding="utf-8") as handle:
writer = csv.DictWriter(handle, fieldnames=CSV_FIELDS)
writer.writeheader()
for row in rows:
writer.writerow({k: row.get(k, "") for k in CSV_FIELDS})
def main(argv=None) -> int:
parser = argparse.ArgumentParser(
description="Offline self-boundary diagnostic; read-only over a bag.")
parser.add_argument("--bag", type=Path, required=True,
help="bag directory containing metadata.yaml and shards")
parser.add_argument("--config", type=Path, required=True,
help="runtime config, e.g. config/flat_corridor.yaml")
parser.add_argument("--output", type=Path, required=True,
help="directory for summary.json and boundary_points.csv")
parser.add_argument("--overwrite", action="store_true",
help="allow replacing existing result files")
args = parser.parse_args(argv)
# Refuse before doing any work: an existing result set is never replaced
# silently, whether the run ends complete or incomplete.
existing = [p for p in (args.output / "summary.json",
args.output / "boundary_points.csv") if p.exists()]
if existing and not args.overwrite:
print(f"[error] refusing to overwrite {existing[0]}; pass --overwrite",
file=sys.stderr)
return EXIT_MISSING
if args.overwrite:
for target in existing:
target.unlink()
try:
geometry = load_geometry(args.config)
report = analyze_bag(args.bag, geometry)
except PathProblem as exc:
print(f"[error] {exc}", file=sys.stderr)
return EXIT_MISSING
except BagProblem as exc:
print(f"[error] {exc}", file=sys.stderr)
return EXIT_INCOMPATIBLE
except MissingTopic as exc:
partial = exc.args[0] if exc.args else {}
if not isinstance(partial, dict):
print(f"[error] {partial}", file=sys.stderr)
return EXIT_MISSING
print(f"[error] {partial.get('conclusion_reason')}", file=sys.stderr)
# A partial report is still written: the missing evidence is itself the
# finding, and the exit code stays 2 so automation cannot mistake it
# for a completed diagnosis.
try:
write_report(partial, args.output)
except (PathProblem, OSError) as write_error:
print(f"[error] {write_error}", file=sys.stderr)
return EXIT_MISSING
try:
write_report(report, args.output)
except PathProblem as exc:
print(f"[error] {exc}", file=sys.stderr)
return EXIT_MISSING
except OSError as exc:
print(f"[error] cannot write results to {args.output}: {exc}", file=sys.stderr)
return EXIT_INCOMPATIBLE
print(json.dumps({
"status": report["status"],
"conclusion": report["conclusion"],
"reason": report["conclusion_reason"],
"output": str(args.output),
}, indent=2, ensure_ascii=False))
return EXIT_OK
if __name__ == "__main__":
try:
sys.exit(main())
except SystemExit:
raise
except Exception: # never report success on an unexpected failure
traceback.print_exc()
print("[error] internal failure; see traceback above", file=sys.stderr)
sys.exit(EXIT_INCOMPATIBLE)