Initial commit

This commit is contained in:
MattMa
2026-07-10 16:58:17 +08:00
commit 7222ba1107
56 changed files with 8433 additions and 0 deletions
+33
View File
@@ -0,0 +1,33 @@
# Python cache
__pycache__/
*.pyc
*.pyo
*.egg-info/
# Training outputs & models
outputs/
logs/
runs/
*.pt
*.pth
*.onnx
# Environment secrets
.env
.env.local
auth_qrcode.png
# IDE
.vscode/
.idea/
# IDE workflow configurations
.windsurf/
.claude/
.qoder/
**/.windsurf/
**/.claude/
**/.qoder/
# OS
.DS_Store
+37
View File
@@ -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
)
+130
View File
@@ -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.
+37
View File
@@ -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
+26
View File
@@ -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]
+271
View File
@@ -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 桥应自动归零(依你的桥行为)
- 关闭电源开关(终极手段)
+441
View File
@@ -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` 全绿,就能开始真机测试。
+553
View File
@@ -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.
+55
View File
@@ -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>
+29
View File
@@ -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>
+121
View File
@@ -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
+214
View File
@@ -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
View File
@@ -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
View File
@@ -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
+331
View File
@@ -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()
+11
View File
@@ -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)
+80
View File
@@ -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
+176
View File
@@ -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.')
+252
View File
@@ -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
+157
View File
@@ -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
+843
View File
@@ -0,0 +1,843 @@
# Complete Porting Guide for Reproducing SRU Navigation on Odin1 + ROS1
> Starting from the paper *Spatially-Enhanced Recurrent Memory for Long-Range Mapless Navigation via End-to-End Reinforcement Learning* and its companion open-source repository [`sru-project-website`](https://michaelfyang.github.io/sru-project-website/), this guide ports the SRU end-to-end navigation policy to the **Odin1 depth camera + ROS1 Noetic + any robot capable of receiving `geometry_msgs/Twist` (`/cmd_vel`)** (with Unitree Go2 as the default hardware reference). The repository `sru_nav_go2_ros1` is the product of this effort.
> **Chinese version**: see [`PORTING_GUIDE_CN.md`](./PORTING_GUIDE_CN.md).
***
## 0. What This Document Is / Is Not
**What it is**: A three-in-one guide containing "Porting Decision Log + AI Replication Prompt + Automated Acceptance Script". After reading, you will:
1. Know why and what we modified;
2. Use a slash command to let an AI agent (Cascade, Claude Code, etc.) **automatically regenerate this repository** starting from the open-source repositories and the paper;
3. Use a single script to verify if the generated results are qualified.
**What it is not**: An explanation of algorithmic principles (please read the paper and original code repositories directly).
**Target Audience**:
- Already possess basic skills with Ubuntu, ROS1, and Python/conda;
- Own a Unitree Go2 (or any mobile robot subscribing to `/cmd_vel`) + Odin1 depth camera;
- Want to run SRU on their own robot, or want to verify "whether an AI agent can replicate a real-robot deployment package from paper + open-source code".
> Zero-barrier commitment: Except for the prerequisite skills mentioned above, all paths, IPs, robot models, and camera models are designed to be **overridden via environment variables or parameters**, without modifying the source code.
***
## 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* | Explains observation/action space, rewards, network architecture (VAE depth encoder + LSTM-SRU + actor head) |
| Project Page | https://michaelfyang.github.io/sru-project-website/ | Indexes repositories, videos, and paper |
| `sru-navigation-learning` | RL training code (rsl_rl style). Provides PPO/MDPO algorithm, reward terms, observation manager | Used for cross-checking **reward design, action squashing, observation hierarchy**, and obtaining the ONNX export script |
| `sru-navigation-sim` | IsaacLab environment, containing B2W / AOW training configurations | Obtains crucial numbers like `policy_scaling`, randomization ranges, observation shape (depth `64×5×8`), etc. |
| `sru-robot-deployment` | Original authors' deployment on Unitree B2W + ZED-X | **The direct reference target for rewriting**: The original uses PyTorch + DLIO odom + custom SDK bridge; this port replaces them with ONNX + Odin1 odom + 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 the state is flattened when exporting to ONNX |
| `sru-depth-pretraining` | VAE depth encoder pretraining | Obtains `vae_encoder.onnx` input shape (`H×W` normalized depth image, single channel) and latent dimension |
If you do not plan to replicate and just want to run it: drop the two open-source ONNX models (`vae_encoder.onnx` + `nav_policy.onnx`) into `sru_nav_go2_ros1/models/` and skip to §6.
***
## 2. Porting Target Matrix
| Dimension | Authors' Deployment (`sru-robot-deployment`) | This Repository (`sru_nav_go2_ros1`) | Abstracted Interface |
| --- | --- | --- | --- |
| Robot | Unitree **B2W** (wheeled-legged) | Unitree **Go2** (pure legged) | Any robot subscribing to `/cmd_vel` (`geometry_msgs/Twist`, body frame) |
| Depth Sensing | ZED-X | **Odin1** (`32FC1` depth, ~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 Frequency | ~10 Hz | **5 Hz** (training-aligned; Odin depth ~10 Hz is naturally downsampled) | `~control_frequency` |
| Operator Joystick | PS5 PerceptiveNavigationSE2 | Same PS5 mapping, **new `require_joystick: false`** headless mode | `--no-deadman` / yaml `require_joystick` |
| Install & Launch | rosinstall suite | **`setup_conda_env.sh` + `launch_sru_nav.sh`** two scripts | env vars `ENV_NAME / ROS_DISTRO / CATKIN_WS` can all be overridden |
***
## 3. Core Porting Decisions (Motivations & Code References)
### 3.1 Inference: PyTorch → ONNX Runtime
- **Motivation**: On Jetson Orin NX, installing the PyTorch + cv_bridge + onnxruntime dependency stack is highly prone to dependency hell. ONNX Runtime loads a single file, easily switches CPU/GPU EPs, and provides ready-made ARM wheels.
- **Interface**: `LearningModel` in `@/sru_nav_go2_ros1/src/sru_nav_go2/model.py` loads `vae_encoder.onnx` (depth → latent) and `nav_policy.onnx` (latent + state vector + previous action + LSTM hidden → action mean + new hidden).
- **Hidden State Convention**: The training side specifies `rnn_hidden_size=512, num_layers=1`. When exporting to ONNX, `(h, c)` are exposed as input/output tensors, which this node explicitly holds between frames; `reset_hidden_state` corresponds to the `is_first` flag during training.
- **Action Squashing**: The network already contains `tanh`, yielding outputs in `(-1, 1)`. The node then multiplies this by `policy_scale=[vx_max, vy_max, ω_max]` (default `[0.6, 0.3, 0.6]`) to obtain SI velocity commands.
### 3.2 Observation Layer: Odin1 replacing ZED-X + DLIO
- **Depth Image**: Odin1 publishes `sensor_msgs/Image` (`32FC1` in meters). In `@/sru_nav_go2_ros1/src/sru_nav_go2/navigation_policy_node.py:209-225`, we perform:
1. `cv_bridge.imgmsg_to_cv2(passthrough)`
2. `nan_to_num(nan=0, posinf=2*max_depth, neginf=0)`
3. Clip to `[min_depth, max_depth] = [0.25, 10.0] m`, with out-of-bounds pixels set to 0.
- **Odom Frame Convention**: The twist in Odin1 odom is in the **world frame**. In `odom_callback`, we rotate the velocities back to the body frame using the body quaternion (to align with training). If your odom is already in the body frame, simply set `use_sim: true` (implemented in `@/sru_nav_go2_ros1/src/sru_nav_go2/navigation_policy_node.py:189-197`).
- **Goal Frame Convention**: `/goal_pose.header.frame_id` must match the odom's `frame_id` (default `odom`); otherwise, the node rejects it. This prevents the operator from mistakenly publishing body-frame coordinates as odom-frame goals.
### 3.3 Action Output: Direct `/cmd_vel`
- The original authors implemented their own SDK bridge on B2W; for Go2, writing a small node using `unitree_legged_sdk` that subscribes to `/cmd_vel` (separated from this repo) is sufficient. This package is **not** tied to any specific robot SDK bridge.
- The default `policy_scale` is set to `[0.6, 0.3, 0.6]` which is more than twice as conservative as the training value of `[1.5, 1.0, 1.0]`, leaving margin for the physical robot. Since action scales were randomized with `Uniform(0.6, 1.2)` during training, the network is robust to runtime scaling.
### 3.4 Safety: Dual-mode Joystick Deadman
| Mode | Trigger | Behavior |
| --- | --- | --- |
| Default (`require_joystick=true`) | Real deployment | `cmd_vel_ratio=0` initially; `/joy` must be continuously published and `axes[4]` (DEADMAN_RATIO) pushed forward to command velocity. No joy for `>15 s` -> forces velocity to zero. |
| Test (`require_joystick=false`) | `--no-deadman` or yaml set to false | Starts with `cmd_vel_ratio=1.0` immediately. Runs without joystick. **Use only when wheels are lifted / in simulation / in open spaces**. |
Code reference: `@/sru_nav_go2_ros1/src/sru_nav_go2/navigation_policy_node.py:118-121, 272-287`.
> ⚠️ **Do NOT collapse "throttle / forward / deadman" into a single axis.** Upstream
> `sru-robot-deployment` uses **independent** axes for the policy's forward
> command (`AXIS_LINEAR_X = 1`) and the safety deadman/ratio gate
> (`AXIS_DEADMAN_RATIO = 4`). They must stay separate; conflating them disables
> either manual driving or the safety gate.
### 3.4.1 Full PS5 joystick contract (MUST match upstream)
The trained policy and the upstream deployment assume the **exact** axis & button
indices below (source: `sru-robot-deployment/rl_nav_controller/rl_nav_controller/constants.py:19-37`).
**Do not infer these from "common ROS PS5 mappings" — copy them verbatim.**
```text
# axes (sensor_msgs/Joy.axes[i])
AXIS_LINEAR_Y = 0 # lateral (strafe), used by manual + smart-joy
AXIS_LINEAR_X = 1 # forward/back, used by manual + smart-joy
AXIS_ANGULAR_Z = 2 # YAW (NOT axis 3)
AXIS_LINEAR_Z = 3 # height delta (smart-joy only)
AXIS_DEADMAN_RATIO = 4 # deadman gate; cmd_vel_ratio = 1 + axes[4]
AXIS_SMART = 5 # < -0.5 -> enter smart-joystick goal mode
# buttons (sensor_msgs/Joy.buttons[i])
BUTTON_DOWN = 0
BUTTON_TRIGGER_WAYPOINTS = 1
BUTTON_RESET_HIDDEN_STATE= 2
BUTTON_UP = 3
BUTTON_CLEAR_WAYPOINT = 4
BUTTON_RECORD_WAYPOINT = 6
BUTTON_ABORT = 9
BUTTON_SEND_GOAL = 10
BUTTON_FORWARD = 11
BUTTON_BACKWARD = 12
BUTTON_LEFT = 13
BUTTON_RIGHT = 14
```
### 3.4.2 Required features to KEEP from `sru-robot-deployment`
Beyond the obvious "subscribe odom/depth/goal/joy, run policy, publish `/cmd_vel`"
loop, the deployment node MUST also implement the following — these are part of
the user-facing safety/usability contract and were validated on real Go2 hardware:
| Feature | Trigger | Notes |
| --- | --- | --- |
| Force reset LSTM hidden state | `BUTTON_RESET_HIDDEN_STATE` (2) | Sets a flag consumed by next `model.predict(..., is_reset=True)`. Operator recovery from stuck recurrent state. |
| Abort current goal | `BUTTON_ABORT` (9) | Clears `target_pos_w`, stops chained waypoint sequence. |
| Record / clear waypoint | `BUTTON_RECORD_WAYPOINT` (6) / `BUTTON_CLEAR_WAYPOINT` (4) | Pushes/pops the current `robot_pos_w` on `WaypointManager`. Cooldown `TRIGGER_BUTTON_COOLDOWN = 1.0 s`. |
| Trigger waypoint sequence | `BUTTON_TRIGGER_WAYPOINTS` (1) | Plays back recorded waypoints, alternating `home` / `inversed` direction. |
| Send moving goal | `BUTTON_SEND_GOAL` (10) | Publishes a body-frame-offset goal accumulated from D-pad nudges (BUTTON_FORWARD/BACKWARD/LEFT/RIGHT/UP/DOWN). |
| Smart-joystick mode | `AXIS_SMART (5) < -0.5` | Continuously generates a rolling body-frame goal from `axes[0,1,3]` scaled by `SMART_JOYSTICK_SCALE = 5.0` / `SMART_JOYSTICK_Z_SCALE = 0.25`, low-pass-filtered with `SMART_JOYSTICK_FILTER_ALPHA = 0.2`. Updated at `SMART_JOYSTICK_UPDATE_FREQUENCY = 5.0 Hz`. |
| Periodic visualization | rospy.Timer at `WAYPOINT_PUBLISH_INTERVAL = TARGET_VECTOR_PUBLISH_INTERVAL = 0.2 s` | Two independent timers publish waypoint markers and the goal-vector arrow (base frame). |
| Near-goal chaining | `_check_near_goal()` returns true within `arrive_goal_threshold * NEAR_GOAL_THRESHOLD_MULTIPLIER (=2.0)` | Used to early-trigger the next waypoint in a sequence, distinct from `_check_goal_reached()`. |
| Own `goal_pose` publisher | Node publishes to `/goal_pose` itself | Required so smart-joystick and waypoint-sequence modes can drive the same callback path as an external goal. |
A correctly ported `navigation_policy_node.py` therefore weighs in around
**550-600 lines** (excluding docstrings). A ~300-line node almost certainly
dropped one of the above blocks.
### 3.5 Installation Layer: conda + System ROS Coexistence (**7 Real-world Gotchas Discovered**)
Jetson Orin NX comes with ROS Noetic (system Python 3.8 + `cv_bridge.so`); onnxruntime / opencv / numpy are easier to install in a conda env. When bridges are built between these two worlds, we encountered several issues (listed in order of discovery):
1. **PYTHONPATH Injection**: `/opt/ros/noetic/lib/python3/dist-packages` must be appended to the conda Python's search path, so that `rospy / cv_bridge / sensor_msgs / tf2_ros` can be imported.
2. **shebang Locking**: `catkin_make` must be executed with `-DPYTHON_EXECUTABLE=$(which python)` **while the conda env is activated**; otherwise, the `#!` in `devel/lib/.../sru_nav_node` will point to `/usr/bin/python3`, failing to import onnxruntime. `launch_sru_nav.sh` implements an **idempotent shebang rewriter** as a fallback.
3. **ABI Conflict (libffi)**: Conda's `libffi.so` is ABI-incompatible with the system's `libp11-kit / cv_bridge` compiled against the system libffi (`undefined symbol: ffi_type_pointer, version LIBFFI_BASE_7.0`). `launch_sru_nav.sh` searches for the system `libffi.so` using `ldconfig -p` and forces it via `LD_PRELOAD` (typically `.7` on aarch64, `.8` on x86_64).
4. **rospy Implicit Dependencies**: `netifaces` / `defusedxml` are provided via apt in system Python, but must be pip-installed in the conda env. **Symptoms of their absence are highly elusive**: the node starts and transitions to ready normally, but **the moment a subscriber connects to a topic**, the subscription thread crashes with `ModuleNotFoundError`, blocking `/cmd_vel` output. This is now built into `setup_conda_env.sh`.
5. **zsh Variable Leakage -> ROS sourcing setup.zsh by mistake**: When running `bash launch_sru_nav.sh` from a zsh terminal, parent environment variables like `ZSH_VERSION` leak into the bash subprocess, misleading the ROS setup router into sourcing `setup.zsh` instead of `setup.bash`. Since `cd -q` is a zsh-only builtin, bash fails immediately and `set -e` aborts the script. Fixed by unsetting `ZSH_VERSION ZSH_NAME` and exporting `CATKIN_SHELL=bash` before sourcing, wrapped with `set +eu` to prevent uninitialized ROS variables from killing the process.
6. **SIGPIPE Silent Death via `set -e + pipefail`**: In `SYSTEM_LIBFFI=$(ldconfig -p | awk '...{exit}')`, `awk` exiting early causes a SIGPIPE to be sent to `ldconfig`, resulting in exit code 141. Under `pipefail`, the pipeline is evaluated as a failure, silently killing the script under `-e`. Fixed by appending `|| true` to the pipeline.
7. **Clock Sync Issues**: Jetson lack of an RTC battery often reverts system time, causing pip TLS handshakes to fail, and ROS inter-process messaging to drop packets if time offsets exceed 100 ms. **First-time deployments must** execute `sudo ntpdate -u ntp.aliyun.com`.
Complete automation scripts: `@/sru_nav_go2_ros1/scripts/setup_conda_env.sh` and `@/sru_nav_go2_ros1/scripts/launch_sru_nav.sh` address all 7 gotchas.
### 3.6 External Dependencies (not included in this repo)
This repo contains only the SRU policy inference node. The depth/odom driver and `/cmd_vel` actuator bridge are separate:
| Package | Role | conda env (tested) |
| --- | --- | --- |
| `odin_ros_driver` | Odin1 depth camera driver; publishes depth and high-freq odom | `neupan` |
| `unitree_control` (or equivalent) | Subscribes to `/cmd_vel` -> unitree_legged_sdk -> joint cmds | `sru_go2` |
At launch time, the three processes run in three separate terminals; all terminals export `ROS_MASTER_URI=http://localhost:11311`, and the first process to start automatically launches roscore. See §6 and this repo's `docs/DEPLOY.md` §5.
### 3.7 Deliberate Omissions
| Feature in Training | Reason for Omission in Deployment |
| --- | --- |
| Heightmap / heightscan critic | Go2 has no LiDAR; can be added via external topic if needed |
| Critic channels (distance, momentum, etc.) | Critic only used in training; inference only runs actor head |
| MDPO / distillation dual actor-critic | Training-stage optimizer structure; irrelevant to exported actor |
| Training-time reward calculation | Not needed for deployment |
| Action scale training randomization (`Uniform(0.6, 1.2)`) | Fixed scale at deployment; network is already robust |
***
## 4. File List & Roles
```
sru_nav_go2_ros1/
├── CMakeLists.txt # catkin package definition; catkin_python_setup() + install scripts
├── package.xml # Dependencies: 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 # Runtime ROS parameters; the ONLY file users should modify
│ └── waypoints_example.yaml # Multi-goal navigation example (odom-frame waypoints)
├── launch/
│ └── sru_nav_go2.launch # joy_node + static_tf + sru_nav_node
├── models/
│ ├── README.md # Instructions for exporting ONNX from training
│ ├── vae_encoder.onnx # Required (User must supply, ~21 MB)
│ └── nav_policy.onnx # Required (User must supply, ~7 MB)
├── scripts/
│ ├── setup_conda_env.sh # Creates sru_go2 env; includes PIP mirror fallback, netifaces/defusedxml
│ ├── launch_sru_nav.sh # One-click launch wrapper (LD_PRELOAD / PYTHONPATH / shebang rewrite
│ │ # / CATKIN_SHELL=bash preventing zsh leak / SIGPIPE fallback)
│ ├── sru_nav_node # ROS node entry point (copied to devel/lib/... during catkin install)
│ ├── waypoint_runner.py # Publishes sequential /goal_pose
│ └── verify_port.sh # One-click selfcheck: 6-stage check of package structure, shebang, ONNX, and topics
├── src/sru_nav_go2/
│ ├── __init__.py
│ ├── constants.py # All training-aligned constants (frequency, joy mapping, scales, etc.)
│ ├── model.py # ONNX Runtime wrapper: VAE encoder + LSTM-SRU policy with strict shape validation
│ ├── navigation_policy_node.py # Main node: odom/depth/joy/goal callbacks + cmd_vel output
│ ├── utils.py # Quaternion <-> rotation, reprojection, and math utilities (pure numpy, no torch)
│ ├── visualization.py # RViz markers (goal vector, moving_goal, waypoints)
│ └── waypoint_manager.py # Record/play waypoint lists
├── docs/
│ ├── DEPLOY.md # Comprehensive deployment manual (10 sections, 11 troubleshooting, 3 terminals)
│ ├── PORTING_GUIDE.md # Chinese porting guide (in-package copy)
│ ├── PORTING_GUIDE_EN.md # English version
│ └── IO_SPEC.md # ONNX tensor name/shape/dtype contracts
└── notes/
└── upstream_recon.md # Upstream reconnaissance summary output by AI agent in Step 1
```
> ⚠️ Note: `models/{vae_encoder,nav_policy}.onnx` **are not bundled in this repository** due to licensing; users must copy them from training outputs (see `models/README.md`).
***
## 5. Replicating this Repo via an AI Agent
This section answers a concrete question: **Once you have this repo, how do you let an AI agent actually generate the SRU porting code for you?**
We provide the same "porting prompt" in 3 formats (choose one):
| Entry File | Tool | Command (run inside the agent chat) |
| --- | --- | --- |
| `.windsurf/workflows/port-sru-to-ros.md` | Cascade (Windsurf IDE) | `/port-sru-to-ros` |
| `.claude/commands/port-sru-to-ros.md` | Claude Code (CLI / IDE extension) | `/port-sru-to-ros` |
| Prompt text in §5.2 of this document | Any agent (Cursor, Continue, Aider, ChatGPT...) | Paste §5.2 into the system/task prompt |
> ⚠️ **Reproducibility Bounds**: Modern LLMs do not achieve a 100% single-shot success rate when generating ~1500 LoC of ROS porting code. We cut the task into a 6-step phased workflow, each step having grep-able validation points. Any step that veers off-course is immediately rolled back and retried, boosting success rate by an order of magnitude compared to single long prompts.
### 5.0 3-Minute Quickstart: What You Actually Need to Do
Yes — **the essence of all slash commands is simply telling the agent to read `.windsurf/workflows/port-sru-to-ros.md` or `.claude/commands/port-sru-to-ros.md` and execute the 6-step process to generate the code**. The slash command is convenient because it handles the step of feeding the ~370-line prompt to the agent, which specifies what to do, what to self-check, and how to recover from failure.
#### Step A: Preparation (Required for all agents)
```text
$WORKSPACE/ <-- Agent's current working directory (any empty dir)
├── sru_nav_go2_ros1/ <-- Clone/copy this entire repository here
│ ├── .windsurf/workflows/port-sru-to-ros.md ← For Cascade
│ ├── .claude/commands/port-sru-to-ros.md ← For Claude Code
│ └── docs/PORTING_GUIDE.md ← For generic agents, copy §5.2
└── upstream/ <-- Place the 5 upstream repositories here
├── sru-navigation-learning/
├── sru-navigation-sim/
├── sru-robot-deployment/
├── sru-pytorch-spatial-learning/
└── sru-depth-pretraining/
```
Minimal Checklist:
1. **This repository** (including `.windsurf/`, `.claude/`, `docs/`) placed in your workspace, since slash commands locate config files via relative paths.
2. **5 upstream repositories** + **paper PDF** (optional but highly recommended): the agent will read them in Step 1 "Reconnaissance". If any are missing, the agent will stop and report what is missing.
3. **Two ONNX models** (`vae_encoder.onnx` + `nav_policy.onnx`): export from training or use ready-made files in the repo's `models/`.
> If you **only want to replicate the ROS package** (without retraining): place the two ONNX files in the agent's working directory, and the prompt will automatically bypass the training-side export step.
#### Step B: Choose invocation method based on your agent
**B-1 · Cascade (Windsurf IDE)**
```text
1. In Windsurf, File -> Open Folder, select the $WORKSPACE directory.
2. In the Cascade chat panel on the right, enter:
/port-sru-to-ros
3. After hitting Enter, Cascade automatically reads .windsurf/workflows/port-sru-to-ros.md and executes Step 1~6 in order. It will explain what it plans to do at each step and wait for your confirmation.
4. All you need to do is provide file paths when requested, or reply with "retry / skip" on self-check failures.
```
How to confirm Cascade recognizes the workflow: you should see `port-sru-to-ros` under the "Workflows" list in Windsurf settings or the Cascade panel. If it's missing, you may have opened the wrong directory — slash commands are only recognized in the `.windsurf/workflows/` folder of the active workspace root.
**B-2 · Claude Code (CLI or IDE extension)**
```bash
cd $WORKSPACE
claude # Start Claude Code interactive session
# In the Claude prompt:
> /port-sru-to-ros $WORKSPACE upstream sru_go2 noetic
```
All positional arguments are optional; if omitted, they will use default values specified in the frontmatter of `.claude/commands/port-sru-to-ros.md`. Claude will read the `.md` file and execute the 6 steps.
**B-3 · Generic Agents (Cursor / Continue / Aider / Web ChatGPT, etc.)**
```text
1. Copy the entire prompt text in §5.2.
2. Start a new session in your agent, paste the prompt into the system prompt or first user message, specifying:
- The actual absolute paths of $WORKSPACE and $UPSTREAM_DIR
- Whether the ONNX models are already present
3. Instruct the agent to follow the 6 steps in the prompt, pasting self-check outputs at each step.
```
#### Step C: How to verify after completion
Regardless of the entry point, run:
```bash
cd $WORKSPACE/sru_nav_go2_ros1
bash scripts/verify_port.sh
```
All green means the agent didn't diverge on key numbers (`policy_scale`, control frequency, LD_PRELOAD, etc.).
#### Step D: Rolling back on failure
The slash command breaks the task into 6 independent phases:
- If a step self-check fails -> tell the agent "Retry Step N, reason: xxx". The agent will roll back to that step **without** rebuilding previously passed parts.
- If the self-check command itself has environment-specific issues -> fix `verify_port.sh` and tell the agent to continue.
- If upstream repos are not found -> the agent will pause and prompt you, resume after supplying them.
---
### 5.1 Phased Workflow Overview (What actually runs under the hood)
| Step | Inputs | Outputs | Validation |
| --- | --- | --- | --- |
| 1. **Reconnaissance** | 5 upstream repos + paper | Summary `notes/upstream_recon.md`: architecture, obs/actions, shapes, hyperparams | File exists and contains layers, obs dims, and `policy_scaling` |
| 2. **Extract Paths** | `export_onnx` of `sru-navigation-learning` | `models/vae_encoder.onnx`, `models/nav_policy.onnx`, `docs/IO_SPEC.md` | ONNX Runtime loads without error, input/output shapes recorded |
| 3. **Catkin Skeleton** | Previous `IO_SPEC.md` | `package.xml / CMakeLists.txt / setup.py / launch/ / config/sru_nav.yaml` | `catkin_make` compiles successfully |
| 4. **Port Node Logic** | Original `sru-robot-deployment` node + `IO_SPEC.md` | `src/sru_nav_go2/{constants,model,utils,visualization,waypoint_manager,navigation_policy_node}.py` + `scripts/sru_nav_node` | Node starts via `roslaunch` without crashing |
| 5. **Deploy Scripts** | Target platform details | `scripts/setup_conda_env.sh` + `scripts/launch_sru_nav.sh` | Clean environment passes §6 validation commands |
| 6. **Docs & Verify** | All artifacts | `README.md / docs/DEPLOY_*.md / scripts/verify_port.sh` | `bash scripts/verify_port.sh` passes fully |
### 5.2 Full Prompt (Copy this for generic agents)
This is the exact prompt body of `.windsurf/workflows/port-sru-to-ros.md` and `.claude/commands/port-sru-to-ros.md` — the "source of truth" is identical across all entry points. If you are not using Cascade or Claude Code, copy the text below:
```
You are an expert engineer skilled in ROS1 Noetic, conda, ONNX Runtime, and PyTorch.
Your goal is to replicate a production-verified SRU deployment package from scratch.
You must strictly adhere to the 7 hard constraints below; no numbers or filenames should be altered.
[Task]
Starting from the upstream sources, generate a catkin package named `sru_nav_go2_ros1`
to deploy the end-to-end navigation policy proposed in the paper "Spatially-Enhanced
Recurrent Memory for Long-Range Mapless Navigation via End-to-End Reinforcement Learning"
to an Odin1 depth camera + ROS1 Noetic + any robot consuming `geometry_msgs/Twist (/cmd_vel)`
(reference hardware is Unitree Go2).
[Upstream Sources] (located in $UPSTREAM_DIR/)
- Paper PDF (read using path provided by user, e.g., ./2506.05997v2.pdf)
- Project Homepage: https://michaelfyang.github.io/sru-project-website/
- Repositories:
sru-navigation-learning — RL training + ONNX export (extract export_onnx entry point)
sru-navigation-sim — IsaacLab env & config (extract policy_scaling, obs dimensions)
sru-robot-deployment — Original authors' B2W+ZED-X deployment (direct target for rewriting)
sru-pytorch-spatial-learning — SRU/LSTM-SRU cell (extract hidden state shape)
sru-depth-pretraining — VAE depth pretraining (extract VAE input resolution/latent dimension)
- Pre-existing ONNX models (if available): place at models/{vae_encoder,nav_policy}.onnx
[Hard Constraint ① — Sensor and Control Interfaces]
- Depth topic defaults to `/odin1/depth_img_competetion` (sensor_msgs/Image, 32FC1, in meters).
The node performs: cv_bridge.imgmsg_to_cv2(passthrough) -> nan_to_num ->
clip to [min_depth, max_depth]=[0.25, 10.0] m -> resize to (40, 64) for VAE input.
- Odometry topic defaults to `/odin1/odometry_highfreq` (nav_msgs/Odometry, world frame).
The node rotates the twist back to the body frame using the body quaternion (skip if `use_sim:=true`).
- Control output is fixed to `/cmd_vel` (geometry_msgs/Twist, body frame, m/s + rad/s).
This package does NOT implement a robot SDK bridge; the bridge (e.g., unitree_control) must be provided separately.
- `/goal_pose.header.frame_id` must match the odom's frame_id; otherwise, the node rejects it.
[Hard Constraint ② — Inference Backend]
- The inference backend must be ONNX Runtime (PyTorch imports/runtime are STRICTLY forbidden).
- ONNX tensor names and shapes must be validated at startup; mismatches must raise immediately:
vae_encoder.onnx: input='input' [B,1,40,64] -> output='mu' [B,64,5,8]
nav_policy.onnx: inputs = obs[B,2576] + h[1,B,512] + c[1,B,512]
outputs = actions[B,3] + h_new + c_new
Implementation note: discover names via `session.get_inputs()[i].name` AND assert
they match the contract above; do NOT hard-code names without the dynamic fallback.
- LSTM hidden states (h, c) must be held explicitly by the node; `reset_hidden_state()`
must be callable at any time (used by both the warmup and by `BUTTON_RESET_HIDDEN_STATE`).
Do not auto-reset state when switching goals (aligns with training).
- Logger interface: `LearningModel` must NOT call `.info()` on the ROS module. `rospy`
has no attribute `info` — its log API is `rospy.loginfo / logwarn / logerr`. Use
plain `print()` (or `rospy.loginfo` directly) inside `model.py`; do NOT accept a
generic `logger=rospy` argument that assumes Python `logging.Logger` semantics.
This crashes the warmup and prevents the node from ever printing
"Navigation policy node is ready.".
[Hard Constraint ③ — Conda and ROS Coexistence (7 Critical Requirements)]
A) PYTHONPATH Injection: Prepend /opt/ros/$ROS_DISTRO/lib/python3/dist-packages to
the conda Python search path, allowing rospy and cv_bridge imports.
B) shebang Locking: catkin_make must be executed in the activated conda env with
-DPYTHON_EXECUTABLE=$(which python); the launch script must rewrite the shebang of
devel/lib/sru_nav_go2_ros1/sru_nav_node to the conda Python path idempotently.
C) LD_PRELOAD System libffi: Locate the system libffi via `ldconfig -p | awk '/libffi\.so\.[0-9]/{print $NF; exit}'`
(typically .7 on aarch64, .8 on x86_64) and export LD_PRELOAD to resolve conda cv_bridge ABI conflicts.
D) rospy Implicit Dependencies: setup_conda_env.sh MUST install `netifaces` and `defusedxml` via pip.
Without them, the node initializes successfully but crashes with ModuleNotFoundError upon the first subscriber.
E) Prevent zsh Variable Leakage: The launch script must export CATKIN_SHELL=bash and unset ZSH_VERSION/ZSH_NAME
before sourcing ROS setup files, preventing parent shell leakage from executing zsh-only commands like `cd -q`.
F) Prevent SIGPIPE Silence: Ensure ldconfig pipelines wrapped with `|| true` to prevent awk early exit
from triggering SIGPIPE and killing scripts silently under set -e + pipefail.
G) PIP Mirror Fallback: setup_conda_env.sh must support PIP_INDEX_URL overrides; fallback gracefully
across pypi.org -> tsinghua -> aliyun -> ustc.
[Hard Constraint ④ — Parameterization and Environment Variables]
- No hard-coded paths (e.g., `/home/user`) are allowed in source code.
- Crucial variables that must be overridable:
ENV_NAME default: sru_go2
PY_VERSION default: 3.8 (do not change; binds with ROS Noetic ABI)
ROS_DISTRO default: noetic
CATKIN_WS default: $HOME/catkin_ws
CONDA_HOME auto-detected from ~/miniconda3 / ~/anaconda3 / /opt/miniconda3
PIP_INDEX_URL fallback used if empty; otherwise single source enforced
[Hard Constraint ⑤ — Training-Aligned Constants]
Do not modify the following parameters:
- control_frequency = 5.0 Hz
- rnn_hidden_size = 512, rnn_num_layers = 1
- policy_scale default: [0.6, 0.3, 0.6] (conservative; training original: [1.5, 1.0, 1.0])
- LATERAL_VELOCITY_SCALE = 0.6
- LOW_PASS_FILTER_COEF = [0.9, 0.5, 0.5]
- min_depth = 0.25, max_depth = 10.0
- arrive_goal_threshold = 0.75 m
- NEAR_GOAL_THRESHOLD_MULTIPLIER = 2.0
- joystick_timeout = 15.0 s
- TRIGGER_BUTTON_COOLDOWN = 1.0 s
- SMART_JOYSTICK_SCALE = 5.0, SMART_JOYSTICK_Z_SCALE = 0.25,
SMART_JOYSTICK_FILTER_ALPHA = 0.2, SMART_JOYSTICK_UPDATE_FREQUENCY = 5.0 Hz
- WAYPOINT_PUBLISH_INTERVAL = TARGET_VECTOR_PUBLISH_INTERVAL = 0.2 s
- PS5 joystick mapping (copy verbatim from
sru-robot-deployment/rl_nav_controller/rl_nav_controller/constants.py:19-37 —
do NOT infer from "common ROS PS5 mappings"):
axes[0] = JOYSTICK_AXIS_LINEAR_Y (lateral / strafe)
axes[1] = JOYSTICK_AXIS_LINEAR_X (forward / back)
axes[2] = JOYSTICK_AXIS_ANGULAR_Z (YAW — NOT axis 3)
axes[3] = JOYSTICK_AXIS_LINEAR_Z (height delta, smart-joy only)
axes[4] = JOYSTICK_AXIS_DEADMAN_RATIO (deadman gate; ratio = 1 + axes[4])
axes[5] = JOYSTICK_AXIS_SMART (< -0.5 enters smart-joy mode)
buttons[0..14] (sensor_msgs/Joy.buttons[i]):
0=BUTTON_DOWN, 1=BUTTON_TRIGGER_WAYPOINTS, 2=BUTTON_RESET_HIDDEN_STATE,
3=BUTTON_UP, 4=BUTTON_CLEAR_WAYPOINT, 6=BUTTON_RECORD_WAYPOINT,
9=BUTTON_ABORT, 10=BUTTON_SEND_GOAL,
11=BUTTON_FORWARD, 12=BUTTON_BACKWARD, 13=BUTTON_LEFT, 14=BUTTON_RIGHT
Do NOT collapse "throttle / forward / deadman" into a single axis: AXIS_LINEAR_X (1)
and AXIS_DEADMAN_RATIO (4) are independent and must both be wired.
[Hard Constraint ⑥ — Safety + Required Operator Features]
- Joystick deadman control and a 15 s timeout.
- Provide a `require_joystick: false` bypass switch for lifted-wheel / simulation
/ closed-loop regression; must default to true. Print a prominent WARNING if
`require_joystick:=false`.
- The node MUST implement ALL of the following operator features (each is wired
to a button/axis in Hard Constraint ⑤ and is part of the validated upstream UX).
Omitting any of these is a regression, not a simplification:
1. BUTTON_RESET_HIDDEN_STATE -> sets a flag consumed by next
`model.predict(..., is_reset=True)`.
2. BUTTON_ABORT -> clears current target_pos_w and any waypoint sequence.
3. BUTTON_RECORD_WAYPOINT / BUTTON_CLEAR_WAYPOINT -> push/pop on WaypointManager,
gated by TRIGGER_BUTTON_COOLDOWN.
4. BUTTON_TRIGGER_WAYPOINTS -> play back waypoints, alternating home/inversed
direction.
5. BUTTON_SEND_GOAL + D-pad (FORWARD/BACKWARD/LEFT/RIGHT/UP/DOWN) ->
accumulate a body-frame delta and publish a /goal_pose. The node must
own a /goal_pose Publisher (in addition to the Subscriber) so smart-joy
and waypoint modes can drive the same callback path.
6. Smart-joystick mode (axes[5] < -0.5) -> at SMART_JOYSTICK_UPDATE_FREQUENCY,
transform axes[0,1,3] * SMART_JOYSTICK_SCALE (with axes[3] * Z_SCALE) into
the body frame, low-pass-filter with SMART_JOYSTICK_FILTER_ALPHA, publish
as a rolling /goal_pose.
7. Two periodic visualization timers at 0.2 s: one publishes the waypoint
markers and advances the active waypoint sequence (using
`_check_near_goal()` with NEAR_GOAL_THRESHOLD_MULTIPLIER); the other
publishes the goal-vector arrow in the base frame.
A correctly ported `navigation_policy_node.py` is therefore in the
**550-600 LoC** range. If your generated node is under ~400 LoC you almost
certainly dropped one of the blocks above — go back and add it before Step 4
self-check.
[Hard Constraint ⑦ — Deliberate Omissions (Do not implement)]
- No heightmap/heightscan critic channels (inference only runs the actor).
- No critic head exports.
- No MDPO / distillation details.
- No reward calculations.
- No training-time action scale randomizations.
- (Note: the joystick buttons / smart-joy / waypoints in Hard Constraint ⑥ are
NOT in this list — they are required deployment features, not training-only.)
[Output File List] (Strictly 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,
docs/IO_SPEC.md
notes/upstream_recon.md
models/README.md (explaining ONNX export steps)
[Workflow Steps] (Execute sequentially; self-check each step before proceeding)
Step 1 — Reconnaissance: Before starting, you MUST force-pull the following 5 upstream
repositories and the paper into $UPSTREAM_DIR/ (i.e., the upstream/ folder); none may be missing:
git clone sru-pytorch-spatial-learning
git clone sru-navigation-learning
git clone sru-navigation-sim
git clone sru-depth-pretraining
git clone sru-robot-deployment
and place the paper PDF (2506.05997v2.pdf) into upstream/.
If any repository or the paper is missing, report explicitly and pause; do not continue
without the complete materials.
Once everything is present, read the repos and paper, extract architectures, obs/actions,
rsl_rl parameters, and output to notes/upstream_recon.md.
Self-check: all 5 repository directories and the paper PDF exist under upstream/;
grep notes/upstream_recon.md for rnn_hidden_size, policy_scaling, obs_dim.
Step 2 — IO Specification: Locate export_onnx in training repositories, extract
input/output names and shapes, and save to docs/IO_SPEC.md.
Self-check: Load ONNX models using onnxruntime and assert shapes.
Step 3 — Catkin Skeleton: Generate package configs and run `catkin_make` to verify.
Self-check: Zero compilation warnings; sru_nav_node entry point exists.
Step 4 — Implement Node: Using original ROS2 node as reference, swap topics,
remove non-Odin dependencies, replace PyTorch with onnxruntime, and enforce shapes.
Implement every operator feature listed in Hard Constraint ⑥ (joystick buttons,
smart-joy, waypoints, two visualization timers, hidden-state reset, /goal_pose
publisher). Expected node size ~550-600 LoC.
Self-check (all must pass before moving to Step 5):
a. `roslaunch` starts without errors AND the log contains BOTH
"Learning model is ready" (or equivalent warmup-done line) AND
"Navigation policy node is ready." — if the warmup line is missing,
the model wrapper most likely tried to call `rospy.info(...)` (which
does not exist) instead of `print` / `rospy.loginfo` — fix model.py.
b. `grep -c "BUTTON_" src/sru_nav_go2/navigation_policy_node.py` >= 8
(must reference at least 8 of the 12 BUTTON_* constants).
c. `grep -E "AXIS_SMART|SMART_JOYSTICK_SCALE" src/sru_nav_go2/navigation_policy_node.py`
finds at least one hit (smart-joy mode wired).
d. `grep -E "rospy\.Timer" src/sru_nav_go2/navigation_policy_node.py | wc -l`
>= 2 (waypoint + target-vector timers present).
e. `wc -l src/sru_nav_go2/navigation_policy_node.py` is in [500, 800].
Step 5 — Write setup_conda_env.sh / launch_sru_nav.sh, covering all 7 items (A-G) of Hard
Constraint ③ and accepting all environment variables of Hard Constraint ④.
Self-check: setup_conda_env.sh fully OK in a clean env; launch_sru_nav.sh must not be
silently swallowed by set -e on startup, and key logs ("LD_PRELOAD = ..." /
"Sourced ROS ..." / "Launching: roslaunch ...") must all be printed.
Step 6 — Generate verify_port.sh + docs (DEPLOY.md / PORTING_GUIDE*.md / IO_SPEC.md /
models/README.md).
Self-check: bash scripts/verify_port.sh only SKIPs (not FAILs) when ONNX is missing;
all PASS when ONNX is present (except phase F real-time ROS topics SKIP when no roscore).
[Acceptance Criteria] (the user will run verify_port.sh and the commands below)
1. `catkin_make` in a clean catkin_ws: 0 warning 0 error.
2. `bash scripts/setup_conda_env.sh --check` all pass (ROS dist-packages may [FAIL] outside
a container, which is acceptable).
3. `head -1 devel/lib/sru_nav_go2_ros1/sru_nav_node` points to the conda env's python,
not /usr/bin/python3.
4. `roslaunch sru_nav_go2_ros1 sru_nav_go2.launch require_joystick:=false` starts up and
shows `Navigation policy node is ready.` without spamming errors.
5. Using `rostopic pub` to send any odom + one 32FC1 depth frame + one goal_pose, `/cmd_vel`
should output a non-zero Twist (vx ∈ [0, 0.6], vy ∈ [-0.18, 0.18], ωz ∈ [-0.6, 0.6]).
6. `bash scripts/verify_port.sh` all PASS when ONNX is present.
7. In a zsh terminal, `bash scripts/launch_sru_nav.sh require_joystick:=false` starts up
normally (must not be killed by the setup.zsh `cd -q` error).
[Guidelines]
- Strictly do not generate a single reply longer than 1000+ lines; split by Step, reporting
the plan before writing files at each step.
- Run the corresponding self-check after each step; paste the commands and outputs back; fix
immediately on self-check failure.
- If an upstream repository cannot find a file, report explicitly and pause; do not fabricate interfaces.
- Any training constant not in the Hard Constraint ⑤ list must first have its source line number
recorded in notes/upstream_recon.md before use — do not write from memory.
```
The directly executable versions can be found in `@/.windsurf/workflows/port-sru-to-ros.md` and `@/.claude/commands/port-sru-to-ros.md`.
### 5.3 Verifying "Whether the Prompt Can Replicate This Repository"
This is used for comparing and verifying prompt fidelity on a clean system:
```bash
diff -r --exclude=__pycache__ --exclude=.git \
./generated_sru_nav_go2_ros1/ \
./sru_nav_go2_ros1/
```
Expected: **Structure is identical. Differences should be limited to comments and literal ordering; critical parameters, topic names, and function signatures must match exactly.**
***
## 6. Customization and Zero-Barrier Use
All variable components are exposed as configurable parameters:
### 6.1 Paths and Environment Variables
| Parameter | Default | Override Command |
| --- | --- | --- |
| Catkin Workspace | `$HOME/catkin_ws` | `CATKIN_WS=/your/workspace_root bash scripts/launch_sru_nav.sh ...` |
| Conda Env Name | `sru_go2` | `ENV_NAME=my_env bash scripts/setup_conda_env.sh` |
| Python Version | `3.8` | `PY_VERSION=3.10 ...` (**strongly discouraged**; tied to ROS Noetic ABI) |
| ROS Distro | `noetic` | `ROS_DISTRO=melodic ...` (Python 3 compatible only) |
| Conda Home | Auto-detected | `CONDA_HOME=/opt/miniconda3 ...` |
| Pip Mirror | Auto fallback | `PIP_INDEX_URL=https://your-mirror/simple ...` |
> ⚠️ `CATKIN_WS` must point to the **workspace root** (the folder containing `src/`), not the package folder. For Go2, this was `/home/unitree/code/odin_sru_nav_from_prompt/`. Persist this command: `echo "export CATKIN_WS=/your/path" >> ~/.zshrc`.
### 6.2 Topics and Frames
Modify the fields in `config/sru_nav.yaml` without changing the 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 Adapting to Other Robots
Simply supply an actuator bridge that subscribes to `/cmd_vel`. This package is completely independent of specific robot kinematics. Examples:
- Unitree Go2: Write a ~50 line ROS node translating `/cmd_vel` to Sport Mode commands.
- Unitree B2 / B2W: Use the official ROS1 bridge.
- Spot: Use `spot_ros` and subscribe to `/cmd_vel`.
- Simulations: Direct subscription to `/cmd_vel` is supported out-of-the-box.
For TF2, a static transform from `base_link` to `odin1_base_link` is provided in the launch file. Adjust the parameters `odin1_x / y / z / roll / pitch / yaw` according to your mounting offset.
### 6.4 Environment Verification
**Recommended during first-time deployment**:
```bash
# 1) OS / ROS
lsb_release -a # Ubuntu 20.04 recommended
echo $ROS_DISTRO # should be noetic
which roscore # /opt/ros/noetic/bin/roscore
# 2) Conda
conda --version # ≥ 4.10
conda env list | grep -E "sru_go2|base"
# 3) Clock (Jetson RTC batteries are often drained)
date # Verify current time; otherwise pip SSL will fail
# 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"
```
These checks are codified in `verify_port.sh`.
***
## 7. Acceptance Script: `scripts/verify_port.sh`
Designed for **post-generation self-checks**. The script prints detailed `[PASS]/[FAIL]/[WARN]` tags. Key checkpoints:
| Checkpoint | Command | Expected Outcome |
| --- | --- | --- |
| Package Integrity | `find package.xml CMakeLists.txt setup.py launch config models scripts src/sru_nav_go2/{constants,model,navigation_policy_node}.py` | All files exist |
| Model Loading | `python -c "import onnxruntime as ort; ort.InferenceSession('models/vae_encoder.onnx')"` | Loads successfully; prints input shape |
| Catkin Build | `catkin_make -DPYTHON_EXECUTABLE=$(which python3)` | Exit code 0 |
| shebang Match | `head -1 devel/lib/sru_nav_go2_ros1/sru_nav_node | grep -q miniconda3.envs.${ENV_NAME}` | Match |
| Node Launch | `timeout 8 roslaunch sru_nav_go2_ros1 sru_nav_go2.launch launch_joy:=false require_joystick:=false` | Log contains "Navigation policy node is ready" |
| Params Exist | `grep -E "policy_scale|require_joystick|control_frequency" config/sru_nav.yaml` | All three match |
| LD_PRELOAD Present | `grep -q 'LD_PRELOAD.*libffi' scripts/launch_sru_nav.sh` | Match |
Do not deploy on the physical robot unless the terminal prints `ALL CHECKS PASSED`.
***
## 8. Common Pitfalls
Ordered by typical occurrence during deployment (detailed logs and fix details in `sru_nav_go2_ros1/docs/DEPLOY.md` §7):
1. **zsh terminal spawning bash: `setup.zsh: line 7: cd: -q: invalid option`**: The parent shell's `ZSH_VERSION` leaks into the bash subprocess, leading the ROS setup routing to source the zsh branch. Fixed in `launch_sru_nav.sh` by exporting `CATKIN_SHELL=bash` and unsetting `ZSH_VERSION ZSH_NAME` before sourcing.
2. **Scripts exit silently after `PYTHONPATH +=` without logging errors**: Standard Gotcha under `set -e + pipefail + awk '...{exit}'`. Early exit in `awk` triggers SIGPIPE in `ldconfig`, giving exit code 141 and killing the script. Fixed in `launch_sru_nav.sh` by appending `|| true` to the pipeline.
3. **`Missing /home/.../catkin_ws/devel/setup.bash`**: `CATKIN_WS` points to the wrong workspace. Fix: `export CATKIN_WS=/your/real/workspace_root` before running.
4. **`catkin_make` logs "must be invoked in the root of workspace"**: You executed inside `src/sru_nav_go2_ros1/`. Fix: `cd $CATKIN_WS` before invoking `catkin_make`.
5. **`FileNotFoundError: ONNX model not found: .../models/vae_encoder.onnx`**: Model files are missing in `models/`. Ensure both are copied: `vae_encoder.onnx` (~21 MB) and `nav_policy.onnx` (~7 MB).
6. **`No module named 'netifaces'` crashes subscription thread**: The node logs `Navigation policy node is ready` but crashes immediately upon receiving depth/odom data. Fix: `pip install netifaces defusedxml` inside the conda env. This is built into `setup_conda_env.sh`.
7. **`catkin_make` run outside conda environment**: The node shebang gets hardcoded to `/usr/bin/python3`, failing to import `onnxruntime`. Fix: `conda activate sru_go2 && cd $CATKIN_WS && catkin_make clean && catkin_make -DPYTHON_EXECUTABLE=$(which python)`. The `launch_sru_nav.sh` script also rewrites the shebang as a fallback.
8. **pip logs `WARNING: Retrying ... ERROR: Could not find a version`**: Chinese domestic mirrors timed out. `setup_conda_env.sh` automatically falls back to Tsinghua/Alibaba/USTC; force via `PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple bash scripts/setup_conda_env.sh`.
9. **`libp11-kit.so.0: undefined symbol: ffi_type_pointer`**: Conda's libffi overrides system symbols, clashing with `cv_bridge`. Fixed in `launch_sru_nav.sh` by dynamically loading system libffi via `LD_PRELOAD` (.7 on aarch64, .8 on x86_64).
10. **pip logs `certificate is not yet valid`**: Jetson time drifted. Fix: `sudo ntpdate -u ntp.aliyun.com && sudo hwclock --systohc`.
11. **`/cmd_vel` is all zero**: Deadman mode is active by default. Push `axes[4]` on your joystick, or launch via `require_joystick:=false` (only on jack stands / in simulation / for closed-loop regression).
12. **Goal pose ignored**: `/goal_pose.header.frame_id` must match the odom's `frame_id` (default `odom`).
13. **No native Noetic on Ubuntu 24.04**: Use the docker image `osrf/ros:noetic-desktop` and mount the workspace. `docs/DEPLOY.md` §7.10 provides complete docker and mirror instructions.
***
## 9. License & Credits
- Algorithm and training code copyright: the original SRU author team, following their original LICENSE.
- This deployment port package `sru_nav_go2_ros1` is open-sourced under an MIT-style license; files containing upstream-derived code retain their respective original headers.
- For Odin1 driver details, see [https://github.com/manifoldsdk/odin_ros_driver](https://github.com/manifoldsdk/odin_ros_driver).
If you find porting bugs or want one-click support for more robots/cameras, issues and PRs are welcome.
***
## Appendix A: Key Constants to Verify with Paper/Training Code
| Name | 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 as above |
| `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 as above |
| Depth Resolution (VAE input) | Check encoded shape `image_input_dims=(64, 5, 8)` | Any resolution; node downsamples to training specs | `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 table serves as a consistency checklist. Any subsequent ports to other hardware should preserve these values.
***
## Appendix B: Zero-Barrier Quickstart (Real-Robot Path)
This appendix outlines the minimal command sequence to execute. Detailed descriptions are in `sru_nav_go2_ros1/docs/DEPLOY.md`.
### B.1 One-Time Environment Setup
```bash
# === System Level (requires sudo) =========================================
sudo apt-get update
sudo apt-get install -y curl build-essential ros-noetic-desktop \
ros-noetic-joy ros-noetic-tf2-tools \
python3-catkin-tools ntpdate
# === Install Miniconda (skip if already present) ===========================
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
# === Set Workspace Root (Persisted) =======================================
export CATKIN_WS=$HOME/catkin_ws # or your actual workspace root
echo "export CATKIN_WS=$CATKIN_WS" >> ~/.zshrc # or ~/.bashrc
mkdir -p $CATKIN_WS/src && cd $CATKIN_WS/src
# === Clone Repository =====================================================
# Option 1: git clone to src/
git clone https://github.com/<YOUR_FORK>/sru_nav_go2_ros1.git
# Option 2: Extract archive into src/sru_nav_go2_ros1/
# === Place ONNX Models (REQUIRED) ========================================
cp /path/to/vae_encoder.onnx $CATKIN_WS/src/sru_nav_go2_ros1/models/
cp /path/to/nav_policy.onnx $CATKIN_WS/src/sru_nav_go2_ros1/models/
# === Copy External Dependencies (REQUIRED; not in this repo) ==============
# These packages must be obtained from their respective sources:
cp -r /path/to/odin_ros_driver $CATKIN_WS/src/
cp -r /path/to/unitree_control $CATKIN_WS/src/ # or equivalent cmd_vel→Go2 bridge
# Verify odin_ros_driver/config/control_command.yaml:
# senddepth: 1 # Enable dense depth
# sendodom: 1 # Enable odom + odometry_highfreq
# === Build Conda Env (includes onnxruntime / cv2 / netifaces ...) ==========
cd $CATKIN_WS/src/sru_nav_go2_ros1
PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple \
bash scripts/setup_conda_env.sh # fully automatic; takes 5-10 minutes
bash scripts/setup_conda_env.sh --check # Should be all [OK] (ROS dist-packages may [FAIL] outside a container, ignorable)
# === Build Package (must be in conda env + workspace root) ================
mamba activate sru_go2
cd $CATKIN_WS # Must be workspace root
catkin_make -DPYTHON_EXECUTABLE=$(which python)
# === Self-Check ===========================================================
cd $CATKIN_WS/src/sru_nav_go2_ros1
bash scripts/verify_port.sh # All PASS (skips stage F if roscore is absent)
```
### B.2 Three-Terminal Launch (Every Deployment)
Prior to launching, sync system time on **any terminal**:
```bash
sudo ntpdate -u ntp.aliyun.com
```
**Terminal 1 — Odin1 Driver**
```bash
mamba activate neupan # Odin driver env
export ROS_MASTER_URI=http://localhost:11311
export ROS_HOSTNAME=localhost ROS_IP=127.0.0.1
cd $HOME/code/OAYN # Odin workspace
source ros_ws/devel/setup.zsh
roslaunch odin_ros_driver odin1_ros1.launch
```
**Terminal 2 — Go2 cmd_vel Actuator Bridge**
```bash
mamba activate sru_go2 # Same env as SRU node
export ROS_MASTER_URI=http://localhost:11311
export ROS_HOSTNAME=localhost ROS_IP=127.0.0.1
cd $CATKIN_WS
source devel/setup.zsh
rosrun unitree_control unitree_vel_controller __name:=vel_to_sdk
```
**Terminal 3 — SRU Navigation Node**
```bash
cd $CATKIN_WS/src/sru_nav_go2_ros1
ENV_NAME=sru_go2 ROS_DISTRO=noetic CATKIN_WS=$CATKIN_WS \
bash scripts/launch_sru_nav.sh require_joystick:=false
# ↑ require_joystick:=false only for tests; remove parameter for production to enable joystick deadman
```
### B.3 Verifying cmd_vel Communication (Optional Terminal 4)
```bash
mamba activate sru_go2
source /opt/ros/noetic/setup.zsh
source $CATKIN_WS/devel/setup.zsh
export ROS_MASTER_URI=http://localhost:11311
rostopic hz /odin1/depth_img_competetion # Expected: ~10 Hz
rostopic hz /odin1/odometry_highfreq # Expected: ~50 Hz
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 # Expected: Non-zero Twist stream
```
Once non-zero `/cmd_vel` starts streaming, deployment is successfully completed. Before launching outdoors, walk through the safety checklist in `docs/DEPLOY.md` §9.
+495
View File
@@ -0,0 +1,495 @@
# SRU × Odin1: Mapless Navigation with Spatially-Enhanced Recurrent Memory
<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">
</p>
<p align="center">
<b>Deploy cutting-edge paper within half a day using Odin sensor.</b>
</p>
<p align="center">
<!-- VIDEO PLACEHOLDER: Add demo video here -->
<em>Demo video coming soon</em>
</p>
---
## 1. Introduction
**SRU × Odin1** 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/>
---
## 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.
---
## 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. License & Acknowledgments
- **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.
+14
View File
@@ -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/
+3
View File
@@ -0,0 +1,3 @@
# Copy to .env and fill in.
WANDB_API_KEY=
DISPLAY=:0
+148
View File
@@ -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"]
+1
Submodule Train/IsaacLab added at 90b79bb2d4
+248
View File
@@ -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.
[![Isaac Sim](https://img.shields.io/badge/Isaac%20Sim-4.5.0-76B900?logo=nvidia)](https://developer.nvidia.com/isaac-sim)
[![IsaacLab](https://img.shields.io/badge/IsaacLab-v2.1.1-blue)](https://github.com/isaac-sim/IsaacLab)
[![Docker](https://img.shields.io/badge/Docker-Containerized-2496ED?logo=docker)](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.
+75
View File
@@ -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:
Submodule Train/mount/rsl_rl added at df600e8fd0
Submodule Train/mount/sru-navigation-sim added at 80f6c01c2d
+94
View File
@@ -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"
+99
View File
@@ -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"
+19
View File
@@ -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()
+190
View File
@@ -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"
+182
View File
@@ -0,0 +1,182 @@
#!/usr/bin/env bash
# Continue training the Go2 SRU navigation policy with explicit CLI flags.
#
# Examples:
# # Continue from the latest checkpoint of the latest run, train 1000 more iters.
# ./scripts/continue_go2.sh --iters 1000
#
# # Resume from a specific iteration of the latest run.
# ./scripts/continue_go2.sh --iters 2000 --from-iter 1000
#
# # Resume from a specific run directory + iteration.
# ./scripts/continue_go2.sh --iters 500 \
# --run-dir 2026-06-12_08-16-50_resume_from_33 --from-iter 600
#
# # Pin an exact checkpoint file (in-container path).
# ./scripts/continue_go2.sh --iters 500 \
# --checkpoint /workspace/IsaacLab/logs/rsl_rl/go2_navigation_ppo_dev/2026-06-12_08-16-50_resume_from_33/model_1000.pt
#
# # GUI mode, fewer envs.
# ./scripts/continue_go2.sh --iters 200 --envs 8 --gui
#
# # Switch to the full-PPO task (different experiment_name dir).
# ./scripts/continue_go2.sh --iters 2000 --task Isaac-Nav-PPO-Go2-v0 \
# --experiment go2_navigation_ppo_ft_from_b2w
#
# Behavior:
# - --load-optimizer is ON by default (true PPO resume); disable with --no-load-optimizer.
# - A new timestamped run directory is created; old runs are preserved.
# - The new run's --max_iterations is the *absolute* PPO iteration target,
# so set it to (start_iter + extra_iters). For convenience you can pass
# --extra-iters N which will be added to the resumed start_iter.
#
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
# ---- defaults ----
TASK="Isaac-Nav-PPO-Go2-Dev-v0"
EXPERIMENT="go2_navigation_ppo_dev" # log subdir under outputs/logs/rsl_rl/
NUM_ENVS=1024
ITERS="" # absolute target iteration count
EXTRA_ITERS="" # alternative: N more iters past the resumed checkpoint
FROM_ITER="" # specific iteration number to resume from
RUN_DIR="" # specific run dir name under <experiment>/
CHECKPOINT="" # explicit in-container checkpoint path (overrides everything)
SEED=42
RUN_NAME="" # auto-generated if empty
GUI=0
LOAD_OPTIMIZER=1
usage() {
sed -n '1,30p' "$0"
echo
echo "Flags:"
echo " --iters N Absolute target PPO iteration count (overrides max_iterations)."
echo " --extra-iters N Iters to train past the resumed start (alternative to --iters)."
echo " --from-iter N Resume from model_<N>.pt within the chosen run dir."
echo " --run-dir NAME Run dir name under outputs/logs/rsl_rl/<experiment>/."
echo " --checkpoint PATH Explicit in-container checkpoint path (overrides above)."
echo " --task NAME Gym task id (default: $TASK)."
echo " --experiment NAME Log subdir to scan (default: $EXPERIMENT)."
echo " --envs N Parallel envs (default: $NUM_ENVS)."
echo " --seed N Seed (default: $SEED)."
echo " --run-name STR Suffix for the new run dir (default: resume_from_<iter>)."
echo " --gui Show Isaac Sim GUI (X11)."
echo " --no-load-optimizer Load model only (cold optimizer)."
echo " -h, --help Show this help."
exit 0
}
# ---- arg parsing ----
while [[ $# -gt 0 ]]; do
case "$1" in
--iters) ITERS="$2"; shift 2 ;;
--extra-iters) EXTRA_ITERS="$2"; shift 2 ;;
--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 ;;
--seed) SEED="$2"; shift 2 ;;
--run-name) RUN_NAME="$2"; shift 2 ;;
--gui) GUI=1; shift ;;
--no-load-optimizer) LOAD_OPTIMIZER=0; shift ;;
-h|--help) usage ;;
*) echo "[error] Unknown arg: $1" >&2; usage ;;
esac
done
HOST_LOG_ROOT="$REPO_ROOT/outputs/logs/rsl_rl/$EXPERIMENT"
# ---- resolve checkpoint ----
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
# ---- derive start iter from filename if possible ----
START_ITER="$(basename "$HOST_CKPT" | sed -nE 's/model_([0-9]+)\.pt/\1/p')"
[[ -z "$START_ITER" ]] && START_ITER=0
# ---- resolve target iteration count ----
if [[ -z "$ITERS" && -n "$EXTRA_ITERS" ]]; then
ITERS=$(( START_ITER + EXTRA_ITERS ))
fi
if [[ -z "$ITERS" ]]; then
echo "[error] Must provide --iters N (absolute) or --extra-iters N (relative)." >&2
exit 1
fi
[[ -z "$RUN_NAME" ]] && RUN_NAME="resume_from_${START_ITER}"
# ---- GUI plumbing ----
HEADLESS_FLAG="--headless"
EXTRA_DOCKER_ARGS=()
if [[ "$GUI" == "1" ]]; then
HEADLESS_FLAG=""
xhost +local:root >/dev/null 2>&1 || xhost +local:docker >/dev/null 2>&1 || true
EXTRA_DOCKER_ARGS+=(-e "DISPLAY=${DISPLAY:-:1}"
-v /tmp/.X11-unix:/tmp/.X11-unix:rw
-v "$HOME/.Xauthority:/root/.Xauthority:ro")
fi
OPT_FLAG=""
[[ "$LOAD_OPTIMIZER" == "1" ]] && OPT_FLAG="--load_optimizer"
cat <<EOF
[continue_go2] task = $TASK
[continue_go2] experiment = $EXPERIMENT
[continue_go2] checkpoint = $CHECKPOINT
[continue_go2] start iter = $START_ITER
[continue_go2] target iter = $ITERS (= $((ITERS - START_ITER)) more)
[continue_go2] envs = $NUM_ENVS
[continue_go2] seed = $SEED
[continue_go2] run_name = $RUN_NAME
[continue_go2] gui = $GUI
[continue_go2] load_opt = $LOAD_OPTIMIZER
EOF
docker run --rm --gpus all \
-e ACCEPT_EULA=Y -e PRIVACY_CONSENT=Y \
-e PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
-e DEV_DIFFICULTY="${DEV_DIFFICULTY:-}" \
-e GO2_DIFFICULTY="${GO2_DIFFICULTY:-}" \
-e GO2_INIT_LEVEL="${GO2_INIT_LEVEL:-}" \
-e GO2_CELL_SIZE="${GO2_CELL_SIZE:-}" \
-e PUREMAZE_DIFFICULTY="${PUREMAZE_DIFFICULTY:-}" \
-e PUREMAZE_CELL_SIZE="${PUREMAZE_CELL_SIZE:-}" \
-e PUREMAZE_NUM_ROWS="${PUREMAZE_NUM_ROWS:-}" \
-e PUREMAZE_NUM_COLS="${PUREMAZE_NUM_COLS:-}" \
--shm-size=16g --network host --ipc host \
--ulimit memlock=-1 --ulimit stack=67108864 \
"${EXTRA_DOCKER_ARGS[@]}" \
-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/train.py \
--task $TASK \
--num_envs $NUM_ENVS \
--max_iterations $ITERS \
--seed $SEED \
--run_name $RUN_NAME \
--checkpoint $CHECKPOINT \
$OPT_FLAG \
$HEADLESS_FLAG"
+118
View File
@@ -0,0 +1,118 @@
"""Convert an rsl_rl-style training checkpoint (torch.save dict) into a
deployable TorchScript .pt usable by sru-navigation-sim's torch.jit.load().
Input: checkpoint with keys {model_state_dict, optimizer_state_dict, iter, infos}
where model_state_dict has actor.0.weight / actor.2.weight / ...
Output: TorchScript that does forward(obs) -> mean_actions
Usage:
/workspace/IsaacLab/_isaac_sim/python.sh /tmp/convert_rsl_rl_ckpt_to_jit.py \
<input_ckpt.pt> <output_jit.pt>
"""
import sys
import torch
import torch.nn as nn
def infer_actor_dims(state_dict):
"""Walk actor.{0,2,4,...}.weight to recover layer sizes & activation slots."""
layer_dims = []
indices = sorted(
int(k.split(".")[1])
for k in state_dict
if k.startswith("actor.") and k.endswith(".weight")
)
for idx in indices:
w = state_dict[f"actor.{idx}.weight"]
if w.ndim != 2:
continue
if not layer_dims:
layer_dims.append(w.shape[1]) # in_features of first Linear
layer_dims.append(w.shape[0]) # out_features
return layer_dims, indices
def build_actor_mlp(layer_dims, linear_indices, activation_name="elu"):
"""Build an nn.Sequential mirroring rsl_rl's actor:
Linear -> Activation -> Linear -> Activation -> ... -> Linear (no final activation)."""
if activation_name.lower() == "elu":
act_cls = nn.ELU
elif activation_name.lower() == "relu":
act_cls = nn.ReLU
elif activation_name.lower() == "tanh":
act_cls = nn.Tanh
else:
raise ValueError(f"unknown activation: {activation_name}")
# rsl_rl stores layers at indices 0, 2, 4, ... (activations live in odd slots).
# We reconstruct that exact layout so load_state_dict by name works.
layers = []
n_linears = len(layer_dims) - 1
for i in range(n_linears):
layers.append(nn.Linear(layer_dims[i], layer_dims[i + 1]))
if i < n_linears - 1:
layers.append(act_cls())
return nn.Sequential(*layers)
class DeployableActor(nn.Module):
"""Wraps the actor MLP and provides a clean forward(obs) -> mean_actions."""
def __init__(self, actor: nn.Module):
super().__init__()
self.actor = actor
def forward(self, obs: torch.Tensor) -> torch.Tensor:
return self.actor(obs)
def main():
if len(sys.argv) != 3:
print("usage: convert_rsl_rl_ckpt_to_jit.py <input.pt> <output.pt>")
sys.exit(1)
src, dst = sys.argv[1], sys.argv[2]
print(f"[convert] loading checkpoint: {src}")
ckpt = torch.load(src, map_location="cpu", weights_only=False)
sd_full = ckpt["model_state_dict"] if "model_state_dict" in ckpt else ckpt
# Strip critic / std from state dict for the actor-only deployable model.
actor_sd = {k: v for k, v in sd_full.items() if k.startswith("actor.")}
print(f"[convert] actor weights: {len(actor_sd)} tensors")
layer_dims, linear_indices = infer_actor_dims(sd_full)
print(f"[convert] actor MLP shape: {' -> '.join(map(str, layer_dims))}")
print(f"[convert] action_dim = {layer_dims[-1]}, obs_dim = {layer_dims[0]}")
actor = build_actor_mlp(layer_dims, linear_indices, activation_name="elu")
# Strip the "actor." prefix so the bare Sequential can load by index keys.
stripped_sd = {k[len("actor."):]: v for k, v in actor_sd.items()}
missing, unexpected = actor.load_state_dict(stripped_sd, strict=True)
assert not missing and not unexpected, (missing, unexpected)
print(f"[convert] state_dict loaded ✓")
deploy = DeployableActor(actor).eval()
# Sanity forward pass
with torch.inference_mode():
fake = torch.zeros(2, layer_dims[0])
out = deploy(fake)
print(f"[convert] forward sanity: in={tuple(fake.shape)} -> out={tuple(out.shape)}")
print(f"[convert] zero-input output[0]: {out[0].numpy().round(3).tolist()}")
# Trace OR script. We use script since the MLP is straight-line code.
scripted = torch.jit.script(deploy)
scripted.save(dst)
print(f"[convert] saved TorchScript model: {dst}")
# Verify round-trip
reloaded = torch.jit.load(dst, map_location="cpu")
with torch.inference_mode():
out2 = reloaded(fake)
assert torch.allclose(out, out2, atol=1e-6), "round-trip mismatch!"
print(f"[convert] round-trip torch.jit.load() works ✓")
if __name__ == "__main__":
main()
+102
View File
@@ -0,0 +1,102 @@
#!/usr/bin/env bash
# Evaluate a TorchScript JIT navigation policy (e.g. the official B2W baseline
# nav_policy_new.pt) on the IsaacLab navigation env, with the same PLAY_*
# terrain env vars as eval_terminations.sh.
#
# Example: baseline on dense paper-style maze
# PLAY_DIFFICULTY="0.8,1.0" \
# PLAY_SUBTERRAIN_MIX="maze=1,non_maze=0,pits=0" \
# PLAY_CLASSIC_MAZE=1 \
# ./scripts/eval_jit_baseline.sh \
# --task Isaac-Nav-PPO-B2W-Play-v0 \
# --jit-policy assets/baselines/b2w_nav_policy_new.pt \
# --envs 32 --steps 2000
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
TASK="Isaac-Nav-PPO-B2W-Play-v0"
JIT_HOST=""
NUM_ENVS=32
STEPS=2000
SEED=42
usage() {
cat <<EOF
Usage: $(basename "$0") --jit-policy PATH [options]
Required:
--jit-policy PATH Host path to a TorchScript .pt policy.
(will be mounted into /workspace at /jit_policy.pt)
Options:
--task NAME Gym task id (default: $TASK).
--envs N Parallel envs (default: $NUM_ENVS).
--steps N env.step() calls (default: $STEPS).
--seed N (default: $SEED).
-h, --help Show this help.
Forwarded env vars (set on host):
PLAY_DIFFICULTY="lo,hi"
PLAY_SUBTERRAIN_MIX="maze=1,non_maze=0,pits=0"
PLAY_MAZE_ONLY=1
PLAY_CELL_SIZE=2.0
PLAY_CLASSIC_MAZE=1
EOF
exit 0
}
while [[ $# -gt 0 ]]; do
case "$1" in
--jit-policy) JIT_HOST="$2"; shift 2 ;;
--task) TASK="$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
[[ -z "$JIT_HOST" ]] && { echo "[error] --jit-policy is required." >&2; exit 1; }
# Resolve to absolute path
if [[ "$JIT_HOST" != /* ]]; then JIT_HOST="$REPO_ROOT/$JIT_HOST"; fi
[[ -f "$JIT_HOST" ]] || { echo "[error] JIT file not found: $JIT_HOST" >&2; exit 1; }
JIT_CTR="/workspace/baseline_policy.pt"
cat <<EOF
[eval-jit] task = $TASK
[eval-jit] jit (host) = $JIT_HOST
[eval-jit] jit (ctr) = $JIT_CTR
[eval-jit] envs = $NUM_ENVS
[eval-jit] steps = $STEPS
[eval-jit] PLAY_DIFFICULTY = ${PLAY_DIFFICULTY:-(default)}
[eval-jit] PLAY_SUBTERRAIN_MIX = ${PLAY_SUBTERRAIN_MIX:-(default)}
[eval-jit] PLAY_MAZE_ONLY = ${PLAY_MAZE_ONLY:-(default)}
[eval-jit] PLAY_CELL_SIZE = ${PLAY_CELL_SIZE:-(default)}
[eval-jit] PLAY_CLASSIC_MAZE = ${PLAY_CLASSIC_MAZE:-(default)}
EOF
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" \
-v "$JIT_HOST:$JIT_CTR:ro" \
--entrypoint bash sru-nav:latest -lc \
"./isaaclab.sh -p source/isaaclab_nav_task/scripts/eval_jit_policy.py \
--task $TASK \
--num_envs $NUM_ENVS \
--steps $STEPS \
--seed $SEED \
--jit_policy $JIT_CTR \
--headless"
+94
View File
@@ -0,0 +1,94 @@
#!/usr/bin/env bash
# Headless termination breakdown evaluator. Counts per-term terminations over
# N steps so we can read the *true* pit-fall rate (terrain_fall) now that the
# Go2 cfg has tightened fall_height_threshold to -0.3m.
#
# Examples:
# # Latest run, latest ckpt, 64 envs, 2000 steps
# ./scripts/eval_terminations.sh
#
# # Specific run + iter + difficulty band
# PLAY_DIFFICULTY="0.3,0.8" ./scripts/eval_terminations.sh \
# --run-dir 2026-06-20_12-07-08_phase5_refine_0.3_0.8 --from-iter 27800
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
TASK="Isaac-Nav-PPO-Go2-Play-v0"
EXPERIMENT="go2_navigation_ppo_dev"
NUM_ENVS=64
STEPS=2000
FROM_ITER=""
RUN_DIR=""
CHECKPOINT=""
SEED=42
usage() { sed -n '1,15p' "$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"
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
[eval] task = $TASK
[eval] checkpoint = $CHECKPOINT
[eval] host file = $HOST_CKPT
[eval] envs = $NUM_ENVS
[eval] steps = $STEPS
[eval] PLAY_DIFFICULTY = ${PLAY_DIFFICULTY:-(default)}
EOF
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/eval_terminations.py \
--task $TASK \
--num_envs $NUM_ENVS \
--steps $STEPS \
--seed $SEED \
--checkpoint $CHECKPOINT \
--headless"
+251
View File
@@ -0,0 +1,251 @@
#!/usr/bin/env python3
"""Export a trained SRU navigation policy checkpoint to ONNX.
This script reconstructs the ActorCriticSRU model from the checkpoint's
weight shapes (no Isaac Sim / IsaacLab needed), loads the weights, and
calls the built-in export_onnx method.
Usage:
# Export a specific checkpoint
python scripts/export_onnx.py --checkpoint outputs/logs/rsl_rl/go2_navigation_ppo_mixed/<run>/model_4600.pt
# Export and also save JIT
python scripts/export_onnx.py --checkpoint <path> --jit
# Override output location
python scripts/export_onnx.py --checkpoint <path> --output-dir ./exported
Requirements:
- torch
- The rsl_rl fork must be importable (pip-installed or on PYTHONPATH)
ONNX model interface (ActorCriticSRU, single camera):
Inputs:
- obs: (1, num_actor_obs) — flattened observation vector
- h_in: (num_layers, 1, hidden) — LSTM hidden state (zeros at episode start)
- c_in: (num_layers, 1, hidden) — LSTM cell state (zeros at episode start)
Outputs:
- actions: (1, num_actions)
- h_out: (num_layers, 1, hidden) — updated hidden state
- c_out: (num_layers, 1, hidden) — updated cell state
"""
from __future__ import annotations
import argparse
import os
import sys
from pathlib import Path
import torch
def infer_config_from_state_dict(sd: dict) -> dict:
"""Infer ActorCriticSRU constructor args from checkpoint weight shapes."""
# --- image_input_dims and num_cameras ---
# attn_image_net cross-attention query projection weight: (Q, image_dim)
# The first linear in CrossAttentionFuseModule is the query proj.
# We look for attn_image_net.0.weight or similar.
attn_keys = [k for k in sd if k.startswith("attn_image_net.") and "weight" in k]
if not attn_keys:
raise ValueError("Cannot find attn_image_net weights in checkpoint")
# image_dim = out_features of the query projection
# CrossAttentionFuseModule: q_proj weight shape = (image_dim, image_dim)
# Find the first weight (query proj)
attn_w = sd[attn_keys[0]]
image_dim = attn_w.shape[0] # output features
# num_image_features = image_dim * H * W
# We can get it from the actor input: actor_proprioceptive_input_dim + num_image_features = num_actor_obs
# But we need H, W separately. Get from attn_image_net spatial reshape.
# CrossAttentionFuseModule stores no spatial dims as parameters.
# Instead, infer from total image features: look at the first linear of actor
# which takes mlp_input_dim_actor = actor_proprioceptive_input_dim + image_dim
# num_image_features = image_dim * H * W
# We need H, W from image_input_dims=(C, H, W) where C=image_dim.
# Check if there's a pattern in the attn weights that reveals spatial dims.
# Fallback: use the known Go2 config defaults.
# The Go2 config uses image_input_dims=(64, 5, 8), height_input_dims=(64, 7, 7).
# image_dim=64, H=5, W=8 -> num_image_features = 64*5*8 = 2560
# We can infer num_image_features from the observation dimension:
# num_actor_obs = actor_proprioceptive_input_dim + num_image_features * num_cameras
# actor_proprioceptive_input_dim = mlp_input_dim_actor - image_dim
# mlp_input_dim_actor = memory_a input size = rnn input_size
# Get rnn input_size from memory_a.rnn weight
rnn_keys = [k for k in sd if k.startswith("memory_a.") and "weight_ih" in k]
if not rnn_keys:
raise ValueError("Cannot find memory_a.rnn.weight_ih in checkpoint")
rnn_input_size = sd[rnn_keys[0]].shape[1] # input size of LSTM
rnn_hidden_size = sd[rnn_keys[0]].shape[0] // 4 # LSTM has 4 gates
# mlp_input_dim_actor = rnn_input_size
# actor_proprioceptive_input_dim = mlp_input_dim_actor - image_dim
actor_proprioceptive_input_dim = rnn_input_size - image_dim
# Get num_image_features from the linear_dropout_actor or actor first layer
# linear_dropout_actor.linear weight: (actor_hidden_dims[0], rnn_hidden_size)
ld_keys = [k for k in sd if k.startswith("linear_dropout_actor.") and "weight" in k]
if ld_keys:
actor_hidden_0 = sd[ld_keys[0]].shape[0]
else:
actor_hidden_0 = 512 # default
# Get num_actions from actor last layer
actor_linear_keys = [k for k in sd if k.startswith("actor.") and "weight" in k]
if not actor_linear_keys:
raise ValueError("Cannot find actor weights in checkpoint")
# Last actor layer weight: (num_actions, actor_hidden_dims[-1])
last_actor_w = sd[actor_linear_keys[-1]]
num_actions = last_actor_w.shape[0]
# Infer num_cameras: num_actor_obs = actor_proprioceptive_input_dim + num_image_features * num_cameras
# We need num_actor_obs. We can get it from the attn_image_net input.
# CrossAttentionFuseModule q_proj input = image_dim, k_proj input = info_dim = actor_proprioceptive_input_dim
# But we still can't directly get num_image_features.
# However, for Go2 with 1 camera: num_image_features = image_dim * H * W = 64 * 5 * 8 = 2560
# For 2 cameras: num_actor_obs = actor_proprioceptive + 2 * num_image_features
# We can try both and see which gives a "reasonable" obs dim.
# Actually, we can get num_image_features from the attn_image_net more carefully.
# CrossAttentionFuseModule reshapes image (B, C, H, W) -> (B, H*W, C) then projects.
# The number of spatial tokens = H * W. This doesn't show up as a weight shape.
#
# Strategy: use known Go2 defaults (image_input_dims=(64,5,8), num_cameras=1)
# and verify consistency.
H, W = 5, 8 # Go2 default
num_image_features = image_dim * H * W
num_cameras = 1 # Go2 default
num_actor_obs = actor_proprioceptive_input_dim + num_image_features * num_cameras
# Infer height_input_dims for critic (not needed for actor export but for constructor)
height_dim = image_dim # default 64
hH, hW = 7, 7 # Go2 default
num_height_features = height_dim * hH * hW
# critic_proprioceptive_input_dim = num_critic_obs - num_height_features - num_image_features * num_cameras - 1
# We need num_critic_obs. Get from critic rnn input.
critic_rnn_keys = [k for k in sd if k.startswith("memory_c.") and "weight_ih" in k]
if critic_rnn_keys:
critic_rnn_input = sd[critic_rnn_keys[0]].shape[1]
critic_proprioceptive = critic_rnn_input - image_dim - height_dim
num_critic_obs = critic_proprioceptive + num_height_features + num_image_features * num_cameras + 1
else:
num_critic_obs = num_actor_obs # fallback
# rnn_num_layers
rnn_num_layers = len([k for k in sd if k.startswith("memory_a.") and "weight_ih_l" in k])
if rnn_num_layers == 0:
rnn_num_layers = 1
# actor_hidden_dims from actor weights
actor_hidden_dims = []
for k in sorted(actor_linear_keys):
w = sd[k]
actor_hidden_dims.append(w.shape[1])
# Last layer's shape[0] is num_actions, not a hidden dim
if actor_hidden_dims:
actor_hidden_dims[-1] = actor_hidden_dims[-1] # keep last hidden
# Actually actor weights: layer0 (h1, in), layer1 (h2, h1), ..., layerN (num_actions, hN)
# So hidden_dims = [in_of_first] ... no, hidden_dims = [h1, h2, ..., hN]
# weight shapes: (h1, in), (h2, h1), ..., (num_actions, hN)
# hidden_dims = [out of each layer except last] = [h1, h2, ..., hN]
actor_hidden_dims = []
for i, k in enumerate(sorted(actor_linear_keys)):
w = sd[k]
if i < len(actor_linear_keys) - 1:
actor_hidden_dims.append(w.shape[0]) # output dim = next hidden
# last layer: shape[0] = num_actions
config = {
"num_actor_obs": num_actor_obs,
"num_critic_obs": num_critic_obs,
"num_actions": num_actions,
"actor_hidden_dims": actor_hidden_dims if actor_hidden_dims else [512, 256, 128],
"critic_hidden_dims": actor_hidden_dims if actor_hidden_dims else [512, 256, 128],
"activation": "elu",
"init_noise_std": 1.0,
"image_input_dims": (image_dim, H, W),
"height_input_dims": (height_dim, hH, hW),
"rnn_type": "lstm_sru",
"dropout": 0.2,
"rnn_hidden_size": rnn_hidden_size,
"rnn_num_layers": rnn_num_layers,
"time_embed_dim": 8,
"num_cameras": num_cameras,
}
return config
def main():
parser = argparse.ArgumentParser(description="Export SRU navigation policy checkpoint to ONNX.")
parser.add_argument("--checkpoint", type=str, required=True,
help="Path to model checkpoint (.pt file)")
parser.add_argument("--output-dir", type=str, default=None,
help="Output directory (default: <checkpoint_dir>/export)")
parser.add_argument("--filename", type=str, default="policy.onnx",
help="Output filename (default: policy.onnx)")
parser.add_argument("--jit", action="store_true",
help="Also export JIT (policy.pt)")
parser.add_argument("--verbose", action="store_true",
help="Print inferred config and model architecture")
args = parser.parse_args()
checkpoint_path = Path(args.checkpoint).resolve()
if not checkpoint_path.exists():
print(f"[error] Checkpoint not found: {checkpoint_path}", file=sys.stderr)
sys.exit(1)
# Load checkpoint
print(f"[export_onnx] Loading checkpoint: {checkpoint_path}")
ckpt = torch.load(str(checkpoint_path), map_location="cpu", weights_only=False)
sd = ckpt["model_state_dict"]
print(f"[export_onnx] Checkpoint iteration: {ckpt.get('iter', 'unknown')}")
# Infer model config from weights
config = infer_config_from_state_dict(sd)
if args.verbose:
print("\n[export_onnx] Inferred config:")
for k, v in config.items():
print(f" {k}: {v}")
print()
# Build model
from rsl_rl.modules import ActorCriticSRU
model = ActorCriticSRU(**config)
model.load_state_dict(sd, strict=True)
model.eval()
model.to("cpu")
print(f"[export_onnx] Model loaded successfully")
print(f" num_actor_obs: {config['num_actor_obs']}")
print(f" num_actions: {config['num_actions']}")
print(f" num_cameras: {config['num_cameras']}")
print(f" image_dims: {config['image_input_dims']}")
print(f" rnn_hidden: {config['rnn_hidden_size']}")
# Determine output directory
if args.output_dir:
output_dir = Path(args.output_dir)
else:
output_dir = checkpoint_path.parent / "export"
# Export ONNX
print(f"\n[export_onnx] Exporting ONNX to: {output_dir}/{args.filename}")
model.export_onnx(path=str(output_dir), filename=args.filename)
# Optionally export JIT
if args.jit:
jit_filename = args.filename.replace(".onnx", ".pt")
if jit_filename == args.filename:
jit_filename = "policy.pt"
print(f"\n[export_onnx] Exporting JIT to: {output_dir}/{jit_filename}")
model.export_jit(path=str(output_dir), filename=jit_filename)
print(f"\n[export_onnx] Done! Output: {output_dir}")
if __name__ == "__main__":
main()
+218
View File
@@ -0,0 +1,218 @@
#!/usr/bin/env python3
"""Inspect a SRU-Go2 training run: dump TensorBoard scalars + ckpt summary.
Usage:
python scripts/inspect_run.py --run outputs/logs/rsl_rl/<exp>/<timestamp_runname>
python scripts/inspect_run.py --latest # auto-pick newest run
python scripts/inspect_run.py --latest --experiment go2_navigation_ppo_dev
python scripts/inspect_run.py --run <path> --tags Train/mean_reward Loss/value_function
The script tries `tensorboard` first, falls back to `tbparse`, then to a
minimal pure-protobuf reader. Prints a compact markdown-friendly summary
that can be pasted directly into docs/RUN_LOG.md.
"""
from __future__ import annotations
import argparse
import glob
import os
import re
import sys
from pathlib import Path
from typing import Dict, List, Tuple
REPO_ROOT = Path(__file__).resolve().parents[1]
DEFAULT_LOG_ROOT = REPO_ROOT / "outputs" / "logs" / "rsl_rl"
# Tags worth surfacing by default (rsl_rl + custom). The script will keep only
# the ones that actually appear in the events file.
DEFAULT_TAGS = [
"Train/mean_reward",
"Train/mean_episode_length",
"Train/learning_rate",
"Loss/value_function",
"Loss/surrogate",
"Loss/entropy",
"Policy/mean_noise_std",
"Train/mean_success_rate",
"Train/mean_collision_rate",
]
def _find_latest_run(experiment: str | None) -> Path:
if experiment:
roots = [DEFAULT_LOG_ROOT / experiment]
else:
roots = sorted([p for p in DEFAULT_LOG_ROOT.iterdir() if p.is_dir()])
candidates: List[Path] = []
for root in roots:
if not root.exists():
continue
for entry in root.iterdir():
if entry.is_dir() and re.match(r"\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}", entry.name):
candidates.append(entry)
if not candidates:
raise SystemExit(f"[inspect_run] No runs under {DEFAULT_LOG_ROOT}")
candidates.sort(key=lambda p: p.stat().st_mtime)
return candidates[-1]
def _read_scalars(run_dir: Path) -> Dict[str, List[Tuple[int, float]]]:
"""Read all scalar tags from the run's tfevents files.
Returns mapping: tag -> list[(step, value)] sorted by step.
Tries tensorboard.EventAccumulator; falls back to tbparse; then raw protobuf.
"""
files = sorted(glob.glob(str(run_dir / "events.out.tfevents.*")))
if not files:
raise SystemExit(f"[inspect_run] No tfevents in {run_dir}")
# --- attempt 1: tensorboard ---
try:
from tensorboard.backend.event_processing.event_accumulator import EventAccumulator
acc = EventAccumulator(str(run_dir), size_guidance={"scalars": 0})
acc.Reload()
out: Dict[str, List[Tuple[int, float]]] = {}
for tag in acc.Tags().get("scalars", []):
out[tag] = [(e.step, e.value) for e in acc.Scalars(tag)]
return out
except Exception as e:
print(f"[inspect_run] tensorboard path failed: {e}; trying tbparse", file=sys.stderr)
# --- attempt 2: tbparse ---
try:
from tbparse import SummaryReader # type: ignore
reader = SummaryReader(str(run_dir), pivot=False)
df = reader.scalars
out2: Dict[str, List[Tuple[int, float]]] = {}
for tag, group in df.groupby("tag"):
group = group.sort_values("step")
out2[tag] = list(zip(group["step"].astype(int), group["value"].astype(float)))
return out2
except Exception as e:
print(f"[inspect_run] tbparse failed: {e}; trying raw protobuf", file=sys.stderr)
# --- attempt 3: raw protobuf via tensorflow ---
try:
import tensorflow as tf # type: ignore
out3: Dict[str, List[Tuple[int, float]]] = {}
for f in files:
for raw in tf.data.TFRecordDataset(f):
ev = tf.compat.v1.Event.FromString(raw.numpy())
if not ev.summary:
continue
for v in ev.summary.value:
if v.HasField("simple_value"):
out3.setdefault(v.tag, []).append((int(ev.step), float(v.simple_value)))
for k in out3:
out3[k].sort()
return out3
except Exception as e:
raise SystemExit(
f"[inspect_run] All readers failed. Install one of:\n"
f" pip install tensorboard\n pip install tbparse\n"
f"Last error: {e}"
)
def _summarize(series: List[Tuple[int, float]]) -> dict:
if not series:
return {}
steps = [s for s, _ in series]
vals = [v for _, v in series]
peak_idx = max(range(len(vals)), key=lambda i: vals[i])
min_idx = min(range(len(vals)), key=lambda i: vals[i])
# last-decile mean to smooth jitter
tail = vals[max(0, len(vals) - max(1, len(vals) // 10)) :]
return {
"start_step": steps[0],
"start_val": vals[0],
"end_step": steps[-1],
"end_val": vals[-1],
"peak_step": steps[peak_idx],
"peak_val": vals[peak_idx],
"min_step": steps[min_idx],
"min_val": vals[min_idx],
"tail_mean": sum(tail) / len(tail),
"n_points": len(series),
}
def _ckpt_summary(run_dir: Path) -> dict:
ckpts = sorted(run_dir.glob("model_*.pt"), key=lambda p: int(re.findall(r"model_(\d+)\.pt", p.name)[0]))
if not ckpts:
return {}
latest = ckpts[-1]
iter_n = int(re.findall(r"model_(\d+)\.pt", latest.name)[0])
return {
"count": len(ckpts),
"latest": latest.name,
"latest_iter": iter_n,
"size_mb": latest.stat().st_size / 1024 / 1024,
"all_iters": [int(re.findall(r"model_(\d+)\.pt", p.name)[0]) for p in ckpts],
}
def _md_table(rows: List[List[str]], header: List[str]) -> str:
out = ["| " + " | ".join(header) + " |", "| " + " | ".join(["---"] * len(header)) + " |"]
for r in rows:
out.append("| " + " | ".join(r) + " |")
return "\n".join(out)
def main():
ap = argparse.ArgumentParser()
g = ap.add_mutually_exclusive_group()
g.add_argument("--run", type=str, help="Path to a run directory (host).")
g.add_argument("--latest", action="store_true", help="Pick newest run under outputs/logs/rsl_rl/.")
ap.add_argument("--experiment", type=str, default=None, help="Restrict --latest to this experiment subdir.")
ap.add_argument("--tags", nargs="*", default=None, help="Override the tag whitelist; pass tag names.")
ap.add_argument("--all-tags", action="store_true", help="Print every scalar tag found.")
args = ap.parse_args()
if args.run:
run_dir = Path(args.run).resolve()
else:
run_dir = _find_latest_run(args.experiment)
if not run_dir.exists():
raise SystemExit(f"[inspect_run] Not a dir: {run_dir}")
print(f"# Run inspection\n")
print(f"- **dir**: `{run_dir}`")
ck = _ckpt_summary(run_dir)
if ck:
print(f"- **checkpoints**: {ck['count']} files, latest `{ck['latest']}` "
f"(iter {ck['latest_iter']}, {ck['size_mb']:.1f} MB)")
print(f"- **all iters saved**: {ck['all_iters']}")
print()
scalars = _read_scalars(run_dir)
tags = args.tags or (list(scalars.keys()) if args.all_tags else DEFAULT_TAGS)
rows = []
for tag in tags:
if tag not in scalars:
continue
s = _summarize(scalars[tag])
if not s:
continue
rows.append([
f"`{tag}`",
f"{s['start_val']:.3g} @ {s['start_step']}",
f"{s['end_val']:.3g} @ {s['end_step']}",
f"{s['peak_val']:.3g} @ {s['peak_step']}",
f"{s['min_val']:.3g} @ {s['min_step']}",
f"{s['tail_mean']:.3g}",
str(s["n_points"]),
])
print("## Scalars\n")
if rows:
print(_md_table(rows, ["tag", "start", "end", "peak", "min", "tail-mean(10%)", "n"]))
else:
print("_no matching tags found_")
print(f"\navailable tags: {sorted(scalars.keys())}")
print()
if __name__ == "__main__":
main()
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/env bash
# Launch the Isaac Sim full GUI (no task, no policy) in the project's docker.
# Use this to manually inspect USDs (e.g. drag the Go2 USD into the stage,
# expand link tree, view collision meshes).
#
# Usage:
# ./scripts/open_isaacsim_gui.sh
#
# To open the Go2 USD inside the GUI:
# 1. File -> Open -> paste the URL printed below into the file picker
# 2. Or drag it from the Content browser (left panel):
# Robots/Unitree/Go2/go2.usd
set -e
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
xhost +local:root >/dev/null 2>&1 || xhost +local:docker >/dev/null 2>&1 || true
cat <<EOF
[host] DISPLAY=${DISPLAY:-:1}
[host] Launching Isaac Sim GUI from sru-nav:latest ...
To inspect the Go2 USD once GUI is up, look under the Content browser:
omniverse://localhost/NVIDIA/Assets/Isaac/<ver>/Isaac/Robots/Unitree/Go2/go2.usd
or via the cloud asset path used by IsaacLab:
\$ISAACLAB_NUCLEUS_DIR/Robots/Unitree/Go2/go2.usd
EOF
docker run --rm --gpus all \
-e ACCEPT_EULA=Y -e PRIVACY_CONSENT=Y \
-e DISPLAY="${DISPLAY:-:1}" \
-e PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
--shm-size=16g --network host --ipc host \
--ulimit memlock=-1 --ulimit stack=67108864 \
-v /tmp/.X11-unix:/tmp/.X11-unix:rw \
-v "$HOME/.Xauthority:/root/.Xauthority:ro" \
-v "$REPO_ROOT/outputs/logs:/workspace/IsaacLab/logs" \
-v "$REPO_ROOT/mount/sru-navigation-sim:/workspace/IsaacLab/source/isaaclab_nav_task" \
--entrypoint bash sru-nav:latest -lc \
"/isaac-sim/isaac-sim.sh"
+120
View File
@@ -0,0 +1,120 @@
#!/usr/bin/env bash
# Visualize / evaluate a TorchScript JIT navigation policy (e.g. the official
# upstream B2W baseline ``nav_policy_new.pt``) in the IsaacLab pure-maze env.
#
# Examples:
# # GUI viewer, 4 envs, paper-style classic maze
# PLAY_CLASSIC_MAZE=1 PLAY_DIFFICULTY="0.8,1.0" \
# ./scripts/play_b2w_jit.sh --jit-policy assets/baselines/b2w_nav_policy_new.pt
#
# # Headless stats run (no GUI)
# PLAY_CLASSIC_MAZE=1 PLAY_DIFFICULTY="0.8,1.0" \
# ./scripts/play_b2w_jit.sh \
# --jit-policy assets/baselines/b2w_nav_policy_new.pt \
# --headless --envs 32 --steps 2000
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
# ---- defaults (GUI-friendly) ----
TASK="Isaac-Nav-PPO-B2W-Play-v0"
JIT_HOST=""
NUM_ENVS=4
STEPS=100000 # huge so the viewer just keeps running until user closes it
SEED=42
HEADLESS=0
usage() {
cat <<EOF
Usage: $(basename "$0") --jit-policy PATH [options]
Required:
--jit-policy PATH Host path to TorchScript .pt policy
(mounted into /workspace/baseline_policy.pt).
Options:
--task NAME Gym task id (default: $TASK).
--envs N Parallel envs (default: $NUM_ENVS — GUI-friendly).
--steps N env.step() calls (default: $STEPS).
--seed N (default: $SEED).
--headless Run without GUI (faster, no X11).
-h, --help Show this help.
Forwarded env vars (set on host):
PLAY_DIFFICULTY="lo,hi" terrain difficulty band
PLAY_SUBTERRAIN_MIX=... e.g. "maze=1,non_maze=0,pits=0"
PLAY_MAZE_ONLY=1 100% maze sub-terrain
PLAY_CELL_SIZE=2.0 m per maze cell (B2W needs >= ~1.5)
PLAY_CLASSIC_MAZE=1 paper-style uniform walls
EOF
exit 0
}
while [[ $# -gt 0 ]]; do
case "$1" in
--jit-policy) JIT_HOST="$2"; shift 2 ;;
--task) TASK="$2"; shift 2 ;;
--envs) NUM_ENVS="$2"; shift 2 ;;
--steps) STEPS="$2"; shift 2 ;;
--seed) SEED="$2"; shift 2 ;;
--headless) HEADLESS=1; shift ;;
-h|--help) usage ;;
*) echo "[error] Unknown arg: $1" >&2; usage ;;
esac
done
[[ -z "$JIT_HOST" ]] && { echo "[error] --jit-policy is required." >&2; exit 1; }
if [[ "$JIT_HOST" != /* ]]; then JIT_HOST="$REPO_ROOT/$JIT_HOST"; fi
[[ -f "$JIT_HOST" ]] || { echo "[error] JIT file not found: $JIT_HOST" >&2; exit 1; }
JIT_CTR="/workspace/baseline_policy.pt"
# ---- GUI plumbing (same as play_go2.sh) ----
EXTRA_DOCKER_ARGS=()
HEADLESS_FLAG=""
if [[ "$HEADLESS" == "0" ]]; then
xhost +local:root >/dev/null 2>&1 || xhost +local:docker >/dev/null 2>&1 || true
EXTRA_DOCKER_ARGS+=(-e "DISPLAY=${DISPLAY:-:1}"
-v /tmp/.X11-unix:/tmp/.X11-unix:rw
-v "$HOME/.Xauthority:/root/.Xauthority:ro")
else
HEADLESS_FLAG="--headless"
fi
cat <<EOF
[play_b2w_jit] task = $TASK
[play_b2w_jit] jit (host) = $JIT_HOST
[play_b2w_jit] jit (ctr) = $JIT_CTR
[play_b2w_jit] envs = $NUM_ENVS
[play_b2w_jit] steps = $STEPS
[play_b2w_jit] headless = $HEADLESS
[play_b2w_jit] PLAY_DIFFICULTY = ${PLAY_DIFFICULTY:-(default)}
[play_b2w_jit] PLAY_SUBTERRAIN_MIX = ${PLAY_SUBTERRAIN_MIX:-(default)}
[play_b2w_jit] PLAY_MAZE_ONLY = ${PLAY_MAZE_ONLY:-(default)}
[play_b2w_jit] PLAY_CELL_SIZE = ${PLAY_CELL_SIZE:-(default)}
[play_b2w_jit] PLAY_CLASSIC_MAZE = ${PLAY_CLASSIC_MAZE:-(default)}
EOF
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 \
"${EXTRA_DOCKER_ARGS[@]}" \
-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" \
-v "$JIT_HOST:$JIT_CTR:ro" \
--entrypoint bash sru-nav:latest -lc \
"./isaaclab.sh -p source/isaaclab_nav_task/scripts/eval_jit_policy.py \
--task $TASK \
--num_envs $NUM_ENVS \
--steps $STEPS \
--seed $SEED \
--jit_policy $JIT_CTR \
$HEADLESS_FLAG"
+162
View File
@@ -0,0 +1,162 @@
#!/usr/bin/env bash
# Replay a trained Go2 SRU navigation policy in the Isaac Sim GUI.
#
# Examples:
# # Latest run, latest checkpoint, 4 envs (default)
# ./scripts/play_go2.sh
#
# # Specific iter from latest run
# ./scripts/play_go2.sh --from-iter 1000
#
# # Specific iter from a specific run dir
# ./scripts/play_go2.sh \
# --run-dir 2026-06-12_09-32-44_resume_from_1000 \
# --from-iter 50999
#
# # Pin an exact in-container checkpoint path
# ./scripts/play_go2.sh --checkpoint \
# /workspace/IsaacLab/logs/rsl_rl/go2_navigation_ppo_dev/<run>/model_500.pt
#
# # Headless replay (no GUI), e.g. on a server
# ./scripts/play_go2.sh --from-iter 800 --headless --envs 1
#
# # Browse a different experiment dir (e.g. full PPO)
# ./scripts/play_go2.sh --experiment go2_navigation_ppo_ft_from_b2w --from-iter 5000
#
# Notes:
# * --run-dir is the timestamped folder name under
# outputs/logs/rsl_rl/<experiment>/.
# * If neither --run-dir nor --checkpoint is given, the latest run is picked.
# * If --from-iter is omitted, the latest model_*.pt in the run dir is used.
# * The Play task disables corruption / pushes / large terrain to make the
# viewer behave well; that is decided by --task (default: Play-v0).
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
# ---- defaults ----
TASK="Isaac-Nav-PPO-Go2-Play-v0"
EXPERIMENT="go2_navigation_ppo_dev"
NUM_ENVS=4
FROM_ITER=""
RUN_DIR=""
CHECKPOINT=""
HEADLESS=0
SEED=42
EXPORT_ONNX=0
EXPORT_JIT=0
usage() {
sed -n '1,30p' "$0"
echo
echo "Flags:"
echo " --from-iter N Replay model_<N>.pt within the chosen run dir."
echo " --run-dir NAME Run dir name under outputs/logs/rsl_rl/<experiment>/."
echo " --checkpoint PATH Explicit IN-CONTAINER path (overrides --run-dir/--from-iter)."
echo " --task NAME Gym task id (default: $TASK)."
echo " --experiment NAME Log subdir (default: $EXPERIMENT)."
echo " --envs N Parallel envs (default: $NUM_ENVS)."
echo " --seed N Seed (default: $SEED)."
echo " --headless Run without GUI (faster, no X11)."
echo " --export-onnx Also export policy to <run-dir>/export/policy.onnx."
echo " --export-jit Also export policy to <run-dir>/export/policy.pt (TorchScript)."
echo " -h, --help Show this help."
exit 0
}
# ---- arg parsing ----
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 ;;
--seed) SEED="$2"; shift 2 ;;
--headless) HEADLESS=1; shift ;;
--export-onnx) EXPORT_ONNX=1; shift ;;
--export-jit) EXPORT_JIT=1; shift ;;
-h|--help) usage ;;
*) echo "[error] Unknown arg: $1" >&2; usage ;;
esac
done
HOST_LOG_ROOT="$REPO_ROOT/outputs/logs/rsl_rl/$EXPERIMENT"
# ---- resolve checkpoint ----
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"
if [[ ! -f "$HOST_CKPT" ]]; then
echo "[error] Checkpoint not found: $HOST_CKPT" >&2
echo "[hint] Available iters in $RUN_DIR:" >&2
ls -1 "$RUN_PATH"/model_*.pt 2>/dev/null \
| sed -nE 's/.*model_([0-9]+)\.pt/ \1/p' \
| paste -sd ' ' >&2
exit 1
fi
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
# ---- GUI plumbing ----
EXTRA_DOCKER_ARGS=()
HEADLESS_FLAG=""
if [[ "$HEADLESS" == "0" ]]; then
xhost +local:root >/dev/null 2>&1 || xhost +local:docker >/dev/null 2>&1 || true
EXTRA_DOCKER_ARGS+=(-e "DISPLAY=${DISPLAY:-:1}"
-v /tmp/.X11-unix:/tmp/.X11-unix:rw
-v "$HOME/.Xauthority:/root/.Xauthority:ro")
else
HEADLESS_FLAG="--headless"
fi
cat <<EOF
[play_go2] task = $TASK
[play_go2] experiment = $EXPERIMENT
[play_go2] checkpoint = $CHECKPOINT
[play_go2] host file = $HOST_CKPT
[play_go2] envs = $NUM_ENVS
[play_go2] headless = $HEADLESS
EOF
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:-}" \
-e PUREMAZE_DIFFICULTY="${PUREMAZE_DIFFICULTY:-}" \
-e PUREMAZE_CELL_SIZE="${PUREMAZE_CELL_SIZE:-}" \
-e PUREMAZE_NUM_ROWS="${PUREMAZE_NUM_ROWS:-}" \
-e PUREMAZE_NUM_COLS="${PUREMAZE_NUM_COLS:-}" \
--shm-size=16g --network host --ipc host \
--ulimit memlock=-1 --ulimit stack=67108864 \
"${EXTRA_DOCKER_ARGS[@]}" \
-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/play.py \
--task $TASK \
--num_envs $NUM_ENVS \
--seed $SEED \
--checkpoint $CHECKPOINT \
$HEADLESS_FLAG \
$([[ $EXPORT_ONNX == 1 ]] && echo --export_onnx) \
$([[ $EXPORT_JIT == 1 ]] && echo --export_jit)"
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env bash
# Replay a trained Go2 navigation policy in the Isaac Sim GUI (X11 forwarded).
#
# Usage:
# ./scripts/play_go2_gui.sh # latest dev run, 4 envs
# NUM_ENVS=8 ./scripts/play_go2_gui.sh
# CHECKPOINT=/workspace/IsaacLab/logs/rsl_rl/go2_navigation_ppo_dev/2026-06-12_06-25-41/model_33.pt \
# ./scripts/play_go2_gui.sh
#
# The CHECKPOINT path must be the IN-CONTAINER path (under /workspace/IsaacLab/logs/...).
set -e
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
NUM_ENVS="${NUM_ENVS:-4}"
TASK="${TASK:-Isaac-Nav-PPO-Go2-Play-v0}"
# Which experiment subdir to scan when CHECKPOINT not given. Override with
# EXPERIMENT=go2_navigation_ppo_puremaze for P0 / maze runs.
EXPERIMENT="${EXPERIMENT:-go2_navigation_ppo_dev}"
# Auto-pick the latest checkpoint under <EXPERIMENT> if none was provided.
if [[ -z "${CHECKPOINT:-}" ]]; then
HOST_LOG_ROOT="$REPO_ROOT/outputs/logs/rsl_rl/$EXPERIMENT"
LATEST_RUN="$(ls -1 "$HOST_LOG_ROOT" 2>/dev/null | sort | tail -n 1 || true)"
if [[ -z "$LATEST_RUN" ]]; then
echo "[error] No runs found under $HOST_LOG_ROOT and no CHECKPOINT given." >&2
exit 1
fi
LATEST_CKPT="$(ls -1 "$HOST_LOG_ROOT/$LATEST_RUN"/model_*.pt 2>/dev/null | sort -V | tail -n 1)"
if [[ -z "$LATEST_CKPT" ]]; then
echo "[error] No model_*.pt found in $HOST_LOG_ROOT/$LATEST_RUN" >&2
exit 1
fi
# Map host path -> in-container path.
CHECKPOINT="${LATEST_CKPT/$REPO_ROOT\/outputs\/logs/\/workspace\/IsaacLab\/logs}"
fi
xhost +local:root >/dev/null 2>&1 || xhost +local:docker >/dev/null 2>&1 || true
echo "[host] DISPLAY=${DISPLAY:-:1}"
echo "[host] task=$TASK num_envs=$NUM_ENVS"
echo "[host] checkpoint (in container) = $CHECKPOINT"
docker run --rm --gpus all \
-e ACCEPT_EULA=Y -e PRIVACY_CONSENT=Y \
-e DISPLAY="${DISPLAY:-:1}" \
-e PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
-e PLAY_DIFFICULTY="${PLAY_DIFFICULTY:-}" \
-e PLAY_CELL_SIZE="${PLAY_CELL_SIZE:-}" \
-e PLAY_MAZE_ONLY="${PLAY_MAZE_ONLY:-}" \
-e PLAY_CLASSIC_MAZE="${PLAY_CLASSIC_MAZE:-}" \
-e PLAY_SUBTERRAIN_MIX="${PLAY_SUBTERRAIN_MIX:-}" \
--shm-size=16g --network host --ipc host \
--ulimit memlock=-1 --ulimit stack=67108864 \
-v /tmp/.X11-unix:/tmp/.X11-unix:rw \
-v "$HOME/.Xauthority:/root/.Xauthority:ro" \
-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/play.py \
--task $TASK \
--num_envs $NUM_ENVS \
--checkpoint $CHECKPOINT"
+224
View File
@@ -0,0 +1,224 @@
"""Diagnose a TorchScript locomotion .pt file's interface.
Run inside the sru-nav container; mount this script at /tmp/probe_pt.py.
Reports:
1. TorchScript graph code (top-level forward signature)
2. State-dict key names + shapes (gives clues about layer order / obs slicing)
3. Tries common observation dimensions to find the input width
4. Output dimension (= number of joint targets the policy emits)
5. A quick "what zero input produces" check (sanity for output range)
"""
import os
import sys
import torch
DEFAULT_PT = (
"/workspace/IsaacLab/source/isaaclab_nav_task/isaaclab_nav_task/"
"navigation/assets/data/Policies/locomotion/go2/policy_go2.pt"
)
PT_PATH = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_PT
assert os.path.isfile(PT_PATH), f"File not found: {PT_PATH}"
print(f"[probe] loading: {PT_PATH}")
print(f"[probe] file size: {os.path.getsize(PT_PATH) / 1e6:.2f} MB")
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"[probe] device: {device}")
is_torchscript = False
model = None
raw_obj = None
try:
model = torch.jit.load(PT_PATH, map_location=device)
model.eval()
is_torchscript = True
print(f"[probe] format: TorchScript ✓")
print(f"[probe] type: {type(model).__name__}")
except Exception as e:
print(f"[probe] torch.jit.load FAILED: {str(e).splitlines()[0][:120]}")
print(f"[probe] → falling back to torch.load() (pickle)")
try:
raw_obj = torch.load(PT_PATH, map_location=device, weights_only=False)
print(f"[probe] format: pickle (torch.save) — NOT TorchScript")
print(f"[probe] top-level type: {type(raw_obj).__name__}")
except Exception as e2:
print(f"[probe] torch.load ALSO failed: {e2}")
sys.exit(1)
if not is_torchscript:
print("\n=========================================================")
print(" ⚠ This file is NOT a TorchScript model.")
print(" sru-navigation-sim calls `torch.jit.load(.pt)` which will fail.")
print(" You need to either:")
print(" (a) Re-export your policy with torch.jit.script(model).save(...)")
print(" (b) Provide the original nn.Module class so we wrap+script it")
print("=========================================================\n")
# Inspect the loaded object
print("=========================================================")
print(" Contents of torch.load() output")
print("=========================================================")
if isinstance(raw_obj, dict):
print(f" dict with {len(raw_obj)} top-level keys:")
for k, v in raw_obj.items():
t = type(v).__name__
extra = ""
if isinstance(v, torch.Tensor):
extra = f" shape={tuple(v.shape)} dtype={v.dtype}"
elif isinstance(v, dict):
extra = f" ({len(v)} sub-keys)"
print(f" [{k!r}] {t}{extra}")
# If it has 'model_state_dict' or 'state_dict' or is itself a state_dict, dump shapes
sd = None
for key in ["model_state_dict", "state_dict", "model", "policy"]:
if key in raw_obj and isinstance(raw_obj[key], dict):
sd = raw_obj[key]
print(f"\n → Found state-dict under key {key!r}")
break
if sd is None and all(isinstance(v, torch.Tensor) for v in raw_obj.values()):
sd = raw_obj
print(f"\n → Top-level dict appears to be a state_dict itself")
if sd is not None:
print(f"\n State-dict keys & shapes ({len(sd)} entries):")
for i, (k, v) in enumerate(sd.items()):
shape = tuple(v.shape) if isinstance(v, torch.Tensor) else type(v).__name__
print(f" [{i:2d}] {k:60s} {shape}")
if i >= 50:
print(f" ... ({len(sd) - 51} more)")
break
# First Linear's in_features
first_linear_in = None
for k, v in sd.items():
if isinstance(v, torch.Tensor) and v.ndim == 2 and "weight" in k.lower():
first_linear_in = v.shape[1]
print(f"\n → first 2D-weight key {k!r} has in_features = {first_linear_in}")
print(f" most likely D_obs = {first_linear_in}")
break
# Last Linear's out_features
last_linear_out = None
last_linear_key = None
for k, v in sd.items():
if isinstance(v, torch.Tensor) and v.ndim == 2 and "weight" in k.lower():
last_linear_out = v.shape[0]
last_linear_key = k
if last_linear_out is not None:
print(f" → last 2D-weight key {last_linear_key!r} has out_features = {last_linear_out}")
print(f" most likely action_dim = {last_linear_out}")
elif isinstance(raw_obj, torch.nn.Module):
print(f" → It's a raw nn.Module instance (untraced). Class: {type(raw_obj).__name__}")
print(f" → We can try to forward it directly without TorchScript.")
model = raw_obj
model.eval()
is_torchscript = False
else:
print(f" (unsupported type: {type(raw_obj)})")
print("\n[probe] done — see message above for next steps.")
sys.exit(0)
print("\n=========================================================")
print("1. TorchScript .code (forward signature & top-level graph)")
print("=========================================================")
try:
code = getattr(model, "code", None)
if code is None:
print("(no .code attribute -- model may be a ScriptFunction)")
else:
print(code[:4000])
except Exception as e:
print(f"(error reading .code: {e})")
print("\n=========================================================")
print("2. State dict keys & shapes")
print("=========================================================")
sd = model.state_dict()
print(f"total params: {sum(v.numel() for v in sd.values()):,}")
for i, (k, v) in enumerate(sd.items()):
print(f" [{i:2d}] {k:60s} {tuple(v.shape)}")
if i >= 40:
print(f" ... ({len(sd) - 41} more)")
break
# First Linear layer's input dim is a strong hint for D_obs
first_weight = next(
(v for k, v in sd.items() if v.ndim == 2 and ("weight" in k or k.endswith(".weight"))),
None,
)
hint_obs = first_weight.shape[1] if first_weight is not None else None
if hint_obs is not None:
print(f"\n[probe] first Linear weight has in_features = {hint_obs}")
print(f" → most likely D_obs = {hint_obs}")
print("\n=========================================================")
print("3. Trying input dimensions (looking for the one that works)")
print("=========================================================")
# Common Go2 obs dims:
# 33 = 3+3+3+3+12+12 (no last_action)
# 45 = 3+3+3+3+12+12+12 (with last_action of joint dim)
# 48 = 3+3+3+3+12+12+12+3 (with last_action including vel cmd)
# 52 = 3+3+3+3+12+12+16 (sru-nav-sim LowLevelPolicyCfg, with B2W-style last_action=16)
# 60 = 3+3+3+3+12+12+12+12 (joint pos+vel+pos+vel duplicated)
# 235 = with height_scan (legged_gym style)
candidate_dims = [33, 36, 39, 42, 45, 48, 51, 52, 60, 96, 235]
if hint_obs is not None and hint_obs not in candidate_dims:
candidate_dims.insert(0, hint_obs)
working_dims = []
for d in candidate_dims:
try:
with torch.inference_mode():
out = model(torch.zeros(2, d, device=device))
if isinstance(out, tuple):
shapes = [tuple(o.shape) for o in out if isinstance(o, torch.Tensor)]
print(f" D_obs = {d:3d} ✓ (tuple output, shapes={shapes})")
else:
print(f" D_obs = {d:3d} ✓ output shape = {tuple(out.shape)}")
working_dims.append((d, tuple(out.shape)))
except Exception as e:
msg = str(e).split("\n")[0][:90]
print(f" D_obs = {d:3d} ✗ {msg}")
print("\n=========================================================")
print("4. Summary")
print("=========================================================")
if not working_dims:
print(" ⚠ NO standard input dim worked.")
print(" → Inspect step-2 first-Linear in_features and try that exact size.")
print(f" → Expected: D_obs = {hint_obs}")
else:
for d, out_shape in working_dims:
n_out = out_shape[1] if len(out_shape) >= 2 else None
print(f" D_obs = {d}, output_dim = {n_out}")
if n_out == 12:
print(" → 12 outputs = pure leg joint targets (Go2 has 12 leg joints).")
print(" You'll use `low_level_velocity_action = None` (the patched action term).")
elif n_out == 16:
print(" → 16 outputs matches B2W layout (12 legs + 4 wheels).")
print(" Adapter must zero-pad if your Go2 only emits 12.")
elif n_out == 18:
print(" → 18 outputs = 12 legs + something extra (maybe 6 dummy?).")
else:
print(f" → {n_out} outputs is unusual; verify against your training task.")
print("\n=========================================================")
print("5. Probing zero-input output magnitude (sanity)")
print("=========================================================")
if working_dims:
d, _ = working_dims[0]
with torch.inference_mode():
out = model(torch.zeros(1, d, device=device))
if isinstance(out, torch.Tensor):
print(f" output[0] (first 12 dims): "
f"{out[0, :12].cpu().numpy().round(3).tolist()}")
print(f" output stats: mean={out.mean().item():.3f}, "
f"std={out.std().item():.3f}, "
f"min={out.min().item():.3f}, max={out.max().item():.3f}")
if out.abs().max() > 5.0:
print(" ⚠ Output magnitude > 5; policy likely emits raw joint angles or torques.")
print(" Standard IsaacLab convention: tanh-bounded ∈ [-1, 1].")
elif out.abs().max() < 0.05:
print(" ⚠ Output extremely small; may be a state_dict-only file (not a working policy).")
else:
print(" ✓ Output magnitude looks reasonable.")
print("\n[probe] done")
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env bash
# Run probe_pt.py inside the sru-nav container against the Go2 locomotion .pt.
# Usage:
# ./scripts/probe_pt.sh # uses default path under mount/
# ./scripts/probe_pt.sh /custom/path/in/host # absolute host path
set -e
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
HOST_PT="${1:-$REPO_ROOT/mount/sru-navigation-sim/isaaclab_nav_task/navigation/assets/data/Policies/locomotion/go2/policy_go2.pt}"
if [[ ! -f "$HOST_PT" ]]; then
echo "ERROR: .pt not found at: $HOST_PT"
echo " Copy your Go2 locomotion .pt there first."
exit 1
fi
echo "[host] probing: $HOST_PT"
echo "[host] file size: $(du -h "$HOST_PT" | cut -f1)"
# Translate the host path to the corresponding container path (the mount).
HOST_NAV_SIM="$REPO_ROOT/mount/sru-navigation-sim"
CONTAINER_NAV_SIM="/workspace/IsaacLab/source/isaaclab_nav_task"
if [[ "$HOST_PT" == "$HOST_NAV_SIM"/* ]]; then
CONTAINER_PT="${HOST_PT/$HOST_NAV_SIM/$CONTAINER_NAV_SIM}"
else
echo "ERROR: .pt must live under $HOST_NAV_SIM (the live-mounted folder)."
echo " Got: $HOST_PT"
exit 1
fi
echo "[host] container path: $CONTAINER_PT"
docker run --rm --gpus all \
-e ACCEPT_EULA=Y -e PRIVACY_CONSENT=Y \
--shm-size=4g --ipc host \
-v "$REPO_ROOT/scripts/probe_pt.py:/tmp/probe_pt.py:ro" \
-v "$REPO_ROOT/mount/sru-navigation-sim:/workspace/IsaacLab/source/isaaclab_nav_task" \
--entrypoint bash sru-nav:latest -lc \
"/workspace/IsaacLab/_isaac_sim/python.sh /tmp/probe_pt.py '$CONTAINER_PT'"
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
set -e
cd /workspace/IsaacLab
./isaaclab.sh -p source/isaaclab_nav_task/scripts/train.py \
--task Isaac-Nav-MDPO-AoW-D-v0 \
--num_envs ${NUM_ENVS:-2048} \
--max_iterations ${MAX_ITERS:-10000} \
--headless \
"$@"
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# Quick dev/smoke-test (300 iters, tensorboard).
set -e
cd /workspace/IsaacLab
./isaaclab.sh -p source/isaaclab_nav_task/scripts/train.py \
--task Isaac-Nav-PPO-B2W-Dev-v0 \
--num_envs ${NUM_ENVS:-32} \
--headless \
"$@"
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# Run inside the container.
set -e
cd /workspace/IsaacLab
./isaaclab.sh -p source/isaaclab_nav_task/scripts/train.py \
--task Isaac-Nav-PPO-B2W-v0 \
--num_envs ${NUM_ENVS:-4096} \
--headless \
"$@"
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/env bash
# Continue training the Go2 SRU navigation policy from the latest dev checkpoint.
#
# Defaults: headless (no GUI for speed), Dev task (same cfg as the previous
# 33-iter run), warm-start with optimizer state so PPO truly resumes.
#
# Usage:
# ./scripts/train_go2_continue.sh # 1000 iter, 24 envs
# NUM_ENVS=32 MAX_ITER=2000 ./scripts/train_go2_continue.sh
# CHECKPOINT=/workspace/IsaacLab/logs/.../model_33.pt ./scripts/train_go2_continue.sh
# GUI=1 ./scripts/train_go2_continue.sh # show Isaac Sim GUI
# TASK=Isaac-Nav-PPO-Go2-v0 ./scripts/train_go2_continue.sh # full PPO task (5000 iter cap)
#
# Notes:
# * CHECKPOINT must be the IN-CONTAINER path under /workspace/IsaacLab/logs/...
# * --load_optimizer keeps PPO momentum / adaptive-LR state, so loss curves
# look continuous instead of restarting cold.
# * RTX 5070 has 12 GB VRAM. 24 envs headless is conservative; tune up if free.
set -e
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
NUM_ENVS="${NUM_ENVS:-24}"
MAX_ITER="${MAX_ITER:-1000}"
TASK="${TASK:-Isaac-Nav-PPO-Go2-Dev-v0}"
GUI="${GUI:-0}"
SEED="${SEED:-42}"
RUN_NAME="${RUN_NAME:-resume_from_33}"
# Auto-pick the latest dev checkpoint if none provided.
if [[ -z "${CHECKPOINT:-}" ]]; then
HOST_LOG_ROOT="$REPO_ROOT/outputs/logs/rsl_rl/go2_navigation_ppo_dev"
LATEST_RUN="$(ls -1 "$HOST_LOG_ROOT" 2>/dev/null | sort | tail -n 1 || true)"
if [[ -z "$LATEST_RUN" ]]; then
echo "[error] No previous runs under $HOST_LOG_ROOT and no CHECKPOINT given." >&2
exit 1
fi
LATEST_CKPT="$(ls -1 "$HOST_LOG_ROOT/$LATEST_RUN"/model_*.pt 2>/dev/null | sort -V | tail -n 1)"
if [[ -z "$LATEST_CKPT" ]]; then
echo "[error] No model_*.pt found in $HOST_LOG_ROOT/$LATEST_RUN" >&2
exit 1
fi
CHECKPOINT="${LATEST_CKPT/$REPO_ROOT\/outputs\/logs/\/workspace\/IsaacLab\/logs}"
fi
HEADLESS_FLAG="--headless"
EXTRA_DOCKER_ARGS=()
if [[ "$GUI" == "1" ]]; then
HEADLESS_FLAG=""
xhost +local:root >/dev/null 2>&1 || xhost +local:docker >/dev/null 2>&1 || true
EXTRA_DOCKER_ARGS+=(-e "DISPLAY=${DISPLAY:-:1}"
-v /tmp/.X11-unix:/tmp/.X11-unix:rw
-v "$HOME/.Xauthority:/root/.Xauthority:ro")
fi
echo "[host] task=$TASK num_envs=$NUM_ENVS max_iter=$MAX_ITER gui=$GUI"
echo "[host] checkpoint (in container) = $CHECKPOINT"
echo "[host] run_name=$RUN_NAME seed=$SEED"
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 \
"${EXTRA_DOCKER_ARGS[@]}" \
-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/train.py \
--task $TASK \
--num_envs $NUM_ENVS \
--max_iterations $MAX_ITER \
--seed $SEED \
--run_name $RUN_NAME \
--checkpoint $CHECKPOINT \
--load_optimizer \
$HEADLESS_FLAG"
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env bash
# Train Go2 nav with the Isaac Sim GUI visible (X11 forwarded from host).
# Default: 30 iterations, small env count, so you can watch the dogs walking.
#
# Usage:
# ./scripts/train_go2_gui.sh # 30 iter, 32 envs, GUI
# NUM_ENVS=16 MAX_ITER=100 ./scripts/train_go2_gui.sh
#
set -e
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
NUM_ENVS="${NUM_ENVS:-32}"
MAX_ITER="${MAX_ITER:-30}"
TASK="${TASK:-Isaac-Nav-PPO-Go2-Dev-v0}"
# Allow the docker user (any UID) to talk to the host X server.
# This affects only the local user's X server.
xhost +local:root >/dev/null 2>&1 || xhost +local:docker >/dev/null 2>&1 || true
echo "[host] DISPLAY=${DISPLAY:-:1}"
echo "[host] task=$TASK num_envs=$NUM_ENVS max_iterations=$MAX_ITER"
docker run --rm --gpus all \
-e ACCEPT_EULA=Y -e PRIVACY_CONSENT=Y \
-e DISPLAY="${DISPLAY:-:1}" \
-e PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
--shm-size=16g --network host --ipc host \
--ulimit memlock=-1 --ulimit stack=67108864 \
-v /tmp/.X11-unix:/tmp/.X11-unix:rw \
-v "$HOME/.Xauthority:/root/.Xauthority:ro" \
-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/train.py \
--task $TASK \
--num_envs $NUM_ENVS \
--max_iterations $MAX_ITER"
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/env bash
# Train the Go2 SRU navigation policy FROM SCRATCH (no checkpoint).
#
# Defaults: headless, 24 envs, 1000 iter, Dev task, seed=42.
# Use this when you intentionally want a cold start (e.g. after sweeping
# reward / action / terrain shaping where the previous policy mean has
# collapsed into a degenerate solution and resuming would just re-learn it).
#
# Usage:
# ./scripts/train_go2_scratch.sh # 1000 iter, 24 envs, headless
# NUM_ENVS=16 MAX_ITER=500 ./scripts/train_go2_scratch.sh
# GUI=1 NUM_ENVS=4 MAX_ITER=200 ./scripts/train_go2_scratch.sh
# TASK=Isaac-Nav-PPO-Go2-v0 RUN_NAME=scratch_full ./scripts/train_go2_scratch.sh
#
# Notes:
# * No --checkpoint flag is passed, so the agent + critic are re-initialised.
# * RTX 5070 (12 GB VRAM): 24 envs headless is the safe default. GUI + 32
# envs OOMs (G0.0 lesson).
# * Output goes to outputs/logs/rsl_rl/<EXPERIMENT>/<timestamp>_<RUN_NAME>/.
set -e
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
NUM_ENVS="${NUM_ENVS:-24}"
MAX_ITER="${MAX_ITER:-1000}"
TASK="${TASK:-Isaac-Nav-PPO-Go2-Dev-v0}"
GUI="${GUI:-0}"
SEED="${SEED:-42}"
RUN_NAME="${RUN_NAME:-scratch_reward_fix_v1}"
# GPU selection. Set GPU=0 / GPU=1 / GPU=0,1 to pin specific cards.
# Empty (default) = all visible GPUs (--gpus all). The container sees the selected
# GPU(s) as cuda:0,cuda:1,... so the training process always uses cuda:0 inside.
GPU="${GPU:-}"
GPU_FLAG="--gpus all"
if [[ -n "$GPU" ]]; then
GPU_FLAG="--gpus device=${GPU}"
fi
HEADLESS_FLAG="--headless"
EXTRA_DOCKER_ARGS=()
if [[ "$GUI" == "1" ]]; then
HEADLESS_FLAG=""
xhost +local:root >/dev/null 2>&1 || xhost +local:docker >/dev/null 2>&1 || true
EXTRA_DOCKER_ARGS+=(-e "DISPLAY=${DISPLAY:-:1}"
-v /tmp/.X11-unix:/tmp/.X11-unix:rw
-v "$HOME/.Xauthority:/root/.Xauthority:ro")
fi
cat <<EOF
[train_go2_scratch] task = $TASK
[train_go2_scratch] num_envs = $NUM_ENVS
[train_go2_scratch] max_iter = $MAX_ITER
[train_go2_scratch] seed = $SEED
[train_go2_scratch] run_name = $RUN_NAME
[train_go2_scratch] gui = $GUI
[train_go2_scratch] gpu = ${GPU:-all}
[train_go2_scratch] (no --checkpoint: cold start)
EOF
docker run --rm $GPU_FLAG \
--name "go2_train_gpu${GPU:-all}_${RUN_NAME}_$$" \
-e ACCEPT_EULA=Y -e PRIVACY_CONSENT=Y \
-e PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
-e DEV_DIFFICULTY="${DEV_DIFFICULTY:-}" \
-e GO2_DIFFICULTY="${GO2_DIFFICULTY:-}" \
-e GO2_INIT_LEVEL="${GO2_INIT_LEVEL:-}" \
-e GO2_CELL_SIZE="${GO2_CELL_SIZE:-}" \
-e PUREMAZE_DIFFICULTY="${PUREMAZE_DIFFICULTY:-}" \
-e PUREMAZE_CELL_SIZE="${PUREMAZE_CELL_SIZE:-}" \
-e PUREMAZE_NUM_ROWS="${PUREMAZE_NUM_ROWS:-}" \
-e PUREMAZE_NUM_COLS="${PUREMAZE_NUM_COLS:-}" \
--shm-size=16g --network host --ipc host \
--ulimit memlock=-1 --ulimit stack=67108864 \
"${EXTRA_DOCKER_ARGS[@]}" \
-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/train.py \
--task $TASK \
--num_envs $NUM_ENVS \
--max_iterations $MAX_ITER \
--seed $SEED \
--run_name $RUN_NAME \
$HEADLESS_FLAG"
+167
View File
@@ -0,0 +1,167 @@
"""Validate that policy_go2_jit.pt produces correct Go2 locomotion inside the
sru-navigation-sim environment, without any high-level navigation policy.
We feed hard-coded SE2 commands (vx, vy, omega) directly into env.step() and
measure the actual base motion that results. This isolates the low-level
locomotion contract from any navigation training.
Test sequence (each phase ~3 seconds):
1. Stand still (0.0, 0.0, 0.0) -> expect: stays upright, ~0 velocity
2. Forward walk (0.5, 0.0, 0.0) -> expect: moves +X, vx ~ 0.3 m/s
3. Backward walk (-0.5, 0.0, 0.0) -> expect: moves -X, vx ~ -0.3 m/s
4. Lateral right (0.0, 0.5, 0.0) -> expect: moves +Y (limited)
5. Rotate (yaw) (0.0, 0.0, 0.5) -> expect: omega ~ 0.35 rad/s
Run:
./isaaclab.sh -p /tmp/validate_go2_locomotion.py --num_envs 4 --headless
"""
from __future__ import annotations
import argparse
from isaaclab.app import AppLauncher
parser = argparse.ArgumentParser()
parser.add_argument("--task", default="Isaac-Nav-PPO-Go2-Dev-v0")
parser.add_argument("--num_envs", type=int, default=4)
parser.add_argument("--phase_seconds", type=float, default=3.0)
AppLauncher.add_app_launcher_args(parser)
args = parser.parse_args()
args.headless = True
args.enable_cameras = True # depth camera obs needed by env
app_launcher = AppLauncher(args)
simulation_app = app_launcher.app
import torch # noqa: E402
import gymnasium as gym # noqa: E402
import isaaclab_nav_task # noqa: F401, E402
from isaaclab_tasks.utils.parse_cfg import parse_env_cfg # noqa: E402
def main():
env_cfg = parse_env_cfg(
args.task, device="cuda:0", num_envs=args.num_envs, use_fabric=True
)
env = gym.make(args.task, cfg=env_cfg)
print(f"[validate] action_space = {env.action_space}")
print(f"[validate] observation_space (policy group) = "
f"{env.observation_space['policy'].shape}")
obs, _ = env.reset()
device = env.unwrapped.device
# Phase definitions: (label, command, num_steps)
# The env decimation is 4 (low-level @ 50 Hz), and the high-level step is
# called at 10 Hz (env.step). So phase_seconds * 10 = num steps.
phase_steps = int(args.phase_seconds * 10)
phases = [
("stand_still", torch.tensor([ 0.0, 0.0, 0.0])),
("forward", torch.tensor([ 0.7, 0.0, 0.0])),
("backward", torch.tensor([-0.7, 0.0, 0.0])),
("lateral_right", torch.tensor([ 0.0, 0.7, 0.0])),
("yaw_rotate", torch.tensor([ 0.0, 0.0, 0.7])),
]
# Probe sensors
robot = env.unwrapped.scene["robot"]
print("\n" + "=" * 78)
print(f"{'phase':<16} {'cmd (vx,vy,ω)':<22} "
f"{'measured (vx,vy,ω)':<22} "
f"{'h(m)':>6} {'pitch':>7} {'falls':>6}")
print("=" * 78)
fails = []
for label, cmd in phases:
# Fresh reset per phase so prior falls / terrain placement don't bias
# the next phase's height measurement.
env.reset()
cmd_batch = cmd.to(device).unsqueeze(0).expand(args.num_envs, -1).contiguous()
# Reset stats for this phase
v_lin_sum = torch.zeros(3, device=device)
omega_sum = torch.zeros(1, device=device)
height_sum = torch.zeros(1, device=device)
pitch_max = 0.0
n_steps = 0
falls = 0
for _ in range(phase_steps):
obs, _, terminated, truncated, _ = env.step(cmd_batch)
n_steps += 1
base_lin_vel = robot.data.root_lin_vel_b # body frame, (N, 3)
base_ang_vel = robot.data.root_ang_vel_b
root_pos = robot.data.root_pos_w # (N, 3)
grav_b = robot.data.projected_gravity_b # (N, 3)
v_lin_sum += base_lin_vel.mean(dim=0)
omega_sum += base_ang_vel[:, 2].mean().unsqueeze(0)
height_sum += root_pos[:, 2].mean().unsqueeze(0)
# pitch = angle between projected_gravity_b and (-Z body) = (0,0,-1)
pitch_now = (
torch.acos(torch.clamp(-grav_b[:, 2], -1.0, 1.0))
.max().item()
)
pitch_max = max(pitch_max, pitch_now)
falls += int(terminated.any().item() or truncated.any().item())
v_lin = (v_lin_sum / n_steps).cpu().numpy().round(3).tolist()
omega = (omega_sum / n_steps).item()
h_avg = (height_sum / n_steps).item()
# Height threshold uses world-frame Z; the rough terrain in the dev env
# can place the robot on top of features up to ~0.25 m, so allow up
# to 0.65 m total for a healthy Go2 body (~0.40 m default standing).
ok_height = 0.20 < h_avg < 0.70
ok_pitch = pitch_max < 0.6
ok_overall = ok_height and ok_pitch
flag = "✓" if ok_overall else "✗"
cmd_str = f"({cmd[0]:+.1f},{cmd[1]:+.1f},{cmd[2]:+.1f})"
meas_str = f"({v_lin[0]:+.2f},{v_lin[1]:+.2f},{omega:+.2f})"
print(f"{flag} {label:<14} {cmd_str:<22} {meas_str:<22} "
f"{h_avg:>6.3f} {pitch_max:>6.2f}r {falls:>6d}")
# Per-phase pass criteria
if label == "stand_still":
if abs(v_lin[0]) > 0.15 or abs(v_lin[1]) > 0.15:
fails.append(f"{label}: drifting at zero command "
f"(v_lin={v_lin})")
elif label == "forward":
if v_lin[0] < 0.10:
fails.append(f"{label}: not moving forward "
f"(vx={v_lin[0]:.2f})")
elif label == "backward":
if v_lin[0] > -0.10:
fails.append(f"{label}: not moving backward "
f"(vx={v_lin[0]:.2f})")
elif label == "yaw_rotate":
if abs(omega) < 0.10:
fails.append(f"{label}: not rotating (ω={omega:.2f})")
if not ok_height:
fails.append(f"{label}: body too low/high (h={h_avg:.2f})")
if not ok_pitch:
fails.append(f"{label}: tilted over (max pitch={pitch_max:.2f} rad)")
print("=" * 78)
if fails:
print("\n⚠ FAILED CHECKS:")
for f in fails:
print(f" - {f}")
print("\nLikely causes:")
print(" • Action scale mismatch (training used different scale)")
print(" • Joint order mismatch between policy output and IsaacLab USD")
print(" • Observation order mismatch")
else:
print("\n✅ ALL LOCOMOTION CHECKS PASSED")
print(" Go2 stands, walks forward/back, and rotates as commanded.")
print(" Locomotion contract with sru-navigation-sim is correct.")
env.close()
simulation_app.close()
if __name__ == "__main__":
main()