docs(minco_ws): B 线诊断与方案文档,附只读分析脚本

文档:B 线从基线到矩形静止验收的完整记录(BASELINE_*、RECTANGLE_IMPLEMENTATION、
SELF_FILTER_AND_STATIC_ANALYSIS 等 8 篇),方案 C/四的交接提示词,
以及 NAVIGATION_SOLUTION.md 的更新。

diagnostics/ 新增三个只读分析脚本,其中两处是**撤回**先前结论:
- analyze_map_acceptance.py(rev 2)撤回「0.62 m 圆形膨胀解释了车体中心被占据」
  ——真实模型是旋转矩形(SAT)+ 上下分别膨胀,圆形只是数字凑巧吻合;
  同时撤回「3.65 m 连续面封住前方 3.7–4.0 m」,那是跨 x、z 投影后聚类的产物。
- analyze_pose_jitter.py 明确「累积路径长度不得称为漂移」:42 s 静止录包
  路径积分 20.76 m,而 XYZ 包络仅约 5/4.8/9.3 cm,两者不矛盾。

脚本均为只读:不开节点、不回放、不发布,不决定因果,源码事实/数据观察/
待验证假设分字段输出。
This commit is contained in:
walunt5
2026-11-05 11:59:34 +08:00
parent c04c671a20
commit 2ce0d1e9bf
20 changed files with 7400 additions and 18 deletions
@@ -0,0 +1,415 @@
#!/usr/bin/python3
"""Read-only map acceptance for a static bag (revision 2).
Revision 2 withdraws two earlier claims:
* "a 0.62 m circular inflation explains the occupied body centre" -- the
active model is a ROTATED RECTANGLE footprint (SAT test) with separate up /
down z inflation. The circular story was wrong even though the numbers
happened to fit.
* "a 3.65 m continuous surface closes the path 3.7-4.0 m ahead" -- that came
from clustering cells after projecting across x and z. Cross-sections are
now reported independently, at the query height only.
Questions answered:
1. how many frames have the cell at the body-centre height occupied?
2. which raw cells can geometrically cover the body centre, given the real
footprint, its orientation and the up/down inflation range? Reported as
CANDIDATES; no unique cause is claimed.
3. what do independent cross-sections at the query height look like 3.7-4.0 m
ahead, in raw and inflated layers separately?
Rules honoured: an absent cell is "not observed / not inflated", never free;
the display height band is a viewing choice, not a measured body half height;
nothing here claims which physical surface produced a return.
"""
from __future__ import annotations
import argparse
import json
import math
import sys
from collections import Counter
from pathlib import Path
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parent))
import analyze_pose_jitter as pj # load_odom, read_metadata
import analyze_self_boundary as sb # cloud_fields, _stamp_ns
CELL = 0.05
ODOM_MATCH_TOL_S = 0.030
# From planner_vehicle.yaml (z up/down) and the bringup footprint measurement.
# rebuildInflationOffsets() takes the rectangle branch, so the inflation shape is
# the padded footprint, not a disc.
FOOTPRINT_LENGTH = 0.81
FOOTPRINT_WIDTH = 0.80
FOOTPRINT_MARGIN = 0.09
FOOTPRINT_YAW_TOL = 0.035
Z_UP = 0.15
Z_DOWN = 0.05
FORWARD_XS = (3.70, 3.80, 3.90, 4.00)
QUERY_HALF_Z = CELL / 2 + 1e-9
def yaw_from_quat(q):
x, y, z, w = q
return math.atan2(2.0 * (w * z + x * y), 1.0 - 2.0 * (y * y + z * z))
def rect_intersects(x, y, yaw, half_length, half_width, cell_half):
"""Same SAT test as plan_env/rectangular_footprint.h."""
c, s = math.cos(yaw), math.sin(yaw)
ac, as_ = abs(c), abs(s)
return (abs(x) <= half_length * ac + half_width * as_ + cell_half + 1e-10 and
abs(y) <= half_length * as_ + half_width * ac + cell_half + 1e-10 and
abs(c * x + s * y) <= half_length + cell_half * (ac + as_) + 1e-10 and
abs(-s * x + c * y) <= half_width + cell_half * (ac + as_) + 1e-10)
def discrete_inflate_offsets(yaw, res):
"""The integer cell offsets md_.inflate_offsets_ would hold for this yaw.
rebuildInflationOffsets() loops over integer cells x, y in [-n, n], keeps the
ones whose SAT test hits, and for each keeps z in [-down, +up] cells. Marking
is therefore a discrete offset lookup, not continuous containment.
"""
a = 0.5 * FOOTPRINT_LENGTH + FOOTPRINT_MARGIN
b = 0.5 * FOOTPRINT_WIDTH + FOOTPRINT_MARGIN
pad = 2.0 * math.hypot(a, b) * math.sin(0.5 * min(abs(FOOTPRINT_YAW_TOL), math.pi))
n = int(math.ceil((math.hypot(a + pad, b + pad) + res) / res))
up = int(math.ceil(Z_UP / res))
down = int(math.ceil(Z_DOWN / res))
offsets = set()
for ix in range(-n, n + 1):
for iy in range(-n, n + 1):
if rect_intersects(ix * res, iy * res, yaw, a + pad, b + pad, res):
for iz in range(-down, up + 1):
offsets.add((ix, iy, iz))
return offsets, n, up, down, a + pad, b + pad, pad
def inflation_half_extents():
a = 0.5 * FOOTPRINT_LENGTH + FOOTPRINT_MARGIN
b = 0.5 * FOOTPRINT_WIDTH + FOOTPRINT_MARGIN
pad = 2.0 * math.hypot(a, b) * math.sin(0.5 * min(abs(FOOTPRINT_YAW_TOL), math.pi))
return a + pad, b + pad, pad
def load_cloud_frames(bag_dir: Path, topic: str):
meta = pj.read_metadata(bag_dir)
if topic not in meta["topics"]:
raise SystemExit(f"topic {topic} not in bag")
deserialize_message, get_message = pj._load_ros()
for path in meta["files"]:
conn = pj._open_shard(path)
try:
rows = conn.execute("SELECT id, name, type FROM topics").fetchall()
found = [(i, t) for i, n, t in rows if n == topic]
if not found:
continue
topic_id, kind = found[0]
cls = get_message(kind)
for (blob,) in conn.execute(
"SELECT data FROM messages WHERE topic_id=? ORDER BY timestamp",
(topic_id,)):
msg = deserialize_message(blob, cls)
f = sb.cloud_fields(msg)
xyz = np.column_stack([f["x"], f["y"], f["z"]]).astype(np.float64)
xyz = xyz[np.isfinite(xyz).all(axis=1)]
yield sb._stamp_ns(msg.header.stamp), xyz
finally:
conn.close()
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--bag", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
args.output.mkdir(parents=True, exist_ok=True)
odom = pj.load_odom(args.bag, "/body_odom")
stamps = np.asarray(odom["stamp_ns"], dtype=np.int64)
order = np.argsort(stamps)
stamps = stamps[order]
pos = np.asarray(odom["position"], dtype=np.float64)[order]
quat = np.asarray(odom["quaternion"], dtype=np.float64)[order]
yaws = np.array([yaw_from_quat(q) for q in quat])
def nearest_odom(stamp):
i = int(np.searchsorted(stamps, stamp))
best = None
for cand in (i - 1, i, i + 1):
if 0 <= cand < len(stamps):
gap = abs(int(stamps[cand]) - int(stamp)) / 1e9
if gap <= ODOM_MATCH_TOL_S and (best is None or gap < best[0]):
best = (gap, cand)
return best
inflate_frames = list(load_cloud_frames(args.bag, "/grid_map/occupancy_inflate"))
raw_by_stamp = dict(load_cloud_frames(args.bag, "/grid_map/occupancy"))
raw_stamps = np.asarray(sorted(raw_by_stamp), dtype=np.int64)
def nearest_raw(stamp, tol_s=0.25):
if raw_stamps.size == 0:
return None
i = int(np.searchsorted(raw_stamps, stamp))
best = None
for cand in (i - 1, i, i + 1):
if 0 <= cand < len(raw_stamps):
gap = abs(int(raw_stamps[cand]) - int(stamp)) / 1e9
if gap <= tol_s and (best is None or gap < best[0]):
best = (gap, int(raw_stamps[cand]))
return None if best is None else best
half_len, half_wid, pad = inflation_half_extents()
matched = 0
occupied = 0
centre_z = []
candidate_sides = Counter()
frames_with_candidates = 0
candidate_counts = []
candidate_xy = []
samples = []
for stamp, infl in inflate_frames:
hit = nearest_odom(stamp)
if hit is None:
continue
matched += 1
centre = pos[hit[1]]
yaw = yaws[hit[1]]
centre_z.append(float(centre[2]))
same_xy = (np.abs(infl[:, 0] - centre[0]) <= CELL / 2 + 1e-9) & \
(np.abs(infl[:, 1] - centre[1]) <= CELL / 2 + 1e-9)
same_z = np.abs(infl[:, 2] - centre[2]) <= QUERY_HALF_Z
if not (same_xy & same_z).any():
continue
occupied += 1
near = nearest_raw(stamp)
if near is None:
samples.append({"stamp_ns": int(stamp), "candidates": None})
continue
raw = raw_by_stamp[near[1]]
offsets = discrete_inflate_offsets(yaw, CELL)[0]
# centre_cell = raw_cell + offset, so the offset that would produce the
# body-centre cell from this raw cell is (centre - raw) / resolution.
idx = np.rint((centre[None, :] - raw) / CELL).astype(np.int64)
inside = np.fromiter(
(tuple(v) in offsets for v in idx), dtype=bool, count=len(raw))
cand = raw[inside]
candidate_counts.append(len(cand))
if len(cand):
frames_with_candidates += 1
c, s = math.cos(yaw), math.sin(yaw)
bx = c * (cand[:, 0] - centre[0]) + s * (cand[:, 1] - centre[1])
by = -s * (cand[:, 0] - centre[0]) + c * (cand[:, 1] - centre[1])
candidate_xy.extend(zip(bx.tolist(), by.tolist()))
for x_b in bx:
if x_b < -0.5 * FOOTPRINT_LENGTH:
candidate_sides["rear"] += 1
elif x_b > 0.5 * FOOTPRINT_LENGTH:
candidate_sides["front"] += 1
else:
candidate_sides["lateral_or_under"] += 1
if len(samples) < 30:
samples.append({
"stamp_ns": int(stamp),
"raw_stamp_gap_s": near[0],
"candidates": int(len(cand)),
"candidate_body_xy": np.round(
np.column_stack([bx, by]), 3).tolist()[:8],
})
# ---- independent cross-sections --------------------------------------
cross = {}
last_stamp = inflate_frames[-1][0]
hit = nearest_odom(last_stamp)
if hit is not None:
centre = pos[hit[1]]
yaw = yaws[hit[1]]
near = nearest_raw(last_stamp)
raw = raw_by_stamp[near[1]] if near else np.zeros((0, 3))
infl = inflate_frames[-1][1]
c, s = math.cos(yaw), math.sin(yaw)
def to_body(arr):
dx = arr[:, 0] - centre[0]
dy = arr[:, 1] - centre[1]
return np.column_stack([c * dx + s * dy, -s * dx + c * dy, arr[:, 2]])
body_raw = to_body(raw) if len(raw) else np.zeros((0, 3))
body_infl = to_body(infl)
body_raw = body_raw[np.abs(body_raw[:, 2] - centre[2]) <= QUERY_HALF_Z]
body_infl = body_infl[np.abs(body_infl[:, 2] - centre[2]) <= QUERY_HALF_Z]
for x0 in FORWARD_XS:
sel_r = body_raw[np.abs(body_raw[:, 0] - x0) <= CELL / 2 + 1e-9]
sel_i = body_infl[np.abs(body_infl[:, 0] - x0) <= CELL / 2 + 1e-9]
cross[f"{x0:.2f}"] = {
"raw_y": sorted({round(float(v), 2) for v in sel_r[:, 1]}),
"inflate_y": sorted({round(float(v), 2) for v in sel_i[:, 1]}),
"raw_count": int(len(sel_r)),
"inflate_count": int(len(sel_i)),
}
summary = {
"revision": 3,
"superseded_approximations": {
"note": "candidate counts reported before this revision used "
"continuous containment and a 0.80 m length; they are "
"approximate and are replaced by the discrete-offset numbers "
"below",
"old_candidate_count_p50": 3,
"old_candidate_count_max": 7,
"old_total_candidates": 2139,
},
"withdrawn": [
"0.62 m circular inflation explains the occupied body centre",
"a 3.65 m continuous surface closes the path 3.7-4.0 m ahead",
],
"bag": str(args.bag),
"model": {
"source": "plan_env/src/grid_map.cpp rebuildInflationOffsets() "
"rectangle branch; plan_env/rectangular_footprint.h",
"footprint_length_m": FOOTPRINT_LENGTH,
"footprint_width_m": FOOTPRINT_WIDTH,
"footprint_margin_m": FOOTPRINT_MARGIN,
"footprint_yaw_tolerance_rad": FOOTPRINT_YAW_TOL,
"angular_padding_m": pad,
"inflate_half_extents_m": [half_len, half_wid],
"marking_rule": "discrete integer cell offsets computed by the same "
"SAT loop as rebuildInflationOffsets(); membership "
"test, not continuous containment",
"z_up_m": Z_UP,
"z_down_m": Z_DOWN,
},
"query": {
"cell_size_m": CELL,
"body_centre_height_m": {
"p05": float(np.quantile(centre_z, 0.05)) if centre_z else None,
"p50": float(np.quantile(centre_z, 0.50)) if centre_z else None,
"p95": float(np.quantile(centre_z, 0.95)) if centre_z else None,
},
"occupied_test": "inflated cell within one cell of the body-centre XY "
"and in the same z layer",
},
"q1_body_centre": {
"inflate_messages": len(inflate_frames),
"matched_to_body_odom": matched,
"occupied_frames": occupied,
"occupied_fraction": (occupied / matched) if matched else None,
},
"q2_candidates": {
"rule": "raw cells whose offset falls inside the rotated footprint "
"and whose z lies in [centre_z - z_up, centre_z + z_down]",
"frames_with_footprint_candidates": frames_with_candidates,
"frames_checked": occupied,
"frames_without_any_candidate": occupied - frames_with_candidates,
"candidate_count_p50": float(np.median(candidate_counts))
if candidate_counts else None,
"candidate_count_max": int(max(candidate_counts)) if candidate_counts else None,
"candidate_body_xy_p50": [float(np.median([v[0] for v in candidate_xy])),
float(np.median([v[1] for v in candidate_xy]))]
if candidate_xy else None,
"candidate_body_xy_p05_p95": [
[float(np.quantile([v[0] for v in candidate_xy], 0.05)),
float(np.quantile([v[0] for v in candidate_xy], 0.95))],
[float(np.quantile([v[1] for v in candidate_xy], 0.05)),
float(np.quantile([v[1] for v in candidate_xy], 0.95))]]
if candidate_xy else None,
"side_counts": dict(candidate_sides),
"note": "candidate sources only; the map does not record which raw "
"cell produced a given inflated cell",
"samples": samples,
},
"q3_cross_sections": {
"rule": "independent slice at each x in the body frame, using only "
"cells at the body-centre z layer; no aggregation across x or z",
"sections": cross,
},
"limits": [
"An absent cell means not observed or not inflated, never free.",
"The z band used for viewing is a display choice; it is not a "
"measured body half height and it does not establish that the "
"ground was excluded.",
"The body centre height comes from /body_odom, which is an estimate.",
"Attribution lists candidates by geometry only.",
"The map is built with the estimator's own pose; a pose bias shifts "
"the map with it.",
],
}
(args.output / "summary.json").write_text(
json.dumps(summary, indent=2, ensure_ascii=False), encoding="utf-8")
print(json.dumps({k: summary[k] for k in ("q1_body_centre", "q2_candidates")},
indent=2, ensure_ascii=False))
print("cross-sections:", json.dumps(cross, ensure_ascii=False))
# ---- figure: query-height overhead + independent cross-sections -------
try:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
except Exception as exc: # pragma: no cover
print(f"[warn] matplotlib unavailable: {exc}", file=sys.stderr)
return 0
fig = plt.figure(figsize=(14, 8))
gs = fig.add_gridspec(1, 2, width_ratios=[1.5, 1.0])
ax = fig.add_subplot(gs[0, 0])
ax.scatter(body_raw[:, 0], body_raw[:, 1], s=9, c="#1f77b4",
label="raw (query height)")
ax.scatter(body_infl[:, 0], body_infl[:, 1], s=2, c="#d62728", alpha=0.30,
label="inflated (query height)")
ax.add_patch(plt.Rectangle((-0.5 * FOOTPRINT_LENGTH, -0.5 * FOOTPRINT_WIDTH),
FOOTPRINT_LENGTH, FOOTPRINT_WIDTH,
fill=False, ec="black", lw=1.5, label="footprint"))
for x0 in FORWARD_XS:
ax.axvline(x0, color="orange", ls="--", lw=0.8)
ax.set_xlim(-2, 5)
ax.set_ylim(-2.5, 3.5)
ax.set_xlabel("x forward [m]")
ax.set_ylabel("y left [m]")
ax.set_title("query-height slice (body frame)")
ax.grid(alpha=0.3)
ax.legend(fontsize=7, loc="upper right")
right = gs[0, 1].subgridspec(len(FORWARD_XS), 1, hspace=0.55)
for i, x0 in enumerate(FORWARD_XS):
s_ax = fig.add_subplot(right[i])
data = cross.get(f"{x0:.2f}", {})
raw_y = data.get("raw_y", [])
infl_y = data.get("inflate_y", [])
if raw_y:
s_ax.plot(raw_y, np.ones(len(raw_y)), "|", ms=12, color="#1f77b4")
if infl_y:
s_ax.plot(infl_y, np.full(len(infl_y), 0.4), "|", ms=12, color="#d62728")
s_ax.set_ylim(0, 1.3)
s_ax.set_yticks([1.0, 0.4])
s_ax.set_yticklabels(["raw", "infl"], fontsize=7)
s_ax.set_title(f"x = {x0:.2f} m raw {data.get('raw_count',0)} / "
f"inflated {data.get('inflate_count',0)}", fontsize=8)
s_ax.grid(alpha=0.25, axis="x")
if i == len(FORWARD_XS) - 1:
s_ax.set_xlabel("y left [m]")
else:
s_ax.set_xticklabels([])
fig.suptitle("Independent cross-sections at the body-centre height "
"(no cross-x or cross-z projection)")
fig.tight_layout()
fig.savefig(args.output / "cross_sections.png", dpi=140)
plt.close(fig)
print(f"figure -> {args.output / 'cross_sections.png'}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,960 @@
#!/usr/bin/python3
"""Offline analysis of pose jitter in a static recording.
Read-only: opens the bag with sqlite3, never starts a node, never plays the bag
back, never publishes. No ROS import is needed unless a bag is actually read.
WHAT THIS TOOL IS FOR
---------------------
On a 42 s static recording /aft_mapped_to_init accumulates about 20.76 m of
three-dimensional path while the total XYZ span is only ~5.1 / 4.8 / 9.3 cm.
Those two numbers are not in conflict: a path length counts every wiggle, a span
measures the envelope. **The cumulative increment must not be called drift.**
This tool separates the two, quantifies how the answer depends on the sampling
interval, and looks for structure in the wiggle.
It does not decide the cause. Source facts, data observations and open
hypotheses are reported in separate fields on purpose.
SOURCE FACTS (verified by reading the code, not assumed)
--------------------------------------------------------
`minco_ws/src/perception/Point-LIO/src/laserMapping.cpp`:
* publish_odometry() stamps the message with
`publish_odometry_without_downsample ? time_current : lidar_end_time`
(line ~526). `time_current` is a per-point instant inside the scan.
* The pose written by set_posestamp() is the *current filter state*
`kf_output` (line ~489-514, `use_imu_as_input` false).
* Publishing happens inside the point-by-point update loop when
`publish_odometry_without_downsample` is true (lines ~1243, ~1426),
otherwise once per scan at the end (line ~1512).
* frame_id "camera_init", child_frame_id "body" (lines 552-553).
* twist.linear is rotated into the body frame before publishing
(`vel_body`, lines ~618-625); angular is the filter's omg.
* A SensorTimeRateLimiter drops messages closer than 1/frequency in sensor
time, and re-publishes when sensor time goes backwards
(include/sensor_time_rate_limiter.h).
* get_ros_time() builds the stamp from a *double* second value and truncates
the fractional part to nanoseconds (include/common_lib.h ~206), so sub-
microsecond structure in the stamps is not meaningful.
`src/perception/Point-LIO/config/mid360.yaml` (the config used on the vehicle):
* publish_odometry_without_downsample: True
* publish_frequency_hz: 100
`minco_ws/src/scan/body_odom/body_odom/body_odom_node.py`:
* /body_odom is derived from /aft_mapped_to_init by a yaw-rotated planar
offset: p_body = p_imu + R(yaw) * (ox, oy), z adds oz directly.
* The orientation is REBUILT as a pure-yaw quaternion (x=y=0): roll and pitch
of the IMU pose are discarded.
* header is copied verbatim and twist is passed through unchanged.
Consequence: /body_odom and /aft_mapped_to_init differ by a known analytic
transform, so their difference can be checked rather than merely compared. And a
twist value from either topic is in the IMU/lidar body frame, not the chassis
centre frame, even after the position offset.
"""
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.0.0"
SCHEMA_VERSION = 1
DEFAULT_IMU_TOPIC = "/aft_mapped_to_init"
DEFAULT_BODY_TOPIC = "/body_odom"
DEFAULT_CLOUD_TOPIC = "/cloud_registered_full"
# Sampling intervals whose cumulative increment is reported. The point is to
# show that the number is a function of the interval, not a property of the run.
RESAMPLE_INTERVALS_MS = (50, 100, 200, 500, 1000)
# A consecutive increment counts as a jump when it exceeds both terms:
# median_step + JUMP_MAD_K * MAD (robust spread of the run itself)
# JUMP_FLOOR_M (never call sub-millimetre noise a jump)
JUMP_MAD_K = 6.0
JUMP_FLOOR_M = 0.005
MAX_EVENTS = 5000
EXIT_OK = 0
EXIT_INPUT = 2
EXIT_INCOMPATIBLE = 3
class InputProblem(Exception):
"""Bad path or argument; exit code 2."""
class BagProblem(Exception):
"""Corrupt bag or incompatible message; exit code 3."""
# --------------------------------------------------------------------------
# quaternion helpers (x, y, z, w -- the ROS field order)
# --------------------------------------------------------------------------
def yaw_from_quaternion(quaternion) -> float:
q = np.asarray(quaternion, dtype=np.float64)
x, y, z, w = q
siny = 2.0 * (w * z + x * y)
cosy = 1.0 - 2.0 * (y * y + z * z)
return math.atan2(siny, cosy)
def rotation_from_quaternion(quaternion) -> np.ndarray:
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 orientation")
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 angle_between_quaternions(a, b) -> float:
"""Rotation angle between two orientations, in radians."""
qa = np.asarray(a, dtype=np.float64)
qb = np.asarray(b, dtype=np.float64)
na, nb = np.linalg.norm(qa), np.linalg.norm(qb)
if na < 1e-6 or nb < 1e-6:
raise ValueError("invalid orientation")
dot = abs(float(np.dot(qa / na, qb / nb)))
return 2.0 * math.acos(min(1.0, max(-1.0, dot)))
def roll_pitch(quaternion) -> tuple:
"""Return (roll, pitch) in radians from a quaternion."""
x, y, z, w = np.asarray(quaternion, dtype=np.float64)
sinr = 2.0 * (w * x + y * z)
cosr = 1.0 - 2.0 * (x * x + y * y)
roll = math.atan2(sinr, cosr)
sinp = 2.0 * (w * y - z * x)
pitch = math.asin(min(1.0, max(-1.0, sinp)))
return roll, pitch
# --------------------------------------------------------------------------
# path statistics
# --------------------------------------------------------------------------
def _percentiles(values) -> dict:
arr = np.asarray(values, dtype=np.float64)
if arr.size == 0:
return {"count": 0}
return {
"count": int(arr.size),
"p05": float(np.quantile(arr, 0.05)),
"p50": float(np.quantile(arr, 0.50)),
"p95": float(np.quantile(arr, 0.95)),
"p99": float(np.quantile(arr, 0.99)),
"max": float(arr.max()),
}
def path_statistics(positions) -> dict:
"""Net displacement, span and cumulative increment, kept apart on purpose.
The cumulative increment is the sum of absolute consecutive steps: it counts
every wiggle and grows with sampling rate. The span is the bounding-box
extent. Reporting only the former invites calling jitter drift.
"""
pos = np.asarray(positions, dtype=np.float64).reshape((-1, 3))
if len(pos) < 2:
return {"count": int(len(pos))}
steps = np.linalg.norm(np.diff(pos, axis=0), axis=1)
net = pos[-1] - pos[0]
return {
"count": int(len(pos)),
"net_displacement_m": float(np.linalg.norm(net)),
"net_displacement_xyz_m": net.tolist(),
"span_xyz_m": np.ptp(pos, axis=0).tolist(),
"span_2d_m": float(np.linalg.norm(np.ptp(pos[:, :2], axis=0))),
"cumulative_increment_3d_m": float(steps.sum()),
"cumulative_increment_2d_m": float(
np.linalg.norm(np.diff(pos[:, :2], axis=0), axis=1).sum()),
"step_m": _percentiles(steps),
"note": "cumulative increment counts every wiggle; it is NOT drift",
}
def timing_statistics(stamps_ns) -> dict:
"""Time deltas, regressions and duplicates, all in integer nanoseconds."""
stamps = np.asarray(stamps_ns, dtype=np.int64)
if len(stamps) < 2:
return {"count": int(len(stamps))}
diff = np.diff(stamps)
return {
"count": int(len(stamps)),
"dt_s": _percentiles(diff.astype(np.float64) / 1e9),
"non_positive_dt_count": int(np.sum(diff <= 0)),
"duplicate_stamp_count": int(np.sum(diff == 0)),
"regression_count": int(np.sum(diff < 0)),
"duration_s": float((stamps[-1] - stamps[0]) / 1e9),
"effective_rate_hz": float(
(len(stamps) - 1) / max(1e-9, (stamps[-1] - stamps[0]) / 1e9)),
}
def cumulative_at_intervals(stamps_ns, positions,
intervals_ms=RESAMPLE_INTERVALS_MS) -> dict:
"""Cumulative increment when the path is sampled every T milliseconds.
Nearest recorded sample is used, never interpolation: interpolation would
invent positions that were never published. The result describes how the
number depends on the observation interval; it does NOT identify a filter,
and a smaller number at a longer interval is not evidence of a better filter.
"""
stamps = np.asarray(stamps_ns, dtype=np.int64)
pos = np.asarray(positions, dtype=np.float64).reshape((-1, 3))
out = {"method": "nearest recorded sample; no interpolation",
"intervals": {}}
if len(stamps) < 2:
return out
for interval_ms in intervals_ms:
step_ns = int(interval_ms) * 1_000_000
target = np.arange(stamps[0], stamps[-1] + 1, step_ns, dtype=np.int64)
index = np.searchsorted(stamps, target)
index = np.clip(index, 0, len(stamps) - 1)
prev = np.clip(index - 1, 0, len(stamps) - 1)
# pick whichever neighbour is closer in time
take_prev = np.abs(stamps[prev] - target) < np.abs(stamps[index] - target)
chosen = np.where(take_prev, prev, index)
chosen = np.unique(chosen)
if len(chosen) < 2:
continue
picked = pos[chosen]
increments = np.linalg.norm(np.diff(picked, axis=0), axis=1)
out["intervals"][f"{interval_ms}ms"] = {
"samples": int(len(chosen)),
"cumulative_increment_m": float(increments.sum()),
"net_displacement_m": float(np.linalg.norm(picked[-1] - picked[0])),
"span_2d_m": float(np.linalg.norm(np.ptp(picked[:, :2], axis=0))),
}
return out
def jump_threshold(steps) -> float:
"""Robust threshold for calling one consecutive increment a jump."""
arr = np.asarray(steps, dtype=np.float64)
if arr.size == 0:
return math.inf
median = float(np.median(arr))
mad = float(np.median(np.abs(arr - median)))
return max(median + JUMP_MAD_K * mad, JUMP_FLOOR_M)
def scan_phase_seconds(stamps_ns, cloud_stamps_ns):
"""Time since the most recent cloud stamp, for each pose stamp.
Phase is measured against the published cloud header (which is
lidar_end_time), so it says where the pose sits inside the most recently
completed scan. It is a description, not a cause.
"""
stamps = np.asarray(stamps_ns, dtype=np.int64)
clouds = np.asarray(cloud_stamps_ns, dtype=np.int64)
if len(clouds) == 0 or len(stamps) == 0:
return np.full(len(stamps), np.nan)
clouds = np.sort(clouds)
index = np.searchsorted(clouds, stamps, side="right") - 1
index = np.clip(index, 0, len(clouds) - 1)
delta = (stamps - clouds[index]).astype(np.float64) / 1e9
# A pose published before the first cloud has no reference.
delta[stamps < clouds[0]] = np.nan
return delta
def phase_profile(phase_s, steps, period_s: float, bins: int = 10) -> dict:
"""How step size distributes across the scan phase.
Alignment of large steps with a phase bin is a correlation. It does not
establish that the scan boundary causes them.
"""
phase = np.asarray(phase_s, dtype=np.float64)
step = np.asarray(steps, dtype=np.float64)
if len(phase) == 0 or not math.isfinite(period_s) or period_s <= 0:
return {"bins": 0}
valid = np.isfinite(phase) & (phase >= 0) & (phase < period_s * 1.5)
if not valid.any():
return {"bins": 0, "note": "no pose landed inside the scan window"}
phase = phase[valid]
step = step[valid]
edges = np.linspace(0.0, period_s, bins + 1)
index = np.clip(np.digitize(phase, edges) - 1, 0, bins - 1)
profile = []
for b in range(bins):
mask = index == b
profile.append({
"bin": b,
"phase_from_s": float(edges[b]),
"phase_to_s": float(edges[b + 1]),
"count": int(mask.sum()),
"step_p50_m": float(np.median(step[mask])) if mask.any() else None,
"step_max_m": float(step[mask].max()) if mask.any() else None,
})
big = step >= np.quantile(step, 0.99) if len(step) > 10 else np.zeros(len(step), bool)
counts = np.bincount(index[big], minlength=bins) if big.any() else np.zeros(bins, int)
return {
"bins": bins,
"period_s": float(period_s),
"profile": profile,
"largest_1pct_steps_per_bin": counts.tolist(),
"note": "alignment is a correlation, not a cause",
}
# --------------------------------------------------------------------------
# bag access (metadata + sqlite only; ROS bindings are lazy)
# --------------------------------------------------------------------------
def read_metadata(bag_dir: Path) -> dict:
bag_dir = Path(bag_dir)
if not bag_dir.exists():
raise InputProblem(f"bag directory not found: {bag_dir}")
metadata = bag_dir / "metadata.yaml"
if not metadata.is_file():
raise InputProblem(f"metadata.yaml not found in {bag_dir}")
try:
import yaml
except ImportError as exc: # pragma: no cover
raise InputProblem(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", "")
if storage not in ("sqlite3", ""):
raise BagProblem(
f"unsupported storage '{storage}' in {bag_dir}; only sqlite3 is supported")
relative = info.get("relative_file_paths") or [
e.get("path") for e in info.get("files", []) if e.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", {})
if meta.get("name") and meta.get("type"):
topics[meta["name"]] = meta["type"]
return {"files": files, "topics": topics, "storage": storage}
def _open_shard(path: 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 _load_ros():
try:
from rclpy.serialization import deserialize_message
from rosidl_runtime_py.utilities import get_message
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)
def load_odom(bag_dir: Path, topic: str) -> dict:
"""Read one Odometry topic: sensor stamps, receipt stamps, pose, twist.
Sensor stamp comes from the message header; receipt stamp is the bag record
time. They differ when publishing is delayed, and only the pair can tell you
which one is irregular.
"""
meta = read_metadata(bag_dir)
if topic not in meta["topics"]:
raise InputProblem(
f"topic {topic} not present; bag has: {', '.join(sorted(meta['topics']))}")
deserialize_message, get_message = _load_ros()
stamp_ns, recv_ns = [], []
position, quaternion, linear, angular = [], [], [], []
frames, child_frames = set(), set()
invalid_quaternion = 0
invalid_position = 0
messages = 0
for path in meta["files"]:
conn = _open_shard(path)
try:
rows = conn.execute("SELECT id, name, type FROM topics").fetchall()
found = [(i, t) for i, n, t in rows if n == topic]
if not found:
continue
topic_id, kind = found[0]
cls = get_message(kind)
for blob, record_time in conn.execute(
"SELECT data, timestamp FROM messages WHERE topic_id=? "
"ORDER BY timestamp", (topic_id,)):
msg = deserialize_message(blob, cls)
messages += 1
frame = msg.header.frame_id
child = msg.child_frame_id
if frame:
frames.add(frame)
if child:
child_frames.add(child)
pose = msg.pose.pose
quat = [pose.orientation.x, pose.orientation.y,
pose.orientation.z, pose.orientation.w]
try:
rotation_from_quaternion(quat)
except ValueError:
invalid_quaternion += 1
continue
pos = [pose.position.x, pose.position.y, pose.position.z]
if not all(math.isfinite(v) for v in pos):
invalid_position += 1
continue
stamp_ns.append(_stamp_ns(msg.header.stamp))
recv_ns.append(int(record_time))
position.append(pos)
quaternion.append(quat)
linear.append([msg.twist.twist.linear.x,
msg.twist.twist.linear.y,
msg.twist.twist.linear.z])
angular.append([msg.twist.twist.angular.x,
msg.twist.twist.angular.y,
msg.twist.twist.angular.z])
finally:
conn.close()
if messages == 0:
raise BagProblem(f"{topic} present in metadata but yielded no messages")
return {
"topic": topic,
"messages": messages,
"stamp_ns": np.asarray(stamp_ns, dtype=np.int64),
"recv_ns": np.asarray(recv_ns, dtype=np.int64),
"position": np.asarray(position, dtype=np.float64).reshape((-1, 3)),
"quaternion": np.asarray(quaternion, dtype=np.float64).reshape((-1, 4)),
"linear": np.asarray(linear, dtype=np.float64).reshape((-1, 3)),
"angular": np.asarray(angular, dtype=np.float64).reshape((-1, 3)),
"frame_id": sorted(frames),
"child_frame_id": sorted(child_frames),
"invalid_quaternion_skipped": invalid_quaternion,
"invalid_position_skipped": invalid_position,
}
def load_cloud_stamps(bag_dir: Path, topic: str) -> np.ndarray:
"""Header stamps of a PointCloud2 topic, without touching the point data."""
meta = read_metadata(bag_dir)
if topic not in meta["topics"]:
return np.zeros(0, dtype=np.int64)
deserialize_message, get_message = _load_ros()
stamps = []
for path in meta["files"]:
conn = _open_shard(path)
try:
rows = conn.execute("SELECT id, name, type FROM topics").fetchall()
found = [(i, t) for i, n, t in rows if n == topic]
if not found:
continue
topic_id, kind = found[0]
cls = get_message(kind)
for (blob,) in conn.execute(
"SELECT data FROM messages WHERE topic_id=? ORDER BY timestamp",
(topic_id,)):
msg = deserialize_message(blob, cls)
stamps.append(_stamp_ns(msg.header.stamp))
finally:
conn.close()
return np.asarray(stamps, dtype=np.int64)
# --------------------------------------------------------------------------
# analysis
# --------------------------------------------------------------------------
def analyze_jitter(odom: dict, cloud_stamps_ns: np.ndarray) -> dict:
"""Describe the jitter without naming a cause.
Returns net displacement, span, cumulative increments (3D and 2D), the
interval dependence, the distribution of consecutive increments with their
own dt, attitude change, timing defects, and the scan-phase profile.
"""
stamps = np.asarray(odom["stamp_ns"], dtype=np.int64)
pos = np.asarray(odom["position"], dtype=np.float64).reshape((-1, 3))
quat = np.asarray(odom["quaternion"], dtype=np.float64).reshape((-1, 4))
linear = np.asarray(odom["linear"], dtype=np.float64).reshape((-1, 3))
angular = np.asarray(odom["angular"], dtype=np.float64).reshape((-1, 3))
# Timing defects must be judged in PUBLICATION order, before any sorting:
# a regression disappears once the array is sorted by stamp.
timing_raw = timing_statistics(stamps)
timing_raw["note"] = ("measured in publication order, before sorting; "
"path statistics below use time order")
order = np.argsort(stamps, kind="stable")
stamps, pos, quat = stamps[order], pos[order], quat[order]
result = {
"topic": odom.get("topic"),
"frame_id": odom.get("frame_id"),
"child_frame_id": odom.get("child_frame_id"),
"invalid_quaternion_skipped": odom.get("invalid_quaternion_skipped", 0),
"invalid_position_skipped": odom.get("invalid_position_skipped", 0),
"path": {**path_statistics(pos),
"order": "time order; positions reordered by stamp so a "
"regression cannot create a backwards step"},
"timing": timing_raw,
"interval_dependence": cumulative_at_intervals(stamps, pos),
}
# ---- attitude ------------------------------------------------------
if len(quat) > 1:
angular_steps = np.array(
[angle_between_quaternions(quat[i], quat[i + 1])
for i in range(len(quat) - 1)], dtype=np.float64)
rolls, pitches = zip(*(roll_pitch(q) for q in quat))
yaws = np.array([yaw_from_quaternion(q) for q in quat])
result["attitude"] = {
"yaw_span_rad": float(np.ptp(yaws)),
"roll_span_rad": float(np.ptp(rolls)),
"pitch_span_rad": float(np.ptp(pitches)),
"roll_max_abs_rad": float(np.max(np.abs(rolls))),
"pitch_max_abs_rad": float(np.max(np.abs(pitches))),
"cumulative_rotation_rad": float(angular_steps.sum()),
"rotation_step_rad": _percentiles(angular_steps),
}
# ---- twist ---------------------------------------------------------
if len(linear):
result["twist"] = {
"linear_norm_max": float(np.linalg.norm(linear, axis=1).max()),
"linear_norm_median": float(np.median(np.linalg.norm(linear, axis=1))),
"angular_norm_max": float(np.linalg.norm(angular, axis=1).max()),
"angular_norm_median": float(
np.median(np.linalg.norm(angular, axis=1))),
"frame_note": "twist.linear is the IMU/lidar body frame (vel_body), "
"not the chassis centre, even after the body_odom offset",
}
# ---- consecutive increments and phase ------------------------------
if len(stamps) > 2:
dt_ns = np.diff(stamps)
steps = np.linalg.norm(np.diff(pos, axis=0), axis=1)
# Guard against division by zero on duplicate stamps.
safe_dt = np.where(dt_ns > 0, dt_ns.astype(np.float64) / 1e9, np.nan)
speed = np.divide(steps, safe_dt,
out=np.full_like(steps, np.nan),
where=np.isfinite(safe_dt) & (safe_dt > 0))
result["increment"] = {
"dt_s": _percentiles(safe_dt[np.isfinite(safe_dt)]),
"speed_mps": _percentiles(speed[np.isfinite(speed)]),
"zero_dt_pairs_dropped": int(np.sum(dt_ns <= 0)),
}
clouds = np.asarray(cloud_stamps_ns, dtype=np.int64)
if len(clouds) >= 2:
cloud_period = float(np.median(np.diff(np.sort(clouds)))) / 1e9
result["scan_period_s"] = cloud_period
phase = scan_phase_seconds(stamps, clouds)
# Increment i sits between stamps i and i+1; attribute it to stamp i.
result["scan_phase"] = phase_profile(phase[:-1], steps,
cloud_period)
else:
result["scan_phase"] = {"bins": 0,
"note": "no cloud stamps available"}
threshold = jump_threshold(steps)
result["increment"]["jump_threshold_m"] = threshold
result["increment"]["jump_rule"] = (
f"step >= max(median + {JUMP_MAD_K:g}*MAD, {JUMP_FLOOR_M*1000:g} mm)")
result["increment"]["jump_count"] = int(np.sum(steps >= threshold))
result["increment"]["jump_total_m"] = float(steps[steps >= threshold].sum())
return result
def compare_odometry(imu_odom: dict, body_odom: dict) -> dict:
"""Check whether the body-centre extrinsic explains the difference.
body_odom computes p_body = p_imu + R(yaw) * (ox, oy) and rebuilds the
orientation as pure yaw. So in the yaw body frame the difference
R(-yaw)(p_body - p_imu) must be a CONSTANT planar offset. If it is not, the
published body_odom does not match its own documented transform.
The offset values themselves are not needed: constancy is the test.
"""
imu_stamps = np.asarray(imu_odom["stamp_ns"], dtype=np.int64)
body_stamps = np.asarray(body_odom["stamp_ns"], dtype=np.int64)
if len(imu_stamps) == 0 or len(body_stamps) == 0:
return {"matched": 0, "note": "one topic had no usable message"}
# Match by exact stamp: body_odom copies the header verbatim.
common, imu_idx, body_idx = np.intersect1d(
imu_stamps, body_stamps, assume_unique=False, return_indices=True)
if len(common) == 0:
return {"matched": 0,
"note": "no shared stamps; body_odom is expected to copy the "
"input header, so this itself is a finding"}
imu_pos = np.asarray(imu_odom["position"], dtype=np.float64)[imu_idx]
body_pos = np.asarray(body_odom["position"], dtype=np.float64)[body_idx]
imu_quat = np.asarray(imu_odom["quaternion"], dtype=np.float64)[imu_idx]
# Difference expressed in the yaw body frame.
diff_body = np.empty_like(imu_pos)
for i in range(len(common)):
yaw = yaw_from_quaternion(imu_quat[i])
c, s = math.cos(yaw), math.sin(yaw)
d = body_pos[i] - imu_pos[i]
diff_body[i] = [c * d[0] + s * d[1], -s * d[0] + c * d[1], d[2]]
median_offset = np.median(diff_body, axis=0)
residual = np.linalg.norm(diff_body - median_offset, axis=1)
# Orientation: body_odom should be pure yaw; imu may carry roll/pitch.
imu_yaw = np.array([yaw_from_quaternion(q) for q in imu_quat])
body_quat = np.asarray(body_odom["quaternion"], dtype=np.float64)[body_idx]
body_yaw = np.array([yaw_from_quaternion(q) for q in body_quat])
yaw_gap = np.array([math.atan2(math.sin(a - b), math.cos(a - b))
for a, b in zip(body_yaw, imu_yaw)])
imu_roll_pitch = np.array([roll_pitch(q) for q in imu_quat])
body_roll_pitch = np.array([roll_pitch(q) for q in body_quat])
imu_linear = np.asarray(imu_odom["linear"], dtype=np.float64)[imu_idx]
body_linear = np.asarray(body_odom["linear"], dtype=np.float64)[body_idx]
twist_identical = bool(np.allclose(imu_linear, body_linear, atol=1e-12))
return {
"matched": int(len(common)),
"imu_messages": int(len(imu_stamps)),
"body_messages": int(len(body_stamps)),
"body_frame_offset_estimate_m": median_offset.tolist(),
"offset_constancy_residual_m": _percentiles(residual),
"offset_constancy_p95_over_p50": (
float(np.quantile(residual, 0.95) /
max(1e-9, np.quantile(residual, 0.50)))
if len(residual) else None),
"yaw_gap_rad": _percentiles(yaw_gap),
"imu_roll_pitch_max_abs_rad": float(
np.abs(imu_roll_pitch).max()) if len(imu_roll_pitch) else 0.0,
"body_roll_pitch_max_abs_rad": float(
np.abs(body_roll_pitch).max()) if len(body_roll_pitch) else 0.0,
"twist_linear_identical": twist_identical,
"interpretation": (
"body_odom = imu + R(yaw)*offset, orientation rebuilt as pure yaw. "
"A near-constant body-frame offset means the extrinsic explains the "
"difference; position jitter remains in both because it is inherited."),
}
def source_review() -> dict:
"""Facts read out of the source, kept separate from data observations."""
return {
"files": [
"minco_ws/src/perception/Point-LIO/src/laserMapping.cpp",
"minco_ws/src/perception/Point-LIO/src/li_initialization.cpp",
"minco_ws/src/perception/Point-LIO/include/sensor_time_rate_limiter.h",
"minco_ws/src/perception/Point-LIO/include/common_lib.h",
"minco_ws/src/perception/Point-LIO/config/mid360.yaml",
"minco_ws/src/scan/body_odom/body_odom/body_odom_node.py",
],
"facts": [
"publish_odometry() stamps with time_current when "
"publish_odometry_without_downsample is true, else lidar_end_time.",
"The published pose is the current filter state kf_output "
"(use_imu_as_input is false); no per-point snapshot is taken for "
"the odometry message itself.",
"Publishing happens inside the point-by-point update loop when the "
"flag is true, and once per scan otherwise.",
"frame_id=camera_init, child_frame_id=body.",
"twist.linear is rotated into the body frame before publishing.",
"SensorTimeRateLimiter drops messages under 1/frequency of sensor "
"time and re-publishes when sensor time moves backwards.",
"get_ros_time() builds stamps from a double second value and "
"truncates the fraction, so sub-microsecond stamp structure is not "
"meaningful.",
"mid360.yaml sets publish_odometry_without_downsample True and "
"publish_frequency_hz 100.",
"body_odom applies a yaw-rotated planar offset and rebuilds the "
"orientation as pure yaw, discarding IMU roll and pitch.",
"body_odom copies header and passes twist through unchanged, so its "
"twist is in the IMU/lidar body frame, not the chassis centre.",
],
"not_verifiable_here": [
"Whether the filter's per-point update is the cause: no raw IMU was "
"recorded, so the measurement that drives each update is unknown.",
"Whether the deskew assumption holds: it needs per-point timestamps "
"and the anchor state, neither of which is recorded.",
],
}
def _hypotheses(jitter: dict, comparison: dict) -> list:
"""Candidate explanations, each with the evidence that would settle it."""
hypotheses = []
increment = jitter.get("increment", {})
timing = jitter.get("timing", {})
hypotheses.append({
"hypothesis": "odometry jitter is inherited from the filter's "
"point-by-point update, not from motion",
"support": "velocity command is zero throughout and the span is ~cm "
"while the path is metres, so the pose is oscillating around "
"a fixed point rather than travelling",
"strength": "moderate",
"needs": "raw IMU plus a per-point state snapshot would show whether "
"each update moves the position back and forth",
})
hypotheses.append({
"hypothesis": "the wiggle is an artefact of publishing mid-scan at "
"per-point time",
"support": "publish_odometry is called inside the per-point loop with "
"the current filter state, so consecutive messages sample "
"successive updates rather than one settled state per scan",
"strength": "moderate",
"needs": "compare per-point update count against the number of "
"distinct poses, and check the phase profile",
})
if timing.get("non_positive_dt_count", 0) > 0:
hypotheses.append({
"hypothesis": "rate limiter and stamp truncation produce irregular "
"dt that inflates the cumulative increment",
"support": f"{timing['non_positive_dt_count']} non-positive dt pairs",
"strength": "weak",
"needs": "sensor-time arrival log; the bag only has receive time",
})
if comparison.get("matched", 0):
hypotheses.append({
"hypothesis": "body_odom jitter is inherited, not added",
"support": "body_odom shares stamps with its input and its "
"difference is a near-constant body-frame offset, so it "
"cannot introduce position jitter of its own",
"strength": "strong"
if (comparison.get("offset_constancy_residual_m", {})
.get("p95", 1.0) < 0.01) else "moderate",
"needs": "nothing further; the transform is analytic",
})
return hypotheses
def build_summary(imu: dict, body: dict, jitter: dict, comparison: dict,
cloud_stamps) -> dict:
return {
"schema_version": SCHEMA_VERSION,
"tool": {"name": "analyze_pose_jitter", "version": TOOL_VERSION},
"evidence_grade": {
"note": "source facts, data observations and hypotheses are kept in "
"separate fields; the cumulative increment is not drift",
"confirmed_causes": [],
},
"inputs": {
"imu_topic": imu.get("topic"),
"body_topic": body.get("topic"),
"imu_messages": int(len(imu["stamp_ns"])),
"body_messages": int(len(body["stamp_ns"])),
"cloud_stamps": int(len(cloud_stamps)),
"raw_imu_recorded": False,
},
"source_facts": source_review(),
"data_observations": {
"imu_odometry": jitter,
"body_vs_imu": comparison,
},
"hypotheses": _hypotheses(jitter, comparison),
"limits": [
"The bag contains no raw IMU, so any statement about the EKF's "
"measurements is unverifiable here and is marked as a hypothesis.",
"A cumulative increment depends on the sampling interval; the "
"per-interval table is descriptive and does not identify a filter.",
"Scan-phase alignment of large steps is a correlation, not a cause.",
"twist.linear from either topic is in the IMU/lidar body frame; "
"comparing it against a chassis-centre velocity would be a frame "
"error, not a jitter measurement.",
],
}
# --------------------------------------------------------------------------
# output
# --------------------------------------------------------------------------
CSV_FIELDS = [
"index", "stamp_ns", "dt_s", "dx_m", "dy_m", "dz_m", "step_m",
"step_mm", "speed_mps", "yaw_step_rad", "nearest_cloud_dt_ms",
"scan_phase_ms",
]
def write_reports(summary: dict, events: list, output_dir: Path) -> None:
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
targets = [output_dir / "summary.json", output_dir / "jump_events.csv"]
for target in targets:
if target.exists():
raise InputProblem(
f"refusing to overwrite existing {target}; "
"pass --overwrite or choose another --output")
(output_dir / "summary.json").write_text(
json.dumps(summary, indent=2, ensure_ascii=False), encoding="utf-8")
with (output_dir / "jump_events.csv").open(
"w", newline="", encoding="utf-8") as handle:
writer = csv.DictWriter(handle, fieldnames=CSV_FIELDS)
writer.writeheader()
for row in events:
writer.writerow({k: row.get(k, "") for k in CSV_FIELDS})
def collect_events(imu: dict, cloud_stamps) -> tuple:
"""Consecutive increments at or above the robust jump threshold."""
stamps = np.asarray(imu["stamp_ns"], dtype=np.int64)
pos = np.asarray(imu["position"], dtype=np.float64)
quat = np.asarray(imu["quaternion"], dtype=np.float64)
order = np.argsort(stamps, kind="stable")
stamps, pos, quat = stamps[order], pos[order], quat[order]
dt_ns = np.diff(stamps)
delta = np.diff(pos, axis=0)
steps = np.linalg.norm(delta, axis=1)
threshold = jump_threshold(steps)
clouds = np.asarray(cloud_stamps, dtype=np.int64)
phase = scan_phase_seconds(stamps, clouds)
if len(clouds):
clouds_sorted = np.sort(clouds)
nearest = np.searchsorted(clouds_sorted, stamps)
nearest = np.clip(nearest, 0, len(clouds_sorted) - 1)
prev = np.clip(nearest - 1, 0, len(clouds_sorted) - 1)
take_prev = (np.abs(clouds_sorted[prev] - stamps)
< np.abs(clouds_sorted[nearest] - stamps))
chosen = np.where(take_prev, prev, nearest)
cloud_gap_ms = (stamps - clouds_sorted[chosen]) / 1e6
else:
cloud_gap_ms = np.full(len(stamps), np.nan)
events = []
for i in np.where(steps >= threshold)[0]:
if len(events) >= MAX_EVENTS:
break
safe_dt = dt_ns[i] / 1e9 if dt_ns[i] > 0 else None
events.append({
"index": int(i),
"stamp_ns": int(stamps[i]),
"dt_s": f"{safe_dt:.9f}" if safe_dt is not None else "",
"dx_m": f"{delta[i][0]:.6f}",
"dy_m": f"{delta[i][1]:.6f}",
"dz_m": f"{delta[i][2]:.6f}",
"step_m": f"{steps[i]:.6f}",
"step_mm": f"{steps[i]*1000:.3f}",
"speed_mps": f"{steps[i]/safe_dt:.4f}" if safe_dt else "",
"yaw_step_rad": f"{angle_between_quaternions(quat[i], quat[i+1]):.6f}",
"nearest_cloud_dt_ms": f"{cloud_gap_ms[i]:.3f}"
if np.isfinite(cloud_gap_ms[i]) else "",
"scan_phase_ms": f"{phase[i]*1000:.3f}"
if np.isfinite(phase[i]) else "",
})
return events, threshold
def main(argv=None) -> int:
parser = argparse.ArgumentParser(
description="Offline pose-jitter analysis over a static bag (read-only).")
parser.add_argument("--bag", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--imu-topic", default=DEFAULT_IMU_TOPIC)
parser.add_argument("--body-topic", default=DEFAULT_BODY_TOPIC)
parser.add_argument("--cloud-topic", default=DEFAULT_CLOUD_TOPIC)
parser.add_argument("--overwrite", action="store_true")
args = parser.parse_args(argv)
existing = [p for p in (args.output / "summary.json",
args.output / "jump_events.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_INPUT
if args.overwrite:
for target in existing:
target.unlink()
try:
imu = load_odom(args.bag, args.imu_topic)
try:
body = load_odom(args.bag, args.body_topic)
except InputProblem as exc:
print(f"[warn] {exc}; body comparison skipped", file=sys.stderr)
body = {"topic": args.body_topic, "stamp_ns": np.zeros(0, np.int64),
"position": np.zeros((0, 3)), "quaternion": np.zeros((0, 4)),
"linear": np.zeros((0, 3)), "angular": np.zeros((0, 3)),
"frame_id": [], "child_frame_id": []}
cloud_stamps = load_cloud_stamps(args.bag, args.cloud_topic)
jitter = analyze_jitter(imu, cloud_stamps)
comparison = compare_odometry(imu, body)
summary = build_summary(imu, body, jitter, comparison, cloud_stamps)
events, threshold = collect_events(imu, cloud_stamps)
summary["jump_events"] = {
"rule": f"step >= max(median + {JUMP_MAD_K:g}*MAD, "
f"{JUMP_FLOOR_M*1000:g} mm)",
"threshold_m": threshold,
"written": len(events),
"capped": len(events) >= MAX_EVENTS,
"columns": CSV_FIELDS,
"note": "scan_phase_ms is time since the most recent cloud header "
"(lidar_end_time); alignment is a correlation, not a cause",
}
except InputProblem as exc:
print(f"[error] {exc}", file=sys.stderr)
return EXIT_INPUT
except BagProblem as exc:
print(f"[error] {exc}", file=sys.stderr)
return EXIT_INCOMPATIBLE
try:
write_reports(summary, events, args.output)
except InputProblem as exc:
print(f"[error] {exc}", file=sys.stderr)
return EXIT_INPUT
except OSError as exc:
print(f"[error] cannot write to {args.output}: {exc}", file=sys.stderr)
return EXIT_INCOMPATIBLE
path = summary["data_observations"]["imu_odometry"]["path"]
print(json.dumps({
"net_displacement_m": path.get("net_displacement_m"),
"span_xyz_m": path.get("span_xyz_m"),
"cumulative_3d_m": path.get("cumulative_increment_3d_m"),
"cumulative_2d_m": path.get("cumulative_increment_2d_m"),
"jump_events": len(events),
"output": str(args.output),
}, indent=2, ensure_ascii=False))
return EXIT_OK
if __name__ == "__main__":
try:
sys.exit(main())
except SystemExit:
raise
except Exception:
traceback.print_exc()
print("[error] internal failure; see traceback above", file=sys.stderr)
sys.exit(EXIT_INCOMPATIBLE)
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,96 @@
# ros2 bag record subscriptions only; this is not a node parameter file.
/cloud_registered_full:
history: keep_last
depth: 10
reliability: best_effort
durability: volatile
/cloud_registered_full_lidar:
history: keep_last
depth: 10
reliability: best_effort
durability: volatile
/cloud_obstacles_for_scan:
history: keep_last
depth: 10
reliability: best_effort
durability: volatile
/planning/trajectory_status:
history: keep_last
depth: 20
reliability: reliable
durability: transient_local
/planning/perception_ready:
history: keep_last
depth: 20
reliability: reliable
durability: transient_local
/planning/perception_diagnostics:
history: keep_last
depth: 20
reliability: reliable
durability: transient_local
/cloud_registered:
history: keep_last
depth: 10
reliability: best_effort
durability: volatile
/cloud_registered_for_scan:
history: keep_last
depth: 10
reliability: best_effort
durability: volatile
/grid_map/occupancy:
history: keep_last
depth: 10
reliability: best_effort
durability: volatile
/grid_map/occupancy_inflate:
history: keep_last
depth: 10
reliability: best_effort
durability: volatile
/aft_mapped_to_init:
history: keep_last
depth: 50
reliability: best_effort
durability: volatile
/body_odom:
history: keep_last
depth: 50
reliability: best_effort
durability: volatile
/goal_point:
history: keep_last
depth: 20
reliability: reliable
durability: transient_local
/global_list:
history: keep_last
depth: 20
reliability: reliable
durability: transient_local
/a_star_list:
history: keep_last
depth: 20
reliability: reliable
durability: transient_local
/optimal_list:
history: keep_last
depth: 20
reliability: reliable
durability: transient_local
/tf_static:
history: keep_last
depth: 100
reliability: reliable
durability: transient_local
/livox/lidar:
history: keep_last
depth: 10
reliability: best_effort
durability: volatile
/parameter_events:
history: keep_last
depth: 1000
reliability: reliable
durability: transient_local
@@ -0,0 +1,83 @@
#!/usr/bin/python3
"""Offline *static-only* approximation from a raw MID360 bag (no ROS publishers).
Uses nearest IMU pose for all points in a scan, not the live full-cloud deskew
implementation. Run after sourcing Humble and the workspace. Outputs JSON.
"""
import argparse
import json
import sqlite3
import time
from pathlib import Path
import numpy as np
from rclpy.serialization import deserialize_message
from rosidl_runtime_py.utilities import get_message
from obstacle_cloud.core import ObstacleFilter
def stamp(t):
return t.sec + t.nanosec * 1e-9
def rotation(q):
x, y, z, w = 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 main():
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument('db3', type=Path)
ap.add_argument('--output', type=Path, required=True)
ap.add_argument('--extrinsic', type=float, nargs=3, default=[-.011, -.02329, .04412])
args = ap.parse_args()
conn = sqlite3.connect(f'file:{args.db3.resolve()}?mode=ro', uri=True)
topics = {n: (i, get_message(t)) for i, n, t in conn.execute('SELECT id,name,type FROM topics')}
tid, cls = topics['/aft_mapped_to_init']
poses = []
for (blob,) in conn.execute('SELECT data FROM messages WHERE topic_id=? ORDER BY timestamp', (tid,)):
m = deserialize_message(blob, cls)
p, q = m.pose.pose.position, m.pose.pose.orientation
poses.append([stamp(m.header.stamp), p.x, p.y, p.z, q.x, q.y, q.z, q.w])
poses = np.array(poses)
filt = ObstacleFilter()
tid, cls = topics['/livox/lidar']
frames = []
for fi, (blob,) in enumerate(conn.execute('SELECT data FROM messages WHERE topic_id=? ORDER BY timestamp', (tid,))):
m = deserialize_message(blob, cls)
points = np.array([[p.x, p.y, p.z, p.offset_time, p.line, p.tag] for p in m.points])
valid = ((points[:, 4] < 4) & np.isin(points[:, 5].astype(int) & 0x30, [0, 0x10])
& (np.sum(points[:, :3] ** 2, axis=1) >= .55 ** 2))
valid[0] = False
points = points[valid]
if len(points) == 0:
continue
end = stamp(m.header.stamp) + max(points[:, 3]) * 1e-9
pose = poses[np.argmin(abs(poses[:, 0] - end))]
world = (points[:, :3] + args.extrinsic) @ rotation(pose[4:]).T + pose[1:4]
start = time.monotonic()
output, ready, detail = filt.process(world, pose[1:4], end)
detail.update(index=fi, stamp=end, ready=ready, ms=1000*(time.monotonic()-start))
if fi == 370:
# This is a geometric diagnostic probe, NOT the user goal.
query = np.array([4.2, -.2, -.122494])
delta = np.floor(query * 20).astype(int) - np.floor(output * 20).astype(int)
contributors = ((np.linalg.norm(delta[:, :2]*.05, axis=1) < .62)
& (delta[:, 2] >= -1) & (delta[:, 2] <= 3))
detail['diagnostic_query_contributors'] = output[contributors].tolist()
frames.append(detail)
ready = [x for x in frames if x['ready']]
report = dict(static_approximation=True, frames=len(frames), ready_frames=len(ready),
ready_after_first_frame=sum(x['ready'] for x in frames[20:]) / len(frames[20:]),
processing_ms_p50_p95_max=np.quantile([x['ms'] for x in frames], [.5, .95, 1]).tolist(),
pose_span=np.ptp(poses[:, 1:4], axis=0).tolist(), details=frames)
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, indent=2))
print(json.dumps({k: v for k, v in report.items() if k != 'details'}, indent=2))
print('frame370', next((x for x in frames if x['index'] == 370), None))
if __name__ == '__main__':
main()
@@ -0,0 +1,408 @@
#!/usr/bin/python3
"""Unit tests for analyze_pose_jitter.
Run with the system interpreter:
/usr/bin/python3 -m pytest test_analyze_pose_jitter.py -q
The analysis functions take plain dicts, so every case below is built without a
bag, without ROS and without hardware. Only the bag-plumbing exit-code paths
touch sqlite, and they never need the ROS bindings.
"""
import json
import math
import sqlite3
import sys
from pathlib import Path
import numpy as np
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parent))
import analyze_pose_jitter as tool # noqa: E402
HZ = 100
DT_NS = 1_000_000_000 // HZ
def yaw_quat(yaw):
return [0.0, 0.0, math.sin(yaw / 2.0), math.cos(yaw / 2.0)]
def make_odom(positions, stamps_ns=None, quats=None, topic="odom",
linear=None, angular=None):
pos = np.asarray(positions, dtype=np.float64).reshape((-1, 3))
count = len(pos)
if stamps_ns is None:
stamps_ns = np.arange(count, dtype=np.int64) * DT_NS + 1_700_000_000_000_000_000
stamps_ns = np.asarray(stamps_ns, dtype=np.int64)
if quats is None:
quats = [yaw_quat(0.0)] * count
quat = np.asarray(quats, dtype=np.float64).reshape((-1, 4))
return {
"topic": topic,
"messages": count,
"stamp_ns": stamps_ns,
"recv_ns": stamps_ns.copy(),
"position": pos,
"quaternion": quat,
"linear": np.zeros((count, 3)) if linear is None else np.asarray(linear),
"angular": np.zeros((count, 3)) if angular is None else np.asarray(angular),
"frame_id": ["camera_init"],
"child_frame_id": ["body"],
"invalid_quaternion_skipped": 0,
"invalid_position_skipped": 0,
}
# --------------------------------------------------------------- geometry
def test_perfectly_static_reports_no_increment():
"""A truly static pose must produce zero path, zero span, zero steps."""
odom = make_odom(np.zeros((500, 3)))
result = tool.analyze_jitter(odom, np.zeros(0, dtype=np.int64))
path = result["path"]
assert path["net_displacement_m"] == 0.0
assert path["cumulative_increment_3d_m"] == 0.0
assert path["span_xyz_m"] == [0.0, 0.0, 0.0]
assert path["step_m"]["max"] == 0.0
def test_back_and_forth_jitter_is_not_drift():
"""The core case: a long path with a tiny span is jitter, not travel.
400 samples alternating +/-5 mm gives ~2 m of path around a 10 mm span.
The report must show both and must not label the path as drift.
"""
count = 401 # odd, so the series starts and ends at zero
positions = np.zeros((count, 3))
positions[1::2, 0] = 0.005
odom = make_odom(positions)
path = tool.analyze_jitter(odom, np.zeros(0, np.int64))["path"]
assert path["cumulative_increment_3d_m"] > 1.9
assert path["span_xyz_m"][0] == pytest.approx(0.005)
assert "NOT drift" in path["note"]
assert path["net_displacement_m"] == 0.0
def test_monotonic_drift_is_distinguished_from_jitter():
"""Real travel: path equals net displacement, span matches."""
count = 200
positions = np.column_stack([np.arange(count) * 0.001,
np.zeros(count), np.zeros(count)])
path = tool.analyze_jitter(make_odom(positions), np.zeros(0, np.int64))["path"]
assert path["net_displacement_m"] == pytest.approx(0.199, abs=1e-9)
assert path["cumulative_increment_3d_m"] == pytest.approx(0.199, abs=1e-9)
# path and net agree when there is no wiggle
assert (path["cumulative_increment_3d_m"]
- path["net_displacement_m"]) < 1e-9
def test_2d_increment_ignores_vertical_wiggle():
count = 200
positions = np.zeros((count, 3))
positions[1::2, 2] = 0.004
path = tool.analyze_jitter(make_odom(positions), np.zeros(0, np.int64))["path"]
assert path["cumulative_increment_3d_m"] > 0.3
assert path["cumulative_increment_2d_m"] == 0.0
assert path["span_xyz_m"][2] == pytest.approx(0.004)
# ------------------------------------------------------ interval dependence
def test_interval_dependence_shrinks_with_a_longer_interval():
"""Sampling less often must reduce the counted path, by construction."""
count = 1000
positions = np.zeros((count, 3))
positions[1::2, 0] = 0.004
odom = make_odom(positions)
table = tool.cumulative_at_intervals(
odom["stamp_ns"], odom["position"], intervals_ms=(10, 50, 200))["intervals"]
at_10 = table["10ms"]["cumulative_increment_m"]
at_50 = table["50ms"]["cumulative_increment_m"]
at_200 = table["200ms"]["cumulative_increment_m"]
assert at_10 > at_50 >= 0.0
assert at_200 <= at_50
assert "no interpolation" in tool.cumulative_at_intervals(
odom["stamp_ns"], odom["position"])["method"]
def test_interval_table_labels_itself_as_descriptive():
table = tool.cumulative_at_intervals(
np.arange(10, dtype=np.int64) * DT_NS, np.zeros((10, 3)))
assert table["method"].startswith("nearest recorded sample")
# ------------------------------------------------------------------ jumps
def test_periodic_jumps_are_counted_and_attributed_to_the_phase():
"""A jump every 10 samples at 100 Hz aligns with a 100 ms scan period."""
count = 300
positions = np.zeros((count, 3))
jump_indices = np.arange(9, count - 1, 10)
for j in jump_indices:
positions[j + 1:, 0] += 0.02
stamps = np.arange(count, dtype=np.int64) * DT_NS
cloud_period_ns = 100 * DT_NS
clouds = np.arange(0, count, 10, dtype=np.int64) * DT_NS
odom = make_odom(positions, stamps_ns=stamps)
result = tool.analyze_jitter(odom, clouds)
assert result["scan_period_s"] == pytest.approx(0.1, abs=1e-9)
assert result["increment"]["jump_count"] >= len(jump_indices) - 1
profile = result["scan_phase"]
assert profile["bins"] == 10
assert "correlation, not a cause" in profile["note"]
# the jumps sit just before a cloud boundary, i.e. late in the phase
counts = profile["largest_1pct_steps_per_bin"]
assert sum(counts) > 0
def test_jump_threshold_adapts_and_has_a_floor():
"""All-equal steps fall back to the floor; a spread distribution does not."""
stable = np.full(200, 0.0001) # 0.1 mm everywhere -> MAD is 0
assert tool.jump_threshold(stable) == pytest.approx(tool.JUMP_FLOOR_M)
spread = np.linspace(0.0, 0.02, 200) # median 10 mm, MAD ~5 mm
assert tool.jump_threshold(spread) > tool.JUMP_FLOOR_M
assert tool.jump_threshold(spread) > 0.02
# Mostly tight with a few outliers: MAD collapses, so the floor governs.
mostly_tight = np.concatenate([np.full(180, 0.001), np.full(20, 0.05)])
assert tool.jump_threshold(mostly_tight) == pytest.approx(tool.JUMP_FLOOR_M)
def test_jump_rule_is_stated_in_the_report():
odom = make_odom(np.zeros((50, 3)) + np.arange(50)[:, None] * 1e-6)
result = tool.analyze_jitter(odom, np.zeros(0, np.int64))
assert "MAD" in result["increment"]["jump_rule"]
# ------------------------------------------------------------------ timing
def test_duplicate_stamps_do_not_divide_by_zero():
"""Two messages with the same stamp must be reported, not crash."""
count = 50
stamps = np.arange(count, dtype=np.int64) * DT_NS
stamps[10] = stamps[9]
positions = np.zeros((count, 3))
positions[:, 0] = np.arange(count) * 0.001
odom = make_odom(positions, stamps_ns=stamps)
result = tool.analyze_jitter(odom, np.zeros(0, np.int64))
assert result["timing"]["duplicate_stamp_count"] == 1
assert result["timing"]["non_positive_dt_count"] == 1
assert result["increment"]["zero_dt_pairs_dropped"] == 1
# no nan leaked into the reported percentiles
assert all(math.isfinite(v) for v in result["increment"]["speed_mps"].values()
if isinstance(v, float))
def test_time_regression_is_reported_in_publication_order():
"""A regression disappears after sorting, so it must be judged before it."""
count = 20
stamps = np.arange(count, dtype=np.int64) * DT_NS
stamps[15] = stamps[5] # goes backwards
odom = make_odom(np.zeros((count, 3)), stamps_ns=stamps)
result = tool.analyze_jitter(odom, np.zeros(0, np.int64))
assert result["timing"]["regression_count"] >= 1
assert "publication order" in result["timing"]["note"]
def test_timing_stats_use_integer_nanoseconds():
stamps = np.array([0, 10, 25], dtype=np.int64) # 10 ns, 15 ns
stats = tool.timing_statistics(stamps)
assert stats["count"] == 3
assert stats["dt_s"]["p50"] == pytest.approx(12.5e-9, abs=1e-12)
# ------------------------------------------- body_odom centre extrinsic
def build_body_from_imu(imu, offset, yaw_offset=0.0):
"""Reproduce body_odom_node.py: yaw-rotated planar offset, pure-yaw output."""
positions, quats = [], []
for pos, quat in zip(imu["position"], imu["quaternion"]):
yaw = tool.yaw_from_quaternion(quat)
c, s = math.cos(yaw), math.sin(yaw)
ox, oy, oz = offset
positions.append([pos[0] + c * ox - s * oy,
pos[1] + s * ox + c * oy,
pos[2] + oz])
quats.append(yaw_quat(yaw + yaw_offset))
return make_odom(positions, stamps_ns=imu["stamp_ns"], quats=quats,
topic="/body_odom", linear=imu["linear"])
def test_known_centre_extrinsic_is_recovered_exactly():
"""A known offset must come back as a constant body-frame offset."""
count = 60
yaws = np.linspace(0.0, 1.2, count)
quats = [yaw_quat(y) for y in yaws]
imu = make_odom(np.zeros((count, 3)), quats=quats,
stamps_ns=np.arange(count, dtype=np.int64) * DT_NS)
offset = (-0.031, -0.02329, -0.23)
body = build_body_from_imu(imu, offset)
comparison = tool.compare_odometry(imu, body)
assert comparison["matched"] == count
assert comparison["body_frame_offset_estimate_m"] == pytest.approx(
list(offset), abs=1e-9)
assert comparison["offset_constancy_residual_m"]["max"] < 1e-9
assert comparison["twist_linear_identical"] is True
assert comparison["yaw_gap_rad"]["max"] == pytest.approx(0.0, abs=1e-9)
def test_body_odom_discards_roll_and_pitch():
"""body_odom rebuilds a pure-yaw quaternion, so its roll/pitch must be zero."""
count = 10
quats = []
for roll in np.linspace(0.0, 0.1, count):
cr, sr = math.cos(roll / 2), math.sin(roll / 2)
quats.append([sr, 0.0, 0.0, cr])
imu = make_odom(np.zeros((count, 3)), quats=quats,
stamps_ns=np.arange(count, dtype=np.int64) * DT_NS)
body = build_body_from_imu(imu, (0.0, 0.0, 0.0))
comparison = tool.compare_odometry(imu, body)
assert comparison["imu_roll_pitch_max_abs_rad"] > 0.05
assert comparison["body_roll_pitch_max_abs_rad"] < 1e-9
def test_offset_that_drifts_is_flagged_as_inconsistent():
"""If the published difference is not constant, the extrinsic cannot explain it."""
count = 50
imu = make_odom(np.zeros((count, 3)),
stamps_ns=np.arange(count, dtype=np.int64) * DT_NS)
body = build_body_from_imu(imu, (0.0, 0.0, 0.0))
body["position"] = body["position"].copy()
body["position"][:, 0] += np.linspace(0.0, 0.05, count)
comparison = tool.compare_odometry(imu, body)
assert comparison["offset_constancy_residual_m"]["max"] > 0.01
def test_no_shared_stamps_is_reported_not_guessed():
imu = make_odom(np.zeros((5, 3)), stamps_ns=np.arange(5, dtype=np.int64) * DT_NS)
body = make_odom(np.zeros((5, 3)),
stamps_ns=np.arange(5, dtype=np.int64) * DT_NS + 7)
comparison = tool.compare_odometry(imu, body)
assert comparison["matched"] == 0
assert "no shared stamps" in comparison["note"]
# -------------------------------------------------------------- roll/pitch
def test_roll_pitch_extraction():
roll, pitch = tool.roll_pitch(yaw_quat(0.7))
assert roll == pytest.approx(0.0, abs=1e-9)
assert pitch == pytest.approx(0.0, abs=1e-9)
cr, sr = math.cos(0.3), math.sin(0.3)
r, p = tool.roll_pitch([sr, 0.0, 0.0, cr])
assert r == pytest.approx(0.6, abs=1e-6)
# ------------------------------------------------------- report structure
def test_summary_keeps_facts_observations_and_hypotheses_apart():
imu = make_odom(np.zeros((20, 3)),
stamps_ns=np.arange(20, dtype=np.int64) * DT_NS)
body = build_body_from_imu(imu, (0.0, 0.0, 0.0))
jitter = tool.analyze_jitter(imu, np.zeros(0, np.int64))
comparison = tool.compare_odometry(imu, body)
summary = tool.build_summary(imu, body, jitter, comparison, np.zeros(0))
assert set(summary) >= {"source_facts", "data_observations", "hypotheses",
"limits"}
assert summary["source_facts"]["facts"]
assert summary["source_facts"]["not_verifiable_here"]
assert any("raw IMU" in item for item in summary["source_facts"]["not_verifiable_here"])
assert summary["evidence_grade"]["confirmed_causes"] == []
def test_report_never_claims_a_cause():
imu = make_odom(np.zeros((20, 3)),
stamps_ns=np.arange(20, dtype=np.int64) * DT_NS)
jitter = tool.analyze_jitter(imu, np.zeros(0, np.int64))
comparison = tool.compare_odometry(imu, imu)
summary = tool.build_summary(imu, imu, jitter, comparison, np.zeros(0))
for hypothesis in summary["hypotheses"]:
assert set(hypothesis) == {"hypothesis", "support", "strength", "needs"}
assert hypothesis["strength"] in {"weak", "moderate", "strong"}
# ------------------------------------------------------------ bag plumbing
def _write_metadata(bag_dir: Path, topics: dict, storage="sqlite3"):
bag_dir.mkdir(parents=True, exist_ok=True)
(bag_dir / "bag_0.db3").touch()
lines = [
"rosbag2_bagfile_information:", " version: 5",
f" storage_identifier: {storage}",
" duration:", " nanoseconds: 1000000000",
" topics_with_message_count:",
]
for name, kind in topics.items():
lines += [" - topic_metadata:", f" name: {name}",
f" type: {kind}", " serialization_format: cdr",
" message_count: 1"]
lines += [" relative_file_paths:", " - bag_0.db3"]
(bag_dir / "metadata.yaml").write_text("\n".join(lines) + "\n", encoding="utf-8")
def test_missing_bag_returns_2(tmp_path):
code = tool.main(["--bag", str(tmp_path / "absent"),
"--output", str(tmp_path / "out")])
assert code == tool.EXIT_INPUT
def test_missing_topic_returns_2(tmp_path):
bag = tmp_path / "bag"
_write_metadata(bag, {"/body_odom": "nav_msgs/msg/Odometry"})
code = tool.main(["--bag", str(bag), "--output", str(tmp_path / "out")])
assert code == tool.EXIT_INPUT
def test_unsupported_storage_returns_3(tmp_path):
bag = tmp_path / "bag"
_write_metadata(bag, {}, storage="mcap")
code = tool.main(["--bag", str(bag), "--output", str(tmp_path / "out")])
assert code == tool.EXIT_INCOMPATIBLE
def test_corrupt_shard_returns_3(tmp_path):
bag = tmp_path / "bag"
_write_metadata(bag, {"/aft_mapped_to_init": "nav_msgs/msg/Odometry"})
(bag / "bag_0.db3").write_bytes(b"not sqlite")
code = tool.main(["--bag", str(bag), "--output", str(tmp_path / "out")])
assert code == tool.EXIT_INCOMPATIBLE
def test_existing_output_is_not_overwritten(tmp_path):
imu = make_odom(np.zeros((5, 3)), stamps_ns=np.arange(5, dtype=np.int64) * DT_NS)
summary = tool.build_summary(imu, imu, tool.analyze_jitter(imu, np.zeros(0, np.int64)),
tool.compare_odometry(imu, imu), np.zeros(0))
out = tmp_path / "out"
out.mkdir()
(out / "summary.json").write_text("{}", encoding="utf-8")
with pytest.raises(tool.InputProblem):
tool.write_reports(summary, [], out)
assert (out / "summary.json").read_text(encoding="utf-8") == "{}"
def test_written_reports_have_the_documented_shape(tmp_path):
imu = make_odom(np.zeros((5, 3)), stamps_ns=np.arange(5, dtype=np.int64) * DT_NS)
summary = tool.build_summary(imu, imu, tool.analyze_jitter(imu, np.zeros(0, np.int64)),
tool.compare_odometry(imu, imu), np.zeros(0))
tool.write_reports(summary, [], tmp_path)
parsed = json.loads((tmp_path / "summary.json").read_text(encoding="utf-8"))
assert parsed["tool"]["name"] == "analyze_pose_jitter"
header = (tmp_path / "jump_events.csv").read_text(encoding="utf-8").splitlines()[0]
for column in ("stamp_ns", "dt_s", "step_mm", "nearest_cloud_dt_ms",
"scan_phase_ms"):
assert column in header
File diff suppressed because it is too large Load Diff