#!/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)