init: RoboCon 2027 BR 上位机 sru_ws(仅源码/文档/模型;排除构建产物与 venv)
- src/: sru_nav_ros2 (策略) + odin_ros_driver (0.14.x, ament ROS2) + techx_r2_chassis_control (串口桥) - 修复: 驱动目录此前是悬空 gitlink,clone 后为空 -> 现改为普通文件(55 个) - 排除: build/ install/ log/ venv/ .Trash-0/ __pycache__ 及驱动 map/log 运行期产物 - docs/: USAGE / PORT_NOTES / HANDOVER / ROS2_PORT_PLAN / 协议核查报告
This commit is contained in:
@@ -0,0 +1,378 @@
|
||||
# 交接文档 —— SRU-Odin ROS1 → ROS2 Humble 移植
|
||||
|
||||
> **交接方**:Windows 侧会话(已完成仓库全面调研与方案设计)
|
||||
> **接手方**:Ubuntu 22.04 侧 WorkBuddy
|
||||
> **配套文件**:`PROMPT_ROS2_UBUNTU.md`(贴给 AI 的提示词)、`ROS2_PORT_PLAN.md`(详细迁移面与 API 对照表)
|
||||
> **日期**:2026-09-22
|
||||
|
||||
---
|
||||
|
||||
## 1. 怎么用这份交接包
|
||||
|
||||
三步:
|
||||
|
||||
1. **拷**:把 `handover/` 整个文件夹拷到优盘,带到 Ubuntu 那边的电脑
|
||||
2. **贴**:在 Ubuntu 侧 WorkBuddy 里,把 `PROMPT_ROS2_UBUNTU.md` 里「提示词开始 / 结束」之间的全文粘进对话框,回车
|
||||
3. **答**:AI 会先汇报环境检查结果并向你提问,按 `HANDOVER.md` 第 4、6、7 节的内容回答即可
|
||||
|
||||
建议把 `HANDOVER.md` 和 `ROS2_PORT_PLAN.md` 也放到 Ubuntu 侧的 `~/sru_ws/reference/` 下,方便 AI 随时读。
|
||||
|
||||
---
|
||||
|
||||
## 2. 优盘要拷什么
|
||||
|
||||
### 必需(共 3 个 md,体积极小)
|
||||
|
||||
| 文件 | 作用 |
|
||||
|---|---|
|
||||
| `handover/PROMPT_ROS2_UBUNTU.md` | 贴给 Ubuntu 侧 AI 的提示词 |
|
||||
| `handover/HANDOVER.md` | 本文件,人读的交接说明 |
|
||||
| `handover/ROS2_PORT_PLAN.md` | 详细迁移面、ROS1→ROS2 API 逐点对照表(AI 需要它) |
|
||||
|
||||
### 源码:**不用拷,直接 clone 更好**
|
||||
|
||||
我已核实:源仓库的 `.gitignore` 里 `*.onnx` 是**被注释掉的**,两个模型都已入库;且本地工作区干净,`6a81ba7` 就是上游原样提交。
|
||||
|
||||
所以 Ubuntu 侧只要一条命令就能拿到**逐字节一致**的源码,包括 28 MB 的模型:
|
||||
|
||||
```bash
|
||||
mkdir -p ~/sru_ws/src ~/sru_ws/reference
|
||||
cd ~/sru_ws/reference
|
||||
git clone https://github.com/ManifoldTechLtd/SRU-Odin.git
|
||||
cd SRU-Odin
|
||||
git checkout 6a81ba77f46d4ab010d3d3354d54ec25ef730955
|
||||
```
|
||||
|
||||
### 无网络时的兜底:拷 `Deployment/` 目录(32 MB)
|
||||
|
||||
若 Ubuntu 侧连不上 GitHub,把 Windows 这边这个目录拷到优盘:
|
||||
|
||||
```
|
||||
F:\RC2027\odin1_SRU\SRU-Odin-orig\SRU-Odin\Deployment\
|
||||
```
|
||||
|
||||
→ 放到 Ubuntu 的 `~/sru_ws/reference/SRU-Odin/Deployment/`。
|
||||
|
||||
**只拷 `Deployment/` 就够了**(32 MB):A/B/C 三类要处理的文件、两个 ONNX 模型、config、launch、docs 全在里面。`Train/` 是 Isaac Sim 训练环境,与本次部署迁移无关,不用考。
|
||||
|
||||
### 校验拿到的源码是否完整
|
||||
|
||||
```bash
|
||||
cd ~/sru_ws/reference/SRU-Odin/Deployment
|
||||
ls -l models/ # 期望 20971407 和 7054074 字节
|
||||
sha256sum models/vae_encoder.onnx
|
||||
# 期望 de70c217c91ef916b877d81c7a134e00d861d6b282f7de2489984b1818596cd0
|
||||
sha256sum models/nav_policy.onnx
|
||||
# 期望 f1410cb77ee7897874d69ee7ba4c4814c2388810367b1ae4627bb3c12b523f1b
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Ubuntu 侧环境准备
|
||||
|
||||
### 3.1 装 ROS2 与系统依赖
|
||||
|
||||
```bash
|
||||
sudo apt update
|
||||
sudo apt install -y \
|
||||
ros-humble-desktop \
|
||||
ros-humble-cv-bridge \
|
||||
ros-humble-joy \
|
||||
ros-humble-tf2-ros \
|
||||
ros-humble-rviz2 \
|
||||
python3-colcon-common-extensions
|
||||
|
||||
source /opt/ros/humble/setup.bash
|
||||
```
|
||||
|
||||
### 3.2 装 Python 依赖
|
||||
|
||||
```bash
|
||||
pip3 install --user onnxruntime numpy scipy pyyaml
|
||||
```
|
||||
|
||||
说明:
|
||||
- **`scipy` 必需** —— 主节点用 `from scipy.spatial.transform import Rotation as R` 做速度坐标系反旋
|
||||
- **`pyyaml` 必需** —— `waypoint_runner` 读航点文件
|
||||
- **不要 pip 装 `opencv-python`** —— `cv_bridge` 依赖系统的 `python3-opencv`,再装 pip 版会出现 libopencv 双版本冲突(症状是 import cv_bridge 报符号错误)。`model.py` 用的 `cv2.resize` 由系统 opencv 提供就够
|
||||
- **不要装 conda** —— ROS2 用系统 python3.10 即可,ROS1 那套 conda 是历史包袱(见第 5.3 节)
|
||||
|
||||
若 pip 报 `error: externally-managed-environment`,改用虚拟环境(但必须带 `--system-site-packages`,否则 import 不到 rclpy / cv_bridge):
|
||||
|
||||
```bash
|
||||
python3 -m venv --system-site-packages ~/sru_ws/venv
|
||||
source ~/sru_ws/venv/bin/activate
|
||||
pip install onnxruntime numpy scipy pyyaml
|
||||
```
|
||||
|
||||
### 3.3 验证环境
|
||||
|
||||
```bash
|
||||
ros2 --version
|
||||
python3 -c "import rclpy, cv_bridge, numpy, scipy, yaml; print('ros + deps ok')"
|
||||
python3 -c "import onnxruntime as ort; print(ort.get_available_providers())"
|
||||
```
|
||||
|
||||
`get_available_providers()` 出现 `CPUExecutionProvider` 即可;模型合计 28 MB,CPU 推理在 5 Hz 下通常够用。
|
||||
|
||||
---
|
||||
|
||||
## 4. 任务摘要
|
||||
|
||||
### 4.1 一句话
|
||||
|
||||
把源仓库的 **ROS1 Noetic** 部署包(`Deployment/`,包名 `sru_nav_go2_ros1`)反向移植成 **ROS2 Humble** 的 ament_python 包 `sru_nav_ros2`,能跑通 `/cmd_vel` 输出。
|
||||
|
||||
### 4.2 为什么是「反向移植」而不是去改官方 ROS2 仓库
|
||||
|
||||
你原本的想法是「官方说 Odin1 支持 ROS2,去看 sru 官方源代码改话题」。我核实后发现官方那个 ROS2 仓库
|
||||
|
||||
`leggedrobotics/sru-robot-deployment`
|
||||
|
||||
是 **ROS 2 Jazzy** + PyTorch CUDA venv(`~/ros2_torch`)+ ZED-X 深度 + DLIO 里程计 + 输出 `/path_manager/path_manager_ros/nav_vel`(**不是** `/cmd_vel`)+ C++ `b2w_controllers` 专用底层。要把它改成 Odin1 + 你的机器人,得同时动五处强耦合的东西。
|
||||
|
||||
而这个仓库的 ROS1 包**本来就是从 ROS2 机械改写来的**——其主节点文件头自己写着:
|
||||
|
||||
> *"Direct port of the original ROS2 NavigationPolicyNode. Behaviour is preserved; only ROS API calls, time helpers, and topic defaults have been changed."*
|
||||
|
||||
也就是说,**反向改回去等于撤销一次已知的机械变换**,路径最短,而且传感器(Odin1)、推理(ONNX 双模型)、参数(保守 policy_scale)、安全机制(手柄 deadman)全都已经按目标调好了,不用再对齐。
|
||||
|
||||
### 4.3 工作量分布(1942 行里只有 1120 行要改)
|
||||
|
||||
| 分层 | 行数 | 文件 | 处理方式 |
|
||||
|---|---|---|---|
|
||||
| **A 零改动** | 508(26%) | `constants.py`、`model.py`、`utils.py` | 直接拷贝,只改 import 包名。三者**一行 ROS 调用都没有** |
|
||||
| **B 轻改** | 314(16%) | `waypoint_manager.py`、`visualization.py` | 删 `RospyLogger` 包装类;注入 node clock 替代 `rospy.Time` |
|
||||
| **C 重写** | 1120(58%) | `navigation_policy_node.py`(682)、`scripts/sru_nav_node`(107)、`scripts/waypoint_runner.py`(331) | 按 ROS2 API 改写 |
|
||||
|
||||
加 launch / package.xml / CMakeLists / setup.py 全部按 ament_python 重写。
|
||||
|
||||
### 4.4 目标目录结构
|
||||
|
||||
```
|
||||
~/sru_ws/
|
||||
├── src/
|
||||
│ └── sru_nav_ros2/ # 新建的 ROS2 包(要交付的产物)
|
||||
└── reference/
|
||||
└── SRU-Odin/ # 原仓库,只读蓝本
|
||||
└── Deployment/
|
||||
```
|
||||
|
||||
> ⚠️ **重要**:参考源码必须放在 `src/` **外面**。否则 `colcon build` 会去编译它的 catkin `CMakeLists.txt`,直接报错。
|
||||
|
||||
---
|
||||
|
||||
## 5. 硬性约束
|
||||
|
||||
### 5.1 绝对不能改的数值(与训练对齐,改了行为就废)
|
||||
|
||||
```
|
||||
control_frequency = 5.0 Hz
|
||||
rnn_hidden_size = 512
|
||||
rnn_num_layers = 1
|
||||
min_depth / max_depth = 0.25 / 10.0 m
|
||||
ARRIVE_GOAL_THRESHOLD = 0.75 m
|
||||
JOYSTICK_TIMEOUT = 15.0 s
|
||||
LOW_PASS_FILTER_COEF = [0.9, 0.5, 0.5]
|
||||
LATERAL_VELOCITY_SCALE = 0.6
|
||||
深度预处理链:nan_to_num → 裁剪 [0.25, 10.0] → resize (40, 64)
|
||||
latent = 64×5×8 = 2560 维;obs 总维 2576 = 16(状态) + 2560(图像)
|
||||
```
|
||||
|
||||
### 5.2 必须改对的四个语义点
|
||||
|
||||
| # | 项 | 处理 |
|
||||
|---|---|---|
|
||||
| 1 | `use_sim` 参数 | **改名为 `odom_twist_in_base_frame`**。它的真实语义是「odom twist 已在 body 系、直接透传」,与 ROS2 内置 `use_sim_time`(仿真时钟)毫无关系,沿用旧名必被后人误配 |
|
||||
| 2 | 时间戳字段 | `secs/nsecs` → `sec/nanosec`。该值喂给控制频率门控,改错会导致推理频率失控 |
|
||||
| 3 | 深度订阅 QoS | 用 `rclpy.qos.qos_profile_sensor_data`(BEST_EFFORT)。BEST_EFFORT 发布端 + RELIABLE 订阅端 = **静默收不到数据**,这是 ROS2 独有的坑 |
|
||||
| 4 | 私有话题前缀 | `'~base_vel'` → `'~/base_vel'`。节点名保持 `sru_nav_node`,展开结果与 ROS1 一致,rviz 配置可复用 |
|
||||
|
||||
### 5.3 不要移植的 ROS1 专属文件
|
||||
|
||||
`Deployment/scripts/` 下这三个脚本是 **ROS1 + conda 时代的历史包袱,在 ROS2 下完全不需要**,不要移植也不要参考:
|
||||
|
||||
| 文件 | 为什么不要 |
|
||||
|---|---|
|
||||
| `setup_conda_env.sh` | ROS2 不需要 conda,用系统 python3.10 |
|
||||
| `launch_sru_nav.sh` | 它做的三件事(注入 `PYTHONPATH=/opt/ros/noetic/...`、`LD_PRELOAD` 修 conda libffi 与系统 libp11-kit 的 ABI 冲突、检查 catkin wrapper 的 shebang)在 ROS2 下**全部不存在** |
|
||||
| `verify_port.sh` | ROS1 专属自检脚本(且用户明确不要自检脚本) |
|
||||
|
||||
顺带一提:ROS1 README 里列的 5 条常见故障,有 3 条在 ROS2 下自动消失——conda↔系统 ROS 的 libffi ABI 冲突、`PYTHONPATH` 手工注入、catkin 锁 `PYTHON_EXECUTABLE` 导致的 shebang 陷阱。**这是这次迁移最大的红利**,别把包袱一起搬过去。
|
||||
|
||||
### 5.4 安全默认值(不可擅自"优化")
|
||||
|
||||
```yaml
|
||||
policy_scale: [0.6, 0.3, 0.6] # 训练值本是 [1.5, 1.0, 1.0],部署刻意保守化一半以上
|
||||
require_joystick: true # 手柄 deadman,默认必须 true。false 仅限抬轮/仿真测试
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. 存疑未决项(7 项,全部需要你上机实测)
|
||||
|
||||
这些项**暂时存疑是完全可以接受的**——已经要求 AI 全部做成可配置项,不会阻塞开发。你实测后只改 `config/sru_nav.yaml` 即可。
|
||||
|
||||
### ⭐ 第 1 项最关键:Odin1 深度话题的真实名字
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **问题** | 本仓库代码里用的是 `/odin1/depth_img_competetion`,但 Odin1 驱动 `manifoldsdk/odin_ros_driver` 的主线文档只列出 `/odin1/odometry`、`/odin1/odometry_highfreq`、`/odin1/cloud_slam`、`/odin1/imu`、`/odin1/image`,**没有这个深度话题**。它对应驱动配置里 `senddepth: 1` 开启的 dense depth,可能只有部分版本或分支支持 |
|
||||
| **临时默认** | 沿用 `/odin1/depth_img_competetion` |
|
||||
| **实测命令** | `ros2 topic list \| grep -i odin`<br>`ros2 topic list \| grep -iE 'depth\|img'`<br>`ros2 topic hz /odin1/<候选>`(应 ~10 Hz)<br>`ros2 topic echo /odin1/<候选> --once --field encoding`(应为 `32FC1`) |
|
||||
| **不确认的后果** | 节点收不到深度,`/cmd_vel` 恒为 0 |
|
||||
|
||||
同时确认驱动配置:`grep -i senddepth <odin_driver>/config/control_command.yaml` 应为 `1`;ROS2 下还需确认深度节点(`depth_image_ros2_node`)被 launch 起来了。
|
||||
|
||||
`/odin1/odometry_highfreq`(~300–400 Hz)和 `/odin1/odometry`(~10 Hz,SLAM 率,漂移更小但更滞后)两个里程计话题名与 ROS1 一致,可直接用。
|
||||
|
||||
### 第 2 项:深度与 odom 话题的 QoS
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **临时默认** | 深度用 BEST_EFFORT;odom 默认 RELIABLE 但做成可配 |
|
||||
| **实测命令** | `ros2 topic info -v /odin1/<depth_topic>` → 看 `Reliability:` 字段 |
|
||||
| **说明** | BEST_EFFORT 订阅端与两种发布端都兼容,是最安全选择。若实测发现驱动是 BEST_EFFORT 而代码用了 RELIABLE → 订阅静默失败(不报错,最难查) |
|
||||
|
||||
### 第 3 项:odom 的 twist 是 world 系还是 body 系
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **临时默认** | `odom_twist_in_base_frame: false`(按 world 系处理,与 ROS1 包原默认一致) |
|
||||
| **判据** | 规则:朝向 +Y 推进时 `linear.x≈0` 而 `linear.y>0` → **world 系**(保持默认);无论朝向如何 `linear.x` 恒为正、`linear.y≈0` → **body 系**(改为 `true`) |
|
||||
| **实测方法** | ① 让 Odin1 静止:`ros2 topic echo /odin1/odometry_highfreq --field twist.twist.linear`,所有分量应接近 0(这一步只排除非零偏置)<br>② **推荐**:把 Odin1 朝向任意非零方向(如绕 Z 转 90°),手动沿其镜头方向(body +X)匀速推 1 米,同时看 `linear.x` / `linear.y` |
|
||||
| **不确认的后果** | 速度指令剧烈震荡或方向错乱 |
|
||||
|
||||
`Deployment/docs/DEPLOY_GO2_NX.md` 第 5 节有四种判定方法(含 rosbag + 数值导数对比),可直接参考。
|
||||
|
||||
### 第 4 项:odom 的 `header.frame_id`
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **临时默认** | 不写死,代码运行时从 odom 消息里读(原实现就是这么做的) |
|
||||
| **实测命令** | `ros2 topic echo /odin1/odometry_highfreq --once --field header` |
|
||||
| **要记住的规则** | 发 `/goal_pose` 时 `frame_id` **必须**与该值一致,否则节点直接拒绝目标。这就是"发了目标机器人没反应"最常见的原因 |
|
||||
|
||||
### 第 5 项:Odin1 实际装订位置
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **问题** | launch 里静态 TF `base_link → odin1_base_link` 的默认值 `(x=0.25, y=0, z=0.18, roll=0, pitch=0.349, yaw=0)` 是**从原 Go2 平台假设继承来的**,不是你的车 |
|
||||
| **临时默认** | 沿用上述值,但在文档里标注"必须实测替换" |
|
||||
| **要量什么** | Odin1 镜头中心相对机体中心的前向偏移、左向偏移、高度,以及向下俯仰角(弧度)。默认 `pitch=0.349` 约等于 20° 下俯 |
|
||||
| **实测命令** | 若驱动已发 TF:`ros2 run tf2_ros tf2_echo base_link odin1_base_link`;否则用尺子量 |
|
||||
| **不确认的后果** | 深度图视角与训练分布偏离,避障行为异常 |
|
||||
|
||||
### 第 6 项:`/joy` 的轴与键索引
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **临时默认** | 沿用 `constants.py` 里现有 PS5 映射(`JOYSTICK_AXIS_LINEAR_X=1`、`JOYSTICK_AXIS_SMART=5`、`BUTTON_ABORT=9`、`BUTTON_SEND_GOAL=10` 等) |
|
||||
| **实测命令** | `ros2 topic echo /joy`,逐个推摇杆/按键,记录 index |
|
||||
| **说明** | Humble 的 joy 包默认轴映射与 ROS1 未必一致 |
|
||||
|
||||
### 第 7 项:推理能否跟上 5 Hz
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **临时默认** | `control_frequency: 5.0` 不变 |
|
||||
| **实测命令** | `ros2 topic hz /cmd_vel`(应稳定 ~5 Hz);同时看 CPU 占用 |
|
||||
| **说明** | 模型合计 28 MB,CPU EP 通常够用。跟不上再考虑装 JetPack 匹配的 `onnxruntime-gpu`(标准 pip 版在 Jetson 上不可用) |
|
||||
|
||||
---
|
||||
|
||||
## 7. 上机验收清单
|
||||
|
||||
按顺序跑,每步都要过:
|
||||
|
||||
```bash
|
||||
# 0) 环境
|
||||
ros2 --version
|
||||
python3 -c "import onnxruntime as ort; print(ort.get_available_providers())"
|
||||
|
||||
# 1) 构建
|
||||
cd ~/sru_ws
|
||||
source /opt/ros/humble/setup.bash
|
||||
colcon build --symlink-install
|
||||
source install/setup.bash
|
||||
|
||||
# 2) 静态确认:新包内不应有残留 rospy
|
||||
grep -rn "rospy" src/sru_nav_ros2/ ; echo "expect: no match"
|
||||
|
||||
# 3) Odin1 驱动已启动的前提下,确认数据流
|
||||
ros2 topic list | grep odin1
|
||||
ros2 topic hz /odin1/<depth_topic> # ~10 Hz
|
||||
ros2 topic hz /odin1/odometry_highfreq # ~300-400 Hz
|
||||
ros2 topic info -v /odin1/<depth_topic> # 记下 Reliability
|
||||
|
||||
# 4) 无手柄的闭环冒烟测试(务必先抬轮/架空!)
|
||||
ros2 launch sru_nav_ros2 sru_nav.launch.py require_joystick:=false
|
||||
# 期望日志:Navigation policy node is ready.
|
||||
|
||||
# 5) 另开终端发目标 + 看输出
|
||||
ros2 run sru_nav_ros2 waypoint_runner --waypoints "3,0"
|
||||
ros2 topic hz /cmd_vel # 应 ~5 Hz
|
||||
ros2 topic echo /cmd_vel
|
||||
```
|
||||
|
||||
**最后一次检查**:确认 `frames` 一致 —— 发目标用的 `frame_id` 与 odom 的 `header.frame_id` 相同。
|
||||
|
||||
---
|
||||
|
||||
## 8. 常见排错速查
|
||||
|
||||
| 现象 | 排查方向 |
|
||||
|---|---|
|
||||
| 节点启动后一直刷 "Odometry not ready, skipping depth callback" | `/odin1/odometry_highfreq` 是否在跑;话题名是否与 yaml 一致 |
|
||||
| `/cmd_vel` 全是 0 | ① 手柄 deadman(默认开着,`axes[4]` 必须推过 0,15 s 无 joy 强制归零)→ 测试用 `require_joystick:=false`;② 深度话题名错;③ odom twist 坐标系判反 |
|
||||
| 订阅了但收不到深度,且不报错 | **QoS 不匹配**,改用 BEST_EFFORT;用 `ros2 topic info -v` 对比两端 |
|
||||
| 发了 `/goal_pose` 机器人没反应 | `frame_id` 与 odom 的 `frame_id` 不一致(节点会直接拒绝并打 error 日志) |
|
||||
| `cv_bridge` import 报符号错误 / OpenCV 冲突 | 卸掉 pip 版 `opencv-python`,只用 `ros-humble-cv-bridge` + 系统 `python3-opencv` |
|
||||
| import rclpy 失败 | 没 `source /opt/ros/humble/setup.bash`,或 venv 建的时候漏了 `--system-site-packages` |
|
||||
| Twist 数值剧烈震荡 | ① `policy_scale` 太大;② odom twist 坐标系判反;③ 深度 NaN 没被过滤 |
|
||||
| Jetson 上 pip 报 `certificate is not yet valid` | 板子无 RTC 电池导致系统时间回退。`date` 看一下,然后 `sudo timedatectl set-ntp true` 或 `sudo ntpdate -u ntp.aliyun.com && sudo hwclock --systohc` |
|
||||
|
||||
---
|
||||
|
||||
## 9. 紧急停止手段
|
||||
|
||||
| 手段 | 操作 |
|
||||
|---|---|
|
||||
| 手柄放弃当前目标 | 按 `BUTTON_ABORT`(默认 button index 9)→ 立刻发零速、放弃当前目标 |
|
||||
| 杀掉导航节点 | `Ctrl+C` 停 `sru_nav_node` → `/cmd_vel` 不再有发布者,你的桥应自动归零(取决于桥的行为,**上机前先确认**) |
|
||||
| 物理断电 | 终极手段 |
|
||||
|
||||
**首次上机务必抬轮/架空**,确认 `/cmd_vel` 数值有界合理后再落地。
|
||||
|
||||
---
|
||||
|
||||
## 10. 关键事实速查
|
||||
|
||||
| 项 | 值 |
|
||||
|---|---|
|
||||
| 源仓库 | `https://github.com/ManifoldTechLtd/SRU-Odin` |
|
||||
| 精确版本 | `main` @ `6a81ba77f46d4ab010d3d3354d54ec25ef730955`(2026-07-22,"add img encoder model") |
|
||||
| ROS1 部署包 | `Deployment/`,包名 `sru_nav_go2_ros1`,catkin,32 MB |
|
||||
| 论文 | DOI `10.1177/02783649251401926`(IJRR 2025) |
|
||||
| Odin1 驱动 | `manifoldsdk/odin_ros_driver`,单代码库支持 ROS1/ROS2(`#ifdef ROS2`),ROS2 走 `./script/build_ros2.sh` + `ros2 launch odin_ros_driver odin1_ros2.launch.py`,官方推荐 Humble + Ubuntu 22.04 |
|
||||
| 目标包名 / 节点名 | `sru_nav_ros2` / `sru_nav_node` |
|
||||
| `/cmd_vel` 语义 | body 系 `geometry_msgs/Twist`,由调用方的桥接到具体机器人 |
|
||||
|
||||
### ROS2 侧话题接口契约(与 ROS1 一致)
|
||||
|
||||
| 话题 | 类型 | 方向 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `/odin1/depth_img_competetion` ⚠️待实测 | `sensor_msgs/msg/Image` | 入 | 稠密深度,`32FC1`,单位米,~10 Hz |
|
||||
| `/odin1/odometry_highfreq` | `nav_msgs/msg/Odometry` | 入 | ~300–400 Hz |
|
||||
| `/joy` | `sensor_msgs/msg/Joy` | 入 | 手柄 |
|
||||
| `/goal_pose` | `geometry_msgs/msg/PoseStamped` | 入/出 | `frame_id` 必须等于 odom 的 `frame_id` |
|
||||
| `/cmd_vel` | `geometry_msgs/msg/Twist` | 出 | body 系速度指令 |
|
||||
|
||||
### 模型 I/O 契约(不要改)
|
||||
|
||||
| 模型 | 输入 | 输出 |
|
||||
|---|---|---|
|
||||
| `vae_encoder.onnx` | `input` `(B,1,40,64)` | `mu` `(B,64,5,8)` |
|
||||
| `nav_policy.onnx` | `obs` `(B,2576)`, `h` `(1,B,512)`, `c` `(1,B,512)` | `actions` `(B,3)`, `h_new`, `c_new` |
|
||||
|
||||
最终速度 = `tanh(actions) × policy_scale`,其中 `policy_scale = [0.6, 0.3, 0.6]` → `[vx, vy, ωz]`。
|
||||
@@ -0,0 +1,204 @@
|
||||
# sru_nav_ros2 移植记录(本机:/home/xie/sru_nav_handover/sru_ws)
|
||||
|
||||
> 按 `src/sru_nav_ros2/docs/AI_AGENT_PROMPT.md` 执行。**未改动 `src/sru_nav_ros2/` 下任何一行代码或配置**,
|
||||
> 只做了环境配置与验收。日期 2026-09-28。
|
||||
|
||||
---
|
||||
|
||||
## 1. 本机与文档假设的差异(先说清楚,后面所有命令都基于这个)
|
||||
|
||||
| 项 | 文档假设 | 本机实际 |
|
||||
|---|---|---|
|
||||
| 工作区根 | `~/sru_ws` | **`/home/xie/sru_nav_handover/sru_ws`**(下文记作 `$WS`) |
|
||||
| 系统 / 架构 | Ubuntu 22.04 / x86_64 | ✅ Ubuntu 22.04.5 LTS / x86_64,一致 |
|
||||
| ROS 2 Humble | 需安装 | ✅ 已装 `/opt/ros/humble` |
|
||||
| apt 依赖 7 项 | 需安装 | ✅ **全部已装**(desktop / cv-bridge / joy / tf2-ros / rviz2 / colcon / python3.10-venv) |
|
||||
| Odin 驱动 | `~/catkin_ws` 已编译安装 | ⚠️ **不在 catkin_ws**,见 §5 |
|
||||
| 当前 shell 用户 | 普通用户 | ⚠️ 本会话是 **root**;且 `/home/xie` 是 `drwxr-x--- root root`,普通用户 xie 目前**无法进入自己的家目录** |
|
||||
|
||||
## 2. 本次实际做的事(改动清单)
|
||||
|
||||
| # | 动作 | 位置 |
|
||||
|---|---|---|
|
||||
| 1 | 重建 venv(`--system-site-packages`) | `$WS/venv`(约 600 MB,未从开发机拷贝) |
|
||||
| 2 | 装依赖 —— **见 §4 的两处本机适配** | `$WS/venv` 内 numpy 1.26.4 / onnxruntime 1.23.2 / scipy 1.11.4 |
|
||||
| 3 | 往 activate 末尾追加两行 export | `$WS/venv/bin/activate`(`PYTHONNOUSERSITE=1` + 追加式 `PYTHONPATH`) |
|
||||
| 4 | 补 `COLCON_IGNORE` | `$WS/reference/COLCON_IGNORE`(原本就有)、**新建** `$WS/venv/COLCON_IGNORE` |
|
||||
| 5 | 构建 | `$WS/{build,install,log}` |
|
||||
| 6 | 新建 pip 临时目录 | `/home/xie/.pip-tmp`(原因见 §4-A) |
|
||||
|
||||
> 小副作用:`--upgrade pip` 时 pip 把被替换掉的旧 `pip` / `pip3` / `pip3.10` / `latest` 入口脚本
|
||||
> 挪到了工作区根的 `$WS/.Trash-0/`(当前的 `$WS/venv/bin/pip` 是好的、已验证可用)。
|
||||
> 对 colcon 无影响,可以留也可删。
|
||||
|
||||
**没有改**:`sru_nav_ros2/` 下任何 `.py` / `.yaml` / `launch` / `package.xml`;**没有动** `reference/`。
|
||||
|
||||
## 3. 验收原始输出(第三步四条)
|
||||
|
||||
### ① `colcon list` — 只有一行,stderr 为空 ✅
|
||||
```
|
||||
sru_nav_ros2 src/sru_nav_ros2 (ros.ament_python)
|
||||
```
|
||||
|
||||
### ② `colcon build --symlink-install` — 退出码 0 ✅
|
||||
```
|
||||
Starting >>> sru_nav_ros2
|
||||
Finished <<< sru_nav_ros2 [1.59s]
|
||||
Summary: 1 package finished [2.00s]
|
||||
BUILD_EXIT=0
|
||||
```
|
||||
|
||||
### ③ 依赖自检 ✅(一处偏差见 §4-B)
|
||||
```
|
||||
PYTHONNOUSERSITE 1
|
||||
numpy 1.26.4 /home/xie/sru_nav_handover/sru_ws/venv/lib/python3.10/site-packages/numpy/__init__.py
|
||||
cv2 4.5.5 /usr/local/lib/python3.10/dist-packages/cv2/__init__.py <-- 期望 4.5.4 @ /usr/lib/python3/dist-packages
|
||||
scipy 1.11.4 /home/xie/sru_nav_handover/sru_ws/venv/lib/python3.10/site-packages/scipy/__init__.py
|
||||
ort 1.23.2 ['AzureExecutionProvider', 'CPUExecutionProvider']
|
||||
CvBridge <cv_bridge.core.CvBridge object at 0x74fef643dc00>
|
||||
```
|
||||
|
||||
### ④ launch 冒烟 ✅
|
||||
`ros2 launch sru_nav_ros2 sru_nav.launch.py require_joystick:=false launch_joy:=false`
|
||||
```
|
||||
[sru_nav_node-2] [INFO] [sru_nav_node]: VAE encoder: .../share/sru_nav_ros2/models/vae_encoder.onnx
|
||||
[sru_nav_node-2] [INFO] [sru_nav_node]: Policy model: .../share/sru_nav_ros2/models/nav_policy.onnx
|
||||
[sru_nav_node-2] [INFO] [sru_nav_node]: Navigation policy node is ready.
|
||||
[sru_nav_node-2] [INFO] [sru_nav_node]: SRU navigation node spinning (odom_twist_in_base_frame=True, require_joystick=False).
|
||||
```
|
||||
另:`ros2 pkg prefix sru_nav_ros2` → `$WS/install/sru_nav_ros2`;静态 TF 正常发布
|
||||
(`-0.268846, 0.028504, 0.067861` / 四元数 `0.008847,0.122404,-0.001091,0.992440`,`odin1_base_link`→`base_link`)。
|
||||
|
||||
## 4. 两处本机适配(与文档做法不同,但结论一致)
|
||||
|
||||
### A. pip 的临时目录 /tmp 只有 10 MB
|
||||
本机 `/tmp`、`/var`、`/dev/shm` 都是 **10 MB tmpfs**。第一次 `pip install onnxruntime`(wheel 17.4 MB)
|
||||
直接 `OSError: [Errno 28] 设备上没有空间`。真机文件系统 `/` 有 632 GB 空闲。
|
||||
→ 做法:`export TMPDIR=/home/xie/.pip-tmp`(建在 `/` 上)后重跑,成功。
|
||||
**以后在本机跑 pip 都要加这一句**;`/tmp` 正常的终端可忽略。
|
||||
|
||||
### B. 两个"被误判为已满足"的包 —— 必须强制装
|
||||
`--system-site-packages` 的 venv 里,pip 会把系统路径中的包当成"已满足",于是:
|
||||
- `numpy<2`:系统 `/usr/lib/python3/dist-packages/numpy` 是 **1.21.5**,且 `~/.local` 还有 1.26.4,
|
||||
两者都满足 `numpy<2` ⇒ pip 只回 `Requirement already satisfied`,**venv 里没有 numpy**。
|
||||
→ 做法:`pip install --ignore-installed "numpy<2"`,强制装进 venv。
|
||||
- `scipy`:文档已预判,用精确版本号 `scipy==1.11.4` 解决(系统 scipy 1.8.0 被正确跳过、未卸载)。
|
||||
|
||||
另外:pip 装依赖时设了 `PYTHONNOUSERSITE=1`(排除 `~/.local`),否则依赖会落在用户级 site 而不是 venv。
|
||||
|
||||
### C. cv2 版本偏差(**唯一未达标项,未处理,等你决定**)
|
||||
`sys.path` 里 `/usr/local/lib/python3.10/dist-packages` **排在** `/usr/lib/python3/dist-packages` **之前**,
|
||||
而 `/usr/local/...` 下有一份**散装的 `cv2` 目录(4.5.5,无 dist-info,不是 pip 管理的)**,
|
||||
它把 apt 的 4.5.4 顶掉了。
|
||||
|
||||
- apt 那份确实在:`/usr/lib/python3/dist-packages/cv2.cpython-310-x86_64-linux-gnu.so` = **4.5.4**
|
||||
- 实测当前导入的是 4.5.5,`import cv2` 正常、`CvBridge()` 正常、launch 冒烟正常
|
||||
- ⚠️ **没动它**:`/home/xie/techx_R2_algorithm/` 下的 `light_signal_detector` 等节点也 `import cv2`,
|
||||
删/挪可能影响 Rc2026 那套。要不要对齐请你拍板。
|
||||
|
||||
## 5. Odin 驱动现状(不属于本包,但决定能不能真跑)
|
||||
|
||||
本机有**三份**驱动源码树和**已编译**的安装:
|
||||
|
||||
| 位置 | 状态 |
|
||||
|---|---|
|
||||
| `/home/xie/algorithm_test/odin_ws/src/odin_ros_driver` | 源码在,**未编译**(无 build/install) |
|
||||
| `/home/xie/techx_R2_algorithm/r2_nav_ws2/src/odin_ros_driver` | 源码在,**已编译** → `r2_nav_ws2/install/odin_ros_driver` ✅ |
|
||||
| `/home/xie/techx_R2_algorithm/r2_algorithm/src/odin_ros_driver` | 源码在,**已编译** → `r2_algorithm/install/odin_ros_driver` |
|
||||
|
||||
`r2_nav_ws2` 已编译的四个可执行:`host_sdk_sample`、`pcd2depth_ros2_node`、`cloud_reprojection_ros2_node`、`image_overlay_node`。
|
||||
|
||||
**`algorithm_test/odin_ws` 那份 `config/control_command.yaml` 的实际取值**:
|
||||
```
|
||||
senddtof: 1 ✅ sendrgb: 1 ✅ sendrgbcompressed: 1
|
||||
sendimu: 1 ✅ sendodom: 1 ✅ send_odom_baselink_tf: 1 ✅
|
||||
sendcloudslam: 1 sendcloudrender: 1 devstatuslog: 1
|
||||
senddepth: 0 ❌ ← 必须改成 1,否则永远没有深度、一条 /cmd_vel 都不发
|
||||
use_host_ros_time: 0 ⚠️ ← odom 用设备时钟,与 deadman 的 time.time() 不同基准
|
||||
```
|
||||
|
||||
⚠️ **关键提醒**:驱动读的是**编译期 `__FILE__` 反推出的源码树**里的配置。
|
||||
所以"该改哪一份"取决于**你实际启动的那个 install 是谁编译的**——
|
||||
启动 `r2_nav_ws2/install` 的驱动,就要改 `r2_nav_ws2/src/odin_ros_driver/config/control_command.yaml`。
|
||||
改完后必须**整体重启驱动**(这几个键是 `register_keys`,启动时下发给设备)。
|
||||
|
||||
## 6. 与文档描述不一致的地方
|
||||
|
||||
1. **"没有 Odin 数据源时每 5 s 刷 `Odometry not ready, skipping depth callback.`"——实测没有打印。**
|
||||
查源码(`navigation_policy_node.py:452-457`):这句在 `depth_callback()` **内部**,而
|
||||
`depth_callback` 只在**收到深度消息**时才被调用。完全没有数据源时一条深度都不来 ⇒ 这句话永不触发。
|
||||
准确说法应是:**"有深度到达、但 odom 还没就绪"** 时才会每 5 s 刷。不是故障,属文档表述偏松。
|
||||
2. Ctrl-C 收尾时 `sru_nav_node` 打了一段 `KeyboardInterrupt` traceback(在 `destroy_node()` 里被信号打断)。
|
||||
属**退出路径**的正常产物,与启动无关;不影响验收。
|
||||
3. `/tmp` 10 MB 的约束文档未提及(见 §4-A)。
|
||||
|
||||
## 7. 没确认的事项
|
||||
|
||||
- `cv2` 4.5.5 vs 要求的 4.5.4(§4-C)—— 未处理,等决定。
|
||||
- 驱动 `use_host_ros_time: 0` 导致的 deadman 时钟域问题(文档 §11 第 8 项)——真机开手柄前必须处理。
|
||||
- 装订外参 `base_link_*` 仍是从文档继承的 Rc2026 R2 实测值,**不是本机载体**。
|
||||
- 真机链路(深度到达 → 非零 `/cmd_vel`)本次**未验**,因为没有启动驱动(也无载体,安全默认不动)。
|
||||
|
||||
## 8. 下一步建议(对照 HANDOVER_TEAM §6.2 待测清单)
|
||||
|
||||
1. 起驱动(用已编译的 `r2_nav_ws2/install`),先把**实际生效的那份** `control_command.yaml` 的
|
||||
`senddepth` 改 1,整体重启;再用 `dev_status.csv` 确认 `dtof_rx_odr` 等非 0。
|
||||
2. `ros2 topic hz /odin1/odometry_highfreq`、`/odin1/depth_img_competetion` 确认真实速率。
|
||||
3. 无载体先把链路跑通:`waypoint_runner --waypoints "3,0"`,看 `/cmd_vel` 是否非零有界
|
||||
(已知上限 `|vx|≤0.6`、`|vy|≤0.18`、`|ω|≤0.6`)。**务必先抬轮/架空。**
|
||||
4. 上机前处理 deadman 时钟域(`use_host_ros_time` → 1 或 2)。
|
||||
5. 标定装订外参;再逐个试 `/joy` 轴/键索引。
|
||||
6. 密集路点必须 ≥ 3–5 m(`ARRIVE_GOAL_THRESHOLD=0.75`,间距 ≤0.75 m 一步都不走)。
|
||||
|
||||
---
|
||||
|
||||
## 9. 与目标的差异清单(逐条对照,2026-09-28 22:20 复核)
|
||||
|
||||
### 9.1 对照「验收标准」(只差 1 项)
|
||||
|
||||
| # | 标准 | 状态 |
|
||||
|---|---|---|
|
||||
| 1 | `colcon build --symlink-install` 退出码 0 | ✅ 达成 |
|
||||
| 2 | `colcon list` 只有一行、stderr 为空 | ✅ 达成(实测 `sru_nav_ros2 src/sru_nav_ros2 (ros.ament_python)`) |
|
||||
| 3 | 依赖自检 5 项 | ⚠️ **4/5 达成**。numpy 1.26.4✔(venv)、scipy 1.11.4✔(venv)、onnxruntime✔含 CPUExecutionProvider、CvBridge✔;**cv2 = 4.5.5 @ `/usr/local/lib/python3.10/dist-packages`,要求是 4.5.4 @ `/usr/lib/python3/dist-packages`** |
|
||||
| 4 | launch 打印 ready 且 `odom_twist_in_base_frame=True` | ✅ 达成 |
|
||||
|
||||
⇒ **验收层面只剩 cv2 版本这一处差异**(详见 §4-C,未处理,等拍板)。
|
||||
|
||||
### 9.2 对照「上机实测就绪」——未验证项(文档 §6.2 清单,全部仍待测)
|
||||
|
||||
| # | 待测项 | 卡点 |
|
||||
|---|---|---|
|
||||
| 1 | 驱动把深度打开 | `senddepth: 0` 需改 1;**且要先确定哪份源码树生效**(编译期 `__FILE__`) |
|
||||
| 2 | 深度/odom 真实速率 | 需起驱动后用 `dev_status.csv` + `ros2 topic hz` |
|
||||
| 3 | 深度→非零 `/cmd_vel` 真机链路 | 需驱动 + 载体(本次未验,且未抬轮不动) |
|
||||
| 4 | **deadman 时钟域** | `use_host_ros_time: 0` 未处理 ⇒ 开手柄可能"一上来就超时"或 deadman 失效 |
|
||||
| 5 | 装订外参 `base_link_*` | 仍是 Rc2026 **R2 比赛车**实测值,不是本机载体 |
|
||||
| 6 | `/goal_yaw` 朝向精度(±5°) | 从未在真机验证 |
|
||||
| 7 | `/joy` 轴/键索引(17 个参数) | 沿用 PS5 映射,未在真手柄验 |
|
||||
| 8 | odom twist 正负号手感 | 未验,判反会反向跑 |
|
||||
| 9 | 驱动侧 ~1.5 Hz 速率问题 | `QoS(5)`→`QoS(50)`(驱动侧改动,须先报告) |
|
||||
| 10 | `/cmd_vel` 桥 | 底盘侧桥是否存在、节点死后是否自动归零 —— **未确认,最易出事故的点** |
|
||||
|
||||
⇒ 验收(静态)与上机(动态)之间差的是**物理世界**那一半,这一条与文档结论一致。
|
||||
|
||||
### 9.3 其它差异
|
||||
|
||||
- 本次会话是 root,且 `/home/xie` 为 `drwxr-x--- root root` ⇒ 普通用户 xie 目前进不了自己家目录。
|
||||
- 文档"无数据源时每 5 s 刷 `Odometry not ready...`"的表述不准确(见 §6 第 1 条)。
|
||||
|
||||
---
|
||||
|
||||
## 附:速查(本机路径版)
|
||||
|
||||
```bash
|
||||
WS=/home/xie/sru_nav_handover/sru_ws
|
||||
source /opt/ros/humble/setup.bash && source $WS/venv/bin/activate
|
||||
source $WS/install/setup.bash # --symlink-install:改代码/配置免重建,重启进程即可
|
||||
|
||||
ros2 launch sru_nav_ros2 sru_nav.launch.py # 正常(deadman 生效)
|
||||
ros2 launch sru_nav_ros2 sru_nav.launch.py require_joystick:=false launch_joy:=false # 冒烟,先抬轮
|
||||
|
||||
ros2 run sru_nav_ros2 waypoint_runner --waypoints "3,0"
|
||||
ros2 topic hz /cmd_vel
|
||||
```
|
||||
@@ -0,0 +1,36 @@
|
||||
# sru_ws 文档索引
|
||||
|
||||
工作区根:`/home/xie/sru_nav_handover/sru_ws`(下文记作 `$WS`)。
|
||||
|
||||
## 想看什么,点哪里
|
||||
|
||||
| 想解决的问题 | 文档 |
|
||||
|---|---|
|
||||
| **怎么把这个工程跑起来** —— source 哪三行、三个终端怎么开、怎么发目标、上机前安全检查 | **[`USAGE.md`](USAGE.md)** ← 从这里开始 |
|
||||
| 原理、数据流、全部参数、约 20 条排错速查(权威,约 1000 行) | [`../src/sru_nav_ros2/docs/DEPLOY_ROS2.md`](../src/sru_nav_ros2/docs/DEPLOY_ROS2.md) |
|
||||
| 怎么把工程交付/迁移给队友或新机器(打包清单、venv 为何不能拷) | [`../src/sru_nav_ros2/docs/HANDOVER_TEAM.md`](../src/sru_nav_ros2/docs/HANDOVER_TEAM.md) |
|
||||
| 本机(xie 的 Ubuntu 22.04)环境适配与验收记录 | [`PORT_NOTES_2026-09-28.md`](PORT_NOTES_2026-09-28.md) |
|
||||
| 当初交给 AI 执行的移植提示词存档 | [`../src/sru_nav_ros2/docs/AI_AGENT_PROMPT.md`](../src/sru_nav_ros2/docs/AI_AGENT_PROMPT.md) |
|
||||
| Odin1 驱动(上游)中文说明 52 KB | [`../src/odin_ros_driver/README.md`](../src/odin_ros_driver/README.md) |
|
||||
| 驱动运行期服务操作 | [`../src/odin_ros_driver/docs/runtime_service_operations.md`](../src/odin_ros_driver/docs/runtime_service_operations.md) |
|
||||
| 驱动重定位(relocalization)指南 | [`../src/odin_ros_driver/RELOCALIZATION_GUIDE.md`](../src/odin_ros_driver/RELOCALIZATION_GUIDE.md) |
|
||||
| ROS 1 → ROS 2 移植方案与 API 对照表(**历史件,两处结论已被实测推翻**,以 `DEPLOY_ROS2.md` 为准) | [`HANDOVER.md`](HANDOVER.md)、[`ROS2_PORT_PLAN.md`](ROS2_PORT_PLAN.md) |
|
||||
| 上游 ROS 1 蓝本自带的移植指南(中/英)与 Go2 NX 部署 | [`../reference/SRU-Odin/Deployment/docs/`](../reference/SRU-Odin/Deployment/docs/) |
|
||||
| **学习笔记 / 飞书知识库素材**(含排版规范与模板) | [`../notes/`](../notes/) |
|
||||
|
||||
## 文档都放在哪(本工作区的约定)
|
||||
|
||||
| 位置 | 内容 | 能不能改 |
|
||||
|---|---|---|
|
||||
| `docs/` | **工作区级文档**(本目录):使用手册、移植记录、历史交接件、`assets/` 素材 | ✅ |
|
||||
| `src/sru_nav_ros2/docs/` | 交付包自带文档。**会被 `setup.py` 安装到 `share/sru_nav_ros2/docs/`**,属包载荷 | ✅ 按需 |
|
||||
| `src/odin_ros_driver/docs/` | 驱动上游文档 | ⚠️ 尽量只读 |
|
||||
| `reference/SRU-Odin/` | 上游只读快照(ROS 1 蓝图 `Deployment/` + 训练侧 `Train/`) | ❌ **禁止修改**,只做 diff 对照 |
|
||||
| `build/`、`install/` | colcon 构建产物 | ❌ 不要手改 |
|
||||
|
||||
> `docs/` 与 `src/*/docs/` 的分工:前者是给人看的工作区文档,后者是随包发布的载荷。
|
||||
> 两处内容如有出入,以 `src/sru_nav_ros2/docs/DEPLOY_ROS2.md` 为准。
|
||||
|
||||
## 素材
|
||||
|
||||
- `assets/cam_in_ex.txt` —— Odin1 相机内参/外参摘录(`Tcl_0` 外参 + `cam_0` 内参)。
|
||||
@@ -0,0 +1,298 @@
|
||||
# SRU-Odin 从 ROS1 迁移到 ROS 2 Humble —— 方案与迁移清单
|
||||
|
||||
> 针对本地仓库 `F:\RC2027\odin1_SRU\SRU-Odin-orig\SRU-Odin`(`ManifoldTechLtd/SRU-Odin`)
|
||||
> 本轮为**方案与迁移清单**,不含代码实现。
|
||||
|
||||
---
|
||||
|
||||
## 0. 已确认前提
|
||||
|
||||
| 项 | 确认结果 | 影响 |
|
||||
|---|---|---|
|
||||
| 目标发行版 | ROS 2 **Humble**(Ubuntu 22.04) | package.xml format=3、ament_python、`colcon build`、Humble 版 QoS API |
|
||||
| 目标机器人 | 任意订阅 `/cmd_vel` 的平台 | 本包不绑定机型,另给桥接模板;`policy_scale` 保持保守默认 |
|
||||
| 推理后端 | ONNX Runtime 双模型 | 复用仓库现成 `vae_encoder.onnx` + `nav_policy.onnx`,不引入 PyTorch |
|
||||
| 本轮交付 | 方案 + 迁移清单 | 代码待你确认后再写 |
|
||||
|
||||
---
|
||||
|
||||
## 1. 结论:走「反向移植」,不要走「官方 ROS2 仓库改话题」
|
||||
|
||||
你有两条路,我建议第一条。
|
||||
|
||||
| 维度 | 路线 A:反向移植本仓库(**推荐**) | 路线 B:拿官方 ROS2 源码改话题 |
|
||||
|---|---|---|
|
||||
| 起点 | `Deployment/`(ROS1,但传感器/模型/参数已全部按 Odin1 调好) | `leggedrobotics/sru-robot-deployment`(ROS2 Jazzy) |
|
||||
| 要动的传感器 | 无,话题已是 `/odin1/*` | ZED-X → Odin1,含深度预处理口径对齐 |
|
||||
| 要动的里程计 | 无,已是 `/odin1/odometry_highfreq` | DLIO → Odin1,含 twist 坐标系判定 |
|
||||
| 要动的推理 | 无,已是 ONNX 双模型 | PyTorch JIT + `~/ros2_torch` venv → ONNX(或保留重依赖) |
|
||||
| 要动的输出接口 | 无,已是 `/cmd_vel` | `/path_manager/path_manager_ros/nav_vel` → `/cmd_vel`,且要剥离 B2W 专用 C++ 底层 `b2w_controllers` |
|
||||
| 要动的 ROS 版本 | ROS1 API → ROS2 API(机械改写) | 无 |
|
||||
| 主要风险 | ROS1/ROS2 API 语义差异(可控、可查) | 平台耦合 + 依赖重,改动面大且互相牵连 |
|
||||
|
||||
**路线 A 的额外依据**:本仓库 `navigation_policy_node.py` 文件头自己写着
|
||||
|
||||
> *"Direct port of the original ROS2 NavigationPolicyNode. Behaviour is preserved; only ROS API calls, time helpers, and topic defaults have been changed."*
|
||||
|
||||
也就是说,**这个 ROS1 包本来就是从 ROS2 机械改写来的**,反向改写回去等于撤销一次已知的机械变换,路径最短、语义最清楚。而路线 B 的官方仓库是 ROS 2 **Jazzy** + Gazebo Harmonic,与 Odin1 驱动官方推荐的 Humble 也不同版本。
|
||||
|
||||
---
|
||||
|
||||
## 2. 事实核查(本次实际读盘 + 联网确认)
|
||||
|
||||
### 2.1 本地仓库实测
|
||||
|
||||
- 克隆产物路径:`F:\RC2027\odin1_SRU\SRU-Odin-orig\SRU-Odin\`
|
||||
- `Deployment/` 是 ROS1 catkin 包,包名 `sru_nav_go2_ros1`,构建文件为 `CMakeLists.txt` + `catkin_python_setup()`
|
||||
- **模型真实可用,不是 LFS 指针**:
|
||||
- `Deployment/models/nav_policy.onnx` — 7,054,074 字节
|
||||
- `Deployment/models/vae_encoder.onnx` — 20,971,407 字节
|
||||
- 代码行数(`wc -l` 实测):合计 **1942 行**(Python + 入口脚本)
|
||||
|
||||
### 2.2 官方 ROS2 源仓库(`leggedrobotics/sru-robot-deployment`)
|
||||
|
||||
| 项 | 实际值 |
|
||||
|---|---|
|
||||
| ROS 版本 | **Jazzy** |
|
||||
| 仿真 | Gazebo Harmonic |
|
||||
| 高层包 | `rl_nav_controller/`,`rl_nav_controller.py` 916 行 |
|
||||
| 推理 | PyTorch CUDA 版,隔离在 `~/ros2_torch` venv |
|
||||
| 深度 | ZED-X:`/zed/zed_node/depth/depth_registered` |
|
||||
| 里程计 | DLIO |
|
||||
| 速度输出 | `/path_manager/path_manager_ros/nav_vel`(**不是** `/cmd_vel`) |
|
||||
| 底层 | C++ `b2w_controllers`(自带 ONNX locomotion policy) |
|
||||
|
||||
### 2.3 Odin1 驱动的 ROS2 支持情况
|
||||
|
||||
- 官方驱动 `manifoldsdk/odin_ros_driver` **单代码库同时支持 ROS1/ROS2**(源码里用 `#ifdef ROS2` 条件编译),不是两套代码。
|
||||
- ROS2 构建:`./script/build_ros2.sh`
|
||||
- ROS2 启动:`ros2 launch odin_ros_driver odin1_ros2.launch.py`
|
||||
- 官方推荐 ROS2 LTS = **Humble**,OS = **Ubuntu 22.04** → 与你的选择完全一致 ✅
|
||||
- 驱动内已含 `depth_image_ros2_node`、`pcd2depth_ros2` 等 ROS2 节点。
|
||||
|
||||
> ⚠️ **必须实测的风险点**:驱动主线文档列出的话题是
|
||||
> `/odin1/odometry`、`/odin1/odometry_highfreq`、`/odin1/cloud_slam`、`/odin1/imu`、`/odin1/image`,
|
||||
> **没有** `/odin1/depth_img_competetion`。
|
||||
> 该话题名来自本仓库,对应驱动 `config/control_command.yaml` 里 `senddepth: 1` 开启的 dense depth,
|
||||
> 只有部分版本/分支有。**上机第一步必须用 `ros2 topic list` 确认真实深度话题名**,不能照抄。
|
||||
|
||||
---
|
||||
|
||||
## 3. 迁移面:1942 行里只有 1120 行需要改写
|
||||
|
||||
### 3.1 A 类 · 零改动(508 行,26%)
|
||||
|
||||
| 文件 | 行数 | 为什么不用改 |
|
||||
|---|---|---|
|
||||
| `src/sru_nav_go2/constants.py` | 80 | 纯数值常量,无任何 ROS import |
|
||||
| `src/sru_nav_go2/model.py` | 176 | 只依赖 `cv2` / `numpy` / `onnxruntime`,**不含一行 ROS 调用** |
|
||||
| `src/sru_nav_go2/utils.py` | 252 | 纯 NumPy 四元数/变换数学 |
|
||||
|
||||
→ 唯一改动:`from sru_nav_go2 import constants` 里的包名(若新包名不同)。
|
||||
|
||||
### 3.2 B 类 · 轻改(314 行,16%)
|
||||
|
||||
| 文件 | 行数 | 改动点 | 改动量 |
|
||||
|---|---|---|---|
|
||||
| `waypoint_manager.py` | 157 | 删掉 `RospyLogger` 包装类(L10–28),直接把 `node.get_logger()` 传进去即可(rclpy logger 已有 `info/warn/warning/error`) | 删 ~18 行 |
|
||||
| `visualization.py` | 157 | ① 删 `import rospy`;② `_stamp_from_sec()`(L13–15)改为注入的 node clock;③ `rospy.Time.now()`(L141)→ `self.node.get_clock().now().to_msg()`;④ `__init__` 里被注释为"retained for API parity, not used in ROS1"的 `node` 参数**在 ROS2 下真正派上用场** | 改 ~8 行 |
|
||||
|
||||
### 3.3 C 类 · 按 ROS2 API 重写(1120 行,58%)
|
||||
|
||||
| 文件 | 行数 | 重写要点 |
|
||||
|---|---|---|
|
||||
| `src/sru_nav_go2/navigation_policy_node.py` | 682 | 普通类 → `rclpy.node.Node` 子类;Publisher/Subscriber/Timer/参数/日志/时间戳全部换 API;回调组与 QoS 需明确 |
|
||||
| `scripts/sru_nav_node` | 107 | 从独立可执行脚本 → `setup.py` 的 `console_scripts` 入口;`rospkg` → `ament_index_python` |
|
||||
| `scripts/waypoint_runner.py` | 331 | `rospy.Publisher(latch=True)` → QoS `TRANSIENT_LOCAL`;`rospy.Rate` → 节点时钟 sleep;`rospy.myargv()` → `sys.argv` |
|
||||
| `launch/*.launch` | 55 | XML + `rosparam` → `launch.py` + `parameters=[yaml]` |
|
||||
| `CMakeLists.txt` / `package.xml` / `setup.py` | 47+29+11 | catkin → ament_python,全部换掉 |
|
||||
|
||||
---
|
||||
|
||||
## 4. ROS1 → ROS2 API 逐点对照表
|
||||
|
||||
| 位置(ROS1 文件:行) | ROS1 写法 | ROS2 Humble 写法 |
|
||||
|---|---|---|
|
||||
| 节点 L38–41 | `rospy.init_node()` + `object` | `class NavigationPolicyNode(Node)` + `super().__init__('sru_nav_node')` |
|
||||
| 参数 L52–56 | `rospy.get_param('~x', dft)` | `self.declare_parameter('x', dft)` + `self.get_parameter('x').value` |
|
||||
| 发布者 L67–70 | `rospy.Publisher(t, Type, queue_size=10)` | `self.create_publisher(Type, t, 10)` |
|
||||
| 私有话题 L68 | `'~base_vel'` | `'~/base_vel'`(节点名保持 `sru_nav_node` → 展开结果一致,rviz 配置可复用) |
|
||||
| 可视化发布者 L73–80 | `rospy.Publisher('~vis/...', Marker, 10)` | `self.create_publisher(Marker, '~/vis/...', 10)` |
|
||||
| 订阅者 L136–143 | `rospy.Subscriber(t, Type, cb, queue_size=N)` | `self.create_subscription(Type, t, cb, N)` |
|
||||
| 定时器 L146–152 | `rospy.Timer(rospy.Duration(x), cb)` | `self.create_timer(x, cb)` |
|
||||
| 时间戳解析 L30–32 | `stamp.secs + stamp.nsecs*1e-9` | `stamp.sec + stamp.nanosec*1e-9` |
|
||||
| 取时间 L521 | `rospy.Time.from_sec(t)` | `rclpy.time.Time(seconds=t).to_msg()` |
|
||||
| 节流日志 L216–217, L248, L284 | `rospy.loginfo_throttle(1.0, msg)` | `self.get_logger().info(msg, throttle_duration_sec=1.0)` |
|
||||
| 主循环 L103 | `rospy.spin()` | `rclpy.spin(node)` + `try/finally` 收尾 |
|
||||
| 图像转换 L221 | `CvBridge().imgmsg_to_cv2(msg,'passthrough')` | **接口不变**,仅需 `ros-humble-cv-bridge` |
|
||||
| 找包路径 L23–25 | `rospkg.RosPack().get_path('pkg')` | `ament_index_python.packages.get_package_share_directory('pkg')` |
|
||||
| 命令行 L305 | `rospy.myargv()[1:]` | `sys.argv[1:]`(注意 launch 会注入 `--ros-args`,需过滤) |
|
||||
| 锁存发布 L133–134 | `queue_size=1, latch=True` | `QoSProfile(depth=1, durability=DurabilityPolicy.TRANSIENT_LOCAL)` |
|
||||
| 构建 | `catkin_make` | `colcon build --symlink-install` |
|
||||
| 包定义 | `format="2"` + `<buildtool_depend>catkin` | `format="3"` + `<export><build_type>ament_python</build_type>` |
|
||||
| launch | `sru_nav_go2.launch` + `<rosparam command="load">` | `sru_nav.launch.py` + `parameters=[os.path.join(share,'config','sru_nav.yaml')]` |
|
||||
| 静态 TF | `tf2_ros static_transform_publisher x y z yaw pitch roll frame child` | 同节点同用法(8 位置参数形式两边都支持),建议改写成 `launch_ros.actions.Node(arguments=[...])` 并换成实测装订值 |
|
||||
| 手柄 | `rosrun joy joy_node` | `ros2 run joy joy_node`(参数名 `autorepeat_rate` / `deadzone` 一致) |
|
||||
|
||||
---
|
||||
|
||||
## 5. ROS2 专属陷阱(ROS1 里不存在,必须提前防)
|
||||
|
||||
按危险程度排序:
|
||||
|
||||
1. **QoS 不匹配 → 静默收不到数据**。这是 ROS2 最经典的坑,ROS1 完全没有。
|
||||
Odin 驱动若用 `rclcpp::SensorDataQoS()`(BEST_EFFORT)发布深度,而订阅端用默认 RELIABLE,**订阅直接连不上,且不一定报错**。
|
||||
对策:深度订阅用 `qos_profile_sensor_data`(BEST_EFFORT,与两种发布端都兼容);上机用 `ros2 topic info -v /odin1/...` 看真实 QoS 再定。
|
||||
|
||||
2. **`use_sim` 参数名与 ROS2 内置 `use_sim_time` 极易混淆**。
|
||||
本仓库 `use_sim` 的真实语义是"odom twist 已经是 body 系,直接透传"。ROS2 里 `use_sim_time` 是仿真时钟开关,两者含义完全不同。
|
||||
对策:**改名为 `odom_twist_in_base_frame`**,并在 YAML 里写清注释。
|
||||
|
||||
3. **时间戳字段名 `secs/nsecs` → `sec/nanosec`**。漏改会 `AttributeError` 或时间戳恒为 0。
|
||||
控制频率门控(`robot_odom_time - last_run_time < interval`)依赖这个值,改错会导致门控失效、推理频率失控。
|
||||
|
||||
4. **回调线程模型变化**。
|
||||
ROS1 下 `rospy.Timer` 回调在独立线程,而 `generate_cmd_vel()` 是**在 depth 回调里执行**的重活(含 ONNX 推理)。
|
||||
ROS2 默认 `rclpy.spin()` 是单线程 executor,所有回调串行 → **行为与 ROS1 等效,照搬即可**。
|
||||
若为了提频改成 `MultiThreadedExecutor`,必须给各回调加 `MutuallyExclusiveCallbackGroup`,否则 LSTM 隐状态 `(h,c)` 会竞态,产生乱码速度指令。
|
||||
|
||||
5. **参数类型严格**。ROS2 参数声明后类型固定,`policy_scale` 必须声明为 double array。
|
||||
YAML 里若写 `policy_scale: [1, 1, 1]`(整数)会被拒,必须写 `[1.0, 1.0, 1.0]`。
|
||||
|
||||
6. **`/joy` 轴映射需实测**。Humble 的 `joy` 包默认轴映射与 ROS1 未必一致,`constants.py` 里的 PS5 轴/键索引(`JOYSTICK_AXIS_SMART = 5` 等)上机前要用 `ros2 topic echo /joy` 复核。
|
||||
|
||||
7. **cv_bridge 与 OpenCV 版本冲突**。Humble 的 `cv_bridge` 依赖系统 `python3-opencv`;
|
||||
若再用 pip 装 `opencv-python`,可能出现 `libopencv` 双版本冲突(症状是 cv_bridge 导入时报符号错误)。
|
||||
对策:ROS2 侧只用 apt 的 `ros-humble-cv-bridge` + 系统 opencv,**只 pip 装 `onnxruntime`**。
|
||||
|
||||
### 顺带一个好消息:ROS1 侧三大部署痛点会消失
|
||||
|
||||
ROS1 README §9 里 5 条常见坑,有 3 条在 ROS2 下**根本不存在**,因为不再需要 conda 与系统 ROS 共生的 hack:
|
||||
|
||||
| ROS1 坑 | ROS2 下 |
|
||||
|---|---|
|
||||
| conda `libffi` 与系统 `libp11-kit` ABI 冲突(`ffi_type_pointer` 未定义符号)→ `LD_PRELOAD` 硬修 | **消失**:不再需要 conda 与系统 ROS 混用 |
|
||||
| `PYTHONPATH` 手工注入 `/opt/ros/noetic/lib/python3/dist-packages` | **消失**:Humble 原生 python3.10 直接可用 |
|
||||
| `catkin_make -DPYTHON_EXECUTABLE=$(which python)` 锁 shebang,否则 import onnxruntime 失败 | **消失**:`colcon` + 系统解释器,无 shebang 陷阱 |
|
||||
| `netifaces` / `defusedxml` 隐性依赖缺失 | **消失**:ROS2 不再依赖 netifaces |
|
||||
| `zsh` 下 `setup.zsh: cd: -q` 报错 | 仍可能遇到,但 launch.py 不涉及 |
|
||||
|
||||
剩下要保留的只有一条:**Jetson 无 RTC 电池导致系统时钟回退、pip TLS 握手失败** → 上机前 `date` 校验 + `ntpdate`。
|
||||
|
||||
---
|
||||
|
||||
## 6. 目标包结构
|
||||
|
||||
建议**新建独立包**(不改原 ROS1 包,方便 diff 对照):
|
||||
|
||||
```
|
||||
F:\RC2027\odin1_SRU\
|
||||
└── src/
|
||||
└── sru_nav_ros2/ # ament_python 包
|
||||
├── package.xml # format=3, ament_python
|
||||
├── setup.py # 入口: sru_nav_node / waypoint_runner
|
||||
├── setup.cfg
|
||||
├── resource/sru_nav_ros2
|
||||
├── sru_nav_ros2/
|
||||
│ ├── __init__.py
|
||||
│ ├── constants.py # A 类:原样拷贝
|
||||
│ ├── model.py # A 类:原样拷贝
|
||||
│ ├── utils.py # A 类:原样拷贝
|
||||
│ ├── waypoint_manager.py # B 类:删 RospyLogger
|
||||
│ ├── visualization.py # B 类:注入 node clock
|
||||
│ ├── navigation_policy_node.py # C 类:rclpy 重写
|
||||
│ ├── sru_nav_node.py # C 类:main() 入口
|
||||
│ └── waypoint_runner.py # C 类:rclpy 重写
|
||||
├── launch/
|
||||
│ └── sru_nav.launch.py # joy + static TF + 导航节点
|
||||
├── config/
|
||||
│ ├── sru_nav.yaml # 参数(含改名后的 odom_twist_in_base_frame)
|
||||
│ └── waypoints_example.yaml # 原样拷贝
|
||||
├── models/
|
||||
│ ├── vae_encoder.onnx # 20,971,407 B,从 Deployment/models 拷贝
|
||||
│ └── nav_policy.onnx # 7,054,074 B
|
||||
└── docs/
|
||||
└── DEPLOY_ROS2.md
|
||||
```
|
||||
|
||||
### 与 ROS1 包的命名对应
|
||||
|
||||
| ROS1 | ROS2 | 说明 |
|
||||
|---|---|---|
|
||||
| 包名 `sru_nav_go2_ros1` | `sru_nav_ros2` | 去掉机型与 ROS 版本后缀,因为本包已机型无关 |
|
||||
| 节点名 `sru_nav_node` | `sru_nav_node` | **保持不变**,私有话题展开结果一致 |
|
||||
| `config/sru_nav.yaml` | `config/sru_nav.yaml` | 字段基本照搬,仅 `use_sim` 改名 |
|
||||
| `scripts/sru_nav_node` | `sru_nav_ros2.sru_nav_node:main` | console_scripts 入口 |
|
||||
|
||||
---
|
||||
|
||||
## 7. 分步实施清单(每步带可 grep 的验收点)
|
||||
|
||||
| 步骤 | 动作 | 验收 |
|
||||
|---|---|---|
|
||||
| **1. 环境底座** | Ubuntu 22.04 + `ros-humble-desktop` + `ros-humble-cv-bridge` + `ros-humble-joy` + `ros-humble-tf2-ros`;`pip3 install --user onnxruntime numpy scipy pyyaml`(若遇 `externally-managed-environment`,改用 `python3 -m venv --system-site-packages`) | `python3 -c "import rclpy, cv_bridge, onnxruntime; print('ok')"` 无报错 |
|
||||
| **2. 建包骨架** | 建 §6 目录;写 `package.xml`(format=3) / `setup.py` / `setup.cfg` / `resource/`;`data_files` 把 `config/` `launch/` `models/` 装到 `share/` | `colcon build --symlink-install` 退出码 0;`ros2 pkg prefix sru_nav_ros2` 有输出 |
|
||||
| **3. 搬 A 类+B 类** | 拷贝 `constants.py` / `model.py` / `utils.py` / `waypoint_manager.py` / `visualization.py`,改包名 import、删 `RospyLogger`、注入 node clock | `grep -rn "import rospy\|rospy\." sru_nav_ros2/` **零命中** |
|
||||
| **4. 重写节点** | `navigation_policy_node.py` 按 §4 对照表全部改 rclpy;明确 QoS 与单线程 executor;`use_sim` → `odom_twist_in_base_frame` | `grep -n "create_publisher\|create_subscription\|create_timer\|declare_parameter"` 全部命中;`grep -c "rospy"` = 0 |
|
||||
| **5. 入口与 launch** | `sru_nav_node.py` 用 `ament_index_python` 定位 `share/sru_nav_ros2/models`;`sru_nav.launch.py` 做 joy + static TF + 参数注入 | `ros2 launch sru_nav_ros2 sru_nav.launch.py require_joystick:=false` 打印 `Navigation policy node is ready.` 且不刷错 |
|
||||
| **6. 移植 waypoint_runner + 文档** | `waypoint_runner.py` 改 rclpy(latch → TRANSIENT_LOCAL QoS);写 `docs/DEPLOY_ROS2.md` | `ros2 run sru_nav_ros2 waypoint_runner --waypoints "3,0 3,2"` 能发目标 |
|
||||
|
||||
### 上机验收命令(替换掉 ROS1 的 `rostopic` 一族)
|
||||
|
||||
```bash
|
||||
ros2 topic list | grep odin1 # ① 确认深度话题真实名字(关键)
|
||||
ros2 topic info -v /odin1/depth_img_competetion # ② 看 QoS:RELIABLE 还是 BEST_EFFORT
|
||||
ros2 topic hz /odin1/depth_img_competetion # ③ 应 ~10 Hz
|
||||
ros2 topic hz /odin1/odometry_highfreq # ④ 应 ~300–400 Hz
|
||||
ros2 topic echo /odin1/odometry_highfreq --once # ⑤ 看 frame_id / child_frame_id
|
||||
ros2 run sru_nav_ros2 waypoint_runner --waypoints "3,0" # ⑥ 发目标
|
||||
ros2 topic hz /cmd_vel # ⑦ 应稳定 ~5 Hz
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. `/cmd_vel` 桥(你的机型无关选择)
|
||||
|
||||
本包只发布 `geometry_msgs/msg/Twist`,不绑定任何机型。桥由你选:
|
||||
|
||||
| 平台 | 桥方案 |
|
||||
|---|---|
|
||||
| Unitree Go2 / B2 / B2W | `unitree_ros2` 官方包,或自写 50 行 sport_mode 桥(订阅 `/cmd_vel`) |
|
||||
| 其他腿足/轮式 | 厂商 SDK 自写订阅节点 |
|
||||
| 纯 ROS2 仿真 | 直接订阅 `/cmd_vel`,无需桥 |
|
||||
|
||||
安全默认值保持不变,**首次上机务必先抬轮/架空**:
|
||||
|
||||
```yaml
|
||||
policy_scale: [0.6, 0.3, 0.6] # 训练值本是 [1.5, 1.0, 1.0],此处保守一半以上;确认安全后逐步升
|
||||
require_joystick: true # 必须接手柄、推油门 axes[4] 才有速度;首测可用 false 旁路
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. 需要你实测/确认的未决项
|
||||
|
||||
| # | 项 | 为什么必须实测 | 不确认的后果 |
|
||||
|---|---|---|---|
|
||||
| 1 | Odin1 深度话题的真实名字 | 本仓库写 `/odin1/depth_img_competetion`,但驱动主线文档无此话题 | 节点收不到深度,`/cmd_vel` 恒为 0 |
|
||||
| 2 | Odin1 深度/里程计的 QoS | ROS2 特有,驱动端用 RELIABLE 还是 BEST_EFFORT 未知 | 订阅静默失败(不报错) |
|
||||
| 3 | odom 的 twist 是 world 还是 body 系 | 决定 `odom_twist_in_base_frame` 取 true/false | 速度指令剧烈震荡或方向错乱 |
|
||||
| 4 | odom 的 `header.frame_id` | `/goal_pose` 的 frame_id 必须与之一致,否则目标被直接拒绝 | 发目标无反应 |
|
||||
| 5 | Odin1 实际装订位置(xyz / rpy) | launch 里静态 TF 默认值来自 Go2 假设(x=0.25, z=0.18, pitch=0.349) | 深度图姿态与训练分布偏差,避障行为异常 |
|
||||
| 6 | `/joy` 轴与键索引 | Humble joy 包映射可能与 ROS1 不同,`constants.py` 的 PS5 索引需复核 | 手柄控制错位、deadman 推不动 |
|
||||
| 7 | 推理是否跟得上 5 Hz | 目标平台算力未知(模型合计 28 MB,CPU EP 一般够) | 控制频率掉到 5 Hz 以下,行为退化 |
|
||||
|
||||
---
|
||||
|
||||
## 10. 本轮不做的事(待你确认后再进行)
|
||||
|
||||
- 不写任何 ROS2 代码(本轮只要方案与清单)
|
||||
- 不改动 `SRU-Odin-orig` 下的任何原文件
|
||||
- 不新增 ROS2 包目录(§6 结构为规划,尚未落盘)
|
||||
- 不涉及训练侧(`Train/` 为 Isaac Sim 4.5 Docker,与本次部署迁移无关)
|
||||
|
||||
---
|
||||
|
||||
## 附:一句话总结
|
||||
|
||||
这个仓库的 ROS1 包是**从 ROS2 机械改写来的**,其中 508 行(模型推理、数学工具、常量)与 ROS 完全无关、可直接复用,314 行只需删包装类与注入时钟,真正要重写的是 **682 行的主节点 + 三个入口/launch/构建文件**;Odin1 驱动本身自带 ROS2 分支且官方推荐 Humble,所以整件事的难点不在功能,而在 **QoS 对齐、时间戳字段、`use_sim` 改名、以及深度话题名要实测**这四件事上。
|
||||
@@ -0,0 +1,470 @@
|
||||
# sru_ws 使用流程 —— SRU-Odin 无图端到端导航(ROS 2 Humble)
|
||||
|
||||
> **本文件定位**:「怎么用」的操作手册,位于工作区文档目录 `docs/`。
|
||||
> 原理与细节在 `src/sru_nav_ros2/docs/DEPLOY_ROS2.md`(权威,约 1000 行);
|
||||
> 交付/迁移流程在 `src/sru_nav_ros2/docs/HANDOVER_TEAM.md`;本机移植记录在 `docs/PORT_NOTES_2026-09-28.md`。
|
||||
>
|
||||
> 核实日期:2026-09-30。路径以本机为准:`WS=/home/xie/sru_nav_handover/sru_ws`;
|
||||
> 下文所有相对路径均相对 `$WS`。
|
||||
|
||||
---
|
||||
|
||||
## 0. 30 秒速查
|
||||
|
||||
```bash
|
||||
export WS=/home/xie/sru_nav_handover/sru_ws
|
||||
source /opt/ros/humble/setup.bash && source $WS/venv/bin/activate && source $WS/install/setup.bash
|
||||
|
||||
# 终端 A:驱动(含深度节点、rviz2)
|
||||
ros2 launch odin_ros_driver odin1_ros2.launch.py
|
||||
|
||||
# 终端 B:控制器
|
||||
ros2 launch sru_nav_ros2 sru_nav.launch.py # 正常(手柄 deadman 生效)
|
||||
ros2 launch sru_nav_ros2 sru_nav.launch.py require_joystick:=false launch_joy:=false # 冒烟(先抬轮!)
|
||||
|
||||
# 终端 C:发目标 + 看输出
|
||||
ros2 run sru_nav_ros2 waypoint_runner --waypoints "3,0"
|
||||
ros2 topic echo /cmd_vel
|
||||
```
|
||||
|
||||
**三句话记住这个工程**:
|
||||
|
||||
1. 它是**端到端反应式策略**:`深度图 + 16 维状态 → ONNX → /cmd_vel`。没有地图、没有 SLAM、**没有规划路径**。
|
||||
2. **没有深度就一条 `/cmd_vel` 都不发** —— 且连 `cmd_vel_ratio:` / `Published cmd_vel:` 日志都不会出现。
|
||||
3. **到达只看 XY 距离(0.75 m)**,朝向要单独用 `/goal_yaw` 指定。
|
||||
|
||||
---
|
||||
|
||||
## 1. 数据流
|
||||
|
||||
```
|
||||
/odin1/depth_img_competetion ─┐
|
||||
/odin1/odometry_highfreq ├─► sru_nav_node ─► /cmd_vel ─► [你的底盘桥,自备]
|
||||
/joy(deadman + 手动叠加) ┘ (ONNX Rt)
|
||||
▲
|
||||
└─ /goal_pose(位置) + /goal_yaw(朝向)
|
||||
```
|
||||
|
||||
| 事实 | 说明 |
|
||||
|---|---|
|
||||
| 三个速度**同时**输出 | 动作空间是 SE2 `[vx, vy, ω]`,不是"先转好再走" |
|
||||
| **机型无关** | 本包只发 `geometry_msgs/Twist` 到 `/cmd_vel`,桥自己写 |
|
||||
| 推理只由 `depth_callback` 触发 | 深度不到 ⇒ 无 `/cmd_vel`,这是**特征签名**,别去查本包代码 |
|
||||
| 节点名固定 `sru_nav_node` | 私有话题 `/sru_nav_node/vis/*` 与 ROS 1 蓝本一致,rviz 配置可复用 |
|
||||
| 控制频率 5 Hz 是**上限** | 输入只来 ~1.5 Hz 时会如实地慢跑,逻辑不跑偏 |
|
||||
|
||||
---
|
||||
|
||||
## 2. 目录与职责
|
||||
|
||||
| 路径 | 职责 | 能不能改 |
|
||||
|---|---|---|
|
||||
| `src/sru_nav_ros2/` | 交付包本体(含 2 个 ONNX,27 MB) | ✅ 按需 |
|
||||
| `src/sru_nav_ros2/config/sru_nav.yaml` | **唯一调参入口**(39 个参数) | ✅ |
|
||||
| `src/odin_ros_driver/` | Odin1 驱动源码(**编译期源码树**,配置由此处生效) | ⚠️ 见 §4.1 |
|
||||
| `docs/` | **工作区文档统一目录** —— `README.md`(索引,先看这个)、本文件、`PORT_NOTES_2026-09-28.md`、`HANDOVER.md`、`ROS2_PORT_PLAN.md`、`assets/` | ✅ |
|
||||
| `reference/` | 只剩 `COLCON_IGNORE` + `SRU-Odin/`(ROS 1 只读蓝本,`Deployment/models/*.onnx` 已删,与 `src/sru_nav_ros2/models/` 逐字节相同) | ❌ **禁止修改**(只做 diff 对照) |
|
||||
| `venv/` | Python 隔离环境(numpy 1.26.4 / onnxruntime / scipy 1.11.4) | ❌ 不要动内部 |
|
||||
| `install/`、`build/` | 构建产物(`install/` 是 source 对象) | ❌ 不要手改 |
|
||||
| `src/*/docs/` | 包内文档(随包安装到 `share/`,属包载荷) | ✅ 按需 |
|
||||
|
||||
> `log/`(colcon 构建日志)与 `src/odin_ros_driver/{log,map}/`(驱动运行期产物)
|
||||
> 已按需清理:前者可随时由 `colcon build` 重建,后者驱动启动时会自动 `create_directories`。
|
||||
|
||||
---
|
||||
|
||||
## 3. 环境(本机已就绪)
|
||||
|
||||
### 3.1 每次使用前必须 source 这三行(顺序无所谓,但三行都要)
|
||||
|
||||
```bash
|
||||
export WS=/home/xie/sru_nav_handover/sru_ws
|
||||
source /opt/ros/humble/setup.bash
|
||||
source $WS/venv/bin/activate
|
||||
source $WS/install/setup.bash
|
||||
```
|
||||
|
||||
`venv/bin/activate` 末尾有两行**不可删**(已在位):
|
||||
|
||||
```bash
|
||||
export PYTHONNOUSERSITE=1
|
||||
export PYTHONPATH="$WS/venv/lib/python3.10/site-packages${PYTHONPATH:+:$PYTHONPATH}"
|
||||
```
|
||||
|
||||
- `PYTHONNOUSERSITE=1`:挡住 `~/.local` 里 pip 版的 numpy/opencv 顶掉系统版本(否则 `import cv2` 段错误)。
|
||||
- `PYTHONPATH` 必须**追加式**(`${PYTHONPATH:+:$PYTHONPATH}`):覆盖式会冲掉 ROS 路径 →
|
||||
立刻变成 `No module named 'cv_bridge'`。ROS 工具链 shebang 硬编码 `#!/usr/bin/python3`,靠这行才看得见 venv 里的 onnxruntime。
|
||||
|
||||
### 3.2 自检(30 秒)
|
||||
|
||||
```bash
|
||||
cd $WS && colcon list # 期望两行:odin_ros_driver / sru_nav_ros2,stderr 为空
|
||||
python - <<'PY'
|
||||
import os, cv2, numpy, scipy, onnxruntime
|
||||
from cv_bridge import CvBridge
|
||||
print("NOUSERSITE", os.environ.get("PYTHONNOUSERSITE")) # 期望 1
|
||||
print("numpy ", numpy.__version__, numpy.__file__) # 期望 1.26.x @ venv
|
||||
print("cv2 ", cv2.__version__, cv2.__file__) # 注意:本机是 4.5.5 @ /usr/local/...(见 §10)
|
||||
print("scipy ", scipy.__version__) # 期望 1.11.4 @ venv
|
||||
print("ort ", onnxruntime.__version__, onnxruntime.get_available_providers())
|
||||
print("CvBridge", CvBridge())
|
||||
PY
|
||||
```
|
||||
|
||||
### 3.3 本机环境约束(会咬人的三条)
|
||||
|
||||
| 约束 | 处理 |
|
||||
|---|---|
|
||||
| `/tmp`、`/var`、`/dev/shm` 只有 **10 MB** | 任何 pip 操作前先 `export TMPDIR=/home/xie/.pip-tmp` |
|
||||
| `reference/COLCON_IGNORE` 与 `venv/COLCON_IGNORE` **必需** | 缺了 `colcon build` 会去爬 `reference/` 的 catkin 包和 site-packages,直接炸;两者已在位 |
|
||||
| venv **不能拷贝迁移** | 里面全是绝对路径;换机器要在新机器重建(见 HANDOVER_TEAM §2.3) |
|
||||
|
||||
---
|
||||
|
||||
## 4. 标准使用流程(3 个终端)
|
||||
|
||||
### 4.1 终端 A —— 启动 Odin1 驱动
|
||||
|
||||
```bash
|
||||
source /opt/ros/humble/setup.bash
|
||||
source $WS/install/setup.bash
|
||||
ros2 launch odin_ros_driver odin1_ros2.launch.py
|
||||
```
|
||||
|
||||
一次会拉起:`host_sdk_sample`(主驱动)+ `pcd2depth_ros2_node`(深度)+ 重投影 + overlay + **rviz2**。
|
||||
|
||||
| 要点 | 说明 |
|
||||
|---|---|
|
||||
| **USB 独占** | 绝不能同时跑两个 `host_sdk_sample`;重启前先 Ctrl-C 掉旧的 |
|
||||
| **启动顺序** | 深度节点会**等** `calib.yaml`(`$HOME/.ros/odin_ros_driver/calib.yaml`,由主驱动自动写出)。所以**驱动必须先起** |
|
||||
| **生效的配置** | 三个可执行都用编译期 `__FILE__` 反推出**源码树**再读 config(`host_sdk_sample.cpp:2491`、`pcd2depth_ros2.cpp:147`)。本机编译在此工作区 ⇒ 生效文件 = **`$WS/src/odin_ros_driver/config/control_command.yaml`** |
|
||||
| **`install/` 那份不生效** | 实测 `install/odin_ros_driver/share/.../control_command.yaml` 是**独立拷贝**且 `senddepth: 0`,而源码树份是 `1`。**别改错文件**,也别被它误导 |
|
||||
| **三个键必须为 1**(当前源码树份已全为 1) | `senddtof`(= `/odin1/cloud_raw`)、`sendrgb`(= `/odin1/image`)、`senddepth`(= 稠密深度)。深度节点用 `message_filters` 同步 **{cloud_raw + image} 一对**,少一路 ⇒ **永远没有深度 ⇒ 一条 `/cmd_vel` 都不发** |
|
||||
| 改完必须**整体重启驱动** | 这几个键属 `register_keys`,启动时下发给设备 |
|
||||
| `use_host_ros_time: 0` | odom 时间戳是**设备时钟**,与主机墙钟不同基准 ⇒ 开手柄前必须处理(见 §10) |
|
||||
|
||||
> 源码树份与 install 份的差异建议**同步一致**,避免下次误改。
|
||||
|
||||
### 4.2 确认"真的有数据"(关键一步,别用错判据)
|
||||
|
||||
```bash
|
||||
# ① 最权威:驱动自己写的设备状态日志
|
||||
CSV=$(ls -1t $WS/src/odin_ros_driver/log/Driver_*/Conn_*/dev_status.csv | head -1)
|
||||
head -1 "$CSV"; tail -1 "$CSV"
|
||||
```
|
||||
|
||||
期望(本机 2026-09-29 实测的一次健康采集,可直接对照):
|
||||
|
||||
```
|
||||
rgb_rx_odr=10.19 dtof_rx_odr=10.33 slam_cloud_rx_odr=9.84 slam_odom_highfreq_rx_odr=396.37
|
||||
```
|
||||
|
||||
读法:`*_tx_odr` 是设备发送率,`*_rx_odr` 是主机接收率。**`*_rx_odr = 0.00` 的那一路就是没通**(多是对应的 `send*` 开关关着)。
|
||||
|
||||
```bash
|
||||
# ② 辅助
|
||||
ros2 topic hz /odin1/odometry_highfreq # ~300-400 Hz(小消息,hz 可信)
|
||||
ros2 topic hz /odin1/depth_img_competetion # ~1.2-1.9 Hz(本机实测,深度图小,hz 可信)
|
||||
ros2 topic echo /odin1/depth_img_competetion --once --field encoding # 期望 32FC1
|
||||
```
|
||||
|
||||
⚠️ 判据陷阱:
|
||||
|
||||
| 方法 | 可靠性 |
|
||||
|---|---|
|
||||
| `ros2 topic list` | ❌ 存在**任一**端点(哪怕只有订阅者)就会列出来 |
|
||||
| `ros2 topic info` 的 `Publisher count` | ❌ 驱动启动就建好 publisher,没数据时照样是 1 |
|
||||
| `ros2 topic hz` | ✅ 唯一可信,但要排除大消息假象 |
|
||||
| `dev_status.csv` | ✅✅ 最权威 |
|
||||
|
||||
`/odin1/image` 是 1600×1296 bgr8 ≈ **6.2 MB/帧**,Python 订阅者跟不上会把 RELIABLE 发布端一起拖慢(10 Hz 会显示成 0.3 Hz)——**这是测量假象**。深度图 / 云不存在这个问题。
|
||||
|
||||
### 4.3 终端 B —— 启动控制器
|
||||
|
||||
```bash
|
||||
source /opt/ros/humble/setup.bash && source $WS/venv/bin/activate && source $WS/install/setup.bash
|
||||
|
||||
ros2 launch sru_nav_ros2 sru_nav.launch.py # 正常:deadman 生效
|
||||
ros2 launch sru_nav_ros2 sru_nav.launch.py require_joystick:=false launch_joy:=false # 冒烟:先抬轮/架空
|
||||
```
|
||||
|
||||
期望日志(出现这 4 行 = 模型加载成功、参数生效):
|
||||
|
||||
```
|
||||
[INFO] [sru_nav_node]: VAE encoder: .../share/sru_nav_ros2/models/vae_encoder.onnx
|
||||
[INFO] [sru_nav_node]: Policy model: .../share/sru_nav_ros2/models/nav_policy.onnx
|
||||
[INFO] [sru_nav_node]: Navigation policy node is ready.
|
||||
[INFO] [sru_nav_node]: SRU navigation node spinning (odom_twist_in_base_frame=True, require_joystick=...)
|
||||
```
|
||||
|
||||
**不是故障、别误判**:
|
||||
|
||||
- 没发目标时 `/cmd_vel` **恒为 0** 并每秒刷 `Target position reset.` —— 蓝本原有设计。
|
||||
- `waypoint_runner` 约 10 s 后把原地不动的目标判为 `STUCK` 并跳过 —— 车确实没动,是它的设计行为。
|
||||
⇒ 要看非零 `/cmd_vel`,盯**发目标后的头 10 秒**。
|
||||
|
||||
### 4.4 终端 C —— 发目标
|
||||
|
||||
见 §5。
|
||||
|
||||
---
|
||||
|
||||
## 5. 怎么发目标
|
||||
|
||||
### 5.1 推荐:`waypoint_runner`(外部客户端,不碰主节点)
|
||||
|
||||
```bash
|
||||
ros2 run sru_nav_ros2 waypoint_runner --waypoints "3,0"
|
||||
ros2 run sru_nav_ros2 waypoint_runner --waypoints "1,0 2,0 3,0,0,1.5708" # 第 4 个数 = yaw(弧度),只对最后一点要求朝向
|
||||
ros2 run sru_nav_ros2 waypoint_runner --waypoints "0,0,0,1.5708" --no-return-home # 纯原地转到 90°
|
||||
```
|
||||
|
||||
参数(`--help` 可查全部):
|
||||
|
||||
| 参数 | 默认 | 说明 |
|
||||
|---|---|---|
|
||||
| `--waypoints` / `-w` | — | 空格分隔的 `"x,y[,z[,yaw]]"`(yaw 单位**弧度**) |
|
||||
| `--file` / `-f` | — | 从 YAML 读航点(样例:`config/waypoints_example.yaml`) |
|
||||
| `--frame-id` | `odom` | 必须等于 odom 的 `header.frame_id`,否则目标被拒 |
|
||||
| `--timeout` | — | 单目标超时 |
|
||||
| `--arrive-threshold` | — | XY 到达阈值(要与节点一致,默认 0.75 m) |
|
||||
| `--goal-yaw-tolerance` | 0.0873 | 带 yaw 的路点的朝向容差(弧度),**必须与节点一致** |
|
||||
| `--return-home` / `--no-return-home` | 默认回起点 | 走完是否回起点 |
|
||||
|
||||
### 5.2 手发
|
||||
|
||||
```bash
|
||||
# 位置
|
||||
ros2 topic pub --once /goal_pose geometry_msgs/msg/PoseStamped \
|
||||
'{header: {frame_id: odom}, pose: {position: {x: 3.0, y: 0.0}}}'
|
||||
|
||||
# 朝向(弧度;NaN = 本目标不要求朝向)
|
||||
ros2 topic pub --once --qos-durability transient_local \
|
||||
/goal_yaw std_msgs/msg/Float64 '{data: 1.5708}'
|
||||
```
|
||||
|
||||
⚠️ `/goal_yaw` **必须带 `--qos-durability transient_local`**:节点是 TRANSIENT_LOCAL 订阅者,
|
||||
`ros2 topic pub` 默认 VOLATILE 发布者 ⇒ **不兼容、消息被静默丢弃**(发了完全没反应)。
|
||||
`waypoint_runner` 内部已是正确的,不用管。
|
||||
|
||||
⚠️ `/goal_pose` 的 `orientation` 字段**从不被读取**(到达只看 XY 距离)。朝向只能走 `/goal_yaw`。
|
||||
⚠️ `frame_id` 与 odom 的 `header.frame_id` 不一致 ⇒ 节点直接 error 拒绝。
|
||||
|
||||
### 5.3 路点间距:必须 ≥ 3–5 m
|
||||
|
||||
`ARRIVE_GOAL_THRESHOLD = 0.75 m` 且**发布即判到达**。所以:
|
||||
|
||||
| 间距 | 结果 |
|
||||
|---|---|
|
||||
| ≤ 0.75 m | **一步都不走**(发布那一刻就已"到达") |
|
||||
| 1.0 m | 每跳只推进 0.25 m,外加 1.5 s 静置,极慢 |
|
||||
| 2.0 m | 可用但偏碎 |
|
||||
| **3–5 m** | ✅ 推荐 |
|
||||
|
||||
每跳实际推进量 = 间距 − 0.75 m。
|
||||
|
||||
---
|
||||
|
||||
## 6. 判断"在正常工作"的判据
|
||||
|
||||
| 观察点 | 含义 |
|
||||
|---|---|
|
||||
| 启动打印 `Navigation policy node is ready.` | 两个 ONNX 加载成功 |
|
||||
| `spinning (odom_twist_in_base_frame=..., require_joystick=...)` 的值与你 YAML 一致 | 参数真的生效 |
|
||||
| `Odometry not ready, skipping depth callback.` 不再刷新 | odom 已就绪(这条的意思是"还没收到 odom",不是故障) |
|
||||
| 出现 `cmd_vel_ratio: 1.0000 (require_joystick=False)` | 深度已到、走推理分支 |
|
||||
| 出现 `Published cmd_vel: linear_x=... linear_y=... angular_z=...` 且非零 | ✅ 推理链路通了 |
|
||||
| `ros2 topic hz /cmd_vel` ≈ 5 Hz | 门控正常;本机实测只有 1.4–1.7 Hz(**上游慢**,见 §10) |
|
||||
| `/cmd_vel` 全 0 | 先确认**你发了目标**;再查 deadman / 目标是否比 0.75 m 还近 |
|
||||
|
||||
**安全上限的可证不变式**(实测已核对):`|linear_x| ≤ 0.6`、`|linear_y| ≤ 0.18`、`|angular_z| ≤ 0.6`。
|
||||
滤波是 `model_cmd` 与 `prev_cmd` 的**凸组合**(权重非负、和为 1)⇒ **不可能放大**。
|
||||
|
||||
### 在 rviz2 里看(可选)
|
||||
|
||||
Fixed Frame 必须设 **`odom`**(本工程没有 `map`)。Add → By topic:
|
||||
|
||||
| 加什么 | 含义 |
|
||||
|---|---|
|
||||
| `/sru_nav_node/vis/executed_path`(Path) | **实际走过的轨迹**(1 Hz 采样) |
|
||||
| `/sru_nav_node/vis/goal_path`(Path) | 当前位置 → 当前目标的直线 |
|
||||
| `/sru_nav_node/vis/twist_cmd_marker` | 策略发出的速度箭头 |
|
||||
| `/sru_nav_node/vis/goal_vector_marker` | 目标方向单位箭头 |
|
||||
| `/goal_pose`(Pose)、`/odin1/odometry_highfreq`(Odometry)、`/tf` | 目标、车体姿态、坐标树 |
|
||||
|
||||
⚠️ 再说一次:**没有"规划路径"**。`executed_path` 是走过的地方,不是计划。
|
||||
|
||||
---
|
||||
|
||||
## 7. 调参
|
||||
|
||||
### 7.1 改哪里 —— ⚠️ 本机有个坑
|
||||
|
||||
节点读的参数文件是 launch 默认的 **`install/sru_nav_ros2/share/sru_nav_ros2/config/sru_nav.yaml`**。
|
||||
**实测该文件是独立拷贝(与 `src/` 那份 inode 不同,不是符号链接)**。所以:
|
||||
|
||||
```bash
|
||||
# 方案 A(最省事,临时生效):直接用 src 那份启动
|
||||
ros2 launch sru_nav_ros2 sru_nav.launch.py \
|
||||
params_file:=$WS/src/sru_nav_ros2/config/sru_nav.yaml
|
||||
|
||||
# 方案 B(正式):改 src 后重建
|
||||
cd $WS && source /opt/ros/humble/setup.bash && source venv/bin/activate
|
||||
colcon build --symlink-install # 约 2 s
|
||||
# 重建后建议确认 install 份是否已变成符号链接:
|
||||
# stat -c '%i %h %n' src/sru_nav_ros2/config/sru_nav.yaml install/sru_nav_ros2/share/sru_nav_ros2/config/sru_nav.yaml
|
||||
# 若 inode 相同 ⇒ 以后改 src 即生效,免重建
|
||||
```
|
||||
|
||||
改完**必须重启进程**(改了不会热加载),但仍**不需要**重建(代码在 `build/` 侧是符号链接)。
|
||||
|
||||
### 7.2 绝对不能改的(与训练对齐,改了行为就废)
|
||||
|
||||
```
|
||||
control_frequency = 5.0 Hz policy_scale = [0.6, 0.3, 0.6] ← 训练值是 [1.5,1.0,1.0],部署刻意保守
|
||||
require_joystick = true rnn_hidden_size = 512 / rnn_num_layers = 1
|
||||
min/max_depth = 0.25 / 10.0 m resize(40, 64);latent 2560;obs 2576
|
||||
ARRIVE_GOAL_THRESHOLD = 0.75 m JOYSTICK_TIMEOUT = 15.0 s
|
||||
LOW_PASS_FILTER_COEF = [0.9,0.5,0.5] LATERAL_VELOCITY_SCALE = 0.6
|
||||
```
|
||||
|
||||
- 这些多数从 `constants.py` 取值,故意**不放进 YAML**,不给被误配的机会。
|
||||
- `constants.py` / `model.py` / `utils.py` 是**逐字节蓝本拷贝,不要改**。
|
||||
- 想改 `ARRIVE_GOAL_THRESHOLD`(例如降到训练值 0.5 m 以铺更密路点)属**要拍板**的改动,需同步改 runner 的 `--arrive-threshold`。
|
||||
|
||||
### 7.3 可以调的手柄 / 朝向参数(沿用 PS5 映射,**未在真手柄上验过**)
|
||||
|
||||
```bash
|
||||
ros2 param dump /sru_nav_node # 看当前全部取值
|
||||
ros2 param set /sru_nav_node goal_yaw_tolerance 0.05 # 临时改(重启失效)
|
||||
```
|
||||
|
||||
`goal_yaw_*` 组 7 个:`tolerance`(默认 0.0873 ≈ ±5°)、`max_rate`(0.6 rad/s)、
|
||||
`decel`(0.8 rad/s²)、`update_frequency`(20 Hz)、`settle_time`(0.4 s)、`timeout`(15 s)、`topic`。
|
||||
|
||||
调参方向:容差不够小 → 降 `tolerance`;过冲 → 减 `max_rate` 或 `decel`;抖 → 加大 `settle_time`。
|
||||
|
||||
---
|
||||
|
||||
## 8. 首次上机安全流程
|
||||
|
||||
1. **抬轮 / 架空**,别落地。
|
||||
2. 先确认驱动数据流(§4.1–4.2),再起控制器。
|
||||
3. `require_joystick:=false` 跑冒烟,`ros2 topic echo /cmd_vel` 确认数值**有界合理**(§6 的上限)。
|
||||
4. 确认急停手段:
|
||||
- 手柄按 `BUTTON_ABORT`(默认 index 9)→ 立刻发零速并放弃目标;
|
||||
- Ctrl-C 停 `sru_nav_node` → **但必须先确认底盘桥会不会自动归零**(见下);
|
||||
- 物理断电。
|
||||
5. 落地后先用**很慢**的 `policy_scale`(当前已是保守值)跑一次近目标(2–3 m),确认方向手感对了再放大。
|
||||
|
||||
⚠️ **`/cmd_vel` 桥(最容易出事故的点)**:本包只发 `Twist`,底盘桥自备。
|
||||
**上机前必须确认**:`sru_nav_node` 被杀掉后,桥**会不会自动归零**?不会的话,节点一死机器人会**保持最后一条速度指令继续跑**。
|
||||
|
||||
**开手柄前必须先处理**:`use_host_ros_time: 0` 导致 odom 是**设备时钟**,而 deadman 判断式是
|
||||
`odom 时间戳 − time.time() > 15 s`,**混算两个时间域** ⇒ 要么一上来就超时(`/cmd_vel` 恒 0),
|
||||
要么 deadman 事实上失效(更危险)。**处理:把驱动的 `use_host_ros_time` 改成 `1` 或 `2` 后整体重启驱动。**
|
||||
(`require_joystick:=false` 时这段逻辑不执行,所以无载体测试不受影响。)
|
||||
|
||||
---
|
||||
|
||||
## 9. 排错速查(症状 → 原因)
|
||||
|
||||
| 症状 | 原因 / 去处 |
|
||||
|---|---|
|
||||
| `/cmd_vel` **一条都没有**,日志里连 `cmd_vel_ratio:` / `Published cmd_vel:` 都不出现 | **深度没到**。`generate_cmd_vel` 只被 `depth_callback` 调用。查 §4.1 三个键 + §4.2 判据 |
|
||||
| `/cmd_vel` 有输出但**全 0** | ① 根本没发目标(最常见,会刷 `Target position reset.`);② deadman(`axes[4]` 没推过);③ 目标距车 < 0.75 m |
|
||||
| `ModuleNotFoundError: No module named 'onnxruntime'` | 没 `source venv/bin/activate`;或缺 `PYTHONPATH` 追加行(§3.1) |
|
||||
| `No module named 'cv_bridge'` | `PYTHONPATH` 被**覆盖式**写法冲掉了 ROS 路径(§3.1) |
|
||||
| `import cv2` 段错误 / `_ARRAY_API not found` | 缺 `PYTHONNOUSERSITE=1`;或 `~/.local` 里装了 pip 版 opencv(卸掉) |
|
||||
| `colcon build` 报找不到 catkin / 冒出一堆无关包名 | `reference/` 或 `venv/` 缺 `COLCON_IGNORE` |
|
||||
| `topic list` 里有 `/odin1/...` 但收不到数据 | 用 `ros2 topic hz` 判;`topic info` 的 Publisher count 不算数 |
|
||||
| 深度没数据(3 种原因) | ① `senddepth: 0` → 深度节点打印 "Depth image will not be published." 后**直接退出**;② `sendrgb: 0` → 只来一半;③ **`senddtof: 0`**(最易漏,名字像"传感器开关",其实是"发原始点云") |
|
||||
| 改了 `control_command.yaml` 毫无变化 | 改错文件了 —— 要改**源码树**那份(§4.1),且改完**整体重启驱动** |
|
||||
| `waypoint_runner` 报 `No odometry received ... within 30.0s` | 驱动没起,或该话题无发布者。蓝本原始设计,不是 bug |
|
||||
| 启动就崩 `AttributeError: ... has no attribute 'xxx'` | 改了代码但**没重启进程** |
|
||||
| 铺密集路点但一步都不走 | 间距 ≤ 0.75 m(§5.3) |
|
||||
| 位置到了但不自转对准 | 没发 `/goal_yaw`;或话题名不一致;或 deadman 超时(打印 `Joystick timeout during goal-heading alignment`) |
|
||||
| 订阅了却收不到深度且不报错 | **QoS 不匹配**:BEST_EFFORT 发布端 + RELIABLE 订阅端 = 静默收不到。用 `ros2 topic info -v` 对比两端 |
|
||||
| Twist 剧烈震荡 | ① `policy_scale` 太大;② `odom_twist_in_base_frame` 判反;③ 深度 NaN 没被过滤 |
|
||||
| 其它 | `DEPLOY_ROS2.md` §8 排错速查表(约 20 条) |
|
||||
|
||||
---
|
||||
|
||||
## 10. 已知限制 / 未验证项(上机前必读)
|
||||
|
||||
### 10.1 已定性的"不是 bug 的 bug"
|
||||
|
||||
| 项 | 结论 |
|
||||
|---|---|
|
||||
| `/cmd_vel` 只有 1.4–1.7 Hz,深度只有 1.2–1.9 Hz,而设备端是 10 Hz | **8 倍损耗发生在驱动的发布/DDS 环节**。本节点平均 CPU 只占 11%(89% 空等),**已排除本包**。`control_frequency: 5.0` 在代码里是**上限**不是目标值 ⇒ 本包只是如实转发上游速率,逻辑与 5 Hz 时一致 |
|
||||
| 可疑点 | 驱动里两个大话题硬编码 `qos_sensor = rclcpp::QoS(5)`(odom 用 `QoS(4000)`,所以 odom 正常)。候选修法:`QoS(5)` → `QoS(50)`(1 行 + 重编)。⛔ **绝不能只把发布端改成 BEST_EFFORT**,会让现有 RELIABLE 读者静默收不到任何数据 |
|
||||
|
||||
### 10.2 必须上机实测(本机未验)
|
||||
|
||||
| # | 项 | 现状 |
|
||||
|---|---|---|
|
||||
| 1 | **Odin1 装订外参** | 默认值是 Rc2026 比赛车 R2 的实测装订(`base_link` 在 `odin1_base_link` 下 `-0.268846, 0.028504, 0.067861, 0.017828, 0.245433, 0`),**不是本机载体**。接车后必须重测,改 launch 参数 `base_link_x/y/z/roll/pitch/yaw` |
|
||||
| 2 | 目标朝向精度(±5° 是设计目标) | 逻辑就位,**从未在真机验证** |
|
||||
| 3 | `/joy` 轴/键索引(17 个参数) | 沿用 PS5 映射,未在真手柄上验 |
|
||||
| 4 | **deadman 时钟域** | 见 §8,开手柄前必须先改 `use_host_ros_time` |
|
||||
| 5 | odom twist 正负号手感 | 未验,判反会让车反向跑 |
|
||||
| 6 | `/cmd_vel` 桥 | 底盘侧桥是否存在、节点死后是否自动归零 —— **未确认,最易出事故的点** |
|
||||
| 7 | `/sru_nav_node/vis/*` 可视化 | 未在 rviz 里实地看过 |
|
||||
|
||||
### 10.3 环境上的已知偏差(未处理)
|
||||
|
||||
- **`cv2` 是 4.5.5 @ `/usr/local/lib/python3.10/dist-packages`**(散装目录,无 dist-info),
|
||||
而文档期望 4.5.4 @ `/usr/lib/python3/dist-packages`。
|
||||
实测 `import cv2` 正常、`CvBridge()` 正常、launch 冒烟正常。
|
||||
⚠️ **没动它**:`/home/xie/techx_R2_algorithm/` 下的 `light_signal_detector` 等节点也 `import cv2`,
|
||||
删/挪可能影响 Rc2026 那套。**要不要对齐需拍板。**
|
||||
- 本次会话是 root,`/home/xie` 为 `drwxr-x--- root root` ⇒ 普通用户 xie 可能进不了自己家目录。
|
||||
|
||||
### 10.4 残余量(仅记录)
|
||||
|
||||
Odin1 若带俯仰角安装,`odom_twist_in_base_frame: true` 下 `linear.x` 会被乘上约 `cos(pitch)`,
|
||||
并出现一点虚假的 `linear.z`。参考工程也这么接受;精确补偿需要一次 TF 查询(属新增功能,未做)。
|
||||
|
||||
---
|
||||
|
||||
## 附录 A:关键路径一览(本机)
|
||||
|
||||
| 东西 | 路径 |
|
||||
|---|---|
|
||||
| 工作区 | `/home/xie/sru_nav_handover/sru_ws` |
|
||||
| venv | `$WS/venv`(activate 末尾两行 export 不可删) |
|
||||
| 节点参数(调参入口) | `src/sru_nav_ros2/config/sru_nav.yaml`(生效副本在 `install/sru_nav_ros2/share/.../config/`,见 §7.1) |
|
||||
| 模型 | `src/sru_nav_ros2/models/{vae_encoder,nav_policy}.onnx` |
|
||||
| 驱动配置(**生效**) | `$WS/src/odin_ros_driver/config/control_command.yaml` |
|
||||
| 标定(驱动自动写) | `$HOME/.ros/odin_ros_driver/calib.yaml` |
|
||||
| 驱动设备状态日志 | `$WS/src/odin_ros_driver/log/Driver_*/Conn_*/dev_status.csv` |
|
||||
| 节点日志(ROS 自带) | `$HOME/.ros/log/` |
|
||||
|
||||
## 附录 B:记录数据(可选)
|
||||
|
||||
```bash
|
||||
# 写 $HOME 下,别写 /tmp(本机 /tmp 只有 10 MB)
|
||||
rm -rf $HOME/depthbag && ros2 bag record -o $HOME/depthbag /odin1/depth_img_competetion /cmd_vel
|
||||
# 前台跑,约 10 s 后按一次 Ctrl-C;然后
|
||||
ros2 bag info $HOME/depthbag # 用 Message count / Duration 手算速率
|
||||
```
|
||||
|
||||
## 附录 C:参数速查(命令行覆盖)
|
||||
|
||||
```bash
|
||||
ros2 launch sru_nav_ros2 sru_nav.launch.py require_joystick:=false launch_joy:=false # 旁路 deadman
|
||||
ros2 launch sru_nav_ros2 sru_nav.launch.py launch_static_tf:=false # 不发静态 TF
|
||||
ros2 launch sru_nav_ros2 sru_nav.launch.py odom_twist_in_base_frame:=false # 临时翻语义
|
||||
ros2 launch sru_nav_ros2 sru_nav.launch.py base_link_x:=-0.20 base_link_pitch:=0.0 # 装订外参
|
||||
ros2 launch sru_nav_ros2 sru_nav.launch.py params_file:=$WS/src/sru_nav_ros2/config/sru_nav.yaml
|
||||
```
|
||||
|
||||
> `require_joystick` / `odom_twist_in_base_frame` 的 launch 默认值是**从 YAML 读出来的**(不是写死),
|
||||
> 所以改 YAML 就够了;命令行 `:=` 只是临时覆盖。
|
||||
|
||||
---
|
||||
|
||||
**最后一句**:跑不通时先分清是"**本包**"还是"**物理世界那一半**"——
|
||||
`/cmd_vel` 完全没输出 ⇒ 找驱动的深度(§4);
|
||||
`/cmd_vel` 有输出但数值/方向不对 ⇒ 找装订外参、twist 正负号、deadman(§8、§10.2)。
|
||||
**把日志原文发出来,比描述现象有用得多。**
|
||||
@@ -0,0 +1,20 @@
|
||||
Tcl_0: [-0.002730, -0.999970, -0.007210, 0.030500,
|
||||
0.006180, 0.007190, -0.999960, -0.007700,
|
||||
0.999980, -0.002770, 0.006160, -0.004420,
|
||||
0.000000, 0.000000, 0.000000, 1.000000]
|
||||
cam_0:
|
||||
image_width: 1600
|
||||
image_height: 1296
|
||||
k2: -0.029021
|
||||
k3: 0.125546
|
||||
k4: -0.319762
|
||||
k5: 0.365260
|
||||
k6: -0.208654
|
||||
k7: 0.045440
|
||||
p1: 0.000000
|
||||
p2: 0.000000
|
||||
A11: 734.689860
|
||||
A12: 0.020513
|
||||
A22: 735.073544
|
||||
u0: 804.508941
|
||||
v0: 621.747400
|
||||
@@ -0,0 +1,9 @@
|
||||
# colcon must not crawl this directory.
|
||||
#
|
||||
# `reference/` holds the read-only ROS 1 blueprint (ManifoldTechLtd/SRU-Odin,
|
||||
# the `Deployment/` catkin package `sru_nav_go2_ros1` plus the Isaac Sim `Train/`
|
||||
# tree). `colcon build` crawls the whole workspace recursively, not just `src/`,
|
||||
# so without this marker it tries to catkin-build the ROS 1 package, which fails
|
||||
# on Humble with: Could not find a package configuration file provided by "catkin".
|
||||
#
|
||||
# The mere existence of this file is what matters. See docs/DEPLOY_ROS2.md.
|
||||
Binary file not shown.
@@ -0,0 +1,37 @@
|
||||
cmake_minimum_required(VERSION 3.0.2)
|
||||
project(sru_nav_go2_ros1)
|
||||
|
||||
find_package(catkin REQUIRED COMPONENTS
|
||||
rospy
|
||||
std_msgs
|
||||
sensor_msgs
|
||||
geometry_msgs
|
||||
nav_msgs
|
||||
visualization_msgs
|
||||
cv_bridge
|
||||
tf2_ros
|
||||
)
|
||||
|
||||
catkin_python_setup()
|
||||
|
||||
catkin_package(
|
||||
CATKIN_DEPENDS
|
||||
rospy
|
||||
std_msgs
|
||||
sensor_msgs
|
||||
geometry_msgs
|
||||
nav_msgs
|
||||
visualization_msgs
|
||||
cv_bridge
|
||||
tf2_ros
|
||||
)
|
||||
|
||||
catkin_install_python(PROGRAMS
|
||||
scripts/sru_nav_node
|
||||
DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
|
||||
)
|
||||
|
||||
install(DIRECTORY launch config models
|
||||
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}
|
||||
OPTIONAL
|
||||
)
|
||||
@@ -0,0 +1,130 @@
|
||||
# sru_nav_go2_ros1
|
||||
|
||||
ROS 1 (Noetic) port of the SRU autonomous navigation controller, adapted for a
|
||||
**Unitree Go2 + Odin1** stack.
|
||||
|
||||
> 📘 **Want to reproduce or retarget this package?**
|
||||
> See **[`docs/PORTING_GUIDE.md`](docs/PORTING_GUIDE.md)** (中文)
|
||||
> or **[`docs/PORTING_GUIDE_EN.md`](docs/PORTING_GUIDE_EN.md)** (English)
|
||||
> for the full porting decision log + an AI agent slash command
|
||||
> (`/port-sru-to-ros`) that regenerates this package from the upstream
|
||||
> SRU repos and the paper, plus an automated `scripts/verify_port.sh`
|
||||
> acceptance script.
|
||||
|
||||
It is a near-1:1 port of
|
||||
`<upstream-package-path>/sru-robot-deployment/rl_nav_controller/rl_nav_controller/rl_nav_controller.py`
|
||||
with the following substitutions:
|
||||
|
||||
| Original (ROS2, B2W + ZedX + DLIO) | This port (ROS1, Go2 + Odin1) |
|
||||
| ----------------------------------------------------------- | ----------------------------------------- |
|
||||
| `/zed/zed_node/depth/depth_registered` (sensor_msgs/Image) | `/odin1/depth_img_competetion` |
|
||||
| `/dlio/odom_node/odom` (nav_msgs/Odometry) | `/odin1/odometry_highfreq` (~400 Hz) |
|
||||
| `/path_manager/path_manager_ros/nav_vel` (Twist) | `/cmd_vel` |
|
||||
| `rclpy` / Jazzy | `rospy` / Noetic |
|
||||
| `POLICY_SCALE = [1.5, 1.0, 1.0]` (wheeled B2W) | `POLICY_SCALE = [0.6, 0.3, 0.6]` (Go2) |
|
||||
|
||||
Inference is unchanged: ONNX VAE depth encoder (output 2560-dim latent) +
|
||||
LSTM SRU policy (hidden 512, h/c carried as explicit ONNX inputs/outputs).
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
sru_nav_go2_ros1/
|
||||
├── CMakeLists.txt
|
||||
├── package.xml
|
||||
├── setup.py
|
||||
├── README.md
|
||||
├── config/sru_nav.yaml # all runtime parameters
|
||||
├── launch/sru_nav_go2.launch # joy + static TF + main node
|
||||
├── models/ # symlinks to deployment_policies/
|
||||
│ ├── vae_encoder.onnx -> ../../sru-robot-deployment/.../vae_encoder.onnx
|
||||
│ └── nav_policy.onnx -> ../../sru-robot-deployment/.../nav_policy.onnx
|
||||
├── scripts/sru_nav_node # executable rospy entry point
|
||||
└── src/sru_nav_go2/ # importable Python package
|
||||
├── constants.py # tunables (Go2-conservative defaults)
|
||||
├── utils.py # quaternion/transform helpers (pure numpy)
|
||||
├── model.py # ONNX runtime wrapper (LearningModel)
|
||||
├── visualization.py # rviz Marker helpers
|
||||
├── waypoint_manager.py
|
||||
└── navigation_policy_node.py # ported NavigationPolicyNode (rospy)
|
||||
```
|
||||
|
||||
## Build
|
||||
|
||||
Place this directory inside a catkin workspace and build:
|
||||
|
||||
```bash
|
||||
mkdir -p ~/sru_ws/src
|
||||
ln -s /home/lfd/project/SRU_Navigation/sru_nav_go2_ros1 ~/sru_ws/src/
|
||||
cd ~/sru_ws
|
||||
catkin_make # or catkin build
|
||||
source devel/setup.bash
|
||||
```
|
||||
|
||||
## Python dependencies (on Go2's NX, ROS Noetic / Python 3.8+)
|
||||
|
||||
```bash
|
||||
pip install numpy scipy opencv-python onnxruntime # or onnxruntime-gpu
|
||||
```
|
||||
|
||||
For Jetson with CUDA, install the JetPack-matched `onnxruntime-gpu` wheel from
|
||||
[NVIDIA's Jetson Zoo](https://elinux.org/Jetson_Zoo#ONNX_Runtime).
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
# 1) Bring up Odin1 (publishes /odin1/depth_img_competetion and /odin1/odometry)
|
||||
roslaunch odin_ros_driver odin1_ros.launch
|
||||
# Make sure config/control_command.yaml has senddepth: 1 and sendodom: 1.
|
||||
|
||||
# 2) Bring up your Go2 cmd_vel bridge (subscribes to /cmd_vel, drives sport mode)
|
||||
# (Your existing setup.)
|
||||
|
||||
# 3) Launch the SRU navigation node + joy
|
||||
roslaunch sru_nav_go2_ros1 sru_nav_go2.launch
|
||||
|
||||
# 4) Send a goal (in odom frame)
|
||||
rostopic pub /goal_pose geometry_msgs/PoseStamped "{
|
||||
header: {frame_id: 'odom'},
|
||||
pose: {position: {x: 3.0, y: 0.0, z: 0.0}, orientation: {w: 1.0}}
|
||||
}" --once
|
||||
```
|
||||
|
||||
## Tuning knobs (in `config/sru_nav.yaml`)
|
||||
|
||||
- `policy_scale` — start at `[0.6, 0.3, 0.6]`. Increase gradually after
|
||||
verifying tracking and safety on Go2.
|
||||
- `min_depth` / `max_depth` — depth clipping (meters). Default 0.25–10.0.
|
||||
- `control_frequency` — keep at 5 Hz (matches training).
|
||||
|
||||
## Static TF (camera mounting)
|
||||
|
||||
Override in the launch line, e.g.:
|
||||
|
||||
```bash
|
||||
roslaunch sru_nav_go2_ros1 sru_nav_go2.launch \
|
||||
odin1_x:=0.30 odin1_z:=0.22 odin1_pitch:=0.30
|
||||
```
|
||||
|
||||
This must reflect the **real** Odin1 mounting on Go2 (forward distance,
|
||||
height, downward pitch) for correct depth-to-body alignment.
|
||||
|
||||
## Safety
|
||||
|
||||
The joystick acts as a deadman switch. The robot will not move until you
|
||||
push the throttle axis (axis 4, default scale `1.0 + axis[4]`) above 0.
|
||||
After `JOYSTICK_TIMEOUT` (15 s) without a joy message the controller
|
||||
clamps the cmd_vel ratio to zero.
|
||||
|
||||
## Known caveats vs. the original deployment
|
||||
|
||||
1. Odin1's dense depth (`depth_img_competetion`) is computed host-side and is
|
||||
labelled "high computing power required" in the driver README. On Jetson
|
||||
Xavier NX this may bottleneck before the policy itself does — verify with
|
||||
`rostopic hz /odin1/depth_img_competetion` first.
|
||||
2. Odom twist frame: original code calls `convert_vel_frame` when
|
||||
`use_sim=False`, assuming world-frame twist. If Odin1 publishes twist
|
||||
already in `child_frame_id` (`odin1_base_link`) this would double-rotate.
|
||||
Verify on real hardware; if so, set `use_sim: true` in the YAML.
|
||||
3. The pretrained policy was trained on B2W kinematics. Zero-shot transfer
|
||||
to Go2 is unverified; treat the first runs as evaluation, not deployment.
|
||||
@@ -0,0 +1,37 @@
|
||||
# Runtime parameters for sru_nav_node (Go2 + Odin1).
|
||||
# Load via: <rosparam command="load" file="$(find sru_nav_go2_ros1)/config/sru_nav.yaml"/>
|
||||
|
||||
# ---- Topics ---------------------------------------------------------------
|
||||
depth_topic: "/odin1/depth_img_competetion" # sensor_msgs/Image (32FC1, meters)
|
||||
odom_topic: "/odin1/odometry_highfreq" # nav_msgs/Odometry @ ~400 Hz (IMU rate), frame_id=odom, child=odin1_base_link
|
||||
# alt: /odin1/odometry @ ~10 Hz (SLAM rate, less drift but laggier)
|
||||
joy_topic: "/joy" # sensor_msgs/Joy (PS5-like layout)
|
||||
goal_topic: "/goal_pose" # geometry_msgs/PoseStamped
|
||||
cmd_vel_topic: "/cmd_vel" # geometry_msgs/Twist (consumed by Go2 sport mode)
|
||||
|
||||
# ---- Model files (leave empty -> auto-discover under <pkg>/models/) -------
|
||||
vae_model_path: ""
|
||||
policy_model_path: ""
|
||||
|
||||
# ---- Depth filter ---------------------------------------------------------
|
||||
min_depth: 0.25 # meters
|
||||
max_depth: 10.0 # meters
|
||||
|
||||
# ---- Control --------------------------------------------------------------
|
||||
control_frequency: 5.0 # Hz (matches training)
|
||||
# Conservative defaults for Go2 (original B2W used [1.5, 1.0, 1.0]). Tune up
|
||||
# gradually during real testing.
|
||||
policy_scale: [0.6, 0.3, 0.6] # [vx_max, vy_max, omega_max]
|
||||
|
||||
# ---- Sim flag -------------------------------------------------------------
|
||||
# When true the odom twist is treated as already in the base frame.
|
||||
use_sim: false
|
||||
|
||||
# ---- Joystick deadman -----------------------------------------------------
|
||||
# true (default, SAFE): /cmd_vel stays 0 until a /joy publisher exists AND
|
||||
# axes[4] (throttle trigger) is pushed; 15 s without
|
||||
# /joy forces a stop. Use this on real hardware.
|
||||
# false (TESTING ONLY) : skip the deadman; cmd_vel_ratio starts at 1.0 and
|
||||
# the timeout check is disabled. Useful for headless
|
||||
# / autonomous closed-loop tests with no operator.
|
||||
require_joystick: true
|
||||
@@ -0,0 +1,26 @@
|
||||
# Example waypoint list for scripts/waypoint_runner.py
|
||||
#
|
||||
# All waypoints are in the odometry frame (matches what /goal_pose expects).
|
||||
# z is optional; if 0 the main node substitutes the robot's current z.
|
||||
|
||||
frame_id: odom
|
||||
|
||||
# Arrival / timing
|
||||
arrive_threshold: 0.75 # meters (matches constants.ARRIVE_GOAL_THRESHOLD)
|
||||
settle_time: 1.5 # seconds the robot must stay within threshold
|
||||
per_goal_timeout: 60.0 # seconds before giving up on a single goal
|
||||
|
||||
# Stuck detection (script-side; no main-node changes required)
|
||||
stuck_window: 10.0 # seconds of trailing window
|
||||
stuck_displacement: 0.10 # meters; below this -> skip current goal
|
||||
|
||||
# Republish the same goal periodically to defend against missed messages.
|
||||
republish_interval: 5.0
|
||||
|
||||
# Append the script-start odom pose as a final goal after the list.
|
||||
return_home: true
|
||||
|
||||
waypoints:
|
||||
- [3.0, 0.0, 0.0]
|
||||
- [3.0, 2.0, 0.0]
|
||||
- [0.0, 2.0, 0.0]
|
||||
@@ -0,0 +1,271 @@
|
||||
# 部署指南:Go2 NX 上的 `sru_nav_go2_ros1`
|
||||
|
||||
环境前提(已确认):
|
||||
- Go2 onboard NX 已安装 **ROS 1 Noetic**
|
||||
- 已安装 **odin_ros_driver**(发布 `/odin1/*` 话题)
|
||||
- 已安装 **unitree_legged_sdk** + 一个把 `/cmd_vel` 桥接到 Go2 sport_mode 的节点
|
||||
- Odin1 depth 频率 = 10 Hz,odom_highfreq 频率 = 400 Hz
|
||||
|
||||
---
|
||||
|
||||
## 1. 把本包放进 catkin 工作空间
|
||||
|
||||
```bash
|
||||
mkdir -p ~/sru_ws/src
|
||||
ln -s /path/to/SRU_Navigation/sru_nav_go2_ros1 ~/sru_ws/src/sru_nav_go2_ros1
|
||||
cd ~/sru_ws
|
||||
catkin_make
|
||||
source devel/setup.bash
|
||||
```
|
||||
|
||||
> 模型 ONNX 文件位于 `sru_nav_go2_ros1/models/` 下(软链到 `sru-robot-deployment/.../deployment_policies/`)。
|
||||
> 部署到 Go2 NX 时如果没有原仓库,把 `vae_encoder.onnx` 与 `nav_policy.onnx` 直接拷到 `sru_nav_go2_ros1/models/` 即可。
|
||||
|
||||
---
|
||||
|
||||
## 2. 创建 Python conda 环境
|
||||
|
||||
为什么用 conda:onnxruntime / scipy 等 pip 包不污染系统 ROS python;NX (aarch64) 上 miniforge 是最稳的选择。
|
||||
|
||||
```bash
|
||||
cd ~/sru_ws/src/sru_nav_go2_ros1
|
||||
bash scripts/setup_conda_env.sh
|
||||
```
|
||||
|
||||
脚本会:
|
||||
1. 检测 `conda`(没有的话提示安装 miniforge for aarch64)
|
||||
2. 创建名为 `sru_nav` 的环境(**python=3.8**,与 Noetic 系统 python 匹配,才能复用 `rospy` / `cv_bridge`)
|
||||
3. 安装 `numpy / scipy / opencv-python / onnxruntime / rospkg / pyyaml / empy`
|
||||
4. 跑一系列 import sanity check,并尝试加载两个 ONNX 模型,打印输入输出维度
|
||||
|
||||
**GPU 加速(可选)**:标准 pip 的 `onnxruntime-gpu` 在 Jetson 上**不能用**。需要去 [NVIDIA Jetson Zoo](https://elinux.org/Jetson_Zoo#ONNX_Runtime) 下载 JetPack 匹配的 `onnxruntime_gpu-*-cp38-cp38-linux_aarch64.whl`,然后:
|
||||
|
||||
```bash
|
||||
conda activate sru_nav
|
||||
pip install ./onnxruntime_gpu-<ver>-cp38-cp38-linux_aarch64.whl
|
||||
```
|
||||
|
||||
不装 GPU 版本也能跑(CPU EP 上 5 Hz 推理在 NX 上一般够用,因为模型只有 ~28 MB)。
|
||||
|
||||
### 验证环境
|
||||
|
||||
```bash
|
||||
bash scripts/setup_conda_env.sh --check
|
||||
```
|
||||
|
||||
期望输出关键行:
|
||||
```
|
||||
[OK] numpy ...
|
||||
[OK] scipy ...
|
||||
[OK] cv2 ...
|
||||
[OK] onnxruntime ...
|
||||
ORT providers : ['CPUExecutionProvider'] # 或包含 CUDAExecutionProvider
|
||||
[OK] rospy ...
|
||||
[OK] cv_bridge ...
|
||||
```
|
||||
|
||||
如果 `rospy` / `cv_bridge` 失败:确认 `/opt/ros/noetic/lib/python3/dist-packages` 存在且 conda env 使用 python 3.8。
|
||||
|
||||
---
|
||||
|
||||
## 3. 启动流程
|
||||
|
||||
打开 4 个终端(或用 tmux)。
|
||||
|
||||
### Terminal 1 — Odin1 驱动
|
||||
|
||||
确保 `odin_ros_driver/config/control_command.yaml` 中:
|
||||
```yaml
|
||||
senddepth: 1 # 启用 dense depth
|
||||
sendodom: 1 # 启用 odom + odometry_highfreq
|
||||
```
|
||||
|
||||
```bash
|
||||
cd ../OAYN
|
||||
mamba activate neupan
|
||||
source ros_ws/devel/setup.zsh
|
||||
export ROS_MASTER_URI=http://localhost:11311
|
||||
export ROS_HOSTNAME=localhost
|
||||
export ROS_IP=127.0.0.1
|
||||
sudo ntpdate -u ntp.aliyun.com
|
||||
roslaunch odin_ros_driver odin1_ros1.launch # 实际 launch 文件名以驱动包为准
|
||||
```
|
||||
|
||||
### Terminal 2 — Go2 cmd_vel 桥
|
||||
|
||||
你现有的 unitree_legged_sdk 桥接节点,它订阅 `/cmd_vel`,下发到 Go2 sport_mode。
|
||||
|
||||
```bash
|
||||
mamba activate sru_nav
|
||||
export ROS_MASTER_URI=http://localhost:11311
|
||||
export ROS_HOSTNAME=localhost
|
||||
export ROS_IP=127.0.0.1
|
||||
source devel/setup.zsh
|
||||
rosrun unitree_control unitree_vel_controller __name:=vel_to_sdk
|
||||
```
|
||||
|
||||
### Terminal 3 — SRU 导航节点(本包)
|
||||
|
||||
```bash
|
||||
mamba activate sru_nav
|
||||
export ROS_MASTER_URI=http://localhost:11311
|
||||
export ROS_HOSTNAME=localhost
|
||||
export ROS_IP=127.0.0.1
|
||||
cd src/sru_nav_go2_ros1
|
||||
bash scripts/launch_sru_nav.sh
|
||||
# require_joystick=true,必须接手柄,axes[4] 推油门,15 s 看护
|
||||
|
||||
bash scripts/launch_sru_nav.sh --no-deadman
|
||||
# require_joystick=false,cmd_vel_ratio 直接 1.0
|
||||
# 发一个 /goal_pose,policy 就会驱动 /cmd_vel
|
||||
```
|
||||
|
||||
`launch_sru_nav.sh` 自动做:source ROS → source catkin_ws → conda activate sru_nav → 把 `/opt/ros/noetic/lib/python3/dist-packages` 注入 `PYTHONPATH` → `roslaunch sru_nav_go2_ros1 sru_nav_go2.launch`。
|
||||
|
||||
如果手柄 `/joy` 已经在别处启动:
|
||||
```bash
|
||||
bash scripts/launch_sru_nav.sh --no-joy
|
||||
```
|
||||
|
||||
如果不需要静态 TF(你自己发了 `base_link → odin1_base_link`):
|
||||
```bash
|
||||
bash scripts/launch_sru_nav.sh --no-tf
|
||||
```
|
||||
|
||||
### Terminal 4 — 发目标 / 监控
|
||||
|
||||
```bash
|
||||
# 推一个 3 m 前方的目标(odom 帧)
|
||||
mamba activate sru_nav
|
||||
export ROS_MASTER_URI=http://localhost:11311
|
||||
export ROS_HOSTNAME=localhost
|
||||
export ROS_IP=127.0.0.1
|
||||
source devel/setup.zsh
|
||||
rostopic pub /goal_pose geometry_msgs/PoseStamped \
|
||||
"{header: {frame_id: 'odom'},
|
||||
pose: {position: {x: 3.0, y: 0.0, z: 0.0}, orientation: {w: 1.0}}}" --once
|
||||
|
||||
# 检查输出
|
||||
rostopic hz /cmd_vel # 应稳定 ~5 Hz
|
||||
rostopic echo /cmd_vel -n 5
|
||||
```
|
||||
|
||||
# 或者发布连续waypoints
|
||||
```bash
|
||||
mamba activate sru_nav
|
||||
export ROS_MASTER_URI=http://localhost:11311
|
||||
export ROS_HOSTNAME=localhost
|
||||
export ROS_IP=127.0.0.1
|
||||
source devel/setup.zsh
|
||||
cd src/sru_nav_go2_ros1
|
||||
rosrun sru_nav_go2_ros1 waypoint_runner.py \
|
||||
--file config/waypoints_example.yaml
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 首跑前的 sanity check 命令
|
||||
|
||||
```bash
|
||||
# 4.1 频率检查
|
||||
rostopic hz /odin1/depth_img_competetion # 应 ~10 Hz
|
||||
rostopic hz /odin1/odometry_highfreq # 应 ~400 Hz
|
||||
|
||||
# 4.2 深度数据合理性
|
||||
rostopic echo /odin1/depth_img_competetion -n 1 | head -20
|
||||
# 关注 encoding:"32FC1", height/width, 不全为 0
|
||||
|
||||
# 4.3 odom frame
|
||||
rostopic echo /odin1/odometry_highfreq -n 1 | head -20
|
||||
# 关注 header.frame_id="odom", child_frame_id="odin1_base_link"
|
||||
|
||||
# 4.4 节点状态
|
||||
rosnode info /sru_nav_node
|
||||
rostopic list | grep sru_nav
|
||||
|
||||
# 4.5 关闭 Go2 cmd_vel 桥,单跑导航节点空载,看推理输出
|
||||
rostopic echo /cmd_vel
|
||||
# 拖动 Odin1 / 发个 /goal_pose,看 /cmd_vel 是否产生非零有界数值
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. 如何判断 odom twist 的坐标系?
|
||||
|
||||
**这是上机前必须确认的**。理论上 `child_frame_id="odin1_base_link"` 暗示 twist 是 body frame,但很多 SLAM 实现仍在 world frame 输出 twist——必须实测。
|
||||
|
||||
### 方法 A:静止判断(最快)
|
||||
|
||||
让 Odin1 完全静止:
|
||||
```bash
|
||||
rostopic echo -n 20 /odin1/odometry_highfreq | grep -A2 twist
|
||||
```
|
||||
所有 `linear.*` 和 `angular.*` 都应该接近 0。这一步只能排除"非零偏置 bug",分不出 world/body。
|
||||
|
||||
### 方法 B:纯前进运动
|
||||
|
||||
让 Go2 静止站立,**手动**将 Odin1 沿其镜头方向(body +X)匀速推进 1 米,过程录制:
|
||||
```bash
|
||||
rosbag record -O /tmp/odom_test.bag /odin1/odometry_highfreq
|
||||
```
|
||||
然后:
|
||||
```bash
|
||||
rosbag play /tmp/odom_test.bag
|
||||
rqt_plot /odin1/odometry_highfreq/twist/twist/linear/x:y
|
||||
```
|
||||
- 如果 `linear.x` 是显著正值、`linear.y` 几乎 0 → **body frame**(已经是 base 系)
|
||||
- 如果 `linear.x` 与 `linear.y` 数值与机体当前 yaw 有关(旋转 Odin1 朝向再做同样测试,结果改变)→ **world frame**
|
||||
|
||||
### 方法 C:旋转判断(推荐,更确定)
|
||||
|
||||
把 Odin1 朝任意非零方向放置(比如绕 Z 转 90°),再沿 body +X 推进:
|
||||
- **body frame**:无论朝向如何,`linear.x` 总是正、`linear.y` ≈ 0
|
||||
- **world frame**:朝向 +Y 推进时 `linear.y` 是正、`linear.x` ≈ 0
|
||||
|
||||
### 方法 D:对比 dt 数值导数
|
||||
|
||||
```python
|
||||
# 对位置做数值导数,与 twist 对比
|
||||
import rosbag, numpy as np
|
||||
bag = rosbag.Bag('/tmp/odom_test.bag')
|
||||
ts, pos, twist_lin = [], [], []
|
||||
for _, msg, _ in bag.read_messages(topics=['/odin1/odometry_highfreq']):
|
||||
ts.append(msg.header.stamp.to_sec())
|
||||
pos.append([msg.pose.pose.position.x, msg.pose.pose.position.y, msg.pose.pose.position.z])
|
||||
twist_lin.append([msg.twist.twist.linear.x, msg.twist.twist.linear.y, msg.twist.twist.linear.z])
|
||||
ts, pos, twist_lin = map(np.array, (ts, pos, twist_lin))
|
||||
vel_world = np.diff(pos, axis=0) / np.diff(ts)[:, None]
|
||||
print('vel_world (sample):', vel_world[100])
|
||||
print('twist_lin (sample):', twist_lin[100])
|
||||
# 若两者数值在世界系几乎一致 → twist 是 world frame
|
||||
# 若 twist_lin 与 vel_world 大小相同但方向旋转 → twist 是 body frame
|
||||
```
|
||||
|
||||
### 根据结果配置本节点
|
||||
|
||||
- twist **是 world frame**:保持 `use_sim: false`(节点会按机体 quaternion 反旋转到 base 系,与原 DLIO 部署一致)。
|
||||
- twist **是 body frame**:在 `config/sru_nav.yaml` 把 `use_sim` 设为 `true`,节点会直接透传 twist。
|
||||
|
||||
---
|
||||
|
||||
## 6. 常见问题
|
||||
|
||||
| 现象 | 排查 |
|
||||
|---|---|
|
||||
| `pip` 报 `SSL: CERTIFICATE_VERIFY_FAILED ... certificate is not yet valid` | **系统时钟回退了**(Jetson 无 RTC 电池时常见)。`date` 看一下,然后 `sudo timedatectl set-ntp true && sudo systemctl restart systemd-timesyncd`,或离线 `sudo date -s "2026-05-28 14:55:00" && sudo hwclock --systohc`。`setup_conda_env.sh` 已加前置检测。 |
|
||||
| conda 报 `Unexpected error writing token file ... aau_token_host` | anaconda.org 遥测 bug,无害。脚本里 `export ANACONDA_ANON_USAGE=false` 已静音。 |
|
||||
| pip 太慢 / 拉不动 | `setup_conda_env.sh` 默认走清华源;若要换 `PIP_INDEX_URL=... bash scripts/setup_conda_env.sh`。 |
|
||||
| 节点启动后 `Odometry not ready, skipping depth callback.` | `rostopic hz /odin1/odometry_highfreq` 是否在跑?frame_id 是否正确? |
|
||||
| `/cmd_vel` 全是 0 | 手柄 deadman——`axes[4]` 必须推过 0;或 15 s 超时。看 `cmd_vel_ratio` 日志。 |
|
||||
| Twist 数值剧烈震荡 | 1) `policy_scale` 太大;2) odom twist 坐标系判错(world↔body 弄反);3) depth NaN 没被过滤 |
|
||||
| `cv_bridge` import 失败 | conda env 必须是 python 3.8;并且 `PYTHONPATH` 已包含 `/opt/ros/noetic/lib/python3/dist-packages` |
|
||||
| 推理速度跟不上 5 Hz | `rostopic hz /cmd_vel`;用 `nvtop`/`top` 看 NX 满载情况;考虑装 JetPack onnxruntime-gpu wheel |
|
||||
| Goal 发出后立即被忽略 | `/goal_pose` 的 `frame_id` 必须等于 `/odin1/odometry_highfreq` 的 `header.frame_id`(默认 `odom`) |
|
||||
|
||||
---
|
||||
|
||||
## 7. 紧急停止
|
||||
|
||||
- 手柄按下 `BUTTON_ABORT`(默认 button index 9) → 立刻发零速、放弃当前目标
|
||||
- 直接 `Ctrl+C` 杀掉 `sru_nav_node` → `/cmd_vel` 不再有发布者,Go2 桥应自动归零(依你的桥行为)
|
||||
- 关闭电源开关(终极手段)
|
||||
@@ -0,0 +1,441 @@
|
||||
# 把 SRU 导航策略移植到 Odin1 + ROS1 的完整复现指南
|
||||
|
||||
> 从论文 *Spatially-Enhanced Recurrent Memory for Long-Range Mapless Navigation via End-to-End Reinforcement Learning* 与配套开源仓库
|
||||
> [`sru-project-website`](https://michaelfyang.github.io/sru-project-website/) 出发,把 SRU 端到端导航策略部署到 **Odin1 深度相机 + ROS1 Noetic + 任意能消费 `geometry_msgs/Twist`(`/cmd_vel`)的机器人**(默认硬件参考为 Unitree Go2)。本仓库 `sru_nav_go2_ros1` 即为此目标的产物。
|
||||
>
|
||||
> **English version**: see `PORTING_GUIDE_EN.md`.
|
||||
|
||||
---
|
||||
|
||||
## 0. 这份文档是什么 / 不是什么
|
||||
|
||||
**是**:一份「移植决策记录 + AI 复刻 prompt + 自动验收脚本」的三合一指南。读完即可:
|
||||
|
||||
1. 知道我们为什么这样改、改了哪些点;
|
||||
2. 用一个 slash command 让 AI agent(Cascade / Claude Code 等)从开源仓库与论文出发,**自动重新生成本仓库**;
|
||||
3. 用一个脚本一键校验生成结果是否合格。
|
||||
|
||||
**不是**:算法原理讲解(请直接读论文与原始代码仓)。
|
||||
|
||||
**适用读者**:
|
||||
- 已具备 Ubuntu + ROS1 + Python/conda 基本使用能力;
|
||||
- 持有 Unitree Go2(或任何能订阅 `/cmd_vel` 的腿足/轮式机器人)+ Odin1 深度相机;
|
||||
- 想在自己机器人上跑 SRU,或想验证「AI agent 是否能从论文+开源代码复刻一个真机部署包」。
|
||||
|
||||
> 0 门槛承诺:除上述前置技能外,所有路径、IP、机器人型号、摄像头型号都设计为**通过环境变量或参数覆盖**,不用改源码。
|
||||
|
||||
---
|
||||
|
||||
## 1. 上游来源
|
||||
|
||||
| 资产 | 链接 / 路径 | 在本移植里的角色 |
|
||||
|---|---|---|
|
||||
| 论文 | *Spatially-Enhanced Recurrent Memory for Long-Range Mapless Navigation via End-to-End Reinforcement Learning* | 解释观测/动作空间、奖励、网络结构(VAE 深度编码器 + LSTM-SRU + actor head) |
|
||||
| 项目主页 | <https://michaelfyang.github.io/sru-project-website/> | 索引仓库、视频、论文 |
|
||||
| `sru-navigation-learning` | RL 训练代码(rsl_rl 风格)。给出 PPO/MDPO 算法、reward terms、observation manager | 用于核对 **reward 设计、动作 squash、观测层次**,并取得 ONNX 导出脚本 |
|
||||
| `sru-navigation-sim` | IsaacLab 环境,含 B2W / AOW 训练配置 | 取得 `policy_scaling`、随机化范围、观测形状(depth `64×5×8`)等关键数字 |
|
||||
| `sru-robot-deployment` | 原作者在 Unitree B2W + ZED-X 上的真机部署 | **本仓库直接对照重写的对象**:原版用 PyTorch + DLIO odom + 自研 SDK 桥;本仓库换成 ONNX + Odin1 odom + Go2 桥 |
|
||||
| `sru-pytorch-spatial-learning` | SRU/LSTM-SRU 单元的 PyTorch 实现 | 解释 RNN 隐状态形状(`rnn_hidden_size=512, num_layers=1`),导出 ONNX 时的状态展开方式 |
|
||||
| `sru-depth-pretraining` | VAE depth encoder 的预训练 | 取得 `vae_encoder.onnx` 的输入形状(`H×W` 深度图归一化后单通道)与潜变量维度 |
|
||||
|
||||
如果你不打算复刻、只想跑:把训练完得到的两个 onnx(`vae_encoder.onnx` + `nav_policy.onnx`)丢到 `sru_nav_go2_ros1/models/`,跳到 §6。
|
||||
|
||||
---
|
||||
|
||||
## 2. 移植目标矩阵
|
||||
|
||||
| 维度 | 原作者部署 (`sru-robot-deployment`) | 本仓库 (`sru_nav_go2_ros1`) | 抽象后接口 |
|
||||
|---|---|---|---|
|
||||
| 机器人 | Unitree **B2W**(轮足) | Unitree **Go2**(纯腿足) | 任何订阅 `/cmd_vel` (`geometry_msgs/Twist`, body frame) 的机器人 |
|
||||
| 深度传感 | ZED-X | **Odin1**(`32FC1` depth, ~10 Hz) | `~depth_topic` (`sensor_msgs/Image`, 32FC1, 米) |
|
||||
| 里程计 | DLIO(自研 LIO) | Odin1 `odometry_highfreq` | `~odom_topic` (`nav_msgs/Odometry`, world frame) |
|
||||
| 推理后端 | PyTorch JIT | **ONNX Runtime** | `models/{vae_encoder,nav_policy}.onnx` |
|
||||
| 计算平台 | x86 工控机 | **Jetson Orin NX (aarch64) + conda py3.8** | 任何 Linux + ROS1 Noetic + conda |
|
||||
| 控制频率 | ~10 Hz | **5 Hz**(与训练一致;Odin depth ~10 Hz 自然降采样) | `~control_frequency` |
|
||||
| 操作员手柄 | PS5 PerceptiveNavigationSE2 | 同 PS5 mapping,**新增 `require_joystick: false`** 头模式 | `--no-deadman` / yaml `require_joystick` |
|
||||
| 安装与启动 | rosinstall 全家桶 | **`setup_conda_env.sh` + `launch_sru_nav.sh`** 两脚本 | env vars `ENV_NAME / ROS_DISTRO / CATKIN_WS` 全部可覆盖 |
|
||||
|
||||
---
|
||||
|
||||
## 3. 核心移植决策(逐项说明动机与对照位置)
|
||||
|
||||
### 3.1 推理:PyTorch → ONNX Runtime
|
||||
|
||||
- **动机**:Jetson Orin NX 上装 PyTorch + cv_bridge + onnxruntime 的依赖网很容易爆;onnxruntime 单文件加载、CPU/GPU EP 切换简单;ARM wheel 现成。
|
||||
- **接口**:`@/sru_nav_go2_ros1/src/sru_nav_go2/model.py` 实现 `LearningModel`,分别加载 `vae_encoder.onnx`(深度→latent)与 `nav_policy.onnx`(latent + 状态向量 + 上一动作 + LSTM hidden → action mean + 新 hidden)。
|
||||
- **隐状态约定**:训练侧 `rnn_hidden_size=512, num_layers=1`;导出 ONNX 时把 `(h, c)` 作为输入输出张量,本端在每帧之间显式持有;`reset_hidden_state` 对应训练里 `is_first` 标志。
|
||||
- **action squash**:网络已包含 `tanh`,输出在 `(-1, 1)`。本端再乘 `policy_scale=[vx_max, vy_max, ω_max]`(默认 `[0.6, 0.3, 0.6]`)得到 SI 单位速度。
|
||||
|
||||
### 3.2 观测层:Odin1 替代 ZED-X + DLIO
|
||||
|
||||
- **深度图**:Odin1 发布 `sensor_msgs/Image` (`32FC1`,单位米)。`@/sru_nav_go2_ros1/src/sru_nav_go2/navigation_policy_node.py:209-225` 里做:
|
||||
1. `cv_bridge.imgmsg_to_cv2(passthrough)`;
|
||||
2. `nan_to_num(nan=0, posinf=2*max_depth, neginf=0)`;
|
||||
3. 截断到 `[min_depth, max_depth] = [0.25, 10.0] m`,超界置 0。
|
||||
- **里程计帧约定**:Odin1 odom 的 twist 是 **world frame**。我们在 `odom_callback` 里用机体四元数把它反旋到 body frame(与训练对齐)。如果你的 odom 已经是 body frame,把 `use_sim: true` 透传即可(`@/sru_nav_go2_ros1/src/sru_nav_go2/navigation_policy_node.py:189-197`)。
|
||||
- **goal 帧约定**:`/goal_pose.header.frame_id` 必须等于 odom 的 `frame_id`(默认 `odom`),否则节点直接拒绝 — 这是为了防止操作员误把机体系坐标当成 odom 系发出去。
|
||||
|
||||
### 3.3 动作下发:直接 `/cmd_vel`
|
||||
|
||||
- 原作者在 B2W 上自带 SDK 桥;Go2 直接用 unitree_legged_sdk 写一个订阅 `/cmd_vel` 的小节点(与本仓库分离)即可。本包**不**绑定具体桥。
|
||||
- `policy_scale` 默认 `[0.6, 0.3, 0.6]` 比训练侧 `[1.5, 1.0, 1.0]` 保守一半多,给真机留余量;训练时已经做过 `Uniform(0.6, 1.2)` 的 scale 随机化,所以网络对运行时缩放鲁棒。
|
||||
|
||||
### 3.4 安全:手柄 deadman 双模
|
||||
|
||||
| 模式 | 触发 | 行为 |
|
||||
|---|---|---|
|
||||
| 默认 (`require_joystick=true`) | 实机部署 | `cmd_vel_ratio=0`,必须 `/joy` 持续发布且 `axes[4]` 推到正才有速度;`>15 s` 无 joy → 强制归零 |
|
||||
| 测试 (`require_joystick=false`) | `--no-deadman` 或 yaml 改 false | 起步即 `cmd_vel_ratio=1.0`,无 joy 也跑。**只在抬轮 / 仿真 / 空旷场地**用 |
|
||||
|
||||
代码位置:`@/sru_nav_go2_ros1/src/sru_nav_go2/navigation_policy_node.py:118-121, 272-287`。
|
||||
|
||||
### 3.5 安装层:conda + 系统 ROS 共生
|
||||
|
||||
Jetson Orin NX 出厂有 ROS Noetic(系统 python3.8 + cv_bridge.so);同时我们要 onnxruntime / opencv / numpy 等只在 conda env 里好装。两个世界要打通:
|
||||
|
||||
1. **PYTHONPATH 注入**:`/opt/ros/noetic/lib/python3/dist-packages` 加到 conda python 的搜索路径,使 `rospy / cv_bridge / sensor_msgs / tf2_ros` 可 import。
|
||||
2. **shebang 锁定**:catkin_make 时必须 `-DPYTHON_EXECUTABLE=$(which python3)` **在 conda env 已激活** 状态下跑,否则 `devel/lib/.../sru_nav_node` 的 `#!` 会指向 `/usr/bin/python3`,import onnxruntime 失败。
|
||||
3. **ABI 冲突修复**:conda env 自带的 `libffi.so.7` 和系统 `libp11-kit.so.0` 版本符号不兼容,导致 `cv_bridge` 调 OpenCV 时崩溃(`undefined symbol: ffi_type_pointer, version LIBFFI_BASE_7.0`)。`launch_sru_nav.sh` 自动 `LD_PRELOAD=/lib/aarch64-linux-gnu/libffi.so.7` 提前加载系统 libffi。
|
||||
4. **rospy 隐性依赖**:`netifaces` / `defusedxml` 在系统 python 里靠 apt 提供,conda env 里要 pip 装。`setup_conda_env.sh` 已加进默认列表。
|
||||
5. **时钟检查**:Jetson 无 RTC 电池常导致系统时间回退,pip TLS 拒接握手。脚本里前置 `date` 检测并提示 `ntpdate / timedatectl`。
|
||||
|
||||
完整自动化脚本:`@/sru_nav_go2_ros1/scripts/setup_conda_env.sh` + `@/sru_nav_go2_ros1/scripts/launch_sru_nav.sh`。
|
||||
|
||||
### 3.6 故意删减项
|
||||
|
||||
| 训练里有的东西 | 部署里去掉的原因 |
|
||||
|---|---|
|
||||
| Heightmap / heightscan critic | Go2 不带 LiDAR/heightmap,需要的话外部话题再加 |
|
||||
| 距离/动量等 critic 通道 | critic 仅训练用,推理只跑 actor head |
|
||||
| MDPO / distillation 双 actor-critic 互蒸馏 | 训练阶段优化器结构,与导出后的 actor 无关 |
|
||||
| 训练时 reward terms 计算 | 部署不需要计算 reward |
|
||||
| Action scale randomization (`Uniform(0.6, 1.2)`) | 部署是固定缩放;网络已经被训练成对该范围鲁棒 |
|
||||
|
||||
---
|
||||
|
||||
## 4. 文件清单与职能
|
||||
|
||||
```
|
||||
sru_nav_go2_ros1/
|
||||
├── CMakeLists.txt # catkin 包定义;catkin_python_setup() + install scripts
|
||||
├── package.xml # 依赖:rospy, sensor_msgs, geometry_msgs, nav_msgs, cv_bridge, tf2_ros
|
||||
├── setup.py # 把 src/sru_nav_go2 装成 python 包
|
||||
├── README.md
|
||||
├── config/
|
||||
│ ├── sru_nav.yaml # 运行时全部 ROS 参数;唯一应该被用户改的文件
|
||||
│ └── waypoints_example.yaml # 多目标巡航示例(odom 系列点)
|
||||
├── launch/
|
||||
│ └── sru_nav_go2.launch # joy_node + static_tf + sru_nav_node
|
||||
├── models/
|
||||
│ ├── vae_encoder.onnx # 训练侧 export_onnx 产物
|
||||
│ └── nav_policy.onnx
|
||||
├── scripts/
|
||||
│ ├── setup_conda_env.sh # 创建 sru_nav env,装 onnxruntime/cv2/netifaces…
|
||||
│ ├── launch_sru_nav.sh # 一键启动 wrapper(含 LD_PRELOAD / PYTHONPATH 修复)
|
||||
│ ├── sru_nav_node # ROS 节点入口(catkin 安装时拷到 devel/lib/...)
|
||||
│ └── waypoint_runner.py # 顺序发 /goal_pose
|
||||
├── src/sru_nav_go2/
|
||||
│ ├── constants.py # 所有训练对齐常量(控制频率、轴键映射、scale 等)
|
||||
│ ├── model.py # ONNX Runtime 封装:VAE encoder + LSTM-SRU policy
|
||||
│ ├── navigation_policy_node.py # 主节点:odom/depth/joy/goal 回调 + cmd_vel 输出
|
||||
│ ├── utils.py # 四元数<->旋转、reproject 等数学小工具
|
||||
│ ├── visualization.py # rviz marker(目标向量、moving_goal、waypoint)
|
||||
│ └── waypoint_manager.py # 录制/回放 waypoint 列表
|
||||
└── docs/
|
||||
├── DEPLOY_GO2_NX.md # 部署到 NX 的实战记录
|
||||
└── PORTING_GUIDE.md # ← 你正在读的文件
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. 用 AI Agent 自动复刻本仓库
|
||||
|
||||
我们提供 **同一份移植 prompt 的三种调用形式**(内容等价,挑顺手的用):
|
||||
|
||||
| 入口 | 适用工具 | 启动方式 |
|
||||
|---|---|---|
|
||||
| `.windsurf/workflows/port-sru-to-ros.md` | Cascade(Windsurf IDE) | 在 Cascade 聊天框里输 `/port-sru-to-ros` |
|
||||
| `.claude/commands/port-sru-to-ros.md` | Claude Code (CLI / IDE 插件) | `claude` 启动后 `/port-sru-to-ros` |
|
||||
| `docs/PORTING_PROMPT.md` | 任意支持自定义 prompt 的 agent(Cursor、Continue、Aider…) | 把整篇内容粘进系统提示 / 任务描述 |
|
||||
|
||||
三个文件由同一份「**真理 prompt**」生成,差异只在启动头与文件路径约定。下面是完整的 prompt 内容(放在 `.windsurf/workflows/port-sru-to-ros.md` 里以 frontmatter 起头)。
|
||||
|
||||
> ⚠️ **可重复性边界**:现役 LLM 在生成 ~1500 LoC 的 ROS 移植代码时,单次成功率不是 100%。我们用 **分阶段 workflow** 把任务切成 6 步,每步都有可 grep 的验收点;任意一步偏题立刻回滚重试,比一次性长 prompt 的成功率高一个数量级。
|
||||
|
||||
### 5.1 分阶段 workflow 概览
|
||||
|
||||
| 阶段 | 输入 | 输出 | 验收 |
|
||||
|---|---|---|---|
|
||||
| 1. **勘查** | 上游 5 个仓库 + 论文 | 摘要 `notes/upstream_recon.md`:算法、观测/动作、I/O 形状、训练超参 | 文件存在且包含网络层数、obs dims、policy_scale |
|
||||
| 2. **抽取推理路径** | `sru-navigation-learning` 的 export_onnx | `models/vae_encoder.onnx`、`models/nav_policy.onnx`、`docs/IO_SPEC.md` | onnxruntime 可加载,输入/输出名/形状记录 |
|
||||
| 3. **生成 ROS 包骨架** | 上一步 IO_SPEC | `package.xml / CMakeLists.txt / setup.py / launch/ / config/sru_nav.yaml` | `catkin_make` 通过 |
|
||||
| 4. **移植节点逻辑** | 原 `sru-robot-deployment` 节点 + IO_SPEC | `src/sru_nav_go2/{constants,model,utils,visualization,waypoint_manager,navigation_policy_node}.py` + `scripts/sru_nav_node` | 节点能 `roslaunch` 起来不 crash |
|
||||
| 5. **写部署脚本** | 目标 platform 信息 | `scripts/setup_conda_env.sh` + `scripts/launch_sru_nav.sh` | 在干净 env 上跑通 §6 验收命令 |
|
||||
| 6. **文档与验收** | 全部产物 | `README.md / docs/DEPLOY_*.md / scripts/verify_port.sh` | `bash scripts/verify_port.sh` 全绿 |
|
||||
|
||||
### 5.2 通用 prompt(与三个入口文件一致的核心内容)
|
||||
|
||||
```text
|
||||
你是一名熟悉 ROS1 Noetic、conda、ONNX Runtime 与 PyTorch 的高级工程师。
|
||||
|
||||
【任务】
|
||||
从以下上游资料出发,生成一个名为 `sru_nav_go2_ros1` 的 catkin 包,
|
||||
把论文《Spatially-Enhanced Recurrent Memory for Long-Range Mapless
|
||||
Navigation via End-to-End Reinforcement Learning》提出的端到端导航策略
|
||||
部署到 Odin1 深度相机 + ROS1 Noetic + 任意能消费
|
||||
`geometry_msgs/Twist (/cmd_vel)` 的机器人上。
|
||||
|
||||
【上游资料】
|
||||
- 论文 PDF(按用户提供的路径读取,例如 ./2506.05997v2.pdf)
|
||||
- 项目主页 https://michaelfyang.github.io/sru-project-website/
|
||||
- 仓库(按用户工作区下子文件夹):
|
||||
sru-navigation-learning — RL 训练 + ONNX 导出
|
||||
sru-navigation-sim — IsaacLab 环境与训练配置
|
||||
sru-robot-deployment — 原作者 B2W+ZED-X 真机部署(直接对标重写)
|
||||
sru-pytorch-spatial-learning — SRU/LSTM-SRU 单元
|
||||
sru-depth-pretraining — VAE depth encoder 预训练
|
||||
- 已存在的 onnx 模型(如有):models/{vae_encoder,nav_policy}.onnx
|
||||
|
||||
【硬约束】
|
||||
1. 目标传感器固定为 Odin1。深度话题默认 `/odin1/depth_img_competetion`
|
||||
(sensor_msgs/Image, 32FC1, 单位米);里程计默认
|
||||
`/odin1/odometry_highfreq` (nav_msgs/Odometry, world frame)。
|
||||
2. 控制输出固定为 `/cmd_vel` (geometry_msgs/Twist, body frame),由调用方
|
||||
桥接到具体机器人;本包不实现机器人 SDK 桥。
|
||||
3. 推理后端只能用 onnxruntime(不引入 PyTorch 运行时依赖)。
|
||||
4. 必须支持 conda env (默认 `sru_nav`, py3.8) 与系统 ROS 共生:
|
||||
- PYTHONPATH 注入 /opt/ros/<DISTRO>/lib/python3/dist-packages
|
||||
- 启动脚本 LD_PRELOAD 系统 libffi 修复 cv_bridge 的 ABI 冲突
|
||||
- catkin_make 时锁定 PYTHON_EXECUTABLE 为 conda python
|
||||
5. 所有路径、env、distro、机器人型号必须可被环境变量或 ROS 参数覆盖;
|
||||
不得在源码里硬写 `/home/<user>` 一类 path。
|
||||
6. 保留训练对齐的全部数值(control_frequency=5Hz, rnn_hidden=512,
|
||||
policy_scale 默认 [0.6,0.3,0.6],joystick axis 映射等)。
|
||||
7. 关键安全机制:手柄 deadman + 15 s 超时;提供 `require_joystick:
|
||||
false` 旁路开关,但默认必须为 true。
|
||||
|
||||
【输出文件清单】(缺一不可)
|
||||
package.xml, CMakeLists.txt, setup.py
|
||||
launch/sru_nav_go2.launch
|
||||
config/sru_nav.yaml, config/waypoints_example.yaml
|
||||
scripts/setup_conda_env.sh, scripts/launch_sru_nav.sh,
|
||||
scripts/sru_nav_node, scripts/waypoint_runner.py, scripts/verify_port.sh
|
||||
src/sru_nav_go2/{__init__.py, constants.py, model.py, utils.py,
|
||||
visualization.py, waypoint_manager.py,
|
||||
navigation_policy_node.py}
|
||||
docs/DEPLOY.md, docs/PORTING_GUIDE.md (中文), docs/PORTING_GUIDE_EN.md
|
||||
models/README.md (说明从训练侧导出 onnx 的步骤)
|
||||
|
||||
【工作流程】(必须按顺序,每步完成后 self-check 再进下一步)
|
||||
Step 1 — 勘查上游:读取仓库与论文,列出网络架构、观测维度、动作空间、
|
||||
rsl_rl 算法配置、reward 列表,输出到 notes/upstream_recon.md。
|
||||
Step 2 — IO 规范化:在训练仓里找到 export_onnx 入口,记录 vae_encoder
|
||||
与 nav_policy 的 input/output 名与 shape,写到 docs/IO_SPEC.md。
|
||||
Step 3 — 生成 catkin 骨架并 `catkin_make` 验证。
|
||||
Step 4 — 实现节点:以 sru-robot-deployment 的 node 为模板,
|
||||
替换传感器话题、剥离非 Odin 依赖、把 PyTorch 调用换成 onnxruntime。
|
||||
Step 5 — 编写两份脚本(setup_conda_env.sh / launch_sru_nav.sh),
|
||||
覆盖 §硬约束 4 的全部点。
|
||||
Step 6 — 生成 verify_port.sh:检查包结构、shebang 指向、ONNX 推理、
|
||||
rostopic 列表、yaml 必填字段。
|
||||
|
||||
【验收标准】(用户会跑 verify_port.sh 与下述命令)
|
||||
1. `catkin_make` 在干净 catkin_ws 下 0 warning 0 error。
|
||||
2. `bash scripts/setup_conda_env.sh --check` 全部通过。
|
||||
3. `head -1 devel/lib/sru_nav_go2_ros1/sru_nav_node` 指向
|
||||
conda env 的 python,不是 /usr/bin/python3。
|
||||
4. `roslaunch sru_nav_go2_ros1 sru_nav_go2.launch require_joystick:=false`
|
||||
起来后看到 `Navigation policy node is ready.` 且不刷错误。
|
||||
5. 用 `rostopic pub` 发任意 odom + 一帧 32FC1 depth + 一个 goal_pose,
|
||||
`/cmd_vel` 应输出非零 Twist。
|
||||
6. `bash scripts/verify_port.sh` 全部 PASS。
|
||||
|
||||
【回答方式】
|
||||
- 严禁直接生成 1000+ 行的单条回复;按 Step 拆分,每步先汇报计划再写文件。
|
||||
- 每步结束后跑相应 self-check,把命令与输出贴回;自检失败立即修复。
|
||||
- 如果上游仓库找不到某文件,明确报告并暂停,不得编造接口。
|
||||
```
|
||||
|
||||
完整可直接执行的版本见 `@/.windsurf/workflows/port-sru-to-ros.md` 与 `@/.claude/commands/port-sru-to-ros.md`。
|
||||
|
||||
### 5.3 怎样验证「这份 prompt 真的能复刻本仓库」?
|
||||
|
||||
把上述 workflow 在一台干净机器上跑完,最后做:
|
||||
|
||||
```bash
|
||||
diff -r --exclude=__pycache__ --exclude=.git \
|
||||
./generated_sru_nav_go2_ros1/ \
|
||||
./sru_nav_go2_ros1/
|
||||
```
|
||||
|
||||
预期:**结构完全一致;逐行 diff 应集中在注释 / 字面量顺序上,不应在数值常量、话题名、函数签名上有差异**。如果出现关键差异(例如 `policy_scale` 改成 `[1, 1, 1]`、忘记 LD_PRELOAD),说明 agent 没遵 prompt,回到对应 Step 重启。
|
||||
|
||||
---
|
||||
|
||||
## 6. 个性化与 0 门槛使用
|
||||
|
||||
所有「可能因人而异」的点都开成参数。最常见的三类:
|
||||
|
||||
### 6.1 路径
|
||||
|
||||
| 参数 | 默认 | 覆盖方式 |
|
||||
|---|---|---|
|
||||
| catkin workspace | `$HOME/code/odin_sru_nav` | `CATKIN_WS=/path bash scripts/launch_sru_nav.sh` |
|
||||
| conda env 名 | `sru_nav` | `ENV_NAME=my_env bash scripts/setup_conda_env.sh` |
|
||||
| ROS distro | `noetic` | `ROS_DISTRO=melodic bash scripts/launch_sru_nav.sh`(仅 py3 兼容版本) |
|
||||
| pip 镜像 | 清华源 | `PIP_INDEX_URL=https://pypi.org/simple bash scripts/setup_conda_env.sh` |
|
||||
|
||||
### 6.2 话题与帧
|
||||
|
||||
改 `config/sru_nav.yaml` 里这些字段,**不用改源码**:
|
||||
|
||||
```yaml
|
||||
depth_topic: "/your/depth" # sensor_msgs/Image (32FC1, meters)
|
||||
odom_topic: "/your/odometry" # nav_msgs/Odometry, world frame
|
||||
joy_topic: "/joy"
|
||||
goal_topic: "/goal_pose"
|
||||
cmd_vel_topic: "/cmd_vel"
|
||||
```
|
||||
|
||||
### 6.3 不同机器人
|
||||
|
||||
只需提供「订阅 `/cmd_vel` 的桥」。仓库**完全不感知机器人型号**。常见替换:
|
||||
|
||||
- Unitree Go2:用 `unitree_legged_sdk` 写 50 行的 cmd_vel→sport_mode 桥;
|
||||
- Unitree B2 / B2W:用官方 ROS1 桥;
|
||||
- Spot:`spot_ros` + `cmd_vel`;
|
||||
- 任何 ROS 仿真:直接订阅 `/cmd_vel`。
|
||||
|
||||
唯一需要改的可能是 TF:默认 launch 里发 `base_link → odin1_base_link` 的静态 TF,参数 `odin1_x / y / z / roll / pitch / yaw`,按你的相机安装位置改。
|
||||
|
||||
### 6.4 检查环境(你提到要写进文档与 prompt 的部分)
|
||||
|
||||
**第一次部署时建议跑一遍**:
|
||||
|
||||
```bash
|
||||
# 1) OS / ROS
|
||||
lsb_release -a # Ubuntu 20.04 推荐 (Noetic 配套)
|
||||
echo $ROS_DISTRO # 应为 noetic
|
||||
which roscore # /opt/ros/noetic/bin/roscore
|
||||
|
||||
# 2) Conda
|
||||
conda --version # ≥ 4.10
|
||||
conda env list | grep -E "sru_nav|base"
|
||||
|
||||
# 3) 时钟(Jetson 无 RTC 电池常坏)
|
||||
date # 确认是真实当前时间,否则 pip TLS 会拒接
|
||||
|
||||
# 4) 网络
|
||||
ping -c 2 8.8.8.8 || echo "WARN: no internet, pip will fail"
|
||||
|
||||
# 5) 硬件
|
||||
ls /dev/input/js* 2>/dev/null || echo "INFO: no joystick — use --no-deadman for headless tests"
|
||||
rostopic list 2>/dev/null | grep odin1 || echo "WARN: Odin1 driver not running"
|
||||
```
|
||||
|
||||
`scripts/verify_port.sh` 里把这一段固化为前置检查。
|
||||
|
||||
---
|
||||
|
||||
## 7. 验收脚本:`scripts/verify_port.sh`
|
||||
|
||||
设计成「**生成完代码后,开发者一键自检**」。完整列表见脚本本身(自带带 `[PASS]/[FAIL]/[WARN]` 标记),核心检查项:
|
||||
|
||||
| 检查项 | 命令 | 预期 |
|
||||
|---|---|---|
|
||||
| 包结构完整 | `find package.xml CMakeLists.txt setup.py launch config models scripts src/sru_nav_go2/{constants,model,navigation_policy_node}.py` | 全部存在 |
|
||||
| 模型可加载 | `python -c "import onnxruntime as ort; ort.InferenceSession('models/vae_encoder.onnx')"` | 不抛异常,打印 input shape |
|
||||
| catkin 通过 | `catkin_make -DPYTHON_EXECUTABLE=$(which python3)` | exit 0 |
|
||||
| shebang 正确 | `head -1 devel/lib/sru_nav_go2_ros1/sru_nav_node \| grep -q miniconda3.envs.${ENV_NAME}` | match |
|
||||
| 节点能起 | `timeout 8 roslaunch sru_nav_go2_ros1 sru_nav_go2.launch launch_joy:=false require_joystick:=false` | log 含 `Navigation policy node is ready` |
|
||||
| 关键参数存在 | `grep -E "policy_scale\|require_joystick\|control_frequency" config/sru_nav.yaml` | 三项都命中 |
|
||||
| LD_PRELOAD 修复 | `grep -q 'LD_PRELOAD.*libffi' scripts/launch_sru_nav.sh` | 命中 |
|
||||
|
||||
跑完终端打印 `ALL CHECKS PASSED` 才能放行真机。
|
||||
|
||||
---
|
||||
|
||||
## 8. 常见陷阱
|
||||
|
||||
按踩坑频率排序:
|
||||
|
||||
1. **catkin_make 时没在 conda env 里**:节点 shebang 烤进 `/usr/bin/python3`,运行时 `import onnxruntime` 失败。修:`conda activate sru_nav && catkin_make clean && catkin_make -DPYTHON_EXECUTABLE=$(which python3)`。
|
||||
2. **`No module named netifaces / defusedxml`**:rospy 隐性依赖。`pip install netifaces defusedxml` 进 conda env,`setup_conda_env.sh` 已内置。
|
||||
3. **`libp11-kit.so.0: undefined symbol: ffi_type_pointer`**:conda libffi 抢加载。`launch_sru_nav.sh` 里的 `LD_PRELOAD` 已修,新平台只需把版本号 7→8 同步。
|
||||
4. **pip `certificate is not yet valid`**:Jetson 时钟回退。`sudo ntpdate -u ntp.aliyun.com && sudo hwclock --systohc`。
|
||||
5. **`/cmd_vel` 全 0**:deadman 模式默认开。要么接手柄推 `axes[4]`,要么 `--no-deadman`(仅测试)。
|
||||
6. **goal 被忽略**:`/goal_pose.frame_id` 必须等于 odom 的 `frame_id`。
|
||||
|
||||
---
|
||||
|
||||
## 9. 许可与致谢
|
||||
|
||||
- 算法与训练代码版权:原 SRU 作者团队,遵循其原 LICENSE。
|
||||
- 本部署移植包 `sru_nav_go2_ros1` 在 MIT-style 许可下开源;包含上游派生代码的部分文件保留各自原始 header。
|
||||
- Odin1 是第三方深度相机,本仓库不再分发其驱动。
|
||||
|
||||
如发现移植 bug 或想要一键支持更多机器人/相机,欢迎 issue + PR。
|
||||
|
||||
---
|
||||
|
||||
## 附录 A:与论文/训练代码核对的关键数字
|
||||
|
||||
| 名称 | 训练值 | 部署值 | 来源 |
|
||||
|---|---|---|---|
|
||||
| `control_frequency` | 10 Hz (env step) | 5 Hz | `constants.DEFAULT_CONTROL_FREQUENCY` |
|
||||
| `rnn_hidden_size` | 512 | 512 | `b2w/agents/rsl_rl_cfg.py:36` |
|
||||
| `rnn_num_layers` | 1 | 1 | 同上 |
|
||||
| `policy_scaling` | `[1.5, 1.0, 1.0]` × `Uniform(0.8,1.2)/(0.6,1.0)/(0.8,1.2)` | `policy_scale=[0.6,0.3,0.6]`(保守) | `navigation_env_cfg.py:163` |
|
||||
| `entropy_coef` | `0.00375` | n/a | `b2w/agents/rsl_rl_cfg.py:50` |
|
||||
| `value_loss_coef` | `0.02` | n/a | 同上 |
|
||||
| 深度图分辨率(VAE 输入) | 见 `image_input_dims=(64, 5, 8)` 编码后形状 | 任意输入分辨率,节点 resize 到训练规格 | `b2w/agents/rsl_rl_cfg.py:41` |
|
||||
| `min_depth / max_depth` | 0.25 / 10.0 m | 0.25 / 10.0 m | `constants.py` |
|
||||
| `JOYSTICK_TIMEOUT` | n/a | 15 s | `constants.py:16` |
|
||||
|
||||
附录里这张表是「训练-部署一致性」的最小验收清单。任何二次移植(换机器人 / 换相机)都应保留这些数字不变。
|
||||
|
||||
---
|
||||
|
||||
## 附录 B:从空机器开始的 0 门槛 quickstart
|
||||
|
||||
```bash
|
||||
# === 系统级(一次性,需 sudo) =============================================
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y curl git build-essential ros-noetic-desktop \
|
||||
ros-noetic-joy ros-noetic-tf2-tools \
|
||||
python3-catkin-tools
|
||||
|
||||
# === 装 miniconda(如已装可跳过) ==========================================
|
||||
curl -O https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-$(uname -m).sh
|
||||
bash Miniconda3-latest-Linux-$(uname -m).sh -b -p $HOME/miniconda3
|
||||
echo 'source $HOME/miniconda3/etc/profile.d/conda.sh' >> ~/.bashrc
|
||||
source ~/.bashrc
|
||||
|
||||
# === 拉本仓库(替换成你的 fork / 仓库地址) ================================
|
||||
mkdir -p ~/code/odin_sru_nav/src
|
||||
cd ~/code/odin_sru_nav/src
|
||||
git clone https://github.com/<YOUR_FORK>/sru_nav_go2_ros1.git
|
||||
|
||||
# === 装 conda 依赖(含 onnxruntime / cv2 / netifaces ...) =================
|
||||
cd sru_nav_go2_ros1
|
||||
bash scripts/setup_conda_env.sh # 全自动;首次约 5–10 分钟
|
||||
bash scripts/setup_conda_env.sh --check # 自检全 OK 才继续
|
||||
|
||||
# === 编译(必须在 conda env 里) ===========================================
|
||||
conda activate sru_nav
|
||||
cd ~/code/odin_sru_nav
|
||||
catkin_make -DPYTHON_EXECUTABLE=$(which python3)
|
||||
source devel/setup.bash
|
||||
|
||||
# === 一键启动(默认安全模式:必须接手柄) ==================================
|
||||
cd src/sru_nav_go2_ros1
|
||||
bash scripts/launch_sru_nav.sh
|
||||
|
||||
# 或:抬轮 / 仿真 / 闭环回归测试(无手柄) ==================================
|
||||
bash scripts/launch_sru_nav.sh --no-deadman
|
||||
|
||||
# === 一键自检 ==============================================================
|
||||
bash scripts/verify_port.sh
|
||||
```
|
||||
|
||||
到这里只要 `verify_port.sh` 全绿,就能开始真机测试。
|
||||
@@ -0,0 +1,553 @@
|
||||
# Porting the SRU navigation policy to Odin1 + ROS1: full reproduction guide
|
||||
|
||||
> Starting from the paper *Spatially-Enhanced Recurrent Memory for Long-Range
|
||||
> Mapless Navigation via End-to-End Reinforcement Learning* and the
|
||||
> open-source repositories indexed at
|
||||
> [`sru-project-website`](https://michaelfyang.github.io/sru-project-website/),
|
||||
> this guide explains how to deploy the SRU end-to-end navigation policy on
|
||||
> **the Odin1 depth camera + ROS1 Noetic + any robot that consumes
|
||||
> `geometry_msgs/Twist` on `/cmd_vel`** (the reference platform is the
|
||||
> Unitree Go2). The package `sru_nav_go2_ros1` in this repository is the
|
||||
> output of that effort.
|
||||
>
|
||||
> **中文版**: see `PORTING_GUIDE.md`.
|
||||
|
||||
---
|
||||
|
||||
## 0. What this document is — and is not
|
||||
|
||||
**Is**: a three-in-one guide combining (a) the porting decision log, (b) a
|
||||
ready-to-use AI prompt that lets a coding agent regenerate this package
|
||||
from upstream, and (c) an automated acceptance script. After reading you
|
||||
should be able to:
|
||||
|
||||
1. understand which upstream pieces were changed and why,
|
||||
2. run a slash command in Cascade / Claude Code to recreate the package
|
||||
from the open-source repos and the paper,
|
||||
3. run a single script to verify the result.
|
||||
|
||||
**Is not**: an algorithm tutorial. For the model and reward design, read
|
||||
the paper and the upstream code directly.
|
||||
|
||||
**Audience**:
|
||||
- comfortable with Ubuntu + ROS1 + Python/conda,
|
||||
- has a Unitree Go2 (or any robot subscribing to `/cmd_vel`) plus an
|
||||
Odin1 depth camera,
|
||||
- wants to run SRU on their own robot, or to verify whether an AI agent
|
||||
can reproduce a real-robot deployment package from the paper + open
|
||||
code.
|
||||
|
||||
> Zero-barrier promise: every path, IP, robot model, and camera model is
|
||||
> overridable via environment variable or ROS parameter. No source code
|
||||
> edits required to retarget.
|
||||
|
||||
---
|
||||
|
||||
## 1. Upstream sources
|
||||
|
||||
| Asset | Link / path | Role in this port |
|
||||
|---|---|---|
|
||||
| Paper | *Spatially-Enhanced Recurrent Memory for Long-Range Mapless Navigation via End-to-End Reinforcement Learning* | Defines the observation/action space, rewards, and network (depth VAE + LSTM-SRU + actor head) |
|
||||
| Project page | <https://michaelfyang.github.io/sru-project-website/> | Index of repos, videos, paper |
|
||||
| `sru-navigation-learning` | RL training code (rsl_rl-style); contains PPO/MDPO algorithms, reward terms, observation manager | Source of truth for **reward design, action squashing, observation order**, plus the ONNX export entry point |
|
||||
| `sru-navigation-sim` | IsaacLab task with B2W / AOW training configs | Provides `policy_scaling`, randomization ranges, observation shapes (depth `64×5×8`) |
|
||||
| `sru-robot-deployment` | Original B2W + ZED-X real-robot deployment by the authors | The **direct rewrite target**: original uses PyTorch + DLIO odom + a custom SDK bridge; this port uses ONNX + Odin1 odom + a Go2 bridge |
|
||||
| `sru-pytorch-spatial-learning` | PyTorch implementation of the SRU / LSTM-SRU cell | Explains RNN hidden-state shape (`rnn_hidden_size=512, num_layers=1`) and how `(h, c)` are exposed when exporting to ONNX |
|
||||
| `sru-depth-pretraining` | Pretraining of the depth VAE encoder | Provides the input shape (`H×W` normalized depth, single channel) and latent dim of `vae_encoder.onnx` |
|
||||
|
||||
If you only want to run, not reproduce: drop the two trained ONNX files
|
||||
(`vae_encoder.onnx` + `nav_policy.onnx`) into `sru_nav_go2_ros1/models/`
|
||||
and skip to §6.
|
||||
|
||||
---
|
||||
|
||||
## 2. Porting target matrix
|
||||
|
||||
| Aspect | Author deployment (`sru-robot-deployment`) | This package (`sru_nav_go2_ros1`) | Abstracted interface |
|
||||
|---|---|---|---|
|
||||
| Robot | Unitree **B2W** (wheeled-leg) | Unitree **Go2** (pure-leg) | Any robot consuming `/cmd_vel` (`geometry_msgs/Twist`, body frame) |
|
||||
| Depth sensor | ZED-X | **Odin1** (`32FC1`, ~10 Hz) | `~depth_topic` (`sensor_msgs/Image`, 32FC1, meters) |
|
||||
| Odometry | DLIO (custom LIO) | Odin1 `odometry_highfreq` | `~odom_topic` (`nav_msgs/Odometry`, world frame) |
|
||||
| Inference backend | PyTorch JIT | **ONNX Runtime** | `models/{vae_encoder,nav_policy}.onnx` |
|
||||
| Compute platform | x86 industrial PC | **Jetson Orin NX (aarch64) + conda py3.8** | Any Linux + ROS1 Noetic + conda |
|
||||
| Control rate | ~10 Hz | **5 Hz** (matches training; Odin depth ~10 Hz, naturally decimated) | `~control_frequency` |
|
||||
| Operator joystick | PS5 PerceptiveNavigationSE2 | Same PS5 mapping, **plus `require_joystick: false`** for headless | `--no-deadman` / yaml `require_joystick` |
|
||||
| Install / launch | rosinstall full stack | **`setup_conda_env.sh` + `launch_sru_nav.sh`** | env vars `ENV_NAME / ROS_DISTRO / CATKIN_WS`, all overridable |
|
||||
|
||||
---
|
||||
|
||||
## 3. Core porting decisions (motivation + reference)
|
||||
|
||||
### 3.1 Inference: PyTorch → ONNX Runtime
|
||||
|
||||
- **Why**: stacking PyTorch + cv_bridge + onnxruntime on a Jetson Orin NX
|
||||
rapidly snowballs into a dependency mess; onnxruntime ships a single
|
||||
shared-object loader, swaps CPU/GPU EP cleanly, and has prebuilt ARM
|
||||
wheels.
|
||||
- **Interface**: `@/sru_nav_go2_ros1/src/sru_nav_go2/model.py` implements
|
||||
`LearningModel`, which loads `vae_encoder.onnx` (depth → latent) and
|
||||
`nav_policy.onnx` (latent + state vector + last action + LSTM hidden →
|
||||
action mean + new hidden) as two separate sessions.
|
||||
- **Hidden-state contract**: training uses `rnn_hidden_size=512,
|
||||
num_layers=1`; the ONNX export carries `(h, c)` as input/output tensors
|
||||
and the deployment side holds them between frames. `reset_hidden_state`
|
||||
matches the training `is_first` flag.
|
||||
- **Action squash**: the network already includes `tanh`, so the output is
|
||||
in `(-1, 1)`. The deployment then multiplies by
|
||||
`policy_scale = [vx_max, vy_max, ω_max]` (default `[0.6, 0.3, 0.6]`)
|
||||
to obtain SI velocities.
|
||||
|
||||
### 3.2 Observations: Odin1 replaces ZED-X + DLIO
|
||||
|
||||
- **Depth**: Odin1 publishes `sensor_msgs/Image` (`32FC1`, meters). The
|
||||
callback `@/sru_nav_go2_ros1/src/sru_nav_go2/navigation_policy_node.py:209-225`:
|
||||
1. `cv_bridge.imgmsg_to_cv2(passthrough)`,
|
||||
2. `nan_to_num(nan=0, posinf=2*max_depth, neginf=0)`,
|
||||
3. clamps to `[min_depth, max_depth] = [0.25, 10.0] m`, out-of-range
|
||||
pixels set to 0.
|
||||
- **Odometry frame convention**: Odin1's `twist` is **world frame**. The
|
||||
`odom_callback` rotates it back to the body frame using the body
|
||||
quaternion (matching training). If your odom is already in body frame,
|
||||
set `use_sim: true` and the node passes `twist` straight through
|
||||
(`@/sru_nav_go2_ros1/src/sru_nav_go2/navigation_policy_node.py:189-197`).
|
||||
- **Goal frame contract**: `/goal_pose.header.frame_id` must equal the odom
|
||||
`frame_id` (default `odom`). Otherwise the node rejects the message —
|
||||
this guards against operators sending a body-frame coordinate as if it
|
||||
were odom-frame.
|
||||
|
||||
### 3.3 Action egress: straight to `/cmd_vel`
|
||||
|
||||
- The original B2W deployment ships its own SDK bridge; on Go2 a tiny
|
||||
separate node (subscribes to `/cmd_vel`, talks to `unitree_legged_sdk`
|
||||
sport mode) is enough. **This package is robot-agnostic** and does not
|
||||
bind to a specific bridge.
|
||||
- `policy_scale = [0.6, 0.3, 0.6]` is a deliberate halving versus the
|
||||
training value `[1.5, 1.0, 1.0]`, leaving margin for real-robot bring-up.
|
||||
Training already randomized scale by `Uniform(0.6, 1.2)`, so the network
|
||||
is robust to runtime scaling.
|
||||
|
||||
### 3.4 Safety: dual-mode joystick deadman
|
||||
|
||||
| Mode | Trigger | Behavior |
|
||||
|---|---|---|
|
||||
| Default (`require_joystick=true`) | Real-robot deployment | `cmd_vel_ratio=0` until `/joy` is published with `axes[4]` > 0; >15 s without `/joy` forces stop |
|
||||
| Test (`require_joystick=false`) | `--no-deadman` or yaml=false | `cmd_vel_ratio=1.0` from start, no `/joy` required. **Lifted-wheel / sim / open-field only** |
|
||||
|
||||
Source: `@/sru_nav_go2_ros1/src/sru_nav_go2/navigation_policy_node.py:118-121, 272-287`.
|
||||
|
||||
### 3.5 Install layer: conda + system ROS coexistence
|
||||
|
||||
The Jetson Orin NX ships ROS Noetic (system python 3.8 + cv_bridge.so).
|
||||
At the same time we want `onnxruntime / opencv / numpy / …` only inside a
|
||||
conda env. The two worlds must interoperate:
|
||||
|
||||
1. **`PYTHONPATH` injection**: prepend
|
||||
`/opt/ros/noetic/lib/python3/dist-packages` so the conda python can
|
||||
import `rospy / cv_bridge / sensor_msgs / tf2_ros`.
|
||||
2. **Shebang lock**: `catkin_make` must run with
|
||||
`-DPYTHON_EXECUTABLE=$(which python3)` **while the conda env is
|
||||
active**, otherwise `devel/lib/.../sru_nav_node`'s `#!` line will point
|
||||
at `/usr/bin/python3` and `import onnxruntime` fails at runtime.
|
||||
3. **ABI conflict fix**: the conda env ships `libffi.so.7`, but the system
|
||||
`libp11-kit.so.0` was linked against the system `libffi`'s versioned
|
||||
symbols. Without intervention `cv_bridge` crashes with
|
||||
`undefined symbol: ffi_type_pointer, version LIBFFI_BASE_7.0`.
|
||||
`launch_sru_nav.sh` automatically `LD_PRELOAD`s the system
|
||||
`libffi.so.7` so its symbols take priority.
|
||||
4. **Hidden rospy deps**: `netifaces` and `defusedxml` are provided to the
|
||||
system python via apt packages; the conda env needs them via pip.
|
||||
`setup_conda_env.sh` already lists both.
|
||||
5. **Clock check**: Jetson without an RTC battery often boots with a stale
|
||||
clock, breaking pip TLS. The script runs a `date` plausibility check
|
||||
and points to `ntpdate / timedatectl`.
|
||||
|
||||
Full automation: `@/sru_nav_go2_ros1/scripts/setup_conda_env.sh` +
|
||||
`@/sru_nav_go2_ros1/scripts/launch_sru_nav.sh`.
|
||||
|
||||
### 3.6 Deliberate omissions
|
||||
|
||||
| Present in training | Reason for omitting at deployment |
|
||||
|---|---|
|
||||
| Heightmap / heightscan critic | Go2 has no LiDAR/heightmap; can be added as an external topic if needed |
|
||||
| Critic-only observation channels | Critic exists only at training time; only the actor head runs at inference |
|
||||
| MDPO / mutual-distillation dual actor-critic | Optimizer-side mechanism; irrelevant to the exported actor |
|
||||
| Reward computation | Inference does not need rewards |
|
||||
| Action-scale randomization (`Uniform(0.6, 1.2)`) | Deployment uses a fixed scale; the network has been trained to be robust to this range |
|
||||
|
||||
---
|
||||
|
||||
## 4. File map and responsibilities
|
||||
|
||||
```
|
||||
sru_nav_go2_ros1/
|
||||
├── CMakeLists.txt # catkin def: catkin_python_setup() + install scripts
|
||||
├── package.xml # deps: rospy, sensor_msgs, geometry_msgs, nav_msgs, cv_bridge, tf2_ros
|
||||
├── setup.py # installs src/sru_nav_go2 as a Python package
|
||||
├── README.md
|
||||
├── config/
|
||||
│ ├── sru_nav.yaml # all runtime ROS params; the only file users normally touch
|
||||
│ └── waypoints_example.yaml # multi-goal tour example (odom-frame point list)
|
||||
├── launch/
|
||||
│ └── sru_nav_go2.launch # joy_node + static_tf + sru_nav_node
|
||||
├── models/
|
||||
│ ├── vae_encoder.onnx # exported from training side via export_onnx
|
||||
│ └── nav_policy.onnx
|
||||
├── scripts/
|
||||
│ ├── setup_conda_env.sh # creates the sru_nav env, installs onnxruntime / cv2 / netifaces …
|
||||
│ ├── launch_sru_nav.sh # one-liner launcher (with LD_PRELOAD / PYTHONPATH fixes)
|
||||
│ ├── sru_nav_node # ROS node entrypoint (catkin install copies it under devel/lib/…)
|
||||
│ ├── waypoint_runner.py # publishes /goal_pose in sequence
|
||||
│ └── verify_port.sh # acceptance script (see §7)
|
||||
├── src/sru_nav_go2/
|
||||
│ ├── constants.py # all training-aligned constants
|
||||
│ ├── model.py # ONNX Runtime wrapper: VAE encoder + LSTM-SRU policy
|
||||
│ ├── navigation_policy_node.py # main node: odom/depth/joy/goal callbacks + cmd_vel out
|
||||
│ ├── utils.py # quaternion ↔ rotation, projected gravity, etc.
|
||||
│ ├── visualization.py # rviz markers
|
||||
│ └── waypoint_manager.py # record / replay waypoint list
|
||||
└── docs/
|
||||
├── DEPLOY_GO2_NX.md # NX deployment field notes
|
||||
├── PORTING_GUIDE.md # Chinese version
|
||||
└── PORTING_GUIDE_EN.md # ← this file
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Reproducing this package with an AI agent
|
||||
|
||||
We ship **the same porting prompt in three call forms** (use whichever
|
||||
fits your tool):
|
||||
|
||||
| Entry | Tool | How to invoke |
|
||||
|---|---|---|
|
||||
| `.windsurf/workflows/port-sru-to-ros.md` | Cascade (Windsurf IDE) | type `/port-sru-to-ros` in the Cascade panel |
|
||||
| `.claude/commands/port-sru-to-ros.md` | Claude Code (CLI / IDE) | start `claude`, then `/port-sru-to-ros` |
|
||||
| `docs/PORTING_GUIDE.md` §5.2 | Any agent that accepts a custom prompt (Cursor, Continue, Aider, …) | paste §5.2 into the system / task prompt |
|
||||
|
||||
All three derive from one canonical prompt. Differences are limited to
|
||||
the launch header and per-tool path conventions.
|
||||
|
||||
> ⚠️ **Reproducibility caveat**: a single LLM round generating ~1500 LoC
|
||||
> of ROS porting code is not 100% reliable. We split the task into a
|
||||
> 6-step workflow so each step has a grep-able acceptance check; this
|
||||
> dramatically beats one-shot mega-prompts in success rate.
|
||||
|
||||
### 5.1 Workflow at a glance
|
||||
|
||||
| Step | Inputs | Outputs | Acceptance |
|
||||
|---|---|---|---|
|
||||
| 1. **Recon** | 5 upstream repos + paper | `notes/upstream_recon.md` summarizing arch, obs/action, IO shapes, training hyperparams | file exists and lists net depth, obs dims, policy_scale |
|
||||
| 2. **Extract inference** | `sru-navigation-learning` export entry | `models/vae_encoder.onnx`, `models/nav_policy.onnx`, `docs/IO_SPEC.md` | onnxruntime can load both; IO names recorded |
|
||||
| 3. **catkin skeleton** | Step 2 IO spec | `package.xml / CMakeLists.txt / setup.py / launch/ / config/sru_nav.yaml` | `catkin_make` succeeds |
|
||||
| 4. **Port the node** | Original `sru-robot-deployment` node + IO spec | `src/sru_nav_go2/{constants,model,utils,visualization,waypoint_manager,navigation_policy_node}.py` + `scripts/sru_nav_node` | `roslaunch` brings the node up cleanly |
|
||||
| 5. **Deployment scripts** | Target platform info | `scripts/setup_conda_env.sh` + `scripts/launch_sru_nav.sh` | clean-env smoke-test in §6 passes |
|
||||
| 6. **Docs + verify** | All above | `README.md / docs/DEPLOY_*.md / scripts/verify_port.sh` | `bash scripts/verify_port.sh` all green |
|
||||
|
||||
### 5.2 Canonical prompt (the body of all three entry files)
|
||||
|
||||
```text
|
||||
You are a senior engineer fluent in ROS1 Noetic, conda, ONNX Runtime, and
|
||||
PyTorch.
|
||||
|
||||
[Task]
|
||||
From the upstream sources below, generate a catkin package named
|
||||
`sru_nav_go2_ros1` that deploys the navigation policy from the paper
|
||||
"Spatially-Enhanced Recurrent Memory for Long-Range Mapless Navigation
|
||||
via End-to-End Reinforcement Learning" onto an Odin1 depth camera +
|
||||
ROS1 Noetic + any robot consuming `geometry_msgs/Twist` on `/cmd_vel`.
|
||||
|
||||
[Upstream sources]
|
||||
- Paper PDF (path provided by user, e.g. ./2506.05997v2.pdf)
|
||||
- Project page: https://michaelfyang.github.io/sru-project-website/
|
||||
- Repos under user-provided `${UPSTREAM_DIR}`:
|
||||
sru-navigation-learning — RL training + ONNX export
|
||||
sru-navigation-sim — IsaacLab env + training configs
|
||||
sru-robot-deployment — original B2W+ZED-X deployment (the
|
||||
direct rewrite target)
|
||||
sru-pytorch-spatial-learning — SRU / LSTM-SRU cell
|
||||
sru-depth-pretraining — depth VAE pretraining
|
||||
- Pre-existing onnx files (if any):
|
||||
models/{vae_encoder,nav_policy}.onnx
|
||||
|
||||
[Hard constraints]
|
||||
1. Sensors are fixed to Odin1: depth `/odin1/depth_img_competetion`
|
||||
(sensor_msgs/Image, 32FC1, meters), odom
|
||||
`/odin1/odometry_highfreq` (nav_msgs/Odometry, world frame).
|
||||
2. Output is fixed to `/cmd_vel` (geometry_msgs/Twist, body frame). The
|
||||
bridge to a specific robot's SDK is out of scope.
|
||||
3. Only `onnxruntime` for inference. No PyTorch at runtime.
|
||||
4. Must coexist with system ROS python in a conda env (default
|
||||
`sru_nav`, py3.8):
|
||||
- inject /opt/ros/<DISTRO>/lib/python3/dist-packages into PYTHONPATH
|
||||
- LD_PRELOAD system libffi to fix cv_bridge ABI conflict
|
||||
- lock catkin_make's PYTHON_EXECUTABLE to conda python
|
||||
5. Every path / env / distro / robot model must be overridable via env
|
||||
vars or ROS params; never write `/home/<user>` into source files.
|
||||
6. Preserve all training-aligned numbers: control_frequency=5 Hz,
|
||||
rnn_hidden=512, default policy_scale=[0.6,0.3,0.6], joystick axis
|
||||
mapping, etc.
|
||||
7. Safety: joystick deadman + 15 s timeout, with a
|
||||
`require_joystick: false` bypass; default must be true.
|
||||
|
||||
[Output file list] (all required)
|
||||
package.xml, CMakeLists.txt, setup.py
|
||||
launch/sru_nav_go2.launch
|
||||
config/sru_nav.yaml, config/waypoints_example.yaml
|
||||
scripts/setup_conda_env.sh, scripts/launch_sru_nav.sh,
|
||||
scripts/sru_nav_node, scripts/waypoint_runner.py, scripts/verify_port.sh
|
||||
src/sru_nav_go2/{__init__.py, constants.py, model.py, utils.py,
|
||||
visualization.py, waypoint_manager.py,
|
||||
navigation_policy_node.py}
|
||||
docs/DEPLOY.md, docs/PORTING_GUIDE.md (Chinese), docs/PORTING_GUIDE_EN.md
|
||||
models/README.md (how to obtain / export the two ONNX files)
|
||||
|
||||
[Workflow] (must be sequential; self-check after each step)
|
||||
Step 1 — Recon: read repos and paper; emit notes/upstream_recon.md with
|
||||
net architecture, obs dims, action space, rsl_rl algorithm config,
|
||||
reward list.
|
||||
Step 2 — IO normalization: locate export_onnx in the training repo, log
|
||||
input/output names + shapes, emit docs/IO_SPEC.md.
|
||||
Step 3 — Generate catkin skeleton; verify with `catkin_make`.
|
||||
Step 4 — Port the node: use sru-robot-deployment as template, swap
|
||||
sensors, drop non-Odin deps, replace PyTorch calls with
|
||||
onnxruntime.
|
||||
Step 5 — Write the two scripts (setup + launcher), covering all of
|
||||
constraint #4.
|
||||
Step 6 — Generate verify_port.sh: package layout, shebang, ONNX load
|
||||
test, rostopic list, yaml fields.
|
||||
|
||||
[Acceptance] (the user will run verify_port.sh and the commands below)
|
||||
1. `catkin_make` in a clean workspace: 0 warnings, 0 errors.
|
||||
2. `bash scripts/setup_conda_env.sh --check` passes.
|
||||
3. `head -1 devel/lib/sru_nav_go2_ros1/sru_nav_node` points at conda
|
||||
python, not `/usr/bin/python3`.
|
||||
4. `roslaunch sru_nav_go2_ros1 sru_nav_go2.launch require_joystick:=false`
|
||||
prints `Navigation policy node is ready.` and emits no error spam.
|
||||
5. Synthetic odom + a 32FC1 depth frame + a goal_pose results in a
|
||||
non-zero `/cmd_vel`.
|
||||
6. `bash scripts/verify_port.sh` is all green.
|
||||
|
||||
[Response discipline]
|
||||
- Do not emit a single 1000+ line reply; chunk per step, summarize the
|
||||
plan first, then write files.
|
||||
- After each step run the listed self-check, paste the command and
|
||||
output, fix on failure before advancing.
|
||||
- If an upstream file is missing, halt and ask. Never fabricate APIs.
|
||||
```
|
||||
|
||||
The fully executable variants are in
|
||||
`@/.windsurf/workflows/port-sru-to-ros.md` and
|
||||
`@/.claude/commands/port-sru-to-ros.md`.
|
||||
|
||||
### 5.3 How do I prove that this prompt actually reproduces the package?
|
||||
|
||||
Run the workflow on a clean machine, then:
|
||||
|
||||
```bash
|
||||
diff -r --exclude=__pycache__ --exclude=.git \
|
||||
./generated_sru_nav_go2_ros1/ \
|
||||
./sru_nav_go2_ros1/
|
||||
```
|
||||
|
||||
Expected: **identical structure; line-level diffs concentrated in
|
||||
comments and literal ordering, not in numeric constants, topic names,
|
||||
or function signatures**. If you see drift on critical items
|
||||
(`policy_scale` becoming `[1, 1, 1]`, the LD_PRELOAD line missing, etc.),
|
||||
the agent did not follow the prompt — return to that step and retry.
|
||||
|
||||
---
|
||||
|
||||
## 6. Personalization and zero-barrier usage
|
||||
|
||||
Every "user-specific" knob is exposed as a parameter. The three most
|
||||
common categories:
|
||||
|
||||
### 6.1 Paths
|
||||
|
||||
| Parameter | Default | Override |
|
||||
|---|---|---|
|
||||
| catkin workspace | `$HOME/code/odin_sru_nav` | `CATKIN_WS=/path bash scripts/launch_sru_nav.sh` |
|
||||
| conda env name | `sru_nav` | `ENV_NAME=my_env bash scripts/setup_conda_env.sh` |
|
||||
| ROS distro | `noetic` | `ROS_DISTRO=melodic bash scripts/launch_sru_nav.sh` (py3-compatible only) |
|
||||
| pip mirror | Tsinghua | `PIP_INDEX_URL=https://pypi.org/simple bash scripts/setup_conda_env.sh` |
|
||||
|
||||
### 6.2 Topics and frames
|
||||
|
||||
Edit `config/sru_nav.yaml`; **do not edit source code**:
|
||||
|
||||
```yaml
|
||||
depth_topic: "/your/depth" # sensor_msgs/Image (32FC1, meters)
|
||||
odom_topic: "/your/odometry" # nav_msgs/Odometry, world frame
|
||||
joy_topic: "/joy"
|
||||
goal_topic: "/goal_pose"
|
||||
cmd_vel_topic: "/cmd_vel"
|
||||
```
|
||||
|
||||
### 6.3 Different robots
|
||||
|
||||
You only need a `/cmd_vel` bridge. The package is **robot-agnostic**.
|
||||
Common substitutions:
|
||||
|
||||
- Unitree Go2: ~50 LoC bridge wrapping `unitree_legged_sdk` sport mode
|
||||
- Unitree B2 / B2W: official ROS1 bridge
|
||||
- Boston Dynamics Spot: `spot_ros` + `cmd_vel`
|
||||
- Any ROS sim: subscribes to `/cmd_vel` directly
|
||||
|
||||
The only TF you may need to retune is the static
|
||||
`base_link → odin1_base_link` published by the launch file; the args
|
||||
`odin1_x / y / z / roll / pitch / yaw` mirror your camera mounting pose.
|
||||
|
||||
### 6.4 System-environment check (also embedded in the prompt)
|
||||
|
||||
Run once on a fresh host:
|
||||
|
||||
```bash
|
||||
# 1) OS / ROS
|
||||
lsb_release -a # Ubuntu 20.04 recommended (Noetic)
|
||||
echo $ROS_DISTRO # expect: noetic
|
||||
which roscore # /opt/ros/noetic/bin/roscore
|
||||
|
||||
# 2) Conda
|
||||
conda --version # ≥ 4.10
|
||||
conda env list | grep -E "sru_nav|base"
|
||||
|
||||
# 3) Clock (Jetsons without RTC battery often drift)
|
||||
date # must reflect real wall time
|
||||
|
||||
# 4) Network
|
||||
ping -c 2 8.8.8.8 || echo "WARN: no internet, pip will fail"
|
||||
|
||||
# 5) Hardware
|
||||
ls /dev/input/js* 2>/dev/null \
|
||||
|| echo "INFO: no joystick — use --no-deadman for headless tests"
|
||||
rostopic list 2>/dev/null | grep odin1 \
|
||||
|| echo "WARN: Odin1 driver not running"
|
||||
```
|
||||
|
||||
`scripts/verify_port.sh` codifies the same checks.
|
||||
|
||||
---
|
||||
|
||||
## 7. Acceptance script — `scripts/verify_port.sh`
|
||||
|
||||
Designed for the developer to **self-check immediately after generation**.
|
||||
The full set lives in the script itself (with `[PASS]/[FAIL]/[WARN]`
|
||||
markers); the most important checks:
|
||||
|
||||
| Check | Command | Expected |
|
||||
|---|---|---|
|
||||
| Package layout complete | look for `package.xml CMakeLists.txt setup.py launch config models scripts src/sru_nav_go2/{constants,model,navigation_policy_node}.py` | all present |
|
||||
| Models load | `python -c "import onnxruntime as ort; ort.InferenceSession('models/vae_encoder.onnx')"` | no exception, prints input shape |
|
||||
| catkin builds | `catkin_make -DPYTHON_EXECUTABLE=$(which python3)` | exit 0 |
|
||||
| Shebang correct | `head -1 devel/lib/sru_nav_go2_ros1/sru_nav_node \| grep -q miniconda3.envs.${ENV_NAME}` | match |
|
||||
| Node comes up | `timeout 8 roslaunch sru_nav_go2_ros1 sru_nav_go2.launch launch_joy:=false require_joystick:=false` | log contains `Navigation policy node is ready` |
|
||||
| Required yaml params | `grep -E "policy_scale\|require_joystick\|control_frequency" config/sru_nav.yaml` | all three matched |
|
||||
| LD_PRELOAD fix | `grep -q 'LD_PRELOAD.*libffi' scripts/launch_sru_nav.sh` | match |
|
||||
|
||||
The script exits with `ALL CHECKS PASSED` when (and only when) every
|
||||
check is green. Do not move to real-robot tests before that.
|
||||
|
||||
---
|
||||
|
||||
## 8. Common pitfalls
|
||||
|
||||
In rough order of how often they bite:
|
||||
|
||||
1. **Built `catkin_make` outside the conda env** → node shebang baked to
|
||||
`/usr/bin/python3`; `import onnxruntime` fails. Fix:
|
||||
`conda activate sru_nav && catkin_make clean && catkin_make -DPYTHON_EXECUTABLE=$(which python3)`.
|
||||
2. **`No module named netifaces / defusedxml`** → rospy hidden deps.
|
||||
`pip install netifaces defusedxml` into the conda env. Already in
|
||||
`setup_conda_env.sh`.
|
||||
3. **`libp11-kit.so.0: undefined symbol: ffi_type_pointer`** → conda
|
||||
libffi is loaded first. The `LD_PRELOAD` fix in `launch_sru_nav.sh`
|
||||
covers it; on platforms with only `libffi.so.8` change the version
|
||||
number.
|
||||
4. **pip `certificate is not yet valid`** → Jetson clock drift. Fix:
|
||||
`sudo ntpdate -u ntp.aliyun.com && sudo hwclock --systohc`.
|
||||
5. **`/cmd_vel` is all zeros** → deadman is on by default. Either plug
|
||||
in the joystick and push `axes[4]`, or run with `--no-deadman` (test
|
||||
mode only).
|
||||
6. **Goal silently dropped** → `/goal_pose.frame_id` must equal the
|
||||
odom `frame_id`.
|
||||
|
||||
---
|
||||
|
||||
## 9. License & acknowledgments
|
||||
|
||||
- The algorithm and training code remain copyright of the original SRU
|
||||
authors under their original LICENSE.
|
||||
- This deployment port `sru_nav_go2_ros1` is released under an MIT-style
|
||||
license; files derived from upstream retain their original headers.
|
||||
- Odin1 is a third-party depth camera; this repo does not redistribute
|
||||
its driver.
|
||||
|
||||
If you find a porting bug or want first-class support for more robots /
|
||||
cameras, please open an issue or PR.
|
||||
|
||||
---
|
||||
|
||||
## Appendix A: training–deployment numeric cross-check
|
||||
|
||||
| Quantity | Training value | Deployment value | Source |
|
||||
|---|---|---|---|
|
||||
| `control_frequency` | 10 Hz (env step) | 5 Hz | `constants.DEFAULT_CONTROL_FREQUENCY` |
|
||||
| `rnn_hidden_size` | 512 | 512 | `b2w/agents/rsl_rl_cfg.py:36` |
|
||||
| `rnn_num_layers` | 1 | 1 | same file |
|
||||
| `policy_scaling` | `[1.5, 1.0, 1.0]` × `Uniform(0.8,1.2)/(0.6,1.0)/(0.8,1.2)` | `policy_scale=[0.6,0.3,0.6]` (conservative) | `navigation_env_cfg.py:163` |
|
||||
| `entropy_coef` | `0.00375` | n/a | `b2w/agents/rsl_rl_cfg.py:50` |
|
||||
| `value_loss_coef` | `0.02` | n/a | same file |
|
||||
| Depth resolution into the VAE | `image_input_dims=(64, 5, 8)` (post-encoder) | input depth resized at runtime | `b2w/agents/rsl_rl_cfg.py:41` |
|
||||
| `min_depth / max_depth` | 0.25 / 10.0 m | 0.25 / 10.0 m | `constants.py` |
|
||||
| `JOYSTICK_TIMEOUT` | n/a | 15 s | `constants.py:16` |
|
||||
|
||||
This appendix is the minimum viable consistency check. Any second-order
|
||||
port (different robot / different camera) should preserve these numbers
|
||||
verbatim.
|
||||
|
||||
---
|
||||
|
||||
## Appendix B: zero-barrier quickstart from a bare machine
|
||||
|
||||
```bash
|
||||
# === System packages (one-time, sudo) ====================================
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y curl git build-essential ros-noetic-desktop \
|
||||
ros-noetic-joy ros-noetic-tf2-tools \
|
||||
python3-catkin-tools
|
||||
|
||||
# === Install miniconda (skip if you already have one) ====================
|
||||
curl -O https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-$(uname -m).sh
|
||||
bash Miniconda3-latest-Linux-$(uname -m).sh -b -p $HOME/miniconda3
|
||||
echo 'source $HOME/miniconda3/etc/profile.d/conda.sh' >> ~/.bashrc
|
||||
source ~/.bashrc
|
||||
|
||||
# === Clone this package ==================================================
|
||||
mkdir -p ~/code/odin_sru_nav/src
|
||||
cd ~/code/odin_sru_nav/src
|
||||
git clone https://github.com/<YOUR_FORK>/sru_nav_go2_ros1.git
|
||||
|
||||
# === Conda deps (onnxruntime / cv2 / netifaces / ...) ====================
|
||||
cd sru_nav_go2_ros1
|
||||
bash scripts/setup_conda_env.sh # 5–10 minutes the first time
|
||||
bash scripts/setup_conda_env.sh --check # all PASS before continuing
|
||||
|
||||
# === Build (must be inside the conda env) ================================
|
||||
conda activate sru_nav
|
||||
cd ~/code/odin_sru_nav
|
||||
catkin_make -DPYTHON_EXECUTABLE=$(which python3)
|
||||
source devel/setup.bash
|
||||
|
||||
# === Launch (default: safe mode, requires joystick) ======================
|
||||
cd src/sru_nav_go2_ros1
|
||||
bash scripts/launch_sru_nav.sh
|
||||
|
||||
# Or: lifted-wheel / sim / closed-loop regression (no joystick) ===========
|
||||
bash scripts/launch_sru_nav.sh --no-deadman
|
||||
|
||||
# === Self-check ==========================================================
|
||||
bash scripts/verify_port.sh
|
||||
```
|
||||
|
||||
When `verify_port.sh` is fully green, you are ready for real-robot
|
||||
testing.
|
||||
@@ -0,0 +1,55 @@
|
||||
<?xml version="1.0"?>
|
||||
<!--
|
||||
Launch the SRU navigation controller on Unitree Go2 + Odin1.
|
||||
Assumes the Odin1 ROS1 driver and a Go2 cmd_vel bridge are already running
|
||||
(or will be launched separately).
|
||||
-->
|
||||
<launch>
|
||||
<!-- ============================================================== -->
|
||||
<!-- Top-level arguments -->
|
||||
<!-- ============================================================== -->
|
||||
<arg name="sim" default="false" doc="Treat odom twist as already in base frame."/>
|
||||
<arg name="launch_joy" default="true" doc="Start a joy node alongside (PS5/PS4 etc.)."/>
|
||||
<arg name="launch_static_tf" default="true" doc="Publish a static TF base_link->odin1_base_link."/>
|
||||
<arg name="require_joystick" default="true" doc="If false, bypass the joystick deadman (TESTING ONLY)."/>
|
||||
|
||||
<!-- Odin1 mounting on Go2 (measure on the real platform!).
|
||||
xyz in meters (forward, left, up). rpy in radians.
|
||||
Default below: 25 cm forward of Go2 body center, 18 cm up, no roll/yaw,
|
||||
~20 deg downward pitch (matches original ZED X 0.349 rad config). -->
|
||||
<arg name="odin1_x" default="0.25"/>
|
||||
<arg name="odin1_y" default="0.0"/>
|
||||
<arg name="odin1_z" default="0.18"/>
|
||||
<arg name="odin1_roll" default="0.0"/>
|
||||
<arg name="odin1_pitch" default="0.349"/>
|
||||
<arg name="odin1_yaw" default="0.0"/>
|
||||
|
||||
<!-- ============================================================== -->
|
||||
<!-- Optional joy node -->
|
||||
<!-- ============================================================== -->
|
||||
<node if="$(arg launch_joy)" pkg="joy" type="joy_node" name="joy_node" output="screen">
|
||||
<param name="autorepeat_rate" value="50.0"/>
|
||||
<param name="deadzone" value="0.05"/>
|
||||
</node>
|
||||
|
||||
<!-- ============================================================== -->
|
||||
<!-- Static TF: Go2 base_link -> odin1_base_link -->
|
||||
<!-- Adjust args on the real robot. -->
|
||||
<!-- ============================================================== -->
|
||||
<node if="$(arg launch_static_tf)"
|
||||
pkg="tf2_ros" type="static_transform_publisher"
|
||||
name="static_tf_base_to_odin1"
|
||||
args="$(arg odin1_x) $(arg odin1_y) $(arg odin1_z)
|
||||
$(arg odin1_yaw) $(arg odin1_pitch) $(arg odin1_roll)
|
||||
base_link odin1_base_link"/>
|
||||
|
||||
<!-- ============================================================== -->
|
||||
<!-- SRU navigation node -->
|
||||
<!-- ============================================================== -->
|
||||
<node pkg="sru_nav_go2_ros1" type="sru_nav_node" name="sru_nav_node"
|
||||
output="screen" required="true">
|
||||
<rosparam command="load" file="$(find sru_nav_go2_ros1)/config/sru_nav.yaml"/>
|
||||
<param name="use_sim" value="$(arg sim)"/>
|
||||
<param name="require_joystick" value="$(arg require_joystick)"/>
|
||||
</node>
|
||||
</launch>
|
||||
@@ -0,0 +1,29 @@
|
||||
<?xml version="1.0"?>
|
||||
<package format="2">
|
||||
<name>sru_nav_go2_ros1</name>
|
||||
<version>0.1.0</version>
|
||||
<description>
|
||||
ROS1 (Noetic) port of the SRU Navigation controller for Unitree Go2 + Odin1.
|
||||
Loads the pretrained SRU policy (ONNX) and VAE depth encoder, subscribes to
|
||||
Odin1 depth/odom and a joystick, publishes /cmd_vel to Go2.
|
||||
</description>
|
||||
|
||||
<maintainer email="[email protected]">SRU Navigation Port</maintainer>
|
||||
<license>MIT</license>
|
||||
|
||||
<buildtool_depend>catkin</buildtool_depend>
|
||||
|
||||
<depend>rospy</depend>
|
||||
<depend>std_msgs</depend>
|
||||
<depend>sensor_msgs</depend>
|
||||
<depend>geometry_msgs</depend>
|
||||
<depend>nav_msgs</depend>
|
||||
<depend>visualization_msgs</depend>
|
||||
<depend>cv_bridge</depend>
|
||||
<depend>tf2_ros</depend>
|
||||
|
||||
<exec_depend>joy</exec_depend>
|
||||
|
||||
<export>
|
||||
</export>
|
||||
</package>
|
||||
@@ -0,0 +1,121 @@
|
||||
#!/usr/bin/env bash
|
||||
# -----------------------------------------------------------------------------
|
||||
# One-shot launcher for the SRU navigation node on Go2 NX.
|
||||
#
|
||||
# Combines a conda python env (onnxruntime, scipy, ...) with the system
|
||||
# ROS Noetic installation (rospy, cv_bridge). The trick:
|
||||
# 1) source /opt/ros/noetic/setup.bash -> ROS env
|
||||
# 2) source <catkin_ws>/devel/setup.bash -> our package
|
||||
# 3) conda activate sru_nav -> python with onnxruntime
|
||||
# 4) export PYTHONPATH=<ros dist-packages>:$PYTHONPATH so conda python
|
||||
# can still import rospy / cv_bridge / sensor_msgs / etc.
|
||||
#
|
||||
# Usage:
|
||||
# bash launch_sru_nav.sh # full launch (joy + static TF + node)
|
||||
# bash launch_sru_nav.sh --no-joy # if /joy is already provided elsewhere
|
||||
# bash launch_sru_nav.sh --no-deadman # TESTING: skip joystick deadman entirely
|
||||
# # (cmd_vel_ratio=1.0, no /joy needed).
|
||||
# # Robot WILL move on /goal_pose alone.
|
||||
# bash launch_sru_nav.sh --node-only # run just sru_nav_node (assume joy + TF already up)
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
set -eu
|
||||
|
||||
ENV_NAME="${ENV_NAME:-sru_nav}"
|
||||
ROS_DISTRO="${ROS_DISTRO:-noetic}"
|
||||
CATKIN_WS="${CATKIN_WS:-$HOME/code/odin_sru_nav}"
|
||||
|
||||
EXTRA_ARGS=""
|
||||
NODE_ONLY=0
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--no-joy) EXTRA_ARGS="$EXTRA_ARGS launch_joy:=false" ;;
|
||||
--no-tf) EXTRA_ARGS="$EXTRA_ARGS launch_static_tf:=false" ;;
|
||||
--no-deadman) EXTRA_ARGS="$EXTRA_ARGS require_joystick:=false launch_joy:=false" ;;
|
||||
--node-only) NODE_ONLY=1 ;;
|
||||
*) EXTRA_ARGS="$EXTRA_ARGS $arg" ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# ---- 1) ROS env -------------------------------------------------------------
|
||||
if [ ! -f "/opt/ros/${ROS_DISTRO}/setup.bash" ]; then
|
||||
echo "[ERROR] /opt/ros/${ROS_DISTRO}/setup.bash not found"; exit 1
|
||||
fi
|
||||
# shellcheck disable=SC1091
|
||||
source "/opt/ros/${ROS_DISTRO}/setup.bash"
|
||||
|
||||
if [ -f "${CATKIN_WS}/devel/setup.bash" ]; then
|
||||
# shellcheck disable=SC1091
|
||||
source "${CATKIN_WS}/devel/setup.bash"
|
||||
else
|
||||
echo "[WARN] ${CATKIN_WS}/devel/setup.bash not found. Did you catkin_make?"
|
||||
fi
|
||||
|
||||
# ---- 2) conda env -----------------------------------------------------------
|
||||
if ! command -v conda >/dev/null 2>&1; then
|
||||
echo "[ERROR] conda not found. Run setup_conda_env.sh first."; exit 1
|
||||
fi
|
||||
CONDA_BASE="$(conda info --base)"
|
||||
# shellcheck disable=SC1091
|
||||
source "${CONDA_BASE}/etc/profile.d/conda.sh"
|
||||
conda activate "${ENV_NAME}"
|
||||
|
||||
# ---- 3) Make rospy / cv_bridge importable from the conda python -------------
|
||||
ROS_PY_DIST="/opt/ros/${ROS_DISTRO}/lib/python3/dist-packages"
|
||||
export PYTHONPATH="${ROS_PY_DIST}:${PYTHONPATH:-}"
|
||||
|
||||
# Fix conda<->system libffi ABI conflict that breaks cv_bridge:
|
||||
# "libp11-kit.so.0: undefined symbol: ffi_type_pointer, version LIBFFI_BASE_7.0"
|
||||
# Force the system libffi (used to build libp11-kit) to load first.
|
||||
for _sys_libffi in \
|
||||
/lib/aarch64-linux-gnu/libffi.so.7 \
|
||||
/usr/lib/aarch64-linux-gnu/libffi.so.7 \
|
||||
/lib/x86_64-linux-gnu/libffi.so.7 \
|
||||
/usr/lib/x86_64-linux-gnu/libffi.so.7; do
|
||||
if [ -f "${_sys_libffi}" ]; then
|
||||
export LD_PRELOAD="${_sys_libffi}${LD_PRELOAD:+:${LD_PRELOAD}}"
|
||||
echo "[INFO] LD_PRELOAD += ${_sys_libffi}"
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
echo "[INFO] python = $(which python)"
|
||||
echo "[INFO] PYTHONPATH = ${PYTHONPATH}"
|
||||
echo "[INFO] ROS_DISTRO = ${ROS_DISTRO}"
|
||||
echo "[INFO] CATKIN_WS = ${CATKIN_WS}"
|
||||
|
||||
# ---- Sanity: catkin wrapper must call conda's python (not system /usr/bin) ---
|
||||
WRAPPER="${CATKIN_WS}/devel/lib/sru_nav_go2_ros1/sru_nav_node"
|
||||
if [ -f "${WRAPPER}" ]; then
|
||||
WRAPPER_SHEBANG="$(head -n1 "${WRAPPER}")"
|
||||
CONDA_PY="$(which python)"
|
||||
case "${WRAPPER_SHEBANG}" in
|
||||
*"${CONDA_PY}"*|*"/usr/bin/env python"*)
|
||||
: # OK
|
||||
;;
|
||||
*)
|
||||
cat >&2 <<EOF
|
||||
[WARN] Catkin-generated wrapper shebang is NOT the conda python:
|
||||
wrapper : ${WRAPPER}
|
||||
shebang : ${WRAPPER_SHEBANG}
|
||||
conda py: ${CONDA_PY}
|
||||
It will likely fail with 'No module named cv2 / onnxruntime'.
|
||||
Fix:
|
||||
conda activate ${ENV_NAME}
|
||||
cd ${CATKIN_WS}
|
||||
catkin_make clean
|
||||
catkin_make -DPYTHON_EXECUTABLE=\$(which python3)
|
||||
EOF
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
|
||||
# ---- 4) Launch --------------------------------------------------------------
|
||||
if [ "$NODE_ONLY" -eq 1 ]; then
|
||||
exec rosrun sru_nav_go2_ros1 sru_nav_node \
|
||||
__ns:= \
|
||||
_vae_model_path:="" _policy_model_path:=""
|
||||
else
|
||||
# shellcheck disable=SC2086
|
||||
exec roslaunch sru_nav_go2_ros1 sru_nav_go2.launch $EXTRA_ARGS
|
||||
fi
|
||||
@@ -0,0 +1,214 @@
|
||||
#!/usr/bin/env bash
|
||||
# -----------------------------------------------------------------------------
|
||||
# Conda environment bootstrap for sru_nav_go2_ros1 on Go2 NX (Jetson Xavier NX)
|
||||
# -----------------------------------------------------------------------------
|
||||
# Goal: create a python env containing onnxruntime + cv2 + scipy + numpy that
|
||||
# works alongside system ROS Noetic (which provides rospy / cv_bridge).
|
||||
#
|
||||
# We do NOT install rospy / cv_bridge into conda. They come from /opt/ros/noetic
|
||||
# (system python3.8). To make them importable from the conda env we expose the
|
||||
# ROS site-packages via PYTHONPATH at run time (see launch_sru_nav.sh).
|
||||
#
|
||||
# Usage:
|
||||
# bash setup_conda_env.sh # create env and install deps
|
||||
# bash setup_conda_env.sh --gpu # try to install Jetson onnxruntime-gpu wheel
|
||||
# bash setup_conda_env.sh --check # just run sanity checks
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
set -eu
|
||||
|
||||
ENV_NAME="${ENV_NAME:-sru_nav}"
|
||||
PY_VER="${PY_VER:-3.8}" # match Noetic's system python so rospy works
|
||||
USE_GPU=0
|
||||
CHECK_ONLY=0
|
||||
SKIP_TIME_CHECK=0
|
||||
|
||||
# Silence anaconda.org's noisy "aau_token_host" telemetry warnings.
|
||||
export ANACONDA_ANON_USAGE=false
|
||||
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--gpu) USE_GPU=1 ;;
|
||||
--check) CHECK_ONLY=1 ;;
|
||||
--skip-time-check) SKIP_TIME_CHECK=1 ;;
|
||||
*) echo "Unknown arg: $arg"; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# 0. System clock sanity. SSL fails with "certificate is not yet valid" when
|
||||
# the Jetson clock is rolled back (no RTC battery). Detect early.
|
||||
# -----------------------------------------------------------------------------
|
||||
if [ "$SKIP_TIME_CHECK" -eq 0 ]; then
|
||||
NOW_EPOCH=$(date +%s)
|
||||
# 2025-01-01 UTC = 1735689600. Treat anything before that as suspicious.
|
||||
if [ "$NOW_EPOCH" -lt 1735689600 ]; then
|
||||
cat >&2 <<EOF
|
||||
[ERROR] System clock looks wrong: $(date)
|
||||
This will break HTTPS/pip with "certificate is not yet valid".
|
||||
Fix it before continuing:
|
||||
|
||||
sudo timedatectl set-ntp true
|
||||
sudo systemctl restart systemd-timesyncd
|
||||
# or, offline:
|
||||
sudo date -s "$(date -u +'%Y-%m-%d %H:%M:%S' -d '@1748400000')"
|
||||
sudo hwclock --systohc
|
||||
|
||||
Then re-run this script. To override (NOT recommended) pass:
|
||||
bash $0 --skip-time-check
|
||||
EOF
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# 1. Locate conda
|
||||
# -----------------------------------------------------------------------------
|
||||
if ! command -v conda >/dev/null 2>&1; then
|
||||
echo "[ERROR] conda not found. Install miniforge (recommended for aarch64):"
|
||||
echo " wget https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-Linux-aarch64.sh"
|
||||
echo " bash Miniforge3-Linux-aarch64.sh -b -p \$HOME/miniforge3"
|
||||
echo " source \$HOME/miniforge3/etc/profile.d/conda.sh"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
CONDA_BASE="$(conda info --base)"
|
||||
# shellcheck disable=SC1091
|
||||
source "${CONDA_BASE}/etc/profile.d/conda.sh"
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# 2. Create env if missing
|
||||
# -----------------------------------------------------------------------------
|
||||
if [ "$CHECK_ONLY" -eq 0 ]; then
|
||||
if conda env list | awk '{print $1}' | grep -qx "${ENV_NAME}"; then
|
||||
echo "[INFO] Conda env '${ENV_NAME}' already exists. Skipping creation."
|
||||
else
|
||||
echo "[INFO] Creating conda env '${ENV_NAME}' with python=${PY_VER}"
|
||||
conda create -y -n "${ENV_NAME}" "python=${PY_VER}" pip
|
||||
fi
|
||||
fi
|
||||
|
||||
conda activate "${ENV_NAME}"
|
||||
|
||||
if [ "$CHECK_ONLY" -eq 0 ]; then
|
||||
echo "[INFO] Installing Python dependencies into '${ENV_NAME}'"
|
||||
# Optional: use a faster mirror (Tsinghua) if PIP_INDEX_URL is not already set.
|
||||
: "${PIP_INDEX_URL:=}"
|
||||
export PIP_INDEX_URL
|
||||
echo "[INFO] PIP_INDEX_URL=${PIP_INDEX_URL}"
|
||||
|
||||
python -m pip install --upgrade pip
|
||||
# Pin versions that are known to work on python 3.8 + ARM.
|
||||
# netifaces / defusedxml are needed by rospy at runtime (the system ROS
|
||||
# python gets them via apt 'python3-netifaces / python3-defusedxml', but
|
||||
# the conda python does not).
|
||||
python -m pip install \
|
||||
"numpy<2.0" \
|
||||
"scipy>=1.7,<1.11" \
|
||||
"opencv-python>=4.5,<5.0" \
|
||||
"rospkg" \
|
||||
"pyyaml" \
|
||||
"empy==3.3.4" \
|
||||
"netifaces" \
|
||||
"defusedxml"
|
||||
|
||||
if [ "$USE_GPU" -eq 1 ]; then
|
||||
cat <<'EOF'
|
||||
[INFO] --gpu requested. Standard pip onnxruntime-gpu does NOT work on Jetson.
|
||||
Download the JetPack-matched wheel from NVIDIA's Jetson Zoo:
|
||||
https://elinux.org/Jetson_Zoo#ONNX_Runtime
|
||||
Then install with e.g.:
|
||||
pip install ./onnxruntime_gpu-<ver>-cp38-cp38-linux_aarch64.whl
|
||||
Skipping automatic GPU wheel install.
|
||||
EOF
|
||||
python -m pip install "onnxruntime>=1.15,<1.18" # CPU fallback so node still runs
|
||||
else
|
||||
python -m pip install "onnxruntime>=1.15,<1.18"
|
||||
fi
|
||||
fi
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# 3. Sanity checks
|
||||
# -----------------------------------------------------------------------------
|
||||
echo
|
||||
echo "============================================================"
|
||||
echo " Sanity check: conda env '${ENV_NAME}'"
|
||||
echo "============================================================"
|
||||
python - <<'PYEOF'
|
||||
import sys, platform
|
||||
print(f"python : {sys.version.split()[0]} ({platform.machine()})")
|
||||
fail = []
|
||||
|
||||
def check(name, importer):
|
||||
try:
|
||||
mod = importer()
|
||||
ver = getattr(mod, "__version__", "?")
|
||||
print(f" [OK] {name:18s} {ver}")
|
||||
except Exception as e:
|
||||
print(f" [FAIL] {name}: {e}")
|
||||
fail.append(name)
|
||||
|
||||
check("numpy", lambda: __import__("numpy"))
|
||||
check("scipy", lambda: __import__("scipy"))
|
||||
check("cv2", lambda: __import__("cv2"))
|
||||
check("rospkg", lambda: __import__("rospkg"))
|
||||
check("netifaces", lambda: __import__("netifaces"))
|
||||
check("defusedxml", lambda: __import__("defusedxml"))
|
||||
check("onnxruntime", lambda: __import__("onnxruntime"))
|
||||
|
||||
try:
|
||||
import onnxruntime as ort
|
||||
print(f" ORT providers : {ort.get_available_providers()}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# rospy / cv_bridge come from /opt/ros/noetic; only succeed when PYTHONPATH is set.
|
||||
import os
|
||||
ros_path = "/opt/ros/noetic/lib/python3/dist-packages"
|
||||
if os.path.isdir(ros_path) and ros_path not in sys.path:
|
||||
sys.path.insert(0, ros_path)
|
||||
|
||||
check("rospy", lambda: __import__("rospy"))
|
||||
check("cv_bridge", lambda: __import__("cv_bridge"))
|
||||
|
||||
if fail:
|
||||
print(f"\n[WARN] Missing modules: {fail}")
|
||||
sys.exit(1)
|
||||
print("\n[OK] All imports passed.")
|
||||
PYEOF
|
||||
|
||||
echo
|
||||
echo "[INFO] Try loading the policy ONNX files (if present)..."
|
||||
# Resolve the package's models/ directory relative to THIS script.
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
PKG_MODELS_DIR="$(cd "${SCRIPT_DIR}/../models" 2>/dev/null && pwd || echo '')"
|
||||
export PKG_MODELS_DIR
|
||||
python - <<'PYEOF'
|
||||
import os, sys
|
||||
candidates = [
|
||||
os.environ.get("PKG_MODELS_DIR", ""),
|
||||
os.path.expanduser("~/sru_ws/src/sru_nav_go2_ros1/models"),
|
||||
]
|
||||
candidates = [c for c in candidates if c]
|
||||
import onnxruntime as ort
|
||||
for d in candidates:
|
||||
vae = os.path.join(d, "vae_encoder.onnx")
|
||||
pol = os.path.join(d, "nav_policy.onnx")
|
||||
if os.path.exists(vae) and os.path.exists(pol):
|
||||
print(f" Found models in {d}")
|
||||
try:
|
||||
s1 = ort.InferenceSession(vae, providers=["CPUExecutionProvider"])
|
||||
s2 = ort.InferenceSession(pol, providers=["CPUExecutionProvider"])
|
||||
print(f" vae inputs : {[i.name+str(i.shape) for i in s1.get_inputs()]}")
|
||||
print(f" vae outputs : {[o.name+str(o.shape) for o in s1.get_outputs()]}")
|
||||
print(f" pol inputs : {[i.name+str(i.shape) for i in s2.get_inputs()]}")
|
||||
print(f" pol outputs : {[o.name+str(o.shape) for o in s2.get_outputs()]}")
|
||||
except Exception as e:
|
||||
print(f" [FAIL] {e}")
|
||||
break
|
||||
else:
|
||||
print(" (No models found; skipping ORT smoke test.)")
|
||||
PYEOF
|
||||
|
||||
echo
|
||||
echo "[DONE] Activate with: conda activate ${ENV_NAME}"
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
#!/usr/bin/env python3
|
||||
"""ROS1 entry point for the SRU navigation controller on Go2 + Odin1."""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
import rospkg
|
||||
import rospy
|
||||
|
||||
from sru_nav_go2.navigation_policy_node import NavigationPolicyNode
|
||||
from sru_nav_go2 import constants
|
||||
|
||||
|
||||
def _resolve_model_path(param_value, default_basename):
|
||||
"""Resolve a model path: absolute path if given, else look under
|
||||
<package>/models/<default_basename>, else fall back to the original
|
||||
sru-robot-deployment/rl_nav_controller/deployment_policies/ folder if
|
||||
present alongside this package's workspace.
|
||||
"""
|
||||
if param_value and os.path.isabs(param_value) and os.path.exists(param_value):
|
||||
return param_value
|
||||
|
||||
rp = rospkg.RosPack()
|
||||
try:
|
||||
pkg_path = rp.get_path('sru_nav_go2_ros1')
|
||||
except rospkg.ResourceNotFound:
|
||||
pkg_path = None
|
||||
|
||||
candidates = []
|
||||
if param_value:
|
||||
candidates.append(param_value)
|
||||
if pkg_path:
|
||||
candidates.append(os.path.join(pkg_path, 'models', default_basename))
|
||||
# Sibling deployment_policies folder (when sources are checked out together)
|
||||
candidates.append(os.path.join(
|
||||
pkg_path, '..', '..', 'sru-robot-deployment',
|
||||
'rl_nav_controller', 'deployment_policies', default_basename))
|
||||
|
||||
for c in candidates:
|
||||
if c and os.path.exists(c):
|
||||
return os.path.abspath(c)
|
||||
|
||||
raise FileNotFoundError(
|
||||
'Could not locate {} (checked: {})'.format(default_basename, candidates)
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
rospy.init_node('sru_nav_node', anonymous=False)
|
||||
|
||||
# --- Topics ---------------------------------------------------------
|
||||
depth_topic = rospy.get_param('~depth_topic', '/odin1/depth_img_competetion')
|
||||
odom_topic = rospy.get_param('~odom_topic', '/odin1/odometry_highfreq')
|
||||
joy_topic = rospy.get_param('~joy_topic', '/joy')
|
||||
goal_topic = rospy.get_param('~goal_topic', '/goal_pose')
|
||||
cmd_vel_topic = rospy.get_param('~cmd_vel_topic', '/cmd_vel')
|
||||
|
||||
# --- Models ---------------------------------------------------------
|
||||
vae_param = rospy.get_param('~vae_model_path', '')
|
||||
pol_param = rospy.get_param('~policy_model_path', '')
|
||||
try:
|
||||
vae_model_path = _resolve_model_path(vae_param, 'vae_encoder.onnx')
|
||||
policy_model_path = _resolve_model_path(pol_param, 'nav_policy.onnx')
|
||||
except FileNotFoundError as exc:
|
||||
rospy.logerr(str(exc))
|
||||
sys.exit(1)
|
||||
rospy.loginfo('VAE encoder: {}'.format(vae_model_path))
|
||||
rospy.loginfo('Policy model: {}'.format(policy_model_path))
|
||||
|
||||
# --- Numeric params -------------------------------------------------
|
||||
min_depth = rospy.get_param('~min_depth', constants.DEFAULT_MIN_DEPTH)
|
||||
max_depth = rospy.get_param('~max_depth', constants.DEFAULT_MAX_DEPTH)
|
||||
control_frequency = rospy.get_param(
|
||||
'~control_frequency', constants.DEFAULT_CONTROL_FREQUENCY)
|
||||
policy_scale = rospy.get_param('~policy_scale', list(constants.POLICY_SCALE))
|
||||
use_sim = rospy.get_param('~use_sim', False)
|
||||
require_joystick = rospy.get_param('~require_joystick', True)
|
||||
|
||||
if not isinstance(policy_scale, (list, tuple)) or len(policy_scale) != 3:
|
||||
rospy.logwarn('Invalid ~policy_scale, falling back to {}'.format(
|
||||
list(constants.POLICY_SCALE)))
|
||||
policy_scale = list(constants.POLICY_SCALE)
|
||||
|
||||
NavigationPolicyNode(
|
||||
preprocess_model_path=vae_model_path,
|
||||
policy_model_path=policy_model_path,
|
||||
depth_topic=depth_topic,
|
||||
odom_topic=odom_topic,
|
||||
joy_topic=joy_topic,
|
||||
goal_topic=goal_topic,
|
||||
cmd_vel_topic=cmd_vel_topic,
|
||||
min_depth=min_depth,
|
||||
max_depth=max_depth,
|
||||
control_frequency=control_frequency,
|
||||
policy_scale=policy_scale,
|
||||
use_sim=use_sim,
|
||||
require_joystick=require_joystick,
|
||||
)
|
||||
|
||||
rospy.loginfo(
|
||||
'SRU navigation node spinning (sim={}, require_joystick={}).'
|
||||
.format(use_sim, require_joystick))
|
||||
rospy.spin()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+291
@@ -0,0 +1,291 @@
|
||||
#!/usr/bin/env bash
|
||||
# -----------------------------------------------------------------------------
|
||||
# verify_port.sh — automated acceptance checks for sru_nav_go2_ros1
|
||||
#
|
||||
# Run after generating (or updating) the package to confirm the port is
|
||||
# self-consistent and ready for hardware testing.
|
||||
#
|
||||
# Usage:
|
||||
# bash scripts/verify_port.sh # full check
|
||||
# bash scripts/verify_port.sh --skip-roslaunch # skip the live node test
|
||||
# ENV_NAME=my_env CATKIN_WS=/path bash scripts/verify_port.sh
|
||||
#
|
||||
# Exit code: 0 if everything passes, 1 otherwise.
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
set -u
|
||||
|
||||
ENV_NAME="${ENV_NAME:-sru_nav}"
|
||||
ROS_DISTRO="${ROS_DISTRO:-noetic}"
|
||||
CATKIN_WS="${CATKIN_WS:-$HOME/code/odin_sru_nav}"
|
||||
|
||||
PKG_DIR="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
SKIP_ROSLAUNCH=0
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--skip-roslaunch) SKIP_ROSLAUNCH=1 ;;
|
||||
-h|--help)
|
||||
sed -n '2,15p' "$0"; exit 0 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
PASS=0
|
||||
FAIL=0
|
||||
WARN=0
|
||||
|
||||
c_red() { printf "\033[31m%s\033[0m" "$1"; }
|
||||
c_green() { printf "\033[32m%s\033[0m" "$1"; }
|
||||
c_yellow() { printf "\033[33m%s\033[0m" "$1"; }
|
||||
|
||||
ok() { echo " [$(c_green PASS)] $1"; PASS=$((PASS+1)); }
|
||||
fail() { echo " [$(c_red FAIL)] $1"; FAIL=$((FAIL+1)); }
|
||||
warn() { echo " [$(c_yellow WARN)] $1"; WARN=$((WARN+1)); }
|
||||
info() { echo " [INFO] $1"; }
|
||||
|
||||
section() { echo; echo "=== $1 ==="; }
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
section "0. Environment"
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
info "PKG_DIR = ${PKG_DIR}"
|
||||
info "CATKIN_WS = ${CATKIN_WS}"
|
||||
info "ENV_NAME = ${ENV_NAME}"
|
||||
info "ROS_DISTRO = ${ROS_DISTRO}"
|
||||
|
||||
# OS
|
||||
if grep -q "Ubuntu 20.04" /etc/os-release 2>/dev/null; then
|
||||
ok "Ubuntu 20.04 (Noetic-compatible)"
|
||||
else
|
||||
warn "OS is not Ubuntu 20.04 — Noetic may not run cleanly"
|
||||
fi
|
||||
|
||||
# ROS
|
||||
if [ -f "/opt/ros/${ROS_DISTRO}/setup.bash" ]; then
|
||||
ok "ROS ${ROS_DISTRO} installed"
|
||||
else
|
||||
fail "/opt/ros/${ROS_DISTRO}/setup.bash not found"
|
||||
fi
|
||||
|
||||
# Conda
|
||||
if command -v conda >/dev/null 2>&1; then
|
||||
ok "conda available ($(conda --version))"
|
||||
else
|
||||
fail "conda not found in PATH"
|
||||
fi
|
||||
|
||||
# System clock
|
||||
year=$(date +%Y)
|
||||
if [ "$year" -ge 2024 ] && [ "$year" -le 2099 ]; then
|
||||
ok "system clock looks sane ($(date '+%Y-%m-%d %H:%M:%S'))"
|
||||
else
|
||||
fail "system clock implausible ($(date)) — pip TLS will fail"
|
||||
fi
|
||||
|
||||
# libffi
|
||||
if ls /lib/*-linux-gnu/libffi.so.7 2>/dev/null >/dev/null; then
|
||||
ok "system libffi.so.7 present (LD_PRELOAD target)"
|
||||
elif ls /lib/*-linux-gnu/libffi.so.8 2>/dev/null >/dev/null; then
|
||||
warn "only libffi.so.8 found — update launch_sru_nav.sh accordingly"
|
||||
else
|
||||
fail "no system libffi.so.* — cv_bridge will likely fail"
|
||||
fi
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
section "1. Package layout"
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
req_files=(
|
||||
"package.xml"
|
||||
"CMakeLists.txt"
|
||||
"setup.py"
|
||||
"launch/sru_nav_go2.launch"
|
||||
"config/sru_nav.yaml"
|
||||
"scripts/sru_nav_node"
|
||||
"scripts/launch_sru_nav.sh"
|
||||
"scripts/setup_conda_env.sh"
|
||||
"src/sru_nav_go2/__init__.py"
|
||||
"src/sru_nav_go2/constants.py"
|
||||
"src/sru_nav_go2/model.py"
|
||||
"src/sru_nav_go2/utils.py"
|
||||
"src/sru_nav_go2/visualization.py"
|
||||
"src/sru_nav_go2/waypoint_manager.py"
|
||||
"src/sru_nav_go2/navigation_policy_node.py"
|
||||
"models/vae_encoder.onnx"
|
||||
"models/nav_policy.onnx"
|
||||
)
|
||||
|
||||
for f in "${req_files[@]}"; do
|
||||
if [ -e "${PKG_DIR}/${f}" ]; then
|
||||
ok "${f}"
|
||||
else
|
||||
fail "missing: ${f}"
|
||||
fi
|
||||
done
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
section "2. YAML config — required parameters"
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
YAML="${PKG_DIR}/config/sru_nav.yaml"
|
||||
if [ -f "$YAML" ]; then
|
||||
for key in depth_topic odom_topic joy_topic goal_topic cmd_vel_topic \
|
||||
min_depth max_depth control_frequency policy_scale \
|
||||
use_sim require_joystick; do
|
||||
if grep -E "^[[:space:]]*${key}[[:space:]]*:" "$YAML" >/dev/null; then
|
||||
ok "yaml has ${key}"
|
||||
else
|
||||
fail "yaml missing ${key}"
|
||||
fi
|
||||
done
|
||||
else
|
||||
fail "yaml not found"
|
||||
fi
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
section "3. Constants — training-aligned numerics"
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
CONSTS="${PKG_DIR}/src/sru_nav_go2/constants.py"
|
||||
if [ -f "$CONSTS" ]; then
|
||||
declare -A want=(
|
||||
[DEFAULT_CONTROL_FREQUENCY]="5"
|
||||
[DEFAULT_MIN_DEPTH]="0.25"
|
||||
[DEFAULT_MAX_DEPTH]="10"
|
||||
[JOYSTICK_TIMEOUT]="15"
|
||||
)
|
||||
for k in "${!want[@]}"; do
|
||||
if grep -E "^${k}\s*=\s*${want[$k]}" "$CONSTS" >/dev/null; then
|
||||
ok "${k} = ${want[$k]}"
|
||||
else
|
||||
warn "${k} not exactly ${want[$k]} — verify against training cfg"
|
||||
fi
|
||||
done
|
||||
else
|
||||
fail "constants.py not found"
|
||||
fi
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
section "4. Launch script — coexistence fixes"
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
LAUNCH_SH="${PKG_DIR}/scripts/launch_sru_nav.sh"
|
||||
if [ -f "$LAUNCH_SH" ]; then
|
||||
grep -q "LD_PRELOAD" "$LAUNCH_SH" && ok "LD_PRELOAD libffi fix present" \
|
||||
|| fail "no LD_PRELOAD libffi fix"
|
||||
grep -q "PYTHONPATH" "$LAUNCH_SH" && ok "ROS dist-packages injected to PYTHONPATH" \
|
||||
|| fail "no PYTHONPATH injection"
|
||||
grep -q "conda activate" "$LAUNCH_SH" && ok "conda activate in launcher" \
|
||||
|| fail "no conda activate"
|
||||
grep -q -- "--no-deadman" "$LAUNCH_SH" && ok "--no-deadman bypass present" \
|
||||
|| warn "no --no-deadman flag"
|
||||
fi
|
||||
|
||||
SETUP_SH="${PKG_DIR}/scripts/setup_conda_env.sh"
|
||||
if [ -f "$SETUP_SH" ]; then
|
||||
for pkg in onnxruntime netifaces defusedxml opencv-python rospkg empy; do
|
||||
grep -q "$pkg" "$SETUP_SH" \
|
||||
&& ok "setup installs ${pkg}" \
|
||||
|| fail "setup script missing ${pkg}"
|
||||
done
|
||||
fi
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
section "5. ONNX models — load test"
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
if command -v python >/dev/null && python -c "import onnxruntime" 2>/dev/null; then
|
||||
for f in "models/vae_encoder.onnx" "models/nav_policy.onnx"; do
|
||||
full="${PKG_DIR}/${f}"
|
||||
if [ -f "$full" ]; then
|
||||
if python - <<EOF 2>/dev/null
|
||||
import onnxruntime as ort, sys
|
||||
s = ort.InferenceSession("${full}", providers=["CPUExecutionProvider"])
|
||||
print(" ${f} inputs:", [(i.name, i.shape) for i in s.get_inputs()])
|
||||
print(" ${f} outputs:", [(o.name, o.shape) for o in s.get_outputs()])
|
||||
EOF
|
||||
then
|
||||
ok "${f} loads in onnxruntime"
|
||||
else
|
||||
fail "${f} failed to load (corrupt or wrong opset?)"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
else
|
||||
warn "onnxruntime not importable in current shell — skipping load test"
|
||||
warn " hint: 'conda activate ${ENV_NAME}' before running verify_port.sh"
|
||||
fi
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
section "6. catkin build artifacts (optional)"
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
WRAPPER="${CATKIN_WS}/devel/lib/sru_nav_go2_ros1/sru_nav_node"
|
||||
if [ -f "$WRAPPER" ]; then
|
||||
ok "catkin wrapper exists: ${WRAPPER}"
|
||||
shebang=$(head -n1 "$WRAPPER")
|
||||
if echo "$shebang" | grep -qE "miniconda|anaconda|envs/${ENV_NAME}"; then
|
||||
ok "wrapper shebang points at conda python"
|
||||
info " shebang: ${shebang}"
|
||||
else
|
||||
fail "wrapper shebang is NOT conda python: ${shebang}"
|
||||
info " fix: 'conda activate ${ENV_NAME} && cd ${CATKIN_WS} && \\"
|
||||
info " catkin_make clean && catkin_make -DPYTHON_EXECUTABLE=\$(which python3)'"
|
||||
fi
|
||||
else
|
||||
warn "no catkin build artifact — run catkin_make in conda env first"
|
||||
fi
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
section "7. Live roslaunch smoke test"
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
if [ "$SKIP_ROSLAUNCH" -eq 1 ]; then
|
||||
info "skipped (--skip-roslaunch)"
|
||||
elif [ ! -f "${CATKIN_WS}/devel/setup.bash" ]; then
|
||||
warn "catkin workspace not built — skipping roslaunch test"
|
||||
else
|
||||
# shellcheck disable=SC1090
|
||||
source "/opt/ros/${ROS_DISTRO}/setup.bash" || true
|
||||
source "${CATKIN_WS}/devel/setup.bash" || true
|
||||
|
||||
if ! command -v roslaunch >/dev/null; then
|
||||
fail "roslaunch not on PATH after sourcing"
|
||||
else
|
||||
LOG=$(mktemp)
|
||||
timeout 12 roslaunch sru_nav_go2_ros1 sru_nav_go2.launch \
|
||||
launch_joy:=false launch_static_tf:=false \
|
||||
require_joystick:=false >"$LOG" 2>&1 &
|
||||
RPID=$!
|
||||
sleep 8
|
||||
if grep -q "Navigation policy node is ready" "$LOG"; then
|
||||
ok "node became ready within 8 s"
|
||||
else
|
||||
fail "node did not reach 'ready' state within 8 s"
|
||||
info " last 20 log lines:"
|
||||
tail -n 20 "$LOG" | sed 's/^/ /'
|
||||
fi
|
||||
kill "$RPID" 2>/dev/null
|
||||
wait "$RPID" 2>/dev/null
|
||||
rm -f "$LOG"
|
||||
fi
|
||||
fi
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
section "Summary"
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
echo " PASS=${PASS} FAIL=${FAIL} WARN=${WARN}"
|
||||
if [ "$FAIL" -gt 0 ]; then
|
||||
echo
|
||||
c_red "RESULT: FAIL"; echo
|
||||
exit 1
|
||||
elif [ "$WARN" -gt 0 ]; then
|
||||
echo
|
||||
c_yellow "RESULT: PASS WITH WARNINGS"; echo
|
||||
exit 0
|
||||
else
|
||||
echo
|
||||
c_green "ALL CHECKS PASSED"; echo
|
||||
exit 0
|
||||
fi
|
||||
@@ -0,0 +1,331 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Sequential waypoint runner for sru_nav_go2_ros1.
|
||||
|
||||
Publishes a list of goals to /goal_pose one at a time, monitors the robot
|
||||
odometry to decide when each goal is reached (or has timed out, or the robot
|
||||
is stuck), then moves on to the next. After the last waypoint, optionally
|
||||
returns to the pose captured at script start.
|
||||
|
||||
Does NOT modify any code in sru_nav_go2_ros1. Works purely as an external
|
||||
client on top of the existing /goal_pose + /odin1/odometry_highfreq contract.
|
||||
|
||||
Usage
|
||||
-----
|
||||
# YAML file
|
||||
rosrun sru_nav_go2_ros1 waypoint_runner.py --file waypoints.yaml
|
||||
|
||||
# Command line (x,y[,z] tuples separated by spaces)
|
||||
rosrun sru_nav_go2_ros1 waypoint_runner.py \
|
||||
--waypoints "3,0 3,2 0,2" --return-home
|
||||
|
||||
YAML format
|
||||
-----------
|
||||
frame_id: odom
|
||||
arrive_threshold: 0.75 # meters, XY distance to consider 'arrived'
|
||||
settle_time: 1.5 # seconds the robot must stay within threshold
|
||||
per_goal_timeout: 60.0 # seconds before giving up on a goal
|
||||
stuck_window: 10.0 # seconds of trailing window for stuck check
|
||||
stuck_displacement: 0.10 # meters; below this in `stuck_window` -> skip
|
||||
republish_interval: 5.0 # seconds; re-publish the same goal periodically
|
||||
return_home: true
|
||||
waypoints:
|
||||
- [3.0, 0.0, 0.0]
|
||||
- [3.0, 2.0, 0.0]
|
||||
- [0.0, 2.0, 0.0]
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import collections
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
import rospy
|
||||
import yaml
|
||||
from geometry_msgs.msg import PoseStamped
|
||||
from nav_msgs.msg import Odometry
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Defaults (mirror sru_nav_go2_ros1/constants.py where applicable)
|
||||
# ---------------------------------------------------------------------------
|
||||
DEFAULTS = dict(
|
||||
frame_id='odom',
|
||||
arrive_threshold=0.75, # matches constants.ARRIVE_GOAL_THRESHOLD
|
||||
settle_time=1.5,
|
||||
per_goal_timeout=60.0,
|
||||
stuck_window=10.0,
|
||||
stuck_displacement=0.10,
|
||||
republish_interval=5.0,
|
||||
return_home=True,
|
||||
odom_topic='/odin1/odometry_highfreq',
|
||||
goal_topic='/goal_pose',
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Parsing
|
||||
# ---------------------------------------------------------------------------
|
||||
def _parse_inline_waypoints(text):
|
||||
"""Parse "x,y[,z] x,y[,z] ..." into list[list[float]]."""
|
||||
out = []
|
||||
if not text:
|
||||
return out
|
||||
for tok in text.split():
|
||||
parts = tok.split(',')
|
||||
if len(parts) not in (2, 3):
|
||||
raise ValueError(
|
||||
"Bad waypoint '{}': expected 'x,y' or 'x,y,z'".format(tok))
|
||||
xyz = [float(parts[0]), float(parts[1]),
|
||||
float(parts[2]) if len(parts) == 3 else 0.0]
|
||||
out.append(xyz)
|
||||
return out
|
||||
|
||||
|
||||
def _load_yaml(path):
|
||||
with open(path, 'r') as f:
|
||||
data = yaml.safe_load(f) or {}
|
||||
if 'waypoints' not in data or not data['waypoints']:
|
||||
raise ValueError("YAML '{}' has no 'waypoints' list.".format(path))
|
||||
norm = []
|
||||
for wp in data['waypoints']:
|
||||
if len(wp) not in (2, 3):
|
||||
raise ValueError("Bad waypoint {} (need 2 or 3 floats).".format(wp))
|
||||
x = float(wp[0]); y = float(wp[1])
|
||||
z = float(wp[2]) if len(wp) == 3 else 0.0
|
||||
norm.append([x, y, z])
|
||||
data['waypoints'] = norm
|
||||
return data
|
||||
|
||||
|
||||
def build_config(args):
|
||||
cfg = dict(DEFAULTS)
|
||||
if args.file:
|
||||
cfg.update({k: v for k, v in _load_yaml(args.file).items() if v is not None})
|
||||
# Command-line overrides win over YAML
|
||||
if args.waypoints:
|
||||
cfg['waypoints'] = _parse_inline_waypoints(args.waypoints)
|
||||
if args.frame_id is not None:
|
||||
cfg['frame_id'] = args.frame_id
|
||||
if args.timeout is not None:
|
||||
cfg['per_goal_timeout'] = float(args.timeout)
|
||||
if args.arrive_threshold is not None:
|
||||
cfg['arrive_threshold'] = float(args.arrive_threshold)
|
||||
if args.return_home is not None:
|
||||
cfg['return_home'] = args.return_home
|
||||
if 'waypoints' not in cfg or not cfg['waypoints']:
|
||||
raise ValueError("No waypoints provided (use --file or --waypoints).")
|
||||
return cfg
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Runner
|
||||
# ---------------------------------------------------------------------------
|
||||
class WaypointRunner(object):
|
||||
def __init__(self, cfg):
|
||||
self.cfg = cfg
|
||||
|
||||
self._pose = None # latest (x, y, z, t)
|
||||
self._pose_history = collections.deque() # entries: (t, x, y)
|
||||
self._home = None # (x, y, z) captured at first odom
|
||||
|
||||
self.goal_pub = rospy.Publisher(
|
||||
cfg['goal_topic'], PoseStamped, queue_size=1, latch=True)
|
||||
self.odom_sub = rospy.Subscriber(
|
||||
cfg['odom_topic'], Odometry, self._odom_cb, queue_size=20)
|
||||
|
||||
rospy.loginfo("waypoint_runner: waiting for first odom on '%s' ...",
|
||||
cfg['odom_topic'])
|
||||
self._wait_for_odom(timeout=30.0)
|
||||
self._home = (self._pose[0], self._pose[1], self._pose[2])
|
||||
rospy.loginfo("waypoint_runner: home pose captured at "
|
||||
"x=%.3f y=%.3f z=%.3f", *self._home)
|
||||
|
||||
# Give the latched publisher a moment so the first goal isn't lost.
|
||||
time.sleep(0.5)
|
||||
|
||||
# --------------------------------------------------------------- callbacks
|
||||
def _odom_cb(self, msg):
|
||||
t = msg.header.stamp.to_sec() or rospy.get_time()
|
||||
p = msg.pose.pose.position
|
||||
self._pose = (p.x, p.y, p.z, t)
|
||||
self._pose_history.append((t, p.x, p.y))
|
||||
# Trim history to a bit more than stuck_window
|
||||
cutoff = t - max(self.cfg['stuck_window'] * 2.0, 5.0)
|
||||
while self._pose_history and self._pose_history[0][0] < cutoff:
|
||||
self._pose_history.popleft()
|
||||
|
||||
def _wait_for_odom(self, timeout):
|
||||
t0 = time.time()
|
||||
rate = rospy.Rate(20)
|
||||
while not rospy.is_shutdown() and self._pose is None:
|
||||
if time.time() - t0 > timeout:
|
||||
raise RuntimeError(
|
||||
"No odometry received on '{}' within {:.1f}s.".format(
|
||||
self.cfg['odom_topic'], timeout))
|
||||
rate.sleep()
|
||||
|
||||
# ------------------------------------------------------------------ goals
|
||||
def _publish_goal(self, xyz):
|
||||
msg = PoseStamped()
|
||||
msg.header.stamp = rospy.Time.now()
|
||||
msg.header.frame_id = self.cfg['frame_id']
|
||||
msg.pose.position.x = float(xyz[0])
|
||||
msg.pose.position.y = float(xyz[1])
|
||||
msg.pose.position.z = float(xyz[2])
|
||||
msg.pose.orientation.w = 1.0
|
||||
self.goal_pub.publish(msg)
|
||||
|
||||
def _xy_dist(self, ax, ay, bx, by):
|
||||
return math.hypot(ax - bx, ay - by)
|
||||
|
||||
def _displacement_in_window(self, window):
|
||||
"""Max XY distance between any two samples within trailing `window` s."""
|
||||
# Snapshot first: _odom_cb runs in the subscriber thread and may
|
||||
# append/popleft while we iterate, which raises
|
||||
# "deque mutated during iteration".
|
||||
snapshot = list(self._pose_history)
|
||||
if not snapshot:
|
||||
return 0.0
|
||||
now = snapshot[-1][0]
|
||||
cutoff = now - window
|
||||
pts = [(x, y) for (t, x, y) in snapshot if t >= cutoff]
|
||||
if len(pts) < 2:
|
||||
return 0.0
|
||||
xs = [p[0] for p in pts]; ys = [p[1] for p in pts]
|
||||
# Bounding box diagonal is a cheap, monotone proxy for "did it move".
|
||||
return math.hypot(max(xs) - min(xs), max(ys) - min(ys))
|
||||
|
||||
def _run_goal(self, idx, total, xyz, label):
|
||||
cfg = self.cfg
|
||||
rospy.loginfo("\033[96m[%d/%d %s] -> x=%.3f y=%.3f z=%.3f\033[0m",
|
||||
idx, total, label, xyz[0], xyz[1], xyz[2])
|
||||
self._publish_goal(xyz)
|
||||
|
||||
t_start = time.time()
|
||||
t_last_pub = t_start
|
||||
within_since = None
|
||||
rate = rospy.Rate(10)
|
||||
|
||||
while not rospy.is_shutdown():
|
||||
now = time.time()
|
||||
elapsed = now - t_start
|
||||
|
||||
# 1) Timeout
|
||||
if elapsed > cfg['per_goal_timeout']:
|
||||
rospy.logwarn("[%d/%d %s] TIMEOUT after %.1fs; skipping.",
|
||||
idx, total, label, elapsed)
|
||||
return 'timeout'
|
||||
|
||||
# 2) Stuck check (only after the window has elapsed)
|
||||
if elapsed > cfg['stuck_window']:
|
||||
disp = self._displacement_in_window(cfg['stuck_window'])
|
||||
if disp < cfg['stuck_displacement']:
|
||||
rospy.logwarn(
|
||||
"[%d/%d %s] STUCK (disp=%.3fm < %.3fm in last %.1fs); "
|
||||
"skipping.", idx, total, label, disp,
|
||||
cfg['stuck_displacement'], cfg['stuck_window'])
|
||||
return 'stuck'
|
||||
|
||||
# 3) Arrived?
|
||||
x, y, _z, _t = self._pose
|
||||
d = self._xy_dist(x, y, xyz[0], xyz[1])
|
||||
if d <= cfg['arrive_threshold']:
|
||||
if within_since is None:
|
||||
within_since = now
|
||||
elif (now - within_since) >= cfg['settle_time']:
|
||||
rospy.loginfo(
|
||||
"\033[92m[%d/%d %s] ARRIVED (d=%.2fm, settled %.1fs)"
|
||||
"\033[0m", idx, total, label, d, cfg['settle_time'])
|
||||
return 'arrived'
|
||||
else:
|
||||
within_since = None
|
||||
|
||||
# 4) Periodic re-publish (protects against missed first publish)
|
||||
if (cfg['republish_interval'] > 0
|
||||
and (now - t_last_pub) >= cfg['republish_interval']):
|
||||
self._publish_goal(xyz)
|
||||
t_last_pub = now
|
||||
rospy.loginfo_throttle(
|
||||
5.0, "[%d/%d %s] re-published goal (d=%.2fm, t=%.1fs)",
|
||||
idx, total, label, d, elapsed)
|
||||
|
||||
rate.sleep()
|
||||
return 'shutdown'
|
||||
|
||||
def run(self):
|
||||
cfg = self.cfg
|
||||
wps = list(cfg['waypoints'])
|
||||
if cfg['return_home']:
|
||||
wps.append(list(self._home))
|
||||
total = len(wps)
|
||||
|
||||
results = []
|
||||
for i, wp in enumerate(wps, start=1):
|
||||
label = 'HOME' if (cfg['return_home'] and i == total) else 'WP'
|
||||
res = self._run_goal(i, total, wp, label)
|
||||
results.append((i, label, wp, res))
|
||||
if rospy.is_shutdown():
|
||||
break
|
||||
|
||||
# Summary
|
||||
rospy.loginfo("\033[95m===== waypoint_runner summary =====\033[0m")
|
||||
for i, label, wp, res in results:
|
||||
rospy.loginfo(" %2d/%d %s (%.2f, %.2f, %.2f) -> %s",
|
||||
i, total, label, wp[0], wp[1], wp[2], res)
|
||||
rospy.loginfo("\033[95m===================================\033[0m")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Entry point
|
||||
# ---------------------------------------------------------------------------
|
||||
def parse_args(argv):
|
||||
p = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
p.add_argument('--file', '-f', type=str, default=None,
|
||||
help='YAML file with waypoints and (optional) parameters.')
|
||||
p.add_argument('--waypoints', '-w', type=str, default=None,
|
||||
help='Space-separated "x,y[,z]" tuples (overrides YAML).')
|
||||
p.add_argument('--frame-id', type=str, default=None,
|
||||
help="Goal frame_id (default 'odom').")
|
||||
p.add_argument('--timeout', type=float, default=None,
|
||||
help='Per-goal timeout in seconds.')
|
||||
p.add_argument('--arrive-threshold', type=float, default=None,
|
||||
help='XY arrival threshold in meters.')
|
||||
g = p.add_mutually_exclusive_group()
|
||||
g.add_argument('--return-home', dest='return_home', action='store_true',
|
||||
default=None, help='Append start pose as final goal.')
|
||||
g.add_argument('--no-return-home', dest='return_home', action='store_false',
|
||||
help='Do not return to start pose after last waypoint.')
|
||||
return p.parse_args(argv)
|
||||
|
||||
|
||||
def main():
|
||||
args = parse_args(rospy.myargv()[1:])
|
||||
try:
|
||||
cfg = build_config(args)
|
||||
except (ValueError, OSError) as exc:
|
||||
sys.stderr.write('[waypoint_runner] config error: {}\n'.format(exc))
|
||||
sys.exit(2)
|
||||
|
||||
rospy.init_node('waypoint_runner', anonymous=False)
|
||||
|
||||
rospy.loginfo('waypoint_runner config:')
|
||||
for k in ('frame_id', 'arrive_threshold', 'settle_time',
|
||||
'per_goal_timeout', 'stuck_window', 'stuck_displacement',
|
||||
'republish_interval', 'return_home', 'odom_topic', 'goal_topic'):
|
||||
rospy.loginfo(' %s = %r', k, cfg[k])
|
||||
rospy.loginfo(' waypoints (%d):', len(cfg['waypoints']))
|
||||
for i, wp in enumerate(cfg['waypoints'], 1):
|
||||
rospy.loginfo(' %2d: (%.3f, %.3f, %.3f)', i, *wp)
|
||||
|
||||
runner = WaypointRunner(cfg)
|
||||
try:
|
||||
runner.run()
|
||||
except rospy.ROSInterruptException:
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,11 @@
|
||||
## ! DO NOT MANUALLY INVOKE THIS setup.py, USE catkin_make INSTEAD
|
||||
|
||||
from setuptools import setup
|
||||
from catkin_pkg.python_setup import generate_distutils_setup
|
||||
|
||||
setup_args = generate_distutils_setup(
|
||||
packages=['sru_nav_go2'],
|
||||
package_dir={'': 'src'},
|
||||
)
|
||||
|
||||
setup(**setup_args)
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Constants and configuration values for the Go2 + Odin1 SRU navigation port.
|
||||
|
||||
Defaults are tuned conservatively for Unitree Go2 (no wheels, weaker lateral
|
||||
ability) versus the original B2W (wheeled). Override at runtime through the
|
||||
companion YAML / launch parameters.
|
||||
"""
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Control parameters
|
||||
# ---------------------------------------------------------------------------
|
||||
DEFAULT_CONTROL_FREQUENCY = 5.0 # Hz (matches training)
|
||||
DEFAULT_MIN_DEPTH = 0.25 # meters
|
||||
DEFAULT_MAX_DEPTH = 10.0 # meters
|
||||
ARRIVE_GOAL_THRESHOLD = 0.75 # meters
|
||||
NEAR_GOAL_THRESHOLD_MULTIPLIER = 2.0
|
||||
JOYSTICK_TIMEOUT = 15.0 # seconds (safety deadman timeout)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Policy output scaling. Original B2W used [1.5, 1.0, 1.0].
|
||||
# Go2 is conservative until verified safe in real hardware.
|
||||
# ---------------------------------------------------------------------------
|
||||
POLICY_SCALE = [0.6, 0.3, 0.6] # [linear_x, linear_y, angular_z]
|
||||
LATERAL_VELOCITY_SCALE = 0.6 # extra damping on linear_y
|
||||
|
||||
# Low-pass filter coefficients (alpha): output = a*new + (1-a)*prev
|
||||
LOW_PASS_FILTER_COEF = [0.9, 0.5, 0.5]
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Joystick axis / button mappings (PS5-style, same as original)
|
||||
# ---------------------------------------------------------------------------
|
||||
JOYSTICK_AXIS_LINEAR_X = 1
|
||||
JOYSTICK_AXIS_LINEAR_Y = 0
|
||||
JOYSTICK_AXIS_LINEAR_Z = 3
|
||||
JOYSTICK_AXIS_ANGULAR_Z = 2
|
||||
JOYSTICK_AXIS_SMART = 5
|
||||
|
||||
BUTTON_RESET_HIDDEN_STATE = 2
|
||||
BUTTON_RECORD_WAYPOINT = 6
|
||||
BUTTON_CLEAR_WAYPOINT = 4
|
||||
BUTTON_SEND_GOAL = 10
|
||||
BUTTON_ABORT = 9
|
||||
BUTTON_TRIGGER_WAYPOINTS = 1
|
||||
BUTTON_FORWARD = 11
|
||||
BUTTON_BACKWARD = 12
|
||||
BUTTON_LEFT = 13
|
||||
BUTTON_RIGHT = 14
|
||||
BUTTON_UP = 3
|
||||
BUTTON_DOWN = 0
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Scales
|
||||
# ---------------------------------------------------------------------------
|
||||
LINEAR_SCALE = 1.0
|
||||
ANGULAR_SCALE = 1.0
|
||||
MOVING_SCALE = 0.2
|
||||
SMART_JOYSTICK_SCALE = 5.0
|
||||
SMART_JOYSTICK_UPDATE_FREQUENCY = 5.0 # Hz
|
||||
SMART_JOYSTICK_Z_SCALE = 0.25
|
||||
SMART_JOYSTICK_FILTER_ALPHA = 0.2
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Timer intervals
|
||||
# ---------------------------------------------------------------------------
|
||||
WAYPOINT_PUBLISH_INTERVAL = 0.2 # 5 Hz
|
||||
TARGET_VECTOR_PUBLISH_INTERVAL = 0.2 # 5 Hz
|
||||
TRIGGER_BUTTON_COOLDOWN = 1.0 # seconds
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Visualization
|
||||
# ---------------------------------------------------------------------------
|
||||
TWIST_MARKER_SCALE = 5.0
|
||||
TWIST_MARKER_ID = 0
|
||||
TARGET_VECTOR_MARKER_ID = 1
|
||||
MOVING_GOAL_MARKER_ID = 2
|
||||
WAYPOINTS_MARKER_ID = 3
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Physics
|
||||
# ---------------------------------------------------------------------------
|
||||
GRAVITY_MAGNITUDE = 9.81 # m/s^2
|
||||
@@ -0,0 +1,176 @@
|
||||
"""SRU Navigation learning model (ONNX Runtime).
|
||||
|
||||
Identical inference pipeline to the original ROS2 deployment. No ROS deps.
|
||||
"""
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
import onnxruntime as ort
|
||||
|
||||
from sru_nav_go2 import constants
|
||||
from sru_nav_go2.utils import subtract_frame_transforms, transform_points
|
||||
|
||||
|
||||
# Model architecture constants (must match training-time export).
|
||||
STATE_DIM = 16 # linear_vel(3)+angular_vel(3)+gravity(3)+last_action(3)+target_pos_log(4)
|
||||
DEPTH_EMBEDDING_DIM = 2560 # 64 * 5 * 8 (flattened VAE output)
|
||||
POLICY_INPUT_DIM = STATE_DIM + DEPTH_EMBEDDING_DIM # 2576
|
||||
LSTM_HIDDEN_DIM = 512
|
||||
|
||||
|
||||
class LearningModel:
|
||||
"""RL navigation policy + depth VAE encoder (ONNX Runtime).
|
||||
|
||||
VAE encoder:
|
||||
depth_image [1, 1, 40, 64] -> mu [1, 64, 5, 8] -> flat [2560]
|
||||
Policy (LSTM):
|
||||
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
|
||||
"""
|
||||
|
||||
def __init__(self, preprocess_model_path, policy_model_path,
|
||||
policy_scale=None, intra_op_num_threads=4):
|
||||
available_providers = ort.get_available_providers()
|
||||
|
||||
if 'CUDAExecutionProvider' in available_providers:
|
||||
providers = ['CUDAExecutionProvider', 'CPUExecutionProvider']
|
||||
print('\033[92m' + 'Using device: CUDA (ONNX Runtime)' + '\033[0m')
|
||||
elif 'TensorrtExecutionProvider' in available_providers:
|
||||
providers = ['TensorrtExecutionProvider', 'CUDAExecutionProvider',
|
||||
'CPUExecutionProvider']
|
||||
print('\033[92m' + 'Using device: TensorRT (ONNX Runtime)' + '\033[0m')
|
||||
else:
|
||||
providers = ['CPUExecutionProvider']
|
||||
print('\033[93m' + 'Using device: CPU (ONNX Runtime)' + '\033[0m')
|
||||
|
||||
sess_options = ort.SessionOptions()
|
||||
sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
|
||||
sess_options.intra_op_num_threads = int(intra_op_num_threads)
|
||||
|
||||
self.preprocess_session = ort.InferenceSession(
|
||||
preprocess_model_path, sess_options=sess_options, providers=providers
|
||||
)
|
||||
self.policy_session = ort.InferenceSession(
|
||||
policy_model_path, sess_options=sess_options, providers=providers
|
||||
)
|
||||
|
||||
self.preprocess_input_name = self.preprocess_session.get_inputs()[0].name
|
||||
self.preprocess_output_name = self.preprocess_session.get_outputs()[0].name
|
||||
|
||||
self.policy_input_names = {inp.name: inp for inp in self.policy_session.get_inputs()}
|
||||
self.policy_output_names = [out.name for out in self.policy_session.get_outputs()]
|
||||
|
||||
self._h_state = np.zeros((1, 1, LSTM_HIDDEN_DIM), dtype=np.float32)
|
||||
self._c_state = np.zeros((1, 1, LSTM_HIDDEN_DIM), dtype=np.float32)
|
||||
|
||||
if policy_scale is None:
|
||||
policy_scale = constants.POLICY_SCALE
|
||||
self._policy_scale = np.array(policy_scale, dtype=np.float32)
|
||||
|
||||
self.fake_run_once()
|
||||
print('\033[92m' + 'Learning model is ready (ONNX Runtime).' + '\033[0m')
|
||||
|
||||
# -----------------------------------------------------------------
|
||||
# Depth preprocessing
|
||||
# -----------------------------------------------------------------
|
||||
@staticmethod
|
||||
def _resize_bilinear(img, target_size):
|
||||
return cv2.resize(img, (target_size[1], target_size[0]),
|
||||
interpolation=cv2.INTER_LINEAR)
|
||||
|
||||
def depth_preprocess(self, img):
|
||||
"""Encode a depth image (H, W) into a 2560-dim latent."""
|
||||
img_resized = self._resize_bilinear(img, (40, 64))
|
||||
img_tensor = img_resized.astype(np.float32)[np.newaxis, np.newaxis, :, :]
|
||||
vae_output = self.preprocess_session.run(
|
||||
[self.preprocess_output_name],
|
||||
{self.preprocess_input_name: img_tensor},
|
||||
)[0]
|
||||
return vae_output.flatten()
|
||||
|
||||
# -----------------------------------------------------------------
|
||||
# Target encoding
|
||||
# -----------------------------------------------------------------
|
||||
def normalize_target_position(self, target_pos_w, robot_pos_w, robot_orientation_w):
|
||||
target_pos_w = np.array(target_pos_w, dtype=np.float32)[np.newaxis]
|
||||
robot_pos_w = np.array(robot_pos_w, dtype=np.float32)[np.newaxis]
|
||||
robot_orientation_w = np.array(robot_orientation_w, dtype=np.float32)[np.newaxis]
|
||||
|
||||
inv_pos, inv_rot = subtract_frame_transforms(robot_pos_w, robot_orientation_w)
|
||||
target_vec_b = transform_points(target_pos_w, inv_pos, inv_rot)
|
||||
|
||||
dist = np.linalg.norm(target_vec_b, axis=-1, keepdims=True) + 1e-6
|
||||
target_pos = target_vec_b / dist
|
||||
dist_log = np.log(dist + 1.0)
|
||||
|
||||
target_pos = np.concatenate((target_pos, dist_log), axis=-1).reshape(-1)
|
||||
return target_pos, target_vec_b
|
||||
|
||||
# -----------------------------------------------------------------
|
||||
# LSTM state management
|
||||
# -----------------------------------------------------------------
|
||||
def reset_hidden_state(self):
|
||||
self._h_state = np.zeros((1, 1, LSTM_HIDDEN_DIM), dtype=np.float32)
|
||||
self._c_state = np.zeros((1, 1, LSTM_HIDDEN_DIM), dtype=np.float32)
|
||||
|
||||
# -----------------------------------------------------------------
|
||||
# Inference
|
||||
# -----------------------------------------------------------------
|
||||
def predict(self, linear_vel, angular_vel, gravity_vector, last_action,
|
||||
target_pos_w, robot_pos_w, robot_orientation_w, depth_image,
|
||||
is_reset=False):
|
||||
if is_reset:
|
||||
self.reset_hidden_state()
|
||||
|
||||
depth_embedding = self.depth_preprocess(depth_image)
|
||||
|
||||
target_pos_log, target_vec_b = self.normalize_target_position(
|
||||
target_pos_w, robot_pos_w, robot_orientation_w
|
||||
)
|
||||
|
||||
state_input = np.array(
|
||||
list(linear_vel) + list(angular_vel) + list(gravity_vector) +
|
||||
list(last_action) + target_pos_log.tolist(),
|
||||
dtype=np.float32,
|
||||
)
|
||||
|
||||
obs = np.concatenate([state_input, depth_embedding])[np.newaxis].astype(np.float32)
|
||||
|
||||
outputs = self.policy_session.run(
|
||||
None,
|
||||
{
|
||||
'obs': obs,
|
||||
'h_in': self._h_state,
|
||||
'c_in': self._c_state,
|
||||
},
|
||||
)
|
||||
|
||||
raw_action, h_out, c_out = outputs
|
||||
self._h_state = h_out
|
||||
self._c_state = c_out
|
||||
|
||||
cmd_vel = np.tanh(raw_action) * self._policy_scale
|
||||
cmd_vel = cmd_vel.squeeze(0)
|
||||
raw_action = raw_action.squeeze(0)
|
||||
|
||||
return cmd_vel, raw_action, target_vec_b
|
||||
|
||||
def fake_run_once(self):
|
||||
linear_vel = [0.0, 0.0, 0.0]
|
||||
angular_vel = [0.0, 0.0, 0.0]
|
||||
gravity_vector = [0.0, 0.0, -1.0]
|
||||
target_pos_w = [1.0, 0.0, 0.0]
|
||||
robot_pos_w = [0.0, 0.0, 0.0]
|
||||
robot_orientation_w = [1.0, 0.0, 0.0, 0.0]
|
||||
last_action = [0.0, 0.0, 0.0]
|
||||
depth_image = np.random.rand(600, 960).astype(np.float32)
|
||||
|
||||
cmd_vel, _, _ = self.predict(
|
||||
linear_vel, angular_vel, gravity_vector, last_action,
|
||||
target_pos_w, robot_pos_w, robot_orientation_w, depth_image,
|
||||
is_reset=True,
|
||||
)
|
||||
print('Warmup predicted cmd_vel: linear_x={:.4f}, linear_y={:.4f}, '
|
||||
'angular_z={:.4f}'.format(cmd_vel[0], cmd_vel[1], cmd_vel[2]))
|
||||
self.reset_hidden_state()
|
||||
@@ -0,0 +1,682 @@
|
||||
"""ROS1 (rospy) navigation policy node for Unitree Go2 + Odin1.
|
||||
|
||||
Direct port of the original ROS2 NavigationPolicyNode. Behaviour is preserved;
|
||||
only ROS API calls, time helpers, and topic defaults have been changed.
|
||||
"""
|
||||
|
||||
import time
|
||||
|
||||
import cv2 # noqa: F401 (kept for parity; cv2 import inside model.py)
|
||||
import numpy as np
|
||||
import rospy
|
||||
from cv_bridge import CvBridge
|
||||
from geometry_msgs.msg import PoseStamped, Twist
|
||||
from nav_msgs.msg import Odometry
|
||||
from scipy.spatial.transform import Rotation as R
|
||||
from sensor_msgs.msg import Image, Joy
|
||||
from std_msgs.msg import Header
|
||||
from visualization_msgs.msg import Marker
|
||||
|
||||
from sru_nav_go2 import constants
|
||||
from sru_nav_go2.model import LearningModel
|
||||
from sru_nav_go2.utils import transform_points, yaw_quat
|
||||
from sru_nav_go2.visualization import VisualizationManager
|
||||
from sru_nav_go2.waypoint_manager import RospyLogger, WaypointManager
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
def _stamp_to_sec(stamp):
|
||||
"""ROS1 Time -> float seconds."""
|
||||
return stamp.secs + stamp.nsecs * 1e-9
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Node
|
||||
# ---------------------------------------------------------------------------
|
||||
class NavigationPolicyNode(object):
|
||||
"""RL navigation controller node (ROS1)."""
|
||||
|
||||
def __init__(self,
|
||||
preprocess_model_path,
|
||||
policy_model_path,
|
||||
depth_topic,
|
||||
odom_topic,
|
||||
joy_topic,
|
||||
goal_topic,
|
||||
cmd_vel_topic,
|
||||
min_depth=constants.DEFAULT_MIN_DEPTH,
|
||||
max_depth=constants.DEFAULT_MAX_DEPTH,
|
||||
control_frequency=constants.DEFAULT_CONTROL_FREQUENCY,
|
||||
policy_scale=None,
|
||||
use_sim=False,
|
||||
require_joystick=True):
|
||||
# Configuration
|
||||
self.use_sim = use_sim
|
||||
self.require_joystick = bool(require_joystick)
|
||||
self.min_depth = float(min_depth)
|
||||
self.max_depth = float(max_depth)
|
||||
self.control_frequency = float(control_frequency)
|
||||
self.odom_ready = False
|
||||
self.arrive_goal_threshold = constants.ARRIVE_GOAL_THRESHOLD
|
||||
self.last_run_time = 0.0
|
||||
self.system_delay = constants.JOYSTICK_TIMEOUT
|
||||
|
||||
# ----- Publishers ------------------------------------------------
|
||||
self.cmd_vel_publisher = rospy.Publisher(cmd_vel_topic, Twist, queue_size=10)
|
||||
self.base_vel_publisher = rospy.Publisher(
|
||||
'~base_vel', Twist, queue_size=10)
|
||||
self.goal_pose_publisher = rospy.Publisher(goal_topic, PoseStamped, queue_size=1)
|
||||
|
||||
# Visualization
|
||||
self.twist_marker_publisher = rospy.Publisher(
|
||||
'~vis/twist_cmd_marker', Marker, queue_size=10)
|
||||
self.goal_vector_marker_publisher = rospy.Publisher(
|
||||
'~vis/goal_vector_marker', Marker, queue_size=10)
|
||||
self.moving_goal_marker_publisher = rospy.Publisher(
|
||||
'~vis/moving_goal_marker', Marker, queue_size=10)
|
||||
self.recorded_waypoints_marker_pub = rospy.Publisher(
|
||||
'~vis/recorded_waypoints_marker', Marker, queue_size=10)
|
||||
|
||||
# ----- Utilities --------------------------------------------------
|
||||
self.bridge = CvBridge()
|
||||
self.model = LearningModel(
|
||||
preprocess_model_path=preprocess_model_path,
|
||||
policy_model_path=policy_model_path,
|
||||
policy_scale=policy_scale,
|
||||
)
|
||||
self._logger = RospyLogger()
|
||||
self.waypoint_manager = WaypointManager(self._logger)
|
||||
self.visualization_manager = VisualizationManager()
|
||||
|
||||
# ----- Robot state -----------------------------------------------
|
||||
self.map_frame_id = None
|
||||
self.robot_frame_id = None
|
||||
self.robot_odom_time = 0.0
|
||||
self.robot_pos_w = None
|
||||
self.robot_orientation_w = None
|
||||
self.linear_vel_w = None
|
||||
self.angular_vel_w = None
|
||||
self.linear_vel = None
|
||||
self.angular_vel = None
|
||||
self.gravity_vector = None
|
||||
self.depth_image = None
|
||||
|
||||
# ----- Navigation state ------------------------------------------
|
||||
self.target_pos_w = None
|
||||
self.last_target_pos = None
|
||||
self.is_reset_hidden_state = False
|
||||
self.last_action = self._reset_last_action()
|
||||
self.prev_cmd = np.zeros(3)
|
||||
self.is_abort_goal = False
|
||||
|
||||
# ----- Joystick state --------------------------------------------
|
||||
self.joy_linear_x = 0.0
|
||||
self.joy_linear_y = 0.0
|
||||
self.joy_angular_z = 0.0
|
||||
# When require_joystick is False we want the robot to move at full
|
||||
# policy scale even with no /joy publisher (testing / headless runs).
|
||||
# When True (default, safe), ratio stays 0 until joy_callback fires.
|
||||
self.cmd_vel_ratio = 0.0 if self.require_joystick else 1.0
|
||||
self.joy_time = time.time()
|
||||
self.last_trigger_time = time.time()
|
||||
|
||||
# ----- Moving goal state -----------------------------------------
|
||||
self.moving_goal_delta = [0.0, 0.0, 0.0]
|
||||
|
||||
# ----- Smart joystick state --------------------------------------
|
||||
self.smart_joystick_goal = [0.0, 0.0, 0.0]
|
||||
self.prev_smart_joystick_goal = [0.0, 0.0, 0.0]
|
||||
self.smart_joystick_mode_active = False
|
||||
self.smart_joystick_goal_aborted = False
|
||||
self.latest_joystick_axes = [0.0, 0.0, 0.0]
|
||||
|
||||
# ----- Subscribers (created LAST so callbacks fire only after init)
|
||||
self.odom_subscriber = rospy.Subscriber(
|
||||
odom_topic, Odometry, self.odom_callback, queue_size=10)
|
||||
self.depth_subscriber = rospy.Subscriber(
|
||||
depth_topic, Image, self.depth_callback, queue_size=2)
|
||||
self.joy_subscriber = rospy.Subscriber(
|
||||
joy_topic, Joy, self.joy_callback, queue_size=10)
|
||||
self.target_position_subscriber = rospy.Subscriber(
|
||||
goal_topic, PoseStamped, self.target_position_callback, queue_size=1)
|
||||
|
||||
# ----- Timers ----------------------------------------------------
|
||||
rospy.Timer(rospy.Duration(constants.WAYPOINT_PUBLISH_INTERVAL),
|
||||
self._timer_publish_recorded_waypoints)
|
||||
rospy.Timer(rospy.Duration(constants.TARGET_VECTOR_PUBLISH_INTERVAL),
|
||||
self._timer_publish_target_vector)
|
||||
smart_joystick_interval = 1.0 / constants.SMART_JOYSTICK_UPDATE_FREQUENCY
|
||||
rospy.Timer(rospy.Duration(smart_joystick_interval),
|
||||
self._timer_update_smart_joystick_goal)
|
||||
|
||||
rospy.loginfo('\033[92mNavigation policy node is ready.\033[0m')
|
||||
|
||||
# =====================================================================
|
||||
# Callbacks
|
||||
# =====================================================================
|
||||
def odom_callback(self, odom_msg):
|
||||
# 1) odom timestamp
|
||||
self.robot_odom_time = _stamp_to_sec(odom_msg.header.stamp)
|
||||
|
||||
# 2) Frame IDs (once)
|
||||
if self.map_frame_id is None:
|
||||
self.map_frame_id = odom_msg.header.frame_id
|
||||
if self.robot_frame_id is None:
|
||||
self.robot_frame_id = odom_msg.child_frame_id
|
||||
|
||||
# 3) Robot pose
|
||||
self.robot_pos_w = [
|
||||
odom_msg.pose.pose.position.x,
|
||||
odom_msg.pose.pose.position.y,
|
||||
odom_msg.pose.pose.position.z,
|
||||
]
|
||||
self.robot_orientation_w = [
|
||||
odom_msg.pose.pose.orientation.w,
|
||||
odom_msg.pose.pose.orientation.x,
|
||||
odom_msg.pose.pose.orientation.y,
|
||||
odom_msg.pose.pose.orientation.z,
|
||||
]
|
||||
|
||||
# 4) Velocities from odom
|
||||
self.linear_vel_w = [
|
||||
odom_msg.twist.twist.linear.x,
|
||||
odom_msg.twist.twist.linear.y,
|
||||
odom_msg.twist.twist.linear.z,
|
||||
]
|
||||
self.angular_vel_w = [
|
||||
odom_msg.twist.twist.angular.x,
|
||||
odom_msg.twist.twist.angular.y,
|
||||
odom_msg.twist.twist.angular.z,
|
||||
]
|
||||
|
||||
# 5) Convert to base frame (real-hw) or pass-through (sim)
|
||||
if self.use_sim:
|
||||
self.linear_vel = list(self.linear_vel_w)
|
||||
self.angular_vel = list(self.angular_vel_w)
|
||||
else:
|
||||
self.linear_vel = self.convert_vel_frame(
|
||||
self.linear_vel_w, self.robot_orientation_w)
|
||||
self.angular_vel = self.convert_vel_frame(
|
||||
self.angular_vel_w, self.robot_orientation_w)
|
||||
|
||||
# 6) Publish converted base velocity for debug
|
||||
self.publish_base_vel(self.linear_vel, self.angular_vel)
|
||||
|
||||
# 7) Projected gravity in base frame
|
||||
self.gravity_vector = self.projected_gravity_vector(self.robot_orientation_w)
|
||||
|
||||
# 8) Mark odom available
|
||||
if not self.odom_ready:
|
||||
self.odom_ready = True
|
||||
|
||||
def depth_callback(self, depth_msg):
|
||||
if not self.odom_ready:
|
||||
rospy.logwarn_throttle(
|
||||
5.0, '\033[93mOdometry not ready, skipping depth callback.\033[0m')
|
||||
return
|
||||
|
||||
try:
|
||||
depth_array = self.bridge.imgmsg_to_cv2(depth_msg, desired_encoding='passthrough')
|
||||
depth_array = np.nan_to_num(
|
||||
depth_array, nan=0.0, posinf=self.max_depth * 2.0, neginf=0.0)
|
||||
depth_array = depth_array.astype(np.float32, copy=False)
|
||||
depth_array[depth_array > self.max_depth] = 0.0
|
||||
depth_array[depth_array < self.min_depth] = 0.0
|
||||
self.depth_image = depth_array
|
||||
except Exception as e:
|
||||
rospy.logerr('Error converting depth image: {}'.format(e))
|
||||
return
|
||||
|
||||
# Respect control frequency
|
||||
interval = 1.0 / self.control_frequency
|
||||
if (self.robot_odom_time - self.last_run_time) < interval:
|
||||
return
|
||||
self.last_run_time = self.robot_odom_time
|
||||
|
||||
self.generate_cmd_vel()
|
||||
|
||||
def generate_cmd_vel(self):
|
||||
# Visualize moving goal
|
||||
self.visualization_manager.publish_moving_goal_marker(
|
||||
self.moving_goal_delta, self.robot_pos_w, self.robot_orientation_w,
|
||||
self.robot_odom_time, self.map_frame_id, self.moving_goal_marker_publisher,
|
||||
)
|
||||
|
||||
if self.smart_joystick_mode_active:
|
||||
rospy.loginfo_throttle(
|
||||
1.0,
|
||||
'Smart joystick mode active - Goal: [{:.2f}, {:.2f}, {:.2f}]'.format(
|
||||
self.smart_joystick_goal[0], self.smart_joystick_goal[1],
|
||||
self.smart_joystick_goal[2],
|
||||
),
|
||||
)
|
||||
|
||||
is_arrived = self._check_goal_reached(self.target_pos_w, self.robot_pos_w)
|
||||
if is_arrived or self.is_abort_goal:
|
||||
twist = Twist()
|
||||
twist.linear.x = 0.0 + self.joy_linear_x
|
||||
twist.linear.y = 0.0 + self.joy_linear_y
|
||||
twist.angular.z = 0.0 + self.joy_angular_z
|
||||
self.cmd_vel_publisher.publish(twist)
|
||||
|
||||
if self.is_abort_goal:
|
||||
self.waypoint_manager.re_add_aborted_waypoint(self.target_pos_w)
|
||||
|
||||
self.target_pos_w = None
|
||||
self.is_abort_goal = False
|
||||
self.last_action = self._reset_last_action()
|
||||
rospy.loginfo('Target position reset.')
|
||||
|
||||
else:
|
||||
# Joystick deadman timeout (only when joystick is required)
|
||||
if self.require_joystick and \
|
||||
(self.robot_odom_time - self.joy_time > self.system_delay):
|
||||
self.cmd_vel_ratio = 0.0
|
||||
diff = self.robot_odom_time - self.joy_time
|
||||
rospy.logwarn_throttle(
|
||||
2.0,
|
||||
'\033[93mJoystick timeout, stopping the robot. Time diff: {:.4f}s\033[0m'
|
||||
.format(diff),
|
||||
)
|
||||
|
||||
rospy.loginfo_throttle(
|
||||
1.0,
|
||||
'cmd_vel_ratio: {:.4f} (require_joystick={})'.format(
|
||||
self.cmd_vel_ratio, self.require_joystick))
|
||||
|
||||
cmd, action, _target_vec_b = self.model.predict(
|
||||
self.linear_vel, self.angular_vel, self.gravity_vector,
|
||||
self.last_action, self.target_pos_w, self.robot_pos_w,
|
||||
self.robot_orientation_w, self.depth_image,
|
||||
self.is_reset_hidden_state,
|
||||
)
|
||||
|
||||
if self.is_reset_hidden_state:
|
||||
rospy.logwarn('\033[93mResetting hidden state.\033[0m')
|
||||
self.is_reset_hidden_state = False
|
||||
self.last_action = self._reset_last_action()
|
||||
|
||||
self.last_action = action.tolist()
|
||||
|
||||
twist = Twist()
|
||||
model_cmd = np.array([
|
||||
cmd[0].item() * self.cmd_vel_ratio,
|
||||
cmd[1].item() * self.cmd_vel_ratio * constants.LATERAL_VELOCITY_SCALE,
|
||||
cmd[2].item() * self.cmd_vel_ratio,
|
||||
])
|
||||
filter_coef = np.array(constants.LOW_PASS_FILTER_COEF)
|
||||
filt_model = filter_coef * model_cmd + (1 - filter_coef) * self.prev_cmd
|
||||
twist.linear.x = float(filt_model[0]) + self.joy_linear_x
|
||||
twist.linear.y = float(filt_model[1]) + self.joy_linear_y
|
||||
twist.angular.z = float(filt_model[2]) + self.joy_angular_z
|
||||
self.prev_cmd = filt_model
|
||||
self.cmd_vel_publisher.publish(twist)
|
||||
|
||||
self.visualization_manager.publish_twist_marker(
|
||||
twist, self.robot_odom_time, self.robot_frame_id,
|
||||
self.twist_marker_publisher,
|
||||
)
|
||||
|
||||
rospy.loginfo_throttle(
|
||||
1.0,
|
||||
'Published cmd_vel: linear_x={:.4f}, linear_y={:.4f}, angular_z={:.4f}'.format(
|
||||
twist.linear.x, twist.linear.y, twist.angular.z
|
||||
),
|
||||
)
|
||||
self._reset_joystick()
|
||||
|
||||
# =====================================================================
|
||||
# Velocity / orientation helpers
|
||||
# =====================================================================
|
||||
def publish_base_vel(self, linear_vel, angular_vel):
|
||||
twist = Twist()
|
||||
twist.linear.x = linear_vel[0]
|
||||
twist.linear.y = linear_vel[1]
|
||||
twist.angular.z = angular_vel[2]
|
||||
self.base_vel_publisher.publish(twist)
|
||||
|
||||
@staticmethod
|
||||
def convert_vel_frame(vel_vec, orientation_w):
|
||||
# quaternion is (w, x, y, z); scipy expects (x, y, z, w)
|
||||
quat_xyzw = [orientation_w[1], orientation_w[2], orientation_w[3], orientation_w[0]]
|
||||
rotation = R.from_quat(quat_xyzw)
|
||||
inv_rot = rotation.inv()
|
||||
return inv_rot.apply(np.array(vel_vec)).tolist()
|
||||
|
||||
@staticmethod
|
||||
def projected_gravity_vector(robot_orientation_w):
|
||||
quat_xyzw = [robot_orientation_w[1], robot_orientation_w[2],
|
||||
robot_orientation_w[3], robot_orientation_w[0]]
|
||||
rotation = R.from_quat(quat_xyzw)
|
||||
inv_rot = rotation.inv()
|
||||
gravity = np.array([0.0, 0.0, -constants.GRAVITY_MAGNITUDE])
|
||||
proj = inv_rot.apply(gravity)
|
||||
proj = proj / (np.linalg.norm(proj) + 1e-6)
|
||||
return proj.tolist()
|
||||
|
||||
# =====================================================================
|
||||
# Joystick handling
|
||||
# =====================================================================
|
||||
def joy_callback(self, joy_msg):
|
||||
if len(joy_msg.axes) <= max(
|
||||
constants.JOYSTICK_AXIS_LINEAR_X,
|
||||
constants.JOYSTICK_AXIS_LINEAR_Y,
|
||||
constants.JOYSTICK_AXIS_LINEAR_Z,
|
||||
constants.JOYSTICK_AXIS_ANGULAR_Z,
|
||||
constants.JOYSTICK_AXIS_SMART,
|
||||
4):
|
||||
rospy.logwarn_throttle(5.0, 'Joy message has too few axes; ignoring.')
|
||||
return
|
||||
|
||||
self.cmd_vel_ratio = (1.0 + joy_msg.axes[4]) * 1.0
|
||||
|
||||
if (len(joy_msg.buttons) > constants.BUTTON_ABORT and
|
||||
joy_msg.buttons[constants.BUTTON_ABORT] == 1):
|
||||
self.is_abort_goal = True
|
||||
rospy.logwarn('Abort goal')
|
||||
|
||||
dx, dy, dz = self._moving_xyz_with_buttons(joy_msg, scale=constants.MOVING_SCALE)
|
||||
self.moving_goal_delta[0] += dx
|
||||
self.moving_goal_delta[1] += dy
|
||||
self.moving_goal_delta[2] += dz
|
||||
|
||||
current_time = time.time()
|
||||
cooldown = constants.TRIGGER_BUTTON_COOLDOWN
|
||||
|
||||
if (not self.is_abort_goal
|
||||
and (current_time - self.last_trigger_time) > cooldown
|
||||
and len(joy_msg.buttons) > constants.BUTTON_SEND_GOAL
|
||||
and joy_msg.buttons[constants.BUTTON_SEND_GOAL] == 1):
|
||||
rospy.logwarn('Trigger moving goal')
|
||||
self._publish_moving_goal()
|
||||
self.last_trigger_time = current_time
|
||||
|
||||
if ((current_time - self.last_trigger_time) > cooldown
|
||||
and len(joy_msg.buttons) > constants.BUTTON_RECORD_WAYPOINT
|
||||
and joy_msg.buttons[constants.BUTTON_RECORD_WAYPOINT] == 1):
|
||||
self.waypoint_manager.record_waypoint(self.robot_pos_w)
|
||||
self.last_trigger_time = current_time
|
||||
|
||||
if ((current_time - self.last_trigger_time) > cooldown
|
||||
and len(joy_msg.buttons) > constants.BUTTON_CLEAR_WAYPOINT
|
||||
and joy_msg.buttons[constants.BUTTON_CLEAR_WAYPOINT] == 1):
|
||||
self.waypoint_manager.remove_last_waypoint()
|
||||
self.last_trigger_time = current_time
|
||||
|
||||
if (not self.is_abort_goal
|
||||
and (current_time - self.last_trigger_time) > cooldown
|
||||
and len(joy_msg.buttons) > constants.BUTTON_TRIGGER_WAYPOINTS
|
||||
and joy_msg.buttons[constants.BUTTON_TRIGGER_WAYPOINTS] == 1):
|
||||
rospy.logwarn('Trigger waypoints')
|
||||
if self.waypoint_manager.has_home_waypoints():
|
||||
self.waypoint_manager.start_home_waypoint_sequence()
|
||||
elif self.waypoint_manager.has_inversed_waypoints():
|
||||
self.waypoint_manager.start_inversed_waypoint_sequence()
|
||||
self.last_trigger_time = current_time
|
||||
|
||||
if joy_msg.axes[constants.JOYSTICK_AXIS_SMART] < -0.5:
|
||||
if not self.smart_joystick_mode_active:
|
||||
self.smart_joystick_mode_active = True
|
||||
self.smart_joystick_goal_aborted = False
|
||||
|
||||
if not self.smart_joystick_goal_aborted and self.target_pos_w is not None:
|
||||
self.is_abort_goal = True
|
||||
self.smart_joystick_goal_aborted = True
|
||||
rospy.loginfo('Smart joystick mode: aborting current navigation goal')
|
||||
|
||||
self.latest_joystick_axes = [
|
||||
joy_msg.axes[constants.JOYSTICK_AXIS_LINEAR_X],
|
||||
joy_msg.axes[constants.JOYSTICK_AXIS_LINEAR_Y],
|
||||
joy_msg.axes[constants.JOYSTICK_AXIS_LINEAR_Z],
|
||||
]
|
||||
else:
|
||||
if self.smart_joystick_mode_active:
|
||||
self.smart_joystick_mode_active = False
|
||||
self.is_abort_goal = True
|
||||
rospy.loginfo('Exiting smart joystick mode: aborting current navigation goal')
|
||||
|
||||
self._reset_smart_joystick_goal()
|
||||
self.joy_linear_x = (
|
||||
joy_msg.axes[constants.JOYSTICK_AXIS_LINEAR_X]
|
||||
* constants.LINEAR_SCALE * 1.5)
|
||||
self.joy_linear_y = (
|
||||
joy_msg.axes[constants.JOYSTICK_AXIS_LINEAR_Y]
|
||||
* constants.LINEAR_SCALE)
|
||||
self.joy_angular_z = (
|
||||
joy_msg.axes[constants.JOYSTICK_AXIS_ANGULAR_Z]
|
||||
* constants.ANGULAR_SCALE)
|
||||
|
||||
if (len(joy_msg.buttons) > constants.BUTTON_RESET_HIDDEN_STATE and
|
||||
joy_msg.buttons[constants.BUTTON_RESET_HIDDEN_STATE] == 1):
|
||||
self.is_reset_hidden_state = True
|
||||
rospy.logwarn('Force Reset hidden state')
|
||||
|
||||
self.joy_time = time.time()
|
||||
|
||||
def _generate_waypoint_using_joystick(self, linear_x, linear_y, linear_z):
|
||||
if self.robot_pos_w is None or self.robot_orientation_w is None:
|
||||
return
|
||||
|
||||
goal_offset_robot = np.array([
|
||||
linear_x * constants.SMART_JOYSTICK_SCALE,
|
||||
linear_y * constants.SMART_JOYSTICK_SCALE,
|
||||
linear_z * constants.SMART_JOYSTICK_SCALE * constants.SMART_JOYSTICK_Z_SCALE,
|
||||
], dtype=np.float32)
|
||||
|
||||
robot_ori = np.array(self.robot_orientation_w, dtype=np.float32)
|
||||
robot_yaw_ori = yaw_quat(robot_ori)
|
||||
|
||||
goal_offset_world = transform_points(
|
||||
goal_offset_robot[np.newaxis],
|
||||
np.zeros(3, dtype=np.float32)[np.newaxis],
|
||||
robot_yaw_ori[np.newaxis],
|
||||
)[0]
|
||||
|
||||
target_goal_world = [
|
||||
self.robot_pos_w[0] + goal_offset_world[0].item(),
|
||||
self.robot_pos_w[1] + goal_offset_world[1].item(),
|
||||
self.robot_pos_w[2] + goal_offset_world[2].item(),
|
||||
]
|
||||
|
||||
if self.prev_smart_joystick_goal == [0.0, 0.0, 0.0]:
|
||||
self.smart_joystick_goal = target_goal_world
|
||||
else:
|
||||
alpha = constants.SMART_JOYSTICK_FILTER_ALPHA
|
||||
self.smart_joystick_goal = [
|
||||
alpha * target_goal_world[0] + (1 - alpha) * self.prev_smart_joystick_goal[0],
|
||||
alpha * target_goal_world[1] + (1 - alpha) * self.prev_smart_joystick_goal[1],
|
||||
alpha * target_goal_world[2] + (1 - alpha) * self.prev_smart_joystick_goal[2],
|
||||
]
|
||||
self.prev_smart_joystick_goal = list(self.smart_joystick_goal)
|
||||
|
||||
def _publish_smart_joystick_goal(self):
|
||||
if self.robot_pos_w is None or self.robot_orientation_w is None:
|
||||
rospy.logwarn_throttle(
|
||||
5.0, 'Cannot publish smart joystick goal: robot pose not available')
|
||||
return
|
||||
self._publish_goal(self.smart_joystick_goal)
|
||||
|
||||
def _reset_smart_joystick_goal(self):
|
||||
self.smart_joystick_goal = [0.0, 0.0, 0.0]
|
||||
self.prev_smart_joystick_goal = [0.0, 0.0, 0.0]
|
||||
|
||||
@staticmethod
|
||||
def _moving_xyz_with_buttons(joy_msg, scale=1.0):
|
||||
def b(idx):
|
||||
return bool(joy_msg.buttons[idx]) if idx < len(joy_msg.buttons) else False
|
||||
|
||||
dx = scale * (b(constants.BUTTON_FORWARD) - b(constants.BUTTON_BACKWARD))
|
||||
dy = scale * (b(constants.BUTTON_LEFT) - b(constants.BUTTON_RIGHT))
|
||||
dz = (scale / 5.0) * (b(constants.BUTTON_UP) - b(constants.BUTTON_DOWN))
|
||||
return dx, dy, dz
|
||||
|
||||
# =====================================================================
|
||||
# Goal publishing
|
||||
# =====================================================================
|
||||
def _publish_goal(self, goal_pos):
|
||||
goal_pose = PoseStamped()
|
||||
goal_pose.header = Header()
|
||||
goal_pose.header.stamp = rospy.Time.from_sec(self.robot_odom_time)
|
||||
goal_pose.header.frame_id = self.map_frame_id if self.map_frame_id else 'odom'
|
||||
goal_pose.pose.position.x = float(goal_pos[0])
|
||||
goal_pose.pose.position.y = float(goal_pos[1])
|
||||
goal_pose.pose.position.z = float(goal_pos[2])
|
||||
goal_pose.pose.orientation.w = 1.0
|
||||
self.goal_pose_publisher.publish(goal_pose)
|
||||
|
||||
def _publish_moving_goal(self):
|
||||
if self.robot_pos_w is None or self.robot_orientation_w is None:
|
||||
rospy.logwarn('Cannot publish moving goal: robot pose/orientation not yet set.')
|
||||
return
|
||||
|
||||
robot_pos = np.array(self.robot_pos_w, dtype=np.float32)
|
||||
robot_ori = np.array(self.robot_orientation_w, dtype=np.float32)
|
||||
robot_yaw_ori = yaw_quat(robot_ori)
|
||||
|
||||
moving_goal_pos = np.array(self.moving_goal_delta, dtype=np.float32)
|
||||
moving_goal_pos_w = transform_points(
|
||||
moving_goal_pos[np.newaxis],
|
||||
robot_pos[np.newaxis],
|
||||
robot_yaw_ori[np.newaxis],
|
||||
)
|
||||
|
||||
self._publish_goal(moving_goal_pos_w[0].tolist())
|
||||
self._reset_moving_goal()
|
||||
|
||||
# =====================================================================
|
||||
# Timer callbacks
|
||||
# =====================================================================
|
||||
def _timer_publish_recorded_waypoints(self, _event):
|
||||
self.publish_recorded_waypoints()
|
||||
|
||||
def _timer_publish_target_vector(self, _event):
|
||||
self.publish_target_vector()
|
||||
|
||||
def _timer_update_smart_joystick_goal(self, _event):
|
||||
self.update_smart_joystick_goal()
|
||||
|
||||
def publish_recorded_waypoints(self):
|
||||
if self.robot_pos_w is None:
|
||||
return
|
||||
|
||||
self.visualization_manager.publish_waypoints_marker(
|
||||
self.waypoint_manager.waypoints_visualization,
|
||||
self.map_frame_id,
|
||||
self.recorded_waypoints_marker_pub,
|
||||
)
|
||||
|
||||
if (self.waypoint_manager.is_home_sequence_active()
|
||||
and self.waypoint_manager.has_home_waypoints()):
|
||||
if (self.target_pos_w is None
|
||||
or self._check_near_goal(self.target_pos_w, self.robot_pos_w)):
|
||||
next_wp = self.waypoint_manager.get_next_waypoint_home()
|
||||
rospy.loginfo('Publishing next waypoint: {}'.format(next_wp))
|
||||
self._publish_goal(next_wp)
|
||||
else:
|
||||
rospy.loginfo_throttle(1.0, 'Tracking the current waypoint ...')
|
||||
|
||||
if not self.waypoint_manager.has_home_waypoints():
|
||||
self.waypoint_manager.stop_home_waypoint_sequence()
|
||||
|
||||
if (self.waypoint_manager.is_inversed_sequence_active()
|
||||
and self.waypoint_manager.has_inversed_waypoints()):
|
||||
if (self.target_pos_w is None
|
||||
or self._check_near_goal(self.target_pos_w, self.robot_pos_w)):
|
||||
next_wp = self.waypoint_manager.get_next_waypoint_inversed()
|
||||
rospy.loginfo('Publishing next inversed waypoint: {}'.format(next_wp))
|
||||
self._publish_goal(next_wp)
|
||||
else:
|
||||
rospy.loginfo_throttle(1.0, 'Tracking the current waypoint ...')
|
||||
|
||||
if not self.waypoint_manager.has_inversed_waypoints():
|
||||
self.waypoint_manager.stop_inversed_waypoint_sequence()
|
||||
|
||||
self.waypoint_manager.reset_visualization_if_complete()
|
||||
|
||||
def publish_target_vector(self):
|
||||
if self.robot_pos_w is None or self.robot_orientation_w is None:
|
||||
return
|
||||
tgt = self.target_pos_w if self.target_pos_w is not None else self.last_target_pos
|
||||
if tgt is None:
|
||||
return
|
||||
|
||||
_, target_vec_b = self.model.normalize_target_position(
|
||||
tgt, self.robot_pos_w, self.robot_orientation_w
|
||||
)
|
||||
|
||||
self.visualization_manager.publish_target_vector_marker(
|
||||
target_vec_b, self.robot_odom_time, self.robot_frame_id,
|
||||
self.goal_vector_marker_publisher,
|
||||
)
|
||||
|
||||
def update_smart_joystick_goal(self):
|
||||
if not self.smart_joystick_mode_active:
|
||||
return
|
||||
self._generate_waypoint_using_joystick(
|
||||
self.latest_joystick_axes[0],
|
||||
self.latest_joystick_axes[1],
|
||||
self.latest_joystick_axes[2],
|
||||
)
|
||||
self._publish_smart_joystick_goal()
|
||||
|
||||
# =====================================================================
|
||||
# Goal callbacks & checks
|
||||
# =====================================================================
|
||||
def _check_near_goal(self, target_pos_w, robot_pos_w):
|
||||
if target_pos_w is None or robot_pos_w is None:
|
||||
return True
|
||||
dist = np.linalg.norm(np.array(target_pos_w[:2]) - np.array(robot_pos_w[:2]))
|
||||
threshold = self.arrive_goal_threshold * constants.NEAR_GOAL_THRESHOLD_MULTIPLIER
|
||||
if dist > threshold:
|
||||
return False
|
||||
rospy.loginfo('Near the current goal position.')
|
||||
return True
|
||||
|
||||
def _check_goal_reached(self, target_pos_w, robot_pos_w):
|
||||
if target_pos_w is None or robot_pos_w is None:
|
||||
return True
|
||||
dist = np.linalg.norm(np.array(target_pos_w[:2]) - np.array(robot_pos_w[:2]))
|
||||
if dist > self.arrive_goal_threshold:
|
||||
return False
|
||||
rospy.loginfo('Arrived at the goal position.')
|
||||
return True
|
||||
|
||||
def target_position_callback(self, msg):
|
||||
# If the goal arrives before odom, skip frame check.
|
||||
if self.map_frame_id is not None and msg.header.frame_id and \
|
||||
msg.header.frame_id != self.map_frame_id:
|
||||
rospy.logerr(
|
||||
'\033[91mTarget frame_id "{}" does not match odometry frame_id "{}"\033[0m'
|
||||
.format(msg.header.frame_id, self.map_frame_id)
|
||||
)
|
||||
return
|
||||
|
||||
goal_z = msg.pose.position.z
|
||||
if abs(goal_z) < 1e-3:
|
||||
if self.robot_pos_w is not None:
|
||||
goal_z = self.robot_pos_w[2]
|
||||
else:
|
||||
rospy.logwarn('Robot position not available, using received z for target.')
|
||||
|
||||
self.target_pos_w = [msg.pose.position.x, msg.pose.position.y, goal_z]
|
||||
self.last_target_pos = list(self.target_pos_w)
|
||||
|
||||
rospy.loginfo('Received target position: {}'.format(self.target_pos_w))
|
||||
|
||||
# =====================================================================
|
||||
# Misc reset helpers
|
||||
# =====================================================================
|
||||
def _reset_last_action(self):
|
||||
self.prev_cmd = np.zeros(3)
|
||||
return [0.0, 0.0, 0.0]
|
||||
|
||||
def _reset_joystick(self):
|
||||
self.joy_linear_x = 0.0
|
||||
self.joy_linear_y = 0.0
|
||||
self.joy_angular_z = 0.0
|
||||
|
||||
def _reset_moving_goal(self):
|
||||
self.moving_goal_delta = [0.0, 0.0, 0.0]
|
||||
rospy.loginfo('Reset moving goal delta.')
|
||||
@@ -0,0 +1,252 @@
|
||||
"""Quaternion and transformation utilities using NumPy (no PyTorch dependency)."""
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
def normalize(x: np.ndarray, eps: float = 1e-9) -> np.ndarray:
|
||||
"""Normalizes a given input array to unit length.
|
||||
|
||||
Args:
|
||||
x: Input array of shape (N, dims) or (dims,).
|
||||
eps: A small value to avoid division by zero. Defaults to 1e-9.
|
||||
|
||||
Returns:
|
||||
Normalized array of same shape as input.
|
||||
"""
|
||||
if x.ndim == 1:
|
||||
norm = np.linalg.norm(x)
|
||||
return x / max(norm, eps)
|
||||
else:
|
||||
norm = np.linalg.norm(x, axis=-1, keepdims=True)
|
||||
return x / np.clip(norm, eps, None)
|
||||
|
||||
|
||||
def yaw_quat(quat: np.ndarray) -> np.ndarray:
|
||||
"""Extract the yaw component of a quaternion.
|
||||
|
||||
Args:
|
||||
quat: The orientation in (w, x, y, z). Shape is (..., 4)
|
||||
|
||||
Returns:
|
||||
A quaternion with only yaw component.
|
||||
"""
|
||||
shape = quat.shape
|
||||
quat_yaw = quat.copy().reshape(-1, 4)
|
||||
qw = quat_yaw[:, 0]
|
||||
qx = quat_yaw[:, 1]
|
||||
qy = quat_yaw[:, 2]
|
||||
qz = quat_yaw[:, 3]
|
||||
yaw = np.arctan2(2 * (qw * qz + qx * qy), 1 - 2 * (qy * qy + qz * qz))
|
||||
quat_yaw[:] = 0.0
|
||||
quat_yaw[:, 3] = np.sin(yaw / 2)
|
||||
quat_yaw[:, 0] = np.cos(yaw / 2)
|
||||
quat_yaw = normalize(quat_yaw)
|
||||
return quat_yaw.reshape(shape)
|
||||
|
||||
|
||||
def quat_conjugate(q: np.ndarray) -> np.ndarray:
|
||||
"""Computes the conjugate of a quaternion.
|
||||
|
||||
Args:
|
||||
q: The quaternion orientation in (w, x, y, z). Shape is (..., 4).
|
||||
|
||||
Returns:
|
||||
The conjugate quaternion in (w, x, y, z). Shape is (..., 4).
|
||||
"""
|
||||
shape = q.shape
|
||||
q = q.reshape(-1, 4)
|
||||
return np.concatenate((q[:, 0:1], -q[:, 1:]), axis=-1).reshape(shape)
|
||||
|
||||
|
||||
def quat_inv(q: np.ndarray) -> np.ndarray:
|
||||
"""Compute the inverse of a quaternion.
|
||||
|
||||
Args:
|
||||
q: The quaternion orientation in (w, x, y, z). Shape is (N, 4).
|
||||
|
||||
Returns:
|
||||
The inverse quaternion in (w, x, y, z). Shape is (N, 4).
|
||||
"""
|
||||
return normalize(quat_conjugate(q))
|
||||
|
||||
|
||||
def quat_mul(q1: np.ndarray, q2: np.ndarray) -> np.ndarray:
|
||||
"""Multiply two quaternions together.
|
||||
|
||||
Args:
|
||||
q1: The first quaternion in (w, x, y, z). Shape is (..., 4).
|
||||
q2: The second quaternion in (w, x, y, z). Shape is (..., 4).
|
||||
|
||||
Returns:
|
||||
The product of the two quaternions in (w, x, y, z). Shape is (..., 4).
|
||||
|
||||
Raises:
|
||||
ValueError: Input shapes of ``q1`` and ``q2`` are not matching.
|
||||
"""
|
||||
if q1.shape != q2.shape:
|
||||
msg = f"Expected input quaternion shape mismatch: {q1.shape} != {q2.shape}."
|
||||
raise ValueError(msg)
|
||||
|
||||
shape = q1.shape
|
||||
q1 = q1.reshape(-1, 4)
|
||||
q2 = q2.reshape(-1, 4)
|
||||
|
||||
w1, x1, y1, z1 = q1[:, 0], q1[:, 1], q1[:, 2], q1[:, 3]
|
||||
w2, x2, y2, z2 = q2[:, 0], q2[:, 1], q2[:, 2], q2[:, 3]
|
||||
|
||||
ww = (z1 + x1) * (x2 + y2)
|
||||
yy = (w1 - y1) * (w2 + z2)
|
||||
zz = (w1 + y1) * (w2 - z2)
|
||||
xx = ww + yy + zz
|
||||
qq = 0.5 * (xx + (z1 - x1) * (x2 - y2))
|
||||
w = qq - ww + (z1 - y1) * (y2 - z2)
|
||||
x = qq - xx + (x1 + w1) * (x2 + w2)
|
||||
y = qq - yy + (w1 - x1) * (y2 + z2)
|
||||
z = qq - zz + (z1 + y1) * (w2 - x2)
|
||||
|
||||
return np.stack([w, x, y, z], axis=-1).reshape(shape)
|
||||
|
||||
|
||||
def quat_apply(quat: np.ndarray, vec: np.ndarray) -> np.ndarray:
|
||||
"""Apply a quaternion rotation to a vector.
|
||||
|
||||
Args:
|
||||
quat: The quaternion in (w, x, y, z). Shape is (..., 4).
|
||||
vec: The vector in (x, y, z). Shape is (..., 3).
|
||||
|
||||
Returns:
|
||||
The rotated vector in (x, y, z). Shape is (..., 3).
|
||||
"""
|
||||
shape = vec.shape
|
||||
quat = quat.reshape(-1, 4)
|
||||
vec = vec.reshape(-1, 3)
|
||||
|
||||
xyz = quat[:, 1:]
|
||||
t = np.cross(xyz, vec) * 2
|
||||
return (vec + quat[:, 0:1] * t + np.cross(xyz, t)).reshape(shape)
|
||||
|
||||
|
||||
def matrix_from_quat(quaternions: np.ndarray) -> np.ndarray:
|
||||
"""Convert rotations given as quaternions to rotation matrices.
|
||||
|
||||
Args:
|
||||
quaternions: The quaternion orientation in (w, x, y, z). Shape is (..., 4).
|
||||
|
||||
Returns:
|
||||
Rotation matrices. The shape is (..., 3, 3).
|
||||
"""
|
||||
r, i, j, k = quaternions[..., 0], quaternions[..., 1], quaternions[..., 2], quaternions[..., 3]
|
||||
two_s = 2.0 / (quaternions * quaternions).sum(-1)
|
||||
|
||||
o = np.stack(
|
||||
(
|
||||
1 - two_s * (j * j + k * k),
|
||||
two_s * (i * j - k * r),
|
||||
two_s * (i * k + j * r),
|
||||
two_s * (i * j + k * r),
|
||||
1 - two_s * (i * i + k * k),
|
||||
two_s * (j * k - i * r),
|
||||
two_s * (i * k - j * r),
|
||||
two_s * (j * k + i * r),
|
||||
1 - two_s * (i * i + j * j),
|
||||
),
|
||||
axis=-1,
|
||||
)
|
||||
return o.reshape(quaternions.shape[:-1] + (3, 3))
|
||||
|
||||
|
||||
def subtract_frame_transforms(
|
||||
t01: np.ndarray, q01: np.ndarray, t02: np.ndarray = None, q02: np.ndarray = None
|
||||
) -> tuple:
|
||||
r"""Subtract transformations between two reference frames into a stationary frame.
|
||||
|
||||
It performs the following transformation operation: :math:`T_{12} = T_{01}^{-1} \times T_{02}`,
|
||||
where :math:`T_{AB}` is the homogeneous transformation matrix from frame A to B.
|
||||
|
||||
Args:
|
||||
t01: Position of frame 1 w.r.t. frame 0. Shape is (N, 3).
|
||||
q01: Quaternion orientation of frame 1 w.r.t. frame 0 in (w, x, y, z). Shape is (N, 4).
|
||||
t02: Position of frame 2 w.r.t. frame 0. Shape is (N, 3).
|
||||
Defaults to None, in which case the position is assumed to be zero.
|
||||
q02: Quaternion orientation of frame 2 w.r.t. frame 0 in (w, x, y, z). Shape is (N, 4).
|
||||
Defaults to None, in which case the orientation is assumed to be identity.
|
||||
|
||||
Returns:
|
||||
A tuple containing the position and orientation of frame 2 w.r.t. frame 1.
|
||||
Shape of the arrays are (N, 3) and (N, 4) respectively.
|
||||
"""
|
||||
q10 = quat_inv(q01)
|
||||
if q02 is not None:
|
||||
q12 = quat_mul(q10, q02)
|
||||
else:
|
||||
q12 = q10
|
||||
|
||||
if t02 is not None:
|
||||
t12 = quat_apply(q10, t02 - t01)
|
||||
else:
|
||||
t12 = quat_apply(q10, -t01)
|
||||
return t12, q12
|
||||
|
||||
|
||||
def transform_points(
|
||||
points: np.ndarray, pos: np.ndarray = None, quat: np.ndarray = None
|
||||
) -> np.ndarray:
|
||||
r"""Transform input points in a given frame to a target frame.
|
||||
|
||||
This function transform points from a source frame to a target frame. The transformation is defined by the
|
||||
position :math:`t` and orientation :math:`R` of the target frame in the source frame.
|
||||
|
||||
.. math::
|
||||
p_{target} = R_{target} \times p_{source} + t_{target}
|
||||
|
||||
Args:
|
||||
points: Points to transform. Shape is (N, P, 3) or (P, 3).
|
||||
pos: Position of the target frame. Shape is (N, 3) or (3,).
|
||||
Defaults to None, in which case the position is assumed to be zero.
|
||||
quat: Quaternion orientation of the target frame in (w, x, y, z). Shape is (N, 4) or (4,).
|
||||
Defaults to None, in which case the orientation is assumed to be identity.
|
||||
|
||||
Returns:
|
||||
Transformed points in the target frame. Shape is (N, P, 3) or (P, 3).
|
||||
|
||||
Raises:
|
||||
ValueError: If the inputs `points` is not of shape (N, P, 3) or (P, 3).
|
||||
ValueError: If the inputs `pos` is not of shape (N, 3) or (3,).
|
||||
ValueError: If the inputs `quat` is not of shape (N, 4) or (4,).
|
||||
"""
|
||||
points_batch = points.copy()
|
||||
is_batched = points_batch.ndim == 3
|
||||
|
||||
if points_batch.ndim == 2:
|
||||
points_batch = points_batch[np.newaxis] # (P, 3) -> (1, P, 3)
|
||||
if points_batch.ndim != 3:
|
||||
raise ValueError(f"Expected points to have dim = 2 or dim = 3: got shape {points.shape}")
|
||||
if not (pos is None or pos.ndim == 1 or pos.ndim == 2):
|
||||
raise ValueError(f"Expected pos to have dim = 1 or dim = 2: got shape {pos.shape}")
|
||||
if not (quat is None or quat.ndim == 1 or quat.ndim == 2):
|
||||
raise ValueError(f"Expected quat to have dim = 1 or dim = 2: got shape {quat.shape}")
|
||||
|
||||
# -- rotation
|
||||
if quat is not None:
|
||||
rot_mat = matrix_from_quat(quat)
|
||||
if rot_mat.ndim == 2:
|
||||
rot_mat = rot_mat[np.newaxis] # (3, 3) -> (1, 3, 3)
|
||||
# (N, P, 3) -> (N, 3, P)
|
||||
points_batch = np.transpose(points_batch, (0, 2, 1))
|
||||
# Apply rotation: (N, 3, 3) @ (N, 3, P) -> (N, 3, P)
|
||||
points_batch = np.matmul(rot_mat, points_batch)
|
||||
# (N, 3, P) -> (N, P, 3)
|
||||
points_batch = np.transpose(points_batch, (0, 2, 1))
|
||||
|
||||
# -- translation
|
||||
if pos is not None:
|
||||
if pos.ndim == 1:
|
||||
pos = pos[np.newaxis, np.newaxis, :] # (3,) -> (1, 1, 3)
|
||||
else:
|
||||
pos = pos[:, np.newaxis, :] # (N, 3) -> (N, 1, 3)
|
||||
points_batch = points_batch + pos
|
||||
|
||||
if not is_batched:
|
||||
points_batch = points_batch.squeeze(0) # (1, P, 3) -> (P, 3)
|
||||
|
||||
return points_batch
|
||||
@@ -0,0 +1,157 @@
|
||||
"""Visualization utilities for the SRU navigation controller (ROS1 port)."""
|
||||
|
||||
import numpy as np
|
||||
import rospy
|
||||
from geometry_msgs.msg import Point, Quaternion, Vector3
|
||||
from std_msgs.msg import Header
|
||||
from visualization_msgs.msg import Marker
|
||||
|
||||
from sru_nav_go2 import constants
|
||||
from sru_nav_go2.utils import transform_points, yaw_quat
|
||||
|
||||
|
||||
def _stamp_from_sec(sec):
|
||||
"""Build a rospy.Time stamp from a float seconds value."""
|
||||
return rospy.Time.from_sec(float(sec))
|
||||
|
||||
|
||||
class VisualizationManager:
|
||||
"""Manages visualization markers for the navigation controller."""
|
||||
|
||||
def __init__(self, node=None):
|
||||
# `node` retained for API parity with the original class. Not used in ROS1.
|
||||
self.node = node
|
||||
|
||||
def publish_twist_marker(self, twist_msg, robot_odom_time, robot_frame_id, publisher):
|
||||
if robot_frame_id is None:
|
||||
return
|
||||
|
||||
marker = Marker()
|
||||
marker.header = Header()
|
||||
marker.header.stamp = _stamp_from_sec(robot_odom_time)
|
||||
marker.header.frame_id = robot_frame_id
|
||||
|
||||
marker.type = Marker.ARROW
|
||||
marker.action = Marker.ADD
|
||||
marker.id = constants.TWIST_MARKER_ID
|
||||
|
||||
start_point = Point(x=0.0, y=0.0, z=0.0)
|
||||
end_point = Point(
|
||||
x=twist_msg.linear.x * constants.TWIST_MARKER_SCALE,
|
||||
y=twist_msg.linear.y * constants.TWIST_MARKER_SCALE,
|
||||
z=0.0,
|
||||
)
|
||||
marker.points = [start_point, end_point]
|
||||
|
||||
marker.scale = Vector3(x=0.2, y=0.4, z=0.4)
|
||||
marker.color.r = 0.0
|
||||
marker.color.g = 0.0
|
||||
marker.color.b = 1.0
|
||||
marker.color.a = 0.8
|
||||
marker.pose.orientation = Quaternion(w=1.0, x=0.0, y=0.0, z=0.0)
|
||||
marker.frame_locked = False
|
||||
|
||||
publisher.publish(marker)
|
||||
|
||||
def publish_target_vector_marker(self, target_vec_b, robot_odom_time, robot_frame_id, publisher):
|
||||
if robot_frame_id is None:
|
||||
return
|
||||
|
||||
marker = Marker()
|
||||
marker.header = Header()
|
||||
marker.header.stamp = _stamp_from_sec(robot_odom_time)
|
||||
marker.header.frame_id = robot_frame_id
|
||||
|
||||
marker.type = Marker.ARROW
|
||||
marker.action = Marker.ADD
|
||||
marker.id = constants.TARGET_VECTOR_MARKER_ID
|
||||
|
||||
vec = target_vec_b.flatten()
|
||||
|
||||
start_point = Point(x=0.0, y=0.0, z=0.0)
|
||||
end_point = Point(x=float(vec[0]), y=float(vec[1]), z=float(vec[2]))
|
||||
marker.points = [start_point, end_point]
|
||||
|
||||
marker.scale = Vector3(x=0.1, y=0.2, z=0.2)
|
||||
marker.pose.orientation = Quaternion(w=1.0, x=0.0, y=0.0, z=0.0)
|
||||
marker.color.r = 0.0
|
||||
marker.color.g = 1.0
|
||||
marker.color.b = 0.0
|
||||
marker.color.a = 0.5
|
||||
marker.frame_locked = False
|
||||
|
||||
publisher.publish(marker)
|
||||
|
||||
def publish_moving_goal_marker(self, moving_goal_delta, robot_pos_w, robot_orientation_w,
|
||||
robot_odom_time, map_frame_id, publisher):
|
||||
if robot_pos_w is None or map_frame_id is None:
|
||||
return
|
||||
|
||||
robot_pos = np.array(robot_pos_w, dtype=np.float32)
|
||||
robot_ori = np.array(robot_orientation_w, dtype=np.float32)
|
||||
robot_yaw_ori = yaw_quat(robot_ori)
|
||||
moving_goal_pos = np.array(moving_goal_delta, dtype=np.float32)
|
||||
|
||||
moving_goal_pos_w = transform_points(
|
||||
moving_goal_pos[np.newaxis],
|
||||
robot_pos[np.newaxis],
|
||||
robot_yaw_ori[np.newaxis],
|
||||
)
|
||||
|
||||
marker = Marker()
|
||||
marker.header = Header()
|
||||
marker.header.stamp = _stamp_from_sec(robot_odom_time)
|
||||
marker.header.frame_id = map_frame_id
|
||||
|
||||
marker.type = Marker.ARROW
|
||||
marker.action = Marker.ADD
|
||||
marker.id = constants.MOVING_GOAL_MARKER_ID
|
||||
|
||||
start_point = Point(
|
||||
x=float(moving_goal_pos_w[0, 0]),
|
||||
y=float(moving_goal_pos_w[0, 1]),
|
||||
z=float(moving_goal_pos_w[0, 2]) + 1.0,
|
||||
)
|
||||
end_point = Point(
|
||||
x=float(moving_goal_pos_w[0, 0]),
|
||||
y=float(moving_goal_pos_w[0, 1]),
|
||||
z=float(moving_goal_pos_w[0, 2]),
|
||||
)
|
||||
marker.points = [start_point, end_point]
|
||||
|
||||
marker.scale = Vector3(x=0.3, y=0.6, z=0.6)
|
||||
marker.color.r = 1.0
|
||||
marker.color.g = 1.0
|
||||
marker.color.b = 0.0
|
||||
marker.color.a = 0.5
|
||||
marker.pose.orientation = Quaternion(w=1.0, x=0.0, y=0.0, z=0.0)
|
||||
marker.frame_locked = False
|
||||
|
||||
publisher.publish(marker)
|
||||
|
||||
def publish_waypoints_marker(self, waypoints_visualization, map_frame_id, publisher):
|
||||
"""Publish recorded waypoints as a CUBE_LIST marker.
|
||||
|
||||
Note: ROS2 version received a `clock`. In ROS1 we use rospy.Time.now().
|
||||
"""
|
||||
if map_frame_id is None:
|
||||
return
|
||||
|
||||
marker = Marker()
|
||||
marker.header.stamp = rospy.Time.now()
|
||||
marker.header.frame_id = map_frame_id
|
||||
marker.ns = 'recorded_waypoints'
|
||||
marker.id = constants.WAYPOINTS_MARKER_ID
|
||||
marker.type = Marker.CUBE_LIST
|
||||
marker.action = Marker.ADD
|
||||
marker.scale = Vector3(x=0.3, y=0.3, z=0.3)
|
||||
marker.color.r = 0.0
|
||||
marker.color.g = 1.0
|
||||
marker.color.b = 0.0
|
||||
marker.color.a = 1.0
|
||||
|
||||
marker.points = []
|
||||
for waypoint in waypoints_visualization:
|
||||
marker.points.append(Point(x=waypoint[0], y=waypoint[1], z=waypoint[2]))
|
||||
|
||||
publisher.publish(marker)
|
||||
@@ -0,0 +1,157 @@
|
||||
"""Waypoint management for the SRU navigation controller (ROS1 port).
|
||||
|
||||
This module is logger-agnostic: pass any object with .info/.warn methods.
|
||||
For rospy a thin wrapper around rospy.loginfo / rospy.logwarn is provided.
|
||||
"""
|
||||
|
||||
from collections import deque
|
||||
|
||||
|
||||
class RospyLogger:
|
||||
"""Minimal logger duck-type matching the original rclpy logger interface."""
|
||||
|
||||
def __init__(self):
|
||||
import rospy
|
||||
self._rospy = rospy
|
||||
|
||||
def info(self, msg):
|
||||
self._rospy.loginfo(msg)
|
||||
|
||||
def warn(self, msg):
|
||||
self._rospy.logwarn(msg)
|
||||
|
||||
# Keep ROS2-style alias used in original code
|
||||
def warning(self, msg):
|
||||
self._rospy.logwarn(msg)
|
||||
|
||||
def error(self, msg):
|
||||
self._rospy.logerr(msg)
|
||||
|
||||
|
||||
class WaypointManager:
|
||||
"""Manages waypoint recording, tracking, and playback."""
|
||||
|
||||
def __init__(self, logger):
|
||||
self.logger = logger
|
||||
self.recorded_waypoints = deque()
|
||||
self.inversed_ordered_waypoints = deque()
|
||||
self.waypoints_visualization = deque()
|
||||
self.is_publish_waypoints_home = False
|
||||
self.is_publish_waypoints_inversed = False
|
||||
|
||||
def record_waypoint(self, robot_pos_w):
|
||||
if robot_pos_w is None:
|
||||
self.logger.warn('Robot position is not available yet.')
|
||||
return False
|
||||
|
||||
if len(self.recorded_waypoints) == 0 and len(self.inversed_ordered_waypoints) > 0:
|
||||
self.inversed_ordered_waypoints.clear()
|
||||
self.waypoints_visualization.clear()
|
||||
self.logger.info('Clear the inversed waypoints, and visualization waypoints.')
|
||||
|
||||
self.recorded_waypoints.append(robot_pos_w)
|
||||
self.inversed_ordered_waypoints.appendleft(robot_pos_w)
|
||||
self.waypoints_visualization.append(robot_pos_w)
|
||||
self.logger.info(
|
||||
'Waypoint recorded: {}, total waypoints: {}'.format(
|
||||
robot_pos_w, len(self.recorded_waypoints)
|
||||
)
|
||||
)
|
||||
return True
|
||||
|
||||
def remove_last_waypoint(self):
|
||||
removed_count = 0
|
||||
|
||||
if len(self.recorded_waypoints) > 0:
|
||||
self.recorded_waypoints.pop()
|
||||
removed_count += 1
|
||||
self.logger.info(
|
||||
'Removed last waypoint (home), total: {}'.format(len(self.recorded_waypoints))
|
||||
)
|
||||
|
||||
if len(self.inversed_ordered_waypoints) > 0:
|
||||
self.inversed_ordered_waypoints.popleft()
|
||||
removed_count += 1
|
||||
self.logger.info(
|
||||
'Removed last waypoint (inversed), total: {}'.format(
|
||||
len(self.inversed_ordered_waypoints)
|
||||
)
|
||||
)
|
||||
|
||||
if len(self.waypoints_visualization) > 0:
|
||||
self.waypoints_visualization.pop()
|
||||
removed_count += 1
|
||||
self.logger.info(
|
||||
'Removed last waypoint (visualization), total: {}'.format(
|
||||
len(self.waypoints_visualization)
|
||||
)
|
||||
)
|
||||
|
||||
if (len(self.waypoints_visualization) < len(self.recorded_waypoints) or
|
||||
len(self.waypoints_visualization) < len(self.inversed_ordered_waypoints)):
|
||||
raise ValueError(
|
||||
'The visualization waypoints is smaller than the recorded waypoints.'
|
||||
)
|
||||
|
||||
if removed_count == 0:
|
||||
self.logger.warn('No waypoints to remove.')
|
||||
|
||||
return removed_count > 0
|
||||
|
||||
def get_next_waypoint_home(self):
|
||||
if self.recorded_waypoints:
|
||||
return self.recorded_waypoints.pop()
|
||||
return None
|
||||
|
||||
def get_next_waypoint_inversed(self):
|
||||
if self.inversed_ordered_waypoints:
|
||||
return self.inversed_ordered_waypoints.pop()
|
||||
return None
|
||||
|
||||
def start_home_waypoint_sequence(self):
|
||||
if len(self.recorded_waypoints) > 0:
|
||||
self.is_publish_waypoints_home = True
|
||||
return True
|
||||
return False
|
||||
|
||||
def start_inversed_waypoint_sequence(self):
|
||||
if len(self.inversed_ordered_waypoints) > 0:
|
||||
self.is_publish_waypoints_inversed = True
|
||||
return True
|
||||
return False
|
||||
|
||||
def stop_home_waypoint_sequence(self):
|
||||
self.is_publish_waypoints_home = False
|
||||
|
||||
def stop_inversed_waypoint_sequence(self):
|
||||
self.is_publish_waypoints_inversed = False
|
||||
|
||||
def reset_visualization_if_complete(self):
|
||||
if (not self.recorded_waypoints and not self.inversed_ordered_waypoints
|
||||
and self.waypoints_visualization):
|
||||
self.logger.info('All waypoints are published, reset visualization.')
|
||||
self.waypoints_visualization.clear()
|
||||
return True
|
||||
return False
|
||||
|
||||
def re_add_aborted_waypoint(self, target_pos_w):
|
||||
if self.is_publish_waypoints_home:
|
||||
self.recorded_waypoints.append(target_pos_w)
|
||||
self.logger.info('Goal aborted - re-adding current goal as a recorded (home) waypoint.')
|
||||
if self.is_publish_waypoints_inversed:
|
||||
self.inversed_ordered_waypoints.appendleft(target_pos_w)
|
||||
self.logger.info(
|
||||
'Goal aborted: reinserting the current goal as recorded (inversed) waypoint.'
|
||||
)
|
||||
|
||||
def has_home_waypoints(self):
|
||||
return len(self.recorded_waypoints) > 0
|
||||
|
||||
def has_inversed_waypoints(self):
|
||||
return len(self.inversed_ordered_waypoints) > 0
|
||||
|
||||
def is_home_sequence_active(self):
|
||||
return self.is_publish_waypoints_home
|
||||
|
||||
def is_inversed_sequence_active(self):
|
||||
return self.is_publish_waypoints_inversed
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 ManifoldTech
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,516 @@
|
||||
# SRU × Odin: Mapless Navigation with Spatially-Enhanced Recurrent Memory
|
||||
|
||||
<p align="center">
|
||||
<img src="./Img/logo.png" alt="SRU × Odin1 Logo" width="20%">
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/badge/License-MIT-blue.svg" alt="License: MIT">
|
||||
<img src="https://img.shields.io/badge/Isaac%20Sim-4.5.0-76B900.svg" alt="Isaac Sim 4.5.0">
|
||||
<img src="https://img.shields.io/badge/ROS-Noetic-22314E.svg" alt="ROS Noetic">
|
||||
<img src="https://img.shields.io/badge/Sensor-Odin1-FF6F00.svg" alt="Sensor: Odin1">
|
||||
<a href="https://www.bilibili.com/video/BV1LaNq6yEpX"><img src="https://img.shields.io/badge/Video-bilibili-pink" alt="bilibili"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<b>Deploy cutting-edge paper within half a day using Odin1.</b>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="./Img/SRU_ODIN1.gif" alt="SRU Navigation Demo" width="800"/>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
## 1. Introduction
|
||||
|
||||
**SRU × Odin** brings the ETH RSL **SRU** (*Spatially-Enhanced Recurrent Memory for
|
||||
Long-Range Mapless Navigation via End-to-End Reinforcement Learning*) policy to a real
|
||||
quadruped using a single **Odin1** spatial-memory sensor. The original work relies on a
|
||||
**ZED-X** stereo camera for depth mapping and a **DLIO** LIO stack for high-precision
|
||||
odometry tracking; this project collapses both of those subsystems into one compact sensor.
|
||||
|
||||
> **Highlight — one sensor replaces two subsystems.** The **Odin1 spatial memory
|
||||
> module completely replaces BOTH the depth-mapping functionality of the original ZED
|
||||
> camera AND the high-precision odometry tracking from the DLIO LIO stack** used in the
|
||||
> upstream paper. Odin1 publishes a depth stream (`sensor_msgs/Image`, meters,
|
||||
> ~10 Hz) together with a high-frequency odometry topic, so a single device covers both
|
||||
> exteroception and state estimation.
|
||||
|
||||
> **Highlight — Code Generation.** You do not have to hand-write the deployment stack. A
|
||||
> structured LLM prompt (`Prompt/PORTING_GUIDE.md`) lets an AI agent **automatically
|
||||
> generate ready-to-use navigation deployment code for physical robots** — from ONNX I/O
|
||||
> specification through the ROS node down to the launch scripts.
|
||||
|
||||
**Paper:** *Spatially-Enhanced Recurrent Memory for Long-Range Mapless Navigation via
|
||||
End-to-End Reinforcement Learning* — DOI: <https://doi.org/10.1177/02783649251401926> ·
|
||||
Project page: <https://michaelfyang.github.io/sru-project-website/>
|
||||
|
||||
### Related Work
|
||||
|
||||
- **[ManifoldTech Real2Sim Tutorial](https://github.com/ManifoldTechLtd/MT-Real2Sim-Tutorial)** — Transform the real world into a simulated environment using Q9000.
|
||||
- **[Odin-Nav-Stack](https://github.com/ManifoldTechLtd/Odin-Nav-Stack)** — A full-stack navigation framework based on Odin, integrating end-to-end navigation (NeuPAN), classical navigation, modular navigation, VLM, YOLO object detection, and VLN (Vision-and-Language Navigation) into a unified system.
|
||||
|
||||
---
|
||||
|
||||
## 2. Key Features
|
||||
|
||||
- **End-to-end mapless navigation** — depth image + goal vector → velocity command
|
||||
(`/cmd_vel`), with no occupancy grid, no SLAM map, and no global planner.
|
||||
- **Spatially-enhanced recurrent memory** — a VAE depth encoder feeds an LSTM-SRU actor
|
||||
(`rnn_hidden_size=512`, `num_layers=1`) that remembers where obstacles were.
|
||||
- **One sensor, two subsystems replaced** — the Odin1 spatial memory module supplies BOTH
|
||||
the depth mapping that upstream took from the ZED-X camera AND the high-precision
|
||||
odometry that upstream took from the DLIO LIO stack.
|
||||
- **Sensor-agnostic depth pipeline** — any depth image works; Odin1 is the
|
||||
reference sensor, ZED-X the upstream original.
|
||||
- **Robot-agnostic output** — publishes a body-frame `geometry_msgs/Twist`; any robot with
|
||||
a `/cmd_vel` bridge can be driven.
|
||||
- **ONNX Runtime inference** — no PyTorch at deployment time; single-file models, easy
|
||||
CPU/GPU EP switching, ready-made aarch64 wheels for Jetson.
|
||||
- **Reproducible Docker training** — Isaac Sim 4.5.0 + IsaacLab v2.1.1 image, one-click
|
||||
training scripts, VRAM-aware environment scaling.
|
||||
- **Prompt-driven deployment** — a physically tested ROS1 Noetic package plus a
|
||||
prompt-driven workflow to regenerate it from scratch.
|
||||
|
||||
---
|
||||
|
||||
## 3. System Architecture
|
||||
|
||||
```
|
||||
┌──────────────────────────── TRAINING (Isaac Sim 4.5 / Docker) ────────────────────────────┐
|
||||
│ │
|
||||
│ IsaacLab v2.1.1 + sru-navigation-sim task + rsl_rl (ActorCriticSRU: VAE + LSTM-SRU) │
|
||||
│ parallel envs ──► PPO/MDPO ──► checkpoints (outputs/logs/.../model_*.pt) │
|
||||
│ │
|
||||
└───────────────────────────────────────────┬────────────────────────────────────────────┘
|
||||
│ scripts/export_onnx.py
|
||||
▼
|
||||
┌──────────────────────────────── POLICY EXPORT ────────────────────────────────┐
|
||||
│ model_best.pt ──► policy.onnx (obs[1,2576] + h/c[1,1,512] → act[1,3]) │
|
||||
│ (deployment split: vae_encoder.onnx + nav_policy.onnx) │
|
||||
└───────────────────────────────────────────┬──────────────────────────────────┘
|
||||
│ copy into Deployment/models/
|
||||
▼
|
||||
┌──────────────────────── DEPLOYMENT (Go2 + Odin1 + ROS1 Noetic) ─────────────────────┐
|
||||
│ │
|
||||
│ Odin1 driver ──► /odin1/depth_img_competetion (depth) │
|
||||
│ └─► /odin1/odometry_highfreq (odom) │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ sru_nav_node: depth ─► VAE encoder ─► latent ─┐ │
|
||||
│ odom + goal + prev_action ──────┼─► LSTM-SRU actor ─► /cmd_vel │
|
||||
│ LSTM (h,c) held across frames ──┘ (Twist, body frame) │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ cmd_vel bridge (unitree_legged_sdk) ──► sport-mode joint commands │
|
||||
└────────────────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Repository Structure
|
||||
|
||||
```
|
||||
SRU_GO2_ODIN1/
|
||||
├── Prompt/
|
||||
│ └── PORTING_GUIDE.md # Source-of-truth prompt for LLM-based code generation
|
||||
├── Deployment/ # Tested, working ROS1 deployment package (reference)
|
||||
│ ├── src/sru_nav_go2/ # ONNX inference node + helpers (Odin1)
|
||||
│ ├── config/sru_nav.yaml # The ONLY file users normally edit
|
||||
│ ├── launch/sru_nav_go2.launch
|
||||
│ ├── scripts/ # setup_conda_env.sh, launch_sru_nav.sh, verify_port.sh
|
||||
│ ├── models/ # vae_encoder.onnx + nav_policy.onnx (user-supplied)
|
||||
│ └── docs/ # DEPLOY_GO2_NX.md, PORTING_GUIDE(_EN).md
|
||||
├── Train/ # Isaac Sim 4.5 Docker training environment
|
||||
│ ├── Dockerfile # Base: nvcr.io/nvidia/isaac-sim:4.5.0
|
||||
│ ├── docker-compose.yml # shm_size 16gb, NVIDIA runtime, cache volumes
|
||||
│ ├── scripts/ # train_go2_scratch.sh, export_onnx.py
|
||||
│ ├── mount/ # IsaacLab / rsl_rl / sru-navigation-sim (live-mounted)
|
||||
│ └── outputs/logs/ # Checkpoints + TensorBoard logs
|
||||
└── referee_readme/ # Style/structure reference READMEs
|
||||
```
|
||||
|
||||
The three top-level directories map to the three phases of the project:
|
||||
|
||||
| Directory | Role |
|
||||
| -------------- | ------------------------------------------------------------------- |
|
||||
| `Prompt/` | The porting prompt — regenerate the deployment package from scratch |
|
||||
| `Deployment/` | Physically validated deployment code, a practical debugging reference |
|
||||
| `Train/` | Reproducible Docker environment to (re)train the policy |
|
||||
|
||||
---
|
||||
|
||||
## 5. Prompt-Based Code Generation & Deployment
|
||||
|
||||
`Prompt/PORTING_GUIDE.md` is a **three-in-one document**: a porting decision log, an
|
||||
AI-agent replication prompt, and an automated acceptance script. Its purpose is to let an
|
||||
LLM agent (Cascade, Claude Code, Cursor, etc.) **regenerate the entire `sru_nav_go2_ros1`
|
||||
deployment package** starting only from the SRU paper and the five upstream repositories.
|
||||
|
||||
### 5.1 The Prompt
|
||||
|
||||
Modern LLMs cannot reliably one-shot ~1500 lines of ROS porting code, so
|
||||
`Prompt/PORTING_GUIDE.md` cuts the task into a **6-step phased workflow**: reconnaissance,
|
||||
IO specification, catkin skeleton, node logic, deploy scripts, and docs & verify. Each step
|
||||
ends with grep-able validation points, so any diverging step is rolled back and retried
|
||||
before moving on. The prompt is plain Markdown and works with any LLM coding agent.
|
||||
|
||||
### 5.2 `Deployment/` as a practical reference
|
||||
|
||||
The `Deployment/` package is **not generated on the fly** — it is the physically tested,
|
||||
real-hardware-validated code. Think of it as a highly practical reference rather than a
|
||||
strict rulebook: if you hit problems while replicating the code through the prompt workflow,
|
||||
diff your generated package against `Deployment/` to debug and troubleshoot the divergence.
|
||||
|
||||
```bash
|
||||
diff -r --exclude=__pycache__ --exclude=.git \
|
||||
./generated_sru_nav_go2_ros1/ \
|
||||
./Deployment/
|
||||
```
|
||||
|
||||
> **Tip:** Structure should be broadly similar; comments and literal ordering may differ.
|
||||
> When something misbehaves, focus your comparison on the critical parameters
|
||||
> (`policy_scale`, control frequency, topic names, ONNX tensor shapes) — those are the ones
|
||||
> that must match for correct behavior.
|
||||
|
||||
> The quality of code generated via the prompt workflow may vary depending on
|
||||
> the capability of the LLM used. In some cases, the generated code may require further
|
||||
> iteration and refinement with the LLM to achieve full functionality. Always validate
|
||||
> against the `Deployment/` reference and run the acceptance checks before deploying to
|
||||
> real hardware.
|
||||
|
||||
---
|
||||
|
||||
## 6. Training Guide
|
||||
|
||||
This is the core focus of the repository. Training is fully containerized around
|
||||
**Isaac Sim 4.5.0 + IsaacLab v2.1.1** and the `sru-navigation-sim` task extension.
|
||||
|
||||
### 6.1 Adaptation Notes
|
||||
|
||||
**Sensor adaptation — ZED-X + DLIO → Odin1.**
|
||||
The policy consumes a normalized single-channel depth image encoded by a VAE into a
|
||||
`64×5×8` latent (2560 features). Upstream produced depth from a ZED-X stereo stream and
|
||||
odometry from a DLIO LIO stack; here a single Odin1 sensor supplies both. The node ingests
|
||||
Odin1's depth image, applies `nan_to_num`, clips to `[0.25, 10.0] m`, and
|
||||
resizes to the training resolution `(40, 64)` before encoding — the network sees the same
|
||||
tensor regardless of the physical sensor.
|
||||
|
||||
**Robot kinematics — B2W → Unitree Go2.**
|
||||
The upstream B2W is a wheeled-legged platform; the target here is the Unitree Go2. Because the
|
||||
policy only emits a body-frame velocity command, the kinematic difference is absorbed by
|
||||
the actuator bridge and by a conservative action scale. The deployment `policy_scale`
|
||||
defaults to `[0.6, 0.3, 0.6]` (vs. the training `[1.5, 1.0, 1.0]`), leaving safety margin;
|
||||
training randomized the action scale by `Uniform(0.6, 1.2)`, so the network is robust to
|
||||
runtime rescaling.
|
||||
|
||||
### 6.2 Quick Start — Docker Training
|
||||
|
||||
#### Step 1 — Docker setup, NGC login, and build
|
||||
|
||||
```bash
|
||||
# NVIDIA NGC login is required to pull the Isaac Sim base image.
|
||||
docker login nvcr.io
|
||||
# Username: $oauthtoken
|
||||
# Password: <YOUR_NGC_API_KEY>
|
||||
|
||||
cd Train/
|
||||
cp .env.example .env # optional: add WANDB_API_KEY
|
||||
docker compose build # first build > 20 min (network dependent)
|
||||
```
|
||||
|
||||
The build pulls `nvcr.io/nvidia/isaac-sim:4.5.0`, installs IsaacLab `v2.1.1`, replaces the
|
||||
bundled `rsl_rl` with the SRU-enhanced fork (`ActorCriticSRU` + MDPO/PPO), and installs the
|
||||
`sru-navigation-sim` task extension.
|
||||
|
||||
> **Warning — Shared memory is mandatory:** Isaac Sim's OmniGraph pipeline crashes (often as
|
||||
> a silent segfault) if the container's shared memory is too small. Always run with at least
|
||||
> **`--shm-size=4gb`** for `docker run`, or **`shm_size: '4gb'`** under the service in
|
||||
> `docker-compose.yml`. This repository's `docker-compose.yml` and `train_go2_scratch.sh`
|
||||
> already set `16gb` — do **not** lower this below `4gb`.
|
||||
|
||||
#### Step 2 — Launch the container and verify
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
docker compose exec sru-nav bash # working dir: /workspace/IsaacLab
|
||||
|
||||
# Inside the container: confirm the task extension + registered tasks
|
||||
./isaaclab.sh -p -m pip show isaaclab_nav_task
|
||||
./isaaclab.sh -p source/isaaclab_nav_task/scripts/train.py --help
|
||||
```
|
||||
|
||||
You should see task IDs such as `Isaac-Nav-PPO-Go2-Dev-v0` and `Isaac-Nav-PPO-Go2-v0`.
|
||||
|
||||
#### Step 3 — One-click training with environment variables
|
||||
|
||||
From the host, `scripts/train_go2_scratch.sh` launches a cold-start training run inside a
|
||||
disposable container (headless, 24 envs, 1000 iterations, `Isaac-Nav-PPO-Go2-Dev-v0` by
|
||||
default). All knobs are overridable via environment variables:
|
||||
|
||||
```bash
|
||||
# Default: 24 envs, 1000 iter, headless (safe on a 12 GB card)
|
||||
./scripts/train_go2_scratch.sh
|
||||
|
||||
# Scale the parallel environment count to your GPU
|
||||
NUM_ENVS=64 MAX_ITER=2000 ./scripts/train_go2_scratch.sh
|
||||
|
||||
# GUI debugging with a handful of envs
|
||||
GUI=1 NUM_ENVS=4 MAX_ITER=200 ./scripts/train_go2_scratch.sh
|
||||
|
||||
# Pin a specific GPU and run the full PPO task
|
||||
GPU=0 TASK=Isaac-Nav-PPO-Go2-v0 RUN_NAME=scratch_full ./scripts/train_go2_scratch.sh
|
||||
```
|
||||
|
||||
> **VRAM Hardware Scaling Table** — pick `NUM_ENVS` to match your GPU:
|
||||
|
||||
| GPU | VRAM | Recommended `NUM_ENVS` |
|
||||
| ------------------- | ----- | ---------------------- |
|
||||
| RTX 4090 | 24 GB | 64–128 |
|
||||
| RTX 4070 / 5070 | 12 GB | 24 (default) |
|
||||
| 8 GB Laptop GPU | 8 GB | 8–12 |
|
||||
|
||||
> **Note:** On a 12 GB card, `GUI=1` combined with a large `NUM_ENVS` will OOM — keep GUI
|
||||
> runs to ≤ 4 envs and use `--headless` (the default) for real training.
|
||||
|
||||
Outputs land in `outputs/logs/rsl_rl/<experiment>/<timestamp>_<RUN_NAME>/` on the host
|
||||
(bind-mounted into the container).
|
||||
|
||||
#### Step 4 — Monitor and export
|
||||
|
||||
**Monitor** live metrics with TensorBoard:
|
||||
|
||||
```bash
|
||||
# TensorBoard (inside container)
|
||||
docker compose exec sru-nav \
|
||||
./isaaclab.sh -p -m tensorboard.main --logdir logs --bind_all
|
||||
# then open http://<host>:6006
|
||||
```
|
||||
|
||||
**Export** the trained checkpoint to ONNX. The exporter reconstructs `ActorCriticSRU` from
|
||||
the checkpoint weight shapes (no Isaac Sim needed) and writes `policy.onnx`:
|
||||
|
||||
```bash
|
||||
python scripts/export_onnx.py \
|
||||
--checkpoint outputs/logs/scratch_reward_fix_v1/model_best.pt \
|
||||
--output-dir mount/
|
||||
```
|
||||
|
||||
Useful flags (from `scripts/export_onnx.py`):
|
||||
|
||||
| Flag | Default | Description |
|
||||
| -------------- | -------------- | ---------------------------------------- |
|
||||
| `--checkpoint` | *(required)* | Path to the `.pt` checkpoint |
|
||||
| `--output-dir` | `<ckpt>/export`| Output directory |
|
||||
| `--filename` | `policy.onnx` | Output filename |
|
||||
| `--jit` | off | Also export a TorchScript `policy.pt` |
|
||||
| `--verbose` | off | Print inferred config + architecture |
|
||||
|
||||
Copy the exported model(s) into `Deployment/models/` for on-robot inference.
|
||||
|
||||
---
|
||||
|
||||
## 7. ONNX I/O Contract
|
||||
|
||||
The training-side export (`export_onnx.py`) produces a **single combined actor** ONNX that
|
||||
already ingests the fused observation vector:
|
||||
|
||||
| Model | Tensor | Shape | Notes |
|
||||
| ------------- | --------- | ----------------- | -------------------------------------- |
|
||||
| `policy.onnx` | `obs` | `(1, 2576)` | 16 proprio + 2560 image latent (64×5×8)|
|
||||
| (input) | `h_in` | `(1, 1, 512)` | LSTM hidden; zeros at episode start |
|
||||
| (input) | `c_in` | `(1, 1, 512)` | LSTM cell; zeros at episode start |
|
||||
| `policy.onnx` | `actions` | `(1, 3)` | `tanh` output in `(-1, 1)` |
|
||||
| (output) | `h_out` | `(1, 1, 512)` | updated hidden state |
|
||||
| (output) | `c_out` | `(1, 1, 512)` | updated cell state |
|
||||
|
||||
The **deployment** package splits inference into two ONNX files so the depth encoder and the
|
||||
recurrent actor can be validated independently:
|
||||
|
||||
| Model | Inputs | Outputs |
|
||||
| ------------------ | ---------------------------------------- | ---------------------------------- |
|
||||
| `vae_encoder.onnx` | `input` `(B, 1, 40, 64)` | `mu` `(B, 64, 5, 8)` |
|
||||
| `nav_policy.onnx` | `obs` `(B, 2576)`, `h` `(1, B, 512)`, `c` `(1, B, 512)` | `actions` `(B, 3)`, `h_new`, `c_new` |
|
||||
|
||||
> **Note:** The node discovers tensor names via `session.get_inputs()[i].name` **and**
|
||||
> asserts them against this contract at startup — a shape mismatch raises immediately rather
|
||||
> than silently producing garbage commands. Final velocity =
|
||||
> `tanh_output × policy_scale`, with `policy_scale = [0.6, 0.3, 0.6]` → `[vx, vy, ωz]`.
|
||||
|
||||
---
|
||||
|
||||
## 8. Real-Hardware Deployment
|
||||
|
||||
### 8.1 Hardware & Software Requirements
|
||||
|
||||
| Component | Requirement |
|
||||
| ---------------- | -------------------------------------------------------------------- |
|
||||
| Robot | Unitree Go2 (or any `/cmd_vel` consumer quadruped) |
|
||||
| Depth sensor | Odin1 (depth ~10 Hz + high-freq odometry); see launch file for physical mounting offsets |
|
||||
| Compute | Jetson Orin NX (aarch64) or any Linux x86_64 |
|
||||
| OS | Ubuntu 20.04 (native ROS Noetic) or `osrf/ros:noetic-desktop` docker |
|
||||
| Middleware | ROS1 Noetic |
|
||||
| Python env | conda `sru_go2`, Python **3.8** (bound to Noetic ABI — do not change)|
|
||||
| Inference | `onnxruntime` (CPU) or `onnxruntime-gpu` (JetPack-matched wheel) |
|
||||
| Operator input | Unitree remote control |
|
||||
|
||||
### 8.2 ROS1 Interface
|
||||
|
||||
| Topic | Type | Direction | Description |
|
||||
| ------------------------------ | -------------------------- | --------- | ------------------------------------ |
|
||||
| `/odin1/depth_img_competetion` | `sensor_msgs/Image` | in | dense float32 depth, meters, ~10 Hz |
|
||||
| `/odin1/odometry_highfreq` | `nav_msgs/Odometry` | in | odom frame, ~400 Hz (IMU rate) |
|
||||
| `/joy` | `sensor_msgs/Joy` | in | Unitree remote control input |
|
||||
| `/goal_pose` | `geometry_msgs/PoseStamped`| in / out | goal; `frame_id` must equal odom frame|
|
||||
| `/cmd_vel` | `geometry_msgs/Twist` | out | body-frame velocity command |
|
||||
|
||||
> **Note:** `/goal_pose.header.frame_id` **must** match the odom `frame_id` (default
|
||||
> `odom`); otherwise the node rejects the goal to prevent body-frame coordinates being
|
||||
> published as odom-frame goals.
|
||||
|
||||
### 8.3 Build & Environment Setup
|
||||
|
||||
Because conda and system ROS coexist, the launch wrapper handles several ABI hazards
|
||||
automatically (notably the conda/system `libffi` mismatch that otherwise triggers
|
||||
`libp11-kit.so.0: undefined symbol: ffi_type_pointer`). You do not need to configure
|
||||
anything by hand — `launch_sru_nav.sh` takes care of it.
|
||||
|
||||
One-time setup then build inside the conda env at the workspace root:
|
||||
|
||||
```bash
|
||||
# 1) Create the conda env (installs onnxruntime, opencv, netifaces, defusedxml, ...)
|
||||
bash scripts/setup_conda_env.sh
|
||||
bash scripts/setup_conda_env.sh --check # ROS dist-packages may [FAIL] outside a container
|
||||
|
||||
# 2) Build in the ACTIVATED conda env, at the workspace root
|
||||
conda activate sru_go2
|
||||
cd $CATKIN_WS # folder containing src/
|
||||
catkin_make -DPYTHON_EXECUTABLE=$(which python)
|
||||
|
||||
# 3) Self-check
|
||||
cd $CATKIN_WS/src/sru_nav_go2_ros1
|
||||
bash scripts/verify_port.sh # all PASS when ONNX present
|
||||
```
|
||||
|
||||
### 8.4 Three-Terminal Launch
|
||||
|
||||
The first process to start brings up `roscore`.
|
||||
|
||||
**Terminal 1 — Odin1 driver**
|
||||
|
||||
```bash
|
||||
conda activate neupan
|
||||
roslaunch odin_ros_driver odin1_ros1.launch
|
||||
# Ensure config/control_command.yaml has senddepth: 1 and sendodom: 1
|
||||
```
|
||||
|
||||
**Terminal 2 — `/cmd_vel` actuator bridge**
|
||||
|
||||
```bash
|
||||
conda activate sru_go2
|
||||
cd $CATKIN_WS && source devel/setup.bash
|
||||
rosrun unitree_control unitree_vel_controller __name:=vel_to_sdk
|
||||
```
|
||||
|
||||
**Terminal 3 — SRU navigation node**
|
||||
|
||||
```bash
|
||||
cd $CATKIN_WS/src/sru_nav_go2_ros1
|
||||
bash scripts/launch_sru_nav.sh require_joystick:=false
|
||||
```
|
||||
|
||||
Setting `require_joystick:=false` stops the Unitree remote control from constantly
|
||||
broadcasting zero-velocity commands.
|
||||
|
||||
Send a goal (in the odom frame) and watch `/cmd_vel`:
|
||||
|
||||
```bash
|
||||
rostopic pub -1 /goal_pose geometry_msgs/PoseStamped \
|
||||
'{header: {frame_id: "odom"}, pose: {position: {x: 1.0, y: 0.0, z: 0.0}, orientation: {w: 1.0}}}'
|
||||
rostopic echo /cmd_vel # expect a non-zero Twist stream
|
||||
```
|
||||
|
||||
### 8.5 Configuration Notes
|
||||
|
||||
Edit `Deployment/config/sru_nav.yaml` — the only file you normally touch:
|
||||
|
||||
| Parameter | Default | Meaning |
|
||||
| ------------------- | -------------------- | --------------------------------------------------- |
|
||||
| `depth_topic` | `/odin1/depth_img_competetion` | depth image (meters) |
|
||||
| `odom_topic` | `/odin1/odometry_highfreq` | world-frame odometry |
|
||||
| `cmd_vel_topic` | `/cmd_vel` | output body-frame velocity |
|
||||
| `control_frequency` | `5.0` | Hz — keep aligned with training |
|
||||
| `policy_scale` | `[0.6, 0.3, 0.6]` | `[vx_max, vy_max, ωz_max]`; raise gradually |
|
||||
| `min_depth`/`max_depth` | `0.25` / `10.0` | depth clip range (meters) |
|
||||
| `use_sim` | `false` | `true` = odom twist already in base frame |
|
||||
| `require_joystick` | `true` | `false` stops the remote from broadcasting zero-velocity locks (TESTING ONLY) |
|
||||
|
||||
### 8.6 Camera Mounting
|
||||
|
||||
Camera mounting is set in the launch file, which publishes a static TF
|
||||
`base_link → odin1_base_link` (adjust to the real measured mount). Offsets are xyz in
|
||||
meters (forward, left, up) and rpy in radians; defaults are `odin1_x=0.258`, `odin1_y=0.0`,
|
||||
`odin1_z=0.154`, `odin1_roll=0.0`, `odin1_pitch=0.0` (0° downward), `odin1_yaw=0.0`:
|
||||
|
||||
```bash
|
||||
roslaunch sru_nav_go2 sru_nav_go2.launch odin1_x:=0.28 odin1_z:=0.154 odin1_pitch:=0.0
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. Troubleshooting / Common Pitfalls
|
||||
|
||||
| # | Problem | Solution |
|
||||
| - | ------- | -------- |
|
||||
| 1 | **`/cmd_vel` is all zeros.** Node logs "ready" but the robot never moves. | The Unitree remote control is holding the robot stationary with zero-velocity commands. On jack stands / sim, launch with `require_joystick:=false`. |
|
||||
| 2 | **`ModuleNotFoundError: netifaces` / crash on first subscriber.** Node reaches "ready" then dies the moment a topic connects. | `netifaces` / `defusedxml` are missing in the conda env. `pip install netifaces defusedxml` (already built into `setup_conda_env.sh`). |
|
||||
| 3 | **`libp11-kit.so.0: undefined symbol: ffi_type_pointer`.** | Conda's libffi clashes with system `cv_bridge`. Launch via `launch_sru_nav.sh` — the launch script handles this automatically. |
|
||||
| 4 | **Node shebang points to `/usr/bin/python3`; ONNX import fails.** | `catkin_make` was run outside the conda env. `conda activate sru_go2 && cd $CATKIN_WS && catkin_make clean && catkin_make -DPYTHON_EXECUTABLE=$(which python)`. |
|
||||
| 5 | **`zsh` terminal: `setup.zsh: line 7: cd: -q: invalid option`, script dies silently.** | `ZSH_VERSION` leaks into the bash subprocess. `launch_sru_nav.sh` fixes this by exporting `CATKIN_SHELL=bash` and unsetting `ZSH_VERSION`/`ZSH_NAME` before sourcing. |
|
||||
|
||||
> **Note (bonus):** Isaac Sim training crashes with an OmniGraph shared-memory error →
|
||||
> increase `shm_size` (≥ 4 GB, repo default 16 GB). Jetson pip TLS handshake failures →
|
||||
> the RTC drained; run `sudo ntpdate -u ntp.aliyun.com && sudo hwclock --systohc`.
|
||||
|
||||
---
|
||||
|
||||
## 10. Citation
|
||||
|
||||
If you use this work, please cite the SRU paper:
|
||||
|
||||
```bibtex
|
||||
@article{yang2025sru,
|
||||
author = {Yang, Fan and Frivik, Per and Hoeller, David and Wang, Chen and Cadena, Cesar and Hutter, Marco},
|
||||
title = {Spatially-enhanced recurrent memory for long-range mapless navigation via end-to-end reinforcement learning},
|
||||
journal = {The International Journal of Robotics Research},
|
||||
year = {2025},
|
||||
doi = {10.1177/02783649251401926},
|
||||
url = {https://doi.org/10.1177/02783649251401926}
|
||||
}
|
||||
```
|
||||
|
||||
Paper: <https://doi.org/10.1177/02783649251401926> ·
|
||||
Project page: <https://michaelfyang.github.io/sru-project-website/>
|
||||
|
||||
---
|
||||
|
||||
## 11. Acknowledgments
|
||||
|
||||
This project builds upon: <https://github.com/sallu-786/Go2_Isaac_ros2>
|
||||
|
||||
---
|
||||
|
||||
## 12. License
|
||||
|
||||
- **Algorithm & training code** — copyright of the original SRU author team (ETH RSL);
|
||||
follows their upstream LICENSE. Files containing upstream-derived code retain their
|
||||
original headers.
|
||||
- **This deployment port** (`Deployment/`) — released under an **MIT-style** license.
|
||||
- **Upstream sources:** `sru-navigation-learning`, `sru-navigation-sim`,
|
||||
`sru-robot-deployment`, `sru-pytorch-spatial-learning`, `sru-depth-pretraining`
|
||||
(see <https://michaelfyang.github.io/sru-project-website/>).
|
||||
- **Simulation stack:** NVIDIA Isaac Sim 4.5.0 + IsaacLab v2.1.1.
|
||||
- **Odin1 driver:** <https://github.com/manifoldsdk/odin_ros_driver>.
|
||||
|
||||
Issues and PRs — especially one-click support for additional robots or cameras — are welcome.
|
||||
@@ -0,0 +1,14 @@
|
||||
# Keep docker build context small. mount/IsaacLab and mount/sru-navigation-sim
|
||||
# are needed by COPY in Dockerfile, so they MUST NOT be excluded.
|
||||
outputs/
|
||||
log*.txt
|
||||
auth_qrcode.png
|
||||
*.tar.gz
|
||||
*.tgz
|
||||
**/__pycache__/
|
||||
**/*.pyc
|
||||
**/.git/
|
||||
**/.gitignore
|
||||
.windsurf/
|
||||
.vscode/
|
||||
.idea/
|
||||
@@ -0,0 +1,3 @@
|
||||
# Copy to .env and fill in.
|
||||
WANDB_API_KEY=
|
||||
DISPLAY=:0
|
||||
@@ -0,0 +1,148 @@
|
||||
# =====================================================================
|
||||
# SRU Navigation Sim - Reproducible Training Image
|
||||
# Base: NVIDIA Isaac Sim 4.5.0 (matches IsaacLab v2.1.1 requirement)
|
||||
# =====================================================================
|
||||
ARG ISAAC_SIM_VERSION=4.5.0
|
||||
FROM nvcr.io/nvidia/isaac-sim:${ISAAC_SIM_VERSION}
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive \
|
||||
LANG=C.UTF-8 \
|
||||
ACCEPT_EULA=Y \
|
||||
PRIVACY_CONSENT=Y \
|
||||
OMNI_KIT_ALLOW_ROOT=1
|
||||
|
||||
# ---------- System deps ----------
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
git git-lfs curl wget vim ca-certificates build-essential \
|
||||
cmake ninja-build libgl1 libglib2.0-0 libsm6 libxext6 libxrender1 \
|
||||
libglu1-mesa libglib2.0-0 ncurses-term tmux htop \
|
||||
python3-pip && \
|
||||
git lfs install && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Avoid "dubious ownership" inside containers
|
||||
RUN git config --global --add safe.directory '*'
|
||||
|
||||
# ---------- Configure pip mirror (optional) ----------
|
||||
# Default behavior uses the official PyPI. The global pip config is written so
|
||||
# ALL python interpreters in the image (root, kit-bundled
|
||||
# `_isaac_sim/kit/python`, system python3) pick it up.
|
||||
#
|
||||
# Override pip index if needed: --build-arg PIP_INDEX_URL=https://your-mirror/simple --build-arg PIP_TRUSTED_HOST=your-mirror-host
|
||||
ARG PIP_INDEX_URL=
|
||||
ARG PIP_TRUSTED_HOST=
|
||||
RUN if [ -n "${PIP_INDEX_URL}" ]; then \
|
||||
mkdir -p /etc && printf "[global]\nindex-url = %s\ntrusted-host = %s\ntimeout = 120\nretries = 5\n" \
|
||||
"${PIP_INDEX_URL}" "${PIP_TRUSTED_HOST}" > /etc/pip.conf; \
|
||||
mkdir -p /root/.config/pip && cp /etc/pip.conf /root/.config/pip/pip.conf; \
|
||||
echo "[build] pip index -> ${PIP_INDEX_URL}"; \
|
||||
fi
|
||||
|
||||
# Workspace
|
||||
ARG ISAACLAB_VERSION=v2.1.1
|
||||
ENV ISAACLAB_PATH=/workspace/IsaacLab
|
||||
WORKDIR /workspace
|
||||
|
||||
# Optional build-time proxy (pass via: --build-arg HTTP_PROXY=... --build-arg HTTPS_PROXY=...)
|
||||
# Useful when the host is behind GFW / corporate firewall and bare `git clone github.com`
|
||||
# hits `GnuTLS recv error (-110)` / TLS resets. Leave empty to disable.
|
||||
ARG HTTP_PROXY=
|
||||
ARG HTTPS_PROXY=
|
||||
ARG NO_PROXY=
|
||||
ENV http_proxy=${HTTP_PROXY} \
|
||||
https_proxy=${HTTPS_PROXY} \
|
||||
no_proxy=${NO_PROXY}
|
||||
|
||||
# Optional GitHub mirror prefix (e.g. https://ghproxy.com/ or https://gh-proxy.com/).
|
||||
# When set, all subsequent github.com clones are rewritten through it via git insteadOf.
|
||||
ARG GITHUB_MIRROR=
|
||||
RUN if [ -n "${GITHUB_MIRROR}" ]; then \
|
||||
git config --global url."${GITHUB_MIRROR}https://github.com/".insteadOf "https://github.com/"; \
|
||||
echo "[build] github.com clones rewritten via ${GITHUB_MIRROR}"; \
|
||||
fi
|
||||
|
||||
# Harden git for flaky networks (large postBuffer, low-speed timeout, no compression,
|
||||
# disable smart-http v2 which is the layer that surfaces the GnuTLS reset on long clones).
|
||||
RUN git config --global http.postBuffer 1048576000 && \
|
||||
git config --global http.lowSpeedLimit 1000 && \
|
||||
git config --global http.lowSpeedTime 600 && \
|
||||
git config --global core.compression 0 && \
|
||||
git config --global http.version HTTP/1.1
|
||||
|
||||
# ---------- Bring IsaacLab v2.1.1 into the image ----------
|
||||
# We COPY from the local build context (./mount/IsaacLab) instead of `git clone`,
|
||||
# because on GFW-affected servers `git clone github.com` repeatedly fails with
|
||||
# GnuTLS resets / connection timeouts. To set this up on the host:
|
||||
#
|
||||
# # one-shot: clone IsaacLab anywhere reachable from your build context
|
||||
# git clone --depth 1 --branch v2.1.1 \
|
||||
# https://github.com/isaac-sim/IsaacLab.git <repo>/mount/IsaacLab
|
||||
#
|
||||
# If mount/IsaacLab is missing the build will abort here with a clear error.
|
||||
COPY mount/IsaacLab ${ISAACLAB_PATH}
|
||||
RUN test -d ${ISAACLAB_PATH}/source/isaaclab && \
|
||||
echo "[build] using local IsaacLab from mount/IsaacLab"
|
||||
|
||||
# Symlink Isaac Sim into IsaacLab as required by isaaclab.sh
|
||||
RUN ln -s /isaac-sim ${ISAACLAB_PATH}/_isaac_sim
|
||||
|
||||
# ---------- Install IsaacLab (uses bundled python from isaac-sim) ----------
|
||||
WORKDIR ${ISAACLAB_PATH}
|
||||
RUN ./isaaclab.sh --install
|
||||
|
||||
# Workaround: the official --install loop builds extensions in PEP-517 isolation,
|
||||
# which fails for source/isaaclab because the kit-python build env lacks pkg_resources.
|
||||
# Reinstall every source/* extension with --no-build-isolation to guarantee `import isaaclab` works.
|
||||
RUN for d in ${ISAACLAB_PATH}/source/*/; do \
|
||||
if [ -f "$d/setup.py" ]; then \
|
||||
${ISAACLAB_PATH}/_isaac_sim/python.sh -m pip install --no-build-isolation --timeout 180 --retries 5 -e "$d" || exit 1; \
|
||||
fi; \
|
||||
done && \
|
||||
${ISAACLAB_PATH}/_isaac_sim/python.sh -c "import isaaclab; print('isaaclab OK:', isaaclab.__file__)"
|
||||
|
||||
# ---------- Replace bundled rsl_rl with SRU-enhanced fork ----------
|
||||
# sru-navigation-learning provides ActorCriticSRU + MDPO/SPO/PPO required by sru-navigation-sim.
|
||||
# It installs under the package name `rsl_rl`, replacing any prior install.
|
||||
RUN ${ISAACLAB_PATH}/isaaclab.sh -p -m pip uninstall rsl-rl-lib -y || true
|
||||
RUN rm -rf ${ISAACLAB_PATH}/_isaac_sim/kit/python/lib/python3.10/site-packages/rsl_rl
|
||||
WORKDIR /workspace
|
||||
RUN for i in 1 2 3 4 5; do \
|
||||
git clone --depth 1 https://github.com/leggedrobotics/sru-navigation-learning.git /workspace/rsl_rl && break; \
|
||||
echo "[retry $i] sru-navigation-learning clone failed, retrying in 10s..."; \
|
||||
rm -rf /workspace/rsl_rl; \
|
||||
sleep 10; \
|
||||
done && test -d /workspace/rsl_rl/.git
|
||||
RUN ${ISAACLAB_PATH}/isaaclab.sh -p -m pip install --no-build-isolation --timeout 180 --retries 5 -e /workspace/rsl_rl
|
||||
RUN ${ISAACLAB_PATH}/_isaac_sim/python.sh -c "from rsl_rl.modules import ActorCriticSRU; print('SRU OK')"
|
||||
|
||||
# ---------- Clone & install sru-navigation-sim extension ----------
|
||||
ARG SRU_NAV_REPO=https://github.com/leggedrobotics/sru-navigation-sim.git
|
||||
ARG SRU_NAV_REF=main
|
||||
# Note: git network hardening already applied above (postBuffer / lowSpeedTime /
|
||||
# HTTP/1.1 / optional GITHUB_MIRROR), so this block only retries.
|
||||
RUN for i in 1 2 3 4 5; do \
|
||||
git clone --depth 1 --branch ${SRU_NAV_REF} \
|
||||
${SRU_NAV_REPO} ${ISAACLAB_PATH}/source/isaaclab_nav_task && break; \
|
||||
echo "[retry $i] sru-navigation-sim clone failed, cleaning up and retrying in 10s..."; \
|
||||
rm -rf ${ISAACLAB_PATH}/source/isaaclab_nav_task; \
|
||||
sleep 10; \
|
||||
done && \
|
||||
test -d ${ISAACLAB_PATH}/source/isaaclab_nav_task
|
||||
RUN ${ISAACLAB_PATH}/isaaclab.sh -p -m pip install -e \
|
||||
${ISAACLAB_PATH}/source/isaaclab_nav_task
|
||||
|
||||
# Useful Python packages for logging/visualization
|
||||
RUN ${ISAACLAB_PATH}/isaaclab.sh -p -m pip install \
|
||||
wandb tensorboard tensorboardX
|
||||
|
||||
# Common runtime envs
|
||||
ENV PYTHONUNBUFFERED=1 \
|
||||
NVIDIA_DRIVER_CAPABILITIES=all \
|
||||
NVIDIA_VISIBLE_DEVICES=all
|
||||
|
||||
WORKDIR ${ISAACLAB_PATH}
|
||||
|
||||
# Sanity check (non-fatal): list registered tasks
|
||||
RUN ${ISAACLAB_PATH}/isaaclab.sh -p -m pip show isaaclab_nav_task || true
|
||||
|
||||
CMD ["/bin/bash"]
|
||||
@@ -0,0 +1,248 @@
|
||||
# 🤖 SRU Navigation Training with Isaac Sim
|
||||
|
||||
**Reproducible training pipeline for SRU (Spatially-Enhanced Recurrent Units) navigation policy, ported from B2W (wheeled-legged + ZedX depth) to Unitree Go2 (quadruped + LiDAR-derived depth).**
|
||||
|
||||
Built on NVIDIA Isaac Sim 4.5.0 + IsaacLab v2.1.1, fully containerized with Docker.
|
||||
|
||||
[](https://developer.nvidia.com/isaac-sim)
|
||||
[](https://github.com/isaac-sim/IsaacLab)
|
||||
[](https://www.docker.com/)
|
||||
|
||||
---
|
||||
|
||||
## ✨ Highlights
|
||||
|
||||
- **Full B2W → Go2 port** — assets, cameras, terrain, rewards, termination conditions
|
||||
- **4-stage training pipeline** — Smoke → Cold-start (1024 envs, 30k iter) → Curriculum continuation → PureMaze refinement
|
||||
- **Evaluation toolchain** — termination rate stats, baseline comparison, collision analysis, depth ablation
|
||||
- **Env-var driven config** — difficulty, terrain, GPU selection, seed — no code edits needed
|
||||
- **Multi-GPU parallel training** — independent seeds across GPUs
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ Architecture
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ Docker Container (~30GB) │
|
||||
│ │
|
||||
│ ┌───────────────┐ ┌──────────────────────────────────┐ │
|
||||
│ │ Isaac Sim │ │ IsaacLab v2.1.1 │ │
|
||||
│ │ 4.5.0 │ │ ┌────────────┐ ┌─────────────┐ │ │
|
||||
│ └───────┬───────┘ │ │ Nav Task │ │ rsl_rl │ │ │
|
||||
│ │ │ │ (Go2 Port) │ │ (SRU Fork) │ │ │
|
||||
│ ▼ │ └─────┬──────┘ └──────┬──────┘ │ │
|
||||
│ ┌───────────────┐ │ │ │ │ │
|
||||
│ │ PhysX / GPU │ │ ▼ ▼ │ │
|
||||
│ │ Simulation │◄──┤ ┌──────────────────────────┐ │ │
|
||||
│ └───────────────┘ │ │ PPO + ActorCriticSRU │ │ │
|
||||
│ │ └──────────────────────────┘ │ │
|
||||
│ └──────────────────────────────────┘ │
|
||||
│ │
|
||||
│ Depth → VAE Encoder (64×5×8) → SRU Policy → SE2 cmd │
|
||||
│ ↓ │
|
||||
│ policy_go2_jit.pt → Joint Actions │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📋 Prerequisites
|
||||
|
||||
| Requirement | Minimum | Recommended |
|
||||
|---|---|---|
|
||||
| NVIDIA GPU | 12 GB VRAM | 24 GB+ |
|
||||
| NVIDIA Driver | ≥ 570 | ≥ 570 (⚠️ avoid 595.x) |
|
||||
| Docker | 24.0+ | Latest |
|
||||
| NVIDIA Container Toolkit | Installed | Latest |
|
||||
| Disk Space | 80 GB | 120 GB+ |
|
||||
| NGC Access | Required | For `nvcr.io/nvidia/isaac-sim:4.5.0` |
|
||||
|
||||
### VRAM Reference
|
||||
|
||||
| GPU | NUM_ENVS | GO2_CELL_SIZE |
|
||||
|---|---|---|
|
||||
| RTX 5070 12 GB | 768–1024 | 1.0 |
|
||||
| RTX 4090 24 GB | 2048–2820 | 1.0 / 2.0 |
|
||||
| A100 80 GB | 8000+ | 1.0 / 2.0 |
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
### 1. Clone & Configure
|
||||
|
||||
```bash
|
||||
git clone https://github.com/<your-org>/sru-nav-docker.git
|
||||
cd sru-nav-docker
|
||||
cp .env.example .env
|
||||
# Edit .env — set NGC credentials, GPU index, paths
|
||||
```
|
||||
|
||||
### 2. Build the Image
|
||||
|
||||
```bash
|
||||
docker compose build # ~30 GB, takes 20-40 min on first build
|
||||
```
|
||||
|
||||
### 3. Launch Container
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
docker compose exec sru-nav bash
|
||||
```
|
||||
|
||||
### 4. Smoke Test (~30 min)
|
||||
|
||||
```bash
|
||||
TASK=Isaac-Nav-PPO-Go2-Dev-v0 NUM_ENVS=24 MAX_ITER=300 \
|
||||
GO2_DIFFICULTY="0.0,0.4" GO2_INIT_LEVEL=0 \
|
||||
./scripts/train_go2_scratch.sh
|
||||
```
|
||||
|
||||
If training starts and loss decreases — you're good to go.
|
||||
|
||||
---
|
||||
|
||||
## 🏋️ Training Pipeline
|
||||
|
||||
### Stage 1 — Cold Start (36–48h)
|
||||
|
||||
```bash
|
||||
TASK=Isaac-Nav-PPO-Go2-v0 NUM_ENVS=1024 MAX_ITER=30000 \
|
||||
GO2_DIFFICULTY="0.0,0.4" GO2_INIT_LEVEL=0 GO2_CELL_SIZE=1.0 \
|
||||
SEED=42 RUN_NAME=mixed_scratch_v1 \
|
||||
./scripts/train_go2_scratch.sh
|
||||
```
|
||||
|
||||
### Stage 2 — Curriculum Continuation
|
||||
|
||||
```bash
|
||||
./scripts/continue_go2.sh --iters 10000 --from-iter 7400
|
||||
```
|
||||
|
||||
### Stage 3 — PureMaze Refinement
|
||||
|
||||
```bash
|
||||
TASK=Isaac-Nav-PPO-Go2-PureMaze-v0 NUM_ENVS=1024 MAX_ITER=10000 \
|
||||
./scripts/train_go2_scratch.sh
|
||||
```
|
||||
|
||||
### Evaluation
|
||||
|
||||
```bash
|
||||
# Termination rate analysis
|
||||
PLAY_DIFFICULTY="0.3,0.8" ./scripts/eval_terminations.sh --run-dir <run> --from-iter <iter>
|
||||
|
||||
# Baseline comparison
|
||||
./scripts/compare_baselines.sh
|
||||
|
||||
# Collision analysis
|
||||
./scripts/analyze_collisions.sh
|
||||
```
|
||||
|
||||
### Monitoring
|
||||
|
||||
```bash
|
||||
# TensorBoard
|
||||
docker compose exec sru-nav ./isaaclab.sh -p -m tensorboard.main --logdir logs --bind_all
|
||||
|
||||
# Or use Weights & Biases (configure WANDB_API_KEY in .env)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ⚙️ Configuration
|
||||
|
||||
All training behavior is controlled via environment variables — no code changes needed.
|
||||
|
||||
| Variable | Type | Default | Description |
|
||||
|---|---|---|---|
|
||||
| `TASK` | str | `Isaac-Nav-PPO-Go2-Dev-v0` | Gym task ID |
|
||||
| `NUM_ENVS` | int | `24` | Parallel environment count |
|
||||
| `MAX_ITER` | int | `1000` | Max PPO iterations |
|
||||
| `SEED` | int | `42` | Random seed |
|
||||
| `GPU` | str | — | GPU device index |
|
||||
| `RUN_NAME` | str | auto | Run directory name |
|
||||
| `GO2_DIFFICULTY` | `"lo,hi"` | cfg default | Difficulty range |
|
||||
| `GO2_INIT_LEVEL` | int | `5` | Initial max terrain row |
|
||||
| `GO2_CELL_SIZE` | float | `1.0` | Terrain tile cell size (m) |
|
||||
| `PLAY_DIFFICULTY` | `"lo,hi"` | — | Eval-time difficulty override |
|
||||
|
||||
### Gym Tasks
|
||||
|
||||
| Task ID | Purpose | Typical envs |
|
||||
|---|---|---|
|
||||
| `Isaac-Nav-PPO-Go2-v0` | Cold-start training (mixed terrain) | 1024–2048 |
|
||||
| `Isaac-Nav-PPO-Go2-Dev-v0` | Smoke test / debugging | 24–32 |
|
||||
| `Isaac-Nav-PPO-Go2-PureMaze-v0` | Stage-2 maze refinement | 1024 |
|
||||
| `Isaac-Nav-PPO-Go2-Play-v0` | Playback & evaluation | 20 |
|
||||
|
||||
---
|
||||
|
||||
## 📁 Project Structure
|
||||
|
||||
```
|
||||
sru-nav-docker/
|
||||
├── Dockerfile # Image build recipe
|
||||
├── docker-compose.yml # Container runtime config
|
||||
├── .env.example # Environment variable template
|
||||
├── scripts/ # Train / continue / play / eval / diagnostics
|
||||
│ ├── train_go2_scratch.sh
|
||||
│ ├── continue_go2.sh
|
||||
│ ├── eval_terminations.sh
|
||||
│ ├── compare_baselines.sh
|
||||
│ └── ...
|
||||
├── mount/
|
||||
│ ├── sru-navigation-sim/ # Task definitions + Go2 port
|
||||
│ │ ├── isaaclab_nav_task/ # Env, rewards, terrain, obs
|
||||
│ │ └── scripts/ # Entry points
|
||||
│ └── rsl_rl/ # rsl_rl SRU fork (ActorCriticSRU, PPO)
|
||||
├── IsaacLab/ # IsaacLab v2.1.1 source
|
||||
├── assets/baselines/ # Pre-trained baseline checkpoints
|
||||
├── outputs/logs/ # Training artifacts (TB + ckpt)
|
||||
└── docs/handover/ # Handover documentation
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔑 Key Dependencies
|
||||
|
||||
| Dependency | Source |
|
||||
|---|---|
|
||||
| Isaac Sim 4.5.0 | `nvcr.io/nvidia/isaac-sim:4.5.0` (NGC login required) |
|
||||
| IsaacLab v2.1.1 | [isaac-sim/IsaacLab](https://github.com/isaac-sim/IsaacLab) |
|
||||
| rsl_rl (SRU fork) | [leggedrobotics/sru-navigation-learning](https://github.com/leggedrobotics/sru-navigation-learning) |
|
||||
| Nav Task | [leggedrobotics/sru-navigation-sim](https://github.com/leggedrobotics/sru-navigation-sim) |
|
||||
|
||||
---
|
||||
|
||||
## 📖 Citation
|
||||
|
||||
If you use this work, please cite the original SRU navigation paper:
|
||||
|
||||
```bibtex
|
||||
@article{yang2025sru,
|
||||
author = {Yang, Fan and Frivik, Per and Hoeller, David and Wang, Chen and Cadena, Cesar and Hutter, Marco},
|
||||
title = {Spatially-enhanced recurrent memory for long-range mapless navigation via end-to-end reinforcement learning},
|
||||
journal = {The International Journal of Robotics Research},
|
||||
year = {2025},
|
||||
doi = {10.1177/02783649251401926},
|
||||
url = {https://doi.org/10.1177/02783649251401926}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🙏 Acknowledgments
|
||||
|
||||
- **[ETH Legged Robotics](https://rsl.ethz.ch/)** — SRU navigation (original paper & codebase)
|
||||
- **[NVIDIA Isaac Sim / IsaacLab](https://developer.nvidia.com/isaac-sim)** — Simulation platform
|
||||
- **[Unitree Robotics](https://www.unitree.com/)** — Go2 quadruped platform
|
||||
|
||||
---
|
||||
|
||||
## 📄 License
|
||||
|
||||
See [LICENSE](./LICENSE) in the repository root.
|
||||
Sub-components (IsaacLab, rsl_rl) retain their respective licenses.
|
||||
@@ -0,0 +1,75 @@
|
||||
services:
|
||||
sru-nav:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
args:
|
||||
ISAAC_SIM_VERSION: "4.5.0"
|
||||
ISAACLAB_VERSION: "v2.1.1"
|
||||
SRU_NAV_REPO: "https://github.com/leggedrobotics/sru-navigation-sim.git"
|
||||
SRU_NAV_REF: "main"
|
||||
# Optional, for CN servers behind GFW. Pass via env or shell:
|
||||
# GITHUB_MIRROR=https://ghproxy.com/ docker compose build
|
||||
# HTTP_PROXY=http://host:7890 HTTPS_PROXY=http://host:7890 docker compose build
|
||||
GITHUB_MIRROR: "${GITHUB_MIRROR:-}"
|
||||
HTTP_PROXY: "${HTTP_PROXY:-}"
|
||||
HTTPS_PROXY: "${HTTPS_PROXY:-}"
|
||||
NO_PROXY: "${NO_PROXY:-}"
|
||||
PIP_INDEX_URL: "${PIP_INDEX_URL:-}"
|
||||
PIP_TRUSTED_HOST: "${PIP_TRUSTED_HOST:-}"
|
||||
image: sru-nav:latest
|
||||
container_name: sru-nav
|
||||
runtime: nvidia
|
||||
stdin_open: true
|
||||
tty: true
|
||||
network_mode: host
|
||||
ipc: host
|
||||
shm_size: "16gb"
|
||||
ulimits:
|
||||
memlock: -1
|
||||
stack: 67108864
|
||||
environment:
|
||||
- ACCEPT_EULA=Y
|
||||
- PRIVACY_CONSENT=Y
|
||||
- DISPLAY=${DISPLAY:-:0}
|
||||
- NVIDIA_DRIVER_CAPABILITIES=all
|
||||
- NVIDIA_VISIBLE_DEVICES=all
|
||||
# Attempt to avoid RTX segfault on Blackwell (sm_120) by forcing true headless
|
||||
- OMNI_KIT_HEADLESS=1
|
||||
# Optional: put your wandb key in a .env file next to compose
|
||||
- WANDB_API_KEY=${WANDB_API_KEY:-}
|
||||
deploy:
|
||||
resources:
|
||||
reservations:
|
||||
devices:
|
||||
- driver: nvidia
|
||||
count: all
|
||||
capabilities: [gpu]
|
||||
volumes:
|
||||
# X11 for GUI (optional)
|
||||
- /tmp/.X11-unix:/tmp/.X11-unix:rw
|
||||
# Persist Isaac Sim caches across runs
|
||||
- isaac-cache-kit:/isaac-sim/kit/cache
|
||||
- isaac-cache-ov:/root/.cache/ov
|
||||
- isaac-cache-pip:/root/.cache/pip
|
||||
- isaac-cache-gl:/root/.cache/nvidia/GLCache
|
||||
- isaac-cache-compute:/root/.nv/ComputeCache
|
||||
- isaac-logs:/root/.nvidia-omniverse/logs
|
||||
- isaac-data:/root/.local/share/ov/data
|
||||
- isaac-docs:/root/Documents
|
||||
# Persist training outputs (logs/checkpoints)
|
||||
- ./outputs/logs:/workspace/IsaacLab/logs
|
||||
# Optional: live-mount the extension for development. Uncomment to use:
|
||||
# - ./sru-navigation-sim:/workspace/IsaacLab/source/isaaclab_nav_task
|
||||
working_dir: /workspace/IsaacLab
|
||||
command: /bin/bash
|
||||
|
||||
volumes:
|
||||
isaac-cache-kit:
|
||||
isaac-cache-ov:
|
||||
isaac-cache-pip:
|
||||
isaac-cache-gl:
|
||||
isaac-cache-compute:
|
||||
isaac-logs:
|
||||
isaac-data:
|
||||
isaac-docs:
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2025 Fan Yang, Per Frivik, Robotic Systems Lab, ETH Zurich
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
|
||||
# Note: Semantic Versioning is used: https://semver.org/
|
||||
version = "0.1.0"
|
||||
|
||||
# Description
|
||||
title = "IsaacLab Navigation Extension - SRU Project"
|
||||
description = "IsaacLab task extension for SRU visual navigation with hierarchical control, maze terrain generation, and depth-based RL."
|
||||
readme = "docs/README.md"
|
||||
repository = "https://github.com/michaelfyang/sru-pytorch-spatial-learning"
|
||||
category = "robotics"
|
||||
keywords = ["robotics", "rl", "navigation", "visual", "learning", "sru", "depth", "hierarchical", "maze", "isaaclab"]
|
||||
|
||||
[dependencies]
|
||||
"isaaclab" = {}
|
||||
"isaaclab_assets" = {}
|
||||
|
||||
[core]
|
||||
reloadable = false
|
||||
|
||||
[[python.module]]
|
||||
name = "isaaclab_nav_task"
|
||||
@@ -0,0 +1,482 @@
|
||||
# IsaacLab Navigation Extension - SRU Project
|
||||
|
||||
[](https://journals.sagepub.com/home/ijr)
|
||||
[](https://michaelfyang.github.io/sru-project-website/)
|
||||
|
||||
> **📌 Important Note**: This repository contains the **IsaacLab task extension** for the SRU project, providing diverse navigation environments with dynamic obstacle configurations and terrain variations. This repository does **not** include the `rsl_rl` learning module (network architectures, PPO/MDPO training algorithms). See the [project website](https://michaelfyang.github.io/sru-project-website/) for the complete navigation system.
|
||||
|
||||
## Overview
|
||||
|
||||
A standalone, self-contained IsaacLab task extension for visual navigation in Isaac Lab v2.1.1 (Isaac Sim 4.5). This repository provides:
|
||||
|
||||
- **Environment**: Diverse navigation environments in IsaacLab with dynamic obstacle configurations and terrain variations
|
||||
- **Task Definition**: Hierarchical control architecture interface for visual navigation with reinforcement learning
|
||||
- **Simulation**: High-fidelity physics simulation with realistic depth sensor noise
|
||||
|
||||
**Note**: This repository focuses on the simulation environment and task definition. The RL training infrastructure (neural network architectures, PPO/MDPO algorithms) is provided by the separate `rsl_rl` learning module.
|
||||
|
||||
This extension implements a hierarchical control architecture for visual navigation:
|
||||
- **High-level policy**: Learns to output SE2 velocity commands (vx, vy, omega) at 5Hz
|
||||
- **Low-level policy**: Pre-trained locomotion policy that converts velocity commands to joint actions at 50Hz
|
||||
|
||||
The extension is fully self-contained with all necessary robot models, materials, and pre-trained locomotion policies included.
|
||||
|
||||
### What's Included
|
||||
|
||||
- ✅ IsaacLab task extension for visual navigation environments
|
||||
- ✅ Maze terrain generation with curriculum learning
|
||||
- ✅ Self-contained assets: Robot models (USD), locomotion policies, depth encoders
|
||||
- ✅ Multiple robot platforms: B2W (bipedal wheeled) and AoW-D (Anymal on Wheels)
|
||||
- ✅ Observation definitions: Depth images, proprioception, goal commands
|
||||
- ✅ Reward functions: Goal reaching, action smoothing, movement penalties
|
||||
- ✅ Hierarchical action interface: SE2 velocity commands to low-level controllers
|
||||
- ✅ Domain randomization: Camera pose, action scaling, low-pass filters, sensor delays
|
||||
- ✅ Training scripts compatible with RSL-RL (PPO/MDPO algorithms)
|
||||
|
||||
### What's NOT Included
|
||||
|
||||
- ❌ `rsl_rl` learning module (network architectures, PPO/MDPO training algorithms)
|
||||
- ❌ Neural network structures for high-level navigation policy
|
||||
- ❌ On-policy RL training algorithms (PPO/MDPO implementations)
|
||||
|
||||
**Note**: The `rsl_rl` package must be installed separately to train navigation policies. See the Installation section below.
|
||||
|
||||
### Related Projects
|
||||
|
||||
- [sru-pytorch-spatial-learning](https://github.com/michaelfyang/sru-pytorch-spatial-learning) - Core SRU architecture
|
||||
- [SRU Project Website](https://michaelfyang.github.io/sru-project-website/) - Complete navigation system
|
||||
|
||||
## Features
|
||||
|
||||
- **Visual navigation** using depth cameras with realistic noise simulation
|
||||
- **Maze terrain generation** with curriculum learning
|
||||
- **Self-contained assets**: All robot models and locomotion policies included
|
||||
- **Multiple robot platforms**:
|
||||
- **B2W**: Bipedal wheeled robot (with ZedX camera)
|
||||
- **AoW-D**: Anymal on Wheels (with ZedX camera)
|
||||
- **Asymmetric actor-critic** with privileged critic observations
|
||||
- **Curriculum learning** for terrain difficulty progression
|
||||
- **Multiple algorithms**: MDPO and PPO support via RSL-RL
|
||||
- **Domain randomization**: Camera pose, action scaling, low-pass filters, sensor delays
|
||||
|
||||
## Installation
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Isaac Lab v2.1.1 installed and configured
|
||||
- Isaac Sim 4.5.0
|
||||
- Python 3.10
|
||||
- PyTorch >= 2.5.1
|
||||
|
||||
### Step 1: Clone or Place the Extension
|
||||
|
||||
This extension should be placed in the `source/` directory of your IsaacLab installation:
|
||||
|
||||
```bash
|
||||
# Navigate to your IsaacLab installation
|
||||
cd /path/to/IsaacLab
|
||||
|
||||
# If cloning this repository separately, place it in source/
|
||||
# Your directory structure should look like:
|
||||
# IsaacLab/
|
||||
# ├── source/
|
||||
# │ ├── isaaclab/
|
||||
# │ ├── isaaclab_assets/
|
||||
# │ └── isaaclab_nav_task/ <- This extension
|
||||
```
|
||||
|
||||
### Step 2: Install the Extension
|
||||
|
||||
Install the extension in development mode from the IsaacLab root directory:
|
||||
|
||||
```bash
|
||||
# From IsaacLab root directory
|
||||
./isaaclab.sh -p -m pip install -e source/isaaclab_nav_task
|
||||
|
||||
# Or navigate to the extension directory
|
||||
cd source/isaaclab_nav_task
|
||||
../../isaaclab.sh -p -m pip install -e .
|
||||
```
|
||||
|
||||
### Step 3: Install RSL-RL (Required for Training)
|
||||
|
||||
This extension requires the `rsl_rl` package for training. Install the custom version with MDPO/PPO algorithms:
|
||||
|
||||
```bash
|
||||
# Clone and install custom rsl_rl (if not already installed)
|
||||
cd /path/to/your/workspace
|
||||
git clone https://github.com/leggedrobotics/rsl_rl.git
|
||||
cd rsl_rl
|
||||
pip install -e .
|
||||
```
|
||||
|
||||
### Verify Installation
|
||||
|
||||
Test that the extension is properly installed:
|
||||
|
||||
```bash
|
||||
# From IsaacLab root directory
|
||||
./isaaclab.sh -p -m pip show isaaclab_nav_task
|
||||
|
||||
# List available tasks
|
||||
./isaaclab.sh -p source/isaaclab_nav_task/scripts/train.py --help
|
||||
```
|
||||
|
||||
You should see the task IDs listed (e.g., `Isaac-Nav-MDPO-B2W-v0`, `Isaac-Nav-PPO-AoW-D-v0`, etc.).
|
||||
|
||||
## Available Tasks
|
||||
|
||||
### B2W
|
||||
| Task ID | Description |
|
||||
|---------|-------------|
|
||||
| `Isaac-Nav-MDPO-B2W-v0` | MDPO training |
|
||||
| `Isaac-Nav-PPO-B2W-v0` | PPO training |
|
||||
| `Isaac-Nav-MDPO-B2W-Play-v0` | MDPO playback |
|
||||
| `Isaac-Nav-PPO-B2W-Play-v0` | PPO playback |
|
||||
| `Isaac-Nav-MDPO-B2W-Dev-v0` | MDPO development |
|
||||
| `Isaac-Nav-PPO-B2W-Dev-v0` | PPO development |
|
||||
|
||||
### AoW-D
|
||||
| Task ID | Description |
|
||||
|---------|-------------|
|
||||
| `Isaac-Nav-MDPO-AoW-D-v0` | MDPO training |
|
||||
| `Isaac-Nav-PPO-AoW-D-v0` | PPO training |
|
||||
| `Isaac-Nav-MDPO-AoW-D-Play-v0` | MDPO playback |
|
||||
| `Isaac-Nav-PPO-AoW-D-Play-v0` | PPO playback |
|
||||
| `Isaac-Nav-MDPO-AoW-D-Dev-v0` | MDPO development |
|
||||
| `Isaac-Nav-PPO-AoW-D-Dev-v0` | PPO development |
|
||||
|
||||
## Training
|
||||
|
||||
### Using the standalone training script
|
||||
|
||||
```bash
|
||||
# Train B2W with PPO
|
||||
./isaaclab.sh -p source/isaaclab_nav_task/scripts/train.py \
|
||||
--task Isaac-Nav-PPO-B2W-v0 --num_envs 4096 --headless
|
||||
|
||||
# Train AoW-D with PPO
|
||||
./isaaclab.sh -p source/isaaclab_nav_task/scripts/train.py \
|
||||
--task Isaac-Nav-PPO-AoW-D-v0 --num_envs 4096 --headless
|
||||
|
||||
# Train with custom wandb run name
|
||||
./isaaclab.sh -p source/isaaclab_nav_task/scripts/train.py \
|
||||
--task Isaac-Nav-MDPO-B2W-v0 --num_envs 4096 --headless \
|
||||
--run_name "experiment_v1_with_curriculum"
|
||||
|
||||
# Train with multiple custom parameters
|
||||
./isaaclab.sh -p source/isaaclab_nav_task/scripts/train.py \
|
||||
--task Isaac-Nav-PPO-B2W-v0 --num_envs 2048 --headless \
|
||||
--run_name "large_training_run" --seed 42 --max_iterations 20000
|
||||
```
|
||||
|
||||
### Development/Testing (smaller config with tensorboard)
|
||||
|
||||
The `-Dev-v0` variants use tensorboard logging instead of wandb and have reduced iterations (300 vs 15000) for quick testing:
|
||||
|
||||
```bash
|
||||
# Quick test with small environment count
|
||||
./isaaclab.sh -p source/isaaclab_nav_task/scripts/train.py \
|
||||
--task Isaac-Nav-PPO-B2W-Dev-v0 --num_envs 32 --headless
|
||||
```
|
||||
|
||||
### Using the standard RSL-RL workflow
|
||||
|
||||
```bash
|
||||
# Train with RSL-RL
|
||||
./isaaclab.sh -p source/standalone/workflows/rsl_rl/train.py \
|
||||
--task Isaac-Nav-MDPO-B2W-v0 --num_envs 4096
|
||||
```
|
||||
|
||||
## Playing Trained Policies
|
||||
|
||||
```bash
|
||||
# Play using standalone script
|
||||
./isaaclab.sh -p source/isaaclab_nav_task/scripts/play.py \
|
||||
--task Isaac-Nav-MDPO-B2W-Play-v0 --num_envs 16
|
||||
|
||||
# Play with specific checkpoint
|
||||
./isaaclab.sh -p source/isaaclab_nav_task/scripts/play.py \
|
||||
--task Isaac-Nav-MDPO-B2W-Play-v0 \
|
||||
--checkpoint /path/to/model.pt
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
isaaclab_nav_task/
|
||||
├── config/
|
||||
│ └── extension.toml # Extension metadata
|
||||
├── docs/
|
||||
│ └── README.md # This file
|
||||
├── scripts/
|
||||
│ ├── train.py # Training script
|
||||
│ └── play.py # Playback script
|
||||
├── setup.py # Installation script
|
||||
├── pyproject.toml # Build configuration
|
||||
└── isaaclab_nav_task/
|
||||
├── __init__.py # Extension entry point
|
||||
└── navigation/
|
||||
├── __init__.py
|
||||
├── navigation_env_cfg.py # Base environment config
|
||||
├── assets/ # Robot configurations and data
|
||||
│ ├── __init__.py
|
||||
│ ├── b2w.py # B2W robot config
|
||||
│ ├── aow_d.py # AoW-D robot config
|
||||
│ └── data/ # Self-contained asset directory
|
||||
│ ├── Robots/ # Robot USD models and materials
|
||||
│ │ └── AoW-D/ # AoW-D robot assets
|
||||
│ │ ├── aow_d.usd # Robot USD model
|
||||
│ │ └── Props/ # Materials and textures
|
||||
│ └── Policies/ # Pre-trained models
|
||||
│ ├── depth_encoder/ # VAE depth encoders
|
||||
│ │ └── vae_pretrain_new.pth (ZedX)
|
||||
│ └── locomotion/ # Low-level locomotion policies
|
||||
│ ├── aow_d/ # policy_blind_3_1.pt (1.7 MB)
|
||||
│ └── b2w/ # policy_b2w_new_2.pt (2.0 MB)
|
||||
├── config/
|
||||
│ ├── rl_cfg.py # Base RL configurations
|
||||
│ ├── b2w/
|
||||
│ │ ├── __init__.py # Task registration
|
||||
│ │ ├── navigation_env_cfg.py
|
||||
│ │ └── agents/
|
||||
│ │ └── rsl_rl_cfg.py
|
||||
│ └── aow_d/
|
||||
│ ├── __init__.py
|
||||
│ ├── navigation_env_cfg.py
|
||||
│ └── agents/
|
||||
│ └── rsl_rl_cfg.py
|
||||
├── mdp/
|
||||
│ ├── observations.py # Observation functions (13 functions)
|
||||
│ ├── rewards.py # Reward functions (5 functions)
|
||||
│ ├── terminations.py # Termination conditions (4 functions)
|
||||
│ ├── curriculums.py # Curriculum terms (1 function)
|
||||
│ ├── events.py # Domain randomization events (5 functions)
|
||||
│ ├── depth_utils/ # Depth processing utilities
|
||||
│ │ ├── __init__.py
|
||||
│ │ ├── camera_config.py # Camera configurations (ZedX)
|
||||
│ │ └── depth_noise_encoder.py # VAE-based depth encoder
|
||||
│ └── navigation/
|
||||
│ ├── goal_commands.py
|
||||
│ ├── goal_commands_cfg.py
|
||||
│ └── actions/
|
||||
│ ├── __init__.py
|
||||
│ ├── navigation_se2_actions.py
|
||||
│ └── navigation_se2_actions_cfg.py
|
||||
└── terrains/ # Custom terrain generators
|
||||
├── __init__.py
|
||||
├── hf_terrains_maze.py # Maze terrain generation
|
||||
├── hf_terrains_maze_cfg.py # Maze terrain configs
|
||||
├── maze_config.py # Maze parameters
|
||||
└── patches.py # TerrainImporter patches
|
||||
```
|
||||
|
||||
## Compatibility
|
||||
|
||||
- **Isaac Lab**: v2.1.1
|
||||
- **Isaac Sim**: 4.5.0
|
||||
- **Python**: 3.10
|
||||
- **PyTorch**: >= 2.5.1
|
||||
|
||||
## Self-Contained Assets
|
||||
|
||||
The extension includes all necessary assets and does not depend on external asset repositories:
|
||||
|
||||
### Robot Models (`assets/data/Robots/`)
|
||||
- **AoW-D**: Complete USD model with materials and textures
|
||||
- Used when AoW-D robots are not available in the base `isaaclab_assets`
|
||||
- Includes all necessary Props and material textures (11 baked textures)
|
||||
|
||||
### Pre-trained Policies (`assets/data/Policies/`)
|
||||
|
||||
**Depth Encoders** (`depth_encoder/`):
|
||||
- `vae_pretrain_new.pth`: ZedX camera encoder for B2W and AoW-D
|
||||
- VAE architecture with RegNet backbone + Feature Pyramid Network
|
||||
|
||||
**Locomotion Policies** (`locomotion/`):
|
||||
- `aow_d/policy_blind_3_1.pt` (1.7 MB): AoW-D wheeled locomotion
|
||||
- `b2w/policy_b2w_new_2.pt` (2.0 MB): B2W bipedal wheeled locomotion
|
||||
|
||||
All locomotion policies are pre-trained and loaded by the hierarchical action controller.
|
||||
|
||||
## Key Components
|
||||
|
||||
### Navigation Environment (`navigation_env_cfg.py`)
|
||||
- Defines the scene with terrain, robot, and sensors
|
||||
- Configures observation groups for policy and critic
|
||||
- Sets up reward terms for goal reaching and movement penalties
|
||||
- Configures curriculum for terrain difficulty
|
||||
|
||||
### MDP Components (`mdp/`)
|
||||
|
||||
**Cleaned and optimized** - removed unused functions to improve maintainability:
|
||||
|
||||
- **observations.py** (13 functions): Depth image processing, proprioception, goal direction, delay buffers
|
||||
- **rewards.py** (5 functions): Goal reaching, action smoothing, movement penalties
|
||||
- **terminations.py** (4 functions): Timeout, collision detection, angle limits, goal reaching
|
||||
- **curriculums.py** (1 function): Backward movement penalty scheduling
|
||||
- **events.py** (5 functions): Camera randomization, action scaling, delay buffer management
|
||||
|
||||
### Navigation Actions (`mdp/navigation/actions/`)
|
||||
- Hierarchical action space with SE2 velocity commands
|
||||
- Integration with pre-trained low-level locomotion policies
|
||||
|
||||
### Terrain Generation and Goal Sampling (`terrains/`)
|
||||
|
||||
The extension includes custom maze terrain generators built on Isaac Lab's terrain generation system, providing diverse navigation environments with safe goal and spawn position sampling.
|
||||
|
||||
**Key Features:**
|
||||
- **Four terrain types**: Maze, non-maze/random, stairs, and pits
|
||||
- **Curriculum learning**: 180 terrains organized in 6 difficulty levels
|
||||
- **Safe position sampling**: Separate padding for goals (0.5m) and spawns (0.6m)
|
||||
- **Mesh optimization**: ~80-99% vertex reduction for large-scale training
|
||||
- **Explicit boolean masks**: Pre-computed valid positions for efficient sampling
|
||||
|
||||
**Terrain Configuration:**
|
||||
- Grid: 6 rows (difficulty) × 30 columns (variations) = 180 terrains
|
||||
- Size: 30m × 30m per terrain with 0.1m resolution (300×300 cells)
|
||||
- Proportions: 30% maze, 20% random, 30% stairs, 20% pits
|
||||
|
||||
For detailed documentation on terrain generation, goal/spawn sampling, coordinate systems, and implementation details, see [TERRAIN_AND_GOALS.md](TERRAIN_AND_GOALS.md).
|
||||
|
||||
### Depth Processing (`mdp/depth_utils/`)
|
||||
- **DepthNoise**: Simulates realistic stereo camera noise using disparity-based filtering
|
||||
- **DepthNoiseEncoder**: VAE-based depth encoder using RegNet backbone with Feature Pyramid Network
|
||||
- **Camera Configurations**: Pre-defined configs for different camera types:
|
||||
|
||||
| Camera | Robots | Resolution | Depth Range | Encoder |
|
||||
|--------|--------|------------|-------------|---------|
|
||||
| ZedX | B2W, AoW-D | 64x40 | 0.25-10.0m | `vae_pretrain_new.pth` |
|
||||
|
||||
### Custom Robot Assets (`assets/`)
|
||||
|
||||
Robot configuration modules define robot-specific parameters:
|
||||
|
||||
**B2W** (`b2w.py`):
|
||||
- Actuator configurations (position/velocity control)
|
||||
- Initial joint states
|
||||
- USD asset path (from base `isaaclab_assets`)
|
||||
|
||||
**AoW-D** (`aow_d.py`):
|
||||
- Actuator configurations for wheeled quadruped
|
||||
- Initial joint states
|
||||
- USD asset path (from local `assets/data/Robots/AoW-D/`)
|
||||
- Uses local robot model when not available in base assets
|
||||
|
||||
Both configurations integrate seamlessly with the hierarchical navigation controller and pre-trained locomotion policies.
|
||||
|
||||
## Docker and Cluster Setup
|
||||
|
||||
### Docker Modifications
|
||||
|
||||
The Dockerfile includes:
|
||||
1. **Custom RSL-RL**: Installs custom `rsl_rl` package in editable mode
|
||||
2. **Git safe directories**: Prevents ownership errors in containers
|
||||
|
||||
### Quick Start Workflow
|
||||
|
||||
```bash
|
||||
# 1. Build Docker image
|
||||
./docker/container.sh start --suffix nav
|
||||
|
||||
# 2. Push to cluster (converts to Singularity automatically)
|
||||
./docker/cluster/cluster_interface.sh push base-nav
|
||||
|
||||
# 3. Submit training job
|
||||
./docker/cluster/cluster_interface.sh job base-nav \
|
||||
"--task Isaac-Nav-PPO-B2W-v0" \
|
||||
"--num_envs 2048" \
|
||||
"--max_iterations 10000" \
|
||||
"--headless"
|
||||
|
||||
# 4. Monitor job
|
||||
squeue -u $USER
|
||||
```
|
||||
|
||||
### Configuration
|
||||
|
||||
**Step 1**: Create `.env.base-nav` profile in `docker/` directory:
|
||||
```bash
|
||||
cp docker/.env.base docker/.env.base-nav
|
||||
```
|
||||
|
||||
**Step 2**: Configure `docker/cluster/.env.cluster` before deployment:
|
||||
- Set `CLUSTER_PYTHON_EXECUTABLE=source/isaaclab_nav_task/scripts/train.py`
|
||||
- Add cluster credentials and paths
|
||||
|
||||
**Step 3**: Add cluster-specific module loads in `docker/cluster/submit_job_slurm.sh`:
|
||||
```bash
|
||||
module load eth_proxy # Required for network access on ETH cluster
|
||||
```
|
||||
|
||||
See the [IsaacLab cluster guide](https://isaac-sim.github.io/IsaacLab/main/source/deployment/cluster.html#cluster-guide) for details.
|
||||
|
||||
### Training Examples
|
||||
|
||||
```bash
|
||||
# B2W with MDPO training (10k iterations)
|
||||
./docker/cluster/cluster_interface.sh job base-nav \
|
||||
"--task Isaac-Nav-MDPO-B2W-v0" \
|
||||
"--num_envs 2048" \
|
||||
"--max_iterations 10000" \
|
||||
"--headless"
|
||||
|
||||
# B2W with custom run name
|
||||
./docker/cluster/cluster_interface.sh job base-nav \
|
||||
"--task Isaac-Nav-MDPO-B2W-v0" \
|
||||
"--num_envs 2048" \
|
||||
"--max_iterations 10000" \
|
||||
"--run_name experiment_v1_b2w" \
|
||||
"--headless"
|
||||
|
||||
# AoW-D with MDPO training (10k iterations)
|
||||
./docker/cluster/cluster_interface.sh job base-nav \
|
||||
"--task Isaac-Nav-MDPO-AoW-D-v0" \
|
||||
"--num_envs 2048" \
|
||||
"--max_iterations 10000" \
|
||||
"--headless"
|
||||
|
||||
# Quick dev test with PPO training (300 iters, tensorboard)
|
||||
./docker/cluster/cluster_interface.sh job base-nav \
|
||||
"--task Isaac-Nav-PPO-B2W-Dev-v0" \
|
||||
"--num_envs 32" \
|
||||
"--headless"
|
||||
```
|
||||
|
||||
### Troubleshooting
|
||||
|
||||
**Git ownership errors**: Rebuild Docker image (includes fix) or run in container:
|
||||
```bash
|
||||
git config --global --add safe.directory '*'
|
||||
```
|
||||
|
||||
**Memory issues**: Reduce `--num_envs` or increase `#SBATCH --mem-per-cpu`
|
||||
|
||||
## License
|
||||
|
||||
MIT License - See [LICENSE](../LICENSE) file for details
|
||||
|
||||
Copyright (c) 2025 Fan Yang, Per Frivik, Robotic Systems Lab, ETH Zurich
|
||||
|
||||
## Citation
|
||||
|
||||
If you use this codebase in your research, please cite:
|
||||
|
||||
```bibtex
|
||||
@article{yang2025sru,
|
||||
author = {Yang, Fan and Frivik, Per and Hoeller, David and Wang, Chen and Cadena, Cesar and Hutter, Marco},
|
||||
title = {Spatially-enhanced recurrent memory for long-range mapless navigation via end-to-end reinforcement learning},
|
||||
journal = {The International Journal of Robotics Research},
|
||||
year = {2025},
|
||||
doi = {10.1177/02783649251401926},
|
||||
url = {https://doi.org/10.1177/02783649251401926}
|
||||
}
|
||||
```
|
||||
|
||||
## Contact
|
||||
|
||||
**Authors**:
|
||||
- Fan Yang (fanyang1@ethz.ch)
|
||||
- Per Frivik (pfrivik@ethz.ch)
|
||||
|
||||
**Affiliation**: Robotic Systems Lab, ETH Zurich
|
||||
@@ -0,0 +1,340 @@
|
||||
# Terrain Generation and Goal Sampling
|
||||
|
||||
This document provides detailed information about the terrain generation system and goal/spawn position sampling used in the SRU navigation simulation.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Terrain Generation System](#terrain-generation-system)
|
||||
- [Architecture Overview](#architecture-overview)
|
||||
- [Key Files](#key-files)
|
||||
- [Mesh Optimization](#mesh-optimization)
|
||||
- [Terrain Data Flow](#terrain-data-flow)
|
||||
- [Maze Terrain Types](#maze-terrain-types)
|
||||
- [Safety Padding](#safety-padding)
|
||||
- [Terrain Configuration](#terrain-configuration)
|
||||
- [Curriculum Learning](#curriculum-learning)
|
||||
- [Goal and Spawn Sampling](#goal-and-spawn-sampling)
|
||||
- [Architecture](#architecture)
|
||||
- [Key Features](#key-features)
|
||||
- [Coordinate System](#coordinate-system)
|
||||
- [Terrain Index Mapping](#terrain-index-mapping)
|
||||
- [Position Sampling](#position-sampling)
|
||||
- [Robot Spawn Height](#robot-spawn-height)
|
||||
|
||||
## Terrain Generation System
|
||||
|
||||
The extension includes custom maze terrain generators built on Isaac Lab's terrain generation system.
|
||||
|
||||
### Architecture Overview
|
||||
|
||||
```
|
||||
Terrain Generation Flow:
|
||||
┌────────────────────────────────────────────────────────────────────┐
|
||||
│ 1. HfMazeTerrainCfg │
|
||||
│ └─► maze_terrain() generates: │
|
||||
│ - heights: Height field for physics/rendering │
|
||||
│ - valid_mask: Valid goal positions (GOAL_PADDING=5 cells) │
|
||||
│ - spawn_mask: Valid spawn positions (SPAWN_PADDING=6 cells)│
|
||||
│ - platform_mask: Elevated platforms for curriculum │
|
||||
│ │
|
||||
│ 2. TerrainGenerator (patched) │
|
||||
│ └─► Collects height field data from all sub-terrains │
|
||||
│ └─► Concatenates into single tensors per attribute │
|
||||
│ │
|
||||
│ 3. TerrainImporter (patched) │
|
||||
│ └─► Stores on self._height_field_* attributes │
|
||||
│ │
|
||||
│ 4. RobotNavigationGoalCommand │
|
||||
│ └─► Reads from env.scene.terrain._height_field_* │
|
||||
│ └─► Creates PositionSampler with both masks │
|
||||
└────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Key Files
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `hf_terrains_maze.py` | Terrain generation with explicit valid_mask/spawn_mask |
|
||||
| `hf_terrains_maze_cfg.py` | Configuration dataclass (lines 41-51: mask storage attributes) |
|
||||
| `terrain_constants.py` | Constants: PADDING (5/6 cells), HEIGHTS (0/200/300), VERTICAL_SCALE (0.005) |
|
||||
| `patches.py` | Monkey-patches TerrainGenerator/TerrainImporter for mask storage |
|
||||
| `maze_config.py` | MAZE_TERRAIN_CFG with sub-terrain configurations |
|
||||
|
||||
### Mesh Optimization
|
||||
|
||||
The extension includes automatic mesh optimization that significantly reduces GPU memory usage when training with many environments. This is especially important for large-scale RL training (4096+ environments).
|
||||
|
||||
**How it works:**
|
||||
- Uses hierarchical block-based approach (20x20 → 10x10 → 5x5 blocks)
|
||||
- Flat terrain regions are simplified to just 2 triangles instead of full mesh detail
|
||||
- Non-flat regions recursively subdivide until 5x5 blocks, then generate detailed mesh
|
||||
- Applied automatically via monkey-patching when the extension is imported
|
||||
|
||||
**Memory Reduction:**
|
||||
| Terrain Type | Vertex Reduction |
|
||||
|--------------|------------------|
|
||||
| Flat terrain | ~99% |
|
||||
| Maze-like | ~89% |
|
||||
| Pits terrain | ~80% |
|
||||
| Mixed terrain | ~79% |
|
||||
|
||||
This optimization is transparent - it produces visually identical terrains while dramatically reducing the mesh vertex count. The patches are applied before any terrain generation occurs, ensuring all height-field terrains benefit from the optimization.
|
||||
|
||||
### Terrain Data Flow
|
||||
|
||||
The terrain system uses **explicit boolean masks** instead of height-based classification:
|
||||
|
||||
```python
|
||||
# During terrain generation (hf_terrains_maze.py)
|
||||
terrain = TerrainData.create(width, height) # Lines 57-63
|
||||
|
||||
# Mark obstacles as invalid
|
||||
terrain.set_obstacle(x_start, x_end, y_start, y_end, wall_height) # Lines 65-73
|
||||
|
||||
# Apply padding and create masks
|
||||
terrain.apply_padding(PADDING.GOAL_PADDING) # Lines 92-97: 5 cells = 0.5m for goals
|
||||
spawn_mask = terrain.create_spawn_mask(PADDING.SPAWN_PADDING) # Lines 99-104: 6 cells = 0.6m
|
||||
|
||||
# Store on config for patches to pick up
|
||||
cfg.height_field_visual = heights # For Z-lookup (terrain height)
|
||||
cfg.height_field_valid_mask = valid_mask # For goal sampling (5 cell padding)
|
||||
cfg.height_field_spawn_mask = spawn_mask # For spawn sampling (6 cell padding)
|
||||
cfg.height_field_platform_mask = platform_mask # For curriculum learning
|
||||
```
|
||||
|
||||
These masks are set in the maze terrain function and picked up by the patches system (patches.py:45-66), which stores them on `TerrainImporter` for access via `env.scene.terrain._height_field_*`.
|
||||
|
||||
### Maze Terrain Types
|
||||
|
||||
Four terrain types are available via `HfMazeTerrainCfg`:
|
||||
|
||||
1. **Maze** (`non_maze_terrain=False, stairs=False`)
|
||||
- DFS-generated maze with configurable wall openings
|
||||
- Random obstacle shapes (pillars, bars, crosses, blocks)
|
||||
- Optional stairs integration (`add_stairs_to_maze=True`)
|
||||
|
||||
2. **Non-Maze/Random** (`non_maze_terrain=True`)
|
||||
- Random obstacle placement (~15-35% coverage based on difficulty)
|
||||
- Good for testing navigation without maze structure
|
||||
|
||||
3. **Stairs** (`stairs=True`)
|
||||
- 3x3 stair/platform structures with 4 cardinal stairways
|
||||
- Elevated platforms marked for curriculum learning
|
||||
- Tests robot climbing capabilities
|
||||
|
||||
4. **Pits** (`dynamic_obstacles=True`)
|
||||
- Pit rows with bridge crossings
|
||||
- Mix of pit (60%) and wall (40%) obstacles
|
||||
- Tests navigation over negative obstacles
|
||||
|
||||
### Safety Padding
|
||||
|
||||
Two padding levels ensure safe robot placement:
|
||||
|
||||
| Padding Type | Cells | Meters | Purpose |
|
||||
|--------------|-------|--------|---------|
|
||||
| `GOAL_PADDING` | 5 | 0.5m | Goal positions (robot just needs to reach) |
|
||||
| `SPAWN_PADDING` | 6 | 0.6m | Spawn positions (accounts for robot body) |
|
||||
|
||||
The larger spawn padding accounts for:
|
||||
- Robot body dimensions (~0.5m × 0.3m for quadrupeds)
|
||||
- Random yaw orientation (diagonal ~0.58m requires ~0.3m clearance)
|
||||
- Platform edge safety (prevent falling when spawning near stairs)
|
||||
- Controller startup behavior
|
||||
|
||||
These values are defined in `terrain_constants.py` as `PADDING.GOAL_PADDING` and `PADDING.SPAWN_PADDING`.
|
||||
|
||||
### Terrain Configuration
|
||||
|
||||
The main terrain configuration is defined in [maze_config.py](../source/isaaclab_nav_task/isaaclab_nav_task/navigation/terrains/maze_config.py):
|
||||
|
||||
```python
|
||||
MAZE_TERRAIN_CFG = TerrainGeneratorCfg(
|
||||
size=(30.0, 30.0), # 30m × 30m per terrain tile
|
||||
border_width=30.0, # Border around entire grid (not per-tile)
|
||||
num_rows=6, # 6 difficulty levels
|
||||
num_cols=30, # 30 terrain variations
|
||||
horizontal_scale=0.1, # 0.1m per height field cell (300×300 cells)
|
||||
vertical_scale=0.005, # Height conversion: value * 0.005 = meters
|
||||
curriculum=False, # Random terrain, not progressive
|
||||
difficulty_range=(0.5, 1.0), # Difficulty sampling range
|
||||
sub_terrains={
|
||||
"maze": HfMazeTerrainCfg(proportion=0.3, open_probability=0.9,
|
||||
random_wall_ratio=0.5, add_stairs_to_maze=True),
|
||||
"non_maze": HfMazeTerrainCfg(proportion=0.2, non_maze_terrain=True,
|
||||
random_wall_ratio=1.0),
|
||||
"stairs": HfMazeTerrainCfg(proportion=0.3, stairs=True,
|
||||
randomize_wall=False),
|
||||
"pits": HfMazeTerrainCfg(proportion=0.2, dynamic_obstacles=True,
|
||||
random_wall_ratio=1.0),
|
||||
},
|
||||
)
|
||||
```
|
||||
|
||||
**Global Parameters:**
|
||||
- Total: **180 terrains** (6 rows × 30 cols), each 30m × 30m
|
||||
- Height field: **300×300 cells per terrain** (0.1m resolution)
|
||||
- `curriculum=False`: Random assignment across all 180 terrains
|
||||
|
||||
### Curriculum Learning
|
||||
|
||||
Terrains are organized in a grid with difficulty varying by row:
|
||||
- **Rows** (`terrain_levels`): Difficulty levels (0.0 to 1.0)
|
||||
- **Columns** (`terrain_types`): Different terrain types
|
||||
|
||||
```
|
||||
Difficulty
|
||||
1.0 | [Hard Maze] [Random Obs] [Tall Stairs] [Deep Pits] ...
|
||||
0.8 | [Med Maze] [Med Obs] [Med Stairs] [Med Pits] ...
|
||||
0.5 | [Easy Maze] [Few Obs] [Low Stairs] [Shallow] ...
|
||||
0.0 | [Flat] [Flat] [Flat] [Flat] ...
|
||||
└──────────────────────────────────────────────────────
|
||||
maze non_maze stairs pits
|
||||
```
|
||||
|
||||
## Goal and Spawn Sampling
|
||||
|
||||
The goal command generator ([RobotNavigationGoalCommand](../source/isaaclab_nav_task/isaaclab_nav_task/navigation/mdp/navigation/goal_commands.py)) handles sampling valid goal and spawn positions from maze terrains using pre-computed boolean masks.
|
||||
|
||||
### Architecture
|
||||
|
||||
```
|
||||
┌────────────────────────────────────────────────────────────────────┐
|
||||
│ RobotNavigationGoalCommand (goal_commands.py:329-766) │
|
||||
│ └─► _initialize_position_sampling() (once, lines 415-471) │
|
||||
│ └─► Creates PositionSampler with: │
|
||||
│ - heights: Z-lookup for terrain height │
|
||||
│ - valid_mask: Goal positions (5 cells = 0.5m padding) │
|
||||
│ - spawn_mask: Spawn positions (6 cells = 0.6m padding) │
|
||||
│ - platform_mask: Curriculum learning targets │
|
||||
│ - platform_repeat_count: 10 (default, line 74) │
|
||||
│ - border_width: 0.0 (sub-terrain default, line 457) │
|
||||
│ │
|
||||
│ └─► _resample_command(env_ids) (each reset, lines 499-553) │
|
||||
│ └─► sample(): Goal from valid_mask (line 519) │
|
||||
│ └─► sample_spawn(): Spawn from spawn_mask (line 521) │
|
||||
│ └─► Convert local → world coordinates (lines 524-547) │
|
||||
└────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Key Features
|
||||
|
||||
- **Pre-computed masks**: `valid_mask` and `spawn_mask` generated during terrain creation
|
||||
- **Separate padding**: Goals (5 cells = 0.5m) vs spawns (6 cells = 0.6m) for robot body clearance
|
||||
- **Platform repetition**: Stair platforms repeated 10x in sampling for curriculum learning (goal_commands.py:74, 154)
|
||||
- **Efficient lookup**: Pre-built position tables enable O(1) random sampling
|
||||
- **Coordinate conversion**: Handles mesh border offset and centering transform
|
||||
- **Dynamic border calculation**: Border pixels computed from terrain config (goal_commands.py:107)
|
||||
|
||||
### Coordinate System
|
||||
|
||||
The terrain mesh uses a coordinate system with:
|
||||
- **Border pixels**: Dynamically computed as `int(border_width / horizontal_scale) + 1`
|
||||
- Sub-terrain configs default to `border_width=0.0` (from `HfTerrainBaseCfg`)
|
||||
- With default values: `border_pixels = int(0.0 / 0.1) + 1 = 1`
|
||||
- **Centering transform**: Mesh is centered at origin by `-terrain_size/2`
|
||||
|
||||
```python
|
||||
# Converting valid_mask index to local coordinates (goal_commands.py:283-284):
|
||||
local_x = (x_idx + border_pixels) * horizontal_scale - terrain_size/2
|
||||
local_y = (y_idx + border_pixels) * horizontal_scale - terrain_size/2
|
||||
|
||||
# Example: terrain_size=30m, horizontal_scale=0.1m, border_width=0.0
|
||||
# border_pixels = 1
|
||||
# valid_mask[0, 0] → local position: (0.1 - 15, 0.1 - 15) = (-14.9, -14.9)
|
||||
```
|
||||
|
||||
The `border_pixels` calculation is done in the `PositionSampler.__init__()` (goal_commands.py:107) to match the `@height_field_to_mesh` decorator behavior.
|
||||
|
||||
### Terrain Index Mapping
|
||||
|
||||
The terrain index formula depends on the generation mode:
|
||||
|
||||
| Mode | Formula | Description |
|
||||
|------|---------|-------------|
|
||||
| `curriculum=True` | `level + type * num_rows` | Column-major (iterate rows first) |
|
||||
| `curriculum=False` | `level * num_cols + type` | Row-major (iterate cols first) |
|
||||
|
||||
```python
|
||||
# In goal_commands.py:
|
||||
def _get_terrain_indices(self, env_ids):
|
||||
terrain = self.env.scene.terrain
|
||||
levels = terrain.terrain_levels[env_ids] # row
|
||||
types = terrain.terrain_types[env_ids] # col
|
||||
|
||||
if terrain_cfg.curriculum:
|
||||
return levels + types * num_rows # column-major
|
||||
else:
|
||||
return levels * num_cols + types # row-major
|
||||
```
|
||||
|
||||
### Position Sampling
|
||||
|
||||
**PositionSampler** (goal_commands.py:51-290) provides two sampling methods:
|
||||
|
||||
```python
|
||||
class PositionSampler:
|
||||
def sample(terrain_indices) -> (x, y, z):
|
||||
"""Sample GOAL positions from valid_mask.
|
||||
Uses platform repetition for curriculum learning.
|
||||
Default platform_repeat_count=10 (goal_commands.py:74)"""
|
||||
|
||||
def sample_spawn(terrain_indices) -> (x, y, z):
|
||||
"""Sample SPAWN positions from spawn_mask.
|
||||
Larger padding (6 cells vs 5 cells) for robot body with random orientation."""
|
||||
```
|
||||
|
||||
**Implementation Details:**
|
||||
- Pre-computes position tables during initialization (goal_commands.py:115-201)
|
||||
- Platform positions are repeated 10x in goal sampling for curriculum learning
|
||||
- Uses efficient O(1) random sampling from pre-built position tables
|
||||
- Falls back to `valid_mask` if `spawn_mask` is not provided (goal_commands.py:99)
|
||||
|
||||
**Sampling flow during episode reset:**
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ _resample_command(env_ids) (goal_commands.py:499-553) │
|
||||
├─────────────────────────────────────────────────────────────────┤
|
||||
│ 1. Get terrain indices for each environment (line 516) │
|
||||
│ - terrain_levels[env_ids] → row (difficulty) │
|
||||
│ - terrain_types[env_ids] → col (terrain type) │
|
||||
│ - Apply curriculum/random index formula (lines 473-493) │
|
||||
│ │
|
||||
│ 2. Sample goal position from valid_mask (line 519) │
|
||||
│ - Random sample from pre-computed goal position table │
|
||||
│ - Platform positions repeated 10x for curriculum weighting │
|
||||
│ - Uses GOAL_PADDING = 5 cells = 0.5m │
|
||||
│ │
|
||||
│ 3. Sample spawn position from spawn_mask (line 521) │
|
||||
│ - Random sample from pre-computed spawn position table │
|
||||
│ - Larger padding (SPAWN_PADDING = 6 cells = 0.6m) │
|
||||
│ - Ensures robot body clearance with random orientation │
|
||||
│ │
|
||||
│ 4. Convert to world coordinates (lines 524-547) │
|
||||
│ - Add terrain_origins[level, type] offset │
|
||||
│ - Goal: Add random height offset (0.2-0.8m) for marker │
|
||||
│ - Spawn: Add spawn_offset = 0.05m (NOT 0.5m!) │
|
||||
│ (robot's default_root_state already has standing height) │
|
||||
│ │
|
||||
│ 5. Update environment origins (lines 540-542) │
|
||||
│ - env.scene.terrain.env_origins[env_ids] = spawn position │
|
||||
│ - Robot will be reset to this position │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Robot Spawn Height
|
||||
|
||||
The spawn height offset accounts for the robot's standing height:
|
||||
|
||||
```python
|
||||
# In _resample_command() (goal_commands.py:537-542):
|
||||
spawn_offset = 0.05 # Small offset to prevent clipping into terrain
|
||||
|
||||
# Note: robot's default_root_state already includes standing height (~0.5m)
|
||||
terrain.env_origins[env_ids, 0] = terrain_origins[:, 0] + spawn_x
|
||||
terrain.env_origins[env_ids, 1] = terrain_origins[:, 1] + spawn_y
|
||||
terrain.env_origins[env_ids, 2] = spawn_z + spawn_offset # Just 5cm above terrain
|
||||
```
|
||||
|
||||
**Key Change:** The implementation uses only a small 5cm offset because the robot's `default_root_state` configuration already includes the proper standing height (~0.5m). This ensures the robot spawns at the correct height without double-counting the base height.
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""
|
||||
Isaac Lab Navigation Tasks extension.
|
||||
|
||||
This extension provides navigation tasks for robot learning with visual perception.
|
||||
|
||||
On import, this module:
|
||||
1. Applies monkey-patches to Isaac Lab terrain system for height field storage
|
||||
2. Registers maze terrain types
|
||||
3. Registers navigation task environments
|
||||
"""
|
||||
|
||||
import os
|
||||
import toml
|
||||
|
||||
# Conveniences to other module directories via relative paths
|
||||
ISAACLAB_NAV_TASKS_EXT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "../"))
|
||||
"""Path to the extension source directory."""
|
||||
|
||||
ISAACLAB_NAV_TASKS_METADATA = toml.load(os.path.join(ISAACLAB_NAV_TASKS_EXT_DIR, "config", "extension.toml"))
|
||||
"""Extension metadata dictionary parsed from the extension.toml file."""
|
||||
|
||||
# Configure the module-level variables
|
||||
__version__ = ISAACLAB_NAV_TASKS_METADATA["package"]["version"]
|
||||
|
||||
##
|
||||
# Apply patches to Isaac Lab terrain system.
|
||||
# This must be done before any terrain generation happens.
|
||||
# IMPORTANT: Import patches directly from the module file, NOT through
|
||||
# terrains/__init__.py, to avoid triggering terrain imports before patching.
|
||||
##
|
||||
|
||||
# Direct import from patches module to avoid loading terrains/__init__.py
|
||||
import importlib.util
|
||||
import os as _os
|
||||
_patches_path = _os.path.join(_os.path.dirname(__file__), "terrains", "patches.py")
|
||||
_spec = importlib.util.spec_from_file_location("patches", _patches_path)
|
||||
_patches_module = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(_patches_module)
|
||||
_patches_module.apply_terrain_patches()
|
||||
del _patches_path, _spec, _patches_module
|
||||
|
||||
##
|
||||
# Export terrain types for convenient access.
|
||||
##
|
||||
|
||||
from .terrains import (
|
||||
HfMazeTerrainCfg,
|
||||
MAZE_TERRAIN_CFG,
|
||||
)
|
||||
|
||||
##
|
||||
# Register Gym environments.
|
||||
##
|
||||
|
||||
from isaaclab_tasks.utils import import_packages
|
||||
|
||||
# The blacklist is used to prevent importing configs from sub-packages
|
||||
_BLACKLIST_PKGS = ["utils", "terrains"]
|
||||
# Import all configs in this package
|
||||
import_packages(__name__, _BLACKLIST_PKGS)
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Navigation task environments for Isaac Lab."""
|
||||
|
||||
from .navigation_env import NavigationEnv
|
||||
from .navigation_env_cfg import *
|
||||
|
||||
# Import robot-specific configurations
|
||||
from .config import *
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Robot-specific configuration modules for navigation tasks."""
|
||||
|
||||
from .b2w import *
|
||||
from .aow_d import *
|
||||
from .go2 import *
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
import gymnasium as gym
|
||||
|
||||
from . import agents, navigation_env_cfg
|
||||
|
||||
##
|
||||
# Register Gym environments.
|
||||
##
|
||||
|
||||
##############################################################################################################
|
||||
# MDPO
|
||||
|
||||
gym.register(
|
||||
id="Isaac-Nav-MDPO-AoW-D-v0",
|
||||
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
|
||||
disable_env_checker=True,
|
||||
kwargs={
|
||||
"env_cfg_entry_point": navigation_env_cfg.AowDNavigationEnvCfg,
|
||||
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AowDNavMDPORunnerCfg,
|
||||
},
|
||||
)
|
||||
|
||||
gym.register(
|
||||
id="Isaac-Nav-MDPO-AoW-D-Play-v0",
|
||||
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
|
||||
disable_env_checker=True,
|
||||
kwargs={
|
||||
"env_cfg_entry_point": navigation_env_cfg.AowDNavigationEnvCfg_PLAY,
|
||||
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AowDNavMDPORunnerCfg,
|
||||
},
|
||||
)
|
||||
|
||||
gym.register(
|
||||
id="Isaac-Nav-MDPO-AoW-D-Dev-v0",
|
||||
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
|
||||
disable_env_checker=True,
|
||||
kwargs={
|
||||
"env_cfg_entry_point": navigation_env_cfg.AowDNavigationEnvCfg_DEV,
|
||||
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AowDNavMDPORunnerDevCfg,
|
||||
},
|
||||
)
|
||||
|
||||
######################################################################################
|
||||
# PPO
|
||||
|
||||
gym.register(
|
||||
id="Isaac-Nav-PPO-AoW-D-v0",
|
||||
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
|
||||
disable_env_checker=True,
|
||||
kwargs={
|
||||
"env_cfg_entry_point": navigation_env_cfg.AowDNavigationEnvCfg,
|
||||
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AowDNavPPORunnerCfg,
|
||||
},
|
||||
)
|
||||
|
||||
gym.register(
|
||||
id="Isaac-Nav-PPO-AoW-D-Play-v0",
|
||||
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
|
||||
disable_env_checker=True,
|
||||
kwargs={
|
||||
"env_cfg_entry_point": navigation_env_cfg.AowDNavigationEnvCfg_PLAY,
|
||||
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AowDNavPPORunnerCfg,
|
||||
},
|
||||
)
|
||||
|
||||
gym.register(
|
||||
id="Isaac-Nav-PPO-AoW-D-Dev-v0",
|
||||
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
|
||||
disable_env_checker=True,
|
||||
kwargs={
|
||||
"env_cfg_entry_point": navigation_env_cfg.AowDNavigationEnvCfg_DEV,
|
||||
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AowDNavPPORunnerDevCfg,
|
||||
},
|
||||
)
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Agent configurations for AoW-D navigation tasks."""
|
||||
|
||||
from . import rsl_rl_cfg
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""RSL-RL agent configurations for AoW-D navigation tasks."""
|
||||
|
||||
from isaaclab.utils import configclass
|
||||
|
||||
from isaaclab_nav_task.navigation.config.rl_cfg import (
|
||||
RslRlOnPolicyRunnerCfg,
|
||||
RslRlPpoActorCriticCfg,
|
||||
RslRlPpoAlgorithmCfg,
|
||||
)
|
||||
|
||||
|
||||
@configclass
|
||||
class AowDNavMDPORunnerCfg(RslRlOnPolicyRunnerCfg):
|
||||
"""MDPO runner configuration for AoW-D navigation."""
|
||||
|
||||
num_steps_per_env = 16
|
||||
max_iterations = 15000
|
||||
save_interval = 500
|
||||
logger = "wandb"
|
||||
seed = 50
|
||||
wandb_project = "isaaclab_nav_aow_d"
|
||||
experiment_name = "aow_d_navigation_mdpo"
|
||||
empirical_normalization = False
|
||||
reward_shifting_value = 0.05
|
||||
policy = RslRlPpoActorCriticCfg(
|
||||
class_name="ActorCriticSRU",
|
||||
init_noise_std=1.0,
|
||||
actor_hidden_dims=[512, 256, 128],
|
||||
critic_hidden_dims=[512, 256, 128],
|
||||
activation="elu",
|
||||
rnn_hidden_size=512,
|
||||
rnn_type="lstm_sru",
|
||||
rnn_num_layers=1,
|
||||
dropout=0.2,
|
||||
num_cameras=1,
|
||||
image_input_dims=(64, 5, 8),
|
||||
)
|
||||
algorithm = RslRlPpoAlgorithmCfg(
|
||||
class_name="MDPO",
|
||||
value_loss_coef=0.02,
|
||||
use_clipped_value_loss=True,
|
||||
clip_param=0.2,
|
||||
value_clip_param=0.2,
|
||||
entropy_coef=0.00375,
|
||||
num_learning_epochs=5,
|
||||
num_mini_batches=4,
|
||||
learning_rate=1.0e-3,
|
||||
schedule="adaptive",
|
||||
gamma=0.995,
|
||||
lam=0.95,
|
||||
desired_kl=0.01,
|
||||
max_grad_norm=1.0,
|
||||
)
|
||||
|
||||
|
||||
@configclass
|
||||
class AowDNavMDPORunnerDevCfg(AowDNavMDPORunnerCfg):
|
||||
"""Development configuration for MDPO with reduced iterations."""
|
||||
|
||||
def __post_init__(self):
|
||||
super().__post_init__()
|
||||
self.max_iterations = 300
|
||||
self.experiment_name = "aow_d_navigation_mdpo_dev"
|
||||
self.logger = "tensorboard"
|
||||
|
||||
|
||||
@configclass
|
||||
class AowDNavPPORunnerCfg(RslRlOnPolicyRunnerCfg):
|
||||
"""PPO runner configuration for AoW-D navigation."""
|
||||
|
||||
num_steps_per_env = 24
|
||||
max_iterations = 15000
|
||||
save_interval = 500
|
||||
logger = "wandb"
|
||||
wandb_project = "isaaclab_nav_aow_d"
|
||||
experiment_name = "aow_d_navigation_ppo"
|
||||
empirical_normalization = False
|
||||
policy = RslRlPpoActorCriticCfg(
|
||||
class_name="ActorCriticSRU",
|
||||
init_noise_std=1.0,
|
||||
actor_hidden_dims=[512, 256, 128],
|
||||
critic_hidden_dims=[512, 256, 128],
|
||||
activation="elu",
|
||||
rnn_hidden_size=256,
|
||||
rnn_type="lstm_sru",
|
||||
num_cameras=1,
|
||||
image_input_dims=(64, 5, 8),
|
||||
)
|
||||
algorithm = RslRlPpoAlgorithmCfg(
|
||||
class_name="PPO",
|
||||
value_loss_coef=0.1,
|
||||
use_clipped_value_loss=True,
|
||||
clip_param=0.2,
|
||||
entropy_coef=0.005,
|
||||
num_learning_epochs=5,
|
||||
num_mini_batches=4,
|
||||
learning_rate=1.0e-3,
|
||||
schedule="adaptive",
|
||||
gamma=0.995,
|
||||
lam=0.95,
|
||||
desired_kl=0.01,
|
||||
max_grad_norm=1.0,
|
||||
)
|
||||
|
||||
|
||||
@configclass
|
||||
class AowDNavPPORunnerDevCfg(AowDNavPPORunnerCfg):
|
||||
"""Development configuration for PPO with reduced iterations."""
|
||||
|
||||
def __post_init__(self):
|
||||
super().__post_init__()
|
||||
self.max_iterations = 300
|
||||
self.experiment_name = "aow_d_navigation_ppo_dev"
|
||||
self.logger = "tensorboard"
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""AoW-D (Anymal on Wheels) specific configuration for navigation environment."""
|
||||
|
||||
from isaaclab.utils import configclass
|
||||
|
||||
from isaaclab_nav_task.navigation.navigation_env_cfg import NavigationEnvCfg
|
||||
import isaaclab_nav_task.navigation.mdp as mdp
|
||||
|
||||
from isaaclab_nav_task.navigation.assets import ANYMAL_D_ON_WHEELS_CFG # isort: skip
|
||||
|
||||
|
||||
@configclass
|
||||
class AowDNavigationEnvCfg(NavigationEnvCfg):
|
||||
def __post_init__(self):
|
||||
super().__post_init__()
|
||||
|
||||
from isaaclab_nav_task.navigation.mdp.observations import initialize_depth_noise_generator
|
||||
from isaaclab_nav_task.navigation.mdp.depth_utils.camera_config import get_camera_config
|
||||
|
||||
initialize_depth_noise_generator(robot_name="aow_d", use_jit_precompiled=False)
|
||||
|
||||
camera_config = get_camera_config("aow_d")
|
||||
CAMERA_RESOLUTION = camera_config.resolution
|
||||
|
||||
self.scene.robot = ANYMAL_D_ON_WHEELS_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot")
|
||||
|
||||
self.scene.terrain.max_init_terrain_level = 10
|
||||
self.scene.terrain.terrain_generator.difficulty_range = [0.5, 1.0]
|
||||
self.scene.terrain.terrain_generator.curriculum = False
|
||||
|
||||
@configclass
|
||||
class AowDNavigationEnvCfg_DEV(AowDNavigationEnvCfg):
|
||||
def __post_init__(self):
|
||||
super().__post_init__()
|
||||
self.scene.terrain.terrain_generator.num_rows = 1
|
||||
self.scene.terrain.terrain_generator.num_cols = 30
|
||||
self.scene.terrain.max_init_terrain_level = 10
|
||||
self.scene.terrain.terrain_generator.difficulty_range = [0.4, 0.8]
|
||||
self.scene.terrain.terrain_generator.curriculum = True
|
||||
self.scene.num_envs = 1
|
||||
|
||||
@configclass
|
||||
class AowDNavigationEnvCfg_PLAY(AowDNavigationEnvCfg):
|
||||
def __post_init__(self):
|
||||
super().__post_init__()
|
||||
|
||||
self.scene.num_envs = 20
|
||||
self.scene.env_spacing = 2.5
|
||||
self.scene.terrain.max_init_terrain_level = None
|
||||
if self.scene.terrain.terrain_generator is not None:
|
||||
self.scene.terrain.terrain_generator.num_rows = 2
|
||||
self.scene.terrain.terrain_generator.num_cols = 2
|
||||
|
||||
self.observations.policy.enable_corruption = False
|
||||
self.events.base_external_force_torque = None
|
||||
self.events.push_robot = None
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
import gymnasium as gym
|
||||
|
||||
from . import agents, navigation_env_cfg
|
||||
|
||||
##
|
||||
# Register Gym environments.
|
||||
##
|
||||
|
||||
##############################################################################################################
|
||||
# MDPO
|
||||
|
||||
gym.register(
|
||||
id="Isaac-Nav-MDPO-B2W-v0",
|
||||
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
|
||||
disable_env_checker=True,
|
||||
kwargs={
|
||||
"env_cfg_entry_point": navigation_env_cfg.B2WNavigationEnvCfg,
|
||||
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.B2WNavMDPORunnerCfg,
|
||||
},
|
||||
)
|
||||
|
||||
gym.register(
|
||||
id="Isaac-Nav-MDPO-B2W-Play-v0",
|
||||
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
|
||||
disable_env_checker=True,
|
||||
kwargs={
|
||||
"env_cfg_entry_point": navigation_env_cfg.B2WNavigationEnvCfg_PLAY,
|
||||
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.B2WNavMDPORunnerCfg,
|
||||
},
|
||||
)
|
||||
|
||||
gym.register(
|
||||
id="Isaac-Nav-MDPO-B2W-Dev-v0",
|
||||
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
|
||||
disable_env_checker=True,
|
||||
kwargs={
|
||||
"env_cfg_entry_point": navigation_env_cfg.B2WNavigationEnvCfg_DEV,
|
||||
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.B2WNavMDPORunnerDevCfg,
|
||||
},
|
||||
)
|
||||
|
||||
######################################################################################
|
||||
# PPO
|
||||
|
||||
gym.register(
|
||||
id="Isaac-Nav-PPO-B2W-v0",
|
||||
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
|
||||
disable_env_checker=True,
|
||||
kwargs={
|
||||
"env_cfg_entry_point": navigation_env_cfg.B2WNavigationEnvCfg,
|
||||
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.B2WNavPPORunnerCfg,
|
||||
},
|
||||
)
|
||||
|
||||
gym.register(
|
||||
id="Isaac-Nav-PPO-B2W-Play-v0",
|
||||
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
|
||||
disable_env_checker=True,
|
||||
kwargs={
|
||||
"env_cfg_entry_point": navigation_env_cfg.B2WNavigationEnvCfg_PLAY,
|
||||
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.B2WNavPPORunnerCfg,
|
||||
},
|
||||
)
|
||||
|
||||
gym.register(
|
||||
id="Isaac-Nav-PPO-B2W-Dev-v0",
|
||||
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
|
||||
disable_env_checker=True,
|
||||
kwargs={
|
||||
"env_cfg_entry_point": navigation_env_cfg.B2WNavigationEnvCfg_DEV,
|
||||
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.B2WNavPPORunnerDevCfg,
|
||||
},
|
||||
)
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Agent configurations for B2W navigation tasks."""
|
||||
|
||||
from . import rsl_rl_cfg
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""RSL-RL agent configurations for B2W navigation tasks."""
|
||||
|
||||
from isaaclab.utils import configclass
|
||||
|
||||
from isaaclab_nav_task.navigation.config.rl_cfg import (
|
||||
RslRlOnPolicyRunnerCfg,
|
||||
RslRlPpoActorCriticCfg,
|
||||
RslRlPpoAlgorithmCfg,
|
||||
)
|
||||
|
||||
|
||||
@configclass
|
||||
class B2WNavMDPORunnerCfg(RslRlOnPolicyRunnerCfg):
|
||||
"""MDPO runner configuration for B2W navigation."""
|
||||
|
||||
num_steps_per_env = 16
|
||||
max_iterations = 15000
|
||||
save_interval = 500
|
||||
logger = "wandb"
|
||||
seed = 60
|
||||
wandb_project = "isaaclab_nav_b2w"
|
||||
experiment_name = "b2w_navigation_mdpo"
|
||||
empirical_normalization = False
|
||||
reward_shifting_value = 0.05
|
||||
policy = RslRlPpoActorCriticCfg(
|
||||
class_name="ActorCriticSRU",
|
||||
init_noise_std=1.0,
|
||||
actor_hidden_dims=[512, 256, 128],
|
||||
critic_hidden_dims=[512, 256, 128],
|
||||
activation="elu",
|
||||
rnn_hidden_size=512,
|
||||
rnn_type="lstm_sru",
|
||||
rnn_num_layers=1,
|
||||
dropout=0.2,
|
||||
num_cameras=1,
|
||||
image_input_dims=(64, 5, 8), # depth image: 64 channels * 5 * 8 = 2560
|
||||
height_input_dims=(64, 7, 7), # encoded height_scan_critic: 64*7*7 = 3136
|
||||
)
|
||||
algorithm = RslRlPpoAlgorithmCfg(
|
||||
class_name="MDPO",
|
||||
value_loss_coef=0.02,
|
||||
use_clipped_value_loss=True,
|
||||
clip_param=0.2,
|
||||
value_clip_param=0.2,
|
||||
entropy_coef=0.00375,
|
||||
num_learning_epochs=5,
|
||||
num_mini_batches=4,
|
||||
learning_rate=1.0e-3,
|
||||
schedule="exponential",
|
||||
gamma=0.999,
|
||||
lam=0.95,
|
||||
desired_kl=0.01,
|
||||
max_grad_norm=1.0,
|
||||
)
|
||||
|
||||
|
||||
@configclass
|
||||
class B2WNavMDPORunnerDevCfg(B2WNavMDPORunnerCfg):
|
||||
"""Development configuration for MDPO with reduced iterations."""
|
||||
|
||||
def __post_init__(self):
|
||||
super().__post_init__()
|
||||
self.max_iterations = 300
|
||||
self.experiment_name = "b2w_navigation_mdpo_dev"
|
||||
self.logger = "tensorboard"
|
||||
|
||||
|
||||
@configclass
|
||||
class B2WNavPPORunnerCfg(RslRlOnPolicyRunnerCfg):
|
||||
"""PPO runner configuration for B2W navigation."""
|
||||
|
||||
num_steps_per_env = 16
|
||||
max_iterations = 15000
|
||||
save_interval = 500
|
||||
logger = "wandb"
|
||||
seed = 60
|
||||
wandb_project = "isaaclab_nav_b2w"
|
||||
experiment_name = "b2w_navigation_ppo"
|
||||
empirical_normalization = False
|
||||
reward_shifting_value = 0.05
|
||||
policy = RslRlPpoActorCriticCfg(
|
||||
class_name="ActorCriticSRU",
|
||||
init_noise_std=1.0,
|
||||
actor_hidden_dims=[512, 256, 128],
|
||||
critic_hidden_dims=[512, 256, 128],
|
||||
activation="elu",
|
||||
rnn_hidden_size=512,
|
||||
rnn_type="lstm_sru",
|
||||
rnn_num_layers=1,
|
||||
dropout=0.2,
|
||||
num_cameras=1,
|
||||
image_input_dims=(64, 5, 8), # depth image: 64 channels * 5 * 8 = 2560
|
||||
height_input_dims=(64, 7, 7), # encoded height_scan_critic: 64*7*7 = 3136
|
||||
)
|
||||
algorithm = RslRlPpoAlgorithmCfg(
|
||||
class_name="PPO",
|
||||
value_loss_coef=0.02,
|
||||
use_clipped_value_loss=True,
|
||||
clip_param=0.2,
|
||||
value_clip_param=0.2,
|
||||
entropy_coef=0.00375,
|
||||
num_learning_epochs=5,
|
||||
num_mini_batches=4,
|
||||
learning_rate=1.0e-3,
|
||||
schedule="adaptive",
|
||||
gamma=0.995,
|
||||
lam=0.95,
|
||||
desired_kl=0.01,
|
||||
max_grad_norm=1.0,
|
||||
)
|
||||
|
||||
|
||||
@configclass
|
||||
class B2WNavPPORunnerDevCfg(B2WNavPPORunnerCfg):
|
||||
"""Development configuration for PPO with reduced iterations."""
|
||||
|
||||
def __post_init__(self):
|
||||
super().__post_init__()
|
||||
self.max_iterations = 300
|
||||
self.experiment_name = "b2w_navigation_ppo_dev"
|
||||
self.logger = "tensorboard"
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""B2W specific configuration for navigation environment."""
|
||||
|
||||
import os
|
||||
|
||||
from isaaclab.utils import configclass
|
||||
from isaaclab.managers import SceneEntityCfg
|
||||
|
||||
from isaaclab_nav_task.navigation.navigation_env_cfg import NavigationEnvCfg
|
||||
import isaaclab_nav_task.navigation.mdp as mdp
|
||||
|
||||
from isaaclab_nav_task.navigation.assets import B2W_CFG, ISAACLAB_NAV_TASKS_ASSETS_DIR # isort: skip
|
||||
|
||||
|
||||
LEG_JOINT_NAMES = [".*hip_joint", ".*thigh_joint", ".*calf_joint"]
|
||||
WHEEL_JOINT_NAMES = [".*foot_joint"]
|
||||
|
||||
@configclass
|
||||
class B2WNavigationEnvCfg(NavigationEnvCfg):
|
||||
def __post_init__(self):
|
||||
super().__post_init__()
|
||||
|
||||
from isaaclab_nav_task.navigation.mdp.observations import initialize_depth_noise_generator
|
||||
from isaaclab_nav_task.navigation.mdp.depth_utils.camera_config import get_camera_config
|
||||
|
||||
initialize_depth_noise_generator(robot_name="b2w", use_jit_precompiled=False)
|
||||
|
||||
camera_config = get_camera_config("b2w")
|
||||
CAMERA_RESOLUTION = camera_config.resolution
|
||||
|
||||
self.scene.robot = B2W_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot")
|
||||
|
||||
self.scene.raycast_camera.prim_path = "{ENV_REGEX_NS}/Robot/base_link"
|
||||
self.scene.raycast_camera.offset.pos = (0.387, 0.0, 0.28)
|
||||
self.scene.height_scanner_critic.prim_path = "{ENV_REGEX_NS}/Robot/base_link"
|
||||
|
||||
self.terminations.base_contact.params = {"sensor_cfg": SceneEntityCfg("contact_forces", body_names=["base_link", ".*hip", ".*thigh"]), "threshold": 1.0}
|
||||
|
||||
self.actions.velocity_command.low_level_position_action = mdp.JointPositionActionCfg(asset_name="robot", joint_names=[".*hip_joint", ".*thigh_joint", ".*calf_joint"], scale=0.5, use_default_offset=True)
|
||||
self.actions.velocity_command.low_level_velocity_action = mdp.JointVelocityActionCfg(asset_name="robot", joint_names=[".*foot_joint"], scale=5.0, use_default_offset=True)
|
||||
self.actions.velocity_command.low_level_policy_file = os.path.join(ISAACLAB_NAV_TASKS_ASSETS_DIR, "Policies", "locomotion", "b2w", "policy_b2w_new_2.pt")
|
||||
|
||||
self.rewards.joint_acc_l2_joint.params = {"asset_cfg": SceneEntityCfg("robot", joint_names=LEG_JOINT_NAMES+WHEEL_JOINT_NAMES)}
|
||||
|
||||
self.terminations.base_contact.params = {"sensor_cfg": SceneEntityCfg("contact_forces", body_names=["base_link", ".*hip", ".*thigh"]), "threshold": 1.0}
|
||||
|
||||
self.events.randomize_low_pass_filter_alpha.params = {
|
||||
"alpha_range": (0.1, 0.6),
|
||||
"action_term": "velocity_command",
|
||||
"per_dimension": True,
|
||||
"alpha_range_vx": (0.1, 0.6),
|
||||
"alpha_range_vy": (0.1, 0.6),
|
||||
"alpha_range_omega": (0.1, 0.6),
|
||||
}
|
||||
|
||||
self.scene.terrain.max_init_terrain_level = 10
|
||||
self.scene.terrain.terrain_generator.difficulty_range = [0.5, 1.0]
|
||||
self.scene.terrain.terrain_generator.curriculum = False
|
||||
|
||||
@configclass
|
||||
class B2WNavigationEnvCfg_DEV(B2WNavigationEnvCfg):
|
||||
def __post_init__(self):
|
||||
super().__post_init__()
|
||||
self.scene.terrain.terrain_generator.num_rows = 2
|
||||
self.scene.terrain.terrain_generator.num_cols = 30
|
||||
self.scene.terrain.max_init_terrain_level = 10
|
||||
self.scene.terrain.terrain_generator.difficulty_range = [0.5, 1.0]
|
||||
self.scene.terrain.terrain_generator.curriculum = False
|
||||
|
||||
@configclass
|
||||
class B2WNavigationEnvCfg_PLAY(B2WNavigationEnvCfg):
|
||||
def __post_init__(self):
|
||||
super().__post_init__()
|
||||
|
||||
self.scene.num_envs = 20
|
||||
self.scene.env_spacing = 2.5
|
||||
self.scene.terrain.max_init_terrain_level = None
|
||||
if self.scene.terrain.terrain_generator is not None:
|
||||
self.scene.terrain.terrain_generator.num_rows = 2
|
||||
self.scene.terrain.terrain_generator.num_cols = 2
|
||||
|
||||
# ---- PLAY_DIFFICULTY="lo,hi": difficulty band ----
|
||||
lo, hi = 0.5, 1.0
|
||||
_play_diff = os.environ.get("PLAY_DIFFICULTY", "").strip()
|
||||
if _play_diff:
|
||||
_parts = _play_diff.replace(" ", "").split(",")
|
||||
lo, hi = float(_parts[0]), float(_parts[1])
|
||||
self.scene.terrain.terrain_generator.difficulty_range = [lo, hi]
|
||||
self.scene.terrain.terrain_generator.curriculum = False
|
||||
print(f"[B2W PLAY] terrain difficulty_range = [{lo}, {hi}] (curriculum off)")
|
||||
|
||||
sub_terrains = self.scene.terrain.terrain_generator.sub_terrains
|
||||
|
||||
# PLAY_MAZE_ONLY=1: 100% maze sub-terrain
|
||||
_maze_only = os.environ.get("PLAY_MAZE_ONLY", "").strip().lower() in ("1", "true", "yes")
|
||||
if _maze_only and "maze" in sub_terrains:
|
||||
for name in list(sub_terrains.keys()):
|
||||
sub_terrains[name].proportion = 1.0 if name == "maze" else 0.0
|
||||
print(f"[B2W PLAY] PLAY_MAZE_ONLY=1 -> 100% maze sub-terrain")
|
||||
|
||||
# PLAY_SUBTERRAIN_MIX="maze=1,non_maze=0,pits=0"
|
||||
_mix = os.environ.get("PLAY_SUBTERRAIN_MIX", "").strip()
|
||||
if _mix:
|
||||
overrides = {}
|
||||
for part in _mix.split(","):
|
||||
if "=" not in part:
|
||||
continue
|
||||
k, v = part.split("=", 1)
|
||||
overrides[k.strip()] = float(v.strip())
|
||||
for name, prop in overrides.items():
|
||||
if name in sub_terrains:
|
||||
sub_terrains[name].proportion = prop
|
||||
final = {n: sub_terrains[n].proportion for n in sub_terrains}
|
||||
print(f"[B2W PLAY] PLAY_SUBTERRAIN_MIX -> {final}")
|
||||
|
||||
# PLAY_CELL_SIZE: meters per maze cell
|
||||
_play_cell = os.environ.get("PLAY_CELL_SIZE", "").strip()
|
||||
if _play_cell:
|
||||
new_cell = float(_play_cell)
|
||||
for cfg_sub in sub_terrains.values():
|
||||
cfg_sub.cell_size = new_cell
|
||||
tile_m = 15 * new_cell
|
||||
self.scene.terrain.terrain_generator.size = (tile_m, tile_m)
|
||||
print(f"[B2W PLAY] PLAY_CELL_SIZE={new_cell}m -> tile={tile_m}m")
|
||||
|
||||
# PLAY_CLASSIC_MAZE=1: paper-style uniform walls
|
||||
_classic = os.environ.get("PLAY_CLASSIC_MAZE", "").strip().lower() in ("1", "true", "yes")
|
||||
if _classic and "maze" in sub_terrains:
|
||||
sub_terrains["maze"].randomize_wall = False
|
||||
sub_terrains["maze"].random_wall_ratio = 0.0
|
||||
print(f"[B2W PLAY] PLAY_CLASSIC_MAZE=1 -> classic uniform walls in maze")
|
||||
|
||||
self.observations.policy.enable_corruption = False
|
||||
self.events.base_external_force_torque = None
|
||||
self.events.push_robot = None
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
import gymnasium as gym
|
||||
|
||||
from . import agents, navigation_env_cfg
|
||||
|
||||
##
|
||||
# Register Gym environments.
|
||||
##
|
||||
|
||||
##############################################################################################################
|
||||
# PPO
|
||||
|
||||
gym.register(
|
||||
id="Isaac-Nav-PPO-Go2-v0",
|
||||
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
|
||||
disable_env_checker=True,
|
||||
kwargs={
|
||||
"env_cfg_entry_point": navigation_env_cfg.Go2NavigationEnvCfg,
|
||||
# MixedCfg is the cold-start tuned variant of the Dev hyperparams;
|
||||
# the original B2W-FT ``Go2NavPPORunnerCfg`` collapses exploration on a
|
||||
# from-scratch run (init_std=0.5, entropy=0.001, clip=0.1).
|
||||
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.Go2NavPPORunnerMixedCfg,
|
||||
},
|
||||
)
|
||||
|
||||
gym.register(
|
||||
id="Isaac-Nav-PPO-Go2-Play-v0",
|
||||
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
|
||||
disable_env_checker=True,
|
||||
kwargs={
|
||||
"env_cfg_entry_point": navigation_env_cfg.Go2NavigationEnvCfg_PLAY,
|
||||
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.Go2NavPPORunnerCfg,
|
||||
},
|
||||
)
|
||||
|
||||
gym.register(
|
||||
id="Isaac-Nav-PPO-Go2-Dev-v0",
|
||||
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
|
||||
disable_env_checker=True,
|
||||
kwargs={
|
||||
"env_cfg_entry_point": navigation_env_cfg.Go2NavigationEnvCfg_DEV,
|
||||
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.Go2NavPPORunnerDevCfg,
|
||||
},
|
||||
)
|
||||
|
||||
gym.register(
|
||||
id="Isaac-Nav-PPO-Go2-PureMaze-v0",
|
||||
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
|
||||
disable_env_checker=True,
|
||||
kwargs={
|
||||
"env_cfg_entry_point": navigation_env_cfg.Go2NavigationEnvCfg_PureMaze,
|
||||
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.Go2NavPPORunnerPureMazeCfg,
|
||||
},
|
||||
)
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Agent configurations for Go2 navigation tasks."""
|
||||
|
||||
from . import rsl_rl_cfg
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""RSL-RL agent configurations for Unitree Go2 navigation tasks.
|
||||
|
||||
The policy block is intentionally identical to ``B2WNavPPORunnerCfg`` so that a
|
||||
B2W checkpoint can be warm-started via ``--resume`` / ``--load_run`` with
|
||||
``strict=True`` state-dict loading.
|
||||
"""
|
||||
|
||||
from isaaclab.utils import configclass
|
||||
|
||||
from isaaclab_nav_task.navigation.config.rl_cfg import (
|
||||
RslRlOnPolicyRunnerCfg,
|
||||
RslRlPpoActorCriticCfg,
|
||||
RslRlPpoAlgorithmCfg,
|
||||
)
|
||||
|
||||
|
||||
@configclass
|
||||
class Go2NavPPORunnerCfg(RslRlOnPolicyRunnerCfg):
|
||||
"""PPO runner configuration for Go2 navigation, tuned for fine-tuning from a B2W checkpoint."""
|
||||
|
||||
num_steps_per_env = 16
|
||||
max_iterations = 5000
|
||||
save_interval = 200
|
||||
# Use TensorBoard by default; wandb requires WANDB_API_KEY and an interactive
|
||||
# tty for first-time login, neither of which is available inside the headless
|
||||
# docker container. All downstream cfgs (Dev / PureMaze) already override to
|
||||
# tensorboard; the base now matches so the mixed-terrain task
|
||||
# ``Isaac-Nav-PPO-Go2-v0`` no longer crashes on cold start.
|
||||
logger = "tensorboard"
|
||||
seed = 42
|
||||
wandb_project = "isaaclab_nav_go2"
|
||||
experiment_name = "go2_navigation_ppo_ft_from_b2w"
|
||||
empirical_normalization = False
|
||||
reward_shifting_value = 0.05
|
||||
|
||||
# IMPORTANT: must match the B2W policy block byte-for-byte so that
|
||||
# ActorCriticSRU.load_state_dict(..., strict=True) succeeds.
|
||||
policy = RslRlPpoActorCriticCfg(
|
||||
class_name="ActorCriticSRU",
|
||||
init_noise_std=0.5, # ↓ vs 1.0: warm-start, less exploration noise
|
||||
actor_hidden_dims=[512, 256, 128],
|
||||
critic_hidden_dims=[512, 256, 128],
|
||||
activation="elu",
|
||||
rnn_hidden_size=512,
|
||||
rnn_type="lstm_sru",
|
||||
rnn_num_layers=1,
|
||||
dropout=0.2,
|
||||
num_cameras=1,
|
||||
image_input_dims=(64, 5, 8),
|
||||
height_input_dims=(64, 7, 7),
|
||||
)
|
||||
|
||||
# Conservative fine-tuning hyperparameters: smaller LR, tighter clip,
|
||||
# smaller KL target, lower grad-norm cap.
|
||||
algorithm = RslRlPpoAlgorithmCfg(
|
||||
class_name="PPO",
|
||||
value_loss_coef=0.05,
|
||||
use_clipped_value_loss=True,
|
||||
clip_param=0.1,
|
||||
value_clip_param=0.1,
|
||||
entropy_coef=0.001,
|
||||
num_learning_epochs=3,
|
||||
num_mini_batches=4,
|
||||
learning_rate=3.0e-4,
|
||||
schedule="adaptive",
|
||||
gamma=0.995,
|
||||
lam=0.95,
|
||||
desired_kl=0.005,
|
||||
max_grad_norm=0.5,
|
||||
)
|
||||
|
||||
|
||||
@configclass
|
||||
class Go2NavPPORunnerDevCfg(Go2NavPPORunnerCfg):
|
||||
"""Dev cfg used by the smoke-test task (Isaac-Nav-PPO-Go2-Dev-v0).
|
||||
|
||||
Unlike the production ``Go2NavPPORunnerCfg`` (whose hyperparameters are
|
||||
deliberately conservative for warm-starting from a B2W checkpoint), the dev
|
||||
cfg is meant for *from-scratch* Go2 training with the Odin1 camera. The
|
||||
conservative FT settings (entropy_coef=0.001, desired_kl=0.005, clip=0.1,
|
||||
lr=3e-4) caused exploration to collapse (noise_std plateaued at ~0.157) and
|
||||
success to stall at ~0.5 by 23k iters. Here we re-open exploration and the
|
||||
learning rate so the policy can escape that local optimum.
|
||||
"""
|
||||
|
||||
def __post_init__(self):
|
||||
super().__post_init__()
|
||||
self.max_iterations = 300
|
||||
self.experiment_name = "go2_navigation_ppo_dev"
|
||||
self.logger = "tensorboard"
|
||||
|
||||
# ---- Phase 1 (from-scratch, 0->2000): re-open exploration ----
|
||||
# init_noise_std only takes effect on a from-scratch run (a resumed
|
||||
# run loads the std from the checkpoint, which was ~0.76 after Phase 1).
|
||||
# Phase 1 broke the 0.5 plateau (success ~0.65, noise_std held at 0.76),
|
||||
# but two issues appeared: (a) adaptive LR floored at 1e-5 because
|
||||
# desired_kl=0.01 was too tight against clip=0.2/entropy=0.005, throttling
|
||||
# late updates; (b) Loss/value_function spiked to ~127 around iter 1600.
|
||||
#
|
||||
# ---- Phase 2 (resume 2000->5000): refine & stabilise ----
|
||||
# Relax desired_kl so adaptive LR can climb off the 1e-5 floor, anneal
|
||||
# exploration down, and tighten clip to curb the value-loss instability.
|
||||
#
|
||||
# ---- Phase 3 (resume 7000->14000, difficulty [0.2, 0.6]): ----
|
||||
# Kept Phase 2 hyperparams. Result: success 0.93, base_contact -71%,
|
||||
# tip-over -76%. Confirmed depth is used and avoidance generalises when
|
||||
# the task forces it.
|
||||
#
|
||||
# ---- Phase 4 (resume 14000->24000, difficulty [0.3, 0.8]): ----
|
||||
# noise_std fell to ~0.20 in Phase 3 (close to collapse). The Phase 4
|
||||
# difficulty jump (0.6 -> 0.8) demands fresh exploration on unseen
|
||||
# terrain, so re-open entropy a notch. Result: success climbed 0 -> 0.88
|
||||
# (peak 0.91 @ iter 20519). But noise_std overshot to 0.33 by iter 23999,
|
||||
# LR hit 1e-5 floor again, and success retreated from 0.905 -> 0.876.
|
||||
#
|
||||
# ---- Phase 5 (resume 24000->?, difficulty [0.3, 0.8]): refine ----
|
||||
# Anneal entropy back to let noise_std settle ~0.22-0.25 so the policy
|
||||
# can stop trembling and finish the last refinement past 0.91 success.
|
||||
self.policy.init_noise_std = 1.0 # only matters on a fresh run
|
||||
self.algorithm.entropy_coef = 0.003 # 0.005 -> 0.003: anneal exploration for Phase 5 refinement
|
||||
self.algorithm.desired_kl = 0.02 # 0.01 -> 0.02: let adaptive LR recover off the 1e-5 floor
|
||||
self.algorithm.clip_param = 0.15 # 0.2 -> 0.15: smaller, more stable policy updates
|
||||
self.algorithm.value_clip_param = 0.15 # 0.2 -> 0.15: match, curb value-loss spikes
|
||||
self.algorithm.learning_rate = 1.0e-3 # adaptive ceiling reference
|
||||
self.algorithm.num_learning_epochs = 5 # keep: more updates per batch
|
||||
self.algorithm.max_grad_norm = 0.8 # 1.0 -> 0.8: tighten to damp the value-fn spike
|
||||
|
||||
|
||||
@configclass
|
||||
class Go2NavPPORunnerMixedCfg(Go2NavPPORunnerDevCfg):
|
||||
"""Cold-start hyperparameters for mixed-terrain training (maze + non_maze
|
||||
+ pits) on the full-size ``Isaac-Nav-PPO-Go2-v0`` task.
|
||||
|
||||
Inherits from the Dev cfg (which already overrides the B2W-FT defaults to
|
||||
something usable from scratch), but rolls the *exploration-heavy* knobs
|
||||
BACK to the Phase 1/2 values that were proven to break the 0.5 plateau in
|
||||
the dev curriculum, rather than the Phase 5 refinement settings the Dev cfg
|
||||
currently sits at.
|
||||
|
||||
Distilled lessons from the dev curriculum (see comments in
|
||||
``Go2NavPPORunnerDevCfg``):
|
||||
* Phase 1 (entropy=0.005, init_std=1.0): broke success 0.5 -> 0.65 plateau
|
||||
but kl=0.01 was too tight (LR floored at 1e-5).
|
||||
* Phase 2 (kl=0.02, clip=0.15, epochs=5): unflored the LR and tamed the
|
||||
Loss/value_function spike.
|
||||
* Phase 5 (entropy=0.003): refinement-only, kills exploration too early
|
||||
for a from-scratch run.
|
||||
|
||||
Cold-start recipe = Phase 1 exploration + Phase 2 stability:
|
||||
entropy=0.005, init_std=1.0, kl=0.02, clip=0.15, lr=1e-3, epochs=5,
|
||||
grad_norm=0.8.
|
||||
"""
|
||||
|
||||
def __post_init__(self):
|
||||
super().__post_init__()
|
||||
# Independent experiment dir keeps mixed runs out of the dev TB tree.
|
||||
self.experiment_name = "go2_navigation_ppo_mixed"
|
||||
|
||||
# Override Dev's Phase 5 refinement back to cold-start values.
|
||||
self.policy.init_noise_std = 1.0 # Phase 1: re-open exploration
|
||||
self.algorithm.entropy_coef = 0.005 # Phase 1/4: cold-start exploration
|
||||
self.algorithm.desired_kl = 0.02 # Phase 2: avoid 1e-5 LR floor
|
||||
self.algorithm.clip_param = 0.15 # Phase 2: avoid value-loss spikes
|
||||
self.algorithm.value_clip_param = 0.15
|
||||
self.algorithm.learning_rate = 1.0e-3 # adaptive ceiling
|
||||
self.algorithm.num_learning_epochs = 5
|
||||
self.algorithm.max_grad_norm = 0.8
|
||||
|
||||
|
||||
@configclass
|
||||
class Go2NavPPORunnerPureMazeCfg(Go2NavPPORunnerDevCfg):
|
||||
"""Hyperparameters for the pure-maze training task.
|
||||
|
||||
Inherits the Phase 5 dev hyperparams (they shipped a strong checkpoint at
|
||||
iter 27800 on the mixed terrain). Only the log directory differs so
|
||||
pure-maze runs don't mix with the dev curriculum's TensorBoard history.
|
||||
"""
|
||||
|
||||
def __post_init__(self):
|
||||
super().__post_init__()
|
||||
self.experiment_name = "go2_navigation_ppo_puremaze"
|
||||
+445
@@ -0,0 +1,445 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Unitree Go2 specific configuration for navigation environment."""
|
||||
|
||||
import os
|
||||
|
||||
from isaaclab.utils import configclass
|
||||
from isaaclab.managers import SceneEntityCfg
|
||||
|
||||
from isaaclab_nav_task.navigation.navigation_env_cfg import NavigationEnvCfg
|
||||
import isaaclab_nav_task.navigation.mdp as mdp
|
||||
|
||||
from isaaclab_nav_task.navigation.assets import GO2_CFG, ISAACLAB_NAV_TASKS_ASSETS_DIR # isort: skip
|
||||
|
||||
|
||||
# Go2 has 12 leg joints (no wheels). Joint names use the underscore convention
|
||||
# from the IsaacLab Go2 USD: FL_hip_joint, FL_thigh_joint, FL_calf_joint, ...
|
||||
LEG_JOINT_NAMES = [".*_hip_joint", ".*_thigh_joint", ".*_calf_joint"]
|
||||
|
||||
|
||||
@configclass
|
||||
class Go2NavigationEnvCfg(NavigationEnvCfg):
|
||||
"""Navigation env for Unitree Go2 (legs-only quadruped).
|
||||
|
||||
The locomotion checkpoint expected at
|
||||
``assets/data/Policies/locomotion/go2/policy_go2_jit.pt`` was converted from
|
||||
a rsl_rl checkpoint trained on Isaac-Velocity-Flat-Unitree-Go2-v0:
|
||||
- input : 48-dim observation (matches sru-navigation-sim's
|
||||
LowLevelPolicyCfg)
|
||||
- output : 12-dim joint position deltas (one per leg joint)
|
||||
"""
|
||||
|
||||
def __post_init__(self):
|
||||
super().__post_init__()
|
||||
|
||||
from isaaclab_nav_task.navigation.mdp.observations import initialize_depth_noise_generator
|
||||
from isaaclab_nav_task.navigation.mdp.depth_utils.camera_config import get_camera_config
|
||||
|
||||
initialize_depth_noise_generator(robot_name="go2", use_jit_precompiled=False)
|
||||
camera_config = get_camera_config("go2")
|
||||
# Camera resolution is consumed implicitly through the encoder; sru-nav
|
||||
# always feeds (64, 40) into the VAE regardless of robot.
|
||||
_ = camera_config
|
||||
|
||||
# ---- Robot ----
|
||||
self.scene.robot = GO2_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot")
|
||||
|
||||
# Go2's body link is named "base" in the IsaacLab USD (not "base_link"
|
||||
# like B2W).
|
||||
self.scene.raycast_camera.prim_path = "{ENV_REGEX_NS}/Robot/base"
|
||||
# Real-robot Odin1 mount on Go2: 25.8 cm forward, 15.4 cm above body
|
||||
# center, camera looking straight ahead (no pitch).
|
||||
# NOTE: The extrinsic Tcl from the Odin1 calibration is camera-from-lidar,
|
||||
# not camera-from-base. Until we have T_base_lidar (lidar pose in Go2 base
|
||||
# frame), keep this measured mount offset rather than chaining Tcl.
|
||||
self.scene.raycast_camera.offset.pos = (0.258, 0.0, 0.154)
|
||||
self.scene.raycast_camera.offset.rot = (1.0, 0.0, 0.0, 0.0)
|
||||
self.scene.height_scanner_critic.prim_path = "{ENV_REGEX_NS}/Robot/base"
|
||||
|
||||
# ---- Camera intrinsics: Odin1 (LiDAR-aligned depth) ----
|
||||
# Real Odin1 @ 1600x1296:
|
||||
# fx = 737.357, fy = 737.292, cx = 794.372, cy = 666.259
|
||||
# hFOV ~94.67 deg, vFOV ~82.65 deg
|
||||
# To preserve the FOV while keeping the upstream downsample_factor=3
|
||||
# (raycast at 192x120 then downsample to the VAE-required 64x40), we
|
||||
# scale the intrinsics linearly:
|
||||
# fx_192 = 737.357 * 192/1600 = 88.48 px
|
||||
# fy_120 = 737.292 * 120/1296 = 68.27 px
|
||||
# cx_192 = 794.372 * 192/1600 = 95.32 px
|
||||
# cy_120 = 666.259 * 120/1296 = 61.69 px
|
||||
# Distortion (k2..k7) is ignored: raycast uses an ideal pinhole. The
|
||||
# real-side pipeline must undistort before feeding the network.
|
||||
# max_distance raised slightly because Odin1's wider FOV picks up more
|
||||
# nearby clutter; keep 11 m to match upstream.
|
||||
from isaaclab.sensors import patterns
|
||||
self.scene.raycast_camera.max_distance = 11.0
|
||||
self.scene.raycast_camera.pattern_cfg = patterns.PinholeCameraPatternCfg.from_ros_camera_info(
|
||||
fx=88.48,
|
||||
fy=68.27,
|
||||
cx=95.32,
|
||||
cy=61.69,
|
||||
width=192,
|
||||
height=120,
|
||||
downsample_factor=3, # 192x120 -> 64x40 to match VAE input
|
||||
)
|
||||
|
||||
# ---- Goal placement ----
|
||||
# The default goal height offset (0.2-0.8 m above ground) is tuned for
|
||||
# B2W's body height (~0.5-0.6 m). Go2 stands at ~0.3 m, so lower the
|
||||
# range to (0.1, 0.4) m to keep the goal marker near the Go2 body.
|
||||
# NOTE: success/termination is purely horizontal (xy), so this is mostly
|
||||
# a visual fix + removes the small constant z-error in the 3D
|
||||
# reach_goal_xy_soft reward term.
|
||||
self.commands.robot_goal.goal_height_offset_range = (0.1, 0.4)
|
||||
|
||||
# ---- Termination ----
|
||||
# Penalize/terminate if the body, hips, thighs, or head links hit
|
||||
# something. Go2's main body is "base"; the front "head" is split into
|
||||
# two extra rigid links ("Head_upper" / "Head_lower" in the upstream
|
||||
# Unitree Go2 USD) which stick forward ~10cm past the base. Without
|
||||
# those head links in the watch-list, GUI playback shows the snout
|
||||
# visually crashing into walls while the base contact sensor stays
|
||||
# silent and the episode does not terminate. Including them closes
|
||||
# that loophole.
|
||||
self.terminations.base_contact.params = {
|
||||
"sensor_cfg": SceneEntityCfg(
|
||||
"contact_forces",
|
||||
body_names=["base", ".*_hip", ".*_thigh", "Head_upper", "Head_lower"],
|
||||
),
|
||||
"threshold": 1.0,
|
||||
}
|
||||
|
||||
# Diagnostic-only: tighten `terrain_fall` so it actually fires when the
|
||||
# robot drops into the pit terrain. The base default of -2.0m never
|
||||
# triggered for Go2 (standing base_z ~+0.4m, typical pit depth 0.75-2.25m
|
||||
# -> body z bottoms out around -1.1m, well above -2.0m), making
|
||||
# `Episode_Termination/terrain_fall` permanently 0 across phases 1-5.
|
||||
# -0.3m means: body must be ~0.7m below normal standing height to fire,
|
||||
# which cleanly captures real pit falls without flagging walking dips.
|
||||
# NOTE: `terrain_fall` is `time_out=True`, so it does NOT trigger the
|
||||
# -50 `episode_termination` penalty -- this is purely a metric fix.
|
||||
self.terminations.terrain_fall.params = {"fall_height_threshold": -0.3}
|
||||
|
||||
# ---- Action interface (legs only, no wheels) ----
|
||||
self.actions.velocity_command.low_level_position_action = mdp.JointPositionActionCfg(
|
||||
asset_name="robot",
|
||||
joint_names=LEG_JOINT_NAMES,
|
||||
scale=0.25, # MUST match the scale used to train policy_go2_jit.pt
|
||||
use_default_offset=True,
|
||||
)
|
||||
# Disable the velocity-action branch entirely (patched in
|
||||
# navigation_se2_actions.py to be optional).
|
||||
self.actions.velocity_command.low_level_velocity_action = None
|
||||
self.actions.velocity_command.low_level_policy_file = os.path.join(
|
||||
ISAACLAB_NAV_TASKS_ASSETS_DIR,
|
||||
"Policies", "locomotion", "go2", "policy_go2_jit.pt",
|
||||
)
|
||||
# SE2 command space scale: Go2 cannot match B2W's wheeled top speed,
|
||||
# so we shrink the SRU command range to what Go2 can actually track.
|
||||
# The high-level SRU policy was trained on B2W with [1.0, 1.0, 1.0]; we
|
||||
# shrink each axis so the same network output produces feasible Go2
|
||||
# commands.
|
||||
self.actions.velocity_command.scale = [0.6, 0.3, 0.7]
|
||||
|
||||
# ---- Reward shaping ----
|
||||
self.rewards.joint_acc_l2_joint.params = {
|
||||
"asset_cfg": SceneEntityCfg("robot", joint_names=LEG_JOINT_NAMES),
|
||||
}
|
||||
# Keep the B2W default termination penalty (-50.0). G0-G2 confirmed the
|
||||
# Go2 locomotion JIT is stable enough that we do not need the relaxed
|
||||
# -25 hedge anymore; restoring -50 makes wall hits / falls genuinely
|
||||
# costly so the policy stops trading collisions for goal reward.
|
||||
# (Only fires on `base_contact` + `large_pitch_angle`; `time_out`,
|
||||
# `at_goal`, `terrain_fall` are all marked time_out=True and don't
|
||||
# trigger this term.)
|
||||
self.rewards.episode_termination.weight = -50.0
|
||||
|
||||
# Forward-facing depth camera only senses obstacles ahead of the robot.
|
||||
# In G2.0 the agent learned to walk *backwards* (vx < 0) to hide obstacles
|
||||
# from the camera and bypass forward-collision termination. Enable the
|
||||
# backward-movement penalty (default weight is 0.0 in the base cfg).
|
||||
# NOTE: the base CurriculumCfg disables this penalty after 500 global
|
||||
# steps; if backward-walking re-emerges late in training, either delete
|
||||
# ``curriculum.disable_backward_penalty`` or lift its ``disable_after_steps``.
|
||||
self.rewards.backward_movement_penalty.weight = -1.0
|
||||
|
||||
# ---- Domain randomization ----
|
||||
# Go2 responds slower than wheels; widen the low-pass filter range.
|
||||
self.events.randomize_low_pass_filter_alpha.params = {
|
||||
"alpha_range": (0.3, 0.7),
|
||||
"action_term": "velocity_command",
|
||||
"per_dimension": True,
|
||||
"alpha_range_vx": (0.3, 0.7),
|
||||
"alpha_range_vy": (0.3, 0.7),
|
||||
"alpha_range_omega": (0.3, 0.7),
|
||||
}
|
||||
|
||||
# ---- Terrain ----
|
||||
# The Go2 locomotion .pt is flat-trained, so start with easier terrain.
|
||||
# Defaults assume RESUMING a non-trivial ckpt (max_init level 5, band
|
||||
# [0.3, 0.8]). For a COLD START set GO2_DIFFICULTY="0.0,0.4" (and the
|
||||
# env var GO2_INIT_LEVEL=0 if you want everyone to start at the easiest
|
||||
# row), otherwise the policy gets dropped into mid-difficulty terrain
|
||||
# and stalls. Curriculum stays ON in both cases so envs auto-promote
|
||||
# toward the high end as they succeed.
|
||||
lo, hi = 0.3, 0.8
|
||||
_diff = os.environ.get("GO2_DIFFICULTY", "").strip()
|
||||
if _diff:
|
||||
_parts = _diff.replace(" ", "").split(",")
|
||||
lo, hi = float(_parts[0]), float(_parts[1])
|
||||
init_level = 5
|
||||
_lvl = os.environ.get("GO2_INIT_LEVEL", "").strip()
|
||||
if _lvl:
|
||||
init_level = int(_lvl)
|
||||
self.scene.terrain.max_init_terrain_level = init_level
|
||||
self.scene.terrain.terrain_generator.difficulty_range = [lo, hi]
|
||||
self.scene.terrain.terrain_generator.curriculum = True
|
||||
print(f"[Go2 Mixed] difficulty=[{lo}, {hi}], max_init_terrain_level={init_level} (curriculum on)")
|
||||
|
||||
# Drop the dedicated stairs sub-terrain for Go2: the locomotion JIT is
|
||||
# trained on flat ground only, climbing stairs is unreliable, and the
|
||||
# platform_mask on stair tops would otherwise bias goal sampling
|
||||
# towards stair platforms (see PositionSampler.platform_repeat_count=10
|
||||
# in mdp/navigation/goal_commands.py).
|
||||
# NOTE: ``add_stairs_to_maze`` flag exists in HfMazeTerrainCfg but is
|
||||
# never consumed by hf_terrains_maze.py, so the only real stair source
|
||||
# is the ``"stairs"`` sub-terrain. We rebalance the remaining 3 to keep
|
||||
# roughly the original maze:non_maze:pits ratio (3:2:2 -> ~0.43/0.29/0.29).
|
||||
sub_terrains = self.scene.terrain.terrain_generator.sub_terrains
|
||||
if "stairs" in sub_terrains:
|
||||
del sub_terrains["stairs"]
|
||||
if "maze" in sub_terrains:
|
||||
sub_terrains["maze"].proportion = 0.43
|
||||
if "non_maze" in sub_terrains:
|
||||
sub_terrains["non_maze"].proportion = 0.29
|
||||
if "pits" in sub_terrains:
|
||||
sub_terrains["pits"].proportion = 0.28
|
||||
|
||||
# ---- Shrink tile size for 12 GB VRAM ----
|
||||
# Defaults: 30m x 30m tiles with horizontal_scale=0.1 -> 300x300 cells
|
||||
# per tile heightfield, x 6 rows x 30 cols x 3 sub-terrains = ~16M
|
||||
# heightfield cells + 3 sub-terrain collision meshes. On a 12 GB 5070
|
||||
# that OOMs above ~768 envs. Halve cell_size to 1.0m (matches what the
|
||||
# PureMaze runs used, where 1024 envs ran stably): tile shrinks to
|
||||
# 15m x 15m, heightfield drops 4x to ~4M cells. Override via env var
|
||||
# GO2_CELL_SIZE if you want to go back to the paper-default 2.0m.
|
||||
_cell = os.environ.get("GO2_CELL_SIZE", "1.0").strip()
|
||||
if _cell:
|
||||
new_cell = float(_cell)
|
||||
for cfg_sub in sub_terrains.values():
|
||||
cfg_sub.cell_size = new_cell
|
||||
# grid_size stays (15, 15) -> tile_size = 15 * cell_size meters.
|
||||
tile_m = 15 * new_cell
|
||||
self.scene.terrain.terrain_generator.size = (tile_m, tile_m)
|
||||
print(f"[Go2 Mixed] cell_size={new_cell}m -> tile={tile_m}m "
|
||||
f"(set GO2_CELL_SIZE=2.0 to restore paper defaults)")
|
||||
|
||||
|
||||
@configclass
|
||||
class Go2NavigationEnvCfg_DEV(Go2NavigationEnvCfg):
|
||||
"""Development configuration with smaller terrain and lower difficulty."""
|
||||
|
||||
def __post_init__(self):
|
||||
super().__post_init__()
|
||||
self.scene.terrain.terrain_generator.num_rows = 2
|
||||
self.scene.terrain.terrain_generator.num_cols = 30
|
||||
# The Go2 locomotion JIT is flat-trained. Starting at difficulty 0.3-0.8
|
||||
# with no curriculum produced ~16% tip-overs (large_pitch_angle) and
|
||||
# stalled success at ~0.5. Start from the easiest terrain and let the
|
||||
# curriculum ramp difficulty up as the policy succeeds.
|
||||
#
|
||||
# Phase 1/2 trained on [0.0, 0.4] (success ~0.86, depth confirmed used
|
||||
# via ablation). Phase 3 raises the band so the avoidance behaviour
|
||||
# generalises to denser obstacles / deeper pits. Control the band per
|
||||
# run with DEV_DIFFICULTY="lo,hi" (default stays [0.0, 0.4]); e.g.
|
||||
# DEV_DIFFICULTY="0.2,0.6" (recommended Phase 3 bridge)
|
||||
# DEV_DIFFICULTY="0.3,0.8" (Phase 4, near paper level)
|
||||
# max_init_terrain_level stays 0 so a resumed policy re-enters at the
|
||||
# easy end of the new band and the curriculum re-ramps from there.
|
||||
lo, hi = 0.0, 0.4
|
||||
_dev_diff = os.environ.get("DEV_DIFFICULTY", "").strip()
|
||||
if _dev_diff:
|
||||
_parts = _dev_diff.replace(" ", "").split(",")
|
||||
lo, hi = float(_parts[0]), float(_parts[1])
|
||||
self.scene.terrain.max_init_terrain_level = 0
|
||||
self.scene.terrain.terrain_generator.difficulty_range = [lo, hi]
|
||||
self.scene.terrain.terrain_generator.curriculum = True
|
||||
print(f"[Go2 DEV] terrain difficulty_range = [{lo}, {hi}] (curriculum on)")
|
||||
|
||||
|
||||
@configclass
|
||||
class Go2NavigationEnvCfg_PureMaze(Go2NavigationEnvCfg):
|
||||
"""Pure-maze training configuration.
|
||||
|
||||
All tiles are paper-style mazes:
|
||||
* 100% ``maze`` sub-terrain (no ``non_maze`` / ``pits`` sub-terrains).
|
||||
* Walls are uniform full-height rectangles (no randomized pillar/bar/cross
|
||||
obstacles inserted into the maze pattern).
|
||||
* Curriculum on, ramps difficulty from open to dense corridors.
|
||||
|
||||
Env-var overrides:
|
||||
* ``PUREMAZE_DIFFICULTY="lo,hi"``: difficulty band (default ``"0.0,1.0"``;
|
||||
higher band -> denser corridors / more dead-ends).
|
||||
* ``PUREMAZE_CELL_SIZE``: meters per maze cell (default 2.0). Lowering
|
||||
tightens corridors; tile size scales accordingly so total terrain area
|
||||
stays the same per tile in cells.
|
||||
"""
|
||||
|
||||
def __post_init__(self):
|
||||
super().__post_init__()
|
||||
|
||||
sub_terrains = self.scene.terrain.terrain_generator.sub_terrains
|
||||
# Lock to 100% maze, paper-style walls.
|
||||
for name in list(sub_terrains.keys()):
|
||||
sub_terrains[name].proportion = 1.0 if name == "maze" else 0.0
|
||||
if "maze" in sub_terrains:
|
||||
sub_terrains["maze"].randomize_wall = False
|
||||
sub_terrains["maze"].random_wall_ratio = 0.0
|
||||
|
||||
# Difficulty range (curriculum on, ramps from easy to hard).
|
||||
lo, hi = 0.0, 1.0
|
||||
_diff = os.environ.get("PUREMAZE_DIFFICULTY", "").strip()
|
||||
if _diff:
|
||||
_parts = _diff.replace(" ", "").split(",")
|
||||
lo, hi = float(_parts[0]), float(_parts[1])
|
||||
self.scene.terrain.max_init_terrain_level = 0
|
||||
self.scene.terrain.terrain_generator.difficulty_range = [lo, hi]
|
||||
self.scene.terrain.terrain_generator.curriculum = True
|
||||
|
||||
# Cell size (corridor width).
|
||||
_cell = os.environ.get("PUREMAZE_CELL_SIZE", "").strip()
|
||||
if _cell:
|
||||
new_cell = float(_cell)
|
||||
for cfg_sub in sub_terrains.values():
|
||||
cfg_sub.cell_size = new_cell
|
||||
tile_m = 15 * new_cell
|
||||
self.scene.terrain.terrain_generator.size = (tile_m, tile_m)
|
||||
print(f"[Go2 PureMaze] cell_size={new_cell}m -> tile={tile_m}m, "
|
||||
f"corridor ~{new_cell * 0.6:.2f}-{new_cell * 0.9:.2f}m")
|
||||
|
||||
# Terrain grid dimensions. Defaults are compact (3×10=30 tiles) to save
|
||||
# VRAM; the original 6×30=180 tiles wasted mesh memory when most tiles
|
||||
# were never visited (especially with few envs / play). Override via
|
||||
# PUREMAZE_NUM_ROWS / PUREMAZE_NUM_COLS for large-scale training.
|
||||
_rows = int(os.environ.get("PUREMAZE_NUM_ROWS", "3"))
|
||||
_cols = int(os.environ.get("PUREMAZE_NUM_COLS", "10"))
|
||||
self.scene.terrain.terrain_generator.num_rows = _rows
|
||||
self.scene.terrain.terrain_generator.num_cols = _cols
|
||||
|
||||
print(f"[Go2 PureMaze] 100% maze sub-terrain, classic walls, "
|
||||
f"difficulty=[{lo}, {hi}] (curriculum on), "
|
||||
f"grid={_rows}x{_cols}={_rows*_cols} tiles")
|
||||
|
||||
|
||||
@configclass
|
||||
class Go2NavigationEnvCfg_PLAY(Go2NavigationEnvCfg):
|
||||
"""Evaluation/visualization configuration."""
|
||||
|
||||
def __post_init__(self):
|
||||
super().__post_init__()
|
||||
|
||||
self.scene.num_envs = 20
|
||||
self.scene.env_spacing = 2.5
|
||||
self.scene.terrain.max_init_terrain_level = None
|
||||
if self.scene.terrain.terrain_generator is not None:
|
||||
self.scene.terrain.terrain_generator.num_rows = 2
|
||||
self.scene.terrain.terrain_generator.num_cols = 2
|
||||
|
||||
# ---- Evaluate on the SAME difficulty the policy was trained on ----
|
||||
# The base Go2NavigationEnvCfg uses difficulty_range=[0.3, 0.8], but
|
||||
# the Dev curriculum (what model_*.pt was actually trained on) ran on
|
||||
# [0.0, 0.4]. Replaying on [0.3, 0.8] shows the policy unseen-hard
|
||||
# terrain and makes it look like it "can't avoid" obstacles. Default
|
||||
# the PLAY difficulty to the training band for an honest read; allow
|
||||
# an explicit stress-test override via PLAY_DIFFICULTY="lo,hi".
|
||||
lo, hi = 0.0, 0.4
|
||||
_play_diff = os.environ.get("PLAY_DIFFICULTY", "").strip()
|
||||
if _play_diff:
|
||||
_parts = _play_diff.replace(" ", "").split(",")
|
||||
lo, hi = float(_parts[0]), float(_parts[1])
|
||||
self.scene.terrain.terrain_generator.difficulty_range = [lo, hi]
|
||||
# Fixed difficulty band for evaluation (no curriculum ramping).
|
||||
self.scene.terrain.terrain_generator.curriculum = False
|
||||
print(f"[Go2 PLAY] terrain difficulty_range = [{lo}, {hi}] (curriculum off)")
|
||||
|
||||
# ---- Stress-test knobs for narrow-passage / dense-scene eval ----
|
||||
# PLAY_CELL_SIZE: meters per maze cell (default 2.0). Lowering this
|
||||
# tightens corridor width without changing tile size:
|
||||
# 2.0m -> 1.7m-2.0m open corridors (default; very wide for Go2)
|
||||
# 1.5m -> 1.0m-1.3m corridors (Go2 fits comfortably with margin)
|
||||
# 1.2m -> 0.7m-0.9m corridors (tight, real perception test)
|
||||
# 1.0m -> 0.5m-0.7m corridors (Go2 body width ~0.3m -> very tight)
|
||||
# NOTE: grid_size stays (15,15) so tile size shrinks proportionally
|
||||
# (30m -> 15m at cell_size=1.0). To preserve outer terrain footprint,
|
||||
# the tile size is rescaled below.
|
||||
_play_cell = os.environ.get("PLAY_CELL_SIZE", "").strip()
|
||||
# PLAY_MAZE_ONLY=1: force 100% maze sub-terrain (drop pits/non_maze)
|
||||
# so every tile is a corridor navigation challenge -- no easy open
|
||||
# tiles diluting the sample.
|
||||
_maze_only = os.environ.get("PLAY_MAZE_ONLY", "").strip().lower() in ("1", "true", "yes")
|
||||
|
||||
sub_terrains = self.scene.terrain.terrain_generator.sub_terrains
|
||||
if _maze_only and "maze" in sub_terrains:
|
||||
for name in list(sub_terrains.keys()):
|
||||
sub_terrains[name].proportion = 1.0 if name == "maze" else 0.0
|
||||
print(f"[Go2 PLAY] PLAY_MAZE_ONLY=1 -> 100% maze sub-terrain")
|
||||
|
||||
# PLAY_SUBTERRAIN_MIX="maze=0.5,non_maze=0.3,pits=0.2"
|
||||
# Override any subset of sub-terrain proportions. Names not listed
|
||||
# are left at their training-cfg default. Values do NOT need to sum
|
||||
# to 1.0 (IsaacLab normalizes them internally before sampling).
|
||||
# Setting a value to 0 effectively disables that sub-terrain.
|
||||
_mix = os.environ.get("PLAY_SUBTERRAIN_MIX", "").strip()
|
||||
if _mix:
|
||||
overrides = {}
|
||||
for part in _mix.split(","):
|
||||
if "=" not in part:
|
||||
continue
|
||||
k, v = part.split("=", 1)
|
||||
overrides[k.strip()] = float(v.strip())
|
||||
for name, prop in overrides.items():
|
||||
if name in sub_terrains:
|
||||
sub_terrains[name].proportion = prop
|
||||
else:
|
||||
print(f"[Go2 PLAY] WARNING: unknown sub-terrain '{name}' "
|
||||
f"(known: {list(sub_terrains.keys())})")
|
||||
final = {n: sub_terrains[n].proportion for n in sub_terrains}
|
||||
print(f"[Go2 PLAY] PLAY_SUBTERRAIN_MIX -> {final}")
|
||||
|
||||
if _play_cell:
|
||||
new_cell = float(_play_cell)
|
||||
for cfg_sub in sub_terrains.values():
|
||||
cfg_sub.cell_size = new_cell
|
||||
# Keep grid_size=(15,15) -> tile size = 15 * cell_size meters.
|
||||
# Match outer tile size so the scene grid stays consistent.
|
||||
tile_m = 15 * new_cell
|
||||
self.scene.terrain.terrain_generator.size = (tile_m, tile_m)
|
||||
print(f"[Go2 PLAY] PLAY_CELL_SIZE={new_cell}m -> tile={tile_m}m, "
|
||||
f"corridor ~{new_cell * 0.6:.2f}-{new_cell * 0.9:.2f}m")
|
||||
|
||||
# PLAY_CLASSIC_MAZE=1: reproduce paper-style mazes with uniform
|
||||
# rectangular walls and clear corridors (no randomized pillar / bar
|
||||
# / cross obstacles inserted into the maze pattern). Affects only
|
||||
# the `maze` sub-terrain since `non_maze` and `pits` rely on the
|
||||
# randomized shapes for their gameplay.
|
||||
_classic = os.environ.get("PLAY_CLASSIC_MAZE", "").strip().lower() in ("1", "true", "yes")
|
||||
if _classic and "maze" in sub_terrains:
|
||||
sub_terrains["maze"].randomize_wall = False
|
||||
sub_terrains["maze"].random_wall_ratio = 0.0
|
||||
print(f"[Go2 PLAY] PLAY_CLASSIC_MAZE=1 -> maze walls are full-height "
|
||||
f"rectangles (no randomized obstacle shapes)")
|
||||
|
||||
self.observations.policy.enable_corruption = False
|
||||
self.events.base_external_force_torque = None
|
||||
self.events.push_robot = None
|
||||
|
||||
# Visualize the depth-camera ray hits + height scanner grid in the GUI.
|
||||
# The RayCasterCamera draws a point per ray that hits geometry; the
|
||||
# density / pattern of these points is the effective FOV / resolution.
|
||||
self.scene.raycast_camera.debug_vis = True
|
||||
if self.scene.height_scanner_critic is not None:
|
||||
self.scene.height_scanner_critic.debug_vis = True
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Custom RSL-RL configuration classes for navigation tasks.
|
||||
|
||||
These config classes replace the standard Isaac Lab RL configs to support
|
||||
custom network architectures used in navigation tasks with depth camera inputs.
|
||||
"""
|
||||
|
||||
from dataclasses import MISSING
|
||||
from typing import Literal, Optional
|
||||
|
||||
from isaaclab.utils import configclass
|
||||
|
||||
|
||||
@configclass
|
||||
class RslRlPpoActorCriticCfg:
|
||||
"""Configuration for the PPO actor-critic networks with navigation extensions."""
|
||||
|
||||
class_name: str = "ActorCritic"
|
||||
"""The policy class name. Default is ActorCritic."""
|
||||
|
||||
init_noise_std: float = MISSING
|
||||
"""The initial noise standard deviation for the policy."""
|
||||
|
||||
actor_hidden_dims: list[int] = MISSING
|
||||
"""The hidden dimensions of the actor network."""
|
||||
|
||||
critic_hidden_dims: list[int] = MISSING
|
||||
"""The hidden dimensions of the critic network."""
|
||||
|
||||
activation: str = MISSING
|
||||
"""The activation function for the actor and critic networks."""
|
||||
|
||||
rnn_type: str = "lstm"
|
||||
"""The type of RNN to use."""
|
||||
|
||||
rnn_hidden_size: int = 256
|
||||
"""The hidden size of the RNN."""
|
||||
|
||||
rnn_num_layers: int = 1
|
||||
"""The number of layers in the RNN."""
|
||||
|
||||
dropout: float = 0.0
|
||||
"""The dropout rate for the first layer of the actor and critic networks."""
|
||||
|
||||
# Visual inputs
|
||||
num_cameras: int = 1
|
||||
"""Number of depth cameras encoded into the observation (1 or 2)."""
|
||||
|
||||
image_input_dims: tuple[int, int, int] = (64, 5, 8)
|
||||
"""Encoded depth feature shape as (C, H, W)."""
|
||||
|
||||
height_input_dims: tuple[int, int, int] = (64, 7, 7)
|
||||
"""Encoded height scan feature shape as (C, H, W). Default is (64, 7, 7) for 64*7*7=3136 features."""
|
||||
|
||||
|
||||
@configclass
|
||||
class RslRlPpoAlgorithmCfg:
|
||||
"""Configuration for the PPO algorithm."""
|
||||
|
||||
class_name: str = MISSING
|
||||
"""The algorithm class name. Default is PPO."""
|
||||
|
||||
value_loss_coef: float = MISSING
|
||||
"""The coefficient for the value loss."""
|
||||
|
||||
use_clipped_value_loss: bool = MISSING
|
||||
"""Whether to use clipped value loss."""
|
||||
|
||||
clip_param: float = MISSING
|
||||
"""The clipping parameter for the policy."""
|
||||
|
||||
value_clip_param: float = 0.2
|
||||
"""The value clipping parameter. Default is 0.2."""
|
||||
|
||||
entropy_coef: float = MISSING
|
||||
"""The coefficient for the entropy loss."""
|
||||
|
||||
num_learning_epochs: int = MISSING
|
||||
"""The number of learning epochs per update."""
|
||||
|
||||
num_mini_batches: int = MISSING
|
||||
"""The number of mini-batches per update."""
|
||||
|
||||
learning_rate: float = MISSING
|
||||
"""The learning rate for the policy."""
|
||||
|
||||
schedule: str = MISSING
|
||||
"""The learning rate schedule."""
|
||||
|
||||
gamma: float = MISSING
|
||||
"""The discount factor."""
|
||||
|
||||
lam: float = MISSING
|
||||
"""The lambda parameter for Generalized Advantage Estimation (GAE)."""
|
||||
|
||||
desired_kl: float = MISSING
|
||||
"""The desired KL divergence."""
|
||||
|
||||
max_grad_norm: float = MISSING
|
||||
"""The maximum gradient norm."""
|
||||
|
||||
|
||||
@configclass
|
||||
class RslRlOnPolicyRunnerCfg:
|
||||
"""Configuration of the runner for on-policy algorithms."""
|
||||
|
||||
seed: Optional[int] = 42
|
||||
"""The seed for the experiment. Default is 42."""
|
||||
|
||||
device: str = "cuda:0"
|
||||
"""The device for the rl-agent. Default is cuda:0."""
|
||||
|
||||
num_steps_per_env: int = MISSING
|
||||
"""The number of steps per environment per update."""
|
||||
|
||||
max_iterations: int = MISSING
|
||||
"""The maximum number of iterations."""
|
||||
|
||||
empirical_normalization: bool = MISSING
|
||||
"""Whether to use empirical normalization."""
|
||||
|
||||
policy: RslRlPpoActorCriticCfg = MISSING
|
||||
"""The policy configuration."""
|
||||
|
||||
algorithm: RslRlPpoAlgorithmCfg = MISSING
|
||||
"""The algorithm configuration."""
|
||||
|
||||
reward_shifting_value: float = 0.0
|
||||
"""The value to shift the reward by. Default is 0.0."""
|
||||
|
||||
##
|
||||
# Checkpointing parameters
|
||||
##
|
||||
|
||||
save_interval: int = MISSING
|
||||
"""The number of iterations between saves."""
|
||||
|
||||
experiment_name: str = MISSING
|
||||
"""The experiment name."""
|
||||
|
||||
run_name: str = ""
|
||||
"""The run name. Default is empty string."""
|
||||
|
||||
##
|
||||
# Logging parameters
|
||||
##
|
||||
|
||||
logger: Literal["tensorboard", "neptune", "wandb"] = "tensorboard"
|
||||
"""The logger to use. Default is tensorboard."""
|
||||
|
||||
neptune_project: str = "isaaclab"
|
||||
"""The neptune project name. Default is "isaaclab"."""
|
||||
|
||||
wandb_project: str = "isaaclab"
|
||||
"""The wandb project name. Default is "isaaclab"."""
|
||||
|
||||
##
|
||||
# Loading parameters
|
||||
##
|
||||
|
||||
resume: bool = False
|
||||
"""Whether to resume. Default is False."""
|
||||
|
||||
load_run: str = ".*"
|
||||
"""The run directory to load. Default is ".*" (all)."""
|
||||
|
||||
load_checkpoint: str = "model_.*.pt"
|
||||
"""The checkpoint file to load. Default is "model_.*.pt" (all)."""
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""MDP components for navigation tasks.
|
||||
|
||||
This module provides observations, rewards, terminations, curriculums,
|
||||
and actions specific to navigation tasks.
|
||||
"""
|
||||
|
||||
from isaaclab.envs.mdp import * # noqa: F401, F403
|
||||
|
||||
from .curriculums import * # noqa: F401, F403
|
||||
from .events import * # noqa: F401, F403
|
||||
from .rewards import * # noqa: F401, F403
|
||||
from .terminations import * # noqa: F401, F403
|
||||
from .observations import * # noqa: F401, F403
|
||||
from .navigation import * # noqa: F401, F403
|
||||
from .delay_manager import ObservationDelayManager, ObservationDelayManagerCfg, DelayBufferState # noqa: F401
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Curriculum functions for navigation tasks.
|
||||
|
||||
The functions can be passed to the :class:`isaaclab.managers.CurriculumTermCfg` object to enable
|
||||
the curriculum introduced by the function.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import torch
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from isaaclab.envs import ManagerBasedRLEnv
|
||||
|
||||
|
||||
def disable_backward_penalty_after_steps(
|
||||
env: ManagerBasedRLEnv,
|
||||
env_ids: Sequence[int],
|
||||
term_name: str = "backward_movement_penalty",
|
||||
num_steps: int = 1000
|
||||
) -> torch.Tensor:
|
||||
"""Curriculum that disables the backward movement penalty after a certain number of steps.
|
||||
|
||||
This helps with early training by preventing backward movement, but removes the constraint
|
||||
later to allow more natural movement patterns.
|
||||
|
||||
Args:
|
||||
env: The learning environment.
|
||||
env_ids: Not used since all environments are affected.
|
||||
term_name: The name of the backward movement penalty term.
|
||||
num_steps: The number of steps after which the penalty should be disabled.
|
||||
|
||||
Returns:
|
||||
Current step counter as float for logging purposes.
|
||||
"""
|
||||
if env.common_step_counter > num_steps:
|
||||
# Check if the term exists and has a non-zero weight
|
||||
if hasattr(env.reward_manager, 'get_term_cfg'):
|
||||
try:
|
||||
term_cfg = env.reward_manager.get_term_cfg(term_name)
|
||||
if term_cfg.weight != 0.0:
|
||||
# Disable the penalty by setting weight to 0
|
||||
term_cfg.weight = 0.0
|
||||
env.reward_manager.set_term_cfg(term_name, term_cfg)
|
||||
print(f"Disabled backward movement penalty at step {env.common_step_counter}")
|
||||
except KeyError:
|
||||
# Term doesn't exist, which is fine
|
||||
pass
|
||||
|
||||
return torch.tensor(float(env.common_step_counter))
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Custom noise configurations for navigation tasks."""
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from isaaclab.utils import configclass
|
||||
from isaaclab.utils.math import quat_from_euler_xyz, transform_points
|
||||
from isaaclab.utils.noise import NoiseCfg
|
||||
|
||||
if TYPE_CHECKING:
|
||||
pass
|
||||
|
||||
|
||||
@torch.jit.script
|
||||
def goal_to_xyz(goal: torch.Tensor) -> torch.Tensor:
|
||||
"""Convert goal in (direction, log distance) format to (x, y, z) coordinates."""
|
||||
direction = goal[:, :3] # Extract directional vector
|
||||
distance = torch.exp(goal[:, 3]) - 1 # Convert log distance back to distance
|
||||
return direction * distance.unsqueeze(-1) # Scale direction by distance
|
||||
|
||||
|
||||
@torch.jit.script
|
||||
def xyz_to_goal(xyz: torch.Tensor) -> torch.Tensor:
|
||||
"""Convert (x, y, z) coordinates to (direction, log distance) format."""
|
||||
distance = torch.norm(xyz, dim=1, keepdim=True) + 1e-6 # Calculate distance
|
||||
direction = xyz / distance # Normalize to get directional vector
|
||||
distance = torch.log(1 + distance) # Convert distance to log distance
|
||||
return torch.cat([direction, distance], dim=1) # Concatenate direction and log distance
|
||||
|
||||
|
||||
@torch.inference_mode()
|
||||
def delta_transformation_noise(data: torch.Tensor, cfg: "DeltaTransformationNoiseCfg") -> torch.Tensor:
|
||||
"""Delta transformation noise involving random rotation and translation.
|
||||
|
||||
The output is returned in a new tensor (instead of modifying 'data' in-place).
|
||||
"""
|
||||
# Ensure the data has the shape (..., 3) for 3D coordinates, or (direction, log distance)
|
||||
if data.shape[-1] not in (3, 4):
|
||||
raise ValueError(
|
||||
"Data must have shape (..., 3) for 3D coordinates, or (..., 4) for (direction, log distance)."
|
||||
)
|
||||
|
||||
# Determine whether data is in (direction, log distance) format
|
||||
unit_vec = data.shape[-1] == 4
|
||||
|
||||
# Convert to (x, y, z) if needed
|
||||
if unit_vec:
|
||||
coordinate = goal_to_xyz(data)
|
||||
else:
|
||||
coordinate = data
|
||||
|
||||
# Generate small rotation noise (Rx, Ry, Rz) using uniform distribution
|
||||
rotation_noise = torch.empty((data.shape[0], 3), device=data.device).uniform_(-cfg.rotation, cfg.rotation)
|
||||
|
||||
# Convert Euler angles (Rx, Ry, Rz) to quaternions
|
||||
quat_noise = quat_from_euler_xyz(rotation_noise[:, 0], rotation_noise[:, 1], rotation_noise[:, 2])
|
||||
|
||||
# Generate small translation noise (Tx, Ty, Tz) using uniform distribution
|
||||
translation_noise = torch.empty((data.shape[0], 3), device=data.device).uniform_(-cfg.translation, cfg.translation)
|
||||
|
||||
# Apply random rotation + translation
|
||||
transformed_data = transform_points(coordinate.unsqueeze(1), translation_noise, quat_noise).squeeze(1)
|
||||
|
||||
# If input was in goal format, convert back
|
||||
if unit_vec:
|
||||
transformed_data = xyz_to_goal(transformed_data)
|
||||
|
||||
# Randomly apply the noise based on the probability
|
||||
random_mask = torch.rand(data.shape[0], device=data.device) < cfg.noise_prob
|
||||
|
||||
# Use torch.where to select transformed values on the mask
|
||||
random_mask_expanded = random_mask.unsqueeze(-1)
|
||||
output = torch.where(random_mask_expanded, transformed_data, data)
|
||||
|
||||
if cfg.remove_dist:
|
||||
if unit_vec:
|
||||
# Zero out the distance component by directly assigning 0
|
||||
output[..., 3:] = 0
|
||||
else:
|
||||
# Normalize the vector by its norm (avoiding division by zero)
|
||||
norm = torch.norm(output, dim=-1, keepdim=True) + 1e-6
|
||||
output = output / norm
|
||||
|
||||
return output
|
||||
|
||||
|
||||
@configclass
|
||||
class DeltaTransformationNoiseCfg(NoiseCfg):
|
||||
"""Configuration for small delta transformation noise involving rotation and translation."""
|
||||
|
||||
func = delta_transformation_noise
|
||||
|
||||
rotation: float = 0.1
|
||||
"""The maximum rotation angle in radians. Defaults to 0.1."""
|
||||
translation: float = 0.5
|
||||
"""The maximum translation in meters. Defaults to 0.5."""
|
||||
noise_prob: float = 0.25
|
||||
"""The probability of applying the noise. Defaults to 0.25."""
|
||||
remove_dist: bool = False
|
||||
"""Whether to remove the distance from the output. Defaults to False."""
|
||||
+272
@@ -0,0 +1,272 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Standalone observation delay manager for simulating sensor delays."""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
import torch
|
||||
|
||||
from isaaclab.utils import DelayBuffer, configclass
|
||||
|
||||
|
||||
@configclass
|
||||
class ObservationDelayManagerCfg:
|
||||
"""Configuration for the observation delay manager.
|
||||
|
||||
This configuration controls the simulation of sensor delays, where each environment
|
||||
can have a different random delay sampled from [0, max_delay] at episode reset.
|
||||
"""
|
||||
|
||||
enabled: bool = True
|
||||
"""Whether to enable delay simulation for observations."""
|
||||
|
||||
max_delay_lin_vel: int = 2
|
||||
"""Maximum delay in timesteps for linear velocity observations."""
|
||||
|
||||
max_delay_ang_vel: int = 2
|
||||
"""Maximum delay in timesteps for angular velocity observations."""
|
||||
|
||||
max_delay_projected_gravity: int = 2
|
||||
"""Maximum delay in timesteps for projected gravity observations."""
|
||||
|
||||
max_delay_target_position: int = 2
|
||||
"""Maximum delay in timesteps for target position/goal observations."""
|
||||
|
||||
max_delay_depth: int = 2
|
||||
"""Maximum delay in timesteps for depth image observations."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class DelayBufferState:
|
||||
"""Container for a delay buffer and its associated time lags.
|
||||
|
||||
This encapsulates the state needed for delayed observations:
|
||||
- The buffer storing historical data
|
||||
- Per-environment time lags (delays)
|
||||
- Maximum delay configured for this buffer
|
||||
"""
|
||||
|
||||
buffer: DelayBuffer
|
||||
time_lags: torch.Tensor
|
||||
max_delay: int
|
||||
|
||||
def compute(self, data: torch.Tensor) -> torch.Tensor:
|
||||
"""Append data and return delayed version."""
|
||||
return self.buffer.compute(data)
|
||||
|
||||
def reset(self, env_ids: Sequence[int] | None = None):
|
||||
"""Reset buffer for specified environments."""
|
||||
self.buffer.reset(env_ids)
|
||||
|
||||
def randomize_lags(self, env_ids: torch.Tensor, device: str):
|
||||
"""Randomize time lags for specified environments."""
|
||||
new_lags = torch.randint(0, self.max_delay + 1, (len(env_ids),), dtype=torch.int, device=device)
|
||||
self.time_lags[env_ids] = new_lags
|
||||
env_ids_list = env_ids.tolist() if env_ids is not None else None
|
||||
self.buffer.set_time_lag(new_lags, env_ids_list)
|
||||
|
||||
def set_lags(self, time_lags: torch.Tensor, env_ids: torch.Tensor | None = None):
|
||||
"""Set time lags for specified environments."""
|
||||
if env_ids is None:
|
||||
self.time_lags[:] = time_lags
|
||||
self.buffer.set_time_lag(time_lags)
|
||||
else:
|
||||
self.time_lags[env_ids] = time_lags
|
||||
self.buffer.set_time_lag(time_lags, env_ids.tolist())
|
||||
|
||||
|
||||
class ObservationDelayManager:
|
||||
"""Standalone manager for simulating observation delays.
|
||||
|
||||
This manager can be added to any environment to simulate sensor delays
|
||||
without coupling to a specific action term. Each observation type can
|
||||
have its own delay buffer with per-environment random delays.
|
||||
|
||||
Usage:
|
||||
# In environment config or __init__:
|
||||
self.delay_manager = ObservationDelayManager(cfg, num_envs, device)
|
||||
|
||||
# In observation functions:
|
||||
delayed_vel = env.delay_manager.compute_delayed_lin_vel(current_vel)
|
||||
|
||||
# On episode reset:
|
||||
env.delay_manager.reset(env_ids)
|
||||
env.delay_manager.randomize_lags(env_ids)
|
||||
"""
|
||||
|
||||
def __init__(self, cfg: ObservationDelayManagerCfg, num_envs: int, device: str):
|
||||
"""Initialize the observation delay manager.
|
||||
|
||||
Args:
|
||||
cfg: Configuration for delay buffers.
|
||||
num_envs: Number of parallel environments.
|
||||
device: Device for tensor operations.
|
||||
"""
|
||||
self.cfg = cfg
|
||||
self.num_envs = num_envs
|
||||
self.device = device
|
||||
self._delay_enabled = cfg.enabled
|
||||
|
||||
self._init_delay_buffers()
|
||||
|
||||
def _create_delay_buffer_state(self, max_delay: int) -> DelayBufferState:
|
||||
"""Create a DelayBufferState with initialized buffer and random time lags."""
|
||||
buffer = DelayBuffer(max_delay, batch_size=self.num_envs, device=self.device)
|
||||
time_lags = torch.randint(0, max_delay + 1, (self.num_envs,), dtype=torch.int, device=self.device)
|
||||
buffer.set_time_lag(time_lags)
|
||||
return DelayBufferState(buffer=buffer, time_lags=time_lags, max_delay=max_delay)
|
||||
|
||||
def _init_delay_buffers(self):
|
||||
"""Initialize all delay buffers based on configuration."""
|
||||
if not self.cfg.enabled:
|
||||
# No delays - set all delay states to None
|
||||
self._delay_lin_vel: DelayBufferState | None = None
|
||||
self._delay_ang_vel: DelayBufferState | None = None
|
||||
self._delay_projected_gravity: DelayBufferState | None = None
|
||||
self._delay_target_position: DelayBufferState | None = None
|
||||
self._delay_depth_buffers: dict[str, DelayBufferState] = {}
|
||||
self._max_delay_depth = 0
|
||||
return
|
||||
|
||||
# Initialize delay buffer states for each observation type
|
||||
self._delay_lin_vel = self._create_delay_buffer_state(self.cfg.max_delay_lin_vel)
|
||||
self._delay_ang_vel = self._create_delay_buffer_state(self.cfg.max_delay_ang_vel)
|
||||
self._delay_projected_gravity = self._create_delay_buffer_state(self.cfg.max_delay_projected_gravity)
|
||||
self._delay_target_position = self._create_delay_buffer_state(self.cfg.max_delay_target_position)
|
||||
# Depth buffers are created dynamically per camera
|
||||
self._delay_depth_buffers: dict[str, DelayBufferState] = {}
|
||||
self._max_delay_depth = self.cfg.max_delay_depth
|
||||
|
||||
@property
|
||||
def enabled(self) -> bool:
|
||||
"""Whether delay simulation is enabled."""
|
||||
return self._delay_enabled
|
||||
|
||||
def get_or_create_depth_delay_buffer(self, camera_name: str) -> DelayBufferState:
|
||||
"""Get or create a delay buffer for a specific depth camera.
|
||||
|
||||
Args:
|
||||
camera_name: Name of the depth camera sensor.
|
||||
|
||||
Returns:
|
||||
DelayBufferState for the specified camera.
|
||||
"""
|
||||
if camera_name not in self._delay_depth_buffers:
|
||||
self._delay_depth_buffers[camera_name] = self._create_delay_buffer_state(self._max_delay_depth)
|
||||
return self._delay_depth_buffers[camera_name]
|
||||
|
||||
def reset(self, env_ids: torch.Tensor):
|
||||
"""Reset all delay buffers for specified environments.
|
||||
|
||||
Args:
|
||||
env_ids: Environment indices to reset.
|
||||
"""
|
||||
env_ids_list = env_ids.tolist() if env_ids is not None else None
|
||||
|
||||
if self._delay_lin_vel is not None:
|
||||
self._delay_lin_vel.reset(env_ids_list)
|
||||
if self._delay_ang_vel is not None:
|
||||
self._delay_ang_vel.reset(env_ids_list)
|
||||
if self._delay_projected_gravity is not None:
|
||||
self._delay_projected_gravity.reset(env_ids_list)
|
||||
if self._delay_target_position is not None:
|
||||
self._delay_target_position.reset(env_ids_list)
|
||||
|
||||
# Reset all depth buffers
|
||||
for depth_buffer in self._delay_depth_buffers.values():
|
||||
depth_buffer.reset(env_ids_list)
|
||||
|
||||
def randomize_lags(self, env_ids: torch.Tensor):
|
||||
"""Randomize time lags for all delay buffers.
|
||||
|
||||
Args:
|
||||
env_ids: Environment indices to randomize.
|
||||
"""
|
||||
if self._delay_lin_vel is not None:
|
||||
self._delay_lin_vel.randomize_lags(env_ids, self.device)
|
||||
if self._delay_ang_vel is not None:
|
||||
self._delay_ang_vel.randomize_lags(env_ids, self.device)
|
||||
if self._delay_projected_gravity is not None:
|
||||
self._delay_projected_gravity.randomize_lags(env_ids, self.device)
|
||||
if self._delay_target_position is not None:
|
||||
self._delay_target_position.randomize_lags(env_ids, self.device)
|
||||
|
||||
# Randomize all depth buffers
|
||||
for depth_buffer in self._delay_depth_buffers.values():
|
||||
depth_buffer.randomize_lags(env_ids, self.device)
|
||||
|
||||
# ============================================================================
|
||||
# Delayed observation computation methods
|
||||
# ============================================================================
|
||||
|
||||
def compute_delayed_lin_vel(self, lin_vel: torch.Tensor) -> torch.Tensor:
|
||||
"""Compute delayed linear velocity observation.
|
||||
|
||||
Args:
|
||||
lin_vel: Current linear velocity tensor of shape (num_envs, 3).
|
||||
|
||||
Returns:
|
||||
Delayed linear velocity, or original if delays disabled.
|
||||
"""
|
||||
if self._delay_lin_vel is None:
|
||||
return lin_vel
|
||||
return self._delay_lin_vel.compute(lin_vel)
|
||||
|
||||
def compute_delayed_ang_vel(self, ang_vel: torch.Tensor) -> torch.Tensor:
|
||||
"""Compute delayed angular velocity observation.
|
||||
|
||||
Args:
|
||||
ang_vel: Current angular velocity tensor of shape (num_envs, 3).
|
||||
|
||||
Returns:
|
||||
Delayed angular velocity, or original if delays disabled.
|
||||
"""
|
||||
if self._delay_ang_vel is None:
|
||||
return ang_vel
|
||||
return self._delay_ang_vel.compute(ang_vel)
|
||||
|
||||
def compute_delayed_projected_gravity(self, projected_gravity: torch.Tensor) -> torch.Tensor:
|
||||
"""Compute delayed projected gravity observation.
|
||||
|
||||
Args:
|
||||
projected_gravity: Current projected gravity tensor of shape (num_envs, 3).
|
||||
|
||||
Returns:
|
||||
Delayed projected gravity, or original if delays disabled.
|
||||
"""
|
||||
if self._delay_projected_gravity is None:
|
||||
return projected_gravity
|
||||
return self._delay_projected_gravity.compute(projected_gravity)
|
||||
|
||||
def compute_delayed_target_position(self, target_position: torch.Tensor) -> torch.Tensor:
|
||||
"""Compute delayed target position observation.
|
||||
|
||||
Args:
|
||||
target_position: Current target position tensor.
|
||||
|
||||
Returns:
|
||||
Delayed target position, or original if delays disabled.
|
||||
"""
|
||||
if self._delay_target_position is None:
|
||||
return target_position
|
||||
return self._delay_target_position.compute(target_position)
|
||||
|
||||
def compute_delayed_depth(self, depth_features: torch.Tensor, camera_name: str) -> torch.Tensor:
|
||||
"""Compute delayed depth observation for a specific camera.
|
||||
|
||||
Args:
|
||||
depth_features: Encoded depth features of shape (num_envs, feature_dim).
|
||||
camera_name: Name of the camera sensor.
|
||||
|
||||
Returns:
|
||||
Delayed depth features, or original if delays disabled.
|
||||
"""
|
||||
if not self._delay_enabled:
|
||||
return depth_features
|
||||
delay_buffer = self.get_or_create_depth_delay_buffer(camera_name)
|
||||
return delay_buffer.compute(depth_features)
|
||||
+332
@@ -0,0 +1,332 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Depth noise encoder module for visual navigation.
|
||||
|
||||
This module provides a VAE-based depth encoder with realistic stereo depth noise simulation.
|
||||
"""
|
||||
import os
|
||||
from collections import OrderedDict
|
||||
from typing import Tuple
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from torchvision.models import regnet_x_400mf
|
||||
from torchvision.ops import Conv2dNormActivation, FeaturePyramidNetwork
|
||||
|
||||
from isaaclab_assets import ISAACLAB_ASSETS_DATA_DIR
|
||||
|
||||
from .camera_config import CameraConfig
|
||||
|
||||
# Default camera configuration (ZedX Camera for b2w and aow d)
|
||||
DEFAULT_CAMERA_CONFIG = CameraConfig(
|
||||
focal_length=25.0,
|
||||
baseline=0.12,
|
||||
min_depth=0.25,
|
||||
max_depth=10.0,
|
||||
depth_encoder_path=os.path.join(str(ISAACLAB_ASSETS_DATA_DIR), "Policies", "RSL-ETHZ/AoW_d/depth_encoder", "vae_pretrain_fuse.pth")
|
||||
)
|
||||
|
||||
class VAESampler(nn.Module):
|
||||
def __init__(self, input_dim, latent_dim):
|
||||
super(VAESampler, self).__init__()
|
||||
self.input_dim = input_dim
|
||||
self.latent_dim = latent_dim
|
||||
self.conv = Conv2dNormActivation(input_dim, latent_dim, kernel_size=3, stride=1, padding=1, bias=False)
|
||||
|
||||
# Convolutional Layers for 2D mean and logvar
|
||||
self.mean_layers = nn.Sequential(
|
||||
Conv2dNormActivation(latent_dim, latent_dim, kernel_size=3, stride=1, padding=1, bias=False),
|
||||
nn.Conv2d(latent_dim, latent_dim, kernel_size=1, stride=1, padding=0)
|
||||
)
|
||||
|
||||
self.logvar_layers = nn.Sequential(
|
||||
Conv2dNormActivation(latent_dim, latent_dim, kernel_size=3, stride=1, padding=1, bias=False),
|
||||
nn.Conv2d(latent_dim, latent_dim, kernel_size=1, stride=1, padding=0)
|
||||
)
|
||||
|
||||
def reparameterize(self, mu, logvar):
|
||||
std = torch.exp(0.5 * logvar)
|
||||
eps = torch.randn_like(std)
|
||||
return mu + eps * std
|
||||
|
||||
def forward(self, x):
|
||||
x = self.conv(x)
|
||||
x = self.mean_layers(x)
|
||||
return x
|
||||
|
||||
class EncoderFPN(nn.Module):
|
||||
def __init__(self, in_channel, out_channel):
|
||||
super(EncoderFPN, self).__init__()
|
||||
encoder = regnet_x_400mf(weights=None)
|
||||
# Remove classification head from the encoder
|
||||
encoder = nn.Sequential(*list(encoder.children())[:-2])
|
||||
# Modify the first layer to accept the number of channels in the input image
|
||||
encoder[0][0] = nn.Conv2d(in_channel, 32, kernel_size=3, stride=2, padding=1, bias=False)
|
||||
self.enc = encoder[0]
|
||||
self.enc_1 = encoder[1][:2]
|
||||
self.enc_2 = encoder[1][2]
|
||||
self.enc_3 = encoder[1][3]
|
||||
|
||||
# Feature Pyramid Network
|
||||
self.fpn = FeaturePyramidNetwork([64, 160, 400], out_channel)
|
||||
|
||||
def forward(self, x):
|
||||
raise NotImplementedError("Forward method must be implemented in the child class.")
|
||||
|
||||
|
||||
class DepthEncoder(EncoderFPN):
|
||||
"""Depth image encoder using Feature Pyramid Network."""
|
||||
def __init__(self, out_channel):
|
||||
super(DepthEncoder, self).__init__(1, out_channel)
|
||||
|
||||
def forward(self, x):
|
||||
# check if depth has channel dimension
|
||||
if x.dim() == 3:
|
||||
x = x.unsqueeze(1)
|
||||
|
||||
out = OrderedDict()
|
||||
x = self.enc(x)
|
||||
out['feat1'] = self.enc_1(x)
|
||||
out['feat2'] = self.enc_2(out['feat1'])
|
||||
out['feat3'] = self.enc_3(out['feat2'])
|
||||
|
||||
out = self.fpn(out)
|
||||
|
||||
return out['feat1']
|
||||
|
||||
|
||||
class VAEDecoder(nn.Module):
|
||||
def __init__(self, input_dim, out_dim):
|
||||
super(VAEDecoder, self).__init__()
|
||||
self.input_dim = input_dim
|
||||
self.conv = Conv2dNormActivation(input_dim, input_dim, kernel_size=3, stride=1, padding=1, bias=False)
|
||||
|
||||
self.decoder = nn.Sequential(
|
||||
# Layer 0
|
||||
nn.ConvTranspose2d(input_dim, input_dim, kernel_size=4, stride=2, padding=1, bias=False),
|
||||
nn.BatchNorm2d(input_dim),
|
||||
nn.ReLU(inplace=True),
|
||||
# Layer 1
|
||||
nn.ConvTranspose2d(input_dim, input_dim, kernel_size=4, stride=2, padding=1, bias=False),
|
||||
nn.BatchNorm2d(input_dim),
|
||||
nn.ReLU(inplace=True),
|
||||
# Layer 2
|
||||
nn.ConvTranspose2d(input_dim, input_dim, kernel_size=4, stride=2, padding=1, bias=False),
|
||||
nn.BatchNorm2d(input_dim),
|
||||
nn.ReLU(inplace=True),
|
||||
# Final Output Layer
|
||||
nn.Conv2d(input_dim, out_dim, kernel_size=3, stride=1, padding=1)
|
||||
) # Expand the spatial dimensions by a factor of 2**4=16
|
||||
|
||||
def forward(self, z):
|
||||
z = self.conv(z)
|
||||
img = self.decoder(z)
|
||||
return img
|
||||
|
||||
class DepthDecoder(VAEDecoder):
|
||||
def __init__(self, input_dim):
|
||||
super(DepthDecoder, self).__init__(input_dim, 1)
|
||||
|
||||
class VAENet(nn.Module):
|
||||
def __init__(self, latent_dim):
|
||||
super(VAENet, self).__init__()
|
||||
self.depth_encoder = DepthEncoder(latent_dim)
|
||||
|
||||
self.vae_sampler = VAESampler(latent_dim, latent_dim)
|
||||
|
||||
self.depth_decoder = DepthDecoder(latent_dim)
|
||||
|
||||
def forward(self, x):
|
||||
x = self.depth_encoder(x)
|
||||
x = self.vae_sampler(x)
|
||||
return x
|
||||
|
||||
def decode(self, z):
|
||||
return self.depth_decoder(z)
|
||||
|
||||
class DepthNoise(torch.nn.Module):
|
||||
def __init__(self,
|
||||
focal_length,
|
||||
baseline,
|
||||
min_depth,
|
||||
max_depth,
|
||||
filter_size=3,
|
||||
inlier_thred_range=(0.01, 0.05),
|
||||
prob_range=(0.4, 0.6),
|
||||
invalid_disp=1e7
|
||||
):
|
||||
"""
|
||||
A Simply PyTorch module to add realistic noise to depth images.
|
||||
|
||||
Args:
|
||||
focal_length (float): Focal length of the camera (in pixels).
|
||||
baseline (float): Baseline distance between stereo cameras (in meters).
|
||||
min_depth (float): Minimum depth value after clamping.
|
||||
max_depth (float): Maximum depth value after clamping.
|
||||
filter_size (int): Kernel size for local mean disparity computation. (tuning based on image resolution)
|
||||
inlier_thred_range (tuple): Threshold range for normalized disparity differences.
|
||||
prob_range (tuple): Probability range for matching pixels.
|
||||
invalid_disp (float): Invalid disparity
|
||||
|
||||
"""
|
||||
super().__init__()
|
||||
self.focal_length = focal_length
|
||||
self.baseline = baseline
|
||||
self.min_depth = min_depth
|
||||
self.max_depth = max_depth
|
||||
self.invalid_disp = invalid_disp
|
||||
self.inlier_thred_range = inlier_thred_range
|
||||
self.prob_range = prob_range
|
||||
self.filter_size = filter_size
|
||||
|
||||
weights, substitutes = self._compute_weights(filter_size)
|
||||
self.register_buffer('weights', weights.view(1, 1, filter_size, filter_size))
|
||||
self.register_buffer('substitutes', substitutes.view(1, 1, filter_size, filter_size))
|
||||
|
||||
|
||||
def _compute_weights(self, filter_size):
|
||||
"""
|
||||
Compute weights and substitutes for disparity filtering.
|
||||
|
||||
Args:
|
||||
filter_size (int): Kernel size for local mean disparity computation.
|
||||
"""
|
||||
center = filter_size // 2
|
||||
idx = torch.arange(filter_size) - center
|
||||
x_filter, y_filter = torch.meshgrid(idx, idx, indexing='ij')
|
||||
sqr_radius = x_filter ** 2 + y_filter ** 2
|
||||
sqrt_radius = torch.sqrt(sqr_radius)
|
||||
weights = 1 / torch.where(sqr_radius == 0, torch.ones_like(sqrt_radius), sqrt_radius)
|
||||
weights = weights / weights.sum()
|
||||
fill_weights = 1 / (1 + sqrt_radius)
|
||||
fill_weights = torch.where(sqr_radius > filter_size, -1.0, fill_weights)
|
||||
substitutes = (fill_weights > 0).float()
|
||||
|
||||
return weights, substitutes
|
||||
|
||||
def filter_disparity(self, disparity):
|
||||
"""
|
||||
Filter the disparity map using local mean disparity.
|
||||
|
||||
Args:
|
||||
disparity (torch.Tensor): Input disparity map tensor of shape (B, C, H, W).
|
||||
"""
|
||||
B, _, H, W = disparity.shape
|
||||
device = disparity.device
|
||||
center = self.filter_size // 2
|
||||
|
||||
output_disparity = torch.full_like(disparity, self.invalid_disp)
|
||||
|
||||
prob = torch.rand(B, 1, 1, 1, device=device) * (self.prob_range[1] - self.prob_range[0]) + self.prob_range[0]
|
||||
random_mask = (torch.rand(B, 1, H, W, device=device) < prob)
|
||||
|
||||
# Compute mean disparity
|
||||
weighted_disparity = F.conv2d(disparity, self.weights, padding=center)
|
||||
|
||||
# Compute differences
|
||||
differences = torch.abs(disparity - weighted_disparity)
|
||||
|
||||
# Normalize differences based on current image statistics for consistent thresholding
|
||||
differences_flat = differences.view(B, -1) # Flatten spatial dimensions
|
||||
mean_diff = torch.mean(differences_flat, dim=1, keepdim=True)
|
||||
std_diff = torch.std(differences_flat, dim=1, keepdim=True) + 1e-6 # Add epsilon to avoid division by zero
|
||||
|
||||
# Normalize differences: (diff - mean) / std, then shift to [0, 1] range approximately
|
||||
normalized_differences_flat = (differences_flat - mean_diff) / std_diff
|
||||
normalized_differences = normalized_differences_flat.view_as(differences)
|
||||
|
||||
# Use parameter-based threshold on normalized differences
|
||||
threshold = torch.rand(B, 1, 1, 1, device=device) * (self.inlier_thred_range[1] - self.inlier_thred_range[0]) + self.inlier_thred_range[0]
|
||||
update_mask = (normalized_differences < threshold) & random_mask
|
||||
|
||||
# Compute output value: round with 1/32 precision
|
||||
disparity = torch.round(disparity * 32.0) / 32.0
|
||||
|
||||
# Update output disparity
|
||||
output_disparity = torch.where(update_mask, disparity, output_disparity)
|
||||
|
||||
# Apply substitutes to fill neighboring pixels
|
||||
filled_values = F.conv2d(update_mask.float() * disparity, self.substitutes, padding=center)
|
||||
counts = F.conv2d(update_mask.float(), self.substitutes, padding=center) + 1e-9
|
||||
average_filled_values = filled_values / counts
|
||||
output_disparity = torch.where(counts >= 1, average_filled_values, output_disparity)
|
||||
|
||||
return output_disparity
|
||||
|
||||
def forward(self, depth, add_noise: bool) -> torch.Tensor:
|
||||
# correct input shape
|
||||
if len(depth.shape) == 3:
|
||||
depth = depth.unsqueeze(1) # add channel dimension
|
||||
|
||||
# check dimension (B, 1, H, W)
|
||||
assert depth.shape[1] == 1, "Input depth tensor must have shape (B, 1, H, W)."
|
||||
assert len(depth.shape) == 4, "Input depth tensor must have shape (B, 1, H, W)."
|
||||
|
||||
if add_noise:
|
||||
# Clamp the depth values
|
||||
depth = torch.clamp(depth, min=1. / self.invalid_disp)
|
||||
|
||||
# Step 1: Convert depth to disparity
|
||||
disparity = self.focal_length * self.baseline / depth
|
||||
|
||||
# Step 2: Filter the disparity map
|
||||
filtered_disparity = self.filter_disparity(disparity)
|
||||
|
||||
# Step 3: Recompute depth from disparity
|
||||
depth = self.focal_length * self.baseline / filtered_disparity
|
||||
|
||||
# Step 4: Clamp the depth values
|
||||
depth[depth < self.min_depth] = 0.0
|
||||
|
||||
# Step 5: Set invalid depth values to 0.0 (values outside valid range are not measurable)
|
||||
depth[depth > self.max_depth] = 0.0
|
||||
|
||||
return depth
|
||||
|
||||
|
||||
class DepthNoiseEncoder(torch.nn.Module):
|
||||
def __init__(self,
|
||||
feature_dim,
|
||||
camera_config: CameraConfig = None
|
||||
):
|
||||
"""
|
||||
A Simply PyTorch module to add realistic noise to depth images.
|
||||
|
||||
Args:
|
||||
feature_dim (int): Number of output channels from the encoder.
|
||||
camera_config (CameraConfig, optional): Camera configuration parameters.
|
||||
If None, uses DEFAULT_CAMERA_CONFIG.
|
||||
"""
|
||||
super().__init__()
|
||||
|
||||
# Use provided config or default
|
||||
if camera_config is None:
|
||||
camera_config = DEFAULT_CAMERA_CONFIG
|
||||
|
||||
self.camera_config = camera_config
|
||||
self.depth_noise = DepthNoise(
|
||||
focal_length=camera_config.focal_length,
|
||||
baseline=camera_config.baseline,
|
||||
min_depth=camera_config.min_depth,
|
||||
max_depth=camera_config.max_depth
|
||||
)
|
||||
|
||||
self.encoder = VAENet(feature_dim)
|
||||
|
||||
try:
|
||||
self.encoder.load_state_dict(torch.load(camera_config.depth_encoder_path, weights_only=True), strict=True)
|
||||
print('\033[92m' + f'Successfully loaded pre-trained weights from {camera_config.depth_encoder_path}' + '\033[0m')
|
||||
except Exception as e:
|
||||
print('\033[91m' + f'Failed to load pre-trained weights: {e}' + '\033[0m')
|
||||
|
||||
def forward(self, depth: torch.Tensor, add_noise: bool = True) -> Tuple[torch.Tensor, torch.Tensor]:
|
||||
noisy_depth = self.depth_noise(depth, add_noise)
|
||||
encoded_depth = self.encoder(noisy_depth) # (B, 1, H, W) -> (B, C, H//8, W//8)
|
||||
return encoded_depth, noisy_depth
|
||||
|
||||
@torch.jit.export
|
||||
def decode(self, z: torch.Tensor) -> torch.Tensor:
|
||||
return self.encoder.decode(z)
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Depth noise and encoding utilities for navigation tasks."""
|
||||
|
||||
from .camera_config import (
|
||||
CameraConfig,
|
||||
ZEDX_CAMERA_CONFIG,
|
||||
DEFAULT_CAMERA_CONFIG,
|
||||
ROBOT_CAMERA_CONFIGS,
|
||||
get_camera_config,
|
||||
)
|
||||
from .depth_noise_encoder import DepthNoiseEncoder, DepthNoise
|
||||
|
||||
__all__ = [
|
||||
"CameraConfig",
|
||||
"ZEDX_CAMERA_CONFIG",
|
||||
"DEFAULT_CAMERA_CONFIG",
|
||||
"ROBOT_CAMERA_CONFIGS",
|
||||
"get_camera_config",
|
||||
"DepthNoiseEncoder",
|
||||
"DepthNoise",
|
||||
]
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Camera configuration parameters for different robots and camera types.
|
||||
|
||||
This module provides camera-specific parameters for depth noise generation and encoding.
|
||||
"""
|
||||
|
||||
import os
|
||||
from typing import Optional
|
||||
|
||||
from isaaclab.utils import configclass
|
||||
|
||||
# Local assets directory for this extension
|
||||
# Path: depth_utils -> mdp -> navigation -> assets/data
|
||||
_ASSETS_DIR = os.path.normpath(
|
||||
os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "assets", "data")
|
||||
)
|
||||
|
||||
|
||||
def _get_encoder_path(model_filename: str) -> str:
|
||||
"""Helper function to construct encoder model path.
|
||||
|
||||
Args:
|
||||
model_filename: Name of the encoder model file (e.g., 'vae_pretrain_new.pth')
|
||||
|
||||
Returns:
|
||||
Full path to the encoder model file
|
||||
"""
|
||||
return os.path.join(_ASSETS_DIR, "Policies", "depth_encoder", model_filename)
|
||||
|
||||
|
||||
@configclass
|
||||
class CameraConfig:
|
||||
"""Configuration class for camera parameters.
|
||||
|
||||
This class contains all camera-specific parameters needed for depth noise generation
|
||||
and depth encoder initialization.
|
||||
"""
|
||||
|
||||
# Camera intrinsic parameters
|
||||
focal_length: float = 25.0
|
||||
baseline: float = 0.12
|
||||
|
||||
# Depth range parameters
|
||||
min_depth: float = 0.25
|
||||
max_depth: float = 10.0
|
||||
|
||||
# Camera resolution (width, height)
|
||||
resolution: tuple[int, int] = (53, 30)
|
||||
|
||||
# Depth encoder model path
|
||||
depth_encoder_path: str = ""
|
||||
|
||||
def __post_init__(self):
|
||||
"""Post-initialization to set default encoder path if not provided."""
|
||||
if not self.depth_encoder_path:
|
||||
self.depth_encoder_path = _get_encoder_path("vae_pretrain_fuse.pth")
|
||||
|
||||
|
||||
# Predefined camera configurations
|
||||
ZEDX_CAMERA_CONFIG = CameraConfig(
|
||||
focal_length=25.0,
|
||||
baseline=0.12,
|
||||
min_depth=0.25,
|
||||
max_depth=10.0,
|
||||
resolution=(64, 40),
|
||||
depth_encoder_path=_get_encoder_path("vae_pretrain_new.pth"),
|
||||
)
|
||||
"""Configuration for ZedX camera (used with b2w and aow_d robots)."""
|
||||
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Odin1 (LiDAR-aligned depth on Unitree Go2)
|
||||
# -----------------------------------------------------------------------------
|
||||
# Real intrinsics @ native 1600x1296 (from ROS calibration):
|
||||
# fx = 737.357 px, fy = 737.292 px, cx = 794.372 px, cy = 666.259 px
|
||||
# hFOV = 2*atan(W / 2fx) = 94.67 deg
|
||||
# vFOV = 2*atan(H / 2fy) = 82.65 deg
|
||||
#
|
||||
# Scaled to VAE-fixed 64x40 input (keep FOV identical):
|
||||
# fx_sim = 737.357 * 64/1600 = 29.49 px
|
||||
# fy_sim = 737.292 * 40/1296 = 22.76 px
|
||||
# cx_sim ~= 31.77 px (close to width/2)
|
||||
# cy_sim ~= 20.56 px (close to height/2)
|
||||
#
|
||||
# Noise model caveat: the upstream DepthNoise module simulates *stereo*
|
||||
# disparity-quantization noise (sigma_d proportional to d^2 / (fx * baseline)).
|
||||
# Odin1 depth comes from LiDAR-to-image alignment, where the real noise is
|
||||
# closer to a constant ~1-2 cm regardless of range. We keep the stereo-style
|
||||
# noise as a coarse proxy (set focal_length=fx_sim, baseline=0.05 m) but if
|
||||
# sim2real depth fidelity becomes a problem, swap in a constant-sigma noise
|
||||
# model later.
|
||||
ODIN1_CAMERA_CONFIG = CameraConfig(
|
||||
focal_length=29.49, # pixels (NOT mm; matches sim pinhole fx)
|
||||
baseline=0.05, # fudge: makes per-meter quantization noise sane
|
||||
min_depth=0.25,
|
||||
max_depth=10.0,
|
||||
resolution=(64, 40), # do not change; VAE encoder input is fixed
|
||||
depth_encoder_path=_get_encoder_path("vae_pretrain_new.pth"),
|
||||
)
|
||||
"""Configuration for Odin1 LiDAR-aligned depth (used with Go2)."""
|
||||
|
||||
|
||||
# Default camera configuration
|
||||
DEFAULT_CAMERA_CONFIG = ZEDX_CAMERA_CONFIG
|
||||
"""Default camera configuration (ZedX camera settings)."""
|
||||
|
||||
# Robot-to-camera mapping. Go2 now uses Odin1 (LiDAR-aligned depth). b2w and
|
||||
# aow_d keep the original ZedX profile so the upstream paper results stay
|
||||
# reproducible.
|
||||
ROBOT_CAMERA_CONFIGS = {
|
||||
"b2w": ZEDX_CAMERA_CONFIG,
|
||||
"aow_d": ZEDX_CAMERA_CONFIG,
|
||||
"go2": ODIN1_CAMERA_CONFIG,
|
||||
}
|
||||
"""Dictionary mapping robot names to their camera configurations."""
|
||||
|
||||
|
||||
def get_camera_config(robot_name: str, use_default_fallback: bool = False) -> CameraConfig:
|
||||
"""Get camera configuration for a specific robot.
|
||||
|
||||
Args:
|
||||
robot_name: Name of the robot (e.g., 'b2w', 'aow_d')
|
||||
use_default_fallback: If True, return DEFAULT_CAMERA_CONFIG when robot not found
|
||||
instead of raising an error (default: False)
|
||||
|
||||
Returns:
|
||||
Camera configuration for the specified robot
|
||||
|
||||
Raises:
|
||||
KeyError: If robot_name not found and use_default_fallback is False
|
||||
"""
|
||||
if robot_name in ROBOT_CAMERA_CONFIGS:
|
||||
return ROBOT_CAMERA_CONFIGS[robot_name]
|
||||
|
||||
if use_default_fallback:
|
||||
return DEFAULT_CAMERA_CONFIG
|
||||
|
||||
available_robots = ", ".join(sorted(ROBOT_CAMERA_CONFIGS.keys()))
|
||||
raise KeyError(
|
||||
f"Robot '{robot_name}' not found in camera configurations. "
|
||||
f"Available robots: {available_robots}"
|
||||
)
|
||||
+361
@@ -0,0 +1,361 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Depth noise generation and encoding for navigation tasks."""
|
||||
|
||||
import os
|
||||
from collections import OrderedDict
|
||||
from typing import Tuple
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from torchvision.models import regnet_x_400mf
|
||||
from torchvision.ops import Conv2dNormActivation, FeaturePyramidNetwork
|
||||
|
||||
from isaaclab_assets import ISAACLAB_ASSETS_DATA_DIR
|
||||
|
||||
from .camera_config import CameraConfig
|
||||
|
||||
# Default camera configuration (ZedX Camera for b2w and aow d)
|
||||
DEFAULT_CAMERA_CONFIG = CameraConfig(
|
||||
focal_length=25.0,
|
||||
baseline=0.12,
|
||||
min_depth=0.25,
|
||||
max_depth=10.0,
|
||||
depth_encoder_path=os.path.join(
|
||||
str(ISAACLAB_ASSETS_DATA_DIR),
|
||||
"Policies",
|
||||
"RSL-ETHZ/AoW_d/depth_encoder",
|
||||
"vae_pretrain_fuse.pth"
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class VAESampler(nn.Module):
|
||||
def __init__(self, input_dim, latent_dim):
|
||||
super(VAESampler, self).__init__()
|
||||
self.input_dim = input_dim
|
||||
self.latent_dim = latent_dim
|
||||
self.conv = Conv2dNormActivation(
|
||||
input_dim, latent_dim, kernel_size=3, stride=1, padding=1, bias=False
|
||||
)
|
||||
|
||||
# Convolutional Layers for 2D mean and logvar
|
||||
self.mean_layers = nn.Sequential(
|
||||
Conv2dNormActivation(
|
||||
latent_dim, latent_dim, kernel_size=3, stride=1, padding=1, bias=False
|
||||
),
|
||||
nn.Conv2d(latent_dim, latent_dim, kernel_size=1, stride=1, padding=0)
|
||||
)
|
||||
|
||||
self.logvar_layers = nn.Sequential(
|
||||
Conv2dNormActivation(
|
||||
latent_dim, latent_dim, kernel_size=3, stride=1, padding=1, bias=False
|
||||
),
|
||||
nn.Conv2d(latent_dim, latent_dim, kernel_size=1, stride=1, padding=0)
|
||||
)
|
||||
|
||||
def reparameterize(self, mu, logvar):
|
||||
std = torch.exp(0.5 * logvar)
|
||||
eps = torch.randn_like(std)
|
||||
return mu + eps * std
|
||||
|
||||
def forward(self, x):
|
||||
x = self.conv(x)
|
||||
x = self.mean_layers(x)
|
||||
return x
|
||||
|
||||
|
||||
class EncoderFPN(nn.Module):
|
||||
def __init__(self, in_channel, out_channel):
|
||||
super(EncoderFPN, self).__init__()
|
||||
encoder = regnet_x_400mf(weights=None)
|
||||
# Remove classification head from the encoder
|
||||
encoder = nn.Sequential(*list(encoder.children())[:-2])
|
||||
# Modify the first layer to accept the number of channels in the input image
|
||||
encoder[0][0] = nn.Conv2d(in_channel, 32, kernel_size=3, stride=2, padding=1, bias=False)
|
||||
self.enc = encoder[0]
|
||||
self.enc_1 = encoder[1][:2]
|
||||
self.enc_2 = encoder[1][2]
|
||||
self.enc_3 = encoder[1][3]
|
||||
|
||||
# Feature Pyramid Network
|
||||
self.fpn = FeaturePyramidNetwork([64, 160, 400], out_channel)
|
||||
|
||||
def forward(self, x):
|
||||
raise NotImplementedError("Forward method must be implemented in the child class.")
|
||||
|
||||
|
||||
# Depth image encoder
|
||||
class DepthEncoder(EncoderFPN):
|
||||
def __init__(self, out_channel):
|
||||
super(DepthEncoder, self).__init__(1, out_channel)
|
||||
|
||||
def forward(self, x):
|
||||
# check if depth has channel dimension
|
||||
if x.dim() == 3:
|
||||
x = x.unsqueeze(1)
|
||||
|
||||
out = OrderedDict()
|
||||
x = self.enc(x)
|
||||
out['feat1'] = self.enc_1(x)
|
||||
out['feat2'] = self.enc_2(out['feat1'])
|
||||
out['feat3'] = self.enc_3(out['feat2'])
|
||||
|
||||
out = self.fpn(out)
|
||||
|
||||
return out['feat1']
|
||||
|
||||
|
||||
class VAEDecoder(nn.Module):
|
||||
def __init__(self, input_dim, out_dim):
|
||||
super(VAEDecoder, self).__init__()
|
||||
self.input_dim = input_dim
|
||||
self.conv = Conv2dNormActivation(
|
||||
input_dim, input_dim, kernel_size=3, stride=1, padding=1, bias=False
|
||||
)
|
||||
|
||||
self.decoder = nn.Sequential(
|
||||
# Layer 0
|
||||
nn.ConvTranspose2d(input_dim, input_dim, kernel_size=4, stride=2, padding=1, bias=False),
|
||||
nn.BatchNorm2d(input_dim),
|
||||
nn.ReLU(inplace=True),
|
||||
# Layer 1
|
||||
nn.ConvTranspose2d(input_dim, input_dim, kernel_size=4, stride=2, padding=1, bias=False),
|
||||
nn.BatchNorm2d(input_dim),
|
||||
nn.ReLU(inplace=True),
|
||||
# Layer 2
|
||||
nn.ConvTranspose2d(input_dim, input_dim, kernel_size=4, stride=2, padding=1, bias=False),
|
||||
nn.BatchNorm2d(input_dim),
|
||||
nn.ReLU(inplace=True),
|
||||
# Final Output Layer
|
||||
nn.Conv2d(input_dim, out_dim, kernel_size=3, stride=1, padding=1)
|
||||
) # Expand the spatial dimensions by a factor of 2**4=16
|
||||
|
||||
def forward(self, z):
|
||||
z = self.conv(z)
|
||||
img = self.decoder(z)
|
||||
return img
|
||||
|
||||
|
||||
class DepthDecoder(VAEDecoder):
|
||||
def __init__(self, input_dim):
|
||||
super(DepthDecoder, self).__init__(input_dim, 1)
|
||||
|
||||
|
||||
class VAENet(nn.Module):
|
||||
def __init__(self, latent_dim):
|
||||
super(VAENet, self).__init__()
|
||||
self.depth_encoder = DepthEncoder(latent_dim)
|
||||
|
||||
self.vae_sampler = VAESampler(latent_dim, latent_dim)
|
||||
|
||||
self.depth_decoder = DepthDecoder(latent_dim)
|
||||
|
||||
def forward(self, x):
|
||||
x = self.depth_encoder(x)
|
||||
x = self.vae_sampler(x)
|
||||
return x
|
||||
|
||||
def decode(self, z):
|
||||
return self.depth_decoder(z)
|
||||
|
||||
|
||||
class DepthNoise(torch.nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
focal_length,
|
||||
baseline,
|
||||
min_depth,
|
||||
max_depth,
|
||||
filter_size=3,
|
||||
inlier_thred_range=(0.01, 0.05),
|
||||
prob_range=(0.4, 0.6),
|
||||
invalid_disp=1e7
|
||||
):
|
||||
"""A Simply PyTorch module to add realistic noise to depth images.
|
||||
|
||||
Args:
|
||||
focal_length (float): Focal length of the camera (in pixels).
|
||||
baseline (float): Baseline distance between stereo cameras (in meters).
|
||||
min_depth (float): Minimum depth value after clamping.
|
||||
max_depth (float): Maximum depth value after clamping.
|
||||
filter_size (int): Kernel size for local mean disparity computation.
|
||||
inlier_thred_range (tuple): Threshold range for normalized disparity differences.
|
||||
prob_range (tuple): Probability range for matching pixels.
|
||||
invalid_disp (float): Invalid disparity
|
||||
"""
|
||||
super().__init__()
|
||||
self.focal_length = focal_length
|
||||
self.baseline = baseline
|
||||
self.min_depth = min_depth
|
||||
self.max_depth = max_depth
|
||||
self.invalid_disp = invalid_disp
|
||||
self.inlier_thred_range = inlier_thred_range
|
||||
self.prob_range = prob_range
|
||||
self.filter_size = filter_size
|
||||
|
||||
weights, substitutes = self._compute_weights(filter_size)
|
||||
self.register_buffer('weights', weights.view(1, 1, filter_size, filter_size))
|
||||
self.register_buffer('substitutes', substitutes.view(1, 1, filter_size, filter_size))
|
||||
|
||||
def _compute_weights(self, filter_size):
|
||||
"""Compute weights and substitutes for disparity filtering.
|
||||
|
||||
Args:
|
||||
filter_size (int): Kernel size for local mean disparity computation.
|
||||
"""
|
||||
center = filter_size // 2
|
||||
idx = torch.arange(filter_size) - center
|
||||
x_filter, y_filter = torch.meshgrid(idx, idx, indexing='ij')
|
||||
sqr_radius = x_filter ** 2 + y_filter ** 2
|
||||
sqrt_radius = torch.sqrt(sqr_radius)
|
||||
weights = 1 / torch.where(sqr_radius == 0, torch.ones_like(sqrt_radius), sqrt_radius)
|
||||
weights = weights / weights.sum()
|
||||
fill_weights = 1 / (1 + sqrt_radius)
|
||||
fill_weights = torch.where(sqr_radius > filter_size, -1.0, fill_weights)
|
||||
substitutes = (fill_weights > 0).float()
|
||||
|
||||
return weights, substitutes
|
||||
|
||||
def filter_disparity(self, disparity):
|
||||
"""Filter the disparity map using local mean disparity.
|
||||
|
||||
Args:
|
||||
disparity (torch.Tensor): Input disparity map tensor of shape (B, C, H, W).
|
||||
"""
|
||||
B, _, H, W = disparity.shape
|
||||
device = disparity.device
|
||||
center = self.filter_size // 2
|
||||
|
||||
output_disparity = torch.full_like(disparity, self.invalid_disp)
|
||||
|
||||
prob = (
|
||||
torch.rand(B, 1, 1, 1, device=device)
|
||||
* (self.prob_range[1] - self.prob_range[0])
|
||||
+ self.prob_range[0]
|
||||
)
|
||||
random_mask = (torch.rand(B, 1, H, W, device=device) < prob)
|
||||
|
||||
# Compute mean disparity
|
||||
weighted_disparity = F.conv2d(disparity, self.weights, padding=center)
|
||||
|
||||
# Compute differences
|
||||
differences = torch.abs(disparity - weighted_disparity)
|
||||
|
||||
# Normalize differences based on current image statistics
|
||||
differences_flat = differences.view(B, -1)
|
||||
mean_diff = torch.mean(differences_flat, dim=1, keepdim=True)
|
||||
std_diff = torch.std(differences_flat, dim=1, keepdim=True) + 1e-6
|
||||
|
||||
normalized_differences_flat = (differences_flat - mean_diff) / std_diff
|
||||
normalized_differences = normalized_differences_flat.view_as(differences)
|
||||
|
||||
# Use parameter-based threshold on normalized differences
|
||||
threshold = (
|
||||
torch.rand(B, 1, 1, 1, device=device)
|
||||
* (self.inlier_thred_range[1] - self.inlier_thred_range[0])
|
||||
+ self.inlier_thred_range[0]
|
||||
)
|
||||
update_mask = (normalized_differences < threshold) & random_mask
|
||||
|
||||
# Compute output value: round with 1/32 precision
|
||||
disparity = torch.round(disparity * 32.0) / 32.0
|
||||
|
||||
# Update output disparity
|
||||
output_disparity = torch.where(update_mask, disparity, output_disparity)
|
||||
|
||||
# Apply substitutes to fill neighboring pixels
|
||||
filled_values = F.conv2d(update_mask.float() * disparity, self.substitutes, padding=center)
|
||||
counts = F.conv2d(update_mask.float(), self.substitutes, padding=center) + 1e-9
|
||||
average_filled_values = filled_values / counts
|
||||
output_disparity = torch.where(counts >= 1, average_filled_values, output_disparity)
|
||||
|
||||
return output_disparity
|
||||
|
||||
def forward(self, depth, add_noise: bool) -> torch.Tensor:
|
||||
# correct input shape
|
||||
if len(depth.shape) == 3:
|
||||
depth = depth.unsqueeze(1) # add channel dimension
|
||||
|
||||
# check dimension (B, 1, H, W)
|
||||
assert depth.shape[1] == 1, "Input depth tensor must have shape (B, 1, H, W)."
|
||||
assert len(depth.shape) == 4, "Input depth tensor must have shape (B, 1, H, W)."
|
||||
|
||||
if add_noise:
|
||||
# Clamp the depth values
|
||||
depth = torch.clamp(depth, min=1. / self.invalid_disp)
|
||||
|
||||
# Step 1: Convert depth to disparity
|
||||
disparity = self.focal_length * self.baseline / depth
|
||||
|
||||
# Step 2: Filter the disparity map
|
||||
filtered_disparity = self.filter_disparity(disparity)
|
||||
|
||||
# Step 3: Recompute depth from disparity
|
||||
depth = self.focal_length * self.baseline / filtered_disparity
|
||||
|
||||
# Step 4: Clamp the depth values
|
||||
depth[depth < self.min_depth] = 0.0
|
||||
|
||||
# Step 5: Set invalid depth values to 0.0
|
||||
depth[depth > self.max_depth] = 0.0
|
||||
|
||||
return depth
|
||||
|
||||
|
||||
class DepthNoiseEncoder(torch.nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
feature_dim,
|
||||
camera_config: CameraConfig = None
|
||||
):
|
||||
"""A Simply PyTorch module to add realistic noise to depth images.
|
||||
|
||||
Args:
|
||||
feature_dim (int): Number of output channels from the encoder.
|
||||
camera_config (CameraConfig, optional): Camera configuration parameters.
|
||||
If None, uses DEFAULT_CAMERA_CONFIG.
|
||||
"""
|
||||
super().__init__()
|
||||
|
||||
# Use provided config or default
|
||||
if camera_config is None:
|
||||
camera_config = DEFAULT_CAMERA_CONFIG
|
||||
|
||||
self.camera_config = camera_config
|
||||
self.depth_noise = DepthNoise(
|
||||
focal_length=camera_config.focal_length,
|
||||
baseline=camera_config.baseline,
|
||||
min_depth=camera_config.min_depth,
|
||||
max_depth=camera_config.max_depth
|
||||
)
|
||||
|
||||
self.encoder = VAENet(feature_dim)
|
||||
|
||||
try:
|
||||
self.encoder.load_state_dict(
|
||||
torch.load(camera_config.depth_encoder_path, weights_only=True),
|
||||
strict=True
|
||||
)
|
||||
print(
|
||||
'\033[92m'
|
||||
+ f'Successfully loaded pre-trained weights from {camera_config.depth_encoder_path}'
|
||||
+ '\033[0m'
|
||||
)
|
||||
except Exception as e:
|
||||
print('\033[91m' + f'Failed to load pre-trained weights: {e}' + '\033[0m')
|
||||
|
||||
def forward(
|
||||
self, depth: torch.Tensor, add_noise: bool = True
|
||||
) -> Tuple[torch.Tensor, torch.Tensor]:
|
||||
noisy_depth = self.depth_noise(depth, add_noise)
|
||||
encoded_depth = self.encoder(noisy_depth) # (B, 1, H, W) -> (B, C, H//8, W//8)
|
||||
return encoded_depth, noisy_depth
|
||||
|
||||
@torch.jit.export
|
||||
def decode(self, z: torch.Tensor) -> torch.Tensor:
|
||||
return self.encoder.decode(z)
|
||||
+229
@@ -0,0 +1,229 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Custom event functions for navigation tasks.
|
||||
|
||||
These functions are ported from the internal Isaac Lab fork and provide
|
||||
domain randomization and environment events specific to navigation tasks.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import torch
|
||||
|
||||
from isaaclab.envs import ManagerBasedEnv
|
||||
from isaaclab.managers import SceneEntityCfg
|
||||
from isaaclab.utils import math as math_utils
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from isaaclab.sensors import RayCasterCamera
|
||||
from isaaclab_nav_task.navigation.mdp import PerceptiveNavigationSE2Action
|
||||
|
||||
|
||||
def randomize_camera_height(
|
||||
env: ManagerBasedEnv,
|
||||
env_ids: torch.Tensor,
|
||||
height_range: float,
|
||||
roll_angle_range: float,
|
||||
pitch_angle_range: float,
|
||||
yaw_angle_range: float,
|
||||
asset_cfg: SceneEntityCfg = SceneEntityCfg("raycast_camera"),
|
||||
):
|
||||
"""Randomize the camera's height and orientation around the original values.
|
||||
|
||||
The function samples around the original camera offset and orientation:
|
||||
- height: original height +- height_range (meters)
|
||||
- roll: original roll +- roll_angle_range (degrees)
|
||||
- pitch: original pitch +- pitch_angle_range (degrees)
|
||||
- yaw: original yaw +- yaw_angle_range (degrees)
|
||||
|
||||
Args:
|
||||
env: The environment manager.
|
||||
env_ids: The environment ids to randomize.
|
||||
height_range: Range around original height (meters).
|
||||
roll_angle_range: Range around original roll angle (degrees).
|
||||
pitch_angle_range: Range around original pitch angle (degrees).
|
||||
yaw_angle_range: Range around original yaw angle (degrees).
|
||||
asset_cfg: Scene entity configuration for the camera.
|
||||
"""
|
||||
camera: RayCasterCamera = env.scene[asset_cfg.name]
|
||||
|
||||
# Get original camera position and orientation
|
||||
original_camera_pos = camera.cfg.offset.pos
|
||||
original_camera_quat = camera.cfg.offset.rot
|
||||
|
||||
# Sample position around original value
|
||||
num_envs = env_ids.numel()
|
||||
pos_delta = torch.zeros((num_envs, 3), device=env.device)
|
||||
pos_delta[:, 0] = torch.randn(num_envs, device=env.device) * (height_range / 2.0)
|
||||
pos_delta[:, 1] = torch.randn(num_envs, device=env.device) * (height_range / 2.0)
|
||||
pos_delta[:, 0] = torch.clamp(pos_delta[:, 0], -height_range, height_range)
|
||||
pos_delta[:, 1] = torch.clamp(pos_delta[:, 1], -height_range, height_range)
|
||||
pos_delta[:, 2] = torch.rand(num_envs, device=env.device) * 2.0 * height_range - height_range
|
||||
camera._offset_pos[env_ids] = torch.tensor(original_camera_pos, device=env.device) + pos_delta
|
||||
|
||||
# Convert original quaternion to Euler angles (XYZ convention)
|
||||
quat_tensor = torch.tensor(original_camera_quat, device=env.device).unsqueeze(0)
|
||||
original_euler = math_utils.euler_xyz_from_quat(quat_tensor)
|
||||
original_roll_deg = original_euler[0] * 180.0 / torch.pi
|
||||
original_pitch_deg = original_euler[1] * 180.0 / torch.pi
|
||||
original_yaw_deg = original_euler[2] * 180.0 / torch.pi
|
||||
|
||||
# Sample angles around original values
|
||||
roll_delta_deg = torch.randn(num_envs, device=env.device) * (roll_angle_range / 2.0)
|
||||
roll_delta_deg = torch.clamp(roll_delta_deg, -roll_angle_range, roll_angle_range)
|
||||
pitch_delta_deg = torch.rand(num_envs, device=env.device) * 2.0 * pitch_angle_range - pitch_angle_range
|
||||
yaw_delta_deg = torch.randn(num_envs, device=env.device) * (yaw_angle_range / 2.0)
|
||||
yaw_delta_deg = torch.clamp(yaw_delta_deg, -yaw_angle_range, yaw_angle_range)
|
||||
|
||||
# Add deltas to original angles
|
||||
sampled_roll_deg = original_roll_deg + roll_delta_deg
|
||||
sampled_pitch_deg = original_pitch_deg + pitch_delta_deg
|
||||
sampled_yaw_deg = original_yaw_deg + yaw_delta_deg
|
||||
|
||||
# Convert to radians and build quaternion (XYZ convention)
|
||||
sampled_roll_rad = sampled_roll_deg * torch.pi / 180.0
|
||||
sampled_pitch_rad = sampled_pitch_deg * torch.pi / 180.0
|
||||
sampled_yaw_rad = sampled_yaw_deg * torch.pi / 180.0
|
||||
|
||||
camera._offset_quat[env_ids] = math_utils.quat_from_euler_xyz(sampled_roll_rad, sampled_pitch_rad, sampled_yaw_rad)
|
||||
|
||||
|
||||
def randomize_action_scale(
|
||||
env: ManagerBasedEnv,
|
||||
env_ids: torch.Tensor,
|
||||
scale_range_x: tuple[float, float],
|
||||
scale_range_y: tuple[float, float],
|
||||
scale_range_theta: tuple[float, float],
|
||||
scale_range_xb: float,
|
||||
scale_range_yb: float,
|
||||
scale_range_thetab: float,
|
||||
action_term: str,
|
||||
):
|
||||
"""Change the action scale in the scene.
|
||||
|
||||
Args:
|
||||
env: The environment manager.
|
||||
env_ids: The environment ids to change the action scale in.
|
||||
scale_range_x: The scale range for x.
|
||||
scale_range_y: The scale range for y.
|
||||
scale_range_theta: The scale range for theta.
|
||||
scale_range_xb: The bias range for x.
|
||||
scale_range_yb: The bias range for y.
|
||||
scale_range_thetab: The bias range for theta.
|
||||
action_term: Name of the action term.
|
||||
"""
|
||||
action_term_obj: PerceptiveNavigationSE2Action = env.action_manager._terms[action_term]
|
||||
|
||||
action_term_obj._policy_scaling[env_ids] = torch.tensor(
|
||||
action_term_obj.cfg.policy_scaling, device=action_term_obj.device
|
||||
).expand(len(env_ids), -1)
|
||||
|
||||
random_scales_x = (
|
||||
torch.rand(len(env_ids), 1, device=env.device) * (scale_range_x[1] - scale_range_x[0]) + scale_range_x[0]
|
||||
)
|
||||
random_scales_y = (
|
||||
torch.rand(len(env_ids), 1, device=env.device) * (scale_range_y[1] - scale_range_y[0]) + scale_range_y[0]
|
||||
)
|
||||
random_scales_theta = (
|
||||
torch.rand(len(env_ids), 1, device=env.device) * (scale_range_theta[1] - scale_range_theta[0])
|
||||
+ scale_range_theta[0]
|
||||
)
|
||||
random_scales_xb = (torch.rand(len(env_ids), 1, device=env.device) * 2 - 1) * scale_range_xb
|
||||
random_scales_yb = (torch.rand(len(env_ids), 1, device=env.device) * 2 - 1) * scale_range_yb
|
||||
random_scales_thetab = (torch.rand(len(env_ids), 1, device=env.device) * 2 - 1) * scale_range_thetab
|
||||
|
||||
random_scales = torch.cat((random_scales_x, random_scales_y, random_scales_theta), dim=-1)
|
||||
random_scales_b = torch.cat((random_scales_xb, random_scales_yb, random_scales_thetab), dim=-1)
|
||||
|
||||
action_term_obj._policy_scaling[env_ids] *= random_scales
|
||||
action_term_obj._policy_bias[env_ids, :] = random_scales_b
|
||||
|
||||
|
||||
def reset_and_randomize_delay_buffer(
|
||||
env: ManagerBasedEnv,
|
||||
env_ids: torch.Tensor,
|
||||
):
|
||||
"""Reset and randomize delay buffers.
|
||||
|
||||
This function resets the delay buffers and randomizes the time lags for
|
||||
all observation types. Requires env.delay_manager to exist.
|
||||
|
||||
Args:
|
||||
env: The environment manager (must have delay_manager attribute).
|
||||
env_ids: The environment ids to reset.
|
||||
"""
|
||||
env.delay_manager.reset(env_ids)
|
||||
env.delay_manager.randomize_lags(env_ids)
|
||||
|
||||
|
||||
def randomize_low_pass_filter_alpha(
|
||||
env: ManagerBasedEnv,
|
||||
env_ids: torch.Tensor,
|
||||
alpha_range: tuple[float, float],
|
||||
action_term: str,
|
||||
per_dimension: bool = True,
|
||||
alpha_range_vx: tuple[float, float] | None = None,
|
||||
alpha_range_vy: tuple[float, float] | None = None,
|
||||
alpha_range_omega: tuple[float, float] | None = None,
|
||||
):
|
||||
"""Randomize the low-pass filter alpha parameter for velocity command smoothing.
|
||||
|
||||
Args:
|
||||
env: The environment manager.
|
||||
env_ids: The environment ids to randomize the alpha parameter for.
|
||||
alpha_range: Tuple of (min_alpha, max_alpha) values.
|
||||
action_term: Name of the action term to modify.
|
||||
per_dimension: Whether to use different alpha for each dimension.
|
||||
alpha_range_vx: Optional range for vx dimension.
|
||||
alpha_range_vy: Optional range for vy dimension.
|
||||
alpha_range_omega: Optional range for omega dimension.
|
||||
"""
|
||||
action_term_obj: PerceptiveNavigationSE2Action = env.action_manager._terms[action_term]
|
||||
|
||||
if per_dimension:
|
||||
# Use dimension-specific ranges or fall back to global range
|
||||
vx_range = alpha_range_vx if alpha_range_vx is not None else alpha_range
|
||||
vy_range = alpha_range_vy if alpha_range_vy is not None else alpha_range
|
||||
omega_range = alpha_range_omega if alpha_range_omega is not None else alpha_range
|
||||
|
||||
alpha_vx = torch.rand(len(env_ids), device=env.device) * (vx_range[1] - vx_range[0]) + vx_range[0]
|
||||
alpha_vy = torch.rand(len(env_ids), device=env.device) * (vy_range[1] - vy_range[0]) + vy_range[0]
|
||||
alpha_omega = torch.rand(len(env_ids), device=env.device) * (omega_range[1] - omega_range[0]) + omega_range[0]
|
||||
|
||||
if hasattr(action_term_obj, "_per_env_per_dim_low_pass_alpha"):
|
||||
action_term_obj._per_env_per_dim_low_pass_alpha[env_ids, 0] = alpha_vx
|
||||
action_term_obj._per_env_per_dim_low_pass_alpha[env_ids, 1] = alpha_vy
|
||||
action_term_obj._per_env_per_dim_low_pass_alpha[env_ids, 2] = alpha_omega
|
||||
else:
|
||||
random_alpha = (
|
||||
torch.rand(len(env_ids), device=env.device) * (alpha_range[1] - alpha_range[0]) + alpha_range[0]
|
||||
)
|
||||
if hasattr(action_term_obj, "_per_env_per_dim_low_pass_alpha"):
|
||||
action_term_obj._per_env_per_dim_low_pass_alpha[env_ids] = random_alpha.unsqueeze(-1).expand(-1, 3)
|
||||
|
||||
|
||||
def disable_backward_penalty_after_steps(
|
||||
env: ManagerBasedEnv,
|
||||
env_ids: torch.Tensor,
|
||||
disable_after_steps: int,
|
||||
action_term: str,
|
||||
):
|
||||
"""Disable backward movement penalty after a certain number of steps.
|
||||
|
||||
Args:
|
||||
env: The environment manager.
|
||||
env_ids: The environment ids.
|
||||
disable_after_steps: Number of steps after which to disable the penalty.
|
||||
action_term: Name of the action term.
|
||||
"""
|
||||
action_term_obj: PerceptiveNavigationSE2Action = env.action_manager._terms[action_term]
|
||||
|
||||
if hasattr(action_term_obj, "disable_backward_penalty"):
|
||||
# Check which environments have exceeded the step threshold
|
||||
if hasattr(env, "episode_length_buf"):
|
||||
exceeded_steps = env.episode_length_buf[env_ids] >= disable_after_steps
|
||||
action_term_obj.disable_backward_penalty[env_ids[exceeded_steps]] = True
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Height scan encoder utilities for navigation tasks."""
|
||||
|
||||
from .heightscan_encoder import HeightScanFeatEncoder
|
||||
|
||||
__all__ = ["HeightScanFeatEncoder"]
|
||||
+192
@@ -0,0 +1,192 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
import os
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from typing import Tuple
|
||||
import torch.nn.functional as F
|
||||
from collections import OrderedDict
|
||||
from torchvision.ops import FeaturePyramidNetwork
|
||||
from torchvision.models import regnet_x_400mf
|
||||
from torchvision.ops import Conv2dNormActivation
|
||||
|
||||
# Local path to the encoder weights (relative to this file's directory)
|
||||
_ASSETS_DIR = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "assets", "data"))
|
||||
HEIGHTSCAN_ENCODER_PATH = os.path.join(_ASSETS_DIR, "Policies", "heightscan_encoder", "vae_heightscan3.pth")
|
||||
|
||||
class VAESampler(nn.Module):
|
||||
def __init__(self, input_dim, latent_dim):
|
||||
super(VAESampler, self).__init__()
|
||||
self.input_dim = input_dim
|
||||
self.latent_dim = latent_dim
|
||||
self.conv = Conv2dNormActivation(input_dim, latent_dim, kernel_size=3, stride=1, padding=1, bias=False)
|
||||
|
||||
# Convolutional Layers for 2D mean and logvar
|
||||
self.mean_layers = nn.Sequential(
|
||||
Conv2dNormActivation(latent_dim, latent_dim, kernel_size=3, stride=1, padding=1, bias=False),
|
||||
nn.Conv2d(latent_dim, latent_dim, kernel_size=1, stride=1, padding=0)
|
||||
)
|
||||
|
||||
self.logvar_layers = nn.Sequential(
|
||||
Conv2dNormActivation(latent_dim, latent_dim, kernel_size=3, stride=1, padding=1, bias=False),
|
||||
nn.Conv2d(latent_dim, latent_dim, kernel_size=1, stride=1, padding=0)
|
||||
)
|
||||
|
||||
def reparameterize(self, mu, logvar):
|
||||
std = torch.exp(0.5 * logvar)
|
||||
eps = torch.randn_like(std)
|
||||
return mu + eps * std
|
||||
|
||||
def forward(self, x):
|
||||
x = self.conv(x)
|
||||
x = self.mean_layers(x)
|
||||
return x
|
||||
|
||||
class EncoderFPN(nn.Module):
|
||||
def __init__(self, in_channel, out_channel):
|
||||
super(EncoderFPN, self).__init__()
|
||||
encoder = regnet_x_400mf(weights=None)
|
||||
# Remove classification head from the encoder
|
||||
encoder = nn.Sequential(*list(encoder.children())[:-2])
|
||||
# Modify the first layer to accept the number of channels in the input image
|
||||
encoder[0][0] = nn.Conv2d(in_channel, 32, kernel_size=3, stride=2, padding=1, bias=False)
|
||||
self.enc = encoder[0]
|
||||
self.enc_1 = encoder[1][:2]
|
||||
self.enc_2 = encoder[1][2]
|
||||
self.enc_3 = encoder[1][3]
|
||||
|
||||
# Feature Pyramid Network
|
||||
self.fpn = FeaturePyramidNetwork([64, 160, 400], out_channel)
|
||||
|
||||
def forward(self, x):
|
||||
raise NotImplementedError("Forward method must be implemented in the child class.")
|
||||
|
||||
# Depth image encoder
|
||||
class HeightScanEncoder(EncoderFPN):
|
||||
def __init__(self, out_channel):
|
||||
super(HeightScanEncoder, self).__init__(1, out_channel)
|
||||
|
||||
def forward(self, x):
|
||||
# check if depth has channel dimension
|
||||
if x.dim() == 3:
|
||||
x = x.unsqueeze(1)
|
||||
|
||||
out = OrderedDict()
|
||||
x = self.enc(x)
|
||||
out['feat1'] = self.enc_1(x)
|
||||
out['feat2'] = self.enc_2(out['feat1'])
|
||||
out['feat3'] = self.enc_3(out['feat2'])
|
||||
|
||||
out = self.fpn(out)
|
||||
|
||||
return out['feat1']
|
||||
|
||||
class VAEDecoder(nn.Module):
|
||||
def __init__(self, input_dim, out_dim):
|
||||
super(VAEDecoder, self).__init__()
|
||||
self.input_dim = input_dim
|
||||
self.conv = Conv2dNormActivation(input_dim, input_dim, kernel_size=3, stride=1, padding=1, bias=False)
|
||||
|
||||
self.decoder = nn.Sequential(
|
||||
# Layer 0
|
||||
nn.ConvTranspose2d(input_dim, input_dim, kernel_size=4, stride=2, padding=1, bias=False),
|
||||
nn.BatchNorm2d(input_dim),
|
||||
nn.ReLU(inplace=True),
|
||||
# Layer 1
|
||||
nn.ConvTranspose2d(input_dim, input_dim, kernel_size=4, stride=2, padding=1, bias=False),
|
||||
nn.BatchNorm2d(input_dim),
|
||||
nn.ReLU(inplace=True),
|
||||
# Layer 2
|
||||
nn.ConvTranspose2d(input_dim, input_dim, kernel_size=4, stride=2, padding=1, bias=False),
|
||||
nn.BatchNorm2d(input_dim),
|
||||
nn.ReLU(inplace=True),
|
||||
# Final Output Layer
|
||||
nn.Conv2d(input_dim, out_dim, kernel_size=3, stride=1, padding=1)
|
||||
) # Expand the spatial dimensions by a factor of 2**4=16
|
||||
|
||||
def forward(self, z):
|
||||
z = self.conv(z)
|
||||
img = self.decoder(z)
|
||||
return img
|
||||
|
||||
class HeightScanDecoder(VAEDecoder):
|
||||
def __init__(self, input_dim):
|
||||
super(HeightScanDecoder, self).__init__(input_dim, 1)
|
||||
|
||||
class VAENet(nn.Module):
|
||||
def __init__(self, latent_dim):
|
||||
super(VAENet, self).__init__()
|
||||
self.depth_encoder = HeightScanEncoder(latent_dim)
|
||||
|
||||
self.vae_sampler = VAESampler(latent_dim, latent_dim)
|
||||
|
||||
self.depth_decoder = HeightScanDecoder(latent_dim)
|
||||
|
||||
def forward(self, x):
|
||||
x = self.depth_encoder(x)
|
||||
x = self.vae_sampler(x)
|
||||
return x
|
||||
|
||||
def decode(self, z):
|
||||
return self.depth_decoder(z)
|
||||
|
||||
|
||||
class HeightScanFeatEncoder(torch.nn.Module):
|
||||
def __init__(self,
|
||||
feature_dim,
|
||||
):
|
||||
"""
|
||||
A Simply PyTorch module to add realistic noise to depth images.
|
||||
|
||||
Args:
|
||||
feature_dim (int): Number of output channels from the encoder.
|
||||
"""
|
||||
super().__init__()
|
||||
|
||||
self.encoder = VAENet(feature_dim)
|
||||
|
||||
try:
|
||||
self.encoder.load_state_dict(torch.load(HEIGHTSCAN_ENCODER_PATH, weights_only=True), strict=True)
|
||||
print('\033[92m' + f'Successfully loaded pre-trained weights from {HEIGHTSCAN_ENCODER_PATH}' + '\033[0m')
|
||||
except Exception as e:
|
||||
print('\033[91m' + f'Failed to load pre-trained weights: {e}' + '\033[0m')
|
||||
|
||||
def forward(self, scan: torch.Tensor) -> torch.Tensor:
|
||||
encoded_scan = self.encoder(scan) # (B, 1, H, W) -> (B, C, H//8, W//8)
|
||||
return encoded_scan
|
||||
|
||||
@torch.jit.export
|
||||
def decode(self, z: torch.Tensor) -> torch.Tensor:
|
||||
return self.encoder.decode(z)
|
||||
|
||||
|
||||
# Example usage
|
||||
if __name__ == "__main__":
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
# parameters for the depth noise
|
||||
feature_dim = 64
|
||||
|
||||
# Initialize the DepthNoise class
|
||||
heightscan_feat_encoder = HeightScanFeatEncoder(feature_dim=feature_dim)
|
||||
|
||||
# compile the depth_noise module
|
||||
compiled_scan_encoder = torch.jit.script(heightscan_feat_encoder)
|
||||
|
||||
# random height scan image
|
||||
scan = np.random.rand(51, 51) * 5
|
||||
|
||||
# convert depth to tensor
|
||||
scan = torch.tensor(scan).unsqueeze(0).unsqueeze(0).float()
|
||||
clipped_scan = torch.clamp(scan, min=-5, max=5)
|
||||
|
||||
# Add noise to the depth image
|
||||
noisy_scan = compiled_scan_encoder(clipped_scan)
|
||||
|
||||
noisy_scan = noisy_scan.numpy().squeeze().squeeze()
|
||||
# check the min and max values of the noisy depth
|
||||
print("Min depth: ", noisy_scan.min())
|
||||
print("Max depth: ", noisy_scan.max())
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Custom math utilities for navigation tasks."""
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
@torch.jit.script
|
||||
def vec_to_quat(v: torch.Tensor) -> torch.Tensor:
|
||||
"""Converts a unit vector to a quaternion representing the rotation from the X-axis to the vector v.
|
||||
|
||||
Args:
|
||||
v (torch.Tensor): A tensor of shape (..., 3) representing the unit vectors.
|
||||
|
||||
Returns:
|
||||
torch.Tensor: A tensor of shape (..., 4) representing the quaternions (w, x, y, z).
|
||||
"""
|
||||
# Ensure v is a unit vector
|
||||
norm_v = v / torch.clamp(torch.norm(v, dim=-1, keepdim=True), min=1e-8)
|
||||
|
||||
# Reference vector (X-axis)
|
||||
a = torch.tensor([1.0, 0.0, 0.0], device=norm_v.device, dtype=norm_v.dtype).expand_as(norm_v)
|
||||
|
||||
# Compute dot and cross products
|
||||
dot = torch.sum(a * norm_v, dim=-1, keepdim=True)
|
||||
w = torch.cross(a, norm_v, dim=-1)
|
||||
|
||||
# Compute quaternion components
|
||||
s = torch.sqrt((1.0 + dot) * 0.5).clamp(min=1e-8) # Avoid division by zero
|
||||
q = torch.cat([s, w / (2.0 * s)], dim=-1)
|
||||
|
||||
# Handle edge case when dot == -1 (vectors are opposite)
|
||||
mask = (dot < -0.999999).squeeze(-1)
|
||||
if mask.any():
|
||||
# Choose an arbitrary orthogonal vector
|
||||
orthogonal = torch.cross(
|
||||
a[mask],
|
||||
torch.tensor([0.0, 1.0, 0.0], device=norm_v.device, dtype=norm_v.dtype).expand_as(a[mask]),
|
||||
dim=-1
|
||||
)
|
||||
orthogonal = orthogonal / torch.clamp(torch.norm(orthogonal, dim=-1, keepdim=True), min=1e-8)
|
||||
q[mask] = torch.cat([torch.zeros_like(s[mask]), orthogonal], dim=-1)
|
||||
|
||||
# Normalize the quaternion
|
||||
q = q / torch.clamp(torch.norm(q, dim=-1, keepdim=True), min=1e-8)
|
||||
return q
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Navigation-specific MDP components including goal commands and SE2 actions."""
|
||||
|
||||
from .goal_commands import * # noqa: F401, F403
|
||||
from .goal_commands_cfg import * # noqa: F401, F403
|
||||
from .actions import * # noqa: F401, F403
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
|
||||
from .navigation_se2_actions import PerceptiveNavigationSE2Action
|
||||
from .navigation_se2_actions_cfg import PerceptiveNavigationSE2ActionCfg
|
||||
|
||||
__all__ = ["PerceptiveNavigationSE2Action", "PerceptiveNavigationSE2ActionCfg"]
|
||||
+249
@@ -0,0 +1,249 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Navigation SE2 action term for hierarchical control."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import torch
|
||||
|
||||
from isaaclab.envs import ManagerBasedRLEnv
|
||||
from isaaclab.managers.action_manager import ActionTerm
|
||||
from isaaclab.utils.assets import check_file_path, read_file
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .navigation_se2_actions_cfg import PerceptiveNavigationSE2ActionCfg
|
||||
|
||||
|
||||
class PerceptiveNavigationSE2Action(ActionTerm):
|
||||
"""Actions to navigate a robot using hierarchical control with a pre-trained locomotion policy."""
|
||||
|
||||
cfg: PerceptiveNavigationSE2ActionCfg
|
||||
_env: ManagerBasedRLEnv
|
||||
|
||||
def __init__(self, cfg: PerceptiveNavigationSE2ActionCfg, env: ManagerBasedRLEnv):
|
||||
super().__init__(cfg, env)
|
||||
# Check if policy file exists
|
||||
if not check_file_path(cfg.low_level_policy_file):
|
||||
raise FileNotFoundError(f"Policy file '{cfg.low_level_policy_file}' does not exist.")
|
||||
# Load pre-trained locomotion policy
|
||||
file_bytes = read_file(self.cfg.low_level_policy_file)
|
||||
self.low_level_policy = torch.jit.load(file_bytes, map_location=self.device)
|
||||
self.low_level_policy.eval()
|
||||
|
||||
# prepare joint position actions
|
||||
self.low_level_position_action_term: ActionTerm = self.cfg.low_level_position_action.class_type(cfg.low_level_position_action, env)
|
||||
# Velocity branch is optional (None for legs-only robots like Go2).
|
||||
if self.cfg.low_level_velocity_action is not None:
|
||||
self.low_level_velocity_action_term: ActionTerm | None = self.cfg.low_level_velocity_action.class_type(cfg.low_level_velocity_action, env)
|
||||
else:
|
||||
self.low_level_velocity_action_term = None
|
||||
|
||||
# prepare buffers
|
||||
self._action_dim = 3 # [vx, vy, omega]
|
||||
|
||||
# set up buffers
|
||||
self._init_buffers()
|
||||
|
||||
# Low-pass filter state for velocity commands
|
||||
self._prev_filtered_velocity_commands = torch.zeros((self.num_envs, self._action_dim), device=self.device)
|
||||
self._low_pass_alpha = self.cfg.low_pass_filter_alpha if hasattr(self.cfg, 'low_pass_filter_alpha') else 0.8
|
||||
self._enable_low_pass_filter = self.cfg.enable_low_pass_filter if hasattr(self.cfg, 'enable_low_pass_filter') else True
|
||||
# Per-environment per-dimension alpha values (initialized to default, can be randomized per episode)
|
||||
# Shape: [num_envs, action_dim] where action_dim = 3 (vx, vy, omega)
|
||||
self._per_env_per_dim_low_pass_alpha = torch.full((self.num_envs, self._action_dim), self._low_pass_alpha, device=self.device)
|
||||
|
||||
|
||||
"""
|
||||
Properties.
|
||||
"""
|
||||
|
||||
@property
|
||||
def action_dim(self) -> int:
|
||||
return self._action_dim
|
||||
|
||||
@property
|
||||
def raw_actions(self) -> torch.Tensor:
|
||||
return self._raw_navigation_velocity_actions
|
||||
|
||||
@property
|
||||
def processed_actions(self) -> torch.Tensor:
|
||||
return self._processed_navigation_velocity_actions
|
||||
|
||||
@property
|
||||
def filtered_velocity_commands(self) -> torch.Tensor:
|
||||
"""Get the current filtered (smoothed) velocity commands."""
|
||||
return self._prev_filtered_velocity_commands
|
||||
|
||||
@property
|
||||
def low_pass_alpha_values(self) -> torch.Tensor:
|
||||
"""Get the current per-environment per-dimension low-pass filter alpha values.
|
||||
|
||||
Returns:
|
||||
torch.Tensor: Alpha values with shape [num_envs, action_dim] where:
|
||||
- action_dim = 3 for [vx, vy, omega]
|
||||
- Each environment can have different alpha values for each command dimension
|
||||
"""
|
||||
return self._per_env_per_dim_low_pass_alpha
|
||||
|
||||
@property
|
||||
def low_level_actions(self) -> torch.Tensor:
|
||||
if self.low_level_velocity_action_term is None:
|
||||
return self._low_level_position_actions
|
||||
return torch.cat((self._low_level_position_actions, self._low_level_velocity_actions), dim=1)
|
||||
|
||||
@property
|
||||
def low_level_position_actions(self) -> torch.Tensor:
|
||||
return self._low_level_position_actions
|
||||
|
||||
@property
|
||||
def prev_low_level_position_actions(self) -> torch.Tensor:
|
||||
return self._prev_low_level_position_actions
|
||||
|
||||
@property
|
||||
def low_level_velocity_actions(self) -> torch.Tensor:
|
||||
return self._low_level_velocity_actions
|
||||
|
||||
@property
|
||||
def prev_low_level_velocity_actions(self) -> torch.Tensor:
|
||||
return self._prev_low_level_velocity_actions
|
||||
|
||||
"""
|
||||
Operations.
|
||||
"""
|
||||
|
||||
def apply_low_pass_filter(self, velocity_commands: torch.Tensor) -> torch.Tensor:
|
||||
"""Apply low-pass filter to velocity commands for smoother locomotion.
|
||||
|
||||
The low-pass filter implements exponential smoothing:
|
||||
filtered_cmd(t) = alpha * filtered_cmd(t-1) + (1 - alpha) * new_cmd(t)
|
||||
|
||||
Where alpha is the smoothing factor:
|
||||
- alpha = 0.0: No smoothing (pass through)
|
||||
- alpha = 1.0: Maximum smoothing (no change)
|
||||
- alpha = 0.8: Good balance for locomotion (default)
|
||||
|
||||
This implementation supports per-environment per-dimension alpha values, allowing:
|
||||
- Different smoothing for vx, vy, and omega in each environment
|
||||
- Independent control over linear and angular velocity response
|
||||
|
||||
Args:
|
||||
velocity_commands (torch.Tensor): Raw velocity commands [num_envs, 3] (vx, vy, omega)
|
||||
|
||||
Returns:
|
||||
torch.Tensor: Filtered velocity commands with same shape as input
|
||||
"""
|
||||
if not self._enable_low_pass_filter:
|
||||
return velocity_commands
|
||||
|
||||
# Use per-environment per-dimension alpha values for filtering
|
||||
# Shape: [num_envs, action_dim] - already matches velocity_commands shape
|
||||
alpha_values = self._per_env_per_dim_low_pass_alpha
|
||||
|
||||
# Apply exponential smoothing (low-pass filter) with per-environment per-dimension alpha
|
||||
filtered_commands = (
|
||||
alpha_values * self._prev_filtered_velocity_commands
|
||||
+ (1.0 - alpha_values) * velocity_commands
|
||||
)
|
||||
|
||||
# Update previous filtered commands for next iteration
|
||||
self._prev_filtered_velocity_commands.copy_(filtered_commands)
|
||||
|
||||
return filtered_commands
|
||||
|
||||
def process_actions(self, actions):
|
||||
"""Process low-level navigation actions. This function is called with a frequency of 10Hz.
|
||||
|
||||
Args:
|
||||
actions (torch.Tensor): The low-level navigation actions.
|
||||
"""
|
||||
# Store the raw low-level navigation actions
|
||||
self._raw_navigation_velocity_actions[:] = actions
|
||||
# Apply the affine transformations
|
||||
if not self.cfg.use_raw_actions:
|
||||
self._processed_navigation_velocity_actions = (
|
||||
self._raw_navigation_velocity_actions * self._scale + self._offset
|
||||
)
|
||||
else:
|
||||
self._processed_navigation_velocity_actions[:] = self._raw_navigation_velocity_actions
|
||||
|
||||
if self.cfg.policy_distr_type == "gaussian":
|
||||
# scale the actions to the range [-1, 1] for gaussian distribution
|
||||
self._processed_navigation_velocity_actions = torch.tanh(self._processed_navigation_velocity_actions)
|
||||
elif self.cfg.policy_distr_type == "beta":
|
||||
# scale the actions to the range [-1, 1] for beta distribution
|
||||
self._processed_navigation_velocity_actions = (self._processed_navigation_velocity_actions - 0.5) * 2.0
|
||||
else:
|
||||
raise ValueError(f"Unknown policy distribution type: {self.cfg.policy_distr_type}")
|
||||
|
||||
# compute the current speed of the robot to generate low-level actions based on the current speed
|
||||
observations = self._env.observation_manager.compute_group(group_name=self.cfg.observation_group)
|
||||
base_lin_vel = observations[:, 0:3]
|
||||
vel_xyz = base_lin_vel.norm(dim=1, keepdim=True)
|
||||
|
||||
# [vx, vy, omega]
|
||||
self._processed_navigation_velocity_actions = (self._processed_navigation_velocity_actions + vel_xyz * self._policy_bias) * self._policy_scaling
|
||||
|
||||
# Apply low-pass filter to smooth velocity commands and add delay effect
|
||||
self._processed_navigation_velocity_actions = self.apply_low_pass_filter(self._processed_navigation_velocity_actions)
|
||||
|
||||
@torch.inference_mode()
|
||||
def apply_actions(self):
|
||||
"""Apply low-level actions for the simulator to the physics engine. This functions is called with the
|
||||
simulation frequency of 200Hz. Since low-level locomotion runs at 50Hz, we need to decimate the actions."""
|
||||
|
||||
if self._counter % self.cfg.low_level_decimation == 0:
|
||||
self._counter = 0
|
||||
self._prev_low_level_position_actions[:] = self._low_level_position_actions.clone()
|
||||
if self.low_level_velocity_action_term is not None:
|
||||
self._prev_low_level_velocity_actions[:] = self._low_level_velocity_actions.clone()
|
||||
|
||||
# Get low level actions from low level policy
|
||||
actions_phase = self.low_level_policy(
|
||||
self._env.observation_manager.compute_group(group_name=self.cfg.observation_group)
|
||||
)
|
||||
|
||||
# Process actions and bring them in the right order
|
||||
pos_dim = self.low_level_position_action_term.action_dim
|
||||
self._low_level_position_actions[:] = actions_phase[:, :pos_dim]
|
||||
self.low_level_position_action_term.process_actions(self._low_level_position_actions)
|
||||
if self.low_level_velocity_action_term is not None:
|
||||
self._low_level_velocity_actions[:] = actions_phase[:, pos_dim:]
|
||||
self.low_level_velocity_action_term.process_actions(self._low_level_velocity_actions)
|
||||
|
||||
# Apply low level actions
|
||||
self.low_level_position_action_term.apply_actions()
|
||||
if self.low_level_velocity_action_term is not None:
|
||||
self.low_level_velocity_action_term.apply_actions()
|
||||
self._counter += 1
|
||||
|
||||
def reset_low_pass_filter(self, env_ids: torch.Tensor):
|
||||
"""Reset low-pass filter state for specified environments.
|
||||
|
||||
Args:
|
||||
env_ids: Environment indices to reset.
|
||||
"""
|
||||
self._prev_filtered_velocity_commands[env_ids] = 0.0
|
||||
|
||||
"""
|
||||
Helper functions
|
||||
"""
|
||||
|
||||
def _init_buffers(self):
|
||||
# Prepare buffers
|
||||
self._raw_navigation_velocity_actions = torch.zeros(self.num_envs, self._action_dim, device=self.device)
|
||||
self._processed_navigation_velocity_actions = torch.zeros((self.num_envs, self._action_dim), device=self.device)
|
||||
self._low_level_position_actions = torch.zeros(self.num_envs, self.low_level_position_action_term.action_dim, device=self.device)
|
||||
vel_dim = self.low_level_velocity_action_term.action_dim if self.low_level_velocity_action_term is not None else 0
|
||||
self._low_level_velocity_actions = torch.zeros(self.num_envs, vel_dim, device=self.device)
|
||||
self._prev_low_level_position_actions = torch.zeros_like(self._low_level_position_actions)
|
||||
self._prev_low_level_velocity_actions = torch.zeros_like(self._low_level_velocity_actions)
|
||||
self._low_level_step_dt = self.cfg.low_level_decimation * self._env.physics_dt
|
||||
self._counter = 0
|
||||
self._scale = torch.tensor(self.cfg.scale, device=self.device)
|
||||
self._offset = torch.tensor(self.cfg.offset, device=self.device)
|
||||
self._policy_scaling = torch.tensor(self.cfg.policy_scaling, device=self.device).repeat(self.num_envs, 1)
|
||||
self._policy_bias = torch.zeros(self.num_envs, self._action_dim, device=self.device)
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import MISSING
|
||||
|
||||
from isaaclab.managers.action_manager import ActionTerm, ActionTermCfg
|
||||
from isaaclab.utils import configclass
|
||||
|
||||
from .navigation_se2_actions import PerceptiveNavigationSE2Action
|
||||
|
||||
|
||||
@configclass
|
||||
class PerceptiveNavigationSE2ActionCfg(ActionTermCfg):
|
||||
class_type: type[ActionTerm] = PerceptiveNavigationSE2Action
|
||||
""" Class of the action term."""
|
||||
low_level_decimation: int = 4
|
||||
"""Decimation factor for the low level action term."""
|
||||
use_raw_actions: bool = False
|
||||
"""Whether to use raw actions or not."""
|
||||
scale: list[float] = [1.0, 1.0, 1.0]
|
||||
"""Scale for the actions [vx, vy, w]."""
|
||||
offset: list[float] = [0.0, 0.0, 0.0]
|
||||
"""Offset for the actions [vx, vy, w]."""
|
||||
low_level_velocity_action: ActionTermCfg | None = None
|
||||
"""Configuration of the low level velocity action term.
|
||||
|
||||
Set to ``None`` for legs-only quadrupeds (e.g. Go2) whose locomotion policy
|
||||
only outputs joint position targets. The position-action branch then handles
|
||||
all 12 leg joints, and the velocity-action branch is fully bypassed."""
|
||||
low_level_position_action: ActionTermCfg = MISSING
|
||||
"""Configuration of the low level position action term."""
|
||||
low_level_policy_file: str = MISSING
|
||||
"""Path to the low level policy file."""
|
||||
observation_group: str = "policy"
|
||||
"""Observation group to use for the low level policy."""
|
||||
policy_scaling: list[float] = [1.0, 1.0, 1.0]
|
||||
"""Policy dependent scaling for the actions [vx, vy, w]."""
|
||||
reorder_joint_list: list[str] | None = None
|
||||
"""Reorder the joint actions given from the low-level policy to match the Isaac Sim order if policy has been
|
||||
trained with a different order. Set to None to disable reordering."""
|
||||
policy_distr_type: str = "gaussian"
|
||||
"""Policy distribution type: 'gaussian', 'beta'."""
|
||||
# Low-pass filter parameters
|
||||
enable_low_pass_filter: bool = True
|
||||
"""Whether to enable low-pass filtering for velocity commands."""
|
||||
low_pass_filter_alpha: float = 0.5
|
||||
"""Low-pass filter smoothing factor (0.0 = no smoothing, 1.0 = maximum smoothing).
|
||||
Formula: filtered_cmd = alpha * prev_filtered_cmd + (1 - alpha) * new_cmd"""
|
||||
+786
@@ -0,0 +1,786 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Goal command generator for robot navigation tasks.
|
||||
|
||||
Simplified architecture:
|
||||
1. Terrain generation creates `valid_mask` (boolean mask of valid positions with safety padding)
|
||||
2. This module samples goal/spawn positions uniformly from valid positions
|
||||
3. Z-height is looked up from the visual height field
|
||||
|
||||
The terrain module handles:
|
||||
- Height field generation
|
||||
- Obstacle detection
|
||||
- Safety padding (dilation)
|
||||
- Border exclusion
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from collections.abc import Sequence
|
||||
from typing import TYPE_CHECKING, Tuple, Optional
|
||||
|
||||
import torch
|
||||
|
||||
import isaaclab.utils.math as math_utils
|
||||
from isaaclab.assets import Articulation
|
||||
from isaaclab.managers import CommandTerm
|
||||
from isaaclab.markers import VisualizationMarkers
|
||||
from isaaclab.markers.config import (
|
||||
CUBOID_MARKER_CFG,
|
||||
GREEN_ARROW_X_MARKER_CFG,
|
||||
RED_ARROW_X_MARKER_CFG,
|
||||
)
|
||||
from isaaclab.utils.math import subtract_frame_transforms, transform_points, yaw_quat
|
||||
|
||||
from isaaclab_nav_task.navigation.mdp.math_utils import vec_to_quat
|
||||
from isaaclab_nav_task.terrains.terrain_constants import VERTICAL_SCALE
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from isaaclab.envs import ManagerBasedRLEnv
|
||||
from .goal_commands_cfg import RobotNavigationGoalCommandCfg
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Position Sampler (Simplified)
|
||||
# =============================================================================
|
||||
|
||||
class PositionSampler:
|
||||
"""Samples positions uniformly from valid terrain cells.
|
||||
|
||||
Uses pre-computed valid_mask from terrain generation (already has safety padding).
|
||||
For spawn positions, uses spawn_mask with larger padding to account for robot body.
|
||||
|
||||
Coordinate System:
|
||||
- The height field has shape (num_cells_x, num_cells_y), e.g., (299, 299)
|
||||
- Each cell is horizontal_scale meters (e.g., 0.1m)
|
||||
- The mesh is generated with a border: border_pixels = int(border_width / horizontal_scale) + 1
|
||||
- Our valid_mask corresponds to the inner terrain (no border)
|
||||
- Local coordinates are centered: (-terrain_size/2, -terrain_size/2) to (+terrain_size/2, +terrain_size/2)
|
||||
- Border pixel offset is computed dynamically from terrain config (not hardcoded)
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
heights: torch.Tensor,
|
||||
valid_mask: torch.Tensor,
|
||||
platform_mask: torch.Tensor,
|
||||
terrain_size: float,
|
||||
horizontal_scale: float,
|
||||
device: torch.device,
|
||||
platform_repeat_count: int = 10,
|
||||
spawn_mask: torch.Tensor = None,
|
||||
border_width: float = 0.0,
|
||||
):
|
||||
"""Initialize the sampler.
|
||||
|
||||
Args:
|
||||
heights: Height field (num_terrains, width, height) for Z-lookup.
|
||||
valid_mask: Boolean mask of valid goal positions (num_terrains, width, height).
|
||||
platform_mask: Boolean mask of platform positions for curriculum.
|
||||
terrain_size: Size of each terrain in meters (full mesh size).
|
||||
horizontal_scale: Resolution of height field in meters per cell.
|
||||
device: Torch device.
|
||||
platform_repeat_count: Repetition count for platform positions.
|
||||
spawn_mask: Boolean mask of valid spawn positions with larger padding.
|
||||
If None, defaults to valid_mask.
|
||||
border_width: Border width around terrain in meters (from terrain config).
|
||||
"""
|
||||
self.device = device
|
||||
self.terrain_size = terrain_size
|
||||
self.horizontal_scale = horizontal_scale
|
||||
self.heights = heights
|
||||
self.valid_mask = valid_mask
|
||||
self.platform_mask = platform_mask
|
||||
# Use spawn_mask if provided, otherwise fall back to valid_mask
|
||||
self.spawn_mask = spawn_mask if spawn_mask is not None else valid_mask
|
||||
|
||||
# Use horizontal_scale as cell size (correct resolution)
|
||||
self.cell_size = horizontal_scale
|
||||
|
||||
# Compute border pixel offset dynamically based on terrain configuration
|
||||
# Formula matches patches.py: border_pixels = int(border_width / horizontal_scale) + 1
|
||||
# This ensures valid_mask indices map correctly to mesh coordinates
|
||||
self.border_pixels = int(border_width / horizontal_scale) + 1
|
||||
|
||||
# Mesh center offset (mesh is centered at origin after transform)
|
||||
self.mesh_center = terrain_size / 2 # e.g., 30 / 2 = 15m
|
||||
|
||||
# Build position tables for both goal and spawn sampling
|
||||
self._build_position_tables(platform_repeat_count)
|
||||
|
||||
def _build_position_tables(self, platform_repeat_count: int):
|
||||
"""Build pre-computed position tensors for efficient sampling.
|
||||
|
||||
Creates two sets of position tables:
|
||||
- Goal positions: from valid_mask with platform repetition for curriculum
|
||||
- Spawn positions: from spawn_mask (larger padding for robot body clearance)
|
||||
"""
|
||||
num_terrains = self.valid_mask.shape[0]
|
||||
|
||||
# =========================
|
||||
# Build GOAL position table (from valid_mask with platform repetition)
|
||||
# =========================
|
||||
valid_indices = self.valid_mask.nonzero(as_tuple=False)
|
||||
|
||||
# Build enhanced indices with platform repetition
|
||||
enhanced_indices = []
|
||||
for terrain_idx in range(num_terrains):
|
||||
terrain_valid = valid_indices[valid_indices[:, 0] == terrain_idx]
|
||||
|
||||
if len(terrain_valid) == 0:
|
||||
enhanced_indices.append(terrain_valid)
|
||||
continue
|
||||
|
||||
# Find platform positions
|
||||
terrain_platform = self.platform_mask[terrain_idx]
|
||||
platform_positions = terrain_platform.nonzero(as_tuple=False)
|
||||
|
||||
if len(platform_positions) > 0:
|
||||
# Check which valid positions are platforms (vectorized)
|
||||
valid_xy = terrain_valid[:, 1:] # (num_valid, 2)
|
||||
plat_xy = platform_positions # (num_platforms, 2)
|
||||
|
||||
# Broadcast compare: (num_valid, 1, 2) vs (1, num_platforms, 2)
|
||||
matches = (valid_xy.unsqueeze(1) == plat_xy.unsqueeze(0)).all(dim=2)
|
||||
is_platform = matches.any(dim=1)
|
||||
|
||||
# Repeat platform positions
|
||||
platform_valid = terrain_valid[is_platform]
|
||||
if len(platform_valid) > 0:
|
||||
repeated = platform_valid.repeat(platform_repeat_count, 1)
|
||||
terrain_valid = torch.cat([terrain_valid, repeated], dim=0)
|
||||
|
||||
enhanced_indices.append(terrain_valid)
|
||||
|
||||
# Count positions per terrain for goals
|
||||
self.count_per_terrain = torch.zeros(num_terrains, dtype=torch.long, device=self.device)
|
||||
for terrain_idx in range(num_terrains):
|
||||
self.count_per_terrain[terrain_idx] = len(enhanced_indices[terrain_idx])
|
||||
|
||||
# Create padded tensor for goal positions
|
||||
max_count = max(1, self.count_per_terrain.max().item())
|
||||
self.positions = torch.full(
|
||||
(num_terrains, max_count, 3), -1, dtype=torch.long, device=self.device
|
||||
)
|
||||
|
||||
# Fill goal position tables
|
||||
for terrain_idx in range(num_terrains):
|
||||
terrain_positions = enhanced_indices[terrain_idx]
|
||||
num_pos = terrain_positions.shape[0]
|
||||
if num_pos > 0:
|
||||
self.positions[terrain_idx, :num_pos] = terrain_positions
|
||||
|
||||
# =========================
|
||||
# Build SPAWN position table (from spawn_mask, no platform repetition)
|
||||
# =========================
|
||||
spawn_indices = self.spawn_mask.nonzero(as_tuple=False)
|
||||
|
||||
# Count spawn positions per terrain
|
||||
self.spawn_count_per_terrain = torch.zeros(num_terrains, dtype=torch.long, device=self.device)
|
||||
spawn_positions_list = []
|
||||
for terrain_idx in range(num_terrains):
|
||||
terrain_spawn = spawn_indices[spawn_indices[:, 0] == terrain_idx]
|
||||
self.spawn_count_per_terrain[terrain_idx] = len(terrain_spawn)
|
||||
spawn_positions_list.append(terrain_spawn)
|
||||
|
||||
# Create padded tensor for spawn positions
|
||||
max_spawn_count = max(1, self.spawn_count_per_terrain.max().item())
|
||||
self.spawn_positions = torch.full(
|
||||
(num_terrains, max_spawn_count, 3), -1, dtype=torch.long, device=self.device
|
||||
)
|
||||
|
||||
# Fill spawn position tables
|
||||
for terrain_idx in range(num_terrains):
|
||||
terrain_positions = spawn_positions_list[terrain_idx]
|
||||
num_pos = terrain_positions.shape[0]
|
||||
if num_pos > 0:
|
||||
self.spawn_positions[terrain_idx, :num_pos] = terrain_positions
|
||||
|
||||
def sample(self, terrain_indices: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""Sample GOAL positions for given terrain indices.
|
||||
|
||||
Uses valid_mask with platform repetition for curriculum learning.
|
||||
|
||||
Args:
|
||||
terrain_indices: Tensor of terrain indices to sample from.
|
||||
|
||||
Returns:
|
||||
Tuple of (x, y, z) local coordinates in meters.
|
||||
"""
|
||||
return self._sample_from_table(
|
||||
terrain_indices,
|
||||
self.positions,
|
||||
self.count_per_terrain
|
||||
)
|
||||
|
||||
def sample_spawn(self, terrain_indices: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""Sample SPAWN positions for given terrain indices.
|
||||
|
||||
Uses spawn_mask with larger padding to account for:
|
||||
- Robot body dimensions with random orientation
|
||||
- Platform edge safety margins
|
||||
- Controller startup behavior
|
||||
|
||||
Args:
|
||||
terrain_indices: Tensor of terrain indices to sample from.
|
||||
|
||||
Returns:
|
||||
Tuple of (x, y, z) local coordinates in meters.
|
||||
"""
|
||||
return self._sample_from_table(
|
||||
terrain_indices,
|
||||
self.spawn_positions,
|
||||
self.spawn_count_per_terrain
|
||||
)
|
||||
|
||||
def _sample_from_table(
|
||||
self,
|
||||
terrain_indices: torch.Tensor,
|
||||
positions_table: torch.Tensor,
|
||||
count_per_terrain: torch.Tensor
|
||||
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""Internal method to sample from a position table.
|
||||
|
||||
Args:
|
||||
terrain_indices: Tensor of terrain indices to sample from.
|
||||
positions_table: Pre-computed position table (num_terrains, max_count, 3).
|
||||
count_per_terrain: Number of valid positions per terrain.
|
||||
|
||||
Returns:
|
||||
Tuple of (x, y, z) local coordinates in meters.
|
||||
"""
|
||||
num_samples = terrain_indices.shape[0]
|
||||
|
||||
# Random indices within valid range
|
||||
valid_counts = count_per_terrain[terrain_indices].float().clamp(min=1)
|
||||
random_indices = (torch.rand(num_samples, device=self.device) * valid_counts).long()
|
||||
|
||||
# Lookup positions
|
||||
selected = positions_table[terrain_indices, random_indices] # (n, 3)
|
||||
is_valid = selected[:, 0] >= 0
|
||||
|
||||
local_x = torch.zeros(num_samples, device=self.device)
|
||||
local_y = torch.zeros(num_samples, device=self.device)
|
||||
local_z = torch.zeros(num_samples, device=self.device)
|
||||
|
||||
if is_valid.any():
|
||||
valid_selected = selected[is_valid]
|
||||
x_idx = valid_selected[:, 1]
|
||||
y_idx = valid_selected[:, 2]
|
||||
|
||||
# Convert to meters (accounting for border pixel offset)
|
||||
# The mesh is generated with @height_field_to_mesh which adds a border
|
||||
# border_pixels = int(border_width / horizontal_scale) + 1 (computed dynamically)
|
||||
# Mesh vertex at (i, j) has position: (i * h_scale - terrain_size/2, j * h_scale - terrain_size/2)
|
||||
# Our valid_mask[i, j] corresponds to mesh heights[i + border_pixels, j + border_pixels]
|
||||
# So the world position for valid_mask[i, j] is:
|
||||
# x = (i + border_pixels) * h_scale - terrain_size/2
|
||||
# y = (j + border_pixels) * h_scale - terrain_size/2
|
||||
local_x[is_valid] = (x_idx.float() + self.border_pixels) * self.cell_size - self.mesh_center
|
||||
local_y[is_valid] = (y_idx.float() + self.border_pixels) * self.cell_size - self.mesh_center
|
||||
|
||||
# Lookup Z from heights (our heights tensor matches valid_mask dimensions, no border offset needed)
|
||||
height_values = self.heights[valid_selected[:, 0], x_idx, y_idx]
|
||||
local_z[is_valid] = height_values.float() * VERTICAL_SCALE
|
||||
|
||||
return local_x, local_y, local_z
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Success Rate Tracker
|
||||
# =============================================================================
|
||||
|
||||
class SuccessRateTracker:
|
||||
"""Tracks navigation success rates using a rolling buffer."""
|
||||
|
||||
def __init__(self, num_envs: int, device: torch.device, buffer_size: int = 10):
|
||||
self.device = device
|
||||
self.buffer_size = buffer_size
|
||||
self.buffer = torch.full((num_envs, buffer_size), -1.0, device=device)
|
||||
self.write_index = torch.zeros(num_envs, dtype=torch.long, device=device)
|
||||
|
||||
def record_result(self, success: torch.Tensor, env_ids: torch.Tensor):
|
||||
indices = self.write_index[env_ids] % self.buffer_size
|
||||
self.buffer[env_ids, indices] = success[env_ids].float()
|
||||
self.write_index[env_ids] += 1
|
||||
|
||||
def add(self, results: torch.Tensor, env_ids: torch.Tensor):
|
||||
"""Legacy alias."""
|
||||
self.record_result(results, env_ids)
|
||||
|
||||
def clear(self, env_ids: torch.Tensor):
|
||||
self.buffer[env_ids] = -1.0
|
||||
self.write_index[env_ids] = 0
|
||||
|
||||
def get_success_rate(self) -> torch.Tensor:
|
||||
filled_count = (self.buffer >= 0).sum(dim=1).clamp(min=1)
|
||||
success_count = (self.buffer > 0).sum(dim=1)
|
||||
return success_count.float() / filled_count.float()
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Main Navigation Goal Command Generator
|
||||
# =============================================================================
|
||||
|
||||
class RobotNavigationGoalCommand(CommandTerm):
|
||||
"""Command generator for robot navigation goal positions.
|
||||
|
||||
Samples goal and spawn positions from terrain-provided valid_mask.
|
||||
"""
|
||||
|
||||
cfg: RobotNavigationGoalCommandCfg
|
||||
|
||||
def __init__(self, cfg: RobotNavigationGoalCommandCfg, env: ManagerBasedRLEnv):
|
||||
super().__init__(cfg, env)
|
||||
|
||||
self.env = env
|
||||
self.robot: Articulation = env.scene[cfg.asset_name]
|
||||
|
||||
# Terrain configuration
|
||||
terrain_cfg = env.scene.terrain.cfg.terrain_generator
|
||||
self.num_terrain_rows = terrain_cfg.num_rows
|
||||
self.num_terrain_cols = terrain_cfg.num_cols
|
||||
self.terrain_size = terrain_cfg.size[0]
|
||||
|
||||
# Initialize buffers
|
||||
self._init_command_buffers()
|
||||
self._init_tracking_buffers()
|
||||
self._init_metrics()
|
||||
|
||||
# Position sampling (lazy initialization)
|
||||
self._sampling_initialized = False
|
||||
self._position_sampler: Optional[PositionSampler] = None
|
||||
|
||||
def _init_command_buffers(self):
|
||||
"""Initialize command state buffers."""
|
||||
# Goal in body frame: [direction_x, direction_y, direction_z, log_distance]
|
||||
self.goal_command_body = torch.zeros(self.num_envs, 4, device=self.device)
|
||||
self.goal_command_body_unscaled = torch.ones(self.num_envs, 3, device=self.device)
|
||||
|
||||
# World frame positions
|
||||
self.goal_position_world = torch.zeros(self.num_envs, 3, device=self.device)
|
||||
self.goal_position_world[:, 2] = 0.5
|
||||
|
||||
self.spawn_position_world = torch.zeros(self.num_envs, 3, device=self.device)
|
||||
self.spawn_position_world[:, 2] = 0.5
|
||||
self.spawn_position_world[:, :2] = self.env.scene.env_origins[:, :2]
|
||||
|
||||
self.spawn_heading_world = torch.zeros(self.num_envs, device=self.device)
|
||||
|
||||
def _init_tracking_buffers(self):
|
||||
"""Initialize goal tracking buffers."""
|
||||
self.steps_at_goal = torch.zeros(self.num_envs, device=self.device)
|
||||
self.time_at_goal = torch.zeros(self.num_envs, device=self.device)
|
||||
self.required_steps_at_goal = 4.0 / self.env.step_dt
|
||||
|
||||
self.initial_distance_to_goal = torch.zeros(self.num_envs, device=self.device)
|
||||
self.distance_to_goal = torch.zeros(self.num_envs, device=self.device)
|
||||
self.closest_distance_to_goal = torch.zeros(self.num_envs, device=self.device)
|
||||
|
||||
self.total_distance_traveled = torch.zeros(self.num_envs, device=self.device)
|
||||
self.previous_position = torch.zeros(self.num_envs, 3, device=self.device)
|
||||
|
||||
self.goal_reach_count = torch.zeros(self.num_envs, device=self.device)
|
||||
self.success_tracker = SuccessRateTracker(self.num_envs, self.device, buffer_size=10)
|
||||
self.success_rate_buffer = torch.full((self.num_envs, 10), -1.0, device=self.device)
|
||||
|
||||
def _init_metrics(self):
|
||||
"""Initialize performance metrics."""
|
||||
self.metrics["velocity_toward_goal"] = torch.zeros(self.num_envs, device=self.device)
|
||||
self.metrics["velocity_magnitude"] = torch.zeros(self.num_envs, device=self.device)
|
||||
self.metrics["success_rate"] = torch.zeros(self.num_envs, device=self.device)
|
||||
|
||||
# =========================================================================
|
||||
# Command Interface
|
||||
# =========================================================================
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"NavigationGoalCommand:\n\tCommand dimension: {tuple(self.command.shape[1:])}\n"
|
||||
|
||||
@property
|
||||
def command(self) -> torch.Tensor:
|
||||
return self.goal_command_body
|
||||
|
||||
def _get_unscaled_command(self) -> torch.Tensor:
|
||||
return self.goal_command_body_unscaled
|
||||
|
||||
# =========================================================================
|
||||
# Position Sampling
|
||||
# =========================================================================
|
||||
|
||||
def _initialize_position_sampling(self):
|
||||
"""Initialize position sampling from terrain-provided masks."""
|
||||
if self._sampling_initialized:
|
||||
return
|
||||
|
||||
# Get terrain data from scene.terrain (stored by patches system)
|
||||
terrain = self.env.scene.terrain
|
||||
|
||||
# Check for height field data
|
||||
heights_raw = getattr(terrain, '_height_field_visual', None)
|
||||
valid_mask_raw = getattr(terrain, '_height_field_valid_mask', None)
|
||||
platform_mask_raw = getattr(terrain, '_height_field_platform_mask', None)
|
||||
spawn_mask_raw = getattr(terrain, '_height_field_spawn_mask', None)
|
||||
|
||||
if heights_raw is None or valid_mask_raw is None:
|
||||
raise ValueError(
|
||||
"No height field data found on terrain. "
|
||||
"Ensure add_goal=True is set in terrain configuration and patches are applied."
|
||||
)
|
||||
|
||||
# Move to device
|
||||
heights = heights_raw.to(self.device)
|
||||
valid_mask = valid_mask_raw.to(self.device)
|
||||
|
||||
# Platform mask defaults to empty if not provided
|
||||
if platform_mask_raw is not None:
|
||||
platform_mask = platform_mask_raw.to(self.device)
|
||||
else:
|
||||
platform_mask = torch.zeros_like(valid_mask)
|
||||
|
||||
# Spawn mask defaults to valid_mask if not provided
|
||||
if spawn_mask_raw is not None:
|
||||
spawn_mask = spawn_mask_raw.to(self.device)
|
||||
else:
|
||||
spawn_mask = valid_mask # Fall back to goal mask
|
||||
|
||||
# Get terrain configuration parameters
|
||||
terrain_cfg = self.env.scene.terrain.cfg.terrain_generator
|
||||
horizontal_scale = terrain_cfg.horizontal_scale
|
||||
# Note: border_width for height_field_to_mesh comes from sub-terrain config (HfTerrainBaseCfg),
|
||||
# NOT from TerrainGeneratorCfg. Sub-terrain configs default to border_width=0.0.
|
||||
# TerrainGeneratorCfg.border_width (e.g., 30.0) is for the outer grid border, not per-tile.
|
||||
sub_terrain_border_width = 0.0 # Default from HfTerrainBaseCfg
|
||||
|
||||
# Create sampler with both goal (valid_mask) and spawn (spawn_mask) masks
|
||||
self._position_sampler = PositionSampler(
|
||||
heights=heights,
|
||||
valid_mask=valid_mask,
|
||||
platform_mask=platform_mask,
|
||||
terrain_size=self.terrain_size,
|
||||
horizontal_scale=horizontal_scale,
|
||||
device=self.device,
|
||||
spawn_mask=spawn_mask,
|
||||
border_width=sub_terrain_border_width,
|
||||
)
|
||||
|
||||
self._sampling_initialized = True
|
||||
|
||||
def _get_terrain_indices(self, env_ids: torch.Tensor) -> torch.Tensor:
|
||||
"""Get terrain indices for given environment IDs.
|
||||
|
||||
The terrain index formula depends on the generation order:
|
||||
- curriculum=True: column-major (row + col * num_rows)
|
||||
- curriculum=False: row-major (row * num_cols + col)
|
||||
|
||||
Note: terrain_levels corresponds to row, terrain_types to column.
|
||||
"""
|
||||
terrain = self.env.scene.terrain
|
||||
levels = terrain.terrain_levels[env_ids] # row
|
||||
types = terrain.terrain_types[env_ids] # col
|
||||
|
||||
# Check if curriculum mode
|
||||
terrain_cfg = self.env.scene.terrain.cfg.terrain_generator
|
||||
if terrain_cfg.curriculum:
|
||||
# Column-major order (curriculum mode iterates: for col: for row:)
|
||||
return levels + types * self.num_terrain_rows
|
||||
else:
|
||||
# Row-major order (random mode uses np.unravel_index with (num_rows, num_cols))
|
||||
return levels * self.num_terrain_cols + types
|
||||
|
||||
# =========================================================================
|
||||
# Command Sampling and Update
|
||||
# =========================================================================
|
||||
|
||||
def _resample_command(self, env_ids: Sequence[int]):
|
||||
"""Sample new goal and spawn positions.
|
||||
|
||||
Goal positions use valid_mask (smaller padding, robot just needs to reach).
|
||||
Spawn positions use spawn_mask (larger padding for robot body clearance).
|
||||
"""
|
||||
self._initialize_position_sampling()
|
||||
|
||||
if isinstance(env_ids, torch.Tensor):
|
||||
env_ids_tensor = env_ids.clone().to(device=self.device, dtype=torch.long)
|
||||
else:
|
||||
env_ids_tensor = torch.as_tensor(env_ids, device=self.device, dtype=torch.long)
|
||||
|
||||
# Reset tracking
|
||||
self._reset_tracking_state(env_ids)
|
||||
|
||||
# Get terrain indices
|
||||
terrain_indices = self._get_terrain_indices(env_ids_tensor)
|
||||
|
||||
# Sample goal positions (from valid_mask with smaller padding)
|
||||
goal_x, goal_y, goal_z = self._position_sampler.sample(terrain_indices)
|
||||
# Sample spawn positions (from spawn_mask with larger padding for robot body)
|
||||
spawn_x, spawn_y, spawn_z = self._position_sampler.sample_spawn(terrain_indices)
|
||||
|
||||
# Convert to world coordinates
|
||||
terrain = self.env.scene.terrain
|
||||
levels = terrain.terrain_levels[env_ids]
|
||||
types = terrain.terrain_types[env_ids]
|
||||
terrain_origins = terrain.terrain_origins[levels, types]
|
||||
|
||||
# Update goal position
|
||||
self.goal_position_world[env_ids, 0] = terrain_origins[:, 0] + goal_x
|
||||
self.goal_position_world[env_ids, 1] = terrain_origins[:, 1] + goal_y
|
||||
h_min, h_max = self.cfg.goal_height_offset_range
|
||||
height_offset = torch.rand(len(env_ids), device=self.device) * (h_max - h_min) + h_min
|
||||
self.goal_position_world[env_ids, 2] = goal_z + height_offset
|
||||
|
||||
# Small spawn height offset to prevent clipping into terrain
|
||||
# Note: The robot's default_root_state already includes standing height (~0.5m)
|
||||
spawn_offset = 0.05
|
||||
|
||||
# Update spawn/env origin
|
||||
terrain.env_origins[env_ids, 0] = terrain_origins[:, 0] + spawn_x
|
||||
terrain.env_origins[env_ids, 1] = terrain_origins[:, 1] + spawn_y
|
||||
terrain.env_origins[env_ids, 2] = spawn_z + spawn_offset
|
||||
|
||||
# Track spawn position
|
||||
self.spawn_position_world[env_ids, 0] = terrain_origins[:, 0] + spawn_x
|
||||
self.spawn_position_world[env_ids, 1] = terrain_origins[:, 1] + spawn_y
|
||||
self.spawn_position_world[env_ids, 2] = spawn_z + spawn_offset
|
||||
|
||||
# Initialize distance metrics
|
||||
self.initial_distance_to_goal[env_ids] = torch.norm(
|
||||
self.robot.data.root_pos_w[env_ids] - self.goal_position_world[env_ids], dim=1
|
||||
)
|
||||
self.closest_distance_to_goal[env_ids] = self.initial_distance_to_goal[env_ids]
|
||||
|
||||
def _reset_tracking_state(self, env_ids: Sequence[int]):
|
||||
"""Reset tracking state for specified environments."""
|
||||
self.steps_at_goal[env_ids] = 0
|
||||
self.time_at_goal[env_ids] = 0
|
||||
self.total_distance_traveled[env_ids] = 0.0
|
||||
self.previous_position[env_ids] = self.robot.data.root_pos_w[env_ids].clone()
|
||||
|
||||
def _update_command(self):
|
||||
"""Update command in body frame."""
|
||||
# Transform goal to body frame
|
||||
inverse_pos, inverse_rot = subtract_frame_transforms(
|
||||
self.robot.data.root_pos_w,
|
||||
self.robot.data.root_quat_w
|
||||
)
|
||||
goal_in_body = transform_points(
|
||||
self.goal_position_world.unsqueeze(1),
|
||||
inverse_pos,
|
||||
inverse_rot
|
||||
).squeeze(1)
|
||||
|
||||
self.goal_command_body_unscaled = goal_in_body.clone()
|
||||
|
||||
# Normalized direction and log distance
|
||||
distance = torch.norm(goal_in_body, dim=-1, keepdim=True)
|
||||
direction = goal_in_body / torch.clamp(distance, min=1e-6)
|
||||
log_distance = torch.log(distance + 1.0)
|
||||
|
||||
self.goal_command_body[:, :3] = direction
|
||||
self.goal_command_body[:, 3:] = log_distance
|
||||
|
||||
self._update_distance_tracking()
|
||||
|
||||
def _update_distance_tracking(self):
|
||||
"""Update distance metrics."""
|
||||
self.distance_to_goal = torch.norm(
|
||||
self.robot.data.root_pos_w - self.goal_position_world, dim=1
|
||||
)
|
||||
self.closest_distance_to_goal = torch.min(
|
||||
self.closest_distance_to_goal, self.distance_to_goal
|
||||
)
|
||||
|
||||
step_distance = torch.norm(
|
||||
self.robot.data.root_pos_w - self.previous_position, dim=1
|
||||
)
|
||||
self.total_distance_traveled += step_distance
|
||||
self.previous_position = self.robot.data.root_pos_w.clone()
|
||||
|
||||
def _resample_spawn_positions(self, env_ids: Sequence[int]):
|
||||
"""Update spawn position tracking."""
|
||||
self.spawn_position_world[env_ids, :2] = self.env.scene.env_origins[env_ids, :2]
|
||||
|
||||
# =========================================================================
|
||||
# Metrics and Reset
|
||||
# =========================================================================
|
||||
|
||||
def _update_metrics(self):
|
||||
"""Update performance metrics."""
|
||||
position_error = self.goal_position_world - self.robot.data.root_pos_w[:, :3]
|
||||
position_error_2d = position_error[:, :2]
|
||||
velocity_2d = self.robot.data.root_state_w[:, 7:9]
|
||||
|
||||
self.metrics["velocity_magnitude"] = torch.norm(velocity_2d, dim=1)
|
||||
|
||||
direction_to_goal = position_error_2d / torch.clamp(torch.norm(position_error_2d, dim=1, keepdim=True), min=1e-6)
|
||||
self.metrics["velocity_toward_goal"] = (velocity_2d * direction_to_goal).sum(dim=1)
|
||||
self.metrics["success_rate"] = self.success_tracker.get_success_rate()
|
||||
|
||||
def reset(self, env_ids: Sequence[int] | None = None) -> dict[str, float]:
|
||||
"""Reset command generator and compute episode metrics."""
|
||||
metrics_obs = self.env.observation_manager.compute_group(group_name="metrics")
|
||||
success = metrics_obs["in_goal"][env_ids].squeeze(-1)
|
||||
failed = ~success
|
||||
|
||||
# Update legacy success rate buffer
|
||||
self.success_rate_buffer[env_ids] = torch.roll(
|
||||
self.success_rate_buffer[env_ids], 1, dims=1
|
||||
)
|
||||
rate = success.float() - failed.float()
|
||||
rate[rate == 0] = -1
|
||||
self.success_rate_buffer[env_ids, 0] = rate
|
||||
|
||||
# Reset command state
|
||||
if env_ids is None:
|
||||
env_ids = slice(None)
|
||||
self.command_counter[env_ids] = 0
|
||||
self._resample(env_ids)
|
||||
|
||||
# Return mean metrics
|
||||
extras = {}
|
||||
for name, value in self.metrics.items():
|
||||
extras[name] = torch.mean(value[env_ids]).item()
|
||||
value[env_ids] = 0.0
|
||||
|
||||
return extras
|
||||
|
||||
# =========================================================================
|
||||
# Success/Failure Tracking
|
||||
# =========================================================================
|
||||
|
||||
def update_success(self, at_goal: torch.Tensor):
|
||||
self.goal_reach_count += at_goal.int()
|
||||
|
||||
def update_failures(self, failed: torch.Tensor):
|
||||
self.goal_reach_count -= failed.int()
|
||||
|
||||
# =========================================================================
|
||||
# Visualization
|
||||
# =========================================================================
|
||||
|
||||
def _set_debug_vis_impl(self, debug_vis: bool):
|
||||
if debug_vis:
|
||||
self._setup_visualizers()
|
||||
else:
|
||||
self._hide_visualizers()
|
||||
|
||||
def _setup_visualizers(self):
|
||||
"""Create visualization markers."""
|
||||
if not hasattr(self, "goal_marker"):
|
||||
cfg = CUBOID_MARKER_CFG.copy()
|
||||
cfg.prim_path = "/Visuals/Command/goal_position"
|
||||
cfg.markers["cuboid"].size = (0.2, 0.2, 0.2)
|
||||
cfg.markers["cuboid"].visual_material.diffuse_color = (0.0, 0.0, 1.0)
|
||||
self.goal_marker = VisualizationMarkers(cfg)
|
||||
|
||||
if not hasattr(self, "spawn_marker"):
|
||||
cfg = CUBOID_MARKER_CFG.copy()
|
||||
cfg.prim_path = "/Visuals/Command/spawn_position"
|
||||
cfg.markers["cuboid"].size = (0.2, 0.2, 0.2)
|
||||
cfg.markers["cuboid"].visual_material.diffuse_color = (1.0, 0.5, 0.0)
|
||||
self.spawn_marker = VisualizationMarkers(cfg)
|
||||
|
||||
if not hasattr(self, "desired_velocity_marker"):
|
||||
cfg = GREEN_ARROW_X_MARKER_CFG.copy()
|
||||
cfg.prim_path = "/Visuals/Command/desired_velocity"
|
||||
cfg.markers["arrow"].scale = (0.5, 0.5, 0.5)
|
||||
self.desired_velocity_marker = VisualizationMarkers(cfg)
|
||||
|
||||
if not hasattr(self, "current_velocity_marker"):
|
||||
cfg = RED_ARROW_X_MARKER_CFG.copy()
|
||||
cfg.prim_path = "/Visuals/Command/current_velocity"
|
||||
cfg.markers["arrow"].scale = (0.5, 0.5, 0.5)
|
||||
self.current_velocity_marker = VisualizationMarkers(cfg)
|
||||
|
||||
self.goal_marker.set_visibility(True)
|
||||
self.spawn_marker.set_visibility(True)
|
||||
self.desired_velocity_marker.set_visibility(True)
|
||||
self.current_velocity_marker.set_visibility(True)
|
||||
|
||||
def _hide_visualizers(self):
|
||||
for name in ["goal_marker", "spawn_marker", "desired_velocity_marker", "current_velocity_marker"]:
|
||||
if hasattr(self, name):
|
||||
getattr(self, name).set_visibility(False)
|
||||
|
||||
def _debug_vis_callback(self, event):
|
||||
"""Update visualization markers."""
|
||||
self.goal_marker.visualize(self.goal_position_world)
|
||||
self.spawn_marker.visualize(self.spawn_position_world)
|
||||
|
||||
arrow_position = self.robot.data.root_pos_w.clone()
|
||||
arrow_position[:, 2] += 0.5
|
||||
|
||||
desired_scale, desired_quat = self._compute_velocity_arrow(
|
||||
self.command[:, :3], is_goal_direction=True
|
||||
)
|
||||
self.desired_velocity_marker.visualize(arrow_position, desired_quat, desired_scale)
|
||||
|
||||
current_scale, current_quat = self._compute_velocity_arrow(
|
||||
self.robot.data.root_lin_vel_b, is_goal_direction=False
|
||||
)
|
||||
self.current_velocity_marker.visualize(arrow_position, current_quat, current_scale)
|
||||
|
||||
def _compute_velocity_arrow(
|
||||
self,
|
||||
velocity: torch.Tensor,
|
||||
is_goal_direction: bool
|
||||
) -> Tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Compute arrow visualization parameters."""
|
||||
base_scale = torch.tensor(
|
||||
self.desired_velocity_marker.cfg.markers["arrow"].scale,
|
||||
device=self.device
|
||||
).repeat(velocity.shape[0], 1)
|
||||
|
||||
if not is_goal_direction:
|
||||
velocity = velocity.clone()
|
||||
velocity[:, 2] = 0.0
|
||||
|
||||
base_scale[:, 0] *= torch.norm(velocity, dim=1) * 3.0
|
||||
quat = vec_to_quat(velocity)
|
||||
|
||||
if is_goal_direction:
|
||||
quat = math_utils.quat_mul(self.robot.data.root_quat_w, quat)
|
||||
else:
|
||||
quat = math_utils.quat_mul(yaw_quat(self.robot.data.root_quat_w), quat)
|
||||
|
||||
return base_scale, quat
|
||||
|
||||
# =========================================================================
|
||||
# Utility Methods
|
||||
# =========================================================================
|
||||
|
||||
def _is_position_in_bounds(self, position: torch.Tensor) -> torch.Tensor:
|
||||
half_side = math.ceil(self.num_envs ** 0.5) * self.env.cfg.scene.env_spacing / 2
|
||||
return (position[:, :2].abs() < half_side).all(dim=1)
|
||||
|
||||
def _clamp_to_bounds(self, position: torch.Tensor) -> torch.Tensor:
|
||||
origins = self.env.scene.terrain.terrain_origins.view(-1, 3)
|
||||
bounds_max = origins.max(dim=0)[0][:2]
|
||||
bounds_min = origins.min(dim=0)[0][:2]
|
||||
position[:, 0] = position[:, 0].clamp(bounds_min[0], bounds_max[0])
|
||||
position[:, 1] = position[:, 1].clamp(bounds_min[1], bounds_max[1])
|
||||
return position
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Legacy Aliases
|
||||
# =============================================================================
|
||||
|
||||
RobotNavigationGoalCommand.pos_command_b = property(lambda self: self.goal_command_body)
|
||||
RobotNavigationGoalCommand.pos_command_w = property(lambda self: self.goal_position_world)
|
||||
RobotNavigationGoalCommand.pos_spawn_w = property(lambda self: self.spawn_position_world)
|
||||
RobotNavigationGoalCommand.closes_distance_to_goal = property(
|
||||
lambda self: self.closest_distance_to_goal
|
||||
)
|
||||
RobotNavigationGoalCommand.time_at_goal_in_steps = property(lambda self: self.steps_at_goal)
|
||||
RobotNavigationGoalCommand.required_time_at_goal_in_steps = property(
|
||||
lambda self: self.required_steps_at_goal
|
||||
)
|
||||
RobotNavigationGoalCommand.goal_reached_buffer = property(lambda self: self.success_tracker)
|
||||
RobotNavigationGoalCommand.goal_reached_counter = property(lambda self: self.goal_reach_count)
|
||||
RobotNavigationGoalCommand.distance_traveled = property(lambda self: self.total_distance_traveled)
|
||||
RobotNavigationGoalCommand.previous_pos_3d = property(lambda self: self.previous_position)
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from dataclasses import MISSING
|
||||
from typing import TYPE_CHECKING, Literal
|
||||
|
||||
from isaaclab.managers import CommandTermCfg
|
||||
from isaaclab.utils import configclass
|
||||
from isaaclab.utils.noise import AdditiveUniformNoiseCfg
|
||||
from .goal_commands import RobotNavigationGoalCommand
|
||||
|
||||
|
||||
"""
|
||||
Base command generator.
|
||||
"""
|
||||
|
||||
@configclass
|
||||
class RobotNavigationGoalCommandCfg(CommandTermCfg):
|
||||
"""Configuration for the robot goal command generator."""
|
||||
|
||||
class_type: type = RobotNavigationGoalCommand
|
||||
|
||||
asset_name: str = MISSING
|
||||
"""Name of the asset in the environment for which the commands are generated."""
|
||||
|
||||
robot_to_goal_line_vis: bool = True
|
||||
"""If true, visualize the line from the robot to the goal."""
|
||||
|
||||
goal_height_offset_range: tuple[float, float] = (0.2, 0.8)
|
||||
"""Range (min, max) in meters for the random goal height offset above the ground.
|
||||
|
||||
The goal cube is placed at ``terrain_ground_height + U(min, max)``. The default
|
||||
(0.2, 0.8) is tuned for the B2W body height (~0.5-0.6 m). For shorter robots
|
||||
such as the Go2 (standing height ~0.3 m), lower this range (e.g. (0.1, 0.4)) so
|
||||
the goal marker sits near the robot body. Note: success/termination is purely
|
||||
horizontal (xy), so this offset only affects visualization and the minor 3D
|
||||
``reach_goal_xy_soft`` reward term.
|
||||
"""
|
||||
|
||||
+507
@@ -0,0 +1,507 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Observation functions for navigation tasks.
|
||||
|
||||
These functions can be passed to :class:`isaaclab.managers.ObservationTermCfg`
|
||||
to specify observations for the policy.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import TYPE_CHECKING, Optional, cast
|
||||
|
||||
import torch
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
from isaaclab.assets import Articulation, RigidObject
|
||||
from isaaclab.envs import ManagerBasedEnv, ManagerBasedRLEnv
|
||||
from isaaclab.managers import SceneEntityCfg
|
||||
|
||||
import isaaclab_nav_task.navigation.mdp as mdp
|
||||
|
||||
from .depth_utils.camera_config import CameraConfig, DEFAULT_CAMERA_CONFIG, get_camera_config
|
||||
from .depth_utils.depth_noise_encoder import DepthNoiseEncoder
|
||||
from .heightscan_utils.heightscan_encoder import HeightScanFeatEncoder
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from isaaclab_nav_task.navigation.mdp import PerceptiveNavigationSE2Action
|
||||
from isaaclab_nav_task.navigation.mdp.navigation.goal_commands import RobotNavigationGoalCommand
|
||||
|
||||
# Visualization state
|
||||
_DEPTH_VIZ_WINDOWS: dict[str, dict] = {}
|
||||
|
||||
# Global depth noise generator - will be initialized with camera config
|
||||
DEPTH_NOISE_GENERATOR: Optional[DepthNoiseEncoder] = None
|
||||
JIT_DEPTH_NOISE_GENERATOR: Optional[torch.jit.ScriptModule] = None
|
||||
|
||||
# Global height scan encoder - initialized once on first use
|
||||
HEIGHTSCAN_FEAT_ENCODER: Optional[HeightScanFeatEncoder] = None
|
||||
JIT_HEIGHTSCAN_FEAT_ENCODER: Optional[torch.jit.ScriptModule] = None
|
||||
|
||||
# Global flags/params for depth encoding
|
||||
use_jit = True
|
||||
min_depth = 0.0
|
||||
max_depth = 0.0
|
||||
|
||||
|
||||
def _update_depth_window(camera_name: str, depth_tensor: torch.Tensor, height: int, width: int, title: str) -> None:
|
||||
"""Update (or lazily create) a persistent matplotlib window for a camera.
|
||||
|
||||
This enables continuous, non-blocking visualization across steps for one or more cameras.
|
||||
"""
|
||||
try:
|
||||
# Convert to numpy and handle different tensor shapes
|
||||
if depth_tensor.dim() == 4: # [B, 1, H, W]
|
||||
depth_np = depth_tensor[0, 0].detach().cpu().numpy()
|
||||
elif depth_tensor.dim() == 2: # [B, H*W]
|
||||
depth_np = depth_tensor[0].detach().cpu().numpy().reshape(height, width)
|
||||
else:
|
||||
return
|
||||
|
||||
# Lazily create window if missing
|
||||
if camera_name not in _DEPTH_VIZ_WINDOWS:
|
||||
plt.ion()
|
||||
fig, ax = plt.subplots(1, 1, figsize=(8, 6))
|
||||
im = ax.imshow(depth_np, cmap="plasma", aspect="equal")
|
||||
cbar = plt.colorbar(im, ax=ax, label="Depth (meters)")
|
||||
ax.set_title(title)
|
||||
ax.set_xlabel("Width (pixels)")
|
||||
ax.set_ylabel("Height (pixels)")
|
||||
_DEPTH_VIZ_WINDOWS[camera_name] = {"fig": fig, "ax": ax, "im": im, "cbar": cbar}
|
||||
else:
|
||||
handle = _DEPTH_VIZ_WINDOWS[camera_name]
|
||||
im = handle["im"]
|
||||
ax = handle["ax"]
|
||||
ax.set_title(title)
|
||||
im.set_data(depth_np)
|
||||
# Optional: keep consistent color scaling per window
|
||||
im.set_clim(vmin=depth_np.min(), vmax=depth_np.max())
|
||||
|
||||
# Lightweight draw
|
||||
_DEPTH_VIZ_WINDOWS[camera_name]["fig"].canvas.draw_idle()
|
||||
plt.pause(0.001)
|
||||
except Exception as e:
|
||||
print(f"Error updating depth window for {camera_name}: {e}")
|
||||
|
||||
|
||||
def _ensure_depth_noise_generator_initialized(
|
||||
camera_config: Optional[CameraConfig] = None,
|
||||
use_jit_precompiled: bool = True,
|
||||
feature_dim: int = 64,
|
||||
):
|
||||
"""Ensure the depth noise generator is initialized with the correct configuration.
|
||||
|
||||
This is called automatically by observation functions that need depth encoding.
|
||||
If not explicitly initialized via initialize_depth_noise_generator(), it will use defaults.
|
||||
|
||||
Args:
|
||||
camera_config: The camera configuration to use. If None, uses DEFAULT_CAMERA_CONFIG.
|
||||
use_jit_precompiled: Whether to use JIT compilation for faster inference.
|
||||
feature_dim: Feature dimension for the encoder output.
|
||||
"""
|
||||
global DEPTH_NOISE_GENERATOR, JIT_DEPTH_NOISE_GENERATOR, use_jit, min_depth, max_depth
|
||||
|
||||
# Only initialize if not already done
|
||||
if DEPTH_NOISE_GENERATOR is not None:
|
||||
return
|
||||
|
||||
# Use provided camera config or default
|
||||
config = camera_config if camera_config is not None else DEFAULT_CAMERA_CONFIG
|
||||
|
||||
# Extract camera parameters
|
||||
min_depth = config.min_depth
|
||||
max_depth = config.max_depth
|
||||
resolution = config.resolution
|
||||
|
||||
print("=" * 80)
|
||||
print("Initializing depth noise generator for navigation observation:")
|
||||
print(f" Resolution: {resolution}")
|
||||
print(f" Depth range: [{min_depth}, {max_depth}]")
|
||||
print(f" Feature dim: {feature_dim}")
|
||||
print(f" Encoder path: {config.depth_encoder_path}")
|
||||
print(f" Use JIT: {use_jit_precompiled}")
|
||||
|
||||
# Initialize encoder with the new simplified API
|
||||
# The DepthNoiseEncoder now takes camera_config directly
|
||||
DEPTH_NOISE_GENERATOR = DepthNoiseEncoder(
|
||||
feature_dim=feature_dim,
|
||||
camera_config=config,
|
||||
).to(torch.device("cuda"))
|
||||
DEPTH_NOISE_GENERATOR.eval()
|
||||
|
||||
# Create JIT version for inference (optional optimization)
|
||||
use_jit = use_jit_precompiled
|
||||
if use_jit:
|
||||
# Try to find a JIT compiled version
|
||||
jit_path = config.depth_encoder_path.replace('.pth', '_jit.pt') if config.depth_encoder_path else None
|
||||
if jit_path and os.path.exists(jit_path):
|
||||
print(f" Loading precompiled JIT model from: {jit_path}")
|
||||
JIT_DEPTH_NOISE_GENERATOR = torch.jit.load(jit_path, map_location="cuda")
|
||||
JIT_DEPTH_NOISE_GENERATOR = torch.jit.optimize_for_inference(JIT_DEPTH_NOISE_GENERATOR)
|
||||
else:
|
||||
print(f" JIT compilation requested but no precompiled model found.")
|
||||
print(f" Creating JIT model from encoder...")
|
||||
example_input = torch.randn(1, 1, resolution[1], resolution[0]).cuda() # (B, C, H, W)
|
||||
JIT_DEPTH_NOISE_GENERATOR = torch.jit.trace(DEPTH_NOISE_GENERATOR, example_input)
|
||||
JIT_DEPTH_NOISE_GENERATOR = torch.jit.optimize_for_inference(JIT_DEPTH_NOISE_GENERATOR)
|
||||
else:
|
||||
JIT_DEPTH_NOISE_GENERATOR = DEPTH_NOISE_GENERATOR
|
||||
|
||||
print(" Depth noise generator initialized successfully")
|
||||
print("=" * 80)
|
||||
|
||||
|
||||
def initialize_depth_noise_generator(
|
||||
camera_config: Optional[CameraConfig] = None,
|
||||
robot_name: Optional[str] = None,
|
||||
use_jit_precompiled: bool = True,
|
||||
feature_dim: int = 64,
|
||||
):
|
||||
"""Initialize the depth noise generator with specific configuration.
|
||||
|
||||
This function should be called in the environment's __post_init__() to set up
|
||||
the depth encoder before any observations are computed.
|
||||
|
||||
Args:
|
||||
camera_config: The camera configuration to use. If None and robot_name is provided,
|
||||
uses the config for that robot. If both are None, uses DEFAULT_CAMERA_CONFIG.
|
||||
robot_name: Name of the robot (e.g., 'b2w', 'aow_d'). If provided and
|
||||
camera_config is None, automatically loads the appropriate camera config.
|
||||
use_jit_precompiled: Whether to use JIT compilation for faster inference. Defaults to True.
|
||||
feature_dim: Feature dimension for the encoder output. Defaults to 64.
|
||||
|
||||
Examples:
|
||||
# Using robot name (recommended for multi-robot training)
|
||||
initialize_depth_noise_generator(robot_name="b2w")
|
||||
|
||||
# Using explicit camera config
|
||||
initialize_depth_noise_generator(camera_config=ZEDX_CAMERA_CONFIG)
|
||||
"""
|
||||
# If camera_config not provided, try to get it from robot_name
|
||||
if camera_config is None and robot_name is not None:
|
||||
camera_config = get_camera_config(robot_name, use_default_fallback=False)
|
||||
|
||||
_ensure_depth_noise_generator_initialized(camera_config, use_jit_precompiled, feature_dim)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Observation Functions
|
||||
# ============================================================================
|
||||
|
||||
|
||||
def generated_commands_reshaped(
|
||||
env: ManagerBasedRLEnv, command_name: str, unsqueeze_pos: int = 1, flatten: bool = False
|
||||
) -> torch.Tensor:
|
||||
"""The generated command from command term in the command manager with the given name."""
|
||||
if flatten:
|
||||
return env.command_manager.get_command(command_name)
|
||||
return env.command_manager.get_command(command_name).unsqueeze(unsqueeze_pos)
|
||||
|
||||
|
||||
def base_lin_vel_delayed(
|
||||
env: ManagerBasedEnv,
|
||||
asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"),
|
||||
) -> torch.Tensor:
|
||||
"""Compute delayed root linear velocity.
|
||||
|
||||
Requires env.delay_manager to exist. Each environment has a random delay
|
||||
sampled from [0, max_delay] at episode reset.
|
||||
|
||||
Args:
|
||||
env: The environment object (must have delay_manager attribute).
|
||||
asset_cfg: The name of the asset.
|
||||
|
||||
Returns:
|
||||
The delayed linear velocity in the asset's root frame.
|
||||
"""
|
||||
asset: RigidObject = env.scene[asset_cfg.name]
|
||||
lin_vel = asset.data.root_lin_vel_b
|
||||
return env.delay_manager.compute_delayed_lin_vel(lin_vel)
|
||||
|
||||
|
||||
def base_ang_vel_delayed(
|
||||
env: ManagerBasedEnv,
|
||||
asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"),
|
||||
) -> torch.Tensor:
|
||||
"""Compute delayed root angular velocity.
|
||||
|
||||
Requires env.delay_manager to exist. Each environment has a random delay
|
||||
sampled from [0, max_delay] at episode reset.
|
||||
|
||||
Args:
|
||||
env: The environment object (must have delay_manager attribute).
|
||||
asset_cfg: The name of the asset.
|
||||
|
||||
Returns:
|
||||
The delayed angular velocity in the asset's root frame.
|
||||
"""
|
||||
asset: RigidObject = env.scene[asset_cfg.name]
|
||||
ang_vel = asset.data.root_ang_vel_b
|
||||
return env.delay_manager.compute_delayed_ang_vel(ang_vel)
|
||||
|
||||
|
||||
def projected_gravity_delayed(
|
||||
env: ManagerBasedEnv,
|
||||
asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"),
|
||||
) -> torch.Tensor:
|
||||
"""Compute delayed projected gravity.
|
||||
|
||||
Requires env.delay_manager to exist. Each environment has a random delay
|
||||
sampled from [0, max_delay] at episode reset.
|
||||
|
||||
Args:
|
||||
env: The environment object (must have delay_manager attribute).
|
||||
asset_cfg: The name of the asset.
|
||||
|
||||
Returns:
|
||||
The delayed projected gravity in the asset's root frame.
|
||||
"""
|
||||
asset: RigidObject = env.scene[asset_cfg.name]
|
||||
projected_gravity = asset.data.projected_gravity_b
|
||||
|
||||
return env.delay_manager.compute_delayed_projected_gravity(projected_gravity)
|
||||
|
||||
|
||||
def height_scan_feat(
|
||||
env: ManagerBasedEnv, sensor_cfg: SceneEntityCfg = SceneEntityCfg("height_scanner_critic"), offset: float = 0.5
|
||||
) -> torch.Tensor:
|
||||
"""Height scan feature from a ray caster sensor, encoded using a pre-trained VAE encoder.
|
||||
|
||||
The height scan is reshaped to a 51x51 grid and encoded using a VAE encoder that
|
||||
outputs a 64-channel, 7x7 spatial feature map (64*7*7 = 3136 features).
|
||||
|
||||
Args:
|
||||
env: The environment object.
|
||||
sensor_cfg: The configuration of the height scanner sensor.
|
||||
offset: Offset to subtract from the height values. Defaults to 0.5.
|
||||
|
||||
Returns:
|
||||
The encoded height scan features of shape (num_envs, 3136).
|
||||
"""
|
||||
global HEIGHTSCAN_FEAT_ENCODER, JIT_HEIGHTSCAN_FEAT_ENCODER
|
||||
|
||||
# Initialize the encoder on first call
|
||||
if HEIGHTSCAN_FEAT_ENCODER is None:
|
||||
print("Initializing height scan feature encoder...")
|
||||
HEIGHTSCAN_FEAT_ENCODER = HeightScanFeatEncoder(feature_dim=64).to(torch.device("cuda"))
|
||||
HEIGHTSCAN_FEAT_ENCODER.eval()
|
||||
JIT_HEIGHTSCAN_FEAT_ENCODER = torch.jit.script(HEIGHTSCAN_FEAT_ENCODER)
|
||||
JIT_HEIGHTSCAN_FEAT_ENCODER = torch.jit.optimize_for_inference(JIT_HEIGHTSCAN_FEAT_ENCODER)
|
||||
|
||||
# Get height scanner data
|
||||
height_scanner = env.scene.sensors[sensor_cfg.name]
|
||||
|
||||
# Compute height scan: sensor_height - hit_z - offset
|
||||
scan_data = height_scanner.data.pos_w[:, 2].unsqueeze(1) - height_scanner.data.ray_hits_w[..., 2] - offset
|
||||
|
||||
# Clamp the height scan data to the range [-5, 5]
|
||||
scan_data = torch.clamp(scan_data, min=-5.0, max=5.0)
|
||||
|
||||
# Expected grid size for the height scanner (51x51 = 2601 points)
|
||||
H = W = 51
|
||||
|
||||
# Reshape the height scan data to a 2D grid
|
||||
scan_data = scan_data.view(-1, H, W)
|
||||
|
||||
# Encode using the pre-trained encoder
|
||||
with torch.no_grad():
|
||||
encoded_scan = JIT_HEIGHTSCAN_FEAT_ENCODER(scan_data)
|
||||
|
||||
# Flatten and return: (batch, 64, 7, 7) -> (batch, 3136)
|
||||
return encoded_scan.view(env.num_envs, -1)
|
||||
|
||||
|
||||
def generated_actions(env: ManagerBasedRLEnv, action_name: str) -> torch.Tensor:
|
||||
"""The generated action from action term in the action manager with the given name.
|
||||
|
||||
Args:
|
||||
env: The environment object.
|
||||
action_name: The name of the action term.
|
||||
|
||||
Returns:
|
||||
The processed actions from the action term.
|
||||
"""
|
||||
return env.action_manager.get_term(action_name).processed_actions
|
||||
|
||||
|
||||
def generated_commands_reshaped_delayed(
|
||||
env: ManagerBasedRLEnv,
|
||||
command_name: str,
|
||||
unsqueeze_pos: int = 1,
|
||||
flatten: bool = False,
|
||||
) -> torch.Tensor:
|
||||
"""The generated command with delay applied.
|
||||
|
||||
Requires env.delay_manager to exist. Each environment has a random delay
|
||||
sampled from [0, max_delay] at episode reset.
|
||||
|
||||
Args:
|
||||
env: The environment object (must have delay_manager attribute).
|
||||
command_name: The name of the command term.
|
||||
unsqueeze_pos: Position to unsqueeze the command.
|
||||
flatten: Whether to flatten the command.
|
||||
|
||||
Returns:
|
||||
The delayed command.
|
||||
"""
|
||||
if flatten:
|
||||
command = env.command_manager.get_command(command_name)
|
||||
return env.delay_manager.compute_delayed_target_position(command)
|
||||
|
||||
command = env.command_manager.get_command(command_name).unsqueeze(unsqueeze_pos)
|
||||
return env.delay_manager.compute_delayed_target_position(command)
|
||||
|
||||
|
||||
def last_low_level_action(
|
||||
env: ManagerBasedEnv, action_term: str, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")
|
||||
) -> torch.Tensor:
|
||||
"""The last low-level action.
|
||||
|
||||
Args:
|
||||
env: The environment object.
|
||||
action_term: The name of the action term.
|
||||
|
||||
Returns:
|
||||
The last low-level action.
|
||||
"""
|
||||
action_term: PerceptiveNavigationSE2Action = env.action_manager._terms[action_term]
|
||||
return action_term.low_level_actions[:, asset_cfg.joint_ids]
|
||||
|
||||
|
||||
@torch.inference_mode()
|
||||
def depth_image_prefect(env, sensor_cfg):
|
||||
"""Return the perfect (non-noisy) encoded depth image from the camera.
|
||||
|
||||
Args:
|
||||
env: The environment object.
|
||||
sensor_cfg: The sensor configuration.
|
||||
|
||||
Returns:
|
||||
The encoded depth image features.
|
||||
"""
|
||||
# Ensure encoder is initialized
|
||||
_ensure_depth_noise_generator_initialized()
|
||||
|
||||
depth_camera = env.scene.sensors[sensor_cfg.name]
|
||||
|
||||
# Get depth image tensor
|
||||
depth_tensor = depth_camera.data.output["distance_to_image_plane"].view(env.num_envs, -1)
|
||||
|
||||
# Handle NaN values by replacing them with 50.0
|
||||
depth_tensor = torch.nan_to_num(depth_tensor, nan=50.0, posinf=50.0, neginf=0.0)
|
||||
|
||||
# Reshape the tensor to [B, 1, H, W]
|
||||
H, W = depth_camera.image_shape
|
||||
depth_tensor = depth_tensor.view(-1, 1, H, W)
|
||||
|
||||
assert JIT_DEPTH_NOISE_GENERATOR is not None, (
|
||||
"Depth encoder JIT model is not initialized. Call initialize_depth_noise_generator first."
|
||||
)
|
||||
model = cast(torch.jit.ScriptModule, JIT_DEPTH_NOISE_GENERATOR)
|
||||
if use_jit:
|
||||
depth_tensor[depth_tensor > max_depth] = 0.0
|
||||
encoded_depth_tensor = model(depth_tensor)
|
||||
else:
|
||||
encoded_depth_tensor, _ = model(depth_tensor)
|
||||
|
||||
return encoded_depth_tensor.view(env.num_envs, -1)
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def depth_image_noisy_delayed(
|
||||
env, sensor_cfg, visualize: bool = False
|
||||
):
|
||||
"""Return the noisy and delayed encoded depth image from the camera.
|
||||
|
||||
Requires env.delay_manager to exist. Each environment has a random delay
|
||||
sampled from [0, max_delay] at episode reset.
|
||||
|
||||
Args:
|
||||
env: The environment object (must have delay_manager attribute).
|
||||
sensor_cfg: The sensor configuration.
|
||||
visualize: Whether to visualize the depth image.
|
||||
|
||||
Returns:
|
||||
The delayed encoded depth image features.
|
||||
"""
|
||||
# Ensure encoder is initialized
|
||||
_ensure_depth_noise_generator_initialized()
|
||||
|
||||
depth_camera = env.scene.sensors[sensor_cfg.name]
|
||||
|
||||
# Get depth image tensor
|
||||
depth_tensor = depth_camera.data.output["distance_to_image_plane"].view(env.num_envs, -1)
|
||||
|
||||
# Handle NaN values by replacing them with 50.0
|
||||
depth_tensor = torch.nan_to_num(depth_tensor, nan=50.0, posinf=50.0, neginf=0.0)
|
||||
|
||||
# Reshape the tensor to [B, 1, H, W]
|
||||
H, W = depth_camera.image_shape
|
||||
depth_tensor = depth_tensor.view(-1, 1, H, W)
|
||||
|
||||
assert JIT_DEPTH_NOISE_GENERATOR is not None, (
|
||||
"Depth encoder JIT model is not initialized. Call initialize_depth_noise_generator first."
|
||||
)
|
||||
model = cast(torch.jit.ScriptModule, JIT_DEPTH_NOISE_GENERATOR)
|
||||
if use_jit:
|
||||
depth_tensor[depth_tensor > max_depth] = 0.0 # depth larger than depth max is invalid
|
||||
depth_tensor[depth_tensor < min_depth] = 0.0 # depth smaller than depth min is invalid
|
||||
encoded_depth_tensor = model(depth_tensor)
|
||||
noisy_depth_tensor = depth_tensor
|
||||
else:
|
||||
encoded_depth_tensor, noisy_depth_tensor = model(depth_tensor)
|
||||
|
||||
# Continuous visualization (single-env) with persistent windows
|
||||
if visualize and env.num_envs == 1 and not use_jit:
|
||||
camera_name = sensor_cfg.name if hasattr(sensor_cfg, "name") else "camera"
|
||||
_update_depth_window(camera_name, noisy_depth_tensor, H, W, title=f"Depth (Noisy Delayed) - {camera_name}")
|
||||
|
||||
encoded_depth_tensor_reshaped = encoded_depth_tensor.view(env.num_envs, -1)
|
||||
|
||||
# Apply delay using env's delay manager
|
||||
camera_name = sensor_cfg.name if hasattr(sensor_cfg, "name") else "depth"
|
||||
return env.delay_manager.compute_delayed_depth(encoded_depth_tensor_reshaped, camera_name)
|
||||
|
||||
|
||||
def in_goal(
|
||||
env: ManagerBasedRLEnv,
|
||||
asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"),
|
||||
distance_threshold: float = 0.5,
|
||||
goal_cmd_name: str = "robot_goal",
|
||||
) -> torch.Tensor:
|
||||
"""Check if the robot is within the goal distance threshold.
|
||||
|
||||
Args:
|
||||
env: The learning environment.
|
||||
asset_cfg: The name of the robot asset.
|
||||
distance_threshold: The distance threshold to the goal.
|
||||
goal_cmd_name: The name of the goal command.
|
||||
|
||||
Returns:
|
||||
Boolean tensor indicating whether the robot is within the goal.
|
||||
"""
|
||||
asset: Articulation = env.scene[asset_cfg.name]
|
||||
goal_cmd_generator: RobotNavigationGoalCommand = env.command_manager._terms[goal_cmd_name]
|
||||
distance_goal = torch.norm(asset.data.root_pos_w[:, :2] - goal_cmd_generator.pos_command_w[:, :2], dim=1, p=2, keepdim=True)
|
||||
return distance_goal < distance_threshold
|
||||
|
||||
|
||||
def time_normalized(env: ManagerBasedRLEnv, command_name: str = "robot_goal") -> torch.Tensor:
|
||||
"""Time normalized to the maximum episode length.
|
||||
|
||||
Args:
|
||||
env: The learning environment.
|
||||
command_name: The name of the goal command.
|
||||
|
||||
Returns:
|
||||
The normalized time (current step / max steps).
|
||||
"""
|
||||
T_max = env.max_episode_length
|
||||
if hasattr(env, "episode_length_buf"):
|
||||
t = env.episode_length_buf.unsqueeze(-1)
|
||||
else:
|
||||
t = torch.tensor([0.0]).repeat(env.num_envs, 1).to(env.device)
|
||||
return t / T_max
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Reward functions for navigation tasks.
|
||||
|
||||
These functions can be passed to :class:`isaaclab.managers.RewardTermCfg`
|
||||
to specify the reward function and its parameters.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import torch
|
||||
|
||||
from isaaclab.assets import Articulation
|
||||
from isaaclab.managers import SceneEntityCfg
|
||||
|
||||
from isaaclab_nav_task.navigation.mdp.navigation.goal_commands import RobotNavigationGoalCommand
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from isaaclab.envs import ManagerBasedRLEnv
|
||||
|
||||
|
||||
def action_rate_l1(env: "ManagerBasedRLEnv") -> torch.Tensor:
|
||||
"""Penalize the rate of change of the actions using L1 kernel."""
|
||||
return torch.sum(torch.abs(env.action_manager.action - env.action_manager.prev_action), dim=1)
|
||||
|
||||
|
||||
def lateral_movement(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
|
||||
"""Reward the agent for moving laterally using L1-Kernel.
|
||||
|
||||
Args:
|
||||
env: The learning environment.
|
||||
asset_cfg: The name of the robot asset.
|
||||
|
||||
Returns:
|
||||
Dense reward [0, +1] based on the lateral velocity.
|
||||
"""
|
||||
asset: Articulation = env.scene[asset_cfg.name]
|
||||
# compute the reward
|
||||
lateral_velocity = asset.data.root_lin_vel_b[:, 1]
|
||||
reward = torch.abs(lateral_velocity)
|
||||
return reward
|
||||
|
||||
|
||||
def rot_movement(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
|
||||
"""Reward the agent for rotating around the z-axis using an L2-Kernel.
|
||||
|
||||
Args:
|
||||
env: The learning environment.
|
||||
asset_cfg: The name of the robot asset.
|
||||
|
||||
Returns:
|
||||
Dense reward [0, +1] based on the rotational velocity.
|
||||
"""
|
||||
asset: Articulation = env.scene[asset_cfg.name]
|
||||
rot_vel_norm = torch.norm(asset.data.root_ang_vel_b, dim=1)
|
||||
return rot_vel_norm
|
||||
|
||||
|
||||
def reach_goal_xyz(
|
||||
env: ManagerBasedRLEnv,
|
||||
command_name: str,
|
||||
sigmoid: float,
|
||||
T_r: float,
|
||||
probability: float,
|
||||
flat: bool,
|
||||
ratio: bool,
|
||||
) -> torch.Tensor:
|
||||
"""Reward goal reaching with configurable sigmoid shaping.
|
||||
|
||||
Args:
|
||||
env: The learning environment.
|
||||
command_name: Name of the goal command.
|
||||
sigmoid: Sigmoid parameter for shaping.
|
||||
T_r: Time reward scaling factor.
|
||||
probability: Probability of random sampling.
|
||||
flat: Whether to only consider xy error (ignore z).
|
||||
ratio: Whether to scale by travel distance ratio.
|
||||
|
||||
Returns:
|
||||
Dense reward based on distance to goal.
|
||||
"""
|
||||
goal_cmd_generator: RobotNavigationGoalCommand = env.command_manager._terms[command_name]
|
||||
|
||||
t = env.episode_length_buf
|
||||
T = env.max_episode_length
|
||||
|
||||
if flat:
|
||||
xyz_error = torch.norm(goal_cmd_generator._get_unscaled_command()[:, :2], dim=1)
|
||||
else:
|
||||
xyz_error = torch.norm(goal_cmd_generator._get_unscaled_command(), dim=1)
|
||||
|
||||
reward = 1 / (1 + torch.square(xyz_error / sigmoid)) / T_r
|
||||
|
||||
timeup_mask = t > (T - goal_cmd_generator.required_time_at_goal_in_steps)
|
||||
random_mask = torch.rand_like(t.float()) < probability
|
||||
timeup_mask = torch.logical_or(timeup_mask, random_mask)
|
||||
|
||||
arrive_mask = goal_cmd_generator.time_at_goal > 0.0
|
||||
reward_mask = torch.logical_or(timeup_mask, arrive_mask)
|
||||
|
||||
if ratio:
|
||||
# Calculate the travel distance ratio relative to the initial goal distance
|
||||
travel_distance = torch.max(
|
||||
goal_cmd_generator.distance_traveled, goal_cmd_generator.initial_distance_to_goal
|
||||
)
|
||||
travel_distance_ratio = goal_cmd_generator.initial_distance_to_goal / (travel_distance + 1e-6)
|
||||
else:
|
||||
travel_distance_ratio = torch.ones_like(reward)
|
||||
|
||||
reward = reward * reward_mask.float() * travel_distance_ratio
|
||||
|
||||
return reward
|
||||
|
||||
|
||||
def backward_movement_penalty(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
|
||||
"""Small penalty for backward movement as a regularization term.
|
||||
|
||||
Args:
|
||||
env: The learning environment.
|
||||
asset_cfg: The name of the robot asset.
|
||||
|
||||
Returns:
|
||||
Penalty [0, +1] based on backward velocity (to be used with negative weight).
|
||||
"""
|
||||
asset: Articulation = env.scene[asset_cfg.name]
|
||||
# compute the penalty
|
||||
forward_velocity = asset.data.root_lin_vel_b[:, 0]
|
||||
# Only penalize negative forward velocity (backward movement)
|
||||
backward_velocity = torch.clamp(-forward_velocity, min=0.0, max=1.0)
|
||||
return backward_velocity
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Common functions that can be used to activate certain terminations.
|
||||
|
||||
The functions can be passed to the :class:`isaaclab.managers.TerminationTermCfg` object to enable
|
||||
the termination introduced by the function.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from isaaclab.assets import Articulation
|
||||
from isaaclab.managers import SceneEntityCfg
|
||||
from isaaclab.sensors import ContactSensor
|
||||
from isaaclab.utils.math import quat_inv, yaw_quat, quat_mul, euler_xyz_from_quat
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from isaaclab.envs import ManagerBasedRLEnv
|
||||
from isaaclab_nav_task.navigation.mdp.navigation.goal_commands import RobotNavigationGoalCommand
|
||||
|
||||
|
||||
def euler_xyz_from_quat_wrapped(quat: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""Convert quaternion to Euler angles (XYZ convention) with wrapping to [-pi, pi].
|
||||
|
||||
Args:
|
||||
quat: Quaternion tensor of shape (..., 4) in (w, x, y, z) format.
|
||||
|
||||
Returns:
|
||||
Tuple of (roll, pitch, yaw) tensors.
|
||||
"""
|
||||
roll, pitch, yaw = euler_xyz_from_quat(quat)
|
||||
# Wrap to [-pi, pi]
|
||||
roll = torch.remainder(roll + torch.pi, 2 * torch.pi) - torch.pi
|
||||
pitch = torch.remainder(pitch + torch.pi, 2 * torch.pi) - torch.pi
|
||||
yaw = torch.remainder(yaw + torch.pi, 2 * torch.pi) - torch.pi
|
||||
return roll, pitch, yaw
|
||||
|
||||
|
||||
def time_out_navigation(
|
||||
env: "ManagerBasedRLEnv",
|
||||
goal_cmd_name: str = "robot_goal",
|
||||
distance_threshold: float = 0.5
|
||||
) -> torch.Tensor:
|
||||
"""Terminate the episode when the episode length exceeds the maximum episode length.
|
||||
|
||||
This also tracks success metrics by checking if the robot reached the goal before timeout.
|
||||
"""
|
||||
from isaaclab_nav_task.navigation.mdp.navigation.goal_commands import RobotNavigationGoalCommand
|
||||
|
||||
goal_cmd_generator: RobotNavigationGoalCommand = env.command_manager._terms[goal_cmd_name]
|
||||
|
||||
termination = env.episode_length_buf >= env.max_episode_length
|
||||
|
||||
env_ids = torch.where(termination)[0]
|
||||
|
||||
distance_goal = torch.norm(goal_cmd_generator._get_unscaled_command()[:, :2], dim=1)
|
||||
|
||||
# update time at goal
|
||||
goal_cmd_generator.time_at_goal[distance_goal < distance_threshold] += 1 * env.step_dt
|
||||
|
||||
if env_ids.numel() > 0: # Check if env_ids is not empty
|
||||
success_masks = goal_cmd_generator.time_at_goal > 0.0
|
||||
value_buffer = torch.zeros_like(distance_goal) # init with 0: Fail
|
||||
value_buffer[success_masks] = 1.0 # Success
|
||||
goal_cmd_generator.goal_reached_buffer.add(value_buffer, env_ids)
|
||||
|
||||
return termination
|
||||
|
||||
|
||||
def illegal_contact_navigation(
|
||||
env: "ManagerBasedRLEnv",
|
||||
threshold: float,
|
||||
sensor_cfg: SceneEntityCfg,
|
||||
goal_cmd_name: str = "robot_goal",
|
||||
) -> torch.Tensor:
|
||||
"""Terminate when the contact force on the sensor exceeds the force threshold."""
|
||||
from isaaclab_nav_task.navigation.mdp.navigation.goal_commands import RobotNavigationGoalCommand
|
||||
|
||||
# extract the used quantities (to enable type-hinting)
|
||||
contact_sensor: ContactSensor = env.scene.sensors[sensor_cfg.name]
|
||||
net_contact_forces = contact_sensor.data.net_forces_w_history
|
||||
goal_cmd_generator: RobotNavigationGoalCommand = env.command_manager._terms[goal_cmd_name]
|
||||
|
||||
termination = torch.any(
|
||||
torch.max(torch.norm(net_contact_forces[:, :, sensor_cfg.body_ids], dim=-1), dim=1)[0] > threshold, dim=1
|
||||
)
|
||||
|
||||
env_ids = torch.where(termination)[0]
|
||||
|
||||
if env_ids.numel() > 0: # Check if env_ids is not empty
|
||||
goal_cmd_generator.goal_reached_buffer.add(torch.zeros_like(termination, dtype=torch.float), env_ids)
|
||||
|
||||
return termination
|
||||
|
||||
|
||||
def large_angle_termination_navigation(
|
||||
env: "ManagerBasedRLEnv",
|
||||
threshold: float,
|
||||
goal_cmd_name: str = "robot_goal",
|
||||
) -> torch.Tensor:
|
||||
"""Terminate when the robot exceeds a pitch or roll angle threshold."""
|
||||
from isaaclab_nav_task.navigation.mdp.navigation.goal_commands import RobotNavigationGoalCommand
|
||||
|
||||
goal_cmd_generator: RobotNavigationGoalCommand = env.command_manager._terms[goal_cmd_name]
|
||||
|
||||
# degree to rad
|
||||
threshold_rad = threshold * torch.pi / 180.0
|
||||
|
||||
robot = env.scene["robot"]
|
||||
yaw_q = yaw_quat(robot.data.root_quat_w)
|
||||
base_quat_b = quat_mul(quat_inv(yaw_q), robot.data.root_quat_w)
|
||||
robot_roll, robot_pitch, _ = euler_xyz_from_quat_wrapped(base_quat_b)
|
||||
|
||||
termination = torch.logical_or(torch.abs(robot_pitch) > threshold_rad, torch.abs(robot_roll) > threshold_rad)
|
||||
|
||||
env_ids = torch.where(termination)[0]
|
||||
|
||||
if env_ids.numel() > 0: # Check if env_ids is not empty
|
||||
goal_cmd_generator.goal_reached_buffer.add(torch.zeros_like(termination, dtype=torch.float), env_ids)
|
||||
|
||||
return termination
|
||||
|
||||
|
||||
def at_goal_navigation(
|
||||
env: "ManagerBasedRLEnv",
|
||||
asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"),
|
||||
distance_threshold: float = 0.5,
|
||||
goal_cmd_name: str = "robot_goal",
|
||||
) -> torch.Tensor:
|
||||
"""Terminate the episode when the goal is reached.
|
||||
|
||||
Args:
|
||||
env: The learning environment.
|
||||
asset_cfg: The name of the robot asset.
|
||||
distance_threshold: The distance threshold to the goal.
|
||||
goal_cmd_name: The name of the goal command term.
|
||||
|
||||
Returns:
|
||||
Boolean tensor indicating whether the goal is reached.
|
||||
"""
|
||||
from isaaclab_nav_task.navigation.mdp.navigation.goal_commands import RobotNavigationGoalCommand
|
||||
|
||||
# Extract the used quantities
|
||||
asset: Articulation = env.scene[asset_cfg.name]
|
||||
goal_cmd_generator: RobotNavigationGoalCommand = env.command_manager._terms.get(goal_cmd_name)
|
||||
|
||||
# Calculate distance to goal
|
||||
xy_error = torch.norm(goal_cmd_generator._get_unscaled_command()[:, :2], dim=1)
|
||||
|
||||
# Check conditions for termination
|
||||
at_goal = xy_error < distance_threshold
|
||||
|
||||
# already at goal
|
||||
already_at_goal = goal_cmd_generator.time_at_goal > 0.0
|
||||
at_goal = torch.logical_or(at_goal, already_at_goal)
|
||||
|
||||
# Update the time at goal in steps
|
||||
goal_cmd_generator.time_at_goal_in_steps[at_goal] += 1 # Increment if at goal
|
||||
|
||||
# Determine if termination condition is met
|
||||
termination = goal_cmd_generator.time_at_goal_in_steps > goal_cmd_generator.required_time_at_goal_in_steps
|
||||
|
||||
# Update goal reached buffer if termination condition is met
|
||||
env_ids = torch.where(termination)[0]
|
||||
if env_ids.numel() > 0: # Check if any environments have met the termination condition
|
||||
goal_cmd_generator.goal_reached_buffer.add(torch.ones_like(termination, dtype=torch.float), env_ids)
|
||||
|
||||
return termination
|
||||
|
||||
|
||||
def terrain_fall(
|
||||
env: "ManagerBasedRLEnv",
|
||||
asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"),
|
||||
fall_height_threshold: float = -1.0,
|
||||
goal_cmd_name: str = "robot_goal",
|
||||
) -> torch.Tensor:
|
||||
"""Terminate when the robot falls below a certain height threshold.
|
||||
|
||||
This termination is triggered when the robot's z-position falls below a
|
||||
specified threshold, indicating that the robot has fallen off the terrain
|
||||
or into a deep pit.
|
||||
|
||||
Args:
|
||||
env: The learning environment.
|
||||
asset_cfg: The configuration for the robot asset.
|
||||
fall_height_threshold: The z-height below which the robot is considered fallen (in meters).
|
||||
Default is -1.0m to account for pits which can be ~1.5m deep.
|
||||
goal_cmd_name: The name of the goal command term.
|
||||
|
||||
Returns:
|
||||
Boolean tensor indicating whether the robot has fallen.
|
||||
"""
|
||||
# Direct tensor access for z-coordinate (avoids intermediate variable allocation)
|
||||
termination = env.scene[asset_cfg.name].data.root_pos_w[:, 2] < fall_height_threshold
|
||||
|
||||
# Early exit if no terminations (common case - avoids torch.where overhead)
|
||||
if not termination.any():
|
||||
return termination
|
||||
|
||||
# Update goal reached buffer with failure
|
||||
goal_cmd = env.command_manager._terms.get(goal_cmd_name)
|
||||
if goal_cmd is not None:
|
||||
env_ids = termination.nonzero(as_tuple=False).squeeze(-1)
|
||||
goal_cmd.goal_reached_buffer.add(torch.zeros(env.num_envs, dtype=torch.float, device=env.device), env_ids)
|
||||
|
||||
return termination
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Custom navigation environment with observation delay support."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from isaaclab.envs import ManagerBasedRLEnv
|
||||
|
||||
from isaaclab_nav_task.navigation.mdp.delay_manager import ObservationDelayManager
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from isaaclab_nav_task.navigation.navigation_env_cfg import NavigationEnvCfg
|
||||
|
||||
|
||||
class NavigationEnv(ManagerBasedRLEnv):
|
||||
"""Navigation environment with observation delay manager.
|
||||
|
||||
This environment extends the base ManagerBasedRLEnv to add support for
|
||||
simulating sensor delays. The delay_manager is created before managers
|
||||
are loaded, ensuring observations can access it during initialization.
|
||||
"""
|
||||
|
||||
cfg: NavigationEnvCfg
|
||||
|
||||
def load_managers(self):
|
||||
"""Load managers with delay manager initialization.
|
||||
|
||||
The delay_manager is created before other managers are loaded,
|
||||
ensuring observations can access it during initialization.
|
||||
"""
|
||||
# Create the delay manager before loading other managers
|
||||
# At this point, self.num_envs and self.device are available via scene
|
||||
self.delay_manager = ObservationDelayManager(
|
||||
cfg=self.cfg.delay_cfg,
|
||||
num_envs=self.num_envs,
|
||||
device=self.device,
|
||||
)
|
||||
|
||||
# Now load all other managers
|
||||
super().load_managers()
|
||||
+445
@@ -0,0 +1,445 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Navigation environment configuration.
|
||||
|
||||
This module provides the base environment configuration for navigation tasks
|
||||
with visual perception using depth cameras.
|
||||
"""
|
||||
|
||||
import math
|
||||
import os
|
||||
from dataclasses import MISSING
|
||||
|
||||
import isaaclab.sim as sim_utils
|
||||
from isaaclab.assets import ArticulationCfg, AssetBaseCfg
|
||||
from isaaclab.envs import ManagerBasedRLEnvCfg
|
||||
from isaaclab.managers import CurriculumTermCfg as CurrTerm
|
||||
from isaaclab.managers import EventTermCfg as EventTerm
|
||||
from isaaclab.managers import ObservationGroupCfg as ObsGroup
|
||||
from isaaclab.managers import ObservationTermCfg as ObsTerm
|
||||
from isaaclab.managers import RewardTermCfg as RewTerm
|
||||
from isaaclab.managers import SceneEntityCfg
|
||||
from isaaclab.managers import TerminationTermCfg as DoneTerm
|
||||
from isaaclab.scene import InteractiveSceneCfg
|
||||
from isaaclab.sensors import ContactSensorCfg, RayCasterCfg, patterns, RayCasterCameraCfg
|
||||
from isaaclab.terrains import TerrainImporterCfg
|
||||
from isaaclab.utils import configclass
|
||||
from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR, ISAACLAB_NUCLEUS_DIR
|
||||
from isaaclab.utils.noise import AdditiveUniformNoiseCfg as Unoise
|
||||
|
||||
import isaaclab_nav_task.navigation.mdp as mdp
|
||||
from isaaclab_nav_task.navigation.mdp.custom_noise import DeltaTransformationNoiseCfg
|
||||
from isaaclab_nav_task.navigation.mdp.delay_manager import ObservationDelayManagerCfg
|
||||
from isaaclab_nav_task.navigation.assets import ISAACLAB_NAV_TASKS_ASSETS_DIR
|
||||
|
||||
##
|
||||
# Pre-defined configs
|
||||
##
|
||||
from isaaclab_nav_task.terrains import MAZE_TERRAIN_CFG # isort: skip
|
||||
|
||||
# Constants
|
||||
LEG_JOINT_NAMES = [".*HAA", ".*HFE", ".*KFE"]
|
||||
LEG_BODY_NAMES = [".*HIP", ".*THIGH", ".*SHANK"]
|
||||
WHEEL_JOINT_NAMES = [".*WHEEL"]
|
||||
WHEEL_BODY_NAMES = [".*WHEEL_L"]
|
||||
PLANNING_FREQ = 5.0 # Hz
|
||||
|
||||
##
|
||||
# Scene definition
|
||||
##
|
||||
|
||||
|
||||
@configclass
|
||||
class MySceneCfg(InteractiveSceneCfg):
|
||||
"""Configuration for the terrain scene with a legged robot."""
|
||||
|
||||
# ground terrain
|
||||
terrain = TerrainImporterCfg(
|
||||
prim_path="/World/ground",
|
||||
terrain_type="generator",
|
||||
terrain_generator=MAZE_TERRAIN_CFG,
|
||||
max_init_terrain_level=0,
|
||||
collision_group=-1,
|
||||
physics_material=sim_utils.RigidBodyMaterialCfg(
|
||||
friction_combine_mode="multiply",
|
||||
restitution_combine_mode="multiply",
|
||||
restitution=0.1,
|
||||
static_friction=1.0,
|
||||
dynamic_friction=0.8,
|
||||
compliant_contact_stiffness=5e5,
|
||||
compliant_contact_damping=300.0,
|
||||
),
|
||||
visual_material=sim_utils.MdlFileCfg(
|
||||
mdl_path=f"{ISAACLAB_NUCLEUS_DIR}/Materials/TilesMarbleSpiderWhiteBrickBondHoned/TilesMarbleSpiderWhiteBrickBondHoned.mdl",
|
||||
project_uvw=True,
|
||||
texture_scale=(0.25, 0.25),
|
||||
),
|
||||
debug_vis=False,
|
||||
)
|
||||
# robots
|
||||
robot: ArticulationCfg = MISSING
|
||||
|
||||
raycast_camera = RayCasterCameraCfg(
|
||||
prim_path="{ENV_REGEX_NS}/Robot/base",
|
||||
mesh_prim_paths=["/World/ground"],
|
||||
update_period=0,
|
||||
offset=RayCasterCameraCfg.OffsetCfg(
|
||||
pos=(0.4761, 0.0035, 0.1055), rot=(0.9848078, 0.0, 0.1736482, 0.0), convention="world" # 20 degrees
|
||||
),
|
||||
data_types=["distance_to_image_plane"],
|
||||
debug_vis=False,
|
||||
max_distance=11.0,
|
||||
pattern_cfg=patterns.PinholeCameraPatternCfg.from_ros_camera_info(
|
||||
# ZED camera parameters from ROS camera_info topic
|
||||
fx=72.7025,
|
||||
fy=72.7025,
|
||||
cx=94.4457,
|
||||
cy=62.5424,
|
||||
width=192,
|
||||
height=120,
|
||||
downsample_factor=3, # Downsample from 192x120 to 64x40
|
||||
),
|
||||
)
|
||||
|
||||
height_scanner_critic = RayCasterCfg(
|
||||
prim_path="{ENV_REGEX_NS}/Robot/base",
|
||||
offset=RayCasterCfg.OffsetCfg(pos=(0.0, 0.0, 20.0)),
|
||||
# attach_yaw_only=True,
|
||||
ray_alignment='yaw',
|
||||
pattern_cfg=patterns.GridPatternCfg(resolution=0.2, size=[10.0, 10.0]),
|
||||
debug_vis=False,
|
||||
mesh_prim_paths=["/World/ground"],
|
||||
)
|
||||
|
||||
contact_forces = ContactSensorCfg(prim_path="{ENV_REGEX_NS}/Robot/.*", history_length=3, track_air_time=True)
|
||||
# lights
|
||||
sky_light = AssetBaseCfg(
|
||||
prim_path="/World/skyLight",
|
||||
spawn=sim_utils.DomeLightCfg(
|
||||
intensity=750.0,
|
||||
texture_file=f"{ISAAC_NUCLEUS_DIR}/Materials/Textures/Skies/PolyHaven/kloofendal_43d_clear_puresky_4k.hdr",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
##
|
||||
# MDP settings
|
||||
##
|
||||
|
||||
|
||||
@configclass
|
||||
class CommandsCfg:
|
||||
"""Command specifications for the MDP."""
|
||||
|
||||
robot_goal = mdp.RobotNavigationGoalCommandCfg(
|
||||
asset_name="robot",
|
||||
# Large value to disable automatic resampling - goals only change on episode reset
|
||||
# Note: math.inf doesn't work with PyTorch's uniform_(), so we use 1e9 (~31 years)
|
||||
resampling_time_range=(1e9, 1e9),
|
||||
debug_vis=True,
|
||||
)
|
||||
|
||||
|
||||
@configclass
|
||||
class ActionsCfg:
|
||||
"""Action specifications for the MDP."""
|
||||
|
||||
velocity_command = mdp.PerceptiveNavigationSE2ActionCfg(
|
||||
asset_name="robot",
|
||||
low_level_position_action=mdp.JointPositionActionCfg(
|
||||
asset_name="robot", joint_names=[".*HAA", ".*HFE", ".*KFE"], scale=0.5, use_default_offset=True
|
||||
),
|
||||
low_level_velocity_action=mdp.JointVelocityActionCfg(
|
||||
asset_name="robot", joint_names=[".*WHEEL"], scale=5.0, use_default_offset=True
|
||||
),
|
||||
low_level_decimation=4,
|
||||
low_level_policy_file=os.path.join(
|
||||
ISAACLAB_NAV_TASKS_ASSETS_DIR, "Policies", "locomotion", "aow_d", "policy_blind_3_1.pt"
|
||||
),
|
||||
observation_group="low_level_policy",
|
||||
policy_scaling=[1.5, 1.0, 1.0],
|
||||
use_raw_actions=True,
|
||||
policy_distr_type="gaussian",
|
||||
)
|
||||
|
||||
|
||||
@configclass
|
||||
class ObservationsCfg:
|
||||
"""Observation specifications for the MDP."""
|
||||
|
||||
@configclass
|
||||
class PolicyCfg(ObsGroup):
|
||||
"""Observations for policy group."""
|
||||
|
||||
base_lin_vel = ObsTerm(
|
||||
func=mdp.base_lin_vel_delayed, noise=Unoise(n_min=-0.2, n_max=0.2)
|
||||
)
|
||||
base_ang_vel = ObsTerm(
|
||||
func=mdp.base_ang_vel_delayed, noise=Unoise(n_min=-0.1, n_max=0.1)
|
||||
)
|
||||
projected_gravity = ObsTerm(
|
||||
func=mdp.projected_gravity_delayed, noise=Unoise(n_min=-0.1, n_max=0.1)
|
||||
)
|
||||
last_action = ObsTerm(func=mdp.last_action)
|
||||
target_position = ObsTerm(
|
||||
func=mdp.generated_commands_reshaped_delayed,
|
||||
params={"command_name": "robot_goal", "flatten": True},
|
||||
noise=DeltaTransformationNoiseCfg(rotation=0.1, translation=0.5, noise_prob=0.1, remove_dist=False),
|
||||
)
|
||||
depth_image = ObsTerm(
|
||||
func=mdp.depth_image_noisy_delayed, params={"sensor_cfg": SceneEntityCfg("raycast_camera")}
|
||||
)
|
||||
|
||||
def __post_init__(self):
|
||||
self.enable_corruption = True
|
||||
self.concatenate_terms = True
|
||||
|
||||
@configclass
|
||||
class CriticCfg(ObsGroup):
|
||||
"""Observations for critic group."""
|
||||
|
||||
base_lin_vel = ObsTerm(func=mdp.base_lin_vel)
|
||||
base_ang_vel = ObsTerm(func=mdp.base_ang_vel)
|
||||
projected_gravity = ObsTerm(func=mdp.projected_gravity)
|
||||
last_action = ObsTerm(func=mdp.last_action)
|
||||
target_position = ObsTerm(
|
||||
func=mdp.generated_commands_reshaped, params={"command_name": "robot_goal", "flatten": True}
|
||||
)
|
||||
time_normalized = ObsTerm(func=mdp.time_normalized, params={"command_name": "robot_goal"})
|
||||
height_scan_critic = ObsTerm(
|
||||
func=mdp.height_scan_feat, params={"sensor_cfg": SceneEntityCfg("height_scanner_critic")}
|
||||
)
|
||||
depth_image = ObsTerm(func=mdp.depth_image_prefect, params={"sensor_cfg": SceneEntityCfg("raycast_camera")})
|
||||
|
||||
def __post_init__(self):
|
||||
self.enable_corruption = True
|
||||
self.concatenate_terms = True
|
||||
|
||||
@configclass
|
||||
class LowLevelPolicyCfg(ObsGroup):
|
||||
"""Observations for low-level policy."""
|
||||
|
||||
base_lin_vel = ObsTerm(func=mdp.base_lin_vel, noise=Unoise(n_min=-0.2, n_max=0.2))
|
||||
base_ang_vel = ObsTerm(func=mdp.base_ang_vel, noise=Unoise(n_min=-0.1, n_max=0.1))
|
||||
projected_gravity = ObsTerm(func=mdp.projected_gravity, noise=Unoise(n_min=-0.1, n_max=0.1))
|
||||
velocity_commands = ObsTerm(func=mdp.generated_actions, params={"action_name": "velocity_command"})
|
||||
joint_pos = ObsTerm(func=mdp.joint_pos_rel, noise=Unoise(n_min=-0.2, n_max=0.2))
|
||||
joint_vel = ObsTerm(func=mdp.joint_vel_rel, noise=Unoise(n_min=-1.5, n_max=1.5))
|
||||
actions = ObsTerm(func=mdp.last_low_level_action, params={"action_term": "velocity_command"})
|
||||
|
||||
def __post_init__(self):
|
||||
self.enable_corruption = True
|
||||
self.concatenate_terms = True
|
||||
|
||||
@configclass
|
||||
class MetricsCfg(ObsGroup):
|
||||
"""Observations for metrics tracking."""
|
||||
|
||||
in_goal = ObsTerm(func=mdp.in_goal)
|
||||
|
||||
def __post_init__(self):
|
||||
self.enable_corruption = False
|
||||
self.concatenate_terms = False
|
||||
|
||||
# Observation groups
|
||||
metrics: MetricsCfg = MetricsCfg()
|
||||
policy: PolicyCfg = PolicyCfg()
|
||||
critic: CriticCfg = CriticCfg()
|
||||
low_level_policy: LowLevelPolicyCfg = LowLevelPolicyCfg()
|
||||
|
||||
@configclass
|
||||
class EventCfg:
|
||||
"""Configuration for events."""
|
||||
|
||||
# Startup events
|
||||
physics_material = EventTerm(
|
||||
func=mdp.randomize_rigid_body_material,
|
||||
mode="startup",
|
||||
params={
|
||||
"asset_cfg": SceneEntityCfg("robot", body_names=".*"),
|
||||
"static_friction_range": (0.8, 1.2),
|
||||
"dynamic_friction_range": (0.7, 1.0),
|
||||
"restitution_range": (0.0, 0.1),
|
||||
"num_buckets": 64,
|
||||
},
|
||||
)
|
||||
|
||||
# Reset events
|
||||
reset_base = EventTerm(
|
||||
func=mdp.reset_root_state_uniform,
|
||||
mode="reset",
|
||||
params={
|
||||
"pose_range": {"x": (-0.0, 0.0), "y": (-0.0, 0.0), "yaw": (-math.pi, math.pi)},
|
||||
"velocity_range": {"x": (-0.0, 0.0), "y": (-0.0, 0.0), "z": (-0.0, 0.0)},
|
||||
},
|
||||
)
|
||||
|
||||
reset_robot_joints = EventTerm(
|
||||
func=mdp.reset_joints_by_scale,
|
||||
mode="reset",
|
||||
params={"position_range": (0.5, 1.5), "velocity_range": (0.0, 0.0)},
|
||||
)
|
||||
|
||||
randomize_camera_height = EventTerm(
|
||||
func=mdp.randomize_camera_height,
|
||||
mode="reset",
|
||||
params={
|
||||
"height_range": 0.1,
|
||||
"roll_angle_range": 5.0,
|
||||
"pitch_angle_range": 5.0,
|
||||
"yaw_angle_range": 5.0,
|
||||
"asset_cfg": SceneEntityCfg("raycast_camera"),
|
||||
},
|
||||
)
|
||||
|
||||
randomize_action_scale = EventTerm(
|
||||
func=mdp.randomize_action_scale,
|
||||
mode="reset",
|
||||
params={
|
||||
"scale_range_x": (0.8, 1.2),
|
||||
"scale_range_y": (0.6, 1.0),
|
||||
"scale_range_theta": (0.8, 1.2),
|
||||
"scale_range_xb": 0.1,
|
||||
"scale_range_yb": 0.2,
|
||||
"scale_range_thetab": 0.1,
|
||||
"action_term": "velocity_command",
|
||||
},
|
||||
)
|
||||
|
||||
reset_delay_buffer = EventTerm(
|
||||
func=mdp.reset_and_randomize_delay_buffer,
|
||||
mode="reset",
|
||||
)
|
||||
|
||||
randomize_low_pass_filter_alpha = EventTerm(
|
||||
func=mdp.randomize_low_pass_filter_alpha,
|
||||
mode="reset",
|
||||
params={
|
||||
"alpha_range": (0.4, 0.9),
|
||||
"action_term": "velocity_command",
|
||||
"per_dimension": True,
|
||||
"alpha_range_vx": (0.4, 0.9),
|
||||
"alpha_range_vy": (0.4, 0.9),
|
||||
"alpha_range_omega": (0.4, 0.9),
|
||||
},
|
||||
)
|
||||
|
||||
# Interval events
|
||||
push_robot = EventTerm(
|
||||
func=mdp.push_by_setting_velocity,
|
||||
mode="interval",
|
||||
interval_range_s=(0.2, 5.0),
|
||||
params={"velocity_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5)}},
|
||||
)
|
||||
|
||||
@configclass
|
||||
class RewardsCfg:
|
||||
"""Reward terms for the MDP."""
|
||||
|
||||
# Penalties
|
||||
joint_acc_l2_joint = RewTerm(
|
||||
func=mdp.joint_acc_l2,
|
||||
weight=-1e-7,
|
||||
params={"asset_cfg": SceneEntityCfg("robot", joint_names=LEG_JOINT_NAMES + WHEEL_JOINT_NAMES)},
|
||||
)
|
||||
|
||||
lateral_movement = RewTerm(func=mdp.lateral_movement, weight=-0.1)
|
||||
rot_movement = RewTerm(func=mdp.rot_movement, weight=-1e-5)
|
||||
action_rate_l1 = RewTerm(func=mdp.action_rate_l1, weight=-0.1)
|
||||
episode_termination = RewTerm(func=mdp.is_terminated, weight=-50.0)
|
||||
|
||||
# Goal rewards
|
||||
reach_goal_xy_soft = RewTerm(
|
||||
func=mdp.reach_goal_xyz,
|
||||
weight=0.25,
|
||||
params={"command_name": "robot_goal", "sigmoid": 2.5, "T_r": 1.0, "probability": 0.01, "flat": False, "ratio": False},
|
||||
)
|
||||
reach_goal_xy_tight = RewTerm(
|
||||
func=mdp.reach_goal_xyz,
|
||||
weight=1.5,
|
||||
params={"command_name": "robot_goal", "sigmoid": 0.25, "T_r": 0.1, "probability": 0.01, "flat": True, "ratio": False},
|
||||
)
|
||||
|
||||
# Backward movement penalty (disabled by default, can be enabled via curriculum)
|
||||
backward_movement_penalty = RewTerm(func=mdp.backward_movement_penalty, weight=-0.0)
|
||||
|
||||
|
||||
@configclass
|
||||
class TerminationsCfg:
|
||||
"""Termination terms for the MDP."""
|
||||
|
||||
time_out = DoneTerm(func=mdp.time_out_navigation, time_out=True, params={"distance_threshold": 0.5})
|
||||
base_contact = DoneTerm(
|
||||
func=mdp.illegal_contact_navigation,
|
||||
params={"sensor_cfg": SceneEntityCfg("contact_forces", body_names=["base", ".*HIP", ".*THIGH"]), "threshold": 1.0},
|
||||
)
|
||||
large_pitch_angle = DoneTerm(func=mdp.large_angle_termination_navigation, params={"threshold": 40})
|
||||
early_termination = DoneTerm(func=mdp.at_goal_navigation, time_out=True, params={"distance_threshold": 0.5})
|
||||
# Terrain fall termination (robot fell off terrain or into deep pit)
|
||||
terrain_fall = DoneTerm(
|
||||
func=mdp.terrain_fall,
|
||||
time_out=True,
|
||||
params={"fall_height_threshold": -2.0},
|
||||
)
|
||||
|
||||
|
||||
@configclass
|
||||
class CurriculumCfg:
|
||||
"""Curriculum terms for the MDP."""
|
||||
|
||||
disable_backward_penalty = CurrTerm(
|
||||
func=mdp.disable_backward_penalty_after_steps,
|
||||
params={"disable_after_steps": 500, "action_term": "velocity_command"},
|
||||
)
|
||||
|
||||
##
|
||||
# Environment configuration
|
||||
##
|
||||
|
||||
|
||||
@configclass
|
||||
class NavigationEnvCfg(ManagerBasedRLEnvCfg):
|
||||
"""Configuration for the navigation environment with velocity-tracking."""
|
||||
|
||||
# Scene settings
|
||||
scene: MySceneCfg = MySceneCfg(num_envs=2048, env_spacing=2.5, replicate_physics=False)
|
||||
# Basic settings
|
||||
observations: ObservationsCfg = ObservationsCfg()
|
||||
actions: ActionsCfg = ActionsCfg()
|
||||
commands: CommandsCfg = CommandsCfg()
|
||||
# MDP settings
|
||||
rewards: RewardsCfg = RewardsCfg()
|
||||
terminations: TerminationsCfg = TerminationsCfg()
|
||||
events: EventCfg = EventCfg()
|
||||
curriculum: CurriculumCfg = CurriculumCfg()
|
||||
# Observation delay configuration
|
||||
delay_cfg: ObservationDelayManagerCfg = ObservationDelayManagerCfg()
|
||||
|
||||
def __post_init__(self):
|
||||
"""Post initialization."""
|
||||
# Simulation settings: low_level_policy runs at 50Hz
|
||||
self.sim.dt = 0.005
|
||||
self.is_finite_horizon = True
|
||||
self.low_level_decimation = 4
|
||||
self.decimation = int((1 / self.sim.dt) / PLANNING_FREQ)
|
||||
self.episode_length_s = 60.0
|
||||
self.sim.render_interval = self.low_level_decimation
|
||||
self.sim.disable_contact_processing = True
|
||||
self.sim.physics_material = self.scene.terrain.physics_material
|
||||
|
||||
# Update sensor periods
|
||||
if self.scene.height_scanner_critic is not None:
|
||||
self.scene.height_scanner_critic.update_period = self.decimation * self.sim.dt
|
||||
if self.scene.raycast_camera is not None:
|
||||
self.scene.raycast_camera.update_period = self.decimation * self.sim.dt
|
||||
if self.scene.contact_forces is not None:
|
||||
self.scene.contact_forces.update_period = self.sim.dt
|
||||
self.scene.contact_forces.history_length = self.decimation
|
||||
|
||||
# Terrain curriculum settings
|
||||
self.scene.terrain.max_init_terrain_level = 10
|
||||
self.scene.terrain.terrain_generator.difficulty_range = [0.5, 1.0]
|
||||
self.scene.terrain.terrain_generator.curriculum = False
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Maze terrain generation for navigation tasks.
|
||||
|
||||
This module provides:
|
||||
- Maze terrain generation with various obstacle types
|
||||
- Stair/platform terrain for elevation training
|
||||
- Pit terrain with negative obstacles
|
||||
- Monkey-patches for Isaac Lab terrain system integration
|
||||
- Optimized mesh generation for reduced GPU memory
|
||||
|
||||
Key files:
|
||||
- terrain_constants.py: Centralized height values and thresholds
|
||||
- hf_terrains_maze.py: Terrain generation functions
|
||||
- hf_terrains_maze_cfg.py: Terrain configurations
|
||||
- patches.py: Isaac Lab integration patches
|
||||
"""
|
||||
|
||||
# Patches first (no Isaac Sim required)
|
||||
from .patches import apply_terrain_patches
|
||||
|
||||
# Constants (no Isaac Sim required)
|
||||
from .terrain_constants import (
|
||||
HEIGHTS,
|
||||
THRESHOLDS,
|
||||
PADDING,
|
||||
STAIRS,
|
||||
HeightValues,
|
||||
SamplingThresholds,
|
||||
VERTICAL_SCALE,
|
||||
HORIZONTAL_SCALE,
|
||||
CELL_SIZE,
|
||||
CELL_PIXELS,
|
||||
)
|
||||
|
||||
# Terrain generation (requires Isaac Sim)
|
||||
from .hf_terrains_maze_cfg import HfMazeTerrainCfg
|
||||
from .hf_terrains_maze import maze_terrain
|
||||
from .maze_config import MAZE_TERRAIN_CFG
|
||||
|
||||
__all__ = [
|
||||
# Patches
|
||||
"apply_terrain_patches",
|
||||
# Constants
|
||||
"HEIGHTS",
|
||||
"THRESHOLDS",
|
||||
"PADDING",
|
||||
"STAIRS",
|
||||
"HeightValues",
|
||||
"SamplingThresholds",
|
||||
"VERTICAL_SCALE",
|
||||
"HORIZONTAL_SCALE",
|
||||
"CELL_SIZE",
|
||||
"CELL_PIXELS",
|
||||
# Terrain configs
|
||||
"HfMazeTerrainCfg",
|
||||
"MAZE_TERRAIN_CFG",
|
||||
# Terrain functions
|
||||
"maze_terrain",
|
||||
]
|
||||
+714
@@ -0,0 +1,714 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Maze terrain generation for navigation tasks.
|
||||
|
||||
This module generates terrain height fields with explicit valid position masks.
|
||||
The key simplification is that terrain generation directly outputs:
|
||||
- `heights`: Actual terrain heights for rendering/physics
|
||||
- `valid_mask`: Boolean mask of valid goal/spawn positions
|
||||
|
||||
This eliminates the need for complex height-based classification in goal sampling.
|
||||
|
||||
The terrain data is stored on the config during generation, then picked up by
|
||||
the patches system and stored on TerrainImporter for access via:
|
||||
- self.env.scene.terrain._height_field_visual
|
||||
- self.env.scene.terrain._height_field_valid_mask
|
||||
- self.env.scene.terrain._height_field_platform_mask
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
from dataclasses import dataclass, field
|
||||
from scipy.ndimage import binary_dilation, rotate, shift
|
||||
from typing import TYPE_CHECKING, Tuple
|
||||
|
||||
import torch
|
||||
|
||||
from isaaclab.terrains.height_field.utils import height_field_to_mesh
|
||||
|
||||
from .terrain_constants import HEIGHTS, PADDING, STAIRS, OBSTACLES, ObstacleType
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from . import hf_terrains_maze_cfg
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Terrain Data Container
|
||||
# =============================================================================
|
||||
|
||||
@dataclass
|
||||
class TerrainData:
|
||||
"""Container for terrain height field and valid position mask.
|
||||
|
||||
Attributes:
|
||||
heights: Height field for rendering/physics (actual terrain heights).
|
||||
valid_mask: Boolean mask where True = valid for goals/spawns.
|
||||
platform_mask: Boolean mask where True = elevated platform (for curriculum).
|
||||
"""
|
||||
heights: np.ndarray
|
||||
valid_mask: np.ndarray
|
||||
platform_mask: np.ndarray = field(default_factory=lambda: np.array([]))
|
||||
|
||||
@classmethod
|
||||
def create(cls, width: int, height: int) -> "TerrainData":
|
||||
"""Create empty terrain data with ground-level heights."""
|
||||
return cls(
|
||||
heights=np.zeros((width, height), dtype=np.int16),
|
||||
valid_mask=np.ones((width, height), dtype=bool), # Start all valid
|
||||
platform_mask=np.zeros((width, height), dtype=bool),
|
||||
)
|
||||
|
||||
def set_obstacle(
|
||||
self,
|
||||
x_start: int, x_end: int,
|
||||
y_start: int, y_end: int,
|
||||
height_value: int
|
||||
):
|
||||
"""Set a region as an obstacle (invalid for goals)."""
|
||||
self.heights[x_start:x_end, y_start:y_end] = height_value
|
||||
self.valid_mask[x_start:x_end, y_start:y_end] = False
|
||||
|
||||
def set_platform(
|
||||
self,
|
||||
x_start: int, x_end: int,
|
||||
y_start: int, y_end: int,
|
||||
height_value: int
|
||||
):
|
||||
"""Set a region as a platform (valid for goals, elevated)."""
|
||||
self.heights[x_start:x_end, y_start:y_end] = height_value
|
||||
self.valid_mask[x_start:x_end, y_start:y_end] = True
|
||||
self.platform_mask[x_start:x_end, y_start:y_end] = True
|
||||
|
||||
def set_ground(self, x_start: int, x_end: int, y_start: int, y_end: int):
|
||||
"""Set a region as flat ground (valid for goals)."""
|
||||
self.heights[x_start:x_end, y_start:y_end] = HEIGHTS.GROUND
|
||||
self.valid_mask[x_start:x_end, y_start:y_end] = True
|
||||
self.platform_mask[x_start:x_end, y_start:y_end] = False
|
||||
|
||||
def apply_padding(self, padding_cells: int):
|
||||
"""Dilate invalid regions by padding cells for safety margin."""
|
||||
obstacles = ~self.valid_mask
|
||||
kernel = np.ones((2 * padding_cells + 1, 2 * padding_cells + 1), dtype=bool)
|
||||
dilated = binary_dilation(obstacles, structure=kernel)
|
||||
self.valid_mask = ~dilated
|
||||
|
||||
def create_spawn_mask(self, spawn_padding_cells: int) -> np.ndarray:
|
||||
"""Create a mask for spawn positions with larger padding than goals."""
|
||||
extra_padding = spawn_padding_cells - PADDING.GOAL_PADDING
|
||||
if extra_padding > 0:
|
||||
obstacles = ~self.valid_mask
|
||||
kernel = np.ones((2 * extra_padding + 1, 2 * extra_padding + 1), dtype=bool)
|
||||
dilated = binary_dilation(obstacles, structure=kernel)
|
||||
return ~dilated
|
||||
return self.valid_mask.copy()
|
||||
|
||||
def exclude_borders(self, border_cells: int = 2):
|
||||
"""Mark terrain borders as invalid."""
|
||||
self.valid_mask[:border_cells, :] = False
|
||||
self.valid_mask[-border_cells:, :] = False
|
||||
self.valid_mask[:, :border_cells] = False
|
||||
self.valid_mask[:, -border_cells:] = False
|
||||
|
||||
def apply_height_transition_padding(self, height_threshold: int, padding_cells: int):
|
||||
"""Mark cells near height transitions as invalid."""
|
||||
grad_x = np.abs(np.diff(self.heights, axis=0, prepend=self.heights[:1, :]))
|
||||
grad_y = np.abs(np.diff(self.heights, axis=1, prepend=self.heights[:, :1]))
|
||||
grad_x_back = np.abs(np.diff(self.heights, axis=0, append=self.heights[-1:, :]))
|
||||
grad_y_back = np.abs(np.diff(self.heights, axis=1, append=self.heights[:, -1:]))
|
||||
|
||||
max_grad = np.maximum.reduce([grad_x, grad_y, grad_x_back, grad_y_back])
|
||||
transition_mask = (max_grad >= height_threshold).astype(bool)
|
||||
|
||||
if padding_cells > 0:
|
||||
kernel = np.ones((2 * padding_cells + 1, 2 * padding_cells + 1), dtype=bool)
|
||||
transition_mask = binary_dilation(transition_mask, structure=kernel).astype(bool)
|
||||
|
||||
self.valid_mask = self.valid_mask & ~transition_mask
|
||||
|
||||
|
||||
def get_cell_bounds(
|
||||
cell_x: int, cell_y: int, cell_pixels: int, max_x: int, max_y: int
|
||||
) -> Tuple[int, int, int, int]:
|
||||
"""Get pixel bounds for a maze cell with clamping.
|
||||
|
||||
Returns:
|
||||
Tuple of (x_start, x_end, y_start, y_end).
|
||||
"""
|
||||
return (
|
||||
max(0, cell_x * cell_pixels),
|
||||
min(max_x, (cell_x + 1) * cell_pixels),
|
||||
max(0, cell_y * cell_pixels),
|
||||
min(max_y, (cell_y + 1) * cell_pixels),
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Maze Generation
|
||||
# =============================================================================
|
||||
|
||||
def generate_maze(
|
||||
rng: np.random.Generator,
|
||||
width: int,
|
||||
height: int,
|
||||
open_prob: float
|
||||
) -> np.ndarray:
|
||||
"""Generate maze using DFS with random openings.
|
||||
|
||||
Args:
|
||||
rng: Random number generator for reproducibility.
|
||||
width: Maze width in cells.
|
||||
height: Maze height in cells.
|
||||
open_prob: Probability of random wall removal.
|
||||
|
||||
Returns:
|
||||
2D array where 1=wall, 0=path.
|
||||
"""
|
||||
maze = np.ones((width, height), dtype=np.uint8)
|
||||
stack = [(0, 0)]
|
||||
maze[0, 0] = 0
|
||||
|
||||
while stack:
|
||||
x, y = stack[-1]
|
||||
neighbors = []
|
||||
for dx, dy in [(-2, 0), (2, 0), (0, -2), (0, 2)]:
|
||||
nx, ny = x + dx, y + dy
|
||||
if 0 <= nx < width and 0 <= ny < height and maze[nx, ny] == 1:
|
||||
neighbors.append((nx, ny))
|
||||
|
||||
if neighbors:
|
||||
idx = rng.integers(len(neighbors))
|
||||
nx, ny = neighbors[idx]
|
||||
maze[(x + nx) // 2, (y + ny) // 2] = 0
|
||||
maze[nx, ny] = 0
|
||||
stack.append((nx, ny))
|
||||
else:
|
||||
stack.pop()
|
||||
|
||||
# Random openings
|
||||
maze[rng.random((width, height)) < open_prob] = 0
|
||||
return maze
|
||||
|
||||
|
||||
def clear_center(maze: np.ndarray, terrain: TerrainData, cell_pixels: int):
|
||||
"""Clear the center area for spawning."""
|
||||
cx, cy = maze.shape[0] // 2, maze.shape[1] // 2
|
||||
|
||||
for dx in [-1, 0, 1]:
|
||||
for dy in [-1, 0, 1]:
|
||||
if abs(dx) + abs(dy) <= 1: # Plus shape
|
||||
nx, ny = cx + dx, cy + dy
|
||||
if 0 <= nx < maze.shape[0] and 0 <= ny < maze.shape[1]:
|
||||
maze[nx, ny] = 0
|
||||
|
||||
x_start = (cx - 1) * cell_pixels
|
||||
x_end = (cx + 2) * cell_pixels
|
||||
y_start = (cy - 1) * cell_pixels
|
||||
y_end = (cy + 2) * cell_pixels
|
||||
terrain.set_ground(x_start, x_end, y_start, y_end)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Obstacle Generators
|
||||
# =============================================================================
|
||||
|
||||
def make_pillar(
|
||||
_rng: np.random.Generator,
|
||||
size: int,
|
||||
wall_height: int,
|
||||
scale: float,
|
||||
is_pit: bool,
|
||||
thickness: int
|
||||
) -> np.ndarray:
|
||||
"""Generate a centered pillar obstacle."""
|
||||
grid = np.zeros((size, size), dtype=np.int16)
|
||||
h = int(wall_height * scale) * (-1 if is_pit else 1)
|
||||
grid[thickness:size-thickness, thickness:size-thickness] = h
|
||||
return grid
|
||||
|
||||
|
||||
def make_bar(
|
||||
rng: np.random.Generator,
|
||||
size: int,
|
||||
wall_height: int,
|
||||
scale: float,
|
||||
is_pit: bool,
|
||||
thickness: int
|
||||
) -> np.ndarray:
|
||||
"""Generate a rotated bar obstacle."""
|
||||
grid = np.zeros((size, size), dtype=np.int16)
|
||||
center = size // 2
|
||||
h = int(wall_height * scale)
|
||||
grid[center - thickness//2:center + thickness//2, :] = h
|
||||
|
||||
angle = rng.uniform(-180, 180)
|
||||
grid = rotate(grid, angle, reshape=False, order=1).astype(np.int16)
|
||||
|
||||
if is_pit:
|
||||
grid = -grid
|
||||
return grid
|
||||
|
||||
|
||||
def make_cross(
|
||||
rng: np.random.Generator,
|
||||
size: int,
|
||||
wall_height: int,
|
||||
scale: float,
|
||||
is_pit: bool,
|
||||
thickness: int
|
||||
) -> np.ndarray:
|
||||
"""Generate a cross-shaped obstacle."""
|
||||
grid = np.zeros((size, size), dtype=np.int16)
|
||||
center = size // 2
|
||||
h = int(wall_height * scale)
|
||||
grid[center - thickness//2:center + thickness//2, :] = h
|
||||
grid[:, center - thickness//2:center + thickness//2] = h
|
||||
|
||||
angle = rng.uniform(-180, 180)
|
||||
grid = rotate(grid, angle, reshape=False, order=1).astype(np.int16)
|
||||
|
||||
if is_pit:
|
||||
grid = -grid
|
||||
return grid
|
||||
|
||||
|
||||
def make_shifted_block(
|
||||
rng: np.random.Generator,
|
||||
size: int,
|
||||
wall_height: int,
|
||||
scale: float,
|
||||
is_pit: bool,
|
||||
thickness: int
|
||||
) -> np.ndarray:
|
||||
"""Generate a randomly shifted block."""
|
||||
grid = np.zeros((size, size), dtype=np.int16)
|
||||
h = int(wall_height * scale)
|
||||
grid[thickness:size-thickness, thickness:size-thickness] = h
|
||||
|
||||
room = max(0, size // 2 - thickness)
|
||||
shift_amt = (
|
||||
rng.integers(-room, room + 1),
|
||||
rng.integers(-room, room + 1)
|
||||
)
|
||||
grid = shift(grid, shift=shift_amt, cval=0).astype(np.int16)
|
||||
|
||||
if is_pit:
|
||||
grid = -grid
|
||||
return grid
|
||||
|
||||
|
||||
# Obstacle generator lookup table
|
||||
_OBSTACLE_GENERATORS = {
|
||||
ObstacleType.PILLAR: make_pillar,
|
||||
ObstacleType.BAR: make_bar,
|
||||
ObstacleType.CROSS: make_cross,
|
||||
ObstacleType.SHIFTED_BLOCK: make_shifted_block,
|
||||
}
|
||||
|
||||
|
||||
def make_random_obstacle(
|
||||
rng: np.random.Generator,
|
||||
size: int,
|
||||
wall_height: int,
|
||||
is_pit: bool | None = None,
|
||||
pillar_weight: float | None = None
|
||||
) -> np.ndarray:
|
||||
"""Generate a random obstacle type.
|
||||
|
||||
Args:
|
||||
rng: Random number generator.
|
||||
size: Size of the obstacle grid in pixels.
|
||||
wall_height: Height of walls in terrain units.
|
||||
is_pit: Force pit (True) or wall (False). None = random.
|
||||
pillar_weight: Weight for pillars (0-1). None = uniform distribution.
|
||||
"""
|
||||
scale = rng.uniform(OBSTACLES.SCALE_MIN, OBSTACLES.SCALE_MAX)
|
||||
if is_pit is None:
|
||||
is_pit = rng.random() < OBSTACLES.DEFAULT_PIT_PROB
|
||||
thickness = rng.integers(OBSTACLES.THICKNESS_MIN, OBSTACLES.THICKNESS_MAX)
|
||||
|
||||
# Select obstacle type (with optional pillar weighting)
|
||||
if pillar_weight is not None and pillar_weight > 0:
|
||||
# Weighted selection: pillar_weight for pillars, rest split evenly
|
||||
other_weight = (1.0 - pillar_weight) / (ObstacleType.NUM_TYPES - 1)
|
||||
weights = [other_weight] * ObstacleType.NUM_TYPES
|
||||
weights[ObstacleType.PILLAR] = pillar_weight
|
||||
obstacle_type = rng.choice(ObstacleType.NUM_TYPES, p=weights)
|
||||
else:
|
||||
# Uniform selection
|
||||
obstacle_type = rng.integers(ObstacleType.NUM_TYPES)
|
||||
|
||||
generator = _OBSTACLE_GENERATORS[obstacle_type]
|
||||
return generator(rng, size, wall_height, scale, is_pit, thickness)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Stair/Platform Generator
|
||||
# =============================================================================
|
||||
|
||||
class StairGenerator:
|
||||
"""Generates stair structures with platforms."""
|
||||
|
||||
LAYOUTS = [
|
||||
{"platforms": [(1, 0), (1, 1), (1, 2), (0, 1), (2, 1)],
|
||||
"stairs": [(0, 0, "n"), (2, 2, "s"), (0, 2, "s"), (2, 0, "w")]},
|
||||
{"platforms": [(0, 1), (1, 1), (2, 1)],
|
||||
"stairs": [(0, 0, "n"), (2, 2, "s"), (0, 2, "s"), (2, 0, "n")]},
|
||||
{"platforms": [(0, 1), (1, 1), (2, 1), (1, 0), (1, 2)],
|
||||
"stairs": [(0, 0, "n"), (2, 2, "s"), (0, 2, "s"), (2, 0, "n")]},
|
||||
]
|
||||
|
||||
def __init__(self, wall_height: float, vertical_scale: float):
|
||||
self.wall_height = wall_height
|
||||
self.platform_height = int(wall_height - 0.5 / vertical_scale)
|
||||
self.vertical_scale = vertical_scale
|
||||
self._make_stair_templates()
|
||||
|
||||
def _make_stair_templates(self):
|
||||
"""Create stair templates for each direction."""
|
||||
cell_px = STAIRS.SINGLE_CELL_PIXELS
|
||||
step_res = cell_px // STAIRS.NUM_STEPS
|
||||
|
||||
east = np.zeros((cell_px, cell_px), dtype=np.float32)
|
||||
for i in range(STAIRS.NUM_STEPS):
|
||||
h = STAIRS.STEP_HEIGHT_METERS * (i + 1) / self.vertical_scale
|
||||
east[i * step_res:(i + 1) * step_res, :] = h
|
||||
|
||||
self.templates = {
|
||||
"e": east,
|
||||
"n": rotate(east, 90),
|
||||
"w": rotate(east, 180),
|
||||
"s": rotate(east, 270),
|
||||
}
|
||||
|
||||
def generate(self, rng: np.random.Generator) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
|
||||
"""Generate a 3x3 stair/platform structure.
|
||||
|
||||
Args:
|
||||
rng: Random number generator.
|
||||
|
||||
Returns:
|
||||
Tuple of (heights, valid_mask, platform_mask).
|
||||
"""
|
||||
layout = self.LAYOUTS[rng.integers(len(self.LAYOUTS))]
|
||||
size = STAIRS.STAIR_GRID_SIZE * STAIRS.SINGLE_CELL_PIXELS
|
||||
cell_px = STAIRS.SINGLE_CELL_PIXELS
|
||||
|
||||
heights = np.zeros((size, size), dtype=np.float32)
|
||||
valid_mask = np.zeros((size, size), dtype=bool)
|
||||
platform_mask = np.zeros((size, size), dtype=bool)
|
||||
|
||||
for gx, gy in layout["platforms"]:
|
||||
xs, xe = gx * cell_px, (gx + 1) * cell_px
|
||||
ys, ye = gy * cell_px, (gy + 1) * cell_px
|
||||
heights[xs:xe, ys:ye] = self.platform_height
|
||||
valid_mask[xs:xe, ys:ye] = True
|
||||
platform_mask[xs:xe, ys:ye] = True
|
||||
|
||||
for gx, gy, direction in layout["stairs"]:
|
||||
xs, xe = gx * cell_px, (gx + 1) * cell_px
|
||||
ys, ye = gy * cell_px, (gy + 1) * cell_px
|
||||
heights[xs:xe, ys:ye] = self.templates[direction]
|
||||
|
||||
return heights, valid_mask, platform_mask
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Main Terrain Generation
|
||||
# =============================================================================
|
||||
|
||||
def _get_rng(cfg: "hf_terrains_maze_cfg.HfMazeTerrainCfg") -> np.random.Generator:
|
||||
"""Get RNG from config or create a new one."""
|
||||
if cfg.rng is not None:
|
||||
return cfg.rng
|
||||
# Fallback: create unseeded RNG (non-reproducible)
|
||||
return np.random.default_rng()
|
||||
|
||||
|
||||
@height_field_to_mesh
|
||||
def maze_terrain(difficulty: float, cfg: "hf_terrains_maze_cfg.HfMazeTerrainCfg") -> np.ndarray:
|
||||
"""Generate maze terrain with obstacles and valid position mask.
|
||||
|
||||
Args:
|
||||
difficulty: Terrain difficulty (0-1).
|
||||
cfg: Terrain configuration.
|
||||
|
||||
Returns:
|
||||
Height field for mesh generation.
|
||||
"""
|
||||
rng = _get_rng(cfg)
|
||||
|
||||
# Setup dimensions
|
||||
cell_pixels = int(cfg.cell_size / cfg.horizontal_scale)
|
||||
wall_height = int(cfg.wall_height / cfg.vertical_scale)
|
||||
terrain_w = int(cfg.size[0] / cfg.horizontal_scale)
|
||||
terrain_h = int(cfg.size[1] / cfg.horizontal_scale)
|
||||
|
||||
terrain = TerrainData.create(terrain_w, terrain_h)
|
||||
stair_gen = StairGenerator(wall_height, cfg.vertical_scale)
|
||||
|
||||
# Generate base pattern
|
||||
if cfg.non_maze_terrain:
|
||||
maze = np.zeros(cfg.grid_size, dtype=np.uint8)
|
||||
obstacle_prob = difficulty * OBSTACLES.NON_MAZE_DENSITY
|
||||
maze[rng.random(cfg.grid_size) < obstacle_prob] = 1
|
||||
else:
|
||||
maze = generate_maze(rng, cfg.grid_size[0], cfg.grid_size[1], 1 - difficulty)
|
||||
|
||||
clear_center(maze, terrain, cell_pixels)
|
||||
|
||||
# Generate terrain features based on type
|
||||
if cfg.dynamic_obstacles:
|
||||
_add_pits(rng, terrain, cfg, difficulty, wall_height, cell_pixels)
|
||||
elif cfg.stairs:
|
||||
_add_stairs(rng, terrain, cfg, difficulty, wall_height, cell_pixels, stair_gen)
|
||||
else:
|
||||
_add_walls(rng, maze, terrain, cfg, wall_height, cell_pixels)
|
||||
|
||||
clear_center(maze, terrain, cell_pixels)
|
||||
|
||||
# Apply height transition padding for stair terrain
|
||||
if cfg.stairs:
|
||||
terrain.apply_height_transition_padding(
|
||||
height_threshold=PADDING.HEIGHT_TRANSITION_THRESHOLD,
|
||||
padding_cells=PADDING.HEIGHT_TRANSITION_PADDING
|
||||
)
|
||||
|
||||
# Apply safety padding and border exclusion
|
||||
terrain.apply_padding(PADDING.GOAL_PADDING)
|
||||
terrain.exclude_borders(PADDING.BORDER_CELLS)
|
||||
|
||||
# Create spawn mask with larger padding
|
||||
spawn_mask = terrain.create_spawn_mask(PADDING.SPAWN_PADDING)
|
||||
spawn_mask[:PADDING.BORDER_CELLS, :] = False
|
||||
spawn_mask[-PADDING.BORDER_CELLS:, :] = False
|
||||
spawn_mask[:, :PADDING.BORDER_CELLS] = False
|
||||
spawn_mask[:, -PADDING.BORDER_CELLS:] = False
|
||||
|
||||
# Store data on cfg for patches to pick up
|
||||
if cfg.add_goal:
|
||||
cfg.height_field_visual = torch.from_numpy(terrain.heights.copy()).unsqueeze(0)
|
||||
cfg.height_field_valid_mask = torch.from_numpy(terrain.valid_mask.copy()).unsqueeze(0)
|
||||
cfg.height_field_platform_mask = torch.from_numpy(terrain.platform_mask.copy()).unsqueeze(0)
|
||||
cfg.height_field_spawn_mask = torch.from_numpy(spawn_mask.copy()).unsqueeze(0)
|
||||
|
||||
return terrain.heights
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Terrain Type Generators
|
||||
# =============================================================================
|
||||
|
||||
def _add_walls(
|
||||
rng: np.random.Generator,
|
||||
maze: np.ndarray,
|
||||
terrain: TerrainData,
|
||||
cfg,
|
||||
wall_height: int,
|
||||
cell_pixels: int
|
||||
):
|
||||
"""Add wall obstacles to terrain based on maze pattern."""
|
||||
# Use pillar weighting for non-maze terrain (more thin pillars)
|
||||
pillar_weight = OBSTACLES.NON_MAZE_PILLAR_WEIGHT if cfg.non_maze_terrain else None
|
||||
|
||||
for x in range(cfg.grid_size[0]):
|
||||
for y in range(cfg.grid_size[1]):
|
||||
if maze[x, y] != 1:
|
||||
continue
|
||||
|
||||
xs, xe, ys, ye = get_cell_bounds(
|
||||
x, y, cell_pixels, terrain.heights.shape[0], terrain.heights.shape[1]
|
||||
)
|
||||
|
||||
if cfg.randomize_wall and rng.random() < cfg.random_wall_ratio:
|
||||
obs = make_random_obstacle(rng, cell_pixels, wall_height, pillar_weight=pillar_weight)
|
||||
terrain.heights[xs:xe, ys:ye] = obs[:xe - xs, :ye - ys]
|
||||
terrain.valid_mask[xs:xe, ys:ye] = False
|
||||
else:
|
||||
h = int(wall_height * rng.uniform(OBSTACLES.SCALE_MIN, OBSTACLES.SCALE_MAX))
|
||||
terrain.set_obstacle(xs, xe, ys, ye, h)
|
||||
|
||||
|
||||
def _add_stairs(
|
||||
rng: np.random.Generator,
|
||||
terrain: TerrainData,
|
||||
cfg,
|
||||
difficulty: float,
|
||||
wall_height: int,
|
||||
cell_pixels: int,
|
||||
stair_gen: StairGenerator
|
||||
):
|
||||
"""Add stair/platform structures to terrain."""
|
||||
grid_w, grid_h = cfg.grid_size
|
||||
grid_middle = grid_w // 2
|
||||
excluded = set(range(grid_middle - 1, grid_middle + 1))
|
||||
|
||||
# Compute stair placement locations (avoid center and edges)
|
||||
# Stairs are 3x3, so max position is grid_size - 4 to fit with margin
|
||||
stair_margin = 1
|
||||
max_x = grid_w - STAIRS.STAIR_GRID_SIZE - stair_margin
|
||||
max_y = grid_h - STAIRS.STAIR_GRID_SIZE - stair_margin
|
||||
num_locations = 6
|
||||
x_locs = set(np.round(np.linspace(stair_margin, max_x, num_locations)).astype(int)) - excluded
|
||||
y_locs = set(np.round(np.linspace(stair_margin, max_y, num_locations)).astype(int)) - excluded
|
||||
|
||||
processed = set()
|
||||
stair_size = STAIRS.STAIR_GRID_SIZE * STAIRS.SINGLE_CELL_PIXELS
|
||||
stair_prob = difficulty * OBSTACLES.STAIRS_PLACEMENT_PROB
|
||||
obstacle_prob = difficulty * OBSTACLES.STAIRS_OBSTACLE_DENSITY
|
||||
|
||||
for x in range(grid_w):
|
||||
for y in range(grid_h):
|
||||
if (x, y) in processed:
|
||||
continue
|
||||
|
||||
# Try placing stair structure at valid locations
|
||||
if x in x_locs and y in y_locs and rng.random() < stair_prob:
|
||||
heights, valid, platform = stair_gen.generate(rng)
|
||||
|
||||
xs = x * cell_pixels
|
||||
xe = min(terrain.heights.shape[0], xs + stair_size)
|
||||
ys = y * cell_pixels
|
||||
ye = min(terrain.heights.shape[1], ys + stair_size)
|
||||
|
||||
sx, sy = xe - xs, ye - ys
|
||||
terrain.heights[xs:xe, ys:ye] = heights[:sx, :sy]
|
||||
terrain.valid_mask[xs:xe, ys:ye] = valid[:sx, :sy]
|
||||
terrain.platform_mask[xs:xe, ys:ye] = platform[:sx, :sy]
|
||||
|
||||
# Mark 3x3 area as processed
|
||||
for dx in range(3):
|
||||
for dy in range(3):
|
||||
processed.add((x + dx, y + dy))
|
||||
|
||||
elif rng.random() < obstacle_prob:
|
||||
xs, xe, ys, ye = get_cell_bounds(
|
||||
x, y, cell_pixels, terrain.heights.shape[0], terrain.heights.shape[1]
|
||||
)
|
||||
# Check if area is clear before placing
|
||||
if terrain.valid_mask[xs + 1:xe - 1, ys + 1:ye - 1].all():
|
||||
obs = make_random_obstacle(rng, cell_pixels, wall_height)
|
||||
terrain.heights[xs:xe, ys:ye] = obs[:xe - xs, :ye - ys]
|
||||
terrain.valid_mask[xs:xe, ys:ye] = False
|
||||
|
||||
|
||||
def _add_pits(
|
||||
rng: np.random.Generator,
|
||||
terrain: TerrainData,
|
||||
cfg,
|
||||
difficulty: float,
|
||||
wall_height: int,
|
||||
cell_pixels: int
|
||||
):
|
||||
"""Add pit/trough obstacles to terrain.
|
||||
|
||||
Layout:
|
||||
- Two horizontal pit trenches with random bridges for crossing
|
||||
- Random obstacles (mostly pits) scattered in the middle area
|
||||
"""
|
||||
grid_w, grid_h = cfg.grid_size
|
||||
|
||||
# Pit trench rows (near top and bottom)
|
||||
trench_offset = OBSTACLES.PITS_TRENCH_ROW_OFFSET
|
||||
pit_rows = {trench_offset, grid_h - trench_offset - 1}
|
||||
|
||||
# Generate bridge positions for crossing pit trenches
|
||||
bridges = _generate_bridges(rng, grid_w)
|
||||
|
||||
# Add pit trenches (negative height = troughs)
|
||||
for pit_y in pit_rows:
|
||||
for x in range(grid_w):
|
||||
if x in bridges:
|
||||
continue
|
||||
xs, xe, ys, ye = get_cell_bounds(
|
||||
x, pit_y, cell_pixels, terrain.heights.shape[0], terrain.heights.shape[1]
|
||||
)
|
||||
terrain.set_obstacle(xs, xe, ys, ye, -wall_height)
|
||||
|
||||
# Add random obstacles in middle area (between pit trenches)
|
||||
_add_middle_obstacles(rng, terrain, cfg, difficulty, wall_height, cell_pixels, pit_rows)
|
||||
|
||||
|
||||
def _generate_bridges(rng: np.random.Generator, grid_width: int) -> set:
|
||||
"""Generate bridge positions across pit rows.
|
||||
|
||||
Returns set of x-coordinates where bridges (gaps in pits) are placed.
|
||||
Bridges are 2 cells wide for easier robot crossing.
|
||||
"""
|
||||
num_bridges = rng.integers(OBSTACLES.BRIDGE_COUNT_MIN, OBSTACLES.BRIDGE_COUNT_MAX)
|
||||
margin = OBSTACLES.PITS_EDGE_MARGIN
|
||||
available = list(range(margin, grid_width - margin))
|
||||
rng.shuffle(available)
|
||||
|
||||
bridges = set()
|
||||
for i in range(min(num_bridges, len(available))):
|
||||
pos = available[i]
|
||||
bridges.add(pos)
|
||||
# Make bridges 2 cells wide
|
||||
if pos + 1 < grid_width - margin:
|
||||
bridges.add(pos + 1)
|
||||
|
||||
return bridges
|
||||
|
||||
|
||||
def _add_middle_obstacles(
|
||||
rng: np.random.Generator,
|
||||
terrain: TerrainData,
|
||||
cfg,
|
||||
difficulty: float,
|
||||
wall_height: int,
|
||||
cell_pixels: int,
|
||||
pit_rows: set
|
||||
):
|
||||
"""Add random obstacles in the middle area between pit rows."""
|
||||
grid_w, grid_h = cfg.grid_size
|
||||
obstacle_prob = difficulty * OBSTACLES.PITS_DENSITY
|
||||
|
||||
# Compute valid placement bounds (avoid edges and pit rows)
|
||||
margin = OBSTACLES.PITS_EDGE_MARGIN
|
||||
trench_offset = OBSTACLES.PITS_TRENCH_ROW_OFFSET
|
||||
|
||||
x_range = range(margin, grid_w - margin)
|
||||
# Middle area: between the two pit trenches, with 1 cell buffer
|
||||
y_range = range(trench_offset + 1, grid_h - trench_offset - 1)
|
||||
|
||||
# Iterate only over valid cells (more efficient)
|
||||
for x in x_range:
|
||||
for y in y_range:
|
||||
if y in pit_rows:
|
||||
continue
|
||||
|
||||
if rng.random() < obstacle_prob:
|
||||
xs, xe, ys, ye = get_cell_bounds(
|
||||
x, y, cell_pixels, terrain.heights.shape[0], terrain.heights.shape[1]
|
||||
)
|
||||
obs = _generate_pit_obstacle(rng, cell_pixels, wall_height)
|
||||
terrain.heights[xs:xe, ys:ye] = obs[:xe - xs, :ye - ys]
|
||||
terrain.valid_mask[xs:xe, ys:ye] = False
|
||||
|
||||
|
||||
def _generate_pit_obstacle(
|
||||
rng: np.random.Generator,
|
||||
cell_pixels: int,
|
||||
wall_height: int
|
||||
) -> np.ndarray:
|
||||
"""Generate an obstacle for pit terrain with high pit probability.
|
||||
|
||||
Distribution:
|
||||
- 60% bars (75% negative/pits) -> 45% pit bars
|
||||
- 40% random shapes (50% negative/pits) -> 20% pit shapes
|
||||
- Total: ~65% negative obstacles
|
||||
"""
|
||||
if rng.random() < OBSTACLES.PITS_BAR_RATIO:
|
||||
# Bar obstacle with high pit probability
|
||||
is_pit = rng.random() < OBSTACLES.PITS_BAR_PIT_PROB
|
||||
scale = rng.uniform(OBSTACLES.SCALE_MIN, OBSTACLES.SCALE_MAX)
|
||||
thickness = rng.integers(OBSTACLES.THICKNESS_MIN, OBSTACLES.THICKNESS_MAX)
|
||||
return make_bar(rng, cell_pixels, wall_height, scale, is_pit, thickness)
|
||||
else:
|
||||
# Random obstacle type (pillar, cross, block) with moderate pit probability
|
||||
is_pit = rng.random() < OBSTACLES.PITS_RANDOM_PIT_PROB
|
||||
return make_random_obstacle(rng, cell_pixels, wall_height, is_pit=is_pit)
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Configuration for maze height field terrains."""
|
||||
|
||||
from dataclasses import MISSING
|
||||
from typing import Any, Optional
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from isaaclab.utils import configclass
|
||||
from isaaclab.terrains.height_field.hf_terrains_cfg import HfTerrainBaseCfg
|
||||
|
||||
from . import hf_terrains_maze
|
||||
|
||||
|
||||
@configclass
|
||||
class HfMazeTerrainCfg(HfTerrainBaseCfg):
|
||||
"""Configuration for a maze height field terrain.
|
||||
|
||||
This terrain generates a procedural maze with configurable wall structures,
|
||||
obstacles, and optional stairs. The maze can be used for navigation tasks
|
||||
with various difficulty levels.
|
||||
|
||||
Height Field Data (set during terrain generation):
|
||||
- height_field_visual: Heights for Z-lookup (num_terrains, W, H)
|
||||
- height_field_valid_mask: Valid goal positions with safety padding
|
||||
- height_field_platform_mask: Platform positions for curriculum
|
||||
- height_field_spawn_mask: Valid spawn positions with larger padding
|
||||
"""
|
||||
|
||||
function = hf_terrains_maze.maze_terrain
|
||||
|
||||
# =========================================================================
|
||||
# Height Field Storage (populated during terrain generation)
|
||||
# =========================================================================
|
||||
|
||||
height_field_visual: torch.Tensor = None
|
||||
"""Height field for Z-lookup (actual terrain heights)."""
|
||||
|
||||
height_field_valid_mask: torch.Tensor = None
|
||||
"""Boolean mask of valid goal positions (padded with GOAL_PADDING)."""
|
||||
|
||||
height_field_platform_mask: torch.Tensor = None
|
||||
"""Boolean mask of platform positions for curriculum learning."""
|
||||
|
||||
height_field_spawn_mask: torch.Tensor = None
|
||||
"""Boolean mask of valid spawn positions (larger padding for robot body)."""
|
||||
|
||||
# =========================================================================
|
||||
# Maze Generation Parameters
|
||||
# =========================================================================
|
||||
|
||||
maze: bool = True
|
||||
"""Flag indicating this is a maze terrain."""
|
||||
|
||||
open_probability: float = None
|
||||
"""Probability of a cell being open in the maze."""
|
||||
|
||||
grid_size: tuple[int, int] = (15, 15)
|
||||
"""Size of the maze grid (number of cells in width and height)."""
|
||||
|
||||
cell_size: float = 2.0
|
||||
"""Size of each cell in the maze grid (in meters)."""
|
||||
|
||||
wall_height: float = 1.5
|
||||
"""Height of the walls (in meters). Defaults to 1.5."""
|
||||
|
||||
# =========================================================================
|
||||
# Terrain Features
|
||||
# =========================================================================
|
||||
|
||||
add_goal: Any = MISSING
|
||||
"""Enable goal sampling data generation."""
|
||||
|
||||
add_noise_to_flat: Any = MISSING
|
||||
"""Add noise to flat areas of the maze."""
|
||||
|
||||
randomize_wall: Any = MISSING
|
||||
"""Use randomized obstacle shapes instead of full walls."""
|
||||
|
||||
random_wall_ratio: float = 0.5
|
||||
"""Mix ratio between randomized and standard walls. Defaults to 0.5."""
|
||||
|
||||
non_maze_terrain: bool = False
|
||||
"""Use non-maze terrain with random obstacles. Defaults to False."""
|
||||
|
||||
stairs: bool = False
|
||||
"""Add stairs to empty map. Defaults to False."""
|
||||
|
||||
add_stairs_to_maze: bool = False
|
||||
"""Add stairs to the maze. Defaults to False."""
|
||||
|
||||
dynamic_obstacles: bool = False
|
||||
"""Enable pit/trough obstacles. Defaults to False."""
|
||||
|
||||
# =========================================================================
|
||||
# Random Number Generator
|
||||
# =========================================================================
|
||||
|
||||
rng: Optional[np.random.Generator] = None
|
||||
"""Random number generator for reproducible terrain generation.
|
||||
|
||||
Set by the terrain generator (patches.py) before calling the terrain function.
|
||||
If None, will create a new unseeded generator (non-reproducible).
|
||||
"""
|
||||
|
||||
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Configuration for maze terrains."""
|
||||
|
||||
from isaaclab.terrains.terrain_generator_cfg import TerrainGeneratorCfg
|
||||
|
||||
from .hf_terrains_maze_cfg import HfMazeTerrainCfg
|
||||
|
||||
MAZE_TERRAIN_CFG = TerrainGeneratorCfg(
|
||||
size=(30.0, 30.0),
|
||||
border_width=30.0, # Border around the entire terrain grid (not per-tile)
|
||||
num_rows=6,
|
||||
num_cols=30,
|
||||
horizontal_scale=0.1,
|
||||
vertical_scale=0.005,
|
||||
slope_threshold=0.75,
|
||||
use_cache=False,
|
||||
curriculum=False,
|
||||
difficulty_range=(0.5, 1.0),
|
||||
sub_terrains={
|
||||
"maze": HfMazeTerrainCfg(
|
||||
proportion=0.3,
|
||||
open_probability=0.9,
|
||||
grid_size=(15, 15),
|
||||
cell_size=2.0,
|
||||
add_noise_to_flat=False,
|
||||
add_goal=True,
|
||||
randomize_wall=True,
|
||||
random_wall_ratio=0.5,
|
||||
add_stairs_to_maze=True,
|
||||
),
|
||||
"non_maze": HfMazeTerrainCfg(
|
||||
proportion=0.2,
|
||||
open_probability=0.9,
|
||||
grid_size=(15, 15),
|
||||
cell_size=2.0,
|
||||
add_noise_to_flat=False,
|
||||
add_goal=True,
|
||||
randomize_wall=True,
|
||||
random_wall_ratio=1.0,
|
||||
non_maze_terrain=True,
|
||||
),
|
||||
"stairs": HfMazeTerrainCfg(
|
||||
proportion=0.3,
|
||||
open_probability=0.9,
|
||||
grid_size=(15, 15),
|
||||
cell_size=2.0,
|
||||
add_noise_to_flat=False,
|
||||
add_goal=True,
|
||||
randomize_wall=False,
|
||||
random_wall_ratio=1.0,
|
||||
non_maze_terrain=False,
|
||||
stairs=True,
|
||||
),
|
||||
"pits": HfMazeTerrainCfg(
|
||||
proportion=0.2,
|
||||
open_probability=0.9,
|
||||
grid_size=(15, 15),
|
||||
cell_size=2.0,
|
||||
add_noise_to_flat=False,
|
||||
add_goal=True,
|
||||
randomize_wall=True,
|
||||
random_wall_ratio=1.0,
|
||||
non_maze_terrain=True,
|
||||
dynamic_obstacles=True, # Enables pit/trough generation
|
||||
),
|
||||
},
|
||||
)
|
||||
"""Maze terrain configuration for navigation tasks."""
|
||||
+550
@@ -0,0 +1,550 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Monkey-patches for Isaac Lab terrain system to support navigation tasks.
|
||||
|
||||
This module patches TerrainGenerator and TerrainImporter to:
|
||||
1. Store height field data for goal/spawn sampling
|
||||
2. Use optimized mesh generation to reduce GPU memory
|
||||
|
||||
The patches add these attributes to TerrainImporter (accessed via env.scene.terrain):
|
||||
- _height_field_visual: Heights for Z-lookup (num_terrains, W, H)
|
||||
- _height_field_valid_mask: Valid goal positions with safety padding
|
||||
- _height_field_platform_mask: Platform positions for curriculum
|
||||
- _height_field_spawn_mask: Valid spawn positions with larger padding
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import trimesh
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from isaaclab.terrains.terrain_generator import TerrainGenerator
|
||||
from isaaclab.terrains.terrain_importer import TerrainImporter
|
||||
|
||||
# Flag to track if patches have been applied
|
||||
_patches_applied = False
|
||||
|
||||
# Shared storage for passing height field data from TerrainGenerator to TerrainImporter
|
||||
# Works because TerrainImporter creates TerrainGenerator synchronously in __init__
|
||||
_height_field_storage = {
|
||||
"height_field_visual": None,
|
||||
"height_field_valid_mask": None,
|
||||
"height_field_platform_mask": None,
|
||||
"height_field_spawn_mask": None,
|
||||
}
|
||||
|
||||
|
||||
def apply_terrain_patches():
|
||||
"""Apply monkey-patches to Isaac Lab terrain classes.
|
||||
|
||||
Patches applied:
|
||||
1. height_field_to_mesh - optimized mesh generation (reduces GPU memory)
|
||||
2. TerrainGenerator - collects height field data for goal sampling
|
||||
3. TerrainImporter - stores height field data as attributes
|
||||
4. PinholeCameraPatternCfg - adds from_ros_camera_info convenience method
|
||||
|
||||
Safe to call multiple times - patches are only applied once.
|
||||
"""
|
||||
global _patches_applied
|
||||
if _patches_applied:
|
||||
return
|
||||
|
||||
_patch_height_field_to_mesh()
|
||||
_patch_terrain_generator()
|
||||
_patch_terrain_importer()
|
||||
_patch_pinhole_camera_pattern_cfg()
|
||||
|
||||
_patches_applied = True
|
||||
|
||||
|
||||
def _convert_height_field_to_mesh_with_optimization_dynamic(
|
||||
height_field: np.ndarray, horizontal_scale: float, vertical_scale: float, block_size: int = 20
|
||||
) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Convert a height-field array to a triangle mesh, optimizing large flat ground blocks (20x20, 10x10, 5x5).
|
||||
|
||||
This function optimizes mesh generation by detecting flat regions and simplifying them
|
||||
to just 2 triangles instead of generating full detail. It uses a hierarchical approach:
|
||||
- 20x20 blocks are checked first
|
||||
- Non-flat blocks are subdivided into 10x10, then 5x5
|
||||
- Only 5x5 or smaller blocks with height variation get full detail
|
||||
|
||||
This can dramatically reduce vertex count for terrains with large flat areas,
|
||||
significantly reducing GPU memory usage during simulation.
|
||||
|
||||
Args:
|
||||
height_field: The input height-field array.
|
||||
horizontal_scale: The discretization of the terrain along the x and y axis.
|
||||
vertical_scale: The discretization of the terrain along the z axis.
|
||||
block_size: Initial block size for optimization (default 20).
|
||||
|
||||
Returns:
|
||||
The vertices and triangles of the mesh:
|
||||
- **vertices** (np.ndarray(float)): Array of shape (num_vertices, 3).
|
||||
- **triangles** (np.ndarray(int)): Array of shape (num_triangles, 3).
|
||||
"""
|
||||
num_rows, num_cols = height_field.shape
|
||||
vertices = []
|
||||
triangles = []
|
||||
vertex_count = 0
|
||||
|
||||
def process_block(i, j, block_size):
|
||||
"""Process a block and decide whether to simplify or subdivide into smaller blocks."""
|
||||
nonlocal vertex_count
|
||||
|
||||
# Skip if starting position is at or beyond the terrain bounds
|
||||
if i >= num_rows or j >= num_cols:
|
||||
return
|
||||
|
||||
# Determine block dimensions within bounds of the height field
|
||||
block_end_row = min(i + block_size + 1, num_rows) # +1 to handle the right and bottom edges
|
||||
block_end_col = min(j + block_size + 1, num_cols) # +1 to handle the right and bottom edges
|
||||
|
||||
# Extract the block of height data
|
||||
block = height_field[i:block_end_row, j:block_end_col]
|
||||
|
||||
# Skip empty or single-element blocks (can't form triangles)
|
||||
if block.size == 0 or block.shape[0] < 2 or block.shape[1] < 2:
|
||||
return
|
||||
|
||||
# Check if the entire block is flat (all heights are the same)
|
||||
if np.all(block == block[0, 0]):
|
||||
# Simplify the block by using two large triangles for the whole flat region
|
||||
v0 = [i * horizontal_scale, j * horizontal_scale, block[0, 0] * vertical_scale]
|
||||
v1 = [block_end_row * horizontal_scale, j * horizontal_scale, block[0, 0] * vertical_scale]
|
||||
v2 = [i * horizontal_scale, block_end_col * horizontal_scale, block[0, 0] * vertical_scale]
|
||||
v3 = [block_end_row * horizontal_scale, block_end_col * horizontal_scale, block[0, 0] * vertical_scale]
|
||||
|
||||
# Add the vertices for the large triangles
|
||||
vertices.extend([v0, v1, v2, v3])
|
||||
|
||||
# Add the two triangles for the block
|
||||
triangles.append([vertex_count, vertex_count + 1, vertex_count + 2])
|
||||
triangles.append([vertex_count + 1, vertex_count + 3, vertex_count + 2])
|
||||
|
||||
vertex_count += 4
|
||||
else:
|
||||
# If block is not flat and the block size is larger than 5x5, subdivide into smaller blocks
|
||||
if block_size > 5:
|
||||
half_size = block_size // 2
|
||||
# Process each of the four quadrants of the block
|
||||
process_block(i, j, half_size)
|
||||
process_block(i + half_size, j, half_size)
|
||||
process_block(i, j + half_size, half_size)
|
||||
process_block(i + half_size, j + half_size, half_size)
|
||||
else:
|
||||
# If block size is 5x5 or smaller, generate detailed triangles for each grid point
|
||||
for x in range(block_end_row - i):
|
||||
for y in range(block_end_col - j):
|
||||
# Get the height at this point
|
||||
z = block[x, y] * vertical_scale
|
||||
v = [(i + x) * horizontal_scale, (j + y) * horizontal_scale, z]
|
||||
vertices.append(v)
|
||||
|
||||
# Now create triangles for all internal points including the last row and last column
|
||||
for x in range(block_end_row - i - 1): # Handle rows, including the last row
|
||||
for y in range(block_end_col - j - 1): # Handle columns, including the last column
|
||||
ind0 = vertex_count + x * (block_end_col - j) + y
|
||||
ind1 = ind0 + 1
|
||||
ind2 = ind0 + (block_end_col - j)
|
||||
ind3 = ind2 + 1
|
||||
|
||||
# Create two triangles for this grid cell
|
||||
triangles.append([ind0, ind3, ind1])
|
||||
triangles.append([ind0, ind2, ind3])
|
||||
|
||||
vertex_count += (block_end_row - i) * (block_end_col - j)
|
||||
|
||||
# Start by processing blocks with the initial block size (20x20)
|
||||
for i in range(0, num_rows, block_size):
|
||||
for j in range(0, num_cols, block_size):
|
||||
process_block(i, j, block_size)
|
||||
|
||||
vertices = np.array(vertices)
|
||||
triangles = np.array(triangles)
|
||||
|
||||
# Return vertices and triangles arrays
|
||||
return vertices, triangles
|
||||
|
||||
|
||||
def _patch_height_field_to_mesh():
|
||||
"""Patch height_field_to_mesh decorator to use optimized mesh generation.
|
||||
|
||||
This patch replaces the mesh generation in the height_field_to_mesh decorator
|
||||
with an optimized version that reduces vertex count for flat terrain regions,
|
||||
significantly reducing GPU memory usage during simulation with many environments.
|
||||
"""
|
||||
import copy
|
||||
import functools
|
||||
from isaaclab.terrains.height_field import utils as hf_utils
|
||||
|
||||
def _patched_height_field_to_mesh(func):
|
||||
"""Patched decorator that uses optimized mesh generation."""
|
||||
@functools.wraps(func)
|
||||
def wrapper(difficulty: float, cfg):
|
||||
# check valid border width
|
||||
if cfg.border_width > 0 and cfg.border_width < cfg.horizontal_scale:
|
||||
raise ValueError(
|
||||
f"The border width ({cfg.border_width}) must be greater than or equal to the"
|
||||
f" horizontal scale ({cfg.horizontal_scale})."
|
||||
)
|
||||
# allocate buffer for height field (with border)
|
||||
width_pixels = int(cfg.size[0] / cfg.horizontal_scale) + 1
|
||||
length_pixels = int(cfg.size[1] / cfg.horizontal_scale) + 1
|
||||
border_pixels = int(cfg.border_width / cfg.horizontal_scale) + 1
|
||||
heights = np.zeros((width_pixels, length_pixels), dtype=np.int16)
|
||||
# override size of the terrain to account for the border
|
||||
sub_terrain_size = [width_pixels - 2 * border_pixels, length_pixels - 2 * border_pixels]
|
||||
sub_terrain_size = [dim * cfg.horizontal_scale for dim in sub_terrain_size]
|
||||
# update the config
|
||||
terrain_size = copy.deepcopy(cfg.size)
|
||||
cfg.size = tuple(sub_terrain_size)
|
||||
# generate the height field
|
||||
z_gen = func(difficulty, cfg)
|
||||
# handle the border for the terrain
|
||||
heights[border_pixels:-border_pixels, border_pixels:-border_pixels] = z_gen
|
||||
# set terrain size back to config
|
||||
cfg.size = terrain_size
|
||||
|
||||
# PATCH: Use optimized mesh generation to reduce GPU memory usage
|
||||
vertices, triangles = _convert_height_field_to_mesh_with_optimization_dynamic(
|
||||
heights, cfg.horizontal_scale, cfg.vertical_scale, 20
|
||||
)
|
||||
mesh = trimesh.Trimesh(vertices=vertices, faces=triangles)
|
||||
|
||||
# compute origin
|
||||
x1 = int((cfg.size[0] * 0.5 - 1) / cfg.horizontal_scale)
|
||||
x2 = int((cfg.size[0] * 0.5 + 1) / cfg.horizontal_scale)
|
||||
y1 = int((cfg.size[1] * 0.5 - 1) / cfg.horizontal_scale)
|
||||
y2 = int((cfg.size[1] * 0.5 + 1) / cfg.horizontal_scale)
|
||||
origin_z = np.max(heights[x1:x2, y1:y2]) * cfg.vertical_scale
|
||||
origin = np.array([0.5 * cfg.size[0], 0.5 * cfg.size[1], origin_z])
|
||||
# return mesh and origin
|
||||
return [mesh], origin
|
||||
|
||||
return wrapper
|
||||
|
||||
# Apply patch to the height_field_to_mesh decorator
|
||||
hf_utils.height_field_to_mesh = _patched_height_field_to_mesh
|
||||
|
||||
|
||||
def _patch_terrain_generator():
|
||||
"""Patch TerrainGenerator to collect height field data for goal sampling."""
|
||||
from isaaclab.terrains.terrain_generator import TerrainGenerator
|
||||
from isaaclab.terrains.utils import color_meshes_by_height
|
||||
from isaaclab.utils.timer import Timer
|
||||
from isaaclab.utils.io import dump_yaml
|
||||
from isaaclab.utils.dict import dict_to_md5_hash
|
||||
|
||||
# Height field attribute names we collect
|
||||
_HEIGHT_FIELD_ATTRS = [
|
||||
"height_field_visual",
|
||||
"height_field_valid_mask",
|
||||
"height_field_platform_mask",
|
||||
"height_field_spawn_mask",
|
||||
]
|
||||
|
||||
def _patched_init(self, cfg, device: str = "cpu"):
|
||||
"""Patched __init__ that collects height field data."""
|
||||
# Validate inputs
|
||||
if len(cfg.sub_terrains) == 0:
|
||||
raise ValueError("No sub-terrains specified in the configuration!")
|
||||
if cfg.curriculum and cfg.difficulty_range is None:
|
||||
raise ValueError("Curriculum learning requires 'difficulty_range' to be specified!")
|
||||
|
||||
# Store inputs
|
||||
self.cfg = cfg
|
||||
self.device = device
|
||||
|
||||
# Set common values for all sub-terrains
|
||||
for sub_cfg in self.cfg.sub_terrains.values():
|
||||
sub_cfg.size = self.cfg.size
|
||||
sub_cfg.horizontal_scale = self.cfg.horizontal_scale
|
||||
sub_cfg.vertical_scale = self.cfg.vertical_scale
|
||||
sub_cfg.slope_threshold = self.cfg.slope_threshold
|
||||
|
||||
# Set seed for reproducibility
|
||||
# - seed=None (default): random terrain each time (for training variety)
|
||||
# - seed=<int>: reproducible terrain (for debugging/evaluation)
|
||||
# Note: Always create RNG because Isaac Lab's base code uses self.np_rng
|
||||
self.np_rng = np.random.default_rng(self.cfg.seed)
|
||||
self._reproducible = self.cfg.seed is not None
|
||||
|
||||
# Initialize buffers
|
||||
self.flat_patches = {}
|
||||
self.terrain_meshes = []
|
||||
self.terrain_origins = np.zeros((self.cfg.num_rows, self.cfg.num_cols, 3))
|
||||
|
||||
# PATCH: Temporary lists to collect height field data during generation
|
||||
self._height_field_lists = {attr: [] for attr in _HEIGHT_FIELD_ATTRS}
|
||||
|
||||
# Generate terrains
|
||||
if self.cfg.curriculum:
|
||||
with Timer("[INFO] Generating terrains based on curriculum took"):
|
||||
self._generate_curriculum_terrains()
|
||||
else:
|
||||
with Timer("[INFO] Generating terrains randomly took"):
|
||||
self._generate_random_terrains()
|
||||
|
||||
# Add border and combine meshes
|
||||
self._add_terrain_border()
|
||||
self.terrain_mesh = trimesh.util.concatenate(self.terrain_meshes)
|
||||
|
||||
# PATCH: Consolidate collected height fields into tensors and store in shared storage
|
||||
for attr in _HEIGHT_FIELD_ATTRS:
|
||||
data_list = self._height_field_lists[attr]
|
||||
if data_list:
|
||||
setattr(self, attr, torch.cat(data_list, dim=0))
|
||||
_height_field_storage[attr] = getattr(self, attr)
|
||||
else:
|
||||
setattr(self, attr, None)
|
||||
_height_field_storage[attr] = None
|
||||
del self._height_field_lists # Free memory
|
||||
|
||||
# Color the terrain mesh
|
||||
if self.cfg.color_scheme == "height":
|
||||
self.terrain_mesh = color_meshes_by_height(self.terrain_mesh)
|
||||
elif self.cfg.color_scheme == "random":
|
||||
self.terrain_mesh.visual.vertex_colors = self.np_rng.choice(
|
||||
range(256), size=(len(self.terrain_mesh.vertices), 4)
|
||||
)
|
||||
elif self.cfg.color_scheme != "none":
|
||||
raise ValueError(f"Unknown color scheme: {self.cfg.color_scheme}")
|
||||
|
||||
# Move flat patches to device
|
||||
for name in self.flat_patches:
|
||||
self.flat_patches[name] = self.flat_patches[name].to(self.device)
|
||||
|
||||
def _patched_get_terrain_mesh(self, difficulty: float, cfg) -> tuple:
|
||||
"""Patched _get_terrain_mesh that collects height field data from each terrain."""
|
||||
# Copy configuration and set parameters
|
||||
cfg = cfg.copy()
|
||||
cfg.difficulty = float(difficulty)
|
||||
cfg.seed = self.cfg.seed
|
||||
|
||||
# Clear non-serializable fields for hashing
|
||||
for attr in _HEIGHT_FIELD_ATTRS:
|
||||
if hasattr(cfg, attr):
|
||||
setattr(cfg, attr, None)
|
||||
# Clear RNG for hashing (seed already included, RNG is derived from it)
|
||||
if hasattr(cfg, 'rng'):
|
||||
cfg.rng = None
|
||||
|
||||
# Generate hash and cache paths
|
||||
sub_terrain_hash = dict_to_md5_hash(cfg.to_dict())
|
||||
sub_terrain_cache_dir = os.path.join(self.cfg.cache_dir, sub_terrain_hash)
|
||||
sub_terrain_obj_filename = os.path.join(sub_terrain_cache_dir, "mesh.obj")
|
||||
sub_terrain_csv_filename = os.path.join(sub_terrain_cache_dir, "origin.csv")
|
||||
sub_terrain_meta_filename = os.path.join(sub_terrain_cache_dir, "cfg.yaml")
|
||||
|
||||
# Check cache
|
||||
if self.cfg.use_cache and os.path.exists(sub_terrain_obj_filename):
|
||||
mesh = trimesh.load_mesh(sub_terrain_obj_filename, process=False)
|
||||
origin = np.loadtxt(sub_terrain_csv_filename, delimiter=",")
|
||||
return mesh, origin
|
||||
|
||||
# Set RNG for terrain generation (after hashing, before generation)
|
||||
# Only pass RNG if seed was explicitly set (for reproducibility)
|
||||
# Otherwise cfg.rng stays None and terrain uses fresh random each time
|
||||
if hasattr(cfg, 'rng') and self._reproducible:
|
||||
cfg.rng = self.np_rng.spawn(1)[0]
|
||||
|
||||
# Generate mesh
|
||||
meshes, origin = cfg.function(difficulty, cfg)
|
||||
if not isinstance(meshes, list):
|
||||
meshes = [meshes]
|
||||
mesh = trimesh.util.concatenate(meshes)
|
||||
|
||||
# Center the mesh
|
||||
transform = np.eye(4)
|
||||
transform[0:2, -1] = -cfg.size[0] * 0.5, -cfg.size[1] * 0.5
|
||||
mesh.apply_transform(transform)
|
||||
origin += transform[0:3, -1]
|
||||
|
||||
# PATCH: Collect height field data from cfg (set by terrain generation function)
|
||||
for attr in _HEIGHT_FIELD_ATTRS:
|
||||
if hasattr(cfg, attr):
|
||||
data = getattr(cfg, attr)
|
||||
if data is not None:
|
||||
self._height_field_lists[attr].append(data)
|
||||
setattr(cfg, attr, None) # Clear after collecting
|
||||
|
||||
# Cache if enabled
|
||||
if self.cfg.use_cache:
|
||||
os.makedirs(sub_terrain_cache_dir, exist_ok=True)
|
||||
mesh.export(sub_terrain_obj_filename)
|
||||
np.savetxt(sub_terrain_csv_filename, origin, delimiter=",", header="x,y,z")
|
||||
dump_yaml(sub_terrain_meta_filename, cfg)
|
||||
|
||||
return mesh, origin
|
||||
|
||||
# Apply patches
|
||||
TerrainGenerator.__init__ = _patched_init
|
||||
TerrainGenerator._get_terrain_mesh = _patched_get_terrain_mesh
|
||||
|
||||
|
||||
def _patch_terrain_importer():
|
||||
"""Patch TerrainImporter to store height field data as attributes.
|
||||
|
||||
After TerrainGenerator populates shared storage, we capture the data
|
||||
and store it as attributes on TerrainImporter for access via env.scene.terrain.
|
||||
"""
|
||||
from isaaclab.terrains.terrain_importer import TerrainImporter
|
||||
|
||||
_original_importer_init = TerrainImporter.__init__
|
||||
|
||||
# Attribute names (with underscore prefix for storage on importer)
|
||||
_HEIGHT_FIELD_ATTRS = [
|
||||
"height_field_visual",
|
||||
"height_field_valid_mask",
|
||||
"height_field_platform_mask",
|
||||
"height_field_spawn_mask",
|
||||
]
|
||||
|
||||
def _patched_importer_init(self, cfg):
|
||||
"""Patched __init__ that captures height field data from TerrainGenerator."""
|
||||
# Clear previous storage
|
||||
for attr in _HEIGHT_FIELD_ATTRS:
|
||||
_height_field_storage[attr] = None
|
||||
|
||||
# Call original __init__ - creates TerrainGenerator which populates storage
|
||||
_original_importer_init(self, cfg)
|
||||
|
||||
# Capture height field data from storage and store as attributes
|
||||
for attr in _HEIGHT_FIELD_ATTRS:
|
||||
setattr(self, f"_{attr}", _height_field_storage.get(attr))
|
||||
|
||||
TerrainImporter.__init__ = _patched_importer_init
|
||||
|
||||
|
||||
def _patch_pinhole_camera_pattern_cfg():
|
||||
"""Patch PinholeCameraPatternCfg to add from_ros_camera_info method."""
|
||||
from isaaclab.sensors.ray_caster.patterns.patterns_cfg import PinholeCameraPatternCfg
|
||||
|
||||
# Check if already patched
|
||||
if hasattr(PinholeCameraPatternCfg, 'from_ros_camera_info'):
|
||||
return
|
||||
|
||||
# Add downsample_factor attribute if not present
|
||||
if not hasattr(PinholeCameraPatternCfg, 'downsample_factor'):
|
||||
PinholeCameraPatternCfg.downsample_factor = 1
|
||||
|
||||
# Store original from_intrinsic_matrix
|
||||
_original_from_intrinsic_matrix = PinholeCameraPatternCfg.from_intrinsic_matrix
|
||||
|
||||
@classmethod
|
||||
def _patched_from_intrinsic_matrix(
|
||||
cls,
|
||||
intrinsic_matrix: list[float],
|
||||
width: int,
|
||||
height: int,
|
||||
focal_length: float = 1.0,
|
||||
downsample_factor: int = 1,
|
||||
) -> PinholeCameraPatternCfg:
|
||||
"""Create a PinholeCameraPatternCfg from an intrinsic matrix with downsampling support.
|
||||
|
||||
Args:
|
||||
intrinsic_matrix: The intrinsic matrix as a 9-element list [f_x, 0, c_x, 0, f_y, c_y, 0, 0, 1].
|
||||
width: Width of the image (in pixels).
|
||||
height: Height of the image (in pixels).
|
||||
focal_length: Focal length of the camera (in cm). Defaults to 1.0 cm.
|
||||
downsample_factor: Downsampling factor for RL training. Defaults to 1 (no downsampling).
|
||||
|
||||
Returns:
|
||||
An instance of the PinholeCameraPatternCfg class.
|
||||
"""
|
||||
# Extract standard intrinsic parameters (in pixels)
|
||||
f_x = intrinsic_matrix[0]
|
||||
c_x = intrinsic_matrix[2]
|
||||
f_y = intrinsic_matrix[4]
|
||||
c_y = intrinsic_matrix[5]
|
||||
|
||||
# Apply downsampling adjustments
|
||||
if downsample_factor > 1:
|
||||
f_x = f_x / downsample_factor
|
||||
f_y = f_y / downsample_factor
|
||||
c_x = c_x / downsample_factor
|
||||
c_y = c_y / downsample_factor
|
||||
width = width // downsample_factor
|
||||
height = height // downsample_factor
|
||||
|
||||
# Convert to USD camera parameters
|
||||
horizontal_aperture = width * focal_length / f_x
|
||||
vertical_aperture = height * focal_length / f_y
|
||||
|
||||
# Convert principal point offset from pixels to physical units (cm)
|
||||
horizontal_aperture_offset = (c_x - width / 2) * horizontal_aperture / width
|
||||
vertical_aperture_offset = (c_y - height / 2) * vertical_aperture / height
|
||||
|
||||
return cls(
|
||||
focal_length=focal_length,
|
||||
horizontal_aperture=horizontal_aperture,
|
||||
vertical_aperture=vertical_aperture,
|
||||
horizontal_aperture_offset=horizontal_aperture_offset,
|
||||
vertical_aperture_offset=vertical_aperture_offset,
|
||||
width=width,
|
||||
height=height,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_ros_camera_info(
|
||||
cls,
|
||||
fx: float,
|
||||
fy: float,
|
||||
cx: float,
|
||||
cy: float,
|
||||
width: int,
|
||||
height: int,
|
||||
focal_length: float = 1.0,
|
||||
downsample_factor: int = 1,
|
||||
) -> PinholeCameraPatternCfg:
|
||||
"""Create a PinholeCameraPatternCfg from ROS CameraInfo parameters.
|
||||
|
||||
This is a convenience method for creating camera configurations directly from
|
||||
ROS camera_info topic parameters, avoiding the need to construct the full
|
||||
intrinsic matrix.
|
||||
|
||||
Args:
|
||||
fx: Focal length in x-direction (pixels).
|
||||
fy: Focal length in y-direction (pixels).
|
||||
cx: Principal point x-coordinate (pixels).
|
||||
cy: Principal point y-coordinate (pixels).
|
||||
width: Image width (pixels).
|
||||
height: Image height (pixels).
|
||||
focal_length: USD focal length scaling factor (cm). Defaults to 1.0 cm.
|
||||
downsample_factor: Downsampling factor for RL training. Defaults to 1 (no downsampling).
|
||||
|
||||
Returns:
|
||||
A PinholeCameraPatternCfg instance.
|
||||
|
||||
Example:
|
||||
# From your camera info topic:
|
||||
# K: [419.663, 0, 425.728, 0, 419.663, 238.272, 0, 0, 1]
|
||||
# size: 848 x 480
|
||||
|
||||
# Original resolution
|
||||
cfg = PinholeCameraPatternCfg.from_ros_camera_info(
|
||||
fx=419.663, fy=419.663, cx=425.728, cy=238.272,
|
||||
width=848, height=480
|
||||
)
|
||||
|
||||
# 4x downsampled for RL training (212x120)
|
||||
cfg_rl = PinholeCameraPatternCfg.from_ros_camera_info(
|
||||
fx=419.663, fy=419.663, cx=425.728, cy=238.272,
|
||||
width=848, height=480, downsample_factor=4
|
||||
)
|
||||
"""
|
||||
# Create intrinsic matrix in row-major format
|
||||
intrinsic_matrix = [fx, 0, cx, 0, fy, cy, 0, 0, 1]
|
||||
return cls.from_intrinsic_matrix(intrinsic_matrix, width, height, focal_length, downsample_factor)
|
||||
|
||||
# Apply patches
|
||||
PinholeCameraPatternCfg.from_intrinsic_matrix = _patched_from_intrinsic_matrix
|
||||
PinholeCameraPatternCfg.from_ros_camera_info = from_ros_camera_info
|
||||
+341
@@ -0,0 +1,341 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Constants for terrain generation and goal sampling.
|
||||
|
||||
This module centralizes all height field values and terrain parameters used across
|
||||
terrain generation and goal sampling code. Using these constants ensures consistency
|
||||
and makes the height semantics explicit.
|
||||
|
||||
Height Field Value Semantics (in discretized units):
|
||||
====================================================
|
||||
The height field stores heights as integers where:
|
||||
actual_height_meters = height_value * VERTICAL_SCALE
|
||||
|
||||
Key height values:
|
||||
- GROUND: 0 (flat walkable ground at z=0)
|
||||
- PLATFORM: ~200 (flat raised platforms at ~1.0m, valid for goals)
|
||||
- WALL: ~300 (obstacles/walls at ~1.5m, always excluded from goals)
|
||||
- PIT: ~-300 (negative obstacles/troughs at ~-1.5m, always excluded)
|
||||
|
||||
Goal Sampling Valid Ranges:
|
||||
- Ground: -10 to 50 (allows small noise/variation)
|
||||
- Platform: 150 to 250 (captures platform height with margin)
|
||||
- Excluded: < -10 (pits) or > 250 (walls)
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Tuple
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Scale Factors
|
||||
# =============================================================================
|
||||
|
||||
HORIZONTAL_SCALE: float = 0.1
|
||||
"""Horizontal resolution of height field in meters per cell."""
|
||||
|
||||
VERTICAL_SCALE: float = 0.005
|
||||
"""Vertical resolution of height field (height_meters = height_value * VERTICAL_SCALE)."""
|
||||
|
||||
CELL_SIZE: float = 2.0
|
||||
"""Size of each maze cell in meters (default: 2m x 2m)."""
|
||||
|
||||
CELL_PIXELS: int = int(CELL_SIZE / HORIZONTAL_SCALE)
|
||||
"""Number of height field pixels per maze cell (20 at default scale)."""
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Height Values (in discretized units, multiply by VERTICAL_SCALE for meters)
|
||||
# =============================================================================
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HeightValues:
|
||||
"""Standard height values for terrain features."""
|
||||
|
||||
# Ground level (valid for goals/spawn)
|
||||
GROUND: int = 0
|
||||
|
||||
# Platform height: wall_height - 0.5m in vertical scale units
|
||||
# = 1.5/0.005 - 0.5/0.005 = 300 - 100 = 200
|
||||
PLATFORM: int = 200
|
||||
|
||||
# Wall/obstacle height: 1.5m in vertical scale units
|
||||
# = 1.5/0.005 = 300
|
||||
WALL: int = 300
|
||||
|
||||
# Pit/trough height (negative obstacle)
|
||||
PIT: int = -300
|
||||
|
||||
@property
|
||||
def platform_meters(self) -> float:
|
||||
"""Platform height in meters."""
|
||||
return self.PLATFORM * VERTICAL_SCALE
|
||||
|
||||
@property
|
||||
def wall_meters(self) -> float:
|
||||
"""Wall height in meters."""
|
||||
return self.WALL * VERTICAL_SCALE
|
||||
|
||||
|
||||
HEIGHTS = HeightValues()
|
||||
"""Singleton instance of standard height values."""
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Goal Sampling Thresholds
|
||||
# =============================================================================
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SamplingThresholds:
|
||||
"""Thresholds for classifying height values during goal/spawn sampling.
|
||||
|
||||
These values match the old implementation for strict height classification.
|
||||
"""
|
||||
|
||||
# Ground range (strict: 0-10, allows minimal noise)
|
||||
GROUND_MIN: int = 0
|
||||
GROUND_MAX: int = 10
|
||||
|
||||
# Platform range (strict: 195-205 for stair platforms at ~1.0m)
|
||||
PLATFORM_MIN: int = 195
|
||||
PLATFORM_MAX: int = 205
|
||||
|
||||
# Wall threshold (anything above 10 is obstacle, but also check platform edges)
|
||||
WALL_THRESHOLD: int = 10
|
||||
|
||||
# Pit threshold (anything below 0 is pit/excluded)
|
||||
PIT_THRESHOLD: int = 0
|
||||
|
||||
# Edge detection threshold for Sobel filter (old: any edge > 0.0)
|
||||
EDGE_THRESHOLD: float = 0.0
|
||||
|
||||
# Obstacle marker value (used to mark excluded cells)
|
||||
OBSTACLE_MARKER: int = 110
|
||||
|
||||
# Extended platform range for edge detection (180-220)
|
||||
# Used during padding to detect platform edges with safety margin
|
||||
PLATFORM_EDGE_MIN: int = 180
|
||||
PLATFORM_EDGE_MAX: int = 220
|
||||
|
||||
|
||||
THRESHOLDS = SamplingThresholds()
|
||||
"""Singleton instance of sampling thresholds."""
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Padding and Border Configuration
|
||||
# =============================================================================
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PaddingConfig:
|
||||
"""Configuration for obstacle padding and borders.
|
||||
|
||||
These values match the old implementation for consistent safety margins.
|
||||
With horizontal_scale=0.1m/cell, these translate to:
|
||||
- GOAL_PADDING (3 cells) = 0.3m around obstacles for goal positions
|
||||
- SPAWN_PADDING (8 cells) = 0.8m around obstacles for spawn positions
|
||||
|
||||
The larger spawn padding accounts for:
|
||||
- Robot body dimensions (~0.5m x 0.3m for quadrupeds)
|
||||
- Random yaw orientation (diagonal ~0.58m requires ~0.3m radius)
|
||||
- Platform edge clearance (prevent falling when spawning near stair edges)
|
||||
- Controller startup imprecision
|
||||
"""
|
||||
|
||||
# Padding around obstacles for goals (in height field cells)
|
||||
# 5 cells * 0.1m/cell = 0.5m padding (robot just needs to reach)
|
||||
GOAL_PADDING: int = 5
|
||||
|
||||
# Larger padding for spawn positions (in height field cells)
|
||||
# 6 cells * 0.1m/cell = 0.6m padding
|
||||
# This accounts for:
|
||||
# - Robot body radius (~0.5m) with worst-case orientation
|
||||
# - Additional safety margin for platform edges
|
||||
# - Controller startup behavior
|
||||
SPAWN_PADDING: int = 6
|
||||
|
||||
# Border exclusion (keep away from terrain edges)
|
||||
# Old implementation used 2 layers (inner + outer), we use 2 cells
|
||||
BORDER_CELLS: int = 2
|
||||
|
||||
# Pillar expanded footprint size (5x5 cells around pillar center)
|
||||
PILLAR_FOOTPRINT: int = 5
|
||||
|
||||
# Pillar safe margin from cell edges
|
||||
PILLAR_EDGE_MARGIN: int = 2
|
||||
|
||||
# Height transition detection threshold (height field units)
|
||||
# Marks cells with height differences >= this value as transitions
|
||||
HEIGHT_TRANSITION_THRESHOLD: int = 100
|
||||
|
||||
# Padding around detected height transitions (in cells)
|
||||
HEIGHT_TRANSITION_PADDING: int = 1
|
||||
|
||||
|
||||
PADDING = PaddingConfig()
|
||||
"""Singleton instance of padding configuration."""
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Stair Configuration
|
||||
# =============================================================================
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StairConfig:
|
||||
"""Configuration for stair generation."""
|
||||
|
||||
# Number of steps in a staircase
|
||||
NUM_STEPS: int = 5
|
||||
|
||||
# Height of each step in meters
|
||||
STEP_HEIGHT_METERS: float = 0.2
|
||||
|
||||
# Grid size for 3x3 stair structures
|
||||
STAIR_GRID_SIZE: int = 3
|
||||
|
||||
# Single cell size in pixels (same as CELL_PIXELS)
|
||||
SINGLE_CELL_PIXELS: int = 20
|
||||
|
||||
@property
|
||||
def step_height_units(self) -> float:
|
||||
"""Step height in discretized units."""
|
||||
return self.STEP_HEIGHT_METERS / VERTICAL_SCALE
|
||||
|
||||
@property
|
||||
def step_resolution(self) -> int:
|
||||
"""Pixels per step (cell_pixels / num_steps)."""
|
||||
return self.SINGLE_CELL_PIXELS // self.NUM_STEPS
|
||||
|
||||
|
||||
STAIRS = StairConfig()
|
||||
"""Singleton instance of stair configuration."""
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Obstacle Structure Types
|
||||
# =============================================================================
|
||||
|
||||
class ObstacleType:
|
||||
"""Enumeration of obstacle structure types for random generation."""
|
||||
|
||||
PILLAR = 0
|
||||
BAR = 1
|
||||
CROSS = 2
|
||||
SHIFTED_BLOCK = 3
|
||||
|
||||
# Total number of obstacle types
|
||||
NUM_TYPES = 4
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Obstacle Generation Parameters
|
||||
# =============================================================================
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ObstacleConfig:
|
||||
"""Configuration for random obstacle generation.
|
||||
|
||||
Controls the randomness parameters for obstacle shapes, sizes, and pit ratios.
|
||||
All probabilities are in [0, 1] range.
|
||||
"""
|
||||
|
||||
# Height scale range (multiplier for wall_height)
|
||||
SCALE_MIN: float = 0.5
|
||||
SCALE_MAX: float = 1.5
|
||||
|
||||
# Thickness range (margin cells from obstacle center)
|
||||
# Higher thickness = thinner pillar, thicker bar
|
||||
# Range 7-9: pillars 2-6 pixels (0.2-0.6m), bars 7-9 pixels (0.7-0.9m)
|
||||
THICKNESS_MIN: int = 7
|
||||
THICKNESS_MAX: int = 10 # exclusive upper bound
|
||||
|
||||
# Default pit probability when not specified
|
||||
DEFAULT_PIT_PROB: float = 0.15
|
||||
|
||||
# Pit environment specific settings
|
||||
PITS_BAR_RATIO: float = 0.6 # Ratio of bars vs random obstacles in pit terrain
|
||||
PITS_BAR_PIT_PROB: float = 0.75 # Pit probability for bar obstacles
|
||||
PITS_RANDOM_PIT_PROB: float = 0.5 # Pit probability for random obstacles
|
||||
|
||||
# Bridge configuration for pit terrain
|
||||
BRIDGE_COUNT_MIN: int = 3
|
||||
BRIDGE_COUNT_MAX: int = 6 # exclusive upper bound
|
||||
|
||||
# Pit terrain layout (cell indices from grid edge)
|
||||
PITS_TRENCH_ROW_OFFSET: int = 2 # Pit trenches at rows [offset, grid_h - offset - 1]
|
||||
PITS_EDGE_MARGIN: int = 2 # Margin from grid edges for middle obstacles
|
||||
|
||||
# Obstacle density multipliers (applied to difficulty)
|
||||
NON_MAZE_DENSITY: float = 0.5 # For non-maze terrain (increased from 0.35)
|
||||
PITS_DENSITY: float = 0.6 # For pit terrain middle area
|
||||
STAIRS_OBSTACLE_DENSITY: float = 0.35 # For random obstacles in stair terrain
|
||||
STAIRS_PLACEMENT_PROB: float = 0.75 # Probability of placing stairs at valid locations
|
||||
|
||||
# Non-maze terrain pillar weight (higher = more pillars)
|
||||
# Default uniform is 0.25 (1/4 types), 0.5 means ~50% pillars
|
||||
NON_MAZE_PILLAR_WEIGHT: float = 0.5
|
||||
|
||||
|
||||
OBSTACLES = ObstacleConfig()
|
||||
"""Singleton instance of obstacle configuration."""
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Helper Functions
|
||||
# =============================================================================
|
||||
|
||||
def height_to_meters(height_value: int) -> float:
|
||||
"""Convert discretized height value to meters."""
|
||||
return height_value * VERTICAL_SCALE
|
||||
|
||||
|
||||
def meters_to_height(meters: float) -> int:
|
||||
"""Convert meters to discretized height value."""
|
||||
return int(meters / VERTICAL_SCALE)
|
||||
|
||||
|
||||
def is_valid_ground(height: int) -> bool:
|
||||
"""Check if height value represents valid ground."""
|
||||
return THRESHOLDS.GROUND_MIN <= height <= THRESHOLDS.GROUND_MAX
|
||||
|
||||
|
||||
def is_valid_platform(height: int) -> bool:
|
||||
"""Check if height value represents valid platform."""
|
||||
return THRESHOLDS.PLATFORM_MIN <= height <= THRESHOLDS.PLATFORM_MAX
|
||||
|
||||
|
||||
def is_valid_goal_position(height: int) -> bool:
|
||||
"""Check if height value is valid for goal/spawn placement."""
|
||||
return is_valid_ground(height) or is_valid_platform(height)
|
||||
|
||||
|
||||
def is_obstacle(height: int) -> bool:
|
||||
"""Check if height value represents an obstacle (wall or pit)."""
|
||||
return height > THRESHOLDS.WALL_THRESHOLD or height < THRESHOLDS.PIT_THRESHOLD
|
||||
|
||||
|
||||
def is_pit(height: int) -> bool:
|
||||
"""Check if height value represents a pit."""
|
||||
return height < THRESHOLDS.PIT_THRESHOLD
|
||||
|
||||
|
||||
def is_wall(height: int) -> bool:
|
||||
"""Check if height value represents a wall."""
|
||||
return height > THRESHOLDS.WALL_THRESHOLD
|
||||
|
||||
|
||||
def cell_to_pixels(cell_idx: int) -> Tuple[int, int]:
|
||||
"""Convert cell index to pixel range.
|
||||
|
||||
Args:
|
||||
cell_idx: Cell index in maze grid.
|
||||
|
||||
Returns:
|
||||
Tuple of (start_pixel, end_pixel).
|
||||
"""
|
||||
start = cell_idx * CELL_PIXELS
|
||||
end = (cell_idx + 1) * CELL_PIXELS
|
||||
return start, end
|
||||
@@ -0,0 +1,3 @@
|
||||
[build-system]
|
||||
requires = ["setuptools", "toml"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
@@ -0,0 +1,221 @@
|
||||
#!/usr/bin/env python3
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Depth-ablation diagnostic for a trained navigation policy.
|
||||
|
||||
Question this answers: *does the policy actually use the depth-camera input,
|
||||
or has it learned to ignore it (perception-blind)?*
|
||||
|
||||
Method
|
||||
------
|
||||
1. Load the trained actor-critic exactly like ``play.py``.
|
||||
2. Locate the ``depth_image`` slice inside the concatenated *policy* observation.
|
||||
3. Roll the env out with the REAL on-policy actions, and at every step also
|
||||
compute a counterfactual action where the depth slice is zeroed. Compare.
|
||||
4. Also track the depth-feature statistics (std over envs/time) so we can tell
|
||||
a *dead sensor* (constant features) apart from a policy that *ignores*
|
||||
informative features.
|
||||
|
||||
Verdict logic (printed at the end)
|
||||
----------------------------------
|
||||
* depth features ~constant (std ~ 0) -> SENSOR/ENCODER dead (no signal)
|
||||
* features vary, zeroing barely changes action -> LEARNED-BLIND (ignores depth)
|
||||
* features vary, zeroing changes action a lot -> policy DOES use depth
|
||||
|
||||
Usage (inside container, mirrors play.py):
|
||||
./isaaclab.sh -p source/isaaclab_nav_task/scripts/ablate_depth.py \
|
||||
--task Isaac-Nav-PPO-Go2-Play-v0 --num_envs 16 \
|
||||
--checkpoint <path/model_6998.pt> --steps 300 --headless
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
from isaaclab.app import AppLauncher
|
||||
|
||||
parser = argparse.ArgumentParser(description="Depth-ablation diagnostic for a navigation policy.")
|
||||
parser.add_argument("--num_envs", type=int, default=16, help="Number of environments to simulate.")
|
||||
parser.add_argument("--task", type=str, default=None, help="Name of the task (use a *-Play-v0 variant).")
|
||||
parser.add_argument("--checkpoint", type=str, default=None, help="Path to model checkpoint (.pt).")
|
||||
parser.add_argument("--steps", type=int, default=300, help="Number of env steps to roll out.")
|
||||
parser.add_argument("--warmup", type=int, default=20, help="Steps to skip before collecting stats (let resets settle).")
|
||||
parser.add_argument("--seed", type=int, default=42, help="Seed.")
|
||||
|
||||
AppLauncher.add_app_launcher_args(parser)
|
||||
args_cli, hydra_args = parser.parse_known_args()
|
||||
|
||||
# Cameras are mandatory for the depth observation.
|
||||
args_cli.enable_cameras = True
|
||||
|
||||
app_launcher = AppLauncher(args_cli)
|
||||
simulation_app = app_launcher.app
|
||||
|
||||
import gymnasium as gym
|
||||
import torch
|
||||
|
||||
from rsl_rl.runners import OnPolicyRunner
|
||||
|
||||
import isaaclab_tasks # noqa: F401
|
||||
import isaaclab_nav_task # noqa: F401
|
||||
|
||||
from isaaclab.envs import ManagerBasedRLEnvCfg
|
||||
from isaaclab_rl.rsl_rl import RslRlOnPolicyRunnerCfg, RslRlVecEnvWrapper
|
||||
|
||||
|
||||
def _find_depth_slice(env) -> tuple[int, int, list[tuple[str, int]]]:
|
||||
"""Return (start, end, layout) of the ``depth_image`` term in the policy obs.
|
||||
|
||||
layout is a list of (term_name, flat_dim) in concatenation order, for printing.
|
||||
"""
|
||||
om = env.unwrapped.observation_manager
|
||||
names = om.active_terms["policy"]
|
||||
dims = om.group_obs_term_dim["policy"] # list of shape-tuples per term
|
||||
|
||||
layout: list[tuple[str, int]] = []
|
||||
offset = 0
|
||||
depth_start = depth_end = -1
|
||||
for name, shape in zip(names, dims):
|
||||
flat = 1
|
||||
for s in shape:
|
||||
flat *= s
|
||||
layout.append((name, flat))
|
||||
if name == "depth_image":
|
||||
depth_start, depth_end = offset, offset + flat
|
||||
offset += flat
|
||||
if depth_start < 0:
|
||||
raise RuntimeError(
|
||||
f"No 'depth_image' term found in policy obs group. Terms = {names}"
|
||||
)
|
||||
return depth_start, depth_end, layout
|
||||
|
||||
|
||||
def main():
|
||||
spec = gym.spec(args_cli.task)
|
||||
env_cfg_class = spec.kwargs.get("env_cfg_entry_point")
|
||||
agent_cfg_class = spec.kwargs.get("rsl_rl_cfg_entry_point")
|
||||
|
||||
env_cfg: ManagerBasedRLEnvCfg = env_cfg_class()
|
||||
agent_cfg: RslRlOnPolicyRunnerCfg = agent_cfg_class()
|
||||
|
||||
if args_cli.num_envs is not None:
|
||||
env_cfg.scene.num_envs = args_cli.num_envs
|
||||
|
||||
env = gym.make(args_cli.task, cfg=env_cfg, render_mode=None)
|
||||
env = RslRlVecEnvWrapper(env)
|
||||
|
||||
runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device)
|
||||
|
||||
# --- load checkpoint (same logic as play.py) ---
|
||||
resume_path = args_cli.checkpoint
|
||||
if not resume_path:
|
||||
raise SystemExit("[ablate] --checkpoint is required for the diagnostic.")
|
||||
print(f"[ablate] loading checkpoint: {resume_path}")
|
||||
loaded = torch.load(resume_path, map_location="cpu", weights_only=False)
|
||||
runner.alg.actor_critic.load_state_dict(loaded["model_state_dict"], strict=True)
|
||||
if runner.empirical_normalization:
|
||||
runner.obs_normalizer.load_state_dict(loaded["obs_norm_state_dict"])
|
||||
runner.critic_obs_normalizer.load_state_dict(loaded["critic_obs_norm_state_dict"])
|
||||
print(f"[ablate] checkpoint iter = {loaded.get('iter', '?')}")
|
||||
|
||||
policy = runner.get_inference_policy(device=env.unwrapped.device)
|
||||
|
||||
depth_start, depth_end, layout = _find_depth_slice(env)
|
||||
print("=" * 78)
|
||||
print("[ablate] policy observation layout (term : flat_dim):")
|
||||
for name, flat in layout:
|
||||
marker = " <-- DEPTH" if name == "depth_image" else ""
|
||||
print(f" {name:<28} {flat:>5}{marker}")
|
||||
print(f"[ablate] depth slice = [{depth_start}:{depth_end}] ({depth_end - depth_start} dims)")
|
||||
print("=" * 78)
|
||||
|
||||
obs, _ = env.get_observations()
|
||||
|
||||
# accumulators
|
||||
n = 0
|
||||
act_norm_sum = 0.0 # ||a_real||
|
||||
diff_norm_sum = 0.0 # ||a_real - a_zero||
|
||||
per_dim_abs_diff = None # mean |a_real - a_zero| per action dim
|
||||
per_dim_abs_act = None # mean |a_real| per action dim
|
||||
depth_feat_chunks = [] # collect depth slices to measure variability
|
||||
|
||||
device = env.unwrapped.device
|
||||
step = 0
|
||||
while simulation_app.is_running() and step < args_cli.steps:
|
||||
with torch.inference_mode():
|
||||
a_real = policy(obs)
|
||||
obs_zero = obs.clone()
|
||||
obs_zero[:, depth_start:depth_end] = 0.0
|
||||
a_zero = policy(obs_zero)
|
||||
|
||||
if step >= args_cli.warmup:
|
||||
d = (a_real - a_zero)
|
||||
diff_norm_sum += torch.linalg.vector_norm(d, dim=-1).mean().item()
|
||||
act_norm_sum += torch.linalg.vector_norm(a_real, dim=-1).mean().item()
|
||||
ad = d.abs().mean(dim=0)
|
||||
aa = a_real.abs().mean(dim=0)
|
||||
per_dim_abs_diff = ad if per_dim_abs_diff is None else per_dim_abs_diff + ad
|
||||
per_dim_abs_act = aa if per_dim_abs_act is None else per_dim_abs_act + aa
|
||||
depth_feat_chunks.append(obs[:, depth_start:depth_end].detach().clone())
|
||||
n += 1
|
||||
|
||||
with torch.inference_mode():
|
||||
obs, _, _, _ = env.step(a_real)
|
||||
step += 1
|
||||
|
||||
# --- summarise ---
|
||||
print("\n" + "=" * 78)
|
||||
print(f"[ablate] collected {n} steps (after {args_cli.warmup} warmup), {args_cli.num_envs} envs")
|
||||
if n == 0:
|
||||
print("[ablate] no samples collected; increase --steps.")
|
||||
else:
|
||||
mean_act = act_norm_sum / n
|
||||
mean_diff = diff_norm_sum / n
|
||||
rel = (mean_diff / mean_act) if mean_act > 0 else float("nan")
|
||||
per_dim_abs_diff = (per_dim_abs_diff / n).tolist()
|
||||
per_dim_abs_act = (per_dim_abs_act / n).tolist()
|
||||
|
||||
feats = torch.cat(depth_feat_chunks, dim=0) # (n*envs, depth_dim)
|
||||
feat_std_over_samples = feats.std(dim=0).mean().item() # variability across time/envs
|
||||
feat_abs_mean = feats.abs().mean().item()
|
||||
|
||||
names_se2 = ["vx", "vy", "omega"]
|
||||
print("\n-- ACTION SENSITIVITY TO DEPTH (real vs depth-zeroed) --")
|
||||
print(f" mean ||a_real|| = {mean_act:.4f}")
|
||||
print(f" mean ||a_real - a_zero|| = {mean_diff:.4f}")
|
||||
print(f" RELATIVE action change = {rel*100:.2f}%")
|
||||
print(" per-action-dim |diff| / |act|:")
|
||||
for i, v in enumerate(per_dim_abs_diff):
|
||||
nm = names_se2[i] if i < len(names_se2) else f"a{i}"
|
||||
denom = per_dim_abs_act[i] if per_dim_abs_act[i] > 0 else float("nan")
|
||||
print(f" {nm:<6} |diff|={v:.4f} |act|={per_dim_abs_act[i]:.4f} ratio={v/denom*100:.1f}%")
|
||||
|
||||
print("\n-- DEPTH FEATURE SIGNAL (is the camera/encoder alive?) --")
|
||||
print(f" feature |mean| = {feat_abs_mean:.4f}")
|
||||
print(f" feature std over time/envs = {feat_std_over_samples:.4f}")
|
||||
|
||||
print("\n-- VERDICT --")
|
||||
if feat_std_over_samples < 1e-3:
|
||||
print(" >> DEAD SIGNAL: depth features are ~constant. Camera/encoder is")
|
||||
print(" not producing a varying signal (sensor/render/orientation bug).")
|
||||
elif rel < 0.02:
|
||||
print(" >> LEARNED-BLIND: features vary but zeroing them changes the action")
|
||||
print(f" by only {rel*100:.2f}%. The policy effectively IGNORES depth.")
|
||||
elif rel < 0.10:
|
||||
print(f" >> WEAK USE: depth changes the action by {rel*100:.2f}% (marginal).")
|
||||
else:
|
||||
print(f" >> DEPTH IS USED: zeroing depth changes the action by {rel*100:.2f}%.")
|
||||
print(" Perception is wired in; the failure is likely a difficulty/")
|
||||
print(" generalisation gap, not blindness.")
|
||||
print("=" * 78)
|
||||
|
||||
env.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
simulation_app.close()
|
||||
+325
@@ -0,0 +1,325 @@
|
||||
#!/usr/bin/env python3
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Instrumented collision analysis for a trained navigation policy.
|
||||
|
||||
For every env-step, this script records:
|
||||
* base_lin_vel_b[:, 0] -- forward velocity in body frame (m/s)
|
||||
* max contact-force magnitude over the *termination sensor body subset*
|
||||
(whatever ``terminations.base_contact.params['sensor_cfg'].body_ids`` is)
|
||||
* the per-term ``base_contact`` done flag
|
||||
|
||||
It maintains a per-env rolling buffer of the last K=16 steps so that, when a
|
||||
collision fires for env i, we can dump the *pre-impact trajectory* (velocity +
|
||||
peak force) for that env. The aggregated data is saved as a single .npz which
|
||||
the companion script ``plot_collisions.py`` turns into figures.
|
||||
|
||||
Outputs (under --out-dir, default ``logs/collisions/<task>__<ckpt>``):
|
||||
* collisions.npz full dump (see save_data())
|
||||
* summary.txt human-readable numbers
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
|
||||
from isaaclab.app import AppLauncher
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--num_envs", type=int, default=32)
|
||||
parser.add_argument("--task", type=str, required=True)
|
||||
parser.add_argument("--checkpoint", type=str, required=True)
|
||||
parser.add_argument("--steps", type=int, default=4000)
|
||||
parser.add_argument("--warmup", type=int, default=20)
|
||||
parser.add_argument("--seed", type=int, default=42)
|
||||
parser.add_argument("--lookback", type=int, default=16,
|
||||
help="How many pre-impact steps to capture per collision.")
|
||||
parser.add_argument("--out-dir", type=str, default=None)
|
||||
AppLauncher.add_app_launcher_args(parser)
|
||||
args_cli, _ = parser.parse_known_args()
|
||||
args_cli.enable_cameras = True
|
||||
|
||||
app_launcher = AppLauncher(args_cli)
|
||||
simulation_app = app_launcher.app
|
||||
|
||||
import gymnasium as gym
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from rsl_rl.runners import OnPolicyRunner
|
||||
|
||||
import isaaclab_tasks # noqa: F401
|
||||
import isaaclab_nav_task # noqa: F401
|
||||
from isaaclab.envs import ManagerBasedRLEnvCfg
|
||||
from isaaclab.managers import SceneEntityCfg
|
||||
from isaaclab.sensors import ContactSensor
|
||||
from isaaclab_rl.rsl_rl import RslRlOnPolicyRunnerCfg, RslRlVecEnvWrapper
|
||||
|
||||
|
||||
def main():
|
||||
spec = gym.spec(args_cli.task)
|
||||
env_cfg: ManagerBasedRLEnvCfg = spec.kwargs["env_cfg_entry_point"]()
|
||||
agent_cfg: RslRlOnPolicyRunnerCfg = spec.kwargs["rsl_rl_cfg_entry_point"]()
|
||||
env_cfg.scene.num_envs = args_cli.num_envs
|
||||
|
||||
env = gym.make(args_cli.task, cfg=env_cfg, render_mode=None)
|
||||
env = RslRlVecEnvWrapper(env)
|
||||
device = env.unwrapped.device
|
||||
N = args_cli.num_envs
|
||||
|
||||
# ---- load policy ----
|
||||
runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device)
|
||||
loaded = torch.load(args_cli.checkpoint, map_location="cpu", weights_only=False)
|
||||
runner.alg.actor_critic.load_state_dict(loaded["model_state_dict"], strict=True)
|
||||
if runner.empirical_normalization:
|
||||
runner.obs_normalizer.load_state_dict(loaded["obs_norm_state_dict"])
|
||||
runner.critic_obs_normalizer.load_state_dict(loaded["critic_obs_norm_state_dict"])
|
||||
print(f"[collisions] checkpoint iter = {loaded.get('iter', '?')}")
|
||||
policy = runner.get_inference_policy(device=device)
|
||||
|
||||
# ---- resolve the *exact* body subset used by the base_contact termination ----
|
||||
tm = env.unwrapped.termination_manager
|
||||
tf = tm.get_term_cfg("base_contact")
|
||||
sensor_cfg: SceneEntityCfg = tf.params["sensor_cfg"]
|
||||
threshold = float(tf.params["threshold"])
|
||||
print(f"[collisions] base_contact threshold = {threshold} N")
|
||||
print(f"[collisions] base_contact body_names spec = {sensor_cfg.body_names}")
|
||||
|
||||
# NOTE: TerminationManager already resolved this SceneEntityCfg at env init,
|
||||
# so body_ids is already populated; calling .resolve() again would raise.
|
||||
body_ids = sensor_cfg.body_ids
|
||||
contact_sensor: ContactSensor = env.unwrapped.scene.sensors[sensor_cfg.name]
|
||||
print(f"[collisions] resolved body_ids = {list(body_ids) if not isinstance(body_ids, slice) else body_ids}")
|
||||
|
||||
# episode_termination reward weight (for context in summary)
|
||||
try:
|
||||
ep_term_w = float(env.unwrapped.reward_manager.get_term_cfg("episode_termination").weight)
|
||||
except Exception:
|
||||
ep_term_w = float("nan")
|
||||
|
||||
robot = env.unwrapped.scene["robot"]
|
||||
|
||||
# ---- rolling buffers (K x N) for pre-impact dumps ----
|
||||
K = args_cli.lookback
|
||||
vel_buf = torch.zeros(K, N, device=device) # base lin vel x (body frame)
|
||||
speed_buf = torch.zeros(K, N, device=device) # |v_xy| (body frame)
|
||||
force_buf = torch.zeros(K, N, device=device) # max contact force on subset
|
||||
head = 0 # circular index
|
||||
|
||||
# ---- collected data ----
|
||||
coll_traj_vel = [] # list of (K,) numpy arrays at the impact moment
|
||||
coll_traj_speed = []
|
||||
coll_traj_force = []
|
||||
coll_impact_vel = [] # scalar at the IMPACT step (after termination flag flips)
|
||||
coll_impact_speed = []
|
||||
coll_impact_force = []
|
||||
|
||||
# global histograms over all NON-terminating steps (for context)
|
||||
all_vel_chunks = []
|
||||
all_force_chunks = []
|
||||
|
||||
n_steps_counted = 0
|
||||
n_collisions = 0
|
||||
n_success = 0
|
||||
n_timeout = 0
|
||||
|
||||
obs, _ = env.get_observations()
|
||||
step = 0
|
||||
while simulation_app.is_running() and step < args_cli.steps:
|
||||
# -------------------------------------------------------------
|
||||
# CRITICAL: measure state BEFORE env.step(), because IsaacLab
|
||||
# auto-resets terminated envs INSIDE env.step() and that wipes
|
||||
# both robot.data and contact_sensor.data for the dying envs.
|
||||
# We do NOT lose the impact data: the contact force history
|
||||
# buffer (decimation samples) accumulates within env.step(),
|
||||
# so reading it on the *next* iteration's pre-step pass would
|
||||
# be the natural way -- but at that point reset has zeroed it
|
||||
# for dying envs. Compromise: at pre-step iter t+1, read
|
||||
# sensor history (last decimation_count physics steps from
|
||||
# iter t) for the envs that just died -- still works for envs
|
||||
# whose sensor history isn't fully cleared by reset (depends
|
||||
# on IsaacLab version). Velocity, on the other hand, must
|
||||
# be sampled BEFORE the impact step; using buffer[head-1]
|
||||
# (the prior iteration's measurement) gives us exactly that.
|
||||
# -------------------------------------------------------------
|
||||
v_b = robot.data.root_lin_vel_b # (N, 3) -- state at start of iter t
|
||||
v_fwd = v_b[:, 0]
|
||||
v_xy = torch.norm(v_b[:, :2], dim=-1)
|
||||
|
||||
net_force_hist = contact_sensor.data.net_forces_w_history # (N, H, B_total, 3)
|
||||
f_mags = torch.norm(net_force_hist[:, :, body_ids, :], dim=-1)
|
||||
peak_force, _ = f_mags.reshape(N, -1).max(dim=-1) # (N,)
|
||||
|
||||
# Save what we *had* in the buffer before overwriting, in case
|
||||
# we need to look at "1 step ago" specifically.
|
||||
prev_head = (head - 1) % K
|
||||
prev_vel = vel_buf[prev_head].clone()
|
||||
prev_speed = speed_buf[prev_head].clone()
|
||||
prev_force = force_buf[prev_head].clone()
|
||||
|
||||
# Push into rolling buffer (newest at index `head`, then advance).
|
||||
vel_buf[head] = v_fwd
|
||||
speed_buf[head] = v_xy
|
||||
force_buf[head] = peak_force
|
||||
new_head = head
|
||||
head = (head + 1) % K
|
||||
|
||||
# ---- step the env (terminations + auto-reset happen in here) ----
|
||||
with torch.inference_mode():
|
||||
actions = policy(obs)
|
||||
obs, _, _, _ = env.step(actions)
|
||||
|
||||
# ---- post-step: read sensor history AGAIN for envs that just died;
|
||||
# this captures the *peak* contact force during the impact step
|
||||
# if the reset hasn't yet zeroed the history buffer.
|
||||
post_force_hist = contact_sensor.data.net_forces_w_history
|
||||
post_f_mags = torch.norm(post_force_hist[:, :, body_ids, :], dim=-1)
|
||||
post_peak_force, _ = post_f_mags.reshape(N, -1).max(dim=-1)
|
||||
|
||||
if step >= args_cli.warmup:
|
||||
n_steps_counted += 1
|
||||
|
||||
done_bc = tm.get_term("base_contact").to(torch.bool)
|
||||
done_to = tm.get_term("time_out").to(torch.bool)
|
||||
done_succ = tm.get_term("early_termination").to(torch.bool)
|
||||
|
||||
n_collisions += int(done_bc.sum().item())
|
||||
n_success += int(done_succ.sum().item())
|
||||
n_timeout += int(done_to.sum().item())
|
||||
|
||||
if done_bc.any():
|
||||
idxs = torch.where(done_bc)[0].cpu().tolist()
|
||||
# Buffer order: oldest -> newest. Newest = just pushed at
|
||||
# `new_head`. For envs that died THIS env.step(), the
|
||||
# `new_head` sample is the pre-impact state at iter start.
|
||||
order = [(head + i) % K for i in range(K)]
|
||||
for i in idxs:
|
||||
vt = vel_buf[order, i].cpu().numpy()
|
||||
st = speed_buf[order, i].cpu().numpy()
|
||||
ft = force_buf[order, i].cpu().numpy()
|
||||
coll_traj_vel.append(vt)
|
||||
coll_traj_speed.append(st)
|
||||
coll_traj_force.append(ft)
|
||||
# Pre-impact velocity = the value we measured BEFORE
|
||||
# this env.step() (which contained the actual impact).
|
||||
coll_impact_vel.append(float(v_fwd[i].item()))
|
||||
coll_impact_speed.append(float(v_xy[i].item()))
|
||||
# Impact force: take max of (a) pre-step reading, (b) post-step
|
||||
# reading, (c) buffer max over the window -- whichever is
|
||||
# largest is the best estimate of true peak force.
|
||||
win_peak = float(force_buf[:, i].max().item())
|
||||
impact_f = max(
|
||||
float(peak_force[i].item()),
|
||||
float(post_peak_force[i].item()),
|
||||
win_peak,
|
||||
)
|
||||
coll_impact_force.append(impact_f)
|
||||
|
||||
# Global samples (alive envs only).
|
||||
alive = ~tm.dones.to(torch.bool)
|
||||
if alive.any():
|
||||
all_vel_chunks.append(v_fwd[alive].cpu().numpy())
|
||||
# use post-step force for non-dying envs -- it includes
|
||||
# in-step contacts the policy then recovers from.
|
||||
all_force_chunks.append(post_peak_force[alive].cpu().numpy())
|
||||
|
||||
step += 1
|
||||
|
||||
# ---- save ----
|
||||
out_dir = args_cli.out_dir
|
||||
if out_dir is None:
|
||||
tag = os.path.splitext(os.path.basename(args_cli.checkpoint))[0]
|
||||
out_dir = os.path.join("logs", "collisions", f"{args_cli.task}__{tag}")
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
|
||||
impact_vel_arr = np.array(coll_impact_vel)
|
||||
impact_speed_arr = np.array(coll_impact_speed)
|
||||
impact_force_arr = np.array(coll_impact_force)
|
||||
traj_vel_arr = np.stack(coll_traj_vel) if coll_traj_vel else np.zeros((0, K))
|
||||
traj_speed_arr = np.stack(coll_traj_speed) if coll_traj_speed else np.zeros((0, K))
|
||||
traj_force_arr = np.stack(coll_traj_force) if coll_traj_force else np.zeros((0, K))
|
||||
all_vel_arr = np.concatenate(all_vel_chunks) if all_vel_chunks else np.zeros((0,))
|
||||
all_force_arr = np.concatenate(all_force_chunks) if all_force_chunks else np.zeros((0,))
|
||||
|
||||
np.savez_compressed(
|
||||
os.path.join(out_dir, "collisions.npz"),
|
||||
impact_vel=impact_vel_arr,
|
||||
impact_speed=impact_speed_arr,
|
||||
impact_force=impact_force_arr,
|
||||
traj_vel=traj_vel_arr,
|
||||
traj_speed=traj_speed_arr,
|
||||
traj_force=traj_force_arr,
|
||||
all_vel=all_vel_arr,
|
||||
all_force=all_force_arr,
|
||||
threshold=np.array(threshold, dtype=np.float32),
|
||||
ep_term_weight=np.array(ep_term_w, dtype=np.float32),
|
||||
K=np.array(K),
|
||||
num_envs=np.array(N),
|
||||
steps=np.array(n_steps_counted),
|
||||
n_collisions=np.array(n_collisions),
|
||||
n_success=np.array(n_success),
|
||||
n_timeout=np.array(n_timeout),
|
||||
)
|
||||
|
||||
# ---- human summary ----
|
||||
def pct(x, total):
|
||||
return 100.0 * x / max(total, 1)
|
||||
|
||||
total_term = n_collisions + n_success + n_timeout
|
||||
summary = []
|
||||
summary.append(f"task : {args_cli.task}")
|
||||
summary.append(f"checkpoint : {args_cli.checkpoint}")
|
||||
summary.append(f"steps counted : {n_steps_counted} (warmup={args_cli.warmup})")
|
||||
summary.append(f"num envs : {N}")
|
||||
summary.append(f"")
|
||||
summary.append(f"base_contact threshold (training) : {threshold} N")
|
||||
summary.append(f"episode_termination reward weight : {ep_term_w}")
|
||||
summary.append(f"")
|
||||
summary.append(f"terminations : success={n_success} collision={n_collisions} timeout={n_timeout}")
|
||||
summary.append(f" success % : {pct(n_success, total_term):.1f}")
|
||||
summary.append(f" collision % : {pct(n_collisions, total_term):.1f}")
|
||||
summary.append(f" timeout % : {pct(n_timeout, total_term):.1f}")
|
||||
summary.append(f"")
|
||||
if impact_vel_arr.size > 0:
|
||||
summary.append(f"AT IMPACT (n={impact_vel_arr.size})")
|
||||
summary.append(f" v_fwd (body x) : mean={impact_vel_arr.mean():+.3f} median={np.median(impact_vel_arr):+.3f} "
|
||||
f"p10={np.percentile(impact_vel_arr,10):+.3f} p90={np.percentile(impact_vel_arr,90):+.3f} "
|
||||
f"std={impact_vel_arr.std():.3f} (m/s)")
|
||||
summary.append(f" |v_xy| : mean={impact_speed_arr.mean():.3f} median={np.median(impact_speed_arr):.3f} "
|
||||
f"p10={np.percentile(impact_speed_arr,10):.3f} p90={np.percentile(impact_speed_arr,90):.3f} (m/s)")
|
||||
summary.append(f" peak force : mean={impact_force_arr.mean():.1f} median={np.median(impact_force_arr):.1f} "
|
||||
f"p10={np.percentile(impact_force_arr,10):.1f} p90={np.percentile(impact_force_arr,90):.1f} "
|
||||
f"max={impact_force_arr.max():.1f} (N)")
|
||||
summary.append(f" force / threshold ratio : median {np.median(impact_force_arr)/threshold:.1f}x, "
|
||||
f"max {impact_force_arr.max()/threshold:.1f}x")
|
||||
n_slow = int((impact_speed_arr < 0.2).sum())
|
||||
n_fast = int((impact_speed_arr > 0.8).sum())
|
||||
summary.append(f" slow impacts (|v_xy|<0.2 m/s) : {n_slow} ({pct(n_slow, impact_speed_arr.size):.1f}%)")
|
||||
summary.append(f" fast impacts (|v_xy|>0.8 m/s) : {n_fast} ({pct(n_fast, impact_speed_arr.size):.1f}%)")
|
||||
else:
|
||||
summary.append("NO COLLISIONS in this run.")
|
||||
if all_vel_arr.size > 0:
|
||||
summary.append(f"")
|
||||
summary.append(f"GLOBAL (alive-step samples, n={all_vel_arr.size})")
|
||||
summary.append(f" v_fwd : mean={all_vel_arr.mean():+.3f} median={np.median(all_vel_arr):+.3f} "
|
||||
f"std={all_vel_arr.std():.3f} (m/s)")
|
||||
summary.append(f" peak F : mean={all_force_arr.mean():.2f} median={np.median(all_force_arr):.2f} "
|
||||
f"p99={np.percentile(all_force_arr,99):.2f} (N)")
|
||||
|
||||
txt = "\n".join(summary)
|
||||
with open(os.path.join(out_dir, "summary.txt"), "w") as f:
|
||||
f.write(txt + "\n")
|
||||
print("\n" + "=" * 78)
|
||||
print(txt)
|
||||
print("=" * 78)
|
||||
print(f"\n[collisions] saved to: {out_dir}")
|
||||
env.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
simulation_app.close()
|
||||
+246
@@ -0,0 +1,246 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Convert old policy checkpoints to the new positional encoding structure.
|
||||
|
||||
The old checkpoint uses:
|
||||
attn_*_net.position_embedding.penc.inv_freq
|
||||
|
||||
The new checkpoint uses:
|
||||
attn_*_net.pos_encoding
|
||||
|
||||
This script converts old checkpoints to the new format by:
|
||||
1. Removing the old position_embedding.penc.inv_freq keys
|
||||
2. Computing and adding the new pos_encoding tensors
|
||||
|
||||
Usage:
|
||||
./isaaclab.sh -p scripts/convert_checkpoint.py --input <old_checkpoint.pt> --output <new_checkpoint.pt>
|
||||
|
||||
# Or convert in-place:
|
||||
./isaaclab.sh -p scripts/convert_checkpoint.py --input <checkpoint.pt> --inplace
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import math
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
def _compute_positional_encoding_3d(
|
||||
channels: int, D: int, H: int, W: int, device: torch.device, dtype: torch.dtype
|
||||
) -> torch.Tensor:
|
||||
"""Compute 3D positional encoding for given spatial dimensions.
|
||||
|
||||
This code is adapted from: https://github.com/tatp22/multidim-positional-encoding
|
||||
|
||||
Args:
|
||||
channels: Number of channels for the encoding.
|
||||
D, H, W: Spatial dimensions (depth, height, width).
|
||||
device: Device to create tensor on.
|
||||
dtype: Data type for the encoding tensor.
|
||||
|
||||
Returns:
|
||||
Positional encoding tensor of shape (1, channels, D, H, W).
|
||||
"""
|
||||
org_channels = channels
|
||||
channels = int(math.ceil(channels / 6) * 2)
|
||||
if channels % 2:
|
||||
channels += 1
|
||||
inv_freq = 1.0 / (10000 ** (torch.arange(0, channels, 2, device=device).float() / channels))
|
||||
|
||||
def get_emb(sin_inp: torch.Tensor) -> torch.Tensor:
|
||||
emb = torch.stack((sin_inp.sin(), sin_inp.cos()), dim=-1)
|
||||
return torch.flatten(emb, -2, -1)
|
||||
|
||||
pos_x = torch.arange(D, device=device, dtype=inv_freq.dtype)
|
||||
pos_y = torch.arange(H, device=device, dtype=inv_freq.dtype)
|
||||
pos_z = torch.arange(W, device=device, dtype=inv_freq.dtype)
|
||||
sin_inp_x = torch.einsum("i,j->ij", pos_x, inv_freq)
|
||||
sin_inp_y = torch.einsum("i,j->ij", pos_y, inv_freq)
|
||||
sin_inp_z = torch.einsum("i,j->ij", pos_z, inv_freq)
|
||||
emb_x = get_emb(sin_inp_x).unsqueeze(1).unsqueeze(1)
|
||||
emb_y = get_emb(sin_inp_y).unsqueeze(1)
|
||||
emb_z = get_emb(sin_inp_z)
|
||||
emb = torch.zeros((D, H, W, channels * 3), device=device, dtype=dtype)
|
||||
emb[:, :, :, :channels] = emb_x
|
||||
emb[:, :, :, channels : 2 * channels] = emb_y
|
||||
emb[:, :, :, 2 * channels :] = emb_z
|
||||
|
||||
# Convert from (D, H, W, ch) to (1, ch, D, H, W) format (channel-first with batch dim)
|
||||
enc = emb[None, :, :, :, :org_channels] # (1, D, H, W, org_channels)
|
||||
enc = enc.permute(0, 4, 1, 2, 3) # (1, org_channels, D, H, W)
|
||||
return enc
|
||||
|
||||
|
||||
def convert_checkpoint(
|
||||
input_path: str,
|
||||
output_path: str,
|
||||
image_input_dims: tuple = (64, 5, 8),
|
||||
height_input_dims: tuple = (64, 7, 7),
|
||||
num_cameras: int = 1,
|
||||
force: bool = False,
|
||||
) -> None:
|
||||
"""Convert old checkpoint to new format.
|
||||
|
||||
Args:
|
||||
input_path: Path to the old checkpoint.
|
||||
output_path: Path to save the converted checkpoint.
|
||||
image_input_dims: Tuple of (C, H, W) for image input.
|
||||
height_input_dims: Tuple of (C, H, W) for height map input.
|
||||
num_cameras: Number of cameras (1 or 2).
|
||||
force: Force re-compute pos_encoding even if already in new format.
|
||||
"""
|
||||
print(f"Loading checkpoint from: {input_path}")
|
||||
checkpoint = torch.load(input_path, map_location="cpu", weights_only=False)
|
||||
|
||||
state_dict = checkpoint["model_state_dict"]
|
||||
|
||||
# Find old position_embedding keys to remove
|
||||
old_keys = [k for k in state_dict.keys() if "position_embedding.penc.inv_freq" in k]
|
||||
|
||||
# Check if new keys exist
|
||||
new_keys = [k for k in state_dict.keys() if ".pos_encoding" in k]
|
||||
|
||||
if not old_keys and not force:
|
||||
print("No old position_embedding keys found. Checkpoint may already be in new format.")
|
||||
if new_keys:
|
||||
print(f"Found new pos_encoding keys: {new_keys}")
|
||||
for k in new_keys:
|
||||
print(f" {k}: {state_dict[k].shape}")
|
||||
print("Checkpoint is already in new format. Use --force to re-compute pos_encoding.")
|
||||
return
|
||||
else:
|
||||
print("Warning: Neither old nor new positional encoding keys found!")
|
||||
return
|
||||
|
||||
if old_keys:
|
||||
print(f"Found {len(old_keys)} old position_embedding keys to convert:")
|
||||
for k in old_keys:
|
||||
print(f" - {k}")
|
||||
# Remove old keys
|
||||
for k in old_keys:
|
||||
del state_dict[k]
|
||||
|
||||
if new_keys and force:
|
||||
print(f"Force mode: Replacing {len(new_keys)} existing pos_encoding keys:")
|
||||
for k in new_keys:
|
||||
print(f" - {k}: {state_dict[k].shape}")
|
||||
# Remove existing pos_encoding keys to replace them
|
||||
for k in new_keys:
|
||||
del state_dict[k]
|
||||
|
||||
# Compute and add new positional encodings
|
||||
# For attn_image_net and attn_critic_image_net: spatial_dims = (num_cameras, H, W)
|
||||
# For attn_height_net: spatial_dims = (1, H, W)
|
||||
|
||||
image_channels = image_input_dims[0]
|
||||
height_channels = height_input_dims[0]
|
||||
|
||||
image_spatial_dims = (num_cameras, image_input_dims[1], image_input_dims[2])
|
||||
height_spatial_dims = (1, height_input_dims[1], height_input_dims[2])
|
||||
|
||||
print(f"\nComputing new positional encodings:")
|
||||
print(f" - image_input_dims: {image_input_dims}, num_cameras: {num_cameras}")
|
||||
print(f" - height_input_dims: {height_input_dims}")
|
||||
print(f" - image spatial_dims (D, H, W): {image_spatial_dims}")
|
||||
print(f" - height spatial_dims (D, H, W): {height_spatial_dims}")
|
||||
|
||||
# Compute positional encodings
|
||||
image_pos_enc = _compute_positional_encoding_3d(
|
||||
image_channels, *image_spatial_dims, torch.device("cpu"), torch.float32
|
||||
)
|
||||
height_pos_enc = _compute_positional_encoding_3d(
|
||||
height_channels, *height_spatial_dims, torch.device("cpu"), torch.float32
|
||||
)
|
||||
|
||||
print(f"\nNew positional encoding shapes:")
|
||||
print(f" - attn_image_net.pos_encoding: {image_pos_enc.shape}")
|
||||
print(f" - attn_height_net.pos_encoding: {height_pos_enc.shape}")
|
||||
print(f" - attn_critic_image_net.pos_encoding: {image_pos_enc.shape}")
|
||||
|
||||
# Add new keys
|
||||
state_dict["attn_image_net.pos_encoding"] = image_pos_enc
|
||||
state_dict["attn_height_net.pos_encoding"] = height_pos_enc
|
||||
state_dict["attn_critic_image_net.pos_encoding"] = image_pos_enc.clone()
|
||||
|
||||
# Save converted checkpoint
|
||||
print(f"\nSaving converted checkpoint to: {output_path}")
|
||||
torch.save(checkpoint, output_path)
|
||||
print("Conversion complete!")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Convert old policy checkpoints to new positional encoding structure."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--input", "-i",
|
||||
type=str,
|
||||
required=True,
|
||||
help="Path to the old checkpoint file."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output", "-o",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Path to save the converted checkpoint. If not specified, uses --inplace."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--inplace",
|
||||
action="store_true",
|
||||
help="Convert the checkpoint in-place (overwrite the input file)."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--image-dims",
|
||||
type=str,
|
||||
default="64,5,8",
|
||||
help="Image input dimensions as C,H,W (default: 64,5,8)."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--height-dims",
|
||||
type=str,
|
||||
default="64,7,7",
|
||||
help="Height input dimensions as C,H,W (default: 64,7,7)."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--num-cameras",
|
||||
type=int,
|
||||
default=1,
|
||||
help="Number of cameras (default: 1)."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--force",
|
||||
action="store_true",
|
||||
help="Force re-compute pos_encoding even if already in new format."
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
# Determine output path
|
||||
if args.output:
|
||||
output_path = args.output
|
||||
elif args.inplace:
|
||||
output_path = args.input
|
||||
else:
|
||||
# Default: add _converted suffix
|
||||
input_path = Path(args.input)
|
||||
output_path = str(input_path.parent / f"{input_path.stem}_converted{input_path.suffix}")
|
||||
|
||||
# Parse dimensions
|
||||
image_dims = tuple(int(x) for x in args.image_dims.split(","))
|
||||
height_dims = tuple(int(x) for x in args.height_dims.split(","))
|
||||
|
||||
if len(image_dims) != 3 or len(height_dims) != 3:
|
||||
raise ValueError("Dimensions must be specified as C,H,W (3 values)")
|
||||
|
||||
convert_checkpoint(
|
||||
input_path=args.input,
|
||||
output_path=output_path,
|
||||
image_input_dims=image_dims,
|
||||
height_input_dims=height_dims,
|
||||
num_cameras=args.num_cameras,
|
||||
force=args.force,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env python3
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Headless evaluator for a *TorchScript JIT* navigation policy.
|
||||
|
||||
Mirrors ``eval_terminations.py`` but instead of building an rsl_rl Runner and
|
||||
loading a ``model_*.pt`` checkpoint, it directly loads a JIT-scripted
|
||||
``ActorCriticSRU`` policy (e.g. the official upstream deployment policy
|
||||
``nav_policy_new.pt``) and rolls it out in the IsaacLab navigation env.
|
||||
|
||||
The JIT module exposes:
|
||||
forward(observations: Tensor, reset: bool=False) -> actions: Tensor
|
||||
with internal ``hidden_state`` / ``cell_state`` buffers sized
|
||||
``(num_layers, 1, hidden_size)``. We resize those buffers to
|
||||
``(num_layers, num_envs, hidden_size)`` after load so a single forward call
|
||||
handles all envs in parallel, and we per-env zero them on episode reset.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
|
||||
from isaaclab.app import AppLauncher
|
||||
|
||||
parser = argparse.ArgumentParser(description="Evaluate a JIT navigation policy.")
|
||||
parser.add_argument("--num_envs", type=int, default=32)
|
||||
parser.add_argument("--task", type=str, required=True, help="Gym task id (use a *-Play-v0 variant).")
|
||||
parser.add_argument("--jit_policy", type=str, required=True, help="In-container path to TorchScript .pt.")
|
||||
parser.add_argument("--steps", type=int, default=2000)
|
||||
parser.add_argument("--warmup", type=int, default=20)
|
||||
parser.add_argument("--seed", type=int, default=42)
|
||||
|
||||
AppLauncher.add_app_launcher_args(parser)
|
||||
args_cli, _ = parser.parse_known_args()
|
||||
args_cli.enable_cameras = True
|
||||
|
||||
app_launcher = AppLauncher(args_cli)
|
||||
simulation_app = app_launcher.app
|
||||
|
||||
import gymnasium as gym
|
||||
import torch
|
||||
|
||||
import isaaclab_tasks # noqa: F401
|
||||
import isaaclab_nav_task # noqa: F401
|
||||
|
||||
from isaaclab.envs import ManagerBasedRLEnvCfg
|
||||
from isaaclab_rl.rsl_rl import RslRlVecEnvWrapper
|
||||
|
||||
|
||||
def main():
|
||||
# ---- env setup ----
|
||||
spec = gym.spec(args_cli.task)
|
||||
env_cfg_class = spec.kwargs.get("env_cfg_entry_point")
|
||||
env_cfg: ManagerBasedRLEnvCfg = env_cfg_class()
|
||||
env_cfg.scene.num_envs = args_cli.num_envs
|
||||
|
||||
env = gym.make(args_cli.task, cfg=env_cfg, render_mode=None)
|
||||
env = RslRlVecEnvWrapper(env)
|
||||
device = env.unwrapped.device
|
||||
num_envs = args_cli.num_envs
|
||||
|
||||
# ---- policy load ----
|
||||
print(f"[eval-jit] loading JIT policy: {args_cli.jit_policy}")
|
||||
model = torch.jit.load(args_cli.jit_policy, map_location=device)
|
||||
model.eval()
|
||||
print(f"[eval-jit] model loaded; type={type(model).__name__}")
|
||||
|
||||
# Resize hidden state buffers from (num_layers, 1, hidden_size) to
|
||||
# (num_layers, num_envs, hidden_size). Works because ``rnn`` is a generic
|
||||
# LSTM-style cell that accepts any batch dim.
|
||||
h = model.hidden_state
|
||||
c = model.cell_state
|
||||
print(f"[eval-jit] original hidden_state shape: {tuple(h.shape)}")
|
||||
model.hidden_state = torch.zeros(h.shape[0], num_envs, h.shape[2], device=device, dtype=h.dtype)
|
||||
model.cell_state = torch.zeros(c.shape[0], num_envs, c.shape[2], device=device, dtype=c.dtype)
|
||||
print(f"[eval-jit] resized hidden_state shape: {tuple(model.hidden_state.shape)}")
|
||||
|
||||
# ---- termination accounting ----
|
||||
tm = env.unwrapped.termination_manager
|
||||
term_names = list(tm.active_terms)
|
||||
print(f"[eval-jit] active termination terms: {term_names}")
|
||||
counts = {name: 0 for name in term_names}
|
||||
counts["__any__"] = 0
|
||||
|
||||
# ---- rollout ----
|
||||
obs, _ = env.get_observations()
|
||||
prev_dones = torch.zeros(num_envs, dtype=torch.bool, device=device)
|
||||
step = 0
|
||||
while simulation_app.is_running() and step < args_cli.steps:
|
||||
# Zero hidden state for envs that just terminated (got reset internally
|
||||
# by IsaacLab at the start of this step's env.step()).
|
||||
if prev_dones.any():
|
||||
mask = prev_dones.to(torch.bool)
|
||||
# buffer shape: (num_layers, num_envs, hidden_size)
|
||||
model.hidden_state[:, mask, :] = 0
|
||||
model.cell_state[:, mask, :] = 0
|
||||
|
||||
with torch.inference_mode():
|
||||
actions = model(obs, False)
|
||||
obs, _, dones, _ = env.step(actions)
|
||||
|
||||
prev_dones = dones.to(torch.bool)
|
||||
|
||||
if step >= args_cli.warmup:
|
||||
for name in term_names:
|
||||
counts[name] += int(tm.get_term(name).sum().item())
|
||||
counts["__any__"] += int(env.unwrapped.termination_manager.dones.sum().item())
|
||||
step += 1
|
||||
|
||||
# ---- report ----
|
||||
total = counts["__any__"] if counts["__any__"] > 0 else 1
|
||||
print("\n" + "=" * 78)
|
||||
print(f"[eval-jit] steps counted = {args_cli.steps - args_cli.warmup}, num_envs = {num_envs}")
|
||||
print(f"[eval-jit] total terminations observed = {counts['__any__']}")
|
||||
print("\n TERM COUNT %-of-terms")
|
||||
print(" " + "-" * 50)
|
||||
for name in term_names:
|
||||
c_n = counts[name]
|
||||
pct = 100.0 * c_n / total
|
||||
marker = ""
|
||||
if name == "early_termination":
|
||||
marker = " <- success"
|
||||
elif name in ("base_contact", "large_pitch_angle"):
|
||||
marker = " <- collision/tipover"
|
||||
elif name == "terrain_fall":
|
||||
marker = " <- PIT FALL"
|
||||
elif name == "time_out":
|
||||
marker = " <- ran out of time"
|
||||
print(f" {name:<28} {c_n:>6} {pct:>5.1f}%{marker}")
|
||||
print("=" * 78)
|
||||
|
||||
env.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
simulation_app.close()
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
#!/usr/bin/env python3
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Headless termination-breakdown evaluator for a trained navigation policy.
|
||||
|
||||
Question this answers: *for a given checkpoint on a given task/difficulty,
|
||||
what fraction of episodes end via each termination reason* -- including the
|
||||
re-thresholded ``terrain_fall`` (now -0.3m for Go2) which is the only way to
|
||||
distinguish *fell into a pit* from *bumped a wall*.
|
||||
|
||||
The script mirrors ``play.py`` for env/policy setup, then counts the
|
||||
TerminationManager's per-term done flags across a fixed number of env steps.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
|
||||
from isaaclab.app import AppLauncher
|
||||
|
||||
parser = argparse.ArgumentParser(description="Evaluate termination breakdown for a navigation policy.")
|
||||
parser.add_argument("--num_envs", type=int, default=64, help="Number of parallel environments.")
|
||||
parser.add_argument("--task", type=str, default=None, help="Gym task id (use a *-Play-v0 variant).")
|
||||
parser.add_argument("--checkpoint", type=str, default=None, help="In-container path to model_*.pt.")
|
||||
parser.add_argument("--steps", type=int, default=2000, help="Number of env.step() calls.")
|
||||
parser.add_argument("--warmup", type=int, default=20, help="Steps to skip before counting (let resets settle).")
|
||||
parser.add_argument("--seed", type=int, default=42, help="Seed.")
|
||||
|
||||
AppLauncher.add_app_launcher_args(parser)
|
||||
args_cli, _ = parser.parse_known_args()
|
||||
args_cli.enable_cameras = True
|
||||
|
||||
app_launcher = AppLauncher(args_cli)
|
||||
simulation_app = app_launcher.app
|
||||
|
||||
import gymnasium as gym
|
||||
import torch
|
||||
|
||||
from rsl_rl.runners import OnPolicyRunner
|
||||
|
||||
import isaaclab_tasks # noqa: F401
|
||||
import isaaclab_nav_task # noqa: F401
|
||||
|
||||
from isaaclab.envs import ManagerBasedRLEnvCfg
|
||||
from isaaclab_rl.rsl_rl import RslRlOnPolicyRunnerCfg, RslRlVecEnvWrapper
|
||||
|
||||
|
||||
def main():
|
||||
spec = gym.spec(args_cli.task)
|
||||
env_cfg_class = spec.kwargs.get("env_cfg_entry_point")
|
||||
agent_cfg_class = spec.kwargs.get("rsl_rl_cfg_entry_point")
|
||||
|
||||
env_cfg: ManagerBasedRLEnvCfg = env_cfg_class()
|
||||
agent_cfg: RslRlOnPolicyRunnerCfg = agent_cfg_class()
|
||||
env_cfg.scene.num_envs = args_cli.num_envs
|
||||
|
||||
env = gym.make(args_cli.task, cfg=env_cfg, render_mode=None)
|
||||
env = RslRlVecEnvWrapper(env)
|
||||
|
||||
runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device)
|
||||
|
||||
if not args_cli.checkpoint:
|
||||
raise SystemExit("[eval] --checkpoint is required.")
|
||||
print(f"[eval] loading checkpoint: {args_cli.checkpoint}")
|
||||
loaded = torch.load(args_cli.checkpoint, map_location="cpu", weights_only=False)
|
||||
runner.alg.actor_critic.load_state_dict(loaded["model_state_dict"], strict=True)
|
||||
if runner.empirical_normalization:
|
||||
runner.obs_normalizer.load_state_dict(loaded["obs_norm_state_dict"])
|
||||
runner.critic_obs_normalizer.load_state_dict(loaded["critic_obs_norm_state_dict"])
|
||||
print(f"[eval] checkpoint iter = {loaded.get('iter', '?')}")
|
||||
|
||||
policy = runner.get_inference_policy(device=env.unwrapped.device)
|
||||
|
||||
# Termination manager exposes per-term done flags as torch tensors.
|
||||
tm = env.unwrapped.termination_manager
|
||||
term_names = list(tm.active_terms)
|
||||
print(f"[eval] active termination terms: {term_names}")
|
||||
|
||||
# Per-term running counters (number of envs that ended via this reason).
|
||||
counts = {name: 0 for name in term_names}
|
||||
counts["__any__"] = 0 # any termination (sanity)
|
||||
|
||||
# Print the relevant cfg knobs so the run is self-documenting.
|
||||
try:
|
||||
tf_params = env_cfg.terminations.terrain_fall.params
|
||||
print(f"[eval] terrain_fall.fall_height_threshold = "
|
||||
f"{tf_params.get('fall_height_threshold', 'default')}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
obs, _ = env.get_observations()
|
||||
step = 0
|
||||
while simulation_app.is_running() and step < args_cli.steps:
|
||||
with torch.inference_mode():
|
||||
actions = policy(obs)
|
||||
obs, _, _, _ = env.step(actions)
|
||||
|
||||
if step >= args_cli.warmup:
|
||||
# Each per-term tensor is bool[num_envs]; sum gives this-step count.
|
||||
for name in term_names:
|
||||
term_tensor = tm.get_term(name)
|
||||
counts[name] += int(term_tensor.sum().item())
|
||||
# Any-termination flag (rsl_rl wrapper resets on time_out OR done).
|
||||
any_done = env.unwrapped.termination_manager.dones
|
||||
counts["__any__"] += int(any_done.sum().item())
|
||||
step += 1
|
||||
|
||||
# -------- summarise --------
|
||||
total = counts["__any__"] if counts["__any__"] > 0 else 1
|
||||
print("\n" + "=" * 78)
|
||||
print(f"[eval] steps counted = {args_cli.steps - args_cli.warmup}, num_envs = {args_cli.num_envs}")
|
||||
print(f"[eval] total terminations observed = {counts['__any__']}")
|
||||
print("\n TERM COUNT %-of-terms")
|
||||
print(" " + "-" * 50)
|
||||
for name in term_names:
|
||||
c = counts[name]
|
||||
pct = 100.0 * c / total
|
||||
marker = ""
|
||||
if name == "early_termination":
|
||||
marker = " <- success"
|
||||
elif name in ("base_contact", "large_pitch_angle"):
|
||||
marker = " <- collision/tipover"
|
||||
elif name == "terrain_fall":
|
||||
marker = " <- PIT FALL (with new threshold)"
|
||||
elif name == "time_out":
|
||||
marker = " <- ran out of time"
|
||||
print(f" {name:<28} {c:>6} {pct:>5.1f}%{marker}")
|
||||
print("=" * 78)
|
||||
|
||||
env.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
simulation_app.close()
|
||||
@@ -0,0 +1,277 @@
|
||||
#!/usr/bin/env python3
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Play a trained navigation policy (PPO/MDPO) with automatic checkpoint loading.
|
||||
|
||||
Usage:
|
||||
python scripts/play.py --task <task_name> [options]
|
||||
|
||||
Arguments:
|
||||
--task Task name (required, typically *-Play-v0 variant)
|
||||
--checkpoint Path to model checkpoint (.pt file)
|
||||
--use_last_checkpoint Use latest checkpoint from logs (default behavior)
|
||||
--num_envs Number of parallel environments
|
||||
--video Enable video recording
|
||||
--video_length Video length in steps (default: 200)
|
||||
|
||||
Examples:
|
||||
python scripts/play.py --task Isaac-Navigation-B2W-Play-v0
|
||||
python scripts/play.py --task Isaac-Navigation-B2W-Play-v0 --checkpoint path/to/model.pt
|
||||
python scripts/play.py --task Isaac-Navigation-B2W-Play-v0 --video --num_envs 16
|
||||
|
||||
Note: Automatically finds latest checkpoint if --checkpoint not specified.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
from isaaclab.app import AppLauncher
|
||||
|
||||
# Add argparse arguments
|
||||
parser = argparse.ArgumentParser(description="Play a trained navigation policy with RSL-RL.")
|
||||
parser.add_argument("--video", action="store_true", default=False, help="Record videos during play.")
|
||||
parser.add_argument("--video_length", type=int, default=200, help="Length of the recorded video (in steps).")
|
||||
parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.")
|
||||
parser.add_argument("--task", type=str, default=None, help="Name of the task.")
|
||||
parser.add_argument("--checkpoint", type=str, default=None, help="Path to model checkpoint.")
|
||||
parser.add_argument("--use_last_checkpoint", action="store_true", help="Use last checkpoint from logs.")
|
||||
parser.add_argument("--export_jit", action="store_true", default=False, help="Export policy as JIT module.")
|
||||
parser.add_argument("--export_onnx", action="store_true", default=False, help="Export policy as ONNX model.")
|
||||
|
||||
# Append AppLauncher cli args
|
||||
AppLauncher.add_app_launcher_args(parser)
|
||||
args_cli, hydra_args = parser.parse_known_args()
|
||||
|
||||
# Always enable cameras
|
||||
args_cli.enable_cameras = True
|
||||
|
||||
# Launch simulation
|
||||
app_launcher = AppLauncher(args_cli)
|
||||
simulation_app = app_launcher.app
|
||||
|
||||
# Import after launching simulation
|
||||
import gymnasium as gym
|
||||
import os
|
||||
import re
|
||||
import torch
|
||||
|
||||
from rsl_rl.runners import OnPolicyRunner
|
||||
|
||||
# Import Isaac Lab extensions
|
||||
import isaaclab_tasks # noqa: F401
|
||||
import isaaclab_nav_task # noqa: F401
|
||||
|
||||
from isaaclab.envs import ManagerBasedRLEnvCfg
|
||||
from isaaclab_rl.rsl_rl import RslRlOnPolicyRunnerCfg, RslRlVecEnvWrapper, export_policy_as_onnx
|
||||
|
||||
|
||||
def find_latest_checkpoint(log_path: str, checkpoint_pattern: str = "model_.*.pt") -> str:
|
||||
"""Find the latest checkpoint file in the log directory.
|
||||
|
||||
Args:
|
||||
log_path: Base log directory path
|
||||
checkpoint_pattern: Regex pattern for checkpoint files
|
||||
|
||||
Returns:
|
||||
Path to the latest checkpoint file
|
||||
"""
|
||||
# Find all run directories
|
||||
if not os.path.exists(log_path):
|
||||
raise ValueError(f"Log path does not exist: {log_path}")
|
||||
|
||||
run_dirs = []
|
||||
for entry in os.scandir(log_path):
|
||||
if entry.is_dir() and re.match(r"\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}", entry.name):
|
||||
run_dirs.append(entry.name)
|
||||
|
||||
if not run_dirs:
|
||||
raise ValueError(f"No run directories found in: {log_path}")
|
||||
|
||||
# Sort to get latest run
|
||||
run_dirs.sort()
|
||||
latest_run = run_dirs[-1]
|
||||
run_path = os.path.join(log_path, latest_run)
|
||||
|
||||
# Find checkpoint files
|
||||
checkpoint_files = []
|
||||
for f in os.listdir(run_path):
|
||||
if re.match(checkpoint_pattern, f):
|
||||
checkpoint_files.append(f)
|
||||
|
||||
if not checkpoint_files:
|
||||
raise ValueError(f"No checkpoint files matching '{checkpoint_pattern}' found in: {run_path}")
|
||||
|
||||
# Sort to get latest checkpoint
|
||||
checkpoint_files.sort(key=lambda m: f"{m:0>15}")
|
||||
latest_checkpoint = checkpoint_files[-1]
|
||||
|
||||
return os.path.join(run_path, latest_checkpoint)
|
||||
|
||||
|
||||
def load_checkpoint_with_fallback(runner: OnPolicyRunner, checkpoint_path: str, load_optimizer: bool = True):
|
||||
"""Load checkpoint with fallback for PyTorch compatibility issues.
|
||||
|
||||
Args:
|
||||
runner: RSL-RL runner instance
|
||||
checkpoint_path: Path to checkpoint file
|
||||
load_optimizer: Whether to load optimizer state
|
||||
"""
|
||||
print(f"[INFO] Loading checkpoint from: {checkpoint_path}")
|
||||
|
||||
# Load checkpoint to CPU first for compatibility
|
||||
loaded_dict = torch.load(checkpoint_path, map_location='cpu', weights_only=False)
|
||||
|
||||
# Load model state - handle both standard algorithms (PPO) and MDPO
|
||||
if runner.is_mdpo:
|
||||
# MDPO uses two actor-critics, load same state into both
|
||||
runner.alg.actor_critic_1.load_state_dict(loaded_dict["model_state_dict"], strict=True)
|
||||
runner.alg.actor_critic_2.load_state_dict(loaded_dict["model_state_dict"], strict=True)
|
||||
else:
|
||||
# Standard algorithms use one actor-critic
|
||||
runner.alg.actor_critic.load_state_dict(loaded_dict["model_state_dict"], strict=True)
|
||||
|
||||
# Load normalizers if using empirical normalization
|
||||
if runner.empirical_normalization:
|
||||
runner.obs_normalizer.load_state_dict(loaded_dict["obs_norm_state_dict"])
|
||||
runner.critic_obs_normalizer.load_state_dict(loaded_dict["critic_obs_norm_state_dict"])
|
||||
|
||||
# Load optimizer if requested
|
||||
if load_optimizer:
|
||||
if runner.is_mdpo:
|
||||
runner.alg.optimizer_1.load_state_dict(loaded_dict["optimizer_state_dict"])
|
||||
else:
|
||||
runner.alg.optimizer.load_state_dict(loaded_dict["optimizer_state_dict"])
|
||||
|
||||
runner.current_learning_iteration = loaded_dict["iter"]
|
||||
print(f"[INFO] Loaded checkpoint from iteration {loaded_dict['iter']}")
|
||||
|
||||
|
||||
def export_policy_jit(runner: OnPolicyRunner, checkpoint_path: str):
|
||||
"""Export policy as JIT module to an 'export' folder next to the checkpoint.
|
||||
|
||||
Args:
|
||||
runner: RSL-RL runner instance with loaded policy
|
||||
checkpoint_path: Path to the checkpoint file (used to determine export location)
|
||||
"""
|
||||
# Determine export directory (create 'export' folder in the same directory as checkpoint)
|
||||
checkpoint_dir = os.path.dirname(checkpoint_path)
|
||||
export_dir = os.path.join(checkpoint_dir, "export")
|
||||
|
||||
# Get the actor-critic module
|
||||
if runner.is_mdpo:
|
||||
actor_critic = runner.alg.actor_critic_1
|
||||
else:
|
||||
actor_critic = runner.alg.actor_critic
|
||||
|
||||
# Get normalizer if using empirical normalization
|
||||
normalizer = runner.obs_normalizer if runner.empirical_normalization else None
|
||||
|
||||
# Export using the module's export_jit method
|
||||
print(f"[INFO] Exporting JIT policy to: {export_dir}")
|
||||
actor_critic.export_jit(path=export_dir, filename="policy.pt", normalizer=normalizer)
|
||||
print(f"[INFO] JIT export complete!")
|
||||
|
||||
|
||||
def export_policy_onnx(runner: OnPolicyRunner, checkpoint_path: str):
|
||||
"""Export policy as ONNX model to an 'export' folder next to the checkpoint.
|
||||
|
||||
Args:
|
||||
runner: RSL-RL runner instance with loaded policy
|
||||
checkpoint_path: Path to the checkpoint file (used to determine export location)
|
||||
"""
|
||||
# Determine export directory (create 'export' folder in the same directory as checkpoint)
|
||||
checkpoint_dir = os.path.dirname(checkpoint_path)
|
||||
export_dir = os.path.join(checkpoint_dir, "export")
|
||||
|
||||
# Get the actor-critic module
|
||||
if runner.is_mdpo:
|
||||
actor_critic = runner.alg.actor_critic_1
|
||||
else:
|
||||
actor_critic = runner.alg.actor_critic
|
||||
|
||||
# Get normalizer if using empirical normalization
|
||||
normalizer = runner.obs_normalizer if runner.empirical_normalization else None
|
||||
|
||||
# Check if the module has export_onnx method
|
||||
if not hasattr(actor_critic, "export_onnx"):
|
||||
raise NotImplementedError(
|
||||
f"ONNX export not implemented for {type(actor_critic).__name__}. "
|
||||
"Please add an export_onnx method to this module."
|
||||
)
|
||||
|
||||
# Export using the module's export_onnx method
|
||||
print(f"[INFO] Exporting ONNX policy to: {export_dir}")
|
||||
actor_critic.export_onnx(path=export_dir, filename="policy.onnx", normalizer=normalizer)
|
||||
print(f"[INFO] ONNX export complete!")
|
||||
|
||||
|
||||
def main():
|
||||
"""Play navigation policy with RSL-RL."""
|
||||
# Parse command-line arguments
|
||||
spec = gym.spec(args_cli.task)
|
||||
env_cfg_class = spec.kwargs.get("env_cfg_entry_point")
|
||||
agent_cfg_class = spec.kwargs.get("rsl_rl_cfg_entry_point")
|
||||
|
||||
# Instantiate the configs
|
||||
env_cfg: ManagerBasedRLEnvCfg = env_cfg_class()
|
||||
agent_cfg: RslRlOnPolicyRunnerCfg = agent_cfg_class()
|
||||
|
||||
# Override config from command line
|
||||
if args_cli.num_envs is not None:
|
||||
env_cfg.scene.num_envs = args_cli.num_envs
|
||||
|
||||
# Create the environment
|
||||
env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None)
|
||||
# Wrap the environment
|
||||
env = RslRlVecEnvWrapper(env)
|
||||
|
||||
# Get checkpoint path
|
||||
if args_cli.checkpoint:
|
||||
resume_path = args_cli.checkpoint
|
||||
else:
|
||||
# Get last checkpoint from log directory
|
||||
log_root_path = os.path.join("logs", "rsl_rl", agent_cfg.experiment_name)
|
||||
resume_path = find_latest_checkpoint(log_root_path, checkpoint_pattern="model_.*.pt")
|
||||
|
||||
# Create runner
|
||||
runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device)
|
||||
|
||||
# Load checkpoint with compatibility handling
|
||||
load_checkpoint_with_fallback(runner, resume_path)
|
||||
|
||||
# Export JIT if requested
|
||||
if args_cli.export_jit:
|
||||
export_policy_jit(runner, resume_path)
|
||||
|
||||
# Export ONNX if requested
|
||||
if args_cli.export_onnx:
|
||||
export_policy_onnx(runner, resume_path)
|
||||
|
||||
# Obtain policy for inference
|
||||
policy = runner.get_inference_policy(device=env.unwrapped.device)
|
||||
|
||||
# Reset environment
|
||||
obs, _ = env.get_observations()
|
||||
|
||||
# Simulate environment
|
||||
while simulation_app.is_running():
|
||||
# Run policy
|
||||
with torch.inference_mode():
|
||||
actions = policy(obs)
|
||||
# Step environment
|
||||
obs, _, _, _ = env.step(actions)
|
||||
|
||||
# Close the environment
|
||||
env.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Run the main function
|
||||
main()
|
||||
# Close simulation
|
||||
simulation_app.close()
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Render figures from a collisions.npz produced by analyze_collisions.py.
|
||||
|
||||
Run on the *host* (matplotlib only, no Isaac). Writes PNGs next to the .npz.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import argparse, os
|
||||
import numpy as np
|
||||
import matplotlib
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("npz", help="Path to collisions.npz")
|
||||
args = ap.parse_args()
|
||||
|
||||
d = np.load(args.npz)
|
||||
out_dir = os.path.dirname(os.path.abspath(args.npz))
|
||||
|
||||
thr = float(d["threshold"])
|
||||
ep_w = float(d["ep_term_weight"])
|
||||
K = int(d["K"])
|
||||
n_coll = int(d["n_collisions"])
|
||||
n_succ = int(d["n_success"])
|
||||
n_to = int(d["n_timeout"])
|
||||
|
||||
impact_vel = d["impact_vel"]
|
||||
impact_speed = d["impact_speed"]
|
||||
impact_force = d["impact_force"]
|
||||
traj_vel = d["traj_vel"]
|
||||
traj_speed = d["traj_speed"]
|
||||
traj_force = d["traj_force"]
|
||||
all_vel = d["all_vel"]
|
||||
all_force = d["all_force"]
|
||||
|
||||
# ===== Fig 1: impact velocity histogram =====
|
||||
fig, axes = plt.subplots(1, 2, figsize=(12, 4.5))
|
||||
|
||||
ax = axes[0]
|
||||
if impact_vel.size > 0:
|
||||
ax.hist(impact_vel, bins=40, color="#d9534f", alpha=0.85, edgecolor="white")
|
||||
ax.axvline(impact_vel.mean(), color="black", ls="--", lw=1.5,
|
||||
label=f"mean = {impact_vel.mean():+.2f} m/s")
|
||||
ax.axvline(0.0, color="gray", ls=":", lw=1)
|
||||
ax.set_xlabel("body-frame forward velocity at impact (m/s)")
|
||||
ax.set_ylabel("# collisions")
|
||||
ax.set_title(f"Velocity at collision (n={impact_vel.size})")
|
||||
ax.legend()
|
||||
ax.grid(alpha=0.3)
|
||||
|
||||
ax = axes[1]
|
||||
if impact_speed.size > 0:
|
||||
ax.hist(impact_speed, bins=40, color="#5bc0de", alpha=0.85, edgecolor="white")
|
||||
ax.axvline(impact_speed.mean(), color="black", ls="--", lw=1.5,
|
||||
label=f"mean = {impact_speed.mean():.2f} m/s")
|
||||
ax.axvline(0.2, color="orange", ls=":", lw=1, label="0.2 m/s (slow-impact cutoff)")
|
||||
ax.set_xlabel("planar speed |v_xy| at impact (m/s)")
|
||||
ax.set_ylabel("# collisions")
|
||||
ax.set_title("Planar speed at collision")
|
||||
ax.legend()
|
||||
ax.grid(alpha=0.3)
|
||||
fig.tight_layout()
|
||||
fig.savefig(os.path.join(out_dir, "fig1_impact_velocity.png"), dpi=130)
|
||||
plt.close(fig)
|
||||
|
||||
# ===== Fig 2: contact force histogram (log scale) with threshold =====
|
||||
fig, ax = plt.subplots(figsize=(8, 5))
|
||||
if impact_force.size > 0:
|
||||
bins = np.logspace(np.log10(max(thr * 0.5, 0.5)),
|
||||
np.log10(max(impact_force.max() * 1.2, thr * 10)), 50)
|
||||
ax.hist(impact_force, bins=bins, color="#f0ad4e", alpha=0.85, edgecolor="white",
|
||||
label=f"impact peak force (n={impact_force.size})")
|
||||
ax.axvline(thr, color="red", ls="--", lw=2, label=f"training threshold = {thr:.1f} N")
|
||||
ax.axvline(np.median(impact_force), color="black", ls=":", lw=1.5,
|
||||
label=f"median impact = {np.median(impact_force):.0f} N "
|
||||
f"({np.median(impact_force)/thr:.0f}× thr)")
|
||||
ax.set_xscale("log")
|
||||
ax.set_xlabel("peak contact force on (base, hip, thigh) at impact (N, log)")
|
||||
ax.set_ylabel("# collisions")
|
||||
ax.set_title("Impact force vs training termination threshold")
|
||||
ax.legend()
|
||||
ax.grid(alpha=0.3, which="both")
|
||||
fig.tight_layout()
|
||||
fig.savefig(os.path.join(out_dir, "fig2_impact_force.png"), dpi=130)
|
||||
plt.close(fig)
|
||||
|
||||
# ===== Fig 3: pre-impact trajectory (median + IQR) =====
|
||||
if traj_vel.shape[0] > 0:
|
||||
steps = np.arange(-K + 1, 1)
|
||||
fig, axes = plt.subplots(1, 2, figsize=(12, 4.5), sharex=True)
|
||||
|
||||
for ax, data, ylabel, title, color in [
|
||||
(axes[0], traj_speed, "planar speed |v_xy| (m/s)", "Speed leading up to collision", "#5bc0de"),
|
||||
(axes[1], traj_force, "peak contact force (N)", "Force leading up to collision", "#f0ad4e"),
|
||||
]:
|
||||
med = np.median(data, axis=0)
|
||||
p25 = np.percentile(data, 25, axis=0)
|
||||
p75 = np.percentile(data, 75, axis=0)
|
||||
ax.fill_between(steps, p25, p75, color=color, alpha=0.35, label="IQR (25-75%)")
|
||||
ax.plot(steps, med, color=color, lw=2.2, label="median")
|
||||
ax.axvline(0, color="red", ls="--", lw=1.5, label="impact step")
|
||||
ax.set_xlabel("env-step relative to impact")
|
||||
ax.set_ylabel(ylabel)
|
||||
ax.set_title(f"{title} (n={data.shape[0]})")
|
||||
ax.legend()
|
||||
ax.grid(alpha=0.3)
|
||||
if axes[1].get_ylim()[1] > 5 * thr:
|
||||
axes[1].set_yscale("symlog", linthresh=max(thr, 1.0))
|
||||
axes[1].axhline(thr, color="red", ls=":", lw=1)
|
||||
fig.tight_layout()
|
||||
fig.savefig(os.path.join(out_dir, "fig3_pre_impact.png"), dpi=130)
|
||||
plt.close(fig)
|
||||
|
||||
# ===== Fig 4: global v_fwd distribution (alive steps) vs at-impact =====
|
||||
fig, ax = plt.subplots(figsize=(8, 5))
|
||||
if all_vel.size > 0:
|
||||
ax.hist(all_vel, bins=60, density=True, color="#5cb85c", alpha=0.55,
|
||||
edgecolor="white", label=f"alive steps (n={all_vel.size})")
|
||||
if impact_vel.size > 0:
|
||||
ax.hist(impact_vel, bins=40, density=True, color="#d9534f", alpha=0.55,
|
||||
edgecolor="white", label=f"at impact (n={impact_vel.size})")
|
||||
ax.axvline(0, color="gray", ls=":", lw=1)
|
||||
ax.set_xlabel("body-frame forward velocity v_fwd (m/s)")
|
||||
ax.set_ylabel("density")
|
||||
ax.set_title("Forward velocity: normal navigation vs at collision")
|
||||
ax.legend()
|
||||
ax.grid(alpha=0.3)
|
||||
fig.tight_layout()
|
||||
fig.savefig(os.path.join(out_dir, "fig4_vfwd_normal_vs_impact.png"), dpi=130)
|
||||
plt.close(fig)
|
||||
|
||||
# ===== short text summary =====
|
||||
lines = []
|
||||
lines.append(f"threshold = {thr} N ep_term_w = {ep_w}")
|
||||
lines.append(f"terminations: success={n_succ} collision={n_coll} timeout={n_to}")
|
||||
if impact_force.size > 0:
|
||||
lines.append(f"impact force: median {np.median(impact_force):.1f} N "
|
||||
f"({np.median(impact_force)/thr:.0f}x threshold), "
|
||||
f"p90 {np.percentile(impact_force,90):.1f}, max {impact_force.max():.1f}")
|
||||
if impact_speed.size > 0:
|
||||
slow = (impact_speed < 0.2).mean() * 100
|
||||
fast = (impact_speed > 0.8).mean() * 100
|
||||
lines.append(f"impact |v_xy|: median {np.median(impact_speed):.2f} m/s "
|
||||
f"slow<0.2: {slow:.0f}% fast>0.8: {fast:.0f}%")
|
||||
print("\n".join(lines))
|
||||
print(f"\nfigures saved into: {out_dir}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,150 @@
|
||||
#!/usr/bin/env python3
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Train a navigation policy using RSL-RL (PPO/MDPO algorithms).
|
||||
|
||||
Usage:
|
||||
python scripts/train.py --task <task_name> --num_envs <num> [options]
|
||||
|
||||
Arguments:
|
||||
--task Task name (required)
|
||||
--num_envs Number of parallel environments
|
||||
--seed Random seed
|
||||
--max_iterations Training iterations
|
||||
--run_name Custom run name for logging
|
||||
--video Enable video recording
|
||||
--video_length Video length in steps (default: 200)
|
||||
--video_interval Recording interval in steps (default: 2000)
|
||||
|
||||
Examples:
|
||||
python scripts/train.py --task Isaac-Navigation-B2W-v0 --num_envs 2048
|
||||
python scripts/train.py --task Isaac-Navigation-B2W-v0 --video --seed 42
|
||||
|
||||
Logs saved to: logs/rsl_rl/<experiment_name>/<timestamp>/
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
# Add the parent directory to the path so we can import from the extension
|
||||
from isaaclab.app import AppLauncher
|
||||
|
||||
# Add argparse arguments
|
||||
parser = argparse.ArgumentParser(description="Train a navigation policy with RSL-RL.")
|
||||
parser.add_argument("--video", action="store_true", default=False, help="Record videos during training.")
|
||||
parser.add_argument("--video_length", type=int, default=200, help="Length of the recorded video (in steps).")
|
||||
parser.add_argument("--video_interval", type=int, default=2000, help="Interval between video recordings (in steps).")
|
||||
parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.")
|
||||
parser.add_argument("--task", type=str, default=None, help="Name of the task.")
|
||||
parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment")
|
||||
parser.add_argument("--max_iterations", type=int, default=None, help="RL Policy training iterations.")
|
||||
parser.add_argument("--run_name", type=str, default=None, help="Name of the wandb run (appended to log directory).")
|
||||
parser.add_argument("--checkpoint", type=str, default=None, help="Path to a checkpoint (.pt) to warm-start from before training begins.")
|
||||
parser.add_argument("--load_optimizer", action="store_true", default=False, help="Also load the optimizer state from the checkpoint (default: only load model weights, recommended for cross-robot warm-start).")
|
||||
|
||||
# Append AppLauncher cli args
|
||||
AppLauncher.add_app_launcher_args(parser)
|
||||
args_cli, hydra_args = parser.parse_known_args()
|
||||
|
||||
# always enable cameras to record video
|
||||
if args_cli.video:
|
||||
args_cli.enable_cameras = True
|
||||
|
||||
# Launch simulation
|
||||
app_launcher = AppLauncher(args_cli)
|
||||
simulation_app = app_launcher.app
|
||||
|
||||
# Import after launching simulation
|
||||
import gymnasium as gym
|
||||
import os
|
||||
import torch
|
||||
from datetime import datetime
|
||||
|
||||
from rsl_rl.runners import OnPolicyRunner
|
||||
|
||||
# Import Isaac Lab extensions
|
||||
import isaaclab_tasks # noqa: F401
|
||||
import isaaclab_nav_task # noqa: F401
|
||||
|
||||
from isaaclab.envs import ManagerBasedRLEnvCfg
|
||||
from isaaclab.utils.dict import print_dict
|
||||
from isaaclab.utils.io import dump_pickle, dump_yaml
|
||||
from isaaclab_tasks.utils import get_checkpoint_path
|
||||
from isaaclab_tasks.utils.parse_cfg import load_cfg_from_registry
|
||||
from isaaclab_rl.rsl_rl import RslRlOnPolicyRunnerCfg, RslRlVecEnvWrapper
|
||||
|
||||
# Set torch backends for better performance
|
||||
torch.backends.cuda.matmul.allow_tf32 = True
|
||||
torch.backends.cudnn.allow_tf32 = True
|
||||
torch.backends.cudnn.deterministic = False
|
||||
torch.backends.cudnn.benchmark = False
|
||||
|
||||
|
||||
def main():
|
||||
"""Train navigation policy with RSL-RL."""
|
||||
# Load the configurations from the registry
|
||||
env_cfg = load_cfg_from_registry(args_cli.task, "env_cfg_entry_point")
|
||||
agent_cfg: RslRlOnPolicyRunnerCfg = load_cfg_from_registry(args_cli.task, "rsl_rl_cfg_entry_point")
|
||||
|
||||
# Override config from command line
|
||||
if args_cli.num_envs is not None:
|
||||
env_cfg.scene.num_envs = args_cli.num_envs
|
||||
if args_cli.seed is not None:
|
||||
agent_cfg.seed = args_cli.seed
|
||||
if args_cli.max_iterations is not None:
|
||||
agent_cfg.max_iterations = args_cli.max_iterations
|
||||
if args_cli.run_name is not None:
|
||||
agent_cfg.run_name = args_cli.run_name
|
||||
|
||||
# Create the environment
|
||||
env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None)
|
||||
# Wrap the environment
|
||||
env = RslRlVecEnvWrapper(env)
|
||||
|
||||
# Specify log directory
|
||||
log_root_path = os.path.join("logs", "rsl_rl", agent_cfg.experiment_name)
|
||||
log_root_path = os.path.abspath(log_root_path)
|
||||
print(f"[INFO] Logging experiment in directory: {log_root_path}")
|
||||
# Specify run directory based on timestamp
|
||||
log_dir = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
||||
if agent_cfg.run_name:
|
||||
log_dir += f"_{agent_cfg.run_name}"
|
||||
log_dir = os.path.join(log_root_path, log_dir)
|
||||
|
||||
# Create runner
|
||||
runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=log_dir, device=agent_cfg.device)
|
||||
|
||||
# Optional: warm-start from an existing checkpoint (e.g. cross-robot fine-tuning).
|
||||
if args_cli.checkpoint is not None:
|
||||
ckpt_path = os.path.abspath(args_cli.checkpoint)
|
||||
if not os.path.isfile(ckpt_path):
|
||||
raise FileNotFoundError(f"Checkpoint not found: {ckpt_path}")
|
||||
print(f"[INFO] Warm-starting from checkpoint: {ckpt_path}")
|
||||
print(f"[INFO] load_optimizer = {args_cli.load_optimizer}")
|
||||
runner.load(ckpt_path, load_optimizer=args_cli.load_optimizer)
|
||||
|
||||
# Write git state to log
|
||||
runner.add_git_repo_to_log(__file__)
|
||||
# Save configuration
|
||||
dump_yaml(os.path.join(log_dir, "params", "env.yaml"), env_cfg)
|
||||
dump_yaml(os.path.join(log_dir, "params", "agent.yaml"), agent_cfg)
|
||||
dump_pickle(os.path.join(log_dir, "params", "env.pkl"), env_cfg)
|
||||
dump_pickle(os.path.join(log_dir, "params", "agent.pkl"), agent_cfg)
|
||||
|
||||
# Run training
|
||||
runner.learn(num_learning_iterations=agent_cfg.max_iterations, init_at_random_ep_len=True)
|
||||
|
||||
# Close the environment
|
||||
env.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Run the main function
|
||||
main()
|
||||
# Close simulation
|
||||
simulation_app.close()
|
||||
@@ -0,0 +1,65 @@
|
||||
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
|
||||
# All rights reserved.
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
"""Installation script for the 'isaaclab_nav_task' python package.
|
||||
|
||||
IsaacLab task extension for SRU (Spatially-enhanced Recurrent Unit) visual navigation project.
|
||||
Provides hierarchical control architecture, maze terrain generation with curriculum learning,
|
||||
and depth-based reinforcement learning for legged robot navigation.
|
||||
"""
|
||||
|
||||
import os
|
||||
import toml
|
||||
|
||||
from setuptools import setup
|
||||
|
||||
# Obtain the extension data from the extension.toml file
|
||||
EXTENSION_PATH = os.path.dirname(os.path.realpath(__file__))
|
||||
# Read the extension.toml file
|
||||
EXTENSION_TOML_DATA = toml.load(os.path.join(EXTENSION_PATH, "config", "extension.toml"))
|
||||
|
||||
# Minimum dependencies required prior to installation
|
||||
INSTALL_REQUIRES = [
|
||||
# generic
|
||||
"numpy<2",
|
||||
"torch>=2.5.1",
|
||||
"torchvision>=0.14.1",
|
||||
# io
|
||||
"h5py",
|
||||
# visualization
|
||||
"tensorboard",
|
||||
]
|
||||
|
||||
PYTORCH_INDEX_URL = ["https://download.pytorch.org/whl/cu128"]
|
||||
|
||||
# Installation operation
|
||||
setup(
|
||||
name="isaaclab_nav_task",
|
||||
author="Fan Yang, Per Frivik",
|
||||
author_email="[email protected], [email protected]",
|
||||
maintainer="Fan Yang, Per Frivik",
|
||||
maintainer_email="[email protected], [email protected]",
|
||||
url=EXTENSION_TOML_DATA["package"]["repository"],
|
||||
version=EXTENSION_TOML_DATA["package"]["version"],
|
||||
description=EXTENSION_TOML_DATA["package"]["description"],
|
||||
keywords=EXTENSION_TOML_DATA["package"]["keywords"],
|
||||
include_package_data=True,
|
||||
python_requires=">=3.10",
|
||||
install_requires=INSTALL_REQUIRES,
|
||||
dependency_links=PYTORCH_INDEX_URL,
|
||||
packages=["isaaclab_nav_task"],
|
||||
classifiers=[
|
||||
"Natural Language :: English",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Isaac Sim :: 4.5.0",
|
||||
"Isaac Lab :: 2.1.1",
|
||||
"License :: OSI Approved :: MIT License",
|
||||
"Intended Audience :: Science/Research",
|
||||
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
||||
"Topic :: Scientific/Engineering :: Robotics",
|
||||
],
|
||||
zip_safe=False,
|
||||
license="MIT",
|
||||
)
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
#!/usr/bin/env bash
|
||||
# Depth-ablation diagnostic: does the trained Go2 policy actually USE the depth
|
||||
# camera, or has it learned to ignore it (perception-blind)?
|
||||
#
|
||||
# Runs headless inside the container, rolls out the policy, and compares the
|
||||
# action with vs without the depth slice zeroed. Prints a verdict.
|
||||
#
|
||||
# Examples:
|
||||
# # Latest run, latest checkpoint
|
||||
# ./scripts/ablate_depth.sh
|
||||
#
|
||||
# # Specific run + iter
|
||||
# ./scripts/ablate_depth.sh --run-dir 2026-06-16_09-24-44_phase2 --from-iter 6998
|
||||
#
|
||||
# # More steps / envs for tighter stats
|
||||
# ./scripts/ablate_depth.sh --from-iter 6998 --envs 32 --steps 400
|
||||
set -euo pipefail
|
||||
|
||||
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
|
||||
# ---- defaults ----
|
||||
TASK="Isaac-Nav-PPO-Go2-Play-v0"
|
||||
EXPERIMENT="go2_navigation_ppo_dev"
|
||||
NUM_ENVS=16
|
||||
STEPS=300
|
||||
FROM_ITER=""
|
||||
RUN_DIR=""
|
||||
CHECKPOINT=""
|
||||
SEED=42
|
||||
|
||||
usage() { sed -n '1,18p' "$0"; exit 0; }
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--from-iter) FROM_ITER="$2"; shift 2 ;;
|
||||
--run-dir) RUN_DIR="$2"; shift 2 ;;
|
||||
--checkpoint) CHECKPOINT="$2"; shift 2 ;;
|
||||
--task) TASK="$2"; shift 2 ;;
|
||||
--experiment) EXPERIMENT="$2"; shift 2 ;;
|
||||
--envs) NUM_ENVS="$2"; shift 2 ;;
|
||||
--steps) STEPS="$2"; shift 2 ;;
|
||||
--seed) SEED="$2"; shift 2 ;;
|
||||
-h|--help) usage ;;
|
||||
*) echo "[error] Unknown arg: $1" >&2; usage ;;
|
||||
esac
|
||||
done
|
||||
|
||||
HOST_LOG_ROOT="$REPO_ROOT/outputs/logs/rsl_rl/$EXPERIMENT"
|
||||
|
||||
# ---- resolve checkpoint (same scheme as play_go2.sh) ----
|
||||
if [[ -z "$CHECKPOINT" ]]; then
|
||||
if [[ -z "$RUN_DIR" ]]; then
|
||||
RUN_DIR="$(ls -1 "$HOST_LOG_ROOT" 2>/dev/null | sort | tail -n 1 || true)"
|
||||
[[ -z "$RUN_DIR" ]] && { echo "[error] No runs under $HOST_LOG_ROOT" >&2; exit 1; }
|
||||
fi
|
||||
RUN_PATH="$HOST_LOG_ROOT/$RUN_DIR"
|
||||
[[ -d "$RUN_PATH" ]] || { echo "[error] Run dir not found: $RUN_PATH" >&2; exit 1; }
|
||||
|
||||
if [[ -n "$FROM_ITER" ]]; then
|
||||
HOST_CKPT="$RUN_PATH/model_${FROM_ITER}.pt"
|
||||
[[ -f "$HOST_CKPT" ]] || { echo "[error] Checkpoint not found: $HOST_CKPT" >&2; exit 1; }
|
||||
else
|
||||
HOST_CKPT="$(ls -1 "$RUN_PATH"/model_*.pt 2>/dev/null | sort -V | tail -n 1)"
|
||||
[[ -z "$HOST_CKPT" ]] && { echo "[error] No model_*.pt in $RUN_PATH" >&2; exit 1; }
|
||||
fi
|
||||
CHECKPOINT="${HOST_CKPT/$REPO_ROOT\/outputs\/logs/\/workspace\/IsaacLab\/logs}"
|
||||
else
|
||||
HOST_CKPT="${CHECKPOINT/\/workspace\/IsaacLab\/logs/$REPO_ROOT\/outputs\/logs}"
|
||||
fi
|
||||
|
||||
cat <<EOF
|
||||
[ablate] task = $TASK
|
||||
[ablate] checkpoint = $CHECKPOINT
|
||||
[ablate] host file = $HOST_CKPT
|
||||
[ablate] envs = $NUM_ENVS
|
||||
[ablate] steps = $STEPS
|
||||
EOF
|
||||
|
||||
docker run --rm --gpus all \
|
||||
-e ACCEPT_EULA=Y -e PRIVACY_CONSENT=Y \
|
||||
-e PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
|
||||
--shm-size=16g --network host --ipc host \
|
||||
--ulimit memlock=-1 --ulimit stack=67108864 \
|
||||
-v "$REPO_ROOT/outputs/logs:/workspace/IsaacLab/logs" \
|
||||
-v "$REPO_ROOT/mount/sru-navigation-sim:/workspace/IsaacLab/source/isaaclab_nav_task" \
|
||||
-v "$REPO_ROOT/mount/rsl_rl:/workspace/rsl_rl" \
|
||||
--entrypoint bash sru-nav:latest -lc \
|
||||
"./isaaclab.sh -p source/isaaclab_nav_task/scripts/ablate_depth.py \
|
||||
--task $TASK \
|
||||
--num_envs $NUM_ENVS \
|
||||
--steps $STEPS \
|
||||
--seed $SEED \
|
||||
--checkpoint $CHECKPOINT \
|
||||
--headless"
|
||||
@@ -0,0 +1,99 @@
|
||||
#!/usr/bin/env bash
|
||||
# Run instrumented collision analysis inside the Isaac container, then plot
|
||||
# figures on the host.
|
||||
#
|
||||
# Example:
|
||||
# PLAY_MAZE_ONLY=1 PLAY_CLASSIC_MAZE=1 PLAY_DIFFICULTY="0.8,1.0" PLAY_CELL_SIZE=1.0 \
|
||||
# ./scripts/analyze_collisions.sh \
|
||||
# --task Isaac-Nav-PPO-Go2-Play-v0 \
|
||||
# --experiment go2_navigation_ppo_puremaze \
|
||||
# --run-dir 2026-06-23_11-13-55_puremaze_tight_corridors \
|
||||
# --from-iter 32200 \
|
||||
# --envs 32 --steps 4000
|
||||
set -euo pipefail
|
||||
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
|
||||
TASK="Isaac-Nav-PPO-Go2-Play-v0"
|
||||
EXPERIMENT="go2_navigation_ppo_puremaze"
|
||||
RUN_DIR=""
|
||||
FROM_ITER=""
|
||||
CHECKPOINT=""
|
||||
NUM_ENVS=32
|
||||
STEPS=4000
|
||||
SEED=42
|
||||
|
||||
usage() {
|
||||
cat <<EOF
|
||||
Usage: $(basename "$0") [options]
|
||||
--task NAME (default: $TASK)
|
||||
--experiment NAME (default: $EXPERIMENT)
|
||||
--run-dir NAME run dir under outputs/logs/rsl_rl/<experiment>/
|
||||
--from-iter N model_<N>.pt
|
||||
--checkpoint PATH explicit in-container ckpt (overrides above)
|
||||
--envs N (default: $NUM_ENVS)
|
||||
--steps N (default: $STEPS)
|
||||
--seed N (default: $SEED)
|
||||
|
||||
Forwarded env vars: PLAY_DIFFICULTY PLAY_SUBTERRAIN_MIX PLAY_MAZE_ONLY
|
||||
PLAY_CELL_SIZE PLAY_CLASSIC_MAZE
|
||||
EOF
|
||||
exit 0
|
||||
}
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--task) TASK="$2"; shift 2 ;;
|
||||
--experiment) EXPERIMENT="$2"; shift 2 ;;
|
||||
--run-dir) RUN_DIR="$2"; shift 2 ;;
|
||||
--from-iter) FROM_ITER="$2"; shift 2 ;;
|
||||
--checkpoint) CHECKPOINT="$2"; shift 2 ;;
|
||||
--envs) NUM_ENVS="$2"; shift 2 ;;
|
||||
--steps) STEPS="$2"; shift 2 ;;
|
||||
--seed) SEED="$2"; shift 2 ;;
|
||||
-h|--help) usage ;;
|
||||
*) echo "[error] $1" >&2; usage ;;
|
||||
esac
|
||||
done
|
||||
|
||||
HOST_LOG_ROOT="$REPO_ROOT/outputs/logs/rsl_rl/$EXPERIMENT"
|
||||
if [[ -z "$CHECKPOINT" ]]; then
|
||||
[[ -z "$RUN_DIR" || -z "$FROM_ITER" ]] && { echo "[error] need --run-dir + --from-iter or --checkpoint" >&2; exit 1; }
|
||||
HOST_CKPT="$HOST_LOG_ROOT/$RUN_DIR/model_${FROM_ITER}.pt"
|
||||
[[ -f "$HOST_CKPT" ]] || { echo "[error] not found: $HOST_CKPT" >&2; exit 1; }
|
||||
CHECKPOINT="${HOST_CKPT/$REPO_ROOT\/outputs\/logs/\/workspace\/IsaacLab\/logs}"
|
||||
fi
|
||||
|
||||
TAG="${RUN_DIR:-$(basename "$(dirname "$CHECKPOINT")")}_iter${FROM_ITER:-unknown}"
|
||||
HOST_OUT="$REPO_ROOT/outputs/collisions/$TAG"
|
||||
CTR_OUT="/workspace/IsaacLab/logs/collisions/$TAG"
|
||||
mkdir -p "$HOST_OUT"
|
||||
|
||||
echo "[collisions] task=$TASK"
|
||||
echo "[collisions] ckpt(ctr)=$CHECKPOINT"
|
||||
echo "[collisions] out(host)=$HOST_OUT"
|
||||
|
||||
docker run --rm --gpus all \
|
||||
-e ACCEPT_EULA=Y -e PRIVACY_CONSENT=Y \
|
||||
-e PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
|
||||
-e PLAY_DIFFICULTY="${PLAY_DIFFICULTY:-}" \
|
||||
-e PLAY_SUBTERRAIN_MIX="${PLAY_SUBTERRAIN_MIX:-}" \
|
||||
-e PLAY_MAZE_ONLY="${PLAY_MAZE_ONLY:-}" \
|
||||
-e PLAY_CELL_SIZE="${PLAY_CELL_SIZE:-}" \
|
||||
-e PLAY_CLASSIC_MAZE="${PLAY_CLASSIC_MAZE:-}" \
|
||||
--shm-size=16g --network host --ipc host \
|
||||
--ulimit memlock=-1 --ulimit stack=67108864 \
|
||||
-v "$REPO_ROOT/outputs/logs:/workspace/IsaacLab/logs" \
|
||||
-v "$REPO_ROOT/mount/sru-navigation-sim:/workspace/IsaacLab/source/isaaclab_nav_task" \
|
||||
-v "$REPO_ROOT/mount/rsl_rl:/workspace/rsl_rl" \
|
||||
--entrypoint bash sru-nav:latest -lc \
|
||||
"./isaaclab.sh -p source/isaaclab_nav_task/scripts/analyze_collisions.py \
|
||||
--task $TASK \
|
||||
--num_envs $NUM_ENVS \
|
||||
--steps $STEPS \
|
||||
--seed $SEED \
|
||||
--checkpoint $CHECKPOINT \
|
||||
--out-dir $CTR_OUT \
|
||||
--headless && \
|
||||
./isaaclab.sh -p source/isaaclab_nav_task/scripts/plot_collisions.py $CTR_OUT/collisions.npz"
|
||||
echo "[collisions] done -> $HOST_OUT"
|
||||
ls -la "$HOST_OUT"
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Verify Go2 nav tasks are registered correctly. Must be launched via isaaclab.sh -p."""
|
||||
|
||||
from isaaclab.app import AppLauncher
|
||||
|
||||
# Headless minimal launcher
|
||||
app_launcher = AppLauncher(headless=True, enable_cameras=False)
|
||||
simulation_app = app_launcher.app
|
||||
|
||||
import gymnasium as gym # noqa: E402
|
||||
import isaaclab_nav_task # noqa: F401, E402
|
||||
|
||||
ids = sorted(s for s in gym.envs.registry.keys() if "Go2" in s or "B2W" in s)
|
||||
print("=" * 60)
|
||||
print("Registered Go2 + B2W tasks:")
|
||||
print("=" * 60)
|
||||
for i in ids:
|
||||
print(f" {i}")
|
||||
|
||||
simulation_app.close()
|
||||
@@ -0,0 +1,190 @@
|
||||
#!/usr/bin/env bash
|
||||
# Apples-to-apples comparison: my-Go2-policy vs official-B2W-policy on the
|
||||
# SAME pure-maze scene (same seed, same PLAY_* env vars => same maze layouts).
|
||||
#
|
||||
# Bodies differ (Go2 quadruped vs B2W wheeled), but the terrain topology is
|
||||
# identical, so success-rate / failure-mode breakdowns are directly comparable
|
||||
# as a "policy + body" combo.
|
||||
#
|
||||
# Example:
|
||||
# ./scripts/compare_baselines.sh \
|
||||
# --go2-run 2026-06-23_11-13-55_puremaze_tight_corridors \
|
||||
# --go2-iter 32200 \
|
||||
# --b2w-jit assets/baselines/b2w_nav_policy_new.pt \
|
||||
# --cell-size 2.0 \
|
||||
# --difficulty "0.8,1.0" \
|
||||
# --envs 32 --steps 2000 --seed 42
|
||||
set -euo pipefail
|
||||
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
|
||||
# ---- defaults ----
|
||||
GO2_EXPERIMENT="go2_navigation_ppo_puremaze"
|
||||
GO2_RUN=""
|
||||
GO2_ITER=""
|
||||
B2W_JIT=""
|
||||
CELL_SIZE="2.0"
|
||||
DIFFICULTY="0.8,1.0"
|
||||
NUM_ENVS=32
|
||||
STEPS=2000
|
||||
SEED=42
|
||||
OUT_DIR="$REPO_ROOT/outputs/compare/$(date +%Y%m%d_%H%M%S)"
|
||||
|
||||
usage() {
|
||||
cat <<EOF
|
||||
Usage: $(basename "$0") --go2-run DIR --go2-iter N --b2w-jit PATH [options]
|
||||
|
||||
Required (Go2 side):
|
||||
--go2-run DIR Go2 run-dir name (under outputs/logs/rsl_rl/<experiment>/).
|
||||
--go2-iter N Go2 model_<N>.pt iter.
|
||||
|
||||
Required (B2W side):
|
||||
--b2w-jit PATH Host path to TorchScript B2W policy (e.g. nav_policy_new.pt).
|
||||
|
||||
Options:
|
||||
--go2-experiment N Go2 experiment subdir (default: $GO2_EXPERIMENT).
|
||||
--cell-size F PLAY_CELL_SIZE in meters (default: $CELL_SIZE).
|
||||
NOTE: B2W body is large; cell<1.5 usually impossible.
|
||||
--difficulty "l,h" PLAY_DIFFICULTY band (default: "$DIFFICULTY").
|
||||
--envs N Parallel envs (default: $NUM_ENVS).
|
||||
--steps N env.step() count (default: $STEPS).
|
||||
--seed N Shared seed for both runs (default: $SEED).
|
||||
--out-dir PATH Where to write logs+diff (default: outputs/compare/<ts>).
|
||||
-h, --help
|
||||
|
||||
Both runs share:
|
||||
PLAY_MAZE_ONLY=1 (100% maze sub-terrain)
|
||||
PLAY_CLASSIC_MAZE=1 (paper-style uniform walls)
|
||||
PLAY_DIFFICULTY=\$DIFFICULTY
|
||||
PLAY_CELL_SIZE=\$CELL_SIZE
|
||||
--seed \$SEED, --num_envs \$NUM_ENVS, --steps \$STEPS
|
||||
EOF
|
||||
exit 0
|
||||
}
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--go2-run) GO2_RUN="$2"; shift 2 ;;
|
||||
--go2-iter) GO2_ITER="$2"; shift 2 ;;
|
||||
--go2-experiment) GO2_EXPERIMENT="$2"; shift 2 ;;
|
||||
--b2w-jit) B2W_JIT="$2"; shift 2 ;;
|
||||
--cell-size) CELL_SIZE="$2"; shift 2 ;;
|
||||
--difficulty) DIFFICULTY="$2"; shift 2 ;;
|
||||
--envs) NUM_ENVS="$2"; shift 2 ;;
|
||||
--steps) STEPS="$2"; shift 2 ;;
|
||||
--seed) SEED="$2"; shift 2 ;;
|
||||
--out-dir) OUT_DIR="$2"; shift 2 ;;
|
||||
-h|--help) usage ;;
|
||||
*) echo "[error] Unknown arg: $1" >&2; usage ;;
|
||||
esac
|
||||
done
|
||||
|
||||
[[ -z "$GO2_RUN" || -z "$GO2_ITER" || -z "$B2W_JIT" ]] && \
|
||||
{ echo "[error] --go2-run, --go2-iter, --b2w-jit are required." >&2; usage; }
|
||||
|
||||
mkdir -p "$OUT_DIR"
|
||||
GO2_LOG="$OUT_DIR/go2_eval.log"
|
||||
B2W_LOG="$OUT_DIR/b2w_eval.log"
|
||||
DIFF_TABLE="$OUT_DIR/comparison.md"
|
||||
|
||||
# Shared env vars for both runs.
|
||||
export PLAY_MAZE_ONLY=1
|
||||
export PLAY_CLASSIC_MAZE=1
|
||||
export PLAY_DIFFICULTY="$DIFFICULTY"
|
||||
export PLAY_CELL_SIZE="$CELL_SIZE"
|
||||
|
||||
cat <<EOF | tee "$OUT_DIR/setup.txt"
|
||||
================ COMPARE SETUP ================
|
||||
out_dir = $OUT_DIR
|
||||
seed = $SEED
|
||||
envs = $NUM_ENVS
|
||||
steps = $STEPS
|
||||
PLAY_MAZE_ONLY = 1
|
||||
PLAY_CLASSIC_MAZE = 1
|
||||
PLAY_DIFFICULTY = $DIFFICULTY
|
||||
PLAY_CELL_SIZE = $CELL_SIZE
|
||||
----- GO2 -----
|
||||
experiment = $GO2_EXPERIMENT
|
||||
run-dir = $GO2_RUN
|
||||
iter = $GO2_ITER
|
||||
----- B2W -----
|
||||
jit policy = $B2W_JIT
|
||||
================================================
|
||||
EOF
|
||||
|
||||
# ---- 1. Go2 (my policy) on maze ----
|
||||
echo "[compare] >>> running Go2 eval ..."
|
||||
"$REPO_ROOT/scripts/eval_terminations.sh" \
|
||||
--task Isaac-Nav-PPO-Go2-Play-v0 \
|
||||
--experiment "$GO2_EXPERIMENT" \
|
||||
--run-dir "$GO2_RUN" \
|
||||
--from-iter "$GO2_ITER" \
|
||||
--envs "$NUM_ENVS" --steps "$STEPS" --seed "$SEED" \
|
||||
2>&1 | tee "$GO2_LOG"
|
||||
|
||||
# ---- 2. B2W (official JIT) on maze ----
|
||||
echo "[compare] >>> running B2W eval ..."
|
||||
"$REPO_ROOT/scripts/eval_jit_baseline.sh" \
|
||||
--task Isaac-Nav-PPO-B2W-Play-v0 \
|
||||
--jit-policy "$B2W_JIT" \
|
||||
--envs "$NUM_ENVS" --steps "$STEPS" --seed "$SEED" \
|
||||
2>&1 | tee "$B2W_LOG"
|
||||
|
||||
# ---- 3. Parse both logs and produce a side-by-side table ----
|
||||
python3 - "$GO2_LOG" "$B2W_LOG" "$DIFF_TABLE" <<'PY'
|
||||
import re, sys, pathlib
|
||||
go2_log, b2w_log, out_md = sys.argv[1], sys.argv[2], sys.argv[3]
|
||||
|
||||
def parse(path):
|
||||
"""Extract per-term counts from an eval-style log."""
|
||||
text = pathlib.Path(path).read_text()
|
||||
rows = {}
|
||||
# lines look like: " early_termination 1234 45.6% <- success"
|
||||
for m in re.finditer(r"^\s{2}([a-z_]+)\s+(\d+)\s+([\d.]+)%", text, re.M):
|
||||
rows[m.group(1)] = (int(m.group(2)), float(m.group(3)))
|
||||
return rows
|
||||
|
||||
g = parse(go2_log)
|
||||
b = parse(b2w_log)
|
||||
all_terms = sorted(set(g) | set(b))
|
||||
|
||||
# Ordering: success first, then collisions, then time_out, then rest.
|
||||
priority = {"early_termination": 0, "base_contact": 1, "large_pitch_angle": 2,
|
||||
"terrain_fall": 3, "time_out": 4}
|
||||
all_terms.sort(key=lambda n: (priority.get(n, 99), n))
|
||||
|
||||
lines = []
|
||||
lines.append("# Go2-policy vs official-B2W-policy on identical maze scenes\n")
|
||||
lines.append("| termination | Go2 count | Go2 % | B2W count | B2W % | meaning |")
|
||||
lines.append("|----------------------|-----------|--------|-----------|--------|---------|")
|
||||
meaning = {
|
||||
"early_termination": "**success** (reached goal)",
|
||||
"base_contact": "collision (body hit wall)",
|
||||
"large_pitch_angle": "tipped over",
|
||||
"terrain_fall": "fell into pit",
|
||||
"time_out": "ran out of time",
|
||||
}
|
||||
for t in all_terms:
|
||||
gc, gp = g.get(t, (0, 0.0))
|
||||
bc, bp = b.get(t, (0, 0.0))
|
||||
lines.append(f"| `{t:<20}` | {gc:>9} | {gp:>5.1f}% | {bc:>9} | {bp:>5.1f}% | {meaning.get(t,'')} |")
|
||||
|
||||
# Summary delta on success rate.
|
||||
g_succ = g.get("early_termination", (0, 0.0))[1]
|
||||
b_succ = b.get("early_termination", (0, 0.0))[1]
|
||||
lines.append("")
|
||||
lines.append(f"**Success rate:** Go2 = **{g_succ:.1f}%**, B2W = **{b_succ:.1f}%**, "
|
||||
f"Δ = **{g_succ - b_succ:+.1f}** pp (Go2 - B2W)")
|
||||
|
||||
out = "\n".join(lines) + "\n"
|
||||
pathlib.Path(out_md).write_text(out)
|
||||
print("\n" + "=" * 78)
|
||||
print(out)
|
||||
print(f"[compare] wrote {out_md}")
|
||||
PY
|
||||
|
||||
echo ""
|
||||
echo "[compare] all done."
|
||||
echo " setup: $OUT_DIR/setup.txt"
|
||||
echo " go2 log: $GO2_LOG"
|
||||
echo " b2w log: $B2W_LOG"
|
||||
echo " table: $DIFF_TABLE"
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user