对tools进行了整理,Xmake也改为相对路径,在线 LiDAR-IMU 定位器实现
This commit is contained in:
1 parent
0602144ac5
commit
4502296915
70 files changed
+2648
-1294
No files matched your search
@@ -11,7 +11,7 @@
|
||||
|
||||
## 当前定位入口
|
||||
|
||||
默认定位已切换到连续跟踪的 LIO(`field_localization_node`)。必须先用 `LIO_MODE=mapping` 建立并导出 3D 地图,再以只读地图定位;缺图会明确报错。完整用法、时间/外参约定和局限见 [field_localization](src/field_localization/README.md)。
|
||||
默认定位已切换到连续跟踪的 LIO(`field_localization_node`)。Shell 和 Python 启动默认只读加载仓库随附的 `src/sentry_sim/maps/field_full.flmap`,覆盖当前 Gazebo 场地。完整用法、时间/外参约定和局限见 [field_localization](src/field_localization/README.md)。
|
||||
|
||||
`LOCALIZATION=amcl scripts/sentry_up.sh`(或 Python 启动参数 `localization:=amcl`)选择旧方案。下文与 `docs/定位接入AMCL.md` 中的 AMCL 参数/排障说明仅适用于该分支。每次只启动一种定位器发布 `map→odom`,两种方案均保留 Nav2 的 2D map_server。
|
||||
|
||||
@@ -60,7 +60,7 @@ sentry_nav_dev/ 仓库根(xmake 工程根)
|
||||
│ │
|
||||
│ ├── sentry_nav/ 导航/决策节点(C++,唯一的可编译包)
|
||||
│ └── sentry_sim/ 仿真环境(147 MB,其中网格 146 MB)
|
||||
├── tools/ 模型转换与调试工具(独立脚本,不参与构建)
|
||||
├── tools/ 日常工具、验收和启动/构建辅助脚本
|
||||
├── generated/ 运行时产物(可随时删)
|
||||
├── .vscode/ IDE 配置(不影响仿真)
|
||||
└── build/ xmake 构建产物(不入 git)
|
||||
@@ -74,7 +74,7 @@ sentry_nav_dev/ 仓库根(xmake 工程根)
|
||||
| `src/sentry_nav/` | 算法代码 | 在这块实现算法 |
|
||||
| `src/sentry_sim/` | 仿真基础设施(模型/参数/启动) | 改模型和调参时动 |
|
||||
| `field/` | 官方场地包副本(地图 + 3D 场地) | 官方更新时整包替换 |
|
||||
| `tools/` | 辅助工具脚本 | 按需加新工具 |
|
||||
| `tools/` | [工具索引](tools/README.md) | 日常命令在顶层,内部脚本与验收分别归档 |
|
||||
| `docs/` | 技术文档 | 有新发现就补 |
|
||||
| `generated/` | 运行时产物 | 可删 |
|
||||
| `build/` | xmake 产物 | 不入 git |
|
||||
@@ -132,7 +132,7 @@ ros2 launch src/sentry_sim/launch/sentry_arena.launch.py headless:=true rviz:=fa
|
||||
cd ~/Gazebo_projects/sentry_nav_dev
|
||||
HEADLESS=0 scripts/sentry_up.sh # 启动(日志自动落盘 generated/up.log)
|
||||
python3 tools/check_stack.py # 体检(只读)
|
||||
build/bin/nav_client 2.0 2.0 # 发一个导航目标(先 xmake 编译)
|
||||
build/bin/nav_client 0.0 0.0 # 发一个导航目标(先 xmake 编译)
|
||||
ros2 topic pub -r 10 /cmd_vel geometry_msgs/msg/Twist "{linear: {x: 0.5}}" # 手动前进
|
||||
```
|
||||
|
||||
|
||||
+15
-13
@@ -125,6 +125,8 @@ build/bin/nav_client 2.0 2.0 # 目标 x=2.0 y=2.0(场地坐标,米)
|
||||
换一个开阔的点,或先在 RViz 里看一眼 /global_costmap/costmap。
|
||||
```
|
||||
|
||||
发目标前,客户端还会检查 `map → base_link` 的时效。发现 LIO 心跳时,要求最近 0.3 秒内收到有效心跳。`--force` 只跳过静态地图预检。Nav2 返回的错误码和消息会随结果打印,中止、取消和超时均返回非零退出码。
|
||||
|
||||
**通过预检后**长这样(地图行与预检行是实算的,位姿行是格式示意,逐条刷新):
|
||||
|
||||
```
|
||||
@@ -225,10 +227,10 @@ python3 tools/check_stack.py # 一次性检查节点/话题/TF/真
|
||||
|
||||
## 6. 环境变量
|
||||
|
||||
**路径和版本相关的变量全部是「不设就自动探测」**,探测逻辑只有一份:
|
||||
`src/sentry_sim/scripts/env_common.sh`(shell)和 `tools/project_env.py`(Python)。
|
||||
想看本机实际探到什么:`python3 tools/project_env.py`
|
||||
或(不启动任何进程)`SENTRY_DRY_RUN=1 scripts/sentry_up.sh`。
|
||||
Shell 和 Python 的路径与版本探测都由 `tools/project_env.py` 实现。
|
||||
用 `python3 tools/project_env.py` 查看探测结果,或运行 `SENTRY_DRY_RUN=1 scripts/sentry_up.sh` 预演启动。
|
||||
单项查询成功返回 `0`,探测失败返回 `1`,参数错误返回 `2`。失败时 stdout 为空,错误写入 stderr。
|
||||
未构建时 `--bin-dir` 仍返回预期的 `build/bin`,已加载 ROS 时 `--ros-setup` 返回空值。
|
||||
|
||||
### 行为开关
|
||||
|
||||
@@ -239,6 +241,7 @@ python3 tools/check_stack.py # 一次性检查节点/话题/TF/真
|
||||
| `RVIZ` | `1` | `0` = 不起 RViz |
|
||||
| `ROS_DOMAIN_ID` | `0` | 两个终端必须一致才能互相看到话题 |
|
||||
| `GZ_PARTITION` | `sentry` | Gazebo 分区,多套仿真隔离用 |
|
||||
| `BRIDGE_WAIT_TIMEOUT` | `120` | 等待 Gazebo 发布 `/clock` 的秒数。单次查询至多 2 秒,等不到时启动失败 |
|
||||
| `SENTRY_DRY_RUN` | `0` | `1` = 只打印探测结果然后退出,不启动任何进程 |
|
||||
| `SENTRY_LOG` | `1` | 启动日志自动写 `generated/up.log`(每次加分隔线)。`0` = 关闭,`<路径>` = 换位置 |
|
||||
| `SENTRY_SIM_SHARE` | 仓库内 `src/sentry_sim` | 数据包位置,同时导出给 `xacro` 解析网格路径 |
|
||||
@@ -247,24 +250,23 @@ python3 tools/check_stack.py # 一次性检查节点/话题/TF/真
|
||||
|
||||
| 变量 | 自动探测规则 | 说明 |
|
||||
|---|---|---|
|
||||
| `SENTRY_FIELD_ROOT` | `field/*/src/guodong_sentry_sim` → 退 `~/Gazebo_projects/*map_transfer*/` | 场地迁移包根目录,**不绑具体包名/日期** |
|
||||
| `SENTRY_MAP_YAML` | 迁移包下 `maps/*/rmul_2027.yaml`,没有就取第一个 | 换地图时直接指这个 |
|
||||
| `SENTRY_BIN_DIR` | **`build/bin/`** 优先;老 checkout 退回 `build/*/*/{release,debug}` | xmake 产物目录,**不绑平台三元组**。旧名 `NAV_BIN_DIR` 仍有效 |
|
||||
| `SENTRY_FIELD_ROOT` | 优先仓库内场地包,再查 `~/Gazebo_projects/*map_transfer*/` | 覆盖值必须是现有目录 |
|
||||
| `SENTRY_MAP_YAML` | 依次查标准位置的 `rmul_2027.yaml`、按路径排序的同名文件、按路径排序的第一个普通 YAML 文件 | 覆盖值必须是普通文件 |
|
||||
| `SENTRY_BIN_DIR` | `build/bin` → 旧布局 `release` → 旧布局 `debug`。同一模式按平台和架构路径排序,目录须有已知可执行产物 | 覆盖值必须是现有目录,优先于旧变量 `NAV_BIN_DIR` |
|
||||
|
||||
### 版本(不设就自动探测)
|
||||
|
||||
| 变量 | 自动探测规则 | 说明 |
|
||||
|---|---|---|
|
||||
| `ROS_SETUP` | — | 直接指定要 source 的 `setup.bash` 全路径 |
|
||||
| `ROS_DISTRO` | 环境里已有就用;否则取 `/opt/ros/*` 里版本号最大的 | 换 ROS 发行版不用改脚本 |
|
||||
| `ROS_DISTRO` | 优先使用对应发行版。需自动扫描时按 ROS 安装目录名自然排序,选择最后一个 | ROS 已加载时沿用当前环境 |
|
||||
| `ROS_INSTALL_ROOT` | — | 非 `/opt/ros` 的 ROS 安装前缀(源码编译) |
|
||||
| `ROS_PREFIX` | — | **只给 `xmake` 用**:ROS 安装前缀。都不设时 xmake 依次看 `AMENT_PREFIX_PATH` → `ROS_DISTRO` → 报错 |
|
||||
| `GZ_BIN` | 优先 `/usr/bin/gz` → `/usr/local/bin/gz` → `$PATH` 上的 `gz` | 为什么优先系统版:vendor 版缺 cpu-lidar 插件 |
|
||||
| `GZ_FORCE_VERSION` | 取 `gz sim --version` 的主版本 | 换 Gazebo 大版本不用改脚本 |
|
||||
| `GZ_BIN` | `/usr/bin/gz` → `/usr/local/bin/gz` → `/opt/gz/bin/gz` → `PATH` | 覆盖值必须指向可执行的普通文件 |
|
||||
| `GZ_FORCE_VERSION` | 用选中的 Gazebo 查询主版本,最多等待 5 秒 | 查询失败时警告并继续使用 Gazebo 默认版本。设置此变量可跳过查询 |
|
||||
|
||||
> 上表这些变量**两条启动链都认**(`scripts/sentry_up.sh` 和 `ros2 launch`),
|
||||
> 因为它们读的是同一份探测库(`env_common.sh` / `project_env.py`)。
|
||||
> 注意 `ROS_PREFIX` 是唯一的例外:它只被 `xmake` 读(构建期找 ROS 头文件用)。
|
||||
Python 入口使用已加载的 ROS 环境。`field_root:=` 和 `map:=` 优先于对应的环境变量。只指定场地时,会在该场地目录下自动找地图。
|
||||
`ROS_PREFIX` 用于 xmake 构建。
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -18,23 +18,23 @@ xmake test
|
||||
|
||||
## 建图、保存与只读定位
|
||||
|
||||
先显式建图,再启动只读地图定位:
|
||||
当前 Gazebo 场地可直接用 `scripts/sentry_up.sh` 启动。两个入口默认只读加载 `src/sentry_sim/maps/field_full.flmap`。需要自建地图时可单独写入新路径:
|
||||
|
||||
```bash
|
||||
LIO_MODE=mapping LIO_MAP="$PWD/generated/field.flmap" scripts/sentry_up.sh
|
||||
LIO_MODE=mapping scripts/sentry_up.sh
|
||||
# 在机器人处于已知初始位姿后开始移动;保存当前地图:
|
||||
ros2 service call /field_localization/save_map std_srvs/srv/Trigger '{}'
|
||||
# 停止上一套进程;正常退出也会执行最终地图导出。
|
||||
LIO_MAP="$PWD/generated/field.flmap" scripts/sentry_up.sh
|
||||
LIO_MAP="$PWD/generated/field_mapping.flmap" scripts/sentry_up.sh
|
||||
```
|
||||
|
||||
Shell 默认 `LOCALIZATION=lio`、`LIO_MODE=localization`,缺失地图立即报错。可显式用 `LOCALIZATION=amcl` 选择旧方案;不自动回退。两个分支都保留 Nav2 的 2D map_server,但只有 AMCL 分支启动 AMCL。`NAV2=0` 不启动导航,仍可运行 LIO 建图。
|
||||
Shell 默认 `LOCALIZATION=lio`、`LIO_MODE=localization`,缺失地图立即报错。建图模式默认写入 `generated/field_mapping.flmap`。可显式用 `LOCALIZATION=amcl` 选择旧方案;不自动回退。两个分支都保留 Nav2 的 2D map_server,但只有 AMCL 分支启动 AMCL。`NAV2=0` 不启动导航,仍可运行 LIO 建图。
|
||||
|
||||
Python 启动入口在仿真时钟和 odom/base/lidar TF 就绪后,通过与 shell 相同的独立启动进程运行 Nav2,具有对应参数:
|
||||
|
||||
```bash
|
||||
ros2 launch src/sentry_sim/launch/sentry_arena.launch.py lio_mode:=mapping lio_map:="$PWD/generated/field.flmap"
|
||||
ros2 launch src/sentry_sim/launch/sentry_arena.launch.py lio_map:="$PWD/generated/field.flmap"
|
||||
ros2 launch src/sentry_sim/launch/sentry_arena.launch.py lio_mode:=mapping
|
||||
ros2 launch src/sentry_sim/launch/sentry_arena.launch.py lio_map:="$PWD/generated/field_mapping.flmap"
|
||||
ros2 launch src/sentry_sim/launch/sentry_arena.launch.py localization:=amcl
|
||||
```
|
||||
|
||||
@@ -42,9 +42,20 @@ ros2 launch src/sentry_sim/launch/sentry_arena.launch.py localization:=amcl
|
||||
|
||||
只读定位绝不往地图插点。建图只在无退化、质量门槛通过后插入关键帧,位移必须严格大于 0.5 m,或旋转严格大于 10°。初始化种子帧是唯一例外。配准失败不写图。
|
||||
|
||||
### 单独生成全场 Gazebo 地图
|
||||
|
||||
```bash
|
||||
python3 tools/capture_lio.py --profile mapping --full-field \
|
||||
--output generated/full_survey --map generated/field_full.flmap
|
||||
python3 tools/validation/validate_lio_navigation.py --full-field --launcher shell \
|
||||
--map generated/field_full.flmap --lio-cloud-topic /scan/points_lio --output generated/full_shell
|
||||
```
|
||||
|
||||
该模式在隔离的 Gazebo 空场沿重叠测站采集实际雷达扫描。测站坐标由命令指定,Gazebo 真值只核对到位误差。全场图包含南走廊的地面回波,为 LIO 提供垂直方向约束。避障用的 `/scan/points_filtered` 和 `/scan2d` 继续沿用原有的地面滤除规则。全场图对应当前仿真模型和雷达外参,改场地或更换外参后应重新采集和验收。
|
||||
|
||||
## ROS 接口与坐标约定
|
||||
|
||||
- 默认输入:`point_cloud_topic=/scan/points`、`imu_topic=/imu`。完整启动器显式选择 `/scan/points_filtered`。
|
||||
- 默认输入:`point_cloud_topic=/scan/points`、`imu_topic=/imu`。Shell、Python 启动和录制工具均使用 `/scan/points_lio`。旧版地图可配合 `LIO_POINT_CLOUD_TOPIC=/scan/points_filtered` 显式录制或启动,Python 也可传 `lio_point_cloud_topic:=/scan/points_filtered`。
|
||||
- 原始云在 `lidar_link`,自滤云在 `base_link`;适配器使用固定 TF 统一到 LiDAR 系。方位角时间估计也在 LiDAR 系完成,不重复施加安装外参。
|
||||
- 默认固定帧:`map/odom/base_link/imu_link/lidar_link`,均可通过同名 frame 参数配置。外参从现有固定 TF 读取;缺失时等待,禁止假设为恒等变换。
|
||||
- 内部状态原点为 IMU,`q` 将 IMU 坐标旋转到 map,`v/g` 在 map 系。误差顺序为 `p,v,theta,bg,ba,g`,右扰动态度误差。
|
||||
@@ -69,9 +80,9 @@ Gazebo 的 IMU 传感器配置无噪声;正式回放使用原始数据,不
|
||||
## 离线数据、回放与独立真值
|
||||
|
||||
```bash
|
||||
python3 tools/capture_lio.py --profile mapping --output generated/lio_mapping --map generated/field.flmap --duration 120
|
||||
python3 tools/capture_lio.py --profile evaluation --output generated/lio_evaluation --map generated/field.flmap --duration 120
|
||||
build/bin/field_localization_replay --dataset generated/lio_evaluation --mode localization --map generated/field.flmap --output generated/lio_metrics
|
||||
python3 tools/capture_lio.py --profile mapping --output generated/lio_mapping --map generated/field_mapping.flmap --duration 120
|
||||
python3 tools/capture_lio.py --profile evaluation --output generated/lio_evaluation --map src/sentry_sim/maps/field_full.flmap --duration 120
|
||||
build/bin/field_localization_replay --dataset generated/lio_evaluation --mode localization --map src/sentry_sim/maps/field_full.flmap --output generated/lio_metrics
|
||||
```
|
||||
|
||||
采集前需要已有 ROS Python 环境。脚本使用独立 Gazebo partition 和 ROS domain,只清理由自己创建的进程树;创建输出目录中的 `STOP` 文件可请求停止。控制器仅用轮速里程计走西北走廊路线,真值只进入记录器。两次采集使用不同路线,地图与定位序列分开。
|
||||
@@ -101,12 +112,12 @@ GCC 15.2 清洁重构建零警告,11 套 xmake 测试通过。五组带噪合
|
||||
完整 Nav2 启动检查命令:
|
||||
|
||||
```bash
|
||||
python3 tools/verify_lio_stack.py --map generated/field.flmap --output generated/lio_stack_check
|
||||
python3 tools/validation/verify_lio_stack.py --map src/sentry_sim/maps/field_full.flmap --output generated/lio_stack_check
|
||||
```
|
||||
|
||||
实测 9 个所需生命周期节点均 ACTIVE,AMCL 不存在,map→odom 仅一个发布者,没有 map→base_link 发布。交付数据中附带原始序列、收敛曲线 CSV、轨迹、逐帧状态、TF/生命周期检查 JSON 与构建日志。
|
||||
|
||||
Python 入口可用 `tools/verify_lio_stack.py --launcher python` 做同样的完整启动检查;验证器等待生命周期管理器报告激活完成,并继续观察稳定状态,避免在 bond 握手结束前退出。
|
||||
Python 入口可用 `tools/validation/verify_lio_stack.py --launcher python` 做同样的完整启动检查;验证器等待生命周期管理器报告激活完成,并继续观察稳定状态,避免在 bond 握手结束前退出。
|
||||
|
||||
### 导航有效性与失效保护
|
||||
|
||||
@@ -121,10 +132,29 @@ Python 入口可用 `tools/verify_lio_stack.py --launcher python` 做同样的
|
||||
两个入口都可运行相同的隔离验收。域编号可用 `--domain` 显式保留给并行测试;如域已有导航或定位节点,启动器会拒绝启动。
|
||||
|
||||
```bash
|
||||
python3 tools/run_lio_matrix.py --launcher shell --map generated/field.flmap --output generated/lio_matrix_shell
|
||||
python3 tools/run_lio_matrix.py --launcher python --map generated/field.flmap --output generated/lio_matrix_python
|
||||
python3 tools/validate_lio_navigation.py --launcher shell --scenario lidar_loss --goal 0 0 \
|
||||
--map generated/field.flmap --output generated/lio_lidar_loss
|
||||
python3 tools/validation/run_lio_matrix.py --launcher shell --map src/sentry_sim/maps/field_full.flmap --output generated/lio_matrix_shell
|
||||
python3 tools/validation/run_lio_matrix.py --launcher python --map src/sentry_sim/maps/field_full.flmap --output generated/lio_matrix_python
|
||||
python3 tools/validation/validate_lio_navigation.py --launcher shell --scenario lidar_loss --goal 0 0 \
|
||||
--map src/sentry_sim/maps/field_full.flmap --output generated/lio_lidar_loss
|
||||
```
|
||||
|
||||
默认矩阵各跑三次空场和三次圆柱绕行,再跑一次堵塞。默认圆柱在 `(-4, -1.5)`,半径 0.22 m、高 0.8 m。每次保留启动与目标日志、录制数据、TF 发布者数、最小圆柱净距及无需轨迹对齐的 3D ATE 和 1 秒 RPE。堵塞场景要求 Nav2 返回明确中止。断流场景只停止试验自己创建的自滤节点,并用执行器收到的零速度测量停车延迟。实测位姿来自 Gazebo PosePublisher,只参与评估。
|
||||
|
||||
### 复现连续往返失效
|
||||
|
||||
`--round-trip-regression` 在同一个仿真实例中连续发送五个目标,复现中间停留的时间。支持 `clear` 和 `cylinder`,每段保存单独的目标日志、真值终点误差和轨迹指标。总报告包含停留期间的定位误差和首次定位失效时间。
|
||||
|
||||
```bash
|
||||
python3 tools/validation/validate_lio_navigation.py --launcher shell --scenario clear \
|
||||
--map generated/field.flmap --output generated/lio_round_trip_clear --round-trip-regression
|
||||
```
|
||||
|
||||
用 `--launcher python` 切换入口。每次使用新的输出目录。跟踪 CSV 在原有字段后附加配准阶段和拒绝原因,以及初始与末次匹配的候选平面、支撑范围拒绝、面距离拒绝和内点数。可对同一条瞬时扫描离线比较预测位姿和独立真值附近的地图支持。
|
||||
|
||||
```bash
|
||||
build/bin/field_localization_replay --dataset generated/lio_round_trip_clear/dataset \
|
||||
--mode localization --map generated/field.flmap --output generated/lio_inspect \
|
||||
--inspect-scan 108.7
|
||||
```
|
||||
|
||||
将 108.7 替换为数据集 scans.csv 中要检查的时间戳。回放继续使用估计位姿运行滤波器。真值只用于对照匹配和评估轨迹。
|
||||
@@ -13,7 +13,7 @@ struct NoiseOptions {
|
||||
double accel_bias_walk{1e-4};
|
||||
double gravity_walk{0.0};
|
||||
// Quadrature/model error for unresolved between-sample dynamics, separate from sensor noise.
|
||||
double integration_error_scale{2.0};
|
||||
double integration_error_scale{1.4};
|
||||
double maximum_imu_gap{0.05};
|
||||
};
|
||||
struct FilterSnapshot {
|
||||
|
||||
@@ -37,7 +37,7 @@ struct RegistrationOptions {
|
||||
double neighborhood_radius{0.5};
|
||||
double measurement_sigma{0.02};
|
||||
// Shared map/association uncertainty does not shrink with the number of scan points.
|
||||
double map_translation_sigma{0.02};
|
||||
double map_translation_sigma{0.03};
|
||||
double map_rotation_sigma{0.002};
|
||||
double huber_threshold{0.025};
|
||||
double max_plane_distance{0.12};
|
||||
@@ -56,6 +56,17 @@ struct Degeneracy {
|
||||
};
|
||||
Degeneracy detect_degeneracy(const Matrix6 &normalized_information,const RegistrationOptions &options={});
|
||||
enum class RegistrationFailure { NONE, NO_CORRESPONDENCES, DEGENERATE, INNOVATION, QUALITY };
|
||||
enum class RegistrationStage { NOT_RUN, INITIAL_MATCH, ITERATION, FINAL_FUSION, COMPLETE };
|
||||
|
||||
struct AssociationCounts {
|
||||
std::size_t sampled{0};
|
||||
std::size_t candidate_planes{0};
|
||||
std::size_t outside_support{0};
|
||||
std::size_t plane_distance_rejected{0};
|
||||
std::size_t inliers{0};
|
||||
};
|
||||
const char *registration_stage_name(RegistrationStage stage);
|
||||
const char *registration_failure_name(RegistrationFailure failure);
|
||||
struct RegistrationResult {
|
||||
bool success{false};
|
||||
FilterSnapshot estimate;
|
||||
@@ -69,7 +80,12 @@ struct RegistrationResult {
|
||||
std::size_t inliers{0};
|
||||
double inlier_ratio{0};
|
||||
Degeneracy degeneracy;
|
||||
RegistrationStage stage{RegistrationStage::NOT_RUN};
|
||||
AssociationCounts initial_associations;
|
||||
AssociationCounts last_associations;
|
||||
};
|
||||
AssociationCounts inspect_scan_support(const PointCloud &cloud,const Pose3D &imu_from_sensor,
|
||||
const VoxelMap &map,const Pose3D &map_from_imu,const RegistrationOptions &options={});
|
||||
RegistrationResult scan_to_map(const PointCloud &cloud,const Pose3D &imu_from_sensor,
|
||||
const VoxelMap &map,const FilterSnapshot &prediction,const NoiseOptions &noise={},
|
||||
const RegistrationOptions &options={});
|
||||
|
||||
@@ -129,6 +129,11 @@ void write_filter_trace_header(std::ostream &out) {
|
||||
for(int i=0;i<6;++i) for(int j=0;j<6;++j) out<<",H"<<i<<"_"<<j;
|
||||
for(int i=0;i<6;++i) out<<",gradient"<<i;
|
||||
for(int i=0;i<6;++i) out<<",singular"<<i;
|
||||
out<<",registration_stage,registration_failure_name";
|
||||
for (const char *phase:{"initial","last"}) {
|
||||
for (const char *field:{"sampled","planes","outside_support","distance_rejected","inliers"})
|
||||
out<<','<<phase<<'_'<<field;
|
||||
}
|
||||
out<<'\n';
|
||||
}
|
||||
void write_filter_trace(std::ostream &out,double time,const char *phase,const FilterSnapshot &f,const LocalizationStatus &status) {
|
||||
@@ -143,6 +148,11 @@ void write_filter_trace(std::ostream &out,double time,const char *phase,const Fi
|
||||
for(int i=0;i<6;++i) for(int j=0;j<6;++j) out<<','<<status.registration.information(i,j);
|
||||
for(int i=0;i<6;++i) out<<','<<status.registration.gradient[i];
|
||||
for(int i=0;i<6;++i) out<<','<<status.information_singular_values[i];
|
||||
const auto ®=status.registration;
|
||||
out<<','<<registration_stage_name(reg.stage)<<','<<registration_failure_name(reg.failure);
|
||||
for (const auto &counts:{reg.initial_associations,reg.last_associations})
|
||||
out<<','<<counts.sampled<<','<<counts.candidate_planes<<','<<counts.outside_support
|
||||
<<','<<counts.plane_distance_rejected<<','<<counts.inliers;
|
||||
out<<'\n';
|
||||
}
|
||||
const char *mode_name(TrackingMode mode) { return mode==TrackingMode::FULL ? "FULL" : "IMU_ONLY"; }
|
||||
|
||||
@@ -109,42 +109,81 @@ Degeneracy detect_degeneracy(const Matrix6 &h,const RegistrationOptions &o) {
|
||||
namespace {
|
||||
struct Linearization {
|
||||
Matrix6 h{Matrix6::Zero()}; Vector6 gradient{Vector6::Zero()};
|
||||
double squared_error{0}; std::size_t inliers{0};
|
||||
double squared_error{0}; AssociationCounts counts;
|
||||
};
|
||||
Linearization linearize(const PointCloud &cloud,const Pose3D &extrinsic,const VoxelMap &map,
|
||||
const MotionState &state,const RegistrationOptions &o) {
|
||||
Linearization out;
|
||||
out.counts.sampled=cloud.points.size();
|
||||
for (const auto &point:cloud.points) {
|
||||
const Eigen::Vector3d body=extrinsic.rotation*point.position.cast<double>()+extrinsic.translation;
|
||||
const Eigen::Vector3d world=state.pose.rotation*body+state.pose.translation;
|
||||
const auto plane=map.plane(world,o.neighborhood_radius);
|
||||
if (!plane.valid) continue;
|
||||
++out.counts.candidate_planes;
|
||||
const Eigen::Vector3d offset=world-plane.center;
|
||||
const double residual=plane.normal.dot(offset);
|
||||
if((offset-plane.normal*residual).norm()>plane.support_radius+map.resolution()) continue;
|
||||
if (std::abs(residual)>o.max_plane_distance) continue;
|
||||
if ((offset-plane.normal*residual).norm()>plane.support_radius+map.resolution()) {
|
||||
++out.counts.outside_support;
|
||||
continue;
|
||||
}
|
||||
if (std::abs(residual)>o.max_plane_distance) {
|
||||
++out.counts.plane_distance_rejected;
|
||||
continue;
|
||||
}
|
||||
Vector6 j; j.head<3>()=plane.normal;
|
||||
j.tail<3>()=(-state.pose.rotation.toRotationMatrix()*skew(body)).transpose()*plane.normal;
|
||||
const double weight=std::min(1.0,o.huber_threshold/std::max(1e-12,std::abs(residual)))/
|
||||
(o.measurement_sigma*o.measurement_sigma);
|
||||
out.h.noalias()+=weight*j*j.transpose(); out.gradient.noalias()+=weight*j*residual;
|
||||
out.squared_error+=residual*residual; ++out.inliers;
|
||||
out.squared_error+=residual*residual; ++out.counts.inliers;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
AssociationCounts inspect_scan_support(const PointCloud &cloud,const Pose3D &extrinsic,
|
||||
const VoxelMap &map,const Pose3D &map_from_imu,const RegistrationOptions &options) {
|
||||
MotionState state; state.pose=map_from_imu;
|
||||
return linearize(voxel_downsample(cloud,options.scan_voxel),extrinsic,map,state,options).counts;
|
||||
}
|
||||
|
||||
const char *registration_stage_name(RegistrationStage stage) {
|
||||
switch (stage) {
|
||||
case RegistrationStage::NOT_RUN:return "NOT_RUN";
|
||||
case RegistrationStage::INITIAL_MATCH:return "INITIAL_MATCH";
|
||||
case RegistrationStage::ITERATION:return "ITERATION";
|
||||
case RegistrationStage::FINAL_FUSION:return "FINAL_FUSION";
|
||||
case RegistrationStage::COMPLETE:return "COMPLETE";
|
||||
}
|
||||
return "UNKNOWN";
|
||||
}
|
||||
const char *registration_failure_name(RegistrationFailure failure) {
|
||||
switch (failure) {
|
||||
case RegistrationFailure::NONE:return "NONE";
|
||||
case RegistrationFailure::NO_CORRESPONDENCES:return "NO_CORRESPONDENCES";
|
||||
case RegistrationFailure::DEGENERATE:return "DEGENERATE";
|
||||
case RegistrationFailure::INNOVATION:return "INNOVATION";
|
||||
case RegistrationFailure::QUALITY:return "QUALITY";
|
||||
}
|
||||
return "UNKNOWN";
|
||||
}
|
||||
|
||||
RegistrationResult scan_to_map(const PointCloud &cloud,const Pose3D &extrinsic,const VoxelMap &map,
|
||||
const FilterSnapshot &prediction,const NoiseOptions &noise,const RegistrationOptions &o) {
|
||||
RegistrationResult result; result.estimate=prediction;
|
||||
const auto scan=voxel_downsample(cloud,o.scan_voxel);
|
||||
result.stage=RegistrationStage::INITIAL_MATCH;
|
||||
result.initial_associations.sampled=scan.points.size();
|
||||
result.last_associations=result.initial_associations;
|
||||
if (scan.points.empty() || map.size()<5) return result;
|
||||
ErrorStateFilter filter(noise); filter.restore(prediction);
|
||||
auto record=[&](const Linearization &l) {
|
||||
result.inliers=l.inliers; result.inlier_ratio=static_cast<double>(l.inliers)/scan.points.size();
|
||||
result.residual_available=l.inliers>0;
|
||||
result.rmse=l.inliers ? std::sqrt(l.squared_error/l.inliers) : 0;
|
||||
result.last_associations=l.counts;
|
||||
result.inliers=l.counts.inliers; result.inlier_ratio=static_cast<double>(l.counts.inliers)/scan.points.size();
|
||||
result.residual_available=l.counts.inliers>0;
|
||||
result.rmse=l.counts.inliers ? std::sqrt(l.squared_error/l.counts.inliers) : 0;
|
||||
result.information=l.h; result.gradient=l.gradient;
|
||||
result.degeneracy=detect_degeneracy(l.h/std::max(1.0,static_cast<double>(l.inliers)),o);
|
||||
result.degeneracy=detect_degeneracy(l.h/std::max(1.0,static_cast<double>(l.counts.inliers)),o);
|
||||
result.estimate=filter.snapshot();
|
||||
};
|
||||
Matrix6 model_covariance=Matrix6::Zero();
|
||||
@@ -154,12 +193,14 @@ RegistrationResult scan_to_map(const PointCloud &cloud,const Pose3D &extrinsic,c
|
||||
const auto before=filter.snapshot().state;
|
||||
const auto l=linearize(scan,extrinsic,map,before,o);
|
||||
record(l);
|
||||
if (l.inliers<o.minimum_inliers) return result;
|
||||
const auto deg=detect_degeneracy(l.h/static_cast<double>(l.inliers),o);
|
||||
if (iteration==0) result.initial_associations=l.counts;
|
||||
if (l.counts.inliers<o.minimum_inliers) return result;
|
||||
const auto °=result.degeneracy;
|
||||
if (deg.dimensions==6) { result.failure=RegistrationFailure::DEGENERATE; return result; }
|
||||
// Trial iterates update correspondence geometry in this private filter.
|
||||
// The innovation gate is evaluated against the original prior once those
|
||||
// correspondences have settled, before the result can reach LocalizationCore.
|
||||
result.stage=RegistrationStage::ITERATION;
|
||||
const bool updated=filter.correct_information(prediction,before,l.h,l.gradient,
|
||||
deg.projector,model_covariance,InnovationCheck::TRIAL);
|
||||
result.nis=filter.last_nis(); result.measurement_rank=filter.measurement_rank();
|
||||
@@ -171,6 +212,7 @@ RegistrationResult scan_to_map(const PointCloud &cloud,const Pose3D &extrinsic,c
|
||||
const auto step=ErrorStateFilter::difference(before,filter.snapshot().state);
|
||||
if (step.segment<3>(0).norm()<1e-4 && step.segment<3>(6).norm()<1e-4) break;
|
||||
}
|
||||
result.stage=RegistrationStage::FINAL_FUSION;
|
||||
const auto final=linearize(scan,extrinsic,map,filter.snapshot().state,o);
|
||||
record(final);
|
||||
if (result.inliers<o.minimum_inliers) return result;
|
||||
@@ -185,6 +227,7 @@ RegistrationResult scan_to_map(const PointCloud &cloud,const Pose3D &extrinsic,c
|
||||
result.rmse<=o.max_rmse && result.degeneracy.dimensions<6 &&
|
||||
change.segment<3>(0).norm()<0.5 && change.segment<3>(6).norm()<0.35;
|
||||
result.failure=result.success ? RegistrationFailure::NONE : RegistrationFailure::QUALITY;
|
||||
if (result.success) result.stage=RegistrationStage::COMPLETE;
|
||||
return result;
|
||||
}
|
||||
} // namespace field_localization::core
|
||||
@@ -29,7 +29,7 @@ LocalizationNode::LocalizationNode(const rclcpp::NodeOptions &options):Node("fie
|
||||
core_options_.noise.integration_error_scale=declare_parameter<double>("integration_error_scale",core_options_.noise.integration_error_scale);
|
||||
core_options_.noise.accel_bias_walk=declare_parameter<double>("accel_bias_walk",1e-4);
|
||||
core_options_.map_resolution=declare_parameter<double>("map_voxel_size",0.1);
|
||||
core_options_.registration.map_translation_sigma=declare_parameter<double>("map_translation_sigma",0.02);
|
||||
core_options_.registration.map_translation_sigma=declare_parameter<double>("map_translation_sigma",core_options_.registration.map_translation_sigma);
|
||||
core_options_.registration.map_rotation_sigma=declare_parameter<double>("map_rotation_sigma",0.002);
|
||||
if(!std::isfinite(core_options_.registration.map_translation_sigma) || core_options_.registration.map_translation_sigma<0 ||
|
||||
!std::isfinite(core_options_.registration.map_rotation_sigma) || core_options_.registration.map_rotation_sigma<0)
|
||||
@@ -202,6 +202,16 @@ void LocalizationNode::publish_health(bool heartbeat) {
|
||||
RCLCPP_ERROR(get_logger(),"localization no longer valid for navigation; TF halted: state_age=%.6f correction_age=%.6f position_3sigma=%.6f yaw_3sigma_deg=%.6f reason=%s",
|
||||
now().seconds()-s.state_timestamp,now().seconds()-s.last_correction_timestamp,
|
||||
health_.position_three_sigma(),health_.yaw_three_sigma()*180/std::numbers::pi,core::reason_name(s.reason));
|
||||
if (s.reason==core::FailureReason::REGISTRATION_FAILED) {
|
||||
const auto ®=s.registration;
|
||||
const auto &initial=reg.initial_associations;
|
||||
const auto &last=reg.last_associations;
|
||||
RCLCPP_ERROR(get_logger(),"registration stage=%s failure=%s scan=%.9f initial(inliers=%zu planes=%zu outside_support=%zu distance_rejected=%zu) last(inliers=%zu planes=%zu outside_support=%zu distance_rejected=%zu)",
|
||||
core::registration_stage_name(reg.stage),core::registration_failure_name(reg.failure),
|
||||
s.last_point_cloud_timestamp,initial.inliers,initial.candidate_planes,initial.outside_support,
|
||||
initial.plane_distance_rejected,last.inliers,last.candidate_planes,last.outside_support,
|
||||
last.plane_distance_rejected);
|
||||
}
|
||||
}
|
||||
last_health_=valid;
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ public:
|
||||
imu_.exceptions(std::ios::badbit|std::ios::failbit); scans_.exceptions(std::ios::badbit|std::ios::failbit); truth_.exceptions(std::ios::badbit|std::ios::failbit);
|
||||
imu_<<std::setprecision(17)<<"timestamp,gx,gy,gz,ax,ay,az\n"; scans_<<std::setprecision(17)<<"timestamp,file\n";
|
||||
buffer_=std::make_unique<tf2_ros::Buffer>(get_clock()); listener_=std::make_unique<tf2_ros::TransformListener>(*buffer_);
|
||||
cloud_sub_=create_subscription<sensor_msgs::msg::PointCloud2>(declare_parameter<std::string>("point_cloud_topic","/scan/points_filtered"),
|
||||
cloud_sub_=create_subscription<sensor_msgs::msg::PointCloud2>(declare_parameter<std::string>("point_cloud_topic","/scan/points_lio"),
|
||||
rclcpp::QoS(20).reliable(),[this](sensor_msgs::msg::PointCloud2::ConstSharedPtr msg) {
|
||||
if (!ready_ || done_) return;
|
||||
auto cloud=ros::convert_cloud(*msg);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "field_localization/core/dataset.hpp"
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
@@ -8,6 +9,13 @@
|
||||
#include <stdexcept>
|
||||
#include <unordered_map>
|
||||
using namespace field_localization::core;
|
||||
namespace {
|
||||
void print_support(const char *label,const AssociationCounts &counts) {
|
||||
std::cout<<label<<" sampled="<<counts.sampled<<" planes="<<counts.candidate_planes
|
||||
<<" outside_support="<<counts.outside_support
|
||||
<<" distance_rejected="<<counts.plane_distance_rejected<<" inliers="<<counts.inliers<<'\n';
|
||||
}
|
||||
} // namespace
|
||||
int main(int argc,char **argv) {
|
||||
try {
|
||||
std::unordered_map<std::string,std::string> args;
|
||||
@@ -16,7 +24,7 @@ int main(int argc,char **argv) {
|
||||
args[argv[i]]=argv[i+1];
|
||||
}
|
||||
if (!args.contains("--dataset") || !args.contains("--mode") || !args.contains("--map") || !args.contains("--output"))
|
||||
throw std::runtime_error("usage: field_localization_replay --dataset DIR --mode mapping|localization --map FILE --output DIR");
|
||||
throw std::runtime_error("usage: field_localization_replay --dataset DIR --mode mapping|localization --map FILE --output DIR [--inspect-scan SIM_SECONDS]");
|
||||
const std::filesystem::path dataset=args.at("--dataset"),output=args.at("--output");
|
||||
auto options=read_dataset_config(dataset/"config.txt");
|
||||
if (args.at("--mode")!="mapping" && args.at("--mode")!="localization") throw std::runtime_error("invalid mode");
|
||||
@@ -25,6 +33,20 @@ int main(int argc,char **argv) {
|
||||
if(args.contains("--integration-error-scale")) options.noise.integration_error_scale=std::stod(args.at("--integration-error-scale"));
|
||||
LocalizationCore core(options); std::string error;
|
||||
if (options.map_mode==MapMode::LOCALIZATION && !core.load_map(args.at("--map"),error)) throw std::runtime_error(error);
|
||||
const auto truth_path=dataset/"truth.tum";
|
||||
const bool have_truth=std::filesystem::exists(truth_path);
|
||||
const auto truth=have_truth ? read_trajectory(truth_path) : std::vector<TrajectorySample>{};
|
||||
std::optional<double> inspect_time;
|
||||
std::optional<VoxelMap> inspect_map;
|
||||
if (args.contains("--inspect-scan")) {
|
||||
if (options.map_mode!=MapMode::LOCALIZATION || options.deskew.timing!=ScanTiming::INSTANTANEOUS || !have_truth)
|
||||
throw std::runtime_error("--inspect-scan requires localization with instantaneous scans and truth.tum");
|
||||
inspect_time=std::stod(args.at("--inspect-scan"));
|
||||
if (!std::isfinite(*inspect_time)) throw std::runtime_error("invalid scan timestamp");
|
||||
inspect_map=read_map(args.at("--map"),error);
|
||||
if (!inspect_map) throw std::runtime_error(error);
|
||||
}
|
||||
bool inspected=false;
|
||||
std::ifstream input(dataset/"imu.csv"); if (!input) throw std::runtime_error("missing imu.csv");
|
||||
std::vector<ImuData> imu; std::string line; std::getline(input,line);
|
||||
while (std::getline(input,line)) {
|
||||
@@ -52,6 +74,30 @@ int main(int argc,char **argv) {
|
||||
|
||||
const auto begin=std::chrono::steady_clock::now(); core.process_point_cloud(cloud);
|
||||
const auto diagnostic=core.get_snapshot();
|
||||
if (inspect_time && std::abs(cloud.timestamp_sec-*inspect_time)<1e-8) {
|
||||
const auto truth_base=trajectory_pose(truth,end);
|
||||
const auto ®=diagnostic.status.registration;
|
||||
if (!truth_base || reg.stage==RegistrationStage::NOT_RUN)
|
||||
throw std::runtime_error("scan has no aligned truth or registration prediction");
|
||||
const auto map_from_imu=compose(*truth_base,options.base_from_imu);
|
||||
const auto &prediction=diagnostic.status.registration_prediction.state;
|
||||
const auto corrected=deskew(cloud,std::array{prediction},options.deskew);
|
||||
if (!corrected) throw std::runtime_error("failed to prepare instantaneous scan");
|
||||
const auto truth_support=inspect_scan_support(*corrected,options.deskew.imu_from_sensor,*inspect_map,
|
||||
map_from_imu,options.registration);
|
||||
const auto error_xyz=prediction.pose.translation-map_from_imu.translation;
|
||||
std::cout<<std::setprecision(12)<<"scan="<<cloud.timestamp_sec
|
||||
<<" stage="<<registration_stage_name(reg.stage)
|
||||
<<" failure="<<registration_failure_name(reg.failure)
|
||||
<<" prediction_minus_truth_xyz_m="<<error_xyz.transpose()
|
||||
<<" rotation_error_deg="
|
||||
<<log_so3(map_from_imu.rotation.conjugate()*prediction.pose.rotation).norm()*180/std::numbers::pi
|
||||
<<'\n';
|
||||
print_support("prediction",reg.initial_associations);
|
||||
print_support("last",reg.last_associations);
|
||||
print_support("truth",truth_support);
|
||||
inspected=true;
|
||||
}
|
||||
write_filter_trace(trace,cloud.timestamp_sec,"prediction",diagnostic.status.registration_prediction,diagnostic.status);
|
||||
write_filter_trace(trace,cloud.timestamp_sec,"candidate",diagnostic.status.registration.estimate,diagnostic.status);
|
||||
write_filter_trace(trace,cloud.timestamp_sec,"posterior",diagnostic.filter,diagnostic.status);
|
||||
@@ -66,13 +112,14 @@ int main(int argc,char **argv) {
|
||||
<<','<<s.status.registration_rmse<<','<<s.status.inlier_count<<','<<s.status.inlier_ratio<<','<<s.status.degenerate_dimensions<<','
|
||||
<<state.gyro_bias.x()<<','<<state.gyro_bias.y()<<','<<state.gyro_bias.z()<<','<<state.accel_bias.x()<<','<<state.accel_bias.y()<<','<<state.accel_bias.z()<<','<<s.status.registration_residual_available<<','<<s.status.registration.nis<<','<<s.status.registration.measurement_rank<<','<<static_cast<int>(s.status.registration.failure)<<','<<ms<<'\n';
|
||||
}
|
||||
if (inspect_time && !inspected) throw std::runtime_error("requested scan not in dataset");
|
||||
if (options.map_mode==MapMode::MAPPING && !core.export_map(args.at("--map"),error)) throw std::runtime_error(error);
|
||||
if (total==0) throw std::runtime_error("empty replay");
|
||||
std::sort(latency.begin(),latency.end());
|
||||
std::ostringstream report; report<<std::setprecision(9)<<"scans="<<total<<" FULL="<<full<<" FULL_ratio="<<double(full)/total
|
||||
<<" scan_p95_ms="<<latency[static_cast<std::size_t>(0.95*(latency.size()-1))]<<'\n';
|
||||
if (std::filesystem::exists(dataset/"truth.tum")) {
|
||||
const auto truth=read_trajectory(dataset/"truth.tum"); const auto metric=evaluate(estimated,truth);
|
||||
if (have_truth) {
|
||||
const auto metric=evaluate(estimated,truth);
|
||||
if (metric.matched==0 || metric.relative_pairs==0) throw std::runtime_error("insufficient matching ground truth");
|
||||
report<<"matched="<<metric.matched<<'/'<<metric.total<<" coverage="<<double(metric.matched)/metric.total<<" RPE_pairs="<<metric.relative_pairs<<'\n'
|
||||
<<"ATE_translation_RMSE_m="<<metric.ate_translation<<" ATE_rotation_RMSE_deg="<<metric.ate_rotation_rad*180/std::numbers::pi<<'\n'
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1 @@
|
||||
108.5 -4.9021935418437943 2.9320217193133793 0.1557928922336535 0.11953694764680566 0.19908177120751999 0.045965043312493209 -0.00086052905380611946 3.8835947097606263e-05 -0.55033851439645454 -0.83494118209214019 3.8119482349976081e-05 -4.76556171027656e-05 -1.0893553551394554e-05 -0.0076579611075292681 -0.001573404450170669 0.062223414195409221 -0.020740954303261897 0.047091173245459049 -9.7476220442384385 0.00032180030162672231 -3.3109679715980393e-06 -1.4134561776379964e-07 0.00128395026095998 -1.6746730317314658e-05 -8.4886017517825797e-07 4.1240730271156636e-07 2.1418971002544343e-07 -2.8876581180948139e-07 -4.3422373923642243e-09 -5.1748223345340147e-10 9.9958077796484632e-10 3.3266378490022887e-07 1.0028474513103997e-06 1.0691009716774382e-06 1.1444559866337746e-06 3.7771093654250646e-07 1.0691201494343238e-06 -3.3109679715980393e-06 0.00030135439567193314 -1.7703924751834215e-07 -1.6662850139947176e-05 0.0011985416218993159 3.8619545898588747e-07 -2.6147583384228565e-07 5.5485281955242264e-07 -3.657478893010278e-07 4.2797428049573721e-10 -5.5219694040548798e-09 1.2780944746782657e-09 -1.6542624247824321e-06 8.9990442499691803e-08 -3.7854466338783015e-06 -8.0172810695956697e-07 1.1298994983796557e-06 -3.7801386121655004e-06 -1.4134561776379964e-07 -1.7703924751834215e-07 0.00023484235692365681 7.7976930255511676e-07 -1.5315893762949035e-06 0.00072374316475533275 8.0054833699954886e-07 -3.7983349382611144e-07 4.7014732995790377e-08 -6.6169668059266572e-09 5.1662907401548531e-09 -2.0922013649704161e-10 -2.7197868772262445e-09 4.3794454248856465e-10 -7.2241387348460554e-07 -3.4340629368096118e-09 4.8637981713538916e-09 2.0170234401260474e-08 0.00128395026095998 -1.6662850139947176e-05 7.7976930255511676e-07 0.016671016339951206 0.00028959121918970378 -3.798955913976945e-06 4.2882917579726604e-06 1.8958563347564645e-06 -8.2652501644825307e-08 -4.4522500494586826e-08 -8.0812241942467223e-09 3.0057389155497851e-10 1.8752153113102324e-06 6.3682456726758585e-06 6.5733340033091501e-06 7.1989659236711069e-06 2.4250924065566434e-06 6.5747187554529147e-06 -1.6746730317314658e-05 0.0011985416218993159 -1.5315893762949035e-06 0.00028959121918970378 0.017016380591946909 4.1421284919585015e-06 -2.2637764100331944e-06 5.1619542058896502e-06 -4.0037244977777193e-07 8.6781637833258431e-09 -5.2328110182931958e-08 1.58419438820848e-09 -9.7135882093019719e-06 2.9077145220395079e-07 -2.1870543798192066e-05 -4.6791391025785722e-06 6.6544502227089111e-06 -2.1840445337136608e-05 -8.4886017517825797e-07 3.8619545898588747e-07 0.00072374316475533275 -3.798955913976945e-06 4.1421284919585015e-06 0.012275672165360777 8.4060340358083866e-07 -3.7510481928876981e-07 6.8149456965885298e-08 -6.8844559369381303e-09 4.0437621421826469e-09 -3.4178005968171159e-10 -1.5153987088700559e-08 2.4507827427223861e-09 -4.2341934360751864e-06 -1.889941795210489e-08 2.6848198981890525e-08 1.244230272814858e-07 4.1240730271156636e-07 -2.6147583384228565e-07 8.0054833699954886e-07 4.2882917579726604e-06 -2.2637764100331944e-06 8.4060340358083866e-07 2.8207167738484057e-06 -9.6336778435724137e-08 1.3781317221426031e-08 -2.6440380244751873e-08 4.0522447969181831e-09 -5.8201390497764061e-11 -8.0099878941585013e-10 -7.872340442403864e-10 -3.4323625809851157e-09 -1.0303682108364948e-09 4.8412100509677764e-12 -2.0828522750049064e-09 2.1418971002544343e-07 5.5485281955242264e-07 -3.7983349382611144e-07 1.8958563347564645e-06 5.1619542058896502e-06 -3.7510481928876981e-07 -9.6336778435724137e-08 3.0510260124192839e-06 -8.5184113912824024e-09 -2.5010269657606956e-09 -2.8533187359619162e-08 1.6596970762816415e-11 1.0235809829900821e-09 -4.1617052782586423e-10 3.4166161706316234e-09 2.8897888828753661e-10 -9.6927714973496483e-10 2.9900252507395201e-09 -2.8876581180948139e-07 -3.657478893010278e-07 4.7014732995790377e-08 -8.2652501644825307e-08 -4.0037244977777193e-07 6.8149456965885298e-08 1.3781317221426031e-08 -8.5184113912824024e-09 4.9531797132419396e-06 -1.0899538712701036e-10 1.012607157604397e-10 -2.1846203888502755e-08 6.4585465639471621e-10 -3.8025781452778024e-10 1.3770155571674219e-09 1.3125030002545032e-11 -6.4473039908968704e-10 1.4534369723133827e-09 -4.3422373923642243e-09 4.2797428049573721e-10 -6.6169668059266572e-09 -4.4522500494586826e-08 8.6781637833258431e-09 -6.8844559369381303e-09 -2.6440380244751873e-08 -2.5010269657606956e-09 -1.0899538712701036e-10 9.5243509910712323e-08 -1.2449932005997435e-10 -5.3657067385421009e-12 -1.1880921854779703e-10 2.755054987508737e-10 5.021226678365264e-10 -4.1880538357733795e-10 1.4253390980595335e-10 3.58472159966974e-10 -5.1748223345340147e-10 -5.5219694040548798e-09 5.1662907401548531e-09 -8.0812241942467223e-09 -5.2328110182931958e-08 4.0437621421826469e-09 4.0522447969181831e-09 -2.8533187359619162e-08 1.012607157604397e-10 -1.2449932005997435e-10 9.6602785462132596e-08 7.2250758694789384e-12 2.5951113791785858e-10 -1.9493442618219454e-10 -1.044466662172168e-09 -1.771308527273993e-10 -1.558599068747Line truncated
|
||||
@@ -0,0 +1,5 @@
|
||||
FIELD_LIO_DATASET 1
|
||||
initial_pose -5 3 0 0 0 0 1
|
||||
base_from_imu 0 0 0.14999999999999999 0 0 0 1
|
||||
imu_from_lidar -0.0935 -0.1512 0.25519999999999998 0 0 0 1
|
||||
scan_timing 0 0.10000000000000001 -3.1415926535897931 1 1
|
||||
@@ -0,0 +1,46 @@
|
||||
timestamp,gx,gy,gz,ax,ay,az
|
||||
108.48,-0.00027579711156923295,-9.6228164683447422e-05,-0.56779033555889469,-1.0530966798405577,-2.6010947767770594,9.8095553816565157
|
||||
108.48999999999999,-0.00025615782747161729,-0.00010587090718420355,-0.55785202563478387,-1.7876666177385214,-1.0631781169629055,9.8094280629193058
|
||||
108.5,-0.00023825784714968831,-0.00011711104903238535,-0.58693848212030686,-1.9043254046636544,-1.139065472424273,9.8094578216037966
|
||||
108.51000000000001,-0.0038630553244536035,-0.0038254066591876645,-0.68517701957796229,1.1061646030349155,-2.5481938512545188,9.7882127819939981
|
||||
108.52,-0.012606909063535997,0.016247733271579818,-0.78297260155929282,-2.4583754036013685,-1.7038647361881609,11.839716492099672
|
||||
108.53,-0.061277268073585023,0.079820328714736447,-0.95872965467934201,-4.2708544673441109,-0.84812091026555592,9.9852964166452605
|
||||
108.54000000000001,-0.076112960000572827,0.10118717039092451,-1.0492460237459966,-0.95334847078538454,0.71509630025199966,9.7244760393909324
|
||||
108.55,-0.067641209642736802,0.092385150361106574,-1.0531247188783339,-0.96299303923260471,0.70118110999445338,9.7257429713406207
|
||||
108.56,0.0033595937551803329,0.0020697239466177832,-1.0235049120000919,-8.3456600758072401,-2.6104502542668877,9.1893792949826683
|
||||
108.56999999999999,0.02633565443321674,-0.027770362691463782,-1.0327068282495309,-0.86663841190981339,0.59485616933232788,9.7503275368400892
|
||||
108.58,0.044817131676968228,-0.052668601183060743,-1.0250939063161346,-0.87108193784216637,0.59289071702653651,9.7503813880634009
|
||||
108.59,0.027626257433854592,-0.031687748948603475,-0.97521425042473509,12.881843216107459,71.50407345556205,10.073106197385915
|
||||
108.59999999999999,-0.036474759445082425,0.051364487006142587,-0.96049966667821285,-4.4324684565237389,1.8562481433950828,9.8677515940224332
|
||||
108.61,-0.04134819767885773,0.05920975956051068,-1.030264108649404,-0.99297521928374843,0.65187845641134368,9.7303549205617799
|
||||
108.62,0.01295842388313628,-0.0039726626729746648,-1.0139150953741738,0.19457236107968115,-0.55040386338858716,9.7250152706423183
|
||||
108.63,0.034377204593879558,-0.033473846614123254,-0.99454322329474421,0.2959840955286403,-0.63552909536554569,9.7783991319795742
|
||||
108.64,0.050820131406794901,-0.055549240334301773,-0.97760185137247102,-1.9641378332748467,2.153826777994603,14.191482820845833
|
||||
108.65000000000001,0.061042066837415115,-0.04419677239597361,-0.96473456396457447,-0.18272266438283608,-0.26120167792698396,9.294572520726657
|
||||
108.66,0.089517043233146909,-0.060374879806683657,-0.9403871801458199,-0.15826475289053657,-0.24363012237265588,9.3217861415882517
|
||||
108.67,0.00075568636684762713,0.083573010739332126,-0.91678558238484609,4.0341898535273764,-4.6884496196539844,7.7014957643994784
|
||||
108.68000000000001,0.0021557033600065473,0.12707896757705958,-1.0486907811541184,4.0785371406202495,-4.6392205782611713,7.7203149932024022
|
||||
108.69,0.0020433518921272572,0.0020166876327267751,-0.9054452167476853,2.5840014331377761,-3.0474611788932653,9.7424379876060367
|
||||
108.7,0.0018146512053483586,0.033385534243483068,-0.75254006007709262,2.9177303958871978,-0.9347762921025552,9.2265301165200722
|
||||
108.70999999999999,-0.0071175103038246743,2.2653503118359557e-06,-0.79580071923165763,1.5862332837852466,1.7892895525491757,8.5117099060340156
|
||||
108.72,0.0018226364070514966,-0.00047441621740520361,-0.64959146474622242,-2.5218861545502262,-4.5195339577395215,9.8019501144738008
|
||||
108.73,0.00061213745480492821,0.00064759022433580143,-0.23765205614659146,-2.1891152862620129,-4.6163027052355474,9.7575703912375431
|
||||
108.73999999999999,-8.5173882333780833e-05,-0.00040036893615584556,0.0001979938570819452,-0.029016022025761215,-0.0004040832591799702,9.8094296040077413
|
||||
108.75,-8.2351569187941569e-05,-0.0003822955018146262,0.00018844413837782267,-0.029031520889687464,-0.00034444352750586152,9.8094544409425399
|
||||
108.76000000000001,-7.8845306342528189e-05,-0.00036413257485318955,0.0001793636084983912,-0.028968714585963447,-0.000346458398696414,9.8094811772970907
|
||||
108.77,-7.4880532471881042e-05,-0.00034611221051486372,0.00017072867345419888,-0.028935081983888621,-0.00032672658632929149,9.809505062753086
|
||||
108.78,-7.1115196251946727e-05,-0.00032899306246744709,0.00016251599600637965,-0.02890308134415694,-0.00030795031942689192,9.8095277389049578
|
||||
108.79000000000001,-6.7539261185498663e-05,-0.00031272916713399293,0.00015470497749903061,-0.028872634220905094,-0.00029008367401124532,9.8095492684904784
|
||||
108.8,-6.4222286693821823e-05,-0.00029725638885302771,0.00014727580938687338,-0.02884335197079773,-0.00027185352010715869,9.809571495474632
|
||||
108.81,-6.1074528905443468e-05,-0.00028255450086174305,0.00014021005859313153,-0.02881582584481648,-0.00025581286497402487,9.8095907279037284
|
||||
108.81999999999999,-5.8081104455341283e-05,-0.00026858606364358782,0.00013348999987412524,-0.028789638923466501,-0.00024055457626561674,9.8096089957348145
|
||||
108.83,-5.5234443560975581e-05,-0.00025531389037077289,0.00012709875209389966,-0.028764726530231797,-0.00022604070858204839,9.8096263483606254
|
||||
108.84,-5.2527348000840473e-05,-0.00024270273620216737,0.00012102025508831105,-0.028741027063309946,-0.00021223512807402926,9.8096428325524521
|
||||
108.84999999999999,-4.9952972850119343e-05,-0.00023071919154618757,0.00011523923010331233,-0.028718481854024532,-0.00019910343697915361,9.8096584926023418
|
||||
108.86,-4.7504809118585898e-05,-0.00021933158168783681,0.00010974114210159096,-0.028697035031996648,-0.00018661288834960618,9.8096733704656565
|
||||
108.87,-4.5176667237112169e-05,-0.00020850987238039211,0.00010451216386677535,-0.028676633395378699,-0.00017473231118386127,9.8096875058901745
|
||||
108.88,-4.2962661368461969e-05,-0.00019822558091676793,9.9539141778251435e-05,-0.02865722628771946,-0.00016343203616670909,9.8097009365388317
|
||||
108.89,-4.0857194480294721e-05,-0.00018845169243943518,9.4809563240037353e-05,-0.028638765478787489,-0.00015268382383709634,9.8097136981062469
|
||||
108.90000000000001,-3.8854944159717922e-05,-0.00017916258107389583,9.0311525646290502e-05,-0.028621205051879525,-0.00014246079525618113,9.8097258244280425
|
||||
108.91,-3.6950849126026176e-05,-0.00017033393556493636,8.6033706814335204e-05,-0.028604501294363802,-0.00013273737693193267,9.8097373475763607
|
||||
108.92,-3.5140096402690625e-05,-0.00016194268924257522,8.1965336865759034e-05,-0.028588612596438932,-0.0001234892242220093,9.8097482979663546
|
||||
|
Binary file not shown.
@@ -0,0 +1,9 @@
|
||||
Isolated Gazebo Shell launch, clear scene, second leg from (0,0) back to (-5,3).
|
||||
The checkpoint is the original filter prediction at simulated time 108.5 s.
|
||||
Scans at 108.5--108.9 s, IMU samples and independent truth are from the same run.
|
||||
Acceleration changed by 72.23 m/s^2 at 108.59 s, then by 71.77 m/s^2 at 108.60 s.
|
||||
The old integration scale 2.0 crossed the horizontal position 3-sigma threshold
|
||||
(0.5 m) at 108.7 s and the drive interlock stopped the goal. Map matching continued.
|
||||
The test compares the prior before each scan at both scales and checks corrections
|
||||
and truth error. Truth only scores the output. This is separate from the
|
||||
unrecorded failure that had no correspondences.
|
||||
@@ -0,0 +1,6 @@
|
||||
timestamp,file
|
||||
108.5,1070.flpc
|
||||
108.59999999999999,1071.flpc
|
||||
108.7,1072.flpc
|
||||
108.8,1073.flpc
|
||||
108.90000000000001,1074.flpc
|
||||
|
@@ -0,0 +1,45 @@
|
||||
108.48 -4.9071026036118548 2.9233913230750783 0.0029858126403290871 7.2250798166288425e-06 2.8442624406782508e-05 0.55507890540450322 0.83179769650664104
|
||||
108.48999999999999 -4.9062642203379969 2.9255680970807725 0.0029865468907930271 6.3291191353360092e-06 2.7307813742419122e-05 0.55276430081705308 0.83333764282939971
|
||||
108.5 -4.9053972077996111 2.9275282001593639 0.0029872286798281614 5.5399981504607552e-06 2.6178129603476733e-05 0.55036534252022395 0.83492394206694698
|
||||
108.51000000000001 -4.9046646886830549 2.9292729227331513 0.0029936313785604166 -4.736127786470753e-06 3.3049173620555536e-05 0.54761911569906785 0.83672773529164923
|
||||
108.52 -4.9038096193174239 2.9308242408481151 0.0029844753027834731 -4.9230391904278006e-05 2.243576255743785e-05 0.54461563620190612 0.83868576110328608
|
||||
108.53 -4.9029951128170328 2.9319089098101028 0.0030006080810971733 -0.00037185933427108623 0.00013601574900552754 0.5408852167529149 0.84109632356734498
|
||||
108.54000000000001 -4.9022632148810406 2.9325382215656548 0.0030306202514057898 -0.00098584198609175241 0.00035761968065051636 0.53652427507351241 0.84388423523643596
|
||||
108.55 -4.9016446671925502 2.9330504405569773 0.0030581468303319923 -0.001544564748203659 0.00056650094536240755 0.53207935443970145 0.8466928923614796
|
||||
108.56 -4.9012232035425685 2.9335773095391842 0.0030746075327204988 -0.0018251026007992592 0.00068374173436587299 0.52766200432833754 0.84945218269537615
|
||||
108.56999999999999 -4.9010350946153922 2.9340649288436951 0.0030712408664604692 -0.0017346514287665561 0.0006601243266040756 0.5232426619061783 0.85218171300587708
|
||||
108.58 -4.9009513477400262 2.9345809755178025 0.0030603042691265932 -0.0014667422006025576 0.00056709949674644926 0.5188551578902586 0.8548607209342074
|
||||
108.59 -4.9011856833308274 2.9351716379965223 0.0030486176107153568 -0.0011813940203852925 0.00046400831990277692 0.51448633770426766 0.85749763691808378
|
||||
108.59999999999999 -4.9025325962781743 2.9358826277467109 0.0030583004600324795 -0.0013722337617795045 0.00054506094092712603 0.51048467726222702 0.85988558201865073
|
||||
108.61 -4.9042171088724684 2.9362391277319615 0.0030755562493143384 -0.0017189437160433187 0.0006910657880021667 0.50611596493250299 0.86246344716806356
|
||||
108.62 -4.9059845880932338 2.9365916184328378 0.0030726120932165349 -0.0017579433845956738 0.00072700441405718129 0.50162314016042819 0.86508416142895017
|
||||
108.63 -4.9077037294256938 2.9369549108499187 0.0030549526657664824 -0.0015906492030189677 0.00068766861934978067 0.49727550118258251 0.86759095942188935
|
||||
108.64 -4.9093583297663042 2.9373585080073492 0.0030191847395952794 -0.0012747314821810044 0.00060554175097587125 0.49300634869296989 0.87002456777223369
|
||||
108.65000000000001 -4.9110518183553697 2.9377027711543717 0.0029664317860478985 -0.0009074190385914881 0.00052551606818008632 0.48878714497942805 0.87240244573614656
|
||||
108.66 -4.9127338187093921 2.9380444130606538 0.0028672150785611118 -0.00042283910851417572 0.00046832055697665017 0.48466240927990606 0.87470106374346035
|
||||
108.67 -4.9141628840969114 2.9381489038979098 0.0027565590016154378 -0.00027719379602898368 0.00060403682294858359 0.48064260716109708 0.87691632581706414
|
||||
108.68000000000001 -4.9152086923244882 2.9381074413261659 0.0025694281599019544 -0.00055042288347394999 0.0011055583485082147 0.47628672908702829 0.87928915975972732
|
||||
108.69 -4.9161351835595939 2.93864659832927 0.0025383300594161349 -0.00059853666229444497 0.0012018901858600714 0.47201549865874842 0.88158922761101055
|
||||
108.7 -4.9167952516904698 2.9394702423291088 0.0025057824865530377 -0.00064228777597694423 0.0012922911428858172 0.46842127708854053 0.88350406033065609
|
||||
108.70999999999999 -4.9173018922715146 2.940362071952022 0.0024918813891934215 -0.00068859771738163955 0.0013387330363737859 0.46495892627369939 0.88533097229536117
|
||||
108.72 -4.9177556213521374 2.9411980850974202 0.0025009992843522595 -0.0006718193217249693 0.0013178923164732753 0.46155766211772059 0.8871089765970499
|
||||
108.73 -4.9180187668671556 2.9416340556595397 0.0025015281783265855 -0.00066939373545388465 0.00131865235183839 0.45977143268899689 0.8880360593754677
|
||||
108.73999999999999 -4.9180544473336081 2.941683628128029 0.002501154514657559 -0.00067050560271407912 0.0013205948330638885 0.45956901953254004 0.88814082370839342
|
||||
108.75 -4.9180547737815665 2.9416842658140818 0.0025017594416658884 -0.00067018684139458023 0.001319432124916569 0.45956953788076993 0.88814055745727605
|
||||
108.76000000000001 -4.9180553984216857 2.9416854842061171 0.0025029151068616351 -0.00066957979335071434 0.0013171997000242573 0.45957052959788774 0.8881400480627859
|
||||
108.77 -4.9180559872349887 2.9416866303269003 0.0025040022766528716 -0.00066900887500588179 0.0013150964352657767 0.45957146426949047 0.88813956796085125
|
||||
108.78 -4.918056268866053 2.941687177613542 0.0025045214778418212 -0.00066873603972176642 0.0013140919444938187 0.45957191126200286 0.88813933835488923
|
||||
108.79000000000001 -4.9180566316896259 2.9416878817389449 0.002505189559091462 -0.00066838478328363647 0.0013127993806705148 0.45957248705398718 0.88813904258431309
|
||||
108.8 -4.9180573159650995 2.941689206524909 0.0025064470135053628 -0.0006677233142186968 0.001310366532802802 0.45957357276097899 0.88813848486867997
|
||||
108.81 -4.9180576384942549 2.9416898293585856 0.0025070385860793605 -0.00066741227345367327 0.0013092221421721927 0.45957408439159536 0.88813822204309312
|
||||
108.81999999999999 -4.918057948634182 2.9416904271975306 0.00250760671196067 -0.00066711367701798203 0.0013081232115439393 0.45957457629499837 0.88813796934726208
|
||||
108.83 -4.9180582468721754 2.9416910010247697 0.0025081523257144845 -0.00066682701988258033 0.0013070679209143726 0.45957504924727111 0.8881377263828758
|
||||
108.84 -4.9180585336763993 2.9416915517847468 0.0025086763242520749 -0.00066655181805750784 0.0013060545242227191 0.45957550399401981 0.88813749276724963
|
||||
108.84999999999999 -4.9180588767864721 2.9416922091752897 0.0025093022340924032 -0.00066622321997631935 0.0013048441461448572 0.45957604791451118 0.88813721333567286
|
||||
108.86 -4.9180592035726489 2.9416928336327022 0.0025098973182049495 -0.00066591093349993114 0.0013036934913511122 0.45957656584359741 0.88813694725155701
|
||||
108.87 -4.9180595148337707 2.9416934267685386 0.0025104631019277146 -0.00066561413916471884 0.0013025995936241192 0.45957705905345159 0.88813669386187222
|
||||
108.88 -4.9180598113296483 2.9416939901156209 0.0025110010344434287 -0.00066533205959182315 0.0013015596358814619 0.4595775287540666 0.88813645254548013
|
||||
108.89 -4.9180601486496087 2.9416946288586678 0.0025116117236652956 -0.00066501195181030263 0.0013003791296257951 0.4595780629790025 0.88813617807276113
|
||||
108.90000000000001 -4.9180604669283969 2.9416952291860867 0.002512186535750748 -0.00066471077005743004 0.0012992680814553675 0.45957856688710369 0.88813591917005619
|
||||
108.91 -4.9180607672789973 2.9416957933432286 0.0025127275864666853 -0.00066442738445443193 0.0012982223830156918 0.45957904225069685 0.88813567492744439
|
||||
108.92 -4.9180607672789973 2.9416957933432286 0.0025127275864666853 -0.00066442738445443193 0.0012982223830156918 0.45957904225069685 0.88813567492744439
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1 @@
|
||||
73 -1.1860204800839835 -1.5637071989344469 0.091575138745469603 -0.42970067883716345 -0.32356653324631857 -0.21993780179039443 0.0051528723832590748 0.01813053226079377 -0.96370380891118801 0.2663075297399809 -4.2996599124332597e-05 -0.00013302682205245796 -3.3626316872579628e-05 -0.093146036471238869 -0.033023000640963425 0.043485336943729629 -0.088175115845336036 0.0099135394819331538 -9.7661660023761758 0.00060780813598797028 4.4833770274984383e-05 4.068913437385071e-06 0.0024170781771618599 0.00032731725695303603 2.1443137968033931e-05 -2.3597143001486444e-07 -2.9741917115125317e-07 9.7966640722376522e-08 2.1208513955816369e-09 2.5997265115716957e-09 -5.113828143965986e-10 2.1029545238081228e-05 6.2372126519518097e-06 5.6578640848176513e-06 1.9615872912915468e-05 8.7608927362914083e-06 5.6572697499445987e-06 4.4833770274984383e-05 0.00058045375687999019 3.5739298696195479e-06 0.00032917108381059015 0.0022005736005506395 1.7655757929154496e-05 3.1281479923900358e-07 -1.5012792304465173e-07 -2.8812862283482996e-07 -2.5530828508678023e-09 2.1325162410567553e-09 1.6011305635602758e-09 2.7572024541284657e-05 3.161555051603116e-05 1.2174875434780663e-05 2.2894475561072589e-05 3.5215830711721919e-05 1.2296275724162208e-05 4.068913437385071e-06 3.5739298696195479e-06 0.00036996744205358592 2.1762306440312313e-05 1.8755039425128898e-05 0.001267729477946909 4.5968173799619698e-07 -4.7184537272925347e-07 -4.5523729647643344e-08 -1.2926610506547117e-09 7.6217213133024349e-09 2.0332494642726058e-10 -2.9738024273382044e-07 -8.9656572513236403e-08 -2.3517667470055742e-06 -3.0426650126010034e-07 -1.4059474625069041e-07 9.7645343680620327e-08 0.0024170781771618599 0.00032917108381059015 2.1762306440312313e-05 0.013004981872738922 0.0029538966226704873 0.00015059828618843344 -2.6950965138518528e-06 -3.2909985277179347e-06 1.0445772255283359e-07 1.1634575468226878e-08 3.6590981458874928e-08 4.5667612011030474e-10 0.00015391619821639938 7.0450603260494027e-05 2.6355904239605509e-05 0.00014045666395491198 8.9179988054358458e-05 2.668278274914003e-05 0.00032731725695303603 0.0022005736005506395 1.8755039425128898e-05 0.0029538966226704873 0.010820450467951836 0.00011822554732653555 4.4540326413927473e-06 -2.0273734031960157e-06 -8.1556642792206085e-07 -1.7782839561356206e-08 3.0154785129451994e-08 3.667696296450078e-09 0.00017401610397799848 0.00018705211874168816 0.00010033429121629731 0.00014621392729136367 0.00020948544565366656 0.00010114826278730152 2.1443137968033931e-05 1.7655757929154496e-05 0.001267729477946909 0.00015059828618843344 0.00011822554732653555 0.0055765334401990984 1.1013160576330035e-06 -1.0088574257788578e-06 -1.0961393002398403e-07 1.8637431860427857e-09 1.5312453369595839e-08 3.2583612666746484e-10 3.6917601363854277e-06 4.0897525574045234e-06 -2.4921569959613943e-06 3.0462239662268385e-06 4.4678089343898683e-06 2.1691496353306824e-06 -2.3597143001486444e-07 3.1281479923900358e-07 4.5968173799619698e-07 -2.6950965138518528e-06 4.4540326413927473e-06 1.1013160576330035e-06 3.4247221086581215e-06 -6.5891096198150198e-08 -1.187155203932947e-08 -2.1047558332211635e-08 4.5418772101169739e-09 4.9683278470875706e-11 -1.8711916522636576e-08 -2.2622656198800191e-08 -9.4311040824366266e-09 -1.5400373926889885e-08 -2.5140465461497681e-08 -4.6779374320385916e-09 -2.9741917115125317e-07 -1.5012792304465173e-07 -4.7184537272925347e-07 -3.2909985277179347e-06 -2.0273734031960157e-06 -1.0088574257788578e-06 -6.5891096198150198e-08 2.7149352451710811e-06 7.8258829819440609e-09 -7.5838761822832311e-10 -4.0630668458863094e-08 2.182671615426844e-10 4.9921698727328337e-08 3.448164264717186e-08 1.9429585390713286e-08 4.4425236541581794e-08 4.1186405868944011e-08 1.4371428402872669e-08 9.7966640722376522e-08 -2.8812862283482996e-07 -4.5523729647643344e-08 1.0445772255283359e-07 -8.1556642792206085e-07 -1.0961393002398403e-07 -1.187155203932947e-08 7.8258829819440609e-09 3.014322181734162e-06 -1.2908373390480706e-12 -3.1928208071312328e-10 -2.9578396566249657e-08 -8.0321909476482999e-09 -1.5523546607456403e-08 -6.3644223888952986e-10 -5.8602056426427837e-09 -1.6653232158043849e-08 -1.1790315830824377e-09 2.1208513955816369e-09 -2.5530828508678023e-09 -1.2926610506547117e-09 1.1634575468226878e-08 -1.7782839561356206e-08 1.8637431860427857e-09 -2.1047558332211635e-08 -7.5838761822832311e-10 -1.2908373390480706e-12 1.4050409667273109e-07 2.3134995379579986e-10 -1.0183564798966984e-11 5.6081121799700914e-10 3.6452506447547404e-09 -2.031496723107663e-11 -1.8652785264268853e-10 3.6442353976070112e-09 3.998341940603152e-10 2.5997265115716957e-09 2.1325162410567553e-09 7.6217213133024349e-09 3.6590981458874928e-08 3.0154785129451994e-08 1.5312453369595839e-08 4.5418772101169739e-09 -4.0630668458863094e-08 -3.1928208071312328e-10 2.3134995379579986e-10 1.4357264987777869e-07 2.0860137790629101e-12 -1.9743536842213233e-08 -4.5985801264556568e-09 -8.2796884336933679e-10 -1.9262466674324068e-08 -8.3772533955529158e-09 -2.83116437057Line truncated
|
||||
@@ -0,0 +1,5 @@
|
||||
FIELD_LIO_DATASET 1
|
||||
initial_pose -5 3 0 0 0 0 1
|
||||
base_from_imu 0 0 0.14999999999999999 0 0 0 1
|
||||
imu_from_lidar -0.0935 -0.1512 0.25519999999999998 0 0 0 1
|
||||
scan_timing 0 0.10000000000000001 -3.1415926535897931 1 1
|
||||
@@ -0,0 +1,66 @@
|
||||
timestamp,gx,gy,gz,ax,ay,az
|
||||
72.980000000000004,-7.8354344495958116e-05,0.0095295871084581964,-0.40739038834408964,-0.041949331379137061,-0.40863398003707235,9.8029440637868142
|
||||
72.989999999999995,-7.3445220699919602e-05,0.0095113057692195364,-0.40655347375757722,-0.039464776810238023,-0.40787204291537943,9.802970698353878
|
||||
73,-6.8033195655882233e-05,0.0098425386307416651,-0.42062532687378923,-1.3161440472412049,0.16967734403580129,9.8164590321196279
|
||||
73.010000000000005,-6.3597823361189864e-05,0.0098286904958939207,-0.4199872868871603,-0.034141829697482876,-0.40945695897781187,9.8029496912850789
|
||||
73.019999999999996,-5.9341521983073166e-05,0.0098168195913204692,-0.41943156805504295,-0.031546239725835791,-0.40873087065589297,9.8029742104844022
|
||||
73.030000000000001,-5.5283234408234081e-05,0.0098068675357802157,-0.41896020205728984,-0.02894551323978679,-0.40801612392929887,9.8029980776249648
|
||||
73.040000000000006,-5.1615350498180257e-05,0.0097014442445658815,-0.41442021007447988,0.35012569403667682,-0.57895913734330717,9.7990144597578244
|
||||
73.049999999999997,0.010749540989019113,0.023703760187714196,-0.42430441883196418,-0.11473139056687723,-1.2961638708162919,9.7374199952169338
|
||||
73.060000000000002,0.024303927187207697,0.040879816859937128,-0.42559991237085804,-0.11327635071346677,-1.2928375708421962,9.7374869126916384
|
||||
73.069999999999993,0.011412485762278794,0.024264627647123997,-0.42690041610405216,0.07181388081345752,-0.29356281998120104,9.8063506255141295
|
||||
73.079999999999998,0.011295930155629234,0.024014880793753864,-0.42820673267455744,0.070551367013256525,-0.29155143514622267,9.8064053609436499
|
||||
73.090000000000003,0.011183363015874911,0.023771824625249252,-0.4295188125035202,0.069293193095837022,-0.28955419304502961,9.806459106887063
|
||||
73.099999999999994,0.011349343630145552,0.023428029971142277,-0.40965036640913116,0.8281804914627362,-0.74377350931533792,9.7919120325237081
|
||||
73.109999999999999,0.011239564517979195,0.023191634279775646,-0.41084419631700425,0.062884985538621901,-0.28317107779209555,9.8066250865740248
|
||||
73.120000000000005,0.011133353776816027,0.022961275854002344,-0.41204619386088653,0.061633262867204719,-0.2812335932141441,9.8066751868936297
|
||||
73.129999999999995,0.011030729056048787,0.022736898797387675,-0.41325344136489545,0.060385529321138373,-0.27930995565973848,9.8067243829796755
|
||||
73.140000000000001,0.011009118823154775,0.022477589753996052,-0.40764763612085608,0.73902402991684912,-0.68217803029561108,9.7972592354529766
|
||||
73.150000000000006,0.010911927208145267,0.022262952080531619,-0.40882478462142591,0.056855632474657011,-0.27486972319131597,9.8068356450403389
|
||||
73.159999999999997,0.0011274837720274869,0.0096627950295530875,-0.41000923225785857,-0.59716098488484803,0.99474275639518506,9.9966213998068234
|
||||
73.170000000000002,0.014424957123130768,0.026625172415456429,-0.41119682285533699,-0.096278728185410153,-1.2796255714939075,9.7393101514228846
|
||||
73.180000000000007,0.027789354319285468,0.043528158300441842,-0.41239166812700828,-0.09541531211295326,-1.2760540185785516,9.7393508281239285
|
||||
73.189999999999998,0.041241544356000713,0.060397187554580921,-0.41359304209948777,-0.095928208106676072,-1.2715840444755129,9.7393222843429612
|
||||
73.200000000000003,0.056096268276119438,0.079154014092196731,-0.42882841160407531,-0.37496325908254702,-1.1245738899271704,9.7200666981755059
|
||||
73.209999999999994,0.069771135804016574,0.095975899158274591,-0.43012831949445679,-0.099376497938928374,-1.260096442126009,9.7391313347710557
|
||||
73.219999999999999,0.083602924510002563,0.11284191224767212,-0.43143312218211588,-0.10404648846002076,-1.2527028069300319,9.7388717949879915
|
||||
73.230000000000004,0.097576154389577702,0.1297292978229892,-0.43265617490999292,-0.10193310607482825,-1.2463394403026862,9.7392105327075242
|
||||
73.239999999999995,0.10284555420217026,0.13547804755532483,-0.45082200125836597,1.7493305204857117,-2.2058649128626109,9.8926098286351003
|
||||
73.25,0.11718256848883389,0.15255198489044203,-0.45242543218879611,-0.11573071861390831,-1.2283726625084974,9.7396514667232577
|
||||
73.260000000000005,0.13172216874918213,0.16971541915165328,-0.45387565352792597,-0.13100471438432626,-1.2148573787767349,9.7380098279116929
|
||||
73.269999999999996,0.14651888968594512,0.18702855363576426,-0.45533576667306319,-0.14153514855913343,-1.2027668920853274,9.7373371381992744
|
||||
73.280000000000001,0.16159635833286834,0.20451668446936047,-0.45680629260130595,-0.15347071295778156,-1.1895657968484012,9.7365366560660682
|
||||
73.290000000000006,0.17697857439565889,0.22220474901567216,-0.45828815603846612,-0.16681668041367642,-1.1752044487194755,9.7356001897313185
|
||||
73.299999999999997,0.19317938387111885,0.24096209442295696,-0.44330059132484445,-0.32601790288839161,-1.0814763533931744,9.7179752444769445
|
||||
73.310000000000002,0.20924681156617111,0.2591997520549254,-0.44470322812392088,-0.20005417423733532,-1.1427413633144983,9.7330382921714751
|
||||
73.319999999999993,0.21799100295136525,0.27313151403498587,-0.43980839089244594,-0.21007216449068022,-1.0025491156634148,9.7454605177780973
|
||||
73.329999999999998,0.23288777627506119,0.28981750868208533,-0.44127550976639796,-0.22918030374248341,-0.98393951018281656,9.7439637648319231
|
||||
73.340000000000003,0.24458329896663189,0.30301441633392945,-0.41276865111697753,2.5259868908446221,1.5417214323607373,9.8767183112935903
|
||||
73.349999999999994,0.04670193778725152,0.089972856964108353,-0.33938019711657563,-1.8581802015841355,4.2524418790403562,5.0166236830827415
|
||||
73.359999999999999,-0.023033935035377841,-0.044325621378972835,-0.25668604600173428,-2.4445259469386813,5.6563400047690697,6.5398699530043114
|
||||
73.370000000000005,-0.11548343221942599,-0.16354870515891556,-0.39319706972899976,-4.0700637614422241,-16.712599868001288,31.415677482000284
|
||||
73.379999999999995,-0.10816181034319979,-0.1538397404140206,-0.42195887516994757,-0.24592455318405387,-1.1445999717616107,9.7401309387465353
|
||||
73.390000000000001,-0.093391386527653858,-0.13368654534171145,-0.42320449357488288,-0.23155778985928718,-1.1493817872544265,9.7413798757177315
|
||||
73.400000000000006,-0.084723749092420919,-0.12032911328889175,-0.38509361277589499,0.93222191855265923,-1.6405616540193313,9.8661844224595807
|
||||
73.409999999999997,-0.07001750024545815,-0.10062080805496776,-0.38612060666621112,-0.21128500605782019,-1.154742724074667,9.7426710011034974
|
||||
73.420000000000002,-0.055373222601836629,-0.08114331114713795,-0.3871575638424587,-0.20141361068485586,-1.1570598987616196,9.7434584692680009
|
||||
73.430000000000007,-0.040768607507474686,-0.061867670724642519,-0.38819835455162177,-0.19308418516556647,-1.158355767869238,9.7441003166961409
|
||||
73.439999999999998,-0.029559138861381382,-0.04635890691270271,-0.35746102627438814,0.45053145277940698,-1.4115767250331073,9.807803517919286
|
||||
73.450000000000003,-0.014895278490932962,-0.027306014586986567,-0.35834076391564817,-0.18416775203970459,-1.1572689145193358,9.7445953836794494
|
||||
73.459999999999994,-0.00020511751773792794,-0.0083598975532057015,-0.35922913558038883,-0.1780823996002367,-1.1512554001287785,9.7448560762734751
|
||||
73.469999999999999,0.017576967131798776,0.014387198741614459,-0.36012131810905157,0.12000139884387431,-0.53074901562916732,9.7439790888988966
|
||||
73.480000000000004,0.035455749590555974,0.037087097815893144,-0.36101644273562561,0.11596641417312487,-0.53172432874625919,9.7436965220290936
|
||||
73.489999999999995,0.051139603805240991,0.056629455590295141,-0.36428063944003952,0.081754199690666607,-0.51300593922714532,9.7533136220894736
|
||||
73.5,0.062949892556653259,0.07255574335997958,-0.30458072326919639,5.3607773514998627,4.8651334266379376,9.9672454470668104
|
||||
73.510000000000005,0.080093947171883478,0.093774571062345477,-0.3052256501626589,0.074807149362320746,-0.47877550007980313,9.751305284643589
|
||||
73.519999999999996,0.097420639914153062,0.11507873598934916,-0.3058964247111195,0.064973701725612065,-0.47475406283817656,9.7502222255262012
|
||||
73.530000000000001,0.11495685821268421,0.13649546381171412,-0.3065837564438485,0.053370590896538506,-0.46965324624279176,9.7489145355568247
|
||||
73.540000000000006,0.29723332159126603,0.37461955584236989,-0.22351489315656864,-12.788428419911225,-5.9459184533471117,8.911534997472458
|
||||
73.549999999999997,-0.0066481793987961044,0.20825765418887801,-0.2226766795842833,-3.7620317988710532,1.7741290509259613,5.4903190207580019
|
||||
73.560000000000002,0.0062837318174231993,0.12637890870908894,-0.16769073775878729,-6.6064098596231249,0.41758271667715674,8.3696263076125792
|
||||
73.569999999999993,0.0040442971016930226,0.056573159912984013,-0.10212823950165814,-6.7379210190338803,0.15044657152919713,8.4427996491416533
|
||||
73.579999999999998,0.0016495690894367616,-0.013163794294091001,-0.036572344137316609,-6.7375967545183801,0.15443064835544271,8.4423661799084453
|
||||
73.590000000000003,0.00022069049724417894,-0.08737929976847815,1.7012733126897927e-05,-6.2479265595145961,1.5459013180568317,8.2960183842218616
|
||||
73.599999999999994,4.9683713493571535e-05,-0.16736300845426663,1.5905618074494828e-05,-6.2355129994503384,1.546419311232109,8.3003729570604605
|
||||
73.609999999999999,-0.00012075011793151458,-0.2476389531478862,1.4609841830961557e-05,-6.2108012231131546,1.5441335599584702,8.3018758052246326
|
||||
73.620000000000005,-0.09678470505438122,-0.12357589020282497,-2.1495070713531232e-07,0.10627007267836641,-0.31333170698237695,9.7335273902384483
|
||||
|
@@ -0,0 +1,7 @@
|
||||
Isolated Gazebo Python launch, cylinder centered at (-4,-1.5), radius 0.22 m.
|
||||
The leg from (0,0) back to (-5,3) stopped after rejections at 73.3 and 73.4 s
|
||||
with registration stage FINAL_FUSION and innovation above the rank-six gate.
|
||||
The checkpoint is the live prediction at sim 73.0 s. The estimate was low by
|
||||
0.075 m at 73.3 s. Predicted and true sensor poses had 513 and 545 inliers.
|
||||
Uses return_contact/map.flmap. Ground truth only scores the result.
|
||||
The original unrecorded zero-correspondence failure is a separate symptom.
|
||||
@@ -0,0 +1,8 @@
|
||||
timestamp,file
|
||||
73,716.flpc
|
||||
73.099999999999994,717.flpc
|
||||
73.200000000000003,718.flpc
|
||||
73.299999999999997,719.flpc
|
||||
73.400000000000006,720.flpc
|
||||
73.5,721.flpc
|
||||
73.599999999999994,722.flpc
|
||||
|
@@ -0,0 +1,64 @@
|
||||
72.986000000000004 -1.1827268115237362 -1.5545798885105371 0.0058503683128641685 0.0031301075244346047 -0.011291668895969408 0.96303472306647764 -0.26912231941758785
|
||||
72.995999999999995 -1.1871888648243818 -1.5576408724309503 0.0058506913738757497 0.0031073608787444322 -0.011298428291316116 0.96357973301227318 -0.2671643463385629
|
||||
73.006 -1.1916342342322537 -1.5606819444765541 0.0058509988583626453 0.0030839596115858335 -0.011305291957612885 0.96413552600730001 -0.26515159259844956
|
||||
73.016000000000005 -1.1960801508860572 -1.5637051949047489 0.0058512915210192735 0.0030604007959725938 -0.011312122327296068 0.96469019752111762 -0.26312638150152751
|
||||
73.025999999999996 -1.2005324013228871 -1.5667114803470656 0.0058515701113706535 0.0030368478865988595 -0.01131887567226837 0.96523991156191746 -0.26110261150814101
|
||||
73.036000000000001 -1.2049911000891447 -1.569700966017002 0.0058518353561440436 0.0030132968344191305 -0.011325554296524652 0.9657847915226504 -0.25907988792188191
|
||||
73.046000000000006 -1.2094761555512541 -1.5726563636090436 0.0058514931440729551 0.0029775415743041557 -0.011327041109622219 0.96632793569678654 -0.25704698612872584
|
||||
73.055999999999997 -1.2139813859319666 -1.5755217306559217 0.0058467866734837094 0.0028531614658296417 -0.011290521870982027 0.9668725771097133 -0.25499373172443324
|
||||
73.066000000000003 -1.2184970583372341 -1.5783420770566474 0.0058411485173472224 0.0027101286142647055 -0.011245432738640568 0.9674146672986218 -0.25293290996015494
|
||||
73.075999999999993 -1.2230230999073919 -1.581174339566185 0.0058372459161947837 0.0026026102969416822 -0.011215152911073112 0.96795363620886388 -0.25086491367838176
|
||||
73.085999999999999 -1.2275594802434509 -1.584004724373161 0.0058334010181124874 0.0024965007395751663 -0.011185053184934762 0.96848978920550355 -0.24878944968383798
|
||||
73.096000000000004 -1.2321061458005205 -1.586833273349284 0.0058296125281075833 0.0023917628099110935 -0.011155125972395104 0.96902309106103679 -0.24670648881963916
|
||||
73.105999999999995 -1.2366770672797653 -1.5896597593421413 0.0058257933189042521 0.0022875676175172907 -0.011124399978516344 0.96953274426748903 -0.24469832968916033
|
||||
73.116 -1.2412612759579238 -1.5924844438350985 0.0058220077784071631 0.0021845019836098339 -0.011093611178925624 0.97003453494922343 -0.24270385400305933
|
||||
73.126000000000005 -1.2458551695513467 -1.5953074384597066 0.005818276249389181 0.0020827332471716501 -0.011062995599026178 0.9705336511324667 -0.24070252256692404
|
||||
73.135999999999996 -1.2504586966141451 -1.5981287852739068 0.0058145975239704299 0.0019822282630259577 -0.011032546067196629 0.97103006156964311 -0.23869430916224993
|
||||
73.146000000000001 -1.255084419744052 -1.6009479136873122 0.0058109448845094034 0.001882740217275448 -0.011001970759730145 0.97151727032669921 -0.23670573585284282
|
||||
73.156000000000006 -1.2597227209909205 -1.6037653292807263 0.0058073367000094668 0.0017844065781903173 -0.010971482741895466 0.97200017467302524 -0.23471706988460922
|
||||
73.165999999999997 -1.2643703716012211 -1.6065692004929799 0.0058054351471337629 0.0017207138821939841 -0.010956429657944052 0.97248007250003377 -0.23272194650100214
|
||||
73.176000000000002 -1.2690273659231286 -1.6092870412226157 0.0057995853584831784 0.0015774642266509142 -0.010904630443552707 0.9729579453695304 -0.23071939056742757
|
||||
73.186000000000007 -1.2736936294264443 -1.6119132852962943 0.0057888903842487011 0.0013366454841123518 -0.010807168976942191 0.9734338788669914 -0.22870920827880409
|
||||
73.195999999999998 -1.2783690768235658 -1.6144484411759916 0.0057733570847300335 0.00099838714014245981 -0.010663363271679079 0.97390776174996807 -0.22669134855574477
|
||||
73.206000000000003 -1.2830459816176745 -1.6168935041479873 0.0057526303709198659 0.00055478348460317756 -0.010469086626791425 0.97439213585460505 -0.22461089916828808
|
||||
73.215999999999994 -1.2877302190973396 -1.6192486817193614 0.0057269994531547698 1.1858640024756509e-05 -0.010226038876597652 0.97487711803995747 -0.22250850031037867
|
||||
73.225999999999999 -1.2924236269314422 -1.6215143558841598 0.0056965603103861003 -0.00062870174059144587 -0.0099341254176952484 0.97535929519869891 -0.2203977385451229
|
||||
73.236000000000004 -1.2971263107162498 -1.6236910792608883 0.0056613326323830615 -0.0013670999905177658 -0.0095924540980015325 0.97583833270215847 -0.21827886817341038
|
||||
73.245999999999995 -1.3018883834526711 -1.6257740491873514 0.0056239117144352598 -0.0021517079689924931 -0.0092250211793455002 0.97632841537557724 -0.2160858497617815
|
||||
73.256 -1.3066724522289066 -1.6277675579927218 0.005582366458046736 -0.0030220127470465268 -0.0088121498758130402 0.97681841066491237 -0.21386679508422426
|
||||
73.266000000000005 -1.3114658236480086 -1.6296735204577222 0.005536059271095733 -0.0039917655401962571 -0.0083463838234752209 0.97730427806235165 -0.2116382568581803
|
||||
73.275999999999996 -1.3162683485699671 -1.6314924744494148 0.0054849957814838224 -0.0050619140072993641 -0.007826374711552871 0.97778560591429009 -0.2094001761037505
|
||||
73.286000000000001 -1.3210799159925637 -1.6332249663976133 0.0054291888087800583 -0.0062335075109966193 -0.0072506941703858385 0.97826195609988331 -0.20715239816566938
|
||||
73.296000000000006 -1.3259004157127494 -1.6348715556793953 0.0053686555042825965 -0.0075077337713179019 -0.0066178173011011698 0.9787328436423689 -0.20489475152748682
|
||||
73.305999999999997 -1.3307258730288571 -1.6364331023120495 0.0053031983619743518 -0.0088901447072203075 -0.0059243973886139627 0.97918432592740234 -0.20269169371428425
|
||||
73.316000000000003 -1.3355688420359801 -1.6379338642402002 0.0052066599772398357 -0.010349309723247574 -0.0051351687533685254 0.97962303805373774 -0.20051240646027871
|
||||
73.325999999999993 -1.3404288287396919 -1.6393094520762683 0.0051431728984243112 -0.01191358322865199 -0.0043528051038197648 0.98005172552508568 -0.19833742692110404
|
||||
73.335999999999999 -1.3452969908923822 -1.6406113168530503 0.0050762464459957867 -0.013574640558649069 -0.003513638653623339 0.9804731942281727 -0.19615223393354278
|
||||
73.346000000000004 -1.3501895167318128 -1.6419798548380817 0.005108738976746104 -0.015112268455780108 -0.002745964899443495 0.98085529585059306 -0.19413131540464329
|
||||
73.355999999999995 -1.3549640787730097 -1.643812391091483 0.0052728105183241208 -0.015456375536794619 -0.0026939842015352993 0.98116484973653617 -0.19253410229325085
|
||||
73.366 -1.3595536153661432 -1.6459691252064099 0.0050727415228652038 -0.015103014156831235 -0.0028926586344415043 0.98142075506854209 -0.19125070721462972
|
||||
73.376000000000005 -1.3644408608921856 -1.6481096591831021 0.0050303164843351379 -0.014129238367996394 -0.0031990403064940261 0.98181768324296859 -0.18927273347122053
|
||||
73.385999999999996 -1.3693679054219983 -1.6500463243136565 0.0050716421136637185 -0.013287502301379286 -0.0036035105415935555 0.98222354639289056 -0.18720940656318727
|
||||
73.396000000000001 -1.3743027258731864 -1.6518878352927291 0.0051078334634670477 -0.012558165495312168 -0.0039544144955527879 0.9826243984334011 -0.18513764254949971
|
||||
73.406000000000006 -1.3792750390455779 -1.653630489318143 0.0051402522403393063 -0.011910411700310231 -0.0042684389015000919 0.98299183291174042 -0.18321293336249561
|
||||
73.415999999999997 -1.3842618856175508 -1.6552783728159306 0.0051678629559868527 -0.011365311066434713 -0.0045325318919417308 0.98334805810745662 -0.18131983475424274
|
||||
73.426000000000002 -1.3892557057606063 -1.6568332167167177 0.0051903275164664614 -0.010928970993995174 -0.0047423280642563716 0.98370049479445809 -0.1794196323111874
|
||||
73.436000000000007 -1.394256443797167 -1.6582956225633008 0.0052076506453389328 -0.010600293412376642 -0.0048976108430821763 0.98404929433243071 -0.17751234749010111
|
||||
73.445999999999998 -1.3992803525324311 -1.6596636580785431 0.0052205679673638641 -0.010362552415903985 -0.0050074287281092989 0.9843722748967384 -0.17572355442450174
|
||||
73.456000000000003 -1.4043146774059381 -1.6609397975496776 0.0052285160752110005 -0.010227302423756654 -0.0050641691906889597 0.98468660432798594 -0.17395990265737007
|
||||
73.465999999999994 -1.4093552246548775 -1.6621424203794255 0.0052310615029692153 -0.010203195071777764 -0.0050622497105420518 0.98499790146017485 -0.17219001875035322
|
||||
73.475999999999999 -1.4144019162987285 -1.6633231241499224 0.0052274511189123575 -0.01030546793865101 -0.0049927276760517187 0.98530606351375705 -0.17041370603311956
|
||||
73.486000000000004 -1.4194603931236236 -1.6644842632343171 0.0052180160450279768 -0.010528061320118303 -0.0048578627442221181 0.98561223941979692 -0.16862406293376736
|
||||
73.495999999999995 -1.4245287535741527 -1.6656258096952028 0.0052034305511925519 -0.01086466396589038 -0.0046597265761129372 0.98591593499195707 -0.16682330518869151
|
||||
73.506 -1.4296621409454648 -1.6668540088835526 0.0051845470553112281 -0.011296878445963545 -0.0044096432938098198 0.98617617643336519 -0.16525581568788048
|
||||
73.516000000000005 -1.4348154349037505 -1.6680920915855586 0.0051606356239071475 -0.011842531349017563 -0.0040958759277063429 0.98642343956985878 -0.16374301853453616
|
||||
73.525999999999996 -1.4399737281517972 -1.6693138150216535 0.0051314803138102659 -0.012507535848080481 -0.0037139381697808187 0.98666753687285635 -0.1622249669179523
|
||||
73.536000000000001 -1.4448108571510392 -1.6703872549451679 0.0050748358390243983 -0.013654117135374278 -0.0030522962961160565 0.98687800113934654 -0.16086037249671561
|
||||
73.546000000000006 -1.448396490965824 -1.6708636848531406 0.005251067238020434 -0.015408964009291733 -0.002318675811017387 0.98703020248953166 -0.15977661576124966
|
||||
73.555999999999997 -1.4515248319730381 -1.6713613042405748 0.0055058843437679012 -0.016317612017665597 -0.0026360788593341013 0.98719442384803147 -0.15866302704045965
|
||||
73.566000000000003 -1.4541058422468496 -1.6717288667858907 0.0056966781063328351 -0.016875331532463796 -0.0027096104034522975 0.98730797652805991 -0.15789503057790946
|
||||
73.575999999999993 -1.4561705707068855 -1.6719405539160637 0.005769558057817115 -0.017087362353195943 -0.002733171804277935 0.98737458440055792 -0.15745469792776765
|
||||
73.585999999999999 -1.4577188766658054 -1.6719969350138024 0.0057247128990593867 -0.016953677612950045 -0.0027079798480792918 0.98739581231247131 -0.15733642136623532
|
||||
73.596000000000004 -1.4587606276285694 -1.6719950828801873 0.0055514879861516108 -0.016443476617033503 -0.0026257375244013747 0.98740443243506093 -0.15733786698310492
|
||||
73.605999999999995 -1.4593019073162419 -1.6719919533146337 0.0052435932373300249 -0.015538053557393336 -0.002481383320436847 0.98741908353097274 -0.1573402844389151
|
||||
73.616 -1.4593872573948983 -1.6719896736122408 0.0050093300597352768 -0.014500939174517082 -0.0025331301065374453 0.98743382718860817 -0.1573459339753602
|
||||
@@ -1,50 +1,151 @@
|
||||
#include "field_localization/core/dataset.hpp"
|
||||
#include "field_localization/core/tracking_health.hpp"
|
||||
#include "test_util.hpp"
|
||||
|
||||
#include <Eigen/Eigenvalues>
|
||||
#include <cstdio>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <cstdio>
|
||||
|
||||
using namespace field_localization::core;
|
||||
int main(int argc,char **argv) {
|
||||
CHECK(argc==2);if(argc!=2) return 1;
|
||||
const std::filesystem::path directory=argv[1];
|
||||
auto options=read_dataset_config(directory/"config.txt");
|
||||
FilterSnapshot checkpoint;auto &s=checkpoint.state;std::ifstream input(directory/"checkpoint.txt");
|
||||
input>>s.timestamp_sec;
|
||||
for(auto *v:{&s.pose.translation,&s.velocity}) for(int i=0;i<3;++i) input>>(*v)[i];
|
||||
for(int i=0;i<4;++i) input>>s.pose.rotation.coeffs()[i];
|
||||
for(auto *v:{&s.gyro_bias,&s.accel_bias,&s.gravity}) for(int i=0;i<3;++i) input>>(*v)[i];
|
||||
for(int i=0;i<18;++i) for(int j=0;j<18;++j) input>>checkpoint.covariance(i,j);
|
||||
|
||||
namespace {
|
||||
struct Report {
|
||||
int scans{0};
|
||||
int full{0};
|
||||
int innovation_rejections{0};
|
||||
double maximum_rotation_error{0};
|
||||
double maximum_correction_gap{0};
|
||||
double maximum_position_error{0};
|
||||
double maximum_position_three_sigma{0};
|
||||
};
|
||||
|
||||
Report evaluate_recording(const std::filesystem::path &directory,const NoiseOptions &noise,
|
||||
const std::filesystem::path &map_path,const RegistrationOptions ®istration={}) {
|
||||
const auto options=read_dataset_config(directory/"config.txt");
|
||||
FilterSnapshot checkpoint;
|
||||
auto &state=checkpoint.state;
|
||||
std::ifstream input(directory/"checkpoint.txt");
|
||||
input>>state.timestamp_sec;
|
||||
for (auto *v:{&state.pose.translation,&state.velocity})
|
||||
for (int i=0;i<3;++i) input>>(*v)[i];
|
||||
for (int i=0;i<4;++i) input>>state.pose.rotation.coeffs()[i];
|
||||
for (auto *v:{&state.gyro_bias,&state.accel_bias,&state.gravity})
|
||||
for (int i=0;i<3;++i) input>>(*v)[i];
|
||||
for (int i=0;i<18;++i)
|
||||
for (int j=0;j<18;++j) input>>checkpoint.covariance(i,j);
|
||||
CHECK(static_cast<bool>(input));
|
||||
std::string error;const auto map=read_map(directory/"map.flmap",error);CHECK(map.has_value());if(!map) return 1;
|
||||
ErrorStateFilter filter;filter.restore(checkpoint);
|
||||
std::vector<ImuData> samples;std::ifstream imu(directory/"imu.csv");std::string line;std::getline(imu,line);
|
||||
|
||||
std::string error;
|
||||
const auto map=read_map(map_path,error);
|
||||
CHECK(map.has_value());
|
||||
if (!map) return {};
|
||||
|
||||
std::vector<ImuData> samples;
|
||||
std::ifstream imu(directory/"imu.csv");
|
||||
std::string line;
|
||||
std::getline(imu,line);
|
||||
while (std::getline(imu,line)) {
|
||||
std::replace(line.begin(),line.end(),',',' ');std::istringstream row(line);ImuData value;
|
||||
std::replace(line.begin(),line.end(),',',' ');
|
||||
std::istringstream row(line);
|
||||
ImuData value;
|
||||
row>>value.timestamp_sec>>value.angular_velocity.x()>>value.angular_velocity.y()>>value.angular_velocity.z()
|
||||
>>value.linear_acceleration.x()>>value.linear_acceleration.y()>>value.linear_acceleration.z();
|
||||
CHECK(static_cast<bool>(row));samples.push_back(value);
|
||||
CHECK(static_cast<bool>(row));
|
||||
samples.push_back(value);
|
||||
}
|
||||
const auto truth=read_trajectory(directory/"truth.tum");
|
||||
std::ifstream scans(directory/"scans.csv");std::getline(scans,line);int full=0;double maximum=0;
|
||||
std::ifstream scans(directory/"scans.csv");
|
||||
std::getline(scans,line);
|
||||
ErrorStateFilter filter(noise);
|
||||
filter.restore(checkpoint);
|
||||
Report report;
|
||||
TrackingHealth health;
|
||||
const auto imu_from_base=inverse(options.base_from_imu);
|
||||
double last_correction=-1;
|
||||
auto observe_prior=[&] {
|
||||
const auto &prior=filter.snapshot();
|
||||
LocalizationSnapshot snapshot{compose(prior.state.pose,imu_from_base),prior,{}};
|
||||
health.update(snapshot,options.base_from_imu,prior.state.timestamp_sec);
|
||||
report.maximum_position_three_sigma=std::max(report.maximum_position_three_sigma,
|
||||
health.position_three_sigma());
|
||||
};
|
||||
while (std::getline(scans,line)) {
|
||||
const auto cloud=read_cloud(directory/line.substr(line.find(',')+1));
|
||||
auto a=interpolate_imu(samples,filter.snapshot().state.timestamp_sec);CHECK(a.has_value());if(!a) return 1;
|
||||
for(const auto &b:samples) if(b.timestamp_sec>a->timestamp_sec && b.timestamp_sec<cloud.timestamp_sec) {
|
||||
CHECK(filter.propagate(*a,b));a=b;
|
||||
auto a=interpolate_imu(samples,filter.snapshot().state.timestamp_sec);
|
||||
CHECK(a.has_value());
|
||||
if (!a) return report;
|
||||
for (const auto &b:samples) {
|
||||
if (b.timestamp_sec<=a->timestamp_sec || b.timestamp_sec>=cloud.timestamp_sec) continue;
|
||||
CHECK(filter.propagate(*a,b));
|
||||
observe_prior();
|
||||
a=b;
|
||||
}
|
||||
const auto finish=interpolate_imu(samples,cloud.timestamp_sec);CHECK(finish.has_value());if(!finish) return 1;
|
||||
const auto finish=interpolate_imu(samples,cloud.timestamp_sec);
|
||||
CHECK(finish.has_value());
|
||||
if (!finish) return report;
|
||||
if (finish->timestamp_sec>a->timestamp_sec) CHECK(filter.propagate(*a,*finish));
|
||||
const auto result=scan_to_map(cloud,options.deskew.imu_from_sensor,*map,filter.snapshot());
|
||||
CHECK(result.success);if(result.success) {filter.restore(result.estimate);++full;}
|
||||
const auto base=compose(filter.snapshot().state.pose,inverse(options.base_from_imu));
|
||||
const auto gt=trajectory_pose(truth,cloud.timestamp_sec);CHECK(gt.has_value());if(!gt) return 1;
|
||||
maximum=std::max(maximum,(base.translation-gt->translation).norm());
|
||||
CHECK(log_so3(gt->rotation.conjugate()*base.rotation).norm()<0.02);
|
||||
const Eigen::SelfAdjointEigenSolver<Matrix18> eigen(filter.snapshot().covariance);
|
||||
CHECK(eigen.info()==Eigen::Success);CHECK(eigen.eigenvalues().minCoeff()>-1e-10);
|
||||
observe_prior();
|
||||
const auto result=scan_to_map(cloud,options.deskew.imu_from_sensor,*map,filter.snapshot(),
|
||||
noise,registration);
|
||||
++report.scans;
|
||||
if (result.failure==RegistrationFailure::INNOVATION) ++report.innovation_rejections;
|
||||
if (last_correction>=0)
|
||||
report.maximum_correction_gap=std::max(report.maximum_correction_gap,
|
||||
cloud.timestamp_sec-last_correction);
|
||||
if (result.success) {
|
||||
last_correction=cloud.timestamp_sec;
|
||||
filter.restore(result.estimate);
|
||||
++report.full;
|
||||
}
|
||||
std::printf("recorded transition: FULL=%d/5 maximum_position_error=%.9g m\n",full,maximum);
|
||||
CHECK(full==5);CHECK(maximum<0.10);
|
||||
const auto base=compose(filter.snapshot().state.pose,imu_from_base);
|
||||
const auto gt=trajectory_pose(truth,cloud.timestamp_sec);
|
||||
CHECK(gt.has_value());
|
||||
if (!gt) return report;
|
||||
report.maximum_position_error=std::max(report.maximum_position_error,
|
||||
(base.translation-gt->translation).norm());
|
||||
report.maximum_rotation_error=std::max(report.maximum_rotation_error,
|
||||
log_so3(gt->rotation.conjugate()*base.rotation).norm());
|
||||
const Eigen::SelfAdjointEigenSolver<Matrix18> eigen(filter.snapshot().covariance);
|
||||
CHECK(eigen.info()==Eigen::Success);
|
||||
CHECK(eigen.eigenvalues().minCoeff()>-1e-10);
|
||||
}
|
||||
std::printf("%s scale=%.2f map_sigma=%.3f FULL=%d/%d innovation_rejections=%d max_position_error=%.6f m max_prior_horizontal_3sigma=%.6f m max_rotation_error=%.6f rad max_correction_gap=%.6f s\n",
|
||||
directory.filename().string().c_str(),noise.integration_error_scale,registration.map_translation_sigma,
|
||||
report.full,report.scans,report.innovation_rejections,report.maximum_position_error,
|
||||
report.maximum_position_three_sigma,report.maximum_rotation_error,report.maximum_correction_gap);
|
||||
return report;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main(int argc,char **argv) {
|
||||
CHECK(argc==4);
|
||||
if (argc!=4) return 1;
|
||||
const std::filesystem::path turn=argv[1],clear_return=argv[2],cylinder_return=argv[3];
|
||||
const auto turn_report=evaluate_recording(turn,{},turn/"map.flmap");
|
||||
CHECK(turn_report.scans==5 && turn_report.full==5);
|
||||
CHECK(turn_report.maximum_position_error<0.10);
|
||||
CHECK(turn_report.maximum_rotation_error<0.02);
|
||||
|
||||
const auto return_map=clear_return/"map.flmap";
|
||||
const auto updated=evaluate_recording(clear_return,{},return_map);
|
||||
NoiseOptions previous_noise;
|
||||
previous_noise.integration_error_scale=2.0;
|
||||
RegistrationOptions previous_map;
|
||||
previous_map.map_translation_sigma=0.02;
|
||||
const auto baseline=evaluate_recording(clear_return,previous_noise,return_map,previous_map);
|
||||
CHECK(updated.scans==5 && updated.full==5);
|
||||
CHECK(baseline.scans==5 && baseline.full==5);
|
||||
CHECK(updated.maximum_position_error<0.10);
|
||||
CHECK(baseline.maximum_position_three_sigma>HealthOptions{}.position_three_sigma);
|
||||
CHECK(updated.maximum_position_three_sigma<HealthOptions{}.position_three_sigma);
|
||||
|
||||
const auto cylinder=evaluate_recording(cylinder_return,{},return_map);
|
||||
const auto previous_cylinder=evaluate_recording(cylinder_return,{},return_map,previous_map);
|
||||
CHECK(cylinder.scans==7 && cylinder.full>previous_cylinder.full);
|
||||
CHECK(cylinder.maximum_correction_gap<HealthOptions{}.correction_timeout);
|
||||
CHECK(previous_cylinder.maximum_correction_gap>=HealthOptions{}.correction_timeout-1e-9);
|
||||
CHECK(cylinder.maximum_position_error<0.10);
|
||||
CHECK(previous_cylinder.innovation_rejections>=1);
|
||||
return sentry_nav_test::Summary("RecordedUpdate");
|
||||
}
|
||||
@@ -20,6 +20,20 @@ int main() {
|
||||
RegistrationOptions exact_map; exact_map.map_translation_sigma=0; exact_map.map_rotation_sigma=0;
|
||||
const auto result=scan_to_map(scan,{},map,filter.snapshot(),{},exact_map);
|
||||
CHECK(result.success); CHECK(result.degeneracy.dimensions==0);
|
||||
CHECK(result.stage==RegistrationStage::COMPLETE);
|
||||
const auto support=inspect_scan_support(scan,{},map,initial.pose,exact_map);
|
||||
CHECK(support.candidate_planes<=support.sampled);
|
||||
CHECK(support.candidate_planes==support.outside_support+support.plane_distance_rejected+support.inliers);
|
||||
CHECK(result.initial_associations.inliers==support.inliers);
|
||||
CHECK(result.last_associations.inliers==result.inliers);
|
||||
auto far=initial;
|
||||
far.pose.translation.x()+=20;
|
||||
filter.initialize(far);
|
||||
const auto unsupported=scan_to_map(scan,{},map,filter.snapshot(),{},exact_map);
|
||||
CHECK(!unsupported.success);
|
||||
CHECK(unsupported.stage==RegistrationStage::INITIAL_MATCH);
|
||||
CHECK(unsupported.failure==RegistrationFailure::NO_CORRESPONDENCES);
|
||||
CHECK(unsupported.initial_associations.sampled>0 && unsupported.initial_associations.candidate_planes==0);
|
||||
const double position_error=(result.estimate.state.pose.translation-truth.translation).norm();
|
||||
const double rotation_error=log_so3(truth.rotation.conjugate()*result.estimate.state.pose.rotation).norm();
|
||||
std::printf("3-plane registration: translation %.9g m, rotation %.9g rad, rmse %.9g, inliers %zu\n",
|
||||
@@ -51,6 +65,7 @@ int main() {
|
||||
const auto rejected=scan_to_map(shifted,{},floor,confident,{},strict);
|
||||
CHECK(!rejected.success);
|
||||
CHECK(rejected.failure==RegistrationFailure::INNOVATION);
|
||||
CHECK(rejected.stage==RegistrationStage::FINAL_FUSION);
|
||||
CHECK(rejected.inliers>100);
|
||||
CHECK(rejected.measurement_rank==3);
|
||||
// Rotate the whole plane; verify its null space rather than an axis label.
|
||||
|
||||
@@ -77,10 +77,22 @@ local function ros_common()
|
||||
end
|
||||
end
|
||||
|
||||
if not ROS then
|
||||
local distro = os.getenv("ROS_DISTRO")
|
||||
if distro and distro ~= "" then
|
||||
local candidate = "/opt/ros/" .. distro
|
||||
if os.isdir(candidate .. "/include")
|
||||
and os.isdir(candidate .. "/lib") then
|
||||
|
||||
ROS = candidate
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
if not ROS then
|
||||
raise(
|
||||
"ROS installation not found. "
|
||||
.. "Source ROS setup or set ROS_PREFIX."
|
||||
.. "Source ROS setup or set ROS_PREFIX / ROS_DISTRO."
|
||||
)
|
||||
end
|
||||
end
|
||||
@@ -88,7 +100,7 @@ local function ros_common()
|
||||
-- Resolve ROS include directories.
|
||||
local script = path.join(
|
||||
target:scriptdir(),
|
||||
"../../tools/resolve_ros_includes.py"
|
||||
"../../tools/_internal/resolve_ros_includes.py"
|
||||
)
|
||||
|
||||
if not os.isfile(script) then
|
||||
@@ -416,6 +428,11 @@ target("test_recorded_update")
|
||||
add_files("tests/test_recorded_update.cpp")
|
||||
add_deps("field_localization_core")
|
||||
on_load(function(target)
|
||||
target:set("runargs", {path.join(os.projectdir(), "src/field_localization/tests/data/turn_contact")})
|
||||
local fixtures = path.join(os.projectdir(), "src/field_localization/tests/data")
|
||||
target:set("runargs", {
|
||||
path.join(fixtures, "turn_contact"),
|
||||
path.join(fixtures, "return_contact"),
|
||||
path.join(fixtures, "return_cylinder"),
|
||||
})
|
||||
end)
|
||||
add_tests("default", {group = "unit"})
|
||||
@@ -28,6 +28,7 @@
|
||||
#include <cstdlib>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
@@ -37,6 +38,7 @@
|
||||
#include <nav2_msgs/action/navigate_to_pose.hpp>
|
||||
#include <nav_msgs/msg/occupancy_grid.hpp>
|
||||
#include <geometry_msgs/msg/pose_stamped.hpp>
|
||||
#include <std_msgs/msg/bool.hpp>
|
||||
#include <tf2_ros/buffer.hpp>
|
||||
#include <tf2_ros/transform_listener.hpp>
|
||||
|
||||
@@ -56,6 +58,7 @@ constexpr int kOccupiedThreshold = 65;
|
||||
constexpr double kClearanceSearch = 2.0;
|
||||
// 圆周率(避开 M_PI —— 严格 C++ 里它不是标准宏)。
|
||||
constexpr double kPi = 3.14159265358979323846;
|
||||
constexpr auto kLocalizationFreshness = 300ms;
|
||||
|
||||
struct Args
|
||||
{
|
||||
@@ -166,6 +169,14 @@ int main(int argc, char * argv[])
|
||||
|
||||
tf2_ros::Buffer tf_buffer(node->get_clock());
|
||||
tf2_ros::TransformListener tf_listener(tf_buffer);
|
||||
std::optional<std::chrono::steady_clock::time_point> last_health;
|
||||
bool localization_valid = false;
|
||||
auto health_sub = node->create_subscription<std_msgs::msg::Bool>(
|
||||
"/field_localization/navigation_valid", rclcpp::QoS(1),
|
||||
[&](const std_msgs::msg::Bool & msg) {
|
||||
last_health = std::chrono::steady_clock::now();
|
||||
localization_valid = msg.data;
|
||||
});
|
||||
|
||||
// /map 是 TRANSIENT_LOCAL 发布的,用默认 QoS 会一条都收不到。
|
||||
auto map_qos = rclcpp::QoS(rclcpp::KeepLast(1))
|
||||
@@ -197,7 +208,7 @@ int main(int argc, char * argv[])
|
||||
|
||||
map_executor.remove_node(node);
|
||||
if (!holder.got) {
|
||||
std::printf("⚠️ 15 秒内没收到 /map,跳过预检直接发目标\n");
|
||||
std::printf("⚠️ 15 秒内没收到 /map,跳过静态地图预检\n");
|
||||
} else {
|
||||
const auto & info = holder.last.info;
|
||||
const auto & data = holder.last.data;
|
||||
@@ -254,6 +265,54 @@ int main(int argc, char * argv[])
|
||||
}
|
||||
std::printf("✅ 动作服务器可用\n");
|
||||
|
||||
// Give discovery and the TF listener a bounded window before sending a goal.
|
||||
// AMCL has no LIO heartbeat and uses the same fresh TF check.
|
||||
auto localization_error = [&]() -> const char * {
|
||||
if (last_health || health_sub->get_publisher_count() > 0) {
|
||||
if (!last_health || std::chrono::steady_clock::now() - *last_health > kLocalizationFreshness) {
|
||||
return "LIO 有效性心跳缺失或过期";
|
||||
}
|
||||
if (!localization_valid) {
|
||||
return "LIO 有效性心跳为 false";
|
||||
}
|
||||
}
|
||||
const auto now = node->now();
|
||||
if (now.nanoseconds() <= 0) {
|
||||
return "未收到仿真时钟";
|
||||
}
|
||||
try {
|
||||
const auto transform = tf_buffer.lookupTransform("map", "base_link", rclcpp::Time(0));
|
||||
const rclcpp::Time stamp(transform.header.stamp, now.get_clock_type());
|
||||
if (stamp.nanoseconds() <= 0 ||
|
||||
(now - stamp).nanoseconds() >
|
||||
std::chrono::duration_cast<std::chrono::nanoseconds>(kLocalizationFreshness).count())
|
||||
{
|
||||
return "map → base_link TF 已过期";
|
||||
}
|
||||
} catch (const tf2::TransformException &) {
|
||||
return "map → base_link TF 不连通";
|
||||
}
|
||||
return nullptr;
|
||||
};
|
||||
map_executor.add_node(node);
|
||||
const auto localization_deadline = std::chrono::steady_clock::now() + 5s;
|
||||
const char * reason = nullptr;
|
||||
do {
|
||||
map_executor.spin_some();
|
||||
reason = localization_error();
|
||||
if (reason == nullptr) {
|
||||
break;
|
||||
}
|
||||
std::this_thread::sleep_for(20ms);
|
||||
} while (rclcpp::ok() && std::chrono::steady_clock::now() < localization_deadline);
|
||||
map_executor.remove_node(node);
|
||||
if (reason != nullptr) {
|
||||
std::printf("❌ 定位不可用:%s。未发送导航目标。\n", reason);
|
||||
rclcpp::shutdown();
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
NavigateToPose::Goal goal;
|
||||
goal.pose.header.frame_id = "map";
|
||||
goal.pose.header.stamp = node->now();
|
||||
@@ -288,7 +347,7 @@ int main(int argc, char * argv[])
|
||||
if (rclcpp::spin_until_future_complete(node, goal_future, 15s) !=
|
||||
rclcpp::FutureReturnCode::SUCCESS)
|
||||
{
|
||||
std::printf("❌ 目标被拒绝(耗时 %.1f s)\n", 0.0);
|
||||
std::printf("❌ 等待 Nav2 确认目标超时或中断\n");
|
||||
rclcpp::shutdown();
|
||||
return 1;
|
||||
}
|
||||
@@ -313,19 +372,34 @@ int main(int argc, char * argv[])
|
||||
const double elapsed =
|
||||
std::chrono::duration<double>(std::chrono::steady_clock::now() - t_goal).count();
|
||||
|
||||
int exit_code = 1;
|
||||
if (result_future.valid() && result_future.wait_for(0s) == std::future_status::ready) {
|
||||
const auto code = result_future.get().code;
|
||||
const auto result = result_future.get();
|
||||
const auto code = result.code;
|
||||
const char * name = "❌ 未知状态";
|
||||
if (code == rclcpp_action::ResultCode::SUCCEEDED) {
|
||||
name = "✅ SUCCEEDED";
|
||||
exit_code = 0;
|
||||
} else if (code == rclcpp_action::ResultCode::CANCELED) {
|
||||
name = "❌ CANCELED";
|
||||
} else if (code == rclcpp_action::ResultCode::ABORTED) {
|
||||
name = "❌ ABORTED";
|
||||
}
|
||||
std::printf("结果: %s 导航耗时 %.1f s\n", name, elapsed);
|
||||
if (result.result) {
|
||||
std::printf("Nav2 error_code=%u error_msg=%s\n",
|
||||
static_cast<unsigned>(result.result->error_code), result.result->error_msg.c_str());
|
||||
}
|
||||
} else {
|
||||
std::printf("超时未完成(180 s,已等待 %.0f s)\n", elapsed);
|
||||
std::printf("超时或中断(上限 180 s,已等待 %.0f s)\n", elapsed);
|
||||
if (rclcpp::ok()) {
|
||||
try {
|
||||
auto canceled = client->async_cancel_goal(handle);
|
||||
(void)rclcpp::spin_until_future_complete(node, canceled, 1s);
|
||||
} catch (const rclcpp_action::exceptions::UnknownGoalHandleError &) {
|
||||
// The server can finish the goal while the timeout is being handled.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -340,5 +414,5 @@ int main(int argc, char * argv[])
|
||||
}
|
||||
|
||||
rclcpp::shutdown();
|
||||
return 0;
|
||||
return exit_code;
|
||||
}
|
||||
@@ -39,6 +39,8 @@
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
#include <algorithm>
|
||||
#include <stdexcept>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
@@ -87,6 +89,19 @@ public:
|
||||
declare_parameter<double>("max_range", params.max_range));
|
||||
|
||||
core_ = std::make_unique<sentry_nav::SelfFilterCore>(params);
|
||||
const auto lio_topic = declare_parameter<std::string>("lio_output_topic", "/scan/points_lio");
|
||||
if (!lio_topic.empty()) {
|
||||
if (lio_topic == output_topic_) {
|
||||
throw std::invalid_argument("lio_output_topic must differ from the obstacle cloud topic");
|
||||
}
|
||||
auto lio_params = params;
|
||||
lio_params.keep_min_z = static_cast<float>(declare_parameter<double>("lio_keep_min_z", -0.25));
|
||||
// Keep the floor outside the body footprint without admitting underbody returns.
|
||||
lio_params.box_min_z = std::min(lio_params.box_min_z, lio_params.keep_min_z);
|
||||
lio_core_ = std::make_unique<sentry_nav::SelfFilterCore>(lio_params);
|
||||
lio_pub_ = create_publisher<sensor_msgs::msg::PointCloud2>(lio_topic, rclcpp::QoS(5).reliable());
|
||||
RCLCPP_INFO(get_logger(), "LIO cloud: %s (keep_min_z=%.2f)", lio_topic.c_str(), lio_params.keep_min_z);
|
||||
}
|
||||
|
||||
tf_buffer_ = std::make_unique<tf2_ros::Buffer>(get_clock());
|
||||
tf_listener_ = std::make_shared<tf2_ros::TransformListener>(*tf_buffer_);
|
||||
@@ -149,10 +164,18 @@ private:
|
||||
filtered.reserve(raw.size());
|
||||
|
||||
// 只做遍历和搬运,判定逻辑全在 core_ 里(可单测)。
|
||||
const bool publish_lio = lio_pub_ && lio_pub_->get_subscription_count() > 0;
|
||||
pcl::PointCloud<pcl::PointXYZ> lio_cloud;
|
||||
if (publish_lio) {
|
||||
lio_cloud.reserve(raw.size());
|
||||
}
|
||||
for (const auto & pt : raw) {
|
||||
if (core_->Keep(pt.x, pt.y, pt.z)) {
|
||||
filtered.push_back(pt);
|
||||
}
|
||||
if (publish_lio && lio_core_->Keep(pt.x, pt.y, pt.z)) {
|
||||
lio_cloud.push_back(pt);
|
||||
}
|
||||
}
|
||||
|
||||
// 统计保留率,调参时有用(DEBUG 级别,默认不刷屏)
|
||||
@@ -166,16 +189,27 @@ private:
|
||||
static_cast<unsigned long long>(total_out_),
|
||||
static_cast<unsigned long long>(total_in_));
|
||||
|
||||
sensor_msgs::msg::PointCloud2 out;
|
||||
pcl::toROSMsg(filtered, out);
|
||||
out.header.stamp = msg->header.stamp;
|
||||
out.header.frame_id = target_frame_;
|
||||
pub_->publish(out);
|
||||
PublishCloud(filtered, msg->header.stamp, *pub_);
|
||||
if (publish_lio) {
|
||||
PublishCloud(lio_cloud, msg->header.stamp, *lio_pub_);
|
||||
}
|
||||
|
||||
// 同一份过滤结果再投影成 2D 激光:不新增订阅/进程,数据一致。
|
||||
PublishScan(filtered, msg->header.stamp);
|
||||
}
|
||||
|
||||
void PublishCloud(
|
||||
const pcl::PointCloud<pcl::PointXYZ> & cloud,
|
||||
const builtin_interfaces::msg::Time & stamp,
|
||||
rclcpp::Publisher<sensor_msgs::msg::PointCloud2> & publisher)
|
||||
{
|
||||
sensor_msgs::msg::PointCloud2 out;
|
||||
pcl::toROSMsg(cloud, out);
|
||||
out.header.stamp = stamp;
|
||||
out.header.frame_id = target_frame_;
|
||||
publisher.publish(out);
|
||||
}
|
||||
|
||||
// 把过滤后的点云(已在 base_link 系)投影成 2D 激光:
|
||||
// 每个方位格取该格内最小水平距离,z 只取车体碰撞带 [scan_height_min, scan_height_max]。
|
||||
// 这样投影结果与地图的「体积投影」在同一高度带,避免 AMCL 因高度失配把粒子整团迁走。
|
||||
@@ -223,6 +257,7 @@ private:
|
||||
std::string scan_topic_;
|
||||
|
||||
std::unique_ptr<sentry_nav::SelfFilterCore> core_;
|
||||
std::unique_ptr<sentry_nav::SelfFilterCore> lio_core_;
|
||||
|
||||
std::uint64_t total_in_{0};
|
||||
std::uint64_t total_out_{0};
|
||||
@@ -236,6 +271,7 @@ private:
|
||||
std::unique_ptr<tf2_ros::Buffer> tf_buffer_;
|
||||
std::shared_ptr<tf2_ros::TransformListener> tf_listener_;
|
||||
rclcpp::Publisher<sensor_msgs::msg::PointCloud2>::SharedPtr pub_;
|
||||
rclcpp::Publisher<sensor_msgs::msg::PointCloud2>::SharedPtr lio_pub_;
|
||||
rclcpp::Publisher<sensor_msgs::msg::LaserScan>::SharedPtr scan_pub_;
|
||||
rclcpp::Subscription<sensor_msgs::msg::PointCloud2>::SharedPtr sub_;
|
||||
};
|
||||
|
||||
@@ -15,6 +15,7 @@ local ros_direct_packages = {
|
||||
"nav_msgs",
|
||||
"geometry_msgs",
|
||||
"sensor_msgs",
|
||||
"std_msgs",
|
||||
"tf2_ros",
|
||||
"tf2_sensor_msgs",
|
||||
"pcl_conversions",
|
||||
@@ -128,7 +129,7 @@ local function ros_common()
|
||||
|
||||
local script = path.join(
|
||||
target:scriptdir(),
|
||||
"../../tools/resolve_ros_includes.py"
|
||||
"../../tools/_internal/resolve_ros_includes.py"
|
||||
)
|
||||
|
||||
if not os.isfile(script) then
|
||||
|
||||
@@ -33,14 +33,14 @@ ros2 launch src/sentry_sim/launch/sentry_arena.launch.py --show-args # 看
|
||||
| `map` | 迁移包里的 `rmul_2027.yaml` | Nav2 用的栅格图 |
|
||||
| `field_root` | 仓库内 `field/RMUL2027_map_transfer_20261016_STEP_R1` | 迁移包目录(找不到才退回 `~/Gazebo_projects/` 下的旧路径) |
|
||||
|
||||
环境变量(`GZ_PARTITION` / `ROS_DOMAIN_ID` / `SENTRY_FIELD_ROOT` / `SENTRY_MAP_YAML`)
|
||||
会被继承,行为和 `sentry_up.sh` 一致。详见 `../scripts/README.md`。
|
||||
`map:=` 和 `field_root:=` 优先于对应的环境变量。未提供地图时,从实际选定的场地目录探测。
|
||||
两个启动入口使用同一套环境探测规则,`--show-args` 可独立查看参数。详见[环境变量](../../../docs/操作手册.md#6-环境变量)。
|
||||
|
||||
## 和 `scripts/sentry_up.sh` 的取舍
|
||||
|
||||
| | `sentry_up.sh` | 本 launch 文件 |
|
||||
|---|---|---|
|
||||
| 依赖 | 只要 bash | 要 `ros2 launch`(launch / launch_ros) |
|
||||
| 依赖 | Bash、Python 3 和 ROS | `ros2 launch`(launch / launch_ros) |
|
||||
| 参数可见性 | 看脚本 | `--show-args` 全列出来 |
|
||||
| 进程管理 | `trap` 收尾 | launch 统一收尾、能看进程树 |
|
||||
| 被别的 launch include | ❌ | ✅ |
|
||||
|
||||
@@ -53,12 +53,14 @@ from launch.actions import (
|
||||
LogInfo,
|
||||
OpaqueFunction,
|
||||
SetEnvironmentVariable,
|
||||
SetLaunchConfiguration,
|
||||
)
|
||||
from launch.conditions import IfCondition
|
||||
from launch.event_handlers import OnProcessExit
|
||||
from launch.events import Shutdown
|
||||
from launch.substitutions import (LaunchConfiguration,
|
||||
PathJoinSubstitution, PythonExpression)
|
||||
from launch.substitutions import (
|
||||
EqualsSubstitution, IfElseSubstitution, LaunchConfiguration, PathJoinSubstitution, PythonExpression,
|
||||
)
|
||||
from launch_ros.actions import Node
|
||||
from launch_ros.parameter_descriptions import ParameterValue
|
||||
|
||||
@@ -68,29 +70,61 @@ from launch_ros.parameter_descriptions import ParameterValue
|
||||
PKG_SHARE = Path(__file__).resolve().parents[1] # src/sentry_sim
|
||||
WS = Path(__file__).resolve().parents[3] # 仓库根
|
||||
SCRIPTS = PKG_SHARE / 'scripts'
|
||||
TOOLS_DIR = WS / 'tools'
|
||||
INTERNAL_TOOLS = TOOLS_DIR / '_internal'
|
||||
|
||||
# 可移植探测:xmake 产物目录 / 场地包 / 地图 / gz 版本,一个都不写死。
|
||||
# 规则与 `scripts/env_common.sh` 完全一致(同样支持 SENTRY_BIN_DIR、
|
||||
# SENTRY_FIELD_ROOT、SENTRY_MAP_YAML、GZ_BIN、GZ_FORCE_VERSION 覆盖)。
|
||||
# `tools/` 不是 Python 包(本工程不用 ament),所以直接把目录塞进 sys.path。
|
||||
if str(WS / 'tools') not in sys.path:
|
||||
sys.path.insert(0, str(WS / 'tools'))
|
||||
# 从仓库源码加载工具模块。
|
||||
if str(TOOLS_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(TOOLS_DIR))
|
||||
import project_env # noqa: E402 (必须在 sys.path 调整之后导入)
|
||||
from dds_environment import defaults as dds_defaults # noqa: E402
|
||||
from _internal.dds_environment import defaults as dds_defaults # noqa: E402
|
||||
|
||||
BIN_DIR = project_env.find_bin_dir(WS)
|
||||
GZ_VERSION_ARGS = project_env.gz_version_args()
|
||||
BIN_DIR = LaunchConfiguration('_sentry_bin_dir')
|
||||
GZ_MAJOR_VERSION = LaunchConfiguration('_sentry_gz_major_version')
|
||||
|
||||
_FIELD_ROOT = project_env.find_field_root(WS)
|
||||
if _FIELD_ROOT is None:
|
||||
raise RuntimeError(
|
||||
'找不到场地迁移包。设 SENTRY_FIELD_ROOT=<含 src/guodong_sentry_sim 的目录>。')
|
||||
DEFAULT_FIELD_ROOT = str(_FIELD_ROOT)
|
||||
|
||||
_MAP_YAML = project_env.find_map_yaml(_FIELD_ROOT)
|
||||
if _MAP_YAML is None:
|
||||
raise RuntimeError(f'{_FIELD_ROOT} 下找不到任何栅格图 yaml。设 SENTRY_MAP_YAML=<路径>。')
|
||||
DEFAULT_MAP_YAML = str(_MAP_YAML)
|
||||
def _resolve_environment(context):
|
||||
field_root = project_env.find_field_root(
|
||||
WS, explicit=LaunchConfiguration('field_root').perform(context))
|
||||
map_yaml = project_env.find_map_yaml(
|
||||
field_root, explicit=LaunchConfiguration('map').perform(context))
|
||||
bin_dir = project_env.find_bin_dir(WS)
|
||||
nodes = ['odom_tf', 'cmd_vel_relay', 'self_filter']
|
||||
if LaunchConfiguration('localization').perform(context) == 'lio':
|
||||
nodes.append('field_localization_node')
|
||||
for name in nodes:
|
||||
project_env.require_executable(bin_dir / name, name)
|
||||
gz = project_env.find_gz_bin()
|
||||
versions = project_env.gz_version_args(gz)
|
||||
return [
|
||||
SetLaunchConfiguration('field_root', str(field_root)),
|
||||
SetLaunchConfiguration('map', str(map_yaml)),
|
||||
SetLaunchConfiguration('_sentry_bin_dir', str(bin_dir)),
|
||||
SetEnvironmentVariable('GZ_BIN', str(gz)),
|
||||
SetLaunchConfiguration('_sentry_gz_major_version', versions[1] if versions else ''),
|
||||
]
|
||||
|
||||
|
||||
def _start_gazebo(context):
|
||||
headless = LaunchConfiguration('headless').perform(context).lower() in ('true', '1')
|
||||
# Keep -r in both modes so that the world starts unpaused.
|
||||
args = ['-s', '-r'] if headless else ['-r']
|
||||
if major := GZ_MAJOR_VERSION.perform(context):
|
||||
args.extend(['--force-version', major])
|
||||
world_path = PathJoinSubstitution([str(PKG_SHARE / 'worlds'), LaunchConfiguration('world')])
|
||||
return [ExecuteProcess(
|
||||
cmd=[str(SCRIPTS / 'run_gz.sh'), 'sim', *args, world_path],
|
||||
name='gazebo', output='screen',
|
||||
)]
|
||||
|
||||
|
||||
def _on_bridge_exit(event, context):
|
||||
if event.returncode != 0 and not context.is_shutdown:
|
||||
raise RuntimeError('Gazebo 桥启动或运行失败,请检查 /clock 与 ros_gz_bridge 日志。')
|
||||
return []
|
||||
|
||||
|
||||
def _robot_description():
|
||||
@@ -126,12 +160,15 @@ def _validate_lio(context):
|
||||
path = Path(LaunchConfiguration('lio_map').perform(context))
|
||||
if mode == 'localization' and not path.is_file():
|
||||
raise RuntimeError(f'Missing LIO map: {path}; first select lio_mode:=mapping')
|
||||
if mode == 'mapping':
|
||||
export = Path(LaunchConfiguration('lio_export_map').perform(context))
|
||||
export.parent.mkdir(parents=True, exist_ok=True)
|
||||
return []
|
||||
|
||||
|
||||
def _preflight_nav2(context):
|
||||
if LaunchConfiguration('nav2').perform(context).lower() in ('true', '1'):
|
||||
subprocess.run(['python3', str(WS / 'tools' / 'nav2_startup.py'), '--preflight'],
|
||||
subprocess.run(['python3', str(INTERNAL_TOOLS / 'nav2_startup.py'), '--preflight'],
|
||||
env=dict(context.environment), check=True)
|
||||
return []
|
||||
|
||||
@@ -141,7 +178,7 @@ def _start_velocity_relay(context):
|
||||
localization = LaunchConfiguration('localization').perform(context)
|
||||
input_topic = '/cmd_vel' if navigation else context.environment.get('MANUAL_CMD_VEL_TOPIC', '/cmd_vel')
|
||||
return [ExecuteProcess(
|
||||
cmd=[str(BIN_DIR / 'cmd_vel_relay'),
|
||||
cmd=[PathJoinSubstitution([BIN_DIR, 'cmd_vel_relay']),
|
||||
'--ros-args', '-p', 'use_sim_time:=true',
|
||||
'-p', f'navigation_mode:={str(navigation).lower()}',
|
||||
'-p', f'require_localization_health:={str(localization == "lio").lower()}',
|
||||
@@ -154,31 +191,37 @@ def generate_launch_description():
|
||||
headless = LaunchConfiguration('headless')
|
||||
nav2 = LaunchConfiguration('nav2')
|
||||
rviz = LaunchConfiguration('rviz')
|
||||
world = LaunchConfiguration('world')
|
||||
map_yaml = LaunchConfiguration('map')
|
||||
localization = LaunchConfiguration('localization')
|
||||
lio_mode = LaunchConfiguration('lio_mode')
|
||||
lio_map = LaunchConfiguration('lio_map')
|
||||
lio_export = LaunchConfiguration('lio_export_map')
|
||||
lio_default_map = IfElseSubstitution(
|
||||
EqualsSubstitution(lio_mode, 'mapping'),
|
||||
if_value=str(WS / 'generated' / 'field_mapping.flmap'),
|
||||
else_value=str(PKG_SHARE / 'maps' / 'field_full.flmap'),
|
||||
)
|
||||
|
||||
# 布尔参数统一用 PythonExpression 判,避免 launch 把 "false" 当真值
|
||||
is_headless = PythonExpression(["'", headless, "'.lower() in ('true', '1')"])
|
||||
is_gui = PythonExpression(["'", headless, "'.lower() not in ('true', '1')"])
|
||||
nav2_on = PythonExpression(["'", nav2, "'.lower() in ('true', '1')"])
|
||||
rviz_on = PythonExpression([
|
||||
"'", rviz, "'.lower() in ('true', '1') and '",
|
||||
headless, "'.lower() not in ('true', '1')"])
|
||||
|
||||
robot_description = _robot_description()
|
||||
bridge = ExecuteProcess(
|
||||
cmd=[str(SCRIPTS / 'bridge_after_gz.sh')],
|
||||
name='ros_gz_bridge', output='screen',
|
||||
)
|
||||
|
||||
navigation_ready = ExecuteProcess(
|
||||
cmd=['python3', str(WS / 'tools' / 'wait_navigation_ready.py')],
|
||||
cmd=['python3', str(INTERNAL_TOOLS / 'wait_navigation_ready.py')],
|
||||
name='wait_navigation_ready', output='screen', condition=IfCondition(nav2_on),
|
||||
)
|
||||
# Use the same process boundary and options as the shell entry point.
|
||||
# The nested include path reproduced a Wait action discovery timeout on this setup.
|
||||
navigation = ExecuteProcess(
|
||||
cmd=['python3', str(WS / 'tools' / 'run_nav2.py'),
|
||||
cmd=['python3', str(INTERNAL_TOOLS / 'run_nav2.py'),
|
||||
'--timeout', os.environ.get('SENTRY_NAV2_TIMEOUT', '120'), '--',
|
||||
['map:=', map_yaml], 'use_sim_time:=true', 'autostart:=False',
|
||||
['params_file:=', str(PKG_SHARE / 'config' / 'nav2_params.yaml')],
|
||||
@@ -192,8 +235,13 @@ def generate_launch_description():
|
||||
actions = [
|
||||
DeclareLaunchArgument('localization', default_value='lio', choices=['lio', 'amcl']),
|
||||
DeclareLaunchArgument('lio_mode', default_value='localization', choices=['mapping', 'localization']),
|
||||
DeclareLaunchArgument('lio_map', default_value=str(WS / 'generated' / 'field.flmap')),
|
||||
DeclareLaunchArgument('lio_export_map', default_value=lio_map),
|
||||
DeclareLaunchArgument(
|
||||
'lio_map', default_value=os.environ.get('LIO_MAP') or lio_default_map,
|
||||
description='Full-field localization map or generated/field_mapping.flmap in mapping mode',
|
||||
),
|
||||
DeclareLaunchArgument('lio_export_map', default_value=os.environ.get('LIO_EXPORT_MAP') or lio_map),
|
||||
DeclareLaunchArgument('lio_point_cloud_topic',
|
||||
default_value=os.environ.get('LIO_POINT_CLOUD_TOPIC') or '/scan/points_lio'),
|
||||
DeclareLaunchArgument('lio_initial_x', default_value='-5.0'),
|
||||
DeclareLaunchArgument('lio_initial_y', default_value='3.0'),
|
||||
DeclareLaunchArgument('lio_initial_z', default_value='0.0'),
|
||||
@@ -211,18 +259,19 @@ def generate_launch_description():
|
||||
'world', default_value='sentry_arena.sdf',
|
||||
description='worlds/ 下的世界文件名'),
|
||||
DeclareLaunchArgument(
|
||||
'map', default_value=DEFAULT_MAP_YAML,
|
||||
description='Nav2 用的栅格图 yaml'),
|
||||
'map', default_value='',
|
||||
description='Nav2 栅格图 YAML,留空则从环境或场地包探测'),
|
||||
DeclareLaunchArgument(
|
||||
'field_root', default_value=DEFAULT_FIELD_ROOT,
|
||||
description='迁移包(guodong_sentry_sim)所在目录'),
|
||||
'field_root', default_value='',
|
||||
description='场地包目录,留空则从环境或仓库探测'),
|
||||
OpaqueFunction(function=_resolve_environment),
|
||||
|
||||
# ---------------- 环境变量 ----------------
|
||||
SetEnvironmentVariable('FASTDDS_BUILTIN_TRANSPORTS',
|
||||
dds_defaults(os.environ)['FASTDDS_BUILTIN_TRANSPORTS']),
|
||||
SetEnvironmentVariable('GZ_SIM_RESOURCE_PATH', _gz_resource_path()),
|
||||
SetEnvironmentVariable(
|
||||
'GZ_PARTITION', os.environ.get('GZ_PARTITION', 'sentry')),
|
||||
'GZ_PARTITION', os.environ.get('GZ_PARTITION') or 'sentry'),
|
||||
SetEnvironmentVariable(
|
||||
'ROS_DOMAIN_ID', dds_defaults(os.environ)['ROS_DOMAIN_ID']),
|
||||
# URDF 的网格路径靠它解析;tools/check_stack.py 也读它
|
||||
@@ -230,41 +279,14 @@ def generate_launch_description():
|
||||
OpaqueFunction(function=_preflight_nav2),
|
||||
|
||||
# ---------------- 1. Gazebo ----------------
|
||||
# 用 run_gz.sh 包一层:它会清掉 LD_LIBRARY_PATH,
|
||||
# 否则 source 过 ROS 之后连系统版 gz 也会加载 vendor 库(缺 cpu-lidar 插件)
|
||||
# ⚠️ cmd 列表里的每个元素是**独立 argv**,不会自动拼接。
|
||||
# world 是 LaunchConfiguration,所以必须用 PathJoinSubstitution
|
||||
# 合成成一个参数,否则 gz 会收到三个散参数
|
||||
# (报 "The following arguments were not expected: xxx.sdf /")。
|
||||
ExecuteProcess(
|
||||
cmd=[str(SCRIPTS / 'run_gz.sh'), 'sim', '-r',
|
||||
*GZ_VERSION_ARGS,
|
||||
PathJoinSubstitution([str(PKG_SHARE / 'worlds'), world])],
|
||||
name='gazebo',
|
||||
output='screen',
|
||||
condition=IfCondition(is_gui),
|
||||
),
|
||||
# ⚠️ headless 也必须带 -r(启动即运行)。
|
||||
# 少了 -r 的话 gazebo 以**暂停**状态启动:物理引擎不步进 →
|
||||
# MecanumDrive 不发 /odom、传感器不出数据,但 /clock 照常发布,
|
||||
# 表面上一切正常,实际整条数据链是死的。
|
||||
ExecuteProcess(
|
||||
cmd=[str(SCRIPTS / 'run_gz.sh'), 'sim', '-s', '-r',
|
||||
*GZ_VERSION_ARGS,
|
||||
PathJoinSubstitution([str(PKG_SHARE / 'worlds'), world])],
|
||||
name='gazebo',
|
||||
output='screen',
|
||||
condition=IfCondition(is_headless),
|
||||
),
|
||||
OpaqueFunction(function=_start_gazebo),
|
||||
|
||||
# ---------------- 2. ros_gz 桥 ----------------
|
||||
# bridge_after_gz.sh 自己轮询 /clock 再起桥:
|
||||
# gz-transport 的发现不回补,桥先于话题存在就订阅会一直收不到数据
|
||||
ExecuteProcess(
|
||||
cmd=[str(SCRIPTS / 'bridge_after_gz.sh')],
|
||||
name='ros_gz_bridge',
|
||||
output='screen',
|
||||
),
|
||||
# 等到 /clock 出现再加载桥,否则 gz-transport 可能漏掉话题。
|
||||
RegisterEventHandler(OnProcessExit(
|
||||
target_action=bridge, on_exit=_on_bridge_exit,
|
||||
)),
|
||||
bridge,
|
||||
|
||||
# ---------------- 3. TF 树 ----------------
|
||||
Node(
|
||||
@@ -286,7 +308,7 @@ def generate_launch_description():
|
||||
# 如果写成嵌套列表 ['-p', 'odom_scale:=', v],会被拼成 "-podom_scale:=1.15"(没空格),
|
||||
# rclpy 的参数解析会直接报错。
|
||||
ExecuteProcess(
|
||||
cmd=[str(BIN_DIR / 'odom_tf'), '--ros-args',
|
||||
cmd=[PathJoinSubstitution([BIN_DIR, 'odom_tf']), '--ros-args',
|
||||
'-p', 'use_sim_time:=true',
|
||||
'-p', 'odom_scale:=' + os.environ.get('SENTRY_ODOM_SCALE', '1.0')],
|
||||
name='odom_tf',
|
||||
@@ -300,15 +322,16 @@ def generate_launch_description():
|
||||
# ---------------- 6. 点云自滤 ----------------
|
||||
# 本工程没有 ament 注册,不能 ros2 run,直接跑 xmake 产物
|
||||
ExecuteProcess(
|
||||
cmd=[str(BIN_DIR / 'self_filter'),
|
||||
cmd=[PathJoinSubstitution([BIN_DIR, 'self_filter']),
|
||||
'--ros-args', '-p', 'use_sim_time:=true', '-p', 'reliable_clouds:=true'],
|
||||
name='self_filter',
|
||||
output='screen',
|
||||
),
|
||||
|
||||
ExecuteProcess(
|
||||
cmd=[str(BIN_DIR / 'field_localization_node'), '--ros-args',
|
||||
'-p', 'use_sim_time:=true', '-p', 'reliable_clouds:=true', '-p', 'point_cloud_topic:=/scan/points_filtered',
|
||||
cmd=[PathJoinSubstitution([BIN_DIR, 'field_localization_node']), '--ros-args',
|
||||
'-p', 'use_sim_time:=true', '-p', 'reliable_clouds:=true',
|
||||
'-p', ['point_cloud_topic:=', LaunchConfiguration('lio_point_cloud_topic')],
|
||||
'-p', ['mode:=', lio_mode], '-p', ['map_path:=', lio_map],
|
||||
'-p', ['export_map_path:=', lio_export], '-p', 'publish_map_to_odom:=true',
|
||||
'-p', "diagnostics_path:='" + os.environ.get('LIO_TRACE_PATH', '') + "'",
|
||||
|
||||
Binary file not shown.
@@ -37,20 +37,10 @@
|
||||
| `SENTRY_FIELD_ROOT` | 仓库内 `field/RMUL2027_map_transfer_20261016_STEP_R1` | 场地包位置。**优先用仓库自带的**,找不到才退回 `~/Gazebo_projects/` 下的旧路径 |
|
||||
| `SENTRY_MAP_YAML` | 上面路径下的 `maps/rmul_2027/rmul_2027.yaml` | 想换地图时直接指这个 |
|
||||
| `SENTRY_SIM_SHARE` | 仓库内 `src/sentry_sim` | 数据包位置。设了就以它为准;同时会导出给 `xacro`,URDF 里的网格路径靠它解析 |
|
||||
| `NAV_BIN_DIR` | `<仓库根>/build/bin` | xmake 产物目录。想用别处的二进制时覆盖它 |
|
||||
| `SENTRY_BIN_DIR` | `<仓库根>/build/bin` | xmake 产物目录,旧变量 `NAV_BIN_DIR` 仍可用 |
|
||||
| `BRIDGE_WAIT_TIMEOUT` | `120` | 等待 Gazebo `/clock` 的秒数,两个入口共用 |
|
||||
|
||||
## `FIELD_ROOT` 的解析逻辑(容易踩的一点)
|
||||
|
||||
```bash
|
||||
FIELD_DEFAULT="$HOME/Gazebo_projects/RMUL2027_map_transfer_20261016_STEP_R1"
|
||||
if [ -d "$WS/field/RMUL2027_map_transfer_20261016_STEP_R1" ]; then
|
||||
FIELD_DEFAULT="$WS/field/RMUL2027_map_transfer_20261016_STEP_R1"
|
||||
fi
|
||||
FIELD_ROOT="${SENTRY_FIELD_ROOT:-$FIELD_DEFAULT}"
|
||||
```
|
||||
|
||||
> **不能写成 `[ -d ... ] && FIELD_DEFAULT=...`** —— 脚本第 10 行有 `set -e`,
|
||||
> 目录不存在时那种写法会让整个脚本静默退出(踩过)。
|
||||
场地、地图、构建目录和 Gazebo 的选择顺序见[操作手册](../../../docs/操作手册.md#6-环境变量)。
|
||||
|
||||
## 退出时 Gazebo 可能残留
|
||||
|
||||
|
||||
@@ -5,18 +5,14 @@
|
||||
# (gz-transport 的发现不回补)。先轮询 /clock,再 exec 桥。
|
||||
set -e
|
||||
|
||||
TIMEOUT_SECONDS="${BRIDGE_WAIT_TIMEOUT:-180}"
|
||||
for _ in $(seq 1 "$((TIMEOUT_SECONDS / 2))"); do
|
||||
if gz topic -l 2>/dev/null | grep -qx '/clock'; then
|
||||
echo "[bridge_after_gz] Gazebo 已就绪,启动桥"
|
||||
break
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
SCRIPTS_DIR="$(cd -- "$(dirname -- "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)"
|
||||
# shellcheck source=./env_common.sh
|
||||
. "${SCRIPTS_DIR}/env_common.sh"
|
||||
|
||||
GZ=$(env_gz_bin)
|
||||
env_wait_gz_clock "$GZ"
|
||||
echo "[bridge_after_gz] Gazebo /clock 已就绪,启动桥"
|
||||
echo "[bridge_after_gz] GZ_PARTITION=${GZ_PARTITION:-<unset>} ROS_DOMAIN_ID=${ROS_DOMAIN_ID:-<unset>} RMW=${RMW_IMPLEMENTATION:-<unset>}"
|
||||
echo "[bridge_after_gz] LD_LIBRARY_PATH=${LD_LIBRARY_PATH:0:80}"
|
||||
echo "[bridge_after_gz] gz 话题数=$(gz topic -l 2>/dev/null | wc -l)"
|
||||
exec ros2 run ros_gz_bridge parameter_bridge \
|
||||
'/clock@rosgraph_msgs/msg/Clock[gz.msgs.Clock' \
|
||||
'/model/sentry/cmd_vel@geometry_msgs/msg/Twist]gz.msgs.Twist' \
|
||||
|
||||
@@ -1,263 +1,67 @@
|
||||
#!/usr/bin/env bash
|
||||
# 可移植的环境探测 —— 所有启动脚本共享这一份,别再各写一套。
|
||||
#
|
||||
# 设计原则:
|
||||
# ① **一切都能被环境变量覆盖**:探测只是给个合理默认值,不是唯一真相。
|
||||
# ② **探测失败要吵**:宁可启动时明确报错,也不要带着错路径跑到一半。
|
||||
# ③ **不写死发行版/版本/平台三元组**:换台机器、换个 ROS 版本、换个 Gazebo 大版本
|
||||
# 都不该需要改脚本。
|
||||
#
|
||||
# 覆盖用的环境变量:
|
||||
# ROS_SETUP 直接指定要 source 的 setup.bash 全路径
|
||||
# ROS_DISTRO ROS 发行版名(配合 /opt/ros/<名>/setup.bash)
|
||||
# SENTRY_BIN_DIR xmake 产物目录(默认识别 build/*/*/release)
|
||||
# GZ_BIN Gazebo 可执行文件(默认优先 /usr/bin/gz)
|
||||
# GZ_FORCE_VERSION gz --force-version 的值(默认自动取已安装主版本)
|
||||
# SENTRY_FIELD_ROOT 场地迁移包根目录
|
||||
# SENTRY_MAP_YAML 栅格图 yaml 全路径
|
||||
#
|
||||
# 用法(在脚本里):
|
||||
# WS="$(cd -- "$(dirname -- "$(readlink -f "${BASH_SOURCE[0]}")")/../.." && pwd)"
|
||||
# source "${WS}/src/sentry_sim/scripts/env_common.sh"
|
||||
#
|
||||
# 注意:本文件会被 `set -e` 的脚本 source,所以任何"可能失败"的命令都要兜住。
|
||||
# Share the Python environment probes while keeping ROS setup in the caller's shell.
|
||||
_SENTRY_PROJECT_ENV="$(cd -- "$(dirname -- "$(readlink -f "${BASH_SOURCE[0]}")")/../../.." && pwd)/tools/project_env.py"
|
||||
|
||||
_env_query() {
|
||||
# These functions can also be called from a sourced shell with unexported overrides.
|
||||
ROS_SETUP="${ROS_SETUP:-}" ROS_INSTALL_ROOT="${ROS_INSTALL_ROOT:-}" \
|
||||
ROS_DISTRO="${ROS_DISTRO:-}" AMENT_PREFIX_PATH="${AMENT_PREFIX_PATH:-}" \
|
||||
SENTRY_BIN_DIR="${SENTRY_BIN_DIR:-}" NAV_BIN_DIR="${NAV_BIN_DIR:-}" \
|
||||
SENTRY_FIELD_ROOT="${SENTRY_FIELD_ROOT:-}" SENTRY_MAP_YAML="${SENTRY_MAP_YAML:-}" \
|
||||
GZ_BIN="${GZ_BIN:-}" GZ_FORCE_VERSION="${GZ_FORCE_VERSION:-}" \
|
||||
GZ_PARTITION="${GZ_PARTITION:-}" BRIDGE_WAIT_TIMEOUT="${BRIDGE_WAIT_TIMEOUT:-}" \
|
||||
python3 "$_SENTRY_PROJECT_ENV" "$@"
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1. ROS 2 —— 找到并 source 一个能用的 setup.bash
|
||||
# ---------------------------------------------------------------------------
|
||||
# 为什么要探测:发行版名字(humble / jazzy / lyrical …)会变,
|
||||
# 写死 `/opt/ros/lyrical/setup.bash` 等于把工程锁死在一台机器上。
|
||||
env_source_ros() {
|
||||
# ① 已经 source 过就别再动 —— 重复 source 会把 PATH 越叠越长。
|
||||
if [ -n "${AMENT_PREFIX_PATH:-}" ] && command -v ros2 >/dev/null 2>&1; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
local cand=""
|
||||
|
||||
# ② 显式指定优先
|
||||
if [ -n "${ROS_SETUP:-}" ]; then
|
||||
if [ -f "$ROS_SETUP" ]; then
|
||||
cand="$ROS_SETUP"
|
||||
else
|
||||
echo "[env] ❌ ROS_SETUP 指向的文件不存在: $ROS_SETUP" >&2
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# ③ 自定义安装根(非 /opt/ros 的安装,比如源码编译)
|
||||
if [ -z "$cand" ] && [ -n "${ROS_INSTALL_ROOT:-}" ] \
|
||||
&& [ -f "${ROS_INSTALL_ROOT}/setup.bash" ]; then
|
||||
cand="${ROS_INSTALL_ROOT}/setup.bash"
|
||||
fi
|
||||
|
||||
# ④ 按发行版名找
|
||||
if [ -z "$cand" ] && [ -n "${ROS_DISTRO:-}" ] \
|
||||
&& [ -f "/opt/ros/${ROS_DISTRO}/setup.bash" ]; then
|
||||
cand="/opt/ros/${ROS_DISTRO}/setup.bash"
|
||||
fi
|
||||
|
||||
# ⑤ 在 /opt/ros 下扫,多个时取版本号最大的那个
|
||||
if [ -z "$cand" ]; then
|
||||
cand=$(ls -1d /opt/ros/*/setup.bash 2>/dev/null | sort -V | tail -1)
|
||||
fi
|
||||
|
||||
if [ -z "$cand" ] || [ ! -f "$cand" ]; then
|
||||
echo "[env] ❌ 找不到 ROS 2 安装(/opt/ros/*/setup.bash 全空)。" >&2
|
||||
echo "[env] 办法:先 source 你的 ROS 环境;或设 ROS_SETUP=<setup.bash 全路径>;" >&2
|
||||
echo "[env] 或设 ROS_DISTRO=<发行版名>;或设 ROS_INSTALL_ROOT=<安装前缀>。" >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
local n
|
||||
n=$(ls -1d /opt/ros/*/setup.bash 2>/dev/null | wc -l)
|
||||
if [ "$n" -gt 1 ] && [ -z "${ROS_SETUP:-}" ] && [ -z "${ROS_DISTRO:-}" ]; then
|
||||
echo "[env] ⚠️ 机器上装了 $n 个 ROS,自动选了版本号最大的:$cand" >&2
|
||||
echo "[env] 想用别的就设 ROS_DISTRO=<名字> 或 ROS_SETUP=<全路径>。" >&2
|
||||
fi
|
||||
|
||||
local setup
|
||||
setup=$(_env_query --ros-setup) || return
|
||||
if [ -n "$setup" ]; then
|
||||
# shellcheck disable=SC1090
|
||||
# shellcheck disable=SC1091
|
||||
. "$cand"
|
||||
echo "[env] ROS: ${cand}" >&2
|
||||
. "$setup" || return
|
||||
echo "[env] ROS: ${setup}" >&2
|
||||
fi
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2. Gazebo 可执行文件
|
||||
# ---------------------------------------------------------------------------
|
||||
# 为什么要挑:source 过 ROS 之后,PATH 上的 `gz` 是 gz_tools_vendor 里那个,
|
||||
# 它带着 vendor 的 RUNPATH,会去加载 gz_sim_vendor(缺 cpu-lidar 插件),
|
||||
# 导致雷达传感器创建失败。所以系统装的 /usr/bin/gz 优先。
|
||||
env_gz_bin() {
|
||||
if [ -n "${GZ_BIN:-}" ]; then
|
||||
if [ ! -x "$GZ_BIN" ]; then
|
||||
echo "[env] ❌ GZ_BIN 不可执行: $GZ_BIN" >&2
|
||||
return 1
|
||||
fi
|
||||
printf '%s\n' "$GZ_BIN"
|
||||
return 0
|
||||
fi
|
||||
|
||||
local c
|
||||
for c in /usr/bin/gz /usr/local/bin/gz /opt/gz/bin/gz; do
|
||||
if [ -x "$c" ]; then
|
||||
printf '%s\n' "$c"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
|
||||
c=$(command -v gz 2>/dev/null || true)
|
||||
if [ -n "$c" ]; then
|
||||
printf '%s\n' "$c"
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo "[env] ❌ 找不到 Gazebo 的 gz 可执行文件。设 GZ_BIN=<路径>。" >&2
|
||||
return 1
|
||||
_env_query --gz
|
||||
}
|
||||
|
||||
# 输出 `--force-version <主版本>`,取不到就输出空(表示不传这个参数)。
|
||||
# 为什么要自动取:写死 10 的话,装了 gz 11 就跑不起来。
|
||||
env_gz_version_args() {
|
||||
if [ -n "${GZ_FORCE_VERSION:-}" ]; then
|
||||
printf '%s\n%s\n' --force-version "$GZ_FORCE_VERSION"
|
||||
return 0
|
||||
fi
|
||||
|
||||
local gz v major
|
||||
gz=$(env_gz_bin 2>/dev/null || true)
|
||||
[ -z "$gz" ] && return 0
|
||||
|
||||
v=$("$gz" sim --version 2>/dev/null | head -1 || true)
|
||||
major=$(printf '%s' "$v" | grep -oE '^[0-9]+' || true)
|
||||
if [ -n "$major" ]; then
|
||||
printf '%s\n%s\n' --force-version "$major"
|
||||
fi
|
||||
return 0
|
||||
_env_query --gz-version-args-lines
|
||||
}
|
||||
|
||||
env_wait_gz_clock() {
|
||||
local gz="${1:?需要 Gazebo 可执行文件}"
|
||||
shift
|
||||
GZ_BIN="$gz" _env_query --wait-gz-clock "$@"
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3. xmake 产物目录
|
||||
# ---------------------------------------------------------------------------
|
||||
# **现行布局固定是 `build/bin/`** —— `src/sentry_nav/xmake.lua` 里每个 target 都
|
||||
# `set_targetdir("$(builddir)/bin")`,故意不用 xmake 默认的平台三元组,
|
||||
# 免得 `build/<平台>/<架构>/<模式>` 这种串被抄进文档后换机器就失效。
|
||||
#
|
||||
# 这里仍然按「找某个已知产物的实际位置」来定位(而不是直接拼 build/bin),
|
||||
# 这样老布局的 checkout 也还能用,而且编译模式换了也跟得上。
|
||||
env_bin_dir() {
|
||||
local ws="${1:?需要仓库根路径}"
|
||||
|
||||
# SENTRY_BIN_DIR 是统一名字;NAV_BIN_DIR 是历史名字,保留兼容。
|
||||
if [ -n "${SENTRY_BIN_DIR:-}" ]; then
|
||||
printf '%s\n' "$SENTRY_BIN_DIR"
|
||||
return 0
|
||||
fi
|
||||
if [ -n "${NAV_BIN_DIR:-}" ]; then
|
||||
printf '%s\n' "$NAV_BIN_DIR"
|
||||
return 0
|
||||
fi
|
||||
|
||||
# ① 现行布局优先
|
||||
local name p
|
||||
for name in self_filter nav_client patrol odom_tf field_localization_node; do
|
||||
if [ -x "${ws}/build/bin/${name}" ]; then
|
||||
printf '%s\n' "${ws}/build/bin"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
|
||||
# ② 老布局:去 build/ 里找产物实际所在的那一层
|
||||
for name in self_filter nav_client patrol odom_tf field_localization_node; do
|
||||
p=$(find "$ws/build" -maxdepth 4 -type f -name "$name" 2>/dev/null | head -1 || true)
|
||||
if [ -n "$p" ]; then
|
||||
dirname "$p"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
|
||||
# ③ 还没编译过:返回现行布局的位置
|
||||
printf '%s\n' "${ws}/build/bin"
|
||||
_env_query "${1:?需要仓库根路径}" --bin-dir
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 4. 场地迁移包
|
||||
# ---------------------------------------------------------------------------
|
||||
# 不写死 RMUL2027_map_transfer_20261016_STEP_R1:换一版迁移包(日期变了)就废。
|
||||
env_field_root() {
|
||||
local ws="${1:?需要仓库根路径}"
|
||||
|
||||
if [ -n "${SENTRY_FIELD_ROOT:-}" ]; then
|
||||
if [ ! -d "$SENTRY_FIELD_ROOT" ]; then
|
||||
echo "[env] ❌ SENTRY_FIELD_ROOT 不存在: $SENTRY_FIELD_ROOT" >&2
|
||||
return 1
|
||||
fi
|
||||
printf '%s\n' "$SENTRY_FIELD_ROOT"
|
||||
return 0
|
||||
fi
|
||||
|
||||
local d
|
||||
# ① 仓库自带的 field/ 下任意一个含 guodong_sentry_sim 的包
|
||||
for d in "$ws"/field/*/src/guodong_sentry_sim; do
|
||||
if [ -d "$d" ]; then
|
||||
dirname "$(dirname "$d")"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
|
||||
# ② 退回本机旧位置(任意 *_map_transfer_*)
|
||||
for d in "$HOME"/Gazebo_projects/*map_transfer*/src/guodong_sentry_sim; do
|
||||
if [ -d "$d" ]; then
|
||||
dirname "$(dirname "$d")"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
|
||||
echo "[env] ❌ 找不到场地迁移包。设 SENTRY_FIELD_ROOT=<含 src/guodong_sentry_sim 的目录>。" >&2
|
||||
return 1
|
||||
_env_query "${1:?需要仓库根路径}" --field
|
||||
}
|
||||
|
||||
# 输出栅格图 yaml 路径:优先 rmul_2027.yaml,否则取地图目录里第一个
|
||||
env_map_yaml() {
|
||||
local field_root="${1:?需要场地根路径}"
|
||||
|
||||
if [ -n "${SENTRY_MAP_YAML:-}" ]; then
|
||||
if [ ! -f "$SENTRY_MAP_YAML" ]; then
|
||||
echo "[env] ❌ SENTRY_MAP_YAML 不存在: $SENTRY_MAP_YAML" >&2
|
||||
return 1
|
||||
fi
|
||||
printf '%s\n' "$SENTRY_MAP_YAML"
|
||||
return 0
|
||||
fi
|
||||
|
||||
local m first=""
|
||||
for m in "$field_root"/src/guodong_sentry_sim/maps/*/*.yaml; do
|
||||
[ -f "$m" ] || continue
|
||||
case "$m" in
|
||||
*/rmul_2027.yaml) printf '%s\n' "$m"; return 0 ;;
|
||||
esac
|
||||
if [ -z "$first" ]; then first="$m"; fi
|
||||
done
|
||||
|
||||
if [ -n "$first" ]; then
|
||||
printf '%s\n' "$first"
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo "[env] ❌ $field_root 下找不到任何栅格图 yaml。设 SENTRY_MAP_YAML=<路径>。" >&2
|
||||
return 1
|
||||
_env_query --map --field-root "${1:?需要场地根路径}"
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 5. 一次性打印全部探测结果(调试用)
|
||||
# ---------------------------------------------------------------------------
|
||||
env_report() {
|
||||
local ws="${1:?需要仓库根路径}"
|
||||
echo " SENTRY_SIM_SHARE = ${SENTRY_SIM_SHARE:-<未设>}"
|
||||
echo " ROS = ${AMENT_PREFIX_PATH%%:*}"
|
||||
echo " ROS_DISTRO = ${ROS_DISTRO:-<未设>}"
|
||||
echo " BIN_DIR = $(env_bin_dir "$ws")"
|
||||
echo " GZ_BIN = $(env_gz_bin 2>/dev/null || echo '<找不到>')"
|
||||
echo " GZ 版本参数 = $(env_gz_version_args | tr '\n' ' ')"
|
||||
echo " FIELD_ROOT = $(env_field_root "$ws" 2>/dev/null || echo '<找不到>')"
|
||||
printf ' SENTRY_SIM_SHARE = %s\n' "${SENTRY_SIM_SHARE:-<未设>}"
|
||||
local ros="${AMENT_PREFIX_PATH:-}"
|
||||
printf ' ROS = %s\n' "${ros%%:*}"
|
||||
printf ' ROS_DISTRO = %s\n' "${ROS_DISTRO:-<未设>}"
|
||||
local bin gz versions field
|
||||
bin=$(env_bin_dir "$ws") || return
|
||||
gz=$(env_gz_bin) || return
|
||||
versions=$(GZ_BIN="$gz" env_gz_version_args) || return
|
||||
field=$(env_field_root "$ws") || return
|
||||
printf ' BIN_DIR = %s\n' "$bin"
|
||||
printf ' GZ_BIN = %s\n' "$gz"
|
||||
printf ' GZ 版本参数 = %s\n' "${versions//$'\n'/ }"
|
||||
printf ' FIELD_ROOT = %s\n' "$field"
|
||||
}
|
||||
@@ -15,6 +15,7 @@ set -e
|
||||
|
||||
SELF="$(readlink -f "${BASH_SOURCE[0]}")"
|
||||
WS="$(cd -- "$(dirname -- "$SELF")/../../.." && pwd)"
|
||||
INTERNAL_TOOLS="$WS/tools/_internal"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 日志默认自动落盘:不需要再记得 `| tee generated/up.log`
|
||||
@@ -41,8 +42,7 @@ export SENTRY_SIM_SHARE="$PKG_SHARE"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 环境探测:ROS 发行版 / 场地包 / 地图 / xmake 产物目录 / gz 版本,一个都不写死。
|
||||
# 全部逻辑在 env_common.sh 里,也能被别的脚本复用;每个值都可以用环境变量覆盖
|
||||
# (顶层注释里列了全部变量名)。
|
||||
# env_common.sh 调用 tools/project_env.py,和 Python launch 共用探测规则。
|
||||
# ---------------------------------------------------------------------------
|
||||
# shellcheck source=./env_common.sh
|
||||
. "${PKG_SHARE}/scripts/env_common.sh"
|
||||
@@ -50,22 +50,35 @@ export SENTRY_SIM_SHARE="$PKG_SHARE"
|
||||
# 注意顺序:先 source ROS,后面 `ros2 run` / `xacro` 才在 PATH 上。
|
||||
env_source_ros
|
||||
|
||||
FIELD_ROOT="$(env_field_root "$WS")" || exit 1
|
||||
MAP_YAML="$(env_map_yaml "$FIELD_ROOT")" || exit 1
|
||||
NAV_BIN_DIR="${NAV_BIN_DIR:-$(env_bin_dir "$WS")}"
|
||||
GZ_EXE="$(env_gz_bin)" || exit 1
|
||||
# `--force-version <主版本>`,没装多个版本时可以留空;GZ_FORCE_VERSION 可强制指定。
|
||||
mapfile -t GZ_VER_ARGS < <(env_gz_version_args)
|
||||
FIELD_ROOT="$(env_field_root "$WS")"
|
||||
MAP_YAML="$(env_map_yaml "$FIELD_ROOT")"
|
||||
NAV_BIN_DIR="$(env_bin_dir "$WS")"
|
||||
GZ_EXE="$(env_gz_bin)"
|
||||
GZ_VERSION_LINES="$(GZ_BIN="$GZ_EXE" env_gz_version_args)"
|
||||
GZ_VER_ARGS=()
|
||||
if [ -n "$GZ_VERSION_LINES" ]; then
|
||||
mapfile -t GZ_VER_ARGS <<< "$GZ_VERSION_LINES"
|
||||
fi
|
||||
|
||||
HEADLESS="${HEADLESS:-0}"
|
||||
NAV2="${NAV2:-1}"
|
||||
RVIZ="${RVIZ:-1}"
|
||||
|
||||
# Use exactly the same defaults as the Python launch entry point.
|
||||
eval "$(python3 "$WS/tools/dds_environment.py" --shell)"
|
||||
eval "$(python3 "$INTERNAL_TOOLS/dds_environment.py" --shell)"
|
||||
|
||||
LOCALIZATION="${LOCALIZATION:-lio}"
|
||||
LIO_MODE="${LIO_MODE:-localization}"
|
||||
if [ "$LIO_MODE" = mapping ]; then
|
||||
LIO_DEFAULT_MAP="$WS/generated/field_mapping.flmap"
|
||||
else
|
||||
LIO_DEFAULT_MAP="$PKG_SHARE/maps/field_full.flmap"
|
||||
fi
|
||||
LIO_MAP="${LIO_MAP:-$LIO_DEFAULT_MAP}"
|
||||
LIO_EXPORT_MAP="${LIO_EXPORT_MAP:-$LIO_MAP}"
|
||||
LIO_POINT_CLOUD_TOPIC="${LIO_POINT_CLOUD_TOPIC:-/scan/points_lio}"
|
||||
|
||||
# ---------- 试运行:只打印探测结果,不启动任何东西 ----------
|
||||
# 排查"路径不对/版本不对"时先跑这个,比启动一半再失败好定位:
|
||||
# SENTRY_DRY_RUN=1 scripts/sentry_up.sh
|
||||
if [ "${SENTRY_DRY_RUN:-0}" != "0" ]; then
|
||||
echo "[sentry_up] 试运行(不启动任何进程)"
|
||||
@@ -76,13 +89,16 @@ if [ "${SENTRY_DRY_RUN:-0}" != "0" ]; then
|
||||
echo " GZ 版本参数 = ${GZ_VER_ARGS[*]:-<无>}"
|
||||
echo " FIELD_ROOT = $FIELD_ROOT"
|
||||
echo " MAP_YAML = $MAP_YAML"
|
||||
echo " LIO_MAP = $LIO_MAP"
|
||||
echo " LIO_EXPORT_MAP = $LIO_EXPORT_MAP"
|
||||
echo " LIO_POINT_CLOUD_TOPIC = $LIO_POINT_CLOUD_TOPIC"
|
||||
echo " SENTRY_SIM_SHARE = $SENTRY_SIM_SHARE"
|
||||
echo " ROS_DISTRO = ${ROS_DISTRO:-<未设>}"
|
||||
echo " ROS 前缀 = ${AMENT_PREFIX_PATH%%:*}"
|
||||
echo " HEADLESS/NAV2/RVIZ = $HEADLESS/$NAV2/$RVIZ"
|
||||
echo " 可执行文件检查:"
|
||||
for _n in self_filter odom_tf cmd_vel_relay patrol; do
|
||||
if [ -x "${NAV_BIN_DIR}/${_n}" ]; then
|
||||
if [ -f "${NAV_BIN_DIR}/${_n}" ] && [ -x "${NAV_BIN_DIR}/${_n}" ]; then
|
||||
echo " ✅ ${_n}"
|
||||
else
|
||||
echo " ⚠️ ${_n} 不存在(用到它的部分会失败,先 xmake)"
|
||||
@@ -92,7 +108,7 @@ if [ "${SENTRY_DRY_RUN:-0}" != "0" ]; then
|
||||
fi
|
||||
|
||||
# UDPv4 is a transport default, not a guarantee that service discovery succeeds.
|
||||
python3 "$WS/tools/dds_environment.py"
|
||||
python3 "$INTERNAL_TOOLS/dds_environment.py"
|
||||
|
||||
# ROS 环境由上面的 env_source_ros 自动 source(逻辑在 env_common.sh),
|
||||
# 不再写死 /opt/ros/<发行版>/setup.bash —— 换发行版不用改脚本。
|
||||
@@ -100,7 +116,7 @@ python3 "$WS/tools/dds_environment.py"
|
||||
# 没有资源索引,所以不能 `ros2 run`,只能直接跑路径。
|
||||
nav_cmd() {
|
||||
local node="$1"
|
||||
if [ ! -x "${NAV_BIN_DIR}/${node}" ]; then
|
||||
if [ ! -f "${NAV_BIN_DIR}/${node}" ] || [ ! -x "${NAV_BIN_DIR}/${node}" ]; then
|
||||
echo "[sentry_up] ❌ 找不到可执行文件 ${NAV_BIN_DIR}/${node}" >&2
|
||||
echo "[sentry_up] 先编译:cd ${WS} && xmake" >&2
|
||||
echo "[sentry_up] 产物目录是自动探测的;不对就显式指定:" >&2
|
||||
@@ -110,20 +126,25 @@ nav_cmd() {
|
||||
echo "${NAV_BIN_DIR}/${node}"
|
||||
}
|
||||
|
||||
export GZ_SIM_RESOURCE_PATH="${PKG_SHARE}/models:${FIELD_ROOT}/src/guodong_sentry_sim/models"
|
||||
export GZ_SIM_RESOURCE_PATH="${PKG_SHARE}/models:${FIELD_ROOT}/src/guodong_sentry_sim/models${GZ_SIM_RESOURCE_PATH:+:$GZ_SIM_RESOURCE_PATH}"
|
||||
export GZ_PARTITION="${GZ_PARTITION:-sentry}"
|
||||
export ROS_DOMAIN_ID="${ROS_DOMAIN_ID:-0}" # 默认用 0,跟普通终端一致;要隔离时自己设
|
||||
|
||||
LOCALIZATION="${LOCALIZATION:-lio}"
|
||||
LIO_MODE="${LIO_MODE:-localization}"
|
||||
LIO_MAP="${LIO_MAP:-${WS}/generated/field.flmap}"
|
||||
LIO_EXPORT_MAP="${LIO_EXPORT_MAP:-${LIO_MAP}}"
|
||||
case "$LOCALIZATION" in lio) NAV2_LOCALIZATION=False ;; amcl) NAV2_LOCALIZATION=True ;; *) echo "LOCALIZATION must be lio or amcl" >&2; exit 1 ;; esac
|
||||
case "$LIO_MODE" in mapping|localization) ;; *) echo "LIO_MODE must be mapping or localization" >&2; exit 1 ;; esac
|
||||
if [ "$LOCALIZATION" = lio ] && [ "$LIO_MODE" = localization ] && [ ! -r "$LIO_MAP" ]; then
|
||||
if [ "$LOCALIZATION" = lio ] && [ "$LIO_MODE" = localization ] && { [ ! -f "$LIO_MAP" ] || [ ! -r "$LIO_MAP" ]; }; then
|
||||
echo "[sentry_up] missing LIO map: $LIO_MAP; first run LIO_MODE=mapping or choose LOCALIZATION=amcl" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ "$LOCALIZATION" = lio ] && [ "$LIO_MODE" = mapping ]; then
|
||||
mkdir -p "$(dirname -- "$LIO_EXPORT_MAP")"
|
||||
fi
|
||||
ODOM_TF_EXE="$(nav_cmd odom_tf)"
|
||||
CMD_VEL_RELAY_EXE="$(nav_cmd cmd_vel_relay)"
|
||||
SELF_FILTER_EXE="$(nav_cmd self_filter)"
|
||||
if [ "$LOCALIZATION" = lio ]; then
|
||||
LIO_EXE="$(nav_cmd field_localization_node)"
|
||||
fi
|
||||
WORLD="${PKG_SHARE}/worlds/sentry_arena.sdf"
|
||||
PIDS=()
|
||||
CLEANED=0
|
||||
@@ -187,7 +208,7 @@ cleanup() {
|
||||
trap cleanup EXIT INT TERM
|
||||
|
||||
if [ "$NAV2" = "1" ]; then
|
||||
python3 "$WS/tools/nav2_startup.py" --preflight
|
||||
python3 "$INTERNAL_TOOLS/nav2_startup.py" --preflight
|
||||
fi
|
||||
|
||||
# ---------- 1. Gazebo(系统版,清掉 ROS vendor 的库路径)----------
|
||||
@@ -203,34 +224,9 @@ GZ_PID=$!
|
||||
PIDS+=("$GZ_PID")
|
||||
|
||||
# ---------- 2. 等 Gazebo 就绪(/clock 出现)----------
|
||||
# 查话题也用 $GZ_EXE,而不是 PATH 上的 `gz`:source 过 ROS 之后 PATH 上是
|
||||
# gz_tools_vendor 那份,和真正在跑的进程不一定同一个版本,容易误判。
|
||||
echo -n "[sentry_up] 等 Gazebo 就绪"
|
||||
GZ_READY=0
|
||||
for _ in $(seq 1 120); do
|
||||
# Gazebo 进程提前退出 → 立刻报错,不用干等满 120 秒
|
||||
if ! kill -0 "$GZ_PID" 2>/dev/null; then
|
||||
echo
|
||||
echo "[sentry_up] ❌ Gazebo 启动失败,进程已退出" >&2
|
||||
wait "$GZ_PID" 2>/dev/null || true
|
||||
exit 1
|
||||
fi
|
||||
if env -u LD_LIBRARY_PATH "$GZ_EXE" topic -l 2>/dev/null | grep -qx '/clock'; then
|
||||
GZ_READY=1
|
||||
break
|
||||
fi
|
||||
echo -n "."
|
||||
sleep 1
|
||||
done
|
||||
|
||||
if [ "$GZ_READY" != "1" ]; then
|
||||
echo
|
||||
echo "[sentry_up] ❌ 等待 Gazebo 超时(120 s),没看到 /clock" >&2
|
||||
echo "[sentry_up] 先确认 GZ_PARTITION=${GZ_PARTITION:-<未设>} 和其他终端一致" >&2
|
||||
echo "[sentry_up] 再确认 Gazebo 窗口/进程还活着" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo " OK"
|
||||
echo "[sentry_up] 等 Gazebo /clock"
|
||||
env_wait_gz_clock "$GZ_EXE" --gazebo-pid "$GZ_PID"
|
||||
echo "[sentry_up] Gazebo /clock 已就绪"
|
||||
|
||||
# ---------- 3. ros_gz 桥 ----------
|
||||
echo "[sentry_up] 启动 ros_gz 桥"
|
||||
@@ -265,7 +261,7 @@ PIDS+=($!)
|
||||
# ---------- 5. odom -> base_link ----------
|
||||
echo "[sentry_up] 启动 odom_tf(${NAV_BIN_DIR}/odom_tf,C++ 版)"
|
||||
# SENTRY_ODOM_SCALE != 1.0 时给里程计加比例误差(演示 AMCL 纠正漂移用)
|
||||
$(nav_cmd odom_tf) --ros-args \
|
||||
"$ODOM_TF_EXE" --ros-args \
|
||||
-p use_sim_time:=true -p "odom_scale:=${SENTRY_ODOM_SCALE:-1.0}" &
|
||||
PIDS+=($!)
|
||||
|
||||
@@ -277,20 +273,20 @@ RELAY_HEALTH=false
|
||||
if [ "$LOCALIZATION" = lio ]; then RELAY_HEALTH=true; fi
|
||||
RELAY_INPUT=/cmd_vel
|
||||
if [ "$RELAY_NAVIGATION" = false ]; then RELAY_INPUT="${MANUAL_CMD_VEL_TOPIC:-/cmd_vel}"; fi
|
||||
$(nav_cmd cmd_vel_relay) --ros-args -p use_sim_time:=true \
|
||||
"$CMD_VEL_RELAY_EXE" --ros-args -p use_sim_time:=true \
|
||||
-p navigation_mode:="$RELAY_NAVIGATION" -p require_localization_health:="$RELAY_HEALTH" -p in_topic:="$RELAY_INPUT" &
|
||||
PIDS+=($!)
|
||||
|
||||
# ---------- 5.55 点云自滤(剔除车身自身回波,Nav2 避障用)----------
|
||||
echo "[sentry_up] 启动点云自滤(${NAV_BIN_DIR}/self_filter)"
|
||||
$(nav_cmd self_filter) --ros-args -p use_sim_time:=true -p reliable_clouds:=true &
|
||||
"$SELF_FILTER_EXE" --ros-args -p use_sim_time:=true -p reliable_clouds:=true &
|
||||
PIDS+=($!)
|
||||
|
||||
# ---------- 5.6 唯一 map->odom 发布者:LIO 或 AMCL ----------
|
||||
if [ "$LOCALIZATION" = lio ]; then
|
||||
echo "[sentry_up] LIO mode=$LIO_MODE (AMCL disabled)"
|
||||
$(nav_cmd field_localization_node) --ros-args -p use_sim_time:=true \
|
||||
-p point_cloud_topic:=/scan/points_filtered -p imu_topic:=/imu -p reliable_clouds:=true \
|
||||
echo "[sentry_up] LIO mode=$LIO_MODE map=$LIO_MAP cloud=$LIO_POINT_CLOUD_TOPIC (AMCL disabled)"
|
||||
"$LIO_EXE" --ros-args -p use_sim_time:=true \
|
||||
-p "point_cloud_topic:=$LIO_POINT_CLOUD_TOPIC" -p imu_topic:=/imu -p reliable_clouds:=true \
|
||||
-p mode:="$LIO_MODE" -p map_path:="$LIO_MAP" -p export_map_path:="$LIO_EXPORT_MAP" \
|
||||
-p publish_map_to_odom:=true -p "diagnostics_path:='${LIO_TRACE_PATH:-}'" \
|
||||
-p initial_x:="${LIO_INITIAL_X:--5.0}" -p initial_y:="${LIO_INITIAL_Y:-3.0}" \
|
||||
@@ -317,7 +313,7 @@ echo "体检(含 Gazebo 真值对照):python3 tools/check_stack.py"
|
||||
|
||||
# ---------- 6. Nav2 ----------
|
||||
if [ "$NAV2" = "1" ]; then
|
||||
python3 "$WS/tools/wait_navigation_ready.py"
|
||||
python3 "$INTERNAL_TOOLS/wait_navigation_ready.py"
|
||||
echo "[sentry_up] 启动 Nav2($LOCALIZATION + 栅格图)"
|
||||
# 三个参数都是必需的,各有原因(踩过的坑):
|
||||
# use_composition:=False 组合模式在本机起不来 —— /nav2_container 起来后一个组件都不加载,
|
||||
@@ -328,7 +324,7 @@ if [ "$NAV2" = "1" ]; then
|
||||
# 发现不到,lifecycle_manager 会无限等下去(日志刷
|
||||
# "Waiting for service keepout_costmap_filter_info_server/get_state"),
|
||||
# Nav2 永远不激活 → 所有导航目标被拒。我们不用禁入区/限速区,直接关掉。
|
||||
python3 "$WS/tools/run_nav2.py" --timeout "${SENTRY_NAV2_TIMEOUT:-120}" -- \
|
||||
python3 "$INTERNAL_TOOLS/run_nav2.py" --timeout "${SENTRY_NAV2_TIMEOUT:-120}" -- \
|
||||
map:="${MAP_YAML}" \
|
||||
use_sim_time:=true \
|
||||
autostart:=False \
|
||||
|
||||
+163
-63
@@ -1,76 +1,176 @@
|
||||
# tools/
|
||||
|
||||
模型转换、调试、演示用的小工具(都是独立脚本,不参与构建)。
|
||||
最后更新:2026-11-22
|
||||
|
||||
## 模型相关
|
||||
构建脚本、启动链内部件、验收脚本和回归测试。
|
||||
**除 `check_stack.py` 需要仿真在运行中外,其余命令都可以在仿真没启动时执行。**
|
||||
|
||||
| 脚本 | 用途 |
|
||||
|---|---|
|
||||
| `build_vehicle.py` | **整车装配体 STL → 仿真网格 + 布局 json**(唯一的建模入口) |
|
||||
| `decimate.py` | 顶点聚类减面(纯 numpy,不依赖 MeshLab/Blender) |
|
||||
| `gen_sdf.sh` | URDF(xacro) → `models/sentry/model.sdf` + `generated/sentry.urdf` |
|
||||
> 以下命令**全部从仓库根目录**运行。看到 `AttributeError` / `ModuleNotFoundError` 时
|
||||
> 先确认是不是在 `tools/` 里面敲的。
|
||||
|
||||
## 体检
|
||||
## 目录结构
|
||||
|
||||
| 脚本 | 用途 |
|
||||
|---|---|
|
||||
| `check_dds.sh` | ★ Fast DDS 体检:`/dev/shm` 残留段、进程、DDS 环境变量。加 `--clean` 清理残留 |
|
||||
| `check_stack.py` | ★ **只读体检**:10 个 lifecycle 节点状态 + 节点总览(含 `amcl`、`lifecycle_manager`)+ 话题 + TF + 真值对照,一条命令问清"现在这套栈健康吗" |
|
||||
| `project_env.py` | ★ 路径/版本探测。**排查"路径不对"先跑它**。支持直接取单个值供脚本/文档拼接:`--bin-dir` / `--field` / `--map` / `--gz` / `--gz-version-args` / `--ros-setup`,例:`NAV=$(python3 tools/project_env.py --bin-dir)/nav_client`。它同时被 `launch/` 和 `check_stack.py` import,**是依赖库不只是工具** |
|
||||
|
||||
## 静态审计
|
||||
|
||||
| 脚本 | 用途 |
|
||||
|---|---|
|
||||
| `audit_absolute_paths.py` | 扫全仓的写死绝对路径(`/opt/ros/…`、`/home/…`、`/usr/…`)。`--all` 出完整报告 |
|
||||
|
||||
> ⚠️ **这个工具目前噪音很大**:它把 ROS 话题名也当成绝对路径,全仓会产生
|
||||
> **4700+ 条**命中(`/wait`、`/odom`、`/dev/shm` …),真正要看的只有
|
||||
> `ROS 安装路径` / `用户目录路径` 这两类。查的时候这样过滤:
|
||||
> `python3 tools/audit_absolute_paths.py --all | grep -A1 'ROS 安装路径\|用户目录路径'`
|
||||
|
||||
> **本目录里没有 `nav_client`。** 发 Nav2 目标用的是 **xmake 编译出的二进制**,
|
||||
> 源码在 `src/sentry_nav/src/nav_client.cpp`,产物**固定落在 `build/bin/nav_client`**
|
||||
> (xmake 里每个 target 都 `set_targetdir("$(builddir)/bin")`,故意不用带平台三元组的默认目录)。
|
||||
> 它带地图预检(占据值 ≥65 / 未知格 / 净空 <0.5 m 直接拦下),用法见
|
||||
> [`../docs/操作手册.md`](../docs/操作手册.md) §3。
|
||||
|
||||
## 构建 / 编辑器
|
||||
|
||||
**这里已经没有构建相关的脚本了。**
|
||||
|
||||
`compile_commands.json` 由 xmake 在**每次构建后自动重写**
|
||||
(根 `xmake.lua` 里的 `plugin.compile_commands.autoupdate` 规则),
|
||||
以前那个 `gen_compdb.sh`(合并 colcon 分包产物)已随去 colcon 一起删除。
|
||||
|
||||
改了源码结构后只要跑一次 `xmake`,再在 VS Code 里
|
||||
`Ctrl+Shift+P → clangd: Restart language server`。详见 `../.vscode/README.md`。
|
||||
|
||||
## 典型用法
|
||||
|
||||
```bash
|
||||
# 机械给了新装配体
|
||||
python3 tools/build_vehicle.py --src "/run/media/mzxiang/CPBA_X64FRE/装配车" --out src/sentry_sim/meshes/full
|
||||
python3 tools/decimate.py src/sentry_sim/meshes/full/base.stl src/sentry_sim/meshes/base.stl --grid 0.0025
|
||||
```text
|
||||
tools/
|
||||
├── project_env.py 环境探测(库和 CLI),供 Shell、Python launch 和工具共用
|
||||
├── check_stack.py 整套栈体检(⚠️ 需要仿真在跑)
|
||||
├── check_dds.sh DDS 环境 / 残留进程检查
|
||||
├── capture_lio.py 录制 LIO 建图 / 评估数据
|
||||
├── build_vehicle.py 整车 STL → 仿真网格 + 布局 JSON
|
||||
├── decimate.py 网格降面
|
||||
├── gen_sdf.sh xacro → SDF / URDF
|
||||
├── _internal/ 启动链内部件;被 sentry_up.sh / launch / 测试 import
|
||||
├── validation/ 验收脚本(会真的拉起 Gazebo,跑完整流程)
|
||||
└── tests/ 回归测试(不碰 Gazebo 运动,最快的检查)
|
||||
```
|
||||
|
||||
> 建模类脚本是**离线**的,不需要起仿真。体检类脚本要先按根目录 README 把仿真跑起来,
|
||||
> 再在另一个终端执行。
|
||||
## 一、会被自动调用的(不用手动跑)
|
||||
|
||||
## 2026-11-21 精简掉了什么
|
||||
| 工具 | 谁调它 | 干什么 |
|
||||
|---|---|---|
|
||||
| `project_env.py` | Shell 环境库、Python launch、体检、录包、验收和测试 | 探测 ROS setup / `build/bin` / 场地包 / 地图 / gz 版本,**一个都不写死** |
|
||||
| `_internal/dds_environment.py` | `sentry_up.sh`(`--shell`)、`sentry_arena.launch.py`、`nav2_startup.py`、`validate_lio_navigation.py`、`tests/test_nav2_startup.py` | DDS 默认值统一出口(`rmw_implementation`、`ROS_DOMAIN_ID`、共享内存传输) |
|
||||
| `_internal/resolve_ros_includes.py` | `src/sentry_nav/xmake.lua`、`src/field_localization/xmake.lua` | 经 ament index 解析 ROS 包的头文件目录,喂给 xmake |
|
||||
| `_internal/nav2_startup.py` | `sentry_up.sh`、`sentry_arena.launch.py` | Nav2 域预检(`--preflight`)+ 发现门控 + 有界就绪检查 |
|
||||
| `_internal/run_nav2.py` | `sentry_up.sh`、`sentry_arena.launch.py`、`tests/test_nav2_supervisor.py` | **只监管自己那组 Nav2 进程**;有界重试后才放行导航 |
|
||||
| `_internal/wait_navigation_ready.py` | `sentry_up.sh`、`sentry_arena.launch.py` | 等到仿真时钟 + 基础机器人 TF 就绪才返回 |
|
||||
|
||||
一次性排查脚本已全部删除(都在 git 历史里,需要时 `git show <commit>:tools/<名字>` 能捞回来):
|
||||
**这六个是被 `sentry_up.sh` 和 launch 拉起来的。改它们等于改启动行为,改完必须重跑一次启动验证。**
|
||||
|
||||
| 删掉的 | 原因 |
|
||||
## 二、手动入口(日常用)
|
||||
|
||||
| 命令 | 用途 |
|
||||
|---|---|
|
||||
| `probe_all.py` / `probe_sub.py` | 已被 `check_stack.py` 完全覆盖 |
|
||||
| `probe_cmd.py` / `probe_cmd2.py` / `cmd_probe_all.py` | 同一次排查的三代尸体 |
|
||||
| `smoke_probe.py` | 等激活+收点云+发目标 → `check_stack.py` + `nav_client` |
|
||||
| `nav_diag.py` | 同 `check_stack.py` §2/§3,且还用旧坐标系 |
|
||||
| `cloud_compare.py` | 0 引用 |
|
||||
| `send_goal.py` | **空炮**:往 `/goal_pose` 发,Nav2 没有任何节点订阅它 |
|
||||
| `tf_watch.py` / `scan_probe.py` / `cloud_probe.py` / `free_goals.py` / `mark_field_center.py` / `amcl_drift_demo.py` / `demo.py` / `drive_demo.py` | 精简(替代做法见各文档:用 `ros2 topic echo`、`tf2_echo`、RViz 的 costmap 显示、`ros2 topic pub /cmd_vel`) |
|
||||
| `build_meshes.py` / `build_gimbal.py` | 旧版分件建模(只处理「底盘」或「云台」单独导出),已被 `build_vehicle.py` 的整车装配体方案取代 |
|
||||
| `python3 tools/check_stack.py` | **整套栈体检**:生命周期、话题、TF、Gazebo 真值对照。⚠️ 仿真必须在跑,否则会卡在等服务上 |
|
||||
| `tools/check_dds.sh` | DDS 环境、`/dev/shm`、残留进程。`--clean` 清理残留(**确认所有 ROS 进程已停**再用) |
|
||||
| `python3 tools/project_env.py` | 打印全部探测结果。单项取值:`--bin-dir` / `--field` / `--map` / `--gz` / `--gz-version-args` / `--ros-setup` |
|
||||
| `python3 tools/capture_lio.py --help` | 录制建图(`--profile mapping`)或评估(`--profile evaluation`)数据 |
|
||||
| `python3 tools/build_vehicle.py --help` | 整车装配体 STL → 仿真网格 + 布局 JSON。`--dry-run` 只打印分类结果 |
|
||||
| `python3 tools/decimate.py --help` | 顶点聚类降面:`decimate.py --grid 0.01 src.stl dst.stl` |
|
||||
| `tools/gen_sdf.sh` | xacro → `models/sentry/model.sdf` + `generated/sentry.urdf` |
|
||||
|
||||
> **删脚本不影响已有产物**:`src/sentry_sim/meshes/base.stl`、`wheel.stl` 是已经生成好的,
|
||||
> URDF 引用的是这些文件。重跑建模用 `build_vehicle.py` 即可。
|
||||
**发导航目标不用工具脚本**,用 xmake 产物 `build/bin/nav_client`。
|
||||
`xmake` 构建会自动刷新 `compile_commands.json`(clangd 靠它跳转)。
|
||||
|
||||
## 三、库模块(有 `--help` 不代表要单独跑)
|
||||
|
||||
| 模块 | 被谁 import | 说明 |
|
||||
|---|---|---|
|
||||
| `_internal/arena_grid.py`、`_internal/arena_survey.py` | `capture_lio.py`、`validate_lio_navigation.py` | 栅格可达性、隔离仿真测站和雷达地图生成 |
|
||||
| `validation/lio_metrics.py` | `validate_lio_navigation.py` | ATE / RPE / 圆柱间隙计算。**没有 CLI**,直接跑只会静默退出 |
|
||||
| `project_env.py` | 见上 | 既当库又当命令 |
|
||||
| `_internal/dds_environment.py` | 见上 | 既当库又当命令 |
|
||||
|
||||
## 四、验收脚本(会真的拉起 Gazebo)
|
||||
|
||||
| 命令 | 用途 | 耗时 |
|
||||
|---|---|---|
|
||||
| `python3 tools/validation/verify_lio_stack.py --map <flmap> --output <dir>` | **只验栈、不发运动指令**:Gazebo + LIO + Nav2 能不能一起起来。`--launcher {shell,python}` 选启动入口,`--rviz` 加上离屏 RViz 负载 | 分钟级 |
|
||||
| `python3 tools/validation/validate_lio_navigation.py --map <flmap> --output <dir>` | **真跑导航并用仿真真值打分**。`--scenario {clear,cylinder,blocked,lidar_loss}` 选场景,`--full-field` 检查每个 1 m 瓦片的代表目标并跑全场路线,圆柱场景可调 `--obstacle-x/y/radius`,`--domain` 指定 ROS 域 | 分钟级 |
|
||||
| `python3 tools/validation/run_lio_matrix.py --launcher {shell,python} --map <flmap> --output <dir>` | 每条路线/每个启动器跑 3 次冷启动,外加一次"目标不可达"检查。`--domain` 同上 | **十几分钟** |
|
||||
|
||||
三个都要给 `--map`(例如 `src/sentry_sim/maps/field_full.flmap`)和 `--output`,但**输出目录的要求不同**:
|
||||
|
||||
| 脚本 | 对 `--output` 的要求 |
|
||||
|---|---|
|
||||
| `validate_lio_navigation.py` | **必须不存在**(已存在直接报错) |
|
||||
| `run_lio_matrix.py` | **必须不存在**(`output must be new`) |
|
||||
| `verify_lio_stack.py` | **允许已存在**(会自动 `mkdir -p`) |
|
||||
|
||||
脚本自行分配隔离的 `ROS_DOMAIN_ID`,**不会和你正在跑的仿真撞车**。
|
||||
|
||||
隔离 Gazebo 空场的全场建图与东南回放:
|
||||
|
||||
```bash
|
||||
python3 tools/capture_lio.py --profile mapping --full-field \
|
||||
--output generated/full_survey --map generated/field_full.flmap
|
||||
python3 tools/validation/validate_lio_navigation.py --full-field --launcher shell \
|
||||
--lio-cloud-topic /scan/points_lio \
|
||||
--map generated/field_full.flmap --output generated/full_shell
|
||||
python3 tools/validation/compare_lio_maps.py --dataset generated/full_shell/dataset \
|
||||
--baseline generated/field.flmap --candidate generated/field_full.flmap \
|
||||
--output generated/southeast_comparison
|
||||
```
|
||||
|
||||
全场建图按已知坐标在隔离实例布置测站,使用与在线 LIO 相同的自滤点云。测站位置由命令指定,Gazebo 真值核对实际到位。在线验收使用另一实例,机器人连续行驶。回放需要至少 10 帧独立录制的东南扫描(`x >= 4`、`y <= -1.5`)。
|
||||
|
||||
## 五、回归测试
|
||||
|
||||
按跑得快 → 慢排:
|
||||
|
||||
| 命令 | 需要什么 | 实测 |
|
||||
|---|---|---|
|
||||
| `python3 tools/tests/test_project_env.py` | Python 3 和 Bash | 临时文件和假 Gazebo 覆盖路径、退出码、版本超时与桥等待 |
|
||||
| `python3 tools/tests/test_nav2_supervisor.py` | **什么都不需要**(不碰 ROS、不碰 Gazebo) | ✅ 5 项检查,约 1 秒 |
|
||||
| `python3 tools/tests/test_nav2_startup.py` | ROS 环境(起隔离 domain 的服务) | ✅ 15 项检查 |
|
||||
| `python3 tools/tests/test_motion_interlock.py` | ROS 环境 + `build/bin/cmd_vel_relay`(`--binary` 可指定) | 需已构建 |
|
||||
|
||||
**`test_nav2_supervisor.py` 是最便宜的冒烟测试**:改完 `run_nav2.py` 先跑它。
|
||||
|
||||
### 和 C++ 单测的关系
|
||||
|
||||
C++ 侧的单测走 xmake:
|
||||
|
||||
```bash
|
||||
xmake test # 全部
|
||||
xmake test test_waypoint_sequencer/default # 单个(必须带 /default)
|
||||
```
|
||||
|
||||
三个带 `add_tests` 的 target:`test_self_filter_core`、`test_waypoint_sequencer`、`test_geometry`。
|
||||
|
||||
Python 回归测试用上表中的命令单独运行。
|
||||
|
||||
## 六、加新工具时的规矩
|
||||
|
||||
1. **放哪个目录**
|
||||
- 只给启动链用、且会被 import → `_internal/`
|
||||
- 手动跑、会拉起 Gazebo → `validation/`
|
||||
- 手动跑、不碰 Gazebo → `tests/`
|
||||
- 构建期用的 → 本目录顶层
|
||||
|
||||
2. **跨目录 import 必须自己铺 `sys.path`**,仓库里没有安装成包:
|
||||
|
||||
```python
|
||||
from pathlib import Path
|
||||
import sys
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / '_internal'))
|
||||
```
|
||||
|
||||
3. **别复制公共逻辑**。要读环境变量 / 找产物目录,一律走 `project_env`;
|
||||
要设 DDS 参数,一律走 `_internal/dds_environment.py`。这两处各只有一份实现。
|
||||
|
||||
4. **本文件是唯一索引**。加了工具就在上面的表里补一行,删了工具就把那行删掉
|
||||
—— 否则会出现「文档里有一堆打不开的文件」。
|
||||
|
||||
## 七、这个目录的历史
|
||||
|
||||
`git log --oneline -- tools/` 能看到两次大整理:
|
||||
|
||||
**第一次:删掉 21 个文件**(`git log --diff-filter=D --name-only -- 'tools/*.py' 'tools/*.sh'` 可复现)
|
||||
|
||||
| 类别 | 文件 | 为什么删 |
|
||||
|---|---|---|
|
||||
| 一次性诊断(14) | `probe_all` `probe_sub` `probe_cmd` `probe_cmd2` `cmd_probe_all` `smoke_probe` `nav_diag` `cloud_compare` `cloud_probe` `scan_probe` `tf_watch` `send_goal` `free_goals` `mark_field_center` | 功能被 `check_stack.py` 和 `validation/` 取代 |
|
||||
| 演示(3) | `demo` `drive_demo` `amcl_drift_demo` | 一次性演示,舞台已拆 |
|
||||
| 构建辅助(3) | `build_meshes` `build_gimbal` `gen_compdb.sh` | 前两个并入 `build_vehicle.py`;`compile_commands.json` 改由 xmake 自动刷新 |
|
||||
| 节点迁移(1) | `nav_client.py` | 重写成 C++,在 `src/sentry_nav/src/` |
|
||||
|
||||
**第二次:扁平布局收成三组**
|
||||
|
||||
```
|
||||
_internal/ 启动链内部件(被 shell / launch / 测试 import,一般不当命令用)
|
||||
validation/ 会拉起 Gazebo 的验收脚本
|
||||
tests/ 不碰 Gazebo 的回归测试
|
||||
```
|
||||
|
||||
顺带删了已跑完使命的 `audit_absolute_paths.py`(可移植性重构的一次性审计工具)。
|
||||
|
||||
如果发现 `tools/` 里还残留着已删工具的 `.pyc`,可以安全清掉:
|
||||
|
||||
```bash
|
||||
find . -name __pycache__ -type d -not -path './build/*' -exec rm -rf {} +
|
||||
```
|
||||
|
||||
(`.gitignore` 已经排除 `__pycache__/` 和 `*.pyc`,git 从来不收它们。
|
||||
无源码的 `.pyc` 放在 `__pycache__/` 里也**不会被 import** —— Python 3 的无源码导入要求
|
||||
`.pyc` 直接放在目录里,所以这些是纯死数据。)
|
||||
@@ -0,0 +1,151 @@
|
||||
"""Static arena clearance and deterministic routes for isolated simulation tests."""
|
||||
|
||||
from collections import deque
|
||||
from functools import cache
|
||||
import heapq
|
||||
import math
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import yaml
|
||||
|
||||
|
||||
START = (-5.0, 3.0)
|
||||
SURVEY_GOALS = ((-5., 0.), (-5., -3.), (0., -3.), (5., -3.), (5., 0.), (5., 3.),
|
||||
(0., 3.), (0., 0.), (0., -3.), (-5., -3.), START)
|
||||
# Revisit the reported east route in both directions before covering the perimeter.
|
||||
ARENA_GOALS = ((0., 0.), (5., -3.), (0., 0.), (5., -3.), (5., 0.), (5., 3.),
|
||||
(0., 3.), START, (-5., 0.), (-5., -3.), (0., -3.), (0., 0.), START)
|
||||
|
||||
|
||||
class ArenaGrid:
|
||||
def __init__(self, map_yaml):
|
||||
path = Path(map_yaml)
|
||||
config = yaml.safe_load(path.read_text())
|
||||
self.resolution = float(config['resolution'])
|
||||
self.origin = tuple(config['origin'][:2])
|
||||
if config.get('mode', 'trinary') != 'trinary' or config['origin'][2] != 0:
|
||||
raise ValueError('arena coverage expects an unrotated trinary occupancy map')
|
||||
with (path.parent / config['image']).open('rb') as image:
|
||||
def header():
|
||||
line = image.readline().split(b'#', 1)[0].strip()
|
||||
while not line:
|
||||
raw = image.readline()
|
||||
if not raw:
|
||||
raise ValueError('truncated PGM header')
|
||||
line = raw.split(b'#', 1)[0].strip()
|
||||
return line
|
||||
if header() != b'P5':
|
||||
raise ValueError('expected binary PGM occupancy map')
|
||||
width, height = map(int, header().split())
|
||||
if header() != b'255':
|
||||
raise ValueError('expected 8-bit PGM occupancy map')
|
||||
pixels = np.frombuffer(image.read(), dtype=np.uint8).reshape(height, width)
|
||||
self.size = (height, width)
|
||||
probability = pixels / 255 if config.get('negate', 0) else 1 - pixels / 255
|
||||
self.free = (probability < config['free_thresh'])[::-1]
|
||||
|
||||
def cell(self, point):
|
||||
x, y = point
|
||||
return (math.floor((y-self.origin[1])/self.resolution),
|
||||
math.floor((x-self.origin[0])/self.resolution))
|
||||
|
||||
def point(self, cell):
|
||||
y, x = cell
|
||||
return (self.origin[0]+(x+0.5)*self.resolution,
|
||||
self.origin[1]+(y+0.5)*self.resolution)
|
||||
|
||||
def neighbors(self, cell):
|
||||
y, x = cell
|
||||
h, w = self.size
|
||||
for i, j in ((y-1,x),(y+1,x),(y,x-1),(y,x+1)):
|
||||
if 0 <= i < h and 0 <= j < w:
|
||||
yield i, j
|
||||
|
||||
@cache
|
||||
def clear(self, clearance):
|
||||
radius = math.ceil(clearance/self.resolution)
|
||||
padded = np.pad(self.free, radius)
|
||||
h, w = self.size
|
||||
mask = self.free.copy()
|
||||
for y in range(-radius, radius+1):
|
||||
for x in range(-radius, radius+1):
|
||||
if math.hypot(x, y)*self.resolution <= clearance + 1e-10:
|
||||
mask &= padded[radius+y:radius+y+h, radius+x:radius+x+w]
|
||||
return mask
|
||||
|
||||
def coverage(self):
|
||||
# Largest radius of the existing 0.65 x 0.54 m rectangular footprint.
|
||||
travel = self.clear(math.hypot(0.325, 0.270))
|
||||
start = self.cell(START)
|
||||
if not travel[start]:
|
||||
raise ValueError('spawn pose fails the footprint clearance check')
|
||||
connected = np.zeros(self.size, dtype=bool)
|
||||
connected[start] = True
|
||||
queue = deque([start])
|
||||
while queue:
|
||||
for cell in self.neighbors(queue.popleft()):
|
||||
if travel[cell] and not connected[cell]:
|
||||
connected[cell] = True
|
||||
queue.append(cell)
|
||||
targets = connected & self.clear(0.50)
|
||||
wide = self.clear(0.65)
|
||||
tiles = {}
|
||||
for cell in zip(*np.nonzero(targets)):
|
||||
point = self.point(cell)
|
||||
grid = tuple(map(math.floor, point))
|
||||
score = (not wide[cell], math.dist(point, (grid[0]+0.5, grid[1]+0.5)), point)
|
||||
if grid not in tiles or score < tiles[grid]:
|
||||
tiles[grid] = score
|
||||
ys, xs = np.nonzero(connected)
|
||||
return {'reachable_cells': int(connected.sum()), 'eligible_goal_cells': int(targets.sum()),
|
||||
'reachable_area_m2': float(connected.sum() * self.resolution**2),
|
||||
'center_coordinate_bounds_m': [self.point((min(ys), min(xs))),
|
||||
self.point((max(ys), max(xs)))],
|
||||
'disconnected_goal_cells': int((self.clear(0.50)&~connected).sum()),
|
||||
'resolution_m': self.resolution,
|
||||
'samples': [tiles[tile][2] for tile in sorted(tiles)]}
|
||||
|
||||
def route(self, anchors, clearance=0.55):
|
||||
safe = self.clear(clearance)
|
||||
points = [START]
|
||||
for target in anchors:
|
||||
start, end = self.cell(points[-1]), self.cell(target)
|
||||
if not safe[start] or not safe[end]:
|
||||
raise ValueError(f'unsafe survey anchor {points[-1]} -> {target}')
|
||||
frontier = [(0, 0, start)]
|
||||
distance = {start: 0}
|
||||
previous = {}
|
||||
while frontier:
|
||||
_, cost, node = heapq.heappop(frontier)
|
||||
if node == end:
|
||||
break
|
||||
if cost != distance[node]:
|
||||
continue
|
||||
for cell in self.neighbors(node):
|
||||
if safe[cell] and cost+1 < distance.get(cell, math.inf):
|
||||
distance[cell] = cost+1
|
||||
previous[cell] = node
|
||||
estimate = abs(cell[0]-end[0])+abs(cell[1]-end[1])
|
||||
heapq.heappush(frontier, (cost+1+estimate, cost+1, cell))
|
||||
else:
|
||||
raise ValueError(f'no survey route from {points[-1]} to {target}')
|
||||
cells = [end]
|
||||
while cells[-1] != start:
|
||||
cells.append(previous[cells[-1]])
|
||||
candidates = [self.point(c) for c in reversed(cells[1:-1])] + [target]
|
||||
index = 0
|
||||
while index < len(candidates):
|
||||
a = points[-1]
|
||||
# Advance to the furthest visible waypoint along the grid path.
|
||||
for last in range(len(candidates)-1, index-1, -1):
|
||||
b = candidates[last]
|
||||
count = max(1, math.ceil(2*math.dist(a,b)/self.resolution))
|
||||
if all(safe[self.cell(tuple(x+(y-x)*i/count for x,y in zip(a,b)))]
|
||||
for i in range(count+1)):
|
||||
break
|
||||
else:
|
||||
raise ValueError(f'unable to simplify survey route near {a}')
|
||||
points.append(b)
|
||||
index = last+1
|
||||
return points[1:]
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Make a Gazebo-only map from stationary LiDAR scans at commanded survey stations."""
|
||||
|
||||
import csv
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
import tempfile
|
||||
|
||||
import numpy as np
|
||||
|
||||
import project_env
|
||||
from _internal.arena_grid import START, SURVEY_GOALS
|
||||
|
||||
SETTLE_SECONDS = 0.8
|
||||
STATION_SECONDS = 1.5
|
||||
MAP_RESOLUTION = 0.10
|
||||
|
||||
|
||||
def stations(grid):
|
||||
result = [START]
|
||||
route = grid.route(SURVEY_GOALS)
|
||||
for a, b in zip([START] + route, route):
|
||||
steps = max(1, math.ceil(math.dist(a, b) / 1.5))
|
||||
for i in range(1, steps + 1):
|
||||
point = tuple(round(x + (y - x) * i / steps, 4) for x, y in zip(a, b))
|
||||
if point not in result:
|
||||
result.append(point)
|
||||
return result
|
||||
|
||||
|
||||
def set_station(gz, point, partition):
|
||||
x, y = point
|
||||
request = f'name: "sentry" position: {{ x: {x} y: {y} z: 0 }} orientation: {{ w: 1 }}'
|
||||
response = project_env.run_gz(
|
||||
gz, 'service', '-s', '/world/rmul_arena/set_pose', '--reqtype', 'gz.msgs.Pose',
|
||||
'--reptype', 'gz.msgs.Boolean', '--timeout', '2000', '--req', request,
|
||||
timeout=3, partition=partition,
|
||||
)
|
||||
if response.returncode or not re.search(r'^data:\s*true\s*$', response.stdout, re.M):
|
||||
raise RuntimeError(f'Gazebo did not acknowledge station {point}: {response.stdout} {response.stderr}')
|
||||
|
||||
|
||||
def transform(points, pose):
|
||||
translation, xyz, w = pose[:3], pose[3:6], pose[6]
|
||||
twice = 2 * np.cross(xyz, points)
|
||||
return points + w * twice + np.cross(xyz, twice) + translation
|
||||
|
||||
|
||||
def selected_clouds(directory, survey):
|
||||
with (directory / 'scans.csv').open() as stream:
|
||||
scans = [(float(row['timestamp']), row['file']) for row in csv.DictReader(stream)]
|
||||
for station in survey:
|
||||
stamp = station['command_time']
|
||||
candidates = [scan for scan in scans if stamp + SETTLE_SECONDS <= scan[0] < stamp + STATION_SECONDS]
|
||||
if len(candidates) < 3:
|
||||
raise RuntimeError(f'insufficient settled scans at {station["goal"]}')
|
||||
yield station['goal'], candidates[len(candidates) // 2]
|
||||
|
||||
|
||||
def build_map(directory, selected, output):
|
||||
config = (directory / 'config.txt').read_text().splitlines()
|
||||
extrinsics = [np.array(list(map(float, row.split()[1:]))) for row in config[2:4]]
|
||||
if [line.split()[0] for line in config[2:4]] != ['base_from_imu', 'imu_from_lidar']:
|
||||
raise ValueError('survey recorder configuration is missing LiDAR extrinsics')
|
||||
clouds = []
|
||||
for (x, y), (stamp, filename) in selected:
|
||||
raw = (directory / filename).read_bytes()
|
||||
magic, version, time, count = struct.unpack_from('<8sIdI', raw)
|
||||
if magic != b'FLPC0001' or version != 1 or time != stamp or len(raw) != 24 + count * 24:
|
||||
raise ValueError(f'invalid recorded scan {filename}')
|
||||
rows = np.frombuffer(raw, dtype=[('time', '<f8'), ('point', '<f4', (4,))], offset=24)
|
||||
points = rows['point'][:, :3].astype(np.float64)
|
||||
points = points[np.isfinite(points).all(axis=1)]
|
||||
if not len(points):
|
||||
raise RuntimeError(f'no finite returns at station {(x, y)}')
|
||||
base_from_imu, imu_from_lidar = extrinsics
|
||||
clouds.append(transform(transform(points, imu_from_lidar), base_from_imu) + [x, y, 0])
|
||||
points = np.concatenate(clouds)
|
||||
# Average measured returns that occupy the same voxel across overlapping views.
|
||||
grid = np.floor(points / MAP_RESOLUTION).astype(np.int64)
|
||||
_, bins, counts = np.unique(grid, axis=0, return_inverse=True, return_counts=True)
|
||||
centers = np.column_stack([np.bincount(bins, weights=axis) / counts for axis in points.T])
|
||||
with tempfile.NamedTemporaryFile(dir=output.parent) as stream:
|
||||
stream.write(struct.pack('<8sIdQ', b'FLMAP001', 1, MAP_RESOLUTION, len(centers)))
|
||||
stream.write(centers.astype('<f8').tobytes())
|
||||
stream.flush()
|
||||
os.link(stream.name, output)
|
||||
return len(centers)
|
||||
|
||||
|
||||
def evaluate_stations(directory, selected):
|
||||
# Independent truth is read only after all scan selections have been made.
|
||||
truth = np.loadtxt(directory / 'truth.tum', ndmin=2)
|
||||
report = []
|
||||
for (x, y), (stamp, filename) in selected:
|
||||
index = int(np.argmin(np.abs(truth[:, 0] - stamp)))
|
||||
time, *pose = truth[index]
|
||||
if abs(time - stamp) > 0.025:
|
||||
raise RuntimeError(f'no independent truth for {filename} at {stamp:.3f}s')
|
||||
error = math.dist(pose[:3], (x, y, 0))
|
||||
rotation = math.degrees(2 * math.acos(min(1.0, abs(pose[6]))))
|
||||
report.append({'station': [x, y], 'timestamp': stamp, 'scan': filename,
|
||||
'position_error_m': error, 'rotation_error_deg': rotation})
|
||||
(directory / 'survey_truth.json').write_text(json.dumps(report, indent=2))
|
||||
if any(row['position_error_m'] > 0.02 or row['rotation_error_deg'] > 1 for row in report):
|
||||
raise RuntimeError('commanded poses failed independent survey verification; see survey_truth.json')
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -1,151 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from pathlib import Path
|
||||
from collections import defaultdict
|
||||
import argparse
|
||||
import re
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
EXCLUDED_DIRS = {
|
||||
".git",
|
||||
".xmake",
|
||||
"build",
|
||||
"install",
|
||||
"log",
|
||||
"__pycache__",
|
||||
".cache",
|
||||
}
|
||||
|
||||
EXCLUDED_FILES = {
|
||||
"compile_commands.json",
|
||||
"CMakeCache.txt",
|
||||
}
|
||||
|
||||
# 匹配 Linux 绝对路径,避免匹配 URL 中的 //
|
||||
PATH_PATTERN = re.compile(
|
||||
r'(?<![A-Za-z0-9_./-])'
|
||||
r'/(?:[A-Za-z0-9._~+-]+(?:/[A-Za-z0-9._~+-]*)*)'
|
||||
)
|
||||
|
||||
def classify(path):
|
||||
if path.startswith("/opt/ros/"):
|
||||
return "ROS 安装路径"
|
||||
if path.startswith(("/home/", "/root/")):
|
||||
return "用户目录路径"
|
||||
if path.startswith(("/usr/", "/bin/", "/sbin/", "/lib/")):
|
||||
return "系统路径"
|
||||
if path.startswith(("/tmp/", "/var/tmp/")):
|
||||
return "临时目录路径"
|
||||
if path.startswith("/"):
|
||||
return "其他绝对路径"
|
||||
return "其他"
|
||||
|
||||
def should_skip(path):
|
||||
if any(part in EXCLUDED_DIRS for part in path.parts):
|
||||
return True
|
||||
|
||||
if path.name in EXCLUDED_FILES:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Scan repository for hardcoded absolute paths."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--max-lines",
|
||||
type=int,
|
||||
default=100,
|
||||
help="Maximum findings to display (default: 100)"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--all",
|
||||
action="store_true",
|
||||
help="Show all findings without the display limit"
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
findings = []
|
||||
category_counts = defaultdict(int)
|
||||
file_count = 0
|
||||
|
||||
for file in sorted(ROOT.rglob("*")):
|
||||
if not file.is_file() or should_skip(file.relative_to(ROOT)):
|
||||
continue
|
||||
|
||||
try:
|
||||
content = file.read_text(encoding="utf-8")
|
||||
except (UnicodeDecodeError, OSError):
|
||||
continue
|
||||
|
||||
# 跳过二进制文件
|
||||
if "\0" in content:
|
||||
continue
|
||||
|
||||
file_count += 1
|
||||
relative = file.relative_to(ROOT)
|
||||
|
||||
for line_no, line in enumerate(content.splitlines(), 1):
|
||||
paths = list(dict.fromkeys(PATH_PATTERN.findall(line)))
|
||||
|
||||
for path in paths:
|
||||
category = classify(path)
|
||||
category_counts[category] += 1
|
||||
|
||||
excerpt = " ".join(line.strip().split())
|
||||
if len(excerpt) > 140:
|
||||
excerpt = excerpt[:137] + "..."
|
||||
|
||||
findings.append({
|
||||
"file": str(relative),
|
||||
"line": line_no,
|
||||
"path": path,
|
||||
"category": category,
|
||||
"excerpt": excerpt,
|
||||
})
|
||||
|
||||
print("=" * 72)
|
||||
print("仓库绝对路径审计报告")
|
||||
print("=" * 72)
|
||||
print(f"仓库:{ROOT}")
|
||||
print(f"扫描文件数:{file_count}")
|
||||
print(f"发现路径数:{len(findings)}")
|
||||
print()
|
||||
|
||||
print("[分类统计]")
|
||||
for category, count in sorted(category_counts.items()):
|
||||
print(f" {category:<18} {count:>5}")
|
||||
print()
|
||||
|
||||
limit = len(findings) if args.all else max(0, args.max_lines)
|
||||
shown = findings[:limit]
|
||||
|
||||
current_file = None
|
||||
|
||||
for item in shown:
|
||||
if item["file"] != current_file:
|
||||
current_file = item["file"]
|
||||
print(f"\n[{current_file}]")
|
||||
|
||||
print(
|
||||
f" L{item['line']:<5} "
|
||||
f"[{item['category']}] {item['path']}"
|
||||
)
|
||||
print(f" {item['excerpt']}")
|
||||
|
||||
remaining = len(findings) - len(shown)
|
||||
|
||||
print("\n" + "=" * 72)
|
||||
print(f"已显示:{len(shown)} / {len(findings)}")
|
||||
|
||||
if remaining:
|
||||
print(f"其余隐藏:{remaining} 条")
|
||||
print("需要完整报告时执行:python3 tools/audit_absolute_paths.py --all")
|
||||
|
||||
print("=" * 72)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+78
-13
@@ -2,8 +2,8 @@
|
||||
"""Record an isolated Gazebo mapping/evaluation run; truth is recorder-only.
|
||||
|
||||
Source ROS first. Example:
|
||||
python3 tools/capture_lio.py --profile mapping --output generated/lio_mapping --map generated/field.flmap
|
||||
python3 tools/capture_lio.py --profile evaluation --output generated/lio_evaluation --map generated/field.flmap
|
||||
python3 tools/capture_lio.py --profile mapping --output generated/lio_mapping --map generated/field_mapping.flmap
|
||||
python3 tools/capture_lio.py --profile evaluation --output generated/lio_evaluation --map src/sentry_sim/maps/field_full.flmap
|
||||
"""
|
||||
import argparse
|
||||
import math
|
||||
@@ -25,6 +25,8 @@ from std_srvs.srv import Trigger
|
||||
from tf2_msgs.msg import TFMessage
|
||||
|
||||
import project_env
|
||||
from _internal.arena_grid import ArenaGrid
|
||||
from _internal import arena_survey
|
||||
|
||||
|
||||
def yaw(q):
|
||||
@@ -88,36 +90,75 @@ def main():
|
||||
parser.add_argument('--profile', choices=['mapping', 'evaluation'], required=True)
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
parser.add_argument('--map', type=Path, required=True)
|
||||
parser.add_argument('--duration', type=float, default=120)
|
||||
parser.add_argument('--duration', type=float)
|
||||
parser.add_argument('--lio-cloud-topic', default=os.environ.get('LIO_POINT_CLOUD_TOPIC'),
|
||||
help='override the recorded LiDAR topic')
|
||||
parser.add_argument('--full-field', action='store_true',
|
||||
help='capture stationary scans at overlapping Gazebo survey stations (mapping only)')
|
||||
parser.add_argument('--domain', type=int, choices=range(1, 233), metavar='[1–232]')
|
||||
args = parser.parse_args()
|
||||
if args.full_field and args.profile != 'mapping':
|
||||
parser.error('--full-field requires --profile mapping')
|
||||
if args.duration is not None and (not math.isfinite(args.duration) or args.duration <= 0):
|
||||
parser.error('--duration must be positive and finite')
|
||||
if args.full_field and args.map.exists():
|
||||
parser.error('full-field mapping requires a new output map path')
|
||||
if args.output.exists():
|
||||
parser.error('output directory must not already exist')
|
||||
if args.profile == 'evaluation' and not args.map.is_file():
|
||||
parser.error('evaluation requires an existing map')
|
||||
workspace = project_env.WORKSPACE
|
||||
try:
|
||||
gz_exe = project_env.find_gz_bin()
|
||||
bin_dir = project_env.find_bin_dir(workspace)
|
||||
recorder_exe = project_env.require_executable(bin_dir/'field_localization_record',
|
||||
'field_localization_record')
|
||||
survey = None
|
||||
default_duration = 120.0
|
||||
if args.full_field:
|
||||
survey = arena_survey.stations(ArenaGrid(project_env.find_map_yaml()))
|
||||
default_duration = float(math.ceil(3 + len(survey) * (arena_survey.STATION_SECONDS + 0.7)))
|
||||
if args.duration is not None and args.duration < default_duration:
|
||||
parser.error(f'--duration must be at least {default_duration:.1f} simulated seconds for the survey')
|
||||
print(f'mapping survey: {len(survey)} stationary LiDAR stations', flush=True)
|
||||
if args.duration is None:
|
||||
args.duration = default_duration
|
||||
except (project_env.ProbeError, ValueError, OSError) as error:
|
||||
parser.exit(1, f'{parser.prog}: {error}\n')
|
||||
cloud_topic = args.lio_cloud_topic or '/scan/points_lio'
|
||||
args.output.mkdir(parents=True)
|
||||
args.map.parent.mkdir(parents=True, exist_ok=True)
|
||||
workspace = Path(__file__).resolve().parents[1]
|
||||
binary = project_env.find_bin_dir(workspace)
|
||||
session = uuid.uuid4().hex[:12]
|
||||
os.environ.update(ROS_DOMAIN_ID=str(50 + int(session[:8], 16) % 50), GZ_PARTITION=f'field_lio_{session}', ROS2CLI_DISABLE_DAEMON='1',
|
||||
os.environ.update(GZ_BIN=str(gz_exe), SENTRY_BIN_DIR=str(bin_dir), LIO_POINT_CLOUD_TOPIC=cloud_topic)
|
||||
os.environ.update(ROS_DOMAIN_ID=str(args.domain if args.domain is not None else 50 + int(session[:8], 16) % 50), GZ_PARTITION=f'field_lio_{session}', ROS2CLI_DISABLE_DAEMON='1',
|
||||
FASTDDS_BUILTIN_TRANSPORTS='UDPv4', HEADLESS='1', NAV2='0', RVIZ='0',
|
||||
LOCALIZATION='lio', LIO_MODE='mapping' if args.profile == 'mapping' else 'localization',
|
||||
LIO_MAP=str(args.map.resolve()), LIO_EXPORT_MAP=str(args.map.resolve()),
|
||||
SENTRY_LOG=str((args.output/'stack.log').resolve()))
|
||||
(args.output/'runtime.json').write_text(json.dumps({'ROS_DOMAIN_ID': os.environ['ROS_DOMAIN_ID'],
|
||||
'GZ_PARTITION': os.environ['GZ_PARTITION'], 'duration_sec': args.duration,
|
||||
'profile': args.profile, 'IMU_sensor_noise': 'zero', 'control_input': 'wheel odometry only'}, indent=2))
|
||||
SENTRY_LOG=str((args.output/'stack.log').resolve()),
|
||||
SENTRY_RUNTIME_DIR=str((args.output/'runtime').resolve()))
|
||||
if survey is not None:
|
||||
# NAV2=0 and this branch starts neither AMCL nor LIO. The survey is offline.
|
||||
os.environ['LOCALIZATION'] = 'amcl'
|
||||
os.environ.setdefault('ROS_LOG_DIR', str((args.output/'ros_log').resolve()))
|
||||
os.environ.setdefault('XDG_CACHE_HOME', str((args.output/'cache').resolve()))
|
||||
(args.output/'runtime.json').write_text(json.dumps({
|
||||
'ROS_DOMAIN_ID': os.environ['ROS_DOMAIN_ID'], 'GZ_PARTITION': os.environ['GZ_PARTITION'],
|
||||
'duration_sec': args.duration, 'profile': args.profile, 'survey': survey, 'IMU_sensor_noise': 'zero',
|
||||
'control_input': 'known stationary survey coordinates' if survey else 'wheel odometry',
|
||||
}, indent=2))
|
||||
processes = []
|
||||
log_handles = []
|
||||
rclpy.init()
|
||||
driver = Driver(args.profile)
|
||||
surveyed = []
|
||||
try:
|
||||
processes.append(subprocess.Popen(['bash', str(workspace/'scripts/sentry_up.sh')], start_new_session=True,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, cwd=workspace))
|
||||
log = open(args.output/'record.log', 'w', encoding='utf8')
|
||||
log_handles.append(log)
|
||||
recorder = subprocess.Popen([str(binary/'field_localization_record'), '--ros-args', '-p', 'use_sim_time:=true',
|
||||
'-p', f'output_directory:={args.output.resolve()}', '-p', f'duration_sec:={args.duration}'],
|
||||
recorder = subprocess.Popen([str(recorder_exe), '--ros-args', '-p', 'use_sim_time:=true',
|
||||
'-p', f'output_directory:={args.output.resolve()}', '-p', f'duration_sec:={args.duration}',
|
||||
'-p', f'point_cloud_topic:={cloud_topic}'],
|
||||
stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
|
||||
processes.append(recorder)
|
||||
deadline = time.monotonic() + max(600, args.duration*10)
|
||||
@@ -133,8 +174,22 @@ def main():
|
||||
now = driver.get_clock().now().nanoseconds*1e-9
|
||||
if start is None:
|
||||
start = now
|
||||
if survey is None:
|
||||
driver.drive(now-start)
|
||||
if now-start > last_print+10:
|
||||
elif len(surveyed) < len(survey) and (not surveyed or
|
||||
now >= surveyed[-1]['command_time'] + arena_survey.STATION_SECONDS + 0.1):
|
||||
if not surveyed and (args.output/'scans.csv').stat().st_size == 0:
|
||||
if now-start > 5:
|
||||
raise RuntimeError(f'no LiDAR scans received on {cloud_topic}')
|
||||
continue
|
||||
point = survey[len(surveyed)]
|
||||
arena_survey.set_station(gz_exe, point, os.environ['GZ_PARTITION'])
|
||||
# Sample the newest received /clock after the synchronous service.
|
||||
for _ in range(10):
|
||||
rclpy.spin_once(driver, timeout_sec=0)
|
||||
surveyed.append({'goal': point, 'command_time': driver.get_clock().now().nanoseconds*1e-9})
|
||||
print(f'survey station {len(surveyed)}/{len(survey)} {point}', flush=True)
|
||||
if survey is None and now-start > last_print+10:
|
||||
last_print = now-start
|
||||
print(f'{args.profile}: {last_print:.1f}/{args.duration:.1f} simulated seconds; odom pose={driver.pose}', flush=True)
|
||||
driver.publisher.publish(Twist())
|
||||
@@ -142,6 +197,14 @@ def main():
|
||||
raise RuntimeError('capture deadline exceeded')
|
||||
if recorder.returncode or not (args.output/'complete.txt').exists():
|
||||
raise RuntimeError('recorder failed; inspect record.log')
|
||||
if survey is not None:
|
||||
if len(surveyed) != len(survey):
|
||||
raise RuntimeError(f'survey reached only {len(surveyed)}/{len(survey)} stations')
|
||||
selection = list(arena_survey.selected_clouds(args.output, surveyed))
|
||||
arena_survey.evaluate_stations(args.output, selection)
|
||||
point_count = arena_survey.build_map(args.output, selection, args.map)
|
||||
print(f'survey complete: {len(selection)} stations, {point_count} voxels; {args.map}', flush=True)
|
||||
return
|
||||
if args.profile == 'mapping':
|
||||
client = driver.create_client(Trigger, '/field_localization/save_map')
|
||||
if not client.wait_for_service(timeout_sec=5):
|
||||
@@ -158,6 +221,8 @@ def main():
|
||||
raise RuntimeError(f'TF validation failed: {tf_summary}')
|
||||
print(f'capture complete: {args.output}; TF validation={tf_summary}', flush=True)
|
||||
finally:
|
||||
if survey is not None:
|
||||
(args.output/'survey_progress.json').write_text(json.dumps(surveyed, indent=2))
|
||||
driver.publisher.publish(Twist())
|
||||
for process in reversed(processes):
|
||||
if process.poll() is None:
|
||||
|
||||
+18
-46
@@ -11,7 +11,6 @@
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
@@ -29,6 +28,8 @@ from sensor_msgs.msg import PointCloud2, LaserScan
|
||||
from nav_msgs.msg import Odometry, OccupancyGrid
|
||||
from tf2_ros import Buffer, TransformListener
|
||||
|
||||
import project_env
|
||||
|
||||
|
||||
# 期望处于 ACTIVE 的节点(缺了哪个,导航就会缺一块能力)
|
||||
#
|
||||
@@ -96,53 +97,17 @@ def parse_gz_pose(out):
|
||||
return None
|
||||
|
||||
|
||||
def _gz_bin():
|
||||
"""返回 gz 可执行文件路径(系统安装的那个),找不到返回 None。
|
||||
|
||||
不写死 `/usr/bin/gz`:换台机器 gz 可能装在别处。
|
||||
优先用 tools/project_env.py 的统一探测逻辑(同样支持 GZ_BIN 覆盖)。
|
||||
"""
|
||||
try:
|
||||
import project_env # noqa: PLC0415 (同目录模块,按需导入)
|
||||
gz = project_env.find_gz_bin()
|
||||
if gz is not None:
|
||||
return gz
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
for cand in ('/usr/bin/gz', '/usr/local/bin/gz'):
|
||||
if os.access(cand, os.X_OK):
|
||||
return cand
|
||||
return shutil.which('gz')
|
||||
|
||||
|
||||
def gz_model_pose(model_name):
|
||||
"""从 Gazebo 读模型的世界位姿,返回 (x, y, z, roll, pitch, yaw) 或 None。
|
||||
|
||||
为什么要绕道 gz:ROS 里没有独立的真值来源 ——
|
||||
`map -> base_link` 是由「静态 map->odom + 轮速里程计」拼出来的,
|
||||
它无法证明车真的在哪。Gazebo 的服务端才是真值。
|
||||
|
||||
坑:sentry_up.sh 把仿真跑在 `GZ_PARTITION`(默认 sentry)分区里,
|
||||
新开的终端如果不带这个变量,`gz model` 会报
|
||||
「Service call to [/gazebo/worlds] timed out」,看起来像仿真没跑。
|
||||
"""
|
||||
partition = os.environ.get('GZ_PARTITION', 'sentry')
|
||||
env = dict(os.environ)
|
||||
env['GZ_PARTITION'] = partition
|
||||
# 必须用系统版 gz 并清掉 LD_LIBRARY_PATH,否则会加载 ROS vendor 的库,
|
||||
# 和服务端不是同一套。
|
||||
env.pop('LD_LIBRARY_PATH', None)
|
||||
gz_bin = _gz_bin()
|
||||
if gz_bin is None:
|
||||
return None
|
||||
cmd = [str(gz_bin), 'model', '-m', model_name, '-p']
|
||||
"""Read the model pose from Gazebo in the simulation partition."""
|
||||
gz = project_env.find_gz_bin()
|
||||
env_partition = os.environ.get('GZ_PARTITION') or 'sentry'
|
||||
try:
|
||||
out = subprocess.run(cmd, env=env, capture_output=True, text=True,
|
||||
timeout=10).stdout
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
result = project_env.run_gz(
|
||||
gz, 'model', '-m', model_name, '-p', timeout=10,
|
||||
partition=env_partition)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return None
|
||||
return parse_gz_pose(out)
|
||||
return parse_gz_pose(result.stdout) if result.returncode == 0 else None
|
||||
|
||||
|
||||
def main():
|
||||
@@ -280,7 +245,14 @@ def main():
|
||||
|
||||
# ---------- 4. 定位真值对照 ----------
|
||||
print('\n=== 4. 定位真值对照 ===')
|
||||
try:
|
||||
truth = gz_model_pose('sentry')
|
||||
except project_env.ProbeError as error:
|
||||
truth = None
|
||||
if os.environ.get('GZ_BIN'):
|
||||
problems.append(str(error))
|
||||
else:
|
||||
print(f' ⚠️ {error}')
|
||||
tf_pos = None
|
||||
try:
|
||||
got = buf.lookup_transform('map', 'base_link', rclpy.time.Time(),
|
||||
@@ -292,7 +264,7 @@ def main():
|
||||
if truth is None:
|
||||
print(' ⚠️ 拿不到 Gazebo 真值(仿真没在跑,或 GZ_PARTITION 对不上)')
|
||||
print(' 手动试:GZ_PARTITION=%s gz model -m sentry -p'
|
||||
% os.environ.get('GZ_PARTITION', 'sentry'))
|
||||
% (os.environ.get('GZ_PARTITION') or 'sentry'))
|
||||
else:
|
||||
gx, gy = truth[0], truth[1]
|
||||
print(' [真值] Gazebo 世界坐标 (%.3f, %.3f)' % (gx, gy))
|
||||
|
||||
+241
-196
@@ -1,252 +1,297 @@
|
||||
#!/usr/bin/env python3
|
||||
"""可移植的环境探测(Python 版),和 `scripts/env_common.sh` 保持同一套规则。
|
||||
|
||||
规则(两边一致):
|
||||
|
||||
1. **一切都能被环境变量覆盖** —— 探测只提供合理默认值,不是唯一真相。
|
||||
2. **探测失败要吵** —— 宁可启动时报错,也别带着错路径跑到一半。
|
||||
3. **不写死发行版 / 版本 / 平台三元组** —— 换机器、换 ROS 版本、
|
||||
换 Gazebo 大版本、换迁移包日期,都不该需要改代码。
|
||||
|
||||
覆盖用的环境变量:
|
||||
|
||||
=============== ==========================================
|
||||
变量 作用
|
||||
=============== ==========================================
|
||||
ROS_SETUP 直接指定 setup.bash 全路径
|
||||
ROS_DISTRO ROS 发行版名(配合 /opt/ros/<名>/setup.bash)
|
||||
SENTRY_BIN_DIR xmake 产物目录
|
||||
GZ_BIN Gazebo 可执行文件
|
||||
GZ_FORCE_VERSION gz --force-version 的值
|
||||
SENTRY_FIELD_ROOT 场地迁移包根目录
|
||||
SENTRY_MAP_YAML 栅格图 yaml 全路径
|
||||
=============== ==========================================
|
||||
|
||||
用法::
|
||||
|
||||
import sys
|
||||
sys.path.insert(0, str(WS / 'tools'))
|
||||
import project_env
|
||||
bin_dir = project_env.find_bin_dir(WS)
|
||||
"""
|
||||
"""Shared environment discovery for the simulation launchers and tools."""
|
||||
|
||||
import argparse
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
# xmake 会产出的可执行文件,用来反推产物目录。
|
||||
_KNOWN_BINARIES = ('self_filter', 'nav_client', 'patrol', 'odom_tf', 'field_localization_node')
|
||||
|
||||
# 系统 gz 的常见安装位置(按优先级)。
|
||||
WORKSPACE = Path(__file__).resolve().parents[1]
|
||||
_KNOWN_BINARIES = ('self_filter', 'nav_client', 'patrol', 'odom_tf', 'cmd_vel_relay',
|
||||
'field_localization_node', 'field_localization_record', 'field_localization_replay')
|
||||
_GZ_CANDIDATES = ('/usr/bin/gz', '/usr/local/bin/gz', '/opt/gz/bin/gz')
|
||||
_GZ_VERSION_TIMEOUT = 5
|
||||
_FIELD_PACKAGE = Path('src/guodong_sentry_sim')
|
||||
|
||||
|
||||
class ProbeError(RuntimeError):
|
||||
"""A required setting is missing or points to an unusable path."""
|
||||
|
||||
|
||||
def require_file(path, name):
|
||||
path = Path(path).absolute()
|
||||
if not path.is_file():
|
||||
raise ProbeError(f'{name} 必须指向普通文件: {path}')
|
||||
return path
|
||||
|
||||
|
||||
def require_directory(path, name):
|
||||
path = Path(path).absolute()
|
||||
if not path.is_dir():
|
||||
raise ProbeError(f'{name} 必须指向目录: {path}')
|
||||
return path
|
||||
|
||||
|
||||
def is_executable(path):
|
||||
return Path(path).is_file() and os.access(path, os.X_OK)
|
||||
|
||||
|
||||
def require_executable(path, name):
|
||||
path = Path(path).absolute()
|
||||
if not is_executable(path):
|
||||
raise ProbeError(f'{name} 必须指向可执行的普通文件: {path}')
|
||||
return path
|
||||
|
||||
|
||||
def find_ros_setup():
|
||||
"""返回要 source 的 ROS `setup.bash` 路径;找不到返回 None。
|
||||
|
||||
优先级:`ROS_SETUP` → `ROS_INSTALL_ROOT/setup.bash` →
|
||||
`/opt/ros/<ROS_DISTRO>/setup.bash` → `/opt/ros/*/setup.bash` 里版本号最大的一个。
|
||||
|
||||
已经 source 过(`AMENT_PREFIX_PATH` 非空)时返回 None —— 调用方不该重复 source,
|
||||
否则 PATH 会越叠越长。
|
||||
"""
|
||||
"""Return the ROS setup path, or None when ROS is already sourced."""
|
||||
explicit = os.environ.get('ROS_SETUP')
|
||||
setup = require_file(explicit, 'ROS_SETUP') if explicit else None
|
||||
if os.environ.get('AMENT_PREFIX_PATH') and shutil.which('ros2'):
|
||||
return None
|
||||
|
||||
explicit = os.environ.get('ROS_SETUP')
|
||||
if explicit:
|
||||
p = Path(explicit)
|
||||
return p if p.is_file() else None
|
||||
if setup is not None:
|
||||
return setup
|
||||
|
||||
root = os.environ.get('ROS_INSTALL_ROOT')
|
||||
if root and (Path(root) / 'setup.bash').is_file():
|
||||
return Path(root) / 'setup.bash'
|
||||
if root:
|
||||
setup = Path(root) / 'setup.bash'
|
||||
if setup.is_file():
|
||||
return setup.absolute()
|
||||
|
||||
distro = os.environ.get('ROS_DISTRO')
|
||||
if distro:
|
||||
p = Path('/opt/ros') / distro / 'setup.bash'
|
||||
if p.is_file():
|
||||
return p
|
||||
setup = Path('/opt/ros') / distro / 'setup.bash'
|
||||
if setup.is_file():
|
||||
return setup
|
||||
|
||||
found = sorted(Path('/opt/ros').glob('*/setup.bash'))
|
||||
if not found:
|
||||
return None
|
||||
# 版本号最大 —— `lyrical` > `kilted` > `jazzy` > `iron` > `humble` 这种名字
|
||||
# 排不出来,所以退化成"取最后一个",并在多于一个时提醒调用方。
|
||||
return found[-1]
|
||||
candidates = sorted(
|
||||
(p for p in Path('/opt/ros').glob('*/setup.bash') if p.is_file()),
|
||||
key=lambda p: ([int(part) if i % 2 else part for i, part in
|
||||
enumerate(re.split(r'([0-9]+)', p.parent.name))], p.parent.name),
|
||||
)
|
||||
if not candidates:
|
||||
raise ProbeError('找不到 ROS 2 setup.bash。请加载 ROS 环境或设置 ROS_SETUP。')
|
||||
if len(candidates) > 1:
|
||||
print(f'[env] 警告: 发现多个 ROS 安装,按目录名排序选择 {candidates[-1]}', file=sys.stderr)
|
||||
return candidates[-1]
|
||||
|
||||
|
||||
def ros_setup_candidates():
|
||||
"""列出机器上所有 ROS `setup.bash`,用于在多版本时给出提示。"""
|
||||
return sorted(Path('/opt/ros').glob('*/setup.bash'))
|
||||
def find_bin_dir(ws=WORKSPACE):
|
||||
"""Choose a single build directory without mixing targets from different builds."""
|
||||
for name in ('SENTRY_BIN_DIR', 'NAV_BIN_DIR'):
|
||||
if override := os.environ.get(name):
|
||||
return require_directory(override, name)
|
||||
|
||||
|
||||
def find_bin_dir(ws):
|
||||
"""返回 xmake 产物目录(含 `self_filter` / `nav_client` 等的那个)。
|
||||
|
||||
**现行布局是 `build/bin/`** —— `src/sentry_nav/xmake.lua` 里每个 target 都
|
||||
`set_targetdir("$(builddir)/bin")`,故意不用 xmake 默认的平台三元组,
|
||||
免得 `build/<平台>/<架构>/<模式>` 这种串被抄进文档后换机器就失效。
|
||||
|
||||
仍然兼容老布局(`build/*/*/{release,debug}`),因为别的 checkout 可能还没重建。
|
||||
"""
|
||||
env = os.environ.get('SENTRY_BIN_DIR') or os.environ.get('NAV_BIN_DIR')
|
||||
if env:
|
||||
return Path(env)
|
||||
|
||||
build = Path(ws) / 'build'
|
||||
|
||||
# ① 现行布局:build/bin/
|
||||
build = Path(ws).absolute() / 'build'
|
||||
unified = build / 'bin'
|
||||
if unified.is_dir() and any((unified / n).is_file() for n in _KNOWN_BINARIES):
|
||||
if any(is_executable(unified / name) for name in _KNOWN_BINARIES):
|
||||
return unified
|
||||
|
||||
# ② 老布局:build/<平台>/<架构>/<模式>/
|
||||
for mode in ('release', 'debug'):
|
||||
for d in sorted(build.glob(f'*/*/{mode}')):
|
||||
if any((d / n).is_file() for n in _KNOWN_BINARIES):
|
||||
return d
|
||||
|
||||
# ③ 还没编译过:返回现行布局的位置
|
||||
for candidate in sorted(build.glob(f'*/*/{mode}')):
|
||||
if any(is_executable(candidate / name) for name in _KNOWN_BINARIES):
|
||||
return candidate
|
||||
return unified
|
||||
|
||||
|
||||
def find_gz_bin():
|
||||
"""返回 gz 可执行文件路径;找不到返回 None。
|
||||
|
||||
为什么要挑:`source` 过 ROS 之后,`$PATH` 上的 `gz` 是 `gz_tools_vendor`
|
||||
里那个,带着 vendor 的 RUNPATH,会加载缺 cpu-lidar 插件的 vendor 版 gz-sim。
|
||||
所以系统安装的位置优先。
|
||||
"""
|
||||
env = os.environ.get('GZ_BIN')
|
||||
if env:
|
||||
p = Path(env)
|
||||
return p if os.access(p, os.X_OK) else None
|
||||
|
||||
for cand in _GZ_CANDIDATES:
|
||||
if os.access(cand, os.X_OK):
|
||||
return Path(cand)
|
||||
|
||||
which = shutil.which('gz')
|
||||
return Path(which) if which else None
|
||||
"""Prefer system Gazebo, validating an explicit override before any fallback."""
|
||||
if override := os.environ.get('GZ_BIN'):
|
||||
return require_executable(override, 'GZ_BIN')
|
||||
for path in _GZ_CANDIDATES:
|
||||
if is_executable(path):
|
||||
return Path(path)
|
||||
if path := shutil.which('gz'):
|
||||
return require_executable(path, 'gz')
|
||||
raise ProbeError('找不到 Gazebo 的 gz 可执行文件。请设置 GZ_BIN。')
|
||||
|
||||
|
||||
def gz_version_args():
|
||||
"""返回 `['--force-version', '<主版本>']`,取不到就返回 `[]`。
|
||||
def run_gz(gz, *args, timeout, partition=None):
|
||||
"""Run a Gazebo query in its own process group with a wall-clock deadline."""
|
||||
env = os.environ.copy()
|
||||
env.pop('LD_LIBRARY_PATH', None)
|
||||
if partition is not None:
|
||||
env['GZ_PARTITION'] = partition
|
||||
command = [str(gz), *args]
|
||||
# Files let us read results after a timeout even if a descendant still holds
|
||||
# an output descriptor. Only the process group started here is signalled.
|
||||
with tempfile.TemporaryFile() as stdout, tempfile.TemporaryFile() as stderr:
|
||||
process = subprocess.Popen(command, env=env, start_new_session=True,
|
||||
stdout=stdout, stderr=stderr)
|
||||
try:
|
||||
process.wait(timeout=timeout)
|
||||
except BaseException:
|
||||
try:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
process.wait()
|
||||
raise
|
||||
stdout.seek(0)
|
||||
stderr.seek(0)
|
||||
return subprocess.CompletedProcess(command, process.returncode,
|
||||
stdout.read().decode(errors='replace'),
|
||||
stderr.read().decode(errors='replace'))
|
||||
|
||||
写死 10 的话,装了 gz 11 就跑不起来。`GZ_FORCE_VERSION` 可强制指定。
|
||||
"""
|
||||
forced = os.environ.get('GZ_FORCE_VERSION')
|
||||
if forced:
|
||||
return ['--force-version', str(forced)]
|
||||
|
||||
gz = find_gz_bin()
|
||||
def gz_version_args(gz=None):
|
||||
"""Return force-version arguments, or warn and let Gazebo choose its default."""
|
||||
if gz is None:
|
||||
return []
|
||||
gz = find_gz_bin()
|
||||
if forced := os.environ.get('GZ_FORCE_VERSION'):
|
||||
return ['--force-version', forced]
|
||||
|
||||
try:
|
||||
out = subprocess.run([str(gz), 'sim', '--version'],
|
||||
capture_output=True, text=True, timeout=15)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
result = run_gz(gz, 'sim', '--version', timeout=_GZ_VERSION_TIMEOUT)
|
||||
if result.returncode:
|
||||
reason = f'退出码 {result.returncode}'
|
||||
else:
|
||||
version = re.match(r'^\s*([0-9]+)(?=\.|\s|$)', result.stdout.strip() or result.stderr.strip())
|
||||
if version:
|
||||
return ['--force-version', version[1]]
|
||||
reason = '无法解析版本'
|
||||
except subprocess.TimeoutExpired:
|
||||
reason = f'超时({_GZ_VERSION_TIMEOUT:g} 秒)'
|
||||
except OSError as error:
|
||||
reason = str(error)
|
||||
print(f'[env] 警告: {gz} sim --version {reason},使用 Gazebo 默认版本。'
|
||||
'可通过 GZ_FORCE_VERSION 指定主版本。', file=sys.stderr)
|
||||
return []
|
||||
|
||||
lines = (out.stdout or out.stderr or '').strip().splitlines()
|
||||
if not lines:
|
||||
return []
|
||||
m = re.match(r'\s*(\d+)', lines[0])
|
||||
return ['--force-version', m.group(1)] if m else []
|
||||
|
||||
def wait_gz_clock(gz, gazebo_pid=None):
|
||||
"""Wait for the selected Gazebo transport to advertise /clock."""
|
||||
raw_timeout = os.environ.get('BRIDGE_WAIT_TIMEOUT') or '120'
|
||||
try:
|
||||
timeout = float(raw_timeout)
|
||||
except ValueError:
|
||||
timeout = 0
|
||||
if not math.isfinite(timeout) or timeout <= 0:
|
||||
raise ProbeError(f'BRIDGE_WAIT_TIMEOUT 必须为正数: {raw_timeout}')
|
||||
|
||||
deadline = time.monotonic() + timeout
|
||||
while (remaining := deadline - time.monotonic()) > 0:
|
||||
if gazebo_pid is not None:
|
||||
try:
|
||||
os.kill(gazebo_pid, 0)
|
||||
except ProcessLookupError as error:
|
||||
raise ProbeError('Gazebo 启动失败,进程已退出') from error
|
||||
try:
|
||||
# Listing topics waits for a full discovery cycle (over two seconds on this host).
|
||||
result = run_gz(gz, 'topic', '-e', '-t', '/clock', '-n', '1',
|
||||
timeout=min(2, remaining))
|
||||
if result.returncode == 0 and result.stdout.strip():
|
||||
return
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
time.sleep(max(0, min(1, deadline - time.monotonic())))
|
||||
raise ProbeError(
|
||||
f'等待 Gazebo /clock 超时({timeout:g} 秒),请检查 GZ_PARTITION='
|
||||
f'{os.environ.get("GZ_PARTITION") or "sentry"}')
|
||||
|
||||
|
||||
def find_field_root(ws):
|
||||
"""返回场地迁移包根目录;找不到返回 None。
|
||||
|
||||
不写死 `RMUL2027_map_transfer_20261016_STEP_R1` —— 换一版迁移包日期就变了。
|
||||
找的是「含 `src/guodong_sentry_sim` 的那一层」。
|
||||
"""
|
||||
env = os.environ.get('SENTRY_FIELD_ROOT')
|
||||
if env:
|
||||
return Path(env)
|
||||
|
||||
ws = Path(ws)
|
||||
for p in sorted(ws.glob('field/*/src/guodong_sentry_sim')):
|
||||
if p.is_dir():
|
||||
return p.parent.parent
|
||||
|
||||
for p in sorted((Path.home() / 'Gazebo_projects').glob(
|
||||
'*map_transfer*/src/guodong_sentry_sim')):
|
||||
if p.is_dir():
|
||||
return p.parent.parent
|
||||
|
||||
return None
|
||||
def find_field_root(ws=WORKSPACE, *, explicit=None):
|
||||
if explicit:
|
||||
return require_directory(explicit, 'field_root')
|
||||
if override := os.environ.get('SENTRY_FIELD_ROOT'):
|
||||
return require_directory(override, 'SENTRY_FIELD_ROOT')
|
||||
for parent, pattern in ((Path(ws).absolute() / 'field', '*'),
|
||||
(Path.home() / 'Gazebo_projects', '*map_transfer*')):
|
||||
for candidate in sorted(parent.glob(pattern)):
|
||||
if (candidate / _FIELD_PACKAGE).is_dir():
|
||||
return candidate
|
||||
raise ProbeError('找不到场地迁移包。请设置 SENTRY_FIELD_ROOT。')
|
||||
|
||||
|
||||
def find_map_yaml(field_root):
|
||||
"""返回栅格图 yaml 路径;找不到返回 None。优先 `rmul_2027.yaml`。"""
|
||||
env = os.environ.get('SENTRY_MAP_YAML')
|
||||
if env:
|
||||
return Path(env)
|
||||
|
||||
def find_map_yaml(field_root=None, *, explicit=None, ws=WORKSPACE):
|
||||
if explicit:
|
||||
return require_file(explicit, 'map')
|
||||
if override := os.environ.get('SENTRY_MAP_YAML'):
|
||||
return require_file(override, 'SENTRY_MAP_YAML')
|
||||
if field_root is None:
|
||||
return None
|
||||
|
||||
maps = Path(field_root) / 'src' / 'guodong_sentry_sim' / 'maps'
|
||||
field_root = find_field_root(ws)
|
||||
maps = Path(field_root) / _FIELD_PACKAGE / 'maps'
|
||||
preferred = maps / 'rmul_2027' / 'rmul_2027.yaml'
|
||||
if preferred.is_file():
|
||||
return preferred
|
||||
|
||||
cands = sorted(maps.glob('*/*.yaml'))
|
||||
return cands[0] if cands else None
|
||||
candidates = sorted(p for p in maps.glob('*/*.yaml') if p.is_file())
|
||||
for candidate in candidates:
|
||||
if candidate.name == 'rmul_2027.yaml':
|
||||
return candidate
|
||||
if candidates:
|
||||
return candidates[0]
|
||||
raise ProbeError(f'{maps} 下找不到栅格图 YAML。请设置 SENTRY_MAP_YAML。')
|
||||
|
||||
|
||||
def report(ws):
|
||||
"""打印所有探测结果,排查路径问题时用。"""
|
||||
field_root = find_field_root(ws)
|
||||
setup = find_ros_setup()
|
||||
if setup:
|
||||
ros_line = str(setup)
|
||||
elif os.environ.get('AMENT_PREFIX_PATH'):
|
||||
ros_line = f'<已 source: {os.environ["AMENT_PREFIX_PATH"]}>'
|
||||
else:
|
||||
ros_line = '<找不到>'
|
||||
print(f' ROS setup : {ros_line}')
|
||||
print(f' BIN_DIR : {find_bin_dir(ws)}')
|
||||
print(f' GZ_BIN : {find_gz_bin()}')
|
||||
print(f' gz 版本参数 : {" ".join(gz_version_args()) or "<无>"}')
|
||||
bin_dir = find_bin_dir(ws)
|
||||
field_root = find_field_root(ws)
|
||||
map_yaml = find_map_yaml(field_root)
|
||||
gz = find_gz_bin()
|
||||
versions = ' '.join(gz_version_args(gz))
|
||||
print(f'仓库根: {ws}')
|
||||
print(f' ROS setup : {setup or "<已 source>"}')
|
||||
print(f' BIN_DIR : {bin_dir}')
|
||||
print(f' GZ_BIN : {gz}')
|
||||
print(f' gz 版本参数 : {versions or "<无>"}')
|
||||
print(f' FIELD_ROOT : {field_root}')
|
||||
print(f' MAP_YAML : {find_map_yaml(field_root)}')
|
||||
print(f' MAP_YAML : {map_yaml}')
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('workspace', type=Path, nargs='?', default=WORKSPACE)
|
||||
queries = parser.add_mutually_exclusive_group()
|
||||
for query in ('bin-dir', 'field', 'map', 'gz', 'gz-version-args', 'ros-setup'):
|
||||
queries.add_argument(f'--{query}', dest='query', action='store_const', const=query)
|
||||
for query in ('gz-version-args-lines', 'wait-gz-clock'):
|
||||
queries.add_argument(f'--{query}', dest='query', action='store_const', const=query,
|
||||
help=argparse.SUPPRESS)
|
||||
parser.add_argument('--field-root', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--gazebo-pid', type=int, help=argparse.SUPPRESS)
|
||||
args = parser.parse_args(argv)
|
||||
if args.field_root is not None and args.query != 'map':
|
||||
parser.error('--field-root requires --map')
|
||||
if args.gazebo_pid is not None and (args.query != 'wait-gz-clock' or args.gazebo_pid <= 0):
|
||||
parser.error('--gazebo-pid requires --wait-gz-clock and a positive PID')
|
||||
|
||||
try:
|
||||
ws = require_directory(args.workspace, 'workspace')
|
||||
match args.query:
|
||||
case 'bin-dir':
|
||||
print(find_bin_dir(ws))
|
||||
case 'field':
|
||||
print(find_field_root(ws))
|
||||
case 'map':
|
||||
print(find_map_yaml(args.field_root, ws=ws))
|
||||
case 'gz':
|
||||
print(find_gz_bin())
|
||||
case 'gz-version-args' | 'gz-version-args-lines':
|
||||
separator = '\n' if args.query == 'gz-version-args-lines' else ' '
|
||||
versions = gz_version_args()
|
||||
if versions:
|
||||
print(separator.join(versions))
|
||||
elif args.query == 'gz-version-args':
|
||||
print()
|
||||
case 'ros-setup':
|
||||
print(find_ros_setup() or '')
|
||||
case 'wait-gz-clock':
|
||||
wait_gz_clock(find_gz_bin(), args.gazebo_pid)
|
||||
case None:
|
||||
report(ws)
|
||||
except (ProbeError, OSError) as error:
|
||||
print(f'[env] {error}', file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# 支持直接从命令行取单个值,方便写进文档当可移植的一行命令:
|
||||
# NAV=$(python3 tools/project_env.py --bin-dir)/nav_client
|
||||
# python3 tools/project_env.py --map / --field / --gz / --bin-dir
|
||||
argv = sys.argv[1:]
|
||||
ws_arg = str(Path(__file__).resolve().parents[1])
|
||||
if argv and Path(argv[0]).is_dir():
|
||||
ws_arg = argv.pop(0)
|
||||
|
||||
if argv:
|
||||
opt = argv[0]
|
||||
if opt == '--bin-dir':
|
||||
print(find_bin_dir(ws_arg))
|
||||
elif opt == '--field':
|
||||
print(find_field_root(ws_arg))
|
||||
elif opt == '--map':
|
||||
print(find_map_yaml(find_field_root(ws_arg)))
|
||||
elif opt == '--gz':
|
||||
print(find_gz_bin())
|
||||
elif opt == '--gz-version-args':
|
||||
print(' '.join(gz_version_args()))
|
||||
elif opt == '--ros-setup':
|
||||
print(find_ros_setup() or '')
|
||||
else:
|
||||
print(f'未知选项 {opt},可用:--bin-dir --field --map --gz '
|
||||
'--gz-version-args --ros-setup', file=sys.stderr)
|
||||
sys.exit(2)
|
||||
sys.exit(0)
|
||||
|
||||
print(f'仓库根: {ws_arg}')
|
||||
report(ws_arg)
|
||||
sys.exit(main())
|
||||
@@ -5,14 +5,23 @@ import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
import project_env
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--binary',type=Path,default=Path(__file__).resolve().parents[1]/'build/bin/cmd_vel_relay')
|
||||
parser.add_argument('--binary', type=Path)
|
||||
args=parser.parse_args()
|
||||
try:
|
||||
binary = args.binary or project_env.find_bin_dir()/'cmd_vel_relay'
|
||||
binary = project_env.require_executable(binary, 'cmd_vel_relay')
|
||||
except project_env.ProbeError as error:
|
||||
parser.exit(1, f'{parser.prog}: {error}\n')
|
||||
os.environ.update(ROS_DOMAIN_ID=str(130+int(uuid.uuid4().hex[:4],16)%40),
|
||||
FASTDDS_BUILTIN_TRANSPORTS='UDPv4',ROS2CLI_DISABLE_DAEMON='1')
|
||||
import rclpy
|
||||
@@ -31,7 +40,7 @@ def main():
|
||||
return response
|
||||
services=[node.create_service(CancelGoal,name+'/_action/cancel_goal',cancel)
|
||||
for name in ['/navigate_to_pose','/navigate_through_poses']]
|
||||
process=subprocess.Popen([str(args.binary),'--ros-args','-p','navigation_mode:=true'],
|
||||
process=subprocess.Popen([str(binary),'--ros-args','-p','navigation_mode:=true'],
|
||||
start_new_session=True,stdout=subprocess.DEVNULL,stderr=subprocess.PIPE,text=True)
|
||||
checks=0
|
||||
def check(ok,message):
|
||||
@@ -9,6 +9,8 @@ import time
|
||||
import uuid
|
||||
from types import SimpleNamespace
|
||||
|
||||
INTERNAL_TOOLS = Path(__file__).resolve().parents[1] / '_internal'
|
||||
sys.path.insert(0, str(INTERNAL_TOOLS))
|
||||
from dds_environment import defaults
|
||||
|
||||
|
||||
@@ -73,7 +75,7 @@ def main():
|
||||
services = [node.create_service(GetParameters, '/lifecycle_manager_nav2/get_parameters', parameters),
|
||||
node.create_service(Trigger, '/lifecycle_manager_nav2/is_active', active)]
|
||||
services += [node.create_service(GetState, f'/{name}/get_state', state) for name in managed]
|
||||
command = [sys.executable, str(Path(__file__).with_name('nav2_startup.py'))]
|
||||
command = [sys.executable, str(INTERNAL_TOOLS / 'nav2_startup.py')]
|
||||
|
||||
def run(arguments):
|
||||
process = subprocess.Popen(command+arguments, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
||||
@@ -5,6 +5,7 @@ import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / '_internal'))
|
||||
from run_nav2 import stop_owned, supervise
|
||||
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Exercise the shared environment probes through both CLI entry points."""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
TOOLS = Path(__file__).resolve().parents[1]
|
||||
WORKSPACE = TOOLS.parent
|
||||
SCRIPTS = WORKSPACE / 'src/sentry_sim/scripts'
|
||||
sys.path.insert(0, str(TOOLS))
|
||||
import project_env
|
||||
|
||||
|
||||
class EnvironmentTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory(prefix='sentry env ')
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.root = Path(temp.name)
|
||||
self.env = os.environ.copy()
|
||||
self.env['PYTHONDONTWRITEBYTECODE'] = '1'
|
||||
for name in ('ROS_SETUP', 'ROS_INSTALL_ROOT', 'ROS_DISTRO', 'AMENT_PREFIX_PATH',
|
||||
'SENTRY_BIN_DIR', 'NAV_BIN_DIR', 'SENTRY_FIELD_ROOT', 'SENTRY_MAP_YAML',
|
||||
'GZ_BIN', 'GZ_FORCE_VERSION', 'BRIDGE_WAIT_TIMEOUT', 'GZ_PARTITION'):
|
||||
self.env.pop(name, None)
|
||||
|
||||
def run_command(self, command, **overrides):
|
||||
return subprocess.run(command, cwd=self.root, env={**self.env, **overrides},
|
||||
capture_output=True, text=True, timeout=12)
|
||||
|
||||
def cli(self, *args, **overrides):
|
||||
return self.run_command([sys.executable, str(TOOLS/'project_env.py'), *map(str, args)],
|
||||
**overrides)
|
||||
|
||||
def shell(self, *args, **overrides):
|
||||
return self.run_command(['bash', '-c', 'source "$1"; shift; "$@"',
|
||||
'env-test', str(SCRIPTS/'env_common.sh'), *map(str, args)],
|
||||
**overrides)
|
||||
|
||||
def executable(self, path, script='exit 0'):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text('#!/bin/bash\n' + script + '\n')
|
||||
path.chmod(0o755)
|
||||
return path
|
||||
|
||||
def expect_value(self, result, value):
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stdout, f'{value}\n')
|
||||
|
||||
def expect_error(self, result, text, code=1):
|
||||
self.assertEqual(result.returncode, code, result.stderr)
|
||||
self.assertEqual(result.stdout, '')
|
||||
self.assertIn(text, result.stderr)
|
||||
|
||||
def test_map_overrides(self):
|
||||
field = self.root/'field with spaces'
|
||||
field.mkdir()
|
||||
yaml = self.root/'custom map.yaml'
|
||||
yaml.touch()
|
||||
for bad in (self.root/'missing.yaml', field):
|
||||
with self.subTest(path=bad):
|
||||
self.expect_error(self.cli('--map', SENTRY_MAP_YAML=str(bad)), 'SENTRY_MAP_YAML')
|
||||
self.expect_error(self.shell('env_map_yaml', field, SENTRY_MAP_YAML=str(bad)),
|
||||
'SENTRY_MAP_YAML')
|
||||
self.expect_value(self.cli('--map', SENTRY_MAP_YAML=yaml.name), yaml)
|
||||
self.expect_value(self.shell('env_map_yaml', field, SENTRY_MAP_YAML=yaml.name), yaml)
|
||||
with patch.dict(os.environ, {'SENTRY_MAP_YAML': str(field)}):
|
||||
self.assertEqual(project_env.find_map_yaml(field, explicit=yaml), yaml)
|
||||
|
||||
def test_map_search_order(self):
|
||||
field = self.root/'field'
|
||||
maps = field/'src/guodong_sentry_sim/maps'
|
||||
canonical = maps/'rmul_2027/rmul_2027.yaml'
|
||||
named_first = maps/'a/rmul_2027.yaml'
|
||||
named_last = maps/'z/rmul_2027.yaml'
|
||||
fallback = maps/'a/001.yaml'
|
||||
for path in (canonical, named_first, named_last, fallback):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.touch()
|
||||
(maps/'a/000.yaml').mkdir()
|
||||
|
||||
def expect_map(path):
|
||||
self.expect_value(self.cli('--map', SENTRY_FIELD_ROOT=str(field)), path)
|
||||
self.expect_value(self.shell('env_map_yaml', field), path)
|
||||
|
||||
expect_map(canonical)
|
||||
canonical.unlink()
|
||||
expect_map(named_first)
|
||||
named_first.unlink()
|
||||
expect_map(named_last)
|
||||
named_last.unlink()
|
||||
expect_map(fallback)
|
||||
fallback.unlink()
|
||||
self.expect_error(self.cli('--map', SENTRY_FIELD_ROOT=str(field)), 'SENTRY_MAP_YAML')
|
||||
self.expect_error(self.shell('env_map_yaml', field), 'SENTRY_MAP_YAML')
|
||||
|
||||
def test_field_and_ros_setup_overrides(self):
|
||||
field = self.root/'field'
|
||||
other = self.root/'other field'
|
||||
field.mkdir()
|
||||
other.mkdir()
|
||||
self.expect_error(self.cli('--field', SENTRY_FIELD_ROOT=str(field/'missing')),
|
||||
'SENTRY_FIELD_ROOT')
|
||||
self.expect_error(self.shell('env_field_root', self.root,
|
||||
SENTRY_FIELD_ROOT=str(field/'missing')), 'SENTRY_FIELD_ROOT')
|
||||
self.expect_value(self.cli('--field', SENTRY_FIELD_ROOT=field.name), field)
|
||||
with patch.dict(os.environ, {'SENTRY_FIELD_ROOT': str(field)}):
|
||||
self.assertEqual(project_env.find_field_root(self.root, explicit=other), other)
|
||||
|
||||
setup = self.root/'setup with spaces.bash'
|
||||
setup.write_text('export SENTRY_SETUP_TEST=loaded\n')
|
||||
for invalid in (field, self.root/'missing.bash'):
|
||||
self.expect_error(self.cli('--ros-setup', ROS_SETUP=str(invalid)), 'ROS_SETUP')
|
||||
self.expect_error(self.shell('env_source_ros', ROS_SETUP=str(invalid)), 'ROS_SETUP')
|
||||
self.expect_value(self.cli('--ros-setup', ROS_SETUP=setup.name), setup)
|
||||
result = self.run_command(
|
||||
['bash', '-c', 'source "$1"; env_source_ros && printf "%s\\n" "$SENTRY_SETUP_TEST"',
|
||||
'env-test', str(SCRIPTS/'env_common.sh')], ROS_SETUP=setup.name)
|
||||
self.expect_value(result, 'loaded')
|
||||
ros2 = self.executable(self.root/'ros bin/ros2')
|
||||
self.expect_value(self.cli('--ros-setup', ROS_SETUP=str(setup), AMENT_PREFIX_PATH='/fake',
|
||||
PATH=f'{ros2.parent}:{self.env["PATH"]}'), '')
|
||||
|
||||
def test_cli_status_and_stdout(self):
|
||||
self.expect_error(self.cli('--unknown'), 'unrecognized arguments', code=2)
|
||||
self.expect_error(self.cli('--map', '--gz'), 'not allowed', code=2)
|
||||
self.expect_error(self.cli('--gz', '--field-root', self.root), 'requires --map', code=2)
|
||||
self.expect_error(self.cli('--bin-dir', SENTRY_BIN_DIR=str(self.root/'missing')),
|
||||
'SENTRY_BIN_DIR')
|
||||
with (patch.object(project_env, '_GZ_CANDIDATES', ()),
|
||||
patch.object(project_env.shutil, 'which', return_value=None),
|
||||
patch.dict(os.environ, {'GZ_BIN': ''})):
|
||||
with self.assertRaisesRegex(project_env.ProbeError, '找不到 Gazebo'):
|
||||
project_env.find_gz_bin()
|
||||
|
||||
def test_build_directory_priority_matches_shell(self):
|
||||
build = self.root/'build'
|
||||
unified = build/'bin'
|
||||
|
||||
def expect_bin(path, **overrides):
|
||||
self.expect_value(self.cli(self.root, '--bin-dir', **overrides), path)
|
||||
self.expect_value(self.shell('env_bin_dir', self.root, **overrides), path)
|
||||
|
||||
expect_bin(unified)
|
||||
debug = self.executable(build/'a/first/debug/self_filter')
|
||||
expect_bin(debug.parent)
|
||||
release_last = self.executable(build/'z/last/release/nav_client')
|
||||
release_first = self.executable(build/'a/second/release/odom_tf')
|
||||
(build/'a/first/release').mkdir()
|
||||
(build/'a/first/release/nav_client').touch()
|
||||
expect_bin(release_first.parent)
|
||||
(unified/'self_filter').mkdir(parents=True)
|
||||
(unified/'nav_client').touch()
|
||||
expect_bin(release_first.parent)
|
||||
self.executable(unified/'cmd_vel_relay')
|
||||
expect_bin(unified)
|
||||
expect_bin(release_last.parent, NAV_BIN_DIR=str(release_last.parent))
|
||||
expect_bin(release_first.parent, SENTRY_BIN_DIR=str(release_first.parent),
|
||||
NAV_BIN_DIR=str(release_last.parent))
|
||||
|
||||
def test_gz_executable_validation_matches_shell(self):
|
||||
fake = self.executable(self.root/'fake gazebo')
|
||||
alias = self.root/'link to gz'
|
||||
alias.symlink_to(fake)
|
||||
denied = self.root/'non-executable'
|
||||
denied.touch()
|
||||
for path in (self.root, denied, self.root/'missing'):
|
||||
with self.subTest(path=path):
|
||||
self.expect_error(self.cli('--gz', GZ_BIN=str(path)), 'GZ_BIN')
|
||||
self.expect_error(self.shell('env_gz_bin', GZ_BIN=str(path)), 'GZ_BIN')
|
||||
self.expect_error(self.cli('--gz-version-args', GZ_FORCE_VERSION='12',
|
||||
GZ_BIN=str(path)), 'GZ_BIN')
|
||||
self.expect_value(self.cli('--gz', GZ_BIN=alias.name), alias)
|
||||
self.expect_value(self.shell('env_gz_bin', GZ_BIN=alias.name), alias)
|
||||
|
||||
def test_version_and_explicit_override_matches_shell(self):
|
||||
fake = self.executable(self.root/'fake gz', '''
|
||||
if [[ "$*" != "sim --version" || -v LD_LIBRARY_PATH ]]; then exit 4; fi
|
||||
touch "$SENTRY_GZ_MARKER"
|
||||
echo ' 10.5.0 '
|
||||
''')
|
||||
marker = self.root/'probe-called'
|
||||
env = dict(GZ_BIN=str(fake), LD_LIBRARY_PATH='/test/vendor', SENTRY_GZ_MARKER=str(marker))
|
||||
self.expect_value(self.cli('--gz-version-args', **env), '--force-version 10')
|
||||
self.assertTrue(marker.is_file())
|
||||
self.expect_value(self.shell('env_gz_version_args', **env), '--force-version\n10')
|
||||
marker.unlink()
|
||||
self.expect_value(self.cli('--gz-version-args', GZ_FORCE_VERSION='12', **env),
|
||||
'--force-version 12')
|
||||
self.expect_value(self.shell('env_gz_version_args', GZ_FORCE_VERSION='12', **env),
|
||||
'--force-version\n12')
|
||||
self.assertFalse(marker.exists())
|
||||
|
||||
def test_version_nonzero_and_unparseable_warn_and_continue(self):
|
||||
fake = self.root/'gz'
|
||||
for script, reason in (("echo '10.0'; exit 7", '退出码 7'), ('echo unknown', '无法解析版本')):
|
||||
self.executable(fake, script)
|
||||
cli = self.cli('--gz-version-args', GZ_BIN=str(fake))
|
||||
shell = self.shell('env_gz_version_args', GZ_BIN=str(fake))
|
||||
self.expect_value(cli, '')
|
||||
self.assertIn(reason, cli.stderr)
|
||||
self.assertEqual(shell.returncode, 0, shell.stderr)
|
||||
self.assertEqual(shell.stdout, '')
|
||||
self.assertIn(reason, shell.stderr)
|
||||
|
||||
def test_version_timeout_stops_owned_process_group(self):
|
||||
marker = self.root/'child-pids'
|
||||
fake = self.executable(self.root/'slow gz', '''
|
||||
trap '' TERM
|
||||
sleep 30 &
|
||||
printf '%s %s\\n' "$$" "$!" > "$SENTRY_GZ_MARKER"
|
||||
wait
|
||||
''')
|
||||
start = time.monotonic()
|
||||
result = self.shell('env_gz_version_args', GZ_BIN=str(fake), SENTRY_GZ_MARKER=str(marker))
|
||||
elapsed = time.monotonic() - start
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stdout, '')
|
||||
self.assertIn('超时', result.stderr)
|
||||
self.assertGreaterEqual(elapsed, 5)
|
||||
self.assertLess(elapsed, 8)
|
||||
for pid in marker.read_text().split():
|
||||
try:
|
||||
state = Path(f'/proc/{pid}/stat').read_text().rsplit(')', 1)[1].split()[0]
|
||||
except FileNotFoundError:
|
||||
continue
|
||||
self.assertEqual(state, 'Z', f'Gazebo probe process {pid} is still live')
|
||||
|
||||
def test_bridge_does_not_start_without_clock(self):
|
||||
fake_gz = self.executable(self.root/'fake gz', '''
|
||||
[[ "$*" == 'topic -e -t /clock -n 1' && ! -v LD_LIBRARY_PATH ]] || exit 4
|
||||
sleep 30
|
||||
''')
|
||||
fake_ros2 = self.executable(self.root/'bin/ros2', 'echo "bridge started"')
|
||||
env = dict(BRIDGE_WAIT_TIMEOUT='0.3', GZ_BIN=str(fake_gz), LD_LIBRARY_PATH='/vendor',
|
||||
PATH=f'{fake_ros2.parent}:{self.env["PATH"]}', GZ_PARTITION='isolated_test')
|
||||
start = time.monotonic()
|
||||
result = self.run_command(['bash', str(SCRIPTS/'bridge_after_gz.sh')], **env)
|
||||
self.assertLess(time.monotonic() - start, 2)
|
||||
self.expect_error(result, '等待 Gazebo /clock 超时')
|
||||
self.assertIn('isolated_test', result.stderr)
|
||||
self.executable(fake_gz, '''
|
||||
[[ "$*" == 'topic -e -t /clock -n 1' && ! -v LD_LIBRARY_PATH ]] || exit 4
|
||||
echo 'sim { sec: 1 }'
|
||||
''')
|
||||
result = self.run_command(['bash', str(SCRIPTS/'bridge_after_gz.sh')], **env)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn('bridge started', result.stdout)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main(verbosity=2)
|
||||
@@ -1,334 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run an isolated Gazebo navigation scenario and score it using simulator truth."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
from collections import Counter
|
||||
|
||||
import rclpy
|
||||
from rclpy.node import Node
|
||||
from rclpy.parameter import Parameter
|
||||
from lifecycle_msgs.srv import GetState
|
||||
from tf2_msgs.msg import TFMessage
|
||||
from nav2_msgs.srv import IsPathValid
|
||||
from nav_msgs.msg import Odometry
|
||||
from geometry_msgs.msg import PoseStamped, Twist
|
||||
from rclpy.qos import qos_profile_sensor_data
|
||||
from std_msgs.msg import Bool
|
||||
from rcl_interfaces.srv import GetParameters
|
||||
from std_srvs.srv import Trigger
|
||||
from rclpy.utilities import get_rmw_implementation_identifier
|
||||
from nav2_startup import path_probe_request
|
||||
|
||||
from dds_environment import defaults as dds_defaults
|
||||
from lio_metrics import cylinder_clearance, metrics
|
||||
from verify_lio_stack import NODES, process_environment
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--map', type=Path, required=True)
|
||||
parser.add_argument('--launcher', choices=['shell', 'python'], default='shell')
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
parser.add_argument('--goal', nargs=2, type=float, metavar=('X', 'Y'))
|
||||
parser.add_argument('--domain', type=int, choices=range(1, 233), metavar='[1–232]',
|
||||
help='use an explicitly reserved ROS_DOMAIN_ID for parallel tests')
|
||||
parser.add_argument('--timeout', type=float, default=420.0,
|
||||
help='whole-stack validation deadline, including up to three startup attempts')
|
||||
parser.add_argument('--scenario', choices=['clear', 'cylinder', 'blocked', 'lidar_loss'], default='clear')
|
||||
parser.add_argument('--obstacle-x',type=float,default=-4.0)
|
||||
parser.add_argument('--obstacle-y',type=float,default=-1.5)
|
||||
parser.add_argument('--obstacle-radius',type=float,default=0.22)
|
||||
parser.add_argument('--rviz', action='store_true', help='include offscreen RViz discovery load')
|
||||
args = parser.parse_args()
|
||||
if not args.map.is_file():
|
||||
parser.error('map missing')
|
||||
if args.output.exists():
|
||||
parser.error('output must be a new directory')
|
||||
args.output.mkdir(parents=True)
|
||||
session = uuid.uuid4().hex[:12]
|
||||
os.environ.update(ROS_DOMAIN_ID=str(args.domain if args.domain is not None else 50+int(session[:8], 16) % 50), GZ_PARTITION=f'lio_stack_{session}',
|
||||
ROS2CLI_DISABLE_DAEMON='1',
|
||||
HEADLESS='1', NAV2='1', RVIZ='0', LOCALIZATION='lio', LIO_MODE='localization',
|
||||
LIO_MAP=str(args.map.resolve()), SENTRY_RUNTIME_DIR=str((args.output/'runtime').resolve()),
|
||||
LIO_TRACE_PATH=str((args.output/'filter_trace.csv').resolve()), SENTRY_LOG=str((args.output/'stack.log').resolve()))
|
||||
os.environ.update(dds_defaults(os.environ))
|
||||
workspace = Path(__file__).resolve().parents[1]
|
||||
params_file = workspace/'src/sentry_sim/config/nav2_params.yaml'
|
||||
runtime = {
|
||||
'domain': os.environ['ROS_DOMAIN_ID'],
|
||||
'partition': os.environ['GZ_PARTITION'],
|
||||
'scenario': args.scenario,
|
||||
'obstacle': [args.obstacle_x, args.obstacle_y, args.obstacle_radius],
|
||||
'nav2_config_sha256': hashlib.sha256(params_file.read_bytes()).hexdigest(),
|
||||
}
|
||||
(args.output/'runtime.json').write_text(json.dumps(runtime, indent=2))
|
||||
log = None
|
||||
record_log = open(args.output/'record.log', 'w', encoding='utf8')
|
||||
recorder = subprocess.Popen([str(workspace/'build/bin/field_localization_record'), '--ros-args',
|
||||
'-p', 'use_sim_time:=true', '-p', f'output_directory:={args.output.resolve()}/dataset',
|
||||
'-p', 'duration_sec:=600.0'], stdout=record_log, stderr=subprocess.STDOUT, start_new_session=True)
|
||||
if args.launcher == 'shell':
|
||||
command = ['bash', str(workspace/'scripts/sentry_up.sh')]
|
||||
else:
|
||||
command = ['ros2', 'launch', str(workspace/'src/sentry_sim/launch/sentry_arena.launch.py'),
|
||||
'headless:=true', 'rviz:=false', 'localization:=lio', f'lio_map:={args.map.resolve()}']
|
||||
log = open(args.output/'stack.log', 'w', encoding='utf8')
|
||||
started = time.monotonic()
|
||||
process = subprocess.Popen(command, cwd=workspace, start_new_session=True,
|
||||
stdout=log if log else subprocess.DEVNULL, stderr=subprocess.STDOUT)
|
||||
rclpy.init()
|
||||
node = Node('verify_lio_stack', parameter_overrides=[Parameter('use_sim_time', value=True)])
|
||||
publishers = set()
|
||||
samples = {'truth': [], 'estimate': []}
|
||||
health_events=[]
|
||||
actuator=[]
|
||||
subscription_actuator=node.create_subscription(Twist,'/model/sentry/cmd_vel',lambda msg:actuator.append((time.monotonic(),msg.linear.x,msg.linear.y,msg.angular.z)),100)
|
||||
subscriptions_health=node.create_subscription(Bool,'/field_localization/navigation_valid',
|
||||
lambda msg:health_events.append((time.monotonic(),msg.data)),10)
|
||||
subscriptions = []
|
||||
def sample(message, name):
|
||||
p = message.pose.pose if name == 'estimate' else message.pose
|
||||
samples[name].append([message.header.stamp.sec+1e-9*message.header.stamp.nanosec,
|
||||
p.position.x,p.position.y,p.position.z,p.orientation.x,p.orientation.y,p.orientation.z,p.orientation.w])
|
||||
subscriptions.append(node.create_subscription(PoseStamped, '/evaluation/ground_truth',
|
||||
lambda msg: sample(msg, 'truth'), qos_profile_sensor_data))
|
||||
subscriptions.append(node.create_subscription(Odometry, '/field_localization/odometry',
|
||||
lambda msg: sample(msg, 'estimate'), qos_profile_sensor_data))
|
||||
counts = {'map_to_odom': 0, 'map_to_base_link': 0}
|
||||
|
||||
def on_tf(msg, info):
|
||||
for transform in msg.transforms:
|
||||
if transform.header.frame_id != 'map':
|
||||
continue
|
||||
if transform.child_frame_id == 'odom':
|
||||
gid = info['publisher_gid'] if isinstance(info, dict) else info.publisher_gid
|
||||
publishers.add(json.dumps(gid, sort_keys=True, default=str))
|
||||
counts['map_to_odom'] += 1
|
||||
if transform.child_frame_id == 'base_link':
|
||||
counts['map_to_base_link'] += 1
|
||||
|
||||
subscription = node.create_subscription(TFMessage, '/tf', on_tf, 500)
|
||||
clients = {name: node.create_client(GetState, f'/{name}/get_state') for name in NODES}
|
||||
path_client = node.create_client(IsPathValid, '/is_path_valid')
|
||||
active_client = node.create_client(Trigger, '/lifecycle_manager_nav2/is_active')
|
||||
parameter_client = node.create_client(GetParameters, '/lifecycle_manager_nav2/get_parameters')
|
||||
states = {}
|
||||
processes = []
|
||||
rviz = None
|
||||
goal = None
|
||||
reached_readiness = False
|
||||
result = {}
|
||||
try:
|
||||
if args.rviz:
|
||||
rviz = subprocess.Popen(['ros2', 'run', 'rviz2', 'rviz2', '-d',
|
||||
str(workspace/'src/sentry_sim/config/sentry.rviz'), '--ros-args',
|
||||
'-p', 'use_sim_time:=true'],
|
||||
env={**os.environ, 'QT_QPA_PLATFORM': 'offscreen'},
|
||||
start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
|
||||
deadline = time.monotonic()+args.timeout
|
||||
last_check = 0.0
|
||||
stable_since = None
|
||||
manager_completed = False
|
||||
while time.monotonic() < deadline:
|
||||
rclpy.spin_once(node, timeout_sec=0.1)
|
||||
if process.poll() is not None:
|
||||
raise RuntimeError('stack exited')
|
||||
if time.monotonic()-last_check < 0.5:
|
||||
continue
|
||||
last_check = time.monotonic()
|
||||
if not processes and time.monotonic()-started > 8:
|
||||
processes = process_environment(process.pid)
|
||||
states = {}
|
||||
pending = {}
|
||||
for name, client in clients.items():
|
||||
if not client.service_is_ready():
|
||||
continue
|
||||
pending[name] = client.call_async(GetState.Request())
|
||||
poll_end = time.monotonic()+1
|
||||
while time.monotonic() < poll_end and any(not f.done() for f in pending.values()):
|
||||
rclpy.spin_once(node, timeout_sec=0.02)
|
||||
for name, future in pending.items():
|
||||
if future.done() and future.result():
|
||||
states[name] = future.result().current_state.id
|
||||
else:
|
||||
clients[name].remove_pending_request(future)
|
||||
log_path = args.output/'stack.log'
|
||||
text = log_path.read_text(errors='replace') if log_path.exists() else ''
|
||||
manager_completed = any('lifecycle_manager_nav2' in line and 'Managed nodes are active' in line
|
||||
for line in text.splitlines())
|
||||
if all(states.get(name) == 3 for name in NODES) and counts['map_to_odom'] > 20 and manager_completed and health_events and health_events[-1][1]:
|
||||
if stable_since is None:
|
||||
stable_since = time.monotonic()
|
||||
if time.monotonic()-stable_since >= 2:
|
||||
reached_readiness = True
|
||||
break
|
||||
else:
|
||||
stable_since = None
|
||||
processes = process_environment(process.pid)
|
||||
names = sorted(set(node.get_node_names()))
|
||||
path_ready = path_client.wait_for_service(timeout_sec=2)
|
||||
path_response = None
|
||||
if path_ready:
|
||||
future = path_client.call_async(path_probe_request())
|
||||
rclpy.spin_until_future_complete(node, future, timeout_sec=3)
|
||||
if future.done() and future.result() is not None:
|
||||
path_response = str(future.result())
|
||||
manager_active = False
|
||||
if active_client.wait_for_service(timeout_sec=1):
|
||||
future = active_client.call_async(Trigger.Request())
|
||||
rclpy.spin_until_future_complete(node, future, timeout_sec=2)
|
||||
manager_active = bool(future.done() and future.result() and future.result().success)
|
||||
managed_nodes = []
|
||||
if parameter_client.wait_for_service(timeout_sec=1):
|
||||
future = parameter_client.call_async(GetParameters.Request(names=['node_names']))
|
||||
rclpy.spin_until_future_complete(node, future, timeout_sec=2)
|
||||
if future.done() and future.result() and future.result().values:
|
||||
managed_nodes = list(future.result().values[0].string_array_value)
|
||||
result = {'launcher': args.launcher, 'startup_seconds': time.monotonic()-started,
|
||||
'startup_attempts': sum('startup attempt ' in line for line in text.splitlines()),
|
||||
'rmw': get_rmw_implementation_identifier(), 'processes': processes,
|
||||
'node_counts': dict(Counter(node.get_node_names())),
|
||||
'services': dict(node.get_service_names_and_types()),
|
||||
'path_service_endpoints': {'servers': list(map(str, node.get_servers_info_by_service('/is_path_valid'))),
|
||||
'clients': list(map(str, node.get_clients_info_by_service('/is_path_valid')))},
|
||||
'is_path_valid_discovered': path_ready, 'is_path_valid_response': path_response,
|
||||
'topic_qos':{topic:[{'node':p.node_name,'reliability':str(p.qos_profile.reliability)} for p in node.get_publishers_info_by_topic(topic)] for topic in ['/scan/points','/scan/points_filtered','/imu']},
|
||||
'manager_active': manager_active, 'managed_nodes': managed_nodes,
|
||||
'manager_completed': manager_completed, 'lifecycle_states': states, 'amcl_present': 'amcl' in names,
|
||||
'lio_present': 'field_localization' in names, 'map_to_odom_publishers': len(publishers), **counts}
|
||||
result['passed'] = (reached_readiness and manager_completed and manager_active and path_response is not None
|
||||
and bool(managed_nodes) and all(states.get(name) == 3 for name in managed_nodes)
|
||||
and all(states.get(name) == 3 for name in NODES) and not result['amcl_present']
|
||||
and result['lio_present'] and len(publishers) == 1 and counts['map_to_odom'] > 0
|
||||
and counts['map_to_base_link'] == 0)
|
||||
(args.output/'result.json').write_text(json.dumps(result, indent=2))
|
||||
if args.scenario in ('cylinder','blocked') and result['passed']:
|
||||
# Obstacle lies on the initial straight corridor; a route around the cylinder exists.
|
||||
shape = f'<cylinder><radius>{args.obstacle_radius}</radius><length>0.8</length></cylinder>'
|
||||
pose = f'{args.obstacle_x} {args.obstacle_y} 0.4 0 0 0'
|
||||
if args.scenario == 'blocked':
|
||||
shape = '<box><size>1.6 1.6 0.8</size></box>'
|
||||
pose = '0 0 0.4 0 0 0'
|
||||
sdf = f'<sdf version="1.9"><model name="validation_obstacle"><static>true</static><pose>{pose}</pose><link name="body"><collision name="collision"><geometry>{shape}</geometry></collision><visual name="visual"><geometry>{shape}</geometry></visual></link></model></sdf>'
|
||||
gz = subprocess.run(['/usr/bin/gz', 'service', '-s', '/world/rmul_arena/create',
|
||||
'--reqtype', 'gz.msgs.EntityFactory', '--reptype', 'gz.msgs.Boolean', '--timeout', '5000',
|
||||
'--req', 'sdf: '+json.dumps(sdf)], capture_output=True,text=True,timeout=10)
|
||||
(args.output/'obstacle.log').write_text(gz.stdout+gz.stderr)
|
||||
if gz.returncode or 'data: true' not in gz.stdout:
|
||||
raise RuntimeError('obstacle insertion failed')
|
||||
until=time.monotonic()+2
|
||||
while time.monotonic()<until:
|
||||
rclpy.spin_once(node,timeout_sec=0.02)
|
||||
if args.goal and result['passed']:
|
||||
goal_start_sim=node.get_clock().now().nanoseconds*1e-9
|
||||
goal_start_wall=time.monotonic()
|
||||
goal = subprocess.Popen([str(workspace/'build/bin/nav_client'), *map(str, args.goal), '0'],
|
||||
stdout=open(args.output/'goal.log','w'), stderr=subprocess.STDOUT, text=True, start_new_session=True)
|
||||
until=time.monotonic()+(240 if args.scenario=="blocked" else 120)
|
||||
fault_time=None
|
||||
while goal.poll() is None and time.monotonic()<until:
|
||||
rclpy.spin_once(node,timeout_sec=0.02)
|
||||
if args.scenario=='lidar_loss' and fault_time is None and time.monotonic()-goal_start_wall>=5 and actuator and sum(abs(v) for v in actuator[-1][1:])>0.1:
|
||||
owned=process_environment(process.pid)
|
||||
sensors=[p['pid'] for p in owned if p['executable'] and Path(p['executable'][0]).name=='self_filter']
|
||||
if len(sensors)!=1:
|
||||
raise RuntimeError('cannot identify the owned self_filter for fault injection')
|
||||
fault_time=time.monotonic();os.kill(sensors[0],signal.SIGTERM)
|
||||
if goal.poll() is None:
|
||||
os.killpg(goal.pid,signal.SIGINT)
|
||||
goal.wait(timeout=5)
|
||||
goal.stdout_text=(args.output/'goal.log').read_text()
|
||||
if args.scenario == 'blocked':
|
||||
terminal_time = time.monotonic()
|
||||
while time.monotonic() - terminal_time < 0.5:
|
||||
rclpy.spin_once(node, timeout_sec=0.02)
|
||||
result['blocked_zero_output'] = bool(
|
||||
actuator and actuator[-1][0] > terminal_time and actuator[-1][1:] == (0, 0, 0)
|
||||
)
|
||||
result['passed'] = result['passed'] and result['blocked_zero_output']
|
||||
result.update(counts)
|
||||
result['map_to_odom_publishers'] = len(publishers)
|
||||
result['amcl_present'] = 'amcl' in node.get_node_names()
|
||||
result['passed'] = (result['passed'] and len(publishers) == 1
|
||||
and counts['map_to_base_link'] == 0
|
||||
and not result['amcl_present'])
|
||||
result['goal_exit_code'] = goal.returncode
|
||||
if args.scenario=='lidar_loss':
|
||||
stops=[t for t,x,y,z in actuator if fault_time is not None and t>=fault_time and x==0 and y==0 and z==0]
|
||||
result['fault_stop_delay_sec']=min(stops)-fault_time if stops else None
|
||||
result['fault_goal_canceled']='结果: ❌ CANCELED' in goal.stdout_text
|
||||
result['goal_succeeded'] = '结果: ✅ SUCCEEDED' in goal.stdout_text
|
||||
result['goal_elapsed_wall_sec']=time.monotonic()-goal_start_wall
|
||||
result['trajectory_metrics']=metrics(samples['estimate'],samples['truth'])
|
||||
truth_goal=[row for row in samples['truth'] if row[0]>=goal_start_sim]
|
||||
result['truth_goal_error_m']=math.hypot(truth_goal[-1][1]-args.goal[0],truth_goal[-1][2]-args.goal[1]) if truth_goal else None
|
||||
result['minimum_cylinder_clearance_m']=min(cylinder_clearance(row,args.obstacle_x,args.obstacle_y,args.obstacle_radius) for row in truth_goal) if truth_goal and args.scenario=='cylinder' else None
|
||||
result['health_failures_during_goal']=sum(not value for stamp,value in health_events if stamp>=goal_start_wall)
|
||||
quality=result['trajectory_metrics']
|
||||
result['passed']=result['passed'] and quality['matched']>100 and quality['rpe_pairs']>0 and quality['maximum_position_error_m']<0.25 and quality['ate_translation_m']<0.1
|
||||
if args.scenario not in ('blocked','lidar_loss'):
|
||||
result['passed']=result['passed'] and result['truth_goal_error_m'] is not None and result['truth_goal_error_m']<=0.30
|
||||
if result['minimum_cylinder_clearance_m'] is not None:
|
||||
result['passed']=result['passed'] and result['minimum_cylinder_clearance_m']>=0
|
||||
result['passed'] = result['passed'] and ((args.scenario == 'blocked' and '结果: ❌ ABORTED' in goal.stdout_text) or (args.scenario == 'lidar_loss' and result['fault_goal_canceled'] and result['fault_stop_delay_sec'] is not None and result['fault_stop_delay_sec']<0.5) or (goal.returncode == 0 and result['goal_succeeded']))
|
||||
(args.output/'result.json').write_text(json.dumps(result, indent=2))
|
||||
print(json.dumps({k: v for k, v in result.items() if k not in
|
||||
('processes', 'services', 'node_counts', 'path_service_endpoints')}, indent=2), flush=True)
|
||||
if not result['passed']:
|
||||
raise RuntimeError('stack integration validation failed')
|
||||
except Exception as error:
|
||||
result.update(passed=False, error=str(error))
|
||||
(args.output/'result.json').write_text(json.dumps(result, indent=2))
|
||||
raise
|
||||
finally:
|
||||
_ = subscription, subscriptions, subscriptions_health, subscription_actuator
|
||||
(args.output/'health_events.json').write_text(json.dumps(health_events))
|
||||
for name, rows in samples.items():
|
||||
with open(args.output/(name+'.tum'),'w') as output:
|
||||
for row in rows:
|
||||
output.write(' '.join(map(str,row))+'\n')
|
||||
if goal is not None and goal.poll() is None:
|
||||
os.killpg(goal.pid, signal.SIGINT)
|
||||
try:
|
||||
goal.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(goal.pid, signal.SIGKILL)
|
||||
goal.wait()
|
||||
if recorder.poll() is None:
|
||||
os.killpg(recorder.pid, signal.SIGINT)
|
||||
try:
|
||||
recorder.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(recorder.pid, signal.SIGKILL)
|
||||
recorder.wait()
|
||||
record_log.close()
|
||||
if process.poll() is None:
|
||||
os.killpg(process.pid, signal.SIGINT)
|
||||
try:
|
||||
process.wait(timeout=20)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
process.wait()
|
||||
if rviz is not None:
|
||||
os.killpg(rviz.pid, signal.SIGINT)
|
||||
try:
|
||||
rviz.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(rviz.pid, signal.SIGKILL)
|
||||
rviz.wait()
|
||||
if log:
|
||||
log.close()
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,109 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Replay the same recorded southeast scans against two maps."""
|
||||
|
||||
import argparse
|
||||
from bisect import bisect_left
|
||||
import csv
|
||||
import json
|
||||
from pathlib import Path
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
import project_env
|
||||
|
||||
|
||||
def rotation(quaternion):
|
||||
x, y, z, w = np.asarray(quaternion)/np.linalg.norm(quaternion)
|
||||
return np.array(((1-2*(y*y+z*z), 2*(x*y-z*w), 2*(x*z+y*w)),
|
||||
(2*(x*y+z*w), 1-2*(x*x+z*z), 2*(y*z-x*w)),
|
||||
(2*(x*z-y*w), 2*(y*z+x*w), 1-2*(x*x+y*y))))
|
||||
|
||||
|
||||
def east_scans(dataset):
|
||||
rows = [list(map(float, l.split())) for l in (dataset/'truth.tum').read_text().splitlines()]
|
||||
if not rows:
|
||||
raise ValueError('southeast evaluation requires recorded ground truth')
|
||||
times = [r[0] for r in rows]
|
||||
mask = set()
|
||||
with (dataset/'scans.csv').open() as scans:
|
||||
for entry in csv.DictReader(scans):
|
||||
stamp = float(entry['timestamp'])
|
||||
index = bisect_left(times, stamp)
|
||||
if index == len(times) or (index > 0 and stamp-times[index-1] < times[index]-stamp):
|
||||
index -= 1
|
||||
time, x, y = rows[index][:3]
|
||||
if abs(time-stamp) <= 0.05 and x >= 4 and y <= -1.5:
|
||||
mask.add(stamp)
|
||||
return mask
|
||||
|
||||
|
||||
def compare_trace(path, stamps, imu_from_base):
|
||||
inliers, horizontal, horizontal_prior = [], [], []
|
||||
degenerate = x_weak = full = 0
|
||||
x, y, z = imu_from_base
|
||||
skew = np.array(((0, -z, y), (z, 0, -x), (-y, x, 0)))
|
||||
with path.open() as trace:
|
||||
for row in csv.DictReader(trace):
|
||||
phase = row['phase']
|
||||
stamp = float(row['scan_time'])
|
||||
if stamp not in stamps or phase == 'candidate':
|
||||
continue
|
||||
p = np.array([[float(row[f'P{i}_{j}']) for j in range(18)] for i in range(18)])
|
||||
j = np.zeros((2, 18))
|
||||
j[0, 0] = j[1, 1] = 1
|
||||
j[:, 6:9] = -(rotation([float(row[k]) for k in ('qx','qy','qz','qw')])@skew)[:2, :]
|
||||
sigma = 3*float(np.sqrt(max(0, np.linalg.eigvalsh(j@p@j.T)[-1])))
|
||||
if phase == 'prediction':
|
||||
if row['registration_stage'] != 'NOT_RUN':
|
||||
horizontal_prior.append(sigma)
|
||||
continue
|
||||
horizontal.append(sigma)
|
||||
inliers.append(int(row['inliers']))
|
||||
full += row['mode'] == 'FULL'
|
||||
dims = int(row['degenerate'])
|
||||
if dims:
|
||||
h = np.array([[float(row[f'H{i}_{j}']) for j in range(6)] for i in range(6)])
|
||||
if np.any(h):
|
||||
vt = np.linalg.svd(h)[2]
|
||||
x_weak += int(np.linalg.norm(vt[-dims:, 0]) >= 0.8)
|
||||
degenerate += 1
|
||||
if not inliers:
|
||||
raise RuntimeError('replay did not include the recorded southeast scans')
|
||||
return {'east_scans': len(inliers), 'accepted': full,
|
||||
'median_inliers': statistics.median(inliers), 'degenerate_scans': degenerate,
|
||||
'x_weak_scans': x_weak, 'maximum_horizontal_3sigma_m': max(horizontal),
|
||||
'maximum_prior_horizontal_3sigma_m': max(horizontal_prior, default=None)}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
for name in ('dataset', 'baseline', 'candidate', 'output'):
|
||||
parser.add_argument(f'--{name}', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
stamps = east_scans(args.dataset)
|
||||
if len(stamps) < 10:
|
||||
parser.error('verification dataset must contain at least ten scans in x >= 4, y <= -1.5')
|
||||
transform = next(line for line in (args.dataset/'config.txt').read_text().splitlines()
|
||||
if line.startswith('base_from_imu ')).split()[1:]
|
||||
extrinsic = list(map(float, transform))
|
||||
imu_from_base = -rotation(extrinsic[3:]).T @ extrinsic[:3]
|
||||
exe = project_env.require_executable(project_env.find_bin_dir()/'field_localization_replay',
|
||||
'field_localization_replay')
|
||||
args.output.mkdir(parents=True)
|
||||
reports = {}
|
||||
for name, world_map in (('baseline', args.baseline), ('candidate', args.candidate)):
|
||||
directory = args.output/name
|
||||
subprocess.run([str(exe), '--dataset', str(args.dataset), '--mode', 'localization',
|
||||
'--map', str(world_map), '--output', str(directory)], check=True)
|
||||
reports[name] = compare_trace(directory/'filter_trace.csv', stamps, imu_from_base)
|
||||
content = json.dumps(reports, indent=2)
|
||||
(args.output/'southeast.json').write_text(content+'\n')
|
||||
print(content)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
File renamed without changes.
@@ -21,14 +21,15 @@ def main():
|
||||
parser.error('repeats must be positive')
|
||||
if args.output.exists():parser.error('output must be new')
|
||||
args.output.mkdir(parents=True)
|
||||
root=Path(__file__).resolve().parents[1]
|
||||
script_dir = Path(__file__).resolve().parent
|
||||
root = script_dir.parents[1]
|
||||
results=[]
|
||||
for scenario in args.scenario or ['clear', 'cylinder', 'blocked']:
|
||||
count = args.repeats if args.repeats is not None else (3 if scenario in ('clear', 'cylinder') else 1)
|
||||
for index in range(1, count+1):
|
||||
name=f'{scenario}_{index}';folder=args.output/name
|
||||
with open(args.output/(name+'.log'),'w') as log:
|
||||
command=[sys.executable,str(root/'tools/validate_lio_navigation.py'),
|
||||
command=[sys.executable,str(script_dir/'validate_lio_navigation.py'),
|
||||
'--launcher',args.launcher,'--map',str(args.map.resolve()),'--output',str(folder.resolve()),
|
||||
'--scenario',scenario,'--goal','0','0']
|
||||
if args.domain is not None:
|
||||
@@ -0,0 +1,532 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run an isolated Gazebo navigation scenario and score it using simulator truth."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from collections import Counter
|
||||
|
||||
import rclpy
|
||||
from rclpy.node import Node
|
||||
from rclpy.action import ActionClient
|
||||
from action_msgs.msg import GoalStatus
|
||||
from rclpy.parameter import Parameter
|
||||
from lifecycle_msgs.srv import GetState
|
||||
from tf2_msgs.msg import TFMessage
|
||||
from nav2_msgs.srv import IsPathValid
|
||||
from nav2_msgs.action import ComputePathToPose, FollowPath
|
||||
from nav_msgs.msg import Odometry
|
||||
from geometry_msgs.msg import PoseStamped, Twist
|
||||
from rclpy.qos import qos_profile_sensor_data
|
||||
from std_msgs.msg import Bool
|
||||
from rcl_interfaces.srv import GetParameters
|
||||
from std_srvs.srv import Trigger
|
||||
from rclpy.utilities import get_rmw_implementation_identifier
|
||||
sys.path[:0] = [str(Path(__file__).resolve().parents[1] / '_internal'),
|
||||
str(Path(__file__).resolve().parents[1])]
|
||||
import project_env
|
||||
from arena_grid import ARENA_GOALS, START, ArenaGrid
|
||||
from nav2_startup import path_probe_request
|
||||
|
||||
from dds_environment import defaults as dds_defaults
|
||||
from lio_metrics import cylinder_clearance, metrics
|
||||
from verify_lio_stack import NODES, process_environment
|
||||
|
||||
|
||||
ROUND_TRIP = ((0.0, 0.0), (-5.0, 3.0), (0.0, 0.0), (-5.0, 3.0), (0.0, 0.0))
|
||||
ROUND_TRIP_PAUSES = (0, 24, 10, 35, 16)
|
||||
|
||||
|
||||
def check_field_coverage(node, grid):
|
||||
coverage = grid.coverage()
|
||||
client = ActionClient(node, ComputePathToPose, '/compute_path_to_pose')
|
||||
try:
|
||||
if not client.wait_for_server(timeout_sec=8):
|
||||
raise RuntimeError('compute_path_to_pose unavailable for field coverage')
|
||||
|
||||
def pose(point):
|
||||
message = PoseStamped()
|
||||
message.header.frame_id = 'map'
|
||||
message.pose.position.x, message.pose.position.y = point
|
||||
message.pose.orientation.w = 1.0
|
||||
return message
|
||||
|
||||
checks = []
|
||||
for point in coverage.pop('samples'):
|
||||
request = ComputePathToPose.Goal()
|
||||
request.start = pose(START)
|
||||
request.goal = pose(point)
|
||||
request.use_start = True
|
||||
future = client.send_goal_async(request)
|
||||
rclpy.spin_until_future_complete(node, future, timeout_sec=5)
|
||||
handle = future.result() if future.done() else None
|
||||
check = {'target': point, 'passed': False}
|
||||
if handle is None or not handle.accepted:
|
||||
check['error'] = 'goal rejected or acceptance timed out'
|
||||
else:
|
||||
future = handle.get_result_async()
|
||||
rclpy.spin_until_future_complete(node, future, timeout_sec=5)
|
||||
wrapped = future.result() if future.done() else None
|
||||
if wrapped is None:
|
||||
cancel = handle.cancel_goal_async()
|
||||
rclpy.spin_until_future_complete(node, cancel, timeout_sec=1)
|
||||
check['error'] = 'planner response timed out'
|
||||
else:
|
||||
outcome = wrapped.result
|
||||
check.update(error_code=outcome.error_code, error=outcome.error_msg)
|
||||
if wrapped.status == GoalStatus.STATUS_SUCCEEDED and outcome.path.poses:
|
||||
endpoint = outcome.path.poses[-1].pose.position
|
||||
check['endpoint_error_m'] = math.hypot(endpoint.x-point[0], endpoint.y-point[1])
|
||||
check['passed'] = outcome.error_code == 0 and check['endpoint_error_m'] <= 0.30
|
||||
checks.append(check)
|
||||
finally:
|
||||
client.destroy()
|
||||
coverage.update(planned=sum(c['passed'] for c in checks), sample_count=len(checks), checks=checks)
|
||||
return coverage
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--map', type=Path, required=True)
|
||||
parser.add_argument('--lio-cloud-topic', default=os.environ.get('LIO_POINT_CLOUD_TOPIC') or '/scan/points_lio')
|
||||
parser.add_argument('--launcher', choices=['shell', 'python'], default='shell')
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
goals = parser.add_mutually_exclusive_group()
|
||||
goals.add_argument('--goal', nargs=2, type=float, metavar=('X', 'Y'))
|
||||
goals.add_argument('--full-field', action='store_true',
|
||||
help='check reachability in 1 m tiles and navigate the whole-field route')
|
||||
goals.add_argument('--round-trip-regression', action='store_true',
|
||||
help='run the five recorded goals without restarting the stack')
|
||||
parser.add_argument('--domain', type=int, choices=range(1, 233), metavar='[1–232]',
|
||||
help='use an explicitly reserved ROS_DOMAIN_ID for parallel tests')
|
||||
parser.add_argument('--timeout', type=float, default=420.0,
|
||||
help='whole-stack validation deadline, including up to three startup attempts')
|
||||
parser.add_argument('--scenario', choices=['clear', 'cylinder', 'blocked', 'lidar_loss'], default='clear')
|
||||
parser.add_argument('--obstacle-x',type=float,default=-4.0)
|
||||
parser.add_argument('--obstacle-y',type=float,default=-1.5)
|
||||
parser.add_argument('--obstacle-radius',type=float,default=0.22)
|
||||
parser.add_argument('--rviz', action='store_true', help='include offscreen RViz discovery load')
|
||||
args = parser.parse_args()
|
||||
if args.round_trip_regression and args.scenario not in ('clear', 'cylinder'):
|
||||
parser.error('--round-trip-regression requires clear or cylinder')
|
||||
if args.full_field and args.scenario != 'clear':
|
||||
parser.error('--full-field starts the clear-field coverage route')
|
||||
multileg = args.round_trip_regression or args.full_field
|
||||
route = ARENA_GOALS if args.full_field else ROUND_TRIP if args.round_trip_regression else ((args.goal,) if args.goal else ())
|
||||
pauses = ROUND_TRIP_PAUSES if args.round_trip_regression else (0,)*len(route)
|
||||
if not args.map.is_file():
|
||||
parser.error('map missing')
|
||||
if args.output.exists():
|
||||
parser.error('output must be a new directory')
|
||||
workspace = project_env.WORKSPACE
|
||||
try:
|
||||
gz_exe = project_env.find_gz_bin()
|
||||
bin_dir = project_env.find_bin_dir(workspace)
|
||||
recorder_exe = project_env.require_executable(bin_dir/'field_localization_record',
|
||||
'field_localization_record')
|
||||
grid = ArenaGrid(project_env.find_map_yaml()) if args.full_field else None
|
||||
if route:
|
||||
nav_client = project_env.require_executable(bin_dir/'nav_client', 'nav_client')
|
||||
except (project_env.ProbeError, ValueError, OSError) as error:
|
||||
parser.exit(1, f'{parser.prog}: {error}\n')
|
||||
args.output.mkdir(parents=True)
|
||||
session = uuid.uuid4().hex[:12]
|
||||
os.environ.update(ROS_DOMAIN_ID=str(args.domain if args.domain is not None else 50+int(session[:8], 16) % 50), GZ_PARTITION=f'lio_stack_{session}',
|
||||
ROS2CLI_DISABLE_DAEMON='1',
|
||||
HEADLESS='1', NAV2='1', RVIZ='0', LOCALIZATION='lio', LIO_MODE='localization',
|
||||
LIO_MAP=str(args.map.resolve()), SENTRY_RUNTIME_DIR=str((args.output/'runtime').resolve()),
|
||||
LIO_TRACE_PATH=str((args.output/'filter_trace.csv').resolve()), SENTRY_LOG=str((args.output/'stack.log').resolve()))
|
||||
os.environ.update(GZ_BIN=str(gz_exe), SENTRY_BIN_DIR=str(bin_dir), LIO_POINT_CLOUD_TOPIC=args.lio_cloud_topic)
|
||||
os.environ.update(dds_defaults(os.environ))
|
||||
os.environ.setdefault('ROS_LOG_DIR', str((args.output/'ros_log').resolve()))
|
||||
os.environ.setdefault('XDG_CACHE_HOME', str((args.output/'cache').resolve()))
|
||||
params_file = workspace/'src/sentry_sim/config/nav2_params.yaml'
|
||||
runtime = {
|
||||
'domain': os.environ['ROS_DOMAIN_ID'],
|
||||
'partition': os.environ['GZ_PARTITION'],
|
||||
'scenario': args.scenario,
|
||||
'obstacle': [args.obstacle_x, args.obstacle_y, args.obstacle_radius],
|
||||
'goals': route,
|
||||
'pauses_wall_sec': pauses,
|
||||
'nav2_config_sha256': hashlib.sha256(params_file.read_bytes()).hexdigest(),
|
||||
'lio_map_sha256': hashlib.sha256(args.map.read_bytes()).hexdigest(),
|
||||
'point_cloud_topic': args.lio_cloud_topic,
|
||||
}
|
||||
(args.output/'runtime.json').write_text(json.dumps(runtime, indent=2))
|
||||
log = None
|
||||
record_duration = 3600.0 if args.full_field else 1200.0 if multileg else 600.0
|
||||
record_log = open(args.output/'record.log', 'w', encoding='utf8')
|
||||
recorder = subprocess.Popen([str(recorder_exe), '--ros-args',
|
||||
'-p', 'use_sim_time:=true', '-p', f'output_directory:={args.output.resolve()}/dataset',
|
||||
'-p', f'duration_sec:={record_duration}', '-p', f'point_cloud_topic:={args.lio_cloud_topic}'],
|
||||
stdout=record_log, stderr=subprocess.STDOUT, start_new_session=True)
|
||||
if args.launcher == 'shell':
|
||||
command = ['bash', str(workspace/'scripts/sentry_up.sh')]
|
||||
else:
|
||||
command = ['ros2', 'launch', str(workspace/'src/sentry_sim/launch/sentry_arena.launch.py'),
|
||||
'headless:=true', 'rviz:=false', 'localization:=lio', f'lio_map:={args.map.resolve()}']
|
||||
log = open(args.output/'stack.log', 'w', encoding='utf8')
|
||||
started = time.monotonic()
|
||||
process = subprocess.Popen(command, cwd=workspace, start_new_session=True,
|
||||
stdout=log if log else subprocess.DEVNULL, stderr=subprocess.STDOUT)
|
||||
rclpy.init()
|
||||
node = Node('verify_lio_stack', parameter_overrides=[Parameter('use_sim_time', value=True)])
|
||||
publishers = set()
|
||||
samples = {'truth': [], 'estimate': []}
|
||||
health_events = []
|
||||
health_transitions = []
|
||||
actuator = []
|
||||
last_map_tf_wall = None
|
||||
|
||||
def on_health(msg):
|
||||
stamp = time.monotonic()
|
||||
if not health_events or msg.data != health_events[-1][1]:
|
||||
health_transitions.append({'wall': stamp, 'sim': sim_now(), 'valid': msg.data})
|
||||
health_events.append((stamp, msg.data))
|
||||
|
||||
def sim_now():
|
||||
return node.get_clock().now().nanoseconds * 1e-9
|
||||
|
||||
def spin_for(seconds):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
if process.poll() is not None:
|
||||
raise RuntimeError('stack exited during navigation')
|
||||
rclpy.spin_once(node, timeout_sec=0.02)
|
||||
subscription_actuator=node.create_subscription(Twist,'/model/sentry/cmd_vel',lambda msg:actuator.append((time.monotonic(),msg.linear.x,msg.linear.y,msg.angular.z)),100)
|
||||
subscriptions_health=node.create_subscription(Bool,'/field_localization/navigation_valid',
|
||||
on_health, 10)
|
||||
subscriptions = []
|
||||
def sample(message, name):
|
||||
p = message.pose.pose if name == 'estimate' else message.pose
|
||||
samples[name].append([message.header.stamp.sec+1e-9*message.header.stamp.nanosec,
|
||||
p.position.x,p.position.y,p.position.z,p.orientation.x,p.orientation.y,p.orientation.z,p.orientation.w])
|
||||
subscriptions.append(node.create_subscription(PoseStamped, '/evaluation/ground_truth',
|
||||
lambda msg: sample(msg, 'truth'), qos_profile_sensor_data))
|
||||
subscriptions.append(node.create_subscription(Odometry, '/field_localization/odometry',
|
||||
lambda msg: sample(msg, 'estimate'), qos_profile_sensor_data))
|
||||
counts = {'map_to_odom': 0, 'map_to_base_link': 0}
|
||||
|
||||
def on_tf(msg, info):
|
||||
nonlocal last_map_tf_wall
|
||||
for transform in msg.transforms:
|
||||
if transform.header.frame_id != 'map':
|
||||
continue
|
||||
if transform.child_frame_id == 'odom':
|
||||
gid = info['publisher_gid'] if isinstance(info, dict) else info.publisher_gid
|
||||
publishers.add(json.dumps(gid, sort_keys=True, default=str))
|
||||
counts['map_to_odom'] += 1
|
||||
last_map_tf_wall = time.monotonic()
|
||||
if transform.child_frame_id == 'base_link':
|
||||
counts['map_to_base_link'] += 1
|
||||
|
||||
subscription = node.create_subscription(TFMessage, '/tf', on_tf, 500)
|
||||
clients = {name: node.create_client(GetState, f'/{name}/get_state') for name in NODES}
|
||||
path_client = node.create_client(IsPathValid, '/is_path_valid')
|
||||
active_client = node.create_client(Trigger, '/lifecycle_manager_nav2/is_active')
|
||||
parameter_client = node.create_client(GetParameters, '/lifecycle_manager_nav2/get_parameters')
|
||||
states = {}
|
||||
processes = []
|
||||
rviz = None
|
||||
goal = None
|
||||
reached_readiness = False
|
||||
result = {}
|
||||
try:
|
||||
if args.rviz:
|
||||
rviz = subprocess.Popen(['ros2', 'run', 'rviz2', 'rviz2', '-d',
|
||||
str(workspace/'src/sentry_sim/config/sentry.rviz'), '--ros-args',
|
||||
'-p', 'use_sim_time:=true'],
|
||||
env={**os.environ, 'QT_QPA_PLATFORM': 'offscreen'},
|
||||
start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
|
||||
deadline = time.monotonic()+args.timeout
|
||||
last_check = 0.0
|
||||
stable_since = None
|
||||
manager_completed = False
|
||||
while time.monotonic() < deadline:
|
||||
rclpy.spin_once(node, timeout_sec=0.1)
|
||||
if process.poll() is not None:
|
||||
raise RuntimeError('stack exited')
|
||||
if time.monotonic()-last_check < 0.5:
|
||||
continue
|
||||
last_check = time.monotonic()
|
||||
if not processes and time.monotonic()-started > 8:
|
||||
processes = process_environment(process.pid)
|
||||
states = {}
|
||||
pending = {}
|
||||
for name, client in clients.items():
|
||||
if not client.service_is_ready():
|
||||
continue
|
||||
pending[name] = client.call_async(GetState.Request())
|
||||
poll_end = time.monotonic()+1
|
||||
while time.monotonic() < poll_end and any(not f.done() for f in pending.values()):
|
||||
rclpy.spin_once(node, timeout_sec=0.02)
|
||||
for name, future in pending.items():
|
||||
if future.done() and future.result():
|
||||
states[name] = future.result().current_state.id
|
||||
else:
|
||||
clients[name].remove_pending_request(future)
|
||||
log_path = args.output/'stack.log'
|
||||
text = log_path.read_text(errors='replace') if log_path.exists() else ''
|
||||
manager_completed = any('lifecycle_manager_nav2' in line and 'Managed nodes are active' in line
|
||||
for line in text.splitlines())
|
||||
if all(states.get(name) == 3 for name in NODES) and counts['map_to_odom'] > 20 and manager_completed and health_events and health_events[-1][1]:
|
||||
if stable_since is None:
|
||||
stable_since = time.monotonic()
|
||||
if time.monotonic()-stable_since >= 2:
|
||||
reached_readiness = True
|
||||
break
|
||||
else:
|
||||
stable_since = None
|
||||
processes = process_environment(process.pid)
|
||||
names = sorted(set(node.get_node_names()))
|
||||
path_ready = path_client.wait_for_service(timeout_sec=2)
|
||||
path_response = None
|
||||
if path_ready:
|
||||
future = path_client.call_async(path_probe_request())
|
||||
rclpy.spin_until_future_complete(node, future, timeout_sec=3)
|
||||
if future.done() and future.result() is not None:
|
||||
path_response = str(future.result())
|
||||
manager_active = False
|
||||
if active_client.wait_for_service(timeout_sec=1):
|
||||
future = active_client.call_async(Trigger.Request())
|
||||
rclpy.spin_until_future_complete(node, future, timeout_sec=2)
|
||||
manager_active = bool(future.done() and future.result() and future.result().success)
|
||||
managed_nodes = []
|
||||
if parameter_client.wait_for_service(timeout_sec=1):
|
||||
future = parameter_client.call_async(GetParameters.Request(names=['node_names']))
|
||||
rclpy.spin_until_future_complete(node, future, timeout_sec=2)
|
||||
if future.done() and future.result() and future.result().values:
|
||||
managed_nodes = list(future.result().values[0].string_array_value)
|
||||
result = {'launcher': args.launcher, 'startup_seconds': time.monotonic()-started,
|
||||
'startup_attempts': sum('startup attempt ' in line for line in text.splitlines()),
|
||||
'rmw': get_rmw_implementation_identifier(), 'processes': processes,
|
||||
'node_counts': dict(Counter(node.get_node_names())),
|
||||
'services': dict(node.get_service_names_and_types()),
|
||||
'path_service_endpoints': {'servers': list(map(str, node.get_servers_info_by_service('/is_path_valid'))),
|
||||
'clients': list(map(str, node.get_clients_info_by_service('/is_path_valid')))},
|
||||
'is_path_valid_discovered': path_ready, 'is_path_valid_response': path_response,
|
||||
'topic_qos': {
|
||||
topic: [{'node': p.node_name, 'reliability': str(p.qos_profile.reliability)}
|
||||
for p in node.get_publishers_info_by_topic(topic)]
|
||||
for topic in dict.fromkeys(('/scan/points', '/scan/points_filtered', args.lio_cloud_topic, '/imu'))
|
||||
},
|
||||
'manager_active': manager_active, 'managed_nodes': managed_nodes,
|
||||
'manager_completed': manager_completed, 'lifecycle_states': states, 'amcl_present': 'amcl' in names,
|
||||
'lio_present': 'field_localization' in names, 'map_to_odom_publishers': len(publishers), **counts}
|
||||
result['passed'] = (reached_readiness and manager_completed and manager_active and path_response is not None
|
||||
and bool(managed_nodes) and all(states.get(name) == 3 for name in managed_nodes)
|
||||
and all(states.get(name) == 3 for name in NODES) and not result['amcl_present']
|
||||
and result['lio_present'] and len(publishers) == 1 and counts['map_to_odom'] > 0
|
||||
and counts['map_to_base_link'] == 0)
|
||||
if grid is not None and result['passed']:
|
||||
coverage = check_field_coverage(node, grid)
|
||||
result['field_coverage'] = coverage
|
||||
print(f'field coverage: {coverage["planned"]}/{coverage["sample_count"]} representative goals planned', flush=True)
|
||||
(args.output/'result.json').write_text(json.dumps(result, indent=2))
|
||||
if args.scenario in ('cylinder','blocked') and result['passed']:
|
||||
# Obstacle lies on the initial straight corridor; a route around the cylinder exists.
|
||||
shape = f'<cylinder><radius>{args.obstacle_radius}</radius><length>0.8</length></cylinder>'
|
||||
pose = f'{args.obstacle_x} {args.obstacle_y} 0.4 0 0 0'
|
||||
if args.scenario == 'blocked':
|
||||
shape = '<box><size>1.6 1.6 0.8</size></box>'
|
||||
pose = '0 0 0.4 0 0 0'
|
||||
sdf = f'<sdf version="1.9"><model name="validation_obstacle"><static>true</static><pose>{pose}</pose><link name="body"><collision name="collision"><geometry>{shape}</geometry></collision><visual name="visual"><geometry>{shape}</geometry></visual></link></model></sdf>'
|
||||
gz = project_env.run_gz(gz_exe, 'service', '-s', '/world/rmul_arena/create',
|
||||
'--reqtype', 'gz.msgs.EntityFactory', '--reptype', 'gz.msgs.Boolean', '--timeout', '5000',
|
||||
'--req', 'sdf: '+json.dumps(sdf), timeout=10)
|
||||
(args.output/'obstacle.log').write_text(gz.stdout+gz.stderr)
|
||||
if gz.returncode or 'data: true' not in gz.stdout:
|
||||
raise RuntimeError('obstacle insertion failed')
|
||||
until=time.monotonic()+2
|
||||
while time.monotonic()<until:
|
||||
rclpy.spin_once(node,timeout_sec=0.02)
|
||||
if route and result['passed']:
|
||||
legs = []
|
||||
start_sim = None
|
||||
start_wall = None
|
||||
for index, target in enumerate(route):
|
||||
spin_for(pauses[index])
|
||||
goal_start_sim, goal_start_wall = sim_now(), time.monotonic()
|
||||
if start_sim is None:
|
||||
start_sim, start_wall = goal_start_sim, goal_start_wall
|
||||
goal_log = args.output/(f'goal_{index+1}.log' if multileg else 'goal.log')
|
||||
command = [str(nav_client), *map(str, target), '0']
|
||||
with goal_log.open('w') as stream:
|
||||
goal = subprocess.Popen(command, stdout=stream, stderr=subprocess.STDOUT,
|
||||
text=True, start_new_session=True)
|
||||
until = time.monotonic() + (240 if args.scenario == 'blocked' else 180)
|
||||
fault_time = None
|
||||
while goal.poll() is None and time.monotonic() < until:
|
||||
if process.poll() is not None:
|
||||
raise RuntimeError('stack exited during navigation')
|
||||
rclpy.spin_once(node, timeout_sec=0.02)
|
||||
if (args.scenario == 'lidar_loss' and fault_time is None
|
||||
and time.monotonic()-goal_start_wall >= 5 and actuator
|
||||
and sum(abs(v) for v in actuator[-1][1:]) > 0.1):
|
||||
owned = process_environment(process.pid)
|
||||
sensors = [p['pid'] for p in owned if p['executable']
|
||||
and Path(p['executable'][0]).name == 'self_filter']
|
||||
if len(sensors) != 1:
|
||||
raise RuntimeError('cannot identify the owned self_filter for fault injection')
|
||||
fault_time = time.monotonic()
|
||||
os.kill(sensors[0], signal.SIGTERM)
|
||||
timed_out = goal.poll() is None
|
||||
if timed_out:
|
||||
os.killpg(goal.pid, signal.SIGINT)
|
||||
goal.wait(timeout=5)
|
||||
goal_end_wall = time.monotonic()
|
||||
spin_for(0.3)
|
||||
goal_end_sim = sim_now()
|
||||
output = goal_log.read_text()
|
||||
truth_goal = [row for row in samples['truth'] if goal_start_sim <= row[0] <= goal_end_sim]
|
||||
estimate_goal = [row for row in samples['estimate'] if goal_start_sim <= row[0] <= goal_end_sim]
|
||||
leg = {
|
||||
'goal': target, 'goal_exit_code': goal.returncode,
|
||||
'goal_succeeded': not timed_out and goal.returncode == 0 and '结果: ✅ SUCCEEDED' in output,
|
||||
'goal_elapsed_wall_sec': goal_end_wall-goal_start_wall,
|
||||
'start_sim': goal_start_sim, 'end_sim': goal_end_sim, 'timed_out': timed_out,
|
||||
'trajectory_metrics': metrics(estimate_goal, truth_goal),
|
||||
'truth_goal_error_m': math.hypot(truth_goal[-1][1]-target[0], truth_goal[-1][2]-target[1]) if truth_goal else None,
|
||||
'minimum_cylinder_clearance_m': min(cylinder_clearance(row, args.obstacle_x, args.obstacle_y, args.obstacle_radius) for row in truth_goal)
|
||||
if truth_goal and args.scenario == 'cylinder' else None,
|
||||
'health_failures_during_goal': sum(not value for stamp, value in health_events
|
||||
if goal_start_wall <= stamp <= goal_end_wall),
|
||||
}
|
||||
if args.scenario == 'blocked':
|
||||
stopped = bool(actuator and actuator[-1][0] > goal_end_wall and actuator[-1][1:] == (0, 0, 0))
|
||||
result['blocked_zero_output'] = stopped
|
||||
leg['passed'] = (not timed_out and '结果: ❌ ABORTED' in output and stopped
|
||||
and leg['health_failures_during_goal'] == 0
|
||||
and leg['truth_goal_error_m'] is not None
|
||||
and leg['truth_goal_error_m'] > 0.30)
|
||||
elif args.scenario == 'lidar_loss':
|
||||
spin_for(0.7)
|
||||
stops = [t for t, x, y, z in actuator if fault_time is not None and t >= fault_time and x == y == z == 0]
|
||||
delay = min(stops)-fault_time if stops else None
|
||||
lost = next((event for event in health_transitions if fault_time is not None
|
||||
and event['wall'] >= fault_time and not event['valid']), None)
|
||||
canceled = '结果: ❌ CANCELED' in output
|
||||
# Once TF stops, FollowPath can complete with TF_ERROR before the relay's
|
||||
# cancel request returns. Both outcomes terminate the in-flight goal.
|
||||
tf_abort = ('结果: ❌ ABORTED' in output
|
||||
and f'Nav2 error_code={FollowPath.Result.TF_ERROR} ' in output)
|
||||
terminated = bool(lost and lost['wall'] <= goal_end_wall and (canceled or tf_abort))
|
||||
result.update(fault_goal_canceled=canceled,
|
||||
fault_goal_tf_aborted=tf_abort,
|
||||
fault_goal_terminated=terminated,
|
||||
fault_stop_delay_sec=delay,
|
||||
fault_tf_halted=bool(lost and last_map_tf_wall is not None
|
||||
and last_map_tf_wall <= lost['wall']+0.1))
|
||||
if lost:
|
||||
retry_log = args.output/'retry_invalid_localization.log'
|
||||
with retry_log.open('w') as stream:
|
||||
retry = subprocess.run(command, stdout=stream, stderr=subprocess.STDOUT, timeout=20)
|
||||
retry_text = retry_log.read_text()
|
||||
result['invalid_retry_blocked'] = (retry.returncode != 0 and '定位不可用' in retry_text
|
||||
and '目标已接受' not in retry_text)
|
||||
else:
|
||||
result['invalid_retry_blocked'] = False
|
||||
leg['passed'] = (terminated and not timed_out and delay is not None and delay < 0.5
|
||||
and result['fault_tf_halted'] and result['invalid_retry_blocked'])
|
||||
else:
|
||||
leg['passed'] = (leg['goal_succeeded'] and leg['truth_goal_error_m'] is not None
|
||||
and leg['truth_goal_error_m'] <= 0.30
|
||||
and (leg['minimum_cylinder_clearance_m'] is None
|
||||
or leg['minimum_cylinder_clearance_m'] > 0))
|
||||
quality = leg['trajectory_metrics']
|
||||
leg['passed'] = (leg['passed'] and quality['matched'] > 100 and quality['rpe_pairs'] > 0
|
||||
and quality['maximum_position_error_m'] < 0.25 and quality['ate_translation_m'] < 0.1)
|
||||
legs.append(leg)
|
||||
result.update(leg)
|
||||
result['legs'] = legs
|
||||
(args.output/'result.json').write_text(json.dumps(result, indent=2))
|
||||
print(f'leg {index+1}/{len(route)} {tuple(target)}: passed={leg["passed"]} '
|
||||
f'goal={leg["goal_succeeded"]} max_error={quality["maximum_position_error_m"]}', flush=True)
|
||||
if multileg and not leg['goal_succeeded']:
|
||||
spin_for(8)
|
||||
break
|
||||
result.update(counts)
|
||||
result['map_to_odom_publishers'] = len(publishers)
|
||||
result['amcl_present'] = 'amcl' in node.get_node_names()
|
||||
# Include drift during the pauses, but keep each goal's outcome independent.
|
||||
if multileg:
|
||||
end_sim = legs[-1]['end_sim']
|
||||
quality = metrics(*([row for row in samples[name] if start_sim <= row[0] <= end_sim]
|
||||
for name in ('estimate', 'truth')))
|
||||
result['trajectory_metrics'] = quality
|
||||
result['first_localization_loss'] = next(
|
||||
(event for event in health_transitions if event['wall'] >= start_wall and not event['valid']), None)
|
||||
clearances = [leg['minimum_cylinder_clearance_m'] for leg in legs
|
||||
if leg['minimum_cylinder_clearance_m'] is not None]
|
||||
result['minimum_cylinder_clearance_m'] = min(clearances) if clearances else None
|
||||
result['passed'] = (quality['maximum_position_error_m'] is not None
|
||||
and quality['maximum_position_error_m'] < 0.25
|
||||
and quality['ate_translation_m'] < 0.1
|
||||
and result['first_localization_loss'] is None)
|
||||
if grid is not None:
|
||||
result['passed'] = (result['passed'] and coverage['sample_count'] > 0
|
||||
and coverage['planned'] == coverage['sample_count'])
|
||||
result['passed'] = (result['passed'] and len(legs) == len(route) and all(leg['passed'] for leg in legs)
|
||||
and len(publishers) == 1 and counts['map_to_base_link'] == 0
|
||||
and not result['amcl_present'])
|
||||
(args.output/'result.json').write_text(json.dumps(result, indent=2))
|
||||
print(json.dumps({k: v for k, v in result.items() if k not in
|
||||
('processes', 'services', 'node_counts', 'path_service_endpoints')}, indent=2), flush=True)
|
||||
if not result['passed']:
|
||||
raise RuntimeError('stack integration validation failed')
|
||||
except Exception as error:
|
||||
result.update(passed=False, error=str(error))
|
||||
(args.output/'result.json').write_text(json.dumps(result, indent=2))
|
||||
raise
|
||||
finally:
|
||||
_ = subscription, subscriptions, subscriptions_health, subscription_actuator
|
||||
(args.output/'health_events.json').write_text(json.dumps(health_events))
|
||||
(args.output/'health_transitions.json').write_text(json.dumps(health_transitions, indent=2))
|
||||
for name, rows in samples.items():
|
||||
with open(args.output/(name+'.tum'),'w') as output:
|
||||
for row in rows:
|
||||
output.write(' '.join(map(str,row))+'\n')
|
||||
if goal is not None and goal.poll() is None:
|
||||
os.killpg(goal.pid, signal.SIGINT)
|
||||
try:
|
||||
goal.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(goal.pid, signal.SIGKILL)
|
||||
goal.wait()
|
||||
if recorder.poll() is None:
|
||||
os.killpg(recorder.pid, signal.SIGINT)
|
||||
try:
|
||||
recorder.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(recorder.pid, signal.SIGKILL)
|
||||
recorder.wait()
|
||||
record_log.close()
|
||||
if process.poll() is None:
|
||||
os.killpg(process.pid, signal.SIGINT)
|
||||
try:
|
||||
process.wait(timeout=20)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
process.wait()
|
||||
if rviz is not None:
|
||||
os.killpg(rviz.pid, signal.SIGINT)
|
||||
try:
|
||||
rviz.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(rviz.pid, signal.SIGKILL)
|
||||
rviz.wait()
|
||||
if log:
|
||||
log.close()
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -6,6 +6,7 @@ import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from collections import Counter
|
||||
@@ -19,6 +20,9 @@ from nav2_msgs.srv import IsPathValid
|
||||
from rcl_interfaces.srv import GetParameters
|
||||
from std_srvs.srv import Trigger
|
||||
from rclpy.utilities import get_rmw_implementation_identifier
|
||||
sys.path[:0] = [str(Path(__file__).resolve().parents[1] / '_internal'),
|
||||
str(Path(__file__).resolve().parents[1])]
|
||||
import project_env
|
||||
from nav2_startup import path_probe_request
|
||||
|
||||
NODES = ['map_server', 'controller_server', 'planner_server', 'smoother_server',
|
||||
@@ -77,13 +81,21 @@ def main():
|
||||
args = parser.parse_args()
|
||||
if not args.map.is_file():
|
||||
parser.error('map missing')
|
||||
workspace = project_env.WORKSPACE
|
||||
try:
|
||||
gz_exe = project_env.find_gz_bin()
|
||||
bin_dir = project_env.find_bin_dir(workspace)
|
||||
if args.goal is not None:
|
||||
nav_client = project_env.require_executable(bin_dir/'nav_client', 'nav_client')
|
||||
except project_env.ProbeError as error:
|
||||
parser.exit(1, f'{parser.prog}: {error}\n')
|
||||
args.output.mkdir(parents=True, exist_ok=True)
|
||||
session = uuid.uuid4().hex[:12]
|
||||
os.environ.update(GZ_BIN=str(gz_exe), SENTRY_BIN_DIR=str(bin_dir))
|
||||
os.environ.update(ROS_DOMAIN_ID=str(50+int(session[:8], 16) % 50), GZ_PARTITION=f'lio_stack_{session}',
|
||||
ROS2CLI_DISABLE_DAEMON='1',
|
||||
HEADLESS='1', NAV2='1', RVIZ='0', LOCALIZATION='lio', LIO_MODE='localization',
|
||||
LIO_MAP=str(args.map.resolve()), SENTRY_LOG=str((args.output/'stack.log').resolve()))
|
||||
workspace = Path(__file__).resolve().parents[1]
|
||||
log = None
|
||||
if args.launcher == 'shell':
|
||||
command = ['bash', str(workspace/'scripts/sentry_up.sh')]
|
||||
@@ -202,7 +214,7 @@ def main():
|
||||
and counts['map_to_base_link'] == 0)
|
||||
(args.output/'result.json').write_text(json.dumps(result, indent=2))
|
||||
if args.goal and result['passed']:
|
||||
goal = subprocess.run([str(workspace/'build/bin/nav_client'), *map(str, args.goal), '0'],
|
||||
goal = subprocess.run([str(nav_client), *map(str, args.goal), '0'],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=200)
|
||||
(args.output/'goal.log').write_text(goal.stdout)
|
||||
result['goal_exit_code'] = goal.returncode
|
||||
Reference in new issue
Block a user