feat(sru_ws): 方案 C 零样本评估工具链
tools/ 新增:export_bag_to_npz.py(rosbag→npz)、make_synthetic_bag.py (无真实数据时构造可复现输入)、sru_policy_math.py(策略数学,纯函数)、 sru_zeroshot_replay.py(回放评估),以及 tests/ 单测。 docs/SOLUTION_C_ASSESSMENT.md 记录判据与结论。 文档结论刻意写成「工具与判据已就绪,真实数据的零样本结论尚未获得」: 仓库里没有任何录过深度的包,所以现有数字全部来自合成输入,不构成 对策略能力的判断。文中每个数字都标了复现命令和待确认项。 运行产物 sru_ws/tools/_zs_out/ 不入库(见 .gitignore 第 10 节)。
This commit is contained in:
@@ -0,0 +1,274 @@
|
|||||||
|
# 方案 C(SRU 端到端无图导航)零样本评估
|
||||||
|
|
||||||
|
> 状态:**工具与判据已就绪,真实数据的零样本结论尚未获得**(原因见 §3.4:仓库里没有任何录过深度的包)。
|
||||||
|
> 本文所有数字都可由附录 A 的命令复现;凡是"未确认"的,都写明了由谁确认。
|
||||||
|
> 日期:2026-11-02 | 范围:`sru_ws/`(不动 `minco_ws/`,不提交 `reference/` 训练资源)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0. 结论摘要
|
||||||
|
|
||||||
|
| 问题 | 结论 |
|
||||||
|
|---|---|
|
||||||
|
| 要不要导入车体模型重新训练? | **先不要。** 顺序是:零样本上车 → 微调 → 重训,每一档都能否决下一档 |
|
||||||
|
| 现在能下"零样本可用"的结论吗? | **不能。** 缺一份带 `/odin1/depth_img_competetion` 的录包;本轮交付的是产出这份证据的工具 |
|
||||||
|
| 有没有比重训更值得先做的事? | **有,而且很可能就是主因**:部署侧的速度增益被压到训练值的 **0.40×/0.18×/0.60×**(见 §2.1)。这一条不改,零样本测出任何异常都无法归因 |
|
||||||
|
| 本轮新增的硬结论 | ① 训练用的速度包络是 `[1.5, 1.0, 1.0]`,不是 `[0.6, 0.3, 0.7]`(Go2 的 `scale` 是死代码);② 深度只有 228×185,不是 600×960;③ 策略的**前向速度在通畅走廊里恒定饱和**,几何只改变 ω 与 vy |
|
||||||
|
|
||||||
|
**"建议零样本上车"这个结论依赖以下三条未确认前提**(任一不成立就要降档):
|
||||||
|
|
||||||
|
1. Odin1 装到 RC2027 后,相机**俯仰 = 0**、且深度**已去畸变**(训练侧用理想针孔 raycast,注释明确要求真机先去畸变);
|
||||||
|
2. 车体自身结构**不进入视野**(用 `near_frac` 指标判定,见 §3.3);
|
||||||
|
3. 部署侧 `policy_scale` 至少按 §2.1 做一次 A/B,否则"零样本失败"与"增益不匹配"无法区分。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 本轮交付物
|
||||||
|
|
||||||
|
| 文件 | 作用 | 依赖 |
|
||||||
|
|---|---|---|
|
||||||
|
| `tools/sru_policy_math.py` | 部署侧算术的纯 NumPy 规格:深度清洗/缩放、目标编码、16 维状态拼装、`tanh*scale`、低通 | 仅 numpy |
|
||||||
|
| `tools/tests/test_sru_policy_math.py` | 32 个纯逻辑测试(含与 `model.py` 常量的交叉校验) | 仅 numpy + pytest |
|
||||||
|
| `tools/sru_zeroshot_replay.py` | 离线回放:深度序列 → 原始动作 → 四种增益视图 + 统计 | onnxruntime |
|
||||||
|
| `tools/export_bag_to_npz.py` | rosbag2 → `.npz`(深度/里程计/目标/`/cmd_vel`) | ROS 2(跑一次即可) |
|
||||||
|
| `tools/make_synthetic_bag.py` | 造一个合成 bag,用于无车验证"录制→导出→回放"整条链路 | ROS 2 |
|
||||||
|
| `tools/_zs_out/` | 本轮实跑输出(summary.json / CSV / 深度图),临时目录,可删 | — |
|
||||||
|
|
||||||
|
零样本回放**不重新实现推理**:它直接 `import sru_nav_ros2.model.LearningModel`,所以被测的就是部署代码本身,而不是它的仿写。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 事实核查:四处与既有认知不符
|
||||||
|
|
||||||
|
### 2.1 ⭐ 速度包络:训练是 `[1.5, 1.0, 1.0]`,`scale=[0.6,0.3,0.7]` 是死代码
|
||||||
|
|
||||||
|
证据链(全部为代码事实,可逐行核对):
|
||||||
|
|
||||||
|
| 位置 | 内容 |
|
||||||
|
|---|---|
|
||||||
|
| `Train/.../navigation/navigation_env_cfg.py:150-170` | 基类 `ActionsCfg.velocity_command`:`use_raw_actions=True`,`policy_scaling=[1.5, 1.0, 1.0]` |
|
||||||
|
| `Train/.../config/go2/navigation_env_cfg.py:128-146` | Go2 只覆写了 `low_level_position_action`、`low_level_velocity_action=None`、`low_level_policy_file`、`scale=[0.6, 0.3, 0.7]`;**没有覆写** `use_raw_actions` / `policy_scaling` |
|
||||||
|
| `Train/.../mdp/navigation/actions/navigation_se2_actions.py:166-171` | `if not use_raw_actions:` 才应用 `scale`;否则直接透传 |
|
||||||
|
| 同上 `:175` / `:188` | `tanh(raw)`,然后 `* policy_scaling` |
|
||||||
|
|
||||||
|
⇒ 策略在训练时看到的速度指令是 **`tanh(raw) * [1.5, 1.0, 1.0]`**,Go2 自己那句"shrink the SRU command range to what Go2 can actually track"(用 `scale` 收缩)从未生效。
|
||||||
|
|
||||||
|
⇒ 部署侧 `constants.py:22` 是 `[0.6, 0.3, 0.6]`,再经 `navigation_policy_node.py:552` 的 `LATERAL_VELOCITY_SCALE=0.6`,实际是 **[0.6, 0.18, 0.6]**:
|
||||||
|
|
||||||
|
| 轴 | 训练上限 | 部署上限 | 比值 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| vx | 1.5 m/s | 0.60 m/s | **0.40×** |
|
||||||
|
| vy | 1.0 m/s | 0.18 m/s | **0.18×** |
|
||||||
|
| ω | 1.0 rad/s | 0.60 rad/s | **0.60×** |
|
||||||
|
|
||||||
|
为什么这条比相机高度更要紧:16 维状态里同时有 `last_action`(原始动作,**未缩放**)和**实测速度**,策略内部拟合的是"我发这条指令、我大概会走多快"。指令被砍到 1/2.5 而实测速度跟着掉,这个"动作→下一时刻状态"的预测误差是**每一帧都存在**的;而相机偏 5 cm 只在特定几何下才显著。**零样本要是失败,第一个该排除的就是这条**,而它只要改 YAML。
|
||||||
|
|
||||||
|
> 待确认:以上是从仓库代码推的。若实际训练用了别的入口或 env 覆盖,请拿那次 run 的 TensorBoard `params` 或 checkpoint 同级 cfg 反驳。没有反驳之前,按 `[1.5,1.0,1.0]` 处理。
|
||||||
|
|
||||||
|
### 2.2 深度分辨率是 228×185,不是 600×960
|
||||||
|
|
||||||
|
- `odin_ros_driver` 的 `pcd2depth` 把 1600×1296 按 `scale=7.0` 除 → **228×185,32FC1,单位米**(`docs/DEPLOY_ROS2.md:910`、`HANDOVER_TEAM.md:309`)。
|
||||||
|
- `600×960` 只出现在 `model.py:167` 的 `np.random.rand(600, 960)` 预热里,是占位,不是契约。
|
||||||
|
- 训练侧 `ODIN1_CAMERA_CONFIG.resolution=(64, 40)`(`mdp/depth_utils/camera_config.py`),raycast **直接渲 64×40**,`fx_sim=29.49 / fy_sim=22.76` 恰好复现 94.67°×82.65°。
|
||||||
|
- 228/185 = 1.234,1600/1296 = 1.234 ⇒ 长宽比一致,所以 `resize → (40, 64)` 是对的(各向异性缩放,两侧一致)。测试因此覆盖 228×185、1600×1296 等,**不要**照 600×960 写死。
|
||||||
|
|
||||||
|
### 2.3 低通滤波的参数化方向相反
|
||||||
|
|
||||||
|
- 训练(`navigation_se2_actions.py:118-153`):`filtered = α·prev + (1-α)·new`,α 每 env 每维 **U(0.3, 0.7)**(`config/go2/...:172-180`)。
|
||||||
|
- 部署(`navigation_policy_node.py:555-556`):`out = c·new + (1-c)·prev`,`c=[0.9, 0.5, 0.5]`。
|
||||||
|
- 换到同一参数化下:部署 vx 等价 α=0.1,**落在训练范围之外**(方向是"更跟手",影响小于 §2.1,但会在转向/加速的相位上引入偏差)。
|
||||||
|
|
||||||
|
### 2.4 观测/动作契约(实测 ONNX 签名,非推断)
|
||||||
|
|
||||||
|
```
|
||||||
|
vae_encoder.onnx input [batch,1,40,64] float -> mu [batch,64,5,8] float
|
||||||
|
nav_policy.onnx obs [batch,2576] + h_in [1,batch,512] + c_in [1,batch,512]
|
||||||
|
-> actions [batch,3] + h_out + c_out (actions 为 pre-tanh)
|
||||||
|
```
|
||||||
|
`actions` 是 **pre-tanh** 原始动作,节点把它原样回填为 `last_action`(`navigation_policy_node.py:547`)——这与训练侧 `last_action` 取 raw action 一致,这一点是对的,不用改。
|
||||||
|
|
||||||
|
**副产品**:既然 scale 在 tanh 之外,**原始动作序列与增益无关**。所以一次推理就能同时给出全部候选增益下的指令序列(工具就是这么做的),四档增益的 `raw` 是完全相同的。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 零样本基线:怎么做、跑了什么、能证明什么
|
||||||
|
|
||||||
|
### 3.1 做法
|
||||||
|
|
||||||
|
```
|
||||||
|
rosbag2(含 /odin1/depth_img_competetion + /odin1/odometry_highfreq + /cmd_vel)
|
||||||
|
└─ export_bag_to_npz.py ──► run.npz
|
||||||
|
└─ sru_zeroshot_replay.py ──► 逐帧 raw / 四档 cmd / summary.json + CSV
|
||||||
|
```
|
||||||
|
|
||||||
|
回放严格按节点语义:深度按 `nan→0, >max→0, <min→0` 清洗(`<min` 是 `0.25`,`>max` 是 `10.0`,边界值保留);`last_action` 回填 raw;LSTM 首帧 reset;控制频率由深度帧决定(真机实测 1.4–1.7 Hz,不是 5 Hz,见 `DEPLOY_ROS2.md:1008`)。
|
||||||
|
|
||||||
|
### 3.2 本次实跑(合成走廊,**管线验证**,非行为证据)
|
||||||
|
|
||||||
|
解析式 raycast 走廊 + 一个 2.2–2.7 m 处的箱体障碍,按真实 Odin1 内参渲染到 228×185,相机高 0.50 m、俯仰 0、目标在前方 6 m、无动力学(机器人静止)。
|
||||||
|
|
||||||
|
| 视图 | \|vx\| | \|vy\| | \|ω\| | 步间 dRMS | 与目标夹角 cos>0.5 |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| deploy `[0.6,0.3,0.6]`(+vy×0.6) | 0.599 | 0.034 | 0.157 | 0.026 | 100% |
|
||||||
|
| deploy + 节点低通 | 0.597 | 0.033 | 0.151 | 0.014 | 100% |
|
||||||
|
| train `[1.5,1.0,1.0]` | 1.496 | 0.191 | 0.262 | 0.046 | 100% |
|
||||||
|
| train @ 底盘限幅 0.5 | 0.500 | 0.191 | 0.262 | 0.045 | 100% |
|
||||||
|
|
||||||
|
原始动作:`|raw|` 均值 `[3.63, 0.19, 0.27]`、最大 `[4.30, 0.27, 0.36]`,**vx 有 98.3% 的帧 `|raw|>3`**(`tanh` 已到 0.995),vy/ω 从未接近饱和。
|
||||||
|
|
||||||
|
相机高度扫描(同一场景,60 帧,无障碍走廊):
|
||||||
|
|
||||||
|
| 相机高 | 深度均值 | \|raw_vx\| max | vx 饱和率 | \|ω\| |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| 0.30 m | 2.55 m | 4.45 | 98% | 0.217 |
|
||||||
|
| 0.40 m | 2.67 m | 4.44 | 98% | 0.235 |
|
||||||
|
| 0.50 m | 2.78 m | 5.09 | 98% | 0.273 |
|
||||||
|
| 0.55 m | 2.83 m | 5.01 | 98% | 0.288 |
|
||||||
|
| 0.70 m | 2.96 m | 4.60 | 98% | 0.287 |
|
||||||
|
|
||||||
|
三个可用的观察:
|
||||||
|
|
||||||
|
1. **饱和是"按轴"的,不是全面的**。vx 恒定贴在网络输出的上限(raw>4 ≈ 0.999·scale),vy/ω 只用掉不到 1/3 的量程。所以"输出饱和"这句话必须带轴,否则会得到相反的操作建议。
|
||||||
|
2. **几何影响的是 ω 和 vy,不是 vx**。相机从 0.30 抬到 0.70 m,ω 从 0.217 变到 0.287(+32%),而 vx 始终顶格。带障碍 vs 无障碍(同为 0.50 m):ω 0.157 → 0.273,vx 不动。
|
||||||
|
3. **合成场景有断点,别过度解读**。带障碍时 0.50→0.55 m 的 ω 从 0.157 跳到 0.372,这是"箱顶 0.65 m 与相机光轴的关系翻转"造成遮挡轮廓突变,不是高度的光滑响应;无障碍组才呈现单调趋势。**这也说明:真实装车高度差 5 cm 就可能跨越某个几何临界点**,所以第七节要求"实测后写下来",不是形式主义。
|
||||||
|
|
||||||
|
### 3.3 判据(拿到真机录包后照这个填)
|
||||||
|
|
||||||
|
| 判据 | 计算 | 判"退化"的阈值(建议) | 说明 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 饱和率 | 每轴 `frac(|raw|>3)` | vx 长期 >0.9 **且**目标在 5 m 以外无障碍 | vx 顶格本身不一定是错(策略想巡航),要结合场景读 |
|
||||||
|
| 三轴全饱和 | 同上,三轴同时 >0.8 | 出现即退化 | 说明输入到了分布外,输出退化成常值 |
|
||||||
|
| 抖动 | `step_delta_rms / mean|v|` | >0.3 | 5 Hz 下相邻步变化超过均值的 30% |
|
||||||
|
| 方向一致性 | 平面指令与目标方位的 `cos` | `frac(cos<0) > 0.1` 即异常 | 目标在前方却持续倒车 = 训练里出现过的"倒走逃避相机"模式 |
|
||||||
|
| 复现性 | 同段跑两遍 | raw 必须逐帧一致 | 确定性检查,先排除工具自身问题 |
|
||||||
|
| **自遮挡** | `near_frac`(0.25–0.60 m 像素占比) | 稳定 >0.02 且集中在镜像边缘/顶部条带 | 车体支架/线束会被策略当成障碍,这是装车第 4 条的可量化形式 |
|
||||||
|
| **回放=真机** | `vs_recorded`(回放 deploy+lpf 与录到的 `/cmd_vel`) | `mean|d| < 1e-3` | 工具对真机的唯一实测校验;不吻合就先查工具,别查策略 |
|
||||||
|
|
||||||
|
### 3.4 这些数字能证明什么、不能证明什么
|
||||||
|
|
||||||
|
**能证明**:ONNX 前向链路正确(合成走廊 → 深度图肉眼可辨 → 输出连续、无 NaN、复现);深度缩放路径对 228×185 成立;策略确实读取了深度(几何一变,ω/vy 就变);`tanh*scale` 的边界行为符合规格;bag→npz→回放整条链路可用(12 帧合成 bag 往返一致)。
|
||||||
|
|
||||||
|
**不能证明**:能不能导航。原因很硬——**回放用的是录下来的状态**,没有动力学闭环;合成场景里机器人是静止的,`last_action` 的反馈回路是断的(60 帧里 deploy 的 ω 均值 0.157、末段 0.200,正是 LSTM 在开环里累积的结果)。真正的行为证据只有两种:实车闭环,或 Isaac 里闭环回放。
|
||||||
|
|
||||||
|
**当前最缺的一件事**:`/home/xie/bag_ws` 下 11 个包只录了 `/cmd_vel`、`/odin1/odometry_highfreq`、`/odin1/cloud_slam`,**没有一个包含深度**。所以"真实数据的零样本结论"这一项,本轮只能留空。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 要不要重训:判断与依据
|
||||||
|
|
||||||
|
### 4.1 四个分布偏移(按"可修性"排序,不按影响大小)
|
||||||
|
|
||||||
|
| # | 偏移 | 训练 | RC2027 部署 | 能否不训练就修 | 影响的证据 |
|
||||||
|
|---|---|---|---|---|---|
|
||||||
|
| 1 | **速度增益** | `[1.5,1.0,1.0]` | `[0.6,0.18,0.6]` | ✅ 改 YAML | `navigation_env_cfg.py:150-170` + `navigation_se2_actions.py:166-171` |
|
||||||
|
| 2 | 低通系数 | α∈U(0.3,0.7) | 等价 α=[0.1,0.5,0.5] | ✅ 改 YAML | 同上 `:118-153` |
|
||||||
|
| 3 | 相机安装几何 | 前 0.258 / 上 0.154 / 俯仰 0 / 车体原点系 | **未测** | ⚠️ 机械 0.5–1 天 | `config/go2/navigation_env_cfg.py:58-79` |
|
||||||
|
| 4 | 车体动力学 | 四足:启动滞后、步态起伏、机身俯仰 | 全向轮:响应快、近无侧滑、机身平稳 | ❌ 只能微调/重训 | 状态含 `last_action`+实测速度,动力学先验直接失效 |
|
||||||
|
|
||||||
|
第 1 条是本轮新增的,也是**唯一"改一行就见效"**的;第 4 条是根因,但它是 domain adaptation,不是新任务——观测接口(深度 40×64 + 16 维)与动作接口(SE2 速度)都不用动。
|
||||||
|
|
||||||
|
### 4.2 三档与触发条件
|
||||||
|
|
||||||
|
```
|
||||||
|
零样本(改 §4.1 第 1、2 条并行 A/B)
|
||||||
|
├─ 通过(§3.3 判据全绿 + 实车能到点)→ 停在这里,不训练
|
||||||
|
└─ 不通过
|
||||||
|
├─ 失败集中在"速度跟不上/冲过头/贴边"→ 微调(保留 VAE+LSTM,小规模 Cold-start)
|
||||||
|
└─ 失败形态是"根本不看深度/乱撞/原地打转"→ 需要从零重训(⚠️ 4060 不可行)
|
||||||
|
```
|
||||||
|
|
||||||
|
**微调的代价下限**:Isaac Sim 4.5 + IsaacLab 2.1.1,Docker 约 30 GB,至少 12 GB 显存。8 GB 上只能 `NUM_ENVS≤64` 跑少量迭代,属于"验证流程",不是"训出可用策略"。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 若重训/微调,改什么(对应原改动清单五条)
|
||||||
|
|
||||||
|
| # | 改动 | 工作量 | 现在能做吗 | 备注 |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| 1 | 新增 `ROBOT_CAMERA_CONFIGS["rc2027"]` + `initialize_depth_noise_generator` 复用同一份配置 | 0.5 h | 可先写配置草稿,**验证需 Isaac** | 深度噪声与编码器共用一份相机配置,改一处覆盖两处 |
|
||||||
|
| 2 | `velocity_command` 的增益改成真实限幅 | 2 行 | ✅ 现在就能(YAML) | 注意 `use_raw_actions=True` 下应改 `policy_scaling`,不是 `scale` —— 这正是 §2.1 的坑 |
|
||||||
|
| 3 | 低层动作分支:**新增"运动学底座"**,把 `[vx,vy,ω]` 直接写 root velocity | 1–2 天(新 ActionTerm) | ❌ 需 Isaac | 全向轮近无侧滑,运动学近似足够,**不需要导入整车 USD**;`low_level_velocity_action` 是给 B2W 轮腿的,不能直接用 |
|
||||||
|
| 4 | 车体尺寸/碰撞体(0.81×0.80,含裕度 0.99×0.98) | 1 天 | ❌ | 只在走完整 USD 路线时才需要 |
|
||||||
|
| 5 | 地形与奖励重估 | 视场景 | ❌ | 上游为长距离越野 + PureMaze 设计,结构化室内不要照抄 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 环境核对
|
||||||
|
|
||||||
|
| 项 | 要求 | 本机 | 结论 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| GPU | NVIDIA RTX,Isaac Sim 4.5 不支持 AMD/核显/VM | `lspci` = AMD Rembrandt (rev c9),无 `nvidia-smi` | ❌ **不能训练**,只能做离线回放/几何核对/实车 |
|
||||||
|
| 显存 | 上游最低 12 GB,推荐 24 GB+ | 4060 笔记本 8 GB | ❌ 低于最低要求;**不要**在 8 GB 上跑 1024 env × 30k iter |
|
||||||
|
| 8 GB 能做的 | Smoke(`NUM_ENVS=16~32, MAX_ITER≈100`)、流程验证、小规模微调(≤64 env) | — | ✅ 仅此三件 |
|
||||||
|
| 驱动 / 磁盘 / Docker / NGC 账号 | ≥570;≥80 GB;24.0+ + Container Toolkit;必需 | 未查 | 需用户自查(4060 机器) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 装车几何核对表(**需实测填数**)
|
||||||
|
|
||||||
|
训练规格(`config/go2/navigation_env_cfg.py:56-80`、`camera_config.py`):
|
||||||
|
|
||||||
|
| # | 项 | 训练值 | 实测 | 判定 |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| 1 | 俯仰角 | **0**(`rot=(1,0,0,0)`,无 pitch) | ______ ° | 偏离即改深度图统计,最不可补 |
|
||||||
|
| 2 | 上方高度(相对车体原点) | +0.154 m;相机离地量级 0.4–0.5 m(须实测 Go2 确认) | ______ m | 影响地面/障碍比例(§3.2 显示 0.30→0.70 m 使 ω +32%) |
|
||||||
|
| 3 | 前向偏移 | +0.258 m | ______ m | 太靠后车体会进视野 |
|
||||||
|
| 4 | 自身结构不入视野 | — | `near_frac =` ______ | >0.02 且集中在边缘/顶部条带即不合格 |
|
||||||
|
| 5 | 刚性固定 | — | 松动?______ | 输入含 `last_action`+速度,抖动破坏一致性 |
|
||||||
|
| 6 | **深度已去畸变** | 训练用理想针孔(忽略 k2..k7,`config/go2/navigation_env_cfg.py:75` 原话 "real-side pipeline must undistort before feeding the network") | 驱动输出已去畸变?______ | 配置注释明确要求真机先去畸变,最易漏 |
|
||||||
|
| 7 | 视场/分辨率 | 94.67°×82.65°,228×185 | ______ | 与 2.2 一致才谈得上零样本 |
|
||||||
|
|
||||||
|
第 1、6 条任一不满足,零样本的结论就不成立;第 4 条可以用 `near_frac` 直接量,不需要目测。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. 待确认前提(逐条,含"谁来确认")
|
||||||
|
|
||||||
|
| # | 前提 | 谁确认 | 影响 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 1 | 是否接受"4060 只做流程验证 + 小规模微调"这个上限 | **用户** | 决定第 4 节决策树是否允许走到"重训" |
|
||||||
|
| 2 | 实际训练 run 的 `use_raw_actions` / `policy_scaling`(反驳 §2.1 的唯一方式) | 训练侧同学 / TensorBoard params | 决定 §4.1 第 1 条的处置 |
|
||||||
|
| 3 | Odin1 实测安装高度/前向偏移/俯仰、是否已去畸变 | **实车现场** | 决定零样本能否成立(§7) |
|
||||||
|
| 4 | 场地形态(结构化室内?走廊宽度?) | 用户 | 决定第 5 节第 5 条要不要动 |
|
||||||
|
| 5 | 底盘真实限幅(`[0.5,0.5,0.5]` 是否为硬限) | 底盘方 | 决定增益 A/B 的上界 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. 下一步(按依赖顺序,非并行)
|
||||||
|
|
||||||
|
1. **装车 + 填 §7**(半天,不需要任何算力)——这是后面全部验证的前提。
|
||||||
|
2. **录一份 60–120 帧的深度包**(静止 + 低速直行各一段,同时录 `/cmd_vel`)。
|
||||||
|
3. 跑 `export_bag_to_npz.py` → `sru_zeroshot_replay.py --csv`,按 §3.3 填结论;先看 `vs_recorded` 是否 <1e-3(工具对不对),再看饱和/抖动/方向。
|
||||||
|
4. 若 §3.3 全绿 → 实车:`require_joystick:=false`、`policy_scale` 保持部署值,5 m 空地低速试;**再**做 §2.1 的增益 A/B(`[0.6,0.18,0.6]` vs `[1.5,1.0,1.0]` 并按 0.5 限幅),两轮各至少 5 段。
|
||||||
|
5. 只有在 4 明确失败、且失败形态属"动力学不匹配"时,才进入微调准备(需 ≥12 GB 机器)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 附录 A:复现命令
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 纯逻辑测试(不需要 ROS / onnxruntime / GPU)
|
||||||
|
/usr/bin/python3 -m pytest sru_ws/tools/tests -q # -> 32 passed
|
||||||
|
|
||||||
|
# 合成走廊(管线验证)
|
||||||
|
python3 sru_ws/tools/sru_zeroshot_replay.py --synthetic --steps 60 \
|
||||||
|
--cam-height 0.50 --out sru_ws/tools/_zs_out/sweep_h0.50 --csv --dump-depth-png
|
||||||
|
|
||||||
|
# 无车验证整条链路(需要 ROS)
|
||||||
|
source /opt/ros/humble/setup.bash
|
||||||
|
python3 sru_ws/tools/make_synthetic_bag.py /tmp/syn_bag --frames 12
|
||||||
|
python3 sru_ws/tools/export_bag_to_npz.py /tmp/syn_bag --out /tmp/syn.npz --goal 6,0,0
|
||||||
|
python3 sru_ws/tools/sru_zeroshot_replay.py --npz /tmp/syn.npz
|
||||||
|
|
||||||
|
# 真机录包 → 结论
|
||||||
|
python3 sru_ws/tools/export_bag_to_npz.py <bag_dir> --out run1.npz --max-frames 120
|
||||||
|
python3 sru_ws/tools/sru_zeroshot_replay.py --npz run1.npz --csv --out ./zs_run1
|
||||||
|
```
|
||||||
|
|
||||||
|
`--synthetic` 只能证明管线与几何敏感性;**行为结论必须来自 `--npz`**。
|
||||||
|
|
||||||
|
## 附录 B:本轮改动范围
|
||||||
|
|
||||||
|
- 新增:`sru_ws/tools/*`(5 个脚本/模块 + 测试)、`sru_ws/docs/SOLUTION_C_ASSESSMENT.md`(本文)。
|
||||||
|
- 未改动:`minco_ws/`(零改动)、`sru_ws/src/`(部署包一行未动,`policy_scale` 保持 `[0.6,0.3,0.6]`)、`nav2_ws/`(未 import、未复用)。
|
||||||
|
- 未提交:`reference/SRU-Odin/` 训练资源。
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Export a depth+odom recording into the ``.npz`` that ``sru_zeroshot_replay.py`` eats.
|
||||||
|
|
||||||
|
Run this ON THE MACHINE THAT HAS ROS 2 (``source /opt/ros/humble/setup.bash``),
|
||||||
|
then the replay script itself runs anywhere -- no ROS, no hardware.
|
||||||
|
|
||||||
|
# on the robot, after recording a bag:
|
||||||
|
python3 export_bag_to_npz.py /path/to/bag_dir --out run1.npz --max-frames 600
|
||||||
|
# anywhere:
|
||||||
|
python3 sru_zeroshot_replay.py --npz run1.npz --csv --out ./zs_run1
|
||||||
|
|
||||||
|
Why a separate script: rosbag2 message *deserialisation* needs the generated
|
||||||
|
ROS message types. Parsing CDR by hand would work but would silently diverge
|
||||||
|
from the real message definitions the first time a field is added upstream --
|
||||||
|
not a failure mode worth owning in the tool that is supposed to be the reference.
|
||||||
|
|
||||||
|
Timestamps: the Odin1 driver runs with ``use_host_ros_time: 0`` on this machine,
|
||||||
|
so stamps come from the DEVICE clock. That is fine here -- everything is
|
||||||
|
matched stamp-to-stamp, never against wall time.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
|
||||||
|
def _decode_image(msg):
|
||||||
|
"""sensor_msgs/Image -> (H, W) float32 metres. Only 32FC1 is meaningful here."""
|
||||||
|
if msg.encoding != "32FC1":
|
||||||
|
raise ValueError(f"unsupported depth encoding {msg.encoding!r} (want 32FC1)")
|
||||||
|
h, w = int(msg.height), int(msg.width)
|
||||||
|
buf = np.frombuffer(bytes(msg.data), dtype=np.float32)
|
||||||
|
if buf.size < h * w:
|
||||||
|
raise ValueError(f"short image buffer: {buf.size} < {h * w}")
|
||||||
|
row = int(msg.step) // 4 if msg.step else w
|
||||||
|
return buf[: h * row].reshape(h, row)[:, :w].copy()
|
||||||
|
|
||||||
|
|
||||||
|
def collect(bag_dir, depth_topic, odom_topic, goal_topic, max_frames, stride,
|
||||||
|
cmd_topic="/cmd_vel"):
|
||||||
|
from rclpy.serialization import deserialize_message
|
||||||
|
from rosbag2_py import (ConverterOptions, SequentialReader, StorageFilter,
|
||||||
|
StorageOptions)
|
||||||
|
from sensor_msgs.msg import Image
|
||||||
|
from nav_msgs.msg import Odometry
|
||||||
|
from geometry_msgs.msg import PoseStamped, Twist
|
||||||
|
|
||||||
|
reader = SequentialReader()
|
||||||
|
reader.open(
|
||||||
|
StorageOptions(uri=str(bag_dir), storage_id="sqlite3"),
|
||||||
|
ConverterOptions(input_serialization_format="cdr",
|
||||||
|
output_serialization_format="cdr"),
|
||||||
|
)
|
||||||
|
topics = {t.name: t.type for t in reader.get_all_topics_and_types()}
|
||||||
|
for required in (depth_topic, odom_topic):
|
||||||
|
if required not in topics:
|
||||||
|
raise SystemExit(f"{bag_dir}: no topic {required}. Present:\n "
|
||||||
|
+ "\n ".join(sorted(topics)))
|
||||||
|
wanted = [depth_topic, odom_topic]
|
||||||
|
if goal_topic and goal_topic in topics:
|
||||||
|
wanted.append(goal_topic)
|
||||||
|
if cmd_topic and cmd_topic in topics:
|
||||||
|
wanted.append(cmd_topic)
|
||||||
|
reader.set_filter(StorageFilter(topics=wanted))
|
||||||
|
|
||||||
|
depths, depth_stamps = [], []
|
||||||
|
odom = [] # (stamp, pos(3), quat(4), lin(3), ang(3))
|
||||||
|
goals = [] # (stamp, pos(3))
|
||||||
|
cmds = [] # (stamp, vx, vy, wz) as PUBLISHED by the node
|
||||||
|
seen = 0
|
||||||
|
|
||||||
|
while reader.has_next():
|
||||||
|
topic, raw, stamp = reader.read_next()
|
||||||
|
t = stamp * 1e-9
|
||||||
|
if topic == depth_topic:
|
||||||
|
take = (seen % stride == 0)
|
||||||
|
seen += 1
|
||||||
|
if not take:
|
||||||
|
continue
|
||||||
|
msg = deserialize_message(raw, Image)
|
||||||
|
try:
|
||||||
|
depths.append(_decode_image(msg))
|
||||||
|
except ValueError as exc:
|
||||||
|
raise SystemExit(f"{topic}: {exc}")
|
||||||
|
depth_stamps.append(t)
|
||||||
|
if max_frames and len(depths) >= max_frames:
|
||||||
|
break
|
||||||
|
elif topic == odom_topic:
|
||||||
|
msg = deserialize_message(raw, Odometry)
|
||||||
|
p, q = msg.pose.pose.position, msg.pose.pose.orientation
|
||||||
|
lt, at = msg.twist.twist.linear, msg.twist.twist.angular
|
||||||
|
odom.append((t, p.x, p.y, p.z, q.w, q.x, q.y, q.z,
|
||||||
|
lt.x, lt.y, lt.z, at.x, at.y, at.z))
|
||||||
|
elif cmd_topic and topic == cmd_topic:
|
||||||
|
msg = deserialize_message(raw, Twist)
|
||||||
|
cmds.append((t, msg.linear.x, msg.linear.y, msg.angular.z))
|
||||||
|
elif goal_topic and topic == goal_topic:
|
||||||
|
msg = deserialize_message(raw, PoseStamped)
|
||||||
|
goals.append((t, msg.pose.position.x, msg.pose.position.y,
|
||||||
|
msg.pose.position.z))
|
||||||
|
|
||||||
|
if not depths:
|
||||||
|
raise SystemExit("no depth frames decoded")
|
||||||
|
if not odom:
|
||||||
|
raise SystemExit("no odometry decoded")
|
||||||
|
|
||||||
|
odom = np.array(odom, dtype=np.float64)
|
||||||
|
odom = odom[np.argsort(odom[:, 0])]
|
||||||
|
odom_t = odom[:, 0]
|
||||||
|
|
||||||
|
n = len(depths)
|
||||||
|
depth_arr = np.stack(depths).astype(np.float32)
|
||||||
|
pos = np.zeros((n, 3)); quat = np.zeros((n, 4))
|
||||||
|
lin = np.zeros((n, 3)); ang = np.zeros((n, 3))
|
||||||
|
stamp_arr = np.array(depth_stamps, dtype=np.float64)
|
||||||
|
|
||||||
|
for k, t in enumerate(stamp_arr):
|
||||||
|
j = int(np.clip(np.searchsorted(odom_t, t), 0, len(odom_t) - 1))
|
||||||
|
if j > 0 and abs(odom_t[j - 1] - t) < abs(odom_t[j] - t):
|
||||||
|
j -= 1
|
||||||
|
if abs(odom_t[j] - t) > 0.1:
|
||||||
|
print(f"[export] warning: frame {k} has no odom within 100 ms "
|
||||||
|
f"(gap {abs(odom_t[j] - t) * 1e3:.0f} ms); reusing nearest")
|
||||||
|
pos[k] = odom[j, 1:4]
|
||||||
|
quat[k] = odom[j, 4:8]
|
||||||
|
lin[k] = odom[j, 8:11]
|
||||||
|
ang[k] = odom[j, 11:14]
|
||||||
|
|
||||||
|
cmd_rec = None
|
||||||
|
if cmds:
|
||||||
|
ca = np.array(cmds, dtype=np.float64)
|
||||||
|
ca = ca[np.argsort(ca[:, 0])]
|
||||||
|
cmd_rec = np.zeros((n, 3))
|
||||||
|
for k, t in enumerate(stamp_arr):
|
||||||
|
j = int(np.clip(np.searchsorted(ca[:, 0], t), 0, len(ca) - 1))
|
||||||
|
cmd_rec[k] = ca[j, 1:4]
|
||||||
|
|
||||||
|
if goals:
|
||||||
|
ga = np.array(goals, dtype=np.float64)
|
||||||
|
goal_arr = np.zeros((n, 3))
|
||||||
|
for k, t in enumerate(stamp_arr):
|
||||||
|
j = int(np.clip(np.searchsorted(ga[:, 0], t), 0, len(ga) - 1))
|
||||||
|
goal_arr[k] = ga[j, 1:4]
|
||||||
|
else:
|
||||||
|
goal_arr = None
|
||||||
|
|
||||||
|
out = dict(depth=depth_arr, stamps=stamp_arr, pos_w=pos, quat_wxyz=quat,
|
||||||
|
lin_vel_b=lin, ang_vel_b=ang, goal_w=goal_arr)
|
||||||
|
if cmd_rec is not None:
|
||||||
|
out["cmd_vel_rec"] = cmd_rec
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv=None):
|
||||||
|
ap = argparse.ArgumentParser(description=__doc__,
|
||||||
|
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||||
|
ap.add_argument("bag", type=Path)
|
||||||
|
ap.add_argument("--out", type=Path, required=True)
|
||||||
|
ap.add_argument("--depth-topic", default="/odin1/depth_img_competetion")
|
||||||
|
ap.add_argument("--odom-topic", default="/odin1/odometry_highfreq")
|
||||||
|
ap.add_argument("--goal-topic", default="/goal_pose")
|
||||||
|
ap.add_argument("--cmd-topic", default="/cmd_vel",
|
||||||
|
help="recorded node output, used to verify replay==on-robot")
|
||||||
|
ap.add_argument("--goal", default=None,
|
||||||
|
help="fixed goal 'x,y,z' in the odom frame (overrides --goal-topic)")
|
||||||
|
ap.add_argument("--max-frames", type=int, default=600)
|
||||||
|
ap.add_argument("--stride", type=int, default=1, help="keep every Nth depth frame")
|
||||||
|
args = ap.parse_args(argv)
|
||||||
|
|
||||||
|
data = collect(args.bag, args.depth_topic, args.odom_topic, args.goal_topic,
|
||||||
|
args.max_frames, max(1, args.stride), args.cmd_topic)
|
||||||
|
|
||||||
|
if args.goal:
|
||||||
|
g = np.array([float(v) for v in args.goal.split(",")], dtype=np.float64)
|
||||||
|
if g.size != 3:
|
||||||
|
raise SystemExit("--goal must be 'x,y,z'")
|
||||||
|
data["goal_w"] = np.tile(g, (len(data["depth"]), 1))
|
||||||
|
if data["goal_w"] is None:
|
||||||
|
# Fall back: 3 m straight ahead of the first pose. Recorded bags from
|
||||||
|
# manual driving usually carry no /goal_pose at all.
|
||||||
|
yaw = 2.0 * np.arctan2(data["quat_wxyz"][0, 3], data["quat_wxyz"][0, 0])
|
||||||
|
data["goal_w"] = np.tile(
|
||||||
|
data["pos_w"][0] + 3.0 * np.array([np.cos(yaw), np.sin(yaw), 0.0]),
|
||||||
|
(len(data["depth"]), 1))
|
||||||
|
print("[export] no /goal_pose in bag; using a synthetic goal 3 m ahead")
|
||||||
|
|
||||||
|
data["meta"] = str({"bag": str(args.bag), "depth_topic": args.depth_topic,
|
||||||
|
"odom_topic": args.odom_topic, "goal": args.goal})
|
||||||
|
args.out.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
np.savez_compressed(args.out, **data)
|
||||||
|
print(f"[export] {len(data['depth'])} frames "
|
||||||
|
f"{data['depth'].shape[1:]} -> {args.out} "
|
||||||
|
f"({args.out.stat().st_size / 1e6:.1f} MB)")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Write a small synthetic rosbag2 with depth + odometry.
|
||||||
|
|
||||||
|
Purpose: exercise the real recording -> export -> replay chain WITHOUT the
|
||||||
|
robot. The depth frames come from the same analytic corridor renderer the
|
||||||
|
replay script uses, so a round-trip through a bag must reproduce the same
|
||||||
|
command sequence (up to LSTM warm-up noise). If it does not, the export or the
|
||||||
|
message decoding is wrong -- which is exactly the bug you do not want to
|
||||||
|
discover for the first time on the car.
|
||||||
|
|
||||||
|
Needs ROS 2 (``source /opt/ros/humble/setup.bash``).
|
||||||
|
|
||||||
|
python3 make_synthetic_bag.py /tmp/syn_bag --frames 40
|
||||||
|
python3 export_bag_to_npz.py /tmp/syn_bag --out /tmp/syn.npz --goal 6,0,0
|
||||||
|
python3 sru_zeroshot_replay.py --npz /tmp/syn.npz
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
import sru_zeroshot_replay as replay
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv=None):
|
||||||
|
ap = argparse.ArgumentParser(description=__doc__,
|
||||||
|
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||||
|
ap.add_argument("bag", type=Path)
|
||||||
|
ap.add_argument("--frames", type=int, default=40)
|
||||||
|
ap.add_argument("--dt", type=float, default=0.2)
|
||||||
|
ap.add_argument("--depth-topic", default="/odin1/depth_img_competetion")
|
||||||
|
ap.add_argument("--odom-topic", default="/odin1/odometry_highfreq")
|
||||||
|
ap.add_argument("--goal-topic", default="/goal_pose")
|
||||||
|
ap.add_argument("--cmd-topic", default="/cmd_vel")
|
||||||
|
ap.add_argument("--goal", default="6,0,0")
|
||||||
|
ap.add_argument("--cam-height", type=float, default=0.5)
|
||||||
|
args = ap.parse_args(argv)
|
||||||
|
|
||||||
|
from rclpy.serialization import serialize_message
|
||||||
|
from rosbag2_py import (ConverterOptions, SequentialWriter, StorageOptions,
|
||||||
|
TopicMetadata)
|
||||||
|
from sensor_msgs.msg import Image
|
||||||
|
from nav_msgs.msg import Odometry
|
||||||
|
from geometry_msgs.msg import PoseStamped, Twist
|
||||||
|
|
||||||
|
if args.bag.exists():
|
||||||
|
raise SystemExit(f"{args.bag} exists; remove it first")
|
||||||
|
writer = SequentialWriter()
|
||||||
|
writer.open(
|
||||||
|
StorageOptions(uri=str(args.bag), storage_id="sqlite3"),
|
||||||
|
ConverterOptions(input_serialization_format="cdr",
|
||||||
|
output_serialization_format="cdr"),
|
||||||
|
)
|
||||||
|
for name, typ in ((args.depth_topic, "sensor_msgs/msg/Image"),
|
||||||
|
(args.odom_topic, "nav_msgs/msg/Odometry"),
|
||||||
|
(args.goal_topic, "geometry_msgs/msg/PoseStamped"),
|
||||||
|
(args.cmd_topic, "geometry_msgs/msg/Twist")):
|
||||||
|
writer.create_topic(TopicMetadata(name=name, type=typ,
|
||||||
|
serialization_format="cdr"))
|
||||||
|
|
||||||
|
depth = replay.render_corridor(cam_height=args.cam_height)
|
||||||
|
h, w = depth.shape
|
||||||
|
goal = [float(v) for v in args.goal.split(",")]
|
||||||
|
|
||||||
|
t0 = 1_700_000_000.0
|
||||||
|
n_odom = int(args.frames * args.dt * 50) # 50 Hz odom
|
||||||
|
for k in range(n_odom):
|
||||||
|
t = t0 + k / 50.0
|
||||||
|
msg = Odometry()
|
||||||
|
msg.header.stamp = rclpy_time(t)
|
||||||
|
msg.header.frame_id = "odom"
|
||||||
|
msg.child_frame_id = "base_link"
|
||||||
|
msg.pose.pose.orientation.w = 1.0
|
||||||
|
writer.write(args.odom_topic, serialize_message(msg), int(t * 1e9))
|
||||||
|
|
||||||
|
for k in range(args.frames):
|
||||||
|
t = t0 + k * args.dt
|
||||||
|
img = Image()
|
||||||
|
img.header.stamp = rclpy_time(t)
|
||||||
|
img.header.frame_id = "odin1_base_link"
|
||||||
|
img.height, img.width = h, w
|
||||||
|
img.encoding = "32FC1"
|
||||||
|
img.is_bigendian = 0
|
||||||
|
img.step = 4 * w
|
||||||
|
img.data = depth.astype(np.float32).tobytes()
|
||||||
|
writer.write(args.depth_topic, serialize_message(img), int(t * 1e9))
|
||||||
|
|
||||||
|
cmd = Twist() # a parked robot: the node would publish zeros
|
||||||
|
writer.write(args.cmd_topic, serialize_message(cmd), int(t * 1e9))
|
||||||
|
|
||||||
|
if k == 0:
|
||||||
|
pose = PoseStamped()
|
||||||
|
pose.header.stamp = rclpy_time(t)
|
||||||
|
pose.header.frame_id = "odom"
|
||||||
|
pose.pose.position.x, pose.pose.position.y, pose.pose.position.z = goal
|
||||||
|
pose.pose.orientation.w = 1.0
|
||||||
|
writer.write(args.goal_topic, serialize_message(pose), int(t * 1e9))
|
||||||
|
|
||||||
|
del writer
|
||||||
|
print(f"[synth-bag] {args.frames} depth frames ({h}x{w}) + {n_odom} odom -> {args.bag}")
|
||||||
|
|
||||||
|
|
||||||
|
def rclpy_time(seconds):
|
||||||
|
from builtin_interfaces.msg import Time
|
||||||
|
sec = int(seconds)
|
||||||
|
return Time(sec=sec, nanosec=int(round((seconds - sec) * 1e9)))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,283 @@
|
|||||||
|
"""Pure-NumPy mirror of the SRU-Go2 deployment-side preprocessing.
|
||||||
|
|
||||||
|
Why this file exists
|
||||||
|
--------------------
|
||||||
|
``sru_nav_ros2/model.py`` does the depth preprocessing, the target encoding,
|
||||||
|
the 16-dim state assembly and the ``tanh * POLICY_SCALE`` action transform. All
|
||||||
|
of it lives inside a class that imports ``onnxruntime`` and ``cv2``, so it
|
||||||
|
cannot be exercised on a machine without those packages, and cannot be unit
|
||||||
|
tested without an ONNX session.
|
||||||
|
|
||||||
|
This module restates *exactly the same arithmetic* with NumPy only:
|
||||||
|
|
||||||
|
depth (H, W, metres) -> sanitise -> bilinear resize -> [1,1,40,64]
|
||||||
|
target (world) -> body-frame unit vector + log(distance) -> 4 dims
|
||||||
|
16-dim state -> [lin(3) ang(3) gravity(3) last_action(3) target(4)]
|
||||||
|
raw action -> tanh(raw) * scale -> 3 dims
|
||||||
|
|
||||||
|
Everything here is a *specification*, not a second implementation: the numeric
|
||||||
|
constants are read from the deployment package's own ``constants.py`` whenever
|
||||||
|
that file is reachable, so the two can never silently disagree.
|
||||||
|
|
||||||
|
Two scales are defined on purpose. See ``POLICY_SCALE_TRAIN_GO2``.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import importlib.util
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Constants -- single source of truth is the deployment package
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
_PKG_CONSTANTS = (
|
||||||
|
Path(__file__).resolve().parents[1]
|
||||||
|
/ "src" / "sru_nav_ros2" / "sru_nav_ros2" / "constants.py"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _load_package_constants():
|
||||||
|
"""Import ``sru_nav_ros2/constants.py`` by path (it imports nothing itself)."""
|
||||||
|
if not _PKG_CONSTANTS.is_file():
|
||||||
|
return None
|
||||||
|
spec = importlib.util.spec_from_file_location("_sru_nav_constants", _PKG_CONSTANTS)
|
||||||
|
module = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(module) # type: ignore[union-attr]
|
||||||
|
return module
|
||||||
|
|
||||||
|
|
||||||
|
_CONST = _load_package_constants()
|
||||||
|
|
||||||
|
MIN_DEPTH = float(getattr(_CONST, "DEFAULT_MIN_DEPTH", 0.25))
|
||||||
|
MAX_DEPTH = float(getattr(_CONST, "DEFAULT_MAX_DEPTH", 10.0))
|
||||||
|
ARRIVE_GOAL_THRESHOLD = float(getattr(_CONST, "ARRIVE_GOAL_THRESHOLD", 0.75))
|
||||||
|
|
||||||
|
#: What the node actually multiplies ``tanh(raw)`` by (constants.py / sru_nav.yaml).
|
||||||
|
POLICY_SCALE_DEPLOY = tuple(getattr(_CONST, "POLICY_SCALE", (0.6, 0.3, 0.6)))
|
||||||
|
|
||||||
|
#: Extra damping the node applies to ``linear.y`` *after* the policy scale.
|
||||||
|
LATERAL_VELOCITY_SCALE = float(getattr(_CONST, "LATERAL_VELOCITY_SCALE", 0.6))
|
||||||
|
|
||||||
|
#: Node-side low-pass coefficients, convention ``out = c*new + (1-c)*prev``.
|
||||||
|
LOW_PASS_FILTER_COEF = tuple(getattr(_CONST, "LOW_PASS_FILTER_COEF", (0.9, 0.5, 0.5)))
|
||||||
|
|
||||||
|
#: The scale the Go2 policy was TRAINED with. Not a guess: the Go2 env config
|
||||||
|
#: inherits ``ActionsCfg.velocity_command`` from ``navigation_env_cfg.py`` with
|
||||||
|
#: ``use_raw_actions=True`` and ``policy_scaling=[1.5, 1.0, 1.0]``, and
|
||||||
|
#: ``navigation_se2_actions.py:166-171`` SKIPS ``cfg.scale`` entirely when
|
||||||
|
#: ``use_raw_actions`` is True. So Go2's own ``scale=[0.6, 0.3, 0.7]`` is dead
|
||||||
|
#: code and the trained command range is ``tanh(raw) * [1.5, 1.0, 1.0]``.
|
||||||
|
POLICY_SCALE_TRAIN_GO2 = (1.5, 1.0, 1.0)
|
||||||
|
|
||||||
|
#: Chassis speed envelope measured/declared for RC2027 (m/s, m/s, rad/s).
|
||||||
|
CHASSIS_LIMIT = (0.5, 0.5, 0.5)
|
||||||
|
|
||||||
|
# VAE input geometry. Fixed by the exported ONNX; must not be changed.
|
||||||
|
DEPTH_INPUT_SHAPE = (40, 64) # (H, W) fed to the encoder
|
||||||
|
DEPTH_EMBEDDING_DIM = 64 * 5 * 8 # 2560
|
||||||
|
STATE_DIM = 16
|
||||||
|
POLICY_INPUT_DIM = STATE_DIM + DEPTH_EMBEDDING_DIM # 2576
|
||||||
|
|
||||||
|
#: Field order of the 16-dim state vector, in the order the network sees it.
|
||||||
|
STATE_ORDER = (
|
||||||
|
"linear_vel.x", "linear_vel.y", "linear_vel.z",
|
||||||
|
"angular_vel.x", "angular_vel.y", "angular_vel.z",
|
||||||
|
"gravity.x", "gravity.y", "gravity.z",
|
||||||
|
"last_action.0", "last_action.1", "last_action.2",
|
||||||
|
"target.dir.x", "target.dir.y", "target.dir.z",
|
||||||
|
"target.log_dist",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 1. Depth
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def sanitize_depth(depth, min_depth=MIN_DEPTH, max_depth=MAX_DEPTH):
|
||||||
|
"""Apply the node's invalidation rules, in the node's order.
|
||||||
|
|
||||||
|
``depth_callback`` does::
|
||||||
|
|
||||||
|
np.nan_to_num(d, nan=0.0, posinf=max_depth*2.0, neginf=0.0)
|
||||||
|
d[d > max_depth] = 0.0
|
||||||
|
d[d < min_depth] = 0.0
|
||||||
|
|
||||||
|
Note ``posinf`` becomes ``2*max_depth`` and is then zeroed by the ``>`` test
|
||||||
|
-- so +inf, NaN and "too far" all collapse to the same 0 sentinel the VAE
|
||||||
|
was trained on. Anything inside ``[min_depth, max_depth]`` is kept as-is
|
||||||
|
(the VAE input is raw metres, there is no normalisation step).
|
||||||
|
"""
|
||||||
|
d = np.asarray(depth, dtype=np.float32)
|
||||||
|
if d.ndim != 2:
|
||||||
|
raise ValueError(f"depth must be 2-D (H, W), got shape {d.shape}")
|
||||||
|
d = np.nan_to_num(d, nan=0.0, posinf=max_depth * 2.0, neginf=0.0)
|
||||||
|
d = d.astype(np.float32, copy=True)
|
||||||
|
d[d > max_depth] = 0.0
|
||||||
|
d[d < min_depth] = 0.0
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def resize_bilinear(img, out_hw=DEPTH_INPUT_SHAPE):
|
||||||
|
"""Bilinear resize to ``(H, W)`` with OpenCV's half-pixel convention.
|
||||||
|
|
||||||
|
Equivalent to ``cv2.resize(img, (W, H), interpolation=cv2.INTER_LINEAR)``,
|
||||||
|
reimplemented so the module has no cv2 dependency. Edge coordinates are
|
||||||
|
clamped (edge replication), which is what cv2 does at the border.
|
||||||
|
"""
|
||||||
|
src = np.asarray(img, dtype=np.float32)
|
||||||
|
if src.ndim != 2:
|
||||||
|
raise ValueError(f"img must be 2-D (H, W), got shape {src.shape}")
|
||||||
|
out_h, out_w = int(out_hw[0]), int(out_hw[1])
|
||||||
|
src_h, src_w = src.shape
|
||||||
|
if src_h == out_h and src_w == out_w:
|
||||||
|
return src.copy()
|
||||||
|
|
||||||
|
def axis_coords(src_n, dst_n):
|
||||||
|
scale = src_n / dst_n
|
||||||
|
dst = np.arange(dst_n, dtype=np.float32)
|
||||||
|
src_pos = (dst + 0.5) * scale - 0.5
|
||||||
|
i0 = np.floor(src_pos).astype(np.int64)
|
||||||
|
w = (src_pos - i0).astype(np.float32)
|
||||||
|
i0 = np.clip(i0, 0, src_n - 1)
|
||||||
|
i1 = np.clip(i0 + 1, 0, src_n - 1)
|
||||||
|
return i0, i1, w
|
||||||
|
|
||||||
|
y0, y1, wy = axis_coords(src_h, out_h)
|
||||||
|
x0, x1, wx = axis_coords(src_w, out_w)
|
||||||
|
|
||||||
|
wy = wy[:, None]
|
||||||
|
wx = wx[None, :]
|
||||||
|
top = src[np.ix_(y0, x0)] * (1 - wx) + src[np.ix_(y0, x1)] * wx
|
||||||
|
bot = src[np.ix_(y1, x0)] * (1 - wx) + src[np.ix_(y1, x1)] * wx
|
||||||
|
return (top * (1 - wy) + bot * wy).astype(np.float32)
|
||||||
|
|
||||||
|
|
||||||
|
def depth_preprocess(depth, min_depth=MIN_DEPTH, max_depth=MAX_DEPTH):
|
||||||
|
"""``(H, W)`` metres -> ``[1, 1, 40, 64]`` encoder input.
|
||||||
|
|
||||||
|
The resize is anisotropic on purpose: the training-side raycast camera
|
||||||
|
renders a 64x40 pinhole view whose FOV equals the Odin1's (fx_sim=29.49,
|
||||||
|
fy_sim=22.76, see ``ODIN1_CAMERA_CONFIG``), and the real depth frame is
|
||||||
|
228x185 because the driver divides 1600x1296 by ``scale=7``. Both have the
|
||||||
|
same 1.234 aspect, so a plain resize preserves the FOV mapping.
|
||||||
|
"""
|
||||||
|
d = sanitize_depth(depth, min_depth, max_depth)
|
||||||
|
r = resize_bilinear(d, DEPTH_INPUT_SHAPE)
|
||||||
|
return r[np.newaxis, np.newaxis, :, :]
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 2. Target encoding
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def quat_to_rotmat(q_wxyz):
|
||||||
|
"""(w, x, y, z) -> 3x3 rotation matrix (world <- body)."""
|
||||||
|
w, x, y, z = (float(v) for v in q_wxyz)
|
||||||
|
n = w * w + x * x + y * y + z * z
|
||||||
|
if n < 1e-12:
|
||||||
|
return np.eye(3, dtype=np.float64)
|
||||||
|
s = 2.0 / n
|
||||||
|
return np.array(
|
||||||
|
[
|
||||||
|
[1 - s * (y * y + z * z), s * (x * y - z * w), s * (x * z + y * w)],
|
||||||
|
[s * (x * y + z * w), 1 - s * (x * x + z * z), s * (y * z - x * w)],
|
||||||
|
[s * (x * z - y * w), s * (y * z + x * w), 1 - s * (x * x + y * y)],
|
||||||
|
],
|
||||||
|
dtype=np.float64,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_target_position(target_pos_w, robot_pos_w, robot_orientation_w):
|
||||||
|
"""World goal -> ``[dir_x, dir_y, dir_z, log(dist + 1)]`` in the body frame.
|
||||||
|
|
||||||
|
Mirrors ``LearningModel.normalize_target_position``: rotate the delta into
|
||||||
|
the body frame, unit-normalise its direction, and take ``log(dist + 1)`` of
|
||||||
|
the *true* distance (``+1e-6`` guard added to the distance only).
|
||||||
|
"""
|
||||||
|
target = np.asarray(target_pos_w, dtype=np.float64).reshape(3)
|
||||||
|
robot = np.asarray(robot_pos_w, dtype=np.float64).reshape(3)
|
||||||
|
rot = quat_to_rotmat(robot_orientation_w)
|
||||||
|
delta_b = rot.T @ (target - robot)
|
||||||
|
|
||||||
|
dist = float(np.linalg.norm(delta_b) + 1e-6)
|
||||||
|
direction = delta_b / dist
|
||||||
|
log_dist = float(np.log(dist + 1.0))
|
||||||
|
out = np.concatenate([direction, [log_dist]]).astype(np.float32)
|
||||||
|
return out, delta_b.astype(np.float32)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 3. State vector
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def build_state_vector(linear_vel, angular_vel, gravity_vector, last_action, target_pos_log):
|
||||||
|
"""Assemble the 16-dim state in the network's expected order.
|
||||||
|
|
||||||
|
Order is load-bearing: a silent permutation here produces a policy that
|
||||||
|
still runs and still outputs plausible-looking velocities, which is exactly
|
||||||
|
the failure mode that is hardest to spot on a real robot.
|
||||||
|
"""
|
||||||
|
def _as3(v, name):
|
||||||
|
a = np.asarray(v, dtype=np.float32).reshape(-1)
|
||||||
|
if a.size != 3:
|
||||||
|
raise ValueError(f"{name} must have 3 components, got {a.size}")
|
||||||
|
return a
|
||||||
|
|
||||||
|
lin = _as3(linear_vel, "linear_vel")
|
||||||
|
ang = _as3(angular_vel, "angular_vel")
|
||||||
|
grav = _as3(gravity_vector, "gravity_vector")
|
||||||
|
act = _as3(last_action, "last_action")
|
||||||
|
tgt = np.asarray(target_pos_log, dtype=np.float32).reshape(-1)
|
||||||
|
if tgt.size != 4:
|
||||||
|
raise ValueError(f"target_pos_log must have 4 components, got {tgt.size}")
|
||||||
|
|
||||||
|
state = np.concatenate([lin, ang, grav, act, tgt]).astype(np.float32)
|
||||||
|
assert state.size == STATE_DIM, state.size
|
||||||
|
return state
|
||||||
|
|
||||||
|
|
||||||
|
def projected_gravity(robot_orientation_w, gravity_magnitude=9.81):
|
||||||
|
"""World -Z gravity expressed in the body frame, unit length."""
|
||||||
|
rot = quat_to_rotmat(robot_orientation_w)
|
||||||
|
g = rot.T @ np.array([0.0, 0.0, -float(gravity_magnitude)])
|
||||||
|
n = float(np.linalg.norm(g))
|
||||||
|
return (g / (n + 1e-6)).astype(np.float32)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 4. Action transform
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def apply_policy_scale(raw_action, scale=POLICY_SCALE_DEPLOY, clamp=None):
|
||||||
|
"""``cmd = tanh(raw) * scale``, optionally clamped afterwards.
|
||||||
|
|
||||||
|
``raw_action`` is the ONNX policy output *before* tanh (the deployment feeds
|
||||||
|
the same pre-tanh values back in as ``last_action``, which is what the
|
||||||
|
training-side ``last_action`` observation held as well -- raw actions are
|
||||||
|
stored in ``_raw_navigation_velocity_actions``).
|
||||||
|
|
||||||
|
``clamp`` is applied *after* scaling and is the only place a chassis limit
|
||||||
|
should be enforced: clamping raw or tanh'ed values instead would change the
|
||||||
|
shape of the mapping, not just its range.
|
||||||
|
"""
|
||||||
|
raw = np.asarray(raw_action, dtype=np.float32).reshape(-1)
|
||||||
|
s = np.asarray(scale, dtype=np.float32).reshape(-1)
|
||||||
|
if raw.size != 3 or s.size != 3:
|
||||||
|
raise ValueError(f"expected 3 components, got raw={raw.size}, scale={s.size}")
|
||||||
|
cmd = np.tanh(raw) * s
|
||||||
|
if clamp is not None:
|
||||||
|
cmd = np.clip(cmd, -np.asarray(clamp, dtype=np.float32),
|
||||||
|
np.asarray(clamp, dtype=np.float32))
|
||||||
|
return cmd.astype(np.float32)
|
||||||
|
|
||||||
|
|
||||||
|
def low_pass(prev_cmd, new_cmd, coef=LOW_PASS_FILTER_COEF):
|
||||||
|
"""Node-side smoothing: ``out = c*new + (1-c)*prev`` (NOT the training form).
|
||||||
|
|
||||||
|
Training used ``filtered = alpha*prev + (1-alpha)*new`` with
|
||||||
|
``alpha ~ U(0.3, 0.7)`` per env per dimension
|
||||||
|
(``randomize_low_pass_filter_alpha``), so the two conventions are mirrored:
|
||||||
|
deployment ``c=0.9`` for vx corresponds to training ``alpha=0.1``, which is
|
||||||
|
*outside* the trained range. Keep the two names distinct in any report.
|
||||||
|
"""
|
||||||
|
c = np.asarray(coef, dtype=np.float32).reshape(-1)
|
||||||
|
return (c * np.asarray(new_cmd, dtype=np.float32)
|
||||||
|
+ (1.0 - c) * np.asarray(prev_cmd, dtype=np.float32)).astype(np.float32)
|
||||||
@@ -0,0 +1,485 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Zero-shot baseline for the SRU-Go2 policy on a recorded Odin1 depth stream.
|
||||||
|
|
||||||
|
Pure offline: no ROS, no robot, no rclpy -- it imports the deployment package's
|
||||||
|
``LearningModel`` directly, so the arithmetic under test IS the deployment
|
||||||
|
arithmetic (same ONNX files, same preprocessing, same LSTM bookkeeping).
|
||||||
|
|
||||||
|
Two input modes
|
||||||
|
---------------
|
||||||
|
1. ``--npz`` a sequence exported from a rosbag by ``export_bag_to_npz.py``
|
||||||
|
(needs a bag that actually recorded ``/odin1/depth_img_competetion``)
|
||||||
|
2. ``--synthetic`` an analytically ray-cast corridor, rendered at the real
|
||||||
|
Odin1 intrinsics. This validates the *pipeline* and measures
|
||||||
|
the network's sensitivity to camera geometry. It is NOT
|
||||||
|
evidence that the policy navigates.
|
||||||
|
|
||||||
|
One inference pass, every gain reported
|
||||||
|
--------------------------------------
|
||||||
|
The policy's raw output does not depend on ``POLICY_SCALE`` at all: the scale is
|
||||||
|
applied after tanh, outside the network, and the value fed back as
|
||||||
|
``last_action`` is the pre-tanh raw action. So a single pass yields the full
|
||||||
|
command sequence for every candidate gain. This script therefore reports
|
||||||
|
|
||||||
|
deploy tanh(raw) * [0.6, 0.3, 0.6] (+ vy * 0.6) <- sru_nav.yaml today
|
||||||
|
train tanh(raw) * [1.5, 1.0, 1.0] <- what Go2 trained with
|
||||||
|
train@chassis the same, clamped to [0.5, 0.5, 0.5]
|
||||||
|
|
||||||
|
and, for the deploy view only, the node's own low-pass filtered command.
|
||||||
|
|
||||||
|
What replay can and cannot prove
|
||||||
|
--------------------------------
|
||||||
|
The state fed to the policy is the *recorded* state. If the bag was recorded
|
||||||
|
while another controller drove the robot, the policy is being evaluated
|
||||||
|
off-policy: a "sane" command sequence means the network is not degenerate, not
|
||||||
|
that the robot would have driven well. Only a real, closed-loop run proves the
|
||||||
|
latter.
|
||||||
|
|
||||||
|
Usage
|
||||||
|
-----
|
||||||
|
python sru_zeroshot_replay.py --synthetic --steps 80 --out /tmp/zs
|
||||||
|
python sru_zeroshot_replay.py --npz run1.npz --out /tmp/zs --csv
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import csv
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
HERE = Path(__file__).resolve().parent
|
||||||
|
SRC = HERE.parent / "src" / "sru_nav_ros2"
|
||||||
|
sys.path.insert(0, str(HERE))
|
||||||
|
sys.path.insert(0, str(SRC))
|
||||||
|
|
||||||
|
import sru_policy_math as pm # noqa: E402 (path setup must come first)
|
||||||
|
|
||||||
|
VAE_PATH = SRC / "models" / "vae_encoder.onnx"
|
||||||
|
POLICY_PATH = SRC / "models" / "nav_policy.onnx"
|
||||||
|
|
||||||
|
# Odin1 intrinsics at the native 1600x1296 frame (from the ROS calibration).
|
||||||
|
ODIN1_INTRINSICS = dict(fx=737.357, fy=737.292, cx=794.372, cy=666.259,
|
||||||
|
width=1600, height=1296)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Synthetic corridor
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def _intrinsics_for(height, width):
|
||||||
|
"""Scale the native intrinsics to a rendered frame size (FOV preserved)."""
|
||||||
|
sx = width / ODIN1_INTRINSICS["width"]
|
||||||
|
sy = height / ODIN1_INTRINSICS["height"]
|
||||||
|
return (ODIN1_INTRINSICS["fx"] * sx, ODIN1_INTRINSICS["fy"] * sy,
|
||||||
|
ODIN1_INTRINSICS["cx"] * sx, ODIN1_INTRINSICS["cy"] * sy)
|
||||||
|
|
||||||
|
|
||||||
|
def render_corridor(height=185, width=228, cam_height=0.5, corridor_half_width=1.2,
|
||||||
|
end_distance=8.0, obstacle=True, noise_sigma=0.01, seed=0):
|
||||||
|
"""Analytic ray cast of a straight corridor with an optional box obstacle.
|
||||||
|
|
||||||
|
Camera frame: x forward, y left, z up, mounted at ``cam_height`` above the
|
||||||
|
floor, looking horizontally (pitch = 0, i.e. the trained pose). Returns
|
||||||
|
``(H, W)`` depth in metres, with invalid/far returns set to 0 the way the
|
||||||
|
real pipeline does it.
|
||||||
|
"""
|
||||||
|
fx, fy, cx, cy = _intrinsics_for(height, width)
|
||||||
|
u = np.arange(width, dtype=np.float64)[None, :]
|
||||||
|
v = np.arange(height, dtype=np.float64)[:, None]
|
||||||
|
dx = np.ones((height, width))
|
||||||
|
dy = -(u - cx) / fx + np.zeros((height, 1))
|
||||||
|
dz = -(v - cy) / fy + np.zeros((1, width))
|
||||||
|
norm = np.sqrt(dx * dx + dy * dy + dz * dz)
|
||||||
|
dx, dy, dz = dx / norm, dy / norm, dz / norm
|
||||||
|
|
||||||
|
big = np.full((height, width), np.inf)
|
||||||
|
|
||||||
|
def hit_plane(t, mask):
|
||||||
|
return np.where(mask & (t > 0.05), t, big)
|
||||||
|
|
||||||
|
depth = big.copy()
|
||||||
|
|
||||||
|
# floor at z = 0 : cam_z + t*dz = 0
|
||||||
|
with np.errstate(divide="ignore", invalid="ignore"):
|
||||||
|
t = -cam_height / dz
|
||||||
|
depth = np.minimum(depth, hit_plane(t, dz < -1e-6))
|
||||||
|
|
||||||
|
# threshold: z = 0 cannot be reached by upward rays; nothing else needed.
|
||||||
|
|
||||||
|
# side walls y = +half (left) and y = -half (right)
|
||||||
|
with np.errstate(divide="ignore", invalid="ignore"):
|
||||||
|
t_left = corridor_half_width / dy
|
||||||
|
t_right = -corridor_half_width / dy
|
||||||
|
depth = np.minimum(depth, hit_plane(t_left, dy > 1e-6))
|
||||||
|
depth = np.minimum(depth, hit_plane(t_right, dy < -1e-6))
|
||||||
|
|
||||||
|
# end wall x = end_distance
|
||||||
|
depth = np.minimum(depth, hit_plane(end_distance / dx, dx > 1e-6))
|
||||||
|
|
||||||
|
# box obstacle, axis aligned: x in [2.2, 2.7], |y| <= 0.45, z in [0, 0.65]
|
||||||
|
if obstacle:
|
||||||
|
lo = np.array([2.2, -0.45, 0.0])
|
||||||
|
hi = np.array([2.7, 0.45, 0.65])
|
||||||
|
with np.errstate(divide="ignore", invalid="ignore"):
|
||||||
|
t1 = (lo[0] - 0.0) / dx
|
||||||
|
t2 = (hi[0] - 0.0) / dx
|
||||||
|
t3 = (lo[1] - 0.0) / dy
|
||||||
|
t4 = (hi[1] - 0.0) / dy
|
||||||
|
t5 = (lo[2] - cam_height) / dz
|
||||||
|
t6 = (hi[2] - cam_height) / dz
|
||||||
|
tmin = np.nanmax(np.stack([np.minimum(t1, t2), np.minimum(t3, t4),
|
||||||
|
np.minimum(t5, t6)]), axis=0)
|
||||||
|
tmax = np.nanmin(np.stack([np.maximum(t1, t2), np.maximum(t3, t4),
|
||||||
|
np.maximum(t5, t6)]), axis=0)
|
||||||
|
inside = (tmax >= tmin) & (tmax > 0.05)
|
||||||
|
depth = np.where(inside & (tmin > 0.05), np.minimum(depth, tmin), depth)
|
||||||
|
|
||||||
|
depth = np.where(np.isfinite(depth), depth, 0.0)
|
||||||
|
|
||||||
|
rng = np.random.default_rng(seed)
|
||||||
|
if noise_sigma > 0:
|
||||||
|
depth = depth + rng.normal(0.0, noise_sigma, size=depth.shape) * (depth > 0)
|
||||||
|
depth = np.clip(depth, 0.0, None).astype(np.float32)
|
||||||
|
return depth
|
||||||
|
|
||||||
|
|
||||||
|
def synthetic_sequence(steps=60, dt=0.2, goal_distance=6.0, **render_kwargs):
|
||||||
|
"""Open-loop sequence: robot frozen at the origin, pose/velocities zero.
|
||||||
|
|
||||||
|
Deliberately static. Without a simulator there is no way to advance the
|
||||||
|
robot consistently with the command, and faking an integrator would put
|
||||||
|
invented dynamics into the state vector -- the exact thing this baseline is
|
||||||
|
supposed to measure.
|
||||||
|
"""
|
||||||
|
depth = render_corridor(**render_kwargs)[None, ...]
|
||||||
|
n = int(steps)
|
||||||
|
depth_seq = np.repeat(depth, n, axis=0)
|
||||||
|
return dict(
|
||||||
|
depth=depth_seq,
|
||||||
|
stamps=np.arange(n, dtype=np.float64) * dt,
|
||||||
|
pos_w=np.zeros((n, 3)),
|
||||||
|
quat_wxyz=np.tile(np.array([1.0, 0.0, 0.0, 0.0]), (n, 1)),
|
||||||
|
lin_vel_b=np.zeros((n, 3)),
|
||||||
|
ang_vel_b=np.zeros((n, 3)),
|
||||||
|
goal_w=np.tile(np.array([goal_distance, 0.0, 0.0]), (n, 1)),
|
||||||
|
meta=json.dumps({"source": "synthetic_corridor", **render_kwargs}),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# I/O
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def load_npz(path):
|
||||||
|
with np.load(path, allow_pickle=False) as z:
|
||||||
|
data = {k: z[k] for k in z.files if k != "meta"}
|
||||||
|
data["meta"] = str(z["meta"]) if "meta" in z.files else "{}"
|
||||||
|
required = ("depth", "pos_w", "quat_wxyz", "goal_w")
|
||||||
|
missing = [k for k in required if k not in data]
|
||||||
|
if missing:
|
||||||
|
raise SystemExit(f"{path}: missing arrays {missing}")
|
||||||
|
n = len(data["depth"])
|
||||||
|
for key in ("lin_vel_b", "ang_vel_b"):
|
||||||
|
if key not in data:
|
||||||
|
data[key] = np.zeros((n, 3))
|
||||||
|
if "stamps" not in data:
|
||||||
|
data["stamps"] = np.arange(n, dtype=np.float64) * 0.2
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Inference
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def run_policy(data, vae_path, policy_path):
|
||||||
|
"""One pass with the deployment model; returns raw actions per frame."""
|
||||||
|
from sru_nav_ros2.model import LearningModel
|
||||||
|
|
||||||
|
model = LearningModel(str(vae_path), str(policy_path),
|
||||||
|
policy_scale=[1.0, 1.0, 1.0], intra_op_num_threads=4)
|
||||||
|
model.reset_hidden_state()
|
||||||
|
|
||||||
|
n = len(data["depth"])
|
||||||
|
raws = np.zeros((n, 3), dtype=np.float32)
|
||||||
|
targets_b = np.zeros((n, 3), dtype=np.float32)
|
||||||
|
depths_used = np.zeros((n, 2), dtype=np.float32) # valid frac, mean
|
||||||
|
near = np.zeros((n, 3), dtype=np.float32) # near_all, near_top, near_bot
|
||||||
|
last_action = [0.0, 0.0, 0.0]
|
||||||
|
|
||||||
|
for i in range(n):
|
||||||
|
depth = np.asarray(data["depth"][i], dtype=np.float32)
|
||||||
|
quat = data["quat_wxyz"][i]
|
||||||
|
goal = data["goal_w"][i] if data["goal_w"].ndim == 2 else data["goal_w"]
|
||||||
|
|
||||||
|
_, raw, target_vec_b = model.predict(
|
||||||
|
linear_vel=data["lin_vel_b"][i],
|
||||||
|
angular_vel=data["ang_vel_b"][i],
|
||||||
|
gravity_vector=pm.projected_gravity(quat),
|
||||||
|
last_action=last_action,
|
||||||
|
target_pos_w=goal,
|
||||||
|
robot_pos_w=data["pos_w"][i],
|
||||||
|
robot_orientation_w=quat,
|
||||||
|
depth_image=depth,
|
||||||
|
is_reset=(i == 0),
|
||||||
|
)
|
||||||
|
raws[i] = raw
|
||||||
|
targets_b[i] = target_vec_b
|
||||||
|
last_action = raw.tolist()
|
||||||
|
|
||||||
|
pre = pm.depth_preprocess(depth)[0, 0]
|
||||||
|
valid = pre > 0.0
|
||||||
|
depths_used[i] = (float(valid.mean()),
|
||||||
|
float(pre[valid].mean()) if valid.any() else 0.0)
|
||||||
|
# Near-field occupancy. A camera bracket / wiring loom / radar mount in
|
||||||
|
# view shows up here as a persistent cluster at 0.25-0.6 m, and the
|
||||||
|
# policy has no way to know it is structure rather than an obstacle --
|
||||||
|
# it will treat it as one. This is the quantitative form of
|
||||||
|
# "不能自我遮挡" in the mounting spec.
|
||||||
|
near_px = (pre >= pm.MIN_DEPTH) & (pre <= 0.6)
|
||||||
|
near[i] = (float(near_px.mean()),
|
||||||
|
float(near_px[:8].mean()),
|
||||||
|
float(near_px[-8:].mean()))
|
||||||
|
return raws, targets_b, depths_used, near
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Command views and statistics
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def command_views(raws):
|
||||||
|
"""Every candidate gain applied to the SAME raw sequence."""
|
||||||
|
views = {}
|
||||||
|
views["deploy"] = np.stack([
|
||||||
|
pm.apply_policy_scale(r, pm.POLICY_SCALE_DEPLOY) for r in raws
|
||||||
|
])
|
||||||
|
tmp = views["deploy"].copy()
|
||||||
|
tmp[:, 1] *= pm.LATERAL_VELOCITY_SCALE # node's extra vy damping
|
||||||
|
views["deploy"] = tmp
|
||||||
|
|
||||||
|
views["train"] = np.stack([
|
||||||
|
pm.apply_policy_scale(r, pm.POLICY_SCALE_TRAIN_GO2) for r in raws
|
||||||
|
])
|
||||||
|
views["train@chassis"] = np.stack([
|
||||||
|
pm.apply_policy_scale(r, pm.POLICY_SCALE_TRAIN_GO2, clamp=pm.CHASSIS_LIMIT)
|
||||||
|
for r in raws
|
||||||
|
])
|
||||||
|
|
||||||
|
lpf = np.zeros_like(views["deploy"])
|
||||||
|
prev = np.zeros(3, dtype=np.float32)
|
||||||
|
for i, cmd in enumerate(views["deploy"]):
|
||||||
|
prev = pm.low_pass(prev, cmd)
|
||||||
|
lpf[i] = prev
|
||||||
|
views["deploy+lpf"] = lpf
|
||||||
|
return views
|
||||||
|
|
||||||
|
|
||||||
|
def _sign_flips(x, eps=1e-3):
|
||||||
|
s = np.sign(np.where(np.abs(x) < eps, 0.0, x))
|
||||||
|
s = s[s != 0]
|
||||||
|
if s.size < 2:
|
||||||
|
return 0
|
||||||
|
return int(np.sum(s[1:] != s[:-1]))
|
||||||
|
|
||||||
|
|
||||||
|
def compare_with_recorded(cmds, recorded):
|
||||||
|
"""How far is the replay from what the node actually published on the robot?
|
||||||
|
|
||||||
|
This is the only check that validates the whole offline tool against reality:
|
||||||
|
the same depth frames must produce the same command the node produced when
|
||||||
|
they were recorded. Compared against ``deploy+lpf`` because that is what
|
||||||
|
the node publishes (policy scale -> lateral damping -> low-pass).
|
||||||
|
"""
|
||||||
|
rec = np.asarray(recorded, dtype=np.float32)[: len(cmds["deploy+lpf"])]
|
||||||
|
ref = cmds["deploy+lpf"][: len(rec)]
|
||||||
|
diff = ref - rec
|
||||||
|
return {
|
||||||
|
"frames_compared": int(len(rec)),
|
||||||
|
"mean_abs_diff": np.abs(diff).mean(axis=0).round(5).tolist(),
|
||||||
|
"max_abs_diff": np.abs(diff).max(axis=0).round(5).tolist(),
|
||||||
|
"corr_vx": float(np.corrcoef(ref[:, 0], rec[:, 0])[0, 1])
|
||||||
|
if len(rec) > 1 and np.std(rec[:, 0]) > 1e-6 and np.std(ref[:, 0]) > 1e-6 else None,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def summarize(raws, cmds, targets_b, depths_used, near, dt):
|
||||||
|
n = len(raws)
|
||||||
|
# ``targets_b`` is the body-frame *delta* vector (not yet normalised), so the
|
||||||
|
# distance is recoverable; only the bearing is used below.
|
||||||
|
out = {
|
||||||
|
"frames": int(n),
|
||||||
|
"duration_s": float(n * dt),
|
||||||
|
"depth": {
|
||||||
|
"valid_fraction_mean": float(np.mean(depths_used[:, 0])),
|
||||||
|
"valid_fraction_min": float(np.min(depths_used[:, 0])),
|
||||||
|
"mean_range_m": float(np.mean(depths_used[:, 1])),
|
||||||
|
"near_frac_mean": float(np.mean(near[:, 0])),
|
||||||
|
"near_frac_max": float(np.max(near[:, 0])),
|
||||||
|
"near_top_strip_mean": float(np.mean(near[:, 1])),
|
||||||
|
"near_bottom_strip_mean": float(np.mean(near[:, 2])),
|
||||||
|
},
|
||||||
|
"raw": {
|
||||||
|
"abs_mean": np.abs(raws).mean(axis=0).round(4).tolist(),
|
||||||
|
"abs_max": np.abs(raws).max(axis=0).round(4).tolist(),
|
||||||
|
"sat_gt2_frac": (np.abs(raws) > 2.0).mean(axis=0).round(4).tolist(),
|
||||||
|
"sat_gt3_frac": (np.abs(raws) > 3.0).mean(axis=0).round(4).tolist(),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for name, cmd in cmds.items():
|
||||||
|
planar = cmd[:, :2]
|
||||||
|
pnorm = np.linalg.norm(planar, axis=1)
|
||||||
|
tgt = targets_b[:, :2]
|
||||||
|
tnorm = np.linalg.norm(tgt, axis=1)
|
||||||
|
ok = (pnorm > 0.05) & (tnorm > 1e-6)
|
||||||
|
cos = np.zeros(len(cmd))
|
||||||
|
cos[ok] = (planar[ok] * tgt[ok]).sum(axis=1) / (pnorm[ok] * tnorm[ok])
|
||||||
|
|
||||||
|
tail = cmd[int(len(cmd) * 0.8):]
|
||||||
|
out[name] = {
|
||||||
|
"abs_mean": np.abs(cmd).mean(axis=0).round(4).tolist(),
|
||||||
|
"abs_mean_tail": np.abs(tail).mean(axis=0).round(4).tolist(),
|
||||||
|
"abs_max": np.abs(cmd).max(axis=0).round(4).tolist(),
|
||||||
|
"step_delta_rms": np.sqrt(np.mean(np.diff(cmd, axis=0) ** 2)).round(5)
|
||||||
|
if len(cmd) > 1 else 0.0,
|
||||||
|
"sign_flips_vx": _sign_flips(cmd[:, 0]),
|
||||||
|
"sign_flips_omega": _sign_flips(cmd[:, 2]),
|
||||||
|
"moving_frac": float(np.mean(pnorm > 0.05)),
|
||||||
|
"backward_frac": float(np.mean(cmd[:, 0] < -0.02)),
|
||||||
|
"goal_alignment": {
|
||||||
|
"mean_cos": float(np.mean(cos[ok])) if ok.any() else None,
|
||||||
|
"frac_cos_gt_0.5": float(np.mean(cos[ok] > 0.5)) if ok.any() else None,
|
||||||
|
"frac_cos_lt_0": float(np.mean(cos[ok] < 0.0)) if ok.any() else None,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Entry point
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def main(argv=None):
|
||||||
|
ap = argparse.ArgumentParser(description=__doc__,
|
||||||
|
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||||
|
src = ap.add_mutually_exclusive_group(required=True)
|
||||||
|
src.add_argument("--npz", type=Path, help="sequence exported from a rosbag")
|
||||||
|
src.add_argument("--synthetic", action="store_true",
|
||||||
|
help="analytically ray-cast corridor (pipeline test only)")
|
||||||
|
ap.add_argument("--steps", type=int, default=60)
|
||||||
|
ap.add_argument("--dt", type=float, default=0.2, help="frame period [s] (5 Hz)")
|
||||||
|
ap.add_argument("--goal-distance", type=float, default=6.0)
|
||||||
|
ap.add_argument("--cam-height", type=float, default=0.5,
|
||||||
|
help="synthetic camera height above the floor [m]")
|
||||||
|
ap.add_argument("--corridor-half-width", type=float, default=1.2)
|
||||||
|
ap.add_argument("--no-obstacle", action="store_true")
|
||||||
|
ap.add_argument("--out", type=Path, default=None, help="output directory")
|
||||||
|
ap.add_argument("--csv", action="store_true", help="also write per-frame CSV")
|
||||||
|
ap.add_argument("--dump-depth-png", action="store_true")
|
||||||
|
ap.add_argument("--vae", type=Path, default=VAE_PATH)
|
||||||
|
ap.add_argument("--policy", type=Path, default=POLICY_PATH)
|
||||||
|
args = ap.parse_args(argv)
|
||||||
|
|
||||||
|
if not args.vae.is_file() or not args.policy.is_file():
|
||||||
|
raise SystemExit(f"ONNX not found: {args.vae} / {args.policy}")
|
||||||
|
|
||||||
|
if args.synthetic:
|
||||||
|
data = synthetic_sequence(steps=args.steps, dt=args.dt,
|
||||||
|
goal_distance=args.goal_distance,
|
||||||
|
cam_height=args.cam_height,
|
||||||
|
corridor_half_width=args.corridor_half_width,
|
||||||
|
obstacle=not args.no_obstacle)
|
||||||
|
label = f"synthetic(h={args.cam_height}m,goal={args.goal_distance}m)"
|
||||||
|
else:
|
||||||
|
data = load_npz(args.npz)
|
||||||
|
label = str(args.npz)
|
||||||
|
|
||||||
|
print(f"[replay] source : {label}")
|
||||||
|
print(f"[replay] frames : {len(data['depth'])} "
|
||||||
|
f"depth {data['depth'].shape[1:]} ")
|
||||||
|
|
||||||
|
raws, targets_b, depths_used, near = run_policy(data, args.vae, args.policy)
|
||||||
|
cmds = command_views(raws)
|
||||||
|
summary = summarize(raws, cmds, targets_b, depths_used, near, args.dt)
|
||||||
|
if "cmd_vel_rec" in data:
|
||||||
|
summary["vs_recorded"] = compare_with_recorded(cmds, data["cmd_vel_rec"])
|
||||||
|
summary["source"] = label
|
||||||
|
summary["meta"] = data.get("meta", "{}")
|
||||||
|
|
||||||
|
print(f"[replay] depth valid : {summary['depth']['valid_fraction_mean']:.3f} "
|
||||||
|
f"(min {summary['depth']['valid_fraction_min']:.3f}), "
|
||||||
|
f"mean range {summary['depth']['mean_range_m']:.2f} m")
|
||||||
|
print(f"[replay] near-field : {summary['depth']['near_frac_mean']:.3f} of pixels "
|
||||||
|
f"in 0.25-0.60 m (max {summary['depth']['near_frac_max']:.3f}); "
|
||||||
|
f"top strip {summary['depth']['near_top_strip_mean']:.3f}, "
|
||||||
|
f"bottom strip {summary['depth']['near_bottom_strip_mean']:.3f}")
|
||||||
|
print(f"[replay] raw |max| : "
|
||||||
|
f"{['%.2f' % v for v in summary['raw']['abs_max']]}"
|
||||||
|
f" sat(|raw|>3): "
|
||||||
|
f"{['%.2f' % v for v in summary['raw']['sat_gt3_frac']]}")
|
||||||
|
print()
|
||||||
|
hdr = f"{'view':<14}{'|vx|':>7}{'|vy|':>7}{'|w|':>7}{'tail_w':>8}" \
|
||||||
|
f"{'dRMS':>8}{'flip_x':>7}{'mov%':>7}{'cos>0.5':>9}{'cos<0':>7}"
|
||||||
|
print(hdr)
|
||||||
|
print("-" * len(hdr))
|
||||||
|
for name in ("deploy", "deploy+lpf", "train", "train@chassis"):
|
||||||
|
s = summary[name]
|
||||||
|
ga = s["goal_alignment"]
|
||||||
|
cos_ok = "-" if ga["frac_cos_gt_0.5"] is None else f"{ga['frac_cos_gt_0.5']:.2f}"
|
||||||
|
cos_neg = "-" if ga["frac_cos_lt_0"] is None else f"{ga['frac_cos_lt_0']:.2f}"
|
||||||
|
print(f"{name:<14}"
|
||||||
|
f"{s['abs_mean'][0]:>7.3f}{s['abs_mean'][1]:>7.3f}"
|
||||||
|
f"{s['abs_mean'][2]:>7.3f}{s['abs_mean_tail'][2]:>8.3f}"
|
||||||
|
f"{s['step_delta_rms']:>8.4f}"
|
||||||
|
f"{s['sign_flips_vx']:>7d}{s['moving_frac'] * 100:>7.1f}"
|
||||||
|
f"{cos_ok:>9}{cos_neg:>7}")
|
||||||
|
|
||||||
|
if "vs_recorded" in summary:
|
||||||
|
vr = summary["vs_recorded"]
|
||||||
|
print()
|
||||||
|
print(f"[replay] vs recorded /cmd_vel ({vr['frames_compared']} frames): "
|
||||||
|
f"mean|d|={['%.4f' % v for v in vr['mean_abs_diff']]} "
|
||||||
|
f"max|d|={['%.4f' % v for v in vr['max_abs_diff']]} "
|
||||||
|
f"corr_vx={vr['corr_vx']}")
|
||||||
|
|
||||||
|
if args.out:
|
||||||
|
args.out.mkdir(parents=True, exist_ok=True)
|
||||||
|
(args.out / "summary.json").write_text(
|
||||||
|
json.dumps(summary, indent=2, default=float))
|
||||||
|
if args.csv:
|
||||||
|
with (args.out / "frames.csv").open("w", newline="") as fh:
|
||||||
|
w = csv.writer(fh)
|
||||||
|
w.writerow(["i", "t", "raw0", "raw1", "raw2",
|
||||||
|
"deploy_vx", "deploy_vy", "deploy_w",
|
||||||
|
"deploy_lpf_vx", "deploy_lpf_vy", "deploy_lpf_w",
|
||||||
|
"train_vx", "train_vy", "train_w",
|
||||||
|
"tgt_bx", "tgt_by", "tgt_bz",
|
||||||
|
"depth_valid", "depth_mean"])
|
||||||
|
for i in range(len(raws)):
|
||||||
|
w.writerow([i, f"{data['stamps'][i]:.3f}",
|
||||||
|
*[f"{v:.5f}" for v in raws[i]],
|
||||||
|
*[f"{v:.5f}" for v in cmds["deploy"][i]],
|
||||||
|
*[f"{v:.5f}" for v in cmds["deploy+lpf"][i]],
|
||||||
|
*[f"{v:.5f}" for v in cmds["train"][i]],
|
||||||
|
*[f"{v:.5f}" for v in targets_b[i]],
|
||||||
|
f"{depths_used[i, 0]:.4f}",
|
||||||
|
f"{depths_used[i, 1]:.4f}"])
|
||||||
|
if args.dump_depth_png:
|
||||||
|
try:
|
||||||
|
import cv2
|
||||||
|
pre = pm.depth_preprocess(np.asarray(data["depth"][0]))
|
||||||
|
img = pre[0, 0]
|
||||||
|
img = (255.0 * img / max(1e-6, img.max())).astype(np.uint8)
|
||||||
|
cv2.imwrite(str(args.out / "depth_40x64.png"),
|
||||||
|
cv2.resize(img, (320, 200), interpolation=cv2.INTER_NEAREST))
|
||||||
|
raw = np.asarray(data["depth"][0], dtype=np.float32)
|
||||||
|
raw = (255.0 * raw / max(1e-6, raw.max())).astype(np.uint8)
|
||||||
|
cv2.imwrite(str(args.out / "depth_native.png"), raw)
|
||||||
|
except ImportError:
|
||||||
|
print("[replay] cv2 unavailable; skipped depth png")
|
||||||
|
print(f"[replay] wrote : {args.out}")
|
||||||
|
|
||||||
|
return summary, cmds, raws
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
import pathlib
|
||||||
|
import sys
|
||||||
|
|
||||||
|
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||||
@@ -0,0 +1,264 @@
|
|||||||
|
"""Pure-logic tests for the SRU deployment contract.
|
||||||
|
|
||||||
|
Runs on a bare ``python3`` with numpy only -- no ROS, no onnxruntime, no cv2.
|
||||||
|
The cv2 parity check self-skips when OpenCV is absent.
|
||||||
|
|
||||||
|
python3 -m pytest sru_ws/tools/tests -q
|
||||||
|
"""
|
||||||
|
|
||||||
|
import math
|
||||||
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
import sru_policy_math as m
|
||||||
|
|
||||||
|
PKG = Path(__file__).resolve().parents[2] / "src" / "sru_nav_ros2" / "sru_nav_ros2"
|
||||||
|
MODEL_PY = PKG / "model.py"
|
||||||
|
CONSTANTS_PY = PKG / "constants.py"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Cross-check against the deployment package itself
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def _model_py_int(name, resolved=None):
|
||||||
|
"""Evaluate ``NAME = <int expression>`` straight out of model.py.
|
||||||
|
|
||||||
|
``POLICY_INPUT_DIM`` is written as ``STATE_DIM + DEPTH_EMBEDDING_DIM``, so the
|
||||||
|
right-hand side is evaluated with the previously resolved names in scope
|
||||||
|
instead of being assumed to be a literal.
|
||||||
|
"""
|
||||||
|
text = MODEL_PY.read_text()
|
||||||
|
hit = re.search(rf"^{name}\s*=\s*([^\n#]+)", text, re.MULTILINE)
|
||||||
|
assert hit, f"{name} not found in model.py"
|
||||||
|
return int(eval(hit.group(1).strip(), {"__builtins__": {}}, resolved or {}))
|
||||||
|
|
||||||
|
|
||||||
|
def test_architecture_constants_match_model_py():
|
||||||
|
resolved = {}
|
||||||
|
for name, expected in (("STATE_DIM", 16),
|
||||||
|
("DEPTH_EMBEDDING_DIM", 2560),
|
||||||
|
("LSTM_HIDDEN_DIM", 512),
|
||||||
|
("POLICY_INPUT_DIM", 2576)):
|
||||||
|
value = _model_py_int(name, resolved)
|
||||||
|
assert value == expected, f"model.py {name}={value}, expected {expected}"
|
||||||
|
resolved[name] = value
|
||||||
|
assert m.STATE_DIM == resolved["STATE_DIM"]
|
||||||
|
assert m.DEPTH_EMBEDDING_DIM == resolved["DEPTH_EMBEDDING_DIM"]
|
||||||
|
assert m.POLICY_INPUT_DIM == resolved["POLICY_INPUT_DIM"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_constants_are_read_from_the_package_not_duplicated():
|
||||||
|
# If this fails, sru_policy_math fell back to hard-coded defaults: the
|
||||||
|
# constants.py file moved or became unreadable, and the "single source of
|
||||||
|
# truth" guarantee is gone.
|
||||||
|
assert m._CONST is not None, f"could not import {CONSTANTS_PY}"
|
||||||
|
assert tuple(m.POLICY_SCALE_DEPLOY) == tuple(m._CONST.POLICY_SCALE)
|
||||||
|
|
||||||
|
|
||||||
|
def test_deploy_scale_is_not_the_training_scale():
|
||||||
|
"""Documents the mismatch that the zero-shot baseline must isolate."""
|
||||||
|
assert tuple(m.POLICY_SCALE_DEPLOY) == (0.6, 0.3, 0.6)
|
||||||
|
assert tuple(m.POLICY_SCALE_TRAIN_GO2) == (1.5, 1.0, 1.0)
|
||||||
|
for deploy, train in zip(m.POLICY_SCALE_DEPLOY, m.POLICY_SCALE_TRAIN_GO2):
|
||||||
|
assert deploy < train
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Depth preprocessing
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def test_sanitize_depth_thresholds_are_inclusive():
|
||||||
|
d = np.array([[0.0, 0.1, 0.2499, 0.25, 5.0, 10.0, 10.0001, np.inf, np.nan]],
|
||||||
|
dtype=np.float32)
|
||||||
|
out = m.sanitize_depth(d)
|
||||||
|
assert out.dtype == np.float32
|
||||||
|
assert out[0, 0] == 0.0 # 0 is below min -> invalid
|
||||||
|
assert out[0, 1] == 0.0 # below min
|
||||||
|
assert out[0, 2] == 0.0 # just below min
|
||||||
|
assert out[0, 3] == np.float32(0.25) # min_depth itself is KEPT
|
||||||
|
assert out[0, 4] == np.float32(5.0)
|
||||||
|
assert out[0, 5] == np.float32(10.0) # max_depth itself is KEPT
|
||||||
|
assert out[0, 6] == 0.0 # just above max
|
||||||
|
assert out[0, 7] == 0.0 # +inf -> 2*max -> zeroed
|
||||||
|
assert out[0, 8] == 0.0 # nan
|
||||||
|
|
||||||
|
|
||||||
|
def test_sanitize_depth_does_not_mutate_input():
|
||||||
|
d = np.array([[np.nan, 99.0]], dtype=np.float32)
|
||||||
|
_ = m.sanitize_depth(d)
|
||||||
|
assert np.isnan(d[0, 0]) and d[0, 1] == np.float32(99.0)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("shape", [(228, 185), (185, 228), (1296, 1600),
|
||||||
|
(960, 600), (600, 960), (40, 64), (1, 1)])
|
||||||
|
def test_depth_preprocess_shape_and_dtype(shape):
|
||||||
|
rng = np.random.default_rng(0)
|
||||||
|
depth = rng.uniform(0.0, 12.0, size=shape).astype(np.float32)
|
||||||
|
out = m.depth_preprocess(depth)
|
||||||
|
assert out.shape == (1, 1, 40, 64)
|
||||||
|
assert out.dtype == np.float32
|
||||||
|
assert np.isfinite(out).all()
|
||||||
|
assert out.min() >= 0.0 and out.max() <= m.MAX_DEPTH
|
||||||
|
|
||||||
|
|
||||||
|
def test_depth_preprocess_zeroes_invalid_before_resize():
|
||||||
|
"""A frame of NaN must become an all-zero tensor, not NaN."""
|
||||||
|
depth = np.full((185, 228), np.nan, dtype=np.float32)
|
||||||
|
out = m.depth_preprocess(depth)
|
||||||
|
assert out.shape == (1, 1, 40, 64)
|
||||||
|
assert np.all(out == 0.0)
|
||||||
|
|
||||||
|
|
||||||
|
def test_resize_bilinear_preserves_constant_image():
|
||||||
|
depth = np.full((185, 228), 3.5, dtype=np.float32)
|
||||||
|
out = m.resize_bilinear(depth)
|
||||||
|
assert np.allclose(out, 3.5, atol=1e-5)
|
||||||
|
|
||||||
|
|
||||||
|
def test_resize_bilinear_identity_when_size_matches():
|
||||||
|
depth = np.arange(40 * 64, dtype=np.float32).reshape(40, 64)
|
||||||
|
out = m.resize_bilinear(depth)
|
||||||
|
assert np.array_equal(out, depth)
|
||||||
|
|
||||||
|
|
||||||
|
def test_resize_bilinear_matches_cv2():
|
||||||
|
cv2 = pytest.importorskip("cv2")
|
||||||
|
rng = np.random.default_rng(7)
|
||||||
|
depth = rng.uniform(0.3, 9.0, size=(185, 228)).astype(np.float32)
|
||||||
|
ref = cv2.resize(depth, (64, 40), interpolation=cv2.INTER_LINEAR)
|
||||||
|
got = m.resize_bilinear(depth)
|
||||||
|
assert np.allclose(got, ref, rtol=1e-4, atol=1e-3), np.abs(got - ref).max()
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Target encoding
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def test_state_order_declaration():
|
||||||
|
assert len(m.STATE_ORDER) == m.STATE_DIM == 16
|
||||||
|
assert m.STATE_ORDER[0:3] == ("linear_vel.x", "linear_vel.y", "linear_vel.z")
|
||||||
|
assert m.STATE_ORDER[3:6] == ("angular_vel.x", "angular_vel.y", "angular_vel.z")
|
||||||
|
assert m.STATE_ORDER[6:9] == ("gravity.x", "gravity.y", "gravity.z")
|
||||||
|
assert m.STATE_ORDER[9:12] == ("last_action.0", "last_action.1", "last_action.2")
|
||||||
|
assert m.STATE_ORDER[12] == "target.dir.x"
|
||||||
|
assert m.STATE_ORDER[15] == "target.log_dist"
|
||||||
|
|
||||||
|
|
||||||
|
def test_target_encoding_straight_ahead():
|
||||||
|
tgt, delta_b = m.normalize_target_position([1.0, 0.0, 0.0], [0.0, 0.0, 0.0],
|
||||||
|
[1.0, 0.0, 0.0, 0.0])
|
||||||
|
assert np.allclose(tgt[:3], [1.0, 0.0, 0.0], atol=1e-6)
|
||||||
|
assert math.isclose(float(tgt[3]), math.log(2.0), rel_tol=1e-6)
|
||||||
|
assert tgt.shape == (4,)
|
||||||
|
assert delta_b.shape == (3,)
|
||||||
|
|
||||||
|
|
||||||
|
def test_target_encoding_behind_robot():
|
||||||
|
tgt, _ = m.normalize_target_position([-2.0, 0.0, 0.0], [0.0, 0.0, 0.0],
|
||||||
|
[1.0, 0.0, 0.0, 0.0])
|
||||||
|
assert np.allclose(tgt[:3], [-1.0, 0.0, 0.0], atol=1e-6)
|
||||||
|
|
||||||
|
|
||||||
|
def test_target_encoding_direction_is_unit_length():
|
||||||
|
tgt, _ = m.normalize_target_position([3.0, -4.0, 0.5], [1.0, 1.0, 0.0],
|
||||||
|
[1.0, 0.0, 0.0, 0.0])
|
||||||
|
assert math.isclose(float(np.linalg.norm(tgt[:3])), 1.0, rel_tol=1e-5)
|
||||||
|
|
||||||
|
|
||||||
|
def test_target_encoding_invariant_to_global_yaw():
|
||||||
|
"""Rotating robot AND goal together must not change the body-frame vector."""
|
||||||
|
half = math.sqrt(0.5) # yaw = +90 deg -> q = (cos45, 0, 0, sin45)
|
||||||
|
goal = np.array([2.0, 1.0, 0.0])
|
||||||
|
rot_z90 = np.array([[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]])
|
||||||
|
a, _ = m.normalize_target_position(goal, [0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0])
|
||||||
|
b, _ = m.normalize_target_position(rot_z90 @ goal, [0.0, 0.0, 0.0],
|
||||||
|
[half, 0.0, 0.0, half])
|
||||||
|
assert np.allclose(a, b, atol=1e-5)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# State vector assembly
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def test_build_state_vector_order_is_exact():
|
||||||
|
state = m.build_state_vector([1, 2, 3], [4, 5, 6], [7, 8, 9],
|
||||||
|
[10, 11, 12], [13, 14, 15, 16])
|
||||||
|
assert state.shape == (16,)
|
||||||
|
assert state.dtype == np.float32
|
||||||
|
assert np.array_equal(state, np.arange(1, 17, dtype=np.float32))
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_state_vector_rejects_swapped_arity():
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
m.build_state_vector([1, 2], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15, 16])
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
m.build_state_vector([1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15])
|
||||||
|
|
||||||
|
|
||||||
|
def test_state_plus_embedding_is_the_obs_width():
|
||||||
|
state = m.build_state_vector([0] * 3, [0] * 3, [0, 0, -1], [0] * 3, [0] * 4)
|
||||||
|
obs = np.concatenate([state, np.zeros(m.DEPTH_EMBEDDING_DIM, dtype=np.float32)])
|
||||||
|
assert obs.shape == (2576,)
|
||||||
|
assert obs.shape == (m.POLICY_INPUT_DIM,)
|
||||||
|
|
||||||
|
|
||||||
|
def test_projected_gravity_flat_robot_is_minus_z():
|
||||||
|
g = m.projected_gravity([1.0, 0.0, 0.0, 0.0])
|
||||||
|
assert np.allclose(g, [0.0, 0.0, -1.0], atol=1e-6)
|
||||||
|
assert math.isclose(float(np.linalg.norm(g)), 1.0, rel_tol=1e-6)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Action transform -- tanh * POLICY_SCALE
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def test_policy_scale_output_is_bounded_by_scale():
|
||||||
|
scale = np.array(m.POLICY_SCALE_DEPLOY, dtype=np.float32)
|
||||||
|
for raw in ([0.0, 0.0, 0.0], [1e3, -1e3, 1e3], [-1e3, 1e3, -1e3]):
|
||||||
|
cmd = m.apply_policy_scale(raw, scale)
|
||||||
|
assert np.all(np.abs(cmd) <= scale + 1e-6)
|
||||||
|
|
||||||
|
|
||||||
|
def test_policy_scale_zero_raw_is_zero_cmd():
|
||||||
|
assert np.allclose(m.apply_policy_scale([0.0, 0.0, 0.0]), 0.0, atol=1e-7)
|
||||||
|
|
||||||
|
|
||||||
|
def test_policy_scale_is_monotonic_and_correct_at_one():
|
||||||
|
scale = (1.0, 1.0, 1.0)
|
||||||
|
prev = -1.0
|
||||||
|
for raw in np.linspace(-3, 3, 25):
|
||||||
|
v = float(m.apply_policy_scale([raw, 0, 0], scale)[0])
|
||||||
|
assert v > prev
|
||||||
|
prev = v
|
||||||
|
assert math.isclose(float(m.apply_policy_scale([1.0, 0, 0], scale)[0]),
|
||||||
|
math.tanh(1.0), rel_tol=1e-6)
|
||||||
|
|
||||||
|
|
||||||
|
def test_policy_scale_saturation_point_depends_only_on_raw():
|
||||||
|
"""tanh saturates on raw, so |raw|>3 is already 99.5% of full scale."""
|
||||||
|
full = m.apply_policy_scale([50.0, 50.0, 50.0])
|
||||||
|
assert np.allclose(full, m.POLICY_SCALE_DEPLOY, atol=1e-5)
|
||||||
|
|
||||||
|
|
||||||
|
def test_policy_scale_clamp_applies_after_scaling():
|
||||||
|
cmd = m.apply_policy_scale([5.0, 5.0, 5.0], m.POLICY_SCALE_TRAIN_GO2,
|
||||||
|
clamp=m.CHASSIS_LIMIT)
|
||||||
|
assert np.allclose(cmd, m.CHASSIS_LIMIT, atol=1e-6)
|
||||||
|
|
||||||
|
|
||||||
|
def test_deploy_vs_train_effective_ratio():
|
||||||
|
"""0.40x / 0.18x / 0.60x -- the single cheapest thing to rule out first."""
|
||||||
|
raw = [1.0, 1.0, 1.0]
|
||||||
|
deploy = m.apply_policy_scale(raw, m.POLICY_SCALE_DEPLOY)
|
||||||
|
deploy[1] *= m.LATERAL_VELOCITY_SCALE # node's extra vy damping
|
||||||
|
train = m.apply_policy_scale(raw, m.POLICY_SCALE_TRAIN_GO2)
|
||||||
|
ratio = deploy / train
|
||||||
|
assert np.allclose(ratio, [0.40, 0.18, 0.60], atol=1e-5)
|
||||||
|
|
||||||
|
|
||||||
|
def test_low_pass_convention_is_the_mirror_of_training():
|
||||||
|
prev = np.zeros(3, dtype=np.float32)
|
||||||
|
new = np.ones(3, dtype=np.float32)
|
||||||
|
out = m.low_pass(prev, new, coef=(0.9, 0.5, 0.5))
|
||||||
|
assert np.allclose(out, [0.9, 0.5, 0.5], atol=1e-6)
|
||||||
|
# equivalent training-side alpha = 1 - c
|
||||||
|
assert np.allclose(1.0 - np.array((0.9, 0.5, 0.5)), [0.1, 0.5, 0.5], atol=1e-9)
|
||||||
Reference in New Issue
Block a user