From 2ce0d1e9bf6d7380b2315b00c0ff81b48f2c1607 Mon Sep 17 00:00:00 2001 From: walunt5 Date: Thu, 5 Nov 2026 11:59:34 +0800 Subject: [PATCH] =?UTF-8?q?docs(minco=5Fws):=20B=20=E7=BA=BF=E8=AF=8A?= =?UTF-8?q?=E6=96=AD=E4=B8=8E=E6=96=B9=E6=A1=88=E6=96=87=E6=A1=A3=EF=BC=8C?= =?UTF-8?q?=E9=99=84=E5=8F=AA=E8=AF=BB=E5=88=86=E6=9E=90=E8=84=9A=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 文档: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,两者不矛盾。 脚本均为只读:不开节点、不回放、不发布,不决定因果,源码事实/数据观察/ 待验证假设分字段输出。 --- .../docs/B_BASELINE_ANALYSIS_2026-11-01.md | 126 ++ minco_ws/docs/B_BASELINE_RUNBOOK.md | 141 ++ minco_ws/docs/B_FOOTPRINT_80CM_2026-11-01.md | 67 + .../B_OBSTACLE_STATIC_ANALYSIS_2026-11-01.md | 131 ++ .../B_OPTIMIZATION_AND_TESTS_2026-11-01.md | 124 ++ .../B_RECTANGLE_IMPLEMENTATION_2026-11-01.md | 88 + ...F_FILTER_AND_STATIC_ANALYSIS_2026-11-02.md | 132 ++ .../docs/B_STATIC_RAW_ANALYSIS_2026-11-01.md | 133 ++ minco_ws/docs/CODEX_PROMPT.md | 359 +++ .../docs/DIAGNOSIS_AND_DESIGN_2026-10-31.md | 355 +++ minco_ws/docs/NAVIGATION_SOLUTION.md | 111 +- minco_ws/docs/PROMPT_FOR_SOLUTION_4.md | 301 +++ minco_ws/docs/PROMPT_FOR_SOLUTION_C.md | 360 ++++ .../diagnostics/analyze_map_acceptance.py | 415 ++++ .../docs/diagnostics/analyze_pose_jitter.py | 960 +++++++++ .../docs/diagnostics/analyze_self_boundary.py | 1918 +++++++++++++++++ minco_ws/docs/diagnostics/b_baseline_qos.yaml | 96 + .../check_static_obstacle_cloud.py | 83 + .../diagnostics/test_analyze_pose_jitter.py | 408 ++++ .../diagnostics/test_analyze_self_boundary.py | 1110 ++++++++++ 20 files changed, 7400 insertions(+), 18 deletions(-) create mode 100644 minco_ws/docs/B_BASELINE_ANALYSIS_2026-11-01.md create mode 100644 minco_ws/docs/B_BASELINE_RUNBOOK.md create mode 100644 minco_ws/docs/B_FOOTPRINT_80CM_2026-11-01.md create mode 100644 minco_ws/docs/B_OBSTACLE_STATIC_ANALYSIS_2026-11-01.md create mode 100644 minco_ws/docs/B_OPTIMIZATION_AND_TESTS_2026-11-01.md create mode 100644 minco_ws/docs/B_RECTANGLE_IMPLEMENTATION_2026-11-01.md create mode 100644 minco_ws/docs/B_SELF_FILTER_AND_STATIC_ANALYSIS_2026-11-02.md create mode 100644 minco_ws/docs/B_STATIC_RAW_ANALYSIS_2026-11-01.md create mode 100644 minco_ws/docs/CODEX_PROMPT.md create mode 100644 minco_ws/docs/DIAGNOSIS_AND_DESIGN_2026-10-31.md create mode 100644 minco_ws/docs/PROMPT_FOR_SOLUTION_4.md create mode 100644 minco_ws/docs/PROMPT_FOR_SOLUTION_C.md create mode 100644 minco_ws/docs/diagnostics/analyze_map_acceptance.py create mode 100644 minco_ws/docs/diagnostics/analyze_pose_jitter.py create mode 100644 minco_ws/docs/diagnostics/analyze_self_boundary.py create mode 100644 minco_ws/docs/diagnostics/b_baseline_qos.yaml create mode 100644 minco_ws/docs/diagnostics/check_static_obstacle_cloud.py create mode 100644 minco_ws/docs/diagnostics/test_analyze_pose_jitter.py create mode 100644 minco_ws/docs/diagnostics/test_analyze_self_boundary.py diff --git a/minco_ws/docs/B_BASELINE_ANALYSIS_2026-11-01.md b/minco_ws/docs/B_BASELINE_ANALYSIS_2026-11-01.md new file mode 100644 index 0000000..ef0601b --- /dev/null +++ b/minco_ws/docs/B_BASELINE_ANALYSIS_2026-11-01.md @@ -0,0 +1,126 @@ +# 三次单雷达基线数据分析(2026-11-01) + +分析对象:`log/field_b_baseline_01/`、`02/`、`03/` 的 SQLite rosbag、bringup.log 和参数文件。直接以只读方式反序列化 bag,没有回放话题、启动节点或连接串口。本轮没有修改运行源码或参数。 + +现场最终补充事实:机器人左侧是三个类似长方体的台阶障碍,右侧是墙,二者之间有 **1.35 m 宽的平路**。第一、第三个台阶平面尺寸均为 1.20×1.20 m、高 0.40 m,第二个平面尺寸为 1.20×1.20 m、高 0.20 m。任务是沿中间平路避障通过,不要求驶上台阶。用户同时确认第三次真机确实倒退。后续以这个布局为准,不采用“方块占据 1.35 m 总通道”或“沿坡面上台阶”的解释。 + +后续静态原始点云已提供逐点证据:0.5 m 定位体素会混合地面与较高边缘,形成侵入平路的中间代表点;另需处理地面进入当前查询高度层的条件。详见 [静态原始点云对照分析](B_STATIC_RAW_ANALYSIS_2026-11-01.md)。这项感知问题与本报告的原目标覆盖、局部重规划失败是独立环节,均未实施修复。 + +## 1. 结论与直接证据 + +**两次“约 3.5 m 停车”的直接机制不同,均有数据支持。** 第三次明确发生了原目标替换;第二次没有把最终目标大幅缩到 3.5 m,而是在局部轨迹之后持续重规划失败,控制器停在最后收到的局部轨迹终点附近。 + +| 试验 | 用户输入目标 x | 实际发布样条数 | 最后样条终点 x/y/z | bag 末 2 s 的 body_odom 位置中位数 x/y/z | 直接结论 | +| --- | --- | --- | --- | --- | --- | +| 01 开阔平地 | 1.000 m | 1 | 0.9884 / -0.0009 / -0.5019 | 1.0448 / -0.0261 / -0.4082 | 正常短程控制对照 | +| 02 窄道 | 5.000 m | 2 | 3.4084 / -0.0244 / -0.2598 | 3.3864 / -0.0274 / -0.2200 | 后续局部重规划失败,没有新样条接替 | +| 03 窄道 | 5.000 m | 4 | 3.5371 / -0.0191 / -0.1951 | 3.5744 / -0.0679 / -0.1132 | FSM 将目标缩至约 3.54 m,再按该目标规划 | + +末 2 s 中位数与用户后来手动 echo 的单帧采样时刻不同;不要求完全相等。不能直接比较不同启动中 world z 的绝对值来估计坡高。末 2 s 距原始目标的 XY 误差约为 0.052 / 1.614 / 1.427 m;距最后局部样条终点约 0.062 / 0.022 / 0.061 m。控制器事实上追的是最后收到的样条端点。 + +轨迹端点按完整 order/knots/control points 用 de Boor 算法求值,不是取最后一个控制点;7 条轨迹、每条 301 个采样点均与独立 SciPy BSpline 计算交叉核对一致。 + +## 2. 第二次:局部重规划失败后,旧轨迹终点成了实际停车点 + +`field_b_baseline_02/bringup.log`: + +```text +105 goal: 3.5 ... # 局部规划目标,非用户的全局终点 +111 Received trajectory 1, duration 7.680s +118 goal: 3.48 ... # 局部目标被调整 +134 Received trajectory 2, duration 4.320s +139 goal: 5 0 -0.244, 0 0 0 # 后续仍尝试去 5 m +142 A-star error +143 First three control points are in obstacles; t=0.000000 +... +9068 [FSM]: from REPLAN_TRAJ to REPLAN_TRAJ +``` + +日志中累计 371 次 `final_plan_success=0` 输出、2435 条 `A-star error`、205 条 `First three control points`、23 条 `Trajectory terminal point is in an obstacle`、6 条 `Ran out of pool`。这些是输出条数,不是独立试验次数;包含同一重规划周期内的多次尝试。最后仍停留在 REPLAN_TRAJ,没有出现 max_replan_fail_count 急停,也没有新的成功轨迹。 + +出现两条 `Target [5.00,...] ... using [5.00,...]`,但没有证据表明此轮目标缩短了约 1.5 m。日志两位小数可能隐藏小改动,不能写成“完全没有发生任何修改”。 + +bag 中仅有两条样条: + +| ID | duration | 求值终点 x | 末端速度 x(末端有限差分近似) | +| --- | --- | --- | --- | +| 1 | 7.680 s | 3.4305 m | 0.4215 m/s | +| 2 | 4.320 s | 3.4084 m | 0.4185 m/s | + +该末端速度符合局部窗口还需继续推进的特征。全局目标 5 m 尚未完成,但 controller 的到达判据只看本条样条终点,最终 `/cmd_vel` 变零,车停在 x≈3.386 m。当前 FSM 并未发出“原始目标已完成”的明确任务结果;准确说法是:规划侧持续失败、控制侧在旧局部终点停住。 + +所以不能靠增大 planning_horizon 从 3.5 改为 5 或 10 来解决。这会改变搜索范围和局部化条件,却没有解决后续路径为什么被判碰撞。也不能仅修 raw_goal 就承诺这次会通过。 + +## 3. 第三次:5 m 被明确改成 3.54 m,随后任务转 WAIT_TARGET + +`field_b_baseline_03/bringup.log:260`: + +```text +[1793531883.448364801] Target [5.00, 0.00, -0.19] is occupied; using [3.54, -0.02, -0.20] +``` + +后续同一日志: + +```text +264 goal: 3.54 -0.016 -0.195, 0 0 0 +271 Received trajectory 3, duration 6.400s +276 goal: 3.54 -0.016 -0.195, 0 0 0 +293 Received trajectory 4, duration 2.560s +295 [FSM]: from EXEC_TRAJ to WAIT_TARGET +``` + +这里完成了“修改 end_pt_ → 重规划继续用已缩目标 → 发送对应样条 → 退出执行状态”的完整证据链。最后样条终点 x=3.5371 m,与停点 x≈3.5744 m 对应;不是用户只发了 3.5 m,也不是底盘自行理解错 5 m。 + +第三次还存在真实回折:第 2 条样条先向前、再在 x 方向回退,其后向 y 正方向绕行,整个样条的 y 最大值约 1.541 m。与 `/cmd_vel` 的负向指令、odom 从约 x=2.47 回到 x≈0.74 的记录一致,用户确认真机确实倒退。不是只因为 LIO 跳变而显示倒退。其后安全回调重规划,产生第 3 条短目标样条。叠加后来的地图快照不能证明第 2 条样条发布瞬间每个点都碰撞,但其异常绕行应作为回归重点。 + +末段 odom 曾达到 x≈3.912 m,再回到约 3.57 m,较最后样条终点有约 0.375 m 的纵向越过。这不是“所有定点控制已经通过”的证据,需在修复目标与地形语义后保留该场景回归;本轮不据此直接调 kp/kd。平地 1 m 正常也不能替代坡道/横向误差条件下的验证。 + +## 4. 地形信息改变了根因优先级 + +01 和 03 的 planner/controller/Point-LIO/chassis 四份运行参数逐项一致,包括:模式 1、horizon=3.5、半径=0.62、body_height=0.41、blind=0.55、现有控制增益和限幅。02 四个参数文件为空,无法据此确认其全部实际参数;该轮仍有 bag 和完整日志,可分析轨迹与停车机制。 + +所有日志链路均表现为模式 1 的手动目标。当前实现 `waypointCallback()` 把 RViz/命令目标的 z 设成初次 body_pose 的高度,日志为: + +| 运行 | 固定目标高度 | +| --- | --- | +| 01 | -0.502 m | +| 02 | -0.244 m | +| 03 | -0.191 m | + +`body_height=0.41` 不会在模式 1 自动把每个未来位置的地形高度加进目标。它主要用于模式 3 的参考路径高度处理。因此“把 body_height 再抬一点”既没有解决此模式的主要数据流,也会破坏原有实测折中。 + +第三次目标替换之前的地图快照: + +- occupancy 快照比日志时刻早约 21 ms,occupancy_inflate 快照早约 49 ms;它们不是内部判定瞬间的原子转储。 +- 按 0.05 m 体素索引查询,原目标 `(5,0,-0.191)` 所在的已发布膨胀体素为 occupied。 +- 未膨胀图在通道中央附近已有低位占据,例如 `(5.075,0.125,-0.275)`、`(4.525,0.075,-0.325)`。 +- 第一处与目标的水平距离约 0.146 m、垂直差约 0.084 m;在当前 0.62 m 水平膨胀和向上 0.15 m 的规则下,足以覆盖目标查询高度。这个判断无需假设横向半径应当减小。 + +结合用户最终确认的“左台阶、右墙、中间 1.35 m 平路”,**不能再用真实坡面升高解释这一轮停车,也不应优先设计坡面高度跟随**。左右实体障碍应保留,中央平路是否被错误占据需要继续定位输入点云/高度参考/累计地图。现有证据尚未把每个占据点和实际台阶表面一一对应,不能直接删除所有低位点或抬高轨迹让其穿过障碍。 + +1.35 m 已是平路净宽,不能再减去台阶的 1.20 m。连续几何下,当前 R=0.62 的模型还有 `1.35-2×0.62=0.11 m` 的车心可行带;与几何中心的横向偏差预算约 ±5.5 cm,尚未扣除体素/定位/控制误差,因此不能据此保证离散地图始终连通。起点正前方的固定世界坐标 `(5,0)` 也不自动等于 5 m 处这条带的中心。 + +补充追溯地图输入:目标缩短前约 1.23 s 和 1.03 s,`/cloud_registered_for_scan` 分别已有 `(5.0894,0.1330,-0.2994)` 与 `(5.0655,0.1191,-0.2752)` 两点,落入后来占据的 `(5.075,0.125,-0.275)` 体素。`bringup.log:31` 确认 step_blocker regions 为空、纯透传。因此至少这个占据源在膨胀前已进入地图输入,并非仅是 RViz 膨胀圆显示过粗。仍需区分地面回波、0.5 m LIO 体素降采样的混合点、定位/配准误差或实际障碍表面;没有原始逐点雷达包,当前 bag 不能倒推出该输出点具体由哪些原始回波组成。另两处占据体素在本次追溯的时间范围内未命中,不能认定它们由栅格凭空产生。 + +第二次的窄道相关 z 带里也可见墙面占据点,如 x≈5 m 附近 y≈+0.575 / -0.775 m,局部样本间距约 1.35 m;这不是严格同截面的全墙拟合,不能据此宣称真实墙宽已独立复测。但它说明“通道宽度大致一致”和“固定 y=0 的目标/轨迹处处都在两格可行中心带”是两回事。两格余量里,地图轴与走廊轴的小偏差也可能令路径落入墙体膨胀层。 + +另见一项需要后续单独审计的地图一致性问题:02 的某些未膨胀占据点按当前半径和高度规则应覆盖目标体素,但相邻时间的已发布膨胀层在该体素缺失。末段仍可重复观察到这种关系。可能涉及滑动地图增量膨胀维护或快照时序;单凭两条独立发布消息不能确定内部状态根因。此次不把它当作目标不可达的唯一解释,也不顺手改 grid_map;后续应在同一更新序号下导出原始/膨胀体素和计数验证。 + +## 5. 下一步修改范围与验证顺序(尚未执行) + +现有三包已足够证明上述两种停车机制,现场布局和任务意图也已明确,不需要再机械重复相同基线或补做上台阶测试。下一步沿两个方向推进:保留原始任务目标的最小修复,以及平路中的目标中心带/低位占据来源诊断。 + +1. **任务目标语义的小修独立实施。** FSM 保存不可变原始目标;临时目标不能覆盖任务成功条件;等待/失败给明确状态。模式 1 在局部窗口结束且原目标未达时保留任务并尝试合法下一窗口,不能静默丢目标。重规划持续失败时有界等待/停车/报告,不无限重复。不能把“恢复原目标”实现成忽略 occupied 强行向前。 +2. **验证平路的目标中心带及占据源。** 将左台阶边缘、右墙、原目标与规划曲线放到同一坐标系;按实际查询 z 检查可行中心带。以相同帧的输入点云与原始/膨胀体素对应,查中央低位占据是如何进入并保留的。必要时短时补录原始 CustomMsg,用于追溯 LIO 的 0.5 m 体素降采样,不能先改滤波参数。保持现有半径、blind、body_height、控制增益、z 膨胀和速度限幅;不启用上台阶或坡面跟随逻辑。 +3. **A* 端点外推与地图一致性分开处理。** A* 当前日志确有 pool 越界,但它不是第三次 end_pt_ 被写回的直接机制。拒绝非法碰撞段端点要与优化器段边界适配一起验证。地图增量膨胀需先有同周期证据。 +4. **修后使用相同场地做对照。** 先平地 0.5/1/1.5/3 m,再左台阶/右墙的原 1.35 m 平路、临时堵塞恢复、有界失败、终点 yaw、倒车与贴墙起始。第三次的回折和末段越过也纳入验收,不只要求最后停得接近被替换的点。 + +拟先改文件:`scan_replan_fsm.h/.cpp`(原始目标、窗口推进和失败/完成语义),必要的新任务状态接口和策略参数;是否动 controller 取决于局部停点与真正任务终点的区分接口。地图/感知部分先定位中央占据来源,不能直接大改 grid_map、把模式 3 切换当作现成修复,或将左侧台阶过滤掉。 + +## 6. 可复核产物 + +- `log/field_b_analysis/extract.py`:SQLite 只读消息提取、样条求值;`run_01/02/03.json`:目标、轨迹、日志和汇总;对应 timeseries.npz:odom、cmd_vel、冻结状态。 +- `log/field_b_analysis/maps.py`:指定时刻的地图快照与体素查询,输出 map_*.json/npz。 +- `log/field_b_analysis/trace_points.py`:追溯第三次目标缩短前地图输入中是否已有指定体素的点,输出 `point_sources_03.json`。 +- `log/field_b_analysis/plot.py`:生成 `corridor_comparison.png` 和 PDF。上排对比 odom x 与发布样条终点;下排是路径和一个时刻的已发布地图。不同 z 的曲线/某一快照的 XY 叠加只用于解释形状,不作为全时段碰撞证明。 +- 不运行 ROS 图或回放即可重复分析;所有 bag 以 SQLite `mode=ro` 打开。本轮没有构建或真机回归,不能报告已修复。 diff --git a/minco_ws/docs/B_BASELINE_RUNBOOK.md b/minco_ws/docs/B_BASELINE_RUNBOOK.md new file mode 100644 index 0000000..e78b9c0 --- /dev/null +++ b/minco_ws/docs/B_BASELINE_RUNBOOK.md @@ -0,0 +1,141 @@ +# 问题 B:单雷达现场基线操作单 + +目标:取得同一次试验的用户原目标、修改目标日志、局部轨迹、地图和实际停车位置,作为最小修复前后的对照。只采集,不改运行代码和实测参数,不安装/接入副雷达,不为本次采集重新编译。 + +以下按现有手动目标模式 `navi_mode=1`。若原故障只在模式 3 出现,则保留原有模式 3 的启动命令和参考路径输入;不要为了照抄本单改变复现条件。两种模式的高度语义不同,结果不能混为同一次对照。 + +## 1. 启动或沿用现有系统 + +所有终端先执行: + +```bash +cd /home/xie/RC2027_BR_code/minco_ws +source /opt/ros/humble/setup.bash +source install/setup.bash +``` + +本轮目录固定为 `log/field_b_baseline_01`。后续独立录制改成 `_02` 等;不要覆盖已有 bag。每个新终端单独 source。输出保存在工作区 log 下,便于现场取回;先确认磁盘空间。 + +```bash +mkdir -p log/field_b_baseline_01 +df -h . +git rev-parse HEAD > log/field_b_baseline_01/git_head.txt +git status --short > log/field_b_baseline_01/git_status.txt +``` + +终端 A:**仅在系统没有启动时**,按现有整机入口启动并保存终端输出: + +```bash +ros2 launch scan_planner vehicle_bringup.launch.py launch_rviz:=true \ + 2>&1 | tee log/field_b_baseline_01/bringup.log +``` + +该入口默认启用底盘串口桥,会把后续导航指令发给真机。由现场操作者执行;本轮助手没有启动它。系统已经启动时沿用现有实例,不重复启动,保留原终端日志;录包中的 `/rosout` 会另存 ROS 日志,但不能替代全部 stdout。 + +## 2. 核对实际参数和数据 + +终端 B:先保存实际运行参数(节点名以 node list 为准): + +```bash +ros2 node list +ros2 param dump /scan_planner_node > log/field_b_baseline_01/planner.yaml +ros2 param dump /closed_loop_controller > log/field_b_baseline_01/controller.yaml +ros2 param dump /laserMapping > log/field_b_baseline_01/pointlio.yaml +ros2 param dump /livox_driver_node > log/field_b_baseline_01/livox.yaml +ros2 param dump /body_odom > log/field_b_baseline_01/body_odom.yaml +ros2 param dump /step_blocker > log/field_b_baseline_01/step_blocker.yaml +ros2 param dump /chassis_serial_node > log/field_b_baseline_01/chassis.yaml +ros2 topic info /cmd_vel -v > log/field_b_baseline_01/cmd_vel_endpoints.txt +``` + +至少核对:collision radius=0.62、resolution=0.05、body_height=0.41、blind=0.55、kp_pos=0.5、kd_vel=0.05、vx/vy/wz 上限=0.5/0.4/0.5、底盘各轴限幅=0.5、omega_sign=-1.0。与现场既有设置不一致时先查启动覆盖,暂不调数值。 + +```bash +timeout 8s ros2 topic hz /aft_mapped_to_init +timeout 8s ros2 topic hz /body_odom +timeout 8s ros2 topic hz /cloud_registered_for_scan +``` + +预期:三个话题持续出数,`/cmd_vel` 只有预期的控制器发布者。timeout 到期返回 124 是主动结束观察,不是节点崩溃。odom 无数据或持续断流时先处理数据链路,不进入移动复现。 + +## 3. 开始录包,再发目标 + +仍在终端 B 执行,保持运行: + +```bash +ros2 bag record -s sqlite3 \ + -o log/field_b_baseline_01/bag \ + --qos-profile-overrides-path docs/diagnostics/b_baseline_qos.yaml \ + /move_base_simple/goal /initial_path /goal_point /global_list /a_star_list \ + /planning/bspline /optimal_list /planning/data_display \ + /planning/go2_execution_frozen /aft_mapped_to_init /body_odom \ + /cloud_registered /cloud_registered_for_scan \ + /grid_map/occupancy /grid_map/occupancy_inflate /grid_map/sliding_map_bbox \ + /cmd_vel /livox/imu /tf /tf_static /rosout +``` + +该 QoS 文件只配置 recorder 订阅:地图用 Best Effort,Marker/静态 TF 用 transient local。等 recorder 已订阅当前模式会用到的话题并开始写入后,再发目标。模式 1 没有 `/initial_path` 消息属正常;`/a_star_list` 也不保证每次规划都发布。不要用 `--all` 额外录入全部原始雷达流来增加此次负载。 + +## 4. 现场试验 + +每次用 RViz 发一个目标,完成记录后再发下一个。先记录走廊入口/中段/出口实际净宽,并在地面标注起点、朝向和目标的物理位置。目标是世界坐标,不能无条件把 x=3 当作“车前方 3 m”;跨 LIO 重启需重新确认目标坐标。 + +| 编号 | 操作 | 记录重点 | +| --- | --- | --- | +| T1 | 开阔平地、前方约 1 m 单目标 | 确认本次链路可正常走停,作为控制对照 | +| T2 | 原 1.35 m 窄道,用原来容易复现的物理起点/目标 | 原目标、新目标 WARN、实际停点、地图是否封死 | +| T3 | 条件允许时重复 T2 的相同几何条件 | 是否偶发;每次新目标均在 bag 中可追踪 | + +现场停点出现后,若情况允许保留约 10 s 的静止数据,记录“自行停车/现场中止/尚未到点”。中止试验和自主停车必须分开标记,不为获取日志继续逼近碰撞。不要在这轮同时加入纸箱、调整增益或改变雷达位置。 + +对 T2/T3 截图:未膨胀 occupancy、occupancy_inflate、车体位置与轨迹;PointCloud2 均设 Best Effort。若叠加后看不清可分别截图。注意 `/global_list` 不是每次重规划都更新,不把旧 Marker 当作实时全局参考。 + +在 `log/field_b_baseline_01/notes.md` 写下每次发目标/停车的大致时间、编号、目标 x/y、实际停点 x/y、是否现场中止、三处净宽、截图文件名和任何日志。可用终端 C 取停车位置快照: + +```bash +ros2 topic echo /body_odom --once --qos-reliability best_effort \ + --field pose.pose.position +``` + +体素显示必须结合查询高度解释;本轮先录数据,后续离线测墙宽和样条碰撞,不能仅凭截图判断原因。旧代码不保证障碍解除后自动恢复目标,因此不把本轮“不恢复”当作新发现的控制问题。 + +## 5. 保存和判断 + +试验结束先在终端 B 按 Ctrl+C,让 recorder 正常写完 metadata,再执行: + +```bash +ros2 bag info log/field_b_baseline_01/bag \ + > log/field_b_baseline_01/bag_info.txt +cat log/field_b_baseline_01/bag_info.txt +``` + +至少有:模式 1 的 `/move_base_simple/goal`、`/planning/bspline`、两路 odom、两层 occupancy、`/cmd_vel`、`/rosout`。检查关键话题非零、时间覆盖发目标到停车;没有局部轨迹时也可能是初次规划直接失败,保留失败日志,不强行归为录包错误。若 occupancy 计数为零,先修复录包/话题链路再重测。 + +新启动且有 bringup.log 时: + +```bash +rg -n 'is occupied; using|no collision-free point|End point outside the map region|Ran out of pool|Unable to handle the initial or end point|Obstacle discovered|Replan failed|EMERGENCY_STOP' \ + log/field_b_baseline_01/bringup.log \ + > log/field_b_baseline_01/events.txt +``` + +没有匹配时 rg 返回 1,仅表示这份日志未匹配到,不证明不存在故障。沿用已运行系统时使用原终端日志及对应 `.ros/log/scan_planner_node*.log`,不要把别次运行的命中混入本轮。 + +| 观测 | 能得出的结论 | 后续 | +| --- | --- | --- | +| `Target ... is occupied; using ...` | FSM 此轮替换了全局目标 | 对照原消息、实际停点和地图,准备 raw_goal 最小修复 | +| `no collision-free point` | 当前参考轨迹倒序采样找不到可用点 | 检查未膨胀墙宽、查询 z、是否所有候选均被堵 | +| `Ran out of pool` | 超出 A* 搜索池 | 和滑动地图图外区分;不是直接证明用户目标图外 | +| `End point outside the map region` | A* 搜索端点调整触发地图边界失败 | 需要碰撞段端点信息,不能直接认作 FSM 原目标 | +| 车提前停但没有上述日志 | 证据尚不能归因目标替换 | 核对样条终点、FSM 完成、控制器接收和人工干预 | +| 本次正常通过 | 得到正常对照 | 保留数据;历史缺陷并不会因一次通过而消失 | + +基线完成的交付物是整个 `log/field_b_baseline_01/`(bag、实际参数、日志、notes、截图),不是单张 RViz 图。现有代码没有完整 goal_id/raw_goal 诊断,凭此包也不一定能还原每个内部候选;若仍无法判断,再加最小诊断日志,保留本轮原始基线。 + +## 6. 后续最小修复及回归边界 + +取得以上数据后,先把 raw_goal/临时终点分开,修复重新规划使用缩短目标和图外误放行的语义;定义堵塞等待/失败、原目标恢复及真正完成。单独评估 A* end 拒绝策略和优化器段边界适配,不把两个行为变化不加区分地同时归因。 + +改动前读当前注释;不调整半径、blind、body_height、增益和速度。先做目标保持/释放/超时/模式 3 路径保留的有意义测试,再构建所改包,现场依次回归 0.5/1/1.5/3 m 定点、贴墙、掉头、终点朝向、全零四元数、倒车、原窄道。使用相同物理起终点和参数比较,不以“停在替代点”算成功。 + +本单的命令已核对当前 ROS 2 Humble CLI 参数;QoS 文件可用本地 ros2bag API 解析。没有启动硬件、录包、修改运行参数或执行上述现场试验。不要在连接真机底盘桥的 ROS 图中直接回放包含 `/cmd_vel` 的 bag。 diff --git a/minco_ws/docs/B_FOOTPRINT_80CM_2026-11-01.md b/minco_ws/docs/B_FOOTPRINT_80CM_2026-11-01.md new file mode 100644 index 0000000..133348c --- /dev/null +++ b/minco_ws/docs/B_FOOTPRINT_80CM_2026-11-01.md @@ -0,0 +1,67 @@ +# 80×80 cm 整车外包络与 120 cm 通道(2026-11-01) + +用户已确认:**整车最大外包络长宽均为 80 cm,已经包含轮子、支架和全部突出件**。通道内净宽已复核为 120 cm;右侧是 10 cm 高围栏,左侧为台阶障碍。 + +## 几何判断的修正 + +车身沿通道摆正时,80 cm 宽的车在 120 cm 通道里名义上每侧有 20 cm 间隙。因此“当前圆形模型过不去”不能解释为“实车尺寸必然过不去”。 + +但方形的半宽不是覆盖整车的圆半径。假设规划参考点在车体几何中心,四角距中心为: + +```text +sqrt(0.40² + 0.40²) = 0.565685 m +``` + +圆半径 0.40 m 会漏掉四角。当前 0.62 m 圆形模型覆盖所有朝向,直径 1.24 m,所以拒绝 1.20 m 通道;它相对 80 cm 方形外接圆的径向余量约 5.43 cm。此前源码注释中的“圆形车、物理半径 0.53 m、余量 0.09 m”不再作为尺寸依据。 + +保留圆形模型时,R=0.566 m 已经几乎没有几何安全裕度,而通道中给车心留下的理想带宽只有约 6.9 cm,叠加栅格、定位和跟踪误差后不能仅据尺寸认为可靠。没有直接把半径改成 0.40/0.58/0.60。 + +## 已做的离线点云对照 + +使用本次录制的一个 full 点云帧,按最新实体柱规则重建障碍表达;固定车头朝向,检查同一车体参考高度上的几何连通性。矩形与完整障碍体素做碰撞检查,再加 **9 cm 各向同性候选裕度**;9 cm 在这里是用于对照的新矩形候选,不等于已经实测验收的矩形参数。 + +| 候选模型 | 朝向 | 连通到 x≈4.5 m | +| --- | ---: | --- | +| 当前圆 R=0.62 m | 与朝向无关 | 否 | +| 80×80 cm 矩形 + 9 cm 裕度 | 0° | 是 | +| 80×80 cm 矩形 + 9 cm 裕度 | 10° | 是 | +| 80×80 cm 矩形 + 9 cm 裕度 | 45° | 否 | + +图:[固定朝向的离线轮廓对照](../log/field_b_footprint_analysis/footprint_comparison.png)。脚本和数据在 `log/field_b_footprint_analysis/compare.py`、`comparison.json`。 + +这是**单帧、固定朝向、栅格几何连通性**检查,没有复现整套射线概率累计,也不是规划器输出、连续轨迹碰撞认证或实车通过试验。图上的连通线不能直接给控制器执行。新实体柱的在线负载仍待复核。 + +## 为什么朝向也必须处理 + +80 cm 正方形偏转 θ 后,在通道横向的投影宽度为: + +```text +W(θ) = 0.80 × (|cos θ| + |sin θ|) +``` + +| 相对通道朝向 | 车体横向投影 | 加每侧 9 cm 后 | 120 cm 通道的名义车心带宽 | +| --- | ---: | ---: | ---: | +| 0° | 80.0 cm | 98.0 cm | 22.0 cm | +| 5° | 86.7 cm | 104.7 cm | 15.3 cm | +| 10° | 92.7 cm | 110.7 cm | 9.3 cm | +| 15° | 98.0 cm | 116.0 cm | 4.0 cm | +| 20° | 102.5 cm | 120.5 cm | 无 | +| 45° | 113.1 cm | 131.1 cm | 无 | + +这些是理想几何,尚未计入实际误差预算和离散栅格影响。15° 时只剩 4 cm 带宽,已小于一格 5 cm,不能据此定为可用角度。 + +现有控制器会按前视轨迹方向调整车头,平移冻结门槛为约 0.8 rad(45.8°)。A*、优化器与安全检查用的轨迹段方向,不一定等于控制器前视方向或真机实际 yaw。**只把圆换成矩形而继续沿用这些朝向假设,会出现“规划认为不碰、实际四角扫过去”的风险。** 倒车时矩形在 180° 下几何相同,但中间的转向过程仍需明确处理。 + +## 下一项实现应覆盖的内容 + +推荐方向是可选的真实矩形 footprint 配合明确的朝向策略,保留当前圆形模式作为既有配置。 + +1. 用实际长宽及独立裕度表达轮廓,核实 `body_pose` 对应车体几何中心,不能用调大双圆柱 offset 假装精确矩形。 +2. 规划、优化和安全检查采用一致的车体朝向假设;对全向底盘,可评估通道中保持车头与通道对齐、以侧移修正位置的策略,避免因路径切向变化不断转车头。 +3. 对实际 yaw、平移时的允许角差、原地转动扫掠、终点朝向对齐分别检查。通道里位置可达,不代表任何终点 yaw 都可达。 +4. 验证障碍体素和车体边界相交的离散规则及实时开销,再做隔离 ROS 测试。 +5. 真机先开阔地回归 0.5/1/1.5/3 m、横向误差、倒车和终点 yaw;新感知静止负载通过后,再验证通道中低速、车头对齐的通行。 + +本节记录的几何诊断阶段**尚未将矩形模型接入运行代码**,也未修改圆形半径和其他参数数值。已更新 `planner_vehicle.yaml` 与真机 launch 的过时尺寸说明;确认 YAML 解析后的参数与基线完全一致,launch 语法检查通过。此前代码修改的 27 项测试仍是上一阶段的验证,不能当作矩形模型已实现或已验收。 + +后续实现、实际采用的更保守几何规则与本轮测试见 [矩形模型实现及验收](B_RECTANGLE_IMPLEMENTATION_2026-11-01.md)。 diff --git a/minco_ws/docs/B_OBSTACLE_STATIC_ANALYSIS_2026-11-01.md b/minco_ws/docs/B_OBSTACLE_STATIC_ANALYSIS_2026-11-01.md new file mode 100644 index 0000000..1382ed4 --- /dev/null +++ b/minco_ws/docs/B_OBSTACLE_STATIC_ANALYSIS_2026-11-01.md @@ -0,0 +1,131 @@ +# 实验感知静止包验收与围栏边界(2026-11-01) + +尺寸更新:用户后续确认整车完整最大外包络为 80×80 cm,包含所有突出件。当前圆形模型拒绝通道不代表实车尺寸必然不可通过;外接圆、矩形候选和朝向约束详见 [80 cm 轮廓分析](B_FOOTPRINT_80CM_2026-11-01.md)。 + +数据:`log/field_b_obstacle_static_01/bag/bag_0.db3`,约 3.4 GiB、41.524 s;只读解析,没有回放到 ROS 网络、没有启动硬件。运行参数来自同目录的 `obstacle_cloud.yaml`、`planner.yaml`。 + +用户补充确认:与上次同一窄道入口、同一朝向、全程静止;雷达光心离地约 48 cm。**右侧除了墙,还存在 10 cm 高的平地围栏**,此前未提供此信息。用户现场复核后确认:**实际窄道宽 120 cm,之前的 135 cm 是测量错误**。这与本包点云约 120–123 cm 的估计吻合。 + +## 当前判断 + +**数据链路及本包处理实时性通过初步检查;窄道通行几何未通过。** 右侧低位回波对应真实围栏,不能删成地面,也不能抬高轨迹查询层绕过它。点云中的局部净距约为 1.20–1.23 m,现场确认净宽 1.20 m,与 0.62 m 半径模型所需的 1.24 m 不相容。**本场景当前模型下没有几何可行带,停车符合碰撞模型;不能再以 1.35 m 为前提把这次堵塞判为雷达误占据。** 原先定位质心变形、目标截短等独立问题仍有各自证据与修复,不因尺寸更正而消失。 + +另发现并修正了实验支路的一项高度覆盖缺口:原来只在实测点以上填柱,可能遗漏高台阶下部对应的低查询层;本次改为在同一实测 XY 填充整个指定行驶高度区间。该修正使障碍表达更完整,不会把围栏占据的通道放宽。 + +## 1. 数据链路和时序 + +| 项目 | 本包结果 | +| --- | --- | +| `/cloud_registered_full` | 813 帧,20.00 Hz,点数中位 9090 | +| `/cloud_obstacles_for_scan` | 809 帧,20.01 Hz,点数中位 3355 | +| `/cloud_registered_for_scan` | 807 帧,20.03 Hz | +| 地图输出 | occupancy 821 帧、inflate 807 帧,约 20 Hz | +| `/planning/perception_ready` | 810 条,全部 true | +| `/planning/perception_diagnostics` | 810 条,原因全部 ready | +| 在线处理耗时 | 中位 10.77 ms,95 分位 20.92 ms,最大 39.31 ms | +| 地图输入点云的 header 到录包接收年龄 | 中位 39.79 ms,95 分位 55.26 ms,最大 73.98 ms | +| 下游透传核对 | 全部 807 对共同 header 的 XYZ 完全一致 | +| `/cmd_vel` | 4153 条,vx/vy/wz 全部为零 | +| 任务状态 | HOLD / waiting_for_target,未发目标,符合静止验收要求 | + +少量帧数差异不能单独认定为节点丢帧,也可能含录制发现/首尾边界和传输差异;本包没有持续断流,就绪消息最大接收间隔约 96 ms。 + +以上处理耗时来自在线诊断,包含几何和点云构造;点云年龄是接收时间减 header,不是纯节点耗时。地图消息的 header 在发布时重新生成,没有携带输入云时间,**不能由此直接证明云→地图的端到端延迟**。也没有录制系统 CPU 利用率。静止数据不能验证运动去畸变和行驶时并发负载。 + +车体 odom 的 XYZ 峰峰变化约 5.71/4.11/7.35 cm。用户确认静止,因此这些坐标变化不能被当成真实行驶。5%–95% 的 body_z 约为 -0.2501 到 -0.2083 m;中位 -0.2265 m。地面模型斜率约 0.14°–0.86°。内部 ready 仅说明模型条件满足,不等于通道安全或地面分类全部正确。 + +## 2. 可通行带仍然断开,但不是本包的膨胀计数异常 + +每约 2 s 抽样一次,共检查 21 个膨胀地图。以 body_z 中位及 5%/95% 值作诊断截面,在 `|y|≤0.9 m` 的通道范围内做八邻域连通性检查: + +- 起点均未占据;21/21 个样本均无法连通到 x=4 m,末帧最远约到 x=3.125 m。 +- 末帧在 x=2 m 还有约 y=-0.225…-0.075 的未占据车心格,x=3 m 剩 y=-0.175/-0.125 两格,x=3.5 m 已无空隙。 +- 较高的诊断截面 z≈-0.0416 m 在 8/21 个样本中可连通。这不是修复方案:较高截面可能绕过低围栏,不能据此更改目标 z。 + +静止包未发目标,也没有记录启动时 FSM 固定的 RViz 目标高度;上述高度是基于本包 odom 的诊断取值,不能冒称某条实际目标轨迹的碰撞结果。 + +另外逐样本取前一条同发布周期的未膨胀地图(末帧接收间隔约 22.5 ms),按实际规则独立重建:XY 严格小于 0.62 m、Z 偏移 -1…+3 个 5 cm 栅格。**21 个样本、两个诊断高度,共 42 组重建与录制膨胀层的差异均为零。** 这排除了本包这些切片上“没有占据源却残留膨胀”的解释;不能推广为已验证运动时滑动地图的所有情况。 + +图:[点云与地图切片对照](../log/field_b_obstacle_analysis/static_perception_comparison.png)。 + +## 3. 低位占据点来自真实围栏 + +前方 x=3.2…4.5 m、y≈-0.72 m 的低位点在全分辨率输入中就存在。检查过滤输出,380 帧包含能进入该低位占据行的回波;具体点与同 header 的 full 输入 XYZ 一致,不是本节点生成的虚构 XY 或定位大体素质心。 + +例如一帧中的实测点: + +```text +world (3.582966, -0.708771, -0.358421) +相对该帧拟合地面约 +0.08884 m +过滤输出与 full 输入的 XYZ 差为 0 +``` + +对每 5 帧抽一帧,共 163 帧,检查该截面。低位边界的 y 中位约 -0.7176 m;相对同帧中央平路点簇的高度差中位约 8.82 cm,符合用户确认的 10 cm 围栏。中央平路点簇相对拟合平面的帧中位残差,5%–95% 约为 -2.72…+2.25 cm;低边界不是简单的整帧地面一起抬高。 + +上部墙面比这条低边界更靠外,不能继续用上部墙面计算轮式车的低处净宽。左侧台阶的朝通道面约在 y=+0.47…+0.50 m。按同一 x 段分别估计两侧边界: + +| 入口后 world x 范围 | 左台阶 y 中位 | 围栏 y 中位 | 点云估计间距 | +| --- | ---: | ---: | ---: | +| 3.2–3.4 m | +0.500 | -0.724 | 1.224 m | +| 3.4–3.6 m | +0.497 | -0.715 | 1.212 m | +| 3.6–3.8 m | +0.493 | -0.713 | 1.206 m | +| 3.8–4.0 m | +0.489 | -0.720 | 1.209 m | +| 4.0–4.2 m | +0.483 | -0.723 | 1.206 m | +| 4.2–4.4 m | +0.474 | -0.725 | 1.199 m | + +这些是采样表面点的统计,不是经外部标定的精密测距。原始占据层的局部体素中心约 y=+0.475 与 -0.725,间距 1.20 m;按现有膨胀离散规则确实会把车心带封闭。 + +图:[围栏和台阶的高度截面](../log/field_b_obstacle_analysis/low_edge_profile.png)。红色是已确认的低围栏回波,橙色为左障碍边界,蓝色为较外侧的高墙回波。 + +## 4. 已补齐实体高度表达 + +录包对应修正前的实验支路。原代码: + +```python +p[:, 2] = np.maximum(p[:, 2], ground_z + height) +``` + +这只会在回波以上填点。若雷达仅看到 40 cm 台阶上部,地面+20 cm 的车体查询层可能“从下面漏过”。数据中的诊断点 `(1.0,-0.025,-0.2265)` 在录制膨胀图中未占据,但附近有横向距离约 0.594 m 的上部台阶占据点;小于 0.62 m 横向半径,却因高度未覆盖而没有阻挡。 + +现改为: + +```python +p[:, 2] = ground_z + height +``` + +仍只处理原来高于地面至少 8 cm、低于 50 cm 的实测障碍回波,在同一实测 XY 从地面+5 cm 填到+50 cm;真实采样也保留。该保守实体假设限定于本次平路上的台阶/围栏,不是可从悬空物下面穿行的模型。 + +- 修改 `obstacle_cloud/core.py` 和 `test/test_core.py`,没有修改定位算法、地图实现、碰撞半径、盲区和现有控制参数。 +- 增强测试后,旧代码在低查询层覆盖断言失败;修正后通过。新增 10 cm 围栏、20/40 cm 台阶对低/高查询层的覆盖验证。 +- 同一实际 full 帧、复用其在线地面平面以隔离此次修改:上述诊断点的几何膨胀源由 0 变为 25 个。它是诊断点,不是实际导航目标;这是离线几何证明,不是完整在线概率地图重放。 +- 包已重新编译;全部 27 项检查通过(scan_planner 17、obstacle_cloud 10)。 +- 该示例输出点数从 4864 增至 8781;新版本仍需静止负载复核。**本包的在线 20 Hz 与耗时统计属于修正前版本,不能直接作为新版本的性能验收。** + +## 下一步 + +用户已复核实际内净宽为 120 cm,尺寸问题已解释。当前半径保持 0.62 m,不通过删围栏点、抬查询高度或直接缩半径来放行。 + +| 几何量 | 值 | 含义 | +| --- | ---: | --- | +| 实测通道净宽 | 1.20 m | 用户现场更正并确认 | +| 当前碰撞模型直径 | 1.24 m | 2 × 0.62 m | +| 名义车心自由带 | -0.04 m | 当前模型无几何通路 | +| 半径若改成 0.60 m | 自由带 0 m | 仍不能当作可靠可通过配置 | + +后续已量明:**整车完整外包络为 80×80 cm**。旧注释中的“物理半径 0.53 m”不再作为尺寸事实。摆正时每侧物理间隙为 20 cm,方形车四角的外接圆半径约 56.6 cm。下一项应评估矩形 footprint、明确裕度及朝向控制,而非仅靠缩小圆半径;具体离线结果见上方轮廓分析。 + +随后在开阔地回归本版目标/控制状态的 0.5/1/1.5/3 m 定点、横向误差、终点朝向与倒车。若任务要求固定 120 cm 通道必须通过,再依据实测 footprint、误差与必要裕度评估窄道方案;若允许调整场地,则按所需车心余量扩大净距,不能仅把通道扩大到刚好 124 cm 就判为足够。 + +实验支路本次增加了向下的实体填充,重新上车前需先重启新版本并复核静止输出负载/障碍表达。当前不安排直接再次发 5 m 窄道目标,不报告窄道已经能够通过。 + +## 产物 + +`log/field_b_obstacle_analysis/` 中保留: + +- `summary.json`、`analyze.py/.log`、`poses.npz`、`cloud_meta.npz`:完整性、时序、状态和参数对应。 +- `geometry.json`、`geometry.py`、`map_*.npz`:21 组地图切片与连通性。 +- `inflation_sources.json/.py`、`last_sources_*.npz`:独立膨胀重建和占据来源。 +- `trace_sources.json/.py`、`trace_frame_*.npz`:full 输入与过滤输出逐点对应。 +- `profile.json/.py`、`profile_points.npz`、`widths.json`:围栏高度及同截面净距估计。 +- `column_test_before.txt`、`column_test_after.txt`、`column_fix_evidence.json`、`column_fix_frame.npz`:高度覆盖缺口及修复证据。 +- 两张 PNG/PDF 图,用于复核点云、地图和围栏截面。 diff --git a/minco_ws/docs/B_OPTIMIZATION_AND_TESTS_2026-11-01.md b/minco_ws/docs/B_OPTIMIZATION_AND_TESTS_2026-11-01.md new file mode 100644 index 0000000..a45f8b9 --- /dev/null +++ b/minco_ws/docs/B_OPTIMIZATION_AND_TESTS_2026-11-01.md @@ -0,0 +1,124 @@ +# 窄道优化第一版与验收(2026-11-01) + +更新:第一轮静止包已分析,右侧补充确认为 10 cm 高围栏;用户复核实际净宽为 120 cm(此前 135 cm 量错),小于当前 124 cm 碰撞模型直径;几何通行尚未通过。用户还确认整车完整外包络为 80×80 cm,后续轮廓与朝向分析见 [80 cm 轮廓分析](B_FOOTPRINT_80CM_2026-11-01.md)。本次已补齐障碍柱下部的实体高度,当前共 27 项检查通过。最新结论与下一步见 [静止包验收报告](B_OBSTACLE_STATIC_ANALYSIS_2026-11-01.md)。下文第一版的在线前测试数字保留为阶段记录。 + +本版基于三次行驶包及 `field_b_raw_static_01` 的诊断实施。适用现场:左侧 20/40 cm 台阶视为障碍、右侧墙、中间 1.35 m 平路。此前的诊断文档保留其当时状态;当前实施情况以本文为准。 + +## 已改的行为 + +1. FSM 保存 `raw_goal_`。只有新目标/新预设点可以更改原目标,不再把占据目标缩成附近点,也不截短全局参考路线。远处原目标可以暂在滑动地图外,但每条局部轨迹端点必须位于地图内且膨胀查询为 0;地图内部未知栅格的原有策略未改。 +2. 新增 `BLOCKED`:目标被占据、感知失效或局部规划失败时,发布 HOLD,控制器停止执行旧轨迹。默认每 0.5 s 重试;连续阻塞 10 s 发布 FAILED,保留原目标用于诊断,等待新任务。恢复时仍使用相同任务和原目标;模式 3 重试保留完整参考路线,不改成直线。这个期限不是整个导航任务的总超时。 +3. 新增 `/planning/trajectory_status`:`state=0 HOLD / 1 ACTIVE / 2 SUCCEEDED / 3 FAILED`,包含 `goal_id`、原目标、`traj_id`、是否最后一个局部窗口以及原因。控制器只执行获准的对应轨迹;跨话题到达顺序不一致时先停车。 +4. 控制器通过 `/planning/trajectory_done` 反馈局部空间到达;只有最后窗口、实际 XY 到原目标在 0.08 m 内且所需终点朝向对齐后,真机 FSM 才报 SUCCEEDED。中间窗口结束继续规划,且不执行任务终点朝向对齐。末段参考时间走完后继续监测位置修正段的碰撞,不能据时间结束任务。 +5. A* 遇到占据或地图外端点直接拒绝,不继续向前推。这里的端点是优化器传入的分段搜索锚点,原代码按值传参,并非直接覆盖 FSM 的目标变量;本修改防止搜索擅自换锚点,需要回归绕障成功率。 +6. 最后窗口的 B 样条拟合端点若偏离原目标超过 4 cm,则拒绝发布,避免控制器在未经规划的直线段上追原目标。控制器保持跟踪已检查的样条。 + +真机 `run_vehicle.launch.py` 同时打开轨迹状态授权与控制器完成反馈。非真机 launch 的反馈要求默认 false,以兼容旧开环控制器;这种组合仍须以实际位置到原目标判断成功,但不具备本版真机控制器的 HOLD 协议,不能用它替代真机 launch。 + +## 可选感知支路,默认关闭 + +启动参数 `use_obstacle_cloud:=true` 才启用: + +```text +Point-LIO 原有 /cloud_registered_full + -> obstacle_cloud:ROI、受约束平面地面、5 cm 实测点代表、低障碍高度填充 + -> step_blocker(默认仍为透传) + -> /cloud_registered_for_scan -> 原有 grid_map +``` + +- 保留 Point-LIO 定位支路及其 0.5 m 滤波、blind=0.55、外参、body_odom;不改 grid_map、0.62 m 碰撞半径、速度限幅及已调好的控制增益。 +- 感知每个 5 cm 体素选一个真实最高采样点,避免跨表面求质心。地面模型以 IMU 离地高度 0.44 m 为先验,候选容差 ±8 cm;平面坡度限制 5°,累计窗口 0.7 s,地面删除带宽 ±2.5 cm,并检查点数、比例和二维分布。 +- 0.44 是依据现有约 0.48 m 雷达高度及 lidar→IMU 的 +0.04412 m z 外参估计的**实验参数**。启用前请实测安装高度,必要时只修改新支路配置。不能把 body_odom 的 -0.23 或 `body_height=0.41` 当作 IMU 离地高度。 +- 20/40 cm 台阶顶面及立面保留。对高于地面至少 8 cm、低于 50 cm 的实测回波,在同一实测 XY 上从地面+5 cm 填充至地面+50 cm(静止包后补齐向下的实体部分),使矮障碍能覆盖现有查询高度。低于 8 cm 的非地面回波仍保留原点,但不做高柱填充。该填充代表保守的障碍投影,并非物体真实高度,RViz 中会变高。 +- 地面未确认/失效或处理超时,不把未过滤地面写入地图,发布 `perception_ready=false`。点云/odom 超过 0.25 s、不同 frame、时间对不上也禁止放行。规划器与控制器各自检查这个就绪信号,避免只依赖规划器回调空闲。 +- 仅面向本次确认的平路通道;不是坡面可通行性、台阶攀爬或坡上停车方案。地面模型的 ready 代表内部条件满足,不能代替现场检查。 +- 地图仍是原来的概率射线累计,未实现新的清除/衰减机制。被保留的近地回波或旧占据仍可能让它保守停车。切换感知支路需要停止并重启整套导航,避免混合旧地图。 + +## 改动文件及原因 + +| 文件 | 目的 | +| --- | --- | +| `plan_manage/include/plan_manage/scan_replan_fsm.h`、`src/scan_replan_fsm.cpp` | 原目标、阻塞恢复/失败、局部窗口与真实完成判据 | +| `plan_manage/include/plan_manage/goal_execution_utils.h` | 区分任务意图、局部端点和实际空间到达 | +| `plan_manage/src/closed_loop_controller.cpp` | 轨迹授权停车、完成反馈、仅最终窗口对齐、实验感知看门狗 | +| `scan_planner_msgs/msg/TrajectoryStatus.msg`、消息 CMake | 类型化的任务/轨迹状态协议 | +| `path_searching/src/dyn_a_star.cpp` | 拒绝占据终点,移除向前外推 | +| 新包 `obstacle_cloud/` | 定位之外的实验感知处理及测试 | +| `plan_manage/launch/run_vehicle.launch.py`、`vehicle_bringup.launch.py`、依赖清单 | 接通状态协议及默认关闭的实验支路 | +| `step_blocker/launch/step_blocker.launch.py` | 独立的 `blocker_input_topic`,避免全局 launch 参数串用 | +| 规划器新增测试、CMake、原参考路径发布器测试 | 真实进程的状态/控制检查;原测试发布话题更新为实际 `/body_odom` | +| `docs/diagnostics/b_baseline_qos.yaml`、`check_static_obstacle_cloud.py` | 录包 QoS 和只读离线复算;不修改节点配置 | + +原有混合行尾保持;grid_map、RViz、定位算法和已调 YAML 数值未修改。 + +## 本机验证与边界 + +构建用 `MAKEFLAGS='-j2' colcon build --parallel-workers 1`,所涉及的五个包编译成功,CMAKE_CXX_FLAGS 保持空。原环境仍有缺失 `icp_relocalization/local_setup.bash` 提示,以及 OpenCV 库版本链接警告;本版没有处理这些独立环境问题。 + +测试在 `ROS_LOCALHOST_ONLY=1 ROS_DOMAIN_ID=219` 中使用合成点云/位姿,无底盘、无雷达、无真机指令。FSM 测试将位姿直接放到局部端点,使用固定测试地图来隔离这种非物理瞬移对滑动缓冲区的影响,并按实际控制器重复发送当前轨迹编号的完成反馈;没有据此验证连续滑动地图的正确性。验证覆盖: + +- 占据端点保持原值、阻塞超时失败、清除障碍后同一任务恢复;5 m 意图跨局部窗口续行,不能在约 3.5 m 处报成功。 +- 0.5/1/1.5/3 m 目标能够通过新的终点拟合检查并发布最终轨迹;这是合成位姿下的规划检查,不等于实车停车回归。 +- 无授权、错误轨迹编号、HOLD 均输出零速度;中间窗口不对齐最终 yaw,最后窗口等待 yaw;全零四元数仍跳过朝向对齐;感知 false 独立停车。 +- 地面删除、20/40 cm 顶面保留与填充、原始混合体素不求质心、陡斜面/墙面/台阶顶面不冒充地面、过期/时间回退失效、近地残差不填高柱、ROS 超时与 frame 错误、进程正常退出。 +- 原有参考路径工具及发布器检查。 + +最终测试结果:`scan_planner` 17 项、`obstacle_cloud` 9 项,共 26 项,0 errors、0 failures、0 skipped。构建和测试日志分别在工作区 `log/latest_build/`、`log/latest_test/` 及 `build/*/test_results/`。 + +静态包只读复算脚本: + +```bash +cd /home/xie/RC2027_BR_code/minco_ws +source /opt/ros/humble/setup.bash +source install/setup.bash +OPENBLAS_NUM_THREADS=1 python3 docs/diagnostics/check_static_obstacle_cloud.py \ + log/field_b_raw_static_01/bag/bag_0.db3 \ + --output log/field_b_raw_analysis/obstacle_filter_regression.json +``` + +使用帧尾邻近 odom 变换原始点,属于静态近似,**没有验证在线 `/cloud_registered_full` 的运动去畸变**,也没有重现整套射线概率地图。692 帧中前 4 帧地面尚未确认,688 帧满足模型条件。几何处理耗时中位约 7.4 ms、95 分位约 14.2 ms;不包含真实并发负载和 ROS 点云序列化,不能作为整车 20 Hz 已达标的结论。第 370 帧原诊断点 Q 不再被这批过滤输出的膨胀源覆盖,8 点混合质心也不再生成;Q 不是实际导航目标,不能据此宣称通道已通。20/40 cm 保留由合成几何测试验证;实际台阶的完整在线保留仍要现场录包检查。 + +这些结果不能证明 1.35 m 窄道已可靠通过。第三次试验中的大回折轨迹、跟踪误差、原始目标是否放在车心可行带内,仍须闭环回归,不能用允许倒车的原参数替代验证。 + +## 第一轮静止测试步骤(已录制完成) + +1. 先量当前雷达光心离地高度,确认约 0.48 m;若明显不同,先告诉我实测值。 +2. 停掉原来的整套导航后,用下面命令重新起;车辆保持静止,不发目标: + +```bash +cd /home/xie/RC2027_BR_code/minco_ws +source /opt/ros/humble/setup.bash +source install/setup.bash +ros2 launch scan_planner vehicle_bringup.launch.py \ + launch_chassis:=false use_obstacle_cloud:=true launch_rviz:=true +``` + +3. 另一终端 source 同一环境,录约 30 s,Ctrl+C 结束: + +```bash +ros2 bag record \ + --qos-profile-overrides-path docs/diagnostics/b_baseline_qos.yaml \ + -o log/field_b_obstacle_static_01/bag \ + /livox/lidar /livox/imu \ + /cloud_registered /cloud_registered_full /cloud_obstacles_for_scan \ + /cloud_registered_for_scan /aft_mapped_to_init /body_odom \ + /grid_map/occupancy /grid_map/occupancy_inflate \ + /planning/perception_ready /planning/perception_diagnostics \ + /planning/trajectory_status /cmd_vel /tf /tf_static +``` + +可同时保存参数: + +```bash +ros2 param dump /obstacle_cloud > log/field_b_obstacle_static_01/obstacle_cloud.yaml +ros2 param dump /scan_planner_node > log/field_b_obstacle_static_01/planner.yaml +``` + +验收看:完整点云及过滤输出持续出数;地面不填满平路;20/40 cm 台阶边缘和顶面均保留为障碍;就绪信号是否稳定、每帧耗时及云→地图延迟是否足够小;膨胀后车心通道是否连续。RViz 点云选 Best Effort。先不要靠缩小半径或增大 blind 让通道“变通”。 + +静态验收通过后,再做下面两轮: + +- 开阔平地先用默认感知支路,回归 0.5/1/1.5/3 m 定点,记录实际停点和 `/planning/trajectory_status`;然后验证贴墙起始、掉头、倒车、指定终点 yaw、全零四元数。这里验的是本版控制/任务状态变化。 +- 再开启实验支路复测同样场景,最后做窄道低速通行与真实障碍阻塞/移除。把目标放在实际测定的平路中心带,不能默认世界坐标 `(5,0)` 必然是中心。每次记录状态、轨迹、cmd_vel、里程计和两层地图,确认停车是 SUCCEEDED、HOLD 还是 FAILED。 + +模式 3 参考路线和模式 2 预设点序列若要用于真机,也须单独回归;本次状态机的进程级走行测试使用模式 1。未做实车回归前,不把本版标记为已解决窄道通行问题。 diff --git a/minco_ws/docs/B_RECTANGLE_IMPLEMENTATION_2026-11-01.md b/minco_ws/docs/B_RECTANGLE_IMPLEMENTATION_2026-11-01.md new file mode 100644 index 0000000..8177018 --- /dev/null +++ b/minco_ws/docs/B_RECTANGLE_IMPLEMENTATION_2026-11-01.md @@ -0,0 +1,88 @@ +# 80×80 cm 矩形碰撞与朝向保持:实现及验收 + +> 后续已有 81×80 cm 实测尺寸、IMU/光心原点修正及自身回波过滤,请按[2026-11-02 静止验收说明](B_SELF_FILTER_AND_STATIC_ANALYSIS_2026-11-02.md)操作;下文保留为上一阶段记录。 + +本轮按已经确认的完整外包络 80×80 cm 接入可选矩形模型。通道净宽 120 cm,右侧 10 cm 围栏和左侧台阶均保留为障碍。默认仍是原来 R=0.62 m 的圆形模式。 + +## 取证和实现选择 + +旧圆直径 124 cm,必然拒绝 120 cm 净宽;直接改成 40 cm 半径会漏掉方形车的四角。前一轮单帧理想几何说明矩形有通行潜力,但不能直接交给沿路径转向的原控制器。 + +本轮以完整障碍体素与矩形相交为碰撞,包含接触边界。新模型的默认长宽均 0.80 m,沿车体两轴每侧额外扩张 0.09 m;这是待验收的新模式候选裕度,未冒充原圆形模型已调好的参数。相比之前离线图中的各向同性圆角裕度,此实现使用更保守的方角扩张。 + +规划查询覆盖障碍体素和车心查询格内部的所有位置,再增加 ±0.035 rad(约 2°)朝向误差下的角点位移界。沿用原来的非对称垂直膨胀和参考高度,未抬高轨迹、忽略低围栏或改 LIO 参数。 + +将生产 C++ 几何函数用于已录 full 点云帧、并按最新实体柱规则表达障碍后:0° 连通到 x≈4.5 m;10°、45° 不连通。结果是 `log/field_b_footprint_analysis/implemented_kernel_comparison.json`。这仍然是单帧栅格连通性,未模拟概率地图全历史或实车跟踪。相比前一轮理想图的“10° 连通”,结果变化来自新增的保守量化、朝向误差界和方角裕度,不能按旧图允许车头偏 10° 通行。 + +## 运行行为 + +- 只在显式 `use_rectangle_footprint:=true` 时启用;目前限定 `navi_mode:=1` 手动目标,并要求感知就绪及控制器完成反馈。整机 launch 在启动硬件前拒绝缺失感知支路的矩形配置。 +- 接收新目标时先 HOLD,取当时实际车头 yaw 作为整个任务的固定朝向,再重建膨胀缓存。A*、优化器和轨迹检查共用这一朝向,不取路径切向。全向底盘可向前、后或侧方平移。 +- 膨胀使用原来的增量计数缓存,查询仍为 O(1)。换任务朝向时只重建膨胀层,原始概率占据数据保留。滑动移入的新栅格补齐保留障碍的矩形膨胀,避免原始占据未变化时漏更新;斜向移图的重叠区域不重复计数。RViz 的 `/grid_map/occupancy_inflate` 对应当前任务矩形模型;`/self_inflation` 用实际 yaw 显示含基础裕度的矩形截面,不代表车体实际高度。 +- 转向直接在原始占据层检查矩形的连续扫掠,用不大于 0.05 rad 的角采样和采样间角点位移界覆盖中间角度。90° 的两个端点都放得下,也可能在 45° 途中碰撞。 +- 目标指定朝向时,先检查目标位置周围整个 8 cm 到达容差内的转向空间;空间不足保留原目标,HOLD、重试并按既有超时报 FAILED。全零四元数仍跳过终点朝向对齐。 +- 20 Hz 安全检查覆盖实际姿态、实际位置到当前参考点的修正段,以及剩余整条矩形轨迹;通过后才发布 ACTIVE。控制器要求相同轨迹 ID、矩形标志、有效朝向、200 ms 内的新鲜检查及里程计。数据过期即停止,并冻结参考时间。 +- 角差超过 2° 时停止平移;只有扫掠检查允许时才转回固定朝向。终点对齐有独立转向许可,不能继承平移许可。到达后离开固定朝向也不会重新开始平移。 + +原圆形半径、偏移、body_height、地面高度、LIO 配置,以及控制器 P/D、前视、死区、刹车和速度参数均保持原值。原模式继续按原逻辑使用路径方向和倒车判断。 + +## 文件及理由 + +| 文件 | 作用 | +| --- | --- | +| `plan_env/rectangular_footprint.h`、`grid_map.h/.cpp` | 体素与矩形 SAT、固定朝向缓存、实际姿态和转向扫掠查询,拒绝完整轮廓越出地图 | +| `scan_planner_msgs/msg/TrajectoryStatus.msg` | 同一任务/轨迹的朝向、转向许可与安全检查时间戳,防止跨轨迹继承许可 | +| `plan_manage/scan_replan_fsm.h/.cpp` | 目标朝向预检查、实际位姿检查、检查通过后授权运动 | +| `plan_manage/closed_loop_controller.cpp` | 新模式保持车头、角差限制、转向许可与检查超时停车 | +| `run_vehicle.launch.py`、`vehicle_bringup.launch.py` | 默认关闭的新模式开关及启动前配置校验 | +| 三个 `test_rectangle_*` | 真实 GridMap、控制器进程和 FSM 的隔离验证 | + +以上路径均位于 `minco_ws/src/scan/` 下。修改混合行尾文件采用定点字节替换;不涉及备选导航目录。 + +## 先做静止验收 + +更新后先停止旧整机 bringup,并确认原底盘桥随之退出,再启动下面的静止配置;避免混用旧版消息接口与新节点。新增状态字段也改变了消息定义:旧 bag 的 `TrajectoryStatus` 应按旧定义读取,不能直接用新版结构解码;点云和里程计定义未变。**本轮需要先静止录制,不要直接发 5 m 目标。** 车放在同一入口、车头沿平路通道摆正,底盘串口桥不启动: + +```bash +cd ~/RC2027_BR_code/minco_ws +source /opt/ros/humble/setup.bash +source install/setup.bash +ros2 launch scan_planner vehicle_bringup.launch.py \ + launch_chassis:=false \ + use_obstacle_cloud:=true use_rectangle_footprint:=true \ + navi_mode:=1 launch_rviz:=true +``` + +另一个终端 source 相同环境,车全程静止,不发目标,录 30–40 秒: + +```bash +mkdir -p log/field_b_rectangle_static_01 +ros2 bag record -o log/field_b_rectangle_static_01/bag \ + --qos-profile-overrides-path docs/diagnostics/b_baseline_qos.yaml \ + /body_odom /aft_mapped_to_init \ + /cloud_registered_full /cloud_obstacles_for_scan /cloud_registered_for_scan \ + /grid_map/occupancy /grid_map/occupancy_inflate /self_inflation \ + /planning/perception_ready /planning/perception_diagnostics /planning/trajectory_status \ + /planning/bspline /planning/go2_execution_frozen /cmd_vel /rosout +``` + +检查目标:围栏实体柱从下到上连续;两侧障碍仍在;矩形车心可行带存在且稳定;感知连续就绪;无目标时 `/cmd_vel` 恒零;新版实体柱、膨胀及可视化共同运行时不过载。还需实物核实 `/body_odom` 参考点确实对应 80×80 cm 外包络的几何中心,安装偏心不能用裕度代替。 + +## 静止验收后再做运动回归 + +先在开阔平地沿用已有安全操作,以显式低速覆盖 `max_vel:=0.10 max_vy:=0.10 max_vyaw:=0.15` 做 0.5/1/1.5/3 m、横移、倒车;指定终点朝向及全零四元数分别验收。以上是本轮首次测试的速度覆盖,未写回实测基线 YAML。贴墙起步和转向必须确认扫掠空间不足时停车,不以缩目标或删除回波“通过”。 + +最后才进入通道,从 0.5 m、1 m 的位置目标逐步增加到穿过最窄处。起始车头对齐,目标不要求在通道中转向;手写位置目标需显式使用 `orientation: {x: 0.0, y: 0.0, z: 0.0, w: 0.0}` 才能明确跳过终点对齐;本机 ROS 的 Quaternion 默认 `w=1`,不能用“省略 orientation”代替。不要直接用 RViz 默认世界 yaw=0 的目标去要求车辆在通道里掉头。观察实际角差、左右最小间隙及新的 HOLD 原因;停车应先取证,不能继续放宽裕度。 + +软件测试不等于上述真机回归已通过。新的实体柱在线负载和实际跟踪误差仍需本次静止及低速录制验证。 + +## 本轮软件验证结果 + +- 依赖及规划器均按 `MAKEFLAGS=-j2`、单包串行构建完成;最终受影响的 `plan_env`、`scan_planner` 重建通过。 +- 独立本机域 `ROS_LOCALHOST_ONLY=1 ROS_DOMAIN_ID=219` 下,`scan_planner` 25 项、`obstacle_cloud` 10 项,共 **35 项实际测试全部通过**。`colcon test-result` 汇总 48 项、0 错误/失败/跳过,其中还包含 CTest 层的汇总条目,不把它们重复计为新增行为测试。 +- 新增 6 项 C++ 几何/GridMap 测试,以及矩形控制器和 FSM 各 1 项进程集成测试;覆盖完整体素、车心亚格位置、允许角差、地图边界、垂直膨胀、朝向重建、斜向移图及删除计数、侧移保持朝向、转向拒绝和过期停车。 +- 修正测试里“四元数默认全零”的错误假设,显式填写 w=0 后重新通过全零四元数用例。运行代码的全零处理未被放宽。 +- YAML 解析后与 git HEAD 的原参数字典一致;控制器参数文件未改动;混合行尾变更检查通过。 +- 构建有仓库现存的 PCL/CMake、未使用参数及 OpenCV 链接警告;本轮无编译或测试失败。没有启动真机雷达、底盘桥或在真实 ROS 域发布运动指令。 + +完整测试输出:`/tmp/codex_scan_test_results.log`;详细测试条目位于 `build/scan_planner/test_results/` 和 `build/obstacle_cloud/test_results/`。需要在真机重新验收的场景及录制命令见上文,软件结果不代替实车结论。 diff --git a/minco_ws/docs/B_SELF_FILTER_AND_STATIC_ANALYSIS_2026-11-02.md b/minco_ws/docs/B_SELF_FILTER_AND_STATIC_ANALYSIS_2026-11-02.md new file mode 100644 index 0000000..3b2b89c --- /dev/null +++ b/minco_ws/docs/B_SELF_FILTER_AND_STATIC_ANALYSIS_2026-11-02.md @@ -0,0 +1,132 @@ +# 自体回波、坐标原点与矩形静止验收(2026-11-02) + +## 本次录包的结论 + +`log/field_b_rectangle_static_01/bag/` 共 43.016 秒。当前版本不能据此进入窄道运动测试。 + +| 检查项 | 数据 | +| --- | --- | +| 原始 full / 障碍 / 送图点云 | 860 / 861 / 861 帧,约 20 Hz | +| 感知就绪 | 861 条全为 true,无大于 200 ms 的心跳间隔 | +| 点云透传一致性 | 861 对相同头时间戳消息,完整序列化内容全部一致 | +| 速度输出 | 4230 条全部为零,约 100 Hz | +| 目标/轨迹 | HOLD 等待目标;无 B 样条,不包含运动或 ACTIVE 安全授权验收 | +| 实际车心处膨胀占据 | 655/655 帧占据 | +| 感知节点处理耗时 | 中位 12.79 ms,p95 29.97 ms,最大 50.81 ms | +| 原始 / 膨胀可视化点云 | 约 16.87 / 15.28 Hz;膨胀接收最大间隔 209.6 ms | + +可视化频率低于 20 Hz 说明此录制负载下的显示/传输链路存在开销,但不能把其接收间隔等同于碰撞检查周期。由于没有 ACTIVE 任务,本包不能证明真实负载下安全授权心跳满足 200 ms 时限。 + +## 起点被封住的证据 + +从实际原始占据重建矩形膨胀,与 33 对录制地图在所比较的通道 ROI 中 **全部零差异**。起点的阻塞来自真实写入原始占据层的点,并非仅 RViz 显示或膨胀计数残留。 + +车尾两角附近,原始占据体素约位于 world `x=-0.425 m`,`y=±0.375..0.425 m`,在 `z=-0.375..-0.175 m` 形成柱。full 点云在这两处共有 120 个测量回波,观测高度主要为拟合地面上方 40–46 cm;它们被实体柱规则填到较低车体查询高度后,把车心封住。用户说明车后没有外部物体,可能是车体部件。 + +因此,自身过滤必须在原始测量点的体素化、地面拟合和实体柱生成之前进行,不能只在膨胀图中挖空车周围。 + +## 最新实测尺寸及原点换算 + +用户补充:从雷达光心垂直投影到前/后/左/右边沿分别为 **38.5 / 42.5 / 40 / 40 cm**。按这些较新的测量值,保守采用物理外包络 **81×80 cm**,车体几何中心在光心后方 2 cm。 + +已读活动 Point-LIO 代码:`pointBodyLidarToIMU()` 使用 `p_IMU = R_L_I*p_lidar + T_L_I`,`publish_odometry()` 发布滤波状态的 IMU 位姿。当前配置固定: + +```text +R_L_I = identity +T_L_I = (-0.011, -0.02329, +0.04412) m +``` + +因此,车体平面几何中心在 IMU 系为: + +```text +x = -0.011 + (0.385 - 0.425)/2 = -0.031 m +y = -0.02329 + (0.400 - 0.400)/2 = -0.02329 m +``` + +旧 `body_odom` 的 `(-0.015, 0)` 不能直接作为新实测矩形的几何中心。**仅矩形模式**改用上述计算偏移,物理长宽传入 0.81/0.80;碰撞参考高度 `offset_z=-0.23` 和 yaw 参数沿用原值。圆形模式仍读取原参数文件的 `(-0.015, 0)` 默认值;原参数文件数值不改。单独启动 `run_vehicle.launch.py` 时不会重启或重配已经运行的 `body_odom`,矩形模式必须配合上述中心外参;下面的整机静止命令会自动计算并传递这些值。 + +## 已实现的过滤与保护 + +`use_self_filter:=true` 为默认关闭的独立开关,要求启用 `use_obstacle_cloud:=true`。 + +1. 点云先由匹配时间戳的 IMU 位姿,使用完整四元数和固定外参换回光心坐标,再对实测盒 `x∈[-0.425,0.385]`、`y∈[-0.4,0.4]`、`z∈[-0.48,0]` 裁除自身点。删除范围不向外扩张。 +2. full 点云早于对应里程计到达时,暂存有限帧等待匹配位姿;匹配角度使用完整旋转,允许的头时间戳差不超过 30 ms,仍受既有 250 ms 数据时效限制。姿态无效、缺失或不同步时不授权运动。 +3. 对盒外 2 cm 的**水平边界待确认区**,点仍作为障碍保留、照常生成保守实体柱,同时发布感知未就绪。该范围覆盖本包观测到的最大约 1.3 cm 越界;它是暂停诊断区,不是扩大的删除区。地面模型未确认时仍不发布点云;边界异常且地面已经确认时向地图发布保守障碍云,防止仅丢弃异常帧后又错误恢复通行。 +4. 启动前核对测量配置中的雷达/IMU 外参与活动 MID360 配置一致,并要求固定单位旋转;不支持的标定配置会明确拒绝启动新模式。 +5. 诊断消息补充 `self_removed`、`self_boundary_points`、`publish_blocked_cloud`、`cloud_stamp`、`pose_stamp` 和 `self_filter_enabled`,便于验证实际启用状态和时序。 + +矩形模式的新目标起步改用当前实测速度,避免继承已被 HOLD 取消/冻结的旧轨迹速度;从 `body_odom` 透传的车体系速度先换到世界系再参与规划。此更正限定矩形模式,圆形模式保持原行为。 + +没有改动 LIO 输入或算法、blind、地面分离带、膨胀安全裕度以及已调好的控制增益。 + +## 对本包的离线复核 + +使用全部 860 个 full 帧、最近时间戳的记录 IMU 位姿,运行实际新增几何/过滤函数: + +- 精确实测盒内删除 **112 个**车尾测量回波。 +- **8 个回波、分布于 8 帧**在实测盒外,最大约 1.3 cm;保留为障碍并令就绪为 false。 +- 从录包起点重新建立地面模型:4 帧地面待确认,848 帧就绪,8 帧自身边界待确认。原包开始录制前已启动约 40 秒,所以这 4 帧属于离线重建暖机,不代表在线原包曾未就绪。 +- 地面已确认的 **856/856 帧**,距车体超过 1 m 的输出点数组与相同输入/位姿下未开启自身过滤的结果完全相同;选定围栏、台阶 ROI 的测量点删除数均为 0。 +- 离线 core 耗时中位约 7.69 ms、p95 14.47 ms、最大 25.48 ms;不包含 ROS 编码、传输、等待位姿和地图更新,不能当作在线时延结论。 + +这没有删除实测盒外的 8 个回波,也没有清掉原图中的相应旧占据。它们仍可能使重新运行后的起点保持 BLOCKED,需要下一次原始雷达数据区分真实越界、测量误差和世界点云运动补偿残差。当前不宣称自身问题已经完全消除。 + +前方约 3.7–4 m 的封闭是另一项限制。阻塞点 `(4.325,0.425)` 所在 XY 体素中,在录制 full 数据里既有地面回波,也有大量地面上方 8–42 cm 的真实障碍回波,不能统一按地面删除。离线去掉已定位车尾源后,现有保守查询仍只连通到约 3.725 m;精确点位诊断改变了部分连通结果,但未构成连续轨迹证明,尚未接入运行代码。 + +## 涉及文件 + +| 路径(相对 `minco_ws/src/scan/`) | 改动理由 | +| --- | --- | +| `obstacle_cloud/obstacle_cloud/core.py` | 实测自身盒、完整姿态变换、在实体柱前过滤、保留盒外障碍并抑制就绪 | +| `obstacle_cloud/obstacle_cloud/node.py` | 位姿时间匹配及等待、异常状态保护、诊断字段 | +| `obstacle_cloud/config/flat_corridor.yaml` | 集中保存本车测量值,过滤默认关闭 | +| `plan_manage/launch/vehicle_bringup.launch.py` | 从同一测量配置计算矩形中心/尺寸,新模式校验外参,传递自身过滤开关 | +| `plan_manage/launch/run_vehicle.launch.py` | 接受实测 81×80 cm 矩形尺寸 | +| `plan_manage/src/scan_replan_fsm.cpp` | 新矩形目标使用实测起步速度并正确换算到世界系,避免继承取消轨迹的运动状态 | +| `obstacle_cloud/test/test_core.py`、`test_self_node.py` | 自体柱、旋转外参、外部围栏/台阶、边界及时间对齐测试 | +| `plan_manage/test/test_rectangle_launch.py` | 实际 launch 的规划/控制模式参数、尺寸及冻结信号测试 | + +## 下一次只做静止验收 + +先退出旧整机 bringup 和底盘桥,重新启动空地图。**暂不发目标,不启动底盘桥。** + +```bash +cd ~/RC2027_BR_code/minco_ws +source /opt/ros/humble/setup.bash +source install/setup.bash +ros2 launch scan_planner vehicle_bringup.launch.py \ + launch_chassis:=false use_obstacle_cloud:=true \ + use_rectangle_footprint:=true use_self_filter:=true \ + navi_mode:=1 launch_rviz:=true +``` + +另一个终端 source 相同环境,录 30–40 秒。本次额外录原始 `/livox/lidar`,用于核对少数盒外回波在其原始光心坐标下的位置;当前包只有世界系 full 点,无法无损恢复每点进入运动补偿前的坐标。也录参数事件,核对运行配置。 + +```bash +mkdir -p log/field_b_self_static_01 +ros2 bag record -o log/field_b_self_static_01/bag \ + --qos-profile-overrides-path docs/diagnostics/b_baseline_qos.yaml \ + /livox/lidar /parameter_events \ + /body_odom /aft_mapped_to_init \ + /cloud_registered_full /cloud_obstacles_for_scan /cloud_registered_for_scan \ + /grid_map/occupancy /grid_map/occupancy_inflate /self_inflation \ + /planning/perception_ready /planning/perception_diagnostics \ + /planning/trajectory_status /planning/go2_execution_frozen \ + /planning/bspline /cmd_vel /rosout +``` + +期间关注 `self_filter_enabled=true`、实际移除数量、边界待确认帧、车尾柱与车心占据,以及围栏/台阶保留情况。实际矩形显示含基础裕度的尺寸应为 **0.99×0.98 m**。边界异常要保留数据,不能通过扩大裁剪范围或减小碰撞裕度来取消报警。 + +原始数据和分析脚本在 `log/field_b_rectangle_analysis/`,新增过滤几何与离线复核在 `log/field_b_self_filter_analysis/`。 + +## 最终软件验证 + +`obstacle_cloud`、`scan_planner` 已构建;控制器已强制重新编译,并在实际 `run_vehicle.launch.py` 的隔离启动测试中核对矩形模式、感知门禁、实测长宽及冻结输出。上一阶段的冻结异常与安装产物未完整反映最后源码有关,本轮通过重编译和该集成测试补齐验证。 + +本轮最后一次完整回归:独立本机 `ROS_DOMAIN_ID=219`、`ROS_LOCALHOST_ONLY=1`,`scan_planner` **27 项**、`obstacle_cloud` **15 项**,共 **42 项实际测试全部通过**。`colcon test-result` 报告 57 项、0 错误/失败/跳过,其中额外条目为 CTest 汇总,不重复计作实际行为测试。 + +覆盖自身回波在实体柱前去除、完整姿态/外参、盒外障碍保留及未就绪信号、延迟位姿匹配、外部围栏/台阶不变、实际 launch 的模式/尺寸/默认中心偏移、取消旧任务后的静止起步,以及 yaw=90° 时车体系前进速度换算成世界系 +y。新矩形 FSM 集成测试日志显示,重新接收任务时起步速度为零;90° 用例起步速度为 `(约0, 0.1, 0)`,没有沿错轴继承旧轨迹速度。 + +解析后比对 git HEAD:`planner_vehicle.yaml`、`controllers_vehicle.yaml`、`body_odom.yaml`、`mid360.yaml` 的原参数字典均未变化。新矩形长宽和中心为 launch 的显式新模式覆盖,自身过滤默认关闭。混合行尾检查通过。 + +详细结果:`/tmp/codex_scan_test_results.log`,以及两包 `build/*/test_results/`。本轮未启动真机雷达、底盘桥或在真实 ROS 域发送运动指令;上述仍不代替新的静止和运动验收。 diff --git a/minco_ws/docs/B_STATIC_RAW_ANALYSIS_2026-11-01.md b/minco_ws/docs/B_STATIC_RAW_ANALYSIS_2026-11-01.md new file mode 100644 index 0000000..1602ccf --- /dev/null +++ b/minco_ws/docs/B_STATIC_RAW_ANALYSIS_2026-11-01.md @@ -0,0 +1,133 @@ +# 静态原始点云对照分析(2026-11-01) + +数据:`log/field_b_raw_static_01/bag/`、`pointlio.yaml`。直接只读解析 SQLite,未回放、未启动硬件、未修改运行源码/launch/YAML。现场布局仍为左侧 20/40 cm 台阶障碍、右墙、中间 1.35 m 平路。 + +## 1. 结论 + +**找到一个有逐点证据的感知问题:当前把用于定位的 0.5 m 体素质心点云也用于精细避障,同一体素里的地面点与较高边缘点被平均后,会在两表面之间形成实际不存在的中间表面点。** 新点向平路方向移动并升高,继续硬膨胀后会挤占通道车心可行带。 + +这项结论来自原始点与实际 LIO 输出的一一数值对应,不仅是猜测“滤波可能太粗”。它能解释窄道占据不稳定的一个重要来源,但不能逐点证明此前动态试验的每个异常点均来自同一机制;旧包没有原始 CustomMsg。此外,原始目标被覆盖和持续重规划失败的任务状态问题仍须独立修复。 + +**不要直接减小 Point-LIO 的定位滤波参数,也不要仅切换地图输入就立即进行闭环试跑。** 数据还显示按当前模式 1 车体参考高度进行离线查询时,部分原始地面点本身就可膨胀到查询体素;需要把地面语义和高度一起验收。 + +## 2. 数据完整性 + +录制约 34.638 s,207 MiB 左右: + +| 话题 | 消息数 | 说明 | +| --- | --- | --- | +| `/livox/lidar` | 692 | 原始 CustomMsg,约 20 Hz | +| `/cloud_registered` | 693 | LIO 的定位降采样输出 | +| `/cloud_registered_for_scan` | 693 | 输入地图的点云 | +| `/aft_mapped_to_init` | 3158 | 完整 IMU 状态里程计 | +| `/body_odom` | 3158 | 现有车体参考里程计 | +| `/livox/imu` | 6929 | 约 200 Hz | + +Point-LIO 运行参数与第三次窄道试验文件完全一致:surface voxel=0.5 m、map voxel=0.5 m、blind=0.55 m,其他参数也一致。 + +逐帧对比全部 693 对相同 header 时间的 `/cloud_registered` 与 `/cloud_registered_for_scan`:XYZ 顺序与数值一致。因此本包中的 step_blocker 没有制造这些中间表面点。 + +从 692 个原始帧每隔 10 帧抽取一帧,共 70 帧。按现有 line/tag/盲区规则过滤,并把原始帧尾时间与 LIO 输出 header 对齐,配对时间差中位数为 0;以邻近 odom 做静态坐标变换。每帧平均约 9088 个有效原始点、1615 个 LIO 输出点。 + +离线以 0.5 m 分桶求质心,并变换到世界系,能重现输出点结构。部分帧存在厘米级的近邻差,符合离线使用帧末最近 odom 与运行时逐时间批状态变换的区别;下面选择的是实际输出与质心对应误差约 7.2e-8 m 的具体样本。 + +## 3. 一组直接可复核的原始点 + +抽样索引 370(从 0 开始)的帧:header 起始时间 `1793533046.0257082`,LIO 输出 header=`1793533046.0752091`。以下为原始雷达坐标系,单位 m。 + +同一 0.5 m 体素范围: + +```text +x: [4.0, 4.5) +y: [0.0, 0.5) +z: [-0.5, 0.0) +``` + +其中包含 8 个原始有效点: + +| x | y | z | 几何分组 | +| --- | --- | --- | --- | +| 4.063 | 0.498 | -0.146 | 较高边缘 | +| 4.279 | 0.092 | -0.456 | 地面状低表面 | +| 4.242 | 0.194 | -0.454 | 地面状低表面 | +| 4.208 | 0.293 | -0.452 | 地面状低表面 | +| 4.205 | 0.394 | -0.454 | 地面状低表面 | +| 4.407 | 0.481 | -0.318 | 较高边缘 | +| 4.131 | 0.487 | -0.448 | 地面状低表面 | +| 4.010 | 0.499 | -0.152 | 较高边缘 | + +5 个低表面点的平均 z 为 -0.4528;3 个高边缘点的平均 y 为 0.492667。8 点全部求均值得到: + +```text +离线质心(雷达系): (4.193125, 0.367250, -0.360000) +实际 LIO 输出逆变换回雷达系:(4.193125, 0.367250, -0.360000) +``` + +两者欧氏差约 7.2e-8 m。实际发布的世界系点为 `(4.195190,0.361246,-0.278558)`。 + +这个平均点比低表面抬高约 **9.28 cm**,相对高边缘组向较小 y 的平路方向偏移约 **12.54 cm**。原始点呈低平面与高边缘两组,平均点位于两组之间,不能作为真实障碍表面的位置。 + +单这个位移量就超过名义上 `1.35-2×0.62=0.11 m` 的整个车心可行带宽。不能因此保证每帧都堵死,但足以让一条原本很窄的可行带因抽样/体素相位变化而中断。 + +## 4. 统计及独立碰撞几何对照 + +70 帧抽样内,统一取雷达系 ROI:`4 用法:整段复制 `====` 之间的内容发给 Codex。 +> 本文件是**给 AI 的上下文**,不是给人看的文档。保持精炼,别扩写成教材。 + +--- + +``` +================================================================ +# 角色与边界 + +你是这台轮式全向机器人的导航/控制开发助手。 +工作区:/home/xie/RC2027_BR_code/minco_ws (git 仓库 RC2027_BR_code 的 minco_ws/ 子目录) + +【最重要的约束】 +1. 这是一台**真机**,已经在跑闭环控制,参数是逐项实测调出来的。 + 任何参数改动都必须说明「为什么现在这个值是坏的」,不允许"顺手优化"。 +2. **先诊断,后改代码**。下面每个问题我都给了排查假设,请先按假设取证, + 把日志/数据贴出来,再提方案。不要一上来就重写模块。 +3. 改任何 C++ 前,先读该文件现有注释 —— 里面记了大量"为什么不能这么改"的 + 实测结论(尤其 closed_loop_controller.cpp 和 controllers_vehicle.yaml)。 +4. 不要碰 minco_ws/src/navigation/ 和 sru_ws/。那是两套备选方案,未启用。 + +# 一、先建立心智模型(必读,别跳过) + +数据流: + Livox MID360 (上方, ±7° 垂直视场) + → livox_ros_driver2 (xfer_format=1, publish_freq=20, multi_topic=0) + → Point-LIO (紧耦合 LIO,无回环) 输出 /aft_mapped_to_init (odom) + /cloud_registered + → body_odom (只做坐标变换: offset_x=-0.015, offset_z=-0.23) 输出 /body_odom + → step_blocker (台阶过滤, 当前 regions="" 即纯透传) → /cloud_registered_for_scan + → grid_map (滑动窗口体素占据, 10×10×5 m, res 0.05) + → A* (26 邻域, 允许斜向) → 均匀 B 样条(3 阶) → closed_loop_controller → /cmd_vel + → chassis_serial (techx_r2, omega_sign=-1.0, 限幅均 0.5) → 串口 + +FSM 状态:INIT / WAIT_TARGET / GEN_NEW_TRAJ / REPLAN_TRAJ / EXEC_TRAJ / EMERGENCY_STOP +navi_mode: 1 = /move_base_simple/goal(手动目标), 3 = /initial_path(参考路径) + +包名 ≠ 目录名:plan_manage 目录的**包名是 scan_planner**。 +colcon --packages-select / --packages-up-to 接包名,写 plan_manage 会报 unknown package。 +plan_env 目录包名是 plan_env,path_searching 目录包名是 path_searching。 + +# 二、当前基线参数(已验证可用,改动前请先解释原因) + +规划/栅格 (planner_vehicle.yaml): + resolution 0.05 + double_cylinder_radius 0.62 ← 注意:这是**半径**,不是直径 + double_cylinder_offset 0.0 ← offset=0 时朝向不影响占位(见下) + obstacles_inflation_xy 0.0 ← 额外裕度(叠加在车体半径上) + body_height 0.41 ← 语义陷阱:不是车体高度! + z_traj = waypoint.z + body_height + (曾改 0.25,15° 坡上必被膨胀判碰撞,已回退) + ground_height -0.55 + obstacles_inflation_z_up 0.15 / z_down 0.05 + +控制 (controllers_vehicle.yaml): + time_forward 0.8, min_lookahead_dist 0.35 + kp_pos 0.5(同时承担末端刹车), kd_vel 0.05, vel_filter_tau 0.08, pos_deadband 0.03 + goal_slow_gain 0.5, goal_v_floor 0.05 + max_vx 0.50 / max_vy 0.40 / max_vyaw 0.50(必须 ≤ 底盘限幅,否则被静默截断) + finish_dist 0.08, align_to_goal_yaw true, yaw_goal_tolerance 0.10 + allow_reverse true, reverse_yaw_threshold 2.1 + +雷达/里程计: + mid360.yaml: blind 0.55, blind_center_enable true + ⚠️ blind 是**球形剔除**,不是水平面剔除。走廊半宽 0.675 m 时, + blind=0.60 会把真墙一起删掉 → 正反馈推着车撞墙。 + 0.55 是实测能过窄道、又不删墙的上界,**不要再往上调**。 + +RViz(rviz/vehicle.rviz,用 launch_rviz:=true 加载): + /grid_map/occupancy 未膨胀,绿色,Style: Boxes ← 障碍真实形状 + /grid_map/occupancy_inflate 已膨胀 ← 车中心禁区(半径 0.62 的圆) + /cloud_registered_for_scan, /grid_map/sliding_map_bbox + ⚠️ 所有 PointCloud2 必须设 Reliability Policy: Best Effort + 发布端是 SensorDataQoS,RViz 默认 Reliable → 不报错但**什么都不显示** + +# 三、待解决问题(按优先级) + +## 问题 B 优先于问题 A 处理 + +原因:B 的根因已经定位到代码(目标点被两个机制修改、且不可恢复), +改动小、收益大;而 A 的"撞过去"和 B 的路径退化很可能同源(见 A4)。 +先修 B 再看 A 是否还复现。 + +## 问题 A:避障偶发失效,有时直走撞过去 + +现象:35 cm 高纸箱放正前方 2 m,RViz 里能看到障碍,但车有时走直线撞上去; +偶尔又确实绕了(/planning/bspline 的 pos_pts 看起来拐了弯)。 + +已排除: + - RViz 显示问题(障碍确实进图层了) + - 雷达盲区(2 m 远,35 cm 高,按下面公式完全可见) + +请先查这几个方向(按可能性排序): + A1. **目标点被偷偷改掉**(与问题 B 同源,最可能)。请先读问题 B 的分析。 + 如果撞过去的方向恰好是"走廊尽头/你发目标的方向",几乎可以确定是 + 机制一(A* 的 end_pt += start_to_end)把终点推到墙外去了。 + A2. 局部规划 vs 全局轨迹不一致。车跟的是 /planning/bspline(局部重规划结果), + 不是全局轨迹。撞过去时请同时录这两个话题,看局部轨迹是否根本没绕。 + A3. EMERGENCY_STOP 是否触发过。查日志有无该状态、checkCollision 的返回。 + A4. 障碍进入地图的延迟。MID360 20 Hz + Point-LIO + grid_map 更新, + 从"看到"到"进栅格"有几十到上百 ms;0.5 m/s 下每 100 ms 走 5 cm。 + 若障碍是突然出现在近处(非静态场景),可能来不及。 + A5. 上面问题 B 提到的 -1 漏检:目标或中间点超出滑动地图(10×10 m)时, + isInMap 失败返回 -1,调用侧 `<= 0` 当作空闲。会让远处障碍"看不见"。 + +## 问题 B:窄道误判目标不可达,走到一半停下(重点) + +现象:窄道(实测宽 1.35 m)里,有时判定目标点被占据/不可达,车到半路停住。 +RViz 里看,路两边的膨胀圆柱把可通行空白区全部占满 —— 但现实中窄道 +从一开始到结束宽度**完全一致**。 + +【结论已确认(2026-10-31):目标点确实被修改。且有**两个独立的机制**在改它, + 方向相反、互不协调。这是本问题的根因,下面的分析已从代码逐行确认。】 + +── 机制一:A* 内部把终点**往外推**(dyn_a_star.cpp:122-141) + + 路径搜索时若终点落在膨胀层: + occ = checkOccupancy(Index2Coord(end_idx), path_yaw); + if (occ) { + do { + end_pt += start_to_end * step_size_; // ← 沿"起点→终点"方向继续前进 + ... + } while (occ); + } + + step_size_ = grid_map_->getResolution() = **0.05 m**(bspline_optimizer.cpp:138 + 传入的)。而膨胀半径 0.62 m ⇒ 最多要推 13 步 = 0.65 m。 + ⚠️ 关键:方向是 `start_to_end`,即**离起点更远**的方向。在走廊尽头做目标时, + 这个方向就是**撞向墙里**。若推几步出了地图,occ 变 -1 → 直接 return false + (打 "[Astar] End point outside the map region.")→ 规划失败。 + 若推出去了但还在图内,生成的路径终点就落在墙外侧。 + +── 机制二:FSM 把终点**往回收**(scan_replan_fsm.cpp:306 adjustGlobalTargetIfOccupied) + + 沿全局轨迹从后往前扫,`sample_dt = 0.05`,把 end_pt_ 改到第一个不占据的点, + 打 WARN: + "Target [x,y,z] is occupied; using [x,y,z]" + 连扫完都找不到才打 ERROR: + "Target is occupied and no collision-free point was found on the global trajectory" + +── 为什么这两条合起来会造成"走到一半停下": + + ⚠️ 最重要的一点:**代码里没有任何地方把 end_pt_ 恢复成用户发的原始目标。** + 函数内的 `raw_end` 只是打日志用的局部变量,写完就丢弃。 + + 于是 end_pt_ 是**单调后退、不可恢复**的。链条为: + 1. 用户目标落在膨胀层 → adjustGlobalTargetIfOccupied 缩到 pt_a,end_pt_ = pt_a + 2. 下一周期从 scan_replan_fsm.cpp:815 附近的分支重规划: + planGlobalTraj(odom, ..., end_pt_=pt_a) → 用**已经缩过的**目标重新生成全局轨迹 + 3. 紧接着**又调一次** adjustGlobalTargetIfOccupied() → 新轨迹终点 pt_a + 若仍被判占据,再缩到 pt_b + 4. 回到第 2 步。end_pt_ 一路后退,直到某个点彻底脱离膨胀层。 + ⇒ 车"走到一半停下"是终点**一点一点退过来**的结果,且退过去就不回来。 + + 这同时解释了两个现象: + - 为什么是"有时"失败:能否一次就找到安全终点、以及退几步才停下, + 取决于走廊的亚格偏移和当时点云的最新状态。 + - 为什么失败点随场景变化:退化点数取决于终点陷进膨胀层的深度。 + +── 第三个因素(几何,决定了上面两条为什么这么容易被触发): + + double_cylinder_radius = 0.62 在 rebuildInflationOffsets() 里是当**半径**用的: + inflate_radius = robot_radius(0.62) + extra_radius(0.0) = 0.62 + inf_step_xy = ceil(0.62 / 0.05) = 13 格 + 单层膨胀模型把机器人当**质点**,所以 RViz 里半径 0.62 的圆柱是 + **车中心**的禁区,不是车体轮廓 —— 看起来"太粗"是正常的。 + + 1.35 m 走廊两侧各吃掉 0.62: + 1.35 - 2×0.62 = **0.11 m** ≈ 2.2 格(res 0.05) + 也就是说整条走廊里车心只能走在两格宽的窄带上。走廊尽头的目标点几乎必然 + 落入"墙的膨胀层 + 侧墙膨胀层"的交叠区域 ⇒ 机制一必然被触发。 + + 补充:A* 是 26 邻域、**允许斜向**(dyn_a_star.cpp:227-259),所以 2 格通道 + 在被量化打断前仍可能斜向连通 —— 这正是"偶发"而非"必然"的原因。 + +── 顺带澄清两个容易搞错的地方: + + 1. yaw 不影响占位。getInflateOccupancy(pos, yaw) 里的 yaw 只通过 + double_cylinder_offset_ 起作用,而该值为 0.0。所以 allow_reverse 安全, + "车头朝向导致过不去"这个方向可以排除。 + 2. 存在一个方向**相反**的隐患(会造成漏检/撞墙,不是停下): + getInflateOccupancyFromBuffer() 里 isInMap() 失败返回 **-1**, + 而调用侧 `if (final_occ <= 0) return true` 把它当成"没占据"。 + 滑动地图 10×10 m,目标超出地图范围时会被当作空闲。 + 排查问题 A(撞过去)时请考虑这一条。 + +【建议的修复方向(请先评估,给方案,不要直接改)】 + + 优先级 1:**让 end_pt_ 可恢复**。保存一份 `raw_goal_`(用户原始目标), + 每次重规划都从 raw_goal_ 出发判断,而不是从上一轮缩过的 end_pt_ 出发。 + 这是最小、最安全的改动,能立刻消除"单调后退"。 + 需要想清楚:什么时候允许"真的"放弃原始目标并报失败(否则会永远缩下去)。 + + 优先级 2:**改掉 A* 的终点外推方向**。现在的 `end_pt += start_to_end` 在 + 走廊尽头等于往墙里推。合理做法是:终点被占据时沿**膨胀层梯度下降** + (离开障碍)方向外推,或者干脆**拒绝该次搜索并上报**,而不是偷偷改目标。 + 注意 start 点那侧用的是 `start_pt -= start_to_end`(往后推,方向是对的), + 只有 end 点这侧有问题。 + + 优先级 3:**终点判据单独放宽**。终点本身不参与 A* 的中间搜索,只用于生成 + 轨迹末端。可以对终点使用更小的膨胀半径(例如只做致命层检查), + 而不是和路径中间点用同一个 0.62 的硬膨胀。 + + 优先级 4(较大改动):引入 Nav2 式两层模型 —— 致命层用真实 footprint, + 膨胀层只做**软代价梯度**。当前是单层硬膨胀,把"车有多大"和 + "离墙多近"两件事压成了同一个数,这是窄道问题的结构性来源。 + (参数已拆出 obstacles_inflation_xy,但语义仍是硬膨胀叠加,不是软代价) + +验证建议(改动前先取证): + B1. 复现时 grep 日志:出现的是 WARN "is occupied; using" 还是 + ERROR "no collision-free point"?前者=机制二,后者=机制二顶到底。 + 再 grep "[Astar] End point outside the map region" 看机制一。 + B2. 打印 raw_end 与 end_pt_ 的差值随时间的序列。若差值单调增大, + 直接证实"单调后退、不可恢复"。 + B3. RViz 中量 /grid_map/occupancy(未膨胀)在两墙之间还剩多少格。 + 若未膨胀层就已贴得很紧,那是感知/定位问题,不是膨胀问题 —— 必须先排除。 + B4. 确认走廊真实净宽。若显著大于 1.35 m,说明墙被多扫进来了 + (雷达点云外扩 / blind 仍有影响),要先解决感知再谈规划。 + B5. 车体实际外包络请自己量(车长约 1.06 m)。等效半径取最大值, + 不要用长度。用来判断 0.62 是否合理。 + +## 问题 C:加装第二个 MID360 并与现有雷达融合 + +需求:底盘再装一个 MID360,位置更低,用于扫近处/低矮物体,与上方 MID360 融合。 + +已知约束(请在设计方案时正面回答): + - 上方 MID360 垂直视场 ±7°。可见最低高度与距离的关系实测拟合为 + H(d) = 0.48 - 0.1228 · d (H = 能看到的最低物高,d = 水平距离) + 所以 16 cm 高的纸箱要走到 **≥ 2.6 m** 才出现在点云里;1.5 m 处看不见 + (该处最低可见高度 29.6 cm)。这不是滤波问题,是几何问题。 + - 请说明:第二个雷达装多高,才能满足你们关心的"最低障碍物高度 × 最近距离"? + 给出高度建议和对应的可见性曲线。 + +需要你决定并说明理由的技术点: + C1. 融合在哪一层? + (a) 点云层:两个 livox driver 实例,两路 → 合并成一个话题 → 同一个 Point-LIO + (b) 里程计层:各自跑 LIO 再融合位姿(复杂度高,双 LIO 一致性难保证) + (c) 只在地图层融合:主雷达跑 LIO 供里程计,副雷达点云只喂 grid_map + → 我的倾向是 (a) 或 (c);(c) 风险最低(不动现有里程计,只增强感知)。 + 但 (a) 能让 Point-LIO 用上更多点,退化场景更稳。请评估后给结论。 + C2. livox_ros_driver2 怎么跑两个实例?必须给两份不同的 + xfer_format / multi_topic / 话题名 / 端口配置,否则两路会互相覆盖。 + 请指出具体要改哪几个字段。 + C3. 两路点云的时间同步与坐标系。外参怎么标(建议给出标定步骤)。 + C4. 点云合并后点数翻倍,grid_map 与 Point-LIO 的实时性是否还够? + 当前 20 Hz、res 0.05、10×10×5 m。请评估 CPU 负载并给出降载手段 + (降频 / 体素降采样 / ROI 裁剪)。 + +## 问题 D:MID360 + Odin1 融合(备选,用户会自己找开源资料) + +现状:Odin1 已存在(见 sru_ws 相关代码),但**未接入当前导航链路**。 +用户会去找现成的开源方案,你这里**先不要动手实现**,只需要: + D1. 说明如果接 Odin1,最可能插在哪一层(里程计冗余?还是点云补充?) + D2. 列出接入前必须确认的信息(话题、频率、坐标系、时间戳基准、外参) + D3. 指出与问题 C 方案的互斥/叠加关系(能不能同时做) + +## 问题 E:斜坡上的停车判定(后续实现,先给设计) + +需求:用 IMU 数据判断车是否在斜坡上。斜坡有倾角、平地是平的; +若 IMU 显示在平地则可停车。 + +设计前请先想清楚(这几点是这个需求真正的难点): + E1. 车在坡上静止时,加速度计测到的"重力分量"会被误认为是加速度。 + 你打算用加速度计算倾角,还是用陀螺积分 + 互补滤波?为什么? + E2. 全向轮底盘在坡上会**溜车**吗?若会,"允许停车"的判据里要不要 + 包含"轮速为零但姿态角不变"? + E3. 停车判据的时间窗。IMU 噪声会导致瞬时倾角跳动, + 如果用单帧判断,会在坡上误停车。建议多长的滑动窗口 + 多大阈值? + E4. body_height 0.41 与坡度的关系:坡面比脚下高 d·tanθ, + 15° 坡上 1 m 距离抬高 0.27 m。膨胀 z_up 只有 0.15。 + 这个已有冲突会不会在坡上重现碰撞误判?(见 planner_vehicle.yaml 注释) + +这里只要求**设计文档 + 参数表**,不要写实现代码。 + +# 四、已知坑(别重复踩) + +0. **【架构级】目标点被两处代码偷偷修改,且不可恢复。** + - dyn_a_star.cpp:122-141:终点被占据时 `end_pt += start_to_end * 0.05` + 循环外推,方向是"离起点更远"。 + - scan_replan_fsm.cpp:306:`adjustGlobalTargetIfOccupied()` 沿全局轨迹 + 往回缩 end_pt_,并**写死**到成员变量上。 + - **没有任何地方把 end_pt_ 还原成原始目标**(raw_end 只是局部变量)。 + ⇒ 结果是单调后退、缩了就不回来。任何涉及目标的改动都要先考虑这一点。 + 如果将来要给目标加"容错/自动修正",必须同时引入 raw_goal_ 并定义放弃条件, + 否则会重蹈覆辙。 + +1. LaunchConfiguration 是**全局作用域**。曾用同一个 params_file 变量名给 + body_odom / step_blocker / chassis 三个节点,结果 step_blocker 读到的是 + body_odom.yaml、chassis 静默回退到 2.5 m/s 限速(绕过 0.5 限幅)。 + 已改名为 blocker_params_file / chassis_params_file。新增节点时务必用独立变量名。 + +2. 底盘角速度符号反了会形成**正反馈**(车的实际转向与指令相反 → 越转越错)。 + 已在 chassis_serial.yaml 用 omega_sign=-1.0 在打包层修正,不要在别处再取反。 + +3. 全零四元数 ≠ yaw=0。手写 goal 消息若漏了 orientation, + closed_loop_controller 会警告并跳过朝向对齐,不会误当 0 处理。保持这个行为。 + +4. 到达判据必须是**空间量**(dist_to_goal),不能用"参考时间走完"。 + 曾用 exec_time_ >= duration,导致 vel_ff 在到点后仍推着车走 → 高速过冲。 + +5. goal_slow_gain 的方向容易搞反:**gain 越小刹车越早**。 + 开始减速距离 = max_vel / gain。gain=5.0 等于没限速(当年调 5 反而更糟)。 + +6. kd_vel 是横向 3~4 Hz 抖动的来源(放大器把 LIO 速度噪声变成指令抖动), + 所以只有 0.05。若日后重新出现过冲,先查到达判据,别急着加 kd。 + +7. 编译 OOM:colcon --packages-up-to 容易 exit 137。 + 用 --parallel-workers 1 + MAKEFLAGS="-j2"。 + 另注意 -DCMAKE_CXX_FLAGS="-O1" 会**持久化在 CMakeCache**, + 要清除必须显式传 -DCMAKE_CXX_FLAGS=""。 + +8. 编辑 grid_map.h / grid_map.cpp / vehicle.rviz 时注意行尾。 + 这几个文件是 **CRLF 与 LF 混用**的,用文本模式整体重写会产生上千行 + 空白 diff。必须按插入位置的原有行尾字节级插入。 + 自检:git diff 与 git diff -w 的输出应一致。 + +9. step_blocker.regions 目前是空字符串 = 纯透传。台阶过滤**没生效**。 + (它用于过滤掉会被误判为障碍的台阶/斜坡面,与问题 E 相关) + +10. mid360.yaml 第 18 行 imu_topic 是**死配置**(被 launch 覆盖)。 + 别被它误导去排查雷达 IP。 + +# 五、未解决的遗留问题(优先级低于上面 A~E,但要知道存在) + +- scan_planner_node 偶尔报 "no odom":SCAN 没收到 /aft_mapped_to_init。 + 怀疑是雷达 IP 与配置不符(配置 .110,但死配置里留过 .135 的痕迹)。 + 排查路径:先 ros2 topic hz /aft_mapped_to_init 确认 Point-LIO 是否出数。 +- 低矮障碍可见性受几何限制(见问题 C 的 H(d) 公式),2.6 m 以内看不到 + 16 cm 高的物体。这个用调参解决不了。 + +# 六、交付要求 + +请按这个格式回复: + 1. 你打算先验证哪几条假设,用什么命令/日志,预期看到什么。(先别改代码) + 2. 拿到上述结果后,给出每个问题的根因判断和方案(含备选与取舍)。 + 3. 列出你要改的文件 + 每个改动点的理由。 + 4. 明确指出哪些改动会影响现有已验证的行为(需要重新回归测试哪些场景)。 + +回归测试清单(改完必须重新跑): + 0.5 / 1 / 1.5 / 3 m 定点 —— 无过冲、无横向抖动、停得准 + 贴墙起始、掉头、指定终点朝向、倒车、窄道(原 1.35 m 那条) +================================================================ +``` + +--- + +## 附:这份提示词里我**没有**替你下结论的地方 + +写文件时我克制住了几个"看起来很有把握"的判断,因为它们需要证据支撑: + +| 我写了什么 | 我为什么没写死 | +|---|---| +| 窄道问题给了 4 个验证步骤(B1~B4) | 0.62 m 与 1.35 m 的算术余量只有 0.11 m,看起来很像根因;但**如果墙本身就没扫全**,现象会和膨胀过头一模一样。B2 就是用来区分这两者的。 | +| 车体等效半径写了"请你自己量车长约 1.06 m" | 我知道车长但不知道车宽,等效半径取决于外包络而不是长度。这个数字我给不出来。 | +| 问题 C 给了 (a)/(c) 两个倾向但要求 Codex 评估 | 融合层级的选择取决于 CPU 余量和退化场景需求,这两个我没有实测数据。 | +| 问题 E 只要求设计文档 | 你说"后续可以在代码中实现试试",所以现在不该写实现。而且 E1(坡上静止时加速度计混入重力)本身就是个需要想清楚的坑。 | + +另外提一句:**A 和 B 有可能是同一个根因**。1.35 m 走廊里车心的通行带只有 2 格时,A* 生成的轨迹会贴着墙走;轨迹贴墙 → 局部重规划时碰撞检查容易失败 → 表现为"偶发"撞过去。文件里我把这条线索留在 A4,没有合并成结论。你如果觉得这个关联值得让 Codex 优先验证,我可以把它提成 A 的第一条。 \ No newline at end of file diff --git a/minco_ws/docs/DIAGNOSIS_AND_DESIGN_2026-10-31.md b/minco_ws/docs/DIAGNOSIS_AND_DESIGN_2026-10-31.md new file mode 100644 index 0000000..80fd01a --- /dev/null +++ b/minco_ws/docs/DIAGNOSIS_AND_DESIGN_2026-10-31.md @@ -0,0 +1,355 @@ +# 真机导航诊断与方案评估(2026-10-31) + +本轮只新增这份诊断/设计文档;没有修改 C++、Python、launch、YAML 或 RViz,没有启动真机链路或发送运动指令。未读取、修改 `src/navigation/` 和 `sru_ws/`。已有未跟踪文件 `docs/CODEX_PROMPT.md` 保留原样。 + +以下区分:**当前源码事实**、**已有运行日志**、**待现场验证的假设**。历史日志主要来自 2026-10-29,不能保证对应当前每个源码版本,也不能确认每次运行都对应所述纸箱/走廊场景。本机没有发现正在运行的 planner、controller、Point-LIO、Livox 进程;本轮未取得实时 topic、参数、CPU 负载和新 rosbag。 + +## 1. 先验证什么、怎么验证、预期看到什么 + +### 1.1 已完成的静态核对与日志取证 + +实际默认入口: + +```text +scan_planner/vehicle_bringup.launch.py + → point_lio/single_livox_pointlio_intra_process.launch.py + → single_MID360_component.yaml:20 Hz、CustomMsg、单雷达、内部合并关闭 + → MID360_config.json:主机 192.168.1.50,雷达 192.168.1.110 + → Point-LIO(launch 覆盖 common.imu_topic=livox/imu) + → /aft_mapped_to_init + /cloud_registered + → body_odom / step_blocker + → scan_planner_node + closed_loop_controller → /cmd_vel → chassis_serial +``` + +`step_blocker.regions=""` 的行为是原点云重发布,不是去除坡面或过滤台阶;配置非空时额外添加封堵墙点云,仍不做地面分类。单独启动 `run_vehicle.launch.py` 的 cloud 默认是 `/cloud_registered`;整机入口才覆盖成 `/cloud_registered_for_scan`。 + +核对了 install 与 src 的规划/控制参数、两个 vehicle launch、mid360.yaml、单雷达 driver 参数、MID360 JSON、串口参数:八项均为符号链接,内容相同。这只能排除本地这八项的安装副本差异,不能代替现场 `ros2 param dump`,也不能证明 C++ 二进制已包含最新源码。 + +目标修改的真实日志:`/home/xie/.ros/log/scan_planner_node_837452_1793279905042.log:3,5,6`,北京时间 2026-10-29 21:18:43~47: + +```text +[1793279923.008610380] Target [6.00, 0.00, -0.22] is occupied; using [5.34, -0.03, -0.22] +[1793279923.224385751] Target [5.34, -0.03, -0.22] is occupied; using [6.25, 0.28, -0.23] +[1793279927.677235275] Target [6.25, 0.28, -0.23] is occupied; using [3.24, -0.01, -0.20] +``` + +相对首条日志旧目标 `(6,0,-0.22)`,三个新目标的偏差约为 0.661 / 0.376 / 2.760 m。这不是有 goal_id 的完整原始目标序列,但足以说明不能把这些日志描述为“空间距离严格单调后退”。当前源码确实未保存不可变的用户目标,也没有地图恢复后自动回到原始目标的机制。 + +急停日志:`/home/xie/.ros/log/scan_planner_node_19689_1793280790791.log:363-384`: + +```text +[1793280813.159875730] [bspline_opt]: A-star failed; aborting optimization +[1793280813.273874469] [scan_planner_node]: Obstacle discovered; emergency stop in 0.570s +[1793280813.377754201] [bspline_opt]: The robot is inside an obstacle +[1793280813.378143626] [scan_planner_node]: Obstacle discovered; emergency stop in 0.000s +``` + +只在 `.ros/log/scan_planner_node*.log` 内统计:目标替换 WARN 16 条;`no collision-free point was found on the global trajectory` 0 条;`End point outside the map region` 0 条;`Obstacle discovered; emergency stop` 122 条;`Replan failed` 7 条;`Ran out of pool` 233 条。均为日志条数,不是独立故障次数。日志缺失不能证明分支从未触发。 + +### 1.2 现场只读基线 + +在已有真机链路运行时执行;本轮没有代为启动整机。以下命令按终端分别执行,超时仅用于结束观察: + +```bash +cd /home/xie/RC2027_BR_code/minco_ws +source /opt/ros/humble/setup.bash +source install/setup.bash + +ros2 node list +ros2 topic info /aft_mapped_to_init -v +ros2 topic info /cloud_registered_for_scan -v +ros2 topic info /cmd_vel -v +ros2 param dump /scan_planner_node > /tmp/scan_planner_before.yaml +ros2 param dump /closed_loop_controller > /tmp/controller_before.yaml +ros2 param dump /laserMapping > /tmp/pointlio_before.yaml +ros2 param dump /livox_driver_node > /tmp/livox_before.yaml +ros2 param dump /chassis_serial_node > /tmp/chassis_before.yaml +ros2 param dump /step_blocker > /tmp/blocker_before.yaml + +timeout 10s ros2 topic hz /aft_mapped_to_init +timeout 10s ros2 topic hz /body_odom +timeout 10s ros2 topic hz /cloud_registered_for_scan +``` + +预期:存在唯一预期的 `/cmd_vel` 发布者;实际参数与用户基线一致;odom 持续出数,cloud 没有长时间断流。节点名以 `ros2 node list` 实际结果为准。不要根据 mid360.yaml 残留的 `.135` IMU 话题判断当前雷达 IP。 + +日志检索需同时包含搜索池越界: + +```bash +rg -n 'is occupied; using|no collision-free point|End point outside the map region|Ran out of pool|Unable to handle the initial or end point|Obstacle discovered|Replan failed|EMERGENCY_STOP' \ + /home/xie/.ros/log -g 'scan_planner_node*.log' +``` + +### 1.3 B1~B5 与 A2~A5 的同步数据 + +先在无运动的静态点云/已有 bag 上核对,再由现场操作人员复现原 1.35 m 走廊和正前方 2 m 的 35 cm 纸箱;本轮没有执行运动试验。 + +```bash +ros2 bag record -o /tmp/scan_diag_ba_01 \ + /move_base_simple/goal /initial_path /goal_point /global_list /a_star_list \ + /planning/bspline /optimal_list /planning/data_display \ + /planning/go2_execution_frozen /aft_mapped_to_init /body_odom \ + /cloud_registered /cloud_registered_for_scan \ + /grid_map/occupancy /grid_map/occupancy_inflate /grid_map/sliding_map_bbox \ + /cmd_vel /livox/imu /tf /tf_static /rosout +``` + +录包后检查 `ros2 bag info` 的消息数量。grid_map 点云是 Best Effort;用 `ros2 topic info -v` 检查协商,若录不到需为该订阅设置 Best Effort。`global_list`、`goal_point` 是 transient local Marker,若启动录包时目标已发过,需 transient local 订阅才能补收历史,或在录包后发布下一次测试目标。完整原始雷达点云另做短时采集,避免同时录所有高带宽话题改变现场延迟。 + +| 假设 | 取证/预期 | 仍缺什么 | +| --- | --- | --- | +| B1 目标被改 | 已找到替换 WARN;失败同一时段同时查 pool/map 越界及急停 | 对应场景、goal_id、地图快照 | +| B2 目标不可恢复 | 源码重规划使用被改过的 end_pt_;现有日志出现明显缩短 | 原始输入、每次候选、采样时刻及失败原因的完整序列 | +| B3 未膨胀地图是否变窄 | 在同一时刻、同一走廊横截面和实际查询 z,拟合两侧 occupancy 墙面,报告净宽及帧间方差 | 尚无 bag,不能报实测地图净宽 | +| B4 实际净宽 | 沿入口/中段/出口测多个横截面;同时测点云/未膨胀体素墙面位置 | 用户给出 1.35 m;本轮无法独立复测 | +| B5 车体外包络 | 实测全部突出物与旋转中心;圆模型取最远点距离,记录跟踪误差预算 | 1.06 m 长度不足以推出外接圆半径 | +| A2 全局与局部不一致 | 同时重建 `/planning/bspline` 与 `/global_list`,对照 odom/cmd_vel | `/global_list` 在 odom 刷新分支未每次发布,可能陈旧;需要诊断发布 | +| A3 急停是否有效 | 已确认历史触发;对齐触发、停止样条发布、控制器接收、cmd_vel 变零、实际减速时刻 | 当前日志不足以证明端到端停车成功 | +| A4 感知/占据延迟 | 记录障碍首次有效回波、进入原始占据/膨胀层、首次判碰撞及制动的时间 | occupancy 消息 stamp 是发布时间,不是源数据时间,精确计时需诊断埋点 | +| A5 图外当空闲 | 已确认目标调整处 `final_occ<=0` 的错误语义;测试目标图内/边界/图外 | 图外目标不能据此认定导致某次撞箱 | + +注意:B 样条的 `pos_pts` 是控制点,不是完整经过点;必须按 `order+knots` 求曲线,再以不大于半格的空间间隔检查。RViz 看见障碍只证明某些 z 切片有点,不证明轨迹查询高度处非空。 + +后续若批准加诊断,至少记录:goal_id、导航模式、原始输入、归一化 raw_goal、effective_goal、local_target、A* 段原/现端点、轨迹 ID、查询 z、occupancy 三态、地图边界/更新序号、数据时间和接收时间、调整原因、FSM 与控制器各自执行时间。当前局部变量 raw_end 无法输出真正的跨周期 raw_goal。 + +## 2. 各问题根因判断与方案 + +### 2.1 B:先修目标所有权和不可恢复;保留已验证碰撞参数 + +当前源码事实: + +- `scan_replan_fsm.cpp:306`:占据时从全局多项式末端按时间倒序找 free 点,同时覆盖 end_pt_、截短 global_duration_。`planFromCurrentTraj():802` 又以这个 end_pt_ 生成下一条参考轨迹。没有成员保存用户原目标。该缺陷成立。 +- 但“向前一个时间样本”不等于“空间上向起点回退”:手动模式参考是带起始速度/加速度的多项式,可能越过端点或弯曲。历史日志还可能对应旧构建。需采样完整参考曲线验证外凸;不能用 A* 直接写 FSM 来解释日志中的外移。 +- `dyn_a_star.cpp:94,130` 的参数按值传入,修改的是本次 A* 搜索索引。`bspline_optimizer.cpp:138,799` 传入的是碰撞段的 in/out 控制点,并不必然是用户导航终点。它会影响优化绕障引导,但不会直接修改 FSM end_pt_。 +- 向 end 方向持续找 free 有穿过膨胀区乃至越过实体墙的风险。代码没有“13 步/0.65 m”上限;半径不能给任意墙厚/入射方向提供上界。退出条件还包括 A* 搜索池越界。当前池为 100³、步长 0.05,即各轴约 5 m,和 10×10×5 m 滑动地图是两个不同边界。 +- 当前 A* 循环只有 dx/dy,z 由起终点平面插值,是 XY 八邻域,不是自由三维 26 邻域。允许斜向,但目前只查目标邻格,未逐段验证跨角边;保留为 A 的候选风险,不在 B 第一补丁顺手重写。 +- 膨胀的 ceil=13 是候选遍历界,随后有 `offset_xy.norm() < 0.62` 的精确半径筛选,不能直接当 0.65 m 有效半径。连续几何净带仍约 0.11 m;离散墙体、栅格相位和定位波动会进一步影响连通性。 +- offset=0 时 yaw 不影响圆模型占位;无需因为该问题关闭倒车。 + +建议的 B 第一阶段(尚未实施): + +1. **明确目标所有权。** 保存收到的原始消息、坐标/高度归一化后的不可变 raw_goal,以及允许变化的 effective_goal、local_target。新目标/新任务 ID 才替换 raw_goal;失败、等待和临时避障不能覆盖它。手动模式保留当前初始 RViz 高度语义;模式 3 保留整条原始参考路径和进度,不能每次把路径抹成 odom→raw_goal 的直线;模式 2 按当前 waypoint 保存目标。 +2. **每次重新评估原目标。** 从不可变输入重建/查询,旧的缩短结果不能充当下一次原始输入。参考轨迹、duration、进度与 effective_goal 必须一致,成功后一次提交;失败不能留下“新目标+旧轨迹”或“旧目标+新轨迹”的半更新状态。 +3. **分开最终目标与安全临时终点。** 原目标不可用时可停在经过整段碰撞检查的临时终点,但状态是 BLOCKED/WAITING,不报告成功、不丢 raw_goal;原目标及连接路径稳定恢复后才重新规划。最终成功按原始目标的位置和任务要求的 yaw 判断,不能用时间走完或到达替代点代替。 +4. **设明确放弃条件。** 取消/替换目标立即终止旧任务;恢复等待使用有界的超时和重试频率;超时/持续无进展后停车、报告原因、等新任务,保留失败目标供诊断。第一版不启用“离原目标几米也算成功”的容差。等待时间的候选见参数表,需按任务需求确认,不沿用 1000 次快循环充当墙钟超时。 +5. **三态查询逐调用处处理。** `0=free`,`1=occupied`,`-1=out_of_map`。远处 raw_goal 可以保留为意图,只规划已知 free 的局部视野;不能给原始远目标贴“已验证安全”,也不能一律拒绝所有远目标。正在执行的局部轨迹一旦图外则无有效安全证明,不能继续据此放行。未知体素与图外也不同;当前图内未观测区的语义不在此补丁中静默更改。 +6. **A* 不再静默外推 end。** 首选拒绝不合法搜索端点,并由调用方记录碰撞段/原端点/原因;不自动改成 `end -= direction`,也不默认做梯度搜索。必须验证优化器能找到合法段边界,否则这个改动会降低绕障成功率。若需边界恢复,应在优化器显式限定同一碰撞段的范围、距离和连接安全性,不扩展到墙另一侧。start 的向后退在任意场景也不保证安全;第一补丁保留既有行为但记录位移,贴墙起始必须回归。 + +拟新增策略参数(全部是设计候选,未写入 YAML): + +| 参数 | 候选初值 | 用途/依据 | +| --- | --- | --- | +| goal_recovery_retry_period | 0.5 s | 等待恢复的低频重试,避免用 10 ms FSM 持续重算同一堵墙 | +| goal_recovery_stable_time | 0.5 s | 原目标及连接安全稳定后恢复,避免占据闪烁导致来回切换 | +| goal_blocked_timeout | 10 s | 提供有界失败;任务等待容忍度未知,需实测确认 | +| substitute_goal_can_succeed | false | 到达临时安全点不等于完成原任务 | +| substitute_success_distance | 不启用 | 暂无业务容差依据,不给大范围替代成功 | + +备选取舍:梯度下降需代价/距离场、边界及可达性验证,当前二值硬膨胀不能直接给稳定梯度。终点仅查原始致命体素不安全,因为车有真实尺寸,且末端控制点会影响整段样条;此方案不建议采用。真实 footprint 致命层+软代价场是后续架构方案,需要重新验证所有路径,不作为此次小修。 + +### 2.2 A:B 是关联缺陷,但尚未证明是撞箱主因 + +已确认历史确实判过碰撞并进入急停,不应再说“急停从没触发”。`checkCollisionCallback():855` 每 50 ms 执行,使用当前轨迹和查询高度;先同步尝试重规划,失败后才按 emergency_time 判断是否转急停;当前 planner 是 SingleThreadedExecutor。A* 单次上限 0.2 s,多次搜索/优化会推迟后续地图和安全回调。控制器独立运行,会继续跟上一条样条。需要测实际最长回调时间,不能把定时器 50 ms 等同于碰撞处理延迟上界。 + +`-1` 的具体调用语义:FSM 原目标调整中的 `final_occ<=0` 会放行图外;A* 的 `if(occ)`、邻格检查、优化器中的 bool 查询、碰撞定时器 `if(getInflateOccupancy(...))` 都把 -1 当作阻塞。因此“所有中间图外点都被当 free”不成立。 + +另外两个直接关联待测项: + +- `/cloud_registered` 来自 `feats_down_world`;当前 Point-LIO 的 surface voxel 为 0.5 m,并非把全部原始回波原样交给 0.05 m grid_map。35 cm 障碍的有效点高度、稀疏程度和更新率需与已存在 `/cloud_registered_full` 对比,不能仅从 grid 分辨率判断感知精度。本轮不调整 LIO 滤波参数。 +- `body_height=0.41` 主要作用于模式 3 参考路径;模式 1 目标 z 固定为初始 body_pose.z,不能把两种模式都按“地面+0.41”推断。当前 FSM 仍存在按局部轨迹时间结束转 WAIT_TARGET 的分支,而控制器按自己的执行时间追踪。安全回调在 WAIT_TARGET 直接返回;若实际车仍在追末端,可能出现检查覆盖缺口。必须同录 FSM、冻结状态、控制器执行时间和 odom 证实,作为独立后续补丁,不顺手改实测到达控制。 + +修复顺序:B 目标语义 → 同场景复测 A → 根据证据选择高度/感知分支、跨角边验证、回调阻塞或安全覆盖修复。目标改对不能替代整段样条安全校验。以 0.5 m/s、仅把 0.6 m/s² 当理想制动加速度估算,制动距离已约 0.208 m,再叠加 `v×总延迟`;manager.max_acc 不是真机制动能力,最后必须实测。 + +### 2.3 C:优先地图层增强,暂不改变主雷达 LIO + +**结论:优先 (c),但需要保留每路射线原点;(a) 作为后续对照实验;(b) 暂不采用。** + +当前源码已有内部双 MID360 merger,具备后雷达到前雷达刚体变换、时间差配对、以最小 base_time 为基准重算每点 offset_time;Point-LIO 预处理会再按点时序排序。因此并非从零实现 (a)。但该实现尚不能直接当本车上下雷达配置使用:旧 mixed 配置主机 `.47`、雷达 `.135/.122`,外参也与新安装不同;默认整机入口加载 single 配置,未启用此功能。旧说明写约 10 Hz,当前 component YAML 为 20 Hz,性能应以实测为准。 + +(a) 风险:主 LIO 改吃两套测量,单雷达 blind 球作用于变换后的合并坐标,可能过滤副雷达近点;每路车体自反射、IMU 杆臂/坐标关系、时间同步和全部点时序都要校验。全局合并后仍丢失射线来源,grid_map 仍用主原点清空副雷达射线途经区域,问题不会因进入 LIO 就消失。任一雷达队列为空时现有 merger 不发半帧,会让单路故障拖停主 LIO;需要显式降级/故障策略才能用于真机主链路。不得把两路 IMU 直接混成一条流。 + +(c) 推荐数据流: + +```text +上雷达 → 现有 Point-LIO → 原 odom + 原主点云 → 主地图更新 +下雷达 → 时间基准校验 → 车体自点过滤 → 点时间姿态变换/去畸变 + → 独立地形/低障碍提取 → 带下雷达原点的地图更新 +两路地图证据 → 同一最终占据/碰撞查询 → 原局部规划 +``` + +`grid_map.cpp:627` 当前每条射线都用 `md_.ray_pos_`,而 lidar pose 是最近收到的主 odom、没有和点云时间同步。因此不能只做“两个世界系 PointCloud2 拼起来喂现有 cloud topic”。需要缓存主 IMU 位姿、按时间插值并保留每路原点,按批次独立 raycast 后融合本周期 hit/miss,避免后处理的一路 free 抹掉另一路 hit。两路更新先入队、再统一融合,不能让两个 cloud 回调反复覆盖单个 `proj_points_`。过期/失步副雷达应告警并退出增量更新,主链路继续;障碍的清除按明确的有效自由空间观测/衰减策略完成,不能因副雷达断流立即清空。 + +**16 cm 障碍还有地图高度门槛。** 即便低雷达看到,模式 3 轨迹高 0.41、z_up=0.15 时,平地上 0.16+0.15=0.31 m,仍达不到轨迹查询高度。主雷达 blind=0.55 和 body_height=0.41 都保留。需对有地面支持的低障碍建立额外致命占据/车体垂向检测;先剔除可通行坡面,再纳入碰撞检查,不能把全部地面点直接向上拉成墙。这是 C 验收的一部分,不能只验 RViz 出点。额外碰撞证据也应进入安全回调和优化器,不只用于显示。 + +#### C2:两实例的具体隔离配置 + +两个实例应在两个进程/容器中运行,避免 driver/SDK 全局状态互相干扰。格式和 multi_topic 是各实例的数据选择,不必为了“不同”强行取不同值;隔离依赖独立话题、设备配置、主机接收端口和实例名。以下为 (c) 的拟议配置,不是已验证设备地址: + +| 字段 | 上雷达(保留) | 下雷达(新增示例) | +| --- | --- | --- | +| 节点/进程 | livox_driver_node,现有容器 | low_livox_driver_node,独立进程/容器 | +| ROS namespace | `/` | `/low` | +| xfer_format | 1,CustomMsg | 0,PointCloud2,保留逐点 timestamp 字段 | +| multi_topic | 0 | 0;namespace 隔离 | +| publish_freq | 20.0 | 20.0 起测 | +| frame_id | livox_frame | low_livox_frame | +| enable_internal_lidar_merge | false | false | +| 输出点云 | `/livox/lidar` | `/low/livox/lidar` | +| 输出 IMU | `/livox/imu` | `/low/livox/imu`,不输入主 LIO | +| user_config_path | MID360_config.json | 独立 low_MID360_config.json | +| lidar_configs[0].ip | 192.168.1.110 | 192.168.1.111,仅示例,先确认无冲突 | +| host_net_info 各接收 IP | 192.168.1.50 | 同机可仍为 .50;以实际网卡为准 | +| host cmd_data_port | 56101 | 56102 | +| host push_msg_port | 56201 | 56202 | +| host point_data_port | 56301 | 56302 | +| host imu_data_port | 56401 | 56402 | +| host log_data_port | 56501 | 56502 | +| lidar_net_info | 56100/56200/56300/56400/56500 | 相同设备端口,不擅改 | +| extrinsic_parameter | 现有零值 | 零值,外参由融合层统一应用一次 | + +launch 分别使用 `upper_driver_params_file` / `lower_driver_params_file`、独立 JSON 路径和 namespace;下雷达使用 `ParameterFile(..., allow_substs=True)`。不要重用通用 `params_file` 覆盖现有 chassis/blocker 参数。当前 driver 的 IMU header.frame_id 在 `lddc.cpp:674` 硬编码 `livox_frame`,改 frame_id 参数不会自动改它;若将来要用副 IMU,需要单独修正或在适配层明确其真实外参,不能信任这条 header 自动隔离。 + +端口表只是拟议 UDP 接收配置:还需验证本机 SDK 版本的发现/命令套接字能否同机双进程共存。若其固定监听端口冲突,改 host point 端口不一定足够;改为单 driver 配置两台设备、`multi_topic=1`、关闭内部合并,按 IP 分开接收,然后把主 CustomMsg 原话题接回主 LIO,副 CustomMsg 转成带时间的地图输入。该备选仍是 (c),并不要求融合进 LIO。单进程多雷达可共用 host 接收端口,由 IP handle 分流,因此“所有双雷达必须不同 UDP 端口”也不是通则。 + +现场核对:`ip -br addr`、`ss -lunp`、`ros2 topic info -v`;需要包级判断时在实际网卡上捕获对应雷达 IP 与接收端口,确认没有抢配置/掉包。不要先套用旧 mixed JSON。 + +#### C3:安装高度、时间与外参 + +先按用户实测的最低向下视线斜率 0.1228 计算;d 是从雷达光心出发的水平距离,不是从车头边缘出发: + +```text +H_min(d) = h - 0.1228 d +看见高度 H_obs 的必要几何条件:h <= H_obs + 0.1228 d +``` + +| 雷达光心离地 h | 0.5 m 处最低高度 | 1.0 m 处 | 1.5 m 处 | +| --- | --- | --- | --- | +| 0.48 m(现有) | 0.419 m | 0.357 m | 0.296 m | +| 0.25 m | 0.189 m | 0.127 m | 0.066 m | +| 0.22 m | 0.159 m | 0.097 m | 0.036 m | +| 0.20 m | 0.139 m | 0.077 m | 0.016 m | + +针对“16 cm 物体,雷达前 0.5 m 已可见”,h 上限约 0.221 m;0.22 几乎无余量,建议从光心离地 **0.20 m、水平安装**开始评估,理想几何余量约 2 cm。若只需最近 1 m,h<=0.283 m,0.25 m 是可行候选。对 10 cm 障碍、0.5 m 要求 h<=0.161 m,需要进一步降低光心或改变视线设计,不能宣称 0.20 m 已满足。若最低障碍/最近距离改变,重新代公式。 + +主雷达 16 cm 物体的理论出现距离约 `(0.48-0.16)/0.1228=2.606 m`。这些是可见性必要条件,尚未计入车体遮挡、点密度、反射率和安装倾斜。全向底盘还需检查左右/后方;单个下置雷达可能被车体挡住,不能承诺整个 360° 都覆盖近障碍。坡上车身俯仰也会改变世界系最低视线。 + +规格纠正:MID360 标称完整垂直 FOV 为 **-7°~52°**,不是 ±7°;用户拟合使用的下边界约 -7° 仍然适用。官方也不保证所有低反射或细小近物体均可可靠检测。[Livox 规格](https://www.livoxtech.com/mid-360/specs) + +时间/外参步骤: + +1. 确认两雷达时间戳类型、epoch、单位、PTP 锁定状态;同一 PTP 主时钟同时约束雷达,主机时钟也须可转换到该时间域。仅两台电脑开 NTP 不证明雷达已同步。配对 5 ms 容差只是丢帧规则,不是同步算法。MID360 支持 PTPv2/GPS。[官方规格](https://www.livoxtech.com/mid-360/specs) +2. 刚性固定后测量平移/旋转初值,记录光心、主 IMU、车体参考点三者定义。当前 `/aft_mapped_to_init` child=`body`,pose 直接来自滤波器 IMU 状态,并不是纯雷达光心位姿;body_odom 又仅保留 yaw。新融合节点应使用完整主 IMU 姿态及现有雷达到 IMU 外参,不能把 yaw-only body_odom 用于坡上点云变换。 +3. 用地面、两面不平行墙及箱体等有重叠且几何丰富的数据,静态多位置初值+点到面配准,避免只用单平面或长走廊求六自由度;低安装视场重叠不足时使用标定靶。预留独立数据验证残差,不能只看优化收敛。 +4. 统一 `T_A_B` 表示 B→A。地图层对下雷达点使用 `p_W(t)=T_W_I(t)·T_I_Llow·p_Llow(t)`,每点时间使用 base_time+offset_time;按时间插值主姿态、去畸变并同时输出该射线世界系原点。变换只做一次,不能 JSON 与 TF 再重复应用。 +5. 在静止、平移、原地旋转、坡道上检查墙面双影和时间相关残差。0.5 m/s×5 ms=2.5 mm 只是平移误差;旋转误差约 `range×omega×dt`,还应计入外参杆臂。静态残差目标可先取小于半格 2.5 cm;这是验收候选,不保证近场硬件噪声可达到,需报告实际分布。 + +驱动字段参考官方配置,但以本地 parser/SDK 版本为准,不照搬新版 JSON 结构:[官方 driver 配置说明](https://github.com/Livox-SDK/livox_ros_driver2/blob/master/README.md)。 + +#### C4:实时性评估与降载 + +当前本机是 Ryzen 5 6600H、12 逻辑 CPU、约 28 GiB RAM,但未运行节点,无法给“CPU 足够”结论,也不知道这是否为最终部署机。MID360 标称 20 万点/s,一台 20 Hz 约 1 万原始点/帧,两台合计约 2 万点/帧;调整发布频率主要改变分帧,不自动按比例减少设备每秒回波量。[官方点率](https://www.livoxtech.com/mid-360/specs) + +grid_map 共 400 万体素,(c) 共享地图时体素数不因雷达翻倍,但射线/输入转换开销增加;当前 0.62 半径、0.05 分辨率下 XY 膨胀偏移 489 个、上下共 5 层,单个占据切换涉及约 2445 个偏移。开启 RViz 时发布两个图层还会扫描大范围体素,并与 planner/safety 共用线程。 + +用单雷达/双雷达相同场景各录一段,比较 CPU 各线程、内存、输入到占据更新延迟、Point-LIO 帧耗时 p50/p95/p99、planner 最长阻塞、cmd_vel 抖动和丢帧: + +```bash +ps -eo pid,comm +# 代入上一步查到的 PID(pidstat 如已安装): +pidstat -t -p ,, 1 60 +``` + +20 Hz 单流周期 50 ms,候选预算为 LIO 帧 p95<40 ms、地图融合 p95<25 ms,留出安全/调度余量;这是验收目标,不能当已测性能。`runtime_pos_log_enable=false`,统计开启会改变负载,应单独短时测量。`grid_map.show_occ_time` 附近实际计时代码被注释,开参数不会自动得到完整性能报告,后续需要埋点。 + +降载顺序:先裁副雷达 ROI(候选近场半径 3 m,保留实际危险区),去自点/无效点,再对副感知支路做 0.03~0.05 m 体素抽样并限入队深度;地图输出可降低可视化频率。若仍超预算,可副支路真正丢弃部分帧降到 10 Hz,但需重新计入 100 ms 周期的检测延迟并验证最小障碍点数。仅把 driver publish_freq 20→10 通常会把每帧点数加倍,不一定降低每秒处理量。保持主 LIO 现有频率、0.5 m surface voxel 和所有闭环参数;如未来改主 LIO 抽样,必须独立回归里程计。 + +### 2.4 D:Odin1 接入只做边界设计 + +若 Odin1 提供可定时、可标定的低位点云,优先复用 C(c) 的地图传感器接口,作为近障碍补充;不先假定它的点格式、量程、频率和动态精度。如果它实际只输出姿态/里程计,则作为监测或独立冗余源评估,需协方差、失效检测、共同时间和坐标约束;不要直接平均两个可能共享信息的 LIO pose。 + +接入前确认:实际型号/固件/驱动及 CPU 开销;topic/type/字段/逐点时间;频率、延迟、丢包、近距/弱反射/FOV;frame/坐标轴/单位;时间源/epoch/同步手段;外参和是否可去畸变;是否已有内部滤波或地面分类;里程计父子 frame/协方差/重置行为;电源、网络、机械遮挡。按用户边界,本轮未进入 sru_ws 检查,以上均为待确认项。 + +C 与 D 可以叠加,共用一个主 LIO 时钟/世界系、独立传感器原点和健康状态。若两者都只是补同一个近场盲区,可先选覆盖和时序更稳定的一种,以控制算力和标定成本;若同时输入,必须避免重复统计同一已合并点云。点云层多雷达 LIO 不等于任意传感器都可直接拼接,Odin1 的点模型未确认前不采用。 + +### 2.5 E:坡道停车设计及参数表(不实现) + +**状态区分:允许结束任务、主动保持位置、紧急停车。** “在坡上不能结束任务”不能屏蔽障碍急停、人工急停或通信故障停车;也不能因为没有平地就继续盲走。当前姿态只能说明当前车体倾斜,不能证明前方存在可停车平台,后者需要参考路径/地形证据。 + +姿态来源:优先读取 `/aft_mapped_to_init` 的完整 roll/pitch,转换到已校准车体坐标并去除平地安装偏置,原始 IMU 用于角速度和加速度可信度。不能用 `/body_odom.orientation`,其节点明确只发布 yaw,x/y 四元数分量清零。若另写姿态估计,使用陀螺传播+条件可信的重力方向互补校正,而非无约束纯陀螺积分或运动中单帧 atan2(acc)。 + +静止坡面上加速度计测到的是包含重力响应的比力,不能把沿坡分量当作机器人在加速;去掉安装偏置后,其方向可用于静态倾角。行驶时平动/振动会污染该估计,必须用角速度、加速度模长和 LIO 动态估计门控重力校正。Livox IMU 数值在当前驱动直接透传,Point-LIO `mapping.acc_norm=1.0` 表明内部按 g 尺度处理,不能未经确认按 SI m/s² 给原 topic 套 9.81 阈值;先静态验证单位和方向,再在新节点内部转换。 + +用总倾角 `alpha=acos(n_body·z_world)`(或由 roll/pitch 等价计算),同时检查双轴,避免只看 pitch 漏掉侧坡。平地标定须真实水平;不允许在“开机所在坡面”自动置零。 + +拟议状态:UNREADY(数据无效/未标定)→ SLOPE_OR_MOVING → FLAT_CANDIDATE → FLAT_STABLE → SETTLED;数据过期/姿态超出退出阈值立即撤销候选许可。危险停车请求始终可抢占这些状态。FLAT_STABLE 只允许按现有减速策略停,不跳变速度;位置/终点 yaw 达标并满足实测静止窗才 SETTLED。状态转换不以轨迹参考时间走完代替空间到位。 + +| 拟议参数 | 候选初值 | 理由与待验证项 | +| --- | --- | --- | +| terrain_stop_gate_enabled | false(先影子模式) | 先记录判定,不改变现有控制;离线和真机影子验证后才允许接管 | +| flat_enter_angle | 3°(0.0524 rad) | 给平地噪声/机械变形留余量;以实测平地分布修订 | +| flat_exit_angle | 5°(0.0873 rad) | 与进入阈值形成滞回;3~5° 不新发许可 | +| flat_window | 1.0 s | 窗内有效样本覆盖需连续满足,不能只统计收到的样本比例 | +| flat_valid_ratio | >=95%,且无样本达退出阈值 | 单帧小抖不打断,明显坡态立即否决;上限基于有效时间覆盖 | +| max_roll_pitch_std | 1° | 排除坡缘摇摆/振动阶段,之后按实测调整 | +| max_tilt_rate_for_candidate | 3°/s | 只限制姿态倾斜变化;原地 yaw 转动另检查最终停稳 | +| imu_max_age / odom_max_age | 0.10 / 0.15 s | 候选数据新鲜度;延迟实测后确定,不复用 chassis 超时 | +| max_abs_acc_norm_error | 0.10 g | 只对重力校正可信度门控,不能据此证明无匀速滑动 | +| stationary_window | 0.5 s | 到点后连续测稳定,避免单帧速度为零 | +| stationary_odom_speed | <0.02 m/s | 实际地面相对速度候选,需验证 LIO 噪声底 | +| stationary_yaw_rate | <0.03 rad/s | 与最终姿态对齐完成联用 | +| stationary_position_range | <0.02 m/窗 | 检出低速滑移,结合速度窗;噪声底决定能否实现 | +| wheel_zero_threshold | 待下位机实测 | 当前串口只发不收,没有轮速反馈,不能假装已有此信号 | +| slope_wait_timeout / hold_mode | 待任务及底盘能力确认 | 超时报告不能停车/无平台;保持或制动必须由实车证明能力 | + +全向轮是否溜车无法从代码确认,要实测受控坡上零速/制动状态。**轮速为零且姿态角不变仍可能整车匀速下滑**,IMU 也不能检测所有匀速滑移;必须依赖地面相对位移/速度(LIO,必要时外部观测),并将其有效性纳入判据。现有 chassis_serial 是单向发送,软件零速度不等于下位机电机抱死或机械制动。不能先承诺有可靠主动驻坡能力。 + +body_height 冲突:对无限平面坡局部圆邻域,最高相邻坡面比脚下高约 `R*tan(theta)`,所以模式 3 的理想避地面条件为 `h > 0.62*tan(theta)+0.15`。15° 需约 0.316 m,0.41 理想余量约 9.4 cm;20° 需约 0.376 m;25° 需约 0.439 m,当前不足。这里用 R=0.62,不是任意前方 1 m;仍应叠加体素量化、坡面噪声和姿态/高度误差,理论余量不等于验收通过。 + +此外,起点来自约地面+0.25 的 body_odom,模式 1 目标 z 是初始固定高度,模式 3 起终点可能不同高度基准,不能假设整段都稳定保持离局部地面 0.41。应测 `z_traj(t)-z_ground(x(t),y(t))` 的最小值,逐点和膨胀层对照。step_blocker 不会自动识别/去掉坡面。保持 0.41 和 z_up/down 不动,坡道误判若复现,优先研究地形参考高度/坡面分类,不能用 IMU 的“平地许可”掩盖规划层碰撞错误。 + +## 3. 文件清单与每个改动的理由 + +本轮实际新增:`docs/DIAGNOSIS_AND_DESIGN_2026-10-31.md`。下面均为**后续拟改**,没有执行: + +| 阶段 | 文件/位置(相对 minco_ws) | 理由/边界 | +| --- | --- | --- | +| B 诊断+目标恢复 | `src/scan/plan_manage/include/plan_manage/scan_replan_fsm.h` | raw_goal、原始参考路径、任务 ID、恢复状态与时限 | +| B 诊断+目标恢复 | `src/scan/plan_manage/src/scan_replan_fsm.cpp` | 所有目标入口及重规划保留原输入;目标/轨迹原子提交;三态处理;临时停点不算完成;每次刷新发布诊断 | +| B 搜索边界 | `src/scan/path_searching/src/dyn_a_star.cpp` | 移除 end 无界外推、记录实际搜索段端点和池/地图越界原因 | +| B 调用端适配,若回归需要 | `src/scan/bspline_opt/src/bspline_optimizer.cpp` | 让不合法段端点显式失败/受限选择边界,防止拒绝策略使所有绕障失效 | +| B/安全诊断,先取证 | `src/scan/plan_manage/src/planner_manager.cpp` | 参考曲线采样/耗时;如有数据证明目标与轨迹更新不一致,再加最小辅助接口 | +| B 新增策略参数 | `src/scan/plan_manage/config/planner_vehicle.yaml` | 只加等待/恢复策略参数及注释,原实测数值保留 | +| B 回归 | 对应 `test/` 与 CMakeLists.txt | 对真机行为有影响,测试 raw goal 恒定、恢复、失败与搜索边界,并验证路径模式不被抹直 | +| C 设备入口 | 独立 lower driver YAML/JSON、独立 launch,最后接入 `vehicle_bringup.launch.py` | 先独立采集验收,再接地图;独立参数变量,默认主链路保持原样 | +| C 融合/低障碍 | 新增感知适配包;`src/scan/plan_env/include/plan_env/grid_map.h`、`src/scan/plan_env/src/grid_map.cpp` | 时间插值、去畸变、原点、hit/miss 融合、低障碍与坡面区分、健康状态和清除策略 | +| C 可选(a) | `src/perception/livox_ros_driver2/config/mixed_MID360_component.yaml`、对应 JSON/内部 merger | 仅在决定试验(a)后改;现成外参/IP不能复用;补主雷达降级策略 | +| E 后续 | 新增停车监督节点/参数;必要时 controller 最小接口 | 先影子模式;只协调终点完成/驻坡/急停,保留调好位置与速度环 | + +若需要让 controller 区分“局部窗口结束/临时停点/真正全局终点”,可能涉及 `closed_loop_controller.cpp` 和专门任务状态接口;先在 B 回归测清楚,不因这份设计直接重写控制器。本轮已阅读其当前注释和 controllers_vehicle.yaml。 + +grid_map.h/cpp、vehicle.rviz 的混合行尾必须按局部原字节保留,检查普通 diff 与忽略空白 diff 的语义范围;本轮没有改这三个文件。也不改 blind、body_height、半径、增益、前视、到达容差、速度限幅或 omega_sign。 + +## 4. 行为影响与回归 + +| 拟改项 | 会改变什么 | 必须重新验证 | +| --- | --- | --- | +| raw_goal 与恢复状态 | 不再把缩短目标当最终任务;地图恢复后可能继续行驶 | 窄道、堵塞后移除障碍、新目标替换/取消、等待超时、恢复时不追旧轨迹 | +| A* 拒绝占据端点 | 过去靠外推成功的碰撞段会失败 | 贴墙起始、墙前终点、连续障碍绕行、池越界/地图越界可区分 | +| -1 三态 | 图外不再伪装安全;远目标通过局部窗口推进 | 目标在 10 m 滑动窗口外、地图滑动、局部路径跨边界 | +| 目标/控制终点区分(若实现) | 临时停点不触发任务成功和不适当最终 yaw 对齐 | 3 m 以上局部窗口、指定终点朝向、倒车、零四元数目标 | +| 副雷达地图感知 | 低矮障碍可影响路径与安全停车;地图负载上升 | 16/35 cm 纸箱、近场侧后遮挡、双影、掉线、时间失步、坡面不被立墙 | +| 以后采用点云层双雷达 LIO | 定位测量及 blind/filter 输入分布改变 | 全部控制用例+走廊退化、静止漂移、旋转、单雷达断流降级 | +| 坡道停车监督(若启用) | 平地判稳前可能不结束任务;不改变危险停车优先级 | 15°坡、坡顶/坡底、侧坡、坡上静止/溜车、IMU掉线、障碍急停 | + +固定回归清单必须完整执行:0.5 / 1 / 1.5 / 3 m 定点(无过冲、无横向抖动、停车准确);贴墙起始;掉头;指定终点朝向;全零四元数仍跳过终点对齐;倒车;原 1.35 m 窄道。记录最大过冲、终点误差、横向振荡、最终 yaw、是否到原始目标、等待/恢复状态;仅停在被缩短点不能记成功。 + +增加具有直接意义的离线/仿真测试:同一 raw_goal 多次占据/释放保持不变并可恢复;临时停点不报成功;无 free 点/图外/池越界返回不同原因;模式 3 参考路径形状与进度保留;真实墙前搜索不把 end 推到墙另一侧;主/副射线原点不同、某一路 miss 不能抹掉同批有效 hit;无数据或匀速滑移不报 SETTLED。不要连接真实串口回放带 cmd_vel 的 bag。 + +后续实施后仅构建所改包及必要依赖,避免误构建备选栈。包名为 `scan_planner`,不是 plan_manage。例如三包都修改时(顺序由 colcon 依赖确定): + +```bash +MAKEFLAGS="-j2" colcon build --symlink-install --parallel-workers 1 \ + --packages-select path_searching bspline_opt scan_planner +``` + +如改 plan_env,显式加该包并重建依赖它的上述包。不要为本轮文档运行构建,也不向 CMakeCache 写入持久的 `-O1`。本轮没有执行回归,不能宣称真机故障已修复。 diff --git a/minco_ws/docs/NAVIGATION_SOLUTION.md b/minco_ws/docs/NAVIGATION_SOLUTION.md index 32bfda3..0c1fbd9 100644 --- a/minco_ws/docs/NAVIGATION_SOLUTION.md +++ b/minco_ws/docs/NAVIGATION_SOLUTION.md @@ -1,24 +1,35 @@ # 机器人定位与导航方案 -> 仓库内共有 **三套** 可行方案:一套在用、两套备用。本文只讲**实现方式与数据流**, +> 仓库内共有 **四套** 可行方案:一套在用、三套备用。本文只讲**实现方式与数据流**, > 具体参数与启动命令见各目录下的 `docs/`。 +> +> | 方案 | 代码位置 | 一句话 | +> |---|---|---| +> | A | `minco_ws/src/scan` | 激光惯性里程计 + 局部 A\*/B 样条 | +> | B | `minco_ws/src/navigation` | Nav2 框架 + 自研 MINCO 后端 | +> | C | `sru_ws` | Odin1 + 端到端学习策略 | +> | **D(方案四)** | **`nav2_ws`** | **先验地图 + slam_toolbox/AMCL + Nav2 + Action 原语 + 行为树** | --- ## 1. 总览 -| | 方案 A(在用) | 方案 B(备用) | 方案 C(备用) | -|---|---|---|---| -| 位置 | `minco_ws/src/scan` | `minco_ws/src/navigation` | `sru_ws` | -| 传感器 | MID360 激光雷达 | MID360 激光雷达 | Odin1 空间记忆相机 | -| 定位 | Point-LIO 激光惯性里程计 | 同左(可换 SLAM Toolbox + 重定位) | Odin1 自带高频里程计 | -| 规划 | A\* + B 样条优化(局部,3.5 m 视野) | Nav2 框架:SMAC 全局 + MINCO 轨迹优化 | **无规划** | -| 控制 | 自写闭环控制器(轨迹跟踪) | MINCO MPC(qpOASES 求解) | **无控制**,网络直接出速度 | -| 本质 | 几何建图 + 优化式局部规划 | 成熟导航框架 + 自研优化后端 | 端到端学习策略(VAE + SRU) | -| 输出 | `/cmd_vel` | `/cmd_vel` | `/cmd_vel` | +| | 方案 A(在用) | 方案 B(备用) | 方案 C(备用) | 方案四(备用) | +|---|---|---|---|---| +| 位置 | `minco_ws/src/scan` | `minco_ws/src/navigation` | `sru_ws` | **`nav2_ws`** | +| 传感器 | MID360 激光雷达 | MID360 激光雷达 | Odin1 空间记忆相机 | **Odin1(双高度带 2D 投影)** | +| 先验地图 | 无,上电原点重置 | 无 | 无 | **有,跨上电全局定位** | +| 定位 | Point-LIO 激光惯性里程计 | 同左(可换 SLAM Toolbox + 重定位) | Odin1 自带高频里程计 | **slam_toolbox 建图 + AMCL 定位** | +| 规划 | A\* + B 样条优化(局部,3.5 m 视野) | Nav2 框架:SMAC 全局 + MINCO 轨迹优化 | **无规划** | **NavFn 全局(地图系)** | +| 控制 | 自写闭环控制器(轨迹跟踪) | MINCO MPC(qpOASES 求解) | **无控制**,网络直接出速度 | **Nav2 MPPI(Omni 模型)** | +| 特例处理 | 靠调参 | 靠调参 | 靠训练 | **切成离散 Action 原语** | +| 编排 | 有限状态机 | Nav2 行为树 | 单节点循环 | **py_trees 行为树** | +| 本质 | 几何建图 + 优化式局部规划 | 成熟导航框架 + 自研优化后端 | 端到端学习策略(VAE + SRU) | 成熟框架 + **先验地图 + 原语编排** | +| 输出 | `/cmd_vel` | `/cmd_vel` | `/cmd_vel` | `/cmd_vel` | -三套方案**最终都只输出 `geometry_msgs/Twist` 到 `/cmd_vel`**,共用同一个底盘串口桥 +四套方案**最终都只输出 `geometry_msgs/Twist` 到 `/cmd_vel`**,共用同一个底盘串口桥 (`techx_r2_chassis_control`),因此可以互相替换而不用改执行层。 +**四套之间分别启动,不可同时跑**(都占用 `/cmd_vel`,且 A 与 D 都要独占传感器链路)。 --- @@ -135,29 +146,93 @@ Odin1 ──┬── 深度图 ──────────┐ --- -## 5. 三套方案的关系 +## 5. 方案四(备用):先验地图 + Nav2 + Action 原语 + 行为树 + +**思路**:前两套都是"上电即失忆"——没有先验地图,原点在启动瞬间重置。 +方案四第一次引入**跨上电的先验地图**:赛前建一张图,比赛时在图上做全局定位, +Nav2 负责大部分路程,Nav2 做不了的动作**退化成离散 PID 原语**,由行为树统一编排。 + +**实现方式** + +- **传感器**:Odin1。点云经 `pointcloud_to_laserscan` 投影成 2D 激光, + **一个节点实例出两个高度带**(`enable_second_scan`): + 低带 0.08–0.45 m 喂 Nav2 的 `obstacle_layer`,高带 0.30–1.20 m 喂 SLAM/AMCL。 + 两带分开喂不同消费者,避免"SLAM 拿到地面杂波、避障拿到墙面特征"的互相污染。 +- **建图**:`slam_toolbox`(`mode: mapping`,50 Hz 发 TF)。里程计来自 Odin1, + `use_scan_matching: false`——完全信任里程计,代价是漂移直接进地图。 +- **定位**:`map_server` 载入先验地图 + `nav2_amcl`(`OmnidirectionalMotionModel`, + 麦轮必须用全向模型,差分模型会把横移当噪声)。AMCL 发 `world → odom`。 +- **规划/控制**:NavFn 全局 + `SimpleSmoother` + MPPI(`motion_model: Omni`), + 代价地图分辨率 0.05 m(0.16 m 的箱在 0.1 m 栅格上只占 1–2 格,膨胀后仍可能被当作可穿越缝隙)。 +- **动作原语**:`MoveTo`(车体系定距,容差 2 cm)、`OrientTo`(odom 绝对 yaw,容差 1°)、 + `RampDrive`(四段速度曲线 + 航向保持)。行为树调用前先暂停 Nav2 生命周期, + 把 `/cmd_vel` 让给原语。 +- **编排**:`py_trees`。共享叶子节点库里只有"调一个 Action/Service 并映射状态", + 决策全部写在装配层。 + +**数据流** ``` - ┌──────────────────────────────┐ - 传感器/定位 ───────► │ 决策:方案 A / B / C 三选一 │ ───► /cmd_vel ──► 底盘 - └──────────────────────────────┘ +Odin1 ──点云──► pointcloud_to_laserscan(双高度带) + ├─ /odin1/scan_low ──► Nav2 obstacle_layer + └─ /odin1/scan_slam ──► slam_toolbox(建图)/ AMCL(定位) +Odin1 ──里程计──► TF: odom ──► imu ──► base_link(地面投影点) + │ + world ◄──(slam/AMCL)───┘ + ▼ + Nav2(NavFn → Smoother → MPPI)──┐ + Action 原语(MoveTo/OrientTo)───┼──► /cmd_vel ──► 底盘串口桥 + 行为树(py_trees)编排 ──────────┘ +``` + +**与前三套的实质差异** + +1. **先验地图 → 全局定位**:上电后不问"我在哪",而是直接匹配到地图上的绝对位置。 + 失效条件也随之而来:场地改动、上电位置在地图外、场地高度对称、地面反光…… + 详见 `nav2_ws/docs/SOLUTION_D.md` 第 5 节。 +2. **Action 原语层**:把"贴边 3 cm""固定退 15 cm 再转 30°"这类 Nav2 天生做不好的动作 + 变成可复用、可单测的闭环原语。 +3. **行为树编排**:异常恢复从"写在 FSM 里的 if"变成树的结构(Selector 换策略、Retry 限次重试)。 + +**已知代价** + +- 2D 投影**丢掉高度信息**:16 cm 的箱与 2 m 的墙在 costmap 里等价, + 对"能不能压过去"的判断比方案 A 更宽松。 +- `range_min 0.6 m ≈ 车体外接圆`(0.81×0.80 → 0.569 m):投影节点没有自车裁剪, + 只能靠距离门限盖住自己的车体,代价是 **0.6 m 内完全看不见**,窄道需靠降速与 `MoveTo` 兜底。 +- 链路比 A 长(驱动 → 投影 → SLAM/AMCL → costmap → planner → controller), + 调参面更大;每层都有 topic/frame 可以看,但排查要按链路顺序走。 + +--- + +## 6. 四套方案的关系 + +``` + ┌────────────────────────────────────┐ + 传感器/定位 ───────► │ 决策:方案 A / B / C / 四 四选一 │ ───► /cmd_vel ──► 底盘 + └────────────────────────────────────┘ ``` - **A 与 B 共享感知层**(MID360 + Point-LIO),只是"规划—控制"这一层不同: A 是自研的轻量局部规划,B 是 Nav2 框架 + 自研优化后端。 -- **C 是另一条技术路线**,感知与决策一起被网络替代,与 A/B 不可混用。 -- 三者输出接口一致,**切换只影响决策层,执行层与底盘协议不变**。 +- **C 是另一条技术路线**,感知与决策一起被网络替代,与 A/B/D 不可混用。 +- **四与前三套都不共享代码**:独立工作空间 `nav2_ws`、独立参数、独立启动; + 只复用执行层的底盘桥(`/cmd_vel`)与 Odin1 驱动(`sru_ws`,一行不改)。 +- 四者输出接口一致,**切换只影响决策层,执行层与底盘协议不变**; + 但**必须分别启动**,不可同时跑。 --- -## 6. 当前状态 +## 7. 当前状态 | | 状态 | |---|---| | A(SCAN) | **实车跑通**:定位、起停、直线、绕障、窄道、掉头、指定终点朝向均已验证 | | B(Nav2+MINCO) | 代码完整,**未上实车** | | C(SRU) | 代码与本机推理链路完整,**未上实车**,需 Odin1 硬件 | +| D(方案四) | 8 个包编译通过、92 项纯逻辑单测全绿、7 个 launch 校验通过;**未上实车**,等 Odin1 装车后标定外参 | 选择 A 作为主方案的原因:链路短、每层都可观测可调, 便于针对比赛场地的具体几何(台阶、窄道、矮障碍)做定向处理; B 的框架更完整但调参面大,C 则缺乏可解释性和现场可调性。 +方案四补的正是 A 缺的那一块——**跨上电的全局定位**,代价是依赖先验地图。 diff --git a/minco_ws/docs/PROMPT_FOR_SOLUTION_4.md b/minco_ws/docs/PROMPT_FOR_SOLUTION_4.md new file mode 100644 index 0000000..32af541 --- /dev/null +++ b/minco_ws/docs/PROMPT_FOR_SOLUTION_4.md @@ -0,0 +1,301 @@ +# 新增方案四(提示词) + +> 用法:在**新窗口**中打开工作区 `/home/xie/RC2027_BR_code`, +> 把下面 `====` 之间的内容整段复制发过去。 +> 本文件是给 AI 的上下文,不是给人读的文档。 +> +> **前提已由用户确认(2026-11-02)**:车上有两台 Odin1、接受先验地图、 +> 方案四与方案 A 独立并新建 `nav2_ws/`、Nav2 插件沿用参考实现。 +> 只剩 2D 投影高度带一项未定,见第八节。 + +--- + +``` +================================================================ +# 角色与边界 + +你是 RC2027 BR 机器人项目的架构与实现助手。 +工作区:/home/xie/RC2027_BR_code(git 仓库) +参考实现:/home/xie/26赛季一队BR源码/Rc2026(**在仓库之外,不得提交入库**) + +【本轮目标】 +新建**第四套定位与导航方案(方案四)**,代码放**新工作空间** `nav2_ws/`, +与 `minco_ws/`、`sru_ws/` 平级。参考 Rc2026 的实现思路与插件选型。 +本轮做:设计文档 + 可编译包骨架 + 纯逻辑单测 + 无绝对路径的 launch。 +**不做**:上实车、改方案 A、重写底盘协议、修改 Odin1 驱动。 + +【最重要的约束】 +1. 方案 A(`minco_ws/src/scan`)实车在用且已逐项验证,**方案四与它完全独立**: + 不共享包、不共享参数文件、不改它的代码。两套分别启动,不可同时跑。 +2. 参考目录在仓库外。只复制必要源码,`files/`(423 MB)与 `.git` 一律不要; + 复制后检查有没有夹带绝对路径。 +3. `/cmd_vel` 是唯一执行接口,复用底盘桥 + `minco_ws/src/chassis/techx_r2_chassis_control`,不要另写一套。 + +# 一、现状:仓库已有三套方案 + +出处:`minco_ws/docs/NAVIGATION_SOLUTION.md`(方案四落地后需更新这一篇) + +| | 方案 A(在用) | 方案 B(备用) | 方案 C(备用) | +|---|---|---|---| +| 位置 | `minco_ws/src/scan` | `minco_ws/src/navigation` | `sru_ws` | +| 传感器 | MID360 | MID360 | Odin1 | +| 定位 | Point-LIO(激光惯性,无回环) | Point-LIO | Odin1 自带高频里程计 | +| 规划 | A* + B 样条(局部滑窗 3.5 m) | Nav2 + SMAC + MINCO | 无规划 | +| 控制 | 自写轨迹跟踪 | MINCO MPC(qpOASES) | 网络直接出速度 | +| 先验地图 | 无 | 无 | 无 | +| 状态 | 实车跑通 | 未上实车 | 未上实车 | + +三者都只输出 `geometry_msgs/Twist` 到 `/cmd_vel`,切换只换决策层。 + +# 二、参考实现 Rc2026 的真实架构(已逐项核实,勿凭印象) + +根目录 `/home/xie/26赛季一队BR源码/Rc2026`,ROS 2 Humble + Python 为主(305 个 .py)。 + +## 2.1 它不是纯脚本走位 + +`src/action/bringup/launch/stable/challenge1.launch.py` 实际启动链: + +``` +odin_ros_driver(点云 + 高频里程计 + RGB) + → pointcloud_to_laserscan(/odin1/cloud_slam → /odin1/scan) + → slam_toolbox online_async(建图,mode: mapping) + → nav2_bringup localization_launch.py(AMCL) + → nav2_bringup navigation_launch.py(planner/controller) + → vehicle_driver(串口桥) + → 各 Action 节点 + py_trees 行为树 +``` + +**方案四的正确定性:先验地图 + 2D 激光 SLAM/Nav2 作主干, +Nav2 做不了的动作退化成离散 PID Action 原语,由行为树统一编排。** + +## 2.2 已核实的 Nav2 插件选型(用户要求"参考源码用什么就用什么") + +出处 `src/action/bringup/config/challenge1/nav2/v2/nav2v2.yaml`: + +| 角色 | 插件 | +|---|---| +| 全局规划 | `nav2_navfn_planner/NavfnPlanner` | +| 控制器 | `nav2_mppi_controller::MPPIController` | +| 平滑器 | `nav2_smoother::SimpleSmoother` | +| 目标判定 | `nav2_controller::SimpleGoalChecker` | +| 进度检查 | `nav2_controller::SimpleProgressChecker` | +| 恢复行为 | `spin` / `backup` / `drive_on_heading` / `assisted_teleop` / `wait` | + +代价地图: +- 局部:`voxel_layer` + `inflation_layer` +- 全局:`static_layer` + `obstacle_layer` + `inflation_layer` +- `consider_footprint: true` + +参考实现的车体参数(**这些必须改,不能照抄**): +``` +footprint: 边长 0.5 m 的正方形,robot_radius 0.25 +footprint_padding: 局部 0.03 / 全局 0.01 +速度上限: [1.5, 1.5, 3.0] (vx, vy, wz) +``` + +⚠️ RC2027 的真实差异: +- 车体 0.81 × 0.80 m(验收文档里含基础裕度为 0.99×0.98),**不是 0.5×0.5** +- 底盘桥限幅 **vx 0.5 / vy 0.5 / wz 0.5**,Nav2 的 `[1.5, 1.5, 3.0]` 会被 + 底盘**静默截断**,表现为跟踪误差累积。必须把 Nav2 限幅设到 ≤ 0.5。 + +## 2.3 slam_toolbox 参数 + +出处 `src/action/bringup/config/challenge1/slam_toolbox/slamtoolbox_v1.yaml`: + +``` +mode: mapping # 建图;定位时改 localization +resolution: 0.1 +max_laser_range: 20.0 +transform_publish_period: 0.02 # 50 Hz +map_update_interval: 1.0 +do_loop_closing: false +minimum_travel_distance: 0.0 +enable_interactive_mode: false +``` + +## 2.4 2D 投影参数(关键,与第八节直接相关) + +出处 `src/action/bringup/config/challenge1/exts/exts_pointcloud_to_laserscan.yaml`: + +``` +target_frame: base_link +cloud_in_topic: /odin1/cloud_slam +min_height: 0.0 max_height: 0.5 # 高度带 0–0.5 m +angle_min/max: ±3.14159 +angle_increment: 0.0043 # ≈0.25° +range_min: 0.6 range_max: 10.0 +scan_time: 0.1 +scan_out_topic: /odin1/scan +``` + +⚠️ **两个必须知道的点**: +1. `range_min: 0.6` 基本等于车体外接圆半径(0.81×0.80 的车,半对角约 0.57 m)。 + 也就是说它**用距离门限代替了自身点过滤**——好处是不用做自身裁剪, + 代价是 **0.6 m 内的障碍完全看不见**。 +2. 仓库里这份 `pointcloud_to_laserscan` 是**改造版**,有 `enable_second_scan` + 参数,但 `cloudCallback` 是对**同一份 `cloud_in`** 调用两次 `processLaserScan`, + 只是高度带/角度/量程不同。参数里的 `scan_out_topic2: '/livox/scan2'` + 是历史遗留的话题名,**并不存在第二路传感器输入**。 + +## 2.5 分层与包清单 + +| 层 | 包 | 做法 | +|---|---|---| +| 驱动 | `src/driver/vehicle_driver` | 50 Hz TX / 100 Hz RX 串口;麦轮、升降、4DOF 臂(含 IK)、吸盘、舵机 | +| 驱动 | `src/driver/odin_ros_driver` | C++ 封装 Odin1 SDK,出点云 / 高频里程计 / RGB | +| 原语 | `src/custom/actions/move_actions` | 车体系 XY 位移 PID Action(`MoveTo.action`),到位 < 2 cm | +| 原语 | `src/custom/actions/orient_actions` | odom 系绝对 yaw PID Action(`OrientTo.action`),误差 < 1° | +| 专用 | `ramp_drive` | 四段速度曲线 + 自适应线保持 | +| 专用 | `fine_tune_align` | 双 AprilTag PID 精对准 | +| 专用 | `merlin_stairs` | ToF 闭环 + 光电触发 + 升降联动 | +| 专用 | `zone_detection` | 点云直方图地面检测 + PCA 方向估计,误差 < 5 cm | +| 专用 | `merlin_planning` | 12 级台阶 BFS | +| 编排 | `src/action/{challenge1,challenge2,competition}` | **py_trees + py_trees_ros 行为树**,共享叶子节点库,含异常恢复 | +| 启动 | `src/action/bringup` | 按赛题分 launch,`config//<子模块>/` 分目录存参数 | + +## 2.6 已知要避开的坑 + +- launch 里有**硬编码绝对路径**,例如 + `/home/inkc/inkc/Rc2026/src/action/bringup/script/rosout_file_logger.py`。 + 复制过来**不会报错,会静默跑错脚本**。必须换成 `get_package_share_directory`。 +- `bringup/config/nav2/` 下 `v1`、`v2`、`backup/nav2v2.yaml` 三份历史版本共存。 +- `zone_detection/zone3_backup_2026xxxx/` 是带时间戳的备份,不是现行代码。 + +# 三、方案四相对前三套的实质差异 + +| | A | B | C | **方案四** | +|---|---|---|---|---| +| 先验地图 | 无,上电原点重置 | 无 | 无 | **有**,跨上电全局定位 | +| 定位 | LIO 里程计 | LIO 里程计 | Odin1 里程计 | **slam_toolbox 建图 + AMCL** | +| 规划 | 局部滑窗 A* | 全局 costmap + SMAC | 无 | Nav2 NavFn(地图系全局) | +| 控制 | 自写跟踪 | MINCO MPC | 网络出速度 | **Nav2 MPPI** | +| 处理特例 | 靠调参 | 靠调参 | 靠训练 | **切成离散 Action 原语** | +| 编排 | FSM | Nav2 BT | 单节点循环 | **py_trees 行为树** | + +新东西是三件:先验地图带来的全局定位、Action 原语层、行为树编排。 + +# 四、移植范围 + +## 要移植 +- `src/exts/pointcloud_to_laserscan`(本机缺这个包;注意它是改造版,见 2.4) +- slam_toolbox 与 Nav2 的**参数组织方式**(分目录),参数值按 RC2027 重调 +- `move_actions` / `orient_actions` 的 **Action 接口与 PID 结构** +- `ramp_drive` 的**四段速度曲线 + 线保持**思路 +- 行为树的**分层方式**(共享叶子节点库 + Sequence/Selector) +- bringup 的分层 launch 写法 + +## 不要移植 +`kfs6d_detect`、`kfs_tracker`、`arm_control`、`weapon_detect`、`merlin_stairs`、 +`fine_tune_align`、`merlin_planning`、`zone_detection` 的赛题几何、 +`files/`、`.git`、任何绝对路径。 + +## 必须改造 +- 底盘:用 `minco_ws/src/chassis/techx_r2_chassis_control` + (订阅 `/cmd_vel`,`omega_sign: -1.0`,限幅 0.5)。**不要**移植 Rc2026 串口协议。 +- Odin1 驱动:仓库已有 `sru_ws/src/odin_ros_driver`,直接复用,不要重复复制。 +- frame 名:RC2027 用 `world` / `camera_init` / `body_odom`, + Rc2026 用 `odom` / `base_link`。统一到 RC2027 命名。 +- footprint / 速度限幅:按 2.2 的告警改。 + +# 五、硬件:两台 Odin1 的可用性 + +用户已确认:**车上有两台 Odin1**,只是在测方案 A 时没有装车。 + +由此带来的设计空间(第八节展开): +- 一台专供 slam_toolbox / AMCL(高位、宽高度带、长量程) +- 另一台可专供**低高度带**做局部障碍,喂 Nav2 的 obstacle_layer +- 但一个 `pointcloud_to_laserscan` 实例只吃一路点云,两路要起两个实例 + +# 六、环境事实(已核实,别重复排查) + +已安装:`nav2_bringup`、`slam_toolbox`、`nav2_amcl`、`nav2_controller`、`nav2_planner` +**缺失**:`pointcloud_to_laserscan`(参考目录 `src/exts/` 有源码;apt 版 +`ros-humble-pointcloud-to-laserscan` **没有** `enable_second_scan` 改造) + +构建:colcon,本机 24 核但编大包会 OOM:用 `--parallel-workers 1` + `MAKEFLAGS="-j2"`。 +`-DCMAKE_CXX_FLAGS="-O1"` 会**持久化在 CMakeCache**,清除须显式传 `""`。 + +Python:ROS 脚本必须用 `/usr/bin/python3`(3.10);默认 `python3` 是 3.13, +`import rclpy` 会失败。 + +# 七、交付物 + +1. `nav2_ws/docs/SOLUTION_D.md` + - 与 A/B/C 的对比表 + - 数据流 ASCII 图(Odin1 → scan → slam/AMCL → Nav2 → `/cmd_vel`) + - 移植映射表(要/不要/要改) + - **明确写出"依赖先验地图"的失效条件** + - 记录 2D 高度带的取舍(第八节) +2. `nav2_ws/src/` 包骨架(colcon 能编过,节点可为空实现) + - 地图与定位:slam_toolbox 配置 + Nav2 params + 示例地图目录 + - `move_actions` / `orient_actions`:Action 定义 + PID 服务器 + 单测 + - `ramp_drive`:速度曲线纯函数 + 单测 + - 行为树:共享叶子节点库 + 一个示例流程 + - `bringup`:无绝对路径的 launch +3. `nav2_ws/docs/PORTING_NOTES.md`:逐条记录复制了什么、改了什么 +4. 更新 `minco_ws/docs/NAVIGATION_SOLUTION.md`:三套 → 四套。 + **等新方案能编译通过之后再改**。 + +# 八、唯一未定项:2D 投影的高度带 + +用户尚未决定,思路是"后续把 Odin1 与 MID360 配合"。请先给方案对比再动手, +不要默认选一个就实现。 + +先摆事实(已核实): + +- 参考实现用 **0–0.5 m** 单带 + `range_min 0.6`。 +- 改造版节点支持 `enable_second_scan`,但那是**同一份点云的第二个高度带**, + **不是第二路传感器**。想接 MID360 必须改 C++ 或先合并点云话题。 +- 2D 投影**丢掉高度信息**:投影后 Nav2 只看到"某方向有一条线", + 16 cm 的箱子和 2 m 的墙在 costmap 里**等价**。 +- 这与方案 A 正在排查的"16 cm 纸箱扫不到"是同一类问题的两面: + A 是看不见矮障碍;方案四是看见了但**无法与高墙区分**。 + 对通过性判断方案四更宽松;对"必须绕开这个矮箱"两者都做不到分层决策。 + +可选路线(评估后给建议,不要直接实现): + +| 路线 | 做法 | 代价 | +|---|---|---| +| 1 单台 Odin1,单高度带 | 照抄 0–0.5 m | 最省事;近距 0.6 m 盲区;无高低分层 | +| 2 单台 Odin1,双高度带 | `enable_second_scan`,如 0–0.5 与 0.4–1.2 | 同一份云;两带都进 costmap 会互相污染,需明确哪路进 obstacle_layer | +| 3 两台 Odin1,各一路 scan | 各起一个实例,各吃自己的点云 | 需解决两路 scan 如何进同一 costmap(obstacle_layer 可配多话题);要标定两台的相对位姿 | +| 4 Odin1 + MID360 融合 | 合并点云再投影,或改节点支持第二路 `cloud_in` | 需改 C++ 并处理两路 QoS/时间戳;MID360 现被方案 A 占用,需确认能否同时发布 | + +必须在文档里回答: +- 选哪条,为什么,以及这条路线**明确放弃**了什么能力 +- 高度带上下界依据(车体高度、地面平整度、目标障碍高度) +- `range_min` 取多少,对应车体外接圆半径多少,近距盲区如何补偿 + +# 九、验收标准 + +- `colcon build` 通过 +- 纯逻辑单测全绿,且可在**未 source ROS** 的环境下运行 +- launch 中不含任何 `/home/` 开头的绝对路径 +- `git status` 只新增 `nav2_ws/`,`minco_ws/` 无改动 +- Nav2 速度限幅 ≤ 0.5,footprint 与 0.81×0.80 车体一致 +- 文档写明"依赖先验地图"的失效条件与高度带取舍 + +# 十、回复格式 + +先给: +1. 第八节四条路线的对比与建议(标清哪条需用户确认) +2. 包结构草案(目录树) +3. 移植映射表(要/不要/要改) +4. 本轮能独立完成的、必须等用户确认的,分开列 + +然后再开始写代码。 +================================================================ +``` + +--- + +## 本版相对上一版的修正(都是查证后改的) + +| 项 | 上一版 | 本版(已核实) | +|---|---|---| +| 控制器插件 | 写成 DWB | **`nav2_mppi_controller::MPPIController`** | +| 全局规划 | 写成 SMAC | **`nav2_navfn_planner/NavfnPlanner`** | +| `enable_second_scan` | 暗示可接第二路传感器 | **同一份点云的两个高度带**,`/livox/scan2` 只是历史话题名 | +| `range_min` | 未提 | **0.6 m ≈ 车体外接圆半径**,等于用距离门限代替自身过滤 | +| 五个待定问题 | 全部待定 | 前四条已闭环,只剩高度带 | diff --git a/minco_ws/docs/PROMPT_FOR_SOLUTION_C.md b/minco_ws/docs/PROMPT_FOR_SOLUTION_C.md new file mode 100644 index 0000000..e5624f5 --- /dev/null +++ b/minco_ws/docs/PROMPT_FOR_SOLUTION_C.md @@ -0,0 +1,360 @@ +# 方案 C(sru_ws)落地提示词 + +> 用法:在**新窗口**中打开工作区 `/home/xie/RC2027_BR_code`, +> 把下面 `====` 之间的内容整段复制发过去。 +> 本文件是给 AI 的上下文,不是给人读的文档。 +> +> 起因:用户问"方案 C 真做出来要怎么做,是不是必须导入车体模型重新训练"。 + +--- + +``` +================================================================ +# 角色与边界 + +你是 RC2027 BR 机器人项目的架构与实现助手。 +工作区:/home/xie/RC2027_BR_code + +【本轮要解决的问题】 +方案 C(`sru_ws`,SRU 端到端无图导航)目前"代码齐、未上实车"。 +用户问的是:**把它真做出来要怎么做,是不是必须导入车体模型重新训练。** +本轮任务是把这个问题做实、给出可执行路径,而不是直接开始训练。 + +【不要做的事】 +- 不要动 `minco_ws/`(方案 A,实车在用) +- 不要提交 `sru_ws/reference/` 里的训练资源(体积大) +- 不要在没做零样本基线之前就开始准备训练环境 +- 不要因为"端到端策略一般要重训"就跳过验证 + +# 一、方案 C 现状(已核实) + +位置 `sru_ws/`,三个包: +| 包 | 作用 | +|---|---| +| `src/sru_nav_ros2/` | 部署包(28 MB,含 `models/vae_encoder.onnx` + `models/nav_policy.onnx`) | +| `src/odin_ros_driver/` | Odin1 驱动(点云、深度、高频里程计、RGB) | +| `src/techx_r2_chassis_control/` | 底盘串口桥(与方案 A 同一个,订阅 `/cmd_vel`) | + +另有 `reference/SRU-Odin/`:上游开源工程,含 `Deployment/`(ROS 1 蓝本) +与 `Train/`(Isaac Sim 训练代码)。 + +**已验证 / 未验证**(出处 `src/sru_nav_ros2/docs/HANDOVER_TEAM.md`): +- 已验证:ROS 2 部署链路能跑、ONNX 推理正常、话题契约自洽 +- **未验证:任何实车行为**。方案 A 的调参经验**完全不可迁移** + +## 与其他方案的关系(2026-11-02 现状) + +- 方案四已落地在 `nav2_ws/`(`behavior` / `bringup` / `exts` / `interfaces` / + `primitives`,已 colcon 构建)。`NAVIGATION_SOLUTION.md` 已更新为四套。 +- ⚠️ **方案 C 与方案四都依赖 Odin1**。车上有两台,理论上可一台各接一路, + 但同时跑两套会争 GPU/CPU、TF 与 `/cmd_vel`。**不要同时启动**。 +- 方案 C 保持独立:**不要 import `nav2_ws/` 的任何包**,也不要复用它 vendor 的 + `pointcloud_to_laserscan`(那是 2D 投影,方案 C 用不上,它的输入是深度图)。 + +# 二、策略的精确规格(写代码前必须按这个来) + +出处 `src/sru_nav_ros2/sru_nav_ros2/model.py`: + +``` +VAE 编码器 : depth [1,1,40,64] -> mu [1,64,5,8] -> flatten 2560 +策略网络 : obs [1,2576] + h_in [1,1,512] + c_in [1,1,512] + -> raw_action [1,3], h_out, c_out + cmd_vel = tanh(raw_action) * POLICY_SCALE +``` + +16 维状态向量(`STATE_DIM = 16`): +``` +linear_vel(3) + angular_vel(3) + gravity(3) + last_action(3) + target_pos(4) +``` + +⭐ **关键:状态里没有任何关节/腿部/轮子信息。** +也就是说**观测接口本身是机型无关的**——这决定了第四节"要不要导入车体模型" +的答案不是简单的是或否。 + +部署侧既有行为(别重复踩): +- 没有深度图就**一条 `/cmd_vel` 都不发**(推理只由 depth 回调触发) +- 三个速度**同时**输出,不是"先转再走" +- 到达判定只看 XY 距离(约 0.75 m),**不要求朝向**;朝向另用 `/goal_yaw` +- 节点名固定 `sru_nav_node` + +# 三、关键事实:它是 Unitree Go2 四足策略 + +出处 `reference/SRU-Odin/Train/README.md` 与 +`Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/go2/`: + +- 训练环境:**Isaac Sim 4.5.0 + IsaacLab 2.1.1**,Docker 约 30 GB,需 GPU +- 算法:PPO + `rsl_rl` 的 SRU fork(`ActorCriticSRU`) +- 四阶段流水线:Smoke → Cold-start(1024 envs,30k iter)→ Curriculum → PureMaze +- 任务注册:`Isaac-Nav-PPO-Go2-v0` 等四个(Play / Dev / PureMaze 变体) + +**它是分层的**: + +``` +高层 SRU 策略(要部署的就是这个) + │ 输出 [vx, vy, ω] —— SE2 速度指令 + ▼ +低层运动策略 policy_go2_jit.pt(12 个腿关节的位置动作) + │ JointPositionAction,scale=0.25 + ▼ +Isaac Sim 里的 Go2 四条腿 +``` + +Go2 配置里的三个关键量(`config/go2/navigation_env_cfg.py`): +``` +low_level_position_action : JointPositionActionCfg,12 个腿关节 +low_level_policy_file : assets/Policies/locomotion/go2/policy_go2_jit.pt +velocity_command.scale : [0.6, 0.3, 0.7] # vx, vy, ω +相机(ODIN1_CAMERA_CONFIG): 实车安装 25.8 cm 前、15.4 cm 高于机体 +``` + +⚠️ **一个容易看错的点**:代码里有 `low_level_velocity_action` 分支, +看着像"给轮式底盘直接发速度"的通道。**它不是。** +`navigation_se2_actions.py` 里低层策略的输出被切成两段: +`actions_phase[:, :pos_dim]` 喂关节位置、`actions_phase[:, pos_dim:]` 喂轮速。 +这个分支是给 **B2W 轮腿**用的(既有轮又有腿), +**不存在"直接把 Twist 写进仿真"的现成通道**。 + +# 四、直接回答:要不要导入车体模型重新训练 + +**结论:要重训或至少微调,但不必先建环境——先花半天做零样本基线。** + +分三步,每步都能否决下一步: + +## 第 1 步(必须先做):零样本基线 + +用录好的 Odin1 深度包离线回放,喂现有 ONNX,看输出是否可用。 +成本最低,且能回答"退化到什么程度"。 + +- 输入:`/odin1/depth_img_competetion`(深度,米,约 10 Hz)+ `/odin1/odometry_highfreq` +- 做法:写纯离线脚本,按时间顺序把深度帧喂进 `LearningModel`, + 记录 `[vx, vy, ω]` 序列;不需 ROS 节点、不需硬件 +- 判据:输出是否**饱和**(长期贴 `POLICY_SCALE`)、是否**抖动**、 + 是否在通畅处仍输出绕行、同一场景是否复现 +- ⚠️ 这只是离线证据,**不能代替实车**;但足以判断"要不要重训" + +## 第 2 步(大概率):微调而非从零训练 + +若第 1 步显示退化,优先**微调**:保留 VAE 与 LSTM 权重, +只针对新机体重跑 Cold-start 的少量迭代。 + +理由:观测接口(深度 40×64 + 16 维状态)与动作接口(SE2 速度)**都不用改**, +改的是"被控对象的响应特性"。这是 domain adaptation,不是新任务。 + +⚠️ 微调也走 Isaac Sim,同样受显存限制。4060 笔记本(8 GB)只能把 +`NUM_ENVS` 压到 64 以下做,见 6.3。 + +## 第 3 步(微调不够时):从零重训 + +按 `Train/README.md` 的四阶段流水线跑。 + +⛔ **这一步在 4060 笔记本(8 GB)上不可行**:上游最低要求 12 GB, +标准 Cold-start 是 1024 envs / 30k iter。需要 ≥12 GB 的卡(4070 Ti 12 GB / +4080 16 GB)或云 GPU(4090 24 GB / A100)。**不要把这一步写进本轮计划**。 + +## 为什么"必须"重训——三个分布偏移 + +| 偏移 | Go2(训练时) | RC2027(部署时) | 影响 | +|---|---|---|---| +| 相机安装高度 | 25.8 cm 前 / 15.4 cm 上 | 未测,需实测 | 深度图统计分布直接变(地面占比、障碍轮廓) | +| 速度包络 | `[0.6, 0.3, 0.7]` | 底盘限 `[0.5, 0.5, 0.5]` | vy 从 0.3 放宽到 0.5、ω 从 0.7 收紧;同一输出物理响应不同 | +| 车体动力学 | 四足:启动滞后、步态起伏、机身俯仰 | 全向轮:响应快、几乎无侧滑、机身平稳 | 策略学到的"动作→下一时刻状态"映射失效 | + +第三个是根因:输入里含 `last_action` 与速度, +策略内部已拟合"发出这条指令后机器人会怎么动"。换底盘,这条动力学先验就是错的。 + +# 五、如果重训,具体改什么(按改动量从小到大) + +1. **相机配置**(必改) + `ROBOT_CAMERA_CONFIGS` 当前是 `{"b2w": ZEDX, "aow_d": ZEDX, "go2": ODIN1}`。 + 需新增 RC2027 条目,填实测安装高度/前向偏移/视场。 + 注意 `initialize_depth_noise_generator(robot_name=...)` 会**复用同一份相机配置** + 生成深度噪声,改一处覆盖两处。 + +2. **速度 scale**(必改) + `velocity_command.scale` 从 `[0.6, 0.3, 0.7]` 改为 RC2027 真实限幅, + 必须 ≤ `0.5`,否则仿真学到的指令实车发不出去。 + +3. **低层动作分支**(必改,**没有现成实现**) + 全向轮没有腿,用不上 `policy_go2_jit.pt`。两条路: + - **推荐**:新增"运动学底座"动作项,直接把 `[vx, vy, ω]` 写进 root velocity + (IsaacLab 有写根速度的接口)。全向轮几乎无侧滑,运动学近似足够, + 且**不需要导入整车 USD** + - 备选:导入完整轮系 USD(4 个轮关节)+ 每轮速度控制器再训练。 + 只有需要建模打滑/轮胎滞后时才值得 + ⚠️ 不要以为 `low_level_velocity_action` 能直接用,见第三节 + +4. **车体尺寸与碰撞体**(仅走完整 USD 时需要) + RC2027 车体 0.81 × 0.80 m(含基础裕度 0.99×0.98),与 Go2 差异大。 + 影响碰撞判定与可行域,不改进不去窄道。 + +5. **地形与奖励**(视场景决定) + 上游是为"长距离无图越野 + PureMaze"设计的。若场地是结构化室内, + 地形复杂度与奖励权重都要重估——**这一项不要照抄**。 + +# 六、环境依赖(训练机已定:RTX 4060 笔记本,但低于上游最低要求) + +## 6.1 本机(开发机)不能训练 + +`lspci` 显示 `AMD/ATI Rembrandt (rev c9)`,**AMD 核显**。 +Isaac Sim 4.5 只支持 NVIDIA RTX(最低 RTX 3070 / 8 GB / 必须有 RT Core), +**AMD 与核显完全不支持,且不支持 VM/WSL**。 +⇒ 本机只能做:离线零样本基线、装车几何核对、实车测试。 + +## 6.2 训练机:RTX 4060 笔记本(8 GB 显存) + +⚠️ **上游 `Train/README.md` 明确写的门槛,4060 笔记本差一条**: + +| 项 | 上游要求 | 4060 笔记本 | 结论 | +|---|---|---|---| +| 显存 | **最低 12 GB**,推荐 24 GB+ | 8 GB | ❌ **低于最低要求** | +| NVIDIA 驱动 | ≥ 570(避开 595.x) | 需自查 | 待确认 | +| 磁盘 | **最低 80 GB**,推荐 120 GB+ | 需自查 | 待确认 | +| Docker | 24.0+,装 NVIDIA Container Toolkit | 需自查 | 待确认 | +| NGC 账号 | 必需(拉 `nvcr.io/nvidia/isaac-sim:4.5.0`) | 需申请 | 待确认 | + +上游给的 VRAM 对照表(`Train/README.md`): +``` +RTX 5070 12 GB → NUM_ENVS 768–1024 +RTX 4090 24 GB → NUM_ENVS 2048–2820 +A100 80 GB → NUM_ENVS 8000+ +``` +**没有 8 GB 那一行**——说明 8 GB 不在作者验证范围内。 + +## 6.3 8 GB 上还能做什么、不能做什么 + +能: +- **Smoke 阶段**:`NUM_ENVS=16~32`,`MAX_ITER=100` 量级,验证镜像能起、 + 任务能注册、能从 ONNX 侧对得上——这一步价值很高,能提前暴露环境问题 +- **流程验证**:跑通 `train_go2_scratch.sh` → `play_go2.sh` → 导出 ONNX 的链路 +- **小规模微调**(若最终决定走微调):`NUM_ENVS` 压到 64 以下, + 只加载已有权重跑少量迭代 + +不能(或代价不可接受): +- **Cold-start 的 1024 envs / 30k iter**:显存差一半,靠降 env 数硬顶会让 + 30k iter 变成不可接受的长跑,而且并行环境太少会显著影响 PPO 的样本效率 +- **从零重训出可用策略**:不在 8 GB 的现实范围内 + +⇒ 结论:**4060 笔记本适合"验证流水线 + 小规模微调",不适合"从零重训"。** +若最终判定必须重训,需要 ≥12 GB 的机器(RTX 4070 Ti 12 GB / 4080 16 GB) +或云 GPU(4090 24 GB / A100)。 + +## 6.4 训练脚本的规模控制方式(不用改代码) + +`Train/scripts/*.sh` 全部由**环境变量**驱动: + +```bash +NUM_ENVS=24 # 并行环境数,默认 24(dev 脚本) +MAX_ITER=1000 # PPO 迭代数 +TASK=Isaac-Nav-PPO-Go2-Dev-v0 +GUI=0 # 默认无头 +SEED=42 +GPU= # 指定卡号 +RUN_NAME=... +``` + +正式入口(`scripts/continue_go2.sh`)默认 `NUM_ENVS=1024`; +`Train/README.md` 里给出的标准命令是 +`TASK=Isaac-Nav-PPO-Go2-v0 NUM_ENVS=1024 MAX_ITER=30000`。 +**8 GB 上必须显式覆盖这些值**,不要用默认。 + +# 七、Odin1 的安装几何(训练时的实测规格,装车前必须按这个来) + +出处 `config/go2/navigation_env_cfg.py`: + +```python +# Real-robot Odin1 mount on Go2: 25.8 cm forward, 15.4 cm above body +# center, camera looking straight ahead (no pitch). +raycast_camera.offset.pos = (0.258, 0.0, 0.154) # 相对 body("base") 系 +raycast_camera.offset.rot = (1.0, 0.0, 0.0, 0.0) # 无俯仰 +raycast_camera.max_distance = 11.0 +``` + +Odin1 真实内参(1600×1296,`ODIN1_CAMERA_CONFIG` 里也是这套比例): +``` +fx = 737.357 fy = 737.292 cx = 794.372 cy = 666.259 +hFOV ≈ 94.67° vFOV ≈ 82.65° +min_depth = 0.25 max_depth = 10.0 +``` + +**装车时的要求(按重要性排序)**: + +1. **俯仰为 0**:相机光轴水平,不仰不俯。这是训练时的姿态,俯仰角偏差会直接 + 改变深度图里地面与障碍的比例。 +2. **高度**:相对车体原点(旋转中心)上方 **0.154 m**。 + Go2 站立时机体高度不在本仓库配置里,实际是"机体中心 + 0.154 m"; + **装到 RC2027 上时应让相机离地高度接近 Go2 训练时的水平**, + 建议实测 Go2 或按 0.4–0.5 m 量级取值后再确认。 +3. **前向偏移**:车体原点前方 **0.258 m**。装得太靠后,车体会进入视野。 +4. **不能自我遮挡**:vFOV 82.65° 很大,向下视野宽。相机附近的车体结构 + (雷达支架、线束、车头护板)若进入视野,会被策略当成障碍。 + **装完必须看一遍深度图**确认没有自身结构。 +5. **刚性固定**:策略输入含 `last_action` 与速度,靠视觉-运动一致性工作。 + 相机松动或抖动会破坏这个一致性。 +6. ⚠️ **深度图必须先去畸变**:训练侧用的是理想针孔 raycast(忽略 k2..k7)。 + 配置注释明确写了 "The real-side pipeline must undistort before feeding the network"。 + **装完要确认驱动输出的深度是否已去畸变**,这是容易漏的一步。 + +# 八、必须先回答的问题 + +1. ~~本机有可用 NVIDIA GPU 吗?~~ **已确认没有**(AMD 核显,见 6.1)。 + 训练机已定为 **RTX 4060 笔记本(8 GB)**,但**低于上游 12 GB 的最低要求**。 + 新的问题是:**是否接受"只做流水线验证 + 小规模微调"这个上限?** + 若最终判定必须从零重训,需要另找 ≥12 GB 的机器或云 GPU。 + 请在结论里写清这个约束,不要给出 4060 跑不动的训练计划。 +2. **Odin1 装在 RC2027 上的实测安装高度、前向偏移、俯仰角是多少?** + 训练时的规格见第七节(相对车体原点:前 0.258 m、上 0.154 m、无俯仰)。 + 需要实测 RC2027 能否复现这个几何;**差多少要量化写下来**, + 因为它直接决定零样本退化程度。 +3. **本轮验收目标是哪一个?** + (a) 只交付零样本基线的证据与结论 + (b) 交付装车几何核对 + 深度图自检结果 + (c) 交付微调后的新 ONNX + 对比数据(**需外部 RTX 机器**) + 三者工作量差一个数量级,不要默认选最大的那个。 +4. **近期有实车测试窗口吗?** 用户已确认**有实车**,只是 Odin1 还没装车。 + 所以第 (b) 项现在就可做,且它决定了后面所有验证的前提。 + +# 九、交付物(按第八节第 3 问的选择裁剪) + +无论选哪个都要有: +1. `sru_ws/docs/SOLUTION_C_ASSESSMENT.md` + - 零样本基线的做法、数据、结论 + - "要不要重训"的判断与依据(指向具体证据,不是"一般认为") + - 若重训:改动清单(对应第五节五条)与环境需求核对结果 +2. 零样本回放脚本(纯离线,不依赖 ROS 与硬件,可用 `/usr/bin/python3` 跑) +3. 单元测试:深度预处理(600×960 → 40×64)、状态向量拼装顺序、 + `tanh * POLICY_SCALE` 的边界行为 + +**不要**在没有 GPU 确认的情况下开始写训练脚本。 + +# 十、验收标准 + +- 零样本脚本能对一段录包产出可读的速度序列与统计 + (饱和率、抖动、与目标方向的一致性) +- 结论明确写出"建议零样本上车 / 建议微调 / 建议重训", + 并列出该结论**依赖哪些未确认的前提** +- 任何"需要重训"的论断都能指到第四节的三个分布偏移之一,不能空泛 +- 不修改 `minco_ws/` +- 纯逻辑测试可在未 source ROS 的环境下运行 + +# 十一、回复格式 + +先给: +1. 第七节四个问题的现状(能查的自己查,查不到的明确标"需用户确认") +2. 你对"零样本 / 微调 / 重训"三档的初步判断与理由 +3. 第五节改动清单里,哪些能在不训练的情况下先做掉 +4. 本轮计划交付到哪一步 + +然后再动手。 +================================================================ +``` + +--- + +## 本文件的关键结论(备查) + +| 问题 | 结论 | 依据 | +|---|---|---| +| 要不要重训 | 要,但先做零样本基线 | 三个分布偏移,见第四节 | +| 要不要导入整车模型 | **不一定**,全向轮用运动学底座即可 | 观测里无关节信息,见第二节 | +| `low_level_velocity_action` 能用吗 | **不能**,那是 B2W 轮腿专用 | 低层策略输出被切成关节+轮速两段 | +| 改动最小的一步 | 相机配置 + 速度 scale | 不动训练,先改配置 | diff --git a/minco_ws/docs/diagnostics/analyze_map_acceptance.py b/minco_ws/docs/diagnostics/analyze_map_acceptance.py new file mode 100644 index 0000000..fd6cb0d --- /dev/null +++ b/minco_ws/docs/diagnostics/analyze_map_acceptance.py @@ -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()) diff --git a/minco_ws/docs/diagnostics/analyze_pose_jitter.py b/minco_ws/docs/diagnostics/analyze_pose_jitter.py new file mode 100644 index 0000000..b6e75e6 --- /dev/null +++ b/minco_ws/docs/diagnostics/analyze_pose_jitter.py @@ -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) diff --git a/minco_ws/docs/diagnostics/analyze_self_boundary.py b/minco_ws/docs/diagnostics/analyze_self_boundary.py new file mode 100644 index 0000000..37e74f6 --- /dev/null +++ b/minco_ws/docs/diagnostics/analyze_self_boundary.py @@ -0,0 +1,1918 @@ +#!/usr/bin/python3 +"""Offline diagnosis of self-body returns that survived the self filter. + +Read-only by construction: this opens a recorded bag and parses it. It never +starts a node, never plays the bag back, and never publishes a topic. Nothing +here influences the running filter, the collision margin, or any parameter. + +EVIDENCE GRADE (revised 2026-11-02 after architecture review) +------------------------------------------------------------ +This tool does not confirm a cause. It separates three kinds of observation and +reports how far each one can carry you. Two earlier claims were withdrawn: + + 1. It used to call the observed pose spread a "motion bound" and treat a + residual below it as explained. That is wrong: the pose spread of the + *recorded* odometry cannot bound the prediction error of the *unpublished* + anchor that Point-LIO actually used. The quantity is now named + observed_motion_scale, and it only brackets the motion that was observed -- + it is not an upper bound on anything. A residual below it is therefore + "inconclusive", and a residual above it is an "anomaly candidate", never a + confirmed transform defect. + + 2. It used to emit `unique` when one raw point was decisively nearest, which + reads as "same-source correspondence confirmed". It is not. Because a + published frame can draw points from several original scans, a competing + return in another candidate scan is not excluded by distance alone. The + value is now `heuristic_nearest`, and the nearest distance, the runner-up + distance, and their gap are all reported so a reviewer can judge for + themselves. + + A high ambiguity rate is a property of the data, not a defect in the tool, and + it is not a reason to relax the evidence requirement. + +Why the inverse transform cannot be exact +----------------------------------------- +Point-LIO publishes /cloud_registered_full through transformFullPointForward() +(laserMapping.cpp), which moves every point with a *predicted* anchor state: + + p_world = R_pred * (R_L_I * p_lidar + T_L_I) + p_pred + R_pred = anchor.rot * Exp(anchor.omg, dt) + p_pred = anchor.pos + anchor.vel*dt + 0.5*anchor.acc*dt*dt + +The anchor (rot/pos/vel/acc/omg) is an internal prediction snapshot and is NOT +published. Only /aft_mapped_to_init (the filtered IMU pose) is recorded. An +inverse built from recorded odometry is therefore an approximation whose error +is unknown, not merely small. + +ImuProcess::Process() (IMU_Processing.cpp) currently copies the cloud unchanged, +so feats_undistort is a raw single-frame cloud in the optical frame; the motion +compensation happens only inside transformFullPointForward(). That also means +the per-point `curvature` field (offset_time / 1e6, milliseconds) survives into +the world cloud -- but since one published frame may hold points from several +original scans, a curvature value maps to a *set* of instants, never one. +""" +from __future__ import annotations + +import argparse +import csv +import json +import math +import sqlite3 +import sys +import traceback +from pathlib import Path + +import numpy as np + +TOOL_VERSION = "1.1.0" +SCHEMA_VERSION = 2 + +# Baseline measurement from the acceptance document. The config file is the +# actual input; a mismatch is reported, never silently accepted. +BASELINE = { + "self_front": 0.385, + "self_rear": 0.425, + "self_left": 0.400, + "self_right": 0.400, + "self_z_min": -0.48, + "self_z_max": 0.0, + "lidar_to_imu_translation": (-0.011, -0.02329, 0.04412), +} + +# Screening threshold for the raw<->world residual, PROVISIONAL. +# +# This is NOT an acceptance tolerance and NOT a verified noise bound. It exists +# only to suppress residual screening below a level where the comparison cannot +# be trusted, and it is reported so it can be challenged or varied afterwards on +# the same bag. +# +# What it is NOT allowed to stand in for: +# * the motion observed in a frame -- that is reported separately and exactly; +# * a measured sensor noise figure -- a raw return and its world-frame copy +# come from the SAME measurement, so they share that noise and it cancels. +# Repeated-measurement spread only enters when two DIFFERENT returns (from +# different scans) are associated. +# * storage resolution -- curvature is a float32 holding milliseconds, so its +# resolution near a 50 ms offset is a few nanoseconds, not one millisecond. +COMPARISON_SCREENING_M = 0.02 +DEFAULT_POSE_TIME_TOL = 0.03 # matches node.py's accepted cloud/pose gap +DEFAULT_POSE_GAP_WARN = 0.15 # node.py treats >0.15 s as a mismatch +DEFAULT_POSE_STALE = 0.25 # node.py's absolute age limit +DEFAULT_ASSOC_TIME_TOL = 0.002 # 2 ms; curvature is stored in ms as float32 +DEFAULT_ASSOC_XYZ_TOL = 0.12 # search radius: raw/world are different pipelines +DEFAULT_ASSOC_TIE_MARGIN = 0.02 # nearest must beat the runner-up by this much +CANDIDATE_FRAME_RADIUS = 2 # scans either side that may contribute points +# Diagnostic region of interest around the measured bodywork. Environment +# returns (walls, steps, furniture) are trivially outside a 0.81x0.80 m box, so +# counting them would make "outside the envelope" meaningless. Only returns this +# close to the box are evidence about the body. +BODY_ROI_MARGIN_M = 0.30 +DEFAULT_SHELL_MARGIN = 0.05 # keep raw points this far inside the box too +MAX_CSV_ROWS = 5000 +MAX_SAMPLE_ROWS = 20 + +TOPIC_RAW = "/livox/lidar" +TOPIC_WORLD = "/cloud_registered_full" +TOPIC_POSE = "/aft_mapped_to_init" +REQUIRED_TOPICS = (TOPIC_RAW, TOPIC_WORLD, TOPIC_POSE) + +EXIT_OK = 0 +EXIT_MISSING = 2 +EXIT_INCOMPATIBLE = 3 + + +class PathProblem(Exception): + """Unusable path or configuration; maps to exit code 2.""" + + +class BagProblem(Exception): + """Corrupt bag, unsupported storage, or incompatible message type. + + Maps to exit code 3. + """ + + +class MissingTopic(Exception): + """A required topic is absent; a partial report is still written.""" + + +# -------------------------------------------------------------------------- +# geometry +# -------------------------------------------------------------------------- + +def rotation_from_quaternion(quaternion): + """Rotation matrix from a quaternion, rejecting degenerate input. + + Mirrors obstacle_cloud.core.rotation_from_quaternion exactly so that a + point classified here matches what the live filter would have classified. + An all-zero quaternion is a missing orientation, not "identity": guessing + would hide the defect this tool is meant to find. + """ + q = np.asarray(quaternion, dtype=np.float64) + if q.shape != (4,) or not np.isfinite(q).all() or np.linalg.norm(q) < 1e-6: + raise ValueError("invalid IMU orientation for self filter") + x, y, z, w = q / np.linalg.norm(q) + return np.array([ + [1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], + [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], + [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)], + ]) + + +def load_geometry(config_path: Path) -> dict: + """Read the measured envelope and extrinsic from the runtime config. + + The config is the single source of truth. Anything that disagrees with the + acceptance document's baseline is surfaced in the returned dict under + 'baseline_differences' instead of being rejected. + """ + config_path = Path(config_path) + if not config_path.is_file(): + raise PathProblem(f"config not found: {config_path}") + try: + import yaml + except ImportError as exc: # pragma: no cover + raise PathProblem(f"PyYAML unavailable: {exc}") from exc + + try: + raw = yaml.safe_load(config_path.read_text(encoding="utf-8")) + except Exception as exc: + raise PathProblem(f"cannot parse config {config_path}: {exc}") from exc + if not isinstance(raw, dict): + raise PathProblem(f"config {config_path} is not a mapping") + + # Accept either the ROS parameter file shape or a flat mapping. + params = raw + for key in ("obstacle_cloud", "ros__parameters"): + if isinstance(params.get(key), dict): + params = params[key] + if isinstance(params.get("ros__parameters"), dict): + params = params["ros__parameters"] + + missing = [k for k in BASELINE if k not in params] + if missing: + raise PathProblem( + f"config {config_path} is missing keys: {', '.join(sorted(missing))}") + + geometry = { + "config_path": str(config_path.resolve()), + "self_front": float(params["self_front"]), + "self_rear": float(params["self_rear"]), + "self_left": float(params["self_left"]), + "self_right": float(params["self_right"]), + "self_z_min": float(params["self_z_min"]), + "self_z_max": float(params["self_z_max"]), + "boundary_guard": float(params.get("self_boundary_guard", 0.02)), + "lidar_to_imu_translation": np.asarray( + params["lidar_to_imu_translation"], dtype=np.float64), + } + + if not np.isfinite([ + geometry["self_front"], geometry["self_rear"], + geometry["self_left"], geometry["self_right"], + geometry["self_z_min"], geometry["self_z_max"]]).all(): + raise PathProblem(f"config {config_path} has non-finite envelope values") + for key in ("self_front", "self_rear", "self_left", "self_right"): + if geometry[key] <= 0: + raise PathProblem(f"config {config_path}: {key} must be positive") + if geometry["self_z_min"] >= geometry["self_z_max"]: + raise PathProblem( + f"config {config_path}: self_z_min must be below self_z_max") + if geometry["lidar_to_imu_translation"].shape != (3,) or \ + not np.isfinite(geometry["lidar_to_imu_translation"]).all(): + raise PathProblem( + f"config {config_path}: lidar_to_imu_translation must be 3 finite values") + + differences = [] + for key, expected in BASELINE.items(): + actual = geometry[key] + if key == "lidar_to_imu_translation": + if not np.allclose(actual, np.asarray(expected), atol=1e-9): + differences.append({ + "key": key, "config": actual.tolist(), + "baseline": list(expected)}) + continue + if not math.isclose(float(actual), float(expected), abs_tol=1e-9): + differences.append({ + "key": key, "config": float(actual), "baseline": float(expected)}) + geometry["baseline_differences"] = differences + geometry["baseline_as_documented"] = { + k: (list(v) if isinstance(v, tuple) else v) for k, v in BASELINE.items()} + return geometry + + +def envelope_bounds(geometry: dict): + """Return (lo, hi, guard) in the optical lidar frame. + + Axis convention comes from obstacle_cloud.core: x forward, y left, z up. + Hence front is +x, rear is -x, left is +y, right is -y. + + The guard is lateral only, matching core.classify_self_returns: extending + it downward would reclassify ordinary ground returns as bodywork. + """ + lo = np.array([-geometry["self_rear"], -geometry["self_right"], + geometry["self_z_min"]], dtype=np.float64) + hi = np.array([geometry["self_front"], geometry["self_left"], + geometry["self_z_max"]], dtype=np.float64) + guard = np.array([geometry["boundary_guard"], + geometry["boundary_guard"], 0.0], dtype=np.float64) + return lo, hi, guard + + +def _direction_label(axis: int, positive: bool) -> str: + return { + (0, True): "front", (0, False): "rear", + (1, True): "left", (1, False): "right", + (2, True): "up", (2, False): "down", + }[(axis, positive)] + + +def classify_envelope(points, geometry: dict) -> dict: + """Split points into inside / boundary band / outside. + + Semantics follow obstacle_cloud.core.classify_self_returns exactly: + inside within the measured box + boundary outside the box but inside the per-axis guard band + outside beyond the guarded box + + 'excess' is measured from the *physical* box faces, not from the guarded + ones, so a boundary-band point still reports how far it is outside the real + bodywork. The guard only decides which band a point falls in; the vertical + guard is zero, so a return below the floor is outside immediately. + """ + pts = np.asarray(points, dtype=np.float64).reshape((-1, 3)) + lo, hi, guard = envelope_bounds(geometry) + if len(pts) == 0: + return { + "inside": np.zeros(0, dtype=bool), + "boundary": np.zeros(0, dtype=bool), + "outside": np.zeros(0, dtype=bool), + "excess": np.zeros(0), "axis": np.zeros(0, dtype=int), + "positive": np.zeros(0, dtype=bool), + "distance_to_box": np.zeros(0), + } + + exceed_hi = pts - hi # >0 means beyond the +side face + exceed_lo = lo - pts # >0 means beyond the -side face + exceed = np.maximum(exceed_hi, exceed_lo) + excess = exceed.max(axis=1) + axis = np.argmax(exceed, axis=1) + rows = np.arange(len(pts)) + positive = exceed_hi[rows, axis] >= exceed_lo[rows, axis] + + inside = ((pts >= lo) & (pts <= hi)).all(axis=1) + within_guard = ((pts >= lo - guard) & (pts <= hi + guard)).all(axis=1) + boundary = within_guard & ~inside + outside = ~within_guard + + # L2 distance to the physical box surface, for readability only. + clipped = np.clip(pts, lo, hi) + distance_to_box = np.linalg.norm(pts - clipped, axis=1) + + return { + "inside": inside, "boundary": boundary, "outside": outside, + "excess": excess, "axis": axis, "positive": positive, + "distance_to_box": distance_to_box, + } + + +def body_shell_mask(classified: dict, + inner_margin: float = DEFAULT_SHELL_MARGIN, + outer_margin: float = BODY_ROI_MARGIN_M) -> np.ndarray: + """Which points are worth carrying into the association stage. + + Only a thin band around the envelope qualifies: a little inside (so a raw + return just inside a face can still be matched) and out to the body ROI. + Both bounds are required -- `excess` is the distance from the box faces, so + an unbounded lower test would accept every distant wall as well. + """ + excess = classified["excess"] + return (excess >= -abs(inner_margin)) & (excess <= outer_margin) + + +def envelope_label(classified: dict) -> np.ndarray: + """Per-point class label: 'inside' / 'boundary' / 'outside'. + + A *label* change is a stronger observation than an `outside` flag change, + because a point can move between inside and the boundary band without ever + becoming outside. Both are recorded, but neither selects a verdict. + """ + count = len(classified["inside"]) + labels = np.full(count, "outside", dtype=object) + labels[classified["boundary"]] = "boundary" + labels[classified["inside"]] = "inside" + return labels + + +# -------------------------------------------------------------------------- +# time +# -------------------------------------------------------------------------- + +def point_time_ns(timebase_ns: int, offset_ns: int) -> int: + """Absolute integer-nanosecond stamp of one Livox point. + + Verified against livox_ros_driver2: InitCustomMsg sets + timebase = pkg.base_time (uint64, ns) + header.stamp = rclcpp::Time(timestamp) (same instant) + and FillPointsToCustomMsg sets + offset_time = point.offset_time - pkg.base_time (uint32, ns) + so the per-point instant is timebase + offset_time, in the same clock as + the message header. Integer arithmetic only: float seconds lose ~100 ns of + resolution near a modern epoch, which is the same order as the offsets we + are trying to resolve. + """ + base = int(timebase_ns) + offset = int(offset_ns) + if base < 0 or offset < 0: + raise ValueError(f"negative timestamp components: {timebase_ns}, {offset_ns}") + if offset > 4_000_000_000: + raise ValueError(f"implausible offset_time {offset} ns for a Livox frame") + return base + offset + + +class PoseIndex: + """Nearest-neighbour lookup over recorded IMU poses. + + Deliberately nearest rather than interpolated: interpolation would invent a + pose that was never recorded and blur exactly the timing error we want to + measure. The returned dt lets callers reject a match instead. + """ + + def __init__(self, times_ns, positions, quaternions): + self.times = np.asarray(times_ns, dtype=np.int64) + self.positions = np.asarray(positions, dtype=np.float64).reshape((-1, 3)) + self.quaternions = np.asarray(quaternions, dtype=np.float64).reshape((-1, 4)) + if not (len(self.times) == len(self.positions) == len(self.quaternions)): + raise ValueError("pose arrays have inconsistent lengths") + self.regressions = int(np.sum(np.diff(self.times) <= 0)) + if len(self.times) > 1: + gaps = np.diff(self.times) / 1e9 + self.max_gap = float(gaps.max()) + else: + self.max_gap = 0.0 + self.valid = np.zeros(len(self.times), dtype=bool) + for i, q in enumerate(self.quaternions): + try: + rotation_from_quaternion(q) + except ValueError: + continue + if np.isfinite(self.positions[i]).all(): + self.valid[i] = True + + def __len__(self): + return len(self.times) + + def nearest(self, query_ns: int): + """Return (dt_seconds, index) or (inf, None) when unusable.""" + if len(self.times) == 0: + return math.inf, None + pos = int(np.searchsorted(self.times, query_ns)) + best = None + for idx in (pos - 1, pos, pos + 1): + if 0 <= idx < len(self.times) and self.valid[idx]: + delta = abs(int(self.times[idx]) - int(query_ns)) + if best is None or delta < best[0]: + best = (delta, idx) + if best is None: + return math.inf, None + return best[0] / 1e9, best[1] + + +# -------------------------------------------------------------------------- +# transforms and observed motion +# -------------------------------------------------------------------------- + +def inverse_transform(points_world, pose_position, pose_quaternion, + translation, rotation_fn=None) -> np.ndarray: + """World -> IMU -> optical lidar, using the full quaternion. + + p_IMU = p_lidar + T_L_I and p_world = R_world * p_IMU + pos + therefore p_lidar = R_world^T (p_world - pos) - T_L_I. + + This is the inverse of Point-LIO's forward map with the *recorded* pose + substituted for the unpublished anchor prediction. The substitution error + is unknown; it is not bounded by anything this tool can measure. + """ + fn = rotation_fn or rotation_from_quaternion + rotation = fn(pose_quaternion) + pts = np.asarray(points_world, dtype=np.float64).reshape((-1, 3)) + translation = np.asarray(translation, dtype=np.float64).reshape(3) + return (pts - np.asarray(pose_position, dtype=np.float64).reshape(3)) @ rotation \ + - translation + + +def observed_motion_scale(pose_positions, pose_quaternions, points_world, + rotation_fn=None) -> float: + """How much motion the recorded odometry actually spans during the frame. + + scale = translational extent + rotational extent * lever arm + + THIS IS NOT AN UPPER BOUND. It describes the observed motion of the robot. + It says nothing about the error of the unpublished anchor prediction, which + is the quantity that actually contaminates the world cloud. A residual above + this scale is therefore only an *anomaly candidate*: it exceeds the motion + that was observed, and no further attribution is supported. + + Returned unmodified, including the exact zero of a perfectly static frame. + Any floor belongs to the screening threshold, not here: mixing the two would + let an assumption masquerade as measured motion. + """ + fn = rotation_fn or rotation_from_quaternion + pos = np.asarray(pose_positions, dtype=np.float64).reshape((-1, 3)) + pts = np.asarray(points_world, dtype=np.float64).reshape((-1, 3)) + if len(pos) == 0 or len(pts) == 0: + return math.inf + + translational = float(np.linalg.norm(np.ptp(pos, axis=0))) if len(pos) > 1 else 0.0 + + rotational = 0.0 + quats = np.asarray(pose_quaternions, dtype=np.float64).reshape((-1, 4)) + if len(quats) > 1: + reference = None + for q in quats: + try: + reference = fn(q) + break + except ValueError: + continue + if reference is not None: + for q in quats: + try: + current = fn(q) + except ValueError: + continue + cosine = (np.trace(reference.T @ current) - 1.0) / 2.0 + rotational = max(rotational, + math.acos(max(-1.0, min(1.0, cosine)))) + + origin = pos.mean(axis=0) + lever = float(np.linalg.norm(pts - origin, axis=1).max()) if len(pts) else 0.0 + return translational + rotational * lever + + +def comparison_threshold(observed_scale_m: float) -> float: + """Residual screening threshold for a frame: the larger of the two. + + The residual is screened against the frame's own observed motion, but never + below the provisional floor, because a static frame has zero motion and a + zero threshold would flag floating-point dust. + + Being below this threshold means only that no screening was triggered. It + does not mean the residual was explained by motion -- that stronger reading + is reserved for residuals within observed_scale_m itself. + """ + if observed_scale_m is None or not math.isfinite(observed_scale_m): + return COMPARISON_SCREENING_M + return max(float(observed_scale_m), COMPARISON_SCREENING_M) + + +# -------------------------------------------------------------------------- +# association +# -------------------------------------------------------------------------- + +def candidate_frame_indices(frames, index: int) -> list: + """Scans that could have supplied a point to the published frame. + + The full-cloud path drains a cross-scan queue, so a published frame may + contain points whose original scan is not the one nearest in time. Every + plausible scan must be searched for competing returns -- searching only the + nearest frame can hide a competitor and manufacture a false `heuristic_nearest`. + """ + lo = max(0, index - CANDIDATE_FRAME_RADIUS) + hi = min(len(frames), index + CANDIDATE_FRAME_RADIUS + 1) + return list(range(lo, hi)) + + +def estimate_scan_window_ns(frames) -> int: + """How far back a point in a published frame can have been sampled. + + One scan duration plus one scan spacing: the queue can hold a full previous + scan, and the frame header sits at that scan's end. Using only the spacing + would exclude every point of the previous scan, which is exactly the case + the cross-scan search exists for. + """ + if not frames: + return 0 + duration = max((f["duration_ns"] for f in frames), default=0) + if len(frames) < 2: + return duration + bases = np.array([f["timebase_ns"] for f in frames], dtype=np.int64) + gaps = np.abs(np.diff(bases)) + gaps = gaps[gaps > 0] + spacing = int(np.median(gaps)) if len(gaps) else 0 + return duration + spacing + + +def candidate_time_window_ns(published_stamp_ns: int, scan_window_ns: int, + time_tolerance_s: float) -> tuple: + """The instants that can physically belong to one published frame. + + One-sided and bounded: a point cannot be sampled after the frame header, and + can be at most a scan duration plus a scan spacing earlier (queued points + that arrived late). A future scan is never admissible. + """ + tolerance_ns = int(round(time_tolerance_s * 1e9)) + published = int(published_stamp_ns) + return (published - max(int(scan_window_ns), 0) - tolerance_ns, + published + tolerance_ns) + + +def candidate_times_ns(frames, indices, curvature_ms: float, + published_stamp_ns: int, scan_window_ns: int, + time_tolerance_s: float) -> list: + """Every instant a world point could have been sampled at. + + curvature is the offset from the *original scan's* base time, and the + original scan is not identified by the published frame. Each candidate scan + therefore contributes its own instant, typically one scan period apart. + Returning a set, rather than picking the most convenient one, keeps the + unresolved assumption visible. + """ + curvature_ns = int(round(float(curvature_ms) * 1e6)) + earliest, latest = candidate_time_window_ns( + published_stamp_ns, scan_window_ns, time_tolerance_s) + out = [] + for i in indices: + candidate = int(frames[i]["timebase_ns"]) + curvature_ns + if earliest <= candidate <= latest: + out.append(candidate) + return sorted(set(out)) + + +def association_pool(frames, indices) -> dict: + """Merge the raw shell of every candidate scan into one searchable pool. + + Searching only frames[index] was a defect: a competitor point living in a + neighbouring scan never entered the comparison, so a distant runner-up could + be missed and a false nearest reported. + """ + times, points, outside, owners, labels = [], [], [], [], [] + for i in indices: + frame = frames[i] + count = len(frame["times_ns"]) + if count == 0: + continue + times.append(frame["times_ns"]) + points.append(frame["points"]) + outside.append(frame["outside"]) + labels.append(frame["labels"]) + owners.append(np.full(count, i, dtype=np.int64)) + if not times: + return { + "times": np.zeros(0, dtype=np.int64), + "points": np.zeros((0, 3)), "outside": np.zeros(0, dtype=bool), + "labels": np.zeros(0, dtype=object), + "owner": np.zeros(0, dtype=np.int64), + } + return { + "times": np.concatenate(times), + "points": np.vstack(points), + "outside": np.concatenate(outside), + "labels": np.concatenate(labels), + "owner": np.concatenate(owners), + } + + +def resolve_association(candidate_times, point_lidar, pool, time_tol_s, + xyz_tol, tie_margin=DEFAULT_ASSOC_TIE_MARGIN) -> tuple: + """Single-assumption association; delegates to the multi-assumption form. + + The position is broadcast across every candidate time on purpose: with one + position and several instants, zip() would silently evaluate only the first + instant and drop the rest. + """ + point = np.asarray(point_lidar, dtype=np.float64).reshape(3) + times = list(candidate_times) + return resolve_association_multi(times, [point] * len(times), pool, + time_tol_s, xyz_tol, tie_margin) + + +def resolve_association_multi(option_times, option_points, pool, time_tol_s, + xyz_tol, + tie_margin=DEFAULT_ASSOC_TIE_MARGIN) -> tuple: + """Rank raw returns while keeping each assumption's own candidate. + + Every admissible assumption searches its own instant and reports at most one + raw return. The per-assumption residuals are kept separately and summarised + as a RANGE: + + residual_min the most favourable admissible reading + residual_max the least favourable one + + A large residual_max must NOT be used to reject the reading that produced a + small residual_min: that would discard the best admissible account of the + observation. Two assumptions with residuals of 1 mm and 50 mm do not + contradict each other -- the 50 mm one simply says that reading fits worse. + + Symmetrically, claiming that the residual exceeds a threshold requires + residual_MIN to exceed it, i.e. every admissible reading fails. That is the + only form of the claim the data can support. + + Quality: + heuristic_nearest one raw return is decisively nearer than the runner-up + ambiguous several are similarly near + unmatched no assumption reached any raw return + + 'heuristic_nearest' ranks candidates by distance. It does not confirm that + the raw and world points are the same measurement. + """ + time_tol_ns = int(round(time_tol_s * 1e9)) + times = pool["times"] + points = pool["points"] + per_assumption_best = [] # each assumption's nearest admissible return + all_hits = {} # every raw index reached, with its best distance + + for candidate, position in zip(option_times, option_points): + position = np.asarray(position, dtype=np.float64).reshape(3) + best = None + if np.isfinite(position).all(): + window = np.abs(times - int(candidate)) <= time_tol_ns + if window.any(): + inside = np.where(window)[0] + distance = np.linalg.norm(points[inside] - position, axis=1) + for local, value in enumerate(distance): + if float(value) <= xyz_tol: + index = int(inside[local]) + all_hits[index] = min(float(value), + all_hits.get(index, math.inf)) + if best is None or value < best[1]: + best = (index, float(value)) + per_assumption_best.append(best) + + reached = [item for item in per_assumption_best if item is not None] + # Two different counts matter: how many assumptions reached something, and + # how many distinct raw returns were reached at all. + diagnostics = { + "assumption_count": len(option_times), + "assumptions_reaching_a_candidate": len(reached), + "candidate_scans": int(len(np.unique(pool["owner"]))) if len(pool["owner"]) else 0, + "hits": len(all_hits), + "nearest_dist": math.nan, "second_dist": math.nan, "margin": math.nan, + "residual_min": math.nan, "residual_max": math.nan, + } + if not reached: + return "unmatched", None, diagnostics + + # Per-assumption residuals: each assumption is summarised by its own best + # account, and the pair is described by the range. Never by the worst alone. + distances = [distance for _, distance in reached] + diagnostics["residual_min"] = float(min(distances)) + diagnostics["residual_max"] = float(max(distances)) + + ordered = sorted(all_hits.items(), key=lambda item: item[1]) + nearest_index, nearest_distance = ordered[0] + diagnostics["nearest_dist"] = nearest_distance + if len(ordered) == 1: + diagnostics["margin"] = math.inf + return "heuristic_nearest", nearest_index, diagnostics + + diagnostics["second_dist"] = ordered[1][1] + diagnostics["margin"] = ordered[1][1] - nearest_distance + if ordered[1][1] - nearest_distance >= tie_margin: + return "heuristic_nearest", nearest_index, diagnostics + return "ambiguous", None, diagnostics + + +def candidate_pose_options(pose_times, pose_valid, frame_bases, offset_ns, + indices, pose_time_tol_s, published_stamp_ns, + scan_window_ns) -> list: + """One pose resolution per admissible sampling assumption. + + The sampling instant is a set, not a value. Picking the assumption whose + odometry happens to be closest would turn a guess into a fact, and would + systematically prefer the time that makes the residual look smallest. Every + assumption is resolved and returned; nothing is collapsed, and no agreement + between assumptions is required. + + An assumption is admissible only when its instant lies inside the published + frame's physical time window. Enforcing that here -- not only when listing + candidate times -- is what keeps future or out-of-window scans out of the + enumeration. + + Each option is a dict: + frame_index, time_ns, pose_index (-1 where none), dt_s, + usable, in_window, pose_valid + """ + options = [] + if len(offset_ns) == 0 or not indices or len(pose_times) == 0: + return options + + earliest, latest = candidate_time_window_ns( + published_stamp_ns, scan_window_ns, 0.0) + last = len(pose_times) - 1 + for frame_index in indices: + candidate = np.int64(frame_bases[frame_index]) + offset_ns + in_window = (candidate >= earliest) & (candidate <= latest) + upper = np.clip(np.searchsorted(pose_times, candidate), 0, last) + lower = np.clip(upper - 1, 0, last) + distance_upper = np.abs(pose_times[upper] - candidate) + distance_lower = np.abs(pose_times[lower] - candidate) + take_lower = distance_lower < distance_upper + pose_index = np.where(take_lower, lower, upper) + distance = np.where(take_lower, distance_lower, distance_upper) + dt = distance / 1e9 + valid = pose_valid[pose_index] + usable = valid & in_window & (dt <= pose_time_tol_s) + options.append({ + "frame_index": int(frame_index), + "time_ns": candidate, + # -1 whenever the assumption cannot be used, so a caller that + # forgets to test `usable` still cannot index a wrong pose. + "pose_index": np.where(usable, pose_index, -1), + "dt_s": dt, + "in_window": in_window, + "pose_valid": valid, + "usable": usable, + }) + return options + + +# -------------------------------------------------------------------------- +# bag access +# -------------------------------------------------------------------------- + +def read_metadata(bag_dir: Path) -> dict: + """Parse metadata.yaml: storage kind, shard list, topic type map.""" + bag_dir = Path(bag_dir) + if not bag_dir.exists(): + raise PathProblem(f"bag directory not found: {bag_dir}") + if bag_dir.is_file(): + if bag_dir.suffix == ".db3": + return { + "storage_identifier": "sqlite3", + "files": [bag_dir.parent / bag_dir.name], + "topics": {}, "metadata_present": False, + "shard_note": "single .db3 passed directly; topic types read from sqlite", + } + raise PathProblem(f"--bag expects a directory, got file: {bag_dir}") + + metadata = bag_dir / "metadata.yaml" + if not metadata.is_file(): + raise PathProblem(f"metadata.yaml not found in {bag_dir}") + + try: + import yaml + except ImportError as exc: # pragma: no cover + raise PathProblem(f"PyYAML unavailable: {exc}") from exc + try: + doc = yaml.safe_load(metadata.read_text(encoding="utf-8")) + except Exception as exc: + raise BagProblem(f"cannot parse {metadata}: {exc}") from exc + + info = (doc or {}).get("rosbag2_bagfile_information") + if not isinstance(info, dict): + raise BagProblem(f"{metadata} has no rosbag2_bagfile_information") + + storage = info.get("storage_identifier", "") + relative = info.get("relative_file_paths") or [ + entry.get("path") for entry in info.get("files", []) if entry.get("path")] + if not relative: + raise BagProblem(f"{metadata} lists no shard files") + files = [bag_dir / name for name in relative] + missing = [str(f) for f in files if not f.is_file()] + if missing: + raise BagProblem(f"shard files listed in metadata are absent: {missing}") + + topics = {} + for entry in info.get("topics_with_message_count", []) or []: + meta = entry.get("topic_metadata", {}) + name, kind = meta.get("name"), meta.get("type") + if name and kind: + topics[name] = kind + + return { + "storage_identifier": storage, + "files": files, + "topics": topics, + "metadata_present": True, + "version": info.get("version"), + "duration_ns": info.get("duration", {}).get("nanoseconds") + if isinstance(info.get("duration"), dict) else None, + } + + +def _open_shard(path: Path): + if not Path(path).is_file(): + raise BagProblem(f"shard not found: {path}") + try: + conn = sqlite3.connect(f"file:{Path(path).resolve()}?mode=ro", uri=True) + conn.execute("SELECT count(*) FROM sqlite_master").fetchone() + except sqlite3.DatabaseError as exc: + raise BagProblem(f"cannot open {path} as sqlite: {exc}") from exc + return conn + + +def _topic_ids(conn, path: Path) -> dict: + try: + rows = conn.execute("SELECT id, name, type FROM topics").fetchall() + except sqlite3.DatabaseError as exc: + raise BagProblem(f"{path} is not a rosbag2 sqlite shard: {exc}") from exc + return {name: (tid, kind) for tid, name, kind in rows} + + +def _load_ros_bindings(): + try: + from rclpy.serialization import deserialize_message # noqa: WPS433 + from rosidl_runtime_py.utilities import get_message # noqa: WPS433 + except ImportError as exc: + raise BagProblem( + "ROS 2 Python bindings unavailable " + f"({exc}); source /opt/ros/humble/setup.bash and install/setup.bash") + return deserialize_message, get_message + + +def _stamp_ns(stamp) -> int: + return int(stamp.sec) * 1_000_000_000 + int(stamp.nanosec) + + +_PC2_DTYPES = { + 1: np.int8, 2: np.uint8, 3: np.int16, 4: np.uint16, + 5: np.int32, 6: np.uint32, 7: np.float32, 8: np.float64, +} + + +def cloud_fields(msg) -> dict: + """Extract named float columns from a PointCloud2 without read_points(). + + read_points() returns a structured array whose dtype varies with the + message; indexing it column-wise is fragile. Reading the raw buffer with + explicit field offsets keeps the arithmetic predictable and avoids one + Python object per point. + """ + count = int(msg.width) * int(msg.height) + if count == 0 or msg.point_step == 0: + return {} + buffer = np.frombuffer(msg.data, dtype=np.uint8) + if buffer.size < count * msg.point_step: + raise BagProblem( + f"PointCloud2 data is {buffer.size} bytes, expected " + f"{count * msg.point_step}") + view = buffer.reshape(count, msg.point_step) + order = ">" if getattr(msg, "is_bigendian", False) else "<" + + columns = {} + for field in msg.fields: + dtype = _PC2_DTYPES.get(int(field.datatype)) + if dtype is None: + continue + width = np.dtype(dtype).itemsize + if field.offset + width > msg.point_step: + continue + chunk = np.ascontiguousarray( + view[:, field.offset:field.offset + width]).copy() + columns[field.name] = chunk.view( + np.dtype(f"{order}{np.dtype(dtype).str[1:]}")).reshape(count) + return columns + + +# -------------------------------------------------------------------------- +# analysis +# -------------------------------------------------------------------------- + +def _collect_poses(paths, topic_type, deserialize_message, get_message): + times, positions, quaternions = [], [], [] + frames = 0 + invalid_quaternion = 0 + for path in paths: + conn = _open_shard(path) + try: + ids = _topic_ids(conn, path) + if TOPIC_POSE not in ids: + continue + tid, kind = ids[TOPIC_POSE] + for (blob,) in conn.execute( + "SELECT data FROM messages WHERE topic_id=? ORDER BY timestamp", (tid,)): + msg = deserialize_message(blob, get_message(kind or topic_type)) + pose = msg.pose.pose + frames += 1 + quaternion = [pose.orientation.x, pose.orientation.y, + pose.orientation.z, pose.orientation.w] + try: + rotation_from_quaternion(quaternion) + except ValueError: + invalid_quaternion += 1 + continue + if not all(math.isfinite(v) for v in + (pose.position.x, pose.position.y, pose.position.z)): + continue + times.append(_stamp_ns(msg.header.stamp)) + positions.append([pose.position.x, pose.position.y, pose.position.z]) + quaternions.append(quaternion) + finally: + conn.close() + order = np.argsort(np.asarray(times, dtype=np.int64), kind="stable") + return ( + np.asarray(times, dtype=np.int64)[order], + np.asarray(positions, dtype=np.float64).reshape((-1, 3))[order], + np.asarray(quaternions, dtype=np.float64).reshape((-1, 4))[order], + {"messages": frames, "invalid_quaternion_skipped": invalid_quaternion}, + ) + + +def _scan_raw(paths, geometry, deserialize_message, get_message, topic_type, + shell_margin): + """First pass: classify raw points in the optical frame, keep a shell. + + Only points at or near the envelope are retained. A whole bag of + full-resolution scans does not fit in memory, and the outside/boundary + points are the only ones this diagnostic needs to associate later. + """ + cls = get_message(topic_type) + frames = [] + total_points = 0 + invalid_points = 0 + counts = {"inside": 0, "boundary": 0, "outside": 0} + roi_counts = {"points": 0, "beyond_solid_envelope": 0, + "within_guard_band": 0, "beyond_guard_band": 0} + for path in paths: + conn = _open_shard(path) + try: + ids = _topic_ids(conn, path) + if TOPIC_RAW not in ids: + continue + tid, kind = ids[TOPIC_RAW] + for (blob,) in conn.execute( + "SELECT data FROM messages WHERE topic_id=? ORDER BY timestamp", (tid,)): + msg = deserialize_message(blob, get_message(kind or topic_type)) + timebase = int(msg.timebase) if msg.timebase else _stamp_ns(msg.header.stamp) + if not msg.points: + continue + xyz = np.array([[p.x, p.y, p.z] for p in msg.points], dtype=np.float64) + offsets = np.array([int(p.offset_time) for p in msg.points], dtype=np.int64) + finite = np.isfinite(xyz).all(axis=1) + invalid_points += int((~finite).sum()) + if not finite.any(): + continue + xyz, offsets = xyz[finite], offsets[finite] + + classified = classify_envelope(xyz, geometry) + counts["inside"] += int(classified["inside"].sum()) + counts["boundary"] += int(classified["boundary"].sum()) + counts["outside"] += int(classified["outside"].sum()) + total_points += len(xyz) + + # Whole-scene counts are dominated by walls and steps, which are + # outside any 0.81x0.80 m box. Only the body ROI is evidence, and + # it is split into "beyond the solid envelope" (which includes the + # 2 cm guard band) and "beyond the guard band as well". + roi = classified["distance_to_box"] <= BODY_ROI_MARGIN_M + roi_counts["points"] += int(roi.sum()) + roi_counts["beyond_solid_envelope"] += int( + (roi & (classified["boundary"] | classified["outside"])).sum()) + roi_counts["within_guard_band"] += int( + (roi & classified["boundary"]).sum()) + roi_counts["beyond_guard_band"] += int( + (roi & classified["outside"]).sum()) + + keep = body_shell_mask(classified, inner_margin=shell_margin) + duration = int(offsets.max()) if len(offsets) else 0 + labels = envelope_label(classified) + if not keep.any(): + frames.append({ + "timebase_ns": timebase, + "times_ns": np.zeros(0, dtype=np.int64), + "points": np.zeros((0, 3)), + "inside": np.zeros(0, dtype=bool), + "boundary": np.zeros(0, dtype=bool), + "outside": np.zeros(0, dtype=bool), + "labels": np.zeros(0, dtype=object), + "excess": np.zeros(0), + "axis": np.zeros(0, dtype=int), + "positive": np.zeros(0, dtype=bool), + "distance_to_box": np.zeros(0), + "duration_ns": duration, + }) + continue + + times = np.array( + [point_time_ns(timebase, off) for off in offsets[keep]], + dtype=np.int64) + frames.append({ + "timebase_ns": timebase, + "times_ns": times, + "points": xyz[keep], + "inside": classified["inside"][keep], + "boundary": classified["boundary"][keep], + "outside": classified["outside"][keep], + "labels": labels[keep], + "excess": classified["excess"][keep], + "axis": classified["axis"][keep], + "positive": classified["positive"][keep], + "distance_to_box": classified["distance_to_box"][keep], + "duration_ns": duration, + }) + finally: + conn.close() + return frames, { + "scans": len(frames), "points": total_points, + "invalid_points_skipped": invalid_points, + "raw_classified": counts, + "raw_body_roi": {**roi_counts, "roi_margin_m": BODY_ROI_MARGIN_M}, + } + + +def _decide(quality, residual_min, observed_scale, threshold, world_outside, + evidence_complete) -> str: + """Decide what a single associated pair supports, in this order. + + Two deliberate omissions: + + * classification_changed is not a parameter here. A raw point and its + inverse-transformed counterpart landing on different sides of the envelope + is an observation, not a cause: a millimetre near a face flips it, and the + inverse transform's unknown error can produce that flip just as easily as + a real defect. It is recorded in the CSV only. + + * the anomaly branch tests residual_MIN, not residual_max. Claiming that the + residual exceeds a threshold means every admissible reading fails. Using a + large worst-case residual while a favourable reading exists would discard + the best account of the observation. + + An anomaly is still only a candidate: observed_motion_scale does not bound + the unpublished anchor prediction error, so no cause follows from it. + """ + if quality == "ambiguous": + return "inconclusive_ambiguous" + if quality == "unmatched": + return "world_outside_no_raw_counterpart" if world_outside \ + else "inconclusive_unmatched" + if not evidence_complete: + return "inconclusive_incomplete_evidence" + if residual_min is None or not math.isfinite(residual_min): + return "inconclusive_unmatched" + if observed_scale is None or not math.isfinite(observed_scale): + return "inconclusive_no_observed_motion_scale" + # Only a residual inside the frame's own observed motion is *explained* by + # motion. Between that and the screening threshold nothing was triggered, + # which is a weaker statement and must not borrow the stronger wording. + if residual_min <= observed_scale: + return "inconclusive_within_observed_motion" + if residual_min <= threshold: + return "inconclusive_below_screening_threshold" + return "anomaly_candidate_unattributed" + + +def _reason(decision, diagnostics) -> str: + base = { + "inconclusive_ambiguous": ( + "candidates similarly close; the nearest is not separable"), + "inconclusive_unmatched": "no raw point within tolerance", + "inconclusive_incomplete_evidence": ( + "at least one admissible sampling assumption had no usable pose, so " + "the candidate set was not fully evaluated"), + "inconclusive_no_observed_motion_scale": ( + "observed motion scale could not be computed"), + "inconclusive_within_observed_motion": ( + "the most favourable admissible reading is no larger than the motion " + "observed in this frame"), + "inconclusive_below_screening_threshold": ( + "the most favourable admissible reading exceeds the observed motion " + "but stays below the provisional screening threshold; no screen was " + "triggered, and the residual is NOT explained"), + "anomaly_candidate_unattributed": ( + "every admissible reading exceeds the observed motion scale, but " + "that scale does not bound the unpublished anchor prediction error; " + "cause not established"), + "world_outside_no_raw_counterpart": ( + "world point is outside but no raw return matches it in time and " + "space; it may be a compensation artefact or an unrecorded raw point"), + }.get(decision, decision) + return base + + +def _conclude(report) -> tuple: + """Return (conclusion, reason) without overstating the evidence. + + The basis is the body-region ROI, not the whole scene: walls, steps and + furniture are trivially outside a 0.81x0.80 m box, so a whole-scene count + would make "outside the envelope" meaningless. + + 'undetermined' is a first-class outcome, and so is + 'raw_outside_measured_unlinked': it states that measured raw coordinates lie + outside the configured envelope near the bodywork, and nothing more. It does + not establish body protrusion, a real obstacle, or a compensation error. + """ + stats = report["statistics"] + decisions = stats.get("decisions", {}) + association = stats.get("association", {}) + roi = stats.get("raw_body_roi", {}) + beyond_solid = int(roi.get("beyond_solid_envelope", 0)) + beyond_band = int(roi.get("beyond_guard_band", 0)) + + nearest = association.get("heuristic_nearest", 0) + ambiguous = association.get("ambiguous", 0) + anomalies = decisions.get("anomaly_candidate_unattributed", 0) + within = decisions.get("inconclusive_within_observed_motion", 0) + below_screen = decisions.get("inconclusive_below_screening_threshold", 0) + incomplete = decisions.get("inconclusive_incomplete_evidence", 0) + no_counterpart = decisions.get("world_outside_no_raw_counterpart", 0) + + if beyond_solid == 0: + return "no_raw_outside_returns", ( + "no raw return inside the body diagnostic region lies outside the " + "measured envelope, so there is no measured out-of-envelope return " + "to explain") + + if nearest == 0: + return "raw_outside_measured_unlinked", ( + f"{beyond_solid} raw return(s) inside the body diagnostic region lie " + f"outside the measured envelope ({beyond_band} of them beyond the " + "2 cm guard band as well). This is a statement about the measured " + "raw coordinates relative to the configured envelope, with no " + "reliable association to the world cloud established. It does not " + "establish body protrusion, a real obstacle, or a compensation " + "error") + + if anomalies > 0: + return "anomaly_candidates_unattributed", ( + f"{anomalies} pair(s) leave every admissible reading larger than the " + f"motion observed in their frame ({within} did not). That scale does " + "not bound the unpublished anchor prediction error, so no cause is " + "attributed; this is a lead to investigate, not a finding") + + if incomplete > 0 and within == 0 and below_screen == 0: + return "undetermined", ( + f"{incomplete} pair(s) could not be fully evaluated because an " + "admissible sampling assumption had no usable pose; the evidence is " + "incomplete rather than negative") + + if within > 0 or below_screen > 0: + return "undetermined", ( + f"{within} pair(s) stay within the motion observed in their frame and " + f"{below_screen} exceed that motion but fall below the provisional " + "screening threshold, so no screen was triggered for them. Neither " + "outcome is evidence about the cause: the inverse transform cannot be " + "separated from the anchor error " + f"(ambiguous candidates: {ambiguous}, no counterpart: {no_counterpart})") + + return "undetermined", ( + f"body-region outside returns={beyond_solid}, heuristic nearest={nearest}, " + f"ambiguous={ambiguous}, no counterpart={no_counterpart}; " + "not enough separable evidence to attribute a cause") + + +def _limits(report) -> list: + limits = [ + "observed_motion_scale describes the motion spanned by the recorded " + "odometry in a frame, measured and reported without any floor. It is NOT " + "an upper bound on the error of the unpublished anchor used by Point-LIO, " + "so a residual above it is only an anomaly candidate and never a " + "confirmed transform defect.", + "The comparison threshold is max(observed motion, provisional screening " + "floor). It is a screening level only: NOT an acceptance tolerance, and " + "NOT a verified noise bound. A raw return and its world-frame copy come " + "from the same measurement, so sensor noise cancels between them; " + "repeated-measurement spread enters only when two different scans are " + "associated. A residual below the threshold was not screened, which is " + "weaker than being explained by motion.", + "World points whose residual never triggered screening are still written " + "to the CSV with their excess distance and classification, and the " + "summary reports the excess distribution regardless of the threshold, so " + "small excursions stay visible and thresholds can be compared later on " + "the same bag.", + "Each admissible sampling assumption is evaluated separately. The " + "reported residual is a range: residual_min is the most favourable " + "reading, residual_max the least favourable. A large residual_max does " + "not invalidate a small residual_min.", + "heuristic_nearest ranks a candidate by distance among the scanned " + "returns. It does not establish that the raw point and the world point " + "came from the same measurement; nearest distance, runner-up distance " + "and their gap are reported for that judgement.", + "The inverse transform substitutes the recorded /aft_mapped_to_init " + "pose for Point-LIO's unpublished anchor prediction, so it is an " + "approximation with unknown error, not an exact inverse.", + "A published /cloud_registered_full frame may contain points from more " + "than one original Livox scan (cross-scan queue). Per-point stamps are " + "therefore a candidate set, enumerated without preference.", + "curvature is the per-point offset in milliseconds. It brackets the " + "sampling instant but does not identify which raw return produced a " + "world point.", + "A classification change across the envelope is recorded as an " + "observation. It is not used to select a verdict, because a millimetre " + "near a face is enough to flip it.", + "Raw-frame classification involves no transform at all, so it is immune " + "to the inverse-transform error. On a static bag the same bodywork is " + "re-measured every scan, so cross-scan association is expected to be " + "largely ambiguous; that limits linking, not the raw measurement.", + "raw_body_roi restricts 'outside the envelope' to returns within " + "BODY_ROI_MARGIN_M of the bodywork. Whole-scene counts include walls and " + "steps and are reported for completeness only, never as evidence.", + "This tool only reports geometry. It does not decide whether any crop " + "should be widened, and it does not modify the running filter.", + ] + if report["geometry"]["baseline_differences"]: + limits.append( + "The config differs from the documented baseline " + f"({len(report['geometry']['baseline_differences'])} key(s)); " + "numbers above use the config, not the document.") + return limits + + +def _percentiles(values) -> dict: + if not values: + return {"count": 0} + arr = np.asarray(values, dtype=np.float64) + return { + "count": int(arr.size), + "p50": float(np.quantile(arr, 0.5)), + "p95": float(np.quantile(arr, 0.95)), + "max": float(arr.max()), + } + + +def analyze_bag(bag_dir: Path, geometry: dict) -> dict: + """Read the bag and produce the full report dict. + + Streaming on purpose: scans are classified one at a time and only a thin + shell near the envelope is retained, so memory stays bounded by the number + of scans rather than by the number of points. + """ + bag_dir = Path(bag_dir) + meta = read_metadata(bag_dir) + if meta["storage_identifier"] not in ("sqlite3", ""): + raise BagProblem( + f"unsupported storage '{meta['storage_identifier']}' in {bag_dir}; " + "only rosbag2 sqlite3 is supported") + + types = dict(meta["topics"]) + # A shard passed directly has no metadata, so read the type from sqlite. + # This needs only sqlite, not the ROS Python bindings. + if not types: + conn = _open_shard(meta["files"][0]) + try: + types = {name: kind for name, (_, kind) in + _topic_ids(conn, meta["files"][0]).items()} + finally: + conn.close() + + missing_topics = [t for t in REQUIRED_TOPICS if t not in types] + report = { + "schema_version": SCHEMA_VERSION, + "tool": {"name": "analyze_self_boundary", "version": TOOL_VERSION}, + "evidence_grade": { + "verdicts": ["undetermined", "no_raw_outside_returns", + "raw_outside_measured_unlinked", + "anomaly_candidates_unattributed"], + "confirmed_causes": [], + "note": "this tool reports observations; it does not confirm causes. " + "raw_outside_measured_unlinked is a direct measurement of " + "the raw cloud (no transform applied) with the cause left " + "open. See limits for what observed_motion_scale and " + "heuristic_nearest do and do not support.", + }, + "geometry": { + "config_path": geometry["config_path"], + "envelope_optical_frame": { + "x_front": geometry["self_front"], "x_rear": geometry["self_rear"], + "y_left": geometry["self_left"], "y_right": geometry["self_right"], + "z_min": geometry["self_z_min"], "z_max": geometry["self_z_max"], + }, + "boundary_guard": geometry["boundary_guard"], + "lidar_to_imu_translation": geometry["lidar_to_imu_translation"].tolist(), + "baseline_differences": geometry["baseline_differences"], + "note": "guard is lateral only, matching core.classify_self_returns", + }, + "bag": { + "path": str(bag_dir.resolve()), + "storage": meta["storage_identifier"], + "shards": [str(Path(f).name) for f in meta["files"]], + "topics": types, + "metadata_present": meta["metadata_present"], + }, + "time_tolerances": { + "pose_match_s": DEFAULT_POSE_TIME_TOL, + "pose_gap_warn_s": DEFAULT_POSE_GAP_WARN, + "pose_stale_s": DEFAULT_POSE_STALE, + "association_time_s": DEFAULT_ASSOC_TIME_TOL, + "association_xyz_m": DEFAULT_ASSOC_XYZ_TOL, + "association_tie_margin_m": DEFAULT_ASSOC_TIE_MARGIN, + "candidate_frame_radius": CANDIDATE_FRAME_RADIUS, + "comparison_screening_floor_m": COMPARISON_SCREENING_M, + "comparison_screening_note": ( + "provisional floor for residual screening only. NOT an " + "acceptance tolerance and NOT a verified noise bound; a raw " + "return and its world copy share the same measurement, so " + "sensor noise cancels between them. Reported separately from " + "the per-frame observed motion scale."), + }, + } + + if missing_topics: + report["status"] = "incomplete" + report["missing_topics"] = missing_topics + report["conclusion"] = "undetermined" + report["conclusion_reason"] = ( + "required topic(s) absent: " + ", ".join(missing_topics) + + ". Without the raw Livox topic the raw-frame out-of-envelope " + "returns cannot be separated from world-cloud compensation " + "residuals.") + report["limits"] = [ + "No raw classification was possible, so evidence class 'raw' is empty.", + "World-cloud points alone cannot distinguish a real out-of-envelope " + "return from a motion-compensation residual.", + ] + raise MissingTopic(report) + + # Only now are the ROS bindings required: up to this point everything was + # metadata and sqlite, which keeps the failure modes separable. + deserialize_message, get_message = _load_ros_bindings() + + # ---- poses ----------------------------------------------------------- + pose_times, pose_pos, pose_quat, pose_meta = _collect_poses( + meta["files"], types[TOPIC_POSE], deserialize_message, get_message) + if len(pose_times) == 0: + raise MissingTopic({**report, "status": "incomplete", + "missing_topics": [TOPIC_POSE], + "conclusion": "undetermined", + "conclusion_reason": f"{TOPIC_POSE} present but yielded no valid pose"}) + poses = PoseIndex(pose_times, pose_pos, pose_quat) + report["data_integrity"] = { + "pose_messages": pose_meta["messages"], + "usable_poses": len(poses), + "invalid_quaternion_skipped": pose_meta["invalid_quaternion_skipped"], + "pose_time_regressions": poses.regressions, + "pose_max_gap_s": poses.max_gap, + "pose_time_range_ns": [int(pose_times.min()), int(pose_times.max())], + } + + # ---- raw ------------------------------------------------------------- + frames, raw_meta = _scan_raw( + meta["files"], geometry, deserialize_message, get_message, + types[TOPIC_RAW], DEFAULT_SHELL_MARGIN) + if not frames: + raise MissingTopic({**report, "status": "incomplete", + "missing_topics": [TOPIC_RAW], + "conclusion": "undetermined", + "conclusion_reason": f"{TOPIC_RAW} present but contained no frames"}) + frame_bases = np.array([f["timebase_ns"] for f in frames], dtype=np.int64) + report["data_integrity"].update({ + "raw_scans": raw_meta["scans"], + "raw_points": raw_meta["points"], + "raw_invalid_points_skipped": raw_meta["invalid_points_skipped"], + "raw_scan_time_range_ns": [int(frame_bases.min()), int(frame_bases.max())], + }) + report["statistics"] = { + "raw_whole_scene_classification": raw_meta["raw_classified"], + "raw_whole_scene_note": ( + "classified directly in the optical frame, no transform applied; " + "this count includes walls, steps and furniture and is NOT the " + "diagnostic basis"), + "raw_body_roi": raw_meta["raw_body_roi"], + "raw_body_roi_note": ( + "only returns within BODY_ROI_MARGIN_M of the bodywork; " + "beyond_solid_envelope includes the 2 cm guard band, " + "beyond_guard_band is the stricter subset"), + # kept for backwards compatibility with earlier reports/tests + "raw_frame_classification": raw_meta["raw_classified"], + } + + # ---- world ----------------------------------------------------------- + world = { + "scans": 0, "points": 0, + "out_of_envelope": 0, "in_boundary_band": 0, "inside": 0, + "pose_undetermined": 0, "classification_samples": 0, + "association": {"heuristic_nearest": 0, "ambiguous": 0, "unmatched": 0}, + "decisions": {}, + "pose_dt_s": [], "residual_m": [], "residual_max_m": [], "scale_m": [], + "threshold_m": [], "world_excess_m": [], + "nearest_margin_m": [], "candidate_scans": [], "candidate_times": [], + "classification_changed": 0, "incomplete_evidence": 0, + "classification_inconsistent": 0, + } + csv_rows = [] + samples = [] + translation = geometry["lidar_to_imu_translation"] + curvature_present = True + pool_cache = {} + scan_window_ns = estimate_scan_window_ns(frames) + + for path in meta["files"]: + conn = _open_shard(path) + try: + ids = _topic_ids(conn, path) + if TOPIC_WORLD not in ids: + continue + tid, kind = ids[TOPIC_WORLD] + cls = get_message(kind or types[TOPIC_WORLD]) + for (blob,) in conn.execute( + "SELECT data FROM messages WHERE topic_id=? ORDER BY timestamp", (tid,)): + msg = deserialize_message(blob, cls) + columns = cloud_fields(msg) + if not all(k in columns for k in ("x", "y", "z")): + raise BagProblem( + f"{TOPIC_WORLD} lacks x/y/z fields; got {sorted(columns)}") + xyz_all = np.column_stack( + [columns["x"], columns["y"], columns["z"]]).astype(np.float64) + finite = np.isfinite(xyz_all).all(axis=1) + if not finite.any(): + continue + xyz = xyz_all[finite] + world["scans"] += 1 + world["points"] += len(xyz) + + stamp_ns = _stamp_ns(msg.header.stamp) + index = int(np.argmin(np.abs(frame_bases - stamp_ns))) + indices = candidate_frame_indices(frames, index) + + if "curvature" in columns: + curvature = columns["curvature"][finite].astype(np.float64) + else: + curvature_present = False + curvature = np.zeros(len(xyz), dtype=np.float64) + offset_ns = np.rint(curvature * 1e6).astype(np.int64) + + # Enumerate every admissible sampling assumption. No single + # assumption is preferred; each yields its own pose and its own + # optical-frame position for the same world point. + options = candidate_pose_options( + pose_times, poses.valid, frame_bases, offset_ns, indices, + DEFAULT_POSE_TIME_TOL, stamp_ns, scan_window_ns) + usable_any = np.zeros(len(xyz), dtype=bool) + for option in options: + usable_any |= option["usable"] + world["pose_undetermined"] += int((~usable_any).sum()) + if not usable_any.any(): + continue + + # Invert under every assumption and take the union of the + # classifications: a point counts as interesting if it is at or + # beyond the envelope under ANY admissible reading. Erring + # towards keeping evidence, never towards dropping it. + local_by_option = [] + outside_any = np.zeros(len(xyz), dtype=bool) + boundary_any = np.zeros(len(xyz), dtype=bool) + first_position = np.full_like(xyz, np.nan) + excess_best = np.full(len(xyz), -np.inf) + axis_best = np.zeros(len(xyz), dtype=int) + positive_best = np.zeros(len(xyz), dtype=bool) + distance_best = np.full(len(xyz), np.inf) + for option in options: + local = np.full_like(xyz, np.nan) + members_index = np.where(option["usable"])[0] + for pi in np.unique(option["pose_index"][members_index]): + if int(pi) < 0: + continue + members = members_index[ + option["pose_index"][members_index] == int(pi)] + rotation = rotation_from_quaternion(pose_quat[int(pi)]) + local[members] = (xyz[members] - pose_pos[int(pi)]) \ + @ rotation - translation + local_by_option.append(local) + if len(members_index) == 0: + continue + unseen = np.isnan(first_position[members_index, 0]) + first_position[members_index[unseen]] = \ + local[members_index[unseen]] + classified = classify_envelope(local[members_index], geometry) + outside_any[members_index] |= classified["outside"] + boundary_any[members_index] |= classified["boundary"] + world["classification_samples"] += int(len(members_index)) + + # Keep the largest excess seen under any assumption, with + # its direction. This is the conservative description of + # how far out the point could be. + better = classified["excess"] > excess_best[members_index] + rows = members_index[better] + excess_best[rows] = classified["excess"][better] + axis_best[rows] = classified["axis"][better] + positive_best[rows] = classified["positive"][better] + distance_best[rows] = classified["distance_to_box"][better] + + # Counted per point on the union, not per assumption: the same + # point outside under three readings is still one point. + world["out_of_envelope"] += int(outside_any.sum()) + world["in_boundary_band"] += int( + (boundary_any & ~outside_any).sum()) + world["inside"] += int((~outside_any & ~boundary_any).sum()) + + world_labels = np.full(len(xyz), "inside", dtype=object) + world_labels[boundary_any] = "boundary" + world_labels[outside_any] = "outside" + + lo_ns = int(frame_bases[index] - frames[index]["duration_ns"]) + hi_ns = int(frame_bases[index] + frames[index]["duration_ns"]) + window = np.where((pose_times >= lo_ns) & (pose_times <= hi_ns))[0] + if len(window) == 0: + window = np.array([int(np.argmin(np.abs(pose_times - stamp_ns)))]) + motion_scale = observed_motion_scale( + pose_pos[window], pose_quat[window], xyz) + threshold = comparison_threshold(motion_scale) + + # Same ROI rule as the raw side: a wall metres away is trivially + # outside a 0.81x0.80 m box and is not evidence about the body. + near_body = distance_best <= BODY_ROI_MARGIN_M + interesting = np.where((outside_any | boundary_any) & near_body)[0] + if len(interesting) == 0: + continue + + key = (indices[0], indices[-1]) + if key not in pool_cache: + pool_cache.clear() + pool_cache[key] = association_pool(frames, indices) + pool = pool_cache[key] + + for i in interesting: + option_times = [] + option_points = [] + valid_assumptions = 0 + invalid_assumptions = 0 + labels_seen = [] + excess_seen = [] + for slot, option in enumerate(options): + # A scan outside the frame's time window is not a + # candidate at all; it must not be counted as evidence + # that failed to resolve. + if not option["in_window"][i]: + continue + if not option["usable"][i]: + invalid_assumptions += 1 + continue + position = local_by_option[slot][i] + valid_assumptions += 1 + option_times.append(int(option["time_ns"][i])) + option_points.append(position) + single = classify_envelope(position.reshape(1, 3), geometry) + labels_seen.append(str(envelope_label(single)[0])) + excess_seen.append(float(single["excess"][0])) + + # Evidence is incomplete whenever an admissible assumption + # could not be evaluated: the candidate set was not fully + # searched, so no claim may be stronger than "inconclusive". + evidence_complete = (invalid_assumptions == 0 + and valid_assumptions > 0) + classification_consistent = len(set(labels_seen)) <= 1 + + quality, hit, diag = resolve_association_multi( + option_times, option_points, pool, + DEFAULT_ASSOC_TIME_TOL, DEFAULT_ASSOC_XYZ_TOL) + world["association"][quality] += 1 + world["pose_dt_s"].append( + float(max(option["dt_s"][i] for option in options))) + world["scale_m"].append(float(motion_scale)) + world["threshold_m"].append(float(threshold)) + world["world_excess_m"].append(float(excess_best[i])) + world["candidate_times"].append(len(option_times)) + if math.isfinite(diag["margin"]): + world["nearest_margin_m"].append(float(diag["margin"])) + world["candidate_scans"].append(diag["candidate_scans"]) + if not evidence_complete: + world["incomplete_evidence"] += 1 + if not classification_consistent: + world["classification_inconsistent"] += 1 + + raw_outside = None + residual_min = diag["residual_min"] + changed = False + if hit is not None: + raw_outside = bool(pool["outside"][hit]) + world["residual_m"].append(float(diag["residual_min"])) + world["residual_max_m"].append(float(diag["residual_max"])) + # A label change is a recorded observation only. It is + # never used to select the decision. + changed = str(pool["labels"][hit]) != str(world_labels[i]) + if changed: + world["classification_changed"] += 1 + + decision = _decide(quality=quality, residual_min=residual_min, + observed_scale=motion_scale, + threshold=threshold, + world_outside=bool(outside_any[i]), + evidence_complete=evidence_complete) + world["decisions"][decision] = \ + world["decisions"].get(decision, 0) + 1 + + times = option_times + span_ms = "" + if len(times) > 1: + span_ms = f"{(max(times) - min(times)) / 1e6:.6f}" + row = { + "source": "world", + "point_time_ns": "", + "candidate_time_count": str(len(option_times)), + "candidate_time_span_ms": span_ms, + "assumptions_valid": str(valid_assumptions), + "assumptions_invalid": str(invalid_assumptions), + "evidence_complete": "yes" if evidence_complete else "no", + "curvature_ms": f"{curvature[i]:.6f}", + "x_m": f"{first_position[i][0]:.6f}", + "y_m": f"{first_position[i][1]:.6f}", + "z_m": f"{first_position[i][2]:.6f}", + "outside_axis": _direction_label( + int(axis_best[i]), bool(positive_best[i])), + "excess_min_m": _fmt(min(excess_seen)) if excess_seen else "", + "excess_max_m": _fmt(max(excess_seen)) if excess_seen else "", + "classification_consistent": "yes" if classification_consistent else "no", + "distance_to_box_m": _fmt(distance_best[i]), + "match_quality": quality, + "residual_min_m": _fmt(diag["residual_min"]), + "residual_max_m": _fmt(diag["residual_max"]), + "nearest_dist_m": _fmt(diag["nearest_dist"]), + "second_dist_m": _fmt(diag["second_dist"]), + "nearest_margin_m": _fmt(diag["margin"]), + "candidate_scans": str(diag["candidate_scans"]), + "pose_dt_s": f"{float(max(option['dt_s'][i] for option in options)):.6f}", + "observed_motion_scale_m": f"{float(motion_scale):.6f}", + "comparison_threshold_m": f"{float(threshold):.6f}", + "classification_changed": "yes" if changed else "no", + "decision": decision, + "reason": _reason(decision, diag), + } + if len(csv_rows) < MAX_CSV_ROWS: + csv_rows.append(row) + elif len(samples) < MAX_SAMPLE_ROWS: + samples.append(row) + finally: + conn.close() + + # ---- raw boundary rows (evidence class 1) ---------------------------- + raw_rows = 0 + for frame in frames: + selected = np.where(frame["boundary"] | frame["outside"])[0] + if len(selected) == 0: + continue + for i in selected: + if len(csv_rows) >= MAX_CSV_ROWS: + break + csv_rows.append({ + "source": "raw", + "point_time_ns": str(int(frame["times_ns"][i])), + "candidate_time_count": "1", + "candidate_time_span_ms": "", + "curvature_ms": "", + "x_m": f"{frame['points'][i][0]:.6f}", + "y_m": f"{frame['points'][i][1]:.6f}", + "z_m": f"{frame['points'][i][2]:.6f}", + "outside_axis": _direction_label( + int(frame["axis"][i]), bool(frame["positive"][i])), + "outside_dist_m": f"{float(frame['excess'][i]):.6f}", + "distance_to_box_m": f"{float(frame['distance_to_box'][i]):.6f}", + "assumptions_valid": "", "assumptions_invalid": "", + "evidence_complete": "", + "match_quality": "n/a", + "excess_min_m": f"{float(frame['excess'][i]):.6f}", + "excess_max_m": f"{float(frame['excess'][i]):.6f}", + "classification_consistent": "", + "residual_min_m": "", "residual_max_m": "", + "nearest_dist_m": "", "second_dist_m": "", + "nearest_margin_m": "", "candidate_scans": "", + "pose_dt_s": "", "observed_motion_scale_m": "", + "comparison_threshold_m": "", + "classification_changed": "", + "decision": "raw_only_in_boundary_band" + if frame["boundary"][i] else "raw_outside_envelope", + "reason": "classified directly in the optical frame; no transform", + }) + raw_rows += 1 + + report["statistics"]["world_inverse_classification"] = { + "points": world["points"], "inside": world["inside"], + "in_boundary_band": world["in_boundary_band"], + "out_of_envelope": world["out_of_envelope"], + "curvature_field_present": curvature_present, + "note": "inverse transform uses the recorded pose at each point's own instant", + } + report["statistics"]["pose_assignment"] = { + "points_with_no_usable_assumption": world["pose_undetermined"], + "classification_samples": world["classification_samples"], + "pairs_with_incomplete_evidence": world["incomplete_evidence"], + "pairs_with_inconsistent_classification": world["classification_inconsistent"], + "note": "every admissible sampling assumption is enumerated separately " + "and none is preferred; no agreement between assumptions is " + "required. Evidence is marked incomplete when any admissible " + "assumption lacked a usable pose.", + } + report["statistics"]["association"] = { + **world["association"], + "note": "heuristic_nearest ranks by distance inside the candidate set; " + "it does not confirm same-source correspondence", + } + report["statistics"]["association_quality"] = { + "candidate_scans": _percentiles(world["candidate_scans"]), + "candidate_times": _percentiles(world["candidate_times"]), + "nearest_margin_m": _percentiles(world["nearest_margin_m"]), + } + report["statistics"]["decisions"] = world["decisions"] + report["statistics"]["classification_changed_pairs"] = \ + world["classification_changed"] + report["statistics"]["observation_note"] = ( + "classification_changed counts pairs that fall on different sides of " + "the envelope in the raw and inverse-transformed clouds. It is an " + "observation and is never used to select a decision.") + report["statistics"]["csv_rows"] = len(csv_rows) + report["statistics"]["raw_rows_written"] = raw_rows + + if world["pose_dt_s"]: + report["statistics"]["pose_dt_summary"] = _percentiles(world["pose_dt_s"]) + if world["residual_m"]: + report["statistics"]["residual_summary"] = { + "residual_min": _percentiles(world["residual_m"]), + "residual_max": _percentiles(world["residual_max_m"]), + "note": "residual_min is the most favourable admissible reading and " + "is the only one used to test the observed motion scale", + } + if world["scale_m"]: + # Reported apart on purpose: one is measured motion, the other is a + # provisional assumption. Merging them would hide which one decided. + report["statistics"]["observed_motion_scale_summary"] = { + **_percentiles(world["scale_m"]), + "note": "measured motion in the frame; no floor applied", + } + report["statistics"]["comparison_threshold_summary"] = { + **_percentiles(world["threshold_m"]), + "screening_floor_m": COMPARISON_SCREENING_M, + "note": "max(observed motion, provisional screening floor); a " + "residual below this was not screened, which is not the " + "same as being explained by motion", + } + if world["world_excess_m"]: + excess = np.asarray(world["world_excess_m"], dtype=np.float64) + report["statistics"]["world_excess_summary"] = { + "count": int(excess.size), + "p50_m": float(np.quantile(excess, 0.5)), + "p95_m": float(np.quantile(excess, 0.95)), + "max_m": float(excess.max()), + "count_over_5mm": int(np.sum(excess > 0.005)), + "count_over_10mm": int(np.sum(excess > 0.010)), + "count_over_13mm": int(np.sum(excess > 0.013)), + "count_over_20mm": int(np.sum(excess > 0.020)), + "note": "how far world points sit outside the envelope, independent " + "of the residual screening threshold; this keeps small " + "excursions visible when screening does not trigger", + } + + report["samples"] = samples or csv_rows[:MAX_SAMPLE_ROWS] + report["conclusion"], report["conclusion_reason"] = _conclude(report) + report["limits"] = _limits(report) + report["status"] = "complete" + return {**report, "_csv_rows": csv_rows} + + +def _fmt(value) -> str: + if value is None: + return "" + if isinstance(value, float) and not math.isfinite(value): + return "inf" if value > 0 else "-inf" + return f"{float(value):.6f}" + + +# -------------------------------------------------------------------------- +# output +# -------------------------------------------------------------------------- + +CSV_FIELDS = [ + "source", "point_time_ns", "candidate_time_count", "candidate_time_span_ms", + "assumptions_valid", "assumptions_invalid", "evidence_complete", + "curvature_ms", "x_m", "y_m", "z_m", + "outside_axis", "excess_min_m", "excess_max_m", + "classification_consistent", "distance_to_box_m", + "match_quality", "residual_min_m", "residual_max_m", + "nearest_dist_m", "second_dist_m", "nearest_margin_m", + "candidate_scans", "pose_dt_s", "observed_motion_scale_m", + "comparison_threshold_m", "classification_changed", "decision", "reason", +] + + +def write_report(report: dict, output_dir: Path) -> None: + """Write summary.json and boundary_points.csv. + + Callers must have already refused to overwrite; this function assumes the + directory is safe to write into. Existing files are never touched here. + """ + output_dir = Path(output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + rows = report.get("_csv_rows", []) + payload = {k: v for k, v in report.items() if not k.startswith("_")} + + summary_path = output_dir / "summary.json" + csv_path = output_dir / "boundary_points.csv" + for target in (summary_path, csv_path): + if target.exists(): + raise PathProblem( + f"refusing to overwrite existing {target}; " + "pass --overwrite or choose another --output") + + summary_path.write_text( + json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8") + with csv_path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=CSV_FIELDS) + writer.writeheader() + for row in rows: + writer.writerow({k: row.get(k, "") for k in CSV_FIELDS}) + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser( + description="Offline self-boundary diagnostic; read-only over a bag.") + parser.add_argument("--bag", type=Path, required=True, + help="bag directory containing metadata.yaml and shards") + parser.add_argument("--config", type=Path, required=True, + help="runtime config, e.g. config/flat_corridor.yaml") + parser.add_argument("--output", type=Path, required=True, + help="directory for summary.json and boundary_points.csv") + parser.add_argument("--overwrite", action="store_true", + help="allow replacing existing result files") + args = parser.parse_args(argv) + + # Refuse before doing any work: an existing result set is never replaced + # silently, whether the run ends complete or incomplete. + existing = [p for p in (args.output / "summary.json", + args.output / "boundary_points.csv") if p.exists()] + if existing and not args.overwrite: + print(f"[error] refusing to overwrite {existing[0]}; pass --overwrite", + file=sys.stderr) + return EXIT_MISSING + if args.overwrite: + for target in existing: + target.unlink() + + try: + geometry = load_geometry(args.config) + report = analyze_bag(args.bag, geometry) + except PathProblem as exc: + print(f"[error] {exc}", file=sys.stderr) + return EXIT_MISSING + except BagProblem as exc: + print(f"[error] {exc}", file=sys.stderr) + return EXIT_INCOMPATIBLE + except MissingTopic as exc: + partial = exc.args[0] if exc.args else {} + if not isinstance(partial, dict): + print(f"[error] {partial}", file=sys.stderr) + return EXIT_MISSING + print(f"[error] {partial.get('conclusion_reason')}", file=sys.stderr) + # A partial report is still written: the missing evidence is itself the + # finding, and the exit code stays 2 so automation cannot mistake it + # for a completed diagnosis. + try: + write_report(partial, args.output) + except (PathProblem, OSError) as write_error: + print(f"[error] {write_error}", file=sys.stderr) + return EXIT_MISSING + + try: + write_report(report, args.output) + except PathProblem as exc: + print(f"[error] {exc}", file=sys.stderr) + return EXIT_MISSING + except OSError as exc: + print(f"[error] cannot write results to {args.output}: {exc}", file=sys.stderr) + return EXIT_INCOMPATIBLE + + print(json.dumps({ + "status": report["status"], + "conclusion": report["conclusion"], + "reason": report["conclusion_reason"], + "output": str(args.output), + }, indent=2, ensure_ascii=False)) + return EXIT_OK + + +if __name__ == "__main__": + try: + sys.exit(main()) + except SystemExit: + raise + except Exception: # never report success on an unexpected failure + traceback.print_exc() + print("[error] internal failure; see traceback above", file=sys.stderr) + sys.exit(EXIT_INCOMPATIBLE) diff --git a/minco_ws/docs/diagnostics/b_baseline_qos.yaml b/minco_ws/docs/diagnostics/b_baseline_qos.yaml new file mode 100644 index 0000000..c0df749 --- /dev/null +++ b/minco_ws/docs/diagnostics/b_baseline_qos.yaml @@ -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 diff --git a/minco_ws/docs/diagnostics/check_static_obstacle_cloud.py b/minco_ws/docs/diagnostics/check_static_obstacle_cloud.py new file mode 100644 index 0000000..d583f4d --- /dev/null +++ b/minco_ws/docs/diagnostics/check_static_obstacle_cloud.py @@ -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() diff --git a/minco_ws/docs/diagnostics/test_analyze_pose_jitter.py b/minco_ws/docs/diagnostics/test_analyze_pose_jitter.py new file mode 100644 index 0000000..34346de --- /dev/null +++ b/minco_ws/docs/diagnostics/test_analyze_pose_jitter.py @@ -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 diff --git a/minco_ws/docs/diagnostics/test_analyze_self_boundary.py b/minco_ws/docs/diagnostics/test_analyze_self_boundary.py new file mode 100644 index 0000000..85efdaf --- /dev/null +++ b/minco_ws/docs/diagnostics/test_analyze_self_boundary.py @@ -0,0 +1,1110 @@ +#!/usr/bin/python3 +"""Unit tests for analyze_self_boundary. + +Run with the system interpreter so ROS's numpy path is used: + + /usr/bin/python3 -m pytest test_analyze_self_boundary.py -q + +These tests deliberately avoid a live bag and avoid the ROS Python bindings. +Everything that decides a verdict is a pure function, and the code paths that +need ROS are reached only after all metadata/sqlite checks, so the failure +modes stay testable on a machine without a sourced workspace. + +The counterexample block at the end encodes the architecture review: none of +those situations may be upgraded to a confirmed transform defect. +""" +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_self_boundary as tool # noqa: E402 + + +GEOMETRY = { + "config_path": "test", + "self_front": 0.385, + "self_rear": 0.425, + "self_left": 0.400, + "self_right": 0.400, + "self_z_min": -0.48, + "self_z_max": 0.0, + "boundary_guard": 0.02, + "lidar_to_imu_translation": np.array([-0.011, -0.02329, 0.04412]), + "baseline_differences": [], +} + + +def config_path(): + workspace = Path(__file__).resolve().parents[2] + return workspace / "src/scan/obstacle_cloud/config/flat_corridor.yaml" + + +def make_pool(times, points, outside=None, owner=None): + points = np.asarray(points, dtype=np.float64).reshape((-1, 3)) + times = np.asarray(times, dtype=np.int64) + count = len(times) + return { + "times": times, + "points": points, + "outside": np.asarray(outside, dtype=bool) if outside is not None + else np.zeros(count, dtype=bool), + "owner": np.asarray(owner, dtype=np.int64) if owner is not None + else np.zeros(count, dtype=np.int64), + } + + +def make_frames(frames_spec, start_ns=1_000_000_000, step_ns=50_000_000): + """frames_spec: list of (points, outside_mask, duration_ns).""" + frames = [] + for i, (points, outside, duration) in enumerate(frames_spec): + points = np.asarray(points, dtype=np.float64).reshape((-1, 3)) + outside = np.asarray(outside, dtype=bool) + offsets = np.arange(len(points), dtype=np.int64) * 100_000 + times = start_ns + i * step_ns + offsets + labels = np.where(outside, "outside", "inside").astype(object) + frames.append({ + "timebase_ns": start_ns + i * step_ns, + "times_ns": times, + "points": points, + "inside": ~outside, + "boundary": np.zeros(len(points), dtype=bool), + "outside": outside, + "labels": labels, + "excess": np.zeros(len(points)), + "axis": np.zeros(len(points), dtype=int), + "positive": np.zeros(len(points), dtype=bool), + "distance_to_box": np.zeros(len(points)), + "duration_ns": int(duration), + }) + return frames + + +# ---------------------------------------------------------------- geometry + +def test_exact_envelope_faces_are_inside(): + """The measured faces themselves must classify as inside, not outside. + + An off-by-epsilon here would report the bodywork's own surface as an + exterior return, which is exactly the confusion this tool must not add. + """ + faces = np.array([ + [0.385, 0.0, -0.24], # front face + [-0.425, 0.0, -0.24], # rear face + [0.0, 0.400, -0.24], # left face + [0.0, -0.400, -0.24], # right face + [0.0, 0.0, -0.48], # floor face + [0.0, 0.0, 0.0], # top face + [0.385, 0.400, 0.0], # corner + ]) + result = tool.classify_envelope(faces, GEOMETRY) + assert result["inside"].all() + assert not result["boundary"].any() + assert not result["outside"].any() + assert (result["excess"] <= 0).all() + + +def test_band_boundaries_are_contiguous(): + """inside -> boundary at zero, boundary -> outside at the guard value.""" + guard = GEOMETRY["boundary_guard"] + front = GEOMETRY["self_front"] + points = np.array([ + [front + 1e-9, 0.0, -0.24], # just outside the box + [front + guard * 0.5, 0.0, -0.24], # middle of the band + [front + guard, 0.0, -0.24], # exactly the band edge + [front + guard + 1e-6, 0.0, -0.24], # just past it + ]) + result = tool.classify_envelope(points, GEOMETRY) + assert result["boundary"].tolist() == [True, True, True, False] + assert result["outside"].tolist() == [False, False, False, True] + assert not result["inside"].any() + + +def test_outside_direction_and_distance(): + """Each outside point reports the face it crossed and how far.""" + points = np.array([ + [0.385 + 0.05, 0.0, -0.24], # front + [-0.425 - 0.07, 0.0, -0.24], # rear + [0.0, 0.400 + 0.03, -0.24], # left + [0.0, -0.400 - 0.04, -0.24], # right + ]) + result = tool.classify_envelope(points, GEOMETRY) + labels = [ + tool._direction_label(int(result["axis"][i]), bool(result["positive"][i])) + for i in range(len(points)) + ] + assert labels == ["front", "rear", "left", "right"] + excess = result["excess"] + assert excess[0] > 0 and excess[1] > excess[0] + assert excess[2] > 0 and excess[3] > 0 + + +def test_vertical_guard_is_zero(): + """The guard must not extend downward; ground returns are not bodywork.""" + point = np.array([[0.0, 0.0, -0.48 - 0.01]]) + result = tool.classify_envelope(point, GEOMETRY) + assert result["outside"][0] + assert not result["boundary"][0] + + +def test_empty_input_is_well_formed(): + result = tool.classify_envelope(np.zeros((0, 3)), GEOMETRY) + assert len(result["excess"]) == 0 + assert len(result["inside"]) == 0 + + +# ------------------------------------------------------------------ pose + +def test_full_quaternion_inverse_round_trip(): + """World -> lidar must invert lidar -> world under an arbitrary rotation.""" + yaw = math.radians(37.0) + pitch = math.radians(-6.0) + roll = math.radians(4.0) + cy, sy = math.cos(yaw / 2), math.sin(yaw / 2) + cp, sp = math.cos(pitch / 2), math.sin(pitch / 2) + cr, sr = math.cos(roll / 2), math.sin(roll / 2) + quaternion = np.array([ + sr * cp * cy - cr * sp * sy, + cr * sp * cy + sr * cp * sy, + cr * cp * sy - sr * sp * cy, + cr * cp * cy + sr * sp * sy, + ]) + position = np.array([1.7, -0.4, -0.35]) + lidar_points = np.array([ + [0.30, 0.10, -0.25], + [-0.40, -0.20, -0.30], + [0.0, 0.0, -0.48], + ]) + translation = GEOMETRY["lidar_to_imu_translation"] + + rotation = tool.rotation_from_quaternion(quaternion) + world = (lidar_points + translation) @ rotation.T + position + recovered = tool.inverse_transform(world, position, quaternion, translation) + assert np.allclose(recovered, lidar_points, atol=1e-12) + + +def test_inverse_transform_rejects_zero_quaternion(): + """A missing orientation is an error, not identity.""" + with pytest.raises(ValueError): + tool.rotation_from_quaternion([0.0, 0.0, 0.0, 0.0]) + with pytest.raises(ValueError): + tool.inverse_transform(np.zeros((1, 3)), np.zeros(3), + [0.0, 0.0, 0.0, 0.0], + GEOMETRY["lidar_to_imu_translation"]) + + +def test_inverse_transform_rejects_non_finite_quaternion(): + with pytest.raises(ValueError): + tool.rotation_from_quaternion([0.0, float("nan"), 0.0, 1.0]) + + +def test_pose_index_excludes_invalid_poses(): + """An invalid pose must never be offered as a nearest match.""" + times = np.array([0, 100_000_000, 200_000_000], dtype=np.int64) + positions = np.zeros((3, 3)) + quaternions = np.array([ + [0.0, 0.0, 0.0, 1.0], + [0.0, 0.0, 0.0, 0.0], # invalid + [0.0, 0.0, 0.0, 1.0], + ]) + index = tool.PoseIndex(times, positions, quaternions) + assert index.valid.tolist() == [True, False, True] + # 40 ms is nearer to 0 ms than to 200 ms, but the invalid pose at 100 ms is + # the true nearest; excluding it is what makes this assert meaningful. + dt, idx = index.nearest(40_000_000) + assert idx == 0 + assert dt == pytest.approx(0.04, abs=1e-9) + + +def test_pose_index_reports_gap_and_regression(): + times = np.array([0, 60_000_000, 400_000_000, 380_000_000], dtype=np.int64) + index = tool.PoseIndex(times, np.zeros((4, 3)), + np.tile([0.0, 0.0, 0.0, 1.0], (4, 1))) + assert index.regressions == 1 + assert index.max_gap == pytest.approx(0.34, abs=1e-9) + + +def test_pose_index_nearest_inside_a_gap_exceeds_tolerance(): + """A point inside a pose gap must fail the tolerance, not be interpolated.""" + times = np.array([0, 1_000_000_000, 2_000_000_000], dtype=np.int64) + index = tool.PoseIndex(times, np.zeros((3, 3)), + np.tile([0.0, 0.0, 0.0, 1.0], (3, 1))) + dt, idx = index.nearest(1_500_000_000) + assert idx in (1, 2) + assert dt > tool.DEFAULT_POSE_TIME_TOL + + +def test_pose_index_handles_out_of_range_queries(): + times = np.array([10, 20], dtype=np.int64) + index = tool.PoseIndex(times, np.zeros((2, 3)), + np.tile([0.0, 0.0, 0.0, 1.0], (2, 1))) + assert index.nearest(-5)[1] == 0 + assert index.nearest(10_000)[1] == 1 + empty = tool.PoseIndex(np.zeros(0, dtype=np.int64), np.zeros((0, 3)), + np.zeros((0, 4))) + dt, idx = empty.nearest(0) + assert idx is None and math.isinf(dt) + + +# --------------------------------------------------------- body shell band + +def test_distant_wall_is_not_shell_material(): + """A wall metres away is outside the box but is not body evidence. + + Regression: the shell test used to be `excess >= -margin` only, which + accepted every distant point and made the whole scene a candidate. On the + field bag that turned ~10 000 points per frame into shell and exhausted + memory. + """ + points = np.array([ + [0.385 + 0.010, 0.0, -0.24], # just outside a face + [0.385 + 0.250, 0.0, -0.24], # still inside the body ROI + [4.000, 0.0, -0.24], # a wall 4 m ahead + [-7.900, 1.000, 0.900], # far corner of the room + ]) + classified = tool.classify_envelope(points, GEOMETRY) + mask = tool.body_shell_mask(classified) + assert mask.tolist() == [True, True, False, False] + + +def test_shell_keeps_a_sliver_inside_the_face(): + """A raw return a few mm inside a face must stay matchable.""" + inside = np.array([[0.385 - 0.030, 0.0, -0.24]]) # 3 cm inside + too_far_inside = np.array([[0.385 - 0.120, 0.0, -0.24]]) # 12 cm inside + assert tool.body_shell_mask( + tool.classify_envelope(inside, GEOMETRY))[0] + assert not tool.body_shell_mask( + tool.classify_envelope(too_far_inside, GEOMETRY))[0] + + +def test_shell_band_is_bounded_on_both_sides(): + mask = tool.body_shell_mask( + {"excess": np.array([-0.20, -0.05, 0.0, 0.02, 0.30, 0.31, 4.6])}) + assert mask.tolist() == [False, True, True, True, True, False, False] + + +# ------------------------------------------------------------------- time + +def test_nanosecond_time_is_integer_exact(): + """Integer ns, because float seconds lose ~100 ns near a modern epoch.""" + base = 1_700_000_000_000_000_000 + assert tool.point_time_ns(base, 50_000_000) == base + 50_000_000 + assert isinstance(tool.point_time_ns(base, 0), int) + assert tool.point_time_ns(base, 100_000_000) - base == 100_000_000 + + +def test_nanosecond_time_rejects_nonsense(): + with pytest.raises(ValueError): + tool.point_time_ns(-1, 0) + with pytest.raises(ValueError): + tool.point_time_ns(1, -5) + with pytest.raises(ValueError): + tool.point_time_ns(1, 10_000_000_000) + + +# ------------------------------------------------------------ association + +def test_heuristic_nearest_for_a_clear_winner(): + pool = make_pool([1_000_000_000, 1_050_000_000], + [[0.400, 0.0, -0.24], [2.0, 2.0, 0.0]]) + quality, hit, diag = tool.resolve_association( + [1_000_000_000], np.array([0.402, 0.001, -0.241]), + pool, 0.002, 0.12) + assert quality == "heuristic_nearest" + assert hit == 0 + assert diag["hits"] == 1 + assert diag["margin"] == math.inf + + +def test_duplicate_candidates_are_ambiguous(): + """Two raw returns satisfying time+space cannot support a verdict.""" + pool = make_pool([1_000_000_000, 1_000_000_000], + [[0.400, 0.0, -0.24], [0.401, 0.001, -0.239]]) + quality, hit, diag = tool.resolve_association( + [1_000_000_000], np.array([0.4005, 0.0005, -0.2405]), + pool, 0.002, 0.12) + assert quality == "ambiguous" + assert hit is None + assert diag["hits"] == 2 + + +def test_decisively_nearest_wins_over_a_distant_second(): + """A clear runner-up must not block ranking on a dense cloud.""" + pool = make_pool([1_000_000_000, 1_000_000_000], + [[0.400, 0.0, -0.24], [0.470, 0.0, -0.24]]) + quality, hit, diag = tool.resolve_association( + [1_000_000_000], np.array([0.402, 0.0, -0.24]), pool, 0.002, 0.12) + assert quality == "heuristic_nearest" + assert hit == 0 + assert diag["nearest_dist"] == pytest.approx(0.002, abs=1e-9) + assert diag["second_dist"] == pytest.approx(0.068, abs=1e-9) + assert diag["margin"] > tool.DEFAULT_ASSOC_TIE_MARGIN + + +def test_equidistant_candidates_are_ambiguous(): + """Two equally plausible raw returns cannot support a verdict.""" + pool = make_pool([1_000_000_000, 1_000_000_000], + [[0.370, 0.0, -0.24], [0.430, 0.0, -0.24]]) + quality, hit, _ = tool.resolve_association( + [1_000_000_000], np.array([0.400, 0.0, -0.24]), pool, 0.002, 0.12) + assert quality == "ambiguous" + assert hit is None + + +def test_unmatched_association(): + pool = make_pool([1_000_000_000], [[0.40, 0.0, -0.24]]) + quality, hit, _ = tool.resolve_association( + [1_000_000_000], np.array([3.0, 3.0, 3.0]), pool, 0.002, 0.12) + assert quality == "unmatched" + assert hit is None + + +def test_no_quality_is_ever_called_unique(): + """The vocabulary itself must not imply confirmed correspondence.""" + pool = make_pool([1_000_000_000], [[0.40, 0.0, -0.24]]) + quality, _, _ = tool.resolve_association( + [1_000_000_000], np.array([0.401, 0.0, -0.24]), pool, 0.002, 0.12) + assert quality != "unique" + assert quality == "heuristic_nearest" + + +# ------------------------------------------- cross-scan search completeness + +def test_competitor_in_a_neighbouring_scan_is_searched(): + """The pool must span every candidate scan, not just the nearest one. + + Before the fix only frames[index] was searched. A competitor living in the + previous scan never entered the comparison, so a distant runner-up was + invisible and a false nearest was reported. + """ + frames = make_frames([ + ([[0.420, 0.0, -0.24]], [True], 100_000), # previous scan: competitor + ([[0.401, 0.0, -0.24]], [True], 100_000), # nearest scan + ([[2.0, 2.0, 0.0]], [False], 100_000), + ]) + indices = tool.candidate_frame_indices(frames, 1) + assert indices == [0, 1, 2] + pool = tool.association_pool(frames, indices) + window = tool.estimate_scan_window_ns(frames) + times = tool.candidate_times_ns(frames, indices, 0.0, + frames[1]["timebase_ns"], window, + tool.DEFAULT_ASSOC_TIME_TOL) + # Scan 2 starts after the published frame header, so it cannot have + # contributed a point and must be excluded by the one-sided window. + assert len(times) == 2, "both earlier scans must contribute an instant" + assert times == [frames[0]["timebase_ns"], frames[1]["timebase_ns"]] + + quality, hit, diag = tool.resolve_association( + times, np.array([0.415, 0.0, -0.24]), pool, 0.002, 0.12) + + # 0.420 is 5 mm away, 0.401 is 14 mm away: the margin is only 9 mm, so the + # pair must NOT be reported as a clean winner. + assert diag["hits"] == 2 + assert diag["nearest_dist"] == pytest.approx(0.005, abs=1e-9) + assert diag["second_dist"] == pytest.approx(0.014, abs=1e-9) + assert quality == "ambiguous" + + +def test_association_pool_marks_the_owning_scan(): + frames = make_frames([ + ([[0.40, 0.0, -0.24]], [True], 100_000), + ([[0.41, 0.0, -0.24]], [True], 100_000), + ]) + pool = tool.association_pool(frames, [0, 1]) + assert pool["owner"].tolist() == [0, 1] + assert pool["outside"].tolist() == [True, True] + + +def test_wrong_candidate_being_nearest_does_not_confirm_anything(): + """A clearly-nearest candidate from another scan is still only a ranking. + + The competitor sits in a different original scan, so its distance says + nothing about which measurement produced the world point. + """ + frames = make_frames([ + ([[0.402, 0.0, -0.24]], [True], 100_000), # other scan, 2 mm away + ([[0.460, 0.0, -0.24]], [True], 100_000), + ]) + indices = tool.candidate_frame_indices(frames, 1) + pool = tool.association_pool(frames, indices) + quality, hit, diag = tool.resolve_association( + [frames[1]["timebase_ns"]], np.array([0.400, 0.0, -0.24]), + pool, 0.002, 0.12) + + assert quality == "heuristic_nearest" + assert diag["candidate_scans"] == 2 + assert diag["margin"] > tool.DEFAULT_ASSOC_TIE_MARGIN + # Even a clean win must not become a cause. + assert tool._decide(quality, residual_min=0.002, observed_scale=0.002, + threshold=0.02, world_outside=True, + evidence_complete=True) == \ + "inconclusive_within_observed_motion" + + +def test_candidate_times_span_all_scans(): + """Every plausible scan contributes its own instant, not just the nearest.""" + frames = make_frames([ + ([[0.40, 0.0, -0.24]], [True], 100_000), + ([[0.40, 0.0, -0.24]], [True], 100_000), + ]) + indices = tool.candidate_frame_indices(frames, 1) + window = tool.estimate_scan_window_ns(frames) + times = tool.candidate_times_ns(frames, indices, 0.0, + frames[1]["timebase_ns"], window, + tool.DEFAULT_ASSOC_TIME_TOL) + assert len(times) == 2 + assert times[1] - times[0] == 50_000_000 + + +# ------------------------------------------------- pose assumption kept open + +def test_pose_options_expose_every_assumption(): + """Each admissible candidate scan yields its own pose; none is chosen.""" + pose_times = np.array([0, 100_000_000, 200_000_000], dtype=np.int64) + frame_bases = np.array([0, 100_000_000], dtype=np.int64) + options = tool.candidate_pose_options( + pose_times, np.ones(3, dtype=bool), frame_bases, + np.zeros(2, dtype=np.int64), [0, 1], tool.DEFAULT_POSE_TIME_TOL, + published_stamp_ns=100_000_000, scan_window_ns=100_000_000) + + assert len(options) == 2 + assert [o["frame_index"] for o in options] == [0, 1] + assert options[0]["pose_index"][0] == 0 + assert options[1]["pose_index"][0] == 1 + assert options[0]["time_ns"][0] == 0 + assert options[1]["time_ns"][0] == 100_000_000 + + +def test_pose_option_is_unusable_outside_tolerance(): + pose_times = np.array([0], dtype=np.int64) + options = tool.candidate_pose_options( + pose_times, np.ones(1, dtype=bool), np.array([90_000_000], dtype=np.int64), + np.zeros(1, dtype=np.int64), [0], tool.DEFAULT_POSE_TIME_TOL, + published_stamp_ns=90_000_000, scan_window_ns=0) + assert len(options) == 1 + assert not options[0]["usable"][0] + assert options[0]["pose_index"][0] == -1 + assert options[0]["dt_s"][0] == pytest.approx(0.09, abs=1e-9) + + +def test_pose_option_is_unusable_without_a_valid_pose(): + pose_times = np.array([0, 100_000_000], dtype=np.int64) + options = tool.candidate_pose_options( + pose_times, np.array([True, False]), + np.array([100_000_000], dtype=np.int64), + np.zeros(1, dtype=np.int64), [0], tool.DEFAULT_POSE_TIME_TOL, + published_stamp_ns=100_000_000, scan_window_ns=0) + assert not options[0]["usable"][0] + assert options[0]["in_window"][0] + assert not options[0]["pose_valid"][0] + + +def test_future_scan_is_excluded_from_the_enumeration(): + """A scan that starts after the published header cannot have contributed.""" + pose_times = np.array([0, 100_000_000, 200_000_000], dtype=np.int64) + frame_bases = np.array([100_000_000, 200_000_000], dtype=np.int64) + options = tool.candidate_pose_options( + pose_times, np.ones(3, dtype=bool), frame_bases, + np.zeros(2, dtype=np.int64), [0, 1], tool.DEFAULT_POSE_TIME_TOL, + published_stamp_ns=100_000_000, scan_window_ns=100_000_000) + assert options[0]["in_window"][0] + assert options[0]["usable"][0] + assert not options[1]["in_window"][0] + assert not options[1]["usable"][0] + + +def test_pose_options_are_empty_without_candidates(): + assert tool.candidate_pose_options( + np.array([0], dtype=np.int64), np.ones(1, dtype=bool), + np.array([0], dtype=np.int64), np.zeros(0, dtype=np.int64), + [], 0.03, 0, 0) == [] + + +def test_per_assumption_residuals_are_a_range_not_a_verdict(): + """1 mm and 50 mm readings coexist; the worst must not erase the best. + + Two assumptions reach two different raw returns. Reporting only the worst + would discard the reading that actually fits, so both ends are kept. + """ + pool = make_pool([1_000_000_000, 1_050_000_000], + [[0.401, 0.0, -0.24], [0.450, 0.0, -0.24]]) + quality, hit, diag = tool.resolve_association_multi( + [1_000_000_000, 1_050_000_000], + [np.array([0.400, 0.0, -0.24]), np.array([0.400, 0.0, -0.24])], + pool, 0.002, 0.12) + assert quality == "heuristic_nearest" + assert hit == 0 + assert diag["residual_min"] == pytest.approx(0.001, abs=1e-9) + assert diag["residual_max"] == pytest.approx(0.050, abs=1e-9) + # The favourable reading governs the verdict. + assert tool._decide(quality, diag["residual_min"], 0.002, 0.02, True, + True) == "inconclusive_within_observed_motion" + + +# --------------------------------------------------------------- decisions + +def test_decision_never_upgrades_weak_evidence(): + assert tool._decide("ambiguous", 0.5, 0.01, 0.02, True, True) == \ + "inconclusive_ambiguous" + assert tool._decide("unmatched", None, 0.01, 0.02, True, True) == \ + "world_outside_no_raw_counterpart" + assert tool._decide("heuristic_nearest", 0.005, 0.01, 0.02, True, True) == \ + "inconclusive_within_observed_motion" + assert tool._decide("heuristic_nearest", 0.5, 0.01, 0.02, True, True) == \ + "anomaly_candidate_unattributed" + + +def test_anomaly_requires_every_admissible_reading_to_fail(): + """A favourable reading must block the anomaly claim. + + The worst-case residual is 50 mm, well beyond the scale, but one admissible + reading fits at 1 mm. Claiming the residual exceeds the scale would mean + discarding the best account of the observation, so the verdict must stay + inconclusive. + """ + assert tool._decide("heuristic_nearest", 0.001, 0.002, 0.02, True, True) == \ + "inconclusive_within_observed_motion" + + +def test_incomplete_evidence_blocks_any_positive_claim(): + assert tool._decide("heuristic_nearest", 0.5, 0.002, 0.02, True, False) == \ + "inconclusive_incomplete_evidence" + + +def test_no_decision_names_a_confirmed_cause(): + """The decision vocabulary may not assert a transform defect.""" + allowed = { + "inconclusive_ambiguous", "inconclusive_unmatched", + "inconclusive_incomplete_evidence", + "inconclusive_no_observed_motion_scale", + "inconclusive_within_observed_motion", + "inconclusive_below_screening_threshold", + "anomaly_candidate_unattributed", "world_outside_no_raw_counterpart", + } + for quality in ("heuristic_nearest", "ambiguous", "unmatched"): + for residual in (None, 0.0, 0.001, 5.0): + for complete in (True, False): + decision = tool._decide(quality, residual, 0.01, 0.02, True, + complete) + assert decision in allowed + assert "supported" not in decision + assert "confirmed" not in decision + + +def test_classification_change_alone_never_selects_a_verdict(): + """A millimetre across a face must not become a cause.""" + within = tool._decide("heuristic_nearest", residual_min=0.0005, + observed_scale=0.01, threshold=0.02, + world_outside=True, evidence_complete=True) + assert within == "inconclusive_within_observed_motion" + + beyond = tool._decide("heuristic_nearest", residual_min=0.5, + observed_scale=0.01, threshold=0.02, + world_outside=True, evidence_complete=True) + assert beyond == "anomaly_candidate_unattributed" + assert "disagreement" not in beyond + + +def test_tiny_residual_crossing_the_boundary_is_not_a_cause(): + """Raw inside, world in the boundary band, but only by a millimetre.""" + raw_point = np.array([[0.384, 0.0, -0.24]]) + world_local = np.array([[0.3855, 0.0, -0.24]]) + raw_labels = tool.envelope_label( + tool.classify_envelope(raw_point, GEOMETRY)) + world_labels = tool.envelope_label( + tool.classify_envelope(world_local, GEOMETRY)) + + assert str(raw_labels[0]) != str(world_labels[0]) + assert raw_labels[0] == "inside" + assert world_labels[0] == "boundary" + + residual = float(np.linalg.norm(world_local[0] - raw_point[0])) + assert residual < tool.COMPARISON_SCREENING_M + + decision = tool._decide("heuristic_nearest", residual_min=residual, + observed_scale=0.002, threshold=0.02, + world_outside=False, evidence_complete=True) + assert decision == "inconclusive_within_observed_motion" + + +# ------------------------------------------------------------- conclusions + +def _report(beyond_solid, beyond_band, nearest, ambiguous, unmatched, decisions, + whole_scene_outside=9999): + return {"statistics": { + "raw_body_roi": {"beyond_solid_envelope": beyond_solid, + "beyond_guard_band": beyond_band, + "within_guard_band": beyond_solid - beyond_band, + "roi_margin_m": tool.BODY_ROI_MARGIN_M}, + "raw_whole_scene_classification": {"outside": whole_scene_outside, + "boundary": 0, "inside": 100}, + "association": {"heuristic_nearest": nearest, "ambiguous": ambiguous, + "unmatched": unmatched}, + "decisions": decisions, + }} + + +def test_environment_points_never_trigger_the_outside_conclusion(): + """Walls and steps are outside the box but are not body evidence. + + The whole-scene count is huge; the ROI count is zero, so the conclusion must + be that nothing near the body is outside. + """ + conclusion, reason = tool._conclude( + _report(0, 0, 0, 0, 0, {}, whole_scene_outside=9999)) + assert conclusion == "no_raw_outside_returns" + assert "diagnostic region" in reason + + +def test_raw_measurement_survives_a_total_link_failure(): + """The raw count needs no transform, so it is reported even when unlinked.""" + conclusion, reason = tool._conclude( + _report(8, 8, 0, 5, 3, {"inconclusive_ambiguous": 5})) + assert conclusion == "raw_outside_measured_unlinked" + assert "measured raw coordinates relative to the configured envelope" in reason + + +def test_raw_measurement_conclusion_refuses_causal_language(): + """It may not claim body protrusion, a real obstacle or a transform error.""" + _, reason = tool._conclude(_report(8, 2, 0, 5, 3, {"inconclusive_ambiguous": 5})) + assert "does not" in reason + assert "body protrusion" in reason + assert "compensation error" in reason + + +def test_guard_band_and_solid_envelope_are_reported_separately(): + _, reason = tool._conclude( + _report(8, 2, 0, 5, 3, {"inconclusive_ambiguous": 5})) + assert "8 raw return(s)" in reason + assert "2 of them beyond the 2 cm guard band" in reason + + +def test_anomaly_conclusion_is_reachable_and_unattributed(): + conclusion, reason = tool._conclude( + _report(8, 8, 2, 0, 0, {"anomaly_candidate_unattributed": 2})) + assert conclusion == "anomaly_candidates_unattributed" + assert "no cause is attributed" in reason + + +def test_incomplete_evidence_conclusion_is_undetermined(): + conclusion, reason = tool._conclude( + _report(8, 8, 2, 0, 0, {"inconclusive_incomplete_evidence": 2})) + assert conclusion == "undetermined" + assert "incomplete rather than negative" in reason + + +def test_within_motion_only_conclusion_is_undetermined(): + conclusion, _ = tool._conclude( + _report(8, 8, 2, 0, 0, {"inconclusive_within_observed_motion": 2})) + assert conclusion == "undetermined" + + +def test_conclusion_never_claims_a_supported_cause(): + for beyond, nearest, decisions in [ + (8, 2, {"anomaly_candidate_unattributed": 2}), + (8, 0, {"inconclusive_ambiguous": 3}), + (0, 0, {}), + ]: + conclusion, _ = tool._conclude( + _report(beyond, beyond, nearest, 0, 0, decisions)) + assert "supported" not in conclusion + assert "confirmed" not in conclusion + + +# ------------------------------------- motion scale vs screening threshold + +def test_threshold_is_reported_separately_from_measured_motion(): + """One is measured, the other is an assumption; they must not be merged.""" + assert tool.comparison_threshold(0.0) == tool.COMPARISON_SCREENING_M + assert tool.comparison_threshold(0.5) == 0.5 + # Below the floor, the floor governs; above it, the motion governs. + assert tool.comparison_threshold(0.001) == tool.COMPARISON_SCREENING_M + + +def test_static_frame_motion_is_zero_not_the_screening_floor(): + zero = tool.observed_motion_scale( + np.zeros((2, 3)), np.tile([0.0, 0.0, 0.0, 1.0], (2, 1)), + np.array([[1.0, 0.0, 0.0]])) + assert zero == 0.0 + assert tool.comparison_threshold(zero) == tool.COMPARISON_SCREENING_M + + +def test_below_threshold_is_not_the_same_as_explained_by_motion(): + """A residual above the motion but under the floor was not screened. + + Calling that "within observed motion" would let an assumption pass as a + measured explanation, so the two outcomes must differ. + """ + explained = tool._decide("heuristic_nearest", residual_min=0.001, + observed_scale=0.005, threshold=0.02, + world_outside=True, evidence_complete=True) + not_screened = tool._decide("heuristic_nearest", residual_min=0.013, + observed_scale=0.005, threshold=0.02, + world_outside=True, evidence_complete=True) + assert explained == "inconclusive_within_observed_motion" + assert not_screened == "inconclusive_below_screening_threshold" + assert explained != not_screened + + reason = tool._reason(not_screened, {"hits": 1}) + assert "NOT explained" in reason + + +def test_thirteen_millimetre_excursion_is_not_screened_but_still_reportable(): + """The previously observed ~13 mm excursion must stay visible. + + 20 mm screening does not flag it, so the excess distance has to carry it. + """ + decision = tool._decide("heuristic_nearest", residual_min=0.013, + observed_scale=0.0, + threshold=tool.COMPARISON_SCREENING_M, + world_outside=True, evidence_complete=True) + assert decision == "inconclusive_below_screening_threshold" + + # The classification and the excess are independent of that decision. + point = np.array([[0.385 + 0.013, 0.0, -0.24]]) + classified = tool.classify_envelope(point, GEOMETRY) + assert classified["boundary"][0] + assert classified["excess"][0] == pytest.approx(0.013, abs=1e-9) + + +def test_screening_floor_is_not_advertised_as_a_noise_bound(): + doc = tool.comparison_threshold.__doc__ or "" + assert "does not mean the residual was explained" in doc + limits = " ".join(tool._limits({"geometry": {"baseline_differences": []}})) + assert "NOT a verified noise bound" in limits + assert "sensor noise cancels" in limits + + +# ------------------------------------------------- observed motion scale + +def test_observed_motion_scale_grows_with_window_motion(): + quaternion = np.tile([0.0, 0.0, 0.0, 1.0], (2, 1)) + still = tool.observed_motion_scale(np.zeros((2, 3)), quaternion, + np.array([[5.0, 0.0, 0.0]])) + moved = tool.observed_motion_scale( + np.array([[0.0, 0.0, 0.0], [0.2, 0.0, 0.0]]), quaternion, + np.array([[5.0, 0.0, 0.0]])) + assert still == 0.0 + assert moved >= 0.2 + + +def test_observed_motion_scale_is_not_called_a_bound(): + """The name and the docstring must not promise an upper bound.""" + assert not hasattr(tool, "motion_bound") + doc = tool.observed_motion_scale.__doc__ or "" + assert "NOT AN UPPER BOUND" in doc + + +def test_scale_exceeded_stays_an_anomaly_candidate(): + """Anchor prediction error can exceed the observed motion, so no cause.""" + scale = tool.observed_motion_scale( + np.array([[0.0, 0.0, 0.0], [0.01, 0.0, 0.0]]), + np.tile([0.0, 0.0, 0.0, 1.0], (2, 1)), + np.array([[5.0, 0.0, 0.0]])) + decision = tool._decide("heuristic_nearest", residual_min=0.5, + observed_scale=scale, threshold=0.02, + world_outside=True, evidence_complete=True) + assert decision == "anomaly_candidate_unattributed" + assert decision != "world_transform_or_timing_supported" + + +def test_observed_motion_scale_empty_is_infinite(): + assert math.isinf(tool.observed_motion_scale( + np.zeros((1, 3)), np.array([[0.0, 0.0, 0.0, 1.0]]), np.zeros((0, 3)))) + + +# ---------------------------------------------------------------- config + +def test_real_config_matches_documented_baseline(): + path = config_path() + if not path.is_file(): + pytest.skip(f"config not present: {path}") + geometry = tool.load_geometry(path) + assert geometry["baseline_differences"] == [] + assert geometry["self_front"] == 0.385 + assert geometry["self_rear"] == 0.425 + assert geometry["boundary_guard"] == 0.02 + assert np.allclose(geometry["lidar_to_imu_translation"], + [-0.011, -0.02329, 0.04412]) + + +def test_config_difference_is_reported_not_rejected(tmp_path): + path = tmp_path / "shifted.yaml" + path.write_text( + "obstacle_cloud:\n ros__parameters:\n" + " self_front: 0.400\n self_rear: 0.425\n" + " self_left: 0.400\n self_right: 0.400\n" + " self_z_min: -0.48\n self_z_max: 0.0\n" + " lidar_to_imu_translation: [-0.011, -0.02329, 0.04412]\n", + encoding="utf-8") + geometry = tool.load_geometry(path) + keys = [d["key"] for d in geometry["baseline_differences"]] + assert keys == ["self_front"] + + +def test_config_rejects_missing_key(tmp_path): + path = tmp_path / "broken.yaml" + path.write_text("obstacle_cloud:\n ros__parameters:\n self_front: 0.4\n", + encoding="utf-8") + with pytest.raises(tool.PathProblem): + tool.load_geometry(path) + + +def test_config_rejects_inverted_vertical_range(tmp_path): + path = tmp_path / "inverted.yaml" + path.write_text( + "obstacle_cloud:\n ros__parameters:\n" + " self_front: 0.385\n self_rear: 0.425\n" + " self_left: 0.4\n self_right: 0.4\n" + " self_z_min: 0.0\n self_z_max: -0.48\n" + " lidar_to_imu_translation: [0, 0, 0]\n", encoding="utf-8") + with pytest.raises(tool.PathProblem): + tool.load_geometry(path) + + +# ------------------------------------------------------------ bag plumbing + +def _write_metadata(bag_dir: Path, topics: dict, storage="sqlite3", + shards=("bag_0.db3",)): + bag_dir.mkdir(parents=True, exist_ok=True) + for shard in shards: + (bag_dir / shard).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.append(" relative_file_paths:") + for shard in shards: + lines.append(f" - {shard}") + (bag_dir / "metadata.yaml").write_text("\n".join(lines) + "\n", + encoding="utf-8") + + +def test_missing_raw_topic_raises_incomplete(tmp_path): + bag = tmp_path / "bag" + _write_metadata(bag, { + "/cloud_registered_full": "sensor_msgs/msg/PointCloud2", + "/aft_mapped_to_init": "nav_msgs/msg/Odometry", + }) + geometry = tool.load_geometry(config_path()) if config_path().is_file() \ + else GEOMETRY + with pytest.raises(tool.MissingTopic) as caught: + tool.analyze_bag(bag, geometry) + report = caught.value.args[0] + assert report["status"] == "incomplete" + assert report["conclusion"] == "undetermined" + assert report["missing_topics"] == ["/livox/lidar"] + assert "raw" in report["conclusion_reason"] + + +def test_unsupported_storage_raises_bag_problem(tmp_path): + bag = tmp_path / "bag" + _write_metadata(bag, {}, storage="mcap") + with pytest.raises(tool.BagProblem) as caught: + tool.analyze_bag(bag, GEOMETRY) + assert "mcap" in str(caught.value) + + +def test_missing_metadata_raises_path_problem(tmp_path): + bag = tmp_path / "bag" + bag.mkdir() + with pytest.raises(tool.PathProblem): + tool.analyze_bag(bag, GEOMETRY) + + +def test_missing_shard_raises_bag_problem(tmp_path): + bag = tmp_path / "empty" + _write_metadata(bag, {}, shards=("bag_0.db3",)) + (bag / "bag_0.db3").unlink() + with pytest.raises(tool.BagProblem): + tool.analyze_bag(bag, GEOMETRY) + + +def test_corrupt_shard_raises_bag_problem(tmp_path): + bag = tmp_path / "bag" + _write_metadata(bag, {}) + (bag / "bag_0.db3").write_bytes(b"not a sqlite database") + with pytest.raises(tool.BagProblem): + tool.analyze_bag(bag, GEOMETRY) + + +def test_shard_without_topics_table_raises(tmp_path): + bag = tmp_path / "bag" + _write_metadata(bag, {}) + conn = sqlite3.connect(bag / "bag_0.db3") + conn.execute("CREATE TABLE unrelated (id INTEGER)") + conn.commit() + conn.close() + with pytest.raises(tool.BagProblem): + tool.analyze_bag(bag, GEOMETRY) + + +# -------------------------------------------------------------- reporting + +def test_report_contains_required_fields(tmp_path): + report = { + "schema_version": tool.SCHEMA_VERSION, + "status": "complete", + "geometry": {"baseline_differences": []}, + "conclusion": "undetermined", + "conclusion_reason": "synthetic", + "limits": [], + "_csv_rows": [{ + "source": "raw", "point_time_ns": "1", + "candidate_time_count": "1", "candidate_time_span_ms": "", + "curvature_ms": "", + "x_m": "0.4", "y_m": "0.0", "z_m": "-0.2", + "outside_axis": "front", "outside_dist_m": "0.01", + "distance_to_box_m": "0.01", "match_quality": "n/a", + "nearest_dist_m": "", "second_dist_m": "", + "nearest_margin_m": "", "candidate_scans": "", + "pose_dt_s": "", "observed_motion_scale_m": "", "residual_m": "", + "classification_changed": "", + "decision": "raw_outside_envelope", "reason": "synthetic", + }], + } + tool.write_report(report, tmp_path) + summary = json.loads((tmp_path / "summary.json").read_text(encoding="utf-8")) + assert summary["schema_version"] == tool.SCHEMA_VERSION + assert summary["conclusion"] == "undetermined" + assert "_csv_rows" not in summary + + header = (tmp_path / "boundary_points.csv").read_text( + encoding="utf-8").splitlines()[0] + for column in ("point_time_ns", "candidate_time_count", "outside_axis", + "match_quality", "nearest_margin_m", + "observed_motion_scale_m", "classification_changed", + "decision"): + assert column in header + + +def test_write_report_refuses_to_overwrite(tmp_path): + report = {"schema_version": 2, "geometry": {"baseline_differences": []}, + "_csv_rows": []} + (tmp_path / "summary.json").write_text("{}", encoding="utf-8") + with pytest.raises(tool.PathProblem) as caught: + tool.write_report(report, tmp_path) + assert "refusing to overwrite" in str(caught.value) + + +# -------------------------------------------------------------- exit codes + +def test_main_missing_bag_returns_2(tmp_path): + code = tool.main(["--bag", str(tmp_path / "absent"), + "--config", str(config_path()), + "--output", str(tmp_path / "out")]) + assert code == tool.EXIT_MISSING + + +def test_main_missing_config_returns_2(tmp_path): + code = tool.main(["--bag", str(tmp_path), + "--config", str(tmp_path / "absent.yaml"), + "--output", str(tmp_path / "out")]) + assert code == tool.EXIT_MISSING + + +def test_main_unsupported_storage_returns_3(tmp_path): + bag = tmp_path / "bag" + _write_metadata(bag, {}, storage="mcap") + code = tool.main(["--bag", str(bag), + "--config", str(config_path()), + "--output", str(tmp_path / "out")]) + assert code == tool.EXIT_INCOMPATIBLE + + +def test_main_missing_topic_writes_partial_and_returns_2(tmp_path): + bag = tmp_path / "bag" + _write_metadata(bag, { + "/cloud_registered_full": "sensor_msgs/msg/PointCloud2", + "/aft_mapped_to_init": "nav_msgs/msg/Odometry", + }) + output = tmp_path / "out" + code = tool.main(["--bag", str(bag), + "--config", str(config_path()), + "--output", str(output)]) + assert code == tool.EXIT_MISSING + summary = json.loads((output / "summary.json").read_text(encoding="utf-8")) + assert summary["status"] == "incomplete" + assert summary["missing_topics"] == ["/livox/lidar"] + + +def test_main_refuses_existing_output_without_overwrite(tmp_path): + bag = tmp_path / "bag" + _write_metadata(bag, {}) + output = tmp_path / "out" + output.mkdir() + (output / "summary.json").write_text("{}", encoding="utf-8") + code = tool.main(["--bag", str(bag), + "--config", str(config_path()), + "--output", str(output)]) + assert code == tool.EXIT_MISSING + assert (output / "summary.json").read_text(encoding="utf-8") == "{}" + + +def test_expected_bag_is_absent_so_no_field_claim_is_made(): + """Guard against a future run silently assuming the field bag exists.""" + workspace = Path(__file__).resolve().parents[2] + bag = workspace / "log/field_b_self_static_01/bag" + if bag.exists(): + pytest.skip("field bag now exists; the synthetic-only caveat no longer applies") + assert not bag.exists() + + +# ------------------------------------------------------- parity with core.py + +def test_classification_matches_obstacle_cloud_core(): + """The offline classifier must agree with the one running on the robot. + + core.classify_self_returns is what the live filter uses. If this tool + drifted from it, a "boundary" point here could be an "inside" point in the + node, and the whole report would describe a different box. + """ + try: + from obstacle_cloud.core import (Config, # noqa: WPS433 + classify_self_returns) + except Exception: + pytest.skip("obstacle_cloud not importable without a sourced workspace") + + rng = np.random.default_rng(11) + points = rng.uniform([-0.6, -0.6, -0.6], [0.6, 0.6, 0.2], size=(4000, 3)) + points = np.vstack([points, np.array([ + [0.385, 0.0, -0.24], [-0.425, 0.0, -0.24], + [0.0, 0.400, -0.24], [0.0, -0.400, -0.24], + [0.0, 0.0, -0.48], [0.0, 0.0, 0.0], + [0.390, 0.0, -0.24], [-0.430, 0.0, -0.24], + [0.0, 0.405, -0.24], [0.0, 0.0, -0.49], + ])]) + + config = Config() + translation = np.asarray(config.lidar_to_imu_translation) + # core.classify_self_returns takes *world* points and converts to the lidar + # frame internally; this tool takes lidar-frame points and leaves the + # transform to inverse_transform(). With an identity pose at the origin the + # world point is simply lidar + T_L_I. + world = points + translation + inside_core, near_core = classify_self_returns( + world, np.zeros(3), [0.0, 0.0, 0.0, 1.0], config) + + geometry = dict(GEOMETRY, boundary_guard=config.self_boundary_guard) + ours = tool.classify_envelope(points, geometry) + + assert np.array_equal(ours["inside"], inside_core) + assert np.array_equal(ours["boundary"], near_core)