diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 56268ea..c7a855b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,9 +1,11 @@ -# CI: pyflakes + hardware-free tests (oakd / slam tests deselected), on pull requests only -# (not again when a PR is merged); run it by hand from the Actions tab if needed. +# CI: pyflakes + hardware-free tests (oakd / slam tests deselected), on pull requests and on +# every push to main; run it by hand from the Actions tab if needed. name: CI on: pull_request: + push: + branches: [main] workflow_dispatch: concurrency: diff --git a/.github/workflows/jetson-image.yml b/.github/workflows/jetson-image.yml new file mode 100644 index 0000000..e60872f --- /dev/null +++ b/.github/workflows/jetson-image.yml @@ -0,0 +1,50 @@ +# Jetson image (JetPack 6, aarch64) built natively on an arm64 runner: on car-v* tags it is pushed +# to ghcr.io; run by hand from the Actions tab to only build it. ORB_SLAM3 is checked out without +# the private firmware submodule, which the image does not need. +name: Jetson image + +on: + push: + tags: ["car-v*"] + workflow_dispatch: + inputs: + target: + description: "Dockerfile target (runtime = with ORB-SLAM3, noslam = without)" + default: runtime + type: choice + options: [runtime, noslam] + +permissions: + contents: read + packages: write + +jobs: + build: + runs-on: ubuntu-24.04-arm + timeout-minutes: 240 + steps: + - uses: actions/checkout@v4 + with: + submodules: false + + - name: ORB_SLAM3 submodule + run: git submodule update --init --depth 1 ORB_SLAM3 + + - name: Disk space for the JetPack base image + run: | + sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache || true + sudo docker system prune -af || true + df -h / + + - name: Build + run: | + docker build --target "${{ inputs.target || 'runtime' }}" -t pilot_core-jetson -f Dockerfile . + docker run --rm --shm-size=1g --entrypoint python3 pilot_core-jetson scripts/jetson_selftest.py --only shm,buffers + + - name: Push + if: startsWith(github.ref, 'refs/tags/car-v') + run: | + echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io -u "${{ github.actor }}" --password-stdin + image="ghcr.io/$(echo "${{ github.repository }}" | tr '[:upper:]' '[:lower:]')" + docker tag pilot_core-jetson "$image:${GITHUB_REF_NAME}" + docker push "$image:${GITHUB_REF_NAME}" diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..8ac6769 --- /dev/null +++ b/NOTICE @@ -0,0 +1,14 @@ +pilot_core +Copyright 2024-2026 UTASR - UT Autonomous Scale Racing + +pilot_core is licensed under the Apache License, Version 2.0 (LICENSE), with the +exceptions below. + +ORB-SLAM3 (submodule ORB_SLAM3/, a fork of UZ-SLAMLab/ORB_SLAM3) is licensed under the +GNU General Public License, version 3 (ORB_SLAM3/LICENSE). orbslam3_wrapper/ links it +and is distributed under the GPL, version 3 or later, as well. The built module +orbslam3_python, and any program or image that includes it (the Dockerfile's slam-build +and runtime targets), is a combined work under the GPL, version 3. The Dockerfile's +noslam target and the Python packages run without ORB-SLAM3 and stay under Apache 2.0. + +The Arduino firmware (submodule firmware/) is a separate repository with its own terms. diff --git a/ORB_SLAM3 b/ORB_SLAM3 index 0bf8173..cea650c 160000 --- a/ORB_SLAM3 +++ b/ORB_SLAM3 @@ -1 +1 @@ -Subproject commit 0bf817361a348ec4707a1d2150d7fd4425788093 +Subproject commit cea650c34373632f13c6b93811403791f7ae0499 diff --git a/README.md b/README.md index e524051..2d881f5 100644 --- a/README.md +++ b/README.md @@ -9,25 +9,26 @@ mapping, control and actuation, run as Python processes that share data through shared-memory ring buffers. The same pipeline drives the real car (OAK-D, Jetson, Arduino) and the AutoDRIVE RoboRacer simulator. -![Telemetry HUD: a mapping lap, then a racing lap, in the AutoDRIVE RoboRacer sim](docs/images/hud.gif) +![Telemetry HUD: a camera-only mapping lap, then racing, in the AutoDRIVE RoboRacer sim](docs/images/hud.gif) -The AutoDRIVE RoboRacer sim at 5× speed. A LiDAR follow-the-gap lap maps the track and closes -the loop, then `pure_pursuit` races the boundary it just extracted (16.73 s, 0 collisions). -Every panel is drawn from the recorded buffers on one clock: - -- sim chase view -- car camera with the live Fast-SCNN segmentation -- map built from LiDAR, with the trail coloured by speed -- controller command vs. what the safety supervisor actually sent - -Rendered by [`scripts/render_hud.py`](#telemetry-hud). Full-resolution frame: [hud_frame.png](docs/images/hud_frame.png). +The AutoDRIVE RoboRacer sim at 4× speed, camera only: follow-the-gap on the segmentation's +track edge drives the mapping lap, the walls come from an occupancy grid over those scans, and +`pure_pursuit` races the map it just built. Every panel is drawn from the recorded buffers on one +clock (sim chase view, car camera with the live Fast-SCNN mask, map and trail, commands before and +after the safety supervisor), by [`scripts/render_hud.py`](#telemetry-hud). +Full-resolution frame: [hud_frame.png](docs/images/hud_frame.png). | | | | --- | --- | -| **Sim validation** | link, arming, steering, reset, stop and map-then-race checks pass; 84 benchmark runs, 0 errors ([results](docs/results.md)) | -| **Controllers** | `pure_pursuit`: 12.89 s best practice lap, 0 collisions; `mpc` about 0.25 s per lap slower, with the lowest cross-track error | -| **Vision** | sim track segmentation IoU 0.94 on an unseen track, live in the loop | -| **Safety** | neutral until armed; 150 ms command watchdog; speed cap and slew limits; RC override on the car | +| **No LiDAR** | car and sim map and race from the camera's segmentation; one set of workers for both ([sim to real](docs/sim_to_real.md)) | +| **Mapping in the loop** | practice track mapped in 55 s with 0 hits, 3 of 3 runs; then 10 laps, 0 collisions, 76.2–76.9 s. Compete track mapped in 3 of 3 runs, 4–5 hits ([results](docs/results.md)) | +| **Racing** | compete track, 10 laps on the camera map: 120.04 s with 0 collisions in 2 of 5 runs (published final: 15th 113.19 s) | +| **Sim to real** | a SLAM-like degraded pose for the sim; latency and dropouts, not noise, are what the race settings cannot take yet | +| **Jetson** | self-test before every start, per-stage latency from any recording, deploys from release tags, image built in CI ([deployment](docs/deployment.md)) | +| **Safety** | neutral until armed; 150 ms command watchdog; speed cap and slew limits; RC override and a 250 ms firmware timeout on the car | +| **Tests** | 398 hardware-free tests in CI | + +Nothing here has yet run on the car with this code; [docs/roadmap.md](docs/roadmap.md#car) lists the steps. ## Quick start @@ -87,17 +88,18 @@ All timestamps are on `time.monotonic()`. Controllers use signed units (steering | `control_mode` | Controller | Needs | | -------------- | ---------- | ----- | -| `pure_pursuit` (default), `stanley`, `lqr`, `mpc` | Track followers | SLAM + mapped track | +| `pure_pursuit` (default), `stanley`, `lqr`, `mpc` | Track followers (`lqr` / `mpc` sim-only until the car's yaw rate is measured) | SLAM + mapped track | | `policy` | PPO policy (ONNX) from `rl/train.py` | SLAM + mapped track + model | | `depth_ftg` | Follow-the-Gap on a depth scan | depth camera | | `bc`, `vae` | Behaviour cloning / VAE policy (ONNX) | depth camera + model | -**No LiDAR on the car.** The follow-the-gap mapping drive (`track_control.mapping_drive`) -takes a 2D scan. In the sim that is the LiDAR's; on the car it is built from the edge of -the segmentation mask and the depth at that edge (`control/seg_scan.py`, `seg_scan:` in the -configs, needs `vision.enabled`). On the sim's showcase run, inside the camera's view, it -places walls within 0.9 cm median (10.9 cm p90) of the LiDAR, misses none within 3 m, and -steers within 0.2° of the LiDAR-driven gap follower ([results](docs/results.md#segmentation-edge-scan)). +**No LiDAR, on the car or in the sim.** `SegScanWorker` turns the segmentation mask's edge +into a LiDAR-format scan (`control/seg_scan.py`): the depth at the edge places it, or where there +is none, the point where its pixel's ray meets the floor. The follow-the-gap mapping drive +(`track_control.mapping_drive`) drives on that scan, and `MappingWorker` builds the walls from it +on an occupancy grid (`control/occupancy_map.py`): rays free the floor they cross, so an edge +placed short from far away is cleared by the floor seen up close. The same workers run on the car +and in the sim ([docs/sim_to_real.md](docs/sim_to_real.md)). Safety supervisor (`control/safety.py`): neutral until armed; commands older than 150 ms, future-stamped or non-finite → neutral throttle; 1.5 m/s speed cap, reverse @@ -156,15 +158,16 @@ python scripts/recording_to_dataset.py --vision datasets/track --bootstrap `config_autodrive.yaml` runs the whole pipeline against the AutoDRIVE RoboRacer Unity simulator. pilot_core is the server the sim connects to on port 4567, so no ROS or bridge is involved. Sensors fill the usual buffers, and the actuator's supervised -command goes back to the sim. A LiDAR follow-the-gap lap maps the track, then the -control mode races on it. Setup on a GPU box, the sim's protocol quirks, calibration -and the benchmark are in [docs/autodrive.md](docs/autodrive.md). +command goes back to the sim. A follow-the-gap lap on the camera's scan maps the track, then +the control mode races on it; `sim_pose_degrade.enabled` makes the sim's ground-truth pose late, +noisy and drifting like ORB-SLAM3's. Setup on a GPU box or a Slurm cluster, the sim's protocol +quirks, calibration and the benchmark are in [docs/autodrive.md](docs/autodrive.md). ```bash python start.py --config config_autodrive.yaml # then: python scripts/autodrive_sim_ctl.py connect ``` -Validation and benchmark results: [docs/results.md](docs/results.md). +Results: [docs/results.md](docs/results.md). ## Telemetry HUD @@ -193,7 +196,7 @@ contents, checksums, rebuild commands and the data still to collect are in | Path | Contents | | ---- | -------- | | `start.py` | Entry point: builds the pipeline from a config, supervises workers, handles keys | -| `workers/` | One process per stage (camera, IMU, SLAM, LiDAR, state, mapping, vision, control, actuator, AutoDRIVE link, recorder) | +| `workers/` | One process per stage (camera, IMU, SLAM, segmentation scan, state, mapping, vision, control, actuator, AutoDRIVE link, recorder) | | `shared_buffer/` | Shared-memory ring buffers, one typed buffer per stream | | `control/` | Controllers, EKF, safety supervisor, bicycle-model sim (plain library) | | `vision/` | Track segmentation models, training and inference | @@ -213,6 +216,7 @@ contents, checksums, rebuild commands and the data still to collect are in python -m pytest -m "not oakd and not slam" # hardware-free suite (CI) OAKD_AVAILABLE=1 python -m pytest -m oakd # with an OAK-D on USB 3 python -m pyflakes control vision workers shared_buffer rl scripts tests start.py +python scripts/jetson_selftest.py --skip camera,i2c # the checks the Jetson runs before a start ``` ## Documentation @@ -220,14 +224,16 @@ python -m pyflakes control vision workers shared_buffer rl scripts tests start.p | Guide | | | ----- | - | | [docs/autodrive.md](docs/autodrive.md) | AutoDRIVE sim: setup, protocol, calibration, benchmark, vision, telemetry export | -| [docs/results.md](docs/results.md) | Sim validation and benchmark results | +| [docs/results.md](docs/results.md) | Sim results: camera-only racing, in-loop mapping, degraded pose, stage latency | +| [docs/sim_to_real.md](docs/sim_to_real.md) | Every gap between the sim and the car, and how the pipeline handles it | | [docs/oakd.md](docs/oakd.md) | OAK-D bench check, USB 3 requirement, open camera items | | [docs/slam.md](docs/slam.md) | ORB-SLAM3 build and the Python wrapper | -| [docs/deployment.md](docs/deployment.md) | Running on the Jetson, natively or in Docker | +| [docs/deployment.md](docs/deployment.md) | Running on the Jetson: release tags, self-test, measuring, Docker | | [docs/datasets.md](docs/datasets.md) | Data and model bundles, and what is still to collect | | [docs/roadmap.md](docs/roadmap.md) | What is next | | `firmware/README.md` | Arduino firmware and the I2C interface | ## License -[Apache-2.0](LICENSE). ORB-SLAM3 (submodule, linked by `orbslam3_wrapper`) is GPLv3. +[Apache-2.0](LICENSE), except `orbslam3_wrapper` and anything built with it, which link the +GPLv3 ORB-SLAM3 submodule and are GPLv3 ([NOTICE](NOTICE)). diff --git a/bench/2026-10-29_autodrive/fig_steer_collisions.png b/bench/2026-10-29_autodrive/fig_steer_collisions.png new file mode 100644 index 0000000..4a2c424 Binary files /dev/null and b/bench/2026-10-29_autodrive/fig_steer_collisions.png differ diff --git a/bench/2026-10-29_autodrive/results.md b/bench/2026-10-29_autodrive/results.md new file mode 100644 index 0000000..411f021 --- /dev/null +++ b/bench/2026-10-29_autodrive/results.md @@ -0,0 +1,36 @@ +# AutoDRIVE re-run and steering-cap sweep (2026-10-29) + +> **Superseded: these runs used a LiDAR-built map and fused the sim's own velocity.** The +> race map and racing line were made in June from a LiDAR mapping lap on the ground-truth +> pose, and StateWorker fused the sim's exact speed. pilot_core no longer does either (no +> LiDAR; no ground-truth speed): see [the no-LiDAR runs](../2026-10-31_autodrive_nolidar/results.md). The leaderboard comparison is +> also not like-for-like: the track was known and settings were tuned on it, one run each. + +`scripts/autodrive_bench.py run --config config_autodrive_compete.yaml --laps 10`, stock 2026-iros +builds, L40S. Scored like the published final: race time + 10 s per collision. + +| run | laps | collisions | laps (s) | adjusted (s) | place of 23 | +|---|---|---|---|---|---| +| qualifier, practice track | 10 | 0 | 9.19, then 6.89-6.98 | ~71.6 | qualified | +| final, compete, steer_lat_accel 5.0 (config) | 10 | 0 | 13.39, then 10.52-10.76 | **109.07** | **15** | +| compete, steer_lat_accel 5.5 | 10 | 6 | 13.98, 10.43-11.62 | 172.85 | 22 | +| compete, steer_lat_accel 6.0 | 8 (stopped at 10+ hits) | 11 | 10.93-12.05 | - | - | +| compete, steer_lat_accel 7.0 | 5 (stopped) | 11 | 10.78-11.75 | - | - | +| compete, steer_lat_accel 8.0 | 5 (stopped) | 11 | 10.60-12.20 | - | - | + +| compete, accel / decel 8 m/s^2 (cap 5.0), 3 runs | 10 | 0 | 12.62, then 10.36-10.65 | **107.19 / 107.17 / 107.62** | **14** | +| qualifier, accel / decel 8 m/s^2 | 10 | 0 | 9.03, then 6.86-6.91 | ~71.0 | qualified | + +Published final: 1st 71.82 s (best lap 7.16 s), 14th 107.77 s, 15th 113.19 s. + +- A higher cap hits the wall at the exit of the bottom hairpin, every time at the same spot + (x 2.4, y -15.3: clipping the end of the inner wall at ~2 m/s), and at 6.0 also out of the + top hairpin (fig_steer_collisions.png). The zig-zags never touched. +- Even clean it would gain little: the best lap at 5.5 was 10.43 s against 10.52 s. +- Where the time goes, flying lap at 5.0: mean 4.1 m/s (the winners ~6.1 m/s); hairpins mean + 2.3 m/s (min 1.6), zig-zag 3.8 m/s, the long straight peaks at 8.8 m/s (v_max 12, accel and + decel 5 m/s^2 never let it get there). + +accel / decel 8 m/s^2 is now in config_autodrive_compete.yaml: 1.5-1.9 s off the race, mostly the +standing-start lap (13.39 -> 12.62 s). The straight still peaks at ~8.6 m/s, so the planner's +acceleration is not what limits it there: the sim car does not accelerate faster than that. diff --git a/bench/2026-10-29_vio_sim/fig_dual_imu.png b/bench/2026-10-29_vio_sim/fig_dual_imu.png new file mode 100644 index 0000000..9e4587c Binary files /dev/null and b/bench/2026-10-29_vio_sim/fig_dual_imu.png differ diff --git a/bench/2026-10-29_vio_sim/fig_slam_compare.png b/bench/2026-10-29_vio_sim/fig_slam_compare.png new file mode 100644 index 0000000..0ce44a7 Binary files /dev/null and b/bench/2026-10-29_vio_sim/fig_slam_compare.png differ diff --git a/bench/2026-10-29_vio_sim/inertial_fix.md b/bench/2026-10-29_vio_sim/inertial_fix.md new file mode 100644 index 0000000..6e09462 --- /dev/null +++ b/bench/2026-10-29_vio_sim/inertial_fix.md @@ -0,0 +1,120 @@ +# ORB-SLAM3 RGB-D-inertial reset loop: cause and fork fix (2026-10-29) + +vast.ai L40S / EPYC 7713. ORB-SLAM3 = the UTASR CUDA fork, upstream policy +(`run_orbslam3.py --upstream-policy`) vs branch `inertial-depth-recovery` (e8bacc9). +Values are per run (3 repeats), `a/b/c`. + +## Cause + +Upstream ORB-SLAM3, in every inertial mode: + +1. resets the active map on any tracking loss before the IMU is initialised and before + inertial BA 2 (~15 s after it); +2. until the IMU is initialised, inserts keyframes only every 0.25 s, and never for weak + visual tracking (also not after initialisation: the IMU is meant to carry it). + +At 4-8 m/s the camera moves 1-2 m between keyframes; inliers fall from ~300 to under 50 +within 4-8 frames, `TrackLocalMap` fails, (1) wipes the map, and the IMU never gets the +~1 s / 10 keyframes it needs to initialise: 84-154 resets per 32 s, IMU never initialised, +each new map tracked for ~0.1 s. + +## Fix (fork, `IMU_RGBD` and `IMU_STEREO` only; `IMU.UpstreamPolicy: 1` restores upstream) + +Depth gives the visual map its scale without the IMU, so a loss is handled as in the +RGB-D mode: no reset, relocalise while the IMU is uninitialised, a new map after 5 s +lost (reset only below 10 keyframes); weak visual tracking asks for a keyframe; no +keyframes from a pose-less frame while lost. (Relocalising after IMU initialisation as +well was tried and dropped: it segfaulted in 3 of 6 runs.) + +## Sequences + +- `render_clean`: the 3 race laps of the sim run re-rendered by `render_track.py` with + exact depth and a non-repeating texture, same ground truth and synthetic IMU. +- `render_blackout`: the same with 0.3 s of featureless frames at 3 s and 9 s. +- `compete_textured_race`: the sim sequence itself (LiDAR depth). Only ~35-65 % of ORB + matches between consecutive frames fit its depth: ORB-SLAM3 loses tracking in every + mode (RGB-D 35 % tracked), so it says nothing about the inertial policy. + +## Results + +| sequence | run | tracked % | maps | resets | IMU init (s) | drift 1 s (%) | +|---|---|---|---|---|---|---| +| render_clean | upstream, IMU noise x1 | 73/73 (1 crash) | 1 | 84/84 | never | 102 | +| render_clean | fix, x1 | 31/24/28 | 3-5 | 0 | 1.2/1.2/7.3 | 19/39/36 | +| render_clean | fix, x10 | 53/82/83 | 2-3 | 0 | 1.2 | 2/1/1 | +| render_clean | RGB-D only | 100 | 1 | 0 | - | 1 | +| render_blackout | upstream, x1 | 71/70/71 | 1 | 84-85 | never | 102 | +| render_blackout | fix, x10 | 67/67/67 | 2 | 0 | 1.2/1.2/7.0 | 1/1/2 | +| render_blackout | RGB-D only | 81 | 3 | 0 | - | 1 | +| compete_textured_race | upstream, x1 | 49/49 (1 crash) | 1 | 152/154 | never | 101 | +| compete_textured_race | fix, x1 | 4/4/4 | 1 | 0 | never | 101 | + +Upstream's "tracked" counts frames of maps that live ~0.1 s each: its trajectory is +fragments (drift ~100 %). "x10" multiplies the IMU noise densities and random walks given +to ORB-SLAM3 (`--imu-noise-scale 10`); `gen_orbslam_settings.py --imu` already writes +values 35-60x the synthetic IMU's. + +- The reset loop is gone: 0 resets, the IMU initialises at ~1.2 s, maps persist and, + while tracked, drift is 1-2 % of distance per second instead of ~100 %. +- Still not as robust as RGB-D only: 53-83 % tracked against 100 %. After IMU + initialisation the tracker leans on the IMU prediction; its speed estimate drifts low + (7-28 % within 2 s at x1) and tracking collapses. Inflating the IMU noise helps (x10) + but runs vary (48-83 % on the same sequence). Inertial BA 2 was reached in 2 of 9 fix + runs. +- ORB-SLAM3 crashed (segfault) in ~1 of 9 runs on this box in every mode, upstream policy + and RGB-D only included: the fork's build here, not the policy. + +Serial latency on `render_clean`, tracking call, ms (mean / p50 / p95 / p99 / max): + +| run | tracked % | ATE RMSE (m) | drift 1 s (%) | latency | +|---|---|---|---|---| +| ORB-SLAM3 fix, IMU_RGBD x10 | 48 | 6.52 (3 maps) | 5.0 | 11.0 / 7.7 / 42.3 / 60.9 / 65.1 | +| ORB-SLAM3 RGB-D | 100 | 0.107 | 0.7 | 12.3 / 8.4 / 41.4 / 48.9 / 58.6 | +| cuVSLAM RGB-D + IMU + SLAM | 100 | 0.900 | 0.6 | 38.0 / 2.8 / 285.1 / 700.5 / 837.9 | +| cuVSLAM RGB-D + IMU, odometry only | 100 | 0.245 | 0.4 | 3.0 / 2.7 / 4.4 / 5.4 / 149.3 | + +On this richly textured sequence cuVSLAM's SLAM back end runs inside `track()`: 110 calls +over 100 ms. Its odometry alone stays at 3-4 ms. + +## Verdict + +Use ORB-SLAM3 in RGB-D mode on the car for now. The inertial mode no longer destroys its +map, but at race speeds it is less robust than RGB-D alone; check it on a real recording +(real IMU, real depth) with `--imu-noise-scale` 1 and 10 before enabling `slam.inertial`. + +## Update: real-time replay, CPU budget, startup (fork 7cb97e4) + +Two benchmark-harness faults distorted everything above: + +- The runners fed frames as fast as tracking allowed (~3x real time for ORB-SLAM3): its + local-mapping thread (keyframes, IMU initialisation, inertial BA) fell behind. Now the + sequence's clock (`--speed 1`). +- The container reports 255 cores but is capped at 30.6 CPUs: ORB-SLAM3's ~500 threads got + the process throttled, which was its 40-60 ms p95. Now pinned (`cpulimit.py`, `--cpus 8`). + +And a fork fix for the start: before the IMU is initialised the inertial modes used +monocular-inertial frame tracking (10 px search window, poses accepted from any number of +matches); through a 4-5 m/s swerve 0.8 s in it lost tracking in 2-7 of 9 runs. With depth, +the RGB-D rules now apply until the IMU is initialised: 18 of 18 runs tracked the first +10 s with no loss, IMU initialised at ~1.1 s. A young lost map (before inertial BA 2) is +given up after 0.5 s instead of 5 s (`IMU.EarlyLostTimeout`). + +Same mode for both: RGB-D + IMU + SLAM. Real time, 8 pinned cores, 3 runs sharing the GPU. +ORB-SLAM3 with IMU noise x10 (`--imu-noise-scale 10`; `gen_orbslam_settings.py --imu` +writes values 35-60x the synthetic IMU's for the car). + +| sequence | system | tracked % | maps | ATE RMSE (m) | drift 1 s (%) | latency p50 / p95 (ms) | +|---|---|---|---|---|---|---| +| clean | ORB-SLAM3 CUDA (3 runs) | 100/100/100 | 1 | 0.12/0.10/0.17 | 0.7/0.7/0.6 | 7.8 / 9.9 | +| clean | cuVSLAM | 100 | 1 | 0.24 | 1.8 | 7.0 / 1837 | +| blackouts 20 s, 26 s | ORB-SLAM3 CUDA (3 runs) | 98/98/98 | 1 | 0.19/0.14/0.14 | 0.9/0.7/1.1 | 7.8 / 10.0 | +| blackouts 20 s, 26 s | cuVSLAM | 100 | 1 | 1.84 | 4.7 | 4.0 / 7.1 | +| blackouts 3 s, 9 s | ORB-SLAM3 CUDA (3 runs) | 96/96/96 | 3 | 6.45/6.44/6.50 | 1.1 | 7.7 / 10.0 | +| blackouts 3 s, 9 s | cuVSLAM | 100 | 1 | 3.95 | 9.8 | 4.2 / 7.2 | + +- ORB-SLAM3's tracked % excludes the blank frames (it gives no pose there; cuVSLAM gives + IMU-only poses). A blackout before inertial BA 2 (~16 s) still costs it a new map, hence + the ATE over 3 maps; afterwards it rides through on the IMU. +- With the true IMU noise (x1) it tracks 93-95 % in 3-4 maps: inflate the noise. +- cuVSLAM's SLAM back end stalls its tracking call on this texture (p95 1.8 s on the clean + laps); its odometry alone: 7.4 / 15.2 ms, ATE 1.58 m. diff --git a/bench/2026-10-29_vio_sim/plot_results.py b/bench/2026-10-29_vio_sim/plot_results.py new file mode 100644 index 0000000..b42ddbc --- /dev/null +++ b/bench/2026-10-29_vio_sim/plot_results.py @@ -0,0 +1,83 @@ +import csv, json, numpy as np +import matplotlib +matplotlib.use("Agg") +import matplotlib.pyplot as plt + +SURF, INK, INK2, MUTED, GRID = "#fcfcfb", "#0b0b0b", "#52514e", "#8a8984", "#e8e7e3" +C = {"imu_ekf": "#2a78d6", "pose_ekf": "#eb6834", "slam_raw": "#1baf7a"} +LBL = {"imu_ekf": "Rear IMU + SLAM (ImuEKF, new)", "pose_ekf": "SLAM poses only (PoseEKF, car today)", "slam_raw": "Latest SLAM pose, no filter"} +plt.rcParams.update({"font.size": 10, "axes.edgecolor": MUTED, "axes.labelcolor": INK2, "xtick.color": INK2, "ytick.color": INK2, + "axes.facecolor": SURF, "figure.facecolor": SURF, "axes.grid": True, "grid.color": GRID, "grid.linewidth": 0.8, + "axes.spines.top": False, "axes.spines.right": False, "lines.linewidth": 2, "legend.frameon": False, "axes.axisbelow": True}) + +r = list(csv.DictReader(open("/workspace/bench/results/fig_bo0/ticks.csv"))) +t0 = float(r[0]["t"]) +t = np.array([float(x["t"]) for x in r]) - t0 +f = lambda k: np.array([float(x[k]) if x[k] not in ("", "nan") else np.nan for x in r]) +err = {n: np.hypot(f(n + "_x") - f("truth_x"), f(n + "_y") - f("truth_y")) for n in C} +gaps = [(3.0, 3.3), (9.0, 9.3)] + +fig, ax = plt.subplots(4, 1, figsize=(11, 13), gridspec_kw={"height_ratios": [1.2, 1.2, 1, 1]}) +fig.suptitle("Dual IMU in the sim: rear-of-car IMU + ORB-SLAM3 vs the car's current estimator\n" + "rendered race laps, two 0.3 s camera blackouts (grey), what the controller would see at each 100 Hz tick", + fontsize=12, color=INK, x=0.01, ha="left") +def shade(a, lo, hi): + for g0, g1 in gaps: + if g1 > lo and g0 < hi: + a.axvspan(g0, g1, color="#d9d8d4", alpha=0.7, lw=0) +for n in ("slam_raw", "pose_ekf", "imu_ekf"): + ax[0].plot(t, err[n], color=C[n], label=LBL[n], lw=1.6 if n != "imu_ekf" else 2.2) +shade(ax[0], 0, 33) +ax[0].set_ylabel("position error (m)"); ax[0].set_xlim(0, t[-1]); ax[0].set_ylim(0, 4.5) +ax[0].set_title("Position error, whole run", loc="left", color=INK, fontsize=11) +ax[0].legend(loc="upper right") +m = (t > 2.6) & (t < 4.6) +for n in ("slam_raw", "pose_ekf", "imu_ekf"): + ax[1].plot(t[m], err[n][m], color=C[n], lw=1.6 if n != "imu_ekf" else 2.4) +shade(ax[1], 2.6, 4.6) +ax[1].set_ylabel("position error (m)"); ax[1].set_xlim(2.6, 4.6); ax[1].set_ylim(0, 2.3) +ax[1].set_title("Zoom on the first blackout: the IMU carries the pose; SLAM's bad first poses after it are rejected", loc="left", color=INK, fontsize=11) +ax[1].annotate("blackout", (3.15, 2.1), ha="center", color=INK2) +ax[1].annotate("SLAM's first poses after the blackout\nare ~1.2 m off; ImuEKF rejects them", (3.75, 1.45), color=INK2, fontsize=9) +m = (t > 5) & (t < 13) +ax[2].plot(t[m], np.degrees(f("pose_ekf_r")[m]), color=C["pose_ekf"], lw=1.4) +ax[2].plot(t[m], np.degrees(f("imu_ekf_r")[m]), color=C["imu_ekf"], lw=2.2) +ax[2].plot(t[m], np.degrees(f("truth_yaw_rate")[m]), color=INK, lw=1.2, ls="--", label="truth") +shade(ax[2], 5, 13) +ax[2].set_ylabel("yaw rate (deg/s)"); ax[2].set_xlim(5, 13); ax[2].set_ylim(-200, 200) +ax[2].set_title("Yaw rate: gyro (blue) vs differenced poses (orange); truth dashed", loc="left", color=INK, fontsize=11) +ax[2].legend(loc="upper right") +ax[3].plot(t[m], f("pose_ekf_v")[m], color=C["pose_ekf"], lw=1.4) +ax[3].plot(t[m], f("imu_ekf_v")[m], color=C["imu_ekf"], lw=2.2) +ax[3].plot(t[m], f("truth_speed")[m], color=INK, lw=1.2, ls="--", label="truth") +shade(ax[3], 5, 13) +ax[3].set_ylabel("speed (m/s)"); ax[3].set_xlabel("time (s)"); ax[3].set_xlim(5, 13); ax[3].set_ylim(0, 8) +ax[3].set_title("Speed", loc="left", color=INK, fontsize=11) +ax[3].legend(loc="upper left") +fig.tight_layout(rect=(0, 0, 1, 0.955)) +fig.savefig("/workspace/bench/results/fig_dual_imu.png", dpi=110) + +# SLAM comparison: two charts, one axis each +S = json.load(open("/workspace/bench/results/slam_summary.json")) +seqs = list(S) +systems = [("ORB-SLAM3 CUDA", "#2a78d6"), ("cuVSLAM", "#eb6834"), ("cuVSLAM odometry", "#1baf7a")] +fig, ax = plt.subplots(1, 2, figsize=(12, 5)) +fig.suptitle("RGB-D + IMU on the rendered race laps: ORB-SLAM3 CUDA (our fork) vs cuVSLAM, real-time, 8 cores, L40S", + fontsize=12, color=INK, x=0.01, ha="left") +x = np.arange(len(seqs)); w = 0.26 +for k, (sname, col) in enumerate(systems): + vals = [S[s][sname]["ate"] for s in seqs] + b = ax[0].bar(x + (k - 1) * w, vals, w - 0.03, color=col, label=sname + (" (median of %s runs)" % "/".join(str(S[s][sname]["n"]) for s in seqs) if sname.startswith("ORB") else "")) + for xi, v in zip(x + (k - 1) * w, vals): + ax[0].annotate(f"{v:.2f}", (xi, v), ha="center", va="bottom", fontsize=9, color=INK2, xytext=(0, 2), textcoords="offset points") + p95 = [S[s][sname]["p95"] for s in seqs] + ax[1].bar(x + (k - 1) * w, p95, w - 0.03, color=col, label=sname) + for xi, v in zip(x + (k - 1) * w, p95): + ax[1].annotate(f"{v:.0f}" if v >= 10 else f"{v:.1f}", (xi, v), ha="center", va="bottom", fontsize=9, color=INK2, xytext=(0, 2), textcoords="offset points") +ax[0].set_xticks(x, seqs); ax[0].set_ylabel("position error after alignment, ATE RMSE (m)") +ax[0].set_title("Accuracy (lower is better)", loc="left", color=INK, fontsize=11); ax[0].legend(loc="upper left") +ax[1].set_yscale("log"); ax[1].set_xticks(x, seqs); ax[1].set_ylabel("tracking call p95 (ms, log scale)") +ax[1].set_title("Latency p95 (lower is better)", loc="left", color=INK, fontsize=11); ax[1].legend(loc="upper right") +fig.tight_layout(rect=(0, 0, 1, 0.93)) +fig.savefig("/workspace/bench/results/fig_slam_compare.png", dpi=110) +print("ok") diff --git a/bench/2026-10-29_vio_sim/rear_imu_fusion.md b/bench/2026-10-29_vio_sim/rear_imu_fusion.md new file mode 100644 index 0000000..59677f8 --- /dev/null +++ b/bench/2026-10-29_vio_sim/rear_imu_fusion.md @@ -0,0 +1,51 @@ +# Dual IMU, sim: rear-of-car IMU + ORB-SLAM3 in a vehicle-state EKF (2026-10-29) + +> Since written: StateWorker runs ImuEKF on the car's rear IMU (`rear_imu`, d5a71c6), not yet +> driven. Caveat: the rear IMU, the camera IMU and the truth come from one ground-truth +> trajectory, so the time-offset estimate and the no-slip pseudo-measurement (the sim car +> barely slips) are easier here than on a real car. The figures (plot_results.py) read the +> box's /workspace/bench/results/ data, which is not in the repo. + +Option A of the dual-IMU plan: ORB-SLAM3 keeps the OAK-D's IMU (device-timestamped with the +frames); the rear IMU (the Arduino's ICM-20948) drives `control.ImuEKF`, corrected by the +SLAM poses, for the controller's pose, speed, yaw rate and sideslip. + +- Rear IMU: `scripts/vio_bench/make_rear_imu.py`, at the rear axle, ICM-20948 noise and + post-calibration bias, its ~24 Hz DLPF, the Jetson polling the latest sample at 100 Hz + with 1 ms jitter, stamped when the read returns (as `IMUWorker` does today). +- Replay and scoring: `scripts/vio_bench/fuse_rear_imu.py`. SLAM poses arrive at frame + time + their measured tracking time + 5 ms; every rear-IMU tick reads what each + estimator would hand the controller then, against ground truth. The rear IMU's time + offset is estimated first by cross-correlating its yaw rate with the camera IMU's + (found 8.5 ms: the DLPF delay plus the read). +- SLAM: the ORB-SLAM3 RGB-D-inertial runs of the fork (7121458), real-time replay. + +ImuEKF settings: no-slip pseudo-measurement vy_std 0.1 m/s (truth at the rear axle: vy RMS +0.015 m/s), pose gate chi2 16.3, re-anchor to SLAM after 2 s of rejected poses (0.5 s +re-anchored onto SLAM's wrong poses after a blackout; 1-3 s: same elsewhere). + +Medians over runs (clean 12, blackouts at 3/9 s 12, blackouts at 20/26 s 6): + +| laps | estimator | pos RMSE / max (m) | pos in SLAM gaps (m) | yaw RMSE (deg) | speed RMSE (m/s) | yaw rate RMSE (deg/s) | +|---|---|---|---|---|---|---| +| clean | ImuEKF (rear IMU + SLAM) | **0.105** / 0.25 | – | **0.91** | **0.081** | **0.74** | +| clean | PoseEKF (the car today) | 0.116 / 0.27 | – | 2.24 | 0.603 | 32.6 | +| clean | latest SLAM pose | 0.168 / 0.47 | – | 2.20 | – | – | +| blackouts 3 s, 9 s | ImuEKF | **0.132** / 0.34 | **0.121** | **0.98** | **0.088** | **0.73** | +| blackouts 3 s, 9 s | PoseEKF | 0.388 / 3.90 | 0.809 | 5.21 | 1.054 | 41.1 | +| blackouts 3 s, 9 s | latest SLAM pose | 0.485 / 3.88 | 1.412 | 5.18 | – | – | +| blackouts 20 s, 26 s | ImuEKF | **0.131** / 0.28 | **0.090** | **1.11** | **0.078** | **0.76** | +| blackouts 20 s, 26 s | PoseEKF | 0.143 / 0.49 | 0.317 | 2.99 | 0.611 | 33.9 | +| blackouts 20 s, 26 s | latest SLAM pose | 0.216 / 1.52 | 0.911 | 2.62 | – | – | + +- Through a 0.3-0.5 s SLAM gap the ImuEKF stays within ~0.1 m (PoseEKF 0.3-0.8 m, the held + pose 0.9-1.4 m). +- After a blackout ORB-SLAM3's first poses can be 1-2 m off for up to ~1.7 s; the gate + rejects them (without it the ImuEKF followed them: max error 3.7 m). +- The car's PoseEKF gets yaw rate from differencing poses: 33-41 deg/s RMS error, useless + for a controller that uses it (LQR / MPC). The gyro gives 0.7 deg/s. +- Sideslip at the rear axle is estimated to 0.013 m/s (truth ~0 here: the sim car barely + slips; a sliding car is not tested). + +Not yet: the car side (firmware per-sample timestamps and a wider DLPF, a raw rear-IMU +buffer with gyro, StateWorker on ImuEKF, extrinsics), and a real recording with both IMUs. diff --git a/bench/2026-10-29_vio_sim/results.md b/bench/2026-10-29_vio_sim/results.md new file mode 100644 index 0000000..91f8099 --- /dev/null +++ b/bench/2026-10-29_vio_sim/results.md @@ -0,0 +1,37 @@ +# RGB-D-inertial, sim: ORB-SLAM3 (CUDA fork) vs cuVSLAM 17.0.1 (2026-10-29) + +> **Superseded.** These are the first runs: replayed ~3x faster than real time on an +> unpinned, CPU-throttled container, with the upstream inertial policy. The ORB-SLAM3 numbers +> below are not current; see [inertial_fix.md](inertial_fix.md) (real-time, pinned, fork fixes). +> Caveats for all VIO numbers here: the sim and rendered sequences are synthetic (rendered +> images, exact depth and the IMU all come from the same ground truth), ORB-SLAM3's IMU noise +> scale was chosen on the sequences it is scored on, and cuVSLAM had one run per sequence. + +Sequence: textured AutoDRIVE compete track, 3 race laps (10.4-10.9 s each, up to ~8 m/s), +31.7 s, 1297 RGB-D frames at ~53 fps (384x216: the sim camera upscaled, depth from the +LiDAR), synthetic 200 Hz IMU. vast.ai box: NVIDIA L40S, AMD EPYC 7713. 3 repeats, mean ± +sd. How the sequence is built and its limits: [scripts/vio_bench/README.md](../../scripts/vio_bench/README.md). + +| run | tracked | ATE RMSE (m) | drift over 1 s | rot. drift (deg / 1 s) | latency mean / p50 / p95 / p99 / max (ms) | +| --- | --- | --- | --- | --- | --- | +| ORB-SLAM3 CUDA, `IMU_RGBD` | 49.1 ± 0.2 % | 6.62 ± 0.00 | 4.70 m, ~100 % | 60.5 | 9.7 / 8.6 / 30.6 / 55.3 / 79.6 | +| ORB-SLAM3 CPU, `IMU_RGBD` | 49.6 ± 0.1 % | 6.61 ± 0.01 | 4.71 m, ~100 % | 59.3 | 21.7 / 12.7 / 69.7 / 80.2 / 94.0 | +| ORB-SLAM3 CUDA, `RGBD` | 42.5 ± 4.1 % | 5.54 ± 0.72 | 5.44 m, 49 % | 95.4 | 10.0 / 7.2 / 35.4 / 44.9 / 57.9 | +| cuVSLAM, Multisensor RGB-D + IMU + SLAM | 100 % | 5.15 ± 0.91 | 0.86 m, 15.1 % | 7.2 | 4.0 / 3.6 / 5.7 / 8.8 / 190 | +| cuVSLAM, `RGBD` + SLAM | 100 % | 4.87 ± 0.45 | 2.15 m, 17.5 % | 20.9 | 3.5 / 3.2 / 5.8 / 8.7 / 25.4 | + +- **ORB-SLAM3 `IMU_RGBD` never initialised its IMU** (cause and fork fix: [inertial_fix.md](inertial_fix.md)). Within ~1 s after starting it needs + 50 inliers per frame; these images often give fewer, and in the inertial modes any + tracking failure before IMU initialisation (and before inertial BA 2) resets the active + map (`Tracking.cc`, "IMU is not or recently initialized"). ~150 resets per run; more + features (2000 / 3000) and 10-300x IMU noise did not break the loop. `RGBD` mode, which + relocalises instead, tracks for seconds at a time. +- **cuVSLAM tracked every frame**, and the IMU cut its rotation drift 3x (7.2 vs 20.9 + deg/s). Its speed is ~15 % low against ground truth with zero lag and 0.98 turn-rate + correlation: the sim depth's scale error, which inflates every ATE here. +- **Latency:** cuVSLAM's tracking call is ~2.4x faster at the median (3.6 vs 8.6 ms) and + ~5x at p95 (5.7 vs 30.6 ms), except one ~190 ms call when its IMU fusion starts. + ORB-SLAM3's CUDA path vs its CPU path: 8.6 vs 12.7 ms median, 30.6 vs 69.7 ms p95. + At the car's 640x400 these grow; measure on the Orin. +- Not a verdict on accuracy: the sim depth, IMU and textures are synthetic. The real-track + recordings are. diff --git a/bench/2026-10-29_vio_sim/run1_summary.md b/bench/2026-10-29_vio_sim/run1_summary.md new file mode 100644 index 0000000..9ea7506 --- /dev/null +++ b/bench/2026-10-29_vio_sim/run1_summary.md @@ -0,0 +1,11 @@ +# RGB-D-inertial benchmark: compete_textured_race + +1297 frames, 31.7 s; AutoDRIVE sim run /workspace/bench/runs/compete_textured_race + +| run | mode | GPU | tracked | first pose (s) | IMU init (s) | ATE RMSE (m) | ATE max (m) | drift 1 s (m / %) | rot drift 1 s (deg) | latency mean / p50 / p95 / p99 / max (ms) | +|---|---|---|---|---|---|---|---|---|---|---| +| orb_cuda_imu | IMU_RGBD | NVIDIA L40S | 49.3 % | 0.06 | – | 6.622 | 10.220 | 4.698 / 100.8 | 60.48 | 9.4 / 8.4 / 28.0 / 47.6 / 78.0 | +| orb_cpu_imu | IMU_RGBD | NVIDIA L40S | 49.4 % | 0.06 | – | 6.598 | 10.230 | 4.725 / 100.7 | 59.22 | 21.7 / 12.6 / 70.2 / 81.9 / 94.0 | +| orb_cuda_rgbd | RGBD | NVIDIA L40S | 48.3 % | 0.00 | – | 5.688 | 13.113 | 6.562 / 55.0 | 89.80 | 10.0 / 7.1 / 35.9 / 45.4 / 61.9 | +| cuv_imu | Multisensor RGB-D + IMU + SLAM | NVIDIA L40S | 100.0 % | 0.00 | – | 4.093 | 10.285 | 0.864 / 15.5 | 6.26 | 3.9 / 3.6 / 5.4 / 8.5 / 186.0 | +| cuv_rgbd | RGBD + SLAM | NVIDIA L40S | 100.0 % | 0.00 | – | 4.233 | 7.418 | 1.405 / 17.1 | 19.23 | 3.5 / 3.2 / 5.7 / 8.5 / 19.4 | diff --git a/bench/2026-10-29_vio_sim/trajectories.png b/bench/2026-10-29_vio_sim/trajectories.png new file mode 100644 index 0000000..e96db59 Binary files /dev/null and b/bench/2026-10-29_vio_sim/trajectories.png differ diff --git a/bench/2026-10-31_autodrive_nolidar/results.md b/bench/2026-10-31_autodrive_nolidar/results.md new file mode 100644 index 0000000..a1c875d --- /dev/null +++ b/bench/2026-10-31_autodrive_nolidar/results.md @@ -0,0 +1,76 @@ +# AutoDRIVE no-LiDAR race runs (2026-10-31) + +The first valid compete-track runs under the no-LiDAR rule: map from the camera's +segmentation, no LiDAR buffer, no sim speed fused (`use_pose_speed: false`). The sim's pose is +still ground truth (ORB-SLAM3 does not run in the sim). Stock 2026-iros builds, L40S, +640x360, about 23 frames/s, `scripts/cluster/autodrive_job.sh`. Scored like the published +final: race time + 10 s per collision. + +| run | laps | collisions | first lap, then | raw (s) | adjusted (s) | +|---|---|---|---|---|---| +| final 1 | 10 | 1 | 13.74, 11.48-12.56 | 120.64 | 130.64 | +| final 2 | 10 | 0 | 14.01, 11.59-12.00 | 120.04 | **120.04** | +| final 3 | 10 | 0 | 13.97, 11.62-12.08 | 120.46 | **120.46** | +| Ultra quality | 10 | 1 | 13.53, 11.52-12.68 | 119.52 | 129.52 | +| competition start (sim restarted, auto_arm, no keys) | 10 | 1 | 22.51, 11.57-12.63 | 129.53 | 139.53 | +| qualifier, practice track | 10 | 0 | 9.37, 7.30-7.33 | 75.21 | 75.21 | + +Published final: 1st 71.82 s (best lap 7.16 s), 14th 107.77 s, 15th 113.19 s, 23 teams. 120 s +is behind 15th. The qualifier needs 10 clean laps, which it did, in one run. + +The LiDAR-map runs (bench/2026-10-29_autodrive) did 107.17-107.62 s, flying laps 10.4-10.7 s. +They do not count: LiDAR-built map, sim speed fused. Flying laps here are about 11.7 s; at +margin 0.5 on the camera map below they were about 11.1 s, so the margin costs some 0.6 s a lap. + +## The margin decides it + +Same five recordings, same settings otherwise. Before the reach limit and margin 0.65: + +| run (margin 0.5, no reach limit) | collisions | raw (s) | adjusted (s) | +|---|---|---|---| +| final 1 / 2 / 3 | 21 / 6 / 9 | 126.78 / 114.66 / 117.16 | 336.78 / 174.66 / 207.16 | +| Ultra | 5 | 112.72 | 162.72 | +| competition start | 26 | 142.09 | 402.09 | + +All hits were at the two left hairpins. The camera map had a pocket past the real wall at +about (-0.3, 3.5), so the line used room that isn't there, and at the bottom hairpin it passed +0.27 m from the LiDAR map's inner tip (the clean LiDAR-map line: 0.46 m). After a hit the car +respawned at (0.8, 3.7), too close to the line's corner to recover, and hit again every 0.8 s: +20 of the 26 in the competition start. + +## The map + +- The mapping lap never got round clean: 2-3 hits a lap in every setting tried (more wall + clearance, a wider bubble, slower, edge memory up to 5 s; `sweep` stage), down from nearly 5. +- The cloud MappingWorker collects is not usable on this track: within 15 cm of the LiDAR + walls by range (replayed masks), straights / corners: + +| scan range (m) | straights | corners | +|---|---|---| +| 0.6-0.9 | 99 % | 68 % | +| 0.9-1.2 | 91 % | 42 % | +| 1.2-1.5 | 76 % | 40 % | +| 1.5-2.0 | 66 % | 31 % | +| 2.0-3.0 | 61 % | 22 % | + +- `scripts/seg_map.py` builds the map from the recordings instead (five mapping runs, about 7 + laps): an occupancy grid where rays free the floor they cross, masks near a hit or with the + car standing dropped, no wall where the car drove, outer wall closed, at most 0.9 m from the + driven path. Against the LiDAR map, used only to score it: outer wall median 0.13 m, p90 0.30, + max 0.51; inner 0.10, 0.28, 0.42. Half-width min 0.40 m. +- Line (margin 0.65): 44.4 m, max curvature 2.97 1/m, closest wall 0.45 m on the camera map. + +Thresholds (`--ratio`, `--min-occ`, `--edge-range`) were picked looking at the distance to +the LiDAR map, so that much of the method saw it; nothing from that map is in the result. + +## Not settled + +- **The obstacle near (0.4, 4.0).** The top hairpin's hits line up with a straight edge the + camera sees across the outer side at y about 4. It may be a lighting edge or something + physical; the LiDAR map shows no wall there. The margin avoids it, the cause is unknown. +- **Not like-for-like with the leaderboard.** The track was known, the map came from 5 + runs on it, settings were tuned on it, and the segmentation model's labels were LiDAR-derived + (training only). The sim's pose is ground truth. +- **Ultra here is 640x360.** At 1920x1080 Ultra on the vast.ai box the sim ran at 0.52x, 5.2 + frames/s, with 9 collisions, CPU-bound on one core; the organisers' resolution is unknown. +- **Clean is not guaranteed.** 2 of the 5 compete runs had no hit, the others one each. diff --git a/bench/2026-11-09_live_mapping/results.md b/bench/2026-11-09_live_mapping/results.md new file mode 100644 index 0000000..486bf02 --- /dev/null +++ b/bench/2026-11-09_live_mapping/results.md @@ -0,0 +1,69 @@ +# In-loop mapping and the degraded pose (2026-11-09) + +Stock AutoDRIVE RoboRacer `2026-iros` builds, L40S, 640×360, `config_autodrive_compete.yaml`, +`scripts/cluster/autodrive_job.sh` stages `live` and `degraded`. No LiDAR, no sim speed. Scored +like the published final: race time + 10 s per collision. Each live run is one job: a mapping lap +with follow-the-gap on the segmentation-edge scan, the walls from the occupancy grid +(`mapping.wall_source: occupancy`), the racing line from that map (margin 0.65 m), then 10 laps on it. + +## Mapping lap in the loop + +| track | run | map built after (s) | hits during the mapping lap | racing line's closest wall (m) | +| --- | --- | --- | --- | --- | +| practice | 1 / 2 / 3 | 54.9 / 54.9 / 55.5 | 0 / 0 / 0 | 0.50 / 0.50 / 0.48 | +| compete | 1 / 2 / 3 | 89.0 / 92.8 / 87.8 | 5 / 4 / 5 | 0.42 / 0.33 / 0.37 | + +Walls against the LiDAR-built map (used only to score them), median / p90 / max, m: + +| map | outer | inner | +| --- | --- | --- | +| practice live 1 / 2 / 3 | 0.17 / 0.36–0.39 / 0.82–1.07 | 0.08 / 0.19–0.24 / 0.71–0.72 | +| compete live 1 / 2 / 3 | 0.10–0.13 / 0.39–0.40 / 0.56–0.60 | 0.15–0.18 / 0.31–0.33 / 0.65–0.74 | +| compete, offline from five recordings (2026-10-31) | 0.13 / 0.30 / 0.51 | 0.10 / 0.28 / 0.42 | + +After the compete mapping lap, runs 1 and 3 drove their one centre-line lap into a respawn trap +at a hairpin (the car respawned too close to the line's corner and hit again every few tenths of +a second, 900+ hits until the timeout). That lap had no racing line yet; the races below use one. + +## Racing on the live maps (10 laps) + +| track | run | collisions | first lap, then (s) | raw (s) | adjusted (s) | +| --- | --- | --- | --- | --- | --- | +| practice | 1 | 0 | 9.55, 7.44–7.52 | 76.89 | 76.89 | +| practice | 2 | 0 | 9.50, 7.37–7.48 | 76.20 | 76.20 | +| practice | 3 | 0 | 9.63, 7.44–7.51 | 76.94 | 76.94 | +| compete | 1 | 4 | 13.40, 11.84–12.92 | 125.60 | 165.60 | +| compete | 2 | 1 | 13.52, 11.76–12.84 | 122.20 | 132.20 | +| compete | 3 | 7 | 13.16, 11.86–12.69 | 124.06 | 194.06 | + +On the practice track the live map races like the offline one (qualifier 75.21 s, 0 collisions). +On the compete track it does not yet: the lines on the live maps pass 0.33–0.42 m from a wall +against 0.45 m on the offline map, and the hits are at the two left hairpins, as in October. + +## Degraded pose (compete, offline map, 10 laps) + +`sim_pose_degrade` defaults: +33 ms, tracking p50 8.4 / p95 41.4 ms, 1 cm and 0.005 rad white +noise, a bias of 0.07 m per axis reverting over 2 s, 0.15 dropouts per second of 0.3 s. The two +partial runs switch off one part each. + +| pose | run 1 / 2 / 3 collisions | raw (s) | adjusted (s) | laps after the first (s) | +| --- | --- | --- | --- | --- | +| ground truth (2026-10-31, finals) | 1 / 0 / 0 | 120.04–120.64 | 120.04–130.64 | 11.48–12.56 | +| noise and bias only | 0 / 2 / 0 | 120.94–122.52 | 120.94–142.52 | 11.43–12.79 | +| latency and dropouts only | 4 / 12 / 7 | 144.70–151.00 | 185.62–271.00 | 12.88–16.92 | +| everything | 15 / 14 / 12 | 151.52–157.65 | 271.52–307.65 | 13.87–18.60 | + +The race settings are tuned on a pose that is exact and on time. Noise and a bounded bias of +the size ORB-SLAM3 showed barely change the race; latency and dropouts cost about 2–3 s a lap +and several hits, although the state estimator already updates at the capture time and predicts +to the present. An earlier version of the degradation let the bias wander without bound (a random +walk); that is not how SLAM localising against a saved map behaves, and it was replaced. + +## Not settled + +- **Which of latency and dropouts.** They were switched off together. +- **Earlier attempts.** The first compete mapping runs never built a map: a failed extraction + slept 2 s, the next pose then looked like a respawn, and the scans around it were dropped. With + the retry made non-blocking and teleports told apart by speed, the runs above mapped every time. + Practice runs 2 and 3 are from before that fix; they mapped on the first try, so it did not + touch them. Four jobs failed to start the sim on two cluster nodes and were rerun on others. diff --git a/config.yaml b/config.yaml index f3d9b1e..8426417 100644 --- a/config.yaml +++ b/config.yaml @@ -10,9 +10,11 @@ use_oakd_imu: false # true = OAK-D IMU through the camera worker, fals i2c_address: 0x08 # Arduino address. null -> actuator/IMU run as dummies i2c_bus: 1 # /dev/i2c- -# drivable-track segmentation; feeds the seg_scan mapping drive +# drivable-track segmentation; feeds the segmentation-edge scan the mapping lap maps from. +# ground_plane needs no training (RANSAC floor from the depth); switch to onnx once a model +# trained on real-track frames exists (docs/datasets.md) vision: - enabled: false + enabled: true model: ground_plane # ground_plane | onnx onnx_model: track_seg.onnx # model: onnx — network from scripts/train_vision.py (+ .json sidecar) @@ -23,7 +25,7 @@ pwm: steer_min: 1105 # full left steer_max: 1825 # full right steer_neutral: 1461 # straight - throttle_min: 1199 # full backward + throttle_min: 1206 # full backward (firmware ESC_MIN) throttle_max: 1595 # full forward throttle_neutral: 1397 # coast @@ -66,10 +68,10 @@ track_control: max_backward: 0.3 # max reverse input used for braking min_speed_for_backward: 0.3 # m/s, no reverse braking below this -# no LiDAR on the car: a track_control.mapping_drive (follow-the-gap mapping lap, otherwise -# driven by hand with RC) runs on a scan made from the segmentation mask's edge + depth -# (control/seg_scan.py). Needs vision.enabled and a segmentation model trained on the real -# track. camera_height / camera_pitch come from depth_ftg (one camera mount) +# no LiDAR on the car: the segmentation mask's edge + depth make a LiDAR-format scan +# (control/seg_scan.py, SegScanWorker), the same worker as in the sim. The mapping lap's walls +# come from it, and a track_control.mapping_drive (follow-the-gap; otherwise the lap is driven +# by hand with RC) drives on it. camera_height / camera_pitch come from depth_ftg (one camera mount) seg_scan: origin_forward: 0.0 # m, camera ahead of the scan origin @@ -104,6 +106,17 @@ estimator: yaw_std: 0.03 # rad stale_after: 0.5 # s without a pose and we stop driving +# rear-of-car IMU (the Arduino's ICM-20948 over I2C) for the state estimate: StateWorker runs +# control.ImuEKF on it, corrected by the SLAM poses, instead of the pose-only EKF above (gyro +# yaw rate, bridges SLAM gaps; docs/slam.md). Run scripts/check_rear_imu.py on the car first: +# it measures the rate and finds rotation from a hand turn and a push, and prints this block +rear_imu: + enabled: false + rotation: [[1, 0, 0], [0, 1, 0], [0, 0, 1]] # ICM-20948 axes -> car (x forward, y left, z up) + lever_m: [0.0, 0.0] # m, the IMU from the camera in the car frame (x forward, y left) + delay_s: 0.0 # s, the IMU's filter + read delay (check_rear_imu.py --recording) + estimator: {} # control.ImuEstimatorConfig overrides + # safety supervisor, runs in ActuatorWorker safety: command_timeout: 0.150 # s, no fresh command -> neutral throttle @@ -125,11 +138,19 @@ enable_slam: true # ORB-SLAM3 + mapping, same as start.py --enable slam: vocabulary: ORB_SLAM3/Vocabulary/ORBvoc.txt settings: orbslam_oakd_rgbd.yaml # regenerate with scripts/gen_orbslam_settings.py + # RGB-D-inertial ORB-SLAM3 on the OAK-D's own accel + gyro (separate from use_oakd_imu, + # which picks the IMU for imu_buf). Needs the settings' IMU block: generate them with + # scripts/gen_orbslam_settings.py --imu, at the camera's imu_rate_hz (default 100) + inertial: false # mapping / BEV boundaries mapping: - boundary_min_points: 50 # wall points needed before we try extracting boundaries - max_track_half_width: 1.5 # m, wall points further from the driven line are dropped + wall_source: occupancy # occupancy (segmentation-edge scans, as in the sim) | cloud (SLAM map points) + scan_offset: [0.0, 0.0, 0.0] # m, scan origin in the vehicle (camera) frame: [forward, left, up] + bev_axes: [0, 2] # SLAM's levelled camera frame: X right, Z forward + forward_axis: 2 + boundary_min_points: 50 # wall points needed before we try extracting boundaries (cloud) + max_track_half_width: 1.5 # m, wall points further from the driven line are dropped (cloud) recording: false # dump buffers to disk (or start.py --recording) recording_path: /tmp/pilot_recordings # a timestamped folder per run is created here diff --git a/config_autodrive.yaml b/config_autodrive.yaml index 14e12f3..62e7fe8 100644 --- a/config_autodrive.yaml +++ b/config_autodrive.yaml @@ -1,6 +1,6 @@ # AutoDRIVE RoboRacer Unity sim, linked directly (no ROS, no bridge): pilot_core is the # server the sim connects to on sim_port; telemetry in, supervised commands out. -# python start.py --config config_autodrive.yaml # LiDAR mapping lap, then race +# python start.py --config config_autodrive.yaml # segmentation mapping lap, then race # (race on a saved map instead: enable_slam: false, use_saved_map: true below) # then connect the sim: HUD menu -> "Disconnected" toggle, or # python scripts/autodrive_sim_ctl.py connect @@ -24,12 +24,18 @@ fps: 15 depth_max_meters: 15.0 # Joshua Choi's modified build: far clip of DepthCamera.cs (stock build has no depth) depth_raw_scale: null +# no LiDAR, as on the car: the drivable area comes from the camera's segmentation. sim_depth +# prepares the frames it was trained on (upscaled x2, car body painted out) with depth: none +sim_depth: + camera: "sim_camera/camera.yaml" + scale: 2 + depth: none # none: no depth (lidar would synthesise it from the LiDAR) + vision: - enabled: false - # needs sim_depth (frames upscaled x2, car body hidden, depth from the LiDAR): the - # intrinsics are the sim camera's at that resolution, not slam.settings + enabled: true + # the intrinsics are the sim camera's at sim_depth's resolution, not slam.settings camera_settings: "sim_camera/orbslam_settings.yaml" - model: ground_plane # ground_plane | onnx + model: onnx # ground_plane needs depth | onnx # Fast-SCNN trained on sim runs (not tracked; regenerate, docs/autodrive.md "Vision"): # unseen compete track, live: IoU 0.94 onnx_model: "sim_track_seg.onnx" @@ -39,6 +45,12 @@ control_rate_hz: 50 # StateWorker + ActuatorWorker loop rate vehicle_params: "vehicle_params_roboracer.yaml" +# state estimate: a collision respawns the car elsewhere; a pose that far from the +# prediction restarts the EKF there (standing still) and resets the controllers, instead of +# reading the jump as speed and yaw rate (that steered it into the wall again, every respawn) +estimator: + jump_reset_m: 0.4 # m, as mapping.jump_threshold + # runtime safety (ActuatorWorker). In the stock sim throttle behaves like a speed # set-point of ~25 m/s per unit (0.06 -> 1.5 m/s), so every throttle bound is small; # speed_per_throttle is the steady-state fit from docs/autodrive.md (Calibration) @@ -60,29 +72,45 @@ track_control: ki: 0.006 integral_limit: 0.006 max_backward: 0.012 - # drives the LiDAR mapping lap (on the car a human does that with the RC transmitter) + # drives the mapping lap on the segmentation-edge scan (on the car a human can drive it by RC) mapping_drive: speed: 0.6 # m/s min_speed: 0.4 gap_select: area # widest-gap turns into the compete track's hairpin pockets -# the mapping drive's scan from the segmentation mask's edge + depth (control/seg_scan.py), the -# car's stand-in for a LiDAR. Here the LiDAR is used unless source: segmentation (needs -# vision.enabled and sim_depth); scripts/seg_scan_eval.py scores it against the LiDAR offline +# the mapping lap's scan from the segmentation mask's edge (control/seg_scan.py), as on the car; +# with no depth in the sim each edge is placed where its pixel's ray meets the floor seg_scan: - source: auto # auto: LiDAR if there is one | segmentation + source: segmentation # no LiDAR: track edges from the mask, placed on the floor (no depth) camera_pitch: 0.1833 # rad, 10.5 deg down (sim_camera/camera.yaml) camera_height: 0.17 # m origin_forward: -0.2883 # m, camera behind the LiDAR (cam_x - lidar_x), so ranges match its tuning -# LidarProjectionWorker (enable_slam + sim_pose); sim Hokuyo UST-10LX, 1081 rays, 0.06-10 m +# never used (the car has none). With mapping.wall_source: cloud the segmentation-edge scans are +# projected like a LiDAR's (LidarProjectionWorker), with these range / voxel settings lidar: + enabled: false range_min: 0.1 range_max: 9.5 voxel_size: 0.10 move_threshold: 0.05 -# mapping. enable_slam here means LiDAR mapping on the ground-truth pose, not ORB-SLAM3 +# the sim's ground-truth pose published like ORB-SLAM3's on the car: late, noisy, off by a +# wandering bias, with tracking dropouts (control/pose_degrade.py). Defaults from ORB-SLAM3 RGB-D on rendered +# sequences of this track (bench/2026-10-29_vio_sim/inertial_fix.md), not from the car +sim_pose_degrade: + enabled: false + base_latency_s: 0.033 + latency_median_s: 0.0084 + latency_p95_s: 0.0414 + xy_sigma: 0.01 + yaw_sigma: 0.005 + bias_sigma: 0.07 + bias_tau: 2.0 + dropout_rate: 0.15 + dropout_s: 0.3 + +# mapping. enable_slam here means a mapping lap on the ground-truth pose, not ORB-SLAM3 enable_slam: true use_saved_map: false saved_map_path: "maps/autodrive_practice" @@ -90,6 +118,9 @@ slam: vocabulary: "ORB_SLAM3/Vocabulary/ORBvoc.txt" mapping: + wall_source: occupancy # walls from the segmentation-edge scans' occupancy grid + # the segmentation scan's origin in the vehicle frame (camera x - seg_scan.origin_forward) + scan_offset: [0.2733, 0.0, 0.10] boundary_min_points: 50 bev_axes: [0, 1] # sim world is Z-up so X, Y are horizontal forward_axis: 0 # X forward in the sim vehicle frame @@ -99,7 +130,7 @@ mapping: auto_loop_overrun: 1.0 # m past the start before the lap is closed (covers the seam) jump_threshold: 0.4 # m; longer pose steps are sim respawns after a wall hit min_track_half_width: 0.2 # m; a narrower extracted track is rejected (bad lap), map again - boundary_save_path: "maps/autodrive_practice" # null = don't save + boundary_save_path: "maps/autodrive_practice_seg" # null = don't save buffers: frame: diff --git a/config_autodrive_compete.yaml b/config_autodrive_compete.yaml new file mode 100644 index 0000000..cfc22db --- /dev/null +++ b/config_autodrive_compete.yaml @@ -0,0 +1,176 @@ +# AutoDRIVE RoboRacer sim, race settings: config_autodrive.yaml plus a saved map, the +# racing line (scripts/make_raceline.py), the speeds validated on the stock 2026-iros +# compete build (10 laps, 0-1 collisions, laps 11.5-12.1 s; docs/autodrive.md) and auto_arm, +# so it drives as soon as the sim connects (competition container: no operator keys). +# Practice track: saved_map_path / raceline_path -> maps/autodrive_practice_seg. +# python start.py --config config_autodrive.yaml # segmentation mapping lap, then race +# (race on a saved map instead: enable_slam: false, use_saved_map: true below) +# then connect the sim: HUD menu -> "Disconnected" toggle, or +# python scripts/autodrive_sim_ctl.py connect +# Keys: [a] arm, [SPACE] disarm, [r] reset the sim, [l] end the mapping lap, [q] quit. +# Setup on a cloud GPU box (vast.ai): scripts/vast_autodrive_setup.sh; details in docs/autodrive.md. + +sim: autodrive +sim_host: "0.0.0.0" +sim_port: 4567 +auto_arm: true # sim only: armed at start-up, no [a] needed +sim_pose: true # ground-truth pose from the sim (Z-up world, X forward) +sim_camera: true # decode the 192x108 front camera into frame_buf + +# hardware, all unused in the sim +i2c_address: null +i2c_bus: null +use_oakd_imu: false + +resolution: [192, 108] # sim front camera, [width, height] +fps: 15 + +depth_max_meters: 15.0 # Joshua Choi's modified build: far clip of DepthCamera.cs (stock build has no depth) +depth_raw_scale: null + +# no LiDAR, as on the car: the drivable area comes from the camera's segmentation. sim_depth +# prepares the frames it was trained on (upscaled x2, car body painted out) with depth: none +sim_depth: + camera: "sim_camera/camera.yaml" + scale: 2 + depth: none # none: no depth (lidar would synthesise it from the LiDAR) + +vision: + enabled: true + # the intrinsics are the sim camera's at sim_depth's resolution, not slam.settings + camera_settings: "sim_camera/orbslam_settings.yaml" + model: onnx # ground_plane needs depth | onnx + # Fast-SCNN trained on sim runs (not tracked; regenerate, docs/autodrive.md "Vision"): + # unseen compete track, live: IoU 0.94 + onnx_model: "sim_track_seg.onnx" + +control_mode: "pure_pursuit" # pure_pursuit | stanley | lqr | mpc | policy +control_rate_hz: 50 # StateWorker + ActuatorWorker loop rate + +vehicle_params: "vehicle_params_roboracer.yaml" + +# state estimate: a collision respawns the car elsewhere; a pose that far from the +# prediction restarts the EKF there (standing still) and resets the controllers, instead of +# reading the jump as speed and yaw rate (that steered it into the wall again, every respawn) +estimator: + jump_reset_m: 0.4 # m, as mapping.jump_threshold + +# runtime safety (ActuatorWorker). In the stock sim throttle behaves like a speed +# set-point of ~25 m/s per unit (0.06 -> 1.5 m/s), so every throttle bound is small; +# speed_per_throttle is the steady-state fit from docs/autodrive.md (Calibration) +safety: + command_timeout: 0.150 # s; also the age after which AutoDRIVEWorker sends neutral + speed_cap: 12.5 # m/s + cap_margin: 0.2 # m/s + speed_per_throttle: 24.8 # m/s per unit throttle, steady state (0.02..0.10 -> 0.50..2.45 m/s) + max_throttle_no_speed: 0.04 # forward bound with no speed estimate (1 m/s) + max_reverse_throttle: 0.06 # -1.5 m/s + throttle_rate: 0.5 # signed units/s (12 m/s^2 of set-point) + +track_control: + pure_pursuit: # shorter than the default: a long lookahead cuts the + lookahead_min: 0.5 # line's corners into the inside walls + k_v: 0.25 + lookahead_max: 2.0 + raceline_path: "maps/autodrive_compete_seg/raceline.npy" # margin 0.65 m + speed: + v_max: 12.0 # m/s + lat_accel_fraction: 2.0 # profile a_lat = 2.0 * friction_coeff * g = 10.3 m/s^2 + accel: 8.0 # m/s^2 (5 -> 8: compete 109.1 -> 107.2-107.6 s, still 0 collisions; + decel: 8.0 # bench/2026-10-29_autodrive/results.md) + # speed also capped by the steered curvature at 5 m/s^2: the car slides wide at large + # steering long before the profile's a_lat (hairpins, zig-zag apexes) + steer_speed_limit: true + steer_lat_accel: 5.0 + longitudinal: # gains scaled to the sim's 25 m/s per unit throttle + speed_per_throttle: 24.8 # keep equal to safety.speed_per_throttle + kp: 0.01 # throttle per m/s of error + ki: 0.006 + integral_limit: 0.006 + max_backward: 0.012 + # drives the mapping lap on the segmentation-edge scan (on the car a human can drive it by RC) + mapping_drive: + speed: 0.6 # m/s + min_speed: 0.4 + gap_select: area # widest-gap turns into the compete track's hairpin pockets + +# the mapping lap's scan from the segmentation mask's edge (control/seg_scan.py), as on the car; +# with no depth in the sim each edge is placed where its pixel's ray meets the floor +seg_scan: + source: segmentation # no LiDAR: track edges from the mask, placed on the floor (no depth) + camera_pitch: 0.1833 # rad, 10.5 deg down (sim_camera/camera.yaml) + camera_height: 0.17 # m + origin_forward: -0.2883 # m, camera behind the LiDAR (cam_x - lidar_x), so ranges match its tuning + +# never used (the car has none). With mapping.wall_source: cloud the segmentation-edge scans are +# projected like a LiDAR's (LidarProjectionWorker), with these range / voxel settings +lidar: + enabled: false + range_min: 0.1 + range_max: 9.5 + voxel_size: 0.10 + move_threshold: 0.05 + +# the sim's ground-truth pose published like ORB-SLAM3's on the car: late, noisy, off by a +# wandering bias, with tracking dropouts (control/pose_degrade.py). Defaults from ORB-SLAM3 RGB-D on rendered +# sequences of this track (bench/2026-10-29_vio_sim/inertial_fix.md), not from the car +sim_pose_degrade: + enabled: false + base_latency_s: 0.033 + latency_median_s: 0.0084 + latency_p95_s: 0.0414 + xy_sigma: 0.01 + yaw_sigma: 0.005 + bias_sigma: 0.07 + bias_tau: 2.0 + dropout_rate: 0.15 + dropout_s: 0.3 + +# mapping. enable_slam here means a mapping lap on the ground-truth pose, not ORB-SLAM3 +enable_slam: false +use_saved_map: true +saved_map_path: "maps/autodrive_compete_seg" +slam: + vocabulary: "ORB_SLAM3/Vocabulary/ORBvoc.txt" + +mapping: + wall_source: occupancy # walls from the segmentation-edge scans' occupancy grid + # the segmentation scan's origin in the vehicle frame (camera x - seg_scan.origin_forward) + scan_offset: [0.2733, 0.0, 0.10] + boundary_min_points: 50 + bev_axes: [0, 1] # sim world is Z-up so X, Y are horizontal + forward_axis: 0 # X forward in the sim vehicle frame + auto_loop_close: true # end the mapping lap when the car is back at its start + auto_loop_min_length: 8.0 # m + lap_close_radius: 0.6 # m + auto_loop_overrun: 1.0 # m past the start before the lap is closed (covers the seam) + jump_threshold: 0.4 # m; longer pose steps are sim respawns after a wall hit + min_track_half_width: 0.2 # m; a narrower extracted track is rejected (bad lap), map again + boundary_save_path: "maps/autodrive_compete_seg" # null = don't save + +buffers: + frame: + slots: 8 + imu: + slots: 32 + segmentation: + slots: 4 + pose: + slots: 8 + control: + slots: 8 + pointcloud: + slots: 4 + boundary: + slots: 2 + lidar: + slots: 16 + +# recording (also start.py --recording): buffers + sim_messages.csv / sim_events.jsonl +recording: false +recording_path: "/tmp/pilot_recordings" +recording_config: + sample_k: 1 + top_n: 0 # one file per buffer per run + frame: + sample_k: 2 diff --git a/config_cpu.yaml b/config_cpu.yaml index c58be9e..d2e407b 100644 --- a/config_cpu.yaml +++ b/config_cpu.yaml @@ -68,10 +68,9 @@ track_control: max_backward: 0.3 # reverse input allowed for braking min_speed_for_backward: 0.3 # m/s -# no LiDAR on the car: a track_control.mapping_drive (follow-the-gap mapping lap, otherwise -# driven by hand with RC) runs on a scan made from the segmentation mask's edge + depth -# (control/seg_scan.py). Needs vision.enabled and a segmentation model trained on the real -# track. camera_height / camera_pitch come from depth_ftg (one camera mount) +# no LiDAR on the car: the segmentation mask's edge + depth make a LiDAR-format scan +# (control/seg_scan.py, SegScanWorker) for the mapping lap's walls and a track_control.mapping_drive. +# Needs vision.enabled. camera_height / camera_pitch come from depth_ftg (one camera mount) seg_scan: origin_forward: 0.0 # m, camera ahead of the scan origin @@ -121,8 +120,12 @@ slam: settings: orbslam_oakd_rgbd.yaml # see scripts/gen_orbslam_settings.py mapping: - boundary_min_points: 50 # wall points before boundary extraction starts - max_track_half_width: 1.5 # m, wall points further from the driven line are dropped + wall_source: occupancy # occupancy (segmentation-edge scans, as in the sim) | cloud (SLAM map points) + scan_offset: [0.0, 0.0, 0.0] # m, scan origin in the vehicle (camera) frame: [forward, left, up] + bev_axes: [0, 2] # SLAM's levelled camera frame: X right, Z forward + forward_axis: 2 + boundary_min_points: 50 # wall points before boundary extraction starts (cloud) + max_track_half_width: 1.5 # m, wall points further from the driven line are dropped (cloud) recording: false # or --recording recording_path: /tmp/pilot_recordings diff --git a/control/__init__.py b/control/__init__.py index 2a4d7f0..6983d49 100644 --- a/control/__init__.py +++ b/control/__init__.py @@ -1,13 +1,13 @@ """Vehicle control library. Pure Python; must not import the workers or the IPC buffers.""" from .controllers import PurePursuit, Stanley, TrackFollower, build_track_follower -from .estimator import EstimatorConfig, PoseEKF +from .estimator import EstimatorConfig, ImuEKF, ImuEstimatorConfig, PoseEKF from .safety import SafetyConfig, SafetySupervisor from .track import TrackModel from .types import Command, VehicleParams, VehicleState, wrap_angle __all__ = [ - "Command", "EstimatorConfig", "PoseEKF", "PurePursuit", "SafetyConfig", + "Command", "EstimatorConfig", "ImuEKF", "ImuEstimatorConfig", "PoseEKF", "PurePursuit", "SafetyConfig", "SafetySupervisor", "Stanley", "TrackFollower", "TrackModel", "VehicleParams", "VehicleState", "build_track_follower", "wrap_angle", ] diff --git a/control/controllers.py b/control/controllers.py index e79fbe3..35f9778 100644 --- a/control/controllers.py +++ b/control/controllers.py @@ -81,6 +81,11 @@ class SpeedConfig: accel: float = 1.5 # m/s² used by the profile (well below the car's limit) decel: float = 1.0 # m/s^2: coasting plus a little backward input preview: float = 0.5 # s, how far ahead to sample the speed ref + # also cap the ref by the curvature actually steered (v <= sqrt(a_lat_max / kappa_cmd)): + # the profile only knows the centre line, and on a hairpin exit the car is still turning + # tighter than that while the profile already lets it accelerate (sim: slides wide) + steer_speed_limit: bool = False + steer_lat_accel: float | None = None # m/s^2 for that cap; None = the profile's a_lat_max longitudinal: LongitudinalConfig = field(default_factory=LongitudinalConfig) @@ -103,10 +108,11 @@ def __init__( self._last_t: float | None = None self._v_cmd: float | None = None self.last_projection: Projection | None = None + self._a_lat_max = self.speed.lat_accel_fraction * params.friction_coeff * G self.v_profile = speed_profile( track, v_max=min(self.speed.v_max, params.max_speed), - a_lat_max=self.speed.lat_accel_fraction * params.friction_coeff * G, + a_lat_max=self._a_lat_max, a_accel=self.speed.accel, a_decel=self.speed.decel, ) @@ -118,10 +124,15 @@ def reset(self) -> None: self._last_t = None self._v_cmd = None - def v_ref(self, proj: Projection, v: float, dt: float) -> float: + def v_ref(self, proj: Projection, v: float, dt: float, delta: float = 0.0) -> float: # profile speed a little ahead, ramped at `accel` so the ref can't run away from the car s_preview = proj.s + max(abs(v), 0.3) * self.speed.preview target = float(self.v_profile[self.track.index_at(s_preview)]) + if self.speed.steer_speed_limit: + kappa = abs(np.tan(delta)) / self.params.wheelbase + if kappa > 1e-6: + a_lat = self.speed.steer_lat_accel or self._a_lat_max + target = min(target, float(np.sqrt(a_lat / kappa))) prev = self._v_cmd if self._v_cmd is not None else max(v, 0.0) self._v_cmd = min(target, prev + self.speed.accel * dt) return self._v_cmd @@ -136,7 +147,7 @@ def step(self, state: VehicleState) -> Command: delta = self.lateral.steer(state, self.track, proj) steering = delta / self.params.max_steering_angle dt = min(dt, 0.2) - throttle = self.longitudinal.step(self.v_ref(proj, state.v, dt), state.v, dt) + throttle = self.longitudinal.step(self.v_ref(proj, state.v, dt, delta), state.v, dt) return Command(steering, throttle).clipped() diff --git a/control/estimator.py b/control/estimator.py index 93f0a08..0606924 100644 --- a/control/estimator.py +++ b/control/estimator.py @@ -22,6 +22,8 @@ class EstimatorConfig: accel_std: float = 2.0 # m/s^2, process noise on v yaw_accel_std: float = 4.0 # rad/s², process noise on yaw rate stale_after: float = 0.5 # s without a pose before the estimate is invalid + jump_reset_m: float | None = None # a pose this far from the prediction restarts the filter + # there, standing still (a sim respawn after a collision) class PoseEKF: @@ -31,6 +33,7 @@ def __init__(self, cfg: EstimatorConfig | None = None) -> None: self.P = np.eye(5) self.t: float | None = None self.last_pose_t: float | None = None + self.jumps = 0 @property def initialized(self) -> bool: @@ -83,6 +86,12 @@ def update_pose(self, t: float, x: float, y: float, yaw: float) -> None: if t < self.t: # out of order, drop it return self._advance(t) + if self.cfg.jump_reset_m is not None and np.hypot(x - self.x[0], y - self.x[1]) > self.cfg.jump_reset_m: + # a respawn, not motion: differencing it would give a huge speed and yaw rate + self.x = None + self.jumps += 1 + self.update_pose(t, x, y, yaw) + return H = np.zeros((3, 5)) H[0, 0] = H[1, 1] = H[2, 2] = 1.0 R = np.diag([self.cfg.pos_std ** 2] * 2 + [self.cfg.yaw_std ** 2]) @@ -114,3 +123,211 @@ def predict_to(self, t: float) -> VehicleState | None: v=float(v), yaw_rate=float(w), ) + + +@dataclass +class ImuEstimatorConfig: + pos_std: float = 0.03 # m, pose position measurement noise + yaw_std: float = 0.02 # rad, pose yaw measurement noise + acc_std: float = 0.5 # m/s^2, accelerometer noise (white + model error) + gyro_std: float = 0.02 # rad/s, gyro noise + acc_bias_walk: float = 0.05 # m/s^2/sqrt(s) + gyro_bias_walk: float = 0.002 # rad/s/sqrt(s) + vy_std: float | None = 0.1 # m/s: pseudo-measurement vy = 0 at the IMU (a rear axle barely slips); None = off + history_s: float = 1.0 # s of IMU kept to apply late poses at their capture time + stale_after: float = 1.0 # s without a pose before the estimate is invalid + gate_chi2: float | None = 16.3 # reject a pose whose innovation exceeds this (3 dof, 99.9 %); None = off + gate_reset_s: float = 2.0 # s of rejected poses after which the filter is re-anchored to SLAM + + +class ImuEKF: + """Planar EKF driven by an IMU on the car (update_imu), corrected by SLAM poses. + + State [x, y, yaw, vx, vy, b_gz, b_ax, b_ay]: the IMU point's position and heading in the + pose frame, its velocity in the body frame (vx forward, vy left: vy is sideslip), and the + gyro-z / accelerometer biases. IMU samples are in the body frame (x forward, y left, + z up; level mount, so only ax, ay and gz are used): + + yaw' = gz - b_gz vx' = ax - b_ax + r vy vy' = ay - b_ay - r vx + + Poses usually arrive after later IMU samples (SLAM latency): a pose is applied at its + capture time and the IMU since then is replayed. A pose that disagrees with the IMU's + prediction beyond gate_chi2 is rejected (SLAM's first poses after a loss can be off by + a metre); if poses keep disagreeing for gate_reset_s the filter is re-anchored to SLAM. + Same interface as PoseEKF (update_pose, predict_to, valid), plus update_imu. + """ + + N = 8 + + def __init__(self, cfg: ImuEstimatorConfig | None = None) -> None: + self.cfg = cfg or ImuEstimatorConfig() + self.reset() + + def reset(self) -> None: + self.x: np.ndarray | None = None + self.P = np.eye(self.N) + self.t: float | None = None + self.last_pose_t: float | None = None + self._u: np.ndarray | None = None # last IMU input [ax, ay, gz] + self._hist: list = [] # (t, x, P, u) after each IMU step + self._pending: list = [] # IMU samples before the first pose + self._reject_since: float | None = None + self.rejected = 0 + + @property + def initialized(self) -> bool: + return self.x is not None + + # model + + def _step(self, x: np.ndarray, P: np.ndarray, u: np.ndarray | None, dt: float): + px, py, yaw, vx, vy, bg, bax, bay = x + ax, ay, gz = u if u is not None else (0.0, 0.0, bg) # no IMU yet (first pose came first) + r = gz - bg + c, s = np.cos(yaw), np.sin(yaw) + xn = np.array([ + px + (c * vx - s * vy) * dt, + py + (s * vx + c * vy) * dt, + wrap_angle(yaw + r * dt), + vx + (ax - bax + r * vy) * dt, + vy + (ay - bay - r * vx) * dt, + bg, bax, bay, + ]) + F = np.eye(self.N) + F[0, 2], F[0, 3], F[0, 4] = (-s * vx - c * vy) * dt, c * dt, -s * dt + F[1, 2], F[1, 3], F[1, 4] = (c * vx - s * vy) * dt, s * dt, c * dt + F[2, 5] = -dt + F[3, 4], F[3, 5], F[3, 6] = r * dt, -vy * dt, -dt + F[4, 3], F[4, 5], F[4, 7] = -r * dt, vx * dt, -dt + cfg = self.cfg + Q = np.zeros(self.N) + Q[2] = (cfg.gyro_std * dt) ** 2 + Q[3] = Q[4] = (cfg.acc_std * dt) ** 2 + Q[5] = cfg.gyro_bias_walk ** 2 * dt + Q[6] = Q[7] = cfg.acc_bias_walk ** 2 * dt + return xn, F @ P @ F.T + np.diag(Q) + + def _update(self, z: np.ndarray, H: np.ndarray, R: np.ndarray, angle_rows: tuple = ()) -> None: + y = z - H @ self.x + for r in angle_rows: + y[r] = wrap_angle(y[r]) + S = H @ self.P @ H.T + R + K = self.P @ H.T @ np.linalg.inv(S) + self.x = self.x + K @ y + self.x[2] = wrap_angle(self.x[2]) + I_KH = np.eye(self.N) - K @ H + self.P = I_KH @ self.P @ I_KH.T + K @ R @ K.T + + def _slip_update(self) -> None: + if self.cfg.vy_std is not None: + H = np.zeros((1, self.N)) + H[0, 4] = 1.0 + self._update(np.zeros(1), H, np.array([[self.cfg.vy_std ** 2]])) + + def _gate(self, t: float, z: np.ndarray, H: np.ndarray, R: np.ndarray) -> str: + """For a pose at time t against the current (x, P), at that time: "accept", "reject", + or "reset" (poses rejected for gate_reset_s: the filter is re-anchored to this one).""" + if self.cfg.gate_chi2 is None: + return "accept" + y = z - H @ self.x + y[2] = wrap_angle(y[2]) + d2 = float(y @ np.linalg.solve(H @ self.P @ H.T + R, y)) + if d2 <= self.cfg.gate_chi2: + self._reject_since = None + return "accept" + if self._reject_since is None: + self._reject_since = t + if t - self._reject_since < self.cfg.gate_reset_s: + self.rejected += 1 + return "reject" + self._reject_since = None + self.x[:3] = z + self.P[:3, :] = 0.0 + self.P[:, :3] = 0.0 + self.P[:3, :3] = R + return "reset" + + # inputs + + def update_imu(self, t: float, ax: float, ay: float, gz: float) -> None: + u = np.array([ax, ay, gz], dtype=np.float64) + if self.x is None: + self._pending.append((t, u)) + del self._pending[:-200] + return + if t <= self.t: + return + self.x, self.P = self._step(self.x, self.P, self._u if self._u is not None else u, t - self.t) + self._slip_update() + self.t, self._u = t, u + self._hist.append((t, self.x.copy(), self.P.copy(), u)) + while self._hist and self._hist[0][0] < t - self.cfg.history_s: + self._hist.pop(0) + + def update_pose(self, t: float, x: float, y: float, yaw: float) -> None: + cfg = self.cfg + z = np.array([x, y, wrap_angle(yaw)]) + H = np.zeros((3, self.N)) + H[0, 0] = H[1, 1] = H[2, 2] = 1.0 + R = np.diag([cfg.pos_std ** 2] * 2 + [cfg.yaw_std ** 2]) + if self.x is None: + self.x = np.array([x, y, wrap_angle(yaw), 0.0, 0.0, 0.0, 0.0, 0.0]) + self.P = np.diag([cfg.pos_std ** 2] * 2 + [cfg.yaw_std ** 2, 4.0, 1.0, 0.01 ** 2, 0.2 ** 2, 0.2 ** 2]) + self.t = self.last_pose_t = t + self._u = next((u for tu, u in reversed(self._pending) if tu <= t), None) + later = [(tu, u) for tu, u in self._pending if tu > t] + self._pending = [] + self._hist = [(t, self.x.copy(), self.P.copy(), self._u)] + for tu, u in later: + self.update_imu(tu, *u) + return + if t >= self.t: # no newer IMU yet: coast to t + if self._u is not None: + self.x, self.P = self._step(self.x, self.P, self._u, t - self.t) + self.t = t + if self._gate(t, z, H, R) == "accept": + self._update(z, H, R, angle_rows=(2,)) + self._hist = [(t, self.x.copy(), self.P.copy(), self._u)] + self.last_pose_t = t + return + # late pose: rewind to the last IMU step at or before t, apply it there, replay the rest + k = max((i for i, h in enumerate(self._hist) if h[0] <= t), default=None) + if k is None: # older than the history: drop it + return + t0, x0, P0, u0 = self._hist[k] + later = self._hist[k + 1:] + saved = (self.x, self.P, self.t, self._u) + self.x, self.P = self._step(x0, P0, u0, t - t0) if t > t0 else (x0.copy(), P0.copy()) + verdict = self._gate(t, z, H, R) + if verdict == "reject": # as if it never came + self.x, self.P, self.t, self._u = saved + return + if verdict == "accept": + self._update(z, H, R, angle_rows=(2,)) + self.t, self._u = t, u0 + self._hist = self._hist[:k + 1] + for tu, _, _, u in later: + self.x, self.P = self._step(self.x, self.P, self._u, tu - self.t) + self._slip_update() + self.t, self._u = tu, u + self._hist.append((tu, self.x.copy(), self.P.copy(), u)) + self.last_pose_t = max(self.last_pose_t or t, t) + + def valid(self, t: float) -> bool: + return self.last_pose_t is not None and (t - self.last_pose_t) <= self.cfg.stale_after + + @property + def sideslip(self) -> float: + """rad, angle of the IMU point's velocity to the body x axis""" + return float(np.arctan2(self.x[4], self.x[3])) if self.x is not None and abs(self.x[3]) > 0.3 else 0.0 + + def predict_to(self, t: float) -> VehicleState | None: + """Extrapolate to t (constant body velocity and yaw rate) without touching the filter.""" + if self.x is None or not self.valid(t): + return None + x = self.x.copy() + if t > self.t and self._u is not None: + x, _ = self._step(x, self.P, self._u, t - self.t) + r = float((self._u[2] if self._u is not None else 0.0) - x[5]) + return VehicleState(t=t, x=float(x[0]), y=float(x[1]), yaw=float(x[2]), + v=float(np.hypot(x[3], x[4]) * np.sign(x[3])), yaw_rate=r) diff --git a/control/occupancy_map.py b/control/occupancy_map.py new file mode 100644 index 0000000..3b12cc1 --- /dev/null +++ b/control/occupancy_map.py @@ -0,0 +1,194 @@ +""" +Track walls from segmentation-edge scans, as an occupancy grid. + +Each scan is a ray fan from the scan origin to the drivable area's edge (control/seg_scan.py). +A ray frees the floor it crosses; an edge only counts as wall when it was seen from close by, +so an edge placed short from far away (dark corners, the far end of a straight) is cleared +again by the floor seen up close. The drivable region is the floor seen free, connected to the +driven path and within `reach` of it; its outer contour and its hole are the two walls. + +Scans taken while the car stands still, or around a disturbance (a wall hit, a respawn), are +left out: they repeat one view of a wall many times. + +Used live by MappingWorker (`wall_source: occupancy`) and offline by scripts/seg_map.py. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +import numpy as np + +from .track import _resample_closed, _smooth_closed + + +@dataclass +class OccupancyConfig: + res: float = 0.05 # m, grid cell + beam_step: int = 6 # every n-th beam is used + pad: float = 3.0 # m of grid around the driven path + min_move: float = 0.03 # m driven between scans used + drop_before: float = 1.5 # s before a disturbance whose scans are dropped + drop_after: float = 2.5 # s after it + edge_range: float = 2.5 # m; edges farther than this are not walls + free_range: float = 1.6 # m of each ray that frees the floor + ratio: float = 0.35 # occupied / (occupied + free) of a wall cell + min_occ: float = 0.6 # smoothed edge count of a wall cell + min_free: float = 2.0 # smoothed ray count of a free cell + reach: float = 0.9 # m from the driven path the track can extend + seal: int = 3 # cells; wall gaps up to twice this are closed + car_radius: int = 3 # cells around the driven path that cannot be wall + close: int = 10 # cells; notches in the outer wall narrower than twice this are filled + grow: int = 8 # cells the region grows to reach the walls + trim: int = 6 # cells; necks narrower than twice this are cut + smooth: int = 11 # points, moving average of the wall contours + spacing: float = 0.1 # m between output boundary points + + +def signed_area(p: np.ndarray) -> float: + return 0.5 * float(np.sum(p[:, 0] * np.roll(p[:, 1], -1) - np.roll(p[:, 0], -1) * p[:, 1])) + + +def scan_to_samples(ranges: np.ndarray, angles: np.ndarray, origin: np.ndarray, heading: float, + cfg: OccupancyConfig) -> np.ndarray: + """One scan in its origin's frame -> (N, 5) [edge x, edge y, range, origin x, origin y], world.""" + ok = np.isfinite(ranges) & (ranges > 0.05) & (ranges < cfg.edge_range + 2.5) + ok[np.arange(len(ranges)) % cfg.beam_step != 0] = False + c, s = np.cos(heading), np.sin(heading) + fx, fy = ranges[ok] * np.cos(angles[ok]), ranges[ok] * np.sin(angles[ok]) + ox, oy = float(origin[0]), float(origin[1]) + n = int(ok.sum()) + return np.column_stack([ox + fx * c - fy * s, oy + fx * s + fy * c, ranges[ok], + np.full(n, ox), np.full(n, oy)]) + + +def occupancy(samples: np.ndarray, x0: float, y0: float, shape: tuple, cfg: OccupancyConfig): + """(free, occupied) smoothed hit counts on the grid.""" + import cv2 + + free, occ = np.zeros(shape, np.float32), np.zeros(shape, np.float32) + h, w = shape + + def add(grid, x, y): + i, j = ((y - y0) / cfg.res).astype(int), ((x - x0) / cfg.res).astype(int) + inside = (i >= 0) & (i < h) & (j >= 0) & (j < w) + np.add.at(grid, (i[inside], j[inside]), 1) + + ex, ey, r, ox, oy = samples.T + for k in np.linspace(0.2, 0.92, 10): # along each ray, stopping short of the edge + m = r * k < cfg.free_range + add(free, ox[m] + (ex[m] - ox[m]) * k, oy[m] + (ey[m] - oy[m]) * k) + m = r < cfg.edge_range + add(occ, ex[m], ey[m]) + return cv2.GaussianBlur(free, (0, 0), 1.5), cv2.GaussianBlur(occ, (0, 0), 1.0) + + +def _largest_on_path(mask: np.ndarray, path_cells: np.ndarray) -> np.ndarray: + import cv2 + + n, labels = cv2.connectedComponents(mask) + on_path = labels[path_cells[:, 1], path_cells[:, 0]] + on_path = on_path[on_path > 0] + if len(on_path) == 0: + raise ValueError("no free floor connected to the driven path") + return (labels == np.bincount(on_path, minlength=n).argmax()).astype(np.uint8) + + +def walls_from_grid(free: np.ndarray, occ: np.ndarray, path_cells: np.ndarray, cfg: OccupancyConfig): + """(outer, inner) contours in cells (x, y) and the drivable region. Rays stop at walls, + so a gap in a wall does not let the region out.""" + import cv2 + + wall = (occ / (occ + free + 1e-6) > cfg.ratio) & (occ > cfg.min_occ) + # no wall where the car drove: a lighting edge across the floor looks like one, and the + # camera only looks ahead, so nothing else clears it + driven = np.ones(free.shape, np.uint8) + driven[path_cells[:, 1], path_cells[:, 0]] = 0 + distance = cv2.distanceTransform(driven, cv2.DIST_L2, 5) + wall &= distance > cfg.car_radius + disc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * cfg.seal + 1, 2 * cfg.seal + 1)) + seen = ((cv2.dilate(wall.astype(np.uint8), disc) == 0) & (free > cfg.min_free)).astype(np.uint8) + region = _largest_on_path(seen, path_cells) + # out to the walls (rays stop short of them), no further than reach from the driven path; + # then cut off whatever got out through a gap in a wall + solid = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)) + for _ in range(cfg.grow): + region = cv2.dilate(region, solid) & (~wall).astype(np.uint8) + region &= (distance < cfg.reach / cfg.res).astype(np.uint8) + trim = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * cfg.trim + 1, 2 * cfg.trim + 1)) + region = _largest_on_path(cv2.morphologyEx(region, cv2.MORPH_OPEN, trim), path_cells) + contours, _ = cv2.findContours(region, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE) + by_area = sorted(contours, key=lambda c: -abs(cv2.contourArea(c))) + if len(by_area) < 2: + raise ValueError("the drivable region has no hole: the lap is not closed") + # the outer wall has no thin spikes into the track, the inner one has (hairpin tips): + # only the outer contour is closed + outside = cv2.drawContours(np.zeros_like(region), by_area[:1], -1, 1, cv2.FILLED) + fill = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * cfg.close + 1, 2 * cfg.close + 1)) + outside, _ = cv2.findContours(cv2.morphologyEx(outside, cv2.MORPH_CLOSE, fill), + cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) + outer = max(outside, key=lambda c: abs(cv2.contourArea(c))) + return outer[:, 0].astype(np.float64), by_area[1][:, 0].astype(np.float64), region + + +class OccupancyTrackMapper: + """Collects scans along a lap and extracts the two walls.""" + + def __init__(self, cfg: OccupancyConfig | None = None) -> None: + self.cfg = cfg or OccupancyConfig() + self.reset() + + def reset(self) -> None: + self._samples: list[tuple[float, np.ndarray]] = [] + self._disturbances: list[float] = [] + self._last_origin: np.ndarray | None = None + self.grid = None + + @property + def n_samples(self) -> int: + return sum(len(s) for _, s in self._samples) + + def mark_disturbance(self, t: float) -> None: + """A wall hit or a respawn at time t: scans around it are not used.""" + self._disturbances.append(float(t)) + + def add_scan(self, t: float, ranges: np.ndarray, angles: np.ndarray, origin: np.ndarray, heading: float) -> bool: + """A scan from `origin` (world x, y) facing `heading`. False if it was skipped + (the car has not moved far enough since the last one used).""" + origin = np.asarray(origin, dtype=np.float64)[:2] + if self._last_origin is not None and np.linalg.norm(origin - self._last_origin) < self.cfg.min_move: + return False + self._last_origin = origin + self._samples.append((float(t), scan_to_samples(np.asarray(ranges, np.float64), angles, origin, + heading, self.cfg))) + return True + + def _kept(self) -> np.ndarray: + d = np.asarray(self._disturbances) + keep = [s for t, s in self._samples + if not np.any((t > d - self.cfg.drop_before) & (t < d + self.cfg.drop_after))] + return np.vstack(keep) if keep else np.empty((0, 5)) + + def extract(self, path: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """Walls (outer, inner), (N, 2) world coordinates, both ordered along the driven + direction of `path` ((T, 2) positions, the lap first). Raises ValueError if there is + no closed track in the data.""" + cfg = self.cfg + path = np.asarray(path, dtype=np.float64)[:, :2] + samples = self._kept() + if len(samples) == 0 or len(path) < 10: + raise ValueError(f"not enough data ({len(samples)} edge samples, {len(path)} path points)") + x0, y0 = path.min(axis=0) - cfg.pad + w, h = np.ceil((path.max(axis=0) + cfg.pad - [x0, y0]) / cfg.res).astype(int) + free, occ = occupancy(samples, x0, y0, (h, w), cfg) + cells = np.unique(((path - [x0, y0]) / cfg.res).astype(int), axis=0) + cells = cells[(cells[:, 0] >= 0) & (cells[:, 0] < w) & (cells[:, 1] >= 0) & (cells[:, 1] < h)] + outer, inner, region = walls_from_grid(free, occ, cells, cfg) + self.grid = (region, x0, y0, w, h) + turn = signed_area(path[::10]) + lines = [] + for b in (outer, inner): + b = (b + 0.5) * cfg.res + [x0, y0] + b = _resample_closed(_smooth_closed(b, cfg.smooth), cfg.spacing) + lines.append(b if signed_area(b) * turn > 0 else b[::-1]) + return lines[0], lines[1] diff --git a/control/pose_degrade.py b/control/pose_degrade.py new file mode 100644 index 0000000..9937efb --- /dev/null +++ b/control/pose_degrade.py @@ -0,0 +1,96 @@ +""" +Degrade the sim's ground-truth pose to look like a visual SLAM pose on the car. + +The sim's pose is exact and on time; ORB-SLAM3's is late, noisy, off by a slowly wandering +error, and stops while tracking is lost. Each pose is published late (a frame's transfer plus a +log-normal tracking time), in order, still stamped with its capture time; it carries white noise +and a position bias that wanders and reverts (localising against the saved map keeps SLAM's error +bounded, it does not drift away); and during dropouts nothing is published. + +The defaults come from ORB-SLAM3 RGB-D (the CUDA fork) replaying rendered sequences of the +compete track in real time (bench/2026-10-29_vio_sim/inertial_fix.md): tracking time p50 +8.4 ms / p95 41.4 ms, ATE 0.107 m over three laps, and lost stretches around featureless +frames. They are not measured on the car; refit them from car recordings once those exist. +""" + +from __future__ import annotations + +import heapq +import math +from dataclasses import dataclass + +import numpy as np + + +@dataclass +class PoseDegradeConfig: + enabled: bool = False + base_latency_s: float = 0.033 # frame transfer, one 30 fps period + latency_median_s: float = 0.0084 # tracking time + latency_p95_s: float = 0.0414 + xy_sigma: float = 0.01 # m, white noise per pose + yaw_sigma: float = 0.005 # rad, white noise per pose + bias_sigma: float = 0.07 # m per axis, spread of the position bias (about 0.1 m 2-D RMS) + bias_tau: float = 2.0 # s, how fast the bias wanders and reverts + dropout_rate: float = 0.15 # tracking losses per second + dropout_s: float = 0.3 # s, length of each + seed: int = 0 + + +class PoseDegrader: + """add() each ground-truth pose (Z-up world, 4x4) as it arrives; due() returns the poses + whose publication time has come, as (capture time, pose), oldest first.""" + + def __init__(self, cfg: PoseDegradeConfig | None = None) -> None: + self.cfg = cfg or PoseDegradeConfig() + c = self.cfg + self._rng = np.random.default_rng(c.seed) + self._mu = math.log(max(c.latency_median_s, 1e-6)) + self._sigma = max(math.log(max(c.latency_p95_s, c.latency_median_s) / max(c.latency_median_s, 1e-6)) / 1.645, + 0.0) + self._queue: list[tuple[float, int, float, np.ndarray]] = [] # (release, n, capture, pose) + self._n = 0 + self._last_release = -math.inf + self._last_t: float | None = None + self._bias = np.zeros(2) + self._lost_until = -math.inf + self.published = 0 + self.dropped = 0 + + def _latency(self) -> float: + return self.cfg.base_latency_s + float(math.exp(self._mu + self._sigma * self._rng.standard_normal())) + + def add(self, t: float, pose: np.ndarray) -> None: + c = self.cfg + dt = 0.0 if self._last_t is None else max(t - self._last_t, 0.0) + self._last_t = t + if dt > 0 and c.bias_tau > 0: + a = math.exp(-dt / c.bias_tau) + self._bias = a * self._bias + self._rng.normal(0.0, c.bias_sigma * math.sqrt(1.0 - a * a), 2) + if t < self._lost_until: + self.dropped += 1 + return + if dt > 0 and self._rng.random() < 1.0 - math.exp(-c.dropout_rate * dt): + self._lost_until = t + c.dropout_s + self.dropped += 1 + return + out = np.array(pose, dtype=np.float32, copy=True) + out[0, 3] += self._bias[0] + self._rng.normal(0.0, c.xy_sigma) + out[1, 3] += self._bias[1] + self._rng.normal(0.0, c.xy_sigma) + a = self._rng.normal(0.0, c.yaw_sigma) + ca, sa = math.cos(a), math.sin(a) + Rz = np.array([[ca, -sa, 0.0], [sa, ca, 0.0], [0.0, 0.0, 1.0]], dtype=np.float32) + out[:3, :3] = Rz @ out[:3, :3] + # tracking is serial: a pose is never published before the one captured before it + release = max(t + self._latency(), self._last_release) + self._last_release = release + self._n += 1 + heapq.heappush(self._queue, (release, self._n, t, out)) + + def due(self, now: float) -> list[tuple[float, np.ndarray]]: + ready = [] + while self._queue and self._queue[0][0] <= now: + _, _, t, pose = heapq.heappop(self._queue) + ready.append((t, pose)) + self.published += len(ready) + return ready diff --git a/control/raceline.py b/control/raceline.py new file mode 100644 index 0000000..ee67461 --- /dev/null +++ b/control/raceline.py @@ -0,0 +1,106 @@ +""" +Minimum-curvature racing line inside the mapped track. + +The line is the reference path shifted along its normals, P_i + a_i n_i. Squared second +differences of the shifted points (a curvature proxy at uniform spacing) are linear in a, +so each pass is a bounded linear least-squares problem: a_i stays between the walls minus +a margin, measured by casting the normal against the boundaries. A few passes, each +re-linearised about the previous line, let it move further than one pass's normals allow. + +Ref: F. Braghin et al., "Race driving along the minimum curvature path", 2008; +A. Heilmeier et al., "Minimum curvature trajectory planning and control for an +autonomous race car", 2019 (the same QP, with splines). +""" + +from __future__ import annotations + +import numpy as np +from scipy.interpolate import CubicSpline +from scipy.optimize import lsq_linear +from scipy.spatial import cKDTree + +from .track import TrackModel, _resample_closed, _smooth_closed + + +def _normals(pts: np.ndarray) -> np.ndarray: + """Unit left normals of a closed polyline (central differences).""" + d = np.roll(pts, -1, axis=0) - np.roll(pts, 1, axis=0) + d /= np.maximum(np.linalg.norm(d, axis=1, keepdims=True), 1e-12) + return np.column_stack([-d[:, 1], d[:, 0]]) + + +def _ray_distances(origins: np.ndarray, dirs: np.ndarray, seg_a: np.ndarray, seg_b: np.ndarray, + max_dist: float) -> np.ndarray: + """Distance from each origin along its dir to the nearest wall segment (max_dist if none).""" + e = seg_b - seg_a # (M, 2) + out = np.full(len(origins), max_dist) + for k in range(0, len(origins), 256): # chunks bound the (n, M) arrays + o, d = origins[k:k + 256, None, :], dirs[k:k + 256, None, :] + w = seg_a[None] - o # (n, M, 2) + den = d[..., 0] * e[None, :, 1] - d[..., 1] * e[None, :, 0] + with np.errstate(divide="ignore", invalid="ignore"): + t = (w[..., 0] * e[None, :, 1] - w[..., 1] * e[None, :, 0]) / den + u = (w[..., 0] * d[..., 1] - w[..., 1] * d[..., 0]) / den + hit = (np.abs(den) > 1e-12) & (t > 0) & (u >= 0) & (u <= 1) + t = np.where(hit, t, max_dist) + out[k:k + 256] = np.minimum(t.min(axis=1), max_dist) + return out + + +def min_curvature_line( + track: TrackModel, + outer: np.ndarray, + inner: np.ndarray, + margin: float = 0.3, + spacing: float = 0.2, + passes: int = 4, + smooth_window: int = 3, + out_spacing: float = 0.05, +) -> np.ndarray: + """(N, 2) closed racing line in the direction of track.points. + + margin: m kept from either wall (car half-width plus a safety band); + spacing: optimisation sample spacing (m); passes: re-linearisations; out_spacing: + spacing of the returned points, sampled from a periodic cubic spline through the + optimised ones (a linear resample would leave curvature spikes at every knot).""" + walls = [_resample_closed(np.asarray(b, dtype=np.float64)[:, :2], 0.05) for b in (outer, inner)] + seg_a = np.vstack([w for w in walls]) + seg_b = np.vstack([np.roll(w, -1, axis=0) for w in walls]) + wall_pts = seg_a + wall_tree = cKDTree(wall_pts) + pts = _resample_closed(track.points, spacing) + for _ in range(passes): + n = len(pts) + # second-difference operator on a closed loop + D = np.zeros((n, n)) + idx = np.arange(n) + D[idx, (idx - 1) % n], D[idx, idx], D[idx, (idx + 1) % n] = 1.0, -2.0, 1.0 + nrm = _normals(pts) + left = _ray_distances(pts, nrm, seg_a, seg_b, 5.0) - margin + right = _ray_distances(pts, -nrm, seg_a, seg_b, 5.0) - margin + # a squeezed sample (narrower than 2 * margin) stays where it is + lo, hi = np.minimum(-right, 0.0), np.maximum(left, 0.0) + lo, hi = np.where(lo < hi, lo, -1e-6), np.where(lo < hi, hi, 1e-6) + # D (pts + a * nrm) = 0 in least squares, x and y rows stacked + A = np.vstack([D * nrm[:, 0], D * nrm[:, 1]]) + b = -np.concatenate([D @ pts[:, 0], D @ pts[:, 1]]) + # the normal ray misses walls off to the side (a sharp inner corner): where the + # nearest wall is closer than the margin, pull that side's bound in and solve again + for _ in range(8): + a = lsq_linear(A, b, bounds=(lo, hi), method="bvls").x + new = pts + a[:, None] * nrm + d, j = wall_tree.query(new) + short = d < margin - 0.01 + if not short.any(): + break + side = np.sign(((wall_pts[j] - new) * nrm).sum(axis=1)) + push = (margin - d + 0.02)[short] + left_wall, right_wall = short & (side > 0), short & (side <= 0) + hi[left_wall] = np.maximum(a[left_wall] - push[side[short] > 0], lo[left_wall] + 1e-6) + lo[right_wall] = np.minimum(a[right_wall] + push[side[short] <= 0], hi[right_wall] - 1e-6) + pts = _resample_closed(new, spacing) + pts = _smooth_closed(pts, smooth_window) + closed = np.vstack([pts, pts[:1]]) + s = np.concatenate([[0.0], np.cumsum(np.linalg.norm(np.diff(closed, axis=0), axis=1))]) + spline = CubicSpline(s, closed, bc_type="periodic") + return spline(np.arange(0.0, s[-1], out_spacing)) diff --git a/control/track.py b/control/track.py index c740de8..7491f5b 100644 --- a/control/track.py +++ b/control/track.py @@ -71,8 +71,15 @@ def __init__( self._set_centre(centre) # half-width is just distance to the nearest wall - walls = np.vstack([_resample_closed(outer, spacing / 2), _resample_closed(inner, spacing / 2)]) - self.half_width, _ = cKDTree(walls).query(self.points) + self._walls = cKDTree(np.vstack([_resample_closed(outer, spacing / 2), + _resample_closed(inner, spacing / 2)])) + self.half_width, _ = self._walls.query(self.points) + + def set_path(self, path: np.ndarray, spacing: float = 0.05) -> None: + """Follow another closed path between the same walls (a racing line) instead of the + centre-line; half_width becomes the distance from it to the nearest wall.""" + self._set_centre(_resample_closed(np.asarray(path, dtype=np.float64)[:, :2], spacing)) + self.half_width, _ = self._walls.query(self.points) def _set_centre(self, centre: np.ndarray) -> None: self.points = centre diff --git a/docs/autodrive.md b/docs/autodrive.md index 3db9750..f0d5e26 100644 --- a/docs/autodrive.md +++ b/docs/autodrive.md @@ -29,17 +29,41 @@ The script installs the stock `2026-iros` practice and compete builds under `supervisorctl restart autodrive_sim`. To watch, run `ssh -L 6080:127.0.0.1:6080 ` and open `http://localhost:6080/vnc.html`. +### On a Slurm cluster (no Docker or supervisor) + +`scripts/cluster/autodrive_job.sh` runs Xvfb and the sim in a relaunch loop on an L40S node +and any of the stages `sweep`, `segmap`, `live` (mapping lap in the loop, then 10 laps on that map), +`race`, `degraded` (the race with `sim_pose_degrade` on), `qual`, `ultra`, `start`. Each job runs in +its own network namespace with its own sim settings, so several can share a node. `scripts/cluster/bin` +stands in for xdotool, xwininfo and supervisorctl, which the nodes lack. Clicks work without +a window manager. The sim's root and logs come from `AUTODRIVE_ROOT`, `AUTODRIVE_LOG_DIR`. + +```bash +sbatch --export=ALL,TAG=x,SEG_RUNS="runs/y/*/rec/*",STAGES="segmap race qual" scripts/cluster/autodrive_job.sh +``` + +On a slow disk the scene appears seconds after the log's `UnloadTime` and the HUD ignores +clicks until then: `autodrive_sim_ctl.wait_scene()`. + ## Running ```bash -python start.py --config config_autodrive.yaml # LiDAR mapping lap, then race +python start.py --config config_autodrive.yaml # segmentation mapping lap (no LiDAR), then race python scripts/autodrive_sim_ctl.py connect # the sim has no CLI connect option ``` Keys: `a` arm, `SPACE` disarm, `r` reset the sim, `l` end the mapping lap, `q` quit. -- Once armed, `LidarGapFollower` (`track_control.mapping_drive`) drives the mapping lap. - On the car a human drives this lap with the RC transmitter. +- Once armed, the gap follower (`track_control.mapping_drive`) drives the mapping lap on the + segmentation-edge scan (`SegScanWorker`), never the sim's LiDAR. On the car a human + drives this lap with the RC transmitter. + +**What the sim run still gets that the car won't.** pilot_core never uses a LiDAR: +`lidar.enabled: true` or `sim_depth.depth: lidar` is refused at start-up. The sim's +velocity is not fused into the state. The pose, though, is the sim's ground truth +(`sim_pose`), standing in for ORB-SLAM3, which does not run in the sim; the mapping lap +places the segmentation's edges with that pose too. The segmentation model's training +labels came from the LiDAR depth and a LiDAR-built map (training only; it runs on RGB). - `MappingWorker` closes the lap on its own (`mapping.auto_loop_close`) once the car is back past its start. The control mode then takes over. - The map is saved to `maps/autodrive_practice`. To race on a saved map, set @@ -93,6 +117,66 @@ The protocol spike is `scripts/autodrive_spike.py`; the live probes are in - **Steering.** Curvature against yaw rate gives an effective wheelbase of 0.342 m (IQR 0.336–0.351), which is the value in `vehicle_params_roboracer.yaml`. +## Racing (`config_autodrive_compete.yaml`) + +The race settings on the stock `2026-iros` compete build, no LiDAR, no sim speed +(L40S, 640×360), 10 laps, scored like the published final (race time + 10 s per collision), +on the map built offline from five mapping runs +([bench/2026-10-31_autodrive_nolidar/results.md](../bench/2026-10-31_autodrive_nolidar/results.md)): + +| run | collisions | adjusted (s) | +| --- | --- | --- | +| final 1 / 2 / 3, Low quality | 1 / 0 / 0 | 130.64 / 120.04 / 120.46 | +| Ultra quality | 1 | 129.52 | +| competition start (sim restarted, `auto_arm`, no keys) | 1 | 139.53 | +| qualifier, practice track | 0 | 75.21 | + +First lap about 14 s from a standing start (22.5 s after the competition start), then +11.5–12.7 s. Two of the five compete runs were clean. + +Mapping in the loop (`mapping.wall_source: occupancy`, the default) builds the map during the +mapping lap itself; `maps/autodrive_{practice,compete}_live*` are such maps, and +[results.md](results.md#mapping-in-the-loop-2026-11-09) has their races. `scripts/seg_map.py` +builds one offline from recorded laps with the same code: + +```bash +python scripts/seg_map.py runs/x/map/rec/* --out maps/autodrive_compete_seg # camera map +python scripts/make_raceline.py maps/autodrive_compete_seg --margin 0.65 # once per map +python start.py --config config_autodrive_compete.yaml # arms itself (auto_arm) +``` + +- **Racing line** (`control/raceline.py`). Minimum curvature between the mapped walls, + at least `--margin` from either wall (true nearest-wall distance, so sharp inner corners + count). Compete track: 45.7 m centre-line → 44.4 m line; the speed planner's estimate + goes from 10.7 s to 9.2 s per lap. The margin is 0.65 m on the camera map: at 0.5 m the + line used a pocket past the real wall and ran close to the inner tip, 5–26 hits a race + against 0–1, all at the two left hairpins. On the LiDAR map 0.5 m was enough; those runs no + longer count. +- **Pure pursuit with a shorter lookahead** (0.5 + 0.25 v, at most 2 m). The default's + 3 m lookahead cuts the line's corners into the inside walls. The MPC weaved on the + straight at this latency and was not used. +- **Grip.** The planner may use 10.3 m/s² of lateral acceleration + (`lat_accel_fraction: 2.0`), but at large steering the car slides wide long before + that: out of the hairpins and at the zig-zag apexes, into the outer wall, and a higher + speed also clips the end of the inner wall at the bottom hairpin. The speed is + therefore also capped by the curvature actually steered, at 5 m/s² + (`steer_speed_limit`, `steer_lat_accel`). This cap is what keeps it clean: a lower planner + grip (down to 6 m/s²) without the cap, or the cap only above half steering, still hits + walls. Likely cause, not measured: the sim's tyres lose lateral grip under braking or + acceleration, which a fixed profile cannot see and the cap reacts to. +- **Collisions** put the car back a short way. The EKF used to read that jump as speed and + yaw rate and the controller steered straight back into the wall, every respawn (2217 + collisions in one run). With `estimator.jump_reset_m` (0.4 m in the sim configs) a jump + restarts the EKF at the new pose, standing still, and resets the controllers. +- **Respawns are to fixed checkpoints**, up to 1.3 m off the driven path (compete build): + `MappingWorker` keeps the lap through one and only restarts it further off than 2 m. A line + too near a checkpoint's corner traps the car: it hit again every 0.8 s, 20 hits in one run. +- **Results.** Compete 120.04–130.64 s adjusted, behind 15th of 23 in the published + 2026-iros final (race time + 10 s per collision; 15th 113.19 s, 1st 71.82 s, best lap + 7.16 s), on a known track with the sim's ground-truth pose. Qualifier 10 laps, 0 collisions, + 75.21 s (7.30–7.33 s). The 107 s of bench/2026-10-29_autodrive came from a LiDAR-built map + with the sim's speed fused and does not count. + ## Known limitations - **Sim freezes on a shared GPU.** When other jobs load the GPU, the sim freezes for up @@ -136,8 +220,9 @@ per worker. ## Vision (`VisionWorker` in the sim) -Needs `sim_depth` (frames upscaled ×2, car body painted out, depth from the LiDAR); the -vision section of `config_autodrive.yaml` points it at the sim camera's intrinsics. +Needs `sim_depth` (frames upscaled ×2, car body painted out; `depth: none`, no LiDAR); the +vision section of `config_autodrive.yaml` points it at the sim camera's intrinsics. It runs +only for a mapping lap: racing on a saved map nothing would read it. Ground truth comes from `scripts/autodrive_vision_labels.py`: a pixel is track when the LiDAR depth adapter puts its ray on the floor before any wall and that floor point, placed with the sim pose, lies between the mapped boundaries (car body ignored). @@ -162,16 +247,37 @@ mostly checks the wiring. ### The segmentation-edge scan (no LiDAR on the car) -`seg_scan.source: segmentation` (with `vision.enabled` and `sim_depth`) makes the mapping -drive use the scan built from the mask edge (`control/seg_scan.py`) instead of the LiDAR, -as on the car. `seg_scan` in `config_autodrive.yaml` holds the sim camera's mount and its -offset behind the LiDAR. Score it offline against the LiDAR on any export: +The mapping drive and the map's walls use the scan built from the mask edge +(`control/seg_scan.py`, `workers/seg_scan_worker.py`), as on the car. With no depth each +edge is placed where its pixel's ray meets the floor (`seg_scan.camera_height`, +`camera_pitch`). Two things make it work for a camera's ~60 deg view: + +- **Edge memory** (`seg_scan.memory_s`, 1.5 s): edges seen recently, kept in the world frame, + fill the beams outside the current view, so the inside of a hairpin still bounds the gap + follower after it leaves the image (without it the mapping lap clipped both hairpin tips). +- **Mapping only from near edges** (`mapping.scan_range_max`, 2 m), each scan projected with + the pose of its own frame: placing an edge on the floor gets worse with distance (replayed + masks against the old LiDAR walls: within 15 cm 96 % up to 2 m, 66 % at any range). + +- **On the compete track that isn't enough.** Its corners are dark and the mapping drive hits + walls, so the accumulated cloud fills the corners with edges placed short (within 15 cm: 99 % + on straights at 0.6–0.9 m, 22 % in corners at 2–3 m) and its boundaries are rejected. + `scripts/seg_map.py` replays the recorded masks into an occupancy grid instead: rays clear the + floor they cross, which removes those edges; masks near a hit or standing still are dropped; + no wall where the car drove; the outer wall is closed and at most 0.9 m from the driven path. + Five mapping runs, walls within 0.13 / 0.10 m (median, outer / inner) of the LiDAR map. + +Score it offline against the LiDAR on an old export (the LiDAR is not used live): ```bash python scripts/seg_scan_eval.py runs/x/export # range error, missed / phantom walls, gap target ``` -Results: [results.md](results.md#segmentation-edge-scan). It has not been driven live yet. +Results: [results.md](results.md#segmentation-edge-scan) (that table placed edges with +LiDAR-synthesised depth). Driven live 2026-10-29: practice track mapped with 0 collisions, +walls within 5 / 9 cm (median, inner / outer) of the LiDAR map, up to 0.8-1.0 m off where +the camera saw little (both narrower than the real track); qualifier on it 10 laps, 0 +collisions, 7.1-7.2 s laps. ## Telemetry export and HUD diff --git a/docs/datasets.md b/docs/datasets.md index 7fb7b73..47c8919 100644 --- a/docs/datasets.md +++ b/docs/datasets.md @@ -3,9 +3,8 @@ Data and trained models stay out of git (`.gitignore`). These are the bundles the team needs, with where each file goes in a checkout and how to rebuild it from scratch. -**Status (2026-10-21):** all three bundles are built and checksummed, but **not yet uploaded**. -Proposed home: GitHub Release `data-v1` on this repo; every bundle is under the 2 GB -asset limit. After upload: +The three bundles are GitHub Release +[`data-v1`](https://github.com/UTASR-UT-Autonomous-Scale-Racing/pilot_core/releases/tag/data-v1): ```bash gh release download data-v1 -R UTASR-UT-Autonomous-Scale-Racing/pilot_core -D /tmp/data-v1 @@ -48,9 +47,9 @@ efcb62577c7d00e9e67429a4b3f19de8d67359d00a4432a39169552d5aaace0b pilot_core-tel | ---- | ---- | ----- | ------------- | | AutoDRIVE RoboRacer sim builds | – | `/workspaces/autodrive_sim` | `scripts/vast_autodrive_setup.sh` downloads the release; `scripts/autodrive_texture_sim.py` makes the textured copy | | ORB-SLAM3 vocabulary and build | ~930 MB | `ORB_SLAM3/` submodule | `scripts/setup.sh --with-slam`, [slam.md](slam.md) | -| Saved track maps | 28 KB | `maps/autodrive_{practice,compete}` | in git | -| Benchmark raw runs, 2026-10-20 | 1.3 GB | maintainer archive | `scripts/autodrive_bench.py matrix bench/matrix.yaml`. Summary tables are in git (`bench/2026-10-20/`) | -| Validation evidence (runs, GIFs, logs) | 1.1 GB | maintainer archive | `scripts/autodrive_validate.py`; summary in [results.md](results.md) | +| Saved track maps | 28 KB | `maps/autodrive_*` | in git: `_practice` / `_compete` from the LiDAR (reference only), `_seg` built offline from the camera, `_live*` from in-loop mapping laps | +| No-LiDAR sim runs, 2026-10-30 onwards | 5.6 GB | the team's cluster scratch (`runs/`) | `scripts/cluster/autodrive_job.sh`; summary tables in `bench/` | +| Benchmark raw runs and validation evidence, 2026-10-20 | – | not kept: the cloud box was released | `scripts/autodrive_bench.py matrix bench/matrix.yaml`, `scripts/autodrive_validate.py`; summary tables in `bench/2026-10-20/` and [results.md](results.md) | | Real-car recordings (OAK-D) | – | **none yet** | `start.py --recording`; see "Still to collect" | ## Still to collect diff --git a/docs/deployment.md b/docs/deployment.md index 7f41c3c..e8c3d41 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -4,15 +4,27 @@ Natively or in Docker; both use `config.yaml` (I2C actuator on `/dev/i2c-1`) unl you pass `--config`. The Arduino follows the Jetson only while commands are fresh (250 ms) and the RC sticks are centred (`firmware/README.md`). +> **Firmware not yet bench-tested.** The command-source selection and the 250 ms timeout in +> the firmware have not been compiled and run on the Arduino (`firmware/README.md`). Do the +> wheels-off bench test there before the car drives under Jetson control. + +## What runs + +Both scripts check out the newest `car-v*` release tag (a version that passed the bench test +and a drive), or `main` if there is no such tag yet, with the submodules at the commits it +pins. `PILOT_REF=` picks another. Then `scripts/jetson_selftest.py` checks +the platform, power mode, CUDA, `/dev/shm`, the ring buffers, the ORB-SLAM3 bindings, the +OAK-D on USB 3 and the Arduino on I2C; any failure stops the start (`SKIP_SELFTEST=1` skips it). + ## Native ```bash scripts/jetson_run.sh [start.py arguments] ``` -Sets maximum performance, fast-forwards pilot_core (refuses with uncommitted -changes), checks out the pinned submodules, activates `.venv` and runs `start.py`. -Needs the `.venv` and the ORB-SLAM3 build ([slam.md](slam.md)). +Sets maximum performance, checks out the release (refuses with uncommitted changes), runs +the self-test, activates `.venv` and runs `start.py` as root (I2C and USB). Needs the `.venv` +and the ORB-SLAM3 build ([slam.md](slam.md)). ## Docker @@ -20,8 +32,8 @@ Needs the `.venv` and the ORB-SLAM3 build ([slam.md](slam.md)). scripts/start.sh [start.py arguments] ``` -Updates the repo, sets performance mode and the OAK-D udev rule, builds `Dockerfile` -and runs it in the foreground with: +Checks out the release, sets performance mode and the OAK-D udev rule, builds `Dockerfile`, +runs the self-test in the container, then runs it in the foreground with: | Flag | Why | | ---- | --- | @@ -33,7 +45,30 @@ and runs it in the foreground with: Arguments go to `start.py`. The image builds ORB-SLAM3 (`--target noslam` skips it); the base is JetPack 6 (`L4T_BASE`), which must match the Jetson's L4T major version. -Logs: `sudo docker logs -f utasr-container`. +Logs: `sudo docker logs -f utasr-container`. CI builds the same image on an arm64 runner +(`.github/workflows/jetson-image.yml`) and pushes it to `ghcr.io` for each `car-v*` tag. + +## Measuring on the Jetson + +Record a run with the actuator disabled and read the per-stage rates and latencies off it: + +```bash +python start.py --config config_cpu.yaml --enable-slam --recording # 60 s, then q +python scripts/stage_latency.py /tmp/pilot_recordings/ +``` + +Frames, masks and poses are stamped with the camera's capture time, so the table gives each +stage's capture-to-output latency, and the age of the newest pose whenever a command went out. +`SLAMWorker` also logs its mean tracking time every 30 frames. The same table for the sim race +is in [results.md](results.md#stage-latency); the Jetson's is still to be measured. + +## Releasing a car version + +After the firmware bench test and a drive on the track with a version, tag it so the car runs it: + +```bash +git tag -a car-v1.0.0 -m "" && git push origin car-v1.0.0 +``` ## One-time Jetson setup for Docker diff --git a/docs/images/hud.gif b/docs/images/hud.gif index e653691..e7fdefe 100644 Binary files a/docs/images/hud.gif and b/docs/images/hud.gif differ diff --git a/docs/images/hud_frame.png b/docs/images/hud_frame.png index f500ee6..e1ea17b 100644 Binary files a/docs/images/hud_frame.png and b/docs/images/hud_frame.png differ diff --git a/docs/oakd.md b/docs/oakd.md index abc7560..ed1ade4 100644 --- a/docs/oakd.md +++ b/docs/oakd.md @@ -30,8 +30,9 @@ Measured with the `CameraWorker` pipeline: ## Requirements -- **USB 3 for 30 fps.** On USB 2, 30 fps RGB-D drops frames and lags about 320 ms, too old - for the 150 ms command watchdog. Use a SuperSpeed port and a USB 3 cable; with USB-C, try +- **USB 3 for 30 fps.** On USB 2, 30 fps RGB-D drops frames and lags about 320 ms. The 150 ms + command watchdog only checks that commands keep arriving, not how old the camera data behind + them is, so it does not catch this; `scripts/stage_latency.py` on a recording does. Use a SuperSpeed port and a USB 3 cable; with USB-C, try flipping the plug. `CameraWorker` logs a warning when the link is slower than USB 3 and fps is above 15. Check the link: diff --git a/docs/results.md b/docs/results.md index 737442b..720d682 100644 --- a/docs/results.md +++ b/docs/results.md @@ -1,49 +1,81 @@ -# Results: AutoDRIVE RoboRacer sim (October 2026) +# Results -pilot_core was validated end to end against the stock AutoDRIVE RoboRacer `2026-iros` -build over the direct link ([autodrive.md](autodrive.md)), then benchmarked. Sim at 640×360, -Vulkan, Low quality, on a shared-GPU cloud box. Full tables: [bench/2026-10-20/results.md](../bench/2026-10-20/results.md). +pilot_core in the stock AutoDRIVE RoboRacer `2026-iros` simulator, driving like the car: the +drivable area from the camera's segmentation, no LiDAR, no speed from the sim. The sim's pose is +ground truth unless the degraded-pose runs say otherwise; how each gap to the car is handled is +in [sim_to_real.md](sim_to_real.md). Nothing here was measured on the car. -## Validation +## Racing on the camera map (2026-10-31) -| check | result | -| ----- | ------ | -| Link: rates, pose, LiDAR, camera | PASS. Pose error 2.5e-7 m; 100 % of LiDAR points within 10 cm of the mapped walls | -| Disarmed hold / armed command echo | PASS / PASS | -| Steering sign / negative throttle | PASS / PASS | -| Reset | PASS, 0.0001 m from the start | -| Stop: SIGTERM or SIGKILL `start.py` | PASS / PASS. Neutral sent; the car rolled 0.34 / 0.30 m | -| Stop: SIGKILL every pilot_core process | **FAIL**. The sim has no command timeout: 8.51 m driven, 15 wall hits in 21.2 s. Needs a sim-side timeout like the firmware's 250 ms | -| Calibration | 24.80 m/s per unit throttle; effective wheelbase 0.342 m | -| Map, then race 3 laps | PASS: 0 collisions; cross-track RMS 4.1 cm | -| pytest | 357 passed, 7 skipped (all extras installed) | +10 laps on the compete build, L40S, 640×360, scored like the published final (race time + 10 s +per collision), on the map `scripts/seg_map.py` built from five recorded mapping runs +([bench/2026-10-31_autodrive_nolidar/results.md](../bench/2026-10-31_autodrive_nolidar/results.md)): -## Benchmark (84 runs, 0 errors; 3 repeats × 2 laps per cell) +| run | collisions | first lap, then (s) | adjusted (s) | +| --- | --- | --- | --- | +| final 1 | 1 | 13.74, 11.48–12.56 | 130.64 | +| final 2 | 0 | 14.01, 11.59–12.00 | 120.04 | +| final 3 | 0 | 13.97, 11.62–12.08 | 120.46 | +| Ultra quality | 1 | 13.53, 11.52–12.68 | 129.52 | +| competition start (sim restarted, `auto_arm`, no keys) | 1 | 22.51, 11.57–12.63 | 139.53 | +| qualifier, practice track | 0 | 9.37, 7.30–7.33 | 75.21 | -![Benchmark summary](../bench/2026-10-20/summary.png) +Published final: 1st 71.82 s, 15th 113.19 s, 23 teams. These runs are behind 15th, and not +like-for-like: the track was known, the map came from five runs on it, and the pose is ground truth. -- **Controller × v_max.** At v_max 4.0, pure_pursuit and mpc are fastest (mean lap - 14.2–14.4 s) with 0 collisions. mpc has the lowest cross-track error from 1.5 m/s up. - Collisions happen only at v_max ≥ 2.5, with lqr and stanley; stanley at 4.0 is the worst - cell (1.3 ± 2.3 per run). The car never reaches 4.0 m/s: its mean speed is about 2.3 m/s. -- **Loop rate, 30 / 50 / 100 Hz.** Barely matters. pure_pursuit best lap 12.89–12.90 s; - mpc is about 0.25 s slower per lap with 3.8 cm cross-track. -- **Pose and map source.** Saved map: best lap 12.90 s. LiDAR mapping on the fly, then - racing: 12.63 ± 0.25 s. This gap is unexplained; the two maps differ in length by only 0.2 m. - ORB-SLAM3: **FAILED** (below). -- **Track.** Practice best lap 12.89 s; compete best lap 19.53 s; 0 collisions on both. -- **Sim stalls.** 0–89.8 % of a run's wall time in controller × v_max, when other GPU jobs - shared the GPU; 0 % in every other stage. Each run reports `stalled_pct`. +**Map accuracy.** Against the LiDAR-built map, used only to score it: outer wall median 0.13 m, +p90 0.30 m, max 0.51 m; inner wall 0.10 / 0.28 / 0.42 m. The thresholds were picked looking at +that distance, so the method has seen the reference. -## Learned components +## Mapping in the loop (2026-11-09) -- **Track segmentation** (Fast-SCNN, ONNX, trained on sim runs): IoU 0.941 on the - compete track it never saw, 0.939 live in `VisionWorker`, with lap times unchanged. -- **Segmentation-edge scan** (the car's LiDAR stand-in, below). -- **PPO policy** (bicycle-model pretrain, PPO_1): zero-shot on the live sim, lap 1 in 17.58 s - against pure_pursuit's 18.09 s at the same 2.0 m/s cap. About 30 % of live episodes - collide, most likely because the bicycle env's collision body (circles r = 0.14 m) is - smaller than the car. A live fine-tune of 26.5k steps did not improve this. +The mapping lap now builds the walls itself, from an occupancy grid over the segmentation-edge +scans (`mapping.wall_source: occupancy`), then the car races 10 laps on that map +([bench/2026-11-09_live_mapping/results.md](../bench/2026-11-09_live_mapping/results.md)): + +| track | map built after (s) | hits while mapping | walls vs LiDAR map, median outer / inner (m) | 10-lap race: collisions, adjusted (s) | +| --- | --- | --- | --- | --- | +| practice, 3 runs | 54.9–55.5 | 0, 0, 0 | 0.17 / 0.08 | 0, 0, 0; 76.20–76.94 | +| compete, 3 runs | 87.8–92.8 | 5, 4, 5 | 0.10–0.13 / 0.15–0.18 | 1, 4, 7; 132.20–194.06 | + +The practice track maps cleanly in one lap and races like its offline map. On the compete track +every run maps, with a few hits, and the walls are as accurate as the offline map's; but the +racing lines on these maps pass 0.33–0.42 m from a wall (0.45 m on the offline map) and the races +hit the two left hairpins. + +## Degraded pose (2026-11-09) + +The race on the offline compete map with `sim_pose_degrade` making the sim's pose like +ORB-SLAM3's (latency, noise, a bounded bias, dropouts), and with one part switched off at a time: + +| pose | collisions, 3 runs | adjusted (s) | laps after the first (s) | +| --- | --- | --- | --- | +| ground truth | 1, 0, 0 | 120.04–130.64 | 11.48–12.56 | +| noise and bias only | 0, 2, 0 | 120.94–142.52 | 11.43–12.79 | +| latency and dropouts only | 4, 12, 7 | 185.62–271.00 | 12.88–16.92 | +| everything | 15, 14, 12 | 271.52–307.65 | 13.87–18.60 | + +Latency and dropouts, not noise, are what the race settings cannot take, although the estimator +already updates at the capture time and predicts to the present. The settings need tuning against +the degraded pose before they go on the car ([roadmap.md](roadmap.md#simulator)). + +## Stage latency + +`scripts/stage_latency.py` on the clean compete race (final 2). Frames and poses are stamped at +capture, so their column is capture to output; the pose age is that of the newest pose when each +command went out. + +| stage | rate (Hz) | interval p50 / p95 (ms) | capture to output p50 / p95 / max (ms) | +| --- | --- | --- | --- | +| frame | 12.2 | 67.2 / 114.5 | 1.1 / 2.1 / 74.0 | +| pose | 24.3 | 52.4 / 58.8 | 1.2 / 2.3 / 125.4 | +| state | 47.6 | 21.0 / 21.3 | – | +| control | 47.6 | 21.0 / 21.5 | – | +| actuation | 49.8 | 20.1 / 20.1 | – | + +Pose age when a command went out: p50 27.1 ms, p95 53.3 ms, max 154.0 ms. The sim delivers +its pose within about a millisecond; on the car ORB-SLAM3's tracking time and the camera transfer +come on top ([deployment.md](deployment.md#measuring-on-the-jetson) measures it on the Jetson). ## Segmentation-edge scan @@ -70,6 +102,16 @@ camera's view (about −33° to +36°): the unknown beams at the edge of the view into phantom close walls. It now leaves unknown beams out; on all 2261 recorded LiDAR scans its output is unchanged. +## Learned components + +- **Track segmentation** (Fast-SCNN, ONNX, trained on sim runs): IoU 0.941 on the + compete track it never saw, 0.939 live in `VisionWorker`, with lap times unchanged. +- **Segmentation-edge scan** (the car's LiDAR stand-in, below). +- **PPO policy** (bicycle-model pretrain, PPO_1): zero-shot on the live sim, lap 1 in 17.58 s + against pure_pursuit's 18.09 s at the same 2.0 m/s cap. About 30 % of live episodes + collide, most likely because the bicycle env's collision body (circles r = 0.14 m) is + smaller than the car. A live fine-tune of 26.5k steps did not improve this. + ## What did not work - **ORB-SLAM3 on the stock sim camera.** 30–63 % of frames tracked, ATE 2.5–2.7 m over an @@ -79,5 +121,50 @@ camera's view (about −33° to +36°): depth, which Joshua Choi's build provides. - **CPU rendering of the sim.** The build ships only HDRP Vulkan shaders, so lavapipe and GL are impossible, and the sim shares the NVIDIA driver with other jobs. +- **In-loop mapping on the point cloud (compete track).** The mapping lap's accumulated cloud + was not usable on the compete track: within 15 cm of the LiDAR walls for 22–68 % of corner + edges depending on range, and none of five mapping-drive settings closed a lap without a hit. + This is what the occupancy grid replaced (`mapping.wall_source: occupancy`). + +## Superseded: LiDAR campaign (2026-10-20) + +The first validation and benchmark used the sim's LiDAR for the mapping lap and fused the sim's +speed, which pilot_core no longer does (`start.py` refuses `lidar.enabled`). Full tables: +[bench/2026-10-20/results.md](../bench/2026-10-20/results.md). The raw runs were on a cloud box +that has since been released; only the summary tables were kept. + +### Validation + +| check | result | +| ----- | ------ | +| Link: rates, pose, LiDAR, camera | PASS. Pose error 2.5e-7 m; 100 % of LiDAR points within 10 cm of the mapped walls | +| Disarmed hold / armed command echo | PASS / PASS | +| Steering sign / negative throttle | PASS / PASS | +| Reset | PASS, 0.0001 m from the start | +| Stop: SIGTERM or SIGKILL `start.py` | PASS / PASS. Neutral sent; the car rolled 0.34 / 0.30 m | +| Stop: SIGKILL every pilot_core process | **FAIL**. The sim has no command timeout: 8.51 m driven, 15 wall hits in 21.2 s. Needs a sim-side timeout like the firmware's 250 ms | +| Calibration | 24.80 m/s per unit throttle; effective wheelbase 0.342 m | +| Map, then race 3 laps | PASS: 0 collisions; cross-track RMS 4.1 cm | +| pytest | 357 passed, 7 skipped (all extras installed) | + + +### Benchmark (84 completed runs, 2 failed cells, 2 skipped; 3 repeats × 2 laps per cell) + +![Benchmark summary](../bench/2026-10-20/summary.png) + +Of the 84 completed runs, one (mpc, v_max 2.5, repeat 3) finished 1 of its 2 laps. The two +failed cells are ORB-SLAM3 as the pose source (CUDA and CPU), below. + +- **Controller × v_max.** At v_max 4.0, pure_pursuit and mpc are fastest (mean lap + 14.2–14.4 s) with 0 collisions. mpc has the lowest cross-track error from 1.5 m/s up. + Collisions happen only at v_max ≥ 2.5, with lqr and stanley; stanley at 4.0 is the worst + cell (1.3 ± 2.3 per run). The car never reaches 4.0 m/s: its mean speed is about 2.3 m/s. +- **Loop rate, 30 / 50 / 100 Hz.** Barely matters. pure_pursuit best lap 12.89–12.90 s; + mpc is about 0.25 s slower per lap with 3.8 cm cross-track. +- **Pose and map source.** Saved map: best lap 12.90 s. LiDAR mapping on the fly, then + racing: 12.63 ± 0.25 s. This gap is unexplained; the two maps differ in length by only 0.2 m. + ORB-SLAM3: **FAILED** (below). +- **Track.** Practice best lap 12.89 s; compete best lap 19.53 s; 0 collisions on both. +- **Sim stalls.** 0–89.8 % of a run's wall time in controller × v_max, when other GPU jobs + shared the GPU; 0 % in every other stage. Each run reports `stalled_pct`. -Raw runs, GIFs and logs are archived with the maintainers ([datasets.md](datasets.md)). diff --git a/docs/roadmap.md b/docs/roadmap.md index c61599a..83816b6 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,39 +1,71 @@ # Roadmap -Where the work stands and what is next. Results so far: [results.md](results.md). +Where the work stands and what is next. Results: [results.md](results.md). The gaps between +the sim and the car, axis by axis: [sim_to_real.md](sim_to_real.md). -## Car (real hardware) +## Done -1. **OAK-D on USB 3** and a matching SLAM settings file at the car's frame rate - ([oakd.md](oakd.md#open-items)). -2. **First recordings on the track**: hand-driven mapping laps (`--recording`), then BC - data and a real segmentation set from them ([datasets.md](datasets.md#still-to-collect)). -3. **Autonomous mapping lap** on the segmentation-edge scan (no LiDAR on the car): needs the - real segmentation model from (2), `track_control.mapping_drive` and `vision.enabled`. - Before driving it, check the scan with the car standing still against tape-measured wall distances. -4. **Before driving**: calibrate `speed_per_throttle`, measure `vehicle_params.yaml` (still - F1TENTH placeholders) and the camera height and pitch, and bench-test arm / disarm and - the steering direction with the wheels off the ground. +- **One pipeline.** The car and the sim map and drive with the same segmentation, scan, mapping, + control, state and actuator workers; a test keeps it that way. +- **Camera-only mapping and racing in the sim.** Walls from an occupancy grid over the + segmentation-edge scans, in the loop: the practice track maps cleanly in one lap and races 10 + laps without a hit; the compete track maps every time ([results.md](results.md)). +- **A SLAM-like sim pose** (`sim_pose_degrade`) for testing the controllers against late, noisy, + drifting poses with dropouts. +- **Deployment tooling.** `scripts/jetson_selftest.py` before every start, `scripts/stage_latency.py` + for per-stage latency from any recording, deploys from `car-v*` tags, the Jetson image built in + CI ([deployment.md](deployment.md)). + +## Car + +Each step needs the car, the Jetson and the track; in this order, nothing moves a wheel before +steps 1 and 2 pass. + +1. **Firmware bench test.** Compile (`arduino-cli compile -b arduino:esp32:nano_nora firmware/`) + and run the five wheels-off checks in `firmware/README.md`: RC only, Jetson only, stick + override, Jetson timeout (servo to neutral within 250 ms), transmitter off. Then remove its warning. +2. **Jetson bring-up.** `scripts/jetson_selftest.py` all PASS; OAK-D on USB 3; regenerate + `orbslam_oakd_rgbd.yaml` at the car's frame rate (30 fps requested, the file says 15); try the + Pro's IR dot projector for depth indoors; pin `depthai` ([oakd.md](oakd.md#open-items)). +3. **Measure on the Orin.** A recorded run through `scripts/stage_latency.py`, `SLAMWorker`'s + tracking time, CPU / GPU load and thermals at maximum performance, next to the sim's table in + [results.md](results.md#stage-latency). +4. **Calibrate.** `speed_per_throttle` from a straight run, `vehicle_params.yaml` (F1TENTH + placeholders now), and the camera height and pitch (SLAM logs them at start). +5. **Hand-driven recordings.** Five or more RC laps with `--recording`; bootstrap masks from them, + correct a few hundred by hand, train the segmentation on real frames and score it on a held-out + lap ([datasets.md](datasets.md#still-to-collect)). Until then the car uses `ground_plane`. +6. **ORB-SLAM3 on the recordings.** Tracked frames and ATE against AprilTags (`scripts/vio_bench`); + refit `sim_pose_degrade` from the measured latency, noise and dropouts. Drive the rear-IMU + estimator; `lqr` / `mpc` stay sim-only until its yaw rate is measured. +7. **Static scan check.** The car standing still, segmentation-edge scan against tape-measured + wall distances at 0.5, 1, 2 and 3 m. +8. **Autonomous lap.** Mapping lap on the scan, then three laps of `pure_pursuit` with the speed cap + at 1.0 m/s; a kill test at low speed (SIGKILL every process, the firmware timeout stops the car). +9. **Release.** Tag the version that did it `car-v1.0.0` ([deployment.md](deployment.md#releasing-a-car-version)); + the Jetson runs that tag from then on. ## Simulator -1. **Policy collisions.** About 30 % of live episodes collide, most likely because - `rl/bicycle_env.py` models the car as circles of r = 0.14 m. Retrain with the real - footprint and a wall margin, then benchmark against pure_pursuit at the same speed cap - (3 runs × 2 laps, practice and compete). -2. **Drive the segmentation-edge scan live** in the sim (`seg_scan.source: segmentation`): it - is only scored offline so far. -3. **ORB-SLAM3 in the sim** needs Joshua Choi's build (a front camera with depth). The stock - camera cannot support it ([results.md](results.md#what-did-not-work)). -4. **Sim-side command timeout.** If every pilot_core process dies, the stock sim keeps - applying the last command. Raise this upstream. -5. Optional: re-run controller × v_max on a GPU without other jobs (that stage had 0–90 % - sim stalls), and find out why on-the-fly LiDAR maps lap about 0.3 s faster than the - saved map. +1. **Race settings against the degraded pose.** With `sim_pose_degrade` on, the compete race goes + from 0–1 to 12–15 collisions and 2–3 s slower laps, and latency and dropouts are the cause, not + noise ([results.md](results.md#degraded-pose-2026-11-09)). Separate latency from dropouts, then + tune the speed profile and lookahead (or the estimator) until the degraded race is clean; that is + the setting the car should start from. +2. **Compete-track racing lines on live maps.** The live maps are as accurate as the offline one, + but their racing lines pass 0.33–0.42 m from a wall (0.45 m offline) and hit the left hairpins. + Keep the line 0.45 m off on any map, or map two laps before racing. +3. **Policy collisions.** About 30 % of live episodes collide, most likely because + `rl/bicycle_env.py` models the car as circles of r = 0.14 m. Retrain with the real footprint + and a wall margin, then benchmark against `pure_pursuit` at the same speed cap. +4. **ORB-SLAM3 in the sim** needs Joshua Choi's build (a front camera with depth); the stock + camera cannot support it ([results.md](results.md#what-did-not-work)). Until then the degraded + pose stands in. +5. **Sim-side neutral on disconnect.** If every pilot_core process dies, the stock sim keeps + applying the last command. An issue for the simulator's repository (`Tinker-Twins/AutoDRIVE`) + is drafted in the maintainers' notes. ## Repository -- **Sim location.** The sim scripts default to `/workspaces/autodrive_sim` and - `/workspaces/logs` (`autodrive_bench.py`, `autodrive_texture_sim.py`, the supervisor - scripts). Move these to one setting or environment variable. -- Upload the data bundles ([datasets.md](datasets.md)). +- `scripts/autodrive_texture_sim.py` still hard-codes `/workspaces`; the other sim scripts read + `AUTODRIVE_ROOT` and `AUTODRIVE_LOG_DIR`. diff --git a/docs/sim_to_real.md b/docs/sim_to_real.md new file mode 100644 index 0000000..d760219 --- /dev/null +++ b/docs/sim_to_real.md @@ -0,0 +1,54 @@ +# Sim to real + +pilot_core runs the same processes on the car and in the AutoDRIVE RoboRacer simulator; only +the sensor source differs (`CameraWorker` + `IMUWorker` + `SLAMWorker` on the car, +`AutoDRIVEWorker` in the sim). This page lists, axis by axis, what the sim gives, what the car +will give, the gap between them, and what the code does about it. Numbers link to the file they +come from. The car column is mostly unmeasured: nothing in this repository has yet run on the +Jetson with the current code ([roadmap.md](roadmap.md#car)). + +## One pipeline + +For a mapping lap, `config.yaml` (car) and `config_autodrive.yaml` (sim) build the same +segmentation, scan, mapping, control, state and actuator workers, wired the same way: +`tests/test_start_wiring.py::test_car_and_sim_map_and_drive_with_the_same_workers` fails if +they drift apart. + +```mermaid +flowchart LR + src["car: OAK-D + ORB-SLAM3
sim: AutoDRIVE (+ degraded pose)"] -- "frame_buf · pose_buf" --> vis[VisionWorker] + vis -- seg_buf --> scan[SegScanWorker] + scan -- "scan (with edge memory)" --> ctrl[ControlWorker] + scan -- "raw scan" --> map["MappingWorker
occupancy grid"] + map -- boundary_buf --> ctrl + src -- pose_buf --> state[StateWorker] + state --> ctrl + ctrl --> act["ActuatorWorker
safety supervisor"] +``` + +## Axis by axis + +| axis | sim | car | gap | handled by | +| --- | --- | --- | --- | --- | +| Pose | ground truth, on time (stage latency: delivered within ~1 ms, [results.md](results.md#stage-latency)) | ORB-SLAM3 RGB-D, CUDA fork. On rendered sequences of the track: tracking p50 8.4 ms / p95 41.4 ms, ATE 0.107 m over three laps ([inertial_fix.md](../bench/2026-10-29_vio_sim/inertial_fix.md)) | late, noisy, drifting, lost in featureless stretches; not measured on the car | `sim_pose_degrade` publishes the sim pose with that latency, noise, bias and dropouts. The race settings survive the noise and bias, not the latency and dropouts ([results.md](results.md#degraded-pose-2026-11-09)); refit it from car recordings | +| Drivable area | Fast-SCNN trained on sim runs: IoU 0.941 on the unseen compete track | `ground_plane` (RANSAC floor from depth, no training) until a model trained on real frames exists | the sim model does not transfer (other sensor, mount, light) | same `VisionWorker` interface; collect and label real frames ([datasets.md](datasets.md#still-to-collect)) | +| Scan | `SegScanWorker`, 1.5 s edge memory | the same worker and memory | memory computed in each pose's own frame (Z-up sim, SLAM camera frame on the car) | `bev_axes` / `forward_axis`; `tests/test_occupancy_map.py` checks the SLAM frame | +| Edge placement | no depth: each edge where its pixel's ray meets the floor | OAK-D depth, about 33 % valid in a dim room ([oakd.md](oakd.md)) | depth holes | floor intersection where depth is missing (`floor_fallback`); needs the measured camera height and pitch | +| Walls | occupancy grid over the raw scans (`mapping.wall_source: occupancy`) | the same | none in code; not yet run on the car | offline and live mapper share `control/occupancy_map.py`; the offline map is reproduced exactly | +| Camera geometry | 192×108 upscaled to 384×216, 10.5° down, 0.17 m up | OAK-D 640×400; height 0.12 m and pitch 0 are placeholders (`config.yaml`) | unmeasured mount | SLAM fits the floor at start and logs the camera's pitch and height ([slam.md](slam.md#mapping-lap)) | +| Frame rate | camera 12 fps, pose 24 Hz | `config.yaml` asks for 30 fps; `orbslam_oakd_rgbd.yaml` says 15 | settings mismatch | regenerate with `scripts/gen_orbslam_settings.py` at the car's rate ([oakd.md](oakd.md#open-items)) | +| Vehicle model | calibrated: effective wheelbase 0.342 m, 24.8 m/s per unit throttle ([autodrive.md](autodrive.md#calibration-scriptsautodrive_validatepy-calibrate)) | F1TENTH placeholders, 3.0 m/s per unit uncalibrated | unmeasured car | calibrate before driving (README, "Before driving") | +| Speed and yaw rate | no sim speed; `PoseEKF` from poses | the same, or `ImuEKF` on the rear IMU | yaw rate from poses is 33–41 deg/s RMS off ([rear_imu_fusion.md](../bench/2026-10-29_vio_sim/rear_imu_fusion.md)) | `pure_pursuit` (no yaw rate) is the car's controller; `lqr` / `mpc` stay sim-only until the rear-IMU estimator is driven | +| Safety | supervisor in `ActuatorWorker`: neutral until armed, 150 ms command watchdog, 1.5 m/s cap, slew limits | the same, plus the firmware's 250 ms timeout and RC override | the firmware path has not been compiled or bench-tested; the sim has no command timeout of its own | bench test in `firmware/README.md`; the sim gets neutral from pilot_core on SIGTERM / SIGINT | +| Compute | L40S GPU, 12 CPU cores | Jetson Orin | everything runs in less headroom; not measured | `scripts/stage_latency.py` and `scripts/jetson_selftest.py` ([deployment.md](deployment.md)) | + +## What has been shown, and what has not + +Shown in the sim, camera only: the mapping lap's walls from the occupancy grid, and racing on +camera-built maps ([results.md](results.md)). Shown on the bench: the OAK-D's depth and IMU +streams on a development PC ([oakd.md](oakd.md)), and CUDA ORB-SLAM3 on TUM RGB-D at 8.0–8.7 ms +per frame on an RTX 4080 ([slam.md](slam.md)). + +Not yet shown: anything on the Jetson with this code, a real-track segmentation model, ORB-SLAM3 +on real track recordings, and an autonomous lap of the real car. The [roadmap](roadmap.md#car) +orders those steps. diff --git a/docs/slam.md b/docs/slam.md index 0af6668..7aa7715 100644 --- a/docs/slam.md +++ b/docs/slam.md @@ -62,6 +62,69 @@ the camera changes. `CameraWorker` warns if the connected camera doesn't match. python scripts/gen_orbslam_settings.py --config config.yaml ``` +## RGB-D-inertial mode (`slam.inertial`) + +ORB-SLAM3's `IMU_RGBD` sensor adds the OAK-D's own accelerometer and gyro to the RGB-D +frames. Off by default; not yet tried on the car. + +```bash +python scripts/gen_orbslam_settings.py --imu # camera level and still: also checks T_b_c1 against gravity +``` + +then set `slam.inertial: true` (and `camera.imu_rate_hz` if not 100; regenerate the +settings after changing it). `CameraWorker` streams accel + gyro (all three axes) into +`raw_imu_buf`, apart from `imu_buf`, which keeps whichever IMU `use_oakd_imu` selects, so +the external Arduino IMU can run alongside. `SLAMWorker` hands ORB-SLAM3 the samples +between consecutive frames (waiting up to `imu_wait_s` for the IMU to catch up). + +- The noise values written by `--imu` are ORB-SLAM3's D435i example, not measured for + this IMU; an Allan-variance recording of the still camera gives the real ones. +- While the IMU initialises, ORB-SLAM3 rotates its whole map to gravity (up to three + times in the first ~15 s). Poses and map points are published relative to the map's + origin keyframe, which rotates with it, so the published frame stays put; the frame + of each rotation is withheld. +- The IMU initialisation needs varied motion; a car on a flat floor gives it little. + Check it on real laps (the log says when the IMU is initialised) before relying on it. +- Tracking losses: upstream ORB-SLAM3 resets the whole active map on any tracking loss + before the IMU is initialised and before its second inertial BA (~15 s), adds + keyframes only every 0.25 s until the IMU is initialised, and never for weak visual + tracking. At car speeds that loops: the local map falls behind within a few frames, + tracking drops, the map is wiped, repeat. The fork (branch `inertial-depth-recovery`) + changes this for `IMU_RGBD` / `IMU_STEREO`, where depth fixes the scale: a loss before + initialisation is relocalised (then a new map) like the RGB-D mode, and weak tracking + asks for a keyframe. Until the IMU is initialised, frames are tracked with the RGB-D + mode's rules (upstream uses monocular-inertial ones, which lose a swerve at 4-5 m/s), + and before the second inertial BA a lost map is given up after `IMU.EarlyLostTimeout` + (0.5 s). `IMU.UpstreamPolicy: 1` in the settings restores upstream. +- The map is only started once the IMU sees acceleration ("not enough acceleration" in + the log): standing still does not initialise anything; the IMU initialises ~1 s into + driving and is fully refined (inertial BA 2) ~15 s later. A tracking loss before then + starts a new map; after it, short featureless stretches are bridged by the IMU. +- Some OAK-Ds store no IMU calibration (the OAK-D Lite in `ORB_SLAM3/calib_*.json` has + none): `--imu` then stops and asks for the CAM_A -> IMU transform via + `--imu-extrinsics` (a 4x4 matrix as a list of rows, p_imu = T p_cam, metres). + +## Rear IMU state estimate (`rear_imu`) + +The Arduino's ICM-20948 at the back of the car can drive the state estimate: +`StateWorker` then runs `control.ImuEKF` (gyro yaw rate, through SLAM gaps, poses applied +at their capture time) instead of the pose-only EKF. The firmware already sends what it +needs (accel in g, gyro in deg/s, bias-corrected at start-up); `IMUWorker` writes it to +`rear_imu_buf`, dropping polls that repeat the last sample. In the sim this took position +error through 0.3-0.5 s SLAM gaps from 0.3-0.8 m to ~0.1 m and the yaw-rate error from +33-41 deg/s to 0.7 deg/s (`bench/2026-10-29_vio_sim/rear_imu_fusion.md`). + +1. On the car, motors off, `start.py` stopped: `python scripts/check_rear_imu.py`. Keep + still, then turn the car left ~90 deg by hand, then push it forward, when told. It + prints the sample rate and repeats, the gyro bias at rest, and a `rear_imu` block with + the mounting rotation (the firmware forces accel to (0, 0, 1 g) at rest whatever the + mounting, so only motion shows it). The turn should read ~90 deg. +2. Measure `lever_m`: the IMU's position from the camera, in m, x forward, y left. +3. Record with it on (`make_record_config.py`, `rear_imu.enabled: true`) and run + `python scripts/check_rear_imu.py --recording ` for `delay_s` (its lag behind the + OAK-D's IMU from the angular-rate magnitudes; the sim's DLPF + read gave 8.5 ms). +4. Paste the block into `config.yaml`. The published state stays the camera's point. + ## Mapping lap 1. Start with `--enable-slam` and keep the car still on the floor for a second: diff --git a/maps/autodrive_compete/raceline.npy b/maps/autodrive_compete/raceline.npy new file mode 100644 index 0000000..9319f2b Binary files /dev/null and b/maps/autodrive_compete/raceline.npy differ diff --git a/maps/autodrive_compete/raceline.png b/maps/autodrive_compete/raceline.png new file mode 100644 index 0000000..29ee136 Binary files /dev/null and b/maps/autodrive_compete/raceline.png differ diff --git a/maps/autodrive_compete_live1/inner_line.npy b/maps/autodrive_compete_live1/inner_line.npy new file mode 100644 index 0000000..7edda6e Binary files /dev/null and b/maps/autodrive_compete_live1/inner_line.npy differ diff --git a/maps/autodrive_compete_live1/outer_line.npy b/maps/autodrive_compete_live1/outer_line.npy new file mode 100644 index 0000000..8ca4704 Binary files /dev/null and b/maps/autodrive_compete_live1/outer_line.npy differ diff --git a/maps/autodrive_compete_live1/raceline.npy b/maps/autodrive_compete_live1/raceline.npy new file mode 100644 index 0000000..054a90a Binary files /dev/null and b/maps/autodrive_compete_live1/raceline.npy differ diff --git a/maps/autodrive_compete_live1/raceline.png b/maps/autodrive_compete_live1/raceline.png new file mode 100644 index 0000000..61359c4 Binary files /dev/null and b/maps/autodrive_compete_live1/raceline.png differ diff --git a/maps/autodrive_compete_live2/inner_line.npy b/maps/autodrive_compete_live2/inner_line.npy new file mode 100644 index 0000000..639ba64 Binary files /dev/null and b/maps/autodrive_compete_live2/inner_line.npy differ diff --git a/maps/autodrive_compete_live2/outer_line.npy b/maps/autodrive_compete_live2/outer_line.npy new file mode 100644 index 0000000..e59ce15 Binary files /dev/null and b/maps/autodrive_compete_live2/outer_line.npy differ diff --git a/maps/autodrive_compete_live2/raceline.npy b/maps/autodrive_compete_live2/raceline.npy new file mode 100644 index 0000000..2fc4a99 Binary files /dev/null and b/maps/autodrive_compete_live2/raceline.npy differ diff --git a/maps/autodrive_compete_live2/raceline.png b/maps/autodrive_compete_live2/raceline.png new file mode 100644 index 0000000..431c395 Binary files /dev/null and b/maps/autodrive_compete_live2/raceline.png differ diff --git a/maps/autodrive_compete_live3/inner_line.npy b/maps/autodrive_compete_live3/inner_line.npy new file mode 100644 index 0000000..8dddb85 Binary files /dev/null and b/maps/autodrive_compete_live3/inner_line.npy differ diff --git a/maps/autodrive_compete_live3/outer_line.npy b/maps/autodrive_compete_live3/outer_line.npy new file mode 100644 index 0000000..a210b45 Binary files /dev/null and b/maps/autodrive_compete_live3/outer_line.npy differ diff --git a/maps/autodrive_compete_live3/raceline.npy b/maps/autodrive_compete_live3/raceline.npy new file mode 100644 index 0000000..bf602fa Binary files /dev/null and b/maps/autodrive_compete_live3/raceline.npy differ diff --git a/maps/autodrive_compete_live3/raceline.png b/maps/autodrive_compete_live3/raceline.png new file mode 100644 index 0000000..bdc68f0 Binary files /dev/null and b/maps/autodrive_compete_live3/raceline.png differ diff --git a/maps/autodrive_compete_seg/inner_line.npy b/maps/autodrive_compete_seg/inner_line.npy new file mode 100644 index 0000000..9163d70 Binary files /dev/null and b/maps/autodrive_compete_seg/inner_line.npy differ diff --git a/maps/autodrive_compete_seg/map.png b/maps/autodrive_compete_seg/map.png new file mode 100644 index 0000000..eef923e Binary files /dev/null and b/maps/autodrive_compete_seg/map.png differ diff --git a/maps/autodrive_compete_seg/outer_line.npy b/maps/autodrive_compete_seg/outer_line.npy new file mode 100644 index 0000000..3e58902 Binary files /dev/null and b/maps/autodrive_compete_seg/outer_line.npy differ diff --git a/maps/autodrive_compete_seg/raceline.npy b/maps/autodrive_compete_seg/raceline.npy new file mode 100644 index 0000000..de44970 Binary files /dev/null and b/maps/autodrive_compete_seg/raceline.npy differ diff --git a/maps/autodrive_compete_seg/raceline.png b/maps/autodrive_compete_seg/raceline.png new file mode 100644 index 0000000..9a1c283 Binary files /dev/null and b/maps/autodrive_compete_seg/raceline.png differ diff --git a/maps/autodrive_practice/raceline.npy b/maps/autodrive_practice/raceline.npy new file mode 100644 index 0000000..16b3f88 Binary files /dev/null and b/maps/autodrive_practice/raceline.npy differ diff --git a/maps/autodrive_practice/raceline.png b/maps/autodrive_practice/raceline.png new file mode 100644 index 0000000..880a780 Binary files /dev/null and b/maps/autodrive_practice/raceline.png differ diff --git a/maps/autodrive_practice_live1/inner_line.npy b/maps/autodrive_practice_live1/inner_line.npy new file mode 100644 index 0000000..299c297 Binary files /dev/null and b/maps/autodrive_practice_live1/inner_line.npy differ diff --git a/maps/autodrive_practice_live1/outer_line.npy b/maps/autodrive_practice_live1/outer_line.npy new file mode 100644 index 0000000..b6e6bda Binary files /dev/null and b/maps/autodrive_practice_live1/outer_line.npy differ diff --git a/maps/autodrive_practice_live1/raceline.npy b/maps/autodrive_practice_live1/raceline.npy new file mode 100644 index 0000000..0e6bc8e Binary files /dev/null and b/maps/autodrive_practice_live1/raceline.npy differ diff --git a/maps/autodrive_practice_live1/raceline.png b/maps/autodrive_practice_live1/raceline.png new file mode 100644 index 0000000..cc0046d Binary files /dev/null and b/maps/autodrive_practice_live1/raceline.png differ diff --git a/maps/autodrive_practice_live2/inner_line.npy b/maps/autodrive_practice_live2/inner_line.npy new file mode 100644 index 0000000..cb42c86 Binary files /dev/null and b/maps/autodrive_practice_live2/inner_line.npy differ diff --git a/maps/autodrive_practice_live2/outer_line.npy b/maps/autodrive_practice_live2/outer_line.npy new file mode 100644 index 0000000..ea07f57 Binary files /dev/null and b/maps/autodrive_practice_live2/outer_line.npy differ diff --git a/maps/autodrive_practice_live2/raceline.npy b/maps/autodrive_practice_live2/raceline.npy new file mode 100644 index 0000000..2e2cbae Binary files /dev/null and b/maps/autodrive_practice_live2/raceline.npy differ diff --git a/maps/autodrive_practice_live2/raceline.png b/maps/autodrive_practice_live2/raceline.png new file mode 100644 index 0000000..16f42da Binary files /dev/null and b/maps/autodrive_practice_live2/raceline.png differ diff --git a/maps/autodrive_practice_live3/inner_line.npy b/maps/autodrive_practice_live3/inner_line.npy new file mode 100644 index 0000000..853cfd9 Binary files /dev/null and b/maps/autodrive_practice_live3/inner_line.npy differ diff --git a/maps/autodrive_practice_live3/outer_line.npy b/maps/autodrive_practice_live3/outer_line.npy new file mode 100644 index 0000000..0a7146d Binary files /dev/null and b/maps/autodrive_practice_live3/outer_line.npy differ diff --git a/maps/autodrive_practice_live3/raceline.npy b/maps/autodrive_practice_live3/raceline.npy new file mode 100644 index 0000000..b1f8a42 Binary files /dev/null and b/maps/autodrive_practice_live3/raceline.npy differ diff --git a/maps/autodrive_practice_live3/raceline.png b/maps/autodrive_practice_live3/raceline.png new file mode 100644 index 0000000..bb4fcfc Binary files /dev/null and b/maps/autodrive_practice_live3/raceline.png differ diff --git a/maps/autodrive_practice_seg/inner_line.npy b/maps/autodrive_practice_seg/inner_line.npy new file mode 100644 index 0000000..2febd7c Binary files /dev/null and b/maps/autodrive_practice_seg/inner_line.npy differ diff --git a/maps/autodrive_practice_seg/outer_line.npy b/maps/autodrive_practice_seg/outer_line.npy new file mode 100644 index 0000000..838c936 Binary files /dev/null and b/maps/autodrive_practice_seg/outer_line.npy differ diff --git a/maps/autodrive_practice_seg/raceline.npy b/maps/autodrive_practice_seg/raceline.npy new file mode 100644 index 0000000..39f7280 Binary files /dev/null and b/maps/autodrive_practice_seg/raceline.npy differ diff --git a/maps/autodrive_practice_seg/raceline.png b/maps/autodrive_practice_seg/raceline.png new file mode 100644 index 0000000..4de1b00 Binary files /dev/null and b/maps/autodrive_practice_seg/raceline.png differ diff --git a/orbslam3_wrapper/src/bind.cpp b/orbslam3_wrapper/src/bind.cpp index 13be4bd..b9c2bb8 100644 --- a/orbslam3_wrapper/src/bind.cpp +++ b/orbslam3_wrapper/src/bind.cpp @@ -1,12 +1,20 @@ +/* + * Copyright (C) 2024-2026 UTASR - UT Autonomous Scale Racing + * + * This file links ORB-SLAM3 and is distributed under the GNU General Public License, + * version 3 or later, the licence of ORB-SLAM3 (ORB_SLAM3/LICENSE). See NOTICE. + */ /* * pybind11 wrapper for ORB_SLAM3. Only exposes what the pilot_core workers * actually use: * * orbslam3_python.System(vocab, settings, sensor_type) - * .track_rgbd(rgb, depth, timestamp) -> np.ndarray (4x4 float32, Tcw) + * .track_rgbd(rgb, depth, timestamp, imu=None) -> np.ndarray (4x4 float32, Tcw) * .map_changed() -> bool * .is_running_gba() -> bool * .map_info() -> (map_id, init_kf_id, n_keyframes) + * .origin_pose() -> np.ndarray (4x4 float32, Twc of the origin keyframe) + * .imu_initialized() -> bool * .get_all_map_points() -> np.ndarray (N x 3 float32) * .get_all_keyframe_poses() -> np.ndarray (K x 4 x 4 float32, Twc) * .activate_localization_mode() -> None @@ -14,7 +22,8 @@ * .get_tracking_state() -> int * .shutdown() -> None * - * plus the ORB_SLAM3::System::eSensor constants MONOCULAR, STEREO, RGBD. + * plus the ORB_SLAM3::System::eSensor constants (RGBD and IMU_RGBD are the ones + * track_rgbd serves). * * Map points and keyframes are those of the Atlas' *current* map. ORB-SLAM3 * starts a new map (new id) when tracking is lost for good and resets the @@ -51,9 +60,8 @@ class SLAM { SLAM(const std::string &vocab, const std::string &settings, int sensor) - : sys_(vocab, settings, - static_cast(sensor), - /*bUseViewer=*/false) {} + : sensor_(static_cast(sensor)), + sys_(vocab, settings, sensor_, /*bUseViewer=*/false) {} /** * One RGBD tracking step. @@ -61,15 +69,39 @@ class SLAM { * @param rgb uint8 (H, W, 3); channel order must match Camera.RGB in the settings * @param depth float32 (H, W), metres, same H and W as rgb * @param ts timestamp in seconds (capture time) + * @param imu IMU_RGBD only: (N, 7) float64 [t, ax, ay, az, gx, gy, gz] rows, the + * IMU samples with t in (previous frame's ts, ts], in time order; + * None for RGBD * @return 4x4 float32 Tcw (world-to-camera). When tracking isn't OK this * is identity or stale, so check get_tracking_state(). */ py::array_t track_rgbd(py::array_t rgb, py::array_t depth, - double ts) { + double ts, + py::object imu) { auto r = rgb.request(); auto d = depth.request(); + // IMU_RGBD: the samples since the previous frame, (N, 7) float64 rows of + // t (s, same clock as ts), ax, ay, az (m/s^2), gx, gy, gz (rad/s) in the IMU frame + std::vector imu_meas; + if (!imu.is_none()) { + auto arr = py::array_t::ensure(imu); + if (!arr) + throw std::invalid_argument("imu must be convertible to a float64 array"); + auto m = arr.request(); + if (m.ndim != 2 || m.shape[1] != 7) + throw std::invalid_argument("imu must be float64 (N, 7): t, ax, ay, az, gx, gy, gz"); + const double *p = static_cast(m.ptr); + imu_meas.reserve(static_cast(m.shape[0])); + for (py::ssize_t i = 0; i < m.shape[0]; ++i, p += 7) + imu_meas.emplace_back(static_cast(p[1]), static_cast(p[2]), + static_cast(p[3]), static_cast(p[4]), + static_cast(p[5]), static_cast(p[6]), p[0]); + } else if (sensor_ == ORB_SLAM3::System::IMU_RGBD) { + throw std::invalid_argument("an IMU_RGBD system needs the imu samples on every frame"); + } + if (r.ndim != 3 || r.shape[2] != 3) throw std::invalid_argument("rgb must be uint8 (H, W, 3)"); if (d.ndim != 2 || d.shape[0] != r.shape[0] || d.shape[1] != r.shape[1]) @@ -81,7 +113,7 @@ class SLAM { cv::Mat rgb_mat(h, w, CV_8UC3, r.ptr); cv::Mat dep_mat(h, w, CV_32FC1, d.ptr); - Sophus::SE3f pose = sys_.TrackRGBD(rgb_mat, dep_mat, ts); + Sophus::SE3f pose = sys_.TrackRGBD(rgb_mat, dep_mat, ts, imu_meas); Eigen::Matrix4f mat = pose.matrix(); // Eigen is column-major by default, so copy element-wise into the row-major array @@ -172,6 +204,27 @@ class SLAM { return out; } + /* + * Twc (4x4 float32) of the current map's origin keyframe, the one that defined its + * world frame. In the inertial modes ORB-SLAM3 later re-rotates the whole map to + * gravity (up to three times while the IMU initialises), origin included, so poses + * taken relative to it, inv(origin) * Twc, do not move. Identity without one. + */ + py::array_t origin_pose() { + ORB_SLAM3::KeyFrame *kf = sys_.mpAtlas->GetCurrentMap()->GetOriginKF(); + Eigen::Matrix4f T = (kf && !kf->isBad()) ? kf->GetPoseInverse().matrix() + : Eigen::Matrix4f::Identity(); + auto out = py::array_t(std::vector{4, 4}); + auto buf = out.mutable_unchecked<2>(); + for (int i = 0; i < 4; ++i) + for (int j = 0; j < 4; ++j) + buf(i, j) = T(i, j); + return out; + } + + // Inertial modes: true once the IMU (gravity, biases) has been initialised. + bool imu_initialized() { return sys_.mpAtlas->GetCurrentMap()->isImuInitialized(); } + void activate_localization_mode() { sys_.ActivateLocalizationMode(); } void deactivate_localization_mode() { sys_.DeactivateLocalizationMode(); } int get_tracking_state() { return sys_.GetTrackingState(); } @@ -179,6 +232,7 @@ class SLAM { void shutdown() { sys_.Shutdown(); } private: + ORB_SLAM3::System::eSensor sensor_; // declared before sys_, which is built from it ORB_SLAM3::System sys_; std::map last_big_change_; // map id -> last reported big-change index }; @@ -191,8 +245,8 @@ PYBIND11_MODULE(orbslam3_python, m) { .def(py::init(), py::arg("vocab"), py::arg("settings"), py::arg("sensor_type")) .def("track_rgbd", &SLAM::track_rgbd, - py::arg("rgb"), py::arg("depth"), py::arg("timestamp"), - "Run one RGBD tracking step, returns the 4x4 Tcw pose as float32") + py::arg("rgb"), py::arg("depth"), py::arg("timestamp"), py::arg("imu") = py::none(), + "Run one RGBD (or, with imu, RGBD-inertial) tracking step, returns the 4x4 Tcw pose as float32") .def("map_changed", &SLAM::map_changed, "True once after each loop closure / global BA on the current map") .def("is_running_gba", &SLAM::is_running_gba, @@ -203,6 +257,10 @@ PYBIND11_MODULE(orbslam3_python, m) { "Current map's points as (N,3) float32") .def("get_all_keyframe_poses", &SLAM::get_all_keyframe_poses, "Current map's keyframe poses (Twc) as (K,4,4) float32, in id order") + .def("origin_pose", &SLAM::origin_pose, + "Twc of the current map's origin keyframe (moves when an inertial map is re-rotated to gravity)") + .def("imu_initialized", &SLAM::imu_initialized, + "Inertial modes: True once ORB-SLAM3 has initialised the IMU") .def("activate_localization_mode", &SLAM::activate_localization_mode, "Switch to localization-only mode (no mapping)") .def("deactivate_localization_mode", &SLAM::deactivate_localization_mode, @@ -215,4 +273,7 @@ PYBIND11_MODULE(orbslam3_python, m) { m.attr("MONOCULAR") = static_cast(ORB_SLAM3::System::MONOCULAR); m.attr("STEREO") = static_cast(ORB_SLAM3::System::STEREO); m.attr("RGBD") = static_cast(ORB_SLAM3::System::RGBD); + m.attr("IMU_MONOCULAR") = static_cast(ORB_SLAM3::System::IMU_MONOCULAR); + m.attr("IMU_STEREO") = static_cast(ORB_SLAM3::System::IMU_STEREO); + m.attr("IMU_RGBD") = static_cast(ORB_SLAM3::System::IMU_RGBD); } diff --git a/scripts/autodrive_bench.py b/scripts/autodrive_bench.py index 6c4d202..269ec1d 100644 --- a/scripts/autodrive_bench.py +++ b/scripts/autodrive_bench.py @@ -37,6 +37,9 @@ sys.path.insert(0, REPO_ROOT) sys.path.insert(0, os.path.join(REPO_ROOT, "scripts")) PY = sys.executable +_ROOT = os.environ.get("AUTODRIVE_ROOT", "/workspaces") +SIM_LOG = os.path.join(os.environ.get("AUTODRIVE_LOG_DIR", os.path.join(_ROOT, "logs")), "autodrive_sim.log") +SIM_ENV = os.path.join(_ROOT, "autodrive_sim", "sim.env") def set_path(cfg: dict, dotted: str, value: Any) -> None: @@ -105,11 +108,14 @@ def _cpu_ticks(pid: int) -> Optional[int]: def run_pilot(base_config: str, out: str, overrides: dict, laps: int = 3, timeout: float = 600.0, stop: str = "quit", capture: bool = True, settle: float = 2.0, - drive_s: Optional[float] = None, max_collisions: Optional[int] = None) -> dict: + drive_s: Optional[float] = None, max_collisions: Optional[int] = None, + competition_start: bool = False) -> dict: """One start.py run against the sim. Returns timings, laps and paths. stop: quit (key q) | term (SIGTERM to start.py) | kill (SIGKILL to start.py) | killall (SIGKILL to every pilot_core process). drive_s: stop that long after the - racing starts instead of after `laps` laps.""" + racing starts instead of after `laps` laps. competition_start: as the competition container + starts: the sim restarted (car on its spawn), the config's own auto_arm, no reset and no + arm key; the car drives as soon as the sim connects.""" import autodrive_capture as cap import autodrive_sim_ctl as sim_ctl @@ -121,6 +127,14 @@ def run_pilot(base_config: str, out: str, overrides: dict, laps: int = 3, timeou set_path(cfg, k, v) cfg["recording"] = True cfg["recording_path"] = os.path.join(out, "rec") + if competition_start: + if not cfg.get("auto_arm"): + raise ValueError("competition_start needs a config with auto_arm: true (the competition container)") + restart_sim() + else: + # the run resets the sim and then arms: a config that arms itself on connect (the + # competition container) would start driving before that reset teleports it + cfg["auto_arm"] = False cfg_path = os.path.join(out, "config.yaml") with open(cfg_path, "w") as f: yaml.safe_dump(cfg, f, sort_keys=False) @@ -155,9 +169,12 @@ def key(k: str) -> float: rec_dir = rec_dirs[-1] if rec_dirs else None res["recording_dir"] = rec_dir time.sleep(1.0) - res["t_reset"] = key("r") - time.sleep(settle) - res["t_armed"] = key("a") + if competition_start: + res["t_armed"] = res["t_connected"] # armed itself on connect + else: + res["t_reset"] = key("r") + time.sleep(settle) + res["t_armed"] = key("a") pids = _worker_pids(log_path) pids["start"] = proc.pid res["worker_pids"] = pids @@ -410,9 +427,23 @@ def stage_cells(mx: dict, stage: str, out: str) -> list[dict]: return cells +def restart_sim() -> None: + """Restart the supervisor-run sim and wait until it is up: the car back on its spawn.""" + log = SIM_LOG + size = os.path.getsize(log) if os.path.exists(log) else 0 + subprocess.run(["supervisorctl", "restart", "autodrive_sim"], check=True, capture_output=True) + deadline = time.monotonic() + 120 + while not _tail_has(log, "UnloadTime", since=size): + if time.monotonic() > deadline: + raise RuntimeError("the sim did not come up") + time.sleep(1) + import autodrive_sim_ctl as sim_ctl + sim_ctl.wait_scene() + + def ensure_sim_variant(variant: str) -> None: """Switch the supervisor-run sim between the practice and compete builds.""" - env = "/workspaces/autodrive_sim/sim.env" + env = SIM_ENV with open(env) as f: lines = f.read().splitlines() cur = next((ln.split("=", 1)[1] for ln in lines if ln.startswith("SIM_VARIANT=")), "practice") @@ -421,7 +452,7 @@ def ensure_sim_variant(variant: str) -> None: lines = [ln for ln in lines if not ln.startswith("SIM_VARIANT=")] + [f"SIM_VARIANT={variant}"] with open(env, "w") as f: f.write("\n".join(lines) + "\n") - log = "/workspaces/logs/autodrive_sim.log" + log = SIM_LOG size = os.path.getsize(log) if os.path.exists(log) else 0 subprocess.run(["supervisorctl", "restart", "autodrive_sim"], check=True, capture_output=True) deadline = time.monotonic() + 120 @@ -429,7 +460,8 @@ def ensure_sim_variant(variant: str) -> None: if time.monotonic() > deadline: raise RuntimeError(f"sim ({variant}) did not come up") time.sleep(1) - time.sleep(3) + import autodrive_sim_ctl as sim_ctl + sim_ctl.wait_scene() def _summarise(runs: list[dict]) -> dict: @@ -648,6 +680,9 @@ def main() -> int: r.add_argument("--timeout", type=float, default=600) r.add_argument("--stop", choices=["quit", "term", "kill", "killall"], default="quit") r.add_argument("--drive-s", type=float, help="stop after this long racing instead of --laps") + r.add_argument("--max-collisions", type=int, help="stop once the run has more collisions than this") + r.add_argument("--competition-start", action="store_true", + help="start as the competition container does: sim restarted, the config's auto_arm, no reset / arm keys") mxp = sub.add_parser("matrix") mxp.add_argument("matrix") mxp.add_argument("--stage", required=True) @@ -678,7 +713,8 @@ def main() -> int: print(json.dumps(score_run(a.run_dir), indent=1, default=float)) return 0 if a.cmd == "run": - res = run_pilot(a.config, a.out, parse_sets(a.set), a.laps, a.timeout, a.stop, drive_s=a.drive_s) + res = run_pilot(a.config, a.out, parse_sets(a.set), a.laps, a.timeout, a.stop, drive_s=a.drive_s, + max_collisions=a.max_collisions, competition_start=a.competition_start) laps = [e for e in res["events"] if e["event"] == "lap"] coll = [e for e in res["events"] if e["event"] == "collision"] print(json.dumps({"laps": [(round(e["t"] - res["t_armed"], 1), e.get("lap_time")) for e in laps], diff --git a/scripts/autodrive_sim_ctl.py b/scripts/autodrive_sim_ctl.py index 625c00c..d500539 100644 --- a/scripts/autodrive_sim_ctl.py +++ b/scripts/autodrive_sim_ctl.py @@ -92,6 +92,17 @@ def _click(xy) -> None: subprocess.run(["xdotool", "mousemove", str(px), str(py)], env=_env()) # park off the HUD +def wait_scene(timeout: float = 90.0) -> None: + """Wait out Unity's splash (a flat dark window): the HUD ignores clicks until the scene + is up, which on a slow disk is well after the log's UnloadTime.""" + deadline = time.monotonic() + timeout + while _grab().max() < 120: + if time.monotonic() > deadline: + raise RuntimeError(f"no scene on {DISPLAY} after {timeout:.0f} s") + time.sleep(1) + time.sleep(2) + + def menu_open(img=None) -> bool: img = _grab() if img is None else img # threshold scales with the box area diff --git a/scripts/check_rear_imu.py b/scripts/check_rear_imu.py new file mode 100644 index 0000000..42dd123 --- /dev/null +++ b/scripts/check_rear_imu.py @@ -0,0 +1,201 @@ +#!/usr/bin/env python3 +"""Check the rear-of-car IMU (the Arduino's ICM-20948 over I2C) before enabling rear_imu. + + python scripts/check_rear_imu.py # on the car: live, follow the prompts + python scripts/check_rear_imu.py --recording # a recording with rear_imu (+ raw_imu) + +Live, three timed phases (the car on the floor, motors off): + 1. still (3 s): poll rate, new samples per second (the Jetson polls the latest sample, so + repeats are normal), interval jitter, the gyro's residual bias and the accel at rest; + 2. turn the car LEFT (counter-clockwise seen from above) by about 90 deg in place (5 s): + the gyro axis that integrates the turn is the car's up axis, and the angle checks the + scale; + 3. push the car straight FORWARD and stop it (4 s): the accel axis of the push is the + car's forward axis. +The firmware calibrates accel to (0, 0, 1 g) at rest, whatever the mounting, so the +mounting can only be seen from motion. Prints the rear_imu block for config.yaml. + +A recording (scripts/vio_bench/make_record_config.py with rear_imu enabled) gives the +rates and the rear IMU's delay against the OAK-D's IMU (device-timestamped with the +frames) by cross-correlating the angular-rate magnitudes, which don't depend on either +IMU's axes: delay_s for the config. +""" + +from __future__ import annotations + +import argparse +import os +import sys +import time + +import numpy as np + +REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, REPO_ROOT) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + + +def stream_stats(t: np.ndarray, new: np.ndarray) -> dict: + """t: poll times (s), new: True where the poll returned a new sample.""" + dur = max(float(t[-1] - t[0]), 1e-9) + tn = t[new] + gaps = np.diff(tn) if len(tn) > 1 else np.array([np.nan]) + return {"polls_hz": (len(t) - 1) / dur, "new_hz": (len(tn) - 1) / dur if len(tn) > 1 else 0.0, + "repeat_pct": 100.0 * (1.0 - new.mean()), "interval_ms": 1e3 * float(np.median(gaps)), + "interval_p99_ms": 1e3 * float(np.percentile(gaps, 99))} + + +def axis_from_turn(t: np.ndarray, gyro: np.ndarray) -> tuple: + """(axis, sign, degrees): the sensor axis that integrates a left (CCW) turn, its sign + (+1 if positive for CCW) and the integrated angle.""" + trapezoid = getattr(np, "trapezoid", None) or np.trapz # numpy 2 renamed it + ang = np.degrees(trapezoid(gyro, t, axis=0)) + k = int(np.argmax(np.abs(ang))) + return k, int(np.sign(ang[k]) or 1), float(abs(ang[k])) + + +def axis_from_push(acc: np.ndarray, up_axis: int, thresh: float = 0.4) -> tuple: + """(axis, sign): the horizontal sensor axis of a forward push, from its first clear + acceleration (accel minus its median at rest).""" + a = acc - np.median(acc, axis=0) + a[:, up_axis] = 0.0 + k = int(np.argmax(np.abs(a).max(axis=0))) + first = np.nonzero(np.abs(a[:, k]) > thresh)[0] + if not len(first): + raise ValueError("no clear push in the accel (more than 0.4 m/s^2)") + return k, int(np.sign(a[first[0], k])) + + +def rotation_from(up: tuple, fwd: tuple) -> np.ndarray: + """Rotation taking sensor vectors to the car frame (x forward, y left, z up).""" + if up[0] == fwd[0]: + raise ValueError("the turn and the push found the same sensor axis") + ez = np.zeros(3) + ez[up[0]] = up[1] + ex = np.zeros(3) + ex[fwd[0]] = fwd[1] + ey = np.cross(ez, ex) + return np.vstack([ex, ey, ez]) + + +def time_offset(t_ref: np.ndarray, w_ref: np.ndarray, t: np.ndarray, w: np.ndarray, max_s: float = 0.1) -> float: + """s by which the second stream lags the first, from |angular rate| cross-correlation.""" + a_t0, a_t1 = max(t_ref[0], t[0]) + max_s, min(t_ref[-1], t[-1]) - max_s + tg = np.arange(a_t0, a_t1, 0.001) + a = np.interp(tg, t_ref, np.linalg.norm(w_ref, axis=1)) + a = a - a.mean() + wn = np.linalg.norm(w, axis=1) + lags = np.arange(-max_s, max_s, 0.0005) + score = [] + for lag in lags: + b = np.interp(tg + lag, t, wn) + score.append(float(a @ (b - b.mean()))) + return float(lags[int(np.argmax(score))]) + + +def config_block(R: np.ndarray, delay: float = 0.0) -> str: + rows = ", ".join("[" + ", ".join(f"{int(v)}" for v in r) + "]" for r in np.round(R).astype(int)) + return ("rear_imu:\n enabled: true\n" + f" rotation: [{rows}]\n" + " lever_m: [0.0, 0.0] # m, measure: the IMU from the camera (x forward, y left)\n" + f" delay_s: {delay:.4f}\n estimator: {{}}\n") + + +def _poll(bus, addr, seconds: float, hz: float): + import smbus2 + + from workers.imu_worker import I2C_FRAME_SIZE, parse_i2c_raw + + t, s, new, last = [], [], [], None + end, nxt = time.monotonic() + seconds, time.monotonic() + while time.monotonic() < end: + nxt += 1.0 / hz + msg = smbus2.i2c_msg.read(addr, I2C_FRAME_SIZE) + try: + bus.i2c_rdwr(msg) + except OSError: + continue + data = bytes(msg) + x = parse_i2c_raw(data) + if x is not None: + t.append(time.monotonic()) + s.append(x) + new.append(data[16:40] != last) + last = data[16:40] + time.sleep(max(0.0, nxt - time.monotonic())) + return np.array(t), np.array(s), np.array(new, bool) + + +def live(args) -> int: + try: + import smbus2 + except ImportError: + print("smbus2 is not installed: run this on the car", file=sys.stderr) + return 1 + import yaml + + with open(os.path.join(REPO_ROOT, args.config)) as f: + cfg = yaml.safe_load(f) or {} + addr, busn = cfg.get("i2c_address"), cfg.get("i2c_bus", 1) + if addr is None: + print(f"{args.config} has no i2c_address", file=sys.stderr) + return 1 + bus = smbus2.SMBus(int(busn)) + print("1/3 keep the car still ...") + t, s, new = _poll(bus, addr, 3.0, args.poll_hz) + if len(t) < 10: + print("no IMU frames: is the Arduino running (and start.py stopped)?", file=sys.stderr) + return 1 + st = stream_stats(t, new) + g = s[new] + print(f" polls {st['polls_hz']:.0f} Hz, new samples {st['new_hz']:.0f} Hz ({st['repeat_pct']:.0f} % repeats), " + f"interval {st['interval_ms']:.1f} ms (p99 {st['interval_p99_ms']:.1f})") + print(f" gyro at rest {np.degrees(g[:, 3:].mean(0)).round(3)} deg/s (noise {np.degrees(g[:, 3:].std(0)).round(3)}), " + f"accel {g[:, :3].mean(0).round(3)} m/s^2") + print("2/3 turn the car LEFT (counter-clockwise from above) ~90 deg in place, now (5 s) ...") + t, s, new = _poll(bus, addr, 5.0, args.poll_hz) + up = axis_from_turn(t[new], s[new][:, 3:]) + print(f" sensor axis {'xyz'[up[0]]} ({'+' if up[1] > 0 else '-'}) turned {up[2]:.0f} deg") + print("3/3 push the car straight FORWARD and stop it, now (4 s) ...") + t, s, new = _poll(bus, addr, 4.0, args.poll_hz) + fwd = axis_from_push(s[new][:, :3], up[0]) + print(f" forward is sensor axis {'xyz'[fwd[0]]} ({'+' if fwd[1] > 0 else '-'})") + R = rotation_from(up[:2], fwd) + print("\nconfig.yaml (measure lever_m; delay_s from --recording):\n") + print(config_block(R)) + return 0 + + +def recording(args) -> int: + from read_recording import iter_records, list_files + + names = {rf.buffer for rf in list_files(args.recording)} + if "rear_imu" not in names: + print(f"{args.recording} has no rear_imu recording (rear_imu.enabled + recording)", file=sys.stderr) + return 1 + rear = np.array([[r.produced_ts, *r.value.tolist()] for r in iter_records(args.recording, "rear_imu")]) + rear = rear[np.argsort(rear[:, 0])] + gaps = np.diff(rear[:, 0]) + print(f"rear IMU: {len(rear)} samples, {1 / np.median(gaps):.0f} Hz, p99 interval {1e3 * np.percentile(gaps, 99):.1f} ms, " + f"{int(np.sum(gaps > 0.05))} gaps > 50 ms") + if "raw_imu" not in names: + print("no raw_imu (OAK-D) recording: no delay estimate") + return 0 + cam = np.array([[r.produced_ts, *r.value.tolist()] for r in iter_records(args.recording, "raw_imu")]) + cam = cam[np.argsort(cam[:, 0])] + d = time_offset(cam[:, 0], cam[:, 4:7], rear[:, 0], rear[:, 4:7]) + print(f"the rear IMU lags the OAK-D IMU by {1e3 * d:.1f} ms: delay_s: {d:.4f}") + return 0 + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--recording", help="check a recording instead of the live IMU") + ap.add_argument("--config", default="config.yaml") + ap.add_argument("--poll-hz", type=float, default=100.0) + args = ap.parse_args() + return recording(args) if args.recording else live(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/cluster/autodrive_job.sh b/scripts/cluster/autodrive_job.sh new file mode 100755 index 0000000..7e88f59 --- /dev/null +++ b/scripts/cluster/autodrive_job.sh @@ -0,0 +1,138 @@ +#!/bin/bash +#SBATCH --job-name=ad_race +#SBATCH --account=aip-mtaylor3 +#SBATCH --gres=gpu:l40s:1 +#SBATCH --cpus-per-task=12 +#SBATCH --mem=48G +#SBATCH --time=1:40:00 +#SBATCH --exclude=rack13-08 +#SBATCH --output=/scratch/dandebru/pilot_core/logs/%x_%j.out +# AutoDRIVE sim on a Slurm GPU node, no Docker or supervisor: Xvfb, the sim in a +# relaunch loop, the display tools from scripts/cluster/bin. Runs STAGES from this file. +# sbatch [--export=ALL,STAGES="map race"] scripts/cluster/autodrive_job.sh +# Each job in its own network namespace (its own loopback: the sim always connects to :4567) +# and its own sim settings and log, so several jobs can share a node. +if [ -z "${AD_IN_NETNS:-}" ] && unshare -rn true 2>/dev/null; then + exec unshare -rn env AD_IN_NETNS=1 bash -c 'ip link set lo up && exec bash "$0" "$@"' "$0" "$@" +fi +BASE=${AD_BASE:-/scratch/dandebru/pilot_core} +cd "$BASE/repo" || exit 1 +export AUTODRIVE_ROOT=$BASE/root/job_${SLURM_JOB_ID:-local} +export AUTODRIVE_LOG_DIR=$AUTODRIVE_ROOT/logs +mkdir -p "$AUTODRIVE_ROOT/autodrive_sim" "$AUTODRIVE_LOG_DIR" runs +for v in compete practice; do ln -sfn "$BASE/sim/$v" "$AUTODRIVE_ROOT/autodrive_sim/$v"; done +export PATH=$BASE/repo/scripts/cluster/bin:$BASE/venv/bin:/cvmfs/soft.computecanada.ca/gentoo/2023/x86-64-v3/usr/bin:$PATH +export DISPLAY=:$((100 + ${SLURM_JOB_ID:-0} % 800)) OMP_NUM_THREADS=2 +TAG=${TAG:-$(date +%m%d)} +mkdir -p "runs/$TAG"; : > "$AUTODRIVE_LOG_DIR/autodrive_sim.log" +[ -f "$AUTODRIVE_ROOT/autodrive_sim/sim.env" ] || echo SIM_VARIANT=compete > "$AUTODRIVE_ROOT/autodrive_sim/sim.env" + +Xvfb "$DISPLAY" -screen 0 1280x720x24 +extension GLX +render -noreset & XP=$! +sleep 3 +STOP=/tmp/ad_stop_${SLURM_JOB_ID:-0} +( while [ ! -e "$STOP" ]; do bash scripts/supervisor/autodrive_sim.sh >> "$AUTODRIVE_LOG_DIR/autodrive_sim.log" 2>&1; sleep 1; done ) & +trap 'touch "$STOP"; pkill -f "AutoDRIVE Simulator.x86_64"; kill $XP' EXIT + +variant() { # switch build (restarts the sim) and wait for it + timeout -k 10 300 python - "$1" <<'PY' +import sys +sys.path.insert(0, "scripts") +import autodrive_bench as b +b.ensure_sim_variant(sys.argv[1]) +PY +} +wait_sim() { # give up rather than sit out the job's time limit + local t=0 + until grep -q UnloadTime "$AUTODRIVE_LOG_DIR/autodrive_sim.log"; do + sleep 2; t=$((t + 2)) + [ $t -ge 180 ] && { echo "sim not up after ${t} s"; tail -5 "$AUTODRIVE_LOG_DIR/autodrive_sim.log"; exit 1; } + done + timeout -k 10 120 python -c "import sys; sys.path.insert(0, 'scripts'); import autodrive_sim_ctl as c; c.wait_scene()" || exit 1 +} +ultra() { python scripts/autodrive_sim_ctl.py menu; sleep 1; python scripts/autodrive_sim_ctl.py quality; sleep 2 + python scripts/autodrive_sim_ctl.py quality; sleep 3; python scripts/autodrive_sim_ctl.py close-menu; } +bench() { # name, args + local n=$1; shift + timeout -k 20 700 python scripts/autodrive_bench.py run --out "runs/$TAG/$n" "$@" > "runs/$TAG/$n.json" 2>&1 + echo "== $n rc=$? $(tr -d ' \n' < "runs/$TAG/$n.json" | cut -c1-400)" +} +wait_sim +import -window root "runs/$TAG/start.png" || echo "no screenshot" + +for stage in ${STAGES:-map race}; do + case $stage in + map) # segmentation mapping lap on the compete build, then the racing line + variant compete + bench map --laps 1 --timeout 400 --set enable_slam=true --set use_saved_map=false \ + --set mapping.boundary_save_path=maps/autodrive_compete_seg + python scripts/make_raceline.py maps/autodrive_compete_seg --margin 0.5 || exit 1 ;; + sweep) # mapping-lap settings, first to close a lap without a hit wins: a hit respawns + # the car and the wall map is scribbled over around that corner + variant compete + D=track_control.mapping_drive; M=maps/autodrive_compete_seg; n=0; found= + for v in "$D.wall_margin=0.6 $D.wall_gain=1.5 seg_scan.memory_s=3" \ + "$D.wall_margin=0.6 $D.wall_gain=1.5 $D.bubble=0.6 seg_scan.memory_s=3" \ + "$D.wall_margin=0.7 $D.wall_gain=2.5 $D.speed=0.5 $D.min_speed=0.3 seg_scan.memory_s=4" \ + "$D.wall_margin=0.7 $D.wall_gain=2.5 $D.bubble=0.65 $D.speed=0.5 $D.min_speed=0.3 seg_scan.memory_s=4" \ + "$D.wall_margin=0.8 $D.wall_gain=3 $D.bubble=0.7 $D.speed=0.4 $D.min_speed=0.3 seg_scan.memory_s=5"; do + n=$((n + 1)); rm -rf "$M.try"; sets= + for kv in $v; do sets="$sets --set $kv"; done + echo "-- sweep$n $v" + bench sweep$n --laps 1 --timeout 200 --set enable_slam=true --set use_saved_map=false \ + --set mapping.boundary_save_path=$M.try $sets + hits=$(python -c "import json; print(json.load(open('runs/$TAG/sweep$n.json')).get('collisions', -1))" 2>/dev/null) + if [ "$hits" = 0 ] && [ -f "$M.try/outer_line.npy" ]; then found=$n; break; fi + done + [ -n "$found" ] || { echo "no clean mapping lap"; exit 1; } + rm -rf "$M"; mv "$M.try" "$M"; echo "sweep: variant $found" + python scripts/make_raceline.py "$M" --margin 0.5 || exit 1 ;; + segmap) # map from recorded laps ($SEG_RUNS, recording dirs), hits or not; stops if the line + # it gives runs near a wall. The LiDAR map is only a reference in its report + timeout -k 10 900 python scripts/seg_map.py $SEG_RUNS --out maps/autodrive_compete_seg \ + --reference maps/autodrive_compete || exit 1 + timeout -k 10 1200 python scripts/make_raceline.py maps/autodrive_compete_seg --margin ${MARGIN:-0.65} \ + | tee "runs/$TAG/raceline.txt" || exit 1 + python - "runs/$TAG/raceline.txt" <<'PY' || { echo "racing line too close to a wall"; exit 1; } +import re, sys +c = float(re.search(r"closest wall ([0-9.]+)", open(sys.argv[1]).read()).group(1)) +print("closest wall", c) +sys.exit(c < 0.3) +PY + ;; + race) # the final, as the config stands, 3 runs + variant compete + for i in 1 2 3; do bench race$i --config config_autodrive_compete.yaml --laps 10 --timeout 420; done ;; + start) # as the competition container starts: sim restarted, auto_arm, no keys + variant compete + bench compstart --config config_autodrive_compete.yaml --competition-start --laps 10 --timeout 420 ;; + ultra) + variant compete; ultra + bench ultra --config config_autodrive_compete.yaml --laps 10 --timeout 420 ;; + live) # in-loop mapping lap on the occupancy walls, then 10 laps on that map, for each of + # $REPS (default 1 2 3) on $VARIANT (practice | compete): maps/autodrive__live + V=${VARIANT:-compete}; variant "$V" + for i in ${REPS:-1 2 3}; do + M=maps/autodrive_${V}_live$i; rm -rf "$M" + bench map_$i --config config_autodrive_compete.yaml --laps 1 --timeout 600 \ + --set enable_slam=true --set use_saved_map=false --set mapping.boundary_save_path=$M \ + --set track_control.raceline_path=null + [ -f "$M/outer_line.npy" ] || { echo "map_$i: no map"; continue; } + timeout -k 10 1200 python scripts/make_raceline.py "$M" --margin ${MARGIN:-0.65} \ + | tee "runs/$TAG/raceline_$i.txt" || continue + bench race_$i --config config_autodrive_compete.yaml --laps 10 --timeout 420 \ + --set saved_map_path=$M --set track_control.raceline_path=$M/raceline.npy + done ;; + degraded) # the final on the saved map with the pose degraded like SLAM's, for each of $REPS; + # $DEGRADE_SETS (space-separated key=value) overrides parts of the degradation + variant compete + extra=; for kv in ${DEGRADE_SETS:-}; do extra="$extra --set sim_pose_degrade.$kv"; done + for i in ${REPS:-1 2 3}; do bench degraded$i --config config_autodrive_compete.yaml --laps 10 --timeout 420 \ + --set sim_pose_degrade.enabled=true --set sim_pose_degrade.seed=$i $extra; done ;; + qual) # qualifier on the practice build's segmentation map + variant practice + bench qual --config config_autodrive_compete.yaml --laps 10 --timeout 420 \ + --set saved_map_path=maps/autodrive_practice_seg \ + --set track_control.raceline_path=maps/autodrive_practice_seg/raceline.npy ;; + esac +done +echo JOB_DONE diff --git a/scripts/cluster/bin/supervisorctl b/scripts/cluster/bin/supervisorctl new file mode 100755 index 0000000..bea3693 --- /dev/null +++ b/scripts/cluster/bin/supervisorctl @@ -0,0 +1,3 @@ +#!/bin/bash +# "supervisorctl restart autodrive_sim" for a batch job: the job's loop relaunches the sim +pkill -f "AutoDRIVE Simulator.x86_64" diff --git a/scripts/cluster/bin/xdotool b/scripts/cluster/bin/xdotool new file mode 100755 index 0000000..415c34b --- /dev/null +++ b/scripts/cluster/bin/xdotool @@ -0,0 +1,41 @@ +#!/usr/bin/env python3 +"""The xdotool subset autodrive_sim_ctl.py / autodrive_capture.py use, on python-xlib, for +machines without xdotool (the Alliance clusters).""" +import os +import sys + +from Xlib import X, display +from Xlib.ext import xtest + +d = display.Display(os.environ.get("DISPLAY", ":99")) +root = d.screen().root + + +def windows(w): + yield w + for c in w.query_tree().children: + yield from windows(c) + + +a = sys.argv[1:] +if a[:2] == ["search", "--class"]: + for w in windows(root): + try: + cls = w.get_wm_class() + except Exception: + cls = None + if cls and any(a[2].lower() in c.lower() for c in cls): + print(w.id) +elif a[0] == "getdisplaygeometry": + print(d.screen().width_in_pixels, d.screen().height_in_pixels) +elif a[0] == "windowactivate": + d.create_resource_object("window", int(a[-1])).set_input_focus(X.RevertToParent, X.CurrentTime) + d.sync() +elif a[0] == "mousemove": + root.warp_pointer(int(a[1]), int(a[2])) + d.sync() +elif a[0] in ("mousedown", "mouseup"): + xtest.fake_input(d, X.ButtonPress if a[0] == "mousedown" else X.ButtonRelease, int(a[1])) + d.sync() +else: + sys.exit(f"xdotool shim: unsupported {a}") diff --git a/scripts/cluster/bin/xwininfo b/scripts/cluster/bin/xwininfo new file mode 100755 index 0000000..98d6fb0 --- /dev/null +++ b/scripts/cluster/bin/xwininfo @@ -0,0 +1,13 @@ +#!/usr/bin/env python3 +"""xwininfo -id : the geometry lines autodrive_sim_ctl.py parses (python-xlib).""" +import os +import sys + +from Xlib import display + +d = display.Display(os.environ.get("DISPLAY", ":99")) +w = d.create_resource_object("window", int(sys.argv[2], 0)) +g = w.get_geometry() +p = w.translate_coords(d.screen().root, 0, 0) +print(f" Absolute upper-left X: {-p.x}\n Absolute upper-left Y: {-p.y}\n" + f" Width: {g.width}\n Height: {g.height}") diff --git a/scripts/deploy_ref.sh b/scripts/deploy_ref.sh new file mode 100644 index 0000000..5b570fc --- /dev/null +++ b/scripts/deploy_ref.sh @@ -0,0 +1,36 @@ +# Sourced by jetson_run.sh and start.sh: check out what the car runs. +# PILOT_REF= that ref +# otherwise the newest car-v* release tag, or main fast-forwarded if there is none +# Submodules follow the commits that ref pins. Refuses to run with uncommitted changes. +update_repo() { + if ! git diff --quiet --ignore-submodules || ! git diff --cached --quiet --ignore-submodules; then + echo "Error: pilot_core has uncommitted changes; commit or stash them first." >&2 + exit 1 + fi + git fetch --quiet --tags origin + local ref="${PILOT_REF:-$(git tag -l 'car-v*' --sort=-v:refname | head -n 1)}" + if [ -n "$ref" ]; then + git checkout --quiet --detach "$ref" + else + git checkout --quiet main + git pull --quiet --ff-only + ref=main + fi + git submodule sync --quiet + git submodule update --init --recursive + echo "pilot_core at $ref ($(git rev-parse --short HEAD)); submodules:" + git submodule status +} + +# start.py's --config from the arguments, else config.yaml +config_from_args() { + local cfg="" i + local -a a=("$@") + for ((i = 0; i < ${#a[@]}; i++)); do + case "${a[$i]}" in + --config) cfg="${a[$((i + 1))]:-}" ;; + --config=*) cfg="${a[$i]#--config=}" ;; + esac + done + echo "${cfg:-config.yaml}" +} diff --git a/scripts/gen_orbslam_settings.py b/scripts/gen_orbslam_settings.py index b4c73eb..3e644ee 100755 --- a/scripts/gen_orbslam_settings.py +++ b/scripts/gen_orbslam_settings.py @@ -6,6 +6,15 @@ python scripts/gen_orbslam_settings.py # uses config.yaml python scripts/gen_orbslam_settings.py --config config_cpu.yaml python scripts/gen_orbslam_settings.py -o my_settings.yaml + python scripts/gen_orbslam_settings.py --imu # + IMU block (slam.inertial) + +--imu adds ORB-SLAM3's IMU block: the CAM_A -> IMU transform from the factory calibration, +the IMU rate (camera.imu_rate_hz, default 100) and noise densities. The noise values are +starting points (ORB-SLAM3's RealSense D435i example), not measured for this IMU; an Allan +variance run on a still camera gives the real ones. With the camera level and still, the +script also checks the transform against gravity. Some OAK-Ds have no IMU calibration in +their EEPROM (getCameraToImuExtrinsics raises, or the stored rotation is zeros): give the +transform with --imu-extrinsics, a YAML/JSON file holding the 4x4 matrix as a list of rows. """ from __future__ import annotations @@ -84,6 +93,89 @@ Viewer.ViewpointF: 500.0 """ +IMU_TEMPLATE = """ +#-------------------------------------------------------------------------------------------- +# IMU (slam.inertial: ORB-SLAM3 IMU_RGBD on the OAK-D's own IMU, {imu_type}) +#-------------------------------------------------------------------------------------------- +# camera (CAM_A) -> IMU body frame, p_b = T_b_c1 p_c; from the factory calibration +IMU.T_b_c1: !!opencv-matrix + rows: 4 + cols: 4 + dt: f + data: [{T}] + +IMU.InsertKFsWhenLost: 1 # keyframes at the IMU-predicted pose while lost (fork: bridges featureless stretches) + +# starting points (ORB-SLAM3's D435i example), not measured for this IMU +IMU.NoiseGyro: {noise_gyro:g} # rad/s^0.5 +IMU.NoiseAcc: {noise_acc:g} # m/s^1.5 +IMU.GyroWalk: {gyro_walk:g} # rad/s^1.5 +IMU.AccWalk: {acc_walk:g} # m/s^2.5 +IMU.Frequency: {rate:.1f} +""" + + +def gravity_check(dai, R_b_c, seconds: float = 1.0) -> None: + """With the camera level and still, the accelerometer's reaction to gravity, taken into + the camera frame, should point up (-Y, image rows grow downwards). A large angle means + T_b_c1 is wrong or inverted (or the camera is not level).""" + import time + + import numpy as np + + with dai.Pipeline() as pipeline: + imu = pipeline.create(dai.node.IMU) + imu.enableIMUSensor([dai.IMUSensor.ACCELEROMETER], 100) + imu.setBatchReportThreshold(1) + imu.setMaxBatchReports(10) + q = imu.out.createOutputQueue(maxSize=50, blocking=False) + pipeline.start() + acc = [] + t_end = time.monotonic() + seconds + while time.monotonic() < t_end: + for data in q.tryGetAll(): + acc.extend([p.acceleroMeter.x, p.acceleroMeter.y, p.acceleroMeter.z] for p in data.packets) + time.sleep(0.01) + pipeline.stop() + if not acc: + print("gravity check: no IMU samples", file=sys.stderr) + return + a_b = np.mean(np.array(acc), axis=0) + a_c = np.asarray(R_b_c).T @ a_b + up_c = np.array([0.0, -1.0, 0.0]) + ang = float(np.degrees(np.arccos(np.clip(a_c @ up_c / np.linalg.norm(a_c), -1.0, 1.0)))) + print(f"gravity check: |a| {np.linalg.norm(a_b):.2f} m/s^2, angle to camera up {ang:.1f} deg " + f"({len(acc)} samples)") + if ang > 25.0: + print("warning: more than 25 deg off. If the camera was level and still, T_b_c1 is wrong " + "(inverted?)", file=sys.stderr) + + +def imu_extrinsics(dai, calib, path: str | None): + """T_b_c1 (4x4 rows) from --imu-extrinsics or the device calibration; None (after an + explanation) when neither gives a rigid transform.""" + import numpy as np + + if path: + with open(path) as f: + T = np.asarray(yaml.safe_load(f), dtype=np.float64) + src = path + else: + try: + T = np.asarray(calib.getCameraToImuExtrinsics(dai.CameraBoardSocket.CAM_A, False, + dai.LengthUnit.METER), dtype=np.float64) + except RuntimeError as e: + print(f"this OAK-D's calibration has no IMU extrinsics ({e}): measure or look up the " + "CAM_A -> IMU transform and pass it with --imu-extrinsics", file=sys.stderr) + return None + src = "the device calibration" + R = T[:3, :3] if T.shape == (4, 4) else None + if R is None or not np.allclose(R @ R.T, np.eye(3), atol=1e-3) or abs(np.linalg.det(R) - 1.0) > 1e-3: + print(f"the CAM_A -> IMU transform from {src} is not a rigid transform:\n{T}\n" + "(an uncalibrated IMU stores zeros): pass a valid one with --imu-extrinsics", file=sys.stderr) + return None + return T.tolist() + def live_intrinsics(dai, width: int, height: int, fps: float): """(K, source, device_id, calib) for CAM_A's output as CameraWorker requests it.""" @@ -111,6 +203,16 @@ def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--config", default="config.yaml", help="pilot_core config to read resolution/fps from") parser.add_argument("-o", "--output", default="orbslam_oakd_rgbd.yaml", help="output settings file") + parser.add_argument("--imu", action="store_true", help="add the IMU block for slam.inertial") + parser.add_argument("--noise-gyro", type=float, default=1e-2) + parser.add_argument("--noise-acc", type=float, default=1e-1) + parser.add_argument("--gyro-walk", type=float, default=1e-6) + parser.add_argument("--acc-walk", type=float, default=1e-4) + parser.add_argument("--imu-extrinsics", + help="file with the 4x4 CAM_A -> IMU transform (p_imu = T p_cam, metres), rows; " + "instead of the device calibration") + parser.add_argument("--no-gravity-check", action="store_true", + help="skip the check of T_b_c1 against gravity (needs the camera level and still)") args = parser.parse_args() try: @@ -135,12 +237,30 @@ def main() -> int: # left/right stereo baseline, cm -> m baseline = abs(calib.getBaselineDistance(dai.CameraBoardSocket.CAM_B, dai.CameraBoardSocket.CAM_C)) / 100.0 + text = TEMPLATE.format( + device_id=device_id, width=width, height=height, fps=fps, source=source, + fx=K[0][0], fy=K[1][1], cx=K[0][2], cy=K[1][2], baseline=baseline, + ) + if args.imu: + T = imu_extrinsics(dai, calib, args.imu_extrinsics) + if T is None: + return 1 + rate = float(cfg.get("camera", {}).get("imu_rate_hz", 100)) + with dai.Device() as device: + imu_type = str(device.getConnectedIMU()) + text += IMU_TEMPLATE.format( + imu_type=imu_type, T=", ".join(f"{v:.6f}" for row in T for v in row), rate=rate, + noise_gyro=args.noise_gyro, noise_acc=args.noise_acc, + gyro_walk=args.gyro_walk, acc_walk=args.acc_walk, + ) + print(f"IMU {imu_type} at {rate:g} Hz, T_b_c1 translation " + f"{[round(T[i][3], 4) for i in range(3)]} m") + if not args.no_gravity_check: + gravity_check(dai, [row[:3] for row in T[:3]]) + out_path = os.path.join(REPO_ROOT, args.output) with open(out_path, "w") as f: - f.write(TEMPLATE.format( - device_id=device_id, width=width, height=height, fps=fps, source=source, - fx=K[0][0], fy=K[1][1], cx=K[0][2], cy=K[1][2], baseline=baseline, - )) + f.write(text) print(f"Wrote {out_path} (fx={K[0][0]:.1f} fy={K[1][1]:.1f} cx={K[0][2]:.1f} cy={K[1][2]:.1f}, b={baseline:.3f} m)") return 0 diff --git a/scripts/jetson_run.sh b/scripts/jetson_run.sh index 926ded8..32b7a99 100755 --- a/scripts/jetson_run.sh +++ b/scripts/jetson_run.sh @@ -1,7 +1,9 @@ #!/usr/bin/env bash -# Native (no Docker) Jetson run: max perf, ff-pull + pinned submodules, then start.py. -# Refuses to run with uncommitted changes. +# Native (no Docker) Jetson run: max perf, the release tag + pinned submodules, the +# self-test, then start.py. Refuses to run with uncommitted changes. # scripts/jetson_run.sh [start.py args] # config.yaml unless --config is given +# PILOT_REF= scripts/jetson_run.sh # another tag, branch or commit +# SKIP_SELFTEST=1 scripts/jetson_run.sh # skip scripts/jetson_selftest.py set -euo pipefail cd "$(dirname "$0")/.." @@ -10,18 +12,10 @@ echo "Setting performance mode..." sudo nvpmodel -m 0 sudo jetson_clocks -# pilot_core -> latest commit of the current branch (fast-forward only) -if ! git diff --quiet --ignore-submodules || ! git diff --cached --quiet --ignore-submodules; then - echo "Error: pilot_core has uncommitted changes; commit or stash them first." >&2 - exit 1 -fi -git pull --ff-only - -# submodules -> pinned commits; the car needs all of them, ORB_SLAM3 included -git submodule sync --quiet -git submodule update --init --recursive -echo "All repositories are up to date." -git submodule status +# pilot_core at the release tag (or PILOT_REF), submodules at its pinned commits +# shellcheck source=deploy_ref.sh +source scripts/deploy_ref.sh +update_repo # Python environment (docs/slam.md, README quick start) if [ ! -f .venv/bin/activate ]; then @@ -33,13 +27,16 @@ source .venv/bin/activate # config.yaml unless the caller passes --config args=("$@") -has_config=0 -for a in "${args[@]}"; do - case "$a" in --config|--config=*) has_config=1 ;; esac -done -[ "$has_config" -eq 1 ] || args=(--config config.yaml "${args[@]}") +CONFIG_FILE=$(config_from_args "${args[@]}") +case " ${args[*]} " in *" --config"*) ;; *) args=(--config "$CONFIG_FILE" "${args[@]}") ;; esac -# sudo for I2C/USB; -E keeps LD_LIBRARY_PATH, and the venv's python is used explicitly +# root for I2C and USB. sudo drops LD_LIBRARY_PATH; the bindings find ORB-SLAM3 by their RPATH +PY="$(command -v python)" +if [ "${SKIP_SELFTEST:-0}" != 1 ]; then + sudo "$PY" scripts/jetson_selftest.py --config "$CONFIG_FILE" || { + echo "Self-test failed; fix it or run with SKIP_SELFTEST=1." >&2 + exit 1 + } +fi echo "Starting Pilot..." -export LD_LIBRARY_PATH="$PWD/ORB_SLAM3/lib:/usr/local/lib:${LD_LIBRARY_PATH:-}" -exec sudo -E "$(command -v python)" start.py "${args[@]}" +exec sudo "$PY" start.py "${args[@]}" diff --git a/scripts/jetson_selftest.py b/scripts/jetson_selftest.py new file mode 100644 index 0000000..70eaf82 --- /dev/null +++ b/scripts/jetson_selftest.py @@ -0,0 +1,178 @@ +#!/usr/bin/env python3 +"""Checks a machine before start.py drives the car: Jetson platform and power mode, CUDA, the +shared-memory room, the ring buffers, the ORB-SLAM3 bindings, the OAK-D on USB 3 and the +Arduino on I2C. Each check prints PASS, FAIL or SKIP; the exit code is 1 if any check failed. + + python scripts/jetson_selftest.py # every check + python scripts/jetson_selftest.py --skip camera,i2c # bench without the car's hardware + python scripts/jetson_selftest.py --config config.yaml # I2C address / bus from the config +""" + +from __future__ import annotations + +import argparse +import os +import shutil +import subprocess +import sys +import uuid + +REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, REPO_ROOT) + +MIN_SHM_MB = 512 + + +class Skip(Exception): + pass + + +def check_platform(cfg: dict) -> str: + release = "/etc/nv_tegra_release" + if not os.path.exists(release): + raise Skip("not a Jetson (no /etc/nv_tegra_release)") + with open(release) as f: + line = f.readline().strip() + if shutil.which("nvpmodel"): + mode = subprocess.run(["nvpmodel", "-q"], capture_output=True, text=True, timeout=10).stdout.strip() + mode = mode.splitlines()[0] if mode else "unknown" + else: + mode = "nvpmodel not found" + return f"{line.split(',')[0]}; power mode: {mode}" + + +def check_cuda(cfg: dict) -> str: + providers = [] + try: + import onnxruntime as ort + + providers = ort.get_available_providers() + except ImportError: + pass + gpu = [p for p in providers if p in ("CUDAExecutionProvider", "TensorrtExecutionProvider")] + devices = [d for d in ("/dev/nvhost-ctrl-gpu", "/dev/nvidia0") if os.path.exists(d)] + if not devices: + raise AssertionError("no GPU device node (/dev/nvhost-ctrl-gpu or /dev/nvidia0)") + return f"GPU {devices[0]}; onnxruntime GPU providers: {', '.join(gpu) or 'none (CPU inference)'}" + + +def check_shm(cfg: dict) -> str: + st = os.statvfs("/dev/shm") + mb = st.f_bavail * st.f_frsize / 2**20 + if mb < MIN_SHM_MB: + raise AssertionError(f"/dev/shm has {mb:.0f} MB free, need {MIN_SHM_MB} (Docker: --ipc=host)") + return f"/dev/shm {mb:.0f} MB free" + + +def check_buffers(cfg: dict) -> str: + import numpy as np + + from shared_buffer import FrameBuffer + + name = f"selftest_{uuid.uuid4().hex[:8]}" + buf = FrameBuffer(slots=4, name=name, create=True) + try: + rgb = np.random.default_rng(0).integers(0, 255, (400, 640, 3), dtype=np.uint8) + depth = np.full((400, 640), 1.5, np.float32) + buf.write(rgb, depth, ts=1.0) + header, rgb2, depth2 = buf.read_latest() + if not (np.array_equal(rgb, rgb2) and np.array_equal(depth, depth2) and header.produced_ts == 1.0): + raise AssertionError("ring buffer round trip changed the frame") + finally: + buf.unlink() + return "640x400 RGB-D frame round trip" + + +def check_slam(cfg: dict) -> str: + try: + import orbslam3_python + + del orbslam3_python + except ImportError as e: + raise AssertionError(f"orbslam3_python does not import ({e}); build it (docs/slam.md)") + vocab = os.path.join(REPO_ROOT, "ORB_SLAM3", "Vocabulary", "ORBvoc.txt") + if not os.path.exists(vocab): + raise AssertionError(f"{vocab} missing (tar xf ORBvoc.txt.tar.gz)") + return "orbslam3_python imports; vocabulary present" + + +def check_camera(cfg: dict) -> str: + try: + import depthai as dai + except ImportError: + raise AssertionError("depthai not installed") + devices = dai.Device.getAllAvailableDevices() + if not devices: + raise AssertionError("no OAK-D found") + with dai.Device() as device: + speed = device.getUsbSpeed() + name = device.getDeviceName() + if speed not in (dai.UsbSpeed.SUPER, dai.UsbSpeed.SUPER_PLUS): + raise AssertionError(f"{name} on {speed.name}: 30 fps RGB-D needs USB 3 (docs/oakd.md)") + return f"{name} on {speed.name}" + + +def check_i2c(cfg: dict) -> str: + addr = cfg.get("i2c_address", 0x08) + if addr is None: + raise Skip("i2c_address is null in the config") + bus = int(cfg.get("i2c_bus", 1)) + if not os.path.exists(f"/dev/i2c-{bus}"): + raise AssertionError(f"/dev/i2c-{bus} missing") + from smbus2 import SMBus + + if not os.access(f"/dev/i2c-{bus}", os.R_OK | os.W_OK): + raise AssertionError(f"no access to /dev/i2c-{bus} (run as root, or add the user to the i2c group)") + with SMBus(bus) as b: + try: + b.read_byte(int(addr)) + except OSError as e: + raise AssertionError(f"no reply from 0x{int(addr):02x} on /dev/i2c-{bus} ({e})") + return f"Arduino answers at 0x{int(addr):02x} on /dev/i2c-{bus}" + + +CHECKS = { + "platform": check_platform, + "cuda": check_cuda, + "shm": check_shm, + "buffers": check_buffers, + "slam": check_slam, + "camera": check_camera, + "i2c": check_i2c, +} + + +def run(names: list[str], cfg: dict) -> int: + failed = 0 + for name in names: + try: + msg = CHECKS[name](cfg) + print(f"PASS {name:9s} {msg}") + except Skip as e: + print(f"SKIP {name:9s} {e}") + except Exception as e: + failed += 1 + print(f"FAIL {name:9s} {e}") + return 1 if failed else 0 + + +def main() -> None: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--config", default=os.path.join(REPO_ROOT, "config.yaml")) + ap.add_argument("--skip", default="", help=f"comma-separated checks to skip: {', '.join(CHECKS)}") + ap.add_argument("--only", default="", help="comma-separated checks to run") + a = ap.parse_args() + import yaml + + with open(a.config) as f: + cfg = yaml.safe_load(f) or {} + names = [n for n in (a.only.split(",") if a.only else CHECKS) if n] + unknown = [n for n in names + a.skip.split(",") if n and n not in CHECKS] + if unknown: + ap.error(f"unknown check(s): {', '.join(unknown)}") + skip = set(filter(None, a.skip.split(","))) + sys.exit(run([n for n in names if n not in skip], cfg)) + + +if __name__ == "__main__": + main() diff --git a/scripts/make_raceline.py b/scripts/make_raceline.py new file mode 100644 index 0000000..2527b2c --- /dev/null +++ b/scripts/make_raceline.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +"""Minimum-curvature racing line for a saved map (control/raceline.py), for +track_control.raceline_path. Writes /raceline.npy and a preview PNG, and prints the +speed planner's lap-time estimate on the centre-line and on the line. + + python scripts/make_raceline.py maps/autodrive_compete --margin 0.35 +""" + +from __future__ import annotations + +import argparse +import os +import sys + +import numpy as np + +REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, REPO_ROOT) + +from control.raceline import min_curvature_line # noqa: E402 +from control.speed import speed_profile # noqa: E402 +from control.track import TrackModel # noqa: E402 + + +def lap_estimate(track: TrackModel, a_lat: float, accel: float, decel: float, v_max: float) -> tuple: + v = speed_profile(track, v_max, a_lat, accel, decel) + ds = np.diff(np.concatenate([track.s, [track.length]])) + return float((ds / v).sum()), v + + +def main() -> None: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("map_dir", help="directory with outer_line.npy / inner_line.npy") + ap.add_argument("--margin", type=float, default=0.35, help="m kept from either wall") + ap.add_argument("--passes", type=int, default=4) + ap.add_argument("--spacing", type=float, default=0.2) + ap.add_argument("--out", help="default /raceline.npy") + ap.add_argument("--a-lat", type=float, default=10.0, help="m/s^2, for the lap estimate only") + ap.add_argument("--accel", type=float, default=5.0) + ap.add_argument("--decel", type=float, default=5.0) + ap.add_argument("--v-max", type=float, default=12.0) + args = ap.parse_args() + + outer = np.load(os.path.join(args.map_dir, "outer_line.npy")) + inner = np.load(os.path.join(args.map_dir, "inner_line.npy")) + centre = TrackModel(outer, inner) + line = min_curvature_line(centre, outer, inner, margin=args.margin, spacing=args.spacing, + passes=args.passes) + raced = TrackModel(outer, inner) + raced.set_path(line) + out = args.out or os.path.join(args.map_dir, "raceline.npy") + np.save(out, line) + + est = (args.a_lat, args.accel, args.decel, args.v_max) + t_c, _ = lap_estimate(centre, *est) + t_r, v_r = lap_estimate(raced, *est) + print(f"centre-line {centre.length:.1f} m, max |kappa| {np.abs(centre.curvature).max():.2f} 1/m, est {t_c:.2f} s") + print(f"racing line {raced.length:.1f} m, max |kappa| {np.abs(raced.curvature).max():.2f} 1/m, est {t_r:.2f} s, " + f"closest wall {raced.half_width.min():.2f} m") + print(f"wrote {out}") + + import matplotlib + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + fig, ax = plt.subplots(figsize=(7, 9)) + for b in (outer, inner): + ax.plot(b[:, 0], b[:, 1], "k-", lw=1) + ax.plot(centre.points[:, 0], centre.points[:, 1], "b--", lw=0.8, label="centre-line") + sc = ax.scatter(raced.points[:, 0], raced.points[:, 1], c=v_r, s=3, cmap="viridis") + fig.colorbar(sc, ax=ax, label="planned speed (m/s)") + ax.set_aspect("equal") + ax.legend(loc="upper right") + ax.set_title(f"{os.path.basename(os.path.normpath(args.map_dir))}: margin {args.margin} m") + png = os.path.splitext(out)[0] + ".png" + fig.savefig(png, dpi=90, bbox_inches="tight") + print(f"wrote {png}") + + +if __name__ == "__main__": + main() diff --git a/scripts/render_hud.py b/scripts/render_hud.py index 2860986..b48798e 100644 --- a/scripts/render_hud.py +++ b/scripts/render_hud.py @@ -9,8 +9,9 @@ sim view screen.mp4 (sim chase camera); the depth image when the run has no video car camera camera/rgb_*.png with the VisionWorker mask (segmentation/seg_*.png) - map LiDAR wall points accumulated so far, the pose trail coloured by speed, - the current scan, the car, and the extracted boundary once the loop closes + map wall points accumulated so far (point-cloud mapping), the pose trail coloured by + speed, the current scan, the car, and the track boundary (extracted once the + loop closes, or the saved map) telemetry speed / steering / throttle gauges (command vs. after the safety supervisor), 10 s strip charts, lap times, collisions and per-buffer data age @@ -362,7 +363,8 @@ def _map(self, t: float, texts: list) -> np.ndarray: pts = np.round(car_polygon(c, yaw + (np.pi / 2 if m.rot else 0.0)) * 4).astype(np.int32) cv2.fillPoly(img, [pts], (255, 255, 255), cv2.LINE_AA, shift=2) cv2.polylines(img, [pts], True, (0, 0, 0), 1, cv2.LINE_AA, shift=2) - texts.append((12, HEADER + TOP_H + 10, "MAP · LiDAR walls, trail coloured by speed", self.f_label, TEXT)) + source = "mapped from the camera" if self._has_mapping() else "saved map" + texts.append((12, HEADER + TOP_H + 10, f"MAP · {source}, trail coloured by speed", self.f_label, TEXT)) # legend y0 = HEADER + TOP_H + BOT_H - 22 x0 = 12 @@ -506,7 +508,7 @@ def _phase(self, t: float) -> tuple[str, tuple]: if run.t_reset is not None and t < run.t_reset: return "STANDBY", MUTED if self._has_mapping() and _latest(run.boundary["t_mono"], t) < 0: - return "MAPPING LAP · LiDAR follow-the-gap", BOUNDARY + return "MAPPING LAP · follow-the-gap on the camera", BOUNDARY if run.laps and t > run.laps[-1][0]: return "FINISHED", MUTED return f"RACING · {self.ctrl_mode}", SPEED diff --git a/scripts/seg_map.py b/scripts/seg_map.py new file mode 100644 index 0000000..b0b131f --- /dev/null +++ b/scripts/seg_map.py @@ -0,0 +1,156 @@ +#!/usr/bin/env python3 +"""Track map from recorded segmentation masks, no LiDAR: for a mapping lap whose wall hits or +long-range edges spoil MappingWorker's accumulated cloud. Replays each recording's masks +through control/seg_scan.py onto its sim poses and builds an occupancy grid: a ray frees the +floor it crosses and an edge only counts near the car, so an edge placed short from afar +(it gets worse with range, most in dark corners) is cleared by the floor seen up close. The +drivable region is the floor seen free that is connected to the driven path; its outer +contour and its hole are the walls. Works from sim_messages.csv, so a hit's respawn does not matter. + + python scripts/seg_map.py runs/x/map/rec/* --out maps/autodrive_compete_seg --config config_autodrive_compete.yaml +""" + +from __future__ import annotations + +import argparse +import csv +import os +import sys + +import numpy as np +import yaml + +REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, REPO_ROOT) +sys.path.insert(0, os.path.join(REPO_ROOT, "scripts")) + +from control.depth_ftg import Intrinsics # noqa: E402 +from control.lidar_gap import ANGLE_INCREMENT, ANGLE_MIN # noqa: E402 +from control.seg_scan import SegScanConfig, seg_edge_scan # noqa: E402 +from control.occupancy_map import (OccupancyConfig, occupancy, scan_to_samples, signed_area, # noqa: E402 + walls_from_grid) +from control.track import TrackModel, _resample_closed, _smooth_closed # noqa: E402 +from read_recording import _decoder, iter_file, list_files # noqa: E402 + +def load_poses(rec: str) -> dict: + with open(os.path.join(rec, "sim_messages.csv")) as f: + rows = list(csv.DictReader(f)) + p = {k: np.array([float(r[k]) for r in rows]) for k in ("t_rx", "x", "y", "yaw", "collisions")} + p["yaw"] = np.unwrap(p["yaw"]) + return p + + +def replay(rec: str, poses: dict, K: Intrinsics, cfg: SegScanConfig, scan_x: float, occ: OccupancyConfig) -> np.ndarray: + """(N, 5) [edge x, edge y, range, origin x, origin y], world frame.""" + ang = ANGLE_MIN + np.arange(1080) * ANGLE_INCREMENT + t = poses["t_rx"] + rf = list_files(rec, "segmentation")[0] + dec = _decoder(rf) + hits = t[np.flatnonzero(np.diff(poses["collisions"]) > 0)] + out, last = [], None + for r in iter_file(rf, decode=False): + i = min(int(np.searchsorted(t, r.produced_ts)), len(t) - 1) + if abs(t[i] - r.produced_ts) > 0.1: + continue + # a car against a wall, or standing, would repeat one bad view hundreds of times + if np.any((r.produced_ts > hits - occ.drop_before) & (r.produced_ts < hits + occ.drop_after)): + continue + here = np.array([poses["x"][i], poses["y"][i]]) + if last is not None and np.linalg.norm(here - last) < occ.min_move: + continue + last = here + m = dec(r.payload) + m = np.asarray(m[1] if isinstance(m, tuple) else m) + s = seg_edge_scan(m, np.zeros(m.shape, np.float32), K, cfg) + yaw = poses["yaw"][i] + origin = here + scan_x * np.array([np.cos(yaw), np.sin(yaw)]) + out.append(scan_to_samples(s, ang, origin, yaw, occ)) + return np.vstack(out) + + +def main() -> None: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("recordings", nargs="+", help="recording directories") + ap.add_argument("--out", required=True) + ap.add_argument("--config", default="config_autodrive_compete.yaml") + ap.add_argument("--edge-range", type=float, default=2.5, help="m, edges further than this are ignored") + ap.add_argument("--free-range", type=float, default=1.6, help="m of each ray that frees the floor") + ap.add_argument("--ratio", type=float, default=0.35, help="occupied / (occupied + free) of a wall cell") + ap.add_argument("--min-occ", type=float, default=0.6, help="smoothed edge count of a wall cell") + ap.add_argument("--min-free", type=float, default=2.0, help="smoothed ray count of a free cell") + ap.add_argument("--reach", type=float, default=0.9, help="m from the driven path the track can extend") + ap.add_argument("--seal", type=int, default=3, help="cells; wall gaps up to twice this are closed") + ap.add_argument("--reference", help="another map's directory: only reports the distance to its walls") + a = ap.parse_args() + + with open(a.config) as f: + c = yaml.safe_load(f) + s = c["seg_scan"] + cfg = SegScanConfig(camera_pitch=s["camera_pitch"], camera_height=s["camera_height"], + origin_forward=s["origin_forward"]) + settings = c["vision"].get("camera_settings", "sim_camera/orbslam_settings.yaml") + K = Intrinsics.from_orbslam_settings(settings) + scan_x = float(c["mapping"]["scan_offset"][0]) + + occ_cfg = OccupancyConfig(edge_range=a.edge_range, free_range=a.free_range, ratio=a.ratio, min_occ=a.min_occ, + min_free=a.min_free, reach=a.reach, seal=a.seal) + poses, scans = [], [] + for rec in a.recordings: + p = load_poses(rec) + poses.append(p) + scans.append(replay(rec, p, K, cfg, scan_x, occ_cfg)) + scans = np.vstack(scans) + path = np.vstack([np.column_stack([p["x"], p["y"]]) for p in poses]) + + res = occ_cfg.res + x0, y0 = path.min(axis=0) - occ_cfg.pad + w, h = np.ceil((path.max(axis=0) + occ_cfg.pad - [x0, y0]) / res).astype(int) + free, occ = occupancy(scans, x0, y0, (h, w), occ_cfg) + cells = np.unique(((path - [x0, y0]) / res).astype(int), axis=0) + outer, inner, region = walls_from_grid(free, occ, cells, occ_cfg) + + # the lap's direction is the driven path's: the map's files are ordered along it + t = poses[0] + turn = signed_area(np.column_stack([t["x"], t["y"]])[::10]) + lines = [] + for b in (outer, inner): + b = (b + 0.5) * res + [x0, y0] + b = _resample_closed(_smooth_closed(b, occ_cfg.smooth), occ_cfg.spacing) + lines.append(b if signed_area(b) * turn > 0 else b[::-1]) + outer, inner = lines + track = TrackModel(outer, inner) + print(f"{len(a.recordings)} recording(s), {len(scans)} edge samples, outer {len(outer)} pts, inner {len(inner)} pts") + print(f"centre-line {track.length:.1f} m, half-width min {track.half_width.min():.2f} " + f"median {np.median(track.half_width):.2f} m") + os.makedirs(a.out, exist_ok=True) + np.save(os.path.join(a.out, "outer_line.npy"), outer.astype(np.float32)) + np.save(os.path.join(a.out, "inner_line.npy"), inner.astype(np.float32)) + + ref = None + if a.reference: + from scipy.spatial import cKDTree + + ref = [np.load(os.path.join(a.reference, n))[:, :2] for n in ("outer_line.npy", "inner_line.npy")] + for name, line in (("outer", outer), ("inner", inner)): + d = cKDTree(np.vstack(ref)).query(line)[0] + print(f"{name} to the reference walls: median {np.median(d):.2f} p90 {np.percentile(d, 90):.2f} " + f"max {d.max():.2f} m") + + import matplotlib + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + fig, ax = plt.subplots(figsize=(7, 12)) + ax.imshow(region, origin="lower", cmap="Blues", alpha=0.3, extent=(x0, x0 + w * res, y0, y0 + h * res)) + for r in ref or []: + ax.plot(r[:, 0], r[:, 1], "r-", lw=0.5) + for b in (outer, inner): + ax.plot(*np.vstack([b, b[:1]]).T, "k-", lw=1) + ax.plot(*track.points.T, "g--", lw=0.6) + ax.set_aspect("equal") + fig.savefig(os.path.join(a.out, "map.png"), dpi=80, bbox_inches="tight") + print(f"wrote {a.out}") + + +if __name__ == "__main__": + main() diff --git a/scripts/stage_latency.py b/scripts/stage_latency.py new file mode 100644 index 0000000..76eec33 --- /dev/null +++ b/scripts/stage_latency.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""Per-stage rates and latencies of a recorded run (start.py --recording). + +Every record carries the time its sample was produced and the time the recorder read it +(within ~2 ms of the write). Frames, masks and poses are stamped with the camera's capture +time, so for them read - produced is the capture-to-output latency of that stage. For each +actuator command it also reports the age of the newest pose then: how old the vehicle state +behind the command was when it went out. + + python scripts/stage_latency.py /tmp/pilot_recordings/ + python scripts/stage_latency.py --json > latency.json +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys + +import numpy as np + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from read_recording import iter_file, list_files # noqa: E402 + +# buffers stamped with the camera's capture time: their age is the stage's latency +CAPTURE_STAMPED = ("frame", "segmentation", "pose") +ORDER = ("frame", "imu", "segmentation", "pose", "state", "control", "actuation") + + +def _times(rec: str, buffer: str) -> tuple[np.ndarray, np.ndarray]: + produced, read = [], [] + for rf in list_files(rec, buffer): + for r in iter_file(rf, decode=False): + produced.append(r.produced_ts) + read.append(r.read_ts) + return np.asarray(produced), np.asarray(read) + + +def _pct(x: np.ndarray) -> dict: + if len(x) == 0: + return {} + return {"p50_ms": float(np.percentile(x, 50) * 1e3), "p95_ms": float(np.percentile(x, 95) * 1e3), + "max_ms": float(x.max() * 1e3)} + + +def analyse(rec: str) -> dict: + out = {} + present = {rf.buffer for rf in list_files(rec)} + for name in [b for b in ORDER if b in present]: + produced, read = _times(rec, name) + if len(produced) < 2: + continue + span = float(produced[-1] - produced[0]) + row = {"n": int(len(produced)), "rate_hz": float((len(produced) - 1) / span) if span > 0 else 0.0, + "interval": _pct(np.diff(produced))} + if name in CAPTURE_STAMPED: + row["latency"] = _pct(read - produced) + out[name] = row + if "actuation" in present and "pose" in present: + p_prod, p_read = _times(rec, "pose") + a_prod, _ = _times(rec, "actuation") + order = np.argsort(p_read) + p_prod, p_read = p_prod[order], p_read[order] + i = np.searchsorted(p_read, a_prod, side="right") - 1 + ok = i >= 0 + out["pose_age_at_actuation"] = _pct(a_prod[ok] - p_prod[i[ok]]) + return out + + +def table(res: dict) -> str: + lines = ["| stage | samples | rate (Hz) | interval p50 / p95 (ms) | capture to output p50 / p95 / max (ms) |", + "|---|---|---|---|---|"] + for name in ORDER: + r = res.get(name) + if not r: + continue + iv = r["interval"] + lat = r.get("latency") + lat_s = f"{lat['p50_ms']:.1f} / {lat['p95_ms']:.1f} / {lat['max_ms']:.1f}" if lat else "-" + lines.append(f"| {name} | {r['n']} | {r['rate_hz']:.1f} | {iv['p50_ms']:.1f} / {iv['p95_ms']:.1f} | {lat_s} |") + a = res.get("pose_age_at_actuation") + if a: + lines.append("") + lines.append(f"Pose age when a command went out: p50 {a['p50_ms']:.1f} ms, p95 {a['p95_ms']:.1f} ms, " + f"max {a['max_ms']:.1f} ms") + return "\n".join(lines) + + +def main() -> None: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("recording", help="recording directory") + ap.add_argument("--json", action="store_true", help="print JSON instead of a table") + a = ap.parse_args() + res = analyse(a.recording) + print(json.dumps(res, indent=1) if a.json else table(res)) + + +if __name__ == "__main__": + main() diff --git a/scripts/start.sh b/scripts/start.sh index 9528b56..f68dfd3 100755 --- a/scripts/start.sh +++ b/scripts/start.sh @@ -1,14 +1,16 @@ #!/usr/bin/env bash -# Docker deploy on the Jetson: pull, perf mode, OAK-D udev rule, build and run (foreground). +# Docker deploy on the Jetson: the release tag, perf mode, OAK-D udev rule, build, the +# self-test in the container, then run (foreground). # scripts/start.sh # start.py --config config.yaml # scripts/start.sh --config X.yaml [--enable-slam ...] # args are passed to start.py +# PILOT_REF= / SKIP_SELFTEST=1 # as for jetson_run.sh set -euo pipefail cd "$(dirname "$0")/.." -# pilot_core fast-forward, submodules at the commits pilot_core pins -git pull --ff-only -git submodule sync --quiet -git submodule update --init --recursive +# pilot_core at the release tag (or PILOT_REF), submodules at its pinned commits +# shellcheck source=deploy_ref.sh +source scripts/deploy_ref.sh +update_repo # start.py args: config.yaml unless the caller passes --config args=("$@") @@ -57,15 +59,13 @@ echo "" # --privileged: OAK-D over USB; --device: Arduino I2C; --ipc=host: host /dev/shm # for the ring buffers (Docker's default is 64 MB). +RUN_FLAGS=(--runtime nvidia --rm --privileged --net=host --ipc=host --device /dev/i2c-1) +if [ "${SKIP_SELFTEST:-0}" != 1 ]; then + sudo docker run "${RUN_FLAGS[@]}" --entrypoint python3 "$IMAGE_NAME" \ + scripts/jetson_selftest.py --config "$CONFIG_FILE" || { + echo "Self-test failed; fix it or run with SKIP_SELFTEST=1." >&2 + exit 1 + } +fi echo "Started container utasr-container (logs follow; q or Ctrl+C to stop)." -exec sudo docker run \ - --runtime nvidia \ - --rm \ - -it \ - --privileged \ - --net=host \ - --ipc=host \ - --device /dev/i2c-1 \ - --name utasr-container \ - "$IMAGE_NAME" \ - "${args[@]}" +exec sudo docker run "${RUN_FLAGS[@]}" -it --name utasr-container "$IMAGE_NAME" "${args[@]}" diff --git a/scripts/supervisor/autodrive_sim.sh b/scripts/supervisor/autodrive_sim.sh index 819e1ed..fee3430 100755 --- a/scripts/supervisor/autodrive_sim.sh +++ b/scripts/supervisor/autodrive_sim.sh @@ -5,10 +5,11 @@ # shaders only (-force-glcore fails); SIM_VK_ICD picks the Vulkan driver. Mesa lavapipe # (/usr/share/vulkan/icd.d/lvp_icd.json) renders the stock build magenta, so the sim needs # the NVIDIA driver (docs/autodrive.md). +HERE="$(dirname "$(readlink -f "$0")")" # before the cd: $0 may be relative ROOT="${AUTODRIVE_ROOT:-/workspaces}" SIM_VARIANT=practice; SIM_W=640; SIM_H=360; SIM_GFX=vulkan; SIM_ARGS=""; SIM_NICE=0; SIM_VK_ICD="" [ -f "$ROOT/autodrive_sim/sim.env" ] && . "$ROOT/autodrive_sim/sim.env" -export DISPLAY=:99 XDG_RUNTIME_DIR=/tmp/xdg-autodrive +export DISPLAY="${DISPLAY:-:99}" XDG_RUNTIME_DIR=/tmp/xdg-autodrive mkdir -p "$XDG_RUNTIME_DIR" [ -n "$SIM_VK_ICD" ] && export VK_ICD_FILENAMES="$SIM_VK_ICD" until xdpyinfo >/dev/null 2>&1; do sleep 0.5; done @@ -18,4 +19,4 @@ echo "starting $SIM_VARIANT sim at ${SIM_W}x${SIM_H}, gfx=$SIM_GFX ${SIM_VK_ICD: # rate-limits the reconnect storm); stdbuf keeps it line-buffered nice -n "$SIM_NICE" ./"AutoDRIVE Simulator.x86_64" -force-"$SIM_GFX" -screen-fullscreen 0 \ -screen-width "$SIM_W" -screen-height "$SIM_H" $SIM_ARGS -logFile - 2>&1 \ - | python3 -u "$(dirname "$(readlink -f "$0")")/log_filter.py" + | python3 -u "$HERE/log_filter.py" diff --git a/scripts/supervisor/autodrive_xvfb.sh b/scripts/supervisor/autodrive_xvfb.sh index fcc8673..bf4c91a 100755 --- a/scripts/supervisor/autodrive_xvfb.sh +++ b/scripts/supervisor/autodrive_xvfb.sh @@ -1,5 +1,10 @@ #!/bin/bash # Virtual X display for the sim. GLX here is Mesa llvmpipe; the sim renders with -# NVIDIA Vulkan (-force-vulkan) and presents into this display. +# NVIDIA Vulkan (-force-vulkan) and presents into this display. Size from +# $AUTODRIVE_ROOT/autodrive_sim/sim.env (SCREEN_W, SCREEN_H); it must hold the sim window +# (SIM_W x SIM_H) or the HUD buttons autodrive_sim_ctl.py clicks fall off-screen. +ROOT="${AUTODRIVE_ROOT:-/workspaces}" +SCREEN_W=1280; SCREEN_H=720 +[ -f "$ROOT/autodrive_sim/sim.env" ] && . "$ROOT/autodrive_sim/sim.env" rm -f /tmp/.X99-lock -exec Xvfb :99 -screen 0 1280x720x24 +extension GLX +render -noreset +exec Xvfb :99 -screen 0 "${SCREEN_W}x${SCREEN_H}x24" +extension GLX +render -noreset diff --git a/scripts/vio_bench/README.md b/scripts/vio_bench/README.md new file mode 100644 index 0000000..be02503 --- /dev/null +++ b/scripts/vio_bench/README.md @@ -0,0 +1,123 @@ +# RGB-D-inertial benchmark: ORB-SLAM3 (CUDA fork) vs cuVSLAM + +Both systems run offline on the same recorded sequence, in the same `rgbdi` format +([rgbdi.py](rgbdi.py)), and are scored by one script against ground truth. + +| step | script | runs in | +| ---- | ------ | ------- | +| sim run to sequence | `scripts/export_recording.py `, then [sim_to_rgbdi.py](sim_to_rgbdi.py) | pilot_core env | +| sim sequence re-rendered with exact depth (same track, trajectory, IMU) | [render_track.py](render_track.py) | pilot_core env | +| simulated rear-of-car IMU (ICM-20948, DLPF, I2C polling) | [make_rear_imu.py](make_rear_imu.py) | pilot_core env | +| vehicle state from the rear IMU + SLAM (control.ImuEKF vs PoseEKF), causal replay | [fuse_rear_imu.py](fuse_rear_imu.py) | pilot_core env | +| car config for recording (frames + 6-axis IMU, nothing dropped) | [make_record_config.py](make_record_config.py) | pilot_core env | +| car recording to sequence | [car_to_rgbdi.py](car_to_rgbdi.py) | pilot_core env | +| ORB-SLAM3, `IMU_RGBD` (or `RGBD` with `--no-imu`) | [run_orbslam3.py](run_orbslam3.py) | pilot_core env, built `orbslam3_python` | +| cuVSLAM, Multisensor RGB-D + IMU + SLAM (or `RGBD` with `--no-imu`) | [run_cuvslam.py](run_cuvslam.py) | its own venv: the PyCuVSLAM 17.x wheel pins numpy | +| accuracy against ground truth (sim), coverage, latency | [score.py](score.py) | pilot_core env (+ matplotlib) | +| accuracy from AprilTags + lap closure (real track) | [markers.py](markers.py) | pilot_core env | + +```bash +python scripts/autodrive_bench.py run --config config_autodrive_compete.yaml --out runs/vio --laps 3 \ + --set sim_depth.camera=sim_camera/camera.yaml --set sim_depth.scale=2 --set recording_config.frame.sample_k=1 +python scripts/export_recording.py runs/vio +python scripts/vio_bench/sim_to_rgbdi.py runs/vio --out seq/vio +python scripts/vio_bench/run_orbslam3.py seq/vio --out res/orb_imu +ORB_SLAM3_CUDA=0 python scripts/vio_bench/run_orbslam3.py seq/vio --out res/orb_cpu_imu +/venv/cuvslam/bin/python scripts/vio_bench/run_cuvslam.py seq/vio --out res/cuv_imu +python scripts/vio_bench/score.py seq/vio res/* --out res/score +# the same laps rendered with exact depth (and with forced 0.3 s tracking losses) +python scripts/vio_bench/render_track.py seq/vio runs/vio --out seq/vio_render +python scripts/vio_bench/render_track.py seq/vio runs/vio --out seq/vio_blackout --blackout 3.0:0.3 --blackout 9.0:0.3 +``` + +`run_orbslam3.py --upstream-policy` runs upstream ORB-SLAM3's inertial policy (reset the +map on a tracking loss before the IMU is initialised, keyframes by time only) instead of +the fork's depth-inertial one (relocalise, keyframes also when visual tracking weakens). + +Metrics ([score.py](score.py)): ATE after one rigid (no scale) alignment, RPE over 1 s +(translation in m and % of distance, rotation in deg), fraction of frames tracked, time to +the first pose and to IMU initialisation (ORB-SLAM3), and the per-frame tracking call's +latency (mean, p50, p95, p99, max). Latency is the tracking call only: both systems map +and close loops in background threads. + +## Real track (the verdict) + +No motion capture: accuracy comes from AprilTags placed around the track +([markers.py](markers.py)) and from laps that pass them repeatedly. + +**Before the session** + +1. Print 8-12 tag36h11 tags (ids 0..N, any free generator), black square **24 cm or + larger** (A3): a 16 cm tag is only good to ~1.5 cm within 1.5 m of the camera, and + sightings beyond 2.5 m or under 30 px are dropped. Note the printed square edge. +2. Mount them upright on the walls facing the racing line, at camera height (~15-30 cm), + spread round the whole lap, some on straights and some in corners, flat and not + reflective. Never move them during the session. +3. Optional, for absolute accuracy: tape-measure each tag centre in one track frame + (origin on the start line, x along it, y left, z up) into `markers.yaml` (format in + [markers.py](markers.py)); at least 3 tags, not in a line. Without it you still get + lap-to-lap repeatability and closure. +4. Settings with the IMU block at the recording rate, and the recording config: + +```bash +python scripts/gen_orbslam_settings.py --imu # camera level and still: checks T_b_c1 +python scripts/vio_bench/make_record_config.py config.yaml -o config_vio_record.yaml # IMU 200 Hz +``` + +(`make_record_config.py --imu-rate` must match the rate the settings were generated +for: regenerate with `camera.imu_rate_hz` set, or pass `--imu-rate 100`.) + +**Recording** + +5. Car still for ~3 s, then 5+ laps at the speeds you race at (a slow lap first if you + want both), then stop on the start mark (for `--closed`). Over USB 3. + +```bash +python start.py --config config_vio_record.yaml # [q] when done +``` + +**Afterwards** (on the vast.ai box or the Orin; latency on the Orin is the one that counts) + +```bash +python scripts/vio_bench/car_to_rgbdi.py /tmp/pilot_recordings/ --settings orbslam_oakd_rgbd.yaml --out seq/track1 +python scripts/vio_bench/run_orbslam3.py seq/track1 --out res/orb_imu +python scripts/vio_bench/run_orbslam3.py seq/track1 --out res/orb_rgbd --no-imu +/venv/cuvslam/bin/python scripts/vio_bench/run_cuvslam.py seq/track1 --out res/cuv_imu +/venv/cuvslam/bin/python scripts/vio_bench/run_cuvslam.py seq/track1 --out res/cuv_rgbd --no-imu +python scripts/vio_bench/score.py seq/track1 res/* --out res/score # latency, coverage +python scripts/vio_bench/markers.py seq/track1 res/* --survey markers.yaml --closed --out res/markers +``` + +`score.py` has no ground truth here, so it reports coverage and latency only; the +accuracy is in `markers.md`: repeatability (the same tag placed on different laps), its +growth lap by lap, absolute error against the survey, and start/end closure. + +## Sim sequences: what they can and can't show + +- The stock AutoDRIVE build has an untextured floor with camera-fixed glare and black + walls; use the textured copy (`scripts/autodrive_texture_sim.py --variant compete`). +- Depth comes from the 2-D LiDAR (walls extruded, floor plane) through a fitted camera + model. Against ground truth, cuVSLAM's speed comes out ~15 % low with zero time lag and + 0.98 turn-rate correlation: the depth's scale is off, so absolute accuracy in the sim is + pessimistic for both systems. +- The IMU is synthesised from the ground-truth pose (low-passed at 6 Hz, then + differentiated, plus consumer-MEMS noise): no vibration, no real bias behaviour. +- The car-body region of the image is painted flat: it moves with the camera. +- The LiDAR depth and the sim's images do not agree closely: between consecutive frames + only ~35-65 % of ORB matches fit the depth (more for the most distinctive matches), so + a tracker that builds its map from depth (ORB-SLAM3) loses it within a few frames in + every mode, while cuVSLAM, which tracks 2-D features and uses depth for scale, holds + on. [render_track.py](render_track.py) renders the same track and trajectory with a + non-repeating texture and exact depth, keeping the sequence's IMU and ground truth: + that one compares the trackers, not the sim's depth. + +The sim exercises the pipeline and gives comparable latency; the real-track recordings +(markers + lap closure) are the accuracy verdict. + +## Building ORB-SLAM3 on the vast.ai box + +On the AMD EPYC 7713 / Ubuntu 24.04 / gcc 13 box, ORB-SLAM3 built with its default +`-march=native` (ORB_SLAM3, g2o, DBoW2) aborts with "double free or corruption" in +`g2o::HyperGraph::clear` after the first pose optimisation, the C++ `rgbd_tum` example +included. Without `-march=native` in the three CMakeLists it runs. The cause is not +pinned down. diff --git a/scripts/vio_bench/car_to_rgbdi.py b/scripts/vio_bench/car_to_rgbdi.py new file mode 100644 index 0000000..d0b5d6b --- /dev/null +++ b/scripts/vio_bench/car_to_rgbdi.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +"""Car recording (start.py --recording with raw_imu) -> rgbdi sequence (rgbdi.py). + + python scripts/vio_bench/car_to_rgbdi.py --settings orbslam_oakd_rgbd.yaml --out + + holds frame_*.bin (CameraWorker's undistorted RGB + aligned depth) and +raw_imu_*.bin (the OAK-D's accel + gyro), both stamped with the device capture time on +time.monotonic()'s clock. Record with make_record_config.py's config: every frame, no +rotated-out files, the IMU at 200 Hz. The settings file (scripts/gen_orbslam_settings.py +--imu, for the same camera, resolution and IMU rate) gives the intrinsics, IMU.T_b_c1 and +the IMU noise. There is no groundtruth.csv: accuracy comes from AprilTags (markers.py). +""" + +from __future__ import annotations + +import argparse +import os +import sys + +import cv2 +import numpy as np +import yaml + +REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +sys.path.insert(0, REPO_ROOT) +sys.path.insert(0, os.path.join(REPO_ROOT, "scripts")) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import rgbdi # noqa: E402 +from read_recording import iter_records, list_files # noqa: E402 + + +def read_settings(path: str) -> dict: + """Intrinsics, T_b_c1 and the IMU block of an ORB-SLAM3 settings file (File.version 1.0).""" + fs = cv2.FileStorage(path, cv2.FILE_STORAGE_READ) + try: + def num(key): + node = fs.getNode(key) + if node.empty(): + raise SystemExit(f"{path} has no {key}" + (" (generate it with --imu)" if key.startswith("IMU") else "")) + return float(node.real()) + + T = fs.getNode("IMU.T_b_c1").mat() if not fs.getNode("IMU.T_b_c1").empty() else None + if T is None: + raise SystemExit(f"{path} has no IMU.T_b_c1: generate it with scripts/gen_orbslam_settings.py --imu") + return { + "width": int(num("Camera.width")), "height": int(num("Camera.height")), + "fx": num("Camera1.fx"), "fy": num("Camera1.fy"), "cx": num("Camera1.cx"), "cy": num("Camera1.cy"), + "fps": num("Camera.fps"), + "T_imu_cam": np.asarray(T, dtype=np.float64).reshape(4, 4).tolist(), + "imu": {"rate_hz": num("IMU.Frequency"), "noise_gyro": num("IMU.NoiseGyro"), + "noise_acc": num("IMU.NoiseAcc"), "gyro_walk": num("IMU.GyroWalk"), + "acc_walk": num("IMU.AccWalk")}, + } + finally: + fs.release() + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("recording", help="the session directory with frame_*.bin and raw_imu_*.bin") + ap.add_argument("--settings", default=os.path.join(REPO_ROOT, "orbslam_oakd_rgbd.yaml")) + ap.add_argument("--out", required=True) + ap.add_argument("--start", type=float, default=0.0, help="s to skip at the start") + ap.add_argument("--end", type=float, help="s from the start to stop at") + args = ap.parse_args() + + names = {rf.buffer for rf in list_files(args.recording)} + missing = {"frame", "raw_imu"} - names + if missing: + raise SystemExit(f"{args.recording} has no {', '.join(sorted(missing))} recording " + "(record with scripts/vio_bench/make_record_config.py's config)") + calib = read_settings(args.settings) + + imu = np.array([[r.produced_ts, *r.value.tolist()] for r in iter_records(args.recording, "raw_imu")]) + imu = imu[np.argsort(imu[:, 0], kind="stable")] + t0 = imu[0, 0] + + os.makedirs(os.path.join(args.out, "rgb"), exist_ok=True) + os.makedirs(os.path.join(args.out, "depth"), exist_ok=True) + frames, last, dropped = [], None, 0 + for r in iter_records(args.recording, "frame"): + rel = r.produced_ts - t0 + if rel < args.start or (args.end is not None and rel > args.end): + continue + t_ns = int(round(r.produced_ts * 1e9)) + if last is not None and t_ns <= last: + dropped += 1 + continue + last = t_ns + rgb, depth = r.value + if rgb.shape[1] != calib["width"] or rgb.shape[0] != calib["height"]: + raise SystemExit(f"frames are {rgb.shape[1]}x{rgb.shape[0]}, the settings are for " + f"{calib['width']}x{calib['height']}") + a, b = f"rgb/{t_ns}.png", f"depth/{t_ns}.png" + cv2.imwrite(os.path.join(args.out, a), cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)) + d = np.clip(np.nan_to_num(np.asarray(depth, np.float32)) * 1000.0, 0, 65535).astype(np.uint16) + cv2.imwrite(os.path.join(args.out, b), d) + frames.append((t_ns, a, b)) + if not frames: + raise SystemExit("no frames in the selected time range") + + f_t = np.array([f[0] for f in frames]) * 1e-9 + keep = (imu[:, 0] >= f_t[0] - 0.05) & (imu[:, 0] <= f_t[-1] + 0.05) + imu = imu[keep] + gaps = np.diff(imu[:, 0]) + rate = 1.0 / float(np.median(gaps)) + imu_ns = imu.copy() + imu_ns[:, 0] = np.round(imu[:, 0] * 1e9) + with open(os.path.join(args.out, "frames.csv"), "w") as f: + f.write("t_ns,rgb,depth\n") + for t, a, b in frames: + f.write(f"{t},{a},{b}\n") + rgbdi.write_imu(os.path.join(args.out, "imu.csv"), imu_ns) + if "rear_imu" in names: # the rear IMU, in its own axes, host-stamped (check_rear_imu.py) + rear = np.array([[r.produced_ts, *r.value.tolist()] for r in iter_records(args.recording, "rear_imu")]) + rear = rear[np.argsort(rear[:, 0], kind="stable")] + rear = rear[(rear[:, 0] >= f_t[0] - 0.05) & (rear[:, 0] <= f_t[-1] + 0.05)] + rear[:, 0] = np.round(rear[:, 0] * 1e9) + rgbdi.write_imu(os.path.join(args.out, "rear_imu.csv"), rear) + calib.update({"source": f"car recording {os.path.abspath(args.recording)}", + "notes": f"settings {os.path.abspath(args.settings)}"}) + if abs(rate - calib["imu"]["rate_hz"]) > 0.1 * calib["imu"]["rate_hz"]: + print(f"warning: the IMU ran at {rate:.0f} Hz, the settings say {calib['imu']['rate_hz']:.0f} Hz") + with open(os.path.join(args.out, "calib.yaml"), "w") as f: + yaml.safe_dump(calib, f, sort_keys=False) + big = int(np.sum(gaps > 5.0 / rate)) + print(f"{len(frames)} frames ({len(frames) / (f_t[-1] - f_t[0]):.1f} fps), {len(imu)} IMU samples " + f"({rate:.0f} Hz, {big} gaps > 5 samples), {f_t[-1] - f_t[0]:.1f} s" + + (f", {dropped} out-of-order frames dropped" if dropped else "") + f" -> {args.out}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/vio_bench/cpulimit.py b/scripts/vio_bench/cpulimit.py new file mode 100644 index 0000000..5136541 --- /dev/null +++ b/scripts/vio_bench/cpulimit.py @@ -0,0 +1,45 @@ +"""CPU budget for the benchmark runners: import before cv2 / numpy / the SLAM modules. + +Containers often report every host core (nproc 255 on the vast.ai box) but cap the CPU +time (cgroup cpu.max: 30.6 CPUs there). Thread pools sized to nproc then exceed the cap +and the kernel freezes the whole process until the next 100 ms period, which shows up as +40-60 ms tracking calls. This pins the process to --cpus cores (default: the cgroup cap, +else all) and sizes the OpenMP / BLAS pools to match. --cpus 8 also approximates a +Jetson Orin's core count. +""" + +from __future__ import annotations + +import os +import sys + + +def cgroup_cpus() -> int | None: + try: + quota, period = open("/sys/fs/cgroup/cpu.max").read().split()[:2] + return None if quota == "max" else max(1, int(int(quota) // int(period))) + except (OSError, ValueError): + return None + + +def _requested() -> int | None: + argv = sys.argv + for i, a in enumerate(argv): + if a == "--cpus" and i + 1 < len(argv): + return int(argv[i + 1]) + if a.startswith("--cpus="): + return int(a.split("=", 1)[1]) + return None + + +def apply() -> int: + avail = sorted(os.sched_getaffinity(0)) + n = _requested() or cgroup_cpus() or len(avail) + n = max(1, min(n, len(avail))) + os.sched_setaffinity(0, avail[:n]) + for v in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS"): + os.environ.setdefault(v, str(n)) + return n + + +CPUS = apply() diff --git a/scripts/vio_bench/fuse_rear_imu.py b/scripts/vio_bench/fuse_rear_imu.py new file mode 100644 index 0000000..8231d86 --- /dev/null +++ b/scripts/vio_bench/fuse_rear_imu.py @@ -0,0 +1,241 @@ +#!/usr/bin/env python3 +"""Vehicle state from SLAM poses + the rear IMU, scored causally against ground truth. + + python scripts/vio_bench/fuse_rear_imu.py --out + +The sequence needs rear_imu.csv / rear_truth.csv (make_rear_imu.py); the result is a +run_orbslam3.py output. Replays what the car would see: each SLAM pose arrives at its +frame time + its tracking time (frames.csv) + --pipeline-ms, the rear IMU at its host +stamps. Three estimators get the same stream and are read at every rear-IMU tick: + + imu_ekf control.ImuEKF: rear IMU driven, SLAM poses applied at their capture time + pose_ekf control.PoseEKF: SLAM poses only (the car's StateWorker today) + slam_raw the latest SLAM pose that has arrived (no estimator) + +SLAM poses are turned into the planar pose of the IMU point (vehicle frame): camera -> +vehicle with the sequence's T_vehicle_cam, levelled by a plane fit of each map's +trajectory (the car does it by fitting the floor). Each map is scored after one SE(2) +alignment of its SLAM poses to the truth. Before the run the rear IMU's time offset is +estimated by cross-correlating its yaw rate with the camera IMU's (--no-time-sync skips +it). Metrics: position / yaw error at every tick, in SLAM gaps (latest pose older than +--gap-s) separately, speed, yaw-rate and sideslip error, and availability. +""" + +from __future__ import annotations + +import argparse +import csv +import json +import os +import sys + +import numpy as np + +REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +sys.path.insert(0, REPO_ROOT) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import rgbdi # noqa: E402 +from control.estimator import ImuEKF, ImuEstimatorConfig, PoseEKF # noqa: E402 +from control.types import wrap_angle # noqa: E402 + + +def planar(T_wv: np.ndarray) -> np.ndarray: + """(N, 4, 4) levelled poses -> (N, 3) x, y, yaw of the vehicle x axis.""" + return np.column_stack([T_wv[:, 0, 3], T_wv[:, 1, 3], np.arctan2(T_wv[:, 1, 0], T_wv[:, 0, 0])]) + + +def level(T_wv: np.ndarray) -> np.ndarray: + """Rotation taking the plane of a flat-track trajectory to z = 0, z up along the vehicles' z.""" + p = T_wv[:, :3, 3] + if len(p) < 10 or np.ptp(p, axis=0).max() < 0.5: + n = T_wv[:, :3, 2].mean(axis=0) + else: + n = np.linalg.svd(p - p.mean(axis=0))[2][2] + n = n / np.linalg.norm(n) + if n @ T_wv[:, :3, 2].mean(axis=0) < 0: + n = -n + z = np.array([0.0, 0.0, 1.0]) + v, c = np.cross(n, z), float(n @ z) + if np.linalg.norm(v) < 1e-9: + return np.eye(3) + K = np.array([[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]]) + return np.eye(3) + K + K @ K / (1 + c) + + +def se2_align(src: np.ndarray, dst: np.ndarray) -> np.ndarray: + """3x3 rigid 2-D transform minimising |A src - dst| over x, y.""" + ms, md = src[:, :2].mean(0), dst[:, :2].mean(0) + U, _, Vt = np.linalg.svd((dst[:, :2] - md).T @ (src[:, :2] - ms)) + S = np.diag([1.0, np.sign(np.linalg.det(U @ Vt))]) + R = U @ S @ Vt + A = np.eye(3) + A[:2, :2], A[:2, 2] = R, md - R @ ms + return A + + +def apply_se2(A: np.ndarray, p: np.ndarray) -> np.ndarray: + xy = p[:, :2] @ A[:2, :2].T + A[:2, 2] + return np.column_stack([xy, wrap_angle(p[:, 2] + np.arctan2(A[1, 0], A[0, 0]))]) + + +def time_offset(cam_imu: np.ndarray, rear: np.ndarray, max_s: float = 0.08) -> float: + """s to subtract from the rear IMU's stamps: yaw-rate cross-correlation against the + camera IMU (device-timestamped on the frames' clock).""" + t0, t1 = max(cam_imu[0, 0], rear[0, 0]), min(cam_imu[-1, 0], rear[-1, 0]) + tg = np.arange(t0 + max_s, t1 - max_s, 0.001) + a = np.interp(tg, cam_imu[:, 0], cam_imu[:, 6]) + a = a - a.mean() + lags = np.arange(-max_s, max_s, 0.0005) + score = [] + for lag in lags: + b = np.interp(tg + lag, rear[:, 0], rear[:, 6]) + score.append(float(a @ (b - b.mean()))) + return float(lags[int(np.argmax(score))]) + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("seq") + ap.add_argument("result") + ap.add_argument("--out", required=True) + ap.add_argument("--pipeline-ms", type=float, default=5.0, help="frame transfer + publishing, on top of tracking") + ap.add_argument("--gap-s", type=float, default=0.1, help="latest pose older than this = in a SLAM gap") + ap.add_argument("--no-time-sync", action="store_true", help="use the rear IMU's host stamps as they are") + ap.add_argument("--vy-std", type=float, default=0.1, help="ImuEKF no-slip pseudo-measurement (m/s), <= 0: off") + ap.add_argument("--gate-chi2", type=float, default=16.3, help="ImuEKF pose gate, <= 0: off") + ap.add_argument("--gate-reset-s", type=float, default=2.0, help="ImuEKF re-anchors to SLAM after rejecting this long") + args = ap.parse_args() + + seq = rgbdi.load(args.seq) + T_vc = seq.T_imu_cam + rear = np.loadtxt(os.path.join(args.seq, "rear_imu.csv"), delimiter=",", skiprows=1) + rear[:, 0] *= 1e-9 + truth = np.loadtxt(os.path.join(args.seq, "rear_truth.csv"), delimiter=",", skiprows=1) + truth[:, 0] *= 1e-9 + cam_imu = seq.imu.copy() + cam_imu[:, 0] *= 1e-9 + offset = 0.0 if args.no_time_sync else time_offset(cam_imu, rear) + rear_t = rear[:, 0] - offset + + # SLAM: vehicle-frame planar poses per map, with arrival times + with open(os.path.join(args.result, "frames.csv")) as f: + frames = {int(r["t_ns"]): r for r in csv.DictReader(f)} + t_ns, T_wc = rgbdi.read_poses(os.path.join(args.result, "poses.csv")) + T_wv = T_wc @ np.linalg.inv(T_vc) + maps = np.array([int(frames[int(t)].get("map_id", 0)) for t in t_ns]) + arrive = np.array([int(t) * 1e-9 + float(frames[int(t)]["track_ms"]) * 1e-3 + args.pipeline_ms * 1e-3 for t in t_ns]) + meas = np.zeros((len(t_ns), 3)) + G, inside = rgbdi.interpolate_poses(seq.gt_t_ns, seq.gt_T, t_ns) + gt_pl = planar(G @ np.linalg.inv(T_vc)) + align = {} + for m in np.unique(maps): + k = maps == m + L = np.eye(4) + L[:3, :3] = level(T_wv[k]) + meas[k] = planar(L @ T_wv[k]) + ok = k & inside + align[m] = se2_align(meas[ok], gt_pl[ok]) if ok.sum() >= 3 else None + + # replay + cfg = ImuEstimatorConfig(vy_std=args.vy_std if args.vy_std > 0 else None, + gate_chi2=args.gate_chi2 if args.gate_chi2 > 0 else None, gate_reset_s=args.gate_reset_s) + names = ("imu_ekf", "pose_ekf", "slam_raw") + est = {"imu_ekf": ImuEKF(cfg), "pose_ekf": PoseEKF()} + events = sorted([(rear_t[i], 0, i) for i in range(len(rear_t))] + [(arrive[j], 1, j) for j in range(len(t_ns))]) + out = {n: np.full((len(rear_t), 6), np.nan) for n in names} # x, y, yaw, v, yaw rate (aligned), vy + tick_map = np.full(len(rear_t), -1) + last_pose_t = np.full(len(rear_t), np.nan) + cur_map, raw, raw_t = None, None, None + for t_ev, kind, i in events: + if kind == 1: + m = maps[i] + if m != cur_map: # new world frame: start over (the car resets too) + cur_map = m + for e in est.values(): + e.reset() + tm = int(t_ns[i]) * 1e-9 + for e in est.values(): + e.update_pose(tm, *meas[i]) + raw, raw_t = meas[i], tm + continue + t = rear_t[i] + est["imu_ekf"].update_imu(t, rear[i, 1], rear[i, 2], rear[i, 6]) + if cur_map is None or align.get(cur_map) is None: + continue + A = align[cur_map] + tick_map[i], last_pose_t[i] = cur_map, raw_t + for n in ("imu_ekf", "pose_ekf"): + st = est[n].predict_to(t) + if st is not None: + vy = est[n].x[4] if n == "imu_ekf" else np.nan + out[n][i] = np.r_[apply_se2(A, np.array([[st.x, st.y, st.yaw]]))[0], st.v, st.yaw_rate, vy] + if raw is not None: + out["slam_raw"][i, :3] = apply_se2(A, raw[None])[0] + + # truth at the ticks (the rear IMU's own stamps are the ticks) + tr = np.column_stack([np.interp(rear_t, truth[:, 0], truth[:, c]) for c in range(1, 7)]) + tr[:, 2] = np.interp(rear_t, truth[:, 0], np.unwrap(truth[:, 3])) + speed = np.hypot(tr[:, 3], tr[:, 4]) + in_gap = (rear_t - last_pose_t) > args.gap_s + scored = tick_map >= 0 + report = {"sequence": os.path.abspath(args.seq), "slam": os.path.abspath(args.result), + "rear_imu_time_offset_ms": 1e3 * offset, "ticks": int(scored.sum()), + "gap_ticks": int((scored & in_gap).sum()), "estimators": {}} + + def stats(e): + e = e[np.isfinite(e)] + return None if not len(e) else {"rmse": float(np.sqrt(np.mean(e ** 2))), "p95": float(np.percentile(np.abs(e), 95)), + "max": float(np.abs(e).max())} + + for n in names: + o = out[n] + valid = scored & np.isfinite(o[:, 0]) + pos = np.hypot(o[:, 0] - tr[:, 0], o[:, 1] - tr[:, 1]) + yaw = np.degrees(wrap_angle(o[:, 2] - tr[:, 2])) + r = {"available": float(valid.sum() / max(scored.sum(), 1)), + "pos_m": stats(pos[valid]), "pos_in_gaps_m": stats(pos[valid & in_gap]), + "yaw_deg": stats(yaw[valid])} + if n != "slam_raw": + r["speed_mps"] = stats((np.abs(o[:, 3]) - speed)[valid]) + r["yaw_rate_dps"] = stats(np.degrees(o[:, 4] - tr[:, 5])[valid]) + if n == "imu_ekf": + r["sideslip_vy_mps"] = stats((o[:, 5] - tr[:, 4])[valid]) + r["truth_vy_rms_mps"] = float(np.sqrt(np.mean(tr[valid, 4] ** 2))) + report["estimators"][n] = r + os.makedirs(args.out, exist_ok=True) + with open(os.path.join(args.out, "ticks.csv"), "w") as f: # per tick, for plots + f.write("t,map,in_gap,truth_x,truth_y,truth_yaw,truth_speed,truth_yaw_rate," + + ",".join(f"{n}_x,{n}_y,{n}_yaw,{n}_v,{n}_r" for n in names) + "\n") + for i in np.nonzero(scored)[0]: + f.write(f"{rear_t[i]:.4f},{tick_map[i]},{int(in_gap[i])},{tr[i, 0]:.4f},{tr[i, 1]:.4f},{tr[i, 2]:.4f},{speed[i]:.3f},{tr[i, 5]:.4f}," + + ",".join(f"{out[n][i, 0]:.4f},{out[n][i, 1]:.4f},{out[n][i, 2]:.4f},{out[n][i, 3]:.3f},{out[n][i, 4]:.4f}" + for n in names) + "\n") + with open(os.path.join(args.out, "fusion.json"), "w") as f: + json.dump(report, f, indent=1) + + def g(d, *k): + for x in k: + if d is None: + return "–" + d = d.get(x) if isinstance(d, dict) else None + return "–" if d is None else f"{d:.3f}" + + lines = [f"rear IMU time offset {1e3 * offset:.1f} ms; {report['ticks']} ticks, {report['gap_ticks']} in SLAM gaps", + "| estimator | available | pos RMSE / p95 / max (m) | pos in gaps RMSE / max (m) | yaw RMSE (deg) | speed RMSE (m/s) | yaw rate RMSE (deg/s) |", + "|---|---|---|---|---|---|---|"] + for n in names: + r = report["estimators"][n] + lines.append(f"| {n} | {100 * r['available']:.1f} % | {g(r, 'pos_m', 'rmse')} / {g(r, 'pos_m', 'p95')} / {g(r, 'pos_m', 'max')} | " + f"{g(r, 'pos_in_gaps_m', 'rmse')} / {g(r, 'pos_in_gaps_m', 'max')} | {g(r, 'yaw_deg', 'rmse')} | " + f"{g(r, 'speed_mps', 'rmse')} | {g(r, 'yaw_rate_dps', 'rmse')} |") + r = report["estimators"]["imu_ekf"] + lines.append(f"imu_ekf sideslip vy RMSE {g(r, 'sideslip_vy_mps', 'rmse')} m/s (truth vy RMS {r['truth_vy_rms_mps']:.3f} m/s)") + with open(os.path.join(args.out, "fusion.md"), "w") as f: + f.write("\n".join(lines) + "\n") + print("\n".join(lines)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/vio_bench/make_rear_imu.py b/scripts/vio_bench/make_rear_imu.py new file mode 100644 index 0000000..cef4c97 --- /dev/null +++ b/scripts/vio_bench/make_rear_imu.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +"""Add a simulated rear-of-car IMU (the Arduino's ICM-20948) to an rgbdi sequence. + + python scripts/vio_bench/make_rear_imu.py [--poll-hz 100] [--dlpf-hz 24] + +The sequence's IMU (imu.csv) stands for the OAK-D's: device-timestamped on the frames' +clock, what ORB-SLAM3 uses. This one is the second IMU, at the rear axle in the vehicle +frame (x forward, y left, z up), as the car reads it today: + +- ICM-20948 noise densities (gyro 0.015 deg/s/rtHz, accel 230 ug/rtHz) plus a constant + bias left after the firmware's start-up calibration and a slow random walk; +- the chip's digital low-pass filter (DLPF ~24 Hz, a 2nd-order causal filter at 1.1 kHz: + it delays the signal, ~10 ms); +- the Jetson polling the latest sample over I2C at --poll-hz with timing jitter, each + sample stamped with the host's clock when the read returns (not when it was measured). + +Truth comes from groundtruth.csv (camera poses -> vehicle poses, cubic spline; the track +is flat). Writes rear_imu.csv (t_ns, ax, ay, az [m/s^2], gx, gy, gz [rad/s]) and +rear_truth.csv (t_ns at the poll times: x, y, yaw, vx, vy, yaw rate of the IMU point, for +scoring), and a rear_imu block in calib.yaml. +""" + +from __future__ import annotations + +import argparse +import os +import sys + +import numpy as np +import yaml +from scipy.interpolate import CubicSpline +from scipy.signal import butter, lfilter + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import rgbdi # noqa: E402 + +G = 9.81 +ICM20948 = {"noise_gyro": np.radians(0.015), "noise_acc": 230e-6 * G, # per sqrt(Hz) + "bias_gyro": np.radians(0.1), "bias_acc": 0.02 * G, # 1-sigma, after calibration + "gyro_walk": 2e-4, "acc_walk": 2e-3} # per sqrt(s) +INTERNAL_HZ = 1125.0 + + +def vehicle_truth(seq: rgbdi.Sequence, rate: float): + """IMU-point (vehicle frame origin) trajectory at rate: t, x, y, yaw, body velocity, + body acceleration (specific force, gravity on z) and yaw rate.""" + T_wv = seq.gt_T @ np.linalg.inv(seq.T_imu_cam) # T_imu_cam is T_vehicle_cam here + t = seq.gt_t_ns * 1e-9 + yaw = np.unwrap(np.arctan2(T_wv[:, 1, 0], T_wv[:, 0, 0])) + sx, sy, syaw = (CubicSpline(t, T_wv[:, 0, 3]), CubicSpline(t, T_wv[:, 1, 3]), CubicSpline(t, yaw)) + ts = np.arange(t[0], t[-1], 1.0 / rate) + psi, r = syaw(ts), syaw(ts, 1) + c, s = np.cos(psi), np.sin(psi) + vxw, vyw, axw, ayw = sx(ts, 1), sy(ts, 1), sx(ts, 2), sy(ts, 2) + vb = np.column_stack([c * vxw + s * vyw, -s * vxw + c * vyw]) + ab = np.column_stack([c * axw + s * ayw, -s * axw + c * ayw, np.full_like(ts, G)]) + return ts, sx(ts), sy(ts), psi, vb, ab, r + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("seq") + ap.add_argument("--poll-hz", type=float, default=100.0) + ap.add_argument("--dlpf-hz", type=float, default=24.0, help="0 = no filter") + ap.add_argument("--jitter-ms", type=float, default=1.0, help="1-sigma poll timing jitter") + ap.add_argument("--read-ms", type=float, default=0.6, help="I2C read time (60 bytes at 1 MHz)") + ap.add_argument("--seed", type=int, default=1) + args = ap.parse_args() + rng = np.random.default_rng(args.seed) + + seq = rgbdi.load(args.seq) + ts, x, y, psi, vb, ab, r = vehicle_truth(seq, INTERNAL_HZ) + n, dt = len(ts), 1.0 / INTERNAL_HZ + gyro = np.column_stack([np.zeros(n), np.zeros(n), r]) + acc = ab.copy() + b_g = rng.normal(0, ICM20948["bias_gyro"], 3) + np.cumsum(rng.normal(0, ICM20948["gyro_walk"] * np.sqrt(dt), (n, 3)), 0) + b_a = rng.normal(0, ICM20948["bias_acc"], 3) + np.cumsum(rng.normal(0, ICM20948["acc_walk"] * np.sqrt(dt), (n, 3)), 0) + gyro += b_g + rng.normal(0, ICM20948["noise_gyro"] * np.sqrt(INTERNAL_HZ / 2), (n, 3)) + acc += b_a + rng.normal(0, ICM20948["noise_acc"] * np.sqrt(INTERNAL_HZ / 2), (n, 3)) + if args.dlpf_hz > 0: + b, a = butter(2, args.dlpf_hz / (INTERNAL_HZ / 2)) + gyro = lfilter(b, a, gyro - gyro[:1], axis=0) + gyro[:1] + acc = lfilter(b, a, acc - acc[:1], axis=0) + acc[:1] + + # the Jetson polls: each read returns the latest internal sample and is stamped when it returns + polls = np.arange(ts[0] + 0.05, ts[-1], 1.0 / args.poll_hz) + polls = polls + rng.normal(0, args.jitter_ms * 1e-3, len(polls)) + polls = np.sort(polls[(polls > ts[0]) & (polls < ts[-1])]) + idx = np.searchsorted(ts, polls, side="right") - 1 + stamp = polls + args.read_ms * 1e-3 + out = np.column_stack([np.round(stamp * 1e9), acc[idx], gyro[idx]]) + rgbdi.write_imu(os.path.join(args.seq, "rear_imu.csv"), out) + + # truth at the poll times (where the estimate is scored) + k = np.clip(np.searchsorted(ts, stamp), 0, n - 1) + with open(os.path.join(args.seq, "rear_truth.csv"), "w") as f: + f.write("t_ns,x,y,yaw,vx,vy,yaw_rate\n") + for j in range(len(stamp)): + i = k[j] + f.write(f"{int(round(stamp[j] * 1e9))},{x[i]:.6f},{y[i]:.6f},{psi[i]:.6f},{vb[i, 0]:.6f},{vb[i, 1]:.6f},{r[i]:.6f}\n") + + calib_path = os.path.join(args.seq, "calib.yaml") + with open(calib_path) as f: + calib = yaml.safe_load(f) + calib["rear_imu"] = { + "model": "ICM-20948 (Arduino, I2C)", "T_vehicle_imu": np.eye(4).tolist(), + "poll_hz": args.poll_hz, "dlpf_hz": args.dlpf_hz, "jitter_ms": args.jitter_ms, "read_ms": args.read_ms, + **{k: float(v) for k, v in ICM20948.items()}, + } + with open(calib_path, "w") as f: + yaml.safe_dump(calib, f, sort_keys=False) + print(f"{len(out)} rear IMU samples at {args.poll_hz:g} Hz (DLPF {args.dlpf_hz:g} Hz) -> {args.seq}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/vio_bench/make_record_config.py b/scripts/vio_bench/make_record_config.py new file mode 100644 index 0000000..da7ba79 --- /dev/null +++ b/scripts/vio_bench/make_record_config.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +"""Write a car config for benchmark recordings (README.md here) from an existing one. + + python scripts/vio_bench/make_record_config.py config.yaml -o config_vio_record.yaml + python start.py --config config_vio_record.yaml # drive the laps, [q] to stop + +Sets: recording on; the OAK-D's 6-axis IMU recorded (raw_imu) at --imu-rate; every +frame and IMU sample kept (sample_k 1, no file rotation, nothing deleted). Everything +else, including SLAM, control and the operator's arming, stays as in the source config +(the benchmark replays the recording through both systems afterwards). +""" + +from __future__ import annotations + +import argparse +import sys + +import yaml + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("config") + ap.add_argument("-o", "--output", required=True) + ap.add_argument("--imu-rate", type=int, default=200, help="Hz; regenerate the ORB-SLAM3 settings at it") + ap.add_argument("--recording-path", default="/tmp/pilot_recordings") + args = ap.parse_args() + + with open(args.config) as f: + cfg = yaml.safe_load(f) or {} + if cfg.get("sim"): + raise SystemExit("this is for the car (OAK-D); sim runs use sim_to_rgbdi.py") + cfg["recording"] = True + cfg["recording_path"] = args.recording_path + cfg["raw_imu"] = True + cfg.setdefault("camera", {})["imu_rate_hz"] = args.imu_rate + rc = cfg.setdefault("recording_config", {}) + for name in ("frame", "raw_imu"): + rc[name] = {"sample_k": 1, "top_n": 0, "keep_files": 0} + with open(args.output, "w") as f: + f.write(f"# benchmark recording config from {args.config} " + "(scripts/vio_bench/make_record_config.py)\n") + yaml.safe_dump(cfg, f, sort_keys=False) + print(f"wrote {args.output}: recording frames + raw IMU ({args.imu_rate} Hz) to {args.recording_path}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/vio_bench/markers.py b/scripts/vio_bench/markers.py new file mode 100644 index 0000000..7e0cd84 --- /dev/null +++ b/scripts/vio_bench/markers.py @@ -0,0 +1,218 @@ +#!/usr/bin/env python3 +"""Accuracy on the real track from AprilTags (README.md here): no motion capture needed. + + python scripts/vio_bench/markers.py [...] --size 0.16 \ + [--survey markers.yaml] [--closed] --out + +Tags (tag36h11 by default) are found in every RGB frame and located in the camera frame +from their corners and printed size (IPPE). With a result's pose of that frame, each +sighting places the tag in that result's world. Scored per result: + + repeatability the same tag placed on different passes (a pass = sightings with no gap + over --pass-gap s, i.e. one lap): RMS / max distance of each pass's + placement from the tag's mean, and the distance from the first pass by + pass number (drift growth over laps). Needs no survey. + absolute with --survey (tag centres measured on the track, >= 3 tags not in a + line): one rigid alignment of the tags' mean placements onto the + survey, then every sighting's distance from its surveyed position. + closure with --closed (the car was stopped where it started): distance between + the first and last tracked poses. + +Only sightings within --max-dist m and at least --min-side px across are used: a 16 cm +tag at fx ~400 px is placed to ~0.6 cm at 1 m, ~1.5 cm at 1.5 m, ~5 cm at 2.5 m and +~13 cm at 3.5 m (rendered test images), so use big tags. Detections are cached in /tags__.csv. + +markers.yaml: + family: 36h11 + size_m: 0.16 # black square edge, m + tags: # optional survey: tag centre in the track frame, m + 0: [0.0, 0.0, 0.25] +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys + +import cv2 +import numpy as np +import yaml + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import rgbdi # noqa: E402 +from score import umeyama_se3 # noqa: E402 + +FAMILIES = {"36h11": cv2.aruco.DICT_APRILTAG_36h11, "25h9": cv2.aruco.DICT_APRILTAG_25h9, + "16h5": cv2.aruco.DICT_APRILTAG_16h5} + + +def tag_object_points(size: float) -> np.ndarray: + """Corners in the tag frame, in the order the detector returns them (TL, TR, BR, BL).""" + h = size / 2.0 + return np.array([[-h, h, 0], [h, h, 0], [h, -h, 0], [-h, -h, 0]], dtype=np.float64) + + +def detect_frame(gray: np.ndarray, detector, K: np.ndarray, size: float) -> list: + """[(id, p_cam (3,), side_px, reproj_px)] for the tags in one undistorted image.""" + corners, ids, _ = detector.detectMarkers(gray) + out = [] + if ids is None: + return out + obj = tag_object_points(size) + for c, i in zip(corners, ids.ravel()): + img = c.reshape(4, 2).astype(np.float64) + ok, rvec, tvec = cv2.solvePnP(obj, img, K, None, flags=cv2.SOLVEPNP_IPPE_SQUARE) + if not ok: + continue + proj, _ = cv2.projectPoints(obj, rvec, tvec, K, None) + reproj = float(np.sqrt(np.mean(np.sum((proj.reshape(4, 2) - img) ** 2, axis=1)))) + side = float(np.mean(np.linalg.norm(img - np.roll(img, -1, axis=0), axis=1))) + out.append((int(i), tvec.ravel(), side, reproj)) + return out + + +def detect(seq: rgbdi.Sequence, family: str, size: float) -> np.ndarray: + """(N, 7) t_ns, id, x, y, z (camera frame), side_px, reproj_px for every sighting; cached.""" + cache = os.path.join(seq.root, f"tags_{family}_{size:g}.csv") + if os.path.exists(cache): + return np.loadtxt(cache, delimiter=",", skiprows=1, ndmin=2).reshape(-1, 7) + params = cv2.aruco.DetectorParameters() + params.cornerRefinementMethod = cv2.aruco.CORNER_REFINE_SUBPIX + detector = cv2.aruco.ArucoDetector(cv2.aruco.getPredefinedDictionary(FAMILIES[family]), params) + fx, fy, cx, cy = seq.K + K = np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]], dtype=np.float64) + rows = [] + for t, path in zip(seq.t_ns, seq.rgb): + gray = cv2.imread(path, cv2.IMREAD_GRAYSCALE) + for i, p, side, reproj in detect_frame(gray, detector, K, size): + rows.append([t, i, *p, side, reproj]) + det = np.array(rows, dtype=np.float64).reshape(-1, 7) + with open(cache, "w") as f: + f.write("t_ns,id,x,y,z,side_px,reproj_px\n") + for r in det: + f.write(f"{int(r[0])},{int(r[1])}," + ",".join(f"{v:.6f}" for v in r[2:]) + "\n") + return det + + +def passes(t_s: np.ndarray, gap: float) -> np.ndarray: + """Pass number of each (time-sorted) sighting: a new pass after a gap > gap s.""" + return np.concatenate([[0], np.cumsum(np.diff(t_s) > gap)]) + + +def score_result(det: np.ndarray, t_pose: np.ndarray, T_pose: np.ndarray, survey: dict | None, + closed: bool, pass_gap: float) -> dict: + """Marker metrics for one trajectory (poses T_world_cam at t_pose, ns).""" + pose_at = {int(t): T for t, T in zip(t_pose, T_pose)} + seen = [(r, pose_at[int(r[0])]) for r in det if int(r[0]) in pose_at] + out: dict = {"sightings": len(det), "sightings_tracked": len(seen)} + if closed and len(t_pose) >= 2: + out["closure_m"] = float(np.linalg.norm(T_pose[-1][:3, 3] - T_pose[0][:3, 3])) + if not seen: + return out + + by_tag: dict = {} + for r, T in seen: + p_w = (T @ np.append(r[2:5], 1.0))[:3] + by_tag.setdefault(int(r[1]), []).append((r[0] * 1e-9, p_w)) + rep_dev, growth, tag_means = [], {}, {} + for tag, obs in by_tag.items(): + obs.sort(key=lambda o: o[0]) + t = np.array([o[0] for o in obs]) + P = np.array([o[1] for o in obs]) + tag_means[tag] = P.mean(axis=0) + k = passes(t, pass_gap) + med = np.array([np.median(P[k == j], axis=0) for j in range(k.max() + 1)]) + if len(med) >= 2: + rep_dev.extend(np.linalg.norm(med - med.mean(axis=0), axis=1)) + for j in range(1, len(med)): + growth.setdefault(j, []).append(float(np.linalg.norm(med[j] - med[0]))) + out["tags_seen"] = len(by_tag) + if rep_dev: + rep = np.array(rep_dev) + out["repeatability_m"] = {"rms": float(np.sqrt(np.mean(rep ** 2))), "max": float(rep.max()), + "tags": sum(1 for o in by_tag.values() if len(o) > 1)} + out["drift_from_first_pass_m"] = {int(j): float(np.mean(v)) for j, v in sorted(growth.items())} + + if survey: + common = sorted(set(tag_means) & set(survey)) + if len(common) >= 3: + A = umeyama_se3(np.array([tag_means[i] for i in common]), np.array([survey[i] for i in common])) + err = [] + for tag in common: + for _, p in by_tag[tag]: + err.append(np.linalg.norm((A @ np.append(p, 1.0))[:3] - np.asarray(survey[tag]))) + err = np.array(err) + out["absolute_m"] = {"rmse": float(np.sqrt(np.mean(err ** 2))), "median": float(np.median(err)), + "max": float(err.max()), "tags": len(common)} + else: + out["absolute_m"] = f"needs >= 3 surveyed tags seen, have {len(common)}" + return out + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("seq") + ap.add_argument("results", nargs="+") + ap.add_argument("--survey", help="markers.yaml (family, size_m, tags: surveyed centres)") + ap.add_argument("--family", help="tag family, default 36h11 (or the survey's)") + ap.add_argument("--size", type=float, help="black square edge in m (or the survey's size_m)") + ap.add_argument("--closed", action="store_true", help="the car ended where it started") + ap.add_argument("--pass-gap", type=float, default=2.0, help="s without a sighting that starts a new pass") + ap.add_argument("--max-dist", type=float, default=2.5, help="m, farther sightings are dropped") + ap.add_argument("--min-side", type=float, default=30.0, help="px, smaller sightings are dropped") + ap.add_argument("--out", required=True) + args = ap.parse_args() + + survey_cfg = {} + if args.survey: + with open(args.survey) as f: + survey_cfg = yaml.safe_load(f) or {} + family = args.family or str(survey_cfg.get("family", "36h11")) + size = args.size or survey_cfg.get("size_m") + if not size: + raise SystemExit("give the tag size: --size or size_m in the survey") + survey = {int(k): np.asarray(v, dtype=np.float64) for k, v in (survey_cfg.get("tags") or {}).items()} + + seq = rgbdi.load(args.seq) + det = detect(seq, family, float(size)) + good = (np.linalg.norm(det[:, 2:5], axis=1) <= args.max_dist) & (det[:, 5] >= args.min_side) + det = det[good] + print(f"{len(det)} usable sightings of {len(set(det[:, 1].astype(int)))} tags") + + rows = [] + for res in args.results: + t, T = rgbdi.read_poses(os.path.join(res, "poses.csv")) + with open(os.path.join(res, "meta.json")) as f: + meta = json.load(f) + rows.append({"name": os.path.basename(os.path.normpath(res)), "mode": meta.get("mode"), + **score_result(det, t, T, survey, args.closed, args.pass_gap)}) + os.makedirs(args.out, exist_ok=True) + with open(os.path.join(args.out, "markers.json"), "w") as f: + json.dump(rows, f, indent=1) + + def g(d, *keys, fmt="{:.3f}"): + for k in keys: + if not isinstance(d, dict) or k not in d: + return "–" + d = d[k] + return fmt.format(d) if isinstance(d, (int, float)) else str(d) + + lines = ["| run | mode | sightings tracked | repeatability RMS / max (m) | drift from pass 1, last pass (m) | " + "absolute RMSE / max (m) | closure (m) |", "|---|---|---|---|---|---|---|"] + for r in rows: + drift = r.get("drift_from_first_pass_m") or {} + last = f"{drift[max(drift)]:.3f} (pass {max(drift) + 1})" if drift else "–" + lines.append(f"| {r['name']} | {r['mode']} | {r['sightings_tracked']} / {r['sightings']} | " + f"{g(r, 'repeatability_m', 'rms')} / {g(r, 'repeatability_m', 'max')} | {last} | " + f"{g(r, 'absolute_m', 'rmse')} / {g(r, 'absolute_m', 'max')} | {g(r, 'closure_m')} |") + with open(os.path.join(args.out, "markers.md"), "w") as f: + f.write("\n".join(lines) + "\n") + print("\n".join(lines)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/vio_bench/render_track.py b/scripts/vio_bench/render_track.py new file mode 100644 index 0000000..bef9765 --- /dev/null +++ b/scripts/vio_bench/render_track.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python3 +"""Render a geometrically exact RGB-D-inertial sequence of a sim run's track and trajectory. + + python scripts/vio_bench/render_track.py --out \ + [--blackout 4.0:0.3] [--workers 16] + +The sim sequences (sim_to_rgbdi.py) take their depth from the 2-D LiDAR and their images +from the sim's renderer, and the two do not agree well enough for a tracker that builds +its map from depth (ORB-SLAM3): only about half of its matches between consecutive frames +fit the depth. This renders the same track (the run's boundary.npz: floor plus walls +along the inner and outer boundary, a far backdrop) from the same ground-truth camera +poses, with a non-repeating procedural texture and exact depth, and keeps the sim +sequence's IMU, calibration and ground truth: image, depth, IMU and ground truth are +exactly consistent. What is left to differ is the trackers themselves. + +--blackout START:DUR (s from the first frame, repeatable) replaces those frames with a +featureless grey image: a forced tracking loss, e.g. before the IMU is initialised. +""" + +from __future__ import annotations + +import argparse +import os +import shutil +import sys +from concurrent.futures import ProcessPoolExecutor + +for _v in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS"): + os.environ.setdefault(_v, "1") # one thread per worker: BLAS pools x workers exhaust the host's PIDs + +import cv2 +import numpy as np +import yaml + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import rgbdi # noqa: E402 + +WALL_HEIGHT = 0.30 # m +BACKDROP_HEIGHT = 4.0 # m +MAX_DEPTH = 10.0 # m, farther depth is written as 0 (no depth), like the LiDAR depth +SUPERSAMPLE = 2 + + +def _hash(i: np.ndarray, j: np.ndarray, seed: float) -> np.ndarray: + return np.modf(np.abs(np.sin(i * 127.1 + j * 311.7 + seed * 74.7) * 43758.5453))[0] + + +def value_noise(x: np.ndarray, y: np.ndarray, seed: float) -> np.ndarray: + """Smooth lattice noise in [0, 1] with unit cell size.""" + i, j = np.floor(x), np.floor(y) + fx, fy = x - i, y - j + fx, fy = fx * fx * (3 - 2 * fx), fy * fy * (3 - 2 * fy) + a, b = _hash(i, j, seed), _hash(i + 1, j, seed) + c, d = _hash(i, j + 1, seed), _hash(i + 1, j + 1, seed) + return (a * (1 - fx) + b * fx) * (1 - fy) + (c * (1 - fx) + d * fx) * fy + + +def texture(u: np.ndarray, v: np.ndarray, footprint: np.ndarray, seed: float, scales) -> np.ndarray: + """Multi-octave noise in [0, 255] at surface coordinates (u, v) m; octaves finer than + ~2 footprints (m per rendered pixel) fade out instead of aliasing.""" + acc = np.zeros_like(u) + wsum = np.zeros_like(u) + for k, s in enumerate(scales): + w = np.clip((s / np.maximum(footprint, 1e-9) - 2.0) / 2.0, 0.0, 1.0) + acc += w * (value_noise(u / s, v / s, seed + 13 * k) - 0.5) + wsum += w + n = 0.5 + 1.8 * acc / np.maximum(np.sqrt(np.maximum(wsum, 1e-9)), 1.0) + return np.clip(255 * n, 0, 255) + + +class Scene: + def __init__(self, inner: np.ndarray, outer: np.ndarray) -> None: + segs, arcs, seeds = [], [], [] + for k, poly in enumerate((inner, outer)): + p = np.asarray(poly, np.float64) + if np.linalg.norm(p[0] - p[-1]) > 1e-6: + p = np.vstack([p, p[:1]]) # closed loop + e = np.diff(p, axis=0) + L = np.linalg.norm(e, axis=1) + segs.append(np.hstack([p[:-1], e])) + arcs.append(np.concatenate([[0.0], np.cumsum(L)[:-1]])) + seeds.append(np.full(len(e), 100.0 + 50 * k)) + self.seg = np.vstack(segs) # (S, 4): p0x, p0y, ex, ey + self.arc = np.concatenate(arcs) # arc length at p0 + self.len = np.linalg.norm(self.seg[:, 2:], axis=1) + self.seed = np.concatenate(seeds) + allp = np.vstack([inner, outer]) + self.centre = allp.mean(axis=0) + self.r_backdrop = float(np.linalg.norm(allp - self.centre, axis=1).max()) + 8.0 + + def cast(self, T_wc: np.ndarray, K: tuple, w: int, h: int, colour: bool) -> np.ndarray: + """Optical depth (h, w) of the first hit, or grey image if colour.""" + fx, fy, cx, cy = K + u, v = np.meshgrid(np.arange(w, dtype=np.float64), np.arange(h, dtype=np.float64)) + rc = np.stack([(u - cx) / fx, (v - cy) / fy, np.ones_like(u)], -1).reshape(-1, 3) + R, o = T_wc[:3, :3], T_wc[:3, 3] + d = rc @ R.T # world ray per pixel, optical z = 1 + n = len(d) + t = np.full(n, np.inf) + kind = np.zeros(n, np.int8) # 0 sky, 1 floor, 2 wall, 3 backdrop + with np.errstate(divide="ignore", invalid="ignore"): + tf = np.where(d[:, 2] < -1e-9, -o[2] / d[:, 2], np.inf) + t, kind = np.where(tf < t, tf, t), np.where(tf < t, 1, kind) + # walls: segments within reach, vertical from 0 to WALL_HEIGHT + rel = self.seg[:, :2] - o[:2] + near = np.minimum(np.linalg.norm(rel, axis=1), np.linalg.norm(rel + self.seg[:, 2:], axis=1)) < MAX_DEPTH * 1.5 + ws, wsg = np.full(n, 0.0), np.full(n, -1) + for k in np.nonzero(near)[0]: + p0x, p0y, ex, ey = self.seg[k] + den = d[:, 0] * ey - d[:, 1] * ex + with np.errstate(divide="ignore", invalid="ignore"): + tk = ((p0x - o[0]) * ey - (p0y - o[1]) * ex) / den + sk = ((p0x - o[0]) * d[:, 1] - (p0y - o[1]) * d[:, 0]) / den + z = o[2] + tk * d[:, 2] + hit = (tk > 1e-6) & (sk >= 0) & (sk <= 1) & (z >= 0) & (z <= WALL_HEIGHT) & (tk < t) + t[hit], kind[hit], ws[hit], wsg[hit] = tk[hit], 2, sk[hit], k + # backdrop: vertical cylinder around the track + a = d[:, 0] ** 2 + d[:, 1] ** 2 + oc = o[:2] - self.centre + b = 2 * (oc[0] * d[:, 0] + oc[1] * d[:, 1]) + c = oc @ oc - self.r_backdrop ** 2 + with np.errstate(divide="ignore", invalid="ignore"): + tb = (-b + np.sqrt(np.maximum(b * b - 4 * a * c, 0))) / (2 * a) + zb = o[2] + tb * d[:, 2] + hit = (tb > 0) & (zb <= BACKDROP_HEIGHT) & (tb < t) + t, kind = np.where(hit, tb, t), np.where(hit, 3, kind) + if not colour: + depth = np.where((kind > 0) & (kind < 3) & (t <= MAX_DEPTH), t, 0.0) + return depth.reshape(h, w) + + P = o + d * np.where(np.isfinite(t), t, 0.0)[:, None] + foot = np.where(np.isfinite(t), t * np.linalg.norm(d, axis=1), 1e3) / fx + img = np.full(n, 190.0) + m = kind == 1 + img[m] = texture(P[m, 0], P[m, 1], foot[m], 1.0, (0.6, 0.2, 0.07, 0.03)) + m = kind == 2 + g = wsg[m] + img[m] = 0.8 * texture(self.arc[g] + ws[m] * self.len[g], P[m, 2], foot[m], 7.0, (0.3, 0.1, 0.04)) \ + + 0.2 * np.where(self.seed[g] > 120, 40.0, 210.0) + m = kind == 3 + ang = np.arctan2(P[m, 1] - self.centre[1], P[m, 0] - self.centre[0]) * self.r_backdrop + img[m] = 0.6 * texture(ang, P[m, 2], foot[m], 31.0, (2.0, 0.7, 0.25)) + 0.4 * 120 + return img.reshape(h, w) + + +_SCENE: Scene | None = None + + +def _init(inner, outer): + global _SCENE + _SCENE = Scene(inner, outer) + + +def _render(job): + t_ns, T, K, w, h, out, blank = job + if blank: + img = np.full((h, w), 128, np.uint8) + else: + s = SUPERSAMPLE + fx, fy, cx, cy = K + hi = _SCENE.cast(T, (fx * s, fy * s, (cx + 0.5) * s - 0.5, (cy + 0.5) * s - 0.5), w * s, h * s, True) + img = cv2.resize(hi.astype(np.float32), (w, h), interpolation=cv2.INTER_AREA).round().astype(np.uint8) + depth = _SCENE.cast(T, K, w, h, False) + cv2.imwrite(os.path.join(out, "rgb", f"{t_ns}.png"), cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)) + cv2.imwrite(os.path.join(out, "depth", f"{t_ns}.png"), np.round(depth * 1000).astype(np.uint16)) + return t_ns + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("seq", help="sim rgbdi sequence (sim_to_rgbdi.py): poses, IMU, calibration") + ap.add_argument("run", help="the sim run it came from (export/boundary.npz)") + ap.add_argument("--out", required=True) + ap.add_argument("--blackout", action="append", default=[], help="START:DUR s, featureless frames") + ap.add_argument("--workers", type=int, default=min(16, os.cpu_count() or 1)) + args = ap.parse_args() + + seq = rgbdi.load(args.seq) + b = np.load(os.path.join(args.run, "export", "boundary.npz")) + inner, outer = b["inner_0"], b["outer_0"] + G, inside = rgbdi.interpolate_poses(seq.gt_t_ns, seq.gt_T, seq.t_ns) + t_ns = seq.t_ns[inside] + t0 = t_ns[0] + blank = np.zeros(len(t_ns), bool) + for spec in args.blackout: + a, d = (float(x) for x in spec.split(":")) + blank |= ((t_ns - t0) * 1e-9 >= a) & ((t_ns - t0) * 1e-9 < a + d) + + os.makedirs(os.path.join(args.out, "rgb"), exist_ok=True) + os.makedirs(os.path.join(args.out, "depth"), exist_ok=True) + w, h = int(seq.calib["width"]), int(seq.calib["height"]) + jobs = [(int(t), T, tuple(seq.K), w, h, args.out, bool(bl)) for t, T, bl in zip(t_ns, G[inside], blank)] + with ProcessPoolExecutor(args.workers, initializer=_init, initargs=(inner, outer)) as ex: + for k, _ in enumerate(ex.map(_render, jobs, chunksize=4)): + if k % 200 == 0: + print(f"{k}/{len(jobs)}", flush=True) + + with open(os.path.join(args.out, "frames.csv"), "w") as f: + f.write("t_ns,rgb,depth\n") + for t in t_ns: + f.write(f"{t},rgb/{t}.png,depth/{t}.png\n") + for name in ("imu.csv", "groundtruth.csv"): + shutil.copyfile(os.path.join(args.seq, name), os.path.join(args.out, name)) + calib = dict(seq.calib) + calib["source"] = f"render_track.py of {os.path.abspath(args.seq)}" + calib["notes"] = ("rendered: floor + walls from the run's track boundary, procedural texture, exact depth; " + "IMU and ground truth from the sim sequence" + + (f"; featureless frames at {', '.join(args.blackout)} s" if args.blackout else "")) + with open(os.path.join(args.out, "calib.yaml"), "w") as f: + yaml.safe_dump(calib, f, sort_keys=False) + print(f"{len(t_ns)} frames ({int(blank.sum())} blanked) -> {args.out}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/vio_bench/rgbdi.py b/scripts/vio_bench/rgbdi.py new file mode 100644 index 0000000..526c0d9 --- /dev/null +++ b/scripts/vio_bench/rgbdi.py @@ -0,0 +1,118 @@ +""" +The `rgbdi` sequence format shared by the RGB-D-inertial benchmark (README.md here): one +directory per sequence, written from the sim or from a real-car recording, read by both +runners and the scorer. + + rgb/.png 8-bit RGB + depth/.png uint16 millimetres, pixel-aligned with rgb (0 = no depth) + frames.csv t_ns,rgb,depth (time order) + imu.csv t_ns,ax,ay,az,gx,gy,gz IMU frame, m/s^2 and rad/s, one + row per paired accel + gyro sample + groundtruth.csv t_ns,x,y,z,qx,qy,qz,qw camera pose in the world (optional: + the real track has markers.csv instead) + calib.yaml width, height, fx, fy, cx, cy (undistorted pinhole), + T_imu_cam (4x4, p_imu = T p_cam), imu: {rate_hz, noise_gyro, + noise_acc, gyro_walk, acc_walk}, source, notes + +All times are nanoseconds on one clock. Poses use the camera optical frame (x right, +y down, z forward). +""" + +from __future__ import annotations + +import csv +import os +from dataclasses import dataclass, field + +import numpy as np +import yaml +from scipy.spatial.transform import Rotation + + +@dataclass +class Sequence: + root: str + t_ns: np.ndarray # (F,) int64 frame times + rgb: list # F paths + depth: list # F paths + imu: np.ndarray # (M, 7) float64: t_ns, ax, ay, az, gx, gy, gz + calib: dict + gt_t_ns: np.ndarray = field(default_factory=lambda: np.zeros(0, np.int64)) + gt_T: np.ndarray = field(default_factory=lambda: np.zeros((0, 4, 4))) # T_world_cam + + @property + def K(self) -> tuple: + c = self.calib + return c["fx"], c["fy"], c["cx"], c["cy"] + + @property + def T_imu_cam(self) -> np.ndarray: + return np.asarray(self.calib["T_imu_cam"], dtype=np.float64).reshape(4, 4) + + +def load(root: str) -> Sequence: + with open(os.path.join(root, "calib.yaml")) as f: + calib = yaml.safe_load(f) + t, rgb, depth = [], [], [] + with open(os.path.join(root, "frames.csv")) as f: + for r in csv.DictReader(f): + t.append(int(r["t_ns"])) + rgb.append(os.path.join(root, r["rgb"])) + depth.append(os.path.join(root, r["depth"])) + imu = np.loadtxt(os.path.join(root, "imu.csv"), delimiter=",", skiprows=1, ndmin=2) + seq = Sequence(root, np.array(t, np.int64), rgb, depth, imu, calib) + gt_path = os.path.join(root, "groundtruth.csv") + if os.path.exists(gt_path): + g = np.loadtxt(gt_path, delimiter=",", skiprows=1, ndmin=2) + seq.gt_t_ns = g[:, 0].astype(np.int64) + seq.gt_T = poses_from_rows(g[:, 1:]) + return seq + + +def poses_from_rows(rows: np.ndarray) -> np.ndarray: + """(N, 7) x, y, z, qx, qy, qz, qw -> (N, 4, 4).""" + T = np.tile(np.eye(4), (len(rows), 1, 1)) + T[:, :3, :3] = Rotation.from_quat(rows[:, 3:7]).as_matrix() + T[:, :3, 3] = rows[:, :3] + return T + + +def rows_from_poses(T: np.ndarray) -> np.ndarray: + return np.hstack([T[:, :3, 3], Rotation.from_matrix(T[:, :3, :3]).as_quat()]) + + +def write_poses(path: str, t_ns: np.ndarray, T: np.ndarray, header: str = "t_ns,x,y,z,qx,qy,qz,qw") -> None: + rows = rows_from_poses(T) if len(T) else np.zeros((0, 7)) + with open(path, "w") as f: + f.write(header + "\n") + for t, r in zip(t_ns, rows): + f.write(f"{int(t)}," + ",".join(f"{v:.9f}" for v in r) + "\n") + + +def read_poses(path: str) -> tuple: + g = np.loadtxt(path, delimiter=",", skiprows=1, ndmin=2) + if g.size == 0: + return np.zeros(0, np.int64), np.zeros((0, 4, 4)) + return g[:, 0].astype(np.int64), poses_from_rows(g[:, 1:8]) + + +def write_imu(path: str, imu: np.ndarray) -> None: + with open(path, "w") as f: + f.write("t_ns,ax,ay,az,gx,gy,gz\n") + for r in imu: + f.write(f"{int(r[0])}," + ",".join(f"{v:.7f}" for v in r[1:]) + "\n") + + +def interpolate_poses(t_src: np.ndarray, T_src: np.ndarray, t_query: np.ndarray) -> tuple: + """Poses at t_query (linear position, slerp rotation); mask of queries inside t_src.""" + from scipy.spatial.transform import Slerp + + inside = (t_query >= t_src[0]) & (t_query <= t_src[-1]) + out = np.tile(np.eye(4), (len(t_query), 1, 1)) + if inside.any(): + tq = t_query[inside].astype(np.float64) + ts = t_src.astype(np.float64) + out[inside, :3, :3] = Slerp(ts, Rotation.from_matrix(T_src[:, :3, :3]))(tq).as_matrix() + for k in range(3): + out[inside, k, 3] = np.interp(tq, ts, T_src[:, k, 3]) + return out, inside diff --git a/scripts/vio_bench/run_cuvslam.py b/scripts/vio_bench/run_cuvslam.py new file mode 100644 index 0000000..d021d39 --- /dev/null +++ b/scripts/vio_bench/run_cuvslam.py @@ -0,0 +1,164 @@ +#!/usr/bin/env python3 +"""cuVSLAM (PyCuVSLAM 17.x, release wheel) on an rgbdi sequence. + + python scripts/vio_bench/run_cuvslam.py --out [--no-imu] [--odom-only] + +Multisensor odometry with the one RGB-D camera plus the IMU (with --no-imu, the RGBD +mode), and SLAM on top unless --odom-only. The rig frame is the camera's. Each frame +is preceded by every IMU sample up to its time. Writes poses.csv (SLAM poses, or odometry +with --odom-only), odom_poses.csv, frames.csv (every frame: tracked, track time in ms) +and meta.json. Runs in its own venv (the wheel pins numpy). +""" + +from __future__ import annotations + +import argparse +import json +import os +import subprocess +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import cpulimit # noqa: E402,F401 (before cv2 and cuvslam: sizes their thread pools) + +import cv2 +import numpy as np +from scipy.spatial.transform import Rotation + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import rgbdi # noqa: E402 + + +def pose_to_T(pose) -> np.ndarray: + T = np.eye(4) + T[:3, :3] = Rotation.from_quat(np.asarray(pose.rotation)).as_matrix() + T[:3, 3] = np.asarray(pose.translation) + return T + + +def T_to_pose(vslam, T: np.ndarray): + return vslam.Pose(rotation=Rotation.from_matrix(T[:3, :3]).as_quat().tolist(), + translation=T[:3, 3].tolist()) + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("seq") + ap.add_argument("--out", required=True) + ap.add_argument("--imu-noise-scale", type=float, default=1.0, + help="multiply calib.yaml's IMU noise densities and random walks (tuning)") + ap.add_argument("--no-imu", action="store_true", help="RGBD odometry, no IMU") + ap.add_argument("--odom-only", action="store_true", help="no SLAM (no loop closure)") + ap.add_argument("--speed", type=float, default=1.0, + help="replay speed: frames are fed on the sequence's clock (1 = real time, as on the car), " + "0 = as fast as tracking allows (the mapping threads then fall behind)") + ap.add_argument("--cpus", type=int, help="pin to this many cores (cpulimit.py); default the cgroup's CPU cap") + args = ap.parse_args() + + import cuvslam as vslam + + seq = rgbdi.load(args.seq) + c = seq.calib + T = vslam.Tracker + + cam = vslam.Camera() + cam.distortion = vslam.Distortion(vslam.Distortion.Model.Pinhole) + cam.focal = [c["fx"], c["fy"]] + cam.principal = [c["cx"], c["cy"]] + cam.size = [c["width"], c["height"]] + cam.rig_from_camera = T_to_pose(vslam, np.eye(4)) + rig = vslam.Rig() + rig.cameras = [cam] + + inertial = not args.no_imu + if inertial: + im = c["imu"] + imu = vslam.ImuCalibration() + imu.rig_from_imu = T_to_pose(vslam, np.linalg.inv(seq.T_imu_cam)) # rig = camera + imu.gyroscope_noise_density = im["noise_gyro"] * args.imu_noise_scale + imu.gyroscope_random_walk = im["gyro_walk"] * args.imu_noise_scale + imu.accelerometer_noise_density = im["noise_acc"] * args.imu_noise_scale + imu.accelerometer_random_walk = im["acc_walk"] * args.imu_noise_scale + imu.frequency = im["rate_hz"] + rig.imus = [imu] + cfg = T.OdometryConfig( + odometry_mode=T.OdometryMode.Multisensor, + multisensor_settings=T.OdometryMultisensorSettings(depth_camera_ids=[0], depth_scale_factor=1000.0), + ) + else: + cfg = T.OdometryConfig( + odometry_mode=T.OdometryMode.RGBD, + rgbd_settings=T.OdometryRGBDSettings(depth_camera_id=0, depth_scale_factor=1000.0), + ) + slam_cfg = None if args.odom_only else T.SlamConfig() + vslam.warm_up_gpu() + tracker = vslam.Tracker(rig, cfg, slam_cfg) + + k = int(np.searchsorted(seq.imu[:, 0], seq.t_ns[0], side="right")) if inertial else 0 + rows, odom_t, odom_T, slam_t, slam_T = [], [], [], [], [] + wall0 = time.perf_counter() + for t_ns, rp, dp in zip(seq.t_ns, seq.rgb, seq.depth): + rgb = cv2.cvtColor(cv2.imread(rp, cv2.IMREAD_COLOR), cv2.COLOR_BGR2RGB) + depth = cv2.imread(dp, cv2.IMREAD_UNCHANGED).astype(np.uint16) + if inertial: + j = int(np.searchsorted(seq.imu[:, 0], t_ns, side="right")) + for r in seq.imu[k:j]: + m = vslam.ImuMeasurement() + m.timestamp_ns = int(r[0]) + m.linear_accelerations = np.asarray(r[1:4]) + m.angular_velocities = np.asarray(r[4:7]) + tracker.register_imu_measurement(0, m) + k = j + if args.speed > 0: # feed on the sequence's clock + due = wall0 + (t_ns - seq.t_ns[0]) * 1e-9 / args.speed + wait = due - time.perf_counter() + if wait > 0: + time.sleep(wait) + t0 = time.perf_counter() + odom, slam = tracker.track(int(t_ns), [rgb], depths=[depth]) + ms = 1e3 * (time.perf_counter() - t0) + ok = odom.world_from_rig is not None + rows.append((int(t_ns), int(ok), ms)) + if ok: + odom_t.append(int(t_ns)) + odom_T.append(pose_to_T(odom.world_from_rig.pose)) + if slam is not None: + slam_t.append(int(t_ns)) + slam_T.append(pose_to_T(slam)) + + os.makedirs(args.out, exist_ok=True) + rgbdi.write_poses(os.path.join(args.out, "odom_poses.csv"), np.array(odom_t, np.int64), + np.array(odom_T) if odom_T else np.zeros((0, 4, 4))) + # the SLAM pose as track() returned it at the time (what a car would have had then) + main_t, main_T = (odom_t, odom_T) if args.odom_only else (slam_t, slam_T) + # SLAM poses only count on frames odometry tracked + if not args.odom_only: + tracked = set(odom_t) + keep = [i for i, t in enumerate(main_t) if t in tracked] + main_t, main_T = [main_t[i] for i in keep], [main_T[i] for i in keep] + rgbdi.write_poses(os.path.join(args.out, "poses.csv"), np.array(main_t, np.int64), + np.array(main_T) if main_T else np.zeros((0, 4, 4))) + with open(os.path.join(args.out, "frames.csv"), "w") as f: + f.write("t_ns,tracked,track_ms\n") + for r in rows: + f.write(f"{r[0]},{r[1]},{r[2]:.3f}\n") + try: + gpu = subprocess.run(["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"], capture_output=True, + text=True, timeout=10).stdout.strip().splitlines()[0] + except Exception: + gpu = "none" + meta = {"system": f"cuVSLAM {vslam.get_version()}", + "mode": ("Multisensor RGB-D + IMU" if inertial else "RGBD") + ("" if args.odom_only else " + SLAM"), + "speed": args.speed, "cpus": cpulimit.CPUS, + "gpu": gpu, "imu_noise_scale": args.imu_noise_scale, "sequence": os.path.abspath(args.seq), + "frames": len(rows), "tracked": len(main_t)} + with open(os.path.join(args.out, "meta.json"), "w") as f: + json.dump(meta, f, indent=1) + print(json.dumps(meta)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/vio_bench/run_orbslam3.py b/scripts/vio_bench/run_orbslam3.py new file mode 100644 index 0000000..c3e2de2 --- /dev/null +++ b/scripts/vio_bench/run_orbslam3.py @@ -0,0 +1,207 @@ +#!/usr/bin/env python3 +"""ORB-SLAM3 (the UTASR CUDA fork, through orbslam3_python) on an rgbdi sequence. + + python scripts/vio_bench/run_orbslam3.py --out [--no-imu] + +IMU_RGBD by default (RGBD with --no-imu). Each frame gets the IMU samples since the +previous one. Poses are taken as pilot_core's SLAMWorker publishes them: relative to the +map's origin keyframe, so the gravity re-rotations during IMU initialisation don't move +them. Writes poses.csv (tracked frames), frames.csv (every frame: tracking state, map id, +track time in ms, IMU initialised) and meta.json. ORB_SLAM3_CUDA=0 runs the CPU path. +""" + +from __future__ import annotations + +import argparse +import json +import os +import platform +import subprocess +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import cpulimit # noqa: E402,F401 (before cv2 and the SLAM module: sizes their thread pools) + +import cv2 +import numpy as np + +REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +sys.path.insert(0, REPO_ROOT) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import rgbdi # noqa: E402 + +SETTINGS = """%YAML:1.0 +File.version: "1.0" +Camera.type: "PinHole" +Camera1.fx: {fx:.6f} +Camera1.fy: {fy:.6f} +Camera1.cx: {cx:.6f} +Camera1.cy: {cy:.6f} +Camera1.k1: 0.0 +Camera1.k2: 0.0 +Camera1.p1: 0.0 +Camera1.p2: 0.0 +Camera.width: {width} +Camera.height: {height} +Camera.fps: {fps:.0f} +Camera.RGB: 1 +RGBD.DepthMapFactor: 1.0 +Stereo.b: {baseline:.6f} +Stereo.ThDepth: {th_depth:.3f} +ORBextractor.nFeatures: {features} +ORBextractor.scaleFactor: 1.2 +ORBextractor.nLevels: 8 +ORBextractor.iniThFAST: 20 +ORBextractor.minThFAST: 7 +Viewer.KeyFrameSize: 0.05 +Viewer.KeyFrameLineWidth: 1.0 +Viewer.GraphLineWidth: 0.9 +Viewer.PointSize: 2.0 +Viewer.CameraSize: 0.08 +Viewer.CameraLineWidth: 3.0 +Viewer.ViewpointX: 0.0 +Viewer.ViewpointY: -0.7 +Viewer.ViewpointZ: -1.8 +Viewer.ViewpointF: 500.0 +""" + +IMU_BLOCK = """IMU.T_b_c1: !!opencv-matrix + rows: 4 + cols: 4 + dt: f + data: [{T}] +IMU.InsertKFsWhenLost: {insert_lost} +IMU.UpstreamPolicy: {upstream_policy} +IMU.InitTime: {init_time:.3f} +IMU.EarlyLostTimeout: {early_lost:.3f} +IMU.NoiseGyro: {noise_gyro:g} +IMU.NoiseAcc: {noise_acc:g} +IMU.GyroWalk: {gyro_walk:g} +IMU.AccWalk: {acc_walk:g} +IMU.Frequency: {rate_hz:.1f} +""" + +_TRACKING_OK = 2 + + +def gpu_name() -> str: + try: + return subprocess.run(["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"], + capture_output=True, text=True, timeout=10).stdout.strip().splitlines()[0] + except Exception: + return "none" + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("seq") + ap.add_argument("--out", required=True) + ap.add_argument("--imu-noise-scale", type=float, default=1.0, + help="multiply calib.yaml's IMU noise densities and random walks (tuning)") + ap.add_argument("--no-imu", action="store_true", help="RGBD instead of IMU_RGBD") + ap.add_argument("--imu-init-time", type=float, default=1.0, + help="s of keyframes before the first IMU initialisation (IMU.InitTime; upstream 1.0)") + ap.add_argument("--early-lost-timeout", type=float, default=1.0, + help="s lost before inertial BA 2 after which the map is given up (IMU.EarlyLostTimeout; " + "upstream 5.0)") + ap.add_argument("--no-lost-keyframes", action="store_true", + help="IMU.InsertKFsWhenLost: 0 (no keyframes at the IMU-predicted pose while lost)") + ap.add_argument("--upstream-policy", action="store_true", + help="upstream ORB-SLAM3's inertial policy (IMU.UpstreamPolicy: 1): reset the map on a " + "tracking loss before the IMU is initialised (and before inertial BA 2), no " + "keyframes for weak visual tracking; default: the fork's depth-inertial one") + ap.add_argument("--features", type=int, default=1000) + ap.add_argument("--depth-baseline", type=float, + help="m, the virtual stereo baseline ORB-SLAM3 weighs depth with (Stereo.b); default " + "calib.yaml's depth_baseline_m, else the OAK-D's 0.075. Smaller = depth trusted less") + ap.add_argument("--close-depth", type=float, default=3.0, + help="m, depth below which points are 'close' (Stereo.ThDepth = this / baseline)") + ap.add_argument("--speed", type=float, default=1.0, + help="replay speed: frames are fed on the sequence's clock (1 = real time, as on the car), " + "0 = as fast as tracking allows (the mapping threads then fall behind)") + ap.add_argument("--cpus", type=int, help="pin to this many cores (cpulimit.py); default the cgroup's CPU cap") + ap.add_argument("--vocab", default=os.path.join(REPO_ROOT, "ORB_SLAM3/Vocabulary/ORBvoc.txt")) + args = ap.parse_args() + + import importlib + importlib.import_module("ssl") # see SLAMWorker.setup: libcrypto load order + import orbslam3_python as slam_mod + + seq = rgbdi.load(args.seq) + c = seq.calib + os.makedirs(args.out, exist_ok=True) + settings = os.path.join(args.out, "orbslam3_settings.yaml") + baseline = args.depth_baseline or float(c.get("depth_baseline_m", 0.075)) + with open(settings, "w") as f: + f.write(SETTINGS.format(fx=c["fx"], fy=c["fy"], cx=c["cx"], cy=c["cy"], width=c["width"], + height=c["height"], fps=c.get("fps", 30.0), features=args.features, + baseline=baseline, th_depth=args.close_depth / baseline)) + if not args.no_imu: + im = {k: (v * args.imu_noise_scale if k != "rate_hz" else v) for k, v in c["imu"].items()} + f.write(IMU_BLOCK.format(T=", ".join(f"{v:.9f}" for v in seq.T_imu_cam.ravel()), + upstream_policy=int(args.upstream_policy), + init_time=args.imu_init_time, insert_lost=int(not args.no_lost_keyframes), early_lost=args.early_lost_timeout, **im)) + + inertial = not args.no_imu + system = slam_mod.System(args.vocab, settings, slam_mod.IMU_RGBD if inertial else slam_mod.RGBD) + + imu = seq.imu + imu_s = imu.copy() + imu_s[:, 0] = imu[:, 0] * 1e-9 + k = 0 + if inertial: # samples before the first frame are not used + k = int(np.searchsorted(imu[:, 0], seq.t_ns[0], side="right")) + poses_t, poses_T, rows = [], [], [] + wall0 = time.perf_counter() + for i, (t_ns, rp, dp) in enumerate(zip(seq.t_ns, seq.rgb, seq.depth)): + rgb = cv2.cvtColor(cv2.imread(rp, cv2.IMREAD_COLOR), cv2.COLOR_BGR2RGB) + depth = cv2.imread(dp, cv2.IMREAD_UNCHANGED).astype(np.float32) * 1e-3 + batch = None + if inertial: + j = int(np.searchsorted(imu[:, 0], t_ns, side="right")) + batch = np.ascontiguousarray(imu_s[k:j]) + k = j + if args.speed > 0: # feed on the sequence's clock + due = wall0 + (t_ns - seq.t_ns[0]) * 1e-9 / args.speed + wait = due - time.perf_counter() + if wait > 0: + time.sleep(wait) + t0 = time.perf_counter() + Tcw = system.track_rgbd(rgb, depth, t_ns * 1e-9, batch) if inertial else \ + system.track_rgbd(rgb, depth, t_ns * 1e-9) + ms = 1e3 * (time.perf_counter() - t0) + state = int(system.get_tracking_state()) + map_id = int(system.map_info()[0]) + imu_init = bool(system.imu_initialized()) if inertial else False + rows.append((int(t_ns), state, map_id, ms, int(imu_init))) + if state == _TRACKING_OK: + Twc = np.linalg.inv(np.asarray(Tcw, dtype=np.float64)) + if inertial: + Twc = np.linalg.inv(np.asarray(system.origin_pose(), dtype=np.float64)) @ Twc + poses_t.append(int(t_ns)) + poses_T.append(Twc) + system.shutdown() + + rgbdi.write_poses(os.path.join(args.out, "poses.csv"), np.array(poses_t, np.int64), + np.array(poses_T) if poses_T else np.zeros((0, 4, 4))) + with open(os.path.join(args.out, "frames.csv"), "w") as f: + f.write("t_ns,state,map_id,track_ms,imu_initialized\n") + for r in rows: + f.write(f"{r[0]},{r[1]},{r[2]},{r[3]:.3f},{r[4]}\n") + meta = {"system": "ORB-SLAM3 (UTASR CUDA fork)", "mode": "IMU_RGBD" if inertial else "RGBD", + "cuda": os.environ.get("ORB_SLAM3_CUDA", "1") != "0", "gpu": gpu_name(), + "cpu": platform.processor() or platform.machine(), "features": args.features, + "depth_baseline_m": baseline, "speed": args.speed, "cpus": cpulimit.CPUS, + "imu_noise_scale": args.imu_noise_scale, "upstream_policy": args.upstream_policy, + "imu_init_time": args.imu_init_time, "early_lost_timeout": args.early_lost_timeout, + "sequence": os.path.abspath(args.seq), "frames": len(rows), "tracked": len(poses_t)} + with open(os.path.join(args.out, "meta.json"), "w") as f: + json.dump(meta, f, indent=1) + print(json.dumps(meta)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/vio_bench/score.py b/scripts/vio_bench/score.py new file mode 100644 index 0000000..edce62e --- /dev/null +++ b/scripts/vio_bench/score.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +"""Score RGB-D-inertial benchmark results against an rgbdi sequence's ground truth. + + python scripts/vio_bench/score.py [ ...] --out + +Per result (run_orbslam3.py / run_cuvslam.py output): + accuracy ATE: RMSE / median / max position error after one rigid (SE3, no scale: depth + fixes it) alignment of the whole run; drift: RPE over 1 s windows, + translation (m and % of distance) and rotation (deg) + coverage tracked frames / all frames; time from the first frame to the first pose + latency per-frame tracking call, ms: mean, p50, p95, p99, max (the first frame, which + builds the map, is left out) +Without a groundtruth.csv (the real track) only coverage and latency are scored; the +accuracy comes from markers.py. Writes summary.md, summary.json and trajectories.png. +""" + +from __future__ import annotations + +import argparse +import csv +import json +import os +import sys + +import numpy as np + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import rgbdi # noqa: E402 + + +def umeyama_se3(src: np.ndarray, dst: np.ndarray) -> np.ndarray: + """4x4 rigid T minimising |T src - dst|^2 (no scale).""" + mu_s, mu_d = src.mean(0), dst.mean(0) + U, _, Vt = np.linalg.svd((dst - mu_d).T @ (src - mu_s)) + S = np.eye(3) + S[2, 2] = np.sign(np.linalg.det(U @ Vt)) + R = U @ S @ Vt + T = np.eye(4) + T[:3, :3] = R + T[:3, 3] = mu_d - R @ mu_s + return T + + +def rot_angle_deg(R: np.ndarray) -> np.ndarray: + c = (np.trace(R, axis1=-2, axis2=-1) - 1.0) / 2.0 + return np.degrees(np.arccos(np.clip(c, -1.0, 1.0))) + + +def score(seq: rgbdi.Sequence, res_dir: str, window_s: float = 1.0) -> dict: + with open(os.path.join(res_dir, "meta.json")) as f: + meta = json.load(f) + t_est, T_est = rgbdi.read_poses(os.path.join(res_dir, "poses.csv")) + with open(os.path.join(res_dir, "frames.csv")) as f: + fr = list(csv.DictReader(f)) + ms = np.array([float(r["track_ms"]) for r in fr])[1:] + out = {"name": os.path.basename(os.path.normpath(res_dir)), **meta, + "frames": len(seq.t_ns), "tracked_frac": len(t_est) / max(len(seq.t_ns), 1), + "first_pose_s": float((t_est[0] - seq.t_ns[0]) * 1e-9) if len(t_est) else None, + "latency_ms": {"mean": float(ms.mean()), "p50": float(np.percentile(ms, 50)), + "p95": float(np.percentile(ms, 95)), "p99": float(np.percentile(ms, 99)), + "max": float(ms.max())}} + if "imu_initialized" in fr[0]: + init = [int(r["t_ns"]) for r in fr if r["imu_initialized"] == "1"] + out["imu_init_s"] = float((init[0] - seq.t_ns[0]) * 1e-9) if init else None + if "map_id" in fr[0]: + out["maps"] = len({r["map_id"] for r in fr if int(r["state"]) == 2}) + if len(t_est) < 3 or len(seq.gt_t_ns) == 0: + return out + + G, inside = rgbdi.interpolate_poses(seq.gt_t_ns, seq.gt_T, t_est) + t_est, T_est, G = t_est[inside], T_est[inside], G[inside] + A = umeyama_se3(T_est[:, :3, 3], G[:, :3, 3]) + P = A @ T_est + err = np.linalg.norm(P[:, :3, 3] - G[:, :3, 3], axis=1) + out["ate_m"] = {"rmse": float(np.sqrt(np.mean(err ** 2))), "median": float(np.median(err)), + "max": float(err.max())} + # RPE over window_s + ts = t_est * 1e-9 + j = np.searchsorted(ts, ts + window_s) + ok = j < len(ts) + i, j = np.nonzero(ok)[0], j[ok] + if len(i): + dG = np.linalg.inv(G[i]) @ G[j] + dP = np.linalg.inv(P[i]) @ P[j] + E = np.linalg.inv(dG) @ dP + et = np.linalg.norm(E[:, :3, 3], axis=1) + dist = np.linalg.norm(dG[:, :3, 3], axis=1) + moving = dist > 0.05 + out["rpe"] = {"window_s": window_s, "trans_rmse_m": float(np.sqrt(np.mean(et ** 2))), + "trans_pct": float(100 * np.median(et[moving] / dist[moving])) if moving.any() else None, + "rot_rmse_deg": float(np.sqrt(np.mean(rot_angle_deg(E[:, :3, :3]) ** 2)))} + out["_aligned"] = (t_est, P) + return out + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("seq") + ap.add_argument("results", nargs="+") + ap.add_argument("--out", required=True) + args = ap.parse_args() + + seq = rgbdi.load(args.seq) + scores = [score(seq, r) for r in args.results] + os.makedirs(args.out, exist_ok=True) + + def f(v, fmt="{:.3f}"): + return "–" if v is None else fmt.format(v) + + lines = [f"# RGB-D-inertial benchmark: {os.path.basename(os.path.normpath(args.seq))}", "", + f"{len(seq.t_ns)} frames, {(seq.t_ns[-1] - seq.t_ns[0]) * 1e-9:.1f} s; " + f"{seq.calib.get('source', '')}", "", + "| run | mode | GPU | tracked | first pose (s) | IMU init (s) | ATE RMSE (m) | ATE max (m) | " + "drift 1 s (m / %) | rot drift 1 s (deg) | latency mean / p50 / p95 / p99 / max (ms) |", + "|---|---|---|---|---|---|---|---|---|---|---|"] + for s in scores: + L, ate, rpe = s["latency_ms"], s.get("ate_m", {}), s.get("rpe", {}) + lines.append( + f"| {s['name']} | {s['mode']} | {s['gpu']} | {100 * s['tracked_frac']:.1f} % | {f(s['first_pose_s'], '{:.2f}')} | " + f"{f(s.get('imu_init_s'), '{:.1f}')} | {f(ate.get('rmse'))} | {f(ate.get('max'))} | " + f"{f(rpe.get('trans_rmse_m'))} / {f(rpe.get('trans_pct'), '{:.1f}')} | {f(rpe.get('rot_rmse_deg'), '{:.2f}')} | " + f"{L['mean']:.1f} / {L['p50']:.1f} / {L['p95']:.1f} / {L['p99']:.1f} / {L['max']:.1f} |") + with open(os.path.join(args.out, "summary.md"), "w") as fh: + fh.write("\n".join(lines) + "\n") + with open(os.path.join(args.out, "summary.json"), "w") as fh: + json.dump([{k: v for k, v in s.items() if not k.startswith("_")} for s in scores], fh, indent=1) + print("\n".join(lines)) + + if len(seq.gt_T) == 0: + return 0 # no ground truth (real track): accuracy is markers.py's + import matplotlib + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + fig, ax = plt.subplots(figsize=(8, 8)) + g = seq.gt_T[:, :3, 3] + # the plane the trajectory spans: drop the axis with the least spread (gravity for a car) + keep = np.sort(np.argsort(g.std(0))[1:]) + ax.plot(g[:, keep[0]], g[:, keep[1]], "k-", lw=2, label="ground truth") + for s in scores: + if "_aligned" in s: + p = s["_aligned"][1][:, :3, 3] + ax.plot(p[:, keep[0]], p[:, keep[1]], ".", ms=2, label=s["name"]) + ax.set_aspect("equal") + ax.legend() + fig.savefig(os.path.join(args.out, "trajectories.png"), dpi=110, bbox_inches="tight") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/vio_bench/sim_to_rgbdi.py b/scripts/vio_bench/sim_to_rgbdi.py new file mode 100644 index 0000000..1ef1f60 --- /dev/null +++ b/scripts/vio_bench/sim_to_rgbdi.py @@ -0,0 +1,209 @@ +#!/usr/bin/env python3 +"""AutoDRIVE sim run -> rgbdi sequence (rgbdi.py), the sim half of the RGB-D-inertial +benchmark (README.md here). + + python scripts/export_recording.py # -> /export + python scripts/vio_bench/sim_to_rgbdi.py --out + +The run must have been recorded with sim_depth (RGB-D: the camera upscaled, depth from +the LiDAR) and frame.sample_k: 1. The sim has no IMU worth the name (its telemetry +arrives at the frame rate), so the IMU is synthesised from the ground-truth vehicle pose +on the sim's own clock: resampled at --imu-rate, low-passed at --cutoff Hz with a +zero-phase filter (the sim's pose and clock jitter would otherwise differentiate into +metres per second squared of noise), differentiated, plus white noise and a random-walk +bias at the noise densities written to calib.yaml. Ground truth is the same smoothed +trajectory. The sequence starts after the last pose jump (the bench's reset to the line). +That IMU is cleaner and smoother than a real one; this sequence is for exercising the +benchmark, not for judging the IMU fusion. +""" + +from __future__ import annotations + +import argparse +import csv +import os +import shutil +import sys + +import cv2 +import numpy as np +import yaml +from scipy.signal import butter, filtfilt + +REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +sys.path.insert(0, REPO_ROOT) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import rgbdi # noqa: E402 +from workers.lidar_depth import CameraModel # noqa: E402 + +G = 9.81 +VEHICLE_Z = 0.0592 # m, the sim's vehicle frame (rear axle) above the floor (V1 Position z) +# consumer-grade MEMS (the cuVSLAM multisensor example's values; BMI270 / BNO086 class) +IMU_NOISE = {"noise_gyro": 1.6e-4, "gyro_walk": 2.2e-5, "noise_acc": 2.8e-3, "acc_walk": 8.6e-4} + + +def sim_log(sim_messages: str) -> tuple: + """The sim's new frames from sim_messages.csv: t_rx, continuous sim time, x, y, yaw. + V1 Lap Time restarts at every lap and reset, so a backwards step continues at the + median frame period. Positions and that clock agree (step / dt matches the reported + speed to a few %), unlike the receive times.""" + rows = [] + with open(sim_messages) as f: + for r in csv.DictReader(f): + if r["new_frame"] == "1": + rows.append([float(r[k]) for k in ("t_rx", "sim_time", "x", "y", "yaw")]) + a = np.array(rows) + d = np.diff(a[:, 1]) + period = float(np.median(d[d > 0])) + d = np.where((d <= 0) | (d > 1.0), period, d) + t_sim = np.concatenate([[0.0], np.cumsum(d)]) + return a[:, 0], t_sim, a[:, 2], a[:, 3], a[:, 4] + + +def to_sim_time(t_mono: np.ndarray, t_rx: np.ndarray, t_sim: np.ndarray, tol: float = 0.05) -> np.ndarray: + """Sim time of records written while handling the message received at t_rx (the latest + one at or before t_mono); NaN when there is none within tol seconds.""" + i = np.searchsorted(t_rx, t_mono, side="right") - 1 + out = np.full(len(t_mono), np.nan) + ok = (i >= 0) & (t_mono - t_rx[np.clip(i, 0, None)] <= tol) + out[ok] = t_sim[i[ok]] + return out + + +def T_vehicle_cam(cam: CameraModel) -> np.ndarray: + """Camera optical frame (x right, y down, z forward) in the vehicle frame (X forward, + Y left, Z up, at the rear axle), pitched down by cam.pitch_deg.""" + th = np.radians(cam.pitch_deg) + fwd = np.array([np.cos(th), 0.0, -np.sin(th)]) + down = np.array([-np.sin(th), 0.0, -np.cos(th)]) + right = np.cross(down, fwd) + T = np.eye(4) + T[:3, :3] = np.column_stack([right, down, fwd]) + T[:3, 3] = [cam.cam_x, 0.0, cam.cam_height - VEHICLE_Z] + return T + + +def smooth_trajectory(t: np.ndarray, xyz: np.ndarray, yaw: np.ndarray, rate: float, cutoff: float): + """Vehicle trajectory on a uniform grid at rate: (ts, xyz, yaw), zero-phase low-passed.""" + ts = np.arange(t[0], t[-1], 1.0 / rate) + raw = np.column_stack([np.interp(ts, t, xyz[:, k]) for k in range(3)] + [np.interp(ts, t, np.unwrap(yaw))]) + b, a = butter(4, cutoff / (rate / 2.0)) + sm = filtfilt(b, a, raw, axis=0, padtype="even") + return ts, sm[:, :3], sm[:, 3] + + +def synth_imu(ts: np.ndarray, xyz: np.ndarray, yaw: np.ndarray, rate: float, rng) -> np.ndarray: + """(M, 7) [t_s, f_body, w_body]: specific force and angular rate of the vehicle frame + (flat track: roll = pitch = 0) along the smoothed trajectory.""" + dt = 1.0 / rate + acc_w = np.gradient(np.gradient(xyz, dt, axis=0), dt, axis=0) + np.array([0.0, 0.0, G]) + c, s = np.cos(yaw), np.sin(yaw) + f_b = np.column_stack([c * acc_w[:, 0] + s * acc_w[:, 1], -s * acc_w[:, 0] + c * acc_w[:, 1], acc_w[:, 2]]) + w_b = np.column_stack([np.zeros_like(ts), np.zeros_like(ts), np.gradient(yaw, dt)]) + # white noise (density * sqrt(rate)) + random-walk bias + n = len(ts) + b_a = np.cumsum(rng.normal(0, IMU_NOISE["acc_walk"] * np.sqrt(dt), (n, 3)), axis=0) + b_g = np.cumsum(rng.normal(0, IMU_NOISE["gyro_walk"] * np.sqrt(dt), (n, 3)), axis=0) + f_b += b_a + rng.normal(0, IMU_NOISE["noise_acc"] * np.sqrt(rate), (n, 3)) + w_b += b_g + rng.normal(0, IMU_NOISE["noise_gyro"] * np.sqrt(rate), (n, 3)) + return np.column_stack([ts, f_b, w_b]) + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("run", help="run dir with export/ (scripts/export_recording.py) and config.yaml") + ap.add_argument("--out", required=True) + ap.add_argument("--imu-rate", type=float, default=200.0) + ap.add_argument("--cutoff", type=float, default=6.0, help="Hz, trajectory low-pass before differentiating") + ap.add_argument("--seed", type=int, default=0) + args = ap.parse_args() + + exp = os.path.join(args.run, "export") + with open(os.path.join(args.run, "config.yaml")) as f: + cfg = yaml.safe_load(f) + sd = cfg.get("sim_depth") or {} + if not sd: + raise SystemExit("the run was recorded without sim_depth: no depth to benchmark on") + cam = CameraModel.from_yaml(sd.get("camera", "sim_camera/camera.yaml"), scale=float(sd.get("scale", 2.0))) + + t_rx, t_sim, x, y, yaw = sim_log(os.path.join(exp, "sim_messages.csv")) + p_t, p_yaw = t_sim, yaw + p_xyz = np.column_stack([x, y, np.full_like(x, VEHICLE_Z)]) # flat track + # start after the last teleport (reset to the line, or a respawn after a wall hit): + # a step faster than any car speed + step_v = np.linalg.norm(np.diff(p_xyz, axis=0), axis=1) / np.diff(p_t) + jumps = np.nonzero(step_v > 15.0)[0] + if len(jumps): + start = np.searchsorted(p_t, p_t[jumps[-1] + 1] + 0.5) + print(f"{len(jumps)} pose jump(s); last at {p_t[jumps[-1] + 1]:.2f} s, starting at {p_t[start]:.2f} s") + p_t, p_xyz, p_yaw = p_t[start:], p_xyz[start:], p_yaw[start:] + + with open(os.path.join(exp, "camera.csv")) as f: + C = [r for r in csv.DictReader(f)] + c_t = to_sim_time(np.array([float(r["t_mono"]) for r in C]), t_rx, t_sim) + + g_t, g_xyz, g_yaw = smooth_trajectory(p_t, p_xyz, p_yaw, args.imu_rate, args.cutoff) + imu = synth_imu(g_t, g_xyz, g_yaw, args.imu_rate, np.random.default_rng(args.seed)) + + # ground truth: smoothed vehicle pose at each frame -> camera pose + Tvc = T_vehicle_cam(cam) + + # the car body (no depth there) is painted with shading that is fixed to the camera: + # features on it would read as no motion, so it is made flat + body = cam.load_mask() # at the output resolution + + os.makedirs(os.path.join(args.out, "rgb"), exist_ok=True) + os.makedirs(os.path.join(args.out, "depth"), exist_ok=True) + frames, gt_t, gt_T = [], [], [] + last = -1 + for r, t in zip(C, c_t): + if not np.isfinite(t) or t < g_t[0] or t > g_t[-1]: + continue + t_ns = int(round(t * 1e9)) + if t_ns <= last: + continue # one frame per sim time + last = t_ns + rgb, dep = f"rgb/{t_ns}.png", f"depth/{t_ns}.png" + img = cv2.imread(os.path.join(exp, r["rgb_png"]), cv2.IMREAD_COLOR) + if body is not None: + img[body] = 128 + cv2.imwrite(os.path.join(args.out, rgb), img) + shutil.copyfile(os.path.join(exp, r["depth_png_mm"]), os.path.join(args.out, dep)) + frames.append((t_ns, rgb, dep)) + psi = float(np.interp(t, g_t, g_yaw)) + Twv = np.eye(4) + Twv[:3, :3] = [[np.cos(psi), -np.sin(psi), 0], [np.sin(psi), np.cos(psi), 0], [0, 0, 1]] + Twv[:3, 3] = [np.interp(t, g_t, g_xyz[:, k]) for k in range(3)] + gt_t.append(t_ns) + gt_T.append(Twv @ Tvc) + + with open(os.path.join(args.out, "frames.csv"), "w") as f: + f.write("t_ns,rgb,depth\n") + for t, a, b in frames: + f.write(f"{t},{a},{b}\n") + imu_ns = imu.copy() + imu_ns[:, 0] = np.round(imu[:, 0] * 1e9) + rgbdi.write_imu(os.path.join(args.out, "imu.csv"), imu_ns) + rgbdi.write_poses(os.path.join(args.out, "groundtruth.csv"), np.array(gt_t), np.array(gt_T)) + + fx, fy, cx, cy = cam.intrinsics() + w, h = cam.size + calib = { + "source": f"AutoDRIVE sim run {os.path.abspath(args.run)}", + "notes": "depth from the 2-D LiDAR (walls extruded, floor plane); IMU synthesised from the " + "ground-truth pose (cubic spline) plus consumer-MEMS noise", + "width": w, "height": h, "fx": float(fx), "fy": float(fy), "cx": float(cx), "cy": float(cy), + "fps": float(1.0 / np.median(np.diff([fr[0] for fr in frames]) * 1e-9)), + "T_imu_cam": [[float(v) for v in row] for row in Tvc], + "imu": {"rate_hz": args.imu_rate, **IMU_NOISE}, + } + with open(os.path.join(args.out, "calib.yaml"), "w") as f: + yaml.safe_dump(calib, f, sort_keys=False) + print(f"{len(frames)} frames ({calib['fps']:.1f} fps), {len(imu)} IMU samples, " + f"{(frames[-1][0] - frames[0][0]) * 1e-9:.1f} s -> {args.out}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/shared_buffer/__init__.py b/shared_buffer/__init__.py index c5053b5..8925975 100644 --- a/shared_buffer/__init__.py +++ b/shared_buffer/__init__.py @@ -11,7 +11,7 @@ from .schema import SlotHeader, DTypeTag, HEADER_SIZE, HEADER_STRUCT from .typed import TypedRingBuffer from .frame_buffer import FrameBuffer -from .imu_buffer import IMUBuffer +from .imu_buffer import IMUBuffer, RawIMUBuffer from .segment_buffer import SegmentationBuffer from .pose_buffer import PoseBuffer from .control_buffer import ControlBuffer @@ -33,6 +33,7 @@ def buffer_name(prefix: Optional[str], base: str) -> str: BUFFER_CLASSES: Dict[int, Type[TypedRingBuffer]] = { DTypeTag.FRAME: FrameBuffer, DTypeTag.IMU: IMUBuffer, + DTypeTag.RAW_IMU: RawIMUBuffer, DTypeTag.SEGMENTATION: SegmentationBuffer, DTypeTag.POSE: PoseBuffer, DTypeTag.CONTROL: ControlBuffer, @@ -46,6 +47,7 @@ def buffer_name(prefix: Optional[str], base: str) -> str: BUFFER_CLASSES_BY_NAME: Dict[str, Type[TypedRingBuffer]] = { "frame": FrameBuffer, "imu": IMUBuffer, + "raw_imu": RawIMUBuffer, "segmentation": SegmentationBuffer, "pose": PoseBuffer, "control": ControlBuffer, @@ -74,6 +76,7 @@ def buffer_class_for(dtype_tag: int = 0, name: str = "") -> Optional[Type[TypedR "TypedRingBuffer", "FrameBuffer", "IMUBuffer", + "RawIMUBuffer", "SegmentationBuffer", "PoseBuffer", "ControlBuffer", diff --git a/shared_buffer/imu_buffer.py b/shared_buffer/imu_buffer.py index c8ba445..4ca23e3 100644 --- a/shared_buffer/imu_buffer.py +++ b/shared_buffer/imu_buffer.py @@ -7,6 +7,10 @@ feedback from the Arduino (pulse widths in us). NB: the OAK-D IMU path has no such feedback, so it puts gyro x / y (rad/s) in the last two slots instead. read_latest() -> (header, (9,) float32); decode(payload) -> (9,) float32. + +RawIMUBuffer: 6 x float32 (24 bytes), ax, ay, az (m/s^2), gx, gy, gz (rad/s) in the +IMU's own frame, stamped with the sample's capture time. Only the OAK-D path fills +it; it feeds ORB-SLAM3's inertial modes, which need all three gyro axes. """ from __future__ import annotations @@ -50,3 +54,36 @@ def write(self, imu_vector: np.ndarray, ts: Optional[float] = None) -> SlotHeade def decode(payload: bytes) -> np.ndarray: """payload -> (9,) float32 vector""" return np.frombuffer(payload, dtype=np.float32, count=_IMU_FLOATS).copy() + + +_RAW_IMU_FLOATS = 6 +_RAW_PAYLOAD_SIZE = _RAW_IMU_FLOATS * 4 # 24 bytes + + +class RawIMUBuffer(TypedRingBuffer): + + def __init__( + self, + slots: int = 256, + name: str = "raw_imu_buf", + create: bool = True, + ) -> None: + self._rb = SharedRingBuffer( + name=name, + slots=slots, + slot_payload_size=_RAW_PAYLOAD_SIZE, + dtype_tag=DTypeTag.RAW_IMU, + create=create, + ) + + def write(self, sample: np.ndarray, ts: Optional[float] = None) -> SlotHeader: + """sample is (6,): ax, ay, az, gx, gy, gz.""" + vec = np.asarray(sample, dtype=np.float32) + if vec.shape != (_RAW_IMU_FLOATS,): + raise ValueError(f"raw IMU sample must have shape ({_RAW_IMU_FLOATS},), got {vec.shape}") + return self._rb.write(vec.tobytes(), ts) + + @staticmethod + def decode(payload: bytes) -> np.ndarray: + """payload -> (6,) float32 sample""" + return np.frombuffer(payload, dtype=np.float32, count=_RAW_IMU_FLOATS).copy() diff --git a/shared_buffer/schema.py b/shared_buffer/schema.py index 4ef8056..8bdf337 100644 --- a/shared_buffer/schema.py +++ b/shared_buffer/schema.py @@ -20,6 +20,7 @@ class DTypeTag(IntEnum): STATE = 7 # estimated vehicle state (BEV) POINTCLOUD = 8 # N x 3 float32 SLAM map points BOUNDARY = 9 # outer + inner track polylines + RAW_IMU = 10 # accel xyz + gyro xyz, 6 floats (ORB-SLAM3 inertial modes) # seq_no, produced_ts, read_ts, payload_size, schema_version, dtype_tag, reserved. diff --git a/start.py b/start.py index ec6ec27..79abd5a 100644 --- a/start.py +++ b/start.py @@ -29,6 +29,7 @@ LidarBuffer, PointCloudBuffer, PoseBuffer, + RawIMUBuffer, SegmentationBuffer, StateBuffer, TrackBoundaryBuffer, @@ -44,6 +45,7 @@ ControlWorker, IMUWorker, LidarProjectionWorker, + SegScanWorker, MappingWorker, SLAMWorker, StateWorker, @@ -245,7 +247,7 @@ def _build(config: Dict[str, Any], buffers: List[Any]) -> Pipeline: # nothing would ever fill boundary_buf: the controller would wait (or crash) forever raise SystemExit( f"control_mode {control_mode_early!r} needs track boundaries: with the sim's ground-truth " - "pose, map a lap (--enable-slam, LiDAR mapping) or set use_saved_map") + "pose, map a lap (--enable-slam: LiDAR, or segmentation with lidar.enabled false) or set use_saved_map") # shared buffers buf_cfg = config.get("buffers", {}) @@ -288,6 +290,35 @@ def _build(config: Dict[str, Any], buffers: List[Any]) -> Pipeline: buffers.extend([frame_buf, imu_buf, seg_buf, pose_buf, ctrl_buf]) + # the OAK-D's own accel + gyro (all three axes) in raw_imu_buf, apart from imu_buf (which + # keeps whichever IMU use_oakd_imu picks, e.g. the external one for vehicle dynamics): + # for ORB-SLAM3 RGB-D-inertial, or raw_imu: true to record it (scripts/vio_bench) + slam_inertial = bool(enable_slam and config.get("slam", {}).get("inertial", False)) + raw_imu_buf = None + if slam_inertial or config.get("raw_imu", False): + if autodrive: + raise SystemExit("slam.inertial / raw_imu need the OAK-D's IMU; the AutoDRIVE sim has none") + raw_imu_buf = RawIMUBuffer( + slots=buf_cfg.get("raw_imu", {}).get("slots", 256), + name="raw_imu_buf", + create=True, + ) + buffers.append(raw_imu_buf) + + # the rear-of-car IMU (the Arduino's ICM-20948) as a 6-axis stream for the vehicle-state + # EKF (StateWorker -> control.ImuEKF); rear_imu.enabled, Arduino IMU path only + rear_imu_cfg = config.get("rear_imu", {}) or {} + rear_imu_buf = None + if rear_imu_cfg.get("enabled", False): + if autodrive or config.get("use_oakd_imu", False): + raise SystemExit("rear_imu needs the Arduino IMU over I2C (use_oakd_imu: false, not the sim)") + rear_imu_buf = RawIMUBuffer( + slots=buf_cfg.get("rear_imu", {}).get("slots", 256), + name="rear_imu_buf", + create=True, + ) + buffers.append(rear_imu_buf) + pc_buf = None kf_buf = None boundary_buf = None @@ -308,8 +339,15 @@ def _build(config: Dict[str, Any], buffers: List[Any]) -> Pipeline: create=True, ) buffers.extend([b for b in [pc_buf, boundary_buf] if b is not None]) - # the AutoDRIVE link always fills it (recordings, the mapping drive) - needs_lidar = autodrive + # pilot_core never uses a LiDAR (the car has none): the sim's is ignored, the drivable area + # comes from the camera's segmentation. Asking for it is an error, not a silent fallback + if (config.get("lidar") or {}).get("enabled", False): + raise SystemExit("lidar.enabled: pilot_core never uses a LiDAR (the car has none); " + "the sim maps from the segmentation (lidar.enabled: false)") + if str((config.get("sim_depth") or {}).get("depth", "none")) != "none": + raise SystemExit("sim_depth.depth: lidar would synthesise depth from the LiDAR; pilot_core never " + "uses a LiDAR (sim_depth.depth: none)") + needs_lidar = False if needs_lidar: lidar_buf = LidarBuffer( slots=buf_cfg.get("lidar", {}).get("slots", 16), @@ -414,6 +452,7 @@ def _build(config: Dict[str, Any], buffers: List[Any]) -> Pipeline: checkpoint_counter=counters["checkpoint"], log_dir=rec_dir, sim_depth=config.get("sim_depth"), + pose_degrade=config.get("sim_pose_degrade"), ) ) logger.info(f"AutoDRIVE sim link on {sim_host}:{sim_port}") @@ -427,9 +466,10 @@ def _build(config: Dict[str, Any], buffers: List[Any]) -> Pipeline: fps=fps, resolution=resolution, imu_buffer=imu_buf if oakd_imu_via_camera else None, + raw_imu_buffer=raw_imu_buf, settings_path=slam_cfg.get("settings", "orbslam_oakd_rgbd.yaml"), **{k: v for k, v in config.get("camera", {}).items() - if k in ("max_exposure_us", "extended_disparity", "frame_timeout_s")}, + if k in ("max_exposure_us", "extended_disparity", "frame_timeout_s", "imu_rate_hz")}, ) ) if not oakd_imu_via_camera: @@ -437,14 +477,20 @@ def _build(config: Dict[str, Any], buffers: List[Any]) -> Pipeline: IMUWorker( name="imu", output_buffer=imu_buf, + raw_output_buffer=rear_imu_buf, i2c_address=i2c_address, i2c_bus=i2c_bus, poll_hz=config.get("imu_poll_hz", 100.0), ) ) - # segmentation: the mapping drive's scan when there's no LiDAR (control/seg_scan.py); off unless vision.enabled - if vision_cfg.get("enabled", False): + # segmentation: the mapping drive's scan and the map's walls (control/seg_scan.py); off unless + # vision.enabled. In the sim only for a mapping lap: racing on a saved map nothing reads it + sim_mapping_lap = autodrive and enable_slam and not use_saved_map + run_vision = vision_cfg.get("enabled", False) and (not autodrive or sim_mapping_lap) + if vision_cfg.get("enabled", False) and not run_vision: + logger.info("Segmentation off: racing on a saved map, nothing would read it") + if run_vision: workers.append( VisionWorker( name="vision", @@ -465,7 +511,7 @@ def _build(config: Dict[str, Any], buffers: List[Any]) -> Pipeline: # the mapping drive's scan: the LiDAR, or without one (the car) the segmentation-edge # scan (control/seg_scan.py). seg_scan.source: segmentation forces it, e.g. in the sim seg_scan_cfg = dict(config.get("seg_scan", {})) - scan_source = seg_scan_cfg.pop("source", "auto") + scan_source = seg_scan_cfg.pop("source", "segmentation") if scan_source not in ("auto", "segmentation"): raise SystemExit(f"seg_scan.source must be auto or segmentation, not {scan_source!r}") use_seg_scan = scan_source == "segmentation" or lidar_buf is None @@ -473,12 +519,37 @@ def _build(config: Dict[str, Any], buffers: List[Any]) -> Pipeline: and use_seg_scan and not vision_cfg.get("enabled", False)): raise SystemExit("track_control.mapping_drive without a LiDAR drives on the segmentation-edge " "scan, which needs vision.enabled: true") + seg_scan_memory_s = float(seg_scan_cfg.pop("memory_s", 1.5)) seg_scan_cfg.setdefault("camera_settings", vision_cfg.get( "camera_settings", slam_cfg.get("settings", "orbslam_oakd_rgbd.yaml"))) for key in ("camera_height", "camera_pitch"): # one camera mount, shared with depth_ftg if key in depth_ftg_cfg: seg_scan_cfg.setdefault(key, depth_ftg_cfg[key]) + # a mapping lap on the car or in the sim: one SegScanWorker builds the scan of the + # segmentation's track edge, with a short memory of edges that have left the camera's view; + # the mapping drive drives on it, and the mapping lap's walls come from its raw scans + wall_source = mapping_cfg.get("wall_source", "occupancy") + if wall_source not in ("cloud", "occupancy"): + raise SystemExit(f"mapping.wall_source must be cloud or occupancy, not {wall_source!r}") + if wall_source == "occupancy" and enable_slam and not use_saved_map and not run_vision: + raise SystemExit("mapping.wall_source occupancy maps from the segmentation-edge scan, which needs " + "vision.enabled: true (or mapping.wall_source: cloud for SLAM map points)") + seg_scan_buf = seg_raw_buf = None + scan_offset = list(mapping_cfg.get("scan_offset", [0.0, 0.0, 0.0])) + if lidar_buf is None and run_vision and enable_slam and not use_saved_map: + seg_scan_buf = LidarBuffer(slots=16, name="seg_scan_buf", create=True) + buffers.append(seg_scan_buf) + if wall_source == "occupancy": + seg_raw_buf = LidarBuffer(slots=64, name="seg_raw_buf", create=True) + buffers.append(seg_raw_buf) + workers.append(SegScanWorker(name="seg_scan", segment_buffer=seg_buf, frame_buffer=frame_buf, + output_buffer=seg_scan_buf, raw_output_buffer=seg_raw_buf, + seg_scan=seg_scan_cfg, pose_buffer=pose_buf, + memory_s=seg_scan_memory_s, scan_origin=scan_offset[:2], + bev_axes=mapping_cfg.get("bev_axes", [0, 2]), + forward_axis=mapping_cfg.get("forward_axis", 2))) + # control: track modes need a pose source; depth_ftg / vae / bc only frame_buf armed_event = mp.Event() if control_mode in TRACK_MODES and has_pose_source: @@ -491,15 +562,15 @@ def _build(config: Dict[str, Any], buffers: List[Any]) -> Pipeline: state_buffer=state_buf, boundary_buffer=boundary_buf, mapping_done_event=mapping_done_event, + jump_reset_m=(config.get("estimator") or {}).get("jump_reset_m"), track_config=config.get("track_control", {}), safety=safety_cfg, vehicle_params=config.get("vehicle_params", "vehicle_params.yaml"), frame_buffer=frame_buf, camera_settings=slam_cfg.get("settings", "orbslam_oakd_rgbd.yaml"), depth_ftg_config=depth_ftg_cfg, - lidar_buffer=None if use_seg_scan else lidar_buf, - segment_buffer=seg_buf if vision_cfg.get("enabled", False) else None, - seg_scan=seg_scan_cfg, + lidar_buffer=seg_scan_buf if seg_scan_buf is not None else (None if use_seg_scan else lidar_buf), + scan_name="segmentation-edge scan with edge memory (SegScanWorker)" if seg_scan_buf is not None else None, ) ) elif control_mode in ("depth_ftg", "vae", "bc"): @@ -534,8 +605,12 @@ def _build(config: Dict[str, Any], buffers: List[Any]) -> Pipeline: output_buffer=state_buf, bev_axes=mapping_cfg.get("bev_axes", [0, 2]), forward_axis=mapping_cfg.get("forward_axis", 2), - use_pose_speed=sim_pose, + # the sim's own velocity is not fused: the car has no speed sensor, its speed + # comes from the poses (PoseEKF) or the rear IMU (ImuEKF) + use_pose_speed=False, estimator=config.get("estimator", {}), + rear_imu_buffer=rear_imu_buf, + rear_imu={k: v for k, v in rear_imu_cfg.items() if k != "enabled"}, rate_hz=config.get("control_rate_hz", 50.0), ) ) @@ -557,22 +632,39 @@ def _build(config: Dict[str, Any], buffers: List[Any]) -> Pipeline: ) # SLAM + mapping - if enable_slam and sim_pose: - # ground-truth pose mode: 2D LIDAR scan -> world-frame 3D points - lidar_cfg = config.get("lidar", {}) + if enable_slam and sim_pose and wall_source == "cloud": + # ground-truth pose mode: a 2-D scan -> world-frame 3D points: the LiDAR's, or without + # one the scan of the segmentation's track edge (SegScanWorker), from the camera + lidar_cfg = config.get("lidar", {}) or {} + scan_buf, scan_extra = lidar_buf, {} + if lidar_buf is None: + if seg_scan_buf is None: + raise SystemExit("mapping without a LiDAR (lidar.enabled: false) needs the segmentation: " + "vision.enabled: true") + scan_buf = seg_scan_buf + # the scan origin's mount in the vehicle frame; z lifts the edge (a wall's base) into + # MappingWorker's wall-height band. Floor-placed edges are good to ~2 m (5 cm median + # against the LiDAR's walls, 96 % within 15 cm; 66 % at any range) + scan_extra["scan_offset"] = scan_offset + scan_extra["range_max_override"] = float(mapping_cfg.get("scan_range_max", 2.0)) workers.append( LidarProjectionWorker( - name="lidar_proj", - lidar_buffer=lidar_buf, + name="lidar_proj" if lidar_buf is not None else "seg_proj", + lidar_buffer=scan_buf, pose_buffer=pose_buf, output_buffer=pc_buf, range_min=lidar_cfg.get("range_min", 0.1), - range_max=lidar_cfg.get("range_max", 9.5), + range_max=scan_extra.pop("range_max_override", lidar_cfg.get("range_max", 9.5)), voxel_size=lidar_cfg.get("voxel_size", 0.10), move_threshold=lidar_cfg.get("move_threshold", 0.05), + **scan_extra, ) ) - logger.info("Using the sim's ground-truth pose + LIDAR projection for the point cloud") + logger.info("Using the sim's ground-truth pose + " + + ("LiDAR" if lidar_buf is not None else "segmentation-edge scans (no LiDAR)") + + " for the point cloud") + elif enable_slam and sim_pose: + logger.info("Using the sim's ground-truth pose + the segmentation-edge scans' occupancy grid for the walls") elif enable_slam: workers.append( SLAMWorker( @@ -591,6 +683,8 @@ def _build(config: Dict[str, Any], buffers: List[Any]) -> Pipeline: loop_event=loop_event, localize_event=localize_event, warmup_frames=slam_cfg.get("warmup_frames", 15), + inertial=slam_inertial, + raw_imu_buffer=raw_imu_buf, ) ) @@ -603,6 +697,10 @@ def _build(config: Dict[str, Any], buffers: List[Any]) -> Pipeline: keyframe_buffer=kf_buf, map_reset_event=map_reset_event, boundary_buffer=boundary_buf, + wall_source=wall_source, + scan_buffer=seg_raw_buf, + scan_offset=scan_offset, + occupancy=mapping_cfg.get("occupancy", {}), loop_event=loop_event, mapping_done_event=mapping_done_event, boundary_min_points=mapping_cfg.get("boundary_min_points", 50), @@ -623,7 +721,8 @@ def _build(config: Dict[str, Any], buffers: List[Any]) -> Pipeline: # recording_config..{sample_k, top_n, on_full, keep_files} override per buffer rec_cfg = config.get("recording_config", {}) candidates = { - "frame": frame_buf, "imu": imu_buf, "segmentation": seg_buf if vision_cfg.get("enabled", False) else None, + "frame": frame_buf, "imu": imu_buf, "raw_imu": raw_imu_buf, "rear_imu": rear_imu_buf, + "segmentation": seg_buf if vision_cfg.get("enabled", False) else None, "pose": pose_buf, "control": ctrl_buf, "actuation": act_buf, "pointcloud": pc_buf, "keyframes": kf_buf, "boundary": boundary_buf, "state": state_buf, "lidar": lidar_buf, @@ -714,6 +813,15 @@ def main() -> None: logger.info("Outputs are neutral until armed.") logger.info("=" * 60) + # unattended sim runs (competition container): armed from the start, re-armed after a + # critical worker restarts. Never on the car, where only the operator arms. + auto_arm = bool(config.get("auto_arm", False)) + if auto_arm: + if config.get("sim") != "autodrive": + raise SystemExit("auto_arm is only allowed with sim: autodrive") + _armed_event.set() + logger.warning("ARMED automatically (auto_arm)") + try: _mapping_announced = False _next_health_check = 0.0 @@ -788,6 +896,9 @@ def main() -> None: new_p.start() _processes[i] = new_p logger.info(f"Restarted worker: {w.name} (new pid={new_p.pid})") + if auto_arm and w.name in CRITICAL_WORKERS and not _armed_event.is_set(): + _armed_event.set() + logger.warning("Re-ARMED automatically (auto_arm)") except KeyboardInterrupt: pass finally: diff --git a/tests/test_autodrive_worker.py b/tests/test_autodrive_worker.py index 0e8cbdd..6caeac0 100644 --- a/tests/test_autodrive_worker.py +++ b/tests/test_autodrive_worker.py @@ -283,9 +283,10 @@ def run(seconds): @pytest.mark.slow -def test_closed_loop_mapping_lap_then_pure_pursuit(tmp_path, monkeypatch): - """start.build_pipeline(config_autodrive.yaml) + the fake sim: the LiDAR gap follower - drives the mapping lap, auto loop closure extracts the boundaries, pure_pursuit laps.""" +def test_closed_loop_pure_pursuit_on_a_saved_map(tmp_path, monkeypatch): + """start.build_pipeline(config_autodrive.yaml) + the fake sim, no LiDAR: pure_pursuit laps + on a saved map of the fake track, with the state estimated from the poses alone. (The + mapping lap needs the camera's segmentation model, not in the repo: it is checked live.)""" import start suffix = _uid() @@ -296,13 +297,18 @@ def test_closed_loop_mapping_lap_then_pure_pursuit(tmp_path, monkeypatch): lambda *a, _cls=cls, **kw: _cls(*a, **{**kw, "name": f"{kw['name']}_{suffix}"})) port = _free_port() config = start.load_config(os.path.join(REPO_ROOT, "config_autodrive.yaml")) - config.update(sim_host="127.0.0.1", sim_port=port, enable_slam=True, recording=True, + fake = FakeAutoDRIVE(port, rate_hz=20.0, camera=False, lidar=False) + os.makedirs(tmp_path / "map") + np.save(tmp_path / "map" / "outer_line.npy", fake.outer) + np.save(tmp_path / "map" / "inner_line.npy", fake.inner) + config.update(sim_host="127.0.0.1", sim_port=port, enable_slam=False, use_saved_map=True, + saved_map_path=str(tmp_path / "map"), recording=True, recording_path=str(tmp_path / "rec"), sim_camera=False) - config["mapping"]["boundary_save_path"] = str(tmp_path / "map") + config.setdefault("track_control", {}).pop("raceline_path", None) # the centre-line p = start.build_pipeline(config) + assert p.mapping_done_event.is_set() and not any(w.name in ("vision", "seg_scan") for w in p.workers) procs = [] - fake = FakeAutoDRIVE(port, rate_hz=20.0, camera=False) try: for w in p.workers: proc = mp.Process(target=w.run, name=w.name) @@ -311,12 +317,10 @@ def test_closed_loop_mapping_lap_then_pure_pursuit(tmp_path, monkeypatch): fake.start() # only after forking: a running client thread can deadlock a fork _wait(lambda: fake.stats.connected and fake.stats.sent > 10, 20.0, "sim connected") p.armed_event.set() - _wait(lambda: p.mapping_done_event.is_set(), 90.0, "mapping lap + boundaries") laps_at_mapping = fake.lap_count # counted on the pilot_core side: the sim's lap counter reached the shared value _wait(lambda: p.counters["lap"].value >= laps_at_mapping + 2, 90.0, "two pure_pursuit laps") assert fake.collisions == 0, f"{fake.collisions} collisions" - assert os.path.isfile(tmp_path / "map" / "outer_line.npy") with open(os.path.join(p.recording_dir, "sim_events.jsonl")) as f: assert sum(json.loads(line)["event"] == "lap" for line in f) >= 2 finally: diff --git a/tests/test_imu_ekf.py b/tests/test_imu_ekf.py new file mode 100644 index 0000000..0ff7de1 --- /dev/null +++ b/tests/test_imu_ekf.py @@ -0,0 +1,135 @@ +"""control.ImuEKF: IMU-driven planar EKF with late SLAM poses (rear-IMU state estimation).""" + +from __future__ import annotations + +import numpy as np +import pytest + +from control import ImuEKF, ImuEstimatorConfig, PoseEKF + + +def _circle(t: np.ndarray, v: float = 3.0, r: float = 1.0): + """IMU point on a circle at speed v, yaw rate r, no slip: pose and body-frame IMU.""" + yaw = r * t + R = v / r + x, y = R * np.sin(yaw), R * (1 - np.cos(yaw)) + imu = np.column_stack([np.zeros_like(t), np.full_like(t, v * r), np.full_like(t, r)]) # ax, ay, gz + return x, y, yaw, imu + + +def _run(ekf, pose_period=1 / 30, latency=0.03, gap=None, T=6.0): + t_imu = np.arange(0, T, 0.01) + x, y, yaw, imu = _circle(t_imu) + t_pose = np.arange(0, T, pose_period) + px, py, pyaw, _ = _circle(t_pose) + events = [(t, 0, i) for i, t in enumerate(t_imu)] + events += [(t + latency, 1, i) for i, t in enumerate(t_pose) if gap is None or not (gap[0] <= t < gap[1])] + errs = [] + for t_arr, kind, i in sorted(events): + if kind == 0: + if hasattr(ekf, "update_imu"): + ekf.update_imu(t_imu[i], *imu[i]) + st = ekf.predict_to(t_imu[i]) + if st is not None and t_imu[i] > 1.0: + errs.append((t_imu[i], np.hypot(st.x - x[i], st.y - y[i]))) + else: + ekf.update_pose(t_pose[i], px[i], py[i], pyaw[i]) + return np.array(errs) + + +def test_tracks_a_circle_with_late_poses(): + e = _run(ImuEKF()) + assert e[:, 1].max() < 0.02 + + +def test_bridges_a_pose_gap_better_than_the_pose_only_ekf(): + gap = (3.0, 3.5) + imu = _run(ImuEKF(), gap=gap) + pose = _run(PoseEKF(), gap=gap) + in_gap = lambda e: e[(e[:, 0] >= gap[0]) & (e[:, 0] < gap[1] + 0.1), 1] + assert in_gap(imu).max() < 0.03 + assert in_gap(pose).max() > 3 * in_gap(imu).max() + + +def test_a_late_pose_gives_the_same_state_as_an_on_time_one(): + a, b = ImuEKF(), ImuEKF() + t = np.arange(0, 2, 0.01) + x, y, yaw, imu = _circle(t) + for ekf in (a, b): + ekf.update_pose(0.0, x[0], y[0], yaw[0]) + for i in range(1, 100): # a: pose at t=0.5 applied in order + a.update_imu(t[i], *imu[i]) + if i == 50: + a.update_pose(t[50], x[50], y[50], yaw[50]) + for i in range(1, 100): # b: the same pose arrives at t=0.99 + b.update_imu(t[i], *imu[i]) + b.update_pose(t[50], x[50], y[50], yaw[50]) + np.testing.assert_allclose(a.x, b.x, atol=1e-9) + np.testing.assert_allclose(a.P, b.P, atol=1e-9) + + +def test_estimates_sideslip(): + """Body drifting sideways at 0.5 m/s while going 3 m/s straight: vy is observed through poses + (without the no-slip pseudo-measurement, which is for a rear axle).""" + ekf = ImuEKF(ImuEstimatorConfig(vy_std=None)) + for k in range(300): + t = k * 0.01 + ekf.update_imu(t, 0.0, 0.0, 0.0) + if k % 3 == 0: + ekf.update_pose(t, 3.0 * t, 0.5 * t, 0.0) + assert ekf.x[4] == pytest.approx(0.5, abs=0.05) + assert ekf.sideslip == pytest.approx(np.arctan2(0.5, 3.0), abs=0.02) + + +def test_invalid_without_poses(): + ekf = ImuEKF(ImuEstimatorConfig(stale_after=0.5)) + assert ekf.predict_to(0.0) is None + ekf.update_pose(0.0, 0.0, 0.0, 0.0) + assert ekf.predict_to(0.4) is not None and ekf.predict_to(0.6) is None + + +def test_rejects_an_outlier_pose_and_reanchors_on_a_lasting_offset(): + ekf = ImuEKF() + t = np.arange(0, 3, 0.01) + x, y, yaw, imu = _circle(t) + for i, ti in enumerate(t): + ekf.update_imu(ti, *imu[i]) + if i % 3 == 0: + off = 1.0 if 1.5 <= ti < 1.6 else 0.0 # a 0.1 s burst of poses 1 m off + ekf.update_pose(ti, x[i] + off, y[i], yaw[i]) + assert ekf.rejected > 0 + assert np.hypot(ekf.x[0] - x[-1], ekf.x[1] - y[-1]) < 0.05 + ekf = ImuEKF(ImuEstimatorConfig(gate_reset_s=0.5)) + for i, ti in enumerate(t): # SLAM moves its frame by 1 m for good + ekf.update_imu(ti, *imu[i]) + if i % 3 == 0: + ekf.update_pose(ti, x[i] + (1.0 if ti >= 1.5 else 0.0), y[i], yaw[i]) + assert abs(ekf.x[0] - (x[-1] + 1.0)) < 0.05 + + +def test_a_pose_before_any_imu_then_a_late_pose(): + """The first pose can come before the first IMU sample; replaying from it must work.""" + ekf = ImuEKF() + ekf.update_pose(0.0, 0.0, 0.0, 0.0) + for k in range(1, 20): + ekf.update_imu(k * 0.01, 0.0, 0.0, 0.0) + ekf.update_pose(0.005, 0.0, 0.0, 0.0) # late, between the first pose and the first IMU sample + assert np.isfinite(ekf.x).all() + + +def test_pose_ekf_restarts_standing_still_after_a_respawn_jump(): + """A sim respawn moves the car 0.7 m back between two poses: differencing it gave a + huge speed and yaw rate, which steered the car into the wall again after every respawn.""" + from control import EstimatorConfig + + for jump_reset, expect_reset in ((None, False), (0.4, True)): + ekf = PoseEKF(EstimatorConfig(jump_reset_m=jump_reset)) + for k in range(30): # 3 m/s straight along x + ekf.update_pose(k / 30, 3.0 * k / 30, 0.0, 0.0) + ekf.update_pose(30 / 30, 3.0 * 29 / 30 - 0.7, 0.05, -0.5) # respawned back and turned + st = ekf.predict_to(30 / 30 + 0.02) + if expect_reset: + assert ekf.jumps == 1 and st.v == 0.0 and st.yaw_rate == 0.0 + assert st.yaw == pytest.approx(-0.5) + else: + assert abs(st.yaw_rate) > 1.0 or abs(st.v - 3.0) > 1.0 diff --git a/tests/test_imu_i2c.py b/tests/test_imu_i2c.py index b71a40c..e2c8082 100644 --- a/tests/test_imu_i2c.py +++ b/tests/test_imu_i2c.py @@ -116,3 +116,37 @@ def test_worker_survives_oserror(monkeypatch): finally: w.teardown() ib.unlink() + + +def test_raw_parse_converts_units(): + from workers.imu_worker import parse_i2c_raw + + raw = parse_i2c_raw(_frame(acc_g=(0.5, -0.25, 1.0))) # gyro in _frame: 0.1, 0.2, 0.3 deg/s + np.testing.assert_allclose(raw[:3], [0.5 * 9.80665, -0.25 * 9.80665, 9.80665], rtol=1e-6) + np.testing.assert_allclose(raw[3:], np.radians([0.1, 0.2, 0.3]), rtol=1e-6) + assert parse_i2c_raw(b"\x01\x02\x03\x04" + b"\xff" * 56) is None + + +def test_worker_writes_each_new_rear_imu_sample_once(monkeypatch): + from shared_buffer import RawIMUBuffer + + rb = RawIMUBuffer(slots=16, name=f"rear_{uuid.uuid4().hex[:8]}", create=True) + a, b = _frame(acc_g=(0.0, 0.0, 1.0)), _frame(acc_g=(0.1, 0.0, 1.0)) + fake = _FakeSMBus2([a, a, b, b, b]) # the Jetson polls faster than new samples come + monkeypatch.setattr(imu_mod, "smbus2", fake) + ib = IMUBuffer(slots=8, name=f"imu_i2c_{uuid.uuid4().hex[:8]}", create=True) + w = IMUWorker(name="imu", output_buffer=ib, raw_output_buffer=rb, i2c_address=0x08, i2c_bus=1, poll_hz=1000) + w._logger = MagicMock() + w.setup() + try: + for _ in range(5): + w._next_poll = 0.0 + w.step() + recs = rb.read_since(0) + assert len(recs) == 2 + assert recs[1][1][0] == pytest.approx(0.1 * 9.80665, rel=1e-6) + assert len(ib.read_since(0)) == 5 # imu_buf keeps every poll, as before + finally: + w.teardown() + ib.unlink() + rb.unlink() diff --git a/tests/test_jetson_selftest.py b/tests/test_jetson_selftest.py new file mode 100644 index 0000000..d8ea1f5 --- /dev/null +++ b/tests/test_jetson_selftest.py @@ -0,0 +1,26 @@ +"""scripts/jetson_selftest.py on any machine: the hardware-free checks pass.""" + +from __future__ import annotations + +import os +import subprocess +import sys + +from tests.conftest import REPO_ROOT + +SCRIPT = os.path.join(REPO_ROOT, "scripts", "jetson_selftest.py") + + +def _run(*args): + return subprocess.run([sys.executable, SCRIPT, *args], capture_output=True, text=True, timeout=60) + + +def test_hardware_free_checks_pass(): + r = _run("--only", "shm,buffers") + assert r.returncode == 0, r.stdout + r.stderr + assert r.stdout.count("PASS") == 2 + + +def test_unknown_check_is_an_error(): + r = _run("--only", "warp_drive") + assert r.returncode == 2 and "unknown check" in r.stderr diff --git a/tests/test_lidar_depth.py b/tests/test_lidar_depth.py index 9bf90fd..a4c378f 100644 --- a/tests/test_lidar_depth.py +++ b/tests/test_lidar_depth.py @@ -73,8 +73,9 @@ def on_outline(im): assert filled - no_car <= (with_block - no_car) / 4 -def test_autodrive_worker_writes_rgbd_from_lidar(): - """sim_depth on: a sim message becomes an upscaled RGB-D frame for SLAMWorker.""" +def test_autodrive_worker_prepares_frames_without_the_lidar(): + """sim_depth (depth: none, the default): a sim message becomes the upscaled frame the + segmentation was trained on, car body painted out, with no depth: the LiDAR is not read.""" import logging import uuid @@ -91,11 +92,12 @@ def test_autodrive_worker_writes_rgbd_from_lidar(): w._frame_buf = fb w._depth_fn = LidarDepth(CameraModel.from_yaml("sim_camera/camera.yaml", scale=2)) w._depth_clahe = True - w._write_rgbd(autodrive_to_internal(FakeAutoDRIVE(port=1).telemetry())) + assert w._depth_source == "none" + msg = autodrive_to_internal(FakeAutoDRIVE(port=1).telemetry()) + msg.pop("lidar", None) # no LiDAR needed + w._write_rgbd(msg) _, rgb, depth = fb.read_latest() assert rgb.shape == (216, 384, 3) and depth.shape == (216, 384) - assert (depth > 0).mean() > 0.2 # floor / walls below the horizon - assert not depth[w._depth_fn.mask].any() # nothing on the car body - assert depth.max() <= 10.0 + assert not depth.any() # no depth at all finally: fb.unlink() diff --git a/tests/test_mapping_boundaries.py b/tests/test_mapping_boundaries.py index 0de9913..d43db46 100644 --- a/tests/test_mapping_boundaries.py +++ b/tests/test_mapping_boundaries.py @@ -230,6 +230,15 @@ def drive(x, y): drive(*p) assert w._loop_event.is_set() + # a respawn checkpoint can be 1.3 m off the path just driven: the lap goes on + w._loop_event.clear() + w._bev_trajectory, w._path_s, w._path_length = [], [], 0.0 + w._max_dist_from_start, w._closest_start = 0.0, None + for p in circle[:100]: + drive(*p) + drive(*(circle[80] * (1 + 1.3 / 3))) + assert len(w._bev_trajectory) == 81 and tuple(w._bev_trajectory[0][:2]) == pytest.approx(tuple(circle[0])) + # a reset to somewhere off the path (the car parked elsewhere, then 'r'): the lap # restarts at the new pose instead of keeping a stale start point w._loop_event.clear() diff --git a/tests/test_occupancy_map.py b/tests/test_occupancy_map.py new file mode 100644 index 0000000..1a4b48a --- /dev/null +++ b/tests/test_occupancy_map.py @@ -0,0 +1,199 @@ +"""control/occupancy_map.py and MappingWorker's occupancy wall source: a ring track (walls at +r = 2.0 and 3.0 m) scanned 45 deg either side of ahead, lap driven at r = 2.5 m (from there +the inner wall is first seen 37 deg off the heading). +Walls land within about 0.1 m, as on the compete track (docs/results.md).""" + +from __future__ import annotations + +import multiprocessing as mp +import time +import uuid +from unittest.mock import MagicMock + +import numpy as np +import pytest + +from control.lidar_gap import ANGLE_INCREMENT, ANGLE_MIN +from control.occupancy_map import OccupancyConfig, OccupancyTrackMapper +from control.track import TrackModel + +ANG = ANGLE_MIN + np.arange(1080) * ANGLE_INCREMENT +R_IN, R_OUT, R_PATH = 2.0, 3.0, 2.5 +VIEW = np.radians(45) + + +def _ray_circle(o: np.ndarray, d: np.ndarray, r: float) -> np.ndarray: + """Nearest positive hit distance of rays o + t d (d unit, (N, 2)) with the circle |p| = r.""" + b = d @ o + c = o @ o - r * r + disc = b * b - c + with np.errstate(invalid="ignore"): + root = np.sqrt(disc) + t1, t2 = -b - root, -b + root + t = np.where(t1 > 1e-6, t1, np.where(t2 > 1e-6, t2, np.inf)) + return np.where(disc >= 0, t, np.inf) + + +def _scan(x: float, y: float, heading: float) -> np.ndarray: + o = np.array([x, y]) + a = heading + ANG + d = np.column_stack([np.cos(a), np.sin(a)]) + r = np.minimum(_ray_circle(o, d, R_IN), _ray_circle(o, d, R_OUT)) + r[np.abs(ANG) > VIEW] = np.nan + return r.astype(np.float32) + + +def _lap(n: int = 240, laps: float = 1.2): + th = np.linspace(0.0, 2 * np.pi * laps, int(n * laps), endpoint=False) + xs, ys = R_PATH * np.cos(th), R_PATH * np.sin(th) + heading = th + np.pi / 2 # counter-clockwise + return xs, ys, heading + + +def _radii(line: np.ndarray) -> np.ndarray: + return np.hypot(line[:, 0], line[:, 1]) + + +def test_walls_of_a_ring_track(): + m = OccupancyTrackMapper(OccupancyConfig(reach=0.7)) + xs, ys, hs = _lap() + for i, (x, y, h) in enumerate(zip(xs, ys, hs)): + m.add_scan(0.05 * i, _scan(x, y, h), ANG, (x, y), h) + outer, inner = m.extract(np.column_stack([xs, ys])) + assert np.median(np.abs(_radii(outer) - R_OUT)) < 0.12 + assert np.median(np.abs(_radii(inner) - R_IN)) < 0.12 + track = TrackModel(outer, inner) + assert track.length == pytest.approx(2 * np.pi * R_PATH, rel=0.05) + + +def test_scans_around_a_disturbance_and_standing_still_are_left_out(): + m = OccupancyTrackMapper() + assert m.add_scan(0.0, _scan(R_PATH, 0.0, np.pi / 2), ANG, (R_PATH, 0.0), np.pi / 2) + assert not m.add_scan(0.1, _scan(R_PATH, 0.0, np.pi / 2), ANG, (R_PATH, 0.01), np.pi / 2) # 1 cm + assert m.add_scan(0.2, _scan(R_PATH, 0.1, np.pi / 2), ANG, (R_PATH, 0.1), np.pi / 2) + m.mark_disturbance(1.0) + assert len(m._kept()) == 0 # both within 1.5 s before it + + +def test_an_open_path_has_no_track(): + m = OccupancyTrackMapper() + xs, ys, hs = _lap(laps=0.3) + for i, (x, y, h) in enumerate(zip(xs, ys, hs)): + m.add_scan(0.05 * i, _scan(x, y, h), ANG, (x, y), h) + with pytest.raises(ValueError): + m.extract(np.column_stack([xs, ys])) + + +def test_mapping_worker_maps_the_ring_from_scans(): + from shared_buffer import LidarBuffer, PoseBuffer + from shared_buffer.track_boundary_buffer import TrackBoundaryBuffer + from workers import MappingWorker + + u = uuid.uuid4().hex[:8] + pb = PoseBuffer(slots=512, name=f"om_p_{u}", create=True) + sb = LidarBuffer(slots=512, name=f"om_s_{u}", create=True) + bb = TrackBoundaryBuffer(slots=2, name=f"om_b_{u}", create=True) + loop, done = mp.Event(), mp.Event() + w = MappingWorker(name="mapping", pose_buffer=pb, boundary_buffer=bb, loop_event=loop, + mapping_done_event=done, wall_source="occupancy", scan_buffer=sb, + scan_offset=[0.0, 0.0, 0.0], bev_axes=[0, 1], forward_axis=0, + occupancy={"reach": 0.7}) + w._logger = MagicMock() + try: + w.setup() + xs, ys, hs = _lap() + t0 = time.monotonic() + for i, (x, y, h) in enumerate(zip(xs, ys, hs)): + T = np.eye(4, dtype=np.float32) + c, s = np.cos(h), np.sin(h) + T[:2, :2] = [[c, -s], [s, c]] + T[0, 3], T[1, 3] = x, y + ts = t0 + 0.05 * i + pb.write(T, ts=ts) + sb.write(_scan(x, y, h), ts=ts) + w.step() + loop.set() + w.step() + assert done.is_set() + _, outer, inner = bb.read_latest() + assert np.median(np.abs(_radii(outer) - R_OUT)) < 0.12 + assert np.median(np.abs(_radii(inner) - R_IN)) < 0.12 + finally: + for b in (pb, sb, bb): + b.unlink() + + +def test_seg_scan_worker_memory_in_the_slam_frame(): + """On the car the pose is SLAM's camera frame (X right, Y down, Z forward): a remembered edge + lands where it was seen, and the raw output carries no remembered edges.""" + from shared_buffer import FrameBuffer, LidarBuffer, PoseBuffer + from shared_buffer.segment_buffer import SegmentationBuffer + from workers.seg_scan_worker import SegScanWorker + + h, w_ = 216, 384 + u = uuid.uuid4().hex[:8] + sb = SegmentationBuffer(slots=4, name=f"om_g_{u}", create=True, max_payload=h * w_ + 64) + fb = FrameBuffer(slots=4, name=f"om_f_{u}", max_payload=16 + h * w_ * 7) + out = LidarBuffer(slots=4, name=f"om_o_{u}") + raw = LidarBuffer(slots=4, name=f"om_r_{u}") + pb = PoseBuffer(slots=8, name=f"om_q_{u}", create=True) + worker = SegScanWorker(name="seg_scan", segment_buffer=sb, frame_buffer=fb, output_buffer=out, + raw_output_buffer=raw, pose_buffer=pb, memory_s=2.0, bev_axes=[0, 2], forward_axis=2, + seg_scan={"camera_settings": "sim_camera/orbslam_settings.yaml", + "camera_pitch": 0.1833, "camera_height": 0.17}) + worker._logger = MagicMock() + worker.setup() + try: + mask = np.zeros((h, w_), np.uint8) + mask[150:, :] = 1 # an edge across the view + blank = np.zeros((h, w_), np.float32) + # camera facing +Z, then turned 90 deg left (towards -X in the camera's right-handed frame) + for k, yaw in enumerate((0.0, np.pi / 2)): + T = np.eye(4, dtype=np.float32) + c, s = np.cos(yaw), np.sin(yaw) + # rotation about the camera's down axis (Y): forward Z turns towards -X for a left turn + T[0, 0], T[0, 2], T[2, 0], T[2, 2] = c, -s, s, c + ts = 1.0 + k + pb.write(T, ts=ts) + fb.write(np.zeros((h, w_, 3), np.uint8), blank, ts=ts) + sb.write(mask, ts=ts) + worker.step() + _, with_memory = out.read_latest() + _, without = raw.read_latest() + right = int(round((-np.pi / 2 - ANGLE_MIN) / ANGLE_INCREMENT)) + # the first edge is now to the right of the car, at its distance + near = with_memory[right - 15:right + 16] + assert np.isfinite(near).any() + assert np.nanmin(near) == pytest.approx(float(np.nanmin(without[np.abs(ANG) < 0.05])), abs=0.25) + assert not np.isfinite(without[right - 15:right + 16]).any() + finally: + for b in (sb, fb, out, raw, pb): + b.unlink() + + +def test_a_gap_between_reads_is_not_a_teleport(): + """A pose read 2 s after the last one, 1.2 m on, is the car driving; the same step within one + sim message is a respawn.""" + from shared_buffer import LidarBuffer, PoseBuffer + from shared_buffer.track_boundary_buffer import TrackBoundaryBuffer + from workers import MappingWorker + + u = uuid.uuid4().hex[:8] + pb = PoseBuffer(slots=16, name=f"om_tp_{u}", create=True) + sb = LidarBuffer(slots=16, name=f"om_ts_{u}", create=True) + bb = TrackBoundaryBuffer(slots=2, name=f"om_tb_{u}", create=True) + w = MappingWorker(name="mapping", pose_buffer=pb, boundary_buffer=bb, loop_event=mp.Event(), + wall_source="occupancy", scan_buffer=sb, bev_axes=[0, 1], forward_axis=0, + jump_threshold=0.4) + w._logger = MagicMock() + try: + w.setup() + for t, x in ((0.0, 0.0), (0.04, 0.03), (2.04, 1.23), (2.08, 2.43)): + T = np.eye(4, dtype=np.float32) + T[0, 3] = x + pb.write(T, ts=100.0 + t) + w.step() + assert len(w._mapper._disturbances) == 1 # only the 1.2 m step within 40 ms + finally: + for b in (pb, sb, bb): + b.unlink() diff --git a/tests/test_pose_degrade.py b/tests/test_pose_degrade.py new file mode 100644 index 0000000..22d766d --- /dev/null +++ b/tests/test_pose_degrade.py @@ -0,0 +1,60 @@ +"""control/pose_degrade.py: the sim's ground-truth pose published like a SLAM pose.""" + +from __future__ import annotations + +import numpy as np +import pytest + +from control.pose_degrade import PoseDegradeConfig, PoseDegrader + + +def _poses(n: int = 2000, dt: float = 0.02): + for i in range(n): + T = np.eye(4, dtype=np.float32) + T[0, 3] = 0.05 * i + yield i * dt, T + + +def test_poses_are_late_in_order_and_keep_their_capture_time(): + d = PoseDegrader(PoseDegradeConfig(enabled=True, dropout_rate=0.0, seed=1)) + out, delays = [], [] + for t, T in _poses(): + d.add(t, T) + for tc, pose in d.due(t): + out.append(tc) + delays.append(t - tc) + assert out == sorted(out) + delays = np.array(delays) + assert np.median(delays) == pytest.approx(0.033 + 0.0084, abs=0.02) # 20 ms message steps + assert delays.min() >= 0.033 + + +def test_noise_and_drift_are_bounded(): + d = PoseDegrader(PoseDegradeConfig(enabled=True, dropout_rate=0.0, seed=2)) + err = [] + for t, T in _poses(n=600): # 12 s, about one lap + d.add(t, T) + for tc, pose in d.due(t + 1.0): + err.append(abs(float(pose[0, 3]) - 0.05 * round(tc / 0.02))) + assert 0.005 < np.median(err) < 0.2 + + +def test_dropouts_remove_stretches_of_poses(): + cfg = PoseDegradeConfig(enabled=True, dropout_rate=0.5, dropout_s=0.3, seed=3) + d = PoseDegrader(cfg) + for t, T in _poses(n=3000): + d.add(t, T) + d.due(1e9) + lost = d.dropped / (d.dropped + d.published) + expected = 0.5 * 0.3 / (1 + 0.5 * 0.3) + assert lost == pytest.approx(expected, abs=0.05) + + +def test_the_bias_stays_bounded_over_a_long_race(): + d = PoseDegrader(PoseDegradeConfig(enabled=True, dropout_rate=0.0, xy_sigma=0.0, seed=4)) + bias = [] + for i in range(6000): # 240 s at 25 Hz + d.add(0.04 * i, np.eye(4, dtype=np.float32)) + bias.append(float(np.hypot(*d._bias))) + assert np.sqrt(np.mean(np.square(bias))) == pytest.approx(0.07 * np.sqrt(2), rel=0.3) + assert max(bias) < 0.4 diff --git a/tests/test_raceline.py b/tests/test_raceline.py new file mode 100644 index 0000000..f935ffd --- /dev/null +++ b/tests/test_raceline.py @@ -0,0 +1,46 @@ +"""Minimum-curvature racing line (control/raceline.py) and TrackModel.set_path.""" + +from __future__ import annotations + +import numpy as np +import pytest + +from control import TrackModel +from control.raceline import min_curvature_line +from control.sim import oval_track, twisty_track +from control.speed import speed_profile + + +def _lap_estimate(track: TrackModel) -> float: + v = speed_profile(track, v_max=12.0, a_lat_max=8.0, a_accel=5.0, a_decel=5.0) + ds = np.diff(np.concatenate([track.s, [track.length]])) + return float((ds / v).sum()) + + +@pytest.mark.parametrize("make", [oval_track, twisty_track]) +def test_line_stays_inside_and_is_faster(make): + outer, inner, _ = make() + centre = TrackModel(outer, inner) + margin = 0.3 + line = min_curvature_line(centre, outer, inner, margin=margin) + raced = TrackModel(outer, inner) + raced.set_path(line) + + assert raced.half_width.min() > margin - 0.08 # smoothing may shave a few cm + assert raced.length < centre.length + # minimising total curvature need not lower the peak (an ellipse's ends), but the + # speed planner's lap time on the line must improve + assert _lap_estimate(raced) < _lap_estimate(centre) + + +def test_set_path_keeps_direction_and_walls(): + outer, inner, _ = twisty_track() + track = TrackModel(outer, inner) + heading0 = track.heading[0] + line = min_curvature_line(track, outer, inner, margin=0.3) + track.set_path(line) + p = track.project(*line[0]) + # same travel direction as the centre-line it came from + assert abs(np.angle(np.exp(1j * (p.path_heading - heading0)))) < np.pi / 2 + # half_width is now measured from the line, so it is smaller on one side somewhere + assert track.half_width.min() < TrackModel(outer, inner).half_width.min() diff --git a/tests/test_rear_imu_state.py b/tests/test_rear_imu_state.py new file mode 100644 index 0000000..cdf1c3a --- /dev/null +++ b/tests/test_rear_imu_state.py @@ -0,0 +1,116 @@ +"""The rear IMU on the car: StateWorker on control.ImuEKF (axes, lever arm, buffers) and the +mounting / delay logic of scripts/check_rear_imu.py.""" + +from __future__ import annotations + +import os +import sys +import uuid +from unittest.mock import MagicMock + +import numpy as np +import pytest +import yaml + +import workers.state_worker as sw_mod +from shared_buffer import PoseBuffer, RawIMUBuffer, StateBuffer +from workers.state_worker import StateWorker + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "scripts")) +import check_rear_imu as chk # noqa: E402 + + +def _cam_pose(x, y, yaw): + """ORB-SLAM3-style camera-to-world (world Y down, camera Z forward): BEV (x, y) = (X, Z).""" + c, s = np.cos(yaw), np.sin(yaw) + T = np.eye(4, dtype=np.float32) + T[:3, 0], T[:3, 1], T[:3, 2] = (s, 0, -c), (0, 1, 0), (c, 0, s) + T[0, 3], T[2, 3] = x, y + return T + + +def test_state_worker_runs_the_imu_ekf_on_the_rear_imu(monkeypatch): + """Car on a circle (3 m/s, 1 rad/s); the IMU 0.25 m behind the camera and mounted with its + x forward and its y down; poses are the camera's. The published state is the camera's + point, with the gyro's yaw rate.""" + v, r, lever = 3.0, 1.0, np.array([-0.25, 0.0]) + R_cfg = chk.rotation_from((1, -1), (0, 1)) # car = R_cfg @ sensor + clock = {"t": 0.0} + monkeypatch.setattr(sw_mod.time, "monotonic", lambda: clock["t"]) + monkeypatch.setattr(sw_mod.time, "sleep", lambda s: None) + u = uuid.uuid4().hex[:8] + pb, ib, sb = PoseBuffer(slots=8, name=f"rs_p_{u}"), RawIMUBuffer(slots=64, name=f"rs_i_{u}"), StateBuffer(slots=8, name=f"rs_s_{u}") + w = StateWorker(name="state", pose_buffer=pb, output_buffer=sb, rear_imu_buffer=ib, + rear_imu={"rotation": R_cfg.tolist(), "lever_m": lever.tolist()}, rate_hz=50) + w._logger = MagicMock() + w.setup() + try: + def imu_point(t): + yaw = r * t + return (v / r) * np.sin(yaw), (v / r) * (1 - np.cos(yaw)), yaw + + for k in range(400): # 4 s: IMU at 100 Hz, poses at 30 Hz, 30 ms late + t = k * 0.01 + car_acc, car_gyro = np.array([0.0, v * r, 9.81]), np.array([0.0, 0.0, r]) + ib.write(np.r_[R_cfg.T @ car_acc, R_cfg.T @ car_gyro].astype(np.float32), ts=t) + if k % 3 == 0 and t >= 0.03: + tp = t - 0.03 + x, y, yaw = imu_point(tp) + cx, cy = x - (np.cos(yaw) * lever[0] - np.sin(yaw) * lever[1]), y - (np.sin(yaw) * lever[0] + np.cos(yaw) * lever[1]) + pb.write(_cam_pose(cx, cy, yaw), ts=tp) + clock["t"] = t + w.step() + _, st = sb.read_latest() + x, y, yaw = imu_point(st.t) + cx, cy = x - np.cos(yaw) * lever[0], y - np.sin(yaw) * lever[0] + assert np.hypot(st.x - cx, st.y - cy) < 0.05 + assert st.yaw_rate == pytest.approx(r, abs=0.02) + assert st.v == pytest.approx(v, abs=0.1) + finally: + for b in (pb, ib, sb): + b.unlink() + + +def test_state_worker_rejects_a_non_rotation(): + u = uuid.uuid4().hex[:8] + pb, ib, sb = PoseBuffer(slots=4, name=f"rn_p_{u}"), RawIMUBuffer(slots=4, name=f"rn_i_{u}"), StateBuffer(slots=4, name=f"rn_s_{u}") + w = StateWorker(name="state", pose_buffer=pb, output_buffer=sb, rear_imu_buffer=ib, + rear_imu={"rotation": [[1, 0, 0], [0, 1, 0], [0, 0, 0]]}) + w._logger = MagicMock() + try: + with pytest.raises(ValueError): + w.setup() + finally: + for b in (pb, ib, sb): + b.unlink() + + +def test_check_finds_the_mounting_from_a_turn_and_a_push(): + # sensor y points down (car up = -y), sensor x points backward (forward = -x) + t = np.linspace(0, 5, 501) + gyro = np.zeros((501, 3)) + gyro[:, 1] = -np.radians(18.0) # 90 deg left turn over 5 s, about -y + up = chk.axis_from_turn(t, gyro) + assert up[:2] == (1, -1) and up[2] == pytest.approx(90.0, abs=0.5) + acc = np.tile([0.0, -9.81, 0.0], (400, 1)) + acc[100:130, 0] = -1.5 # pushed forward: -x + acc[200:230, 0] = +1.5 # stopped + fwd = chk.axis_from_push(acc, up[0]) + assert fwd == (0, -1) + R = chk.rotation_from(up[:2], fwd) + assert np.linalg.det(R) == pytest.approx(1.0) + np.testing.assert_allclose(R @ [-1, 0, 0], [1, 0, 0]) # sensor -x = car forward + np.testing.assert_allclose(R @ [0, -1, 0], [0, 0, 1]) # sensor -y = car up + block = yaml.safe_load(chk.config_block(R, 0.012))["rear_imu"] + np.testing.assert_allclose(block["rotation"], R) + assert block["enabled"] and block["delay_s"] == pytest.approx(0.012) + + +def test_check_measures_the_rear_imu_delay(): + rng = np.random.default_rng(0) + t = np.arange(0, 20, 0.005) + yaw_rate = np.convolve(rng.normal(0, 1, len(t)), np.ones(40) / 40, mode="same") + cam = np.column_stack([np.zeros_like(t), yaw_rate, np.zeros_like(t)]) # OAK-D axes differ + t_rear = np.arange(0, 20, 0.01) + rear = np.column_stack([np.zeros_like(t_rear), np.zeros_like(t_rear), np.interp(t_rear - 0.012, t, yaw_rate)]) + assert chk.time_offset(t, cam, t_rear, rear) == pytest.approx(0.012, abs=0.001) diff --git a/tests/test_seg_scan.py b/tests/test_seg_scan.py index 005c19d..0a602fd 100644 --- a/tests/test_seg_scan.py +++ b/tests/test_seg_scan.py @@ -119,14 +119,13 @@ def test_gap_follower_with_nothing_free_aims_at_the_deepest_known_beam(): # ---------------------------------------------------------------- ControlWorker -def _control_rig(segment: bool = True): +def _control_rig(scan: bool = True): from control import VehicleState - from shared_buffer import ControlBuffer, FrameBuffer, SegmentationBuffer, StateBuffer, TrackBoundaryBuffer + from shared_buffer import ControlBuffer, LidarBuffer, StateBuffer, TrackBoundaryBuffer from workers import ControlWorker bufs = { - "frame": FrameBuffer(slots=4, name=f"ss_f_{_uid()}", create=True), - "seg": SegmentationBuffer(slots=4, name=f"ss_s_{_uid()}", create=True), + "scan": LidarBuffer(slots=4, name=f"ss_l_{_uid()}", create=True), "state": StateBuffer(slots=4, name=f"ss_st_{_uid()}", create=True), "boundary": TrackBoundaryBuffer(slots=2, name=f"ss_b_{_uid()}", create=True), "ctrl": ControlBuffer(slots=8, name=f"ss_c_{_uid()}", create=True), @@ -137,9 +136,7 @@ def _control_rig(segment: bool = True): mapping_done_event=MagicMock(is_set=MagicMock(return_value=False)), track_config={"mapping_drive": {"speed": 0.6, "min_speed": 0.4}}, vehicle_params="vehicle_params_roboracer.yaml", - frame_buffer=bufs["frame"], segment_buffer=bufs["seg"] if segment else None, - seg_scan={"camera_settings": "orbslam_oakd_rgbd.yaml", "camera_pitch": float(PITCH), - "camera_height": CAM_H}, + lidar_buffer=bufs["scan"] if scan else None, ) w._logger = MagicMock() bufs["state"].write(VehicleState(t=time.monotonic(), x=0.0, y=0.0, yaw=0.0, v=0.5, yaw_rate=0.0)) @@ -151,11 +148,7 @@ def test_control_worker_drives_the_mapping_lap_on_the_segmentation_scan(): try: w.setup() mask, depth = _scene(wall_fwd=3.0) - rgb = np.zeros((H, W, 3), np.uint8) - ts = time.monotonic() - bufs["frame"].write(rgb, depth, ts=ts) - bufs["frame"].write(rgb, depth, ts=ts + 0.03) # a newer frame arrived during inference - bufs["seg"].write(mask, ts=ts) # VisionWorker stamps the frame's time + bufs["scan"].write(seg_edge_scan(mask, depth, K, _cfg()), ts=time.monotonic()) w.step() assert bufs["ctrl"].latest_seq() == 1 _, steer, throttle = bufs["ctrl"].read_latest() @@ -165,24 +158,25 @@ def test_control_worker_drives_the_mapping_lap_on_the_segmentation_scan(): b.unlink() -def test_a_mask_whose_frame_has_left_the_ring_is_skipped(): +def test_a_scan_is_driven_on_once(): w, bufs = _control_rig() try: w.setup() mask, depth = _scene(wall_fwd=3.0) - bufs["frame"].write(np.zeros((H, W, 3), np.uint8), depth, ts=time.monotonic()) - bufs["seg"].write(mask, ts=time.monotonic() - 5.0) + bufs["scan"].write(seg_edge_scan(mask, depth, K, _cfg()), ts=time.monotonic() - 1.0) w.step() - assert bufs["ctrl"].latest_seq() == 0 + assert bufs["ctrl"].latest_seq() == 1 + w.step() # no new scan, and the old one is too old to hold + assert bufs["ctrl"].latest_seq() == 1 finally: for b in bufs.values(): b.unlink() -def test_mapping_drive_without_lidar_or_segmentation_is_an_error(): - w, bufs = _control_rig(segment=False) +def test_mapping_drive_without_a_scan_is_an_error(): + w, bufs = _control_rig(scan=False) try: - with pytest.raises(RuntimeError, match="segment_buffer"): + with pytest.raises(RuntimeError, match="lidar_buffer"): w.setup() finally: for b in bufs.values(): @@ -229,29 +223,27 @@ def test_car_mapping_drive_runs_on_the_segmentation_scan(_unique_buffer_names): p = _build("config_cpu.yaml", control_mode="pure_pursuit", enable_slam=True, track_control={"mapping_drive": {"speed": 0.5}}, vision={"enabled": True}) try: - ctrl = next(w for w in p.workers if w.name == "control") - vision = next(w for w in p.workers if w.name == "vision") - assert ctrl.config["lidar_buffer"] is None - assert ctrl.config["segment_buffer"] is vision.config["output_buffer"] is not None - assert ctrl.config["seg_scan"]["camera_height"] == 0.12 # depth_ftg's, one camera mount + by = {w.name: w for w in p.workers} + scan = by["seg_scan"] + assert scan.config["segment_buffer"] is by["vision"].config["output_buffer"] is not None + assert by["control"].config["lidar_buffer"] is scan.config["output_buffer"] is not None + assert scan.config["seg_scan"]["camera_height"] == 0.12 # depth_ftg's, one camera mount + assert scan.config["bev_axes"] == [0, 2] and scan.config["forward_axis"] == 2 # SLAM frame + assert by["mapping"].config["scan_buffer"] is scan.config["raw_output_buffer"] is not None finally: for b in p.buffers: b.unlink() -def test_sim_uses_the_lidar_unless_told_otherwise(_unique_buffer_names): +def test_sim_never_uses_the_lidar(_unique_buffer_names): + """The mapping drive drives on SegScanWorker's segmentation-edge scan, never the sim's LiDAR.""" p = _build("config_autodrive.yaml") try: - ctrl = next(w for w in p.workers if w.name == "control") - assert ctrl.config["lidar_buffer"] is not None - finally: - for b in p.buffers: - b.unlink() - p = _build("config_autodrive.yaml", seg_scan={"source": "segmentation"}, vision={"enabled": True}) - try: - ctrl = next(w for w in p.workers if w.name == "control") - assert ctrl.config["lidar_buffer"] is None and ctrl.config["segment_buffer"] is not None - assert ctrl.config["seg_scan"]["origin_forward"] == pytest.approx(-0.2883) + by = {w.name: w for w in p.workers} + ctrl = by["control"] + assert ctrl.config["lidar_buffer"] is by["seg_scan"].config["output_buffer"] + assert by["autodrive"].config.get("lidar_buffer") is None + assert by["seg_scan"].config["seg_scan"]["origin_forward"] == pytest.approx(-0.2883) finally: for b in p.buffers: b.unlink() diff --git a/tests/test_seg_scan_worker.py b/tests/test_seg_scan_worker.py new file mode 100644 index 0000000..dc578e7 --- /dev/null +++ b/tests/test_seg_scan_worker.py @@ -0,0 +1,47 @@ +"""SegScanWorker: a segmentation mask + its frame's (absent) depth -> a LiDAR-format scan, with +the track edge placed on the floor; no LiDAR anywhere.""" + +from __future__ import annotations + +import uuid +from unittest.mock import MagicMock + +import numpy as np + +from control.depth_ftg import Intrinsics +from control.lidar_gap import ANGLE_INCREMENT, ANGLE_MIN +from shared_buffer import FrameBuffer, LidarBuffer +from shared_buffer.segment_buffer import SegmentationBuffer +from workers.seg_scan_worker import SegScanWorker + +SETTINGS = "sim_camera/orbslam_settings.yaml" # 384 x 216, the sim camera upscaled + + +def test_edge_on_the_floor_without_depth(): + K = Intrinsics.from_orbslam_settings(SETTINGS) + h, w = 216, 384 + pitch, height = 0.1833, 0.17 + # floor up to the row where the floor is 2.0 m ahead; nothing drivable above it + yn = (np.tan(np.arctan2(height, 2.0) - pitch)) # ray below the optical axis + edge_row = int(round(K.cy + yn * K.fy)) + mask = np.zeros((h, w), np.uint8) + mask[edge_row:, :] = 1 + u = uuid.uuid4().hex[:8] + sb = SegmentationBuffer(slots=4, name=f"ss_s_{u}", create=True, max_payload=h * w + 64) + fb = FrameBuffer(slots=4, name=f"ss_f_{u}", max_payload=16 + h * w * 7) + lb = LidarBuffer(slots=4, name=f"ss_l_{u}") + w_ = SegScanWorker(name="seg_scan", segment_buffer=sb, frame_buffer=fb, output_buffer=lb, + seg_scan={"camera_settings": SETTINGS, "camera_pitch": pitch, "camera_height": height}) + w_._logger = MagicMock() + w_.setup() + try: + fb.write(np.zeros((h, w, 3), np.uint8), np.zeros((h, w), np.float32), ts=1.0) # no depth + sb.write(mask, ts=1.0) + w_.step() + _, ranges = lb.read_latest() + ahead = int(round((0.0 - ANGLE_MIN) / ANGLE_INCREMENT)) + assert abs(float(ranges[ahead]) - 2.0) < 0.1 + assert np.isfinite(ranges).sum() > 50 # the edge across the camera's view + finally: + for b in (sb, fb, lb): + b.unlink() diff --git a/tests/test_slam_inertial.py b/tests/test_slam_inertial.py new file mode 100644 index 0000000..d437ae8 --- /dev/null +++ b/tests/test_slam_inertial.py @@ -0,0 +1,173 @@ +"""SLAMWorker's RGB-D-inertial mode: IMU samples handed to ORB-SLAM3 per frame, and poses +kept in the origin keyframe's frame across ORB-SLAM3's gravity re-rotations.""" + +from __future__ import annotations + +import sys +import types +import uuid +from unittest.mock import MagicMock + +import numpy as np +import pytest +from scipy.spatial.transform import Rotation + +from shared_buffer import FrameBuffer, PoseBuffer, RawIMUBuffer +from workers.slam_worker import SLAMWorker + + +def _uid() -> str: + return uuid.uuid4().hex[:8] + + +def _rigid(axis: str, deg: float, t) -> np.ndarray: + T = np.eye(4, dtype=np.float32) + T[:3, :3] = Rotation.from_euler(axis, deg, degrees=True).as_matrix() + T[:3, 3] = t + return T + + +@pytest.fixture +def bufs(): + fb = FrameBuffer(slots=2, name=f"si_f_{_uid()}", create=True) + pb = PoseBuffer(slots=4, name=f"si_p_{_uid()}", create=True) + ib = RawIMUBuffer(slots=64, name=f"si_i_{_uid()}", create=True) + yield fb, pb, ib + for b in (fb, pb, ib): + b.unlink() + + +def _inertial_worker(fb, pb, ib, Twc=np.eye(4, dtype=np.float32)): + w = SLAMWorker(name="slam", input_buffer=fb, output_buffer=pb, inertial=True, + raw_imu_buffer=ib, imu_wait_s=0.0, warmup_frames=0) + w._logger = MagicMock() + w._frame_buf, w._pose_buf, w._imu_buf = fb, pb, ib + w._warmup_frames = 0 + w._slam = MagicMock() + w._slam.track_rgbd.return_value = np.linalg.inv(Twc).astype(np.float32) + w._slam.get_tracking_state.return_value = 2 + w._slam.map_changed.return_value = False + w._slam.map_info.return_value = (0, 0, 10) + w._slam.origin_pose.return_value = np.eye(4, dtype=np.float32) + w._slam.imu_initialized.return_value = False + return w + + +def _frame(fb, ts): + fb.write(np.zeros((40, 64, 3), np.uint8), np.ones((40, 64), np.float32), ts=ts) + + +def test_raw_imu_buffer_roundtrip(bufs): + _, _, ib = bufs + ib.write(np.arange(6, dtype=np.float32), ts=5.5) + header, sample = ib.read_latest() + assert header.produced_ts == 5.5 + np.testing.assert_array_equal(sample, np.arange(6, dtype=np.float32)) + with pytest.raises(ValueError): + ib.write(np.zeros(9, np.float32)) + + +def test_imu_samples_are_split_at_frame_times(bufs): + fb, pb, ib = bufs + w = _inertial_worker(fb, pb, ib) + for k, t in enumerate(np.arange(0.90, 1.21, 0.05)): + ib.write(np.array([0, 0, 9.81, 0, 0, k], np.float32), ts=float(t)) + _frame(fb, 1.0) + w.step() + imu = w._slam.track_rgbd.call_args[0][3] + assert imu.dtype == np.float64 and imu.shape[1] == 7 + np.testing.assert_allclose(imu[:, 0], [0.90, 0.95, 1.00], atol=1e-9) + np.testing.assert_allclose(imu[:, 6], [0, 1, 2]) # gyro z made it through + _frame(fb, 1.1) + w.step() + imu = w._slam.track_rgbd.call_args[0][3] + np.testing.assert_allclose(imu[:, 0], [1.05, 1.10], atol=1e-9) # none twice, none lost + + +def test_warmup_frames_consume_their_imu(bufs): + fb, pb, ib = bufs + w = _inertial_worker(fb, pb, ib) + w._warmup_frames = 1 + for t in (0.95, 1.0, 1.05, 1.1): + ib.write(np.zeros(6, np.float32), ts=t) + _frame(fb, 1.0) + w.step() # warm-up: not tracked + assert w._slam.track_rgbd.call_count == 0 + _frame(fb, 1.1) + w.step() + np.testing.assert_allclose(w._slam.track_rgbd.call_args[0][3][:, 0], [1.05, 1.1], atol=1e-9) + + +def test_poses_stay_put_when_the_map_is_rotated_to_gravity(bufs): + fb, pb, ib = bufs + Twc = _rigid("y", 30.0, [1.0, 0.0, 2.0]) + w = _inertial_worker(fb, pb, ib, Twc) + _frame(fb, 1.0) + w.step() + _, pose, _, _ = pb.read_latest() + np.testing.assert_allclose(pose[:3, 3], [1.0, 0.0, 2.0], atol=1e-5) + + # IMU init: ORB-SLAM3 rotates everything, origin keyframe and camera alike + G = _rigid("x", 12.0, [0.0, 0.0, 0.0]) + w._slam.origin_pose.return_value = G + w._slam.track_rgbd.return_value = np.linalg.inv(G @ Twc).astype(np.float32) + w._slam.imu_initialized.return_value = True + _frame(fb, 1.1) + w.step() + assert pb.latest_seq() == 1 # the rotation frame is withheld + _frame(fb, 1.2) + w.step() + assert pb.latest_seq() == 2 + _, pose, _, _ = pb.read_latest() + np.testing.assert_allclose(pose, Twc, atol=1e-5) # same pose as before the rotation + + +def test_setup_picks_imu_rgbd_and_needs_the_raw_imu_buffer(bufs, monkeypatch): + fb, pb, ib = bufs + fake = types.ModuleType("orbslam3_python") + fake.RGBD, fake.IMU_RGBD = 2, 5 + fake.System = MagicMock() + monkeypatch.setitem(sys.modules, "orbslam3_python", fake) + + w = SLAMWorker(name="slam", input_buffer=fb, output_buffer=pb, inertial=True, + raw_imu_buffer=ib, level_world=False) + w._logger = MagicMock() + w.setup() + assert fake.System.call_args[0][2] == 5 + + w = SLAMWorker(name="slam", input_buffer=fb, output_buffer=pb, inertial=True, level_world=False) + w._logger = MagicMock() + with pytest.raises(RuntimeError, match="raw_imu_buffer"): + w.setup() + + +def test_imu_extrinsics_must_be_a_rigid_transform(tmp_path, capsys): + """gen_orbslam_settings --imu: devices without IMU calibration raise or store zeros; + neither may end up in the settings as T_b_c1.""" + import os + + import yaml + + sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "scripts")) + import gen_orbslam_settings as g + + class Calib: + def __init__(self, T=None, error=None): + self.T, self.error = T, error + + def getCameraToImuExtrinsics(self, *args): + if self.error: + raise RuntimeError(self.error) + return self.T + + dai = types.SimpleNamespace(CameraBoardSocket=types.SimpleNamespace(CAM_A=0), + LengthUnit=types.SimpleNamespace(METER=1)) + assert g.imu_extrinsics(dai, Calib(error="IMU calibration data is not available"), None) is None + assert "--imu-extrinsics" in capsys.readouterr().err + zeros = [[0.0] * 4] * 3 + [[0.0, 0.0, 0.0, 1.0]] + assert g.imu_extrinsics(dai, Calib(T=zeros), None) is None + good = _rigid("z", 90.0, [0.01, 0.02, 0.0]).astype(float).tolist() + np.testing.assert_allclose(g.imu_extrinsics(dai, Calib(T=good), None), good) + path = tmp_path / "T_b_c1.yaml" + path.write_text(yaml.safe_dump(good)) + np.testing.assert_allclose(g.imu_extrinsics(dai, Calib(error="none stored"), str(path)), good) diff --git a/tests/test_start_wiring.py b/tests/test_start_wiring.py index 94614c6..a5556ab 100644 --- a/tests/test_start_wiring.py +++ b/tests/test_start_wiring.py @@ -20,7 +20,7 @@ def _unique_buffer_names(monkeypatch): # every buffer class takes name=...; give each test run its own names suffix = uuid.uuid4().hex[:6] for cls_name in ("FrameBuffer", "IMUBuffer", "SegmentationBuffer", "PoseBuffer", "ControlBuffer", - "PointCloudBuffer", "TrackBoundaryBuffer", "LidarBuffer", "StateBuffer"): + "PointCloudBuffer", "TrackBoundaryBuffer", "LidarBuffer", "StateBuffer", "RawIMUBuffer"): cls = getattr(start, cls_name) def make(*args, _cls=cls, **kwargs): @@ -88,24 +88,33 @@ def test_autodrive_wiring(): assert sim.config["reset_event"] is p.reset_event is not None assert sim.config["lap_counter"] is p.counters["lap"] assert sim.config["log_dir"] == p.recording_dir - # LiDAR mapping on the ground-truth pose; the gap follower drives that lap - assert sim.config["lidar_buffer"] is by["lidar_proj"].config["lidar_buffer"] is not None - assert ctrl.config["lidar_buffer"] is sim.config["lidar_buffer"] + # no LiDAR: the mapping lap's walls from the segmentation-edge scan on the ground-truth + # pose; the gap follower drives that lap on the same kind of scan + scan = by["seg_scan"].config["output_buffer"] + assert sim.config["lidar_buffer"] is None and scan is not None + assert ctrl.config["lidar_buffer"] is scan and by["seg_scan"].config["memory_s"] == 1.5 + assert by["mapping"].config["wall_source"] == "occupancy" and "seg_proj" not in by + assert by["mapping"].config["scan_buffer"] is by["seg_scan"].config["raw_output_buffer"] is not None assert by["mapping"].config["auto_loop_close"] is True assert by["mapping"].config["jump_threshold"] == 0.4 # sim respawns; off for SLAM assert "actuation" in by["recorder"].config["buffers"] finally: for b in p.buffers: b.unlink() - # racing on a saved map: no mapping workers, but the scan is still recorded + # racing on a saved map: no mapping workers, no scan p = _build("config_autodrive.yaml", recording=True, enable_slam=False, use_saved_map=True) try: by = {w.name: w for w in p.workers} - assert "mapping" not in by and "lidar_proj" not in by - assert "lidar" in by["recorder"].config["buffers"] + assert "mapping" not in by and "seg_proj" not in by and "lidar_proj" not in by + assert "lidar" not in by["recorder"].config["buffers"] finally: for b in p.buffers: b.unlink() + # asking for the LiDAR, or depth from it, is an error: pilot_core never uses one + with pytest.raises(SystemExit): + _build("config_autodrive.yaml", lidar={"enabled": True}) + with pytest.raises(SystemExit): + _build("config_autodrive.yaml", sim_depth={"camera": "sim_camera/camera.yaml", "scale": 2, "depth": "lidar"}) def test_removed_modes_are_rejected(): @@ -141,3 +150,102 @@ def test_sim_depth_frames_fit_and_vision_uses_the_sim_camera(): finally: for b in p.buffers: b.unlink() + + +def test_rear_imu_feeds_the_imu_worker_and_the_state_worker(): + rear = {"enabled": True, "rotation": [[1, 0, 0], [0, 1, 0], [0, 0, 1]], "lever_m": [-0.25, 0.0]} + p = _build("config.yaml", rear_imu=rear, use_oakd_imu=False, recording=True) + try: + imu = next(w for w in p.workers if w.name == "imu") + buf = imu.config["raw_output_buffer"] + assert buf is not None + state = [w for w in p.workers if w.name == "state"] + if state: + assert state[0].config["rear_imu_buffer"] is buf + assert state[0].config["rear_imu"]["lever_m"] == [-0.25, 0.0] + rec = next(w for w in p.workers if w.name == "recorder") + assert rec.config["buffers"]["rear_imu"]["buffer"] is buf + finally: + for b in p.buffers: + b.unlink() + + +def test_rear_imu_needs_the_arduino_imu(): + with pytest.raises(SystemExit): + _build("config.yaml", rear_imu={"enabled": True}, use_oakd_imu=True) + + +def test_sim_maps_from_the_segmentation_without_a_lidar(): + """The sim configs use no LiDAR (as the car): no lidar buffer; the mapping lap's walls come + from the segmentation-edge scan (VisionWorker -> SegScanWorker -> projection).""" + p = _build("config_autodrive.yaml") + try: + names = [w.name for w in p.workers] + assert "vision" in names and "seg_scan" in names and "lidar_proj" not in names + assert not any(getattr(b, "name", "").startswith("lidar_buf") for b in p.buffers) + sim = next(w for w in p.workers if w.name == "autodrive") + assert sim.config.get("lidar_buffer") is None and sim.config["sim_depth"]["depth"] == "none" + mapping = next(w for w in p.workers if w.name == "mapping") + assert mapping.config["scan_offset"] == [0.2733, 0.0, 0.10] + ctrl = next(w for w in p.workers if w.name == "control") + assert ctrl.config.get("lidar_buffer") is next(w for w in p.workers if w.name == "seg_scan").config["output_buffer"] + finally: + for b in p.buffers: + b.unlink() + + + +def test_sim_race_uses_no_lidar_no_ground_truth_speed_and_no_idle_segmentation(): + """The race config: no LiDAR buffer, the sim's own velocity is not fused into the state, and + the segmentation (only needed for a mapping lap) is not started.""" + p = _build("config_autodrive_compete.yaml") + try: + by = {w.name: w for w in p.workers} + assert by["autodrive"].config.get("lidar_buffer") is None + assert by["state"].config["use_pose_speed"] is False + assert "vision" not in by and "seg_scan" not in by + assert p.mapping_done_event.is_set() # racing on the saved map + finally: + for b in p.buffers: + b.unlink() + + +def test_cloud_walls_project_the_segmentation_scan(): + """mapping.wall_source: cloud keeps the projected point cloud (the earlier method).""" + config = start.load_config(os.path.join(REPO_ROOT, "config_autodrive.yaml")) + config["mapping"] = {**config["mapping"], "wall_source": "cloud"} + p = start.build_pipeline(config) + try: + by = {w.name: w for w in p.workers} + assert by["seg_proj"].config["lidar_buffer"] is by["seg_scan"].config["output_buffer"] + assert by["seg_proj"].config["range_max"] == 2.0 + assert by["mapping"].config["scan_buffer"] is None + finally: + for b in p.buffers: + b.unlink() + + +def _mapping_lap_classes(config_name, **overrides): + p = _build(config_name, **overrides) + try: + by = {w.name: type(w).__name__ for w in p.workers} + workers = {w.name: w for w in p.workers} + scan = workers["seg_scan"] + wiring = (workers["control"].config["lidar_buffer"] is scan.config["output_buffer"], + workers["mapping"].config["scan_buffer"] is scan.config["raw_output_buffer"], + workers["mapping"].config["wall_source"]) + return {k: by[k] for k in ("vision", "seg_scan", "mapping", "control", "state", "actuator")}, wiring + finally: + for b in p.buffers: + b.unlink() + + +def test_car_and_sim_map_and_drive_with_the_same_workers(): + """One pipeline: the car's mapping lap (SLAM pose) and the sim's (ground-truth pose) run the + same segmentation, scan, mapping, control, state and actuator workers, wired the same way.""" + car = _mapping_lap_classes("config.yaml", i2c_address=None, + track_control={**start.load_config(os.path.join(REPO_ROOT, "config.yaml"))["track_control"], + "mapping_drive": {"speed": 0.5}}) + sim = _mapping_lap_classes("config_autodrive.yaml") + assert car == sim + assert car[1] == (True, True, "occupancy") diff --git a/tests/test_vio_bench.py b/tests/test_vio_bench.py new file mode 100644 index 0000000..551ffcf --- /dev/null +++ b/tests/test_vio_bench.py @@ -0,0 +1,232 @@ +"""scripts/vio_bench: car recording -> rgbdi sequence, AprilTag sightings and the marker metrics.""" + +from __future__ import annotations + +import os +import sys +import uuid +from unittest.mock import MagicMock + +import cv2 +import numpy as np +import pytest + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "scripts", "vio_bench")) + +import car_to_rgbdi # noqa: E402 +import markers # noqa: E402 +import rgbdi # noqa: E402 +from shared_buffer import FrameBuffer, RawIMUBuffer # noqa: E402 +from workers.buffer_recorder_worker import BufferRecorderWorker # noqa: E402 + +K = np.array([[400.0, 0, 320.0], [0, 400.0, 200.0], [0, 0, 1]]) + + +def _render_tag(tag_id: int, size: float, R: np.ndarray, t: np.ndarray, shape=(400, 640)) -> np.ndarray: + """Grey image of one tag36h11 at pose (R, t) in the camera frame (tag x right, y up).""" + d = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_APRILTAG_36h11) + s = 400 + tag = cv2.aruco.generateImageMarker(d, tag_id, s, borderBits=1) + corners3d = markers.tag_object_points(size) @ R.T + t + img_pts = (corners3d @ K.T)[:, :2] / (corners3d @ K.T)[:, 2:] + e = (-0.5, s - 0.5) # the marker image's outer pixel edges + H = cv2.getPerspectiveTransform(np.float32([[e[0], e[0]], [e[1], e[0]], [e[1], e[1]], [e[0], e[1]]]), + img_pts.astype(np.float32)) + canvas = np.full(shape, 255, np.uint8) + warped = cv2.warpPerspective(tag, H, (shape[1], shape[0]), borderValue=255) + mask = cv2.warpPerspective(np.full_like(tag, 255), H, (shape[1], shape[0])) > 0 + canvas[mask] = warped[mask] + return canvas + + +def test_tag_is_located_in_the_camera_frame(): + R = np.diag([1.0, -1.0, -1.0]) # facing the camera + R = cv2.Rodrigues(np.array([0.0, 0.4, 0.0]))[0] @ R # and turned 23 deg + t = np.array([0.3, 0.1, 1.5]) + params = cv2.aruco.DetectorParameters() + params.cornerRefinementMethod = cv2.aruco.CORNER_REFINE_SUBPIX + det = cv2.aruco.ArucoDetector(cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_APRILTAG_36h11), params) + found = markers.detect_frame(_render_tag(7, 0.16, R, t), det, K, 0.16) + assert [f[0] for f in found] == [7] + _, p, side, reproj = found[0] + assert np.linalg.norm(p - t) < 0.02 + assert side > 30 and reproj < 1.0 + + +def _sightings(tags: dict, t_ns: np.ndarray, T_wc: np.ndarray) -> np.ndarray: + rows = [] + for t, T in zip(t_ns, T_wc): + Tcw = np.linalg.inv(T) + for i, p in tags.items(): + rows.append([t, i, *(Tcw @ np.append(p, 1.0))[:3], 50.0, 0.2]) + return np.array(rows) + + +def _two_laps(): + """Two passes 10 s apart past the same tags along a straight; T_world_cam per frame.""" + t = np.concatenate([np.arange(0, 1, 0.1), np.arange(10, 11, 0.1)]) + T = np.tile(np.eye(4), (len(t), 1, 1)) + T[:, 0, 3] = np.concatenate([np.arange(10) * 0.1, np.arange(10) * 0.1]) + tags = {0: np.array([0.5, 0.2, 2.0]), 1: np.array([-0.4, 0.0, 2.5]), 2: np.array([0.3, -0.3, 3.0])} + return (t * 1e9).astype(np.int64), T, tags + + +def test_perfect_trajectory_scores_zero_in_any_world_frame(): + t, T, tags = _two_laps() + det = _sightings(tags, t, T) + W = np.eye(4) + W[:3, :3] = cv2.Rodrigues(np.array([0.1, 1.2, -0.3]))[0] + W[:3, 3] = [5, -2, 1] # the result's own world frame + r = markers.score_result(det, t, W @ T, tags, closed=False, pass_gap=2.0) + assert r["sightings_tracked"] == len(det) + assert r["repeatability_m"]["rms"] < 1e-9 + assert r["absolute_m"]["rmse"] < 1e-6 + + +def test_drift_between_laps_shows_in_repeatability_and_growth(): + t, T, tags = _two_laps() + det = _sightings(tags, t, T) + est = T.copy() + est[10:, 0, 3] += 0.3 # lap 2 believes it is 0.3 m further along + r = markers.score_result(det, t, est, tags, closed=False, pass_gap=2.0) + assert r["repeatability_m"]["rms"] == pytest.approx(0.15, abs=1e-6) + assert r["drift_from_first_pass_m"][1] == pytest.approx(0.3, abs=1e-6) + assert r["absolute_m"]["rmse"] > 0.1 + # frames the result did not track are not scored + r = markers.score_result(det, t[:10], est[:10], None, closed=True, pass_gap=2.0) + assert r["sightings_tracked"] == 30 and "repeatability_m" not in r + assert r["closure_m"] == pytest.approx(0.9) + + +SETTINGS = """%YAML:1.0 +File.version: "1.0" +Camera1.fx: 50.0 +Camera1.fy: 50.0 +Camera1.cx: 31.5 +Camera1.cy: 19.5 +Camera.width: 64 +Camera.height: 40 +Camera.fps: 30 +IMU.T_b_c1: !!opencv-matrix + rows: 4 + cols: 4 + dt: f + data: [1, 0, 0, 0.05, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] +IMU.NoiseGyro: 0.01 +IMU.NoiseAcc: 0.1 +IMU.GyroWalk: 1e-06 +IMU.AccWalk: 0.0001 +IMU.Frequency: 200.0 +""" + + +def test_car_recording_converts_to_a_sequence(tmp_path, monkeypatch): + u = uuid.uuid4().hex[:8] + fb = FrameBuffer(slots=8, name=f"vb_f_{u}", max_payload=16 + 64 * 40 * 7) + ib = RawIMUBuffer(slots=64, name=f"vb_i_{u}") + rec = tmp_path / "rec" + try: + w = BufferRecorderWorker(name="recorder", output_dir=str(rec), buffers={"frame": fb, "raw_imu": ib}) + w._logger = MagicMock() + w.setup() + t0 = 500.0 + for k in range(40): # 200 Hz IMU, a frame every 6th sample + t = t0 + k * 0.005 + ib.write(np.array([0, 0, 9.81, 0, 0, 0.1 * k], np.float32), ts=t) + if k % 6 == 0: + rgb = np.full((40, 64, 3), k, np.uint8) + fb.write(rgb, np.full((40, 64), 1.25, np.float32), ts=t) + w.step() + w.teardown() + finally: + fb.unlink() + ib.unlink() + settings = tmp_path / "s.yaml" + settings.write_text(SETTINGS) + out = tmp_path / "seq" + monkeypatch.setattr(sys, "argv", ["car_to_rgbdi.py", str(rec), "--settings", str(settings), "--out", str(out)]) + assert car_to_rgbdi.main() == 0 + + seq = rgbdi.load(str(out)) + assert len(seq.t_ns) == 7 + assert seq.t_ns[0] == int(round(t0 * 1e9)) + assert seq.calib["fx"] == 50.0 and seq.calib["imu"]["rate_hz"] == 200.0 + np.testing.assert_allclose(seq.T_imu_cam[0, 3], 0.05) + assert (seq.imu[:, 0] >= seq.t_ns[0] - 5e7).all() + np.testing.assert_allclose(seq.imu[:3, 3], 9.81, atol=1e-5) + depth = cv2.imread(seq.depth[0], cv2.IMREAD_UNCHANGED) + assert depth.dtype == np.uint16 and int(depth[0, 0]) == 1250 + rgb = cv2.imread(seq.rgb[2], cv2.IMREAD_COLOR) + assert int(rgb[0, 0, 0]) == 12 + + +def test_markers_cli_on_a_rendered_sequence(tmp_path, monkeypatch): + """Two passes along a straight past three tags; a perfect and a drifting result.""" + import json + + import yaml + + tags = {0: np.array([-0.5, 0.0, 1.4]), 1: np.array([0.0, -0.2, 1.6]), 2: np.array([0.5, 0.1, 1.3])} + face = np.diag([1.0, -1.0, -1.0]) # tags face the camera (-z) + t_ns, T = [], [] + for k in range(12): # passes at 0-0.55 s and 10-10.55 s + t = (k % 6) * 0.1 + (10.0 if k >= 6 else 0.0) + Twc = np.eye(4) + Twc[0, 3] = 0.02 * (k % 6) + t_ns.append(int(t * 1e9)) + T.append(Twc) + (tmp_path / "seq" / "rgb").mkdir(parents=True) + (tmp_path / "seq" / "depth").mkdir() + with open(tmp_path / "seq" / "frames.csv", "w") as f: + f.write("t_ns,rgb,depth\n") + for t, Twc in zip(t_ns, T): + img = np.full((400, 640), 255, np.uint8) + Tcw = np.linalg.inv(Twc) + for i, p in tags.items(): + one = _render_tag(i, 0.16, Tcw[:3, :3] @ face, (Tcw @ np.append(p, 1))[:3]) + img = np.minimum(img, one) + cv2.imwrite(str(tmp_path / "seq" / "rgb" / f"{t}.png"), img) + cv2.imwrite(str(tmp_path / "seq" / "depth" / f"{t}.png"), np.zeros((400, 640), np.uint16)) + f.write(f"{t},rgb/{t}.png,depth/{t}.png\n") + (tmp_path / "seq" / "imu.csv").write_text("t_ns,ax,ay,az,gx,gy,gz\n0,0,0,9.81,0,0,0\n") + calib = {"width": 640, "height": 400, "fx": 400.0, "fy": 400.0, "cx": 320.0, "cy": 200.0, + "T_imu_cam": np.eye(4).tolist(), "imu": {"rate_hz": 200.0}} + (tmp_path / "seq" / "calib.yaml").write_text(yaml.safe_dump(calib)) + est = [Ti.copy() for Ti in T] + for Ti in est[6:]: + Ti[0, 3] += 0.2 # the second pass is 0.2 m off + for name, poses in (("perfect", T), ("drift", est)): + d = tmp_path / "res" / name + d.mkdir(parents=True) + rgbdi.write_poses(str(d / "poses.csv"), np.array(t_ns), np.array(poses)) + (d / "meta.json").write_text(json.dumps({"mode": "test"})) + survey = {"family": "36h11", "size_m": 0.16, "tags": {i: p.tolist() for i, p in tags.items()}} + (tmp_path / "markers.yaml").write_text(yaml.safe_dump(survey)) + monkeypatch.setattr(sys, "argv", ["markers.py", str(tmp_path / "seq"), str(tmp_path / "res" / "perfect"), + str(tmp_path / "res" / "drift"), "--survey", str(tmp_path / "markers.yaml"), + "--out", str(tmp_path / "out")]) + assert markers.main() == 0 + perfect, drift = json.loads((tmp_path / "out" / "markers.json").read_text()) + assert perfect["tags_seen"] == 3 and perfect["sightings_tracked"] == 36 + assert perfect["repeatability_m"]["rms"] < 0.01 + assert perfect["absolute_m"]["rmse"] < 0.02 + assert drift["drift_from_first_pass_m"]["1"] == pytest.approx(0.2, abs=0.02) + + +def test_rendered_depth_is_exact(): + """render_track.Scene: floor and wall depths along known rays, and a textured image.""" + import render_track + + inner = np.array([[30.0, -1.0], [31.0, -1.0], [31.0, 1.0], [30.0, 1.0]]) # out of the way + outer = np.array([[-5.0, -5.0], [5.0, -5.0], [5.0, 5.0], [-5.0, 5.0]]) # wall 5 m ahead + scene = render_track.Scene(inner, outer) + T = np.eye(4) + T[:3, :3] = np.column_stack([[0, -1, 0], [0, 0, -1], [1, 0, 0]]) # optical z along world x, level + T[:3, 3] = [0.0, 0.0, 0.2] # 0.2 m above the floor + K = (400.0, 400.0, 319.5, 199.5) + depth = scene.cast(T, K, 640, 400, colour=False) + assert depth[199 + 41, 319] == pytest.approx(0.2 * 400 / (41 - 0.5), rel=1e-9) # floor + assert depth[199 - 4, 319] == pytest.approx(5.0, rel=1e-9) # wall + assert depth[0, 319] == 0.0 # above the wall + img = scene.cast(T, K, 640, 400, colour=True) + assert img.shape == (400, 640) and img[250:].std() > 20 # textured floor diff --git a/workers/__init__.py b/workers/__init__.py index 47ac991..4a477b0 100644 --- a/workers/__init__.py +++ b/workers/__init__.py @@ -12,6 +12,7 @@ from .state_worker import StateWorker from .sim_decoder import SimDecoder from .lidar_projection_worker import LidarProjectionWorker +from .seg_scan_worker import SegScanWorker from .autodrive_worker import AutoDRIVEWorker __all__ = [ @@ -27,5 +28,6 @@ "StateWorker", "SimDecoder", "LidarProjectionWorker", + "SegScanWorker", "AutoDRIVEWorker", ] diff --git a/workers/autodrive_worker.py b/workers/autodrive_worker.py index aebe6f8..f9cec21 100644 --- a/workers/autodrive_worker.py +++ b/workers/autodrive_worker.py @@ -134,11 +134,14 @@ class AutoDRIVEWorker(SimDecoder): sim_depth {camera: sim_camera/camera.yaml, scale: 2}: RGB-D for ORB-SLAM3 from a camera without depth (workers/lidar_depth.py): the frame is upscaled, the car body hidden, depth comes from the same message's LiDAR scan + pose_degrade control.pose_degrade.PoseDegradeConfig fields: the ground-truth pose + published late, noisy, drifting and with dropouts, like SLAM's """ def __init__(self, name: str = "autodrive", **kwargs: Any) -> None: super().__init__(name, **kwargs) self._server = None + self._depth_source = "none" # sim_depth.depth (setup); never the LiDAR self._server_thread: Optional[threading.Thread] = None self._ws = None self._ws_lock: Optional[threading.Lock] = None # created in setup(): spawn pickles the worker @@ -156,6 +159,7 @@ def __init__(self, name: str = "autodrive", **kwargs: Any) -> None: self._frames = 0 self._connections = 0 self._last_rx = 0.0 + self._degrader = None # setup / teardown @@ -183,7 +187,21 @@ def setup(self) -> None: self._reset_started: Optional[float] = None self._dedupe = bool(cfg.get("sim_time_dedupe", True)) self._depth_fn = None + self._depth_source = "none" self._frame_errors = 0 + self._degrader = None + pd = dict(cfg.get("pose_degrade") or {}) + if pd.get("enabled") and self._pose_buf is not None: + from control.pose_degrade import PoseDegradeConfig, PoseDegrader + + self._degrader = PoseDegrader(PoseDegradeConfig(**pd)) + self._degrade_lock = threading.Lock() + threading.Thread(target=self._release_poses, daemon=True, name="pose-degrade").start() + c = self._degrader.cfg + self.logger.info(f"Pose degraded like SLAM: +{c.base_latency_s * 1000:.0f} ms + tracking " + f"{c.latency_median_s * 1000:.1f}/{c.latency_p95_s * 1000:.1f} ms (p50/p95), " + f"noise {c.xy_sigma} m / {c.yaw_sigma} rad, bias {c.bias_sigma} m over {c.bias_tau} s, " + f"{c.dropout_rate}/s dropouts of {c.dropout_s} s") sd = cfg.get("sim_depth") if sd and self._frame_buf is not None: from .lidar_depth import CameraModel, LidarDepth @@ -191,7 +209,13 @@ def setup(self) -> None: cam = CameraModel.from_yaml(sd.get("camera", "sim_camera/camera.yaml"), scale=float(sd.get("scale", 2.0))) self._depth_fn = LidarDepth(cam) self._depth_clahe = bool(sd.get("clahe", True)) - self.logger.info(f"RGB-D from LiDAR: {cam.size[0]}x{cam.size[1]}, vfov {cam.vfov_deg:.1f} deg, " + # depth: lidar (synthesised from the 2-D LiDAR) or none (frames prepared the same way, + # depth all zero: no LiDAR is used; the segmentation scan places edges on the floor) + self._depth_source = str(sd.get("depth", "none")) + if self._depth_source not in ("lidar", "none"): + raise ValueError(f"sim_depth.depth must be lidar or none, not {self._depth_source!r}") + self.logger.info(f"{'RGB-D from LiDAR' if self._depth_source == 'lidar' else 'RGB, no depth (no LiDAR)'}: " + f"{cam.size[0]}x{cam.size[1]}, vfov {cam.vfov_deg:.1f} deg, " f"car mask {'on' if self._depth_fn.mask is not None else 'off'}") log_dir = cfg.get("log_dir") @@ -216,6 +240,20 @@ def setup(self) -> None: f"connect the sim (HUD 'Disconnected' toggle, or scripts/autodrive_sim_ctl.py connect)" ) + def _write_pose(self, pose: np.ndarray, speed: float, ts: float) -> None: + if self._degrader is None: + return super()._write_pose(pose, speed, ts) + with self._degrade_lock: + self._degrader.add(ts, pose) + + def _release_poses(self) -> None: + while not self._closing: + with self._degrade_lock: + ready = self._degrader.due(time.monotonic()) + for t, pose in ready: + self._pose_buf.write(pose, None, speed=0.0, ts=t) + time.sleep(0.002) + def step(self) -> None: now = time.monotonic() self._check_silence(now) @@ -321,7 +359,8 @@ def _on_bridge(self, ws, raw: str) -> None: # (and so the controller) or the other sensors try: if self._frame_buf is not None: - if self._depth_fn is not None and data.get("front_camera") and data.get("lidar"): + if self._depth_fn is not None and data.get("front_camera") and ( + self._depth_source == "none" or data.get("lidar")): self._write_rgbd(data) else: self._process_frame_data(data) @@ -340,7 +379,8 @@ def _on_bridge(self, ws, raw: str) -> None: self._log_message(data, sim_time, new_frame, *sent) def _write_rgbd(self, data: dict) -> None: - """Sim camera + LiDAR depth -> frame_buf (see workers/lidar_depth.py).""" + """Sim camera (upscaled, car body painted out) + LiDAR depth, or none -> frame_buf + (see workers/lidar_depth.py).""" import cv2 from .lidar_depth import mask_rgb @@ -352,7 +392,10 @@ def _write_rgbd(self, data: dict) -> None: w, h = self._depth_fn.cam.size rgb = cv2.resize(cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB), (w, h), interpolation=cv2.INTER_LINEAR) rgb = mask_rgb(rgb, self._depth_fn.mask, clahe=self._depth_clahe) - depth = self._depth_fn(np.asarray(data["lidar"], dtype=np.float32)) + if self._depth_source == "none": + depth = np.zeros((h, w), dtype=np.float32) + else: + depth = self._depth_fn(np.asarray(data["lidar"], dtype=np.float32)) self._frame_buf.write(np.ascontiguousarray(rgb), depth) def _command(self, now: float) -> tuple[float, float, float]: diff --git a/workers/camera_worker.py b/workers/camera_worker.py index 469bdc3..d45e868 100644 --- a/workers/camera_worker.py +++ b/workers/camera_worker.py @@ -71,6 +71,8 @@ class CameraWorker(BaseWorker): fps default 30 resolution [w, h] for RGB and depth, default [640, 400] imu_buffer stream the on-board IMU into it if given + raw_imu_buffer also stream accel + all three gyro axes (RawIMUBuffer), for + ORB-SLAM3's RGB-D-inertial mode imu_rate_hz default 100 max_exposure_us auto-exposure limit, default 4000 (0 = DepthAI default) settings_path ORB-SLAM3 settings to check against, default orbslam_oakd_rgbd.yaml @@ -88,6 +90,7 @@ def __init__(self, name: str = "camera", **kwargs: Any) -> None: self._sync_q = None self._frame_count: int = 0 self._imu_buf = None + self._raw_imu_buf = None self._imu_q = None self._has_rotation_vector = False self._step_errors = 0 @@ -101,6 +104,7 @@ def setup(self) -> None: raise RuntimeError("depthai is not installed; CameraWorker needs it for the OAK-D") self._frame_buf = self.config["output_buffer"] self._imu_buf = self.config.get("imu_buffer") + self._raw_imu_buf = self.config.get("raw_imu_buffer") self._frame_timeout = float(self.config.get("frame_timeout_s", 1.0)) self._startup_timeout = float(self.config.get("startup_timeout_s", 5.0)) self._max_step_errors = int(self.config.get("max_step_errors", 5)) @@ -170,7 +174,7 @@ def _start_device(self) -> None: self._sync_q = sync.out.createOutputQueue(maxSize=2, blocking=False) self._imu_q = None - if self._imu_buf is not None: + if self._imu_buf is not None or self._raw_imu_buf is not None: self._setup_imu(device, self.config.get("imu_rate_hz", 100)) self._pipeline.start() @@ -298,7 +302,8 @@ def _setup_imu(self, device, rate_hz: int) -> None: def _drain_imu(self) -> None: """Push pending IMU packets as [qw, qx, qy, qz, ax, ay, az, gx, gy] (gyro x/y where the I2C path has throttle/steering feedback), stamped with the - accelerometer capture time. Quaternion is NaN without a rotation vector.""" + accelerometer capture time. Quaternion is NaN without a rotation vector. + With a raw_imu_buffer, also [ax, ay, az, gx, gy, gz] per packet.""" for imu_data in self._imu_q.tryGetAll(): for packet in imu_data.packets: acc = packet.acceleroMeter @@ -308,10 +313,19 @@ def _drain_imu(self) -> None: quat = (rv.real, rv.i, rv.j, rv.k) else: quat = (np.nan,) * 4 - vec = np.array( - [*quat, acc.x, acc.y, acc.z, gyro.x, gyro.y], dtype=np.float32 - ) - self._imu_buf.write(vec, ts=acc.getTimestamp().total_seconds()) + ts = acc.getTimestamp().total_seconds() + if self._imu_buf is not None: + vec = np.array( + [*quat, acc.x, acc.y, acc.z, gyro.x, gyro.y], dtype=np.float32 + ) + self._imu_buf.write(vec, ts=ts) + if self._raw_imu_buf is not None: + # a packet pairs an accel and a gyro sample whose own stamps can differ + # by up to a sample period: stamp the pair with their mean + t_pair = 0.5 * (ts + gyro.getTimestamp().total_seconds()) + self._raw_imu_buf.write( + np.array([acc.x, acc.y, acc.z, gyro.x, gyro.y, gyro.z], dtype=np.float32), + ts=t_pair) def step(self) -> None: try: diff --git a/workers/control_worker.py b/workers/control_worker.py index 9951223..5fd2ca8 100644 --- a/workers/control_worker.py +++ b/workers/control_worker.py @@ -41,14 +41,12 @@ class ControlWorker(BaseWorker): mode one of TRACK_MODES, depth_ftg, vae, bc (default pure_pursuit) output_buffer ControlBuffer armed_event optional; controllers are reset on arming so nothing winds up + jump_reset_m optional; a state this far from the last one resets them too (sim respawn) state_buffer, boundary_buffer, mapping_done_event track modes track_config track_control config section (fallback: depth_ftg; mapping_drive: LidarGapConfig fields, drives the mapping lap) - lidar_buffer LidarBuffer, for track_config.mapping_drive (simulator) - segment_buffer SegmentationBuffer: without a lidar_buffer, mapping_drive gets an - approximate scan from the mask's edge and the frame's depth - (control/seg_scan.py; needs frame_buffer) - seg_scan seg_scan config: camera_settings + SegScanConfig fields + lidar_buffer LidarBuffer of LiDAR-format scans for track_config.mapping_drive: + SegScanWorker's segmentation-edge scan, on the car and in the sim vehicle_params vehicle params YAML safety runtime safety settings, compared with a policy's frame_buffer, camera_settings, depth_ftg_config depth_ftg / fallback @@ -109,6 +107,8 @@ def _setup_track(self) -> None: self._vehicle = VehicleParams.load(self.config.get("vehicle_params", "vehicle_params.yaml")) self._track_cfg = self.config.get("track_config", {}) self._last_state_seq = 0 + self._last_state_xy = None + self._jump_reset_m = self.config.get("jump_reset_m") self._last_state_time = time.monotonic() self._next_policy_step = 0.0 if self._track_cfg.get("fallback") == "depth_ftg": @@ -116,18 +116,22 @@ def _setup_track(self) -> None: self._fallback_after = float(self._track_cfg.get("fallback_after", 0.3)) self._fallback_active = False drive_cfg = self._track_cfg.get("mapping_drive") + done = self.config.get("mapping_done_event") + if drive_cfg and self.config.get("lidar_buffer") is None and done is not None and done.is_set(): + drive_cfg = None # racing on a saved map: there is no mapping lap to drive if drive_cfg: from control.lidar_gap import LidarGapConfig, LidarGapFollower self._lidar_buf = self.config.get("lidar_buffer") self._last_lidar_seq = 0 if self._lidar_buf is None: - self._setup_seg_scan() + raise RuntimeError("mapping_drive needs a scan: lidar_buffer (SegScanWorker's output, " + "vision.enabled)") cfg = dict(drive_cfg) cfg.setdefault("speed_per_throttle", self._track_cfg.get("speed", {}).get( "longitudinal", {}).get("speed_per_throttle", 3.0)) self._mapping_driver = LidarGapFollower(self._vehicle, LidarGapConfig(**cfg)) - source = "LiDAR" if self._lidar_buf is not None else "segmentation-edge scan" + source = self.config.get("scan_name") or "segmentation-edge scan" self.logger.info(f"Mapping lap driven by follow-the-gap on the {source} ({cfg})") self.logger.info( f"ControlWorker ready — {self._mode} mode " @@ -137,6 +141,7 @@ def _setup_track(self) -> None: def _build_follower(self, outer: np.ndarray, inner: np.ndarray, state) -> None: from control.controllers import build_track_follower from control.track import TrackModel + from control.types import resolve_path cfg = self._track_cfg if self._mode == "policy": @@ -154,6 +159,11 @@ def _build_follower(self, outer: np.ndarray, inner: np.ndarray, state) -> None: self.logger.warning(f"Policy was trained with different safety settings: {trained}") return track = TrackModel(outer, inner, spacing=cfg.get("spacing", 0.05)) + raceline = cfg.get("raceline_path") + if raceline: + # precomputed by scripts/make_raceline.py from the same map + track.set_path(np.load(resolve_path(raceline)), spacing=cfg.get("spacing", 0.05)) + self.logger.info(f"Following the racing line {raceline}") reversed_ = track.align_direction(state.x, state.y, state.yaw) self._follower = build_track_follower( self._mode, track, self._vehicle, cfg.get(self._mode, {}), cfg.get("speed", {}) @@ -183,6 +193,14 @@ def _step_track(self) -> None: header, state = result self._last_state_seq = header.seq_no self._last_state_time = time.monotonic() + if self._jump_reset_m is not None and self._last_state_xy is not None and \ + np.hypot(state.x - self._last_state_xy[0], state.y - self._last_state_xy[1]) > self._jump_reset_m: + # the car was put somewhere else (sim respawn): nothing the controllers integrated applies + for follower in (self._follower, self._fallback): + if follower is not None: + follower.reset() + self.logger.info("Pose jump (respawn?) — controllers reset") + self._last_state_xy = (state.x, state.y) if self._fallback is not None and self._fallback_active: self._fallback_active = False if self._follower is not None: @@ -213,48 +231,15 @@ def _step_track(self) -> None: f"steer={cmd.steering:+.3f} throttle={cmd.throttle:+.3f}" ) - def _setup_seg_scan(self) -> None: - """No LiDAR: build the mapping drive's scan from the segmentation mask + depth.""" - from control.depth_ftg import Intrinsics - from control.seg_scan import SegScanConfig - - self._seg_buf = self.config.get("segment_buffer") - self._frame_buf = self.config.get("frame_buffer") - if self._seg_buf is None or self._frame_buf is None: - raise RuntimeError("mapping_drive needs a scan: a lidar_buffer, or a segment_buffer and " - "frame_buffer for the segmentation-edge scan (vision.enabled)") - cfg = dict(self.config.get("seg_scan", {})) - self._seg_K = Intrinsics.from_orbslam_settings( - cfg.pop("camera_settings", self.config.get("camera_settings", "orbslam_oakd_rgbd.yaml"))) - self._seg_cfg = SegScanConfig(**cfg) - def _read_scan(self): - """Newest unseen scan as (header, ranges), or None: the LiDAR's, or one built from the - newest mask and the depth of the frame it was computed from.""" - if self._lidar_buf is not None: - result = self._lidar_buf.read_latest() - if result is None or result[0].seq_no <= self._last_lidar_seq: - return None - return result - from control.seg_scan import seg_edge_scan - - seg = self._seg_buf.read_latest() - if seg is None or seg[0].seq_no <= self._last_lidar_seq: - return None - header, mask = seg - # VisionWorker stamps a mask with its frame's capture time: find that frame's depth - frames = [self._frame_buf.read_latest()] - if frames[0] is not None and frames[0][0].produced_ts != header.produced_ts: - frames = self._frame_buf.read_since(max(0, frames[0][0].seq_no - 3)) # 1-2 behind normally - depth = next((f[2] for f in frames if f is not None and f[0].produced_ts == header.produced_ts), None) - if depth is None: - self._last_lidar_seq = header.seq_no # its frame has left the ring; wait for the next + """Newest unseen scan as (header, ranges), or None.""" + result = self._lidar_buf.read_latest() + if result is None or result[0].seq_no <= self._last_lidar_seq: return None - return header, seg_edge_scan(mask, depth, self._seg_K, self._seg_cfg) + return result def _step_mapping_drive(self) -> None: - """Follow-the-gap until the track is mapped (sim stand-in for the RC lap): on the - LiDAR, or without one on the segmentation-edge scan.""" + """Follow-the-gap on the segmentation-edge scan until the track is mapped.""" result = self._read_scan() now = time.monotonic() if result is None: diff --git a/workers/imu_worker.py b/workers/imu_worker.py index 93b220e..90c3d59 100644 --- a/workers/imu_worker.py +++ b/workers/imu_worker.py @@ -2,6 +2,13 @@ Arduino IMU over I2C -> IMUBuffer vectors [qw, qx, qy, qz, ax, ay, az, throttle_raw, steering_raw], accel in m/s^2, stamped with host time.monotonic() at the read. The OAK-D IMU is streamed by CameraWorker. + +With a raw_output_buffer (RawIMUBuffer), also the 6-axis sample [ax, ay, az (m/s^2), +gx, gy, gz (rad/s)] in the ICM-20948's axes, for the vehicle-state EKF (rear_imu in the +config): the firmware sends accel in g and gyro in deg/s, bias-corrected at its start-up +(it also forces accel to (0, 0, 1 g) at rest, so the mounting can't be seen at rest: +scripts/check_rear_imu.py finds it from motion). The Jetson polls the latest sample, so a +poll can return the one it already had: those repeats are not written. """ from __future__ import annotations @@ -22,8 +29,9 @@ G = 9.80665 # m/s^2 per g -# Arduino frame (firmware jetson_i2c.cpp): quat wxyz, accel xyz (g), gyro xyz, mag xyz -# (float32 each), Arduino ms (uint32), throttle, steering raw (uint16) +# Arduino frame (firmware jetson_i2c.cpp): quat wxyz, accel xyz (g), gyro xyz (deg/s), +# mag xyz (float32 each), micros() of the last DMP quaternion update (uint32, wraps every +# ~71.6 min), throttle, steering raw (uint16) I2C_FRAME = struct.Struct("<4f3f3f3fIHH") I2C_FRAME_SIZE = I2C_FRAME.size # 60 @@ -51,13 +59,28 @@ def parse_i2c_frame(raw: bytes) -> np.ndarray | None: ) +def parse_i2c_raw(raw: bytes) -> np.ndarray | None: + """60-byte Arduino frame -> (6,) [ax, ay, az (m/s^2), gx, gy, gz (rad/s)], sensor axes. + None if short, non-finite or out of the ICM-20948's ranges (16 g, 2000 deg/s).""" + if len(raw) < I2C_FRAME_SIZE: + return None + v = I2C_FRAME.unpack_from(raw) + acc_g, gyro_dps = np.array(v[4:7], dtype=np.float64), np.array(v[7:10], dtype=np.float64) + if not (np.all(np.isfinite(acc_g)) and np.all(np.isfinite(gyro_dps))): + return None + if np.abs(acc_g).max() > 16.5 or np.abs(gyro_dps).max() > 2050.0: + return None + return np.concatenate([acc_g * G, np.radians(gyro_dps)]).astype(np.float32) + + class IMUWorker(BaseWorker): """IMU worker. I2C errors are retried with back-off (up to 1 s), never fatal. Without a full I2C address/bus it idles: no fake data when a real sensor is expected. Config kwargs: - output_buffer IMUBuffer + output_buffer IMUBuffer + raw_output_buffer RawIMUBuffer for the 6-axis sample (optional, rear_imu) i2c_address Arduino I2C address i2c_bus I2C bus number poll_hz I2C polling rate, default 100 @@ -71,9 +94,15 @@ def __init__(self, name: str = "imu", **kwargs: Any) -> None: self._errors = 0 self._period = 0.01 self._next_poll = 0.0 + self._raw_buf = None + self._last_raw: bytes | None = None + self._raw_written = 0 + self._raw_repeats = 0 + self._stats_t = 0.0 def setup(self) -> None: self._imu_buf = self.config["output_buffer"] + self._raw_buf = self.config.get("raw_output_buffer") i2c_address = self.config.get("i2c_address") i2c_bus = self.config.get("i2c_bus") @@ -124,11 +153,32 @@ def _step_i2c(self) -> None: self.logger.info(f"I2C reads back after {self._errors} errors") self._errors = 0 - vec = parse_i2c_frame(bytes(msg)) + data = bytes(msg) + vec = parse_i2c_frame(data) if vec is None: # e.g. the 4-byte handshake reply or a garbled transfer return self._imu_buf.write(vec, ts=ts) + if self._raw_buf is not None: + self._write_raw(data, ts) + + def _write_raw(self, data: bytes, ts: float) -> None: + sample = parse_i2c_raw(data) + if sample is None: + return + key = data[16:40] # accel + gyro bytes: unchanged = the same sample + if key == self._last_raw: + self._raw_repeats += 1 + else: + self._last_raw = key + self._raw_buf.write(sample, ts=ts) + self._raw_written += 1 + if ts - self._stats_t >= 30.0: + if self._stats_t: + n = self._raw_written + self._raw_repeats + self.logger.info(f"rear IMU: {self._raw_written / (ts - self._stats_t):.0f} new samples/s, " + f"{100.0 * self._raw_repeats / max(n, 1):.0f} % of polls repeated the last one") + self._stats_t, self._raw_written, self._raw_repeats = ts, 0, 0 def step(self) -> None: if self._dummy: diff --git a/workers/lidar_projection_worker.py b/workers/lidar_projection_worker.py index b7d02cb..63a55f9 100644 --- a/workers/lidar_projection_worker.py +++ b/workers/lidar_projection_worker.py @@ -57,6 +57,8 @@ def __init__(self, name: str = "lidar_proj", **kwargs: Any) -> None: self._last_lidar_seq: int = 0 self._last_proj_pos: np.ndarray | None = None self._frame_count: int = 0 + self._pose_seq = 0 + self._poses: list = [] # (t, Twv) of the last second, to project a scan with its own pose # ray angles are fixed, precompute angles = _ANGLE_MIN + np.arange(_N_RAYS) * _ANGLE_INCREMENT @@ -71,6 +73,9 @@ def setup(self) -> None: self._range_max = float(self.config.get("range_max", 9.5)) self._voxel_size = float(self.config.get("voxel_size", 0.10)) self._move_threshold = float(self.config.get("move_threshold", 0.05)) + # the scan origin in the vehicle frame: the LiDAR's mount, or the camera's for a scan + # built from the segmentation (SegScanWorker) + self._offset = np.asarray(self.config.get("scan_offset", _LIDAR_OFFSET), dtype=np.float32) self._pc_capacity = self._pc_buf.max_points self.logger.info( f"LidarProjectionWorker ready " @@ -93,10 +98,9 @@ def step(self) -> None: return self._last_lidar_seq = lidar_header.seq_no - pose_result = self._pose_buf.read_latest() - if pose_result is None: + pose = self._pose_at(lidar_header.produced_ts) + if pose is None: return - pose = pose_result[1] # 4x4 float32 Twv (world-from-vehicle) current_pos = pose[:2, 3] if self._last_proj_pos is not None: @@ -132,6 +136,21 @@ def step(self) -> None: f"frame={self._frame_count}" ) + def _pose_at(self, t: float): + """Twv (4x4) nearest in time to t from the recent poses: a scan built from a camera frame + (SegScanWorker) is older than the latest pose by the segmentation's latency, which at + a hairpin's yaw rate smears the points. None without a pose.""" + for header, pose, *_ in self._pose_buf.read_since(self._pose_seq): + self._pose_seq = header.seq_no + self._poses.append((header.produced_ts, pose)) + if not self._poses: + res = self._pose_buf.read_latest() + return None if res is None else res[1] + cutoff = self._poses[-1][0] - 1.0 + while len(self._poses) > 1 and self._poses[0][0] < cutoff: + self._poses.pop(0) + return min(self._poses, key=lambda p: abs(p[0] - t))[1] + def _add_to_voxel_map(self, pts: np.ndarray) -> int: """Add the points whose voxel is still empty; returns how many were new. @@ -163,9 +182,9 @@ def _project_scan(self, ranges: np.ndarray, pose: np.ndarray) -> np.ndarray: z_lidar = np.zeros(len(r), dtype=np.float32) # mount offset only, the LIDAR isn't rotated relative to the car - x_veh = x_lidar + _LIDAR_OFFSET[0] - y_veh = y_lidar + _LIDAR_OFFSET[1] - z_veh = z_lidar + _LIDAR_OFFSET[2] + x_veh = x_lidar + self._offset[0] + y_veh = y_lidar + self._offset[1] + z_veh = z_lidar + self._offset[2] pts_veh = np.stack([x_veh, y_veh, z_veh], axis=1) # (N, 3) diff --git a/workers/mapping_worker.py b/workers/mapping_worker.py index 5ce9132..770f8bd 100644 --- a/workers/mapping_worker.py +++ b/workers/mapping_worker.py @@ -1,8 +1,15 @@ """ MappingWorker: records the driven BEV trajectory (PoseBuffer, or SLAM keyframes if -given) and the newest wall point cloud, and on ``loop_event`` extracts outer/inner -track boundaries (extract_track_boundaries) into TrackBoundaryBuffer, then sets -mapping_done_event. map_reset_event (SLAM world frame changed) drops everything recorded. +given) and the walls, and on ``loop_event`` extracts outer/inner track boundaries into +TrackBoundaryBuffer, then sets mapping_done_event. map_reset_event (SLAM world frame +changed) drops everything recorded. + +Two wall sources: + cloud the newest wall point cloud (SLAM map points, or projected scans), boundaries + by extract_track_boundaries + occupancy the segmentation-edge scans themselves, on an occupancy grid + (control/occupancy_map.py): rays free the floor they cross, so edges placed + short from far away are cleared by the floor seen up close """ from __future__ import annotations @@ -20,6 +27,12 @@ from shared_buffer.pointcloud_buffer import PointCloudBuffer from shared_buffer.track_boundary_buffer import TrackBoundaryBuffer +# m; the sim respawns to fixed checkpoints, up to 1.3 m off the path driven (compete build). +# Further off than this the car was moved elsewhere and the lap starts again. +RESPAWN_MAX_OFF_PATH = 2.0 +# m/s; a pose step faster than this is a teleport (the car tops out near 8 m/s in the sim) +TELEPORT_SPEED = 12.0 + def _to_bev(points_3d: np.ndarray, axes: tuple = (0, 2)) -> np.ndarray: """3D -> BEV, just picks out the two horizontal axes.""" @@ -291,6 +304,11 @@ class MappingWorker(BaseWorker): the car after a wall hit): the trajectory is cut back to the point nearest the new pose. Default None (off): SLAM poses can legitimately be sparse + wall_source "cloud" (default) or "occupancy" + scan_buffer LidarBuffer of segmentation-edge scans without edge memory + (SegScanWorker raw_output_buffer); wall_source occupancy + scan_offset [forward, left, up] of the scan origin in the vehicle frame, m + occupancy control.occupancy_map.OccupancyConfig overrides """ def __init__(self, name: str = "mapping", **kwargs: Any) -> None: @@ -319,7 +337,24 @@ def __init__(self, name: str = "mapping", **kwargs: Any) -> None: def setup(self) -> None: c = self.config self._pose_buf = c["pose_buffer"] - self._pc_buf = c["pointcloud_buffer"] + self._wall_source = c.get("wall_source", "cloud") + if self._wall_source not in ("cloud", "occupancy"): + raise ValueError(f"wall_source must be cloud or occupancy, not {self._wall_source!r}") + self._pc_buf = c.get("pointcloud_buffer") + if self._wall_source == "cloud" and self._pc_buf is None: + raise ValueError("wall_source cloud needs a pointcloud_buffer") + self._mapper = None + if self._wall_source == "occupancy": + from control.lidar_gap import ANGLE_INCREMENT, ANGLE_MIN + from control.occupancy_map import OccupancyConfig, OccupancyTrackMapper + + self._scan_buf = c["scan_buffer"] + self._mapper = OccupancyTrackMapper(OccupancyConfig(**dict(c.get("occupancy") or {}))) + self._scan_angles = ANGLE_MIN + np.arange(1080) * ANGLE_INCREMENT + self._scan_offset = np.asarray(list(c.get("scan_offset", [0.0, 0.0]))[:2], dtype=np.float64) + self._last_scan_seq = 0 + self._hist_seq = 0 + self._pose_hist: list[tuple[float, float, float, float]] = [] # (t, x, y, heading) self._kf_buf = c.get("keyframe_buffer") self._boundary_buf = c["boundary_buffer"] self._loop_event = c.get("loop_event") @@ -347,13 +382,16 @@ def setup(self) -> None: self._jump = float(jump) if jump is not None else math.inf self._path_length = 0.0 self._path_s: list[float] = [] # arc length at each trajectory point + self._last_pose_t: Optional[float] = None + self._next_extract = 0.0 + self._driven: list[tuple[float, float]] = [] # every position driven, 5 cm apart (occupancy) self._max_dist_from_start = 0.0 self._closest_start: Optional[tuple[float, float]] = None # (distance, arc length) self.logger.info( f"MappingWorker ready (min_pts={self._min_points}, " f"bev_axes={self._bev_axes}, forward_axis={self._forward_axis}, " - f"half_width={self._half_width}m, height_band={self._height_band}m)" + f"half_width={self._half_width}m, height_band={self._height_band}m, walls={self._wall_source})" ) def _reset(self) -> None: @@ -372,7 +410,14 @@ def _reset(self) -> None: self._kf_traj = None # anything already in the buffers may still be from the old map self._last_pose_seq = self._pose_buf.latest_seq() - self._last_pc_seq = self._pc_buf.latest_seq() + if self._pc_buf is not None: + self._last_pc_seq = self._pc_buf.latest_seq() + if self._mapper is not None: + self._mapper.reset() + self._driven = [] + self._pose_hist = [] + self._hist_seq = self._pose_buf.latest_seq() + self._last_scan_seq = self._scan_buf.latest_seq() if self._kf_buf is not None: self._last_kf_seq = self._kf_buf.latest_seq() self._map_reset_event.clear() @@ -390,10 +435,15 @@ def step(self) -> None: if pose_result is not None and pose_result[0].seq_no > self._last_pose_seq: pose_header, pose, _, _ = pose_result (x, y), heading = pose_to_bev(pose, self._bev_axes, self._forward_axis) + t = pose_header.produced_ts if self._bev_trajectory: step = float(np.hypot(x - self._bev_trajectory[-1][0], y - self._bev_trajectory[-1][1])) - if step > self._jump: + dt = t - self._last_pose_t if self._last_pose_t is not None else 0.0 + # a teleport, not a gap between two reads: faster than the car can drive + if step > self._jump and (dt <= 0 or step / dt > TELEPORT_SPEED): self._cut_back_to(x, y, step) + if self._mapper is not None: + self._mapper.mark_disturbance(pose_header.produced_ts) else: self._path_length += step self._bev_trajectory.append( @@ -401,11 +451,18 @@ def step(self) -> None: ) self._path_s.append(self._path_length) self._last_pose_seq = pose_header.seq_no + self._last_pose_t = t + if self._mapper is not None and ( + not self._driven or np.hypot(x - self._driven[-1][0], y - self._driven[-1][1]) > 0.05): + self._driven.append((float(x), float(y))) if self._auto_loop: self._check_auto_loop(x, y) + if self._mapper is not None: + self._read_scans() + # the cloud is the full deduplicated wall map, so replace rather than append - if self._pc_buf.latest_seq() > self._last_pc_seq: + if self._pc_buf is not None and self._pc_buf.latest_seq() > self._last_pc_seq: pc_result = self._pc_buf.read_latest() if pc_result is not None: pc_header, pts_3d = pc_result @@ -425,19 +482,42 @@ def step(self) -> None: self._loop_event is not None and self._loop_event.is_set() and not self._boundaries_extracted + and time.monotonic() >= self._next_extract ): self._extract_boundaries() time.sleep(0.01) + def _read_scans(self) -> None: + """New scans onto the occupancy grid, each placed with the pose nearest its time.""" + for header, pose, *_ in self._pose_buf.read_since(self._hist_seq): + self._hist_seq = header.seq_no + (x, y), heading = pose_to_bev(pose, self._bev_axes, self._forward_axis) + self._pose_hist.append((header.produced_ts, float(x), float(y), float(heading))) + if not self._pose_hist: + return + newest = self._pose_hist[-1][0] + self._pose_hist = [p for p in self._pose_hist if p[0] > newest - 2.0] + times = np.array([p[0] for p in self._pose_hist]) + for header, ranges in self._scan_buf.read_since(self._last_scan_seq): + self._last_scan_seq = header.seq_no + i = int(np.argmin(np.abs(times - header.produced_ts))) + if abs(times[i] - header.produced_ts) > 0.1: + continue + _, x, y, heading = self._pose_hist[i] + c, s = math.cos(heading), math.sin(heading) + fwd, left = self._scan_offset + origin = (x + fwd * c - left * s, y + fwd * s + left * c) + self._mapper.add_scan(header.produced_ts, ranges, self._scan_angles, origin, heading) + def _cut_back_to(self, x: float, y: float, step: float) -> None: """Teleport (sim respawn after a wall hit): drop the stretch the car is put back over, so the lap doesn't double back on itself.""" traj = np.array(self._bev_trajectory, dtype=np.float32)[:, :2] lo = max(0, len(traj) - 300) # the last few metres only d = np.hypot(traj[lo:, 0] - x, traj[lo:, 1] - y) - if d.min() > self._jump: - # not put back onto the path just driven (a reset to the start, a teleport): + if d.min() > RESPAWN_MAX_OFF_PATH: + # not put back near the path just driven (a reset to the start, a teleport): # start the lap again from here; the wall map stays, it is the same world self.logger.warning(f"Pose jumped {step:.2f} m off the driven path — mapping lap restarts here") self._bev_trajectory.clear() @@ -479,10 +559,29 @@ def _trajectory(self) -> tuple[np.ndarray, str]: return t[:, [0, 1, 3]], "poses" def _retry(self, msg: str) -> None: + # not a sleep: poses and scans keep coming in while the lap goes on self.logger.warning(f"{msg} — will retry in 2s") - time.sleep(2.0) + self._next_extract = time.monotonic() + 2.0 + + def _extract_occupancy(self): + """(outer, inner) from the occupancy grid, or None after scheduling a retry.""" + # everything driven, laps and respawns included: the grid only keeps floor connected to it + path = np.asarray(self._driven, dtype=np.float64).reshape(-1, 2) + try: + outer, inner = self._mapper.extract(path) + except ValueError as e: + self._retry(f"No track in the occupancy grid yet ({e})") + return None + self.logger.info(f"Occupancy map: {self._mapper.n_samples} edge samples, " + f"{len(path)} trajectory pts") + return outer, inner def _extract_boundaries(self) -> None: + if self._mapper is not None: + result = self._extract_occupancy() + if result is not None: + self._publish(*result, ccw=None, n_wall=self._mapper.n_samples) + return if not self._bev_wall_pts: return self._retry("No wall points accumulated") @@ -523,7 +622,10 @@ def _extract_boundaries(self) -> None: if len(outer) == 0 or len(inner) == 0: return self._retry(f"One side empty (outer={len(outer)}, inner={len(inner)})") + self._publish(outer, inner, ccw=ccw, n_wall=len(all_wall)) + def _publish(self, outer: np.ndarray, inner: np.ndarray, ccw: Optional[bool], n_wall: int) -> None: + """Checks, then writes and saves the boundaries and ends the mapping lap.""" if self._min_half_width is not None: from control.track import TrackModel @@ -546,15 +648,13 @@ def _extract_boundaries(self) -> None: if self._save_path is not None: import os os.makedirs(self._save_path, exist_ok=True) - np.save(os.path.join(self._save_path, "outer_line.npy"), outer) - np.save(os.path.join(self._save_path, "inner_line.npy"), inner) + np.save(os.path.join(self._save_path, "outer_line.npy"), outer.astype(np.float32)) + np.save(os.path.join(self._save_path, "inner_line.npy"), inner.astype(np.float32)) self.logger.info(f"Boundaries saved to {self._save_path}") self.logger.info("=" * 60) - self.logger.info( - f"Track mapped ({'counter-clockwise' if ccw else 'clockwise'} lap). " - f"{len(all_wall)} wall points." - ) + direction = "" if ccw is None else f" ({'counter-clockwise' if ccw else 'clockwise'} lap)" + self.logger.info(f"Track mapped{direction}. {n_wall} wall samples.") self.logger.info(f"Outer boundary: {len(outer)} pts") self.logger.info(f"Inner boundary: {len(inner)} pts") self.logger.info("=" * 60) diff --git a/workers/seg_scan_worker.py b/workers/seg_scan_worker.py new file mode 100644 index 0000000..2943d84 --- /dev/null +++ b/workers/seg_scan_worker.py @@ -0,0 +1,143 @@ +""" +SegScanWorker: segmentation mask (VisionWorker) + the depth of its frame -> a 2-D scan in the +LiDAR's format (control/seg_scan.py), for a pipeline without a LiDAR: LidarProjectionWorker +turns these scans into the wall point cloud the mapping lap's boundaries come from. + +The scan's origin is seg_scan.origin_forward behind the camera; give LidarProjectionWorker that +origin's mount in the vehicle frame as its scan_offset (and as scan_origin here). With no depth +(the sim without LiDAR) each track edge is placed where its pixel's ray meets the floor +(camera_height, camera_pitch). + +A camera sees ~60 deg, a LiDAR 270: with a pose_buffer and memory_s, the edges seen in the last +memory_s seconds are kept (world frame) and fill the beams outside the current view, so a wall +that has left the image (the inside of a hairpin) still bounds the scan the gap follower drives on. +The same scan without the remembered edges goes to raw_output_buffer for the mapping lap's +occupancy grid, where a remembered edge seen from the current origin would free floor it never saw. + +The same worker runs on the car (SLAM pose, camera frame) and in the sim (ground-truth pose, Z-up): +bev_axes and forward_axis name the pose's ground plane and travel axis, as for MappingWorker. +""" + +from __future__ import annotations + +import time +from typing import Any + +import numpy as np + +from .base_worker import BaseWorker + + +class SegScanWorker(BaseWorker): + """Config: + segment_buffer SegmentationBuffer (VisionWorker) + frame_buffer FrameBuffer the masks were computed from (for their depth) + output_buffer LidarBuffer: 1080 ranges, -135..+135 deg, as the LiDAR's + raw_output_buffer LidarBuffer for the same scan without remembered edges (optional) + seg_scan camera_settings + control.seg_scan.SegScanConfig fields + pose_buffer PoseBuffer (Twv), optional: with memory_s, remembered edges fill unseen beams + memory_s s of edges kept, default 0 (off) + scan_origin [forward, left] of the scan origin in the vehicle frame (the scan_offset), default [0, 0] + bev_axes pose axes spanning the ground plane: sim [0, 1], SLAM [0, 2] (default) + forward_axis body travel axis: sim 0, SLAM 2 (default) + """ + + def __init__(self, name: str = "seg_scan", **kwargs: Any) -> None: + super().__init__(name, **kwargs) + self._last_seq = 0 + self._scans = 0 + self._missed = 0 + self._pose_seq = 0 + self._poses: list = [] + self._memory: list = [] # (t, (N, 2) world-frame edge points) + + def setup(self) -> None: + from control.depth_ftg import Intrinsics + from control.seg_scan import SegScanConfig + + self._seg_buf = self.config["segment_buffer"] + self._frame_buf = self.config["frame_buffer"] + self._out = self.config["output_buffer"] + self._raw_out = self.config.get("raw_output_buffer") + self._bev_axes = tuple(self.config.get("bev_axes", [0, 2])) + self._forward_axis = int(self.config.get("forward_axis", 2)) + cfg = dict(self.config.get("seg_scan", {})) + self._K = Intrinsics.from_orbslam_settings(cfg.pop("camera_settings", "orbslam_oakd_rgbd.yaml")) + self._cfg = SegScanConfig(**cfg) + self._pose_buf = self.config.get("pose_buffer") + self._memory_s = float(self.config.get("memory_s", 0.0)) + self._origin = np.asarray(self.config.get("scan_origin", [0.0, 0.0]), dtype=np.float64)[:2] + from control.lidar_gap import ANGLE_INCREMENT, ANGLE_MIN + + self._ang = ANGLE_MIN + np.arange(1080) * ANGLE_INCREMENT + self._a0, self._da = ANGLE_MIN, ANGLE_INCREMENT + self.logger.info(f"SegScanWorker ready (segmentation edge -> scan; pitch {self._cfg.camera_pitch:.3f} rad, " + f"height {self._cfg.camera_height:.3f} m, floor fallback {'on' if self._cfg.floor_fallback else 'off'})") + + def step(self) -> None: + from control.seg_scan import seg_edge_scan + + seg = self._seg_buf.read_latest() + if seg is None or seg[0].seq_no <= self._last_seq: + time.sleep(0.005) + return + header, mask = seg + self._last_seq = header.seq_no + # VisionWorker stamps a mask with its frame's capture time: find that frame's depth + frames = [self._frame_buf.read_latest()] + if frames[0] is not None and frames[0][0].produced_ts != header.produced_ts: + frames = self._frame_buf.read_since(max(0, frames[0][0].seq_no - 4)) + depth = next((f[2] for f in frames if f is not None and f[0].produced_ts == header.produced_ts), None) + if depth is None: + self._missed += 1 # its frame has left the ring + return + ranges = seg_edge_scan(mask, depth, self._K, self._cfg) + if self._raw_out is not None: + self._raw_out.write(ranges, ts=header.produced_ts) + if self._memory_s > 0 and self._pose_buf is not None: + ranges = self._with_memory(ranges, header.produced_ts) + self._out.write(ranges, ts=header.produced_ts) + self._scans += 1 + if self._scans % 200 == 0: + self.logger.info(f"{self._scans} scans ({self._missed} masks without their frame)") + + def _pose_at(self, t: float): + for header, pose, *_ in self._pose_buf.read_since(self._pose_seq): + self._pose_seq = header.seq_no + self._poses.append((header.produced_ts, np.asarray(pose, dtype=np.float64))) + if not self._poses: + return None + while len(self._poses) > 1 and self._poses[0][0] < self._poses[-1][0] - 1.0: + self._poses.pop(0) + return min(self._poses, key=lambda p: abs(p[0] - t))[1] + + def _with_memory(self, ranges: np.ndarray, t: float) -> np.ndarray: + """Remember this scan's edges (world frame); fill its unknown (NaN) beams from the + edges remembered from the last memory_s seconds.""" + from .bev import pose_to_bev + + T = self._pose_at(t) + if T is None: + return ranges + p, heading = pose_to_bev(T, self._bev_axes, self._forward_axis) + c, s = np.cos(heading), np.sin(heading) + R = np.array([[c, -s], [s, c]]) + o = np.asarray(p, dtype=np.float64) + R @ self._origin # scan origin, world + ok = np.isfinite(ranges) & (ranges > 0) + pts = np.column_stack([ranges[ok] * np.cos(self._ang[ok]), ranges[ok] * np.sin(self._ang[ok])]) + self._memory.append((t, pts @ R.T + o)) + self._memory = [(tm, q) for tm, q in self._memory if t - tm <= self._memory_s] + unknown = np.isnan(ranges) + if not unknown.any() or len(self._memory) < 2: + return ranges + q = np.vstack([q for _, q in self._memory[:-1]]) - o + q = q @ R # world -> scan frame + r = np.hypot(q[:, 0], q[:, 1]) + b = np.round((np.arctan2(q[:, 1], q[:, 0]) - self._a0) / self._da).astype(int) + keep = (b >= 0) & (b < len(ranges)) & (r > 0.05) + best = np.full(len(ranges), np.inf) + np.minimum.at(best, b[keep], r[keep]) + fill = unknown & np.isfinite(best) + out = ranges.copy() + out[fill] = best[fill] + return out.astype(np.float32) diff --git a/workers/sim_decoder.py b/workers/sim_decoder.py index f6d7927..31338c1 100644 --- a/workers/sim_decoder.py +++ b/workers/sim_decoder.py @@ -219,7 +219,7 @@ def _process_pose_data(self, data: dict) -> None: speed = float(data.get('speed', 0.0)) now = time.monotonic() if self._pose_buf is not None: - self._pose_buf.write(pose, None, speed=speed, ts=now) + self._write_pose(pose, speed, now) if self._state_buf is not None: # sim world is Z-up: ground plane is X, Y; yaw from the body X axis yaw = float(np.arctan2(R[1, 0], R[0, 0])) @@ -229,6 +229,9 @@ def _process_pose_data(self, data: dict) -> None: except Exception as e: self.logger.warning(f"Pose processing failed: {e}") + def _write_pose(self, pose: np.ndarray, speed: float, ts: float) -> None: + self._pose_buf.write(pose, None, speed=speed, ts=ts) + def _process_lidar_data(self, data: dict) -> None: if self._lidar_buf is None: return diff --git a/workers/slam_worker.py b/workers/slam_worker.py index d37cc54..906dff3 100644 --- a/workers/slam_worker.py +++ b/workers/slam_worker.py @@ -1,9 +1,13 @@ """ -SLAMWorker: FrameBuffer -> ORB_SLAM3 RGBD -> PoseBuffer (Twc, camera-to-world), map points -and keyframe positions. Poses carry the frame's capture ts (time.monotonic()) and are only +SLAMWorker: FrameBuffer -> ORB_SLAM3 RGBD (or RGBD-inertial, with the OAK-D's IMU samples +from a RawIMUBuffer) -> PoseBuffer (Twc, camera-to-world), map points and keyframe +positions. Poses carry the frame's capture ts (time.monotonic()) and are only published while tracking is OK, in a floor-aligned "level" world frame (Y down along the floor normal, Z = forward on the floor, so BEV axes [0, 2] hold). A map switch sets -map_reset_event; in localization mode poses are withheld outside the reference map. +map_reset_event; in localization mode poses are withheld outside the reference map. In the +inertial mode ORB-SLAM3 re-rotates its map to gravity while the IMU initialises; the +poses and map points are published relative to the map's origin keyframe, which those +rotations move along with everything else, so the published frame does not move. """ from __future__ import annotations @@ -98,6 +102,10 @@ class SLAMWorker(BaseWorker): level_frames good floor fits to average, default 5 level_timeout_frames give up levelling after this many frames, default 150 floor_height_range accepted camera height above the floor, default (0.03, 1.0) m + inertial ORB-SLAM3 IMU_RGBD instead of RGBD, default False (the settings + file needs the IMU block: scripts/gen_orbslam_settings.py --imu) + raw_imu_buffer RawIMUBuffer with the camera's IMU samples (inertial only) + imu_wait_s wait this long for IMU samples to catch up with a frame, default 0.03 """ _PC_PUBLISH_INTERVAL = 30 # also publish point cloud every N frames @@ -133,6 +141,15 @@ def __init__(self, name: str = "slam", **kwargs: Any) -> None: self._level_tries = 0 self._R_level: Optional[np.ndarray] = None # 4x4, world -> level + # inertial mode + self._inertial = bool(kwargs.get("inertial", False)) + self._imu_buf: Optional[Any] = None + self._imu_wait_s = float(kwargs.get("imu_wait_s", 0.03)) + self._imu_seq = 0 + self._imu_pending: list = [] # [t, ax, ay, az, gx, gy, gz] not yet given to SLAM + self._T_origin: Optional[np.ndarray] = None # Twc of the map's origin keyframe + self._imu_initialized = False + # map identity self._map_key: Optional[tuple] = None # current (map_id, init_kf_id) self._ref_map_key: Optional[tuple] = None # map the poses are published in @@ -172,9 +189,17 @@ def setup(self) -> None: from control.types import resolve_path vocab_path, settings_path = resolve_path(vocab_path), resolve_path(settings_path) - self._slam = _slam_mod.System(vocab_path, settings_path, _slam_mod.RGBD) + if self._inertial: + self._imu_buf = self.config.get("raw_imu_buffer") + if self._imu_buf is None: + raise RuntimeError("inertial SLAM needs a raw_imu_buffer (the OAK-D's IMU)") + if not hasattr(_slam_mod, "IMU_RGBD"): + raise RuntimeError("orbslam3_python has no IMU_RGBD: rebuild orbslam3_wrapper") + sensor = _slam_mod.IMU_RGBD if self._inertial else _slam_mod.RGBD + self._slam = _slam_mod.System(vocab_path, settings_path, sensor) self.logger.info( - f"ORB_SLAM3 initialised (vocab={vocab_path}, settings={settings_path})" + f"ORB_SLAM3 initialised ({'RGBD-inertial' if self._inertial else 'RGBD'}, " + f"vocab={vocab_path}, settings={settings_path})" ) if self._level_world: self._K = read_settings_intrinsics(settings_path) @@ -229,6 +254,9 @@ def _update_level(self, depth: np.ndarray) -> None: ) def _level_points(self, pts: np.ndarray) -> np.ndarray: + if self._inertial and self._T_origin is not None: + # world -> origin keyframe frame: R_o^T (p - t_o), as row vectors + pts = (pts - self._T_origin[:3, 3]) @ self._T_origin[:3, :3] return (pts @ self._R_level[:3, :3].T).astype(np.float32) # map identity @@ -250,12 +278,53 @@ def _check_map(self) -> bool: if self._map_reset_event is not None: self._map_reset_event.set() self._map_key = key + self._T_origin = None if self._ref_map_key is None or not self._localization_activated: self._ref_map_key = key if key != self._ref_map_key: return False # localization mode in a map that isn't the mapped track return True + # inertial mode + + def _imu_until(self, ts: float) -> np.ndarray: + """IMU samples with t <= ts not yet handed out, as (N, 7) float64 [t, acc, gyro]. + Waits up to imu_wait_s for the IMU to catch up with the frame (it can lag it).""" + deadline = time.monotonic() + self._imu_wait_s + while True: + for header, sample in self._imu_buf.read_since(self._imu_seq): + if self._imu_seq and header.seq_no > self._imu_seq + 1: + self.logger.warning( + f"Lost {header.seq_no - self._imu_seq - 1} IMU samples (SLAM fell behind " + "the raw IMU buffer)") + self._imu_seq = header.seq_no + self._imu_pending.append([header.produced_ts, *sample.tolist()]) + if (self._imu_pending and self._imu_pending[-1][0] >= ts) or time.monotonic() >= deadline: + break + time.sleep(0.002) + n = sum(1 for row in self._imu_pending if row[0] <= ts) + out = np.array(self._imu_pending[:n], dtype=np.float64).reshape(-1, 7) + del self._imu_pending[:n] + return out + + def _update_origin(self) -> bool: + """Re-read the origin keyframe (inertial mode). False when it rotated since the last + frame: ORB-SLAM3 re-aligned its map to gravity around this frame, so its pose is + withheld in case the tracker's pose and the origin straddle the rotation.""" + T_o = np.asarray(self._slam.origin_pose(), dtype=np.float32) + initialized = bool(self._slam.imu_initialized()) + if initialized and not self._imu_initialized: + self.logger.info("IMU initialised: ORB-SLAM3 map aligned to gravity") + self._imu_initialized = initialized + prev, self._T_origin = self._T_origin, T_o + if prev is None: + return True + cos = (float(np.trace(prev[:3, :3].T @ T_o[:3, :3])) - 1.0) / 2.0 + if math.degrees(math.acos(max(-1.0, min(1.0, cos)))) > 0.2: + self.logger.info("ORB-SLAM3 re-rotated its map (gravity); poses stay in the origin frame") + return False + return True + def step(self) -> None: if ( not self._localization_activated @@ -288,6 +357,7 @@ def step(self) -> None: # keep resetting; they still feed the floor fit if self._R_level is None: self._update_level(depth) + imu = self._imu_until(ts) if self._inertial else None if self._frame_count <= self._warmup_frames: return @@ -302,7 +372,8 @@ def step(self) -> None: ) t0 = time.perf_counter() - Tcw = self._slam.track_rgbd(rgb, depth, ts) + Tcw = self._slam.track_rgbd(rgb, depth, ts, imu) if self._inertial else \ + self._slam.track_rgbd(rgb, depth, ts) self._track_ms.append(1e3 * (time.perf_counter() - t0)) state = self._slam.get_tracking_state() tracking_ok = state == _TRACKING_OK @@ -316,6 +387,12 @@ def step(self) -> None: map_ok = self._check_map() if tracking_ok else False level_ok = self._R_level is not None Twc = invert_se3(np.asarray(Tcw, dtype=np.float32)) + if self._inertial: + # relative to the origin keyframe: the frame the floor was levelled in, and + # unmoved by ORB-SLAM3's gravity re-rotations + if not self._update_origin(): + map_ok = False + Twc = invert_se3(self._T_origin) @ Twc if level_ok: Twc = self._R_level @ Twc if tracking_ok and map_ok and level_ok: diff --git a/workers/state_worker.py b/workers/state_worker.py index 9f45764..8ca3ef4 100644 --- a/workers/state_worker.py +++ b/workers/state_worker.py @@ -2,6 +2,13 @@ StateWorker: PoseBuffer poses -> control.PoseEKF -> StateBuffer at a fixed rate. A stale estimate (no poses for ``stale_after`` s) is not published, so the actuator watchdog takes the car to neutral. + +With a rear_imu_buffer (the Arduino's ICM-20948, IMUWorker's raw output) the estimator is +control.ImuEKF instead: driven by the IMU, corrected by the poses. The IMU's axes are +turned into the car's (x forward, y left, z up) by rear_imu.rotation, the pose's point +(the camera's, for SLAM) is moved to the IMU by rear_imu.lever_m, and the published state +is moved back: controllers see the same point as with PoseEKF, now with the gyro's yaw +rate, through SLAM gaps, and with poses applied at their capture time. """ from __future__ import annotations @@ -9,7 +16,10 @@ import time from typing import Any -from control.estimator import EstimatorConfig, PoseEKF +import numpy as np + +from control.estimator import EstimatorConfig, ImuEKF, ImuEstimatorConfig, PoseEKF +from control.types import VehicleState from .base_worker import BaseWorker from .bev import pose_to_bev @@ -25,6 +35,12 @@ class StateWorker(BaseWorker): rate_hz publish rate, default 50 use_pose_speed also fuse PoseBuffer's speed (sim only; SLAM has none), default off estimator dict of EstimatorConfig overrides + rear_imu_buffer RawIMUBuffer (IMUWorker raw output): use ImuEKF + rear_imu dict: rotation (3x3, sensor -> car axes, default identity), + lever_m ([dx, dy], the IMU's position from the pose's point in the car + frame, x forward, y left; default [0, 0]), delay_s (subtracted from the + IMU's stamps: its filter and read, default 0), estimator (dict of + ImuEstimatorConfig overrides) """ def __init__(self, name: str = "state", **kwargs: Any) -> None: @@ -40,27 +56,60 @@ def setup(self) -> None: self._forward_axis = int(self.config.get("forward_axis", 2)) self._period = 1.0 / float(self.config.get("rate_hz", 50.0)) self._use_pose_speed = bool(self.config.get("use_pose_speed", False)) - self._ekf = PoseEKF(EstimatorConfig(**self.config.get("estimator", {}))) + self._imu_buf = self.config.get("rear_imu_buffer") + self._imu_seq = 0 + if self._imu_buf is not None: + ri = self.config.get("rear_imu", {}) or {} + self._R = np.asarray(ri.get("rotation", np.eye(3)), dtype=np.float64).reshape(3, 3) + if abs(abs(np.linalg.det(self._R)) - 1.0) > 1e-3 or not np.allclose(self._R @ self._R.T, np.eye(3), atol=1e-3): + raise ValueError(f"rear_imu.rotation is not a rotation: {self._R.tolist()}") + self._lever = np.asarray(ri.get("lever_m", [0.0, 0.0]), dtype=np.float64) + self._delay = float(ri.get("delay_s", 0.0)) + self._ekf = ImuEKF(ImuEstimatorConfig(**(ri.get("estimator") or {}))) + else: + self._ekf = PoseEKF(EstimatorConfig(**self.config.get("estimator", {}))) self.logger.info( - f"StateWorker ready (bev_axes={self._bev_axes}, forward_axis={self._forward_axis}, " + f"StateWorker ready ({'ImuEKF on the rear IMU' if self._imu_buf is not None else 'PoseEKF'}, " + f"bev_axes={self._bev_axes}, forward_axis={self._forward_axis}, " f"rate={1 / self._period:.0f} Hz, pose_speed={self._use_pose_speed})" ) + # the pose's point (camera) <-> the IMU's, in the BEV plane + def _shift(self, x: float, y: float, yaw: float, sign: float) -> tuple: + c, s = np.cos(yaw), np.sin(yaw) + dx, dy = self._lever + return x + sign * (c * dx - s * dy), y + sign * (s * dx + c * dy) + + def _drain_imu(self) -> None: + for header, sample in self._imu_buf.read_since(self._imu_seq): + self._imu_seq = header.seq_no + acc = self._R @ sample[:3].astype(np.float64) + gyro = self._R @ sample[3:].astype(np.float64) + self._ekf.update_imu(header.produced_ts - self._delay, acc[0], acc[1], gyro[2]) + def step(self) -> None: + if self._imu_buf is not None: + self._drain_imu() result = self._pose_buf.read_latest() if result is not None: header, pose, _, speed = result if header.seq_no > self._last_pose_seq: self._last_pose_seq = header.seq_no (x, y), yaw = pose_to_bev(pose, self._bev_axes, self._forward_axis) + if self._imu_buf is not None: + x, y = self._shift(float(x), float(y), yaw, +1.0) self._ekf.update_pose(header.produced_ts, float(x), float(y), yaw) - if self._use_pose_speed: + if self._use_pose_speed and hasattr(self._ekf, "update_speed"): self._ekf.update_speed(header.produced_ts, float(speed)) now = time.monotonic() if now >= self._next_pub: self._next_pub = now + self._period state = self._ekf.predict_to(now) + if state is not None and self._imu_buf is not None: + x, y = self._shift(state.x, state.y, state.yaw, -1.0) + state = VehicleState(t=state.t, x=float(x), y=float(y), yaw=state.yaw, v=state.v, + yaw_rate=state.yaw_rate) valid = state is not None if valid: self._state_buf.write(state)