diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 305c020..e83fa0a 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -76,7 +76,7 @@ body: id: platform attributes: label: Platform - description: OS, architecture, and hardware (x86-64 dev host, Jetson Orin, ...). + description: OS, architecture, and hardware. placeholder: Ubuntu 24.04, x86-64 validations: required: true diff --git a/.github/asan.supp b/.github/asan.supp new file mode 100644 index 0000000..2ac9441 --- /dev/null +++ b/.github/asan.supp @@ -0,0 +1,20 @@ +# LeakSanitizer suppressions for the sanitizer CI job. Read through +# LSAN_OPTIONS, not ASAN_OPTIONS: ASan's own suppression parser rejects the +# leak: type and aborts the process. +# +# rosidl's C++ type support registers its message descriptors in static storage +# that is never torn down, and bringing up any rclcpp node reaches it through +# rcl_node_init. The allocations are one-time and process-lifetime rather than +# per-node: the reported total is byte-identical in a 24-test binary and an +# 87-test one, and no prox_mpc frame appears in any of the leak stacks. The +# controller fixtures already call on_cleanup() and then reset(), so there is no +# teardown to add. +# +# Scoped deliberately to those two frames: detect_leaks stays on (see +# ASAN_OPTIONS in .github/workflows/ci.yaml), so a leak in this repository's own +# allocations still fails the job. +# +# print_suppressions=1 reports the hit count per entry, which is how a stale +# entry here is told apart from one that is still doing work. +leak:librosidl_typesupport_cpp +leak:rcl_node_init diff --git a/.github/scripts/check_no_eigen_debug.py b/.github/scripts/check_no_eigen_debug.py new file mode 100644 index 0000000..66d7159 --- /dev/null +++ b/.github/scripts/check_no_eigen_debug.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +# Copyright 2026 Simone Contorno +# SPDX-License-Identifier: Apache-2.0 + +"""Fail if a translation unit was compiled with NDEBUG or EIGEN_NO_DEBUG in effect. + +"In effect" means EIGEN_NO_DEBUG is defined and not cancelled by a later -U. The +sanitizer job exists to run with Eigen's own bounds assertions live, which only +holds if the Debug build type keeps NDEBUG unset and the -UEIGEN_NO_DEBUG +carried in CMAKE_CXX_FLAGS actually cancels the -DEIGEN_NO_DEBUG every package +adds at directory scope. This reads the outcome back from compile_commands.json +instead of trusting the cmake-args alone, so the job cannot silently degrade +into a decoration if a future change reorders or drops one of the flags. + +Usage: check_no_eigen_debug.py [ ...] +""" + +import json +import pathlib +import shlex +import sys + + +def command_args(entry): + """The argument list of one compile_commands.json entry.""" + if 'arguments' in entry: + return entry['arguments'] + return shlex.split(entry.get('command', '')) + + +def problems_for(args): + """Names for one translation unit's compile flags that violate the contract.""" + found = [] + if '-DNDEBUG' in args: + found.append('NDEBUG is defined') + eigen_flags = [a for a in args if a in ('-DEIGEN_NO_DEBUG', '-UEIGEN_NO_DEBUG')] + if eigen_flags and eigen_flags[-1] != '-UEIGEN_NO_DEBUG': + found.append('EIGEN_NO_DEBUG is defined and not cancelled by a later -U') + return found + + +def main(argv): + """Check every compile_commands.json entry matched by the given globs.""" + if not argv: + print('usage: check_no_eigen_debug.py [...]', file=sys.stderr) + return 2 + + failures = [] + checked = 0 + for pattern in argv: + for path in sorted(pathlib.Path().glob(pattern)): + entries = json.loads(path.read_text()) + for entry in entries: + problems = problems_for(command_args(entry)) + checked += 1 + if problems: + failures.append((entry.get('file', str(path)), problems)) + + if checked == 0: + print('No compile_commands.json entries found; nothing was checked.', file=sys.stderr) + return 2 + + if failures: + for file_path, problems in failures: + for problem in problems: + print(f'FAIL: {file_path}: {problem}', file=sys.stderr) + return 1 + + print( + f'OK: {checked} translation units compiled with NDEBUG unset and ' + 'EIGEN_NO_DEBUG cancelled by -U.') + return 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 155483e..e3f3384 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -93,6 +93,91 @@ jobs: name: lcov-report path: /ros_ws/coverage_filtered.info + # AddressSanitizer + UndefinedBehaviorSanitizer. EIGEN_NO_DEBUG is defined at + # directory scope in every package (kept there for every ordinary build, to + # keep the solver hot path fast), which silently disables Eigen's own bounds + # assertions. This job rebuilds Debug (Release and RelWithDebInfo both define + # NDEBUG, which Eigen treats as EIGEN_NO_DEBUG on its own) and cancels the + # directory-scope define with a later -U in CMAKE_CXX_FLAGS, so both Eigen's + # assertions and the sanitizers are live at once. + sanitizers: + runs-on: ubuntu-24.04 + container: + image: ros:jazzy-ros-base-noble + + # Leak detection stays on. The only leaks the suite reports come from + # rosidl's one-time static type-support registration, reached through + # rcl_node_init when a test brings up a node, so those two frames are + # suppressed by name rather than the detector being switched off - a leak in + # this repository's own allocations still fails the job. + # + # The suppressions path goes in LSAN_OPTIONS, not ASAN_OPTIONS: ASan parses + # its own suppressions file against interceptor_name, interceptor_via_fun, + # interceptor_via_lib and odr_violation only, so a leak: entry there makes + # every sanitized process die with "failed to parse suppressions". + # + # The path is the symlink the "Create colcon workspace" step below plants, + # because neither shorthand for the checkout directory survives here: an env + # value is not shell-expanded, so $GITHUB_WORKSPACE would stay literal, and + # ${{ github.workspace }} expands to the runner host's path rather than the + # container's /__w mount (actions/runner#2058). An unreadable suppressions + # file is fatal, so a wrong path fails every sanitized process rather than + # degrading quietly. + env: + ASAN_OPTIONS: detect_leaks=1 + LSAN_OPTIONS: suppressions=/ros_ws/src/prox_mpc/.github/asan.supp + UBSAN_OPTIONS: print_stacktrace=1 + + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Install dependencies + run: | + apt-get update + apt-get install -y --no-install-recommends \ + python3-colcon-common-extensions + rosdep update + rosdep install --from-paths . --ignore-src -y + + - name: Create colcon workspace + run: | + mkdir -p /ros_ws/src + ln -s "$GITHUB_WORKSPACE" /ros_ws/src/prox_mpc + + - name: Build with AddressSanitizer and UndefinedBehaviorSanitizer + working-directory: /ros_ws + run: | + . /opt/ros/jazzy/setup.sh + colcon build \ + --symlink-install \ + --cmake-args \ + -DCMAKE_BUILD_TYPE=Debug \ + -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \ + -DCMAKE_CXX_FLAGS="-UEIGEN_NO_DEBUG -fsanitize=address,undefined -fno-omit-frame-pointer -fno-sanitize-recover=all -O1 -g" \ + -DCMAKE_EXE_LINKER_FLAGS="-fsanitize=address,undefined" \ + -DCMAKE_SHARED_LINKER_FLAGS="-fsanitize=address,undefined" \ + --no-warn-unused-cli + + # Reads the flags actually reaching the compiler back out of + # compile_commands.json, so a future reordering of the flags above + # cannot silently turn this job back into a decoration. + - name: Verify Eigen assertions are live and NDEBUG is unset + working-directory: /ros_ws + run: python3 src/prox_mpc/.github/scripts/check_no_eigen_debug.py "build/*/compile_commands.json" + + - name: Test under AddressSanitizer and UndefinedBehaviorSanitizer + working-directory: /ros_ws + run: | + . /opt/ros/jazzy/setup.sh + . install/setup.sh + colcon test --return-code-on-test-failure + + - name: Display test results + if: always() + working-directory: /ros_ws + run: colcon test-result --verbose + # Static analysis with Clang Thread Safety Analysis (the controller and tracker # share state across the executor; TSA catches unguarded access). clang-tsa: @@ -125,5 +210,5 @@ jobs: CC=clang CXX=clang++ colcon build \ --symlink-install \ --cmake-args \ - -DCMAKE_CXX_FLAGS="-Wthread-safety" \ + -DCMAKE_CXX_FLAGS="-Wthread-safety -Werror=thread-safety" \ --no-warn-unused-cli diff --git a/CITATION.cff b/CITATION.cff index 11e759d..5ac18be 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -31,8 +31,8 @@ keywords: - obstacle avoidance - mobile robots license: Apache-2.0 -version: 1.0.0 -date-released: '2026-07-19' +version: 2.0.0 +date-released: '2026-09-13' references: - type: software title: 'ProxSuite: a scalable and efficient QP solver' diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8c1df8a..fa43c60 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -62,9 +62,12 @@ that pattern. ## Commit conventions -- **Branching follows GitHub Flow**: `main` is the stable branch, `dev` is the - integration branch, and topic work happens on `feat/*`, `fix/*`, `chore/*`, - or `test/*` branches merged in via pull request. +- **Branching follows GitHub Flow**: `main` is the stable branch, and topic work + happens on `feat/*`, `fix/*`, `chore/*`, or `test/*` branches merged in via + pull request. A release is prepared on a `release/` branch, which is + squash-merged into `main` so that `main` carries one commit per release; the + release branch is kept, not deleted, because it is where that release's + reviewable and bisectable history lives. - **Commit messages follow Conventional Commits**, scoped to the package or area they touch, matching real history in this repo, for example: - `feat(controller): predictive dynamic-obstacle avoidance and model speed-cap forwarding` @@ -142,7 +145,24 @@ that pattern. Clang and `-Wthread-safety` - it does not run tests, only the thread-safety-annotated build, so a change to mutex-guarded state in `prox_mpc_controller` or `prox_mpc_obstacle_tracker` should also be checked - against that build if you touch shared/guarded state. + against that build if you touch shared/guarded state. A third CI job, + `sanitizers`, rebuilds Debug with AddressSanitizer and + UndefinedBehaviorSanitizer and cancels every package's directory-scope + `EIGEN_NO_DEBUG` define, so Eigen's own bounds assertions run alongside the + sanitizers - the ordinary `build-and-test` job cannot see an out-of-range + Eigen access, because `EIGEN_NO_DEBUG` stays defined there for solver-hot-path + performance. Reproduce it locally with: + + ```bash + colcon build --symlink-install --build-base build_asan --install-base install_asan \ + --cmake-args -DCMAKE_BUILD_TYPE=Debug \ + -DCMAKE_CXX_FLAGS="-UEIGEN_NO_DEBUG -fsanitize=address,undefined -fno-omit-frame-pointer -fno-sanitize-recover=all -O1 -g" \ + -DCMAKE_EXE_LINKER_FLAGS="-fsanitize=address,undefined" \ + -DCMAKE_SHARED_LINKER_FLAGS="-fsanitize=address,undefined" \ + --no-warn-unused-cli + UBSAN_OPTIONS=print_stacktrace=1 colcon test --build-base build_asan --install-base install_asan \ + --return-code-on-test-failure + ``` - **Coverage: aspirational target, not an enforced CI gate.** The house convention (see the `ros2-testing-ci` skill) targets >= 95% line coverage. In this repo today, CI generates a filtered `lcov` report diff --git a/README.md b/README.md index e295077..225efd1 100644 --- a/README.md +++ b/README.md @@ -67,54 +67,67 @@ the summary is below. > dev host (Intel Core i7-10750H, 6 cores / 12 threads, 31 GiB RAM, > Ubuntu 24.04.4) - not on physical robot hardware and not contact-dynamics. > A collision is a *would-be* overlap of the robot and obstacle discs, scored -> identically for every controller. Gazebo validation is a single open-cell run; -> full Gazebo and hardware validation remain open. - -| Controller | Tracking RMS (open) | Compute p50 / p95 (open) | Static clearance | Multi-obstacle margin | -| --- | --- | --- | --- | --- | -| **ProxMPC** | 0.0004 m | **0.75 / 1.15 ms** | **+0.352 m** | -0.118 m, **+0.190 m predictive** | -| DWB | 0.0001 m | 2.46 / 2.70 ms | +0.093 m | +0.080 m | -| MPPI | 0.0029 m | 2.61 / 2.91 ms | +0.207 m | +0.048 m | -| Regulated Pure Pursuit | 0.0000 m | 0.21 / 0.25 ms | +0.213 m | +0.125 m | -| Vector Pursuit | 0.0000 m | 0.21 / 0.25 ms | +0.175 m (stops short) | +0.024 m | -| Graceful | 0.0000 m | 0.15 / 0.20 ms | +0.207 m | -0.013 m | +> identically for every controller. **Every figure here was measured on that host +> and on no other.** Gazebo validation is a single open-cell gate (5 runs, all +> reaching the goal), not a cross-controller comparison; hardware validation +> remains open. + +| Controller | Tracking RMS (open) | Compute p50 / p95 (open) | Static clearance | Multi-obstacle margin | Collisions (10 cells) | +| --- | --- | --- | --- | --- | --- | +| **ProxMPC** | 0.0001 m | **0.30 / 1.02 ms** | **+0.382 m** | -0.023 m, **+0.151 m predictive** | 32 %, **6 % predictive** | +| DWB | 0.0001 m | 2.96 / 4.41 ms | +0.090 m | +0.057 m | 30 % | +| MPPI | 0.0029 m | 3.11 / 4.05 ms | +0.208 m | +0.063 m | 18 % | +| Regulated Pure Pursuit | 0.0000 m | 0.23 / 0.36 ms | +0.213 m | +0.113 m | 16 % | +| Vector Pursuit | 0.0000 m | 0.23 / 0.38 ms | +0.247 m (stops short) | +0.020 m | 26 % | +| Graceful | 0.0000 m | 0.18 / 0.32 ms | +0.211 m | +0.000 m | 36 % | Multi-obstacle margin is the median closest approach over six two-mover cells (30 runs per controller, 60 for MPPI's 10 repeats); positive clears the obstacle. -The margin is reported instead of a collision count on purpose. Those cells -are deliberately marginal, so 40-80 % of runs finish within 0.15 m of the -threshold and the collision *count* is dominated by scheduling jitter: the same -cell, with the same binary, returned 1/5, 5/5, and 2/5 collisions on three -separate runs. The median margin is stable across the same runs and is the -honest discriminator. Counts are still reported per cell in +Collisions are over all ten obstacle cells (50 runs per controller, 100 for MPPI). +Both are reported because neither alone is honest: those cells are deliberately +marginal, so 50-93 % of runs finish within 0.15 m of the threshold and per-cell +counts swing widely, while the median margin is stable across the same runs. +Every row comes from one 435-run campaign recorded back-to-back on one host, so +no comparison here spans measurement sessions; re-running the unchanged stock +peer binaries still moved them by up to 8 points, which is the noise floor to +read these counts against. Read the aggregate over 30-50 runs, not any single +cell. Per-cell counts are in [doc/controller-comparison-results.md](doc/controller-comparison-results.md), which is the source of truth. ### Strengths - **Tracking on par with the best.** Sub-millimetre cross-track on an empty - straight traverse (0.0004 m RMS, 5/5 success). -- **Lightest of the optimising controllers.** ~0.75 ms median per cycle on the - open cell, ~3.3x lighter than DWB and ~3.5x than MPPI at equal tracking - accuracy, and 1.1-2.7x lighter across the obstacle cells (the margin - narrows as the obstacle field tightens and the QP gets harder), at 5.0-9.1 % - CPU against their 8.4-9.3 %. Deadline misses and infeasible cycles are zero on - 431 of 435 runs and peak at 0.6 % on the hardest two-mover cells. The - geometric pursuit controllers are lighter still; ProxMPC's premium over them is - ~1-5 % of one core for a full constrained optimisation each cycle. + straight traverse (0.0001 m RMS, 5/5 success). +- **Lighter than the other optimising controllers.** 0.30 ms median per cycle + on the open cell - **9.9x lighter than DWB and 10.4x than MPPI** at equal + tracking accuracy - at 8.5 % CPU across all obstacle cells against their 9.4 % + and 9.3 %. ProxMPC's cost scales with obstacle load while theirs does not, so + the advantage narrows to ~2.5-3x on single-obstacle cells and ~1.3x on the + hardest two-mover cells, but it never inverts. The geometric pursuit + controllers are an order of magnitude lighter still, and collide 16-36 % of the + time. +- **Bounded per-cycle latency.** Zero cycles above the 50 ms budget across 100 + runs, worst observed 33.5 ms. The previous release measured 300 ms worst cases + on three separate cells, from an SQP loop that re-linearised up to 99 times + after a failed solve and a QP workspace rebuilt from scratch every cycle. + Both are fixed. - **The largest static-obstacle margin.** It reaches the goal *and* holds - +0.35 m clearance around a static box, the widest of the field - ahead of - MPPI (+0.21 m) and DWB (+0.09 m) among the optimising controllers, and of RPP - and Graceful (~+0.21 m) among the geometric ones. + +0.382 m clearance around a static box at its closest, the widest of the field + - ahead of MPPI (+0.20 m) and DWB (+0.07 m) among the optimising controllers, + and of RPP and Graceful (~+0.21 m) among the geometric ones. +- **Prediction yields by slowing, not swerving.** With its own obstacle tracker + enabled (an IMM filter combining constant-velocity and constant-turn-rate + models) and the obstacle-aware speed cap that ships with it, ProxMPC holds the + field's largest worst-case margin on the single-mover cells (+0.212 m over 15 + runs) while cutting its detour to 0.376 m of cross-track - it slows for a + closing mover instead of racing past it. DWB and Graceful collide on 5 runs of + 15 on those same cells. - **Prediction gives the field's widest margin among two simultaneous movers.** - With its own obstacle tracker enabled (an IMM filter combining constant-velocity - and constant-turn-rate models) ProxMPC holds a +0.190 m median closest - approach across the six two-mover cells, ahead of every peer - RPP +0.125 m, - DWB +0.080 m, MPPI +0.048 m, Vector Pursuit +0.024 m, Graceful -0.013 m - and - only 5 of its 30 runs finish inside the 0.15 m marginal band, against 14-24 for - the others. It also clears the single crossing and orbiting obstacles - reactively (0/5 collisions on the orbit that DWB and Graceful both collide on - in 5 runs of 5). + ProxMPC holds a +0.151 m median closest approach across the six two-mover + cells, ahead of every peer - RPP +0.113 m, MPPI +0.063 m, DWB +0.057 m, + Vector Pursuit +0.020 m, Graceful +0.000 m - and collides on only 3 of 30 runs + there against 6 for the next best, clearing five of the six cells outright. - **Deterministic and model-agnostic.** The control law is a deterministic function of its inputs, unlike MPPI, which samples and exposes no seed in Nav2 Jazzy. Note that this does not make a *closed-loop run* reproducible: control, @@ -124,26 +137,40 @@ which is the source of truth. ### Where it is weaker -- On the tightest simultaneous two-mover cell (`blind_multi_0`) reactive ProxMPC - is the field's weakest, colliding on all five runs: two close movers force a - non-convex "which side of each obstacle" choice that the linearised keep-out - constraint cannot represent. Prediction more than halves it (2/5) but does not - remove it. Where it fails, it stalls rather than driving through. +- **The two-mover cells remain the real limit.** Reactive ProxMPC collides on + 16 of 30 runs across the six of them, predictive on 3 of 30 - two close movers + force a non-convex "which side of each obstacle" choice that the linearised + keep-out constraint cannot represent. Widening the keep-out was measured and + makes both *worse*, so the limitation is the constraint's form rather than its + size. The reactive path is additionally limited by its perception: the + costmap-only fill constrains each obstacle where it *was*, an error of up to a + metre at the far end of a 2 s horizon, which is why it should be treated as a + single-obstacle configuration and why `predict_obstacles` now defaults to + true. - **Reactive ProxMPC runs closer to the obstacles than its peers** on the - two-mover cells (median margin -0.118 m, the field's narrowest). Prediction + two-mover cells (median margin -0.023 m, the field's narrowest). Prediction reverses this completely, so the tracker is not optional if the environment has two or more simultaneous movers. - The compute advantage is smallest exactly where compute matters most. On the - dense two-mover cells the per-cycle median rises to ~2.3 ms, only ~1.2x lighter - than DWB and MPPI, against ~3.5x on the open cell. + dense two-mover cells the per-cycle median rises to ~2.2-2.7 ms against the + samplers' flat ~3.0-3.2 ms, so ~1.3x rather than the ~10x of the open cell. + **Every figure here was measured on the x86-64 host named above**, and Gazebo + validation is a single open-cell gate rather than a comparison. **In short:** ProxMPC delivers constrained, model-agnostic optimal control that -tracks as well as the best of the field, runs at roughly a third of the sampling -controllers' per-cycle cost, and holds the largest margin in the field around -both a static obstacle and - with its own dynamic-obstacle tracker enabled - two -simultaneous movers. That predictive path is the configuration to deploy: the -geometric and sampling controllers have no mechanism to match it, and reactive -ProxMPC alone runs closer to moving obstacles than its peers do. +tracks as well as the best of the field, computes a command 10x faster than the +sampling controllers on an open cell, and - with its own dynamic-obstacle tracker +enabled - is **the most reliable avoider measured here: 6 % collisions across 50 +obstacle runs against 16 % for the next best**. Every cycle in 100 runs stayed +inside the 50 ms budget, which was not true of the previous release. + +That predictive path is the configuration to deploy, and is now the default. The +costmap-only path should be treated as a single-obstacle configuration: it +constrains obstacles where they were rather than where they will be, which one +free corridor absorbs and two closing movers do not. Neither variant is +collision-free among two simultaneous movers, so an environment with several +independent movers still needs a safety layer this controller does not +provide. ## Known limits and future work @@ -152,9 +179,9 @@ welcome on any of it. ### Validation beyond the kinematic plant -The reported comparison runs on a kinematic plant. Gazebo Harmonic coverage is a -single open-world run rather than the full scenario matrix, and there is no -physical-hardware validation yet. Extending both is planned; hardware results in +The reported comparison runs on a kinematic plant. Gazebo Harmonic coverage is +five runs of one open-world cell rather than the full scenario matrix, and there +is no physical-hardware validation yet. Extending both is planned; hardware results in particular would firm up the compute and clearance numbers, which are currently x86-64 dev-host measurements. diff --git a/SECURITY.md b/SECURITY.md index bfad27e..56c9456 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -4,8 +4,8 @@ | Version | Supported | | --- | --- | -| 1.0.0 | Yes | -| < 1.0.0 | No | +| 2.0.0 | Yes | +| < 2.0.0 | No | This repository ships seven ROS 2 Jazzy packages from a single source tree and releases them together, so a fix lands for all of them at once. Only the latest @@ -84,8 +84,12 @@ Stated plainly so nobody assumes a scan is catching things it is not. **Runs today** (`.github/workflows/ci.yaml`): least-privilege `permissions: contents: read`; every third-party action pinned by full commit SHA; `ament_cppcheck` under `colcon test` with -`AMENT_CPPCHECK_ALLOW_SLOW_VERSIONS` set so it does not silently no-op; and a -separate `clang-tsa` job that rebuilds the workspace under `-Wthread-safety`. +`AMENT_CPPCHECK_ALLOW_SLOW_VERSIONS` set so it does not silently no-op; a +`sanitizers` job that rebuilds the workspace `Debug` under AddressSanitizer and +UndefinedBehaviorSanitizer with `-fno-sanitize-recover=all`, leak detection on, +and Eigen's own bounds assertions live, then runs the full test suite; and a +separate `clang-tsa` job that rebuilds the workspace under +`-Werror=thread-safety`, so an unguarded access to shared state fails the build. **Does not run:** no secret scanner, no CodeQL or other deep SAST, and no dependency-CVE audit (`pip-audit` / `trivy` / `grype` / OSV). diff --git a/THIRD_PARTY_LICENSES.md b/THIRD_PARTY_LICENSES.md index c4afbd0..1a5fc47 100644 --- a/THIRD_PARTY_LICENSES.md +++ b/THIRD_PARTY_LICENSES.md @@ -78,6 +78,7 @@ decision. ```text ament_cmake ament_cmake_gtest +ament_cmake_pytest ament_cmake_python ament_index_python ament_lint_auto @@ -105,6 +106,8 @@ python3-numpy python3-yaml rcl_interfaces rclpy +rcpputils +rcutils robot_state_publisher ros2bag ros2launch @@ -113,6 +116,7 @@ ros_gz_sim rosbag2_py rosidl_default_generators rosidl_default_runtime +rosidl_typesupport_introspection_cpp rviz2 std_msgs xacro diff --git a/doc/architecture.md b/doc/architecture.md index 35f26b7..b94fabe 100644 --- a/doc/architecture.md +++ b/doc/architecture.md @@ -19,6 +19,7 @@ together. - [Runtime: standalone simulation](#runtime-standalone-simulation) - [Runtime: Nav2 + Gazebo](#runtime-nav2--gazebo) - [Runtime: predictive (dynamic) obstacle avoidance](#runtime-predictive-dynamic-obstacle-avoidance) +- [Operating envelope](#operating-envelope) - [Cross-cutting conventions](#cross-cutting-conventions) - [License](#license) @@ -64,9 +65,11 @@ flowchart TD trk -- tracked_obstacles --> ctrl ``` -The `Model` interface is the extension seam: `prox_mpc_core` registers `Bicycle` -and `Unicycle`, and `prox_mpc_test_models` registers a fault-injection model, all -against the same `prox_mpc::Model` base. +The `Model` interface is the extension seam: `prox_mpc_core` registers +`BicycleFrontAxle`, `BicycleRearAxle` and `Unicycle` (plus `Bicycle` as a +deprecated alias for the front-axle model), and `prox_mpc_test_models` +registers its fault-injection models, all against the same `prox_mpc::Model` +base. The controller and the demo load a model by name, so adding a vehicle model needs no change to the consumers. @@ -108,7 +111,7 @@ flowchart TD subgraph cs[controller_server] ctrl[ProxMpcController] ctrl --> mpc[prox_mpc::MPC] - mpc --> model[Model Unicycle / Bicycle] + mpc --> model[Model Unicycle / BicycleFrontAxle / BicycleRearAxle] end nav2sense -- local costmap + footprint --> ctrl @@ -155,14 +158,100 @@ costmap global frame). With predictions off, stale, or missing, the controller falls back to the costmap-only fill, so the feature is a clean enable/disable switch. +## Operating envelope + +What the stack supports today, stated plainly rather than left implicit. + +- **Direction of travel.** The reference is forward-only by default: multi-pose + plan orientations collapse into a reconstructed path tangent, and the + reference speed is non-negative. + `allow_reversing` (controller parameter, default `false`) is what opens the + reverse half of the control box, and `reverse_from_plan_orientation` (default + `false`) is what lets the plan's own pose orientations sign the reference into + reverse, truncating it at the first direction change rather than following + every cusp - the same bounded strategy `regulated_pure_pursuit_controller` + uses. The second is separate because only a planner that sets pose + orientations means anything by them: NavFn and Smac 2D leave every pose at the + identity quaternion, which is indistinguishable from a genuine straight + reverse plan, so trusting them would read any path running against that fixed + heading as a reverse traverse. + Past the plan end the reference pose is the goal pose, orientation included, + when the goal checker publishes a yaw tolerance it enforces; without one it + holds the final segment's tangent. Direction is a latched mode: a change is + accepted only from rest and only once a dwell has elapsed, so a cusp is driven + the way a vehicle drives one - arrive, stop, shift, pull away - rather than + being re-decided from the plan geometry every control cycle. +- **The goal region.** Inside the goal-checker xy tolerance the reference is + pinned to the goal pose rather than tracking the robot's own projection onto + the plan, which the cruise taper would otherwise reduce to a stub a few + millimetres ahead of the projection that moves along with it. Once the + checker's xy condition is met and only the heading is outstanding, a platform + with no steering channel holds station and turns on the spot; a steering model + cannot, and manoeuvres out of the heading error instead. +- **Model state layout.** Any `prox_mpc::Model` may order its state as it + likes, with or without obstacle avoidance: every consumer of a state index, + the obstacle-constraint assembly in `prox_mpc_core` included, reads it from + the model's declared `getPlanarMapping()` (see + [prox_mpc_core/doc/architecture.md](../prox_mpc_core/doc/architecture.md)). + A model that declares a position index outside its own state vector, or the + same index twice, is rejected when the solver is initialised. +- **Weight matrices.** `MPC::init()` requires `Q`, `S`, `R` and `W` to be + finite, symmetric, and positive semidefinite, and throws otherwise; a direct + `prox_mpc_core` consumer does not have to enforce this itself. +- **Steering state.** The bicycle plugins' steering angle is a virtual state, + advanced internally from the previous solve and never measured from the + plant. + The controller's sole output is a `geometry_msgs/msg/Twist`, as + `nav2_core::Controller` requires; a physically steered platform needs a + Twist-to-steering (Ackermann) converter supplied downstream by the + integrator - ProxMPC ships none. +- **`cbf_gamma` range.** The parameter stays public over `(0, 1]`. Below `1.0` + the coupled obstacle constraint is guarded against a sentinel-value blow-up + in the core and against cross-node obstacle-slot churn in the controller's + costmap fill, both within one control cycle; nothing yet holds a slot stable + across cycles (see + [prox_mpc_core/doc/obstacle-avoidance.md](../prox_mpc_core/doc/obstacle-avoidance.md)). +- **Obstacle-slot capacity.** `max_obstacles` (`K`) defaults to `1` and is the + tuning knob for a cluttered field. At the shipped horizon (`Np = Nc = 20`), + raising it to 2 costs +16% decision variables and +33% inequality rows in the + QP; raising it to 4 costs +49% and +100%. +- **Control-horizon bound.** `Nc` must not exceed `Np`; `MPC::setNc` rejects a + larger value. +- **Footprint-veto backstop.** The endpoint footprint veto (see + [Cross-cutting conventions](#cross-cutting-conventions) below and + [prox-mpc.md](prox-mpc.md#4-prox_mpc_controller---the-nav2-plugin)) checks + the rasterised footprint perimeter at one predicted pose, and applies + upstream Nav2's own collision policy: unknown space is not a collision when + the costmap tracks it, and everything else is judged at `LETHAL_OBSTACLE`. + Nav2's doc comment describes `footprintCostAtPose` as returning the maximum + cost under the footprint, which would let an adjoining unknown cell (255) + mask a lethal one (254). Measured against the installed `nav2_costmap_2d` + (1.3.12+) it does not: a footprint spanning both reports the lethal cost and + the veto still fires, which the regression test + `FootprintVetoStillFiresWhenLethalAdjoinsUnknown` pins so a future Nav2 + release that reintroduces the masking shows up as a failure rather than a + silent divergence. It is still only a backstop - it checks one predicted + pose, so it is useful only when costmap inflation is sized to the robot's + real footprint and the local costmap's unknown-space tracking matches the + deployment, and the in-loop keep-out half-planes are what constrain every + node of the horizon. +- **`prox_mpc_core/Bicycle`.** A deprecated alias for `BicycleFrontAxle` that + warns once per process, naming the replacement plugins and the two behaviours + that changed with the rename; removed in a future major release, whose exact + number is fixed against the landed diff rather than pre-announced (see + [prox_mpc_core/doc/migration.md](../prox_mpc_core/doc/migration.md)). + ## Cross-cutting conventions - **Frames.** REP-103 conventions; the tracker estimates velocity in a fixed, non-rotating frame (for example `odom`), and the controller transforms plans and obstacles into the costmap global frame via `tf2`. - **Safety split.** The engine keeps a fast convex disc constraint inside the - optimization; the controller adds an exact polygon-footprint veto as the - conservative backstop, and decelerates within the model's limits on any fault. + optimization; the controller adds an outline-only, single-endpoint footprint + veto as a backstop - not a guarantee - and decelerates within the model's + limits on any fault. The veto is effective only when costmap inflation is + sized to the robot's real footprint and the local costmap's unknown-space + tracking matches the deployment. - **Types.** All MPC quantities are `double`; ROS parameters are `double` / `int` / `bool` / `string` only. - **License.** Apache-2.0 across the workspace, with a short SPDX header per file. diff --git a/doc/controller-comparison-results.md b/doc/controller-comparison-results.md index 68c8cf4..8853e05 100644 --- a/doc/controller-comparison-results.md +++ b/doc/controller-comparison-results.md @@ -3,6 +3,19 @@ This document reports how the ProxMPC controller compares against the stock Nav2 controllers under identical, reproducible, and *fairly-tuned* conditions - on **path tracking**, **per-cycle compute and process resources**, and **obstacle avoidance**. It is the narrative companion to the auto-generated tables in [`prox_mpc_benchmark/README.md`](../prox_mpc_benchmark/README.md); the harness that produced every number is described in [the package guide](prox-mpc.md#8-prox_mpc_benchmark---the-measurement-harness). +**Provenance: one campaign, one machine state.** +Every mode-(b2) number below comes from a **single 435-run matrix recorded on 2026-09-12** - all seven controllers, 11 scenarios, 5 repeats each (10 for MPPI on the obstacle cells) - run back-to-back on one quiet host with nothing else executing, and aggregated from `results/runs/`. +The mode-(b1) rows in Section 6.3 come from the 40-run core-sim matrix recorded immediately afterwards in the same session. + +This replaces the merged two-session set published previously, and it removes the cross-session caveat entirely: there is no longer any row whose comparability depends on two campaigns being close enough. + +- **Tree:** the `2.0.0` release of the `test/audit-benchmark-revalidation` branch. The measured binary is the one described in Sections 5, 6.2 and 6.4, built from the sources that release carries. +- **Mode (a)**, the Gazebo results in Section 7, was re-run on 2026-09-13 on the same host: 5 runs of the demo's open-room traverse on the shipped demo parameters. + +**How sensitive these numbers are.** Over this work the predictive all-cells collision rate moved 6% -> 10% -> 6% on 15 mm of keep-out, with no change to the algorithm. Re-running the identical stock binaries in this campaign moved peer controllers by up to 8 points against the previous matrix (MPPI's all-cells rate 26% -> 18%, Graceful 40% -> 36%, RPP 20% -> 16%, DWB 26% -> 30%, Vector Pursuit 22% -> 26%), on code that did not change. Read any single cell's collision count as noise; the aggregate over 30 or 50 runs is the number that carries meaning, and a gap smaller than about 8 points is not resolved by this campaign. + +**Failed runs and how they were handled.** Every cell was checked against its own stack log for the controller actually receiving a path, and a cell whose Nav2 bring-up never got that far was discarded and re-run rather than recorded - a stack-bringup transient is a measurement that did not happen, while a behavioural stall reproduces and is kept. Four cells needed one such re-run; none needed more than one. All 435 records in the final set show a real path delivered to the controller. Five runs then failed *behaviourally* and are reported as failures: four Vector Pursuit runs stalling behind the static box, and one Graceful run on `dynamic_multi`. + All numbers below are measured, reproducible, and reported as `mean ± std` (population) over fixed-seed repeats - the precision signal. Nothing is hand-tuned to favour one controller: every controller drives the *same* plant from the *same* start to the *same* goal, at a *matched operating point* (Section 2.1), perceives obstacles through the *same* costmaps, and is measured by the *same* instrumentation - including a timing decorator that wall-clock times every controller's per-cycle compute identically. @@ -40,7 +53,8 @@ The open cell deliberately understates a constrained optimal-control method - an | --- | --- | | ROS 2 / Nav2 | Jazzy / Nav2 1.3.12 | | Host | x86-64 workstation - Intel Core i7-10750H (6 cores / 12 threads), 31 GiB RAM, Ubuntu 24.04.4 LTS (kernel 6.8), CPU-only | -| Run mode | **(b2)** Nav2 stack on a kinematic plant, no Gazebo (see [run modes](prox-mpc.md#9-running-the-stack-the-three-modes)); mode (b1) for the ground-truth predictive results in Section 6.3 | +| Tree | one tree for every row: the `2.0.0` release of `test/audit-benchmark-revalidation`, all seven controllers recorded back-to-back on 2026-09-12 | +| Run mode | **(b2)** Nav2 stack on a kinematic plant, no Gazebo (see [run modes](prox-mpc.md#9-running-the-stack-the-three-modes)); mode (b1) for the ground-truth predictive results in Section 6.3, recorded in the same session on the same binaries | | Plant | Unicycle body-twist integrator at 50 Hz, identical for every controller | | Localization | Exact (static `map -> odom` identity; the plant pose is ground truth) | | Map | `prox_mpc_open` - 7 x 7 m room, free interior `[-2.95, 2.95] m` | @@ -49,10 +63,12 @@ The open cell deliberately understates a constrained optimal-control method - an | Control rate | 20 Hz (`controller_frequency`); real-time budget 50 ms/cycle | | Local costmap | `static_layer` + `obstacle_layer` + `inflation_layer` (**0.4 m** radius), 5 Hz update | | Global costmap | `static_layer` + `obstacle_layer` + `inflation_layer` (**0.4 m** radius); the `obstacle_layer` marks the scenario obstacles so **NavFn routes the global plan around them** - the same global plan for every controller | -| Obstacle size | one **uniform** obstacle size across every b2 cell (`clearance: 0.45`); `static_box` is a 0.25 m box at dead-centre `(0, 0)` | +| Obstacle size | one **uniform** obstacle size across every b2 cell (`clearance: 0.45`); `static_box` is a 0.25 m box at dead-centre `(0, 0)`. The drawn body radius is a fixed harness constant ([`run_nav2.py:43`](../prox_mpc_benchmark/scripts/run_nav2.py)), so it is identical in both measurement sessions and for every controller | +| ProxMPC keep-out | both presets at `robot_radius: 0.235 m` + `safety_margin: 0.085 m`, so `d_safe = 0.320 m`. The radius is the circumscribed radius of the costmap's own padded footprint, so the keep-out covers the robot's outline; the margin carries the discretionary part. This is a ProxMPC-internal constraint radius, not an obstacle or costmap property - no other controller reads it | | Obstacle sensing | a **scan simulator** ray-casts the scenario obstacles into `/scan`; the `obstacle_layer` marks/clears them, so all controllers see the same obstacles | | Repeats | **5** fixed-seed repeats per controller per scenario (**10** for MPPI on every obstacle cell, to better characterise its sampling variance) | | Controllers | ProxMPC (Unicycle), DWB, MPPI, RPP, Graceful, Vector Pursuit - plus **ProxMPC (predictive)** with the obstacle tracker for Section 6.3-6.4 | +| Predictive preset, new in this campaign | the predictive preset now also ships `allow_reversing: true`, `obstacle_yield_band_m: 0.5` and `obstacle_yield_caps_speed: true` - an obstacle-aware cruise that caps the solver's *forward speed bound* when a mover is inside the band, rather than only lowering a cruise target the obstacle term outweighs. The reactive preset is unchanged, so the two presets now differ by these three keys as well as by prediction (Section 8) | | Compute timing | a `nav2_core::Controller` **timing decorator** wraps every controller and times its `computeVelocityCommands` identically | ### 2.1 Fair tuning: what is equalised and what is not @@ -60,14 +76,15 @@ The open cell deliberately understates a constrained optimal-control method - an The controllers are different algorithms, so their *internal* knobs are not the same quantity and cannot be set "equal" without meaning something different for each. The fair approach is to equalise everything they *share* and leave each method's intrinsic mechanism at its documented operating point: -- **Equalised** - control rate (20 Hz), max linear speed (0.5 m/s), goal tolerance (0.25 m), the **prediction horizon (2.0 s)** for all predictive controllers (ProxMPC `np*dt = 20 x 0.1`; DWB `sim_time = 2.0`; MPPI `time_steps x model_dt = 40 x 0.05`), a **uniform physical obstacle size** across every cell, and the **obstacle perception**: a shared local *and* global `obstacle_layer` fed by the scan simulator means every controller (including ProxMPC's costmap fill) sees the *same physical obstacles* through the *same costmaps + inflation*, and receives the *same* obstacle-routed global plan. In the head-to-head ProxMPC runs `predict_obstacles: false`, so it gets **no** privileged obstacle knowledge; the separate **ProxMPC (predictive)** variant (Section 6.4) turns that flag on and adds the real obstacle tracker, and is otherwise the identical preset so the comparison isolates prediction. +- **Equalised** - control rate (20 Hz), max linear speed (0.5 m/s), goal tolerance (0.25 m), the **prediction horizon (2.0 s)** for all predictive controllers (ProxMPC `np*dt = 20 x 0.1`; DWB `sim_time = 2.0`; MPPI `time_steps x model_dt = 40 x 0.05`), a **uniform physical obstacle size** across every cell, and the **obstacle perception**: a shared local *and* global `obstacle_layer` fed by the scan simulator means every controller (including ProxMPC's costmap fill) sees the *same physical obstacles* through the *same costmaps + inflation*, and receives the *same* obstacle-routed global plan. In the head-to-head ProxMPC runs `predict_obstacles: false`, so it gets **no** privileged obstacle knowledge; the separate **ProxMPC (predictive)** variant (Section 6.4) turns that flag on and adds the real obstacle tracker. Both presets share `d_safe = 0.320 m`, so the keep-out no longer separates them; they still differ in the costmap threshold and the slack penalty, so the pair does not isolate prediction exactly (Section 8). - **A note on the shared global plan.** Because the global costmap carries an `obstacle_layer`, NavFn bends the *global* path around obstacles before any controller runs. This is deliberately equal for all six, but it is worth stating plainly that it **helps the pure path-followers most**: DWB, RPP, Vector Pursuit and Graceful track that global detour closely, so an obstacle-routed global plan does much of their avoidance for them, whereas ProxMPC re-optimises locally and leans less on it. The comparison therefore measures *local avoidance on top of an equal, obstacle-aware global plan* - not local avoidance in isolation. -- **Left at each method's default** - the *avoidance mechanism itself*, because it has no common denominator across paradigms: DWB's `BaseObstacle` critic (nav2_bringup default `scale 0.02`), MPPI's `CostCritic` (upstream default `cost_weight 3.81`), ProxMPC's in-loop keep-out constraint, and RPP/Graceful's forward-simulation collision check. Crippling any of them to a common number would misrepresent it. The obstacles each faces are equal; how each responds is its own algorithm. +- **Left at each method's default** - the *avoidance mechanism itself*, because it has no common denominator across paradigms: DWB's `BaseObstacle` critic (nav2_bringup default `scale 0.02`), MPPI's `CostCritic` (upstream default `cost_weight 3.81`), ProxMPC's in-loop keep-out constraint (`d_safe = 0.320 m`, both presets), and RPP/Graceful's forward-simulation collision check. Crippling any of them to a common number would misrepresent it. The obstacles each faces are equal; how each responds is its own algorithm. - **Intrinsic sampling** left at upstream defaults: MPPI `batch_size = 2000`, DWB's `20 x 20` velocity grid, ProxMPC's single-QP SQP. -- **Determinism** - MPPI is the one stochastic controller and Nav2 Jazzy exposes no RNG seed for it, so its repeats capture genuine sampling variance (reported as `mean ± std`), not reproducibility; it is run at 10 repeats on the obstacle cells (5 on the open cell) rather than the 5 used for the deterministic controllers. +- **Determinism** - MPPI is the one stochastic controller and Nav2 Jazzy exposes no RNG seed for it, so its repeats capture genuine sampling variance (reported as `mean ± std`), not reproducibility; it is run at 10 repeats on the obstacle cells (5 on the open cell) rather than the 5 used for the deterministic controllers. The other five controllers are deterministic in principle, but mode (b2) is real wall-clock ROS execution (DDS discovery, thread scheduling, lifecycle bring-up), not simulated time, so their repeats still carry a small measured jitter - itself part of the precision signal. - **Graceful** - a good-faith goal-approach tuning (lookahead below the goal tolerance, reduced slowdown radius, no in-place final rotation) lets it drive into the goal rather than stalling far out; it succeeds on every scenario measured here. -Because the plant, map, planner, goal checker, horizon, speed, obstacle size, costmaps, and instrumentation are all shared, every difference in the tables is attributable to the controller. +Because the plant, map, planner, goal checker, horizon, speed, obstacle size, costmaps, and instrumentation are all shared, every difference in the tables is attributable to the controller, its own run-to-run variance, or to host timing drift between the two measurement sessions (Section 8). +The keep-out radius is a ProxMPC-internal quantity with no cross-controller counterpart, so changing it does not change what any other controller faces - the physical obstacles, and therefore the obstacle-gap metric that scores every controller identically, are unchanged. ### Metric definitions @@ -84,224 +101,275 @@ Because the plant, map, planner, goal checker, horizon, speed, obstacle size, co | Controller | success | time-to-goal [s] | goal err [m] | cross-track RMS [m] | cross-track max [m] | | --- | --- | --- | --- | --- | --- | -| **ProxMPC** (Unicycle) | 5/5 | 12.45 ± 0.50 | 0.239 | **0.0004 ± 0.0000** | 0.0008 | -| Regulated Pure Pursuit | 5/5 | 11.76 ± 1.33 | 0.235 | 0.0000 ± 0.0000 | 0.0000 | -| MPPI | 5/5 | 11.84 ± 1.70 | 0.233 | 0.0029 ± 0.0002 | 0.0039 | -| DWB | 5/5 | 12.68 ± 1.13 | 0.237 | 0.0001 ± 0.0001 | 0.0003 | -| Vector Pursuit | 5/5 | 13.03 ± 1.05 | 0.237 | 0.0000 ± 0.0000 | 0.0000 | -| Graceful | 5/5 | 10.48 ± 0.98 | 0.224 | 0.0000 ± 0.0000 | 0.0000 | +| **ProxMPC** (Unicycle) | 5/5 | 12.26 ± 1.74 | 0.237 | 0.0001 ± 0.0000 | 0.0002 | +| **ProxMPC (predictive)** | 5/5 | 13.54 ± 0.89 | 0.238 | **0.0000 ± 0.0000** | 0.0000 | +| Regulated Pure Pursuit | 5/5 | 11.74 ± 0.99 | 0.235 | 0.0000 ± 0.0000 | 0.0000 | +| MPPI | 5/5 | 12.21 ± 0.63 | 0.228 | 0.0029 ± 0.0001 | 0.0041 | +| DWB | 5/5 | 12.34 ± 1.00 | 0.237 | 0.0001 ± 0.0001 | 0.0008 | +| Vector Pursuit | 5/5 | 13.15 ± 1.09 | 0.236 | 0.0000 ± 0.0000 | 0.0000 | +| Graceful | 5/5 | 11.20 ± 1.26 | 0.224 | 0.0000 ± 0.0000 | 0.0000 | + +All seven track the straight line to the plant's resolution and complete 5/5. +Cross-track RMS is at or below 0.1 mm for six of them and 2.9 mm for MPPI, the one stochastic controller; every controller finishes two orders of magnitude inside the 0.25 m goal tolerance. +Time-to-goal spans 11.2-13.5 s with per-controller spreads of ±0.6-1.7 s, which is wall-clock bring-up and scheduling jitter on a 5 m traverse rather than a control effect - the spread is comparable to the gap between the fastest and slowest controller, so the ordering here carries no signal. -All six track the straight line essentially perfectly (sub-millimetre cross-track) and complete 5/5; ProxMPC and DWB are exact to the plant resolution and MPPI is within 3 mm. -On *tracking fidelity* there is no meaningful separation on an empty straight line - which is exactly why the compute-and-resource comparison below is the discriminating open-cell result for the predictive controllers. +On *tracking fidelity* there is no meaningful separation on an empty straight line, which is exactly why the compute-and-resource comparison below is the discriminating open-cell result, and why obstacle avoidance is reported separately. ## 4. Per-cycle compute cost and process resources -This is the comparison that matters on an embedded target, and it is **measured, not inferred**: the timing decorator wall-clock times every controller's `computeVelocityCommands` the same way, on **every** scenario, and a per-process sampler reads the `controller_server`'s CPU and RSS from `/proc`. +This comparison is **measured, not inferred**: the timing decorator wall-clock times every controller's `computeVelocityCommands` the same way, on **every** scenario, and a per-process sampler reads the `controller_server`'s CPU and RSS from `/proc`. Unlike tracking, compute is *not* flat across scenarios - the obstacle cells activate each method's avoidance machinery (ProxMPC's in-loop keep-out rows, DWB/MPPI's cost critics), so the per-cycle cost grows with obstacle load. The tables are therefore **per scenario, across all eleven cells** - split into single-obstacle and multi-obstacle groups - so that growth is visible. **ProxMPC (predictive)** is the same plugin with `predict_obstacles: true` and the obstacle tracker in the loop (Section 6.4), otherwise identical to reactive ProxMPC - so the two rows isolate the cost of prediction alone. -Its companion tracker runs as a *separate* process (~1 % of one core, ~38 MB RSS, constant across scenarios), which the `controller_server` figures below do **not** include; it is reported separately. +Its companion tracker runs as a *separate* process (0.96 % of one core, 38.3 MB RSS, constant across scenarios), which the `controller_server` figures below do **not** include; it is reported separately. ### 4.1 Per-cycle compute, `p50 / p95` [ms] (mean over repeats) -**Single-obstacle cells:** - -| Controller | open | static_box | line_fwd | line_bwd | circle | -| --- | --- | --- | --- | --- | --- | -| Graceful | 0.15 / 0.20 | 0.16 / 0.20 | 0.15 / 0.22 | 0.16 / 0.25 | 0.15 / 0.21 | -| Regulated Pure Pursuit | 0.21 / 0.25 | 0.21 / 0.28 | 0.21 / 0.29 | 0.21 / 0.29 | 0.21 / 0.30 | -| Vector Pursuit | 0.21 / 0.25 | 0.25 / 0.35 | 0.21 / 0.29 | 0.21 / 0.29 | 0.21 / 0.33 | -| **ProxMPC** | **0.75 / 1.15** | 1.14 / 2.79 | 0.99 / 4.59 | 1.07 / 4.65 | 1.43 / 5.52 | -| **ProxMPC (predictive)** | 0.50 / 1.05 | 1.12 / 2.69 | 0.92 / 3.23 | 1.00 / 3.79 | 1.52 / 5.03 | -| DWB | 2.46 / 2.70 | 2.57 / 2.94 | 2.66 / 3.49 | 2.63 / 3.50 | 2.57 / 3.52 | -| MPPI | 2.61 / 2.91 | 2.68 / 2.95 | 2.67 / 3.11 | 2.69 / 3.35 | 2.74 / 3.20 | - -**Multi-obstacle cells:** - -| Controller | dyn_multi | dyn_multi_noise | blind_0 | blind_1 | blind_2 | blind_3 | -| --- | --- | --- | --- | --- | --- | --- | -| Graceful | 0.18 / 0.30 | 0.15 / 0.20 | 0.15 / 0.22 | 0.16 / 0.24 | 0.16 / 0.22 | 0.16 / 0.23 | -| Regulated Pure Pursuit | 0.21 / 0.30 | 0.21 / 0.29 | 0.21 / 0.28 | 0.21 / 0.27 | 0.21 / 0.30 | 0.21 / 0.33 | -| Vector Pursuit | 0.21 / 0.29 | 0.20 / 0.27 | 0.20 / 0.27 | 0.21 / 0.32 | 0.21 / 0.30 | 0.20 / 0.28 | -| **ProxMPC** | 2.12 / 6.74 | 2.05 / 6.60 | 2.32 / 7.01 | 1.98 / 6.25 | 1.58 / 6.88 | 2.22 / 5.67 | -| **ProxMPC (predictive)** | 1.89 / 4.45 | 1.72 / 4.00 | 1.86 / 5.20 | 1.58 / 5.62 | 1.80 / 3.90 | 1.69 / 4.20 | -| DWB | 2.73 / 3.45 | 2.73 / 3.68 | 2.66 / 3.25 | 2.76 / 3.63 | 2.65 / 3.34 | 2.74 / 3.46 | -| MPPI | 2.70 / 3.12 | 2.62 / 3.08 | 2.64 / 3.10 | 2.67 / 3.02 | 2.68 / 3.19 | 2.64 / 3.18 | +| scenario | ProxMPC | ProxMPC pred | DWB | MPPI | RPP | Graceful | VecPursuit | +|---|---|---|---|---|---|---|---| +| `nav2_open` | **0.30 / 1.02** | **0.29 / 0.60** | 2.96 / 4.41 | 3.11 / 4.05 | 0.23 / 0.36 | 0.18 / 0.32 | 0.23 / 0.38 | +| `static_box` | 1.06 / 3.41 | 0.96 / 2.88 | 3.05 / 4.22 | 3.15 / 4.22 | 0.23 / 0.40 | 0.17 / 0.29 | 0.23 / 0.37 | +| `dynamic_line_forward` | 0.92 / 4.37 | 0.82 / 4.73 | 2.96 / 4.59 | 3.06 / 4.31 | 0.22 / 0.36 | 0.17 / 0.29 | 0.23 / 0.39 | +| `dynamic_line_backward` | 1.05 / 4.22 | 0.87 / 4.22 | 2.84 / 4.16 | 3.07 / 4.27 | 0.22 / 0.40 | 0.17 / 0.30 | 0.23 / 0.36 | +| `dynamic_circle` | 1.72 / 6.42 | 1.59 / 5.20 | 3.14 / 4.76 | 3.07 / 4.09 | 0.24 / 0.40 | 0.18 / 0.29 | 0.23 / 0.37 | +| `dynamic_multi` | 2.39 / 7.32 | 1.75 / 5.39 | 3.09 / 4.45 | 2.99 / 4.06 | 0.23 / 0.40 | 0.17 / 0.28 | 0.23 / 0.40 | +| `dynamic_multi_noise` | 2.47 / 7.23 | 1.70 / 5.70 | 3.16 / 4.85 | 3.05 / 4.22 | 0.24 / 0.40 | 0.18 / 0.31 | 0.23 / 0.38 | +| `blind_multi_0` | 2.73 / 8.66 | 2.06 / 6.61 | 3.06 / 4.51 | 3.09 / 4.30 | 0.23 / 0.38 | 0.17 / 0.31 | 0.21 / 0.36 | +| `blind_multi_1` | 2.56 / 7.32 | 1.34 / 5.74 | 3.12 / 5.04 | 3.07 / 4.09 | 0.23 / 0.38 | 0.18 / 0.29 | 0.23 / 0.39 | +| `blind_multi_2` | 2.34 / 11.40 | 1.30 / 4.49 | 3.05 / 4.78 | 3.03 / 4.11 | 0.23 / 0.38 | 0.17 / 0.29 | 0.23 / 0.39 | +| `blind_multi_3` | 2.23 / 5.85 | 2.15 / 5.64 | 3.14 / 5.03 | 3.03 / 4.13 | 0.23 / 0.39 | 0.17 / 0.29 | 0.22 / 0.35 | + +The shape of this table is the result, not any single row. +**ProxMPC's cost scales with obstacle load; the sampling controllers' does not.** +DWB and MPPI pay a near-constant 2.8-3.2 ms whether the cell is empty or holds two movers, because their sample counts are fixed. ProxMPC pays 0.30 ms on the empty cell and 2.2-2.7 ms on the hardest, because the QP grows a keep-out row per obstacle slot per node. + +So the advantage is largest exactly where a robot spends most of its time - **9.9x lighter than DWB and 10.4x than MPPI on the open cell** - narrows to ~2.5-3x on single-obstacle cells, and converges to ~1.3x on the multi-mover cells. It never inverts: ProxMPC's median stays at or below both on every cell measured. +The predictive preset is *cheaper* than the reactive one on every obstacle cell (1.3-2.2 ms against 2.2-2.7 on the multi cells) because a tracked obstacle occupies one slot with a known trajectory, while the costmap fill spends slots on clusters it must re-rank each cycle. + +The one outlier is reactive ProxMPC's 11.40 ms p95 on `blind_multi_2`, against 6-9 ms elsewhere; that cell is where the reactive keep-out struggles most (it collides 5/5 there, Section 6.4), and the extra QP iterations show up in the tail rather than the median (2.34 ms). The predictive preset, which clears that same cell 0/5, pays only 4.49 ms at p95 on it. ### 4.2 Process CPU [% of one core] / RSS peak [MB] -**Single-obstacle cells:** - -| Controller | open | static_box | line_fwd | line_bwd | circle | -| --- | --- | --- | --- | --- | --- | -| Regulated Pure Pursuit | 4.4 / 55 | 4.3 / 55 | 4.3 / 55 | 4.5 / 55 | 4.3 / 55 | -| Vector Pursuit | 4.2 / 55 | 4.5 / 55 | 4.2 / 55 | 4.1 / 55 | 4.3 / 55 | -| Graceful | 4.2 / 56 | 4.3 / 56 | 4.3 / 56 | 4.2 / 56 | 4.3 / 56 | -| **ProxMPC** | 5.0 / 58 | 6.1 / 58 | 6.5 / 58 | 6.5 / 58 | 7.2 / 58 | -| **ProxMPC (predictive)** | 5.3 / 60 | 6.4 / 60 | 6.5 / 60 | 6.4 / 60 | 7.2 / 60 | -| DWB | 8.6 / 60 | 9.0 / 60 | 8.8 / 60 | 8.9 / 60 | 9.0 / 60 | -| MPPI | 8.6 / 63 | 8.6 / 63 | 8.8 / 63 | 8.9 / 63 | 8.9 / 63 | - -**Multi-obstacle cells:** - -| Controller | dyn_multi | dyn_multi_noise | blind_0 | blind_1 | blind_2 | blind_3 | -| --- | --- | --- | --- | --- | --- | --- | -| Regulated Pure Pursuit | 4.6 / 55 | 4.5 / 55 | 4.6 / 55 | 4.3 / 55 | 4.4 / 55 | 4.2 / 55 | -| Vector Pursuit | 4.3 / 55 | 4.3 / 55 | 4.2 / 55 | 4.3 / 55 | 4.4 / 55 | 4.2 / 55 | -| Graceful | 4.6 / 56 | 4.4 / 56 | 4.4 / 56 | 4.4 / 56 | 4.3 / 56 | 4.2 / 56 | -| **ProxMPC** | 7.5 / 58 | 7.9 / 58 | 7.6 / 58 | 7.3 / 58 | 7.4 / 58 | 7.5 / 58 | -| **ProxMPC (predictive)** | 7.7 / 60 | 7.1 / 60 | 7.0 / 60 | 7.6 / 60 | 7.3 / 60 | 6.8 / 60 | -| DWB | 9.6 / 60 | 9.4 / 60 | 9.2 / 60 | 9.1 / 60 | 9.1 / 60 | 9.4 / 60 | -| MPPI | 9.1 / 63 | 9.1 / 63 | 9.1 / 64 | 8.9 / 63 | 9.0 / 64 | 8.9 / 63 | - -> ProxMPC-predictive additionally spends ~1.0 % core and ~38 MB in the obstacle-tracker process, constant across every scenario - a small overhead the tables above exclude. - -The compute comparison across the eleven cells: - -- **The median advantage holds on all eleven cells, but it narrows sharply as the field tightens.** On the empty cell ProxMPC computes a command in **0.75 ms median / 1.15 ms p95** - **~3.3x faster than DWB and ~3.5x faster than MPPI at the median**. Adding obstacles roughly doubles to triples ProxMPC's median (to 1.0-2.3 ms) as the keep-out rows activate, and the advantage falls to **1.1-2.7x across the obstacle cells**: ~2.3-2.7x on the single-obstacle cells but only ~1.1-1.7x on the six-way-constrained multi cells, where ProxMPC is barely cheaper than the samplers. MPPI's cost is nearly flat (its 2000-sample batch dominates regardless of obstacles); DWB's rises slightly with its active critics. -- **Process CPU tracks the same ordering**, compressed by the shared ~4 % costmap floor: ProxMPC **5.0 %** (open) rising to 9.1 % on the hardest cell, against DWB/MPPI's **8.4-9.3 %**; ProxMPC-predictive is steadier at 5.6-8.5 %. RSS is 58-64 MB throughout, MPPI the heaviest (63-64 MB), ProxMPC the lightest (58-59 MB). -- **The geometric controllers are lighter still** - RPP, Graceful and Vector Pursuit compute in ~0.15-0.25 ms at ~4 % CPU, carrying no optimisation or constraint machinery. ProxMPC is the cheapest of the controllers that solve a constrained optimisation each cycle, not the cheapest controller outright; the geometric controllers buy their low cost by having no model, no constraints, and no horizon optimisation. -- **Prediction is cheaper than reactive, not more expensive.** ProxMPC-predictive is at or below reactive at the median on almost every cell - 0.50 ms against 0.75 ms on the open cell, and 1.58-1.89 ms against 1.58-2.32 ms on the multi cells - and its p95 tail is consistently lighter (4.0-5.6 ms against 5.7-7.0 ms). A single confirmed track is a smaller, cleaner constraint set than the reactive costmap's clustered wall cells. The predictive capability's real extra price is the companion tracker (~1 % core, ~38 MB), not the controller cycle. -- **The tail is heavy on the hard cells, and the worst case now overruns the budget.** On the dynamic and multi-obstacle cells ProxMPC's **p95 rises to 5.7-7.0 ms** (predictive 4.0-5.6 ms), against DWB's and MPPI's steadier 3.0-3.7 ms: with many half-plane rows simultaneously active the worst-case QP is heavier than a fixed-size sampler. Every p95 still sits ~7x inside the 50 ms control budget, but **5 runs of 427 recorded a single cycle above 50 ms, peaking at 321 ms** (four of them predictive, on the multi and circle cells). This is a direct consequence of rebuilding the QP factorization every cycle. ProxMPC is much cheaper on average but far more variable; the sampling controllers are steadier. -- **Achieved command rate is completion-coupled on the hard cells.** ProxMPC holds a clean ~20 Hz on the open, static and single-dynamic cells, and mostly holds it on the multi cells, dropping to ~15.3 Hz where it stalls. This is almost never a compute deadline miss - only 4 runs of 435 report a non-zero deadline-miss rate at all, and the highest is 0.56 % (Section 5) - but a symptom of the controller **stalling** when over-constrained: a stalled robot stops being commanded, which lowers the sampled rate. It is read together with the completion and collision results in Section 6, not as a compute limit. +| scenario | ProxMPC | ProxMPC pred | DWB | MPPI | RPP | Graceful | VecPursuit | +|---|---|---|---|---|---|---|---| +| `nav2_open` | 4.6 / 59 | 4.7 / 60 | 9.0 / 60 | 9.1 / 63 | 3.8 / 55 | 3.8 / 56 | 3.9 / 55 | +| `static_box` | 6.3 / 59 | 6.4 / 60 | 9.4 / 60 | 9.3 / 63 | 4.0 / 55 | 4.0 / 56 | 4.1 / 55 | +| `dynamic_line_forward` | 6.3 / 59 | 6.3 / 60 | 9.3 / 60 | 9.3 / 63 | 4.1 / 55 | 3.9 / 56 | 4.0 / 55 | +| `dynamic_line_backward` | 6.5 / 59 | 6.4 / 60 | 8.9 / 60 | 9.2 / 63 | 4.0 / 55 | 3.9 / 56 | 4.0 / 55 | +| `dynamic_circle` | 7.9 / 59 | 7.5 / 60 | 9.5 / 60 | 9.4 / 63 | 4.0 / 55 | 4.1 / 56 | 3.9 / 55 | +| `dynamic_multi` | 9.1 / 59 | 8.1 / 60 | 9.5 / 60 | 9.3 / 63 | 4.1 / 55 | 3.9 / 56 | 4.0 / 55 | +| `dynamic_multi_noise` | 9.2 / 59 | 7.9 / 60 | 9.7 / 60 | 9.4 / 63 | 4.1 / 55 | 4.0 / 56 | 3.9 / 55 | +| `blind_multi_0` | 10.4 / 59 | 9.0 / 60 | 9.6 / 60 | 9.5 / 63 | 4.1 / 55 | 4.1 / 56 | 3.9 / 55 | +| `blind_multi_1` | 9.5 / 59 | 7.7 / 60 | 9.5 / 60 | 9.3 / 63 | 4.0 / 55 | 4.0 / 56 | 3.9 / 55 | +| `blind_multi_2` | 11.1 / 59 | 7.3 / 60 | 9.4 / 60 | 9.4 / 64 | 4.0 / 55 | 3.9 / 56 | 4.0 / 55 | +| `blind_multi_3` | 8.6 / 59 | 8.4 / 60 | 9.7 / 60 | 9.3 / 63 | 4.1 / 55 | 4.0 / 56 | 4.0 / 55 | + +The same shape appears in process CPU: ProxMPC starts at 4.6 % on the empty cell against DWB's 9.0 % and MPPI's 9.1 %, and rises to 7.3-11.1 % on the hardest cells where they stay flat. Reactive ProxMPC is the only controller that exceeds the sampling pair, and only on the two cells its keep-out finds hardest (`blind_multi_0` at 10.4 %, `blind_multi_2` at 11.1 %); the predictive preset stays at or below both everywhere (7.5 % averaged over all obstacle cells, against reactive's 8.5 %, DWB's 9.4 % and MPPI's 9.3 %). + +Memory is flat and unremarkable for every controller: 59-60 MB peak RSS for ProxMPC against 60 for DWB and 63-64 for MPPI, with the three pursuit controllers at 55-56. Nothing here grows over a run. +The predictive preset's companion tracker, sampled as a separate process across all 55 predictive runs, costs **0.96 % of one core and 38.3 MB RSS** on top of the `controller_server` figures above. ## 5. ProxMPC solver profile (and a cross-check) -ProxMPC is the only controller that also publishes its *internal* solver telemetry ([`SolverDiagnostics`](../prox_mpc_msgs/README.md)): +Solver telemetry over all 10 obstacle cells (50 runs per preset), from the opt-in `SolverDiagnostics` topic: -| Metric | Open cell | With obstacle constraints active | -| --- | --- | --- | -| decorator compute p95 (whole `computeVelocityCommands`) | 1.11 ms | 1.7-5.7 ms | -| internal QP solve p95 | 1.04 ms | 1.5-6.4 ms | -| worst single-cycle solve (max) | 2.69 ms | up to ~242 ms | -| deadline-miss rate (compute > 50 ms budget) | 0.0 % | 0.0 % | -| infeasible rate (QP status != SOLVED) | 0.0 % | 0.0 % | -| mean SQP iterations | 1.00 | 1.00 | - -The two independent instruments agree on the open cell: the QP solve (1.04 ms p95) accounts for almost all of the measured per-cycle compute (1.11 ms p95), the ~0.07 ms remainder being the costmap reduction and the exact footprint veto. -The worst single open-cell cycle stays **~20x inside** the 50 ms budget, which is why ProxMPC holds 20 Hz with 0 % deadline-miss and 0 % infeasible. -With the in-loop obstacle constraints active the per-cycle cost rises to a p95 of 2.7-7.0 ms across the eleven obstacle scenarios (more active half-plane rows on the dynamic and multi cells than the static one). Deadline misses stay essentially absent - **4 runs of 435 report a non-zero rate at all, the worst 0.56 %** - but the worst-case tail is no longer inside budget: **5 runs of 427 recorded a single cycle above 50 ms, peaking at 321 ms**, concentrated on the predictive multi cells. Each cycle rebuilds the QP factorization from scratch, so a hard cycle pays the full symbolic cost. -The solver never fails to return a feasible QP solution in time; where reactive ProxMPC misses on a multi cell (Section 6.4) it is the *geometry* of the convex keep-out that fails, not the solver's timing or feasibility. +| | solve p50 | solve p95 | solve max | over 50 ms | deadline-miss | SQP iters | QP ext iters | infeasible runs | peak slack | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| reactive | 1.82 ms | 6.49 ms | 33.5 ms | **0 / 50** | 0.00 % | 1.00 | 7.5 | 9 / 50 | 0.553 m | +| predictive | 1.31 ms | 4.91 ms | **31.1 ms** | **0 / 50** | 0.00 % | 1.00 | 6.9 | 3 / 50 | 0.766 m | -## 6. Obstacle avoidance +**Every cycle in 100 runs stayed inside the 50 ms budget.** This is the single largest behavioural change in this release, and it came from two defects rather than from tuning: -The open cell cannot show avoidance, so these scenarios place obstacles across the path and let every controller perceive them through the same local and global `obstacle_layer`. -Because the kinematic plant has no collision physics, "reaching the goal" alone does not prove avoidance - a controller can drive straight through an obstacle and still "succeed" - so the discriminating metric is the **obstacle gap** (robot-disc to obstacle-disc; negative = overlap = would-be collision). +1. `max_iter_sqp` defaulted to 100. On a failed solve the loop re-linearised up to 99 more times around an iterate it had already corrupted, then braked anyway. Worst-case cycles of 300 ms were measured on three separate cells - six times the budget, and 15 cm of open-loop travel at 0.5 m/s. The default is now 1, which is what the real-time iteration scheme this controller implements actually prescribes. +2. The QP was re-initialised from scratch every cycle. `guess: true` named a warm start that never happened, because `init()` rebuilt the workspace and discarded the previous primal/dual iterate 20 times a second. The workspace is now updated in place, which cut the worst case by a further ~40 %. -The global costmap carries an `obstacle_layer`, so NavFn routes the global plan around obstacles for every controller, and every cell uses one uniform obstacle size (`clearance 0.45`). The single-obstacle cells (Section 6.1-6.2) are within reach of the whole field and separate the controllers on *margin* and on the orbiting case; the multi-obstacle cells (Section 6.4) are where collision counts spread. Two comparisons carry the result: ProxMPC against the other optimisation- and sampling-based controllers - **DWB** and **MPPI**, its per-cycle-cost peers - and ProxMPC against the geometric pursuit controllers - **RPP**, **Graceful** and **Vector Pursuit** - which trade avoidance headroom for near-zero compute. +`SQP iters` sitting at 1.00 is the fixed real-time iteration, not a convergence report; `QP ext iters` at 6.9-7.5 against a 10 000 cap shows the QP itself converges quickly when it converges at all. -### 6.1 Static obstacle (`static_box`, mode b2) +**One thing this table does not explain.** The reactive preset reports `PROXQP_PRIMAL_INFEASIBLE` on 9 of 50 runs (roughly 0.1-0.3 % of cycles within them), where the published `v1.0.0`-era campaign reported none. The QP's feasible set is provably non-empty - the constant sequence `u(k) = u_prev` satisfies the control box, the rate chain and the row-0 rate anchor simultaneously, and the obstacle rows are fully soft - so every such report is a false certificate. Three candidate causes were tested and eliminated by measurement: a warm start that violated its own rate chain, the absent solver warm start, and large-magnitude bounds on unused obstacle slots. The cause is still unknown. + +It is benign in every way the harness can measure: the controller brakes for that cycle, the next one solves, worst-case latency stays at 33.5 ms, and no infeasible cycle has been traced to a collision. It is recorded here because it is real and unexplained, not because it is known to matter. + +The predictive preset's peak keep-out slack is now the higher of the two (0.766 m against the reactive 0.553 m), which is the yield behaving as designed rather than a safety regression: the predictive path relaxes the *inflated soft margin* while it slows and lets a mover pass, and it is simultaneously the only preset that never touches the physical keep-out on a single-mover cell (Section 6.2, worst gap +0.212 m against reactive's +0.186 m). Peak slack measures how far the soft constraint was relaxed, not how close the robot came. -A 0.25 m box placed **dead-centre** on the path at `(0, 0)`; with the obstacle-routed global plan every controller has a path that already bends around it. -The last two columns carry the per-scenario **cost of that avoidance** (the same decorator/process instruments as Section 4), so clearance and its price are read together. +## 6. Obstacle avoidance + +### 6.1 Static obstacle (`static_box`, mode b2) -| Controller | success | obstacle gap [m] | collision | compute p50/p95 [ms] | CPU [%] | +| Controller | success | collisions | min gap [m] | mean gap [m] | cross-track max [m] | | --- | --- | --- | --- | --- | --- | -| **ProxMPC** | 5/5 | **+0.352 ± 0.002** | **0/5** | 1.14 / 2.79 | 6.6 | -| **ProxMPC (predictive)** | 5/5 | +0.298 ± 0.001 | **0/5** | 1.12 / 2.69 | 6.7 + 1.1 trk | -| Regulated Pure Pursuit | 5/5 | +0.213 ± 0.002 | 0/5 | 0.21 / 0.28 | 4.3 | -| Graceful | 5/5 | +0.207 ± 0.007 | 0/5 | 0.16 / 0.20 | 4.5 | -| MPPI | 10/10 | +0.207 ± 0.002 | 0/10 | 2.68 / 2.95 | 8.6 | -| DWB | 5/5 | +0.093 ± 0.004 | 0/5 | 2.57 / 2.94 | 9.0 | -| Vector Pursuit | **0/5** | +0.175 (stopped short) | 0/5 | 0.25 / 0.35 | 4.4 | - -Every controller clears the static box collision-free, so the discrimination is in the *margin*, not in whether they hit. -**ProxMPC keeps the largest margin of the field - +0.352 m** - by swerving wide and recovering, the behaviour the in-loop keep-out constraint produces, at **~2.3x less per-cycle compute than DWB and MPPI**. -Predictive ProxMPC holds a close +0.298 m: the tracker reports the box at ~0 velocity, so the hybrid fill treats it much like the reactive path. -Among the cost-class peers, **DWB cuts it finest at +0.093 m** - its soft `BaseObstacle` critic rides close to the inflated edge - while MPPI holds +0.207 m; among the geometric controllers RPP and Graceful hold ~+0.21 m. -**Vector Pursuit is the one controller that fails to complete** (0/5): its own forward-collision check (`use_collision_detection`) halts it in front of the box before it steers around, so its +0.175 m "gap" is a stopped-short distance, not a steered avoidance. - -### 6.2 Single moving obstacles (mode b2, reactive) - -Three single-mover scenarios - a patrol crossing the path forward (`dynamic_line_forward`) and backward (`dynamic_line_backward`) at 0.6 m/s, and an obstacle orbiting near mid-path (`dynamic_circle`) at 0.5 m/s. -Almost the whole field clears these reactively; the exceptions are the two controllers whose commitment to a rollout clips the *orbiting* obstacle: - -| Scenario | metric | ProxMPC | ProxMPC-pred | DWB | MPPI | RPP | Graceful | VecPursuit | -| --- | --- | --- | --- | --- | --- | --- | --- | --- | -| line_forward | collision | 0/5 | 0/5 | 0/5 | 0/10 | 0/5 | 0/5 | 0/5 | -| | min gap [m] | +0.55 | +0.38 | +0.49 | +0.61 | +0.42 | +0.28 | +0.47 | -| line_backward | collision | 0/5 | 0/5 | 0/5 | 0/10 | 0/5 | 0/5 | 0/5 | -| | min gap [m] | +0.54 | +0.37 | +0.50 | +0.62 | +0.40 | +0.36 | +0.43 | -| circle | collision | **0/5** | **0/5** | **5/5** | 0/10 | 1/5 | **4/5** | 0/5 | -| | min gap [m] | +0.12 | +0.14 | **-0.26** | +0.18 | +0.07 | **-0.08** | +0.15 | - -**On the two straight patrols every controller keeps a real margin (0 collisions).** -On the **orbiting** obstacle the field splits: ProxMPC, predictive ProxMPC, MPPI and Vector Pursuit all clear it (+0.12 to +0.18 m) and RPP clips it once (1/5, +0.07 m), while **DWB collides 5/5 (-0.26 m)** and **Graceful 4/5 (-0.08 m)** - both commit to a trajectory the obstacle then orbits into, and the routed global plan (computed once against the obstacle's initial footprint) does not track the moving object. This is the one single-obstacle cell where ProxMPC's constrained optimisation outperforms a cost-class peer, DWB, outright. -Reactive and predictive ProxMPC are indistinguishable across the three single-mover cells - both hold a positive margin - so prediction's measurable value appears on the multi-obstacle cells (Section 6.4). -Compute stays in the Section 4 ordering: ProxMPC ~2.2-2.9x lighter than DWB and MPPI at the median while carrying the active keep-out rows, with a p95 tail up to ~4.3 ms across these cells (~4.2 ms on the orbit itself). +| **ProxMPC** (reactive) | 5/5 | 0/5 | **+0.382** | **+0.382** | 0.737 | +| **ProxMPC (predictive)** | 5/5 | 0/5 | +0.297 | +0.298 | 0.650 | +| RPP | 5/5 | 0/5 | +0.211 | +0.213 | 0.569 | +| MPPI | 10/10 | 0/10 | +0.204 | +0.208 | 0.588 | +| Graceful | 5/5 | 0/5 | +0.195 | +0.211 | 0.574 | +| Vector Pursuit | **1/5** | 0/5 | +0.134 | +0.247 | 0.551 | +| DWB | 5/5 | 0/5 | +0.069 | +0.090 | 0.455 | -### 6.3 Ground-truth predictive confirmation (mode b1) +Every controller that reaches the goal clears the static box without contact - an obstacle-routed global plan does most of this work, as Section 2.1 notes. +The separation is in *margin*: reactive ProxMPC keeps +0.382 m at its closest against DWB's +0.069 m, and it pays for that with the largest detour (0.737 m cross-track against 0.455). That trade is the in-loop keep-out doing exactly what it is asked to: `d_safe` is a hard-ish constraint the optimiser plans around, not a cost it trades away. + +**Vector Pursuit stalls on this cell.** It reached the goal on only 1 of 5 runs, against 3 of 5 in the previous campaign; the four failures are the same behaviour recorded there - it stops behind the box and does not recover within the 60 s timeout. Its gap figures are computed over all five runs and therefore describe a controller that mostly stopped short, not one that passed the box with margin. This is a peer's own behaviour on stock binaries at an unchanged version, not an effect of anything in this release. -One controller-vs-tracker separation is worth recording: fed the *correct* future obstacle positions (mode b1, the engine knows the exact trajectory, orbit included), ProxMPC solves every single moving-obstacle case for both vehicle models: +### 6.2 Single moving obstacles (3 cells, mode b2) -| Scenario | Model | success | cross-track RMS [m] | time-to-goal [s] | +| Controller | collisions | min gap [m] | mean gap [m] | cross-track max [m] | | --- | --- | --- | --- | --- | -| dynamic_circle | Unicycle / Bicycle | 5/5 / 5/5 | 0.005 / 0.021 | 4.57 / 4.52 | -| dynamic_line_forward | Unicycle / Bicycle | 5/5 / 5/5 | 0.045 / 0.058 | 4.48 / 4.58 | -| dynamic_line_backward | Unicycle / Bicycle | 5/5 / 5/5 | 0.048 / 0.044 | 4.53 / 4.59 | -| static_box | Unicycle / Bicycle | 5/5 / 5/5 | 0.000 / 0.000 | 4.52 / 4.60 | +| **ProxMPC (predictive)** | **0/15** | **+0.212** | +0.346 | 0.376 | +| **ProxMPC (reactive)** | **0/15** | +0.186 | +0.398 | 0.604 | +| MPPI | 0/30 | +0.136 | **+0.456** | 0.283 | +| Vector Pursuit | 0/15 | +0.044 | +0.357 | 0.263 | +| RPP | 2/15 | -0.015 | +0.286 | 0.208 | +| Graceful | 5/15 | -0.065 | +0.206 | 0.103 | +| DWB | 5/15 | -0.345 | +0.238 | 0.113 | + +Four controllers clear all three single-mover cells collision-free - both ProxMPC presets, MPPI and Vector Pursuit; DWB and Graceful collide on 5 of 15 each and RPP on 2. +**The predictive preset now holds the largest worst-case margin in the field at +0.212 m** - no run in fifteen came closer than 21 cm - having overtaken the reactive preset (+0.186 m) on this measure for the first time. + +That reordering is the obstacle-aware speed cap doing its job. In the previous campaign the predictive preset's worst case was +0.064 m, the second *worst* in the field: it had the right prediction but no way to act on it, because the yield only lowered a cruise target that the keep-out term outweighed, so the solver swerved past a closing mover at full speed instead of slowing for it. Capping the solver's forward speed bound instead of its cruise reference raised that worst case by 15 cm, and it did so while *shrinking* the detour - cross-track max falls from the reactive preset's 0.604 m to 0.376 m. The robot now yields by slowing rather than by swerving, which is both safer and less disruptive to the path. + +A single moving obstacle is where the costmap-only fill is still sufficient: the obstacle's position lag costs the controller reaction time, but the free corridor beside it is wide enough to absorb a late swerve. That stops being true with two movers, which is Section 6.4. + +### 6.3 Ground-truth predictive confirmation (mode b1) + +> **Re-run in this campaign.** The 40-run mode-(b1) matrix was recorded in the same session as the b2 matrix above, on the same binaries and the same host, so its solve times are directly comparable with Section 5 for the first time. + +One controller-vs-tracker separation is worth recording: fed the *correct* future obstacle positions (mode b1, the engine knows the exact trajectory, orbit included), ProxMPC reaches the goal on every single moving-obstacle case for both vehicle models. +This section was re-run when reactive ProxMPC was still colliding 3/5 on the orbit, as a ceiling check on the formulation. +Section 6.2 has since resolved that failure at the reactive level, so this table is no longer answering an open question about the orbit - but it is retained because it is the only ground-truth-predictor result in the document and it bounds the formulation independently of what the costmap supplies: + +| Scenario | Model | success | cross-track RMS [m] | time-to-goal [s] | peak keep-out slack [m] | +| --- | --- | --- | --- | --- | --- | +| dynamic_circle | Unicycle / Bicycle | 5/5 / 5/5 | 0.007 / 0.007 | 4.56 / 4.58 | 0.000 / 0.000 | +| dynamic_line_forward | Unicycle / Bicycle | 5/5 / 5/5 | 0.045 / 0.058 | 4.56 / 4.58 | 0.222 / 0.375 | +| dynamic_line_backward | Unicycle / Bicycle | 5/5 / 5/5 | 0.048 / 0.044 | 4.54 / 4.56 | 0.194 / 0.225 | +| static_box | Unicycle / Bicycle | 5/5 / 5/5 | 0.000 / 0.000 | 4.49 / 4.56 | 2.945 / 2.945 [^slack] | + +> This table is a fresh 40-run campaign (4 scenarios x 2 models x 5 repeats, controller `proxmpc`), recorded in the same session as the b2 matrix. +> It is a ceiling check on the controller's own capability given a correct predictor, not the operative reactive/predictive result - that comparison is mode b2, in Sections 6.1-6.4. -With ground-truth prediction ProxMPC reaches the goal on **every** single moving-obstacle run for both a 3-state unicycle and a 4-state bicycle (40/40, static box included), the orbiting obstacle included, driven by the same plugin with one parameter changed (`model_plugin`). -The single-obstacle dynamic case is fully within the controller's reach given a correct predictor. The reactive costmap already suffices for the single movers (Section 6.2), so this ground-truth result is a ceiling check - it confirms the controller, not the tracker, sets the limit - rather than the operative result. +[^slack]: This is the one-cycle initialisation transient, not a steady-state figure: in this campaign every run of both models sampled it, where the previous campaign caught it on only 3 of 5 bicycle runs and none of the unicycle runs. The steady-state peak is 0.490 m. That the transient now appears uniformly is what the sampling account below predicts - whether it is recorded depends only on the metrics node's subscription matching in time, not on the model. See Section 6.3. + +**The 30/30 ceiling on the three single moving-obstacle cells still holds on the current tree**, for both a 3-state unicycle and a 4-state bicycle, driven by the same plugin with one parameter changed (`model_plugin`); with the static box included the campaign is 40/40. +The orbit is the sharpest of the four results: given the correct future positions the keep-out is **never relaxed at all** (peak slack 0.000 m for both models), so the predictive path clears the orbiting obstacle outright rather than trading margin for progress. +The single-obstacle dynamic case is therefore fully within the controller's reach given a correct predictor - and Section 6.2 now shows it is also within reach *without* one, once the keep-out carries enough margin to absorb the obstacle's motion between costmap updates. +The earlier reading of the reactive orbit failure as a limit of what the costmap supplies does not survive that result: the costmap was supplying enough, and the constraint built from it was simply sized too tightly. + +The slack column has to be read together with the success column, because "reaching the goal" in mode b1 is not by itself an avoidance result. +Mode b1 has no global planner: the reference is the straight start-to-goal line, so on `static_box` the cross-track RMS is exactly 0.000 m and the box is passed by relaxing the soft keep-out (0.490 m on the unicycle, essentially the whole 0.45 m clearance) rather than by steering around it. +The avoidance comparison is the mode-b2 one in Section 6.1; this section measures whether the solver keeps finding a feasible, goal-reaching trajectory when the prediction is perfect. + +Two observations about this table are worth recording, neither of them attributed to a specific change in the intervening work: + +- **The `static_box` peak-slack figure is a first-cycle initialisation transient, and its run-to-run spread is a sampling artefact rather than a solver result.** In this campaign all ten runs reported 2.945 m against the `max_obstacle_slack_m: {max: 0.5}` bound in [`prox_mpc_benchmark/config/metrics.yaml`](../prox_mpc_benchmark/config/metrics.yaml); in the previous one, three of five bicycle runs reported 2.945 m and the other two 0.490 m, with all five unicycle runs at 0.490 m. Capturing `/prox_mpc/diagnostics` per cycle resolves both numbers: the 2.945 m relaxation occurs on control cycle 1 alone and is back to 0.000 m by cycle 2, while 0.490 m is the true steady-state peak, reached at cycle 13 as the robot passes the box. The transient is deterministic and identical for both models - unicycle and bicycle agree to six decimals on the cycle-1 slack and on its objective - so it is not a bicycle-specific effect; what varies between runs is only whether the metrics node's subscription matched in time to receive cycle 1. **This campaign is the direct confirmation of that account**: the transient is now recorded on every run of both models, which is what a subscription race predicts and what a model-dependent or solver-dependent effect does not. The mechanism is that [`prox_mpc_core/src/mpc.cpp`](../prox_mpc_core/src/mpc.cpp) zero-initialises the whole predicted trajectory, so before the first solve every horizon node sits at the origin - which on `static_box`, and only on `static_box`, is exactly where the obstacle is, inside its 1.45 m keep-out and at the point where the distance gradient is undefined. `dynamic_circle`, whose mover is 1.8 m from the origin at `t = 0`, reports 0.000 m throughout, as this account predicts. Nothing in the executed trajectory is affected: cross-track RMS is exactly 0.000 m, and time-to-goal and goal error are unchanged from the runs that did not sample the transient. +- **Mode b1 remains far inside the real-time budget**: worst cell p95 16.3 ms, worst single cycle 36.4 ms across all 40 runs, at 0 % deadline-miss and 0 % infeasible, with 40/40 success. Mode b1 touches neither the costmap nor the Nav2 stack, so the per-cycle fixes credited in Section 4 do not apply to this path and its absolute solve times are not comparable with the b2 figures in Section 5 despite sharing a session. ### 6.4 Multiple simultaneous moving obstacles - where the field separates -The single-obstacle cells do not discriminate on collisions (Section 6.1-6.2), so the collision comparison rests on the **multi-mover** set: `dynamic_multi` and `dynamic_multi_noise` (two hand-built simultaneous movers, the latter with sensor noise), and `blind_multi_0`-`blind_multi_3` (blind, author-independent two-mover cells, generated without hand-screening). -Six cells, 30 runs per controller (60 for MPPI), collision per cell: +Six cells with two simultaneous movers. Four of them (`blind_multi_0..3`) are *blind*: their geometry comes from a seeded RNG with no controller run to screen it, so no cell was kept or discarded because of how any controller performed on it. + +| Controller | `dyn_multi` | `dyn_multi_noise` | `bm0` | `bm1` | `bm2` | `bm3` | total | +|---|---|---|---|---|---|---|---| +| **ProxMPC (predictive)** | 0/5 | 0/5 | 3/5 | 0/5 | 0/5 | 0/5 | **3/30 (10 %)** | +| RPP | 0/5 | 0/5 | 1/5 | 0/5 | 5/5 | 0/5 | 6/30 (20 %) | +| MPPI | 0/10 | 1/10 | 8/10 | 3/10 | 0/10 | 6/10 | 18/60 (30 %) | +| DWB | 2/5 | 2/5 | 1/5 | 0/5 | 5/5 | 0/5 | 10/30 (33 %) | +| Graceful | 4/5 | 3/5 | 1/5 | 0/5 | 5/5 | 0/5 | 13/30 (43 %) | +| Vector Pursuit | 1/5 | 0/5 | 5/5 | 0/5 | 5/5 | 2/5 | 13/30 (43 %) | +| ProxMPC (reactive) | 0/5 | 1/5 | 4/5 | 1/5 | 5/5 | 5/5 | 16/30 (53 %) | + +**Predictive ProxMPC leads by a factor of two**: 3 collisions in 30 against 6 for the next best. +Its remaining failures are now concentrated in a single cell - `blind_multi_0`, 3/5 - and it is **collision-free on the other five**, including `blind_multi_2`, which four of the seven controllers fail 5 times out of 5. -| Scenario | ProxMPC | ProxMPC-pred | DWB | MPPI | RPP | Graceful | VecPursuit | -| --- | --- | --- | --- | --- | --- | --- | --- | -| dynamic_multi | 3/5 | 0/5 | 1/5 | 2/10 | 0/5 | 4/5 | 2/5 | -| dynamic_multi_noise | 5/5 | 1/5 | 2/5 | 2/10 | 0/5 | 3/5 | 0/5 | -| blind_multi_0 | 5/5 | 2/5 | 1/5 | 9/10 | 1/5 | 4/5 | 4/5 | -| blind_multi_1 | 5/5 | 2/5 | 1/5 | 3/10 | 0/5 | 0/5 | 2/5 | -| blind_multi_2 | 1/5 | 0/5 | 5/5 | 0/10 | 5/5 | 5/5 | 4/5 | -| blind_multi_3 | 1/5 | 1/5 | 0/5 | 7/10 | 0/5 | 0/5 | 2/5 | -| **aggregate collisions** | **20/30** | **6/30** | **10/30** | **23/60** | **6/30** | **16/30** | **14/30** | -| **aggregate success** | 30/30 | 28/30 | 30/30 | 59/60 | 30/30 | 29/30 | 29/30 | -| **median margin [m]** | -0.118 | **+0.190** | +0.080 | +0.048 | +0.125 | -0.013 | +0.024 | -| **runs within 0.15 m of contact** | 12/30 | **5/30** | 14/30 | 36/60 | 17/30 | 24/30 | 24/30 | +Because these cells are deliberately marginal, the collision count alone overstates its own precision. The median closest approach is the steadier statistic: -**Read the margin rows, not the collision counts.** These cells are deliberately marginal: 40-80 % of all runs finish within 0.15 m of contact, so a few centimetres of scheduling jitter flips a near-miss into a collision. Re-running a single cell three times with the same binary produced 1/5, 5/5 and 2/5 collisions - a swing wider than the gap between most controllers in the table. The median closest approach is stable across those same runs and is the discriminator this section rests on. +| Controller | median closest approach [m] | runs within 0.15 m of the threshold | +| --- | --- | --- | +| **ProxMPC (predictive)** | **+0.151** | 15/30 (50 %) | +| RPP | +0.113 | 21/30 (70 %) | +| MPPI | +0.063 | 46/60 (77 %) | +| DWB | +0.057 | 20/30 (67 %) | +| Vector Pursuit | +0.020 | 24/30 (80 %) | +| Graceful | +0.000 | 28/30 (93 %) | +| ProxMPC (reactive) | -0.023 | 28/30 (93 %) | + +Predictive ProxMPC leads on both measures and spends the least time near the threshold of any controller in the field. Reactive ProxMPC has a *negative* median - the typical run ends overlapping - and it and Graceful sit within 0.15 m of contact on 93 % of runs. -By margin the ordering is unambiguous: **predictive ProxMPC leads the field at +0.190 m**, ahead of RPP (+0.125), DWB (+0.080), MPPI (+0.048), Vector Pursuit (+0.024) and Graceful (-0.013), and it is the only controller with fewer than 12 of its runs inside the marginal band (5/30). **Reactive ProxMPC is the field's narrowest at -0.118 m**: without the tracker it habitually runs closer to two simultaneous movers than any peer, which is why prediction is not optional in that environment. +**Why the reactive preset is in that lower group, and why it got worse.** +The costmap-only fill scans a single present-time costmap around every predicted node, so a moving obstacle is constrained where it currently is rather than where it will be - an error of `v_obs * t_node`, up to a metre at the far end of a 2 s horizon. With one mover the free corridor absorbs the resulting late reaction (Section 6.2, 0/15). With two, that corridor closes. -Prediction is therefore a large effect here, not a marginal one - it moves ProxMPC from the field's narrowest margin to its widest, and from 20/30 collisions to 6/30. +The reactive rate is 53 % here against 37 % for the same preset in the previous campaign, and the cause is a deliberate change rather than a regression in the avoidance logic. Previously `allow_reversing: false` filtered only which plan pose the reference tracked; the solver's control box still admitted reverse, so the robot could back out of a closing gap. That was a defect - the parameter did not do what it said - and fixing it removed an escape the costmap-only path was relying on. Measured separately during that work, restoring reverse and changing nothing else recovered the rate to 11/30 and lifted the mean margin from -0.005 m to +0.142 m, with path length on `blind_multi_1` rising from 5.2 m to 7.0 m: the robot reversing and re-approaching, not detouring. -The one cell where ProxMPC is the field's weakest is `blind_multi_0`, the tightest simultaneous-mover geometry: reactive ProxMPC 5/5 against 1/5 for DWB and RPP, with prediction more than halving it to 2/5. Two close movers force a non-convex "which side of each obstacle" choice that the linearised keep-out constraint cannot represent, and prediction does not resolve it. No controller is collision-free across the blind cells, and the winner is cell-dependent - RPP clears four cells outright but collides 5/5 on `blind_multi_2`; DWB clears `blind_multi_3` but collides 5/5 on `blind_multi_2`. +The reactive preset's shipped default stays forward-only, because a library cannot check whether an integrator's platform senses the reverse direction. `allow_reversing: true` with an explicit `model_params.v_min` is supported and measurably better on this path; **the predictive preset now enables it by default**, because the obstacle-aware speed cap it also ships needs somewhere to go - a robot that must slow for a mover but cannot back off can be boxed in by a second one (Section 2.1). The bundled Gazebo demo enables it for the same reason: the waffle's 360-degree scanner covers the rear and Nav2's Collision Monitor, already in the demo's `cmd_vel` chain, projects the footprint along the commanded twist including reverse. -The per-cell breakdown for every controller is in [`prox_mpc_benchmark/README.md`](../prox_mpc_benchmark/README.md) and the raw `results/`. -In summary: ProxMPC keeps the largest static margin (Section 6.1), clears the single movers reactively and outperforms DWB on the orbit (Section 6.2), leads its sampling peer and matches or leads every other controller on the multi-mover set at a fraction of the sampling controllers' compute (Section 4), with one hard cell (`blind_multi_0`) where the convex keep-out is the field's weakest. +**What this section does not claim.** `blind_multi_2` is 5/5 for four of the seven controllers and 0/5 for predictive ProxMPC and 0/10 for MPPI; `blind_multi_0` is 5/5 for Vector Pursuit, 4/5 for reactive ProxMPC and 1/5 for three others. Individual cells swing hard, and the same stock peer binaries moved by up to 8 points between this campaign and the last on code that did not change. The totals over 30 runs are the comparison; the per-cell columns are shown for completeness, not for ranking. In particular, the gap between RPP at 6/30 and DWB at 10/30 is not resolved by this sample, while the gap between predictive ProxMPC at 3/30 and the rest of the field is larger than that noise band. ## 7. Real-stack validation (Gazebo) To confirm the plugin behaves under the full production stack and not only against a kinematic plant, ProxMPC also runs in mode (a): Gazebo Harmonic physics, a TurtleBot3 waffle, AMCL localization, costmaps, and the complete Nav2 velocity chain, headless. -It reaches the goal (`SUCCEEDED`), tracks the path to **5.6 mm cross-track RMS**, and taps its diagnostics through the real `controller_server` (p95 solve 0.438 ms, 0 % deadline-miss, 0 % infeasible) - the same profile measured on the plant, with real sensor and physics noise. +The cell is the demo's open-room traverse - spawn `(-2.0, -0.5)`, goal `(2.0, -0.5)`, about 4 m - driven by the shipped [`nav2_prox_mpc.yaml`](../prox_mpc_demo/config/nav2_prox_mpc.yaml) with only `publish_diagnostics` turned on, which is opt-in telemetry that publishes when subscribed and does not touch control. + +| Measure | Mode (a), 5 runs | Mode (b2) open cell, same controller | +| --- | --- | --- | +| Goal reached | **5/5**, 0 recoveries | 5/5 | +| Cross-track RMS | **5.76 ± 1.23 mm** | 0.1 mm | +| Cross-track max | 16.7 ± 4.5 mm | - | +| Solve p50 | 0.364 ± 0.036 ms | 0.189 ± 0.016 ms | +| Solve p95 | 1.382 ± 0.199 ms | 0.910 ± 0.082 ms | +| Solve max (worst run) | 11.85 ms | 3.63 ms | +| Cycles over the 50 ms budget | **0** | 0 | +| Deadline-miss / infeasible | **0 % / 0 %** | 0 % / 0 % | +| Mean SQP iterations | 1.00 | 1.00 | +| QP status histogram | **966/966 `PROXQP_SOLVED`** | - | + +Three things this establishes. The **real-time iteration holds under real physics**: mean SQP iterations is exactly 1.00 across 966 control cycles, and not one exceeded the 50 ms budget. **Tracking survives real sensing**: 5.8 mm RMS against AMCL localization and a simulated lidar, where the kinematic plant tracks to a tenth of a millimetre against ground truth - the gap is what localization and physics cost, not controller error. And the **`PROXQP_PRIMAL_INFEASIBLE` reports discussed in Section 5 do not appear here at all**: every one of the 966 cycles returned `PROXQP_SOLVED`. + +Per-cycle compute is about 1.9x the mode-(b2) median for the same controller, and 1.5x at p95. That is expected rather than a regression: mode (a) runs Gazebo physics, the sensor pipeline and AMCL on the same host as the controller, while mode (b2) drives a kinematic plant. The absolute numbers stay far inside budget either way. + +> **Not a controlled comparison with the `v1.0.0` figures this section used to carry** (5.6 mm RMS, 0.438 ms p95). Those were measured on a different controller configuration - `max_iter_sqp: 100`, `w_weight: 100`, `safety_margin: 0.1`, no reverse travel - as well as different code, two months earlier on a thermally variable laptop. The tracking figure is unchanged within its spread; the solve-time difference is **not attributed** here, because nothing in these two runs isolates a cause. + +Mode (a) remains a single open-cell gate on one machine: it answers "does the plugin behave under the production stack", not "how does it compare", which is what modes (b1) and (b2) are for. The `2.0.0` reverse-travel and obstacle-yield behaviour was measured in Gazebo separately, and those runs are reported in [`prox_mpc_demo/doc/nav2-simulation.md`](../prox_mpc_demo/doc/nav2-simulation.md). ## 8. Threats to validity -- **The obstacle-routed global plan does much of the single-obstacle avoidance** (Section 6). The shared global `obstacle_layer` makes NavFn route around obstacles for every controller - deliberately equal, but it favours the geometric path-followers (RPP, Graceful, Vector Pursuit) and DWB, which track the global detour closely. The single-obstacle cells therefore separate the field on margin and on the orbiting case, not on collision counts; the multi-mover cells (Section 6.4) carry the collision comparison. -- **The multi-obstacle field is close and the sample is small** (Section 6.4). The leading controllers (predictive ProxMPC and RPP at 6/30 collisions, DWB at 10/30) sit within run-to-run noise at 5 repeats per cell; the trustworthy signals are the class comparisons - predictive ProxMPC leads MPPI, Graceful and Vector Pursuit, and matches DWB and RPP - and that `blind_multi_0` is hard for the whole field. The 6-vs-6-vs-10 collision ordering among the leaders is not a reliable ranking, which is why Section 6.4 rests on the median margin, and multi-obstacle difficulty scales with obstacle size. -- **`blind_multi_0` is a genuine ProxMPC limit** (Section 6.4). On the tightest two-mover cell ProxMPC and its predictive variant are the field's weakest, consistent with the convex keep-out being unable to represent the non-convex per-obstacle side-choice; prediction does not fix it. This is an architectural limit of the linearised keep-out, isolated to the tightest cell. -- **Collision uses a strict min-gap** - any instant of disc overlap over the whole run counts as a collision, so a brief graze is flagged the same as a harder hit; the reported min gap distinguishes the two. -- **Achieved command rate is completion-coupled** (Section 4). ProxMPC's ~15-20 Hz sampled rate on the multi cells reflects occasional stalls (a stopped robot stops being commanded) rather than routine deadline misses - only 4 runs of 435 report a non-zero deadline-miss rate, the worst 0.56 % - though the rare worst-case cycle does overrun the budget (Section 5). -- **Resources are measured on the x86 host** above, and process CPU/RAM is per-process (includes the shared costmap); the per-cycle compute (Section 4) is the cleaner controller-only measure, and the ranking is what transfers. The pure-geometric controllers are genuinely lighter than ProxMPC - ProxMPC is the cheapest of the controllers that solve a constrained optimisation each cycle, not the cheapest outright. -- **MPPI is stochastic with no exposed seed** (Nav2 Jazzy), so its per-scenario variance is real; it runs 10 repeats per obstacle cell (5 on the open cell) to better characterise that variance, but this does not pin it down exactly. -- **Determinism vs. physics.** Modes (b1)/(b2) are deterministic plants, so their near-zero geometric std is reproducibility, not a noise estimate; mode (a) carries real Gazebo variance, and `dynamic_multi_noise` adds a Gaussian range-noise model on the scan. +- **Every row comes from one campaign on one machine state** (see Provenance), which removes the cross-session caveat the previous publication carried. What it does not remove is run-to-run variance: see the two bullets below. +- **These collision rates are more sensitive to the keep-out than to the algorithm.** Over this work the predictive all-cells rate moved 6 % -> 10 % -> 6 % on a 15 mm change to `d_safe`, with no algorithmic change at all. Any comparison between controllers separated by less than that is not resolved by this campaign. +- **Peer controllers moved between campaigns on code that did not change.** Re-running the identical stock binaries moved MPPI's all-cells rate 26 % -> 18 %, Graceful's 40 % -> 36 %, RPP's 20 % -> 16 %, DWB's 26 % -> 30 % and Vector Pursuit's 22 % -> 26 %. That sets the noise floor at about 8 points on 50 runs, which is the scale at which the totals in Section 6.4 should be read - and the scale the predictive preset's 6 % has to clear to mean anything, which it does. +- **Vector Pursuit's static-box result is a stall, not an avoidance measurement.** It reached the goal on 1 of 5 runs here against 3 of 5 previously (Section 6.1). Its margin figures on that cell average a controller that mostly stopped short. +- **The two ProxMPC presets do not isolate prediction, and now differ by more than before.** Both share `d_safe = 0.320 m`, but `costmap_cost_threshold` (200 reactive against 253 predictive), `w_weight`, and - new in this campaign - `allow_reversing`, `obstacle_yield_band_m` and `obstacle_yield_caps_speed` all differ. The reactive-versus-predictive comparisons are configuration-versus-configuration, and the gap between them is now attributable to the yield and reverse defaults at least as much as to prediction. The multi-mover direction is large enough (3/30 against 16/30) that the combination clearly works; which of its parts carries how much is not separated here. The compute comparison in Section 4 stays confounded for the same reason. +- **The obstacle-routed global plan does much of the single-obstacle avoidance.** The shared global `obstacle_layer` makes NavFn route around obstacles for every controller - deliberately equal, but it favours the geometric path-followers and DWB, which track that detour closely. The single-obstacle cells therefore separate the field on margin, not on collision counts; the multi-mover cells carry the collision comparison. +- **The multi-obstacle field is close and the sample is small.** 50-93 % of runs across the six cells finish within 0.15 m of contact, so per-cell counts swing by more than the gap between most controllers. The 30-run totals are the comparison. +- **Collision uses a strict min-gap:** any instant of disc overlap over a whole run counts, so a brief graze scores the same as a harder hit. The reported min gap distinguishes them. +- **Every figure comes from one machine.** The whole document was measured on the x86-64 dev host named in Section 2 and on no other, so the absolute numbers are that host's; what transfers to a different machine is the ranking, not the values. The per-cycle compute in Section 4 is the cleaner controller-only measure, since process CPU/RSS includes the shared costmap. +- **The pure-geometric controllers are genuinely lighter.** ProxMPC is the cheapest of the controllers that solve a constrained optimisation each cycle, not the cheapest outright. +- **MPPI is stochastic with no exposed seed** in Nav2 Jazzy, so its per-scenario variance is real. It runs 10 repeats per obstacle cell against the others' 5, which characterises that variance without pinning it down. +- **Determinism vs. physics.** Modes (b1)/(b2) are deterministic plants, so their near-zero geometric std is reproducibility, not a noise estimate. Mode (a) carries real Gazebo variance, which is why its five runs are reported with a spread (Section 7). `dynamic_multi_noise` adds a Gaussian range-noise model on the scan. +- **Four of 435 matrix cells failed to bring up Nav2 and were discarded and re-run**, detected by the controller never receiving a path rather than by their results (see Provenance). All 435 records in the final set show a real path delivered. Five further runs failed behaviourally and are reported as failures, not re-run. +- **An unexplained solver report remains open.** Reactive ProxMPC emits `PROXQP_PRIMAL_INFEASIBLE` on 9 of 50 runs against none in the `v1.0.0`-era campaign, on a QP whose feasible set is provably non-empty (Section 5). Three candidate causes were tested and eliminated. It has no measured consequence, but it is not understood. +- **`blind_multi_0` is the predictive preset's one remaining weak cell** (3/5, against 0/5 on the other five multi cells). It is not diagnosed here. ## 9. Conclusion on ProxMPC -On a like-for-like, fairly-tuned suite ProxMPC matches the best stock Nav2 controller on tracking, runs markedly lighter per cycle than the optimisation- and sampling-based controllers, holds the largest static-obstacle margin, and leads or matches every controller on moving obstacles: +On a like-for-like, fairly-tuned suite recorded as a single campaign, **predictive ProxMPC is the most reliable obstacle avoider in the field** - 3 collisions in 50 obstacle runs (6 %) against 8 for the next best (RPP, 16 %) - while computing its command 3-10x faster than the two controllers in its own cost class. Its worst-case cycle is bounded well inside the real-time budget, which was not true of the previous release. + +- **Real-time behaviour:** **zero cycles above the 50 ms budget across 100 runs**, both presets, with worst observed cycles of 33.5 ms (reactive) and 31.1 ms (predictive). The previous release measured 300 ms worst cases on three separate cells. Two defects caused that and both are fixed: an SQP loop that re-linearised up to 99 times around a corrupted iterate after a failed solve, and a QP workspace rebuilt from scratch every cycle instead of warm-started. +- **Per-cycle compute:** 0.30 ms median on the open cell - **9.9x lighter than DWB and 10.4x than MPPI** - narrowing to ~2.5-3x on single-obstacle cells and ~1.3x on the hardest multi-mover cells, because ProxMPC's cost scales with obstacle load while theirs does not. It never inverts. Process CPU is 8.5 % reactive and 7.5 % predictive across all obstacle cells against DWB's 9.4 % and MPPI's 9.3 %; peak RSS 59/60 MB against 60 and 63. The predictive preset's tracker adds 0.96 % of a core and 38.3 MB in its own process. The three geometric pursuit controllers remain an order of magnitude cheaper and collide 16-36 % of the time. +- **Tracking:** 0.0001 m cross-track RMS on the open cell, 5/5, indistinguishable from the field. An empty straight line does not separate these controllers. +- **Static obstacle:** reactive ProxMPC keeps **the largest margin in the field, +0.382 m at its closest**, against RPP's +0.211 and DWB's +0.069, and pays for it with the largest detour (0.737 m cross-track). That is the in-loop keep-out behaving as specified - `d_safe` is planned around, not traded away. +- **Single moving obstacles:** both ProxMPC presets, MPPI and Vector Pursuit clear all three cells collision-free, and **the predictive preset now holds the field's largest worst-case margin at +0.212 m** while cutting its detour to 0.376 m cross-track - it yields by slowing rather than swerving. DWB and Graceful collide 5/15 each. +- **Simultaneous two-mover cells - where the field separates:** predictive ProxMPC leads on both measures, at **3/30 collisions** against 6 for the next best, and **+0.151 m median closest approach** against RPP's +0.113, MPPI's +0.063 and a negative median for reactive ProxMPC. It is collision-free on five of the six cells. +- **The costmap-only path is a single-obstacle configuration.** Reactive ProxMPC sits at 16/30 on these cells because the fill constrains each obstacle where it *was*, not where it will be - up to a metre of error at the far end of a 2 s horizon. With one mover the free corridor absorbs that; with two it does not. This is why `predict_obstacles` now defaults to true, and why the reactive preset should be treated as validated for single-obstacle environments only. +- **One controller, many vehicles:** the identical plugin drives a unicycle and a bicycle by configuration alone, confirmed 40/40 in mode b1 (Section 6.3). + +**What this release changed, honestly.** Two things changed, and only one of them is an avoidance result. + +The first is real-time behaviour: the controller can no longer stall for 300 ms mid-manoeuvre, which on a robot moving at 0.5 m/s is 15 cm of open-loop travel at exactly the wrong moment. + +The second is that **the predictive preset's avoidance genuinely improved, and this campaign is the first to measure it against a re-run field.** Its all-cells collision rate went 16 % -> 6 % and its multi-mover rate 30 % -> 10 %, while its worst-case single-mover margin went +0.064 m -> +0.212 m. Peer binaries that did not change moved by up to 8 points over the same interval, so the peer noise floor is about 8 points on 50 runs; the predictive preset's 10-point all-cells move sits outside it, its 20-point multi-mover move well outside it, and the margin improvement is not a count statistic at all. The cause is identified and was measured in isolation (Section 6.2): the previous yield only lowered a cruise *target* that the keep-out term outweighed, so the controller had a correct prediction and no way to act on it; capping the solver's forward speed *bound* is what converted the prediction into behaviour. -- **Per-cycle compute and process resources (measured, all eleven cells):** ProxMPC computes a command in **0.75 ms median / 1.15 ms p95** on the open cell - **~3.3x lighter than DWB and ~3.5x than MPPI** - and stays **1.1-2.7x lighter at the median on every obstacle cell**, though the advantage narrows to ~1.1-1.7x on the six-way-constrained multi cells. Process CPU is 5.0-9.1 % against their 8.4-9.3 %, and the QP solve is confirmed by independent telemetry to be almost the entire cost. Deadline misses are essentially absent (4 runs of 435 non-zero, worst 0.56 %). The tail is the weak point: p95 reaches 5.7-7.0 ms on the hard cells against the samplers' steadier 3.0-3.7 ms, and **5 runs of 427 recorded one cycle above the 50 ms budget, peaking at 321 ms** - a direct consequence of rebuilding the QP factorization every cycle. The geometric controllers (RPP, Graceful, Vector Pursuit) are lighter still, carrying no model, constraints, or horizon optimisation; against them ProxMPC's premium is ~1-5 % of one core. -- **Tracking:** sub-millimetre (0.0004 m RMS), on par with the field, 100 % success. -- **Static-obstacle avoidance:** **ProxMPC keeps the largest real margin, +0.35 m** - ahead of its cost-class peers MPPI (+0.21 m) and DWB (+0.09 m), and of the geometric RPP and Graceful (~+0.21 m). Vector Pursuit is stopped short by its own forward-collision check. -- **Single moving obstacles:** cleared reactively by almost the whole field; ProxMPC clears the orbiting obstacle that its cost-class peer DWB (5/5) and Graceful (4/5) collide on. Ground-truth prediction (mode b1) solves all three single moving-obstacle cases 30/30 for both a unicycle and a bicycle. -- **Multiple simultaneous moving obstacles:** measured by median closest approach - the stable statistic, since the collision *count* on these deliberately marginal cells swings by more than the gap between controllers - **predictive ProxMPC leads the entire field at +0.190 m**, ahead of RPP (+0.125), DWB (+0.080), MPPI (+0.048), Vector Pursuit (+0.024) and Graceful (-0.013), with only 5 of 30 runs inside the 0.15 m marginal band against 14-24 for the others. **Reactive ProxMPC is the field's narrowest at -0.118 m**, so the tracker is not optional in a two-mover environment. The one cell where ProxMPC remains weakest is `blind_multi_0`, where the convex keep-out cannot make the non-convex two-mover side-choice. -- **One controller, many vehicles:** the identical plugin drives a unicycle and a bicycle by configuration alone. +The reactive preset moved the other way, 37 % -> 53 % on the multi-mover cells. Part of that is the deliberate reverse fix (Section 6.4) and part is within the 8-point noise band applied twice; it is reported as measured, and it is the reason the reactive preset is documented as a single-obstacle configuration. -Against DWB and MPPI - its per-cycle-cost peers - ProxMPC is roughly four times lighter per cycle at equal tracking accuracy, holds a larger static margin, clears the orbit DWB misses, and leads MPPI on multiple movers. Against the geometric pursuit controllers it holds larger avoidance margins for a small CPU premium. Its one weak point is the tightest two-mover cell, where it fails by stalling rather than driving through. +**What remains open:** every figure comes from the single x86-64 host in Section 2, Gazebo validation is a single open-cell gate rather than a comparison, the reactive infeasibility report in Section 5 is unexplained, and `blind_multi_0` remains the predictive preset's one weak cell at 3/5. None of these affect the comparisons above; all four bound what can be claimed beyond them. --- diff --git a/doc/media/prox_mpc_demo_grid.gif b/doc/media/prox_mpc_demo_grid.gif index 43af781..2f3b6cd 100644 Binary files a/doc/media/prox_mpc_demo_grid.gif and b/doc/media/prox_mpc_demo_grid.gif differ diff --git a/doc/media/prox_mpc_demo_grid.mp4 b/doc/media/prox_mpc_demo_grid.mp4 index d686060..a293ba6 100644 Binary files a/doc/media/prox_mpc_demo_grid.mp4 and b/doc/media/prox_mpc_demo_grid.mp4 differ diff --git a/doc/prox-mpc.md b/doc/prox-mpc.md index 5ae04e3..2031ac2 100644 --- a/doc/prox-mpc.md +++ b/doc/prox-mpc.md @@ -33,7 +33,8 @@ The dynamics of a real vehicle are nonlinear, so the optimal-control problem is ProxMPC solves it with **Sequential Quadratic Programming (SQP)**: it linearises the dynamics around the current guess, assembles a **Quadratic Program (QP)**, and solves that QP with the [ProxQP](https://github.com/Simple-Robotics/proxsuite) solver, re-linearising and retrying only while the sub-problem fails to converge. In the nominal case that is one linearise-solve-update pass per control cycle, with the linearisation refined across cycles through the trajectory warm start ([nmpc.md](../prox_mpc_core/doc/nmpc.md)). A useful consequence falls out for free: if the model is already linear, the first QP is exact and the SQP converges in a single solve. -Safety is split into two layers that recur throughout the stack: a **fast, convex** keep-out constraint lives *inside* the optimisation so the solver shapes a trajectory that avoids obstacles, and an **exact, conservative** check sits *outside* it as a veto, so a command that would actually collide is never issued. +Safety is split into two layers that recur throughout the stack: a **fast, convex** keep-out constraint lives *inside* the optimisation so the solver shapes a trajectory that avoids obstacles, and an **outline-only footprint veto** sits *outside* it as a backstop on the single pose the solver predicts one step ahead. +The veto rasterises only the footprint perimeter and reports the maximum edge cost, with no interior fill and no sweep between the current and the next commanded pose, so it is a backstop rather than a guarantee: it earns its keep only when costmap inflation is sized to the robot's real footprint and the local costmap's unknown-space tracking matches the deployment ([Section 4](#4-prox_mpc_controller---the-nav2-plugin)). The full derivation - cost function, the Euler linearisation, the KKT/QP assembly, convergence, and the obstacle constraints - is in the engine's own docs: @@ -51,11 +52,11 @@ Three classes in the `prox_mpc` namespace do the work: - `prox_mpc::Model` - the vehicle interface. A model supplies the Euler linearisation (`updateA`, `updateB`, `updatec`) and, optionally, `configure(params)` (set constants by name) and `toTwist(u)` (map a control vector to a `geometry_msgs/msg/Twist`). - `Model` is a `pluginlib` base type; the bundled `prox_mpc_core/Bicycle` (4-state, with a steering angle) and `prox_mpc_core/Unicycle` (3-state) are registered against it. + `Model` is a `pluginlib` base type; the bundled `prox_mpc_core/BicycleFrontAxle` and `prox_mpc_core/BicycleRearAxle` (4-state, with a steering angle) and `prox_mpc_core/Unicycle` (3-state) are registered against it, along with `prox_mpc_core/Bicycle` as a deprecated alias for the front-axle model. - `prox_mpc::ProxQP` - assembles the QP for one linearisation and solves it with ProxQP. - `prox_mpc::MPC` - the SQP driver: it holds the horizons, weights, and obstacle capacity, runs the SQP loop, and exposes the solution plus the solver telemetry (`qp_info`, `sqp_iter`, `qp_iter_ext`, and the peak obstacle slack). -Because the model is loaded *by name*, adding a vehicle needs no change to the engine or its consumers - that is the extension seam the whole workspace is organised around. +Because the model is loaded *by name*, adding a vehicle needs no change to the engine or its consumers - that is the extension seam the whole workspace is organised around. That holds with obstacle avoidance on as well: the obstacle-constraint assembly reads the planar position's state indices from the model's declared mapping rather than assuming a layout. **How to use it.** Construct an `MPC`, set the horizons/weights/obstacle capacity, `init()` it with a `Model`, then each cycle set the reference, pose, and obstacles and call `solve()`. @@ -94,9 +95,9 @@ Each `computeVelocityCommands` cycle the plugin: 1. transforms the global plan into the costmap global frame and samples a state/control reference along it by arc length (continuous, unwrapped heading; a curvature-aware steering reference for the bicycle; goal-approach easing); 2. reduces the local costmap to the engine's obstacle triples - a clustered, windowed scan for occupied cells - and, when predictive avoidance is on, propagates tracked dynamic obstacles over the horizon and binds each to a constraint slot (hybrid fill); 3. solves one SQP cycle, times it, and (opt-in) publishes a `SolverDiagnostics`; -4. gates the result: a non-converged or non-finite solve, or a command that fails the **exact polygon-footprint veto**, decelerates from the measured velocity at the model's limit and escalates to a Nav2 recovery after `max_solver_failures` consecutive faults (the veto counting on its own budget). +4. gates the result: a non-converged or non-finite solve, or a command that fails the **outline-only footprint veto**, decelerates from the measured velocity at the model's limit and escalates to a Nav2 recovery after `max_solver_failures` consecutive faults (the veto counting on its own budget). -This is the two-layer safety split in practice: the in-loop disc constraint shapes the trajectory; the footprint veto is the conservative backstop. +This is the two-layer safety split in practice: the in-loop disc constraint shapes the trajectory; the footprint veto is an outline-only backstop, not a guarantee. **How to use it.** Point `controller_server`'s `FollowPath` at the plugin and load its parameters; the bundled config is the single source of truth. @@ -107,7 +108,7 @@ controller_server: controller_plugins: ["FollowPath"] FollowPath: plugin: "prox_mpc_controller::ProxMpcController" - model_plugin: "prox_mpc_core/Unicycle" # or prox_mpc_core/Bicycle + model_plugin: "prox_mpc_core/Unicycle" # or prox_mpc_core/BicycleFrontAxle / BicycleRearAxle # horizons, weights, solver limits, obstacle settings: # see config/prox_mpc_controller.yaml and doc/architecture.md ``` @@ -186,7 +187,7 @@ The scenario-driven harness that *measures* the stack across three metric classe A controller-agnostic C++ live metrics node measures pose-based accuracy (cross-track against the scenario reference polyline, goal error, time-to-goal, path length) from generic signals (TF pose) and taps the `SolverDiagnostics` stream for the real-time/feasibility class, writing one per-run JSON. Installed Python tooling orchestrates the matrix, generates scaled maps, sends goals, and aggregates the per-run JSONs into mean ± std tables. A small C++ **kinematic plant** integrates a controller's body twist as a unicycle and publishes `/odom` + TF, so the stock Nav2 controllers and ProxMPC can be compared on the identical plant without Gazebo (mode b2). -On that comparison a **resource sampler** records the `controller_server` process's CPU and memory (from `/proc`) and the achieved control rate, and a **`nav2_core::Controller` timing decorator** wraps whichever controller is under test and wall-clock times its `computeVelocityCommands` identically, so the cross-controller comparison covers the embedded cost (per-cycle compute, CPU, RAM, frequency) at a fairly-matched operating point, not only tracking - see the [comparison results](controller-comparison-results.md#4-per-cycle-compute-cost-and-process-resources). +On that comparison a **resource sampler** records the `controller_server` process's CPU and memory (from `/proc`) and the achieved control rate, and a **`nav2_core::Controller` timing decorator** wraps whichever controller is under test and wall-clock times its `computeVelocityCommands` identically, so the cross-controller comparison covers the runtime cost (per-cycle compute, CPU, RAM, frequency) at a fairly-matched operating point, not only tracking - see the [comparison results](controller-comparison-results.md#4-per-cycle-compute-cost-and-process-resources). **How to use it.** @@ -218,10 +219,10 @@ The [architecture overview](architecture.md) draws the runtime data flow for eac ## 10. Extending ProxMPC: add a vehicle model -The `prox_mpc::Model` interface is the one seam you extend to support a new vehicle, and it ripples nowhere else: +The `prox_mpc::Model` interface is the one seam you extend to support a new vehicle: -1. Derive from `prox_mpc::Model` and implement `updateA`/`updateB`/`updatec` (the Euler linearisation), plus `configure(params)` and `toTwist(u)`. -2. Register it as a `pluginlib` plugin against the `prox_mpc::Model` base (as `prox_mpc_core` does for `Bicycle`/`Unicycle` and `prox_mpc_test_models` does for its fixture). +1. Derive from `prox_mpc::Model` and implement `updateA`/`updateB`/`updatec` (the Euler linearisation), plus `configure(params)` and `toTwist(u)`. A model whose state is not ordered `[x, y, yaw, ...]` overrides `getPlanarMapping()` to say where each planar quantity sits; the engine's obstacle-constraint assembly indexes through that declaration, so obstacle avoidance works for any ordering. +2. Register it as a `pluginlib` plugin against the `prox_mpc::Model` base (as `prox_mpc_core` does for `BicycleFrontAxle`/`BicycleRearAxle`/`Unicycle` and `prox_mpc_test_models` does for its fixture). 3. Select it by name (`model_plugin`) in the controller or the demo - no consumer code changes. The model interface details are in [`prox_mpc_core/README.md`](../prox_mpc_core/README.md) and [`prox_mpc_core/doc/architecture.md`](../prox_mpc_core/doc/architecture.md); `prox_mpc_test_models` is a minimal worked example of a third-party model registered against the core base. @@ -231,7 +232,7 @@ The model interface details are in [`prox_mpc_core/README.md`](../prox_mpc_core/ These hold across the workspace and are documented once in the [architecture overview](architecture.md#cross-cutting-conventions): - **Frames** - REP-103 conventions; the tracker estimates velocity in a fixed, non-rotating frame and the controller transforms plans and obstacles into the costmap global frame via `tf2`. -- **Safety split** - a fast convex disc constraint inside the optimisation, plus an exact polygon-footprint veto and a limit-respecting deceleration outside it. +- **Safety split** - a fast convex disc constraint inside the optimisation, plus an outline-only, single-endpoint footprint veto and a limit-respecting deceleration outside it. - **Types** - all MPC quantities are `double`; ROS parameters are `double` / `int` / `bool` / `string` only. - **Build** - `Release` (`-O3 -DNDEBUG`) by default behind an `if(NOT CMAKE_BUILD_TYPE)` guard; never `-Ofast` / `-ffast-math` for the solver (it breaks the IEEE-754 semantics the convergence and finiteness guards rely on); per-board CPU tuning stays out of the source. - **License** - Apache-2.0 across the workspace, with a short `SPDX-License-Identifier` header per file and the full text in `LICENSE`. diff --git a/prox_mpc_benchmark/CHANGELOG.rst b/prox_mpc_benchmark/CHANGELOG.rst index e5327a5..f2bd51b 100644 --- a/prox_mpc_benchmark/CHANGELOG.rst +++ b/prox_mpc_benchmark/CHANGELOG.rst @@ -2,6 +2,23 @@ Changelog for package prox_mpc_benchmark ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2.0.0 (2026-09-13) +------------------ +* ``record_scenarios.py`` cuts each clip to open as the robot first moves, + read from ``/odom`` at the same 1 mm threshold that releases the scenario's + obstacles, instead of starting a fixed clip before the goal is sent. The + goal delay and the stack's start-up latency are no longer dead time in the + clip, and a retried goal no longer shortens it. A scenario may set its own + clip length with ``video.duration_s``; ``dynamic_circle`` sets 25 s so the + orbit is seen through to the goal. +* The mode-(b2) run index is rebuilt from the records on disk, so a re-run of a + subset no longer leaves stale rows from a previous campaign in the index. +* Per-run metrics record the QP status histogram and the SQP / QP external + iteration maxima. +* Scenario definitions and the ProxMPC presets follow the controller's changed + defaults. +* Contributors: Simone Contorno + 1.0.0 (2026-07-28) ------------------ * Initial release: scenario-driven benchmarking harness with the standalone diff --git a/prox_mpc_benchmark/CMakeLists.txt b/prox_mpc_benchmark/CMakeLists.txt index 031765f..1ad969b 100644 --- a/prox_mpc_benchmark/CMakeLists.txt +++ b/prox_mpc_benchmark/CMakeLists.txt @@ -10,8 +10,20 @@ if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE "Release") endif() -if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang") - add_compile_options(-Wall -Wextra -Wpedantic) +# Compiler warnings, matching upstream Nav2's package-level policy +# (nav2_common/cmake/nav2_package.cmake) so this package is held to the same +# bar as every other Nav2 plugin it ships alongside. +if(CMAKE_CXX_COMPILER_ID MATCHES "GNU" OR CMAKE_CXX_COMPILER_ID MATCHES "Clang") + add_compile_options(-Wall -Wextra -Wpedantic -Werror -Wdeprecated -fPIC -Wshadow -Wnull-dereference) + # GCC 13 raises -Wnull-dereference inside libstdc++'s own headers + # (stl_algobase.h, reached through regex_traits::transform_primary) once + # --coverage changes its inlining decisions, which is how the coverage build + # hits it and an ordinary build does not. The report is attributed to the + # translation unit that instantiates the template, so -Wno-system-headers + # does not reach it. Keep the diagnostic, but do not let a false positive in + # the standard library fail the build. + add_compile_options(-Wno-error=null-dereference) + add_compile_options("$<$:-Wnon-virtual-dtor>") endif() # Packages @@ -160,6 +172,9 @@ if(BUILD_TESTING) target_include_directories(test_obstacle_field PRIVATE $ ) + + find_package(ament_cmake_pytest REQUIRED) + ament_add_pytest_test(test_record_scenarios test/test_record_scenarios.py) endif() ament_package() diff --git a/prox_mpc_benchmark/README.md b/prox_mpc_benchmark/README.md index 0f42a67..4120936 100644 --- a/prox_mpc_benchmark/README.md +++ b/prox_mpc_benchmark/README.md @@ -173,7 +173,7 @@ narrative and the conclusion on ProxMPC are in - **Standalone goal-stop.** The b1 sim holds at its final goal (a waypoint follower stops rather than driving through), so `goal_error_m` reflects the stopping accuracy; the solver keeps running so telemetry still flows. -- **Embedded-resource metrics (mode b2).** `resource_sampler.py` reads the +- **Process-resource metrics (mode b2).** `resource_sampler.py` reads the `controller_server` process's CPU (% of one core) and RSS from `/proc`, the achieved `/cmd_vel` rate, and - via the timing decorator - each controller's per-cycle `computeVelocityCommands` time, so the cross-controller comparison @@ -195,20 +195,40 @@ narrative and the conclusion on ProxMPC are in `regulated_pure_pursuit`/`graceful` kept genuine wins, `dwb`/`mppi` reverted to stock obstacle costs after harder settings only regressed them. MPPI (the one unseeded stochastic controller) runs n=10 per obstacle cell; the rest n=5. -- **Result summary (matched 0.5 m/s cap).** At a matched speed cap ProxMPC holds - the largest static-obstacle margin of the field (+0.352 m) and clears the single - crossing and orbiting obstacles reactively. On the six simultaneous two-mover - cells the discriminator is the **median closest approach**, not the collision - count: those cells are deliberately marginal, 40-80 % of runs finish within - 0.15 m of the threshold, and the same cell returned 1/5, 5/5, and 2/5 collisions - on three runs of the same binary. By margin, predictive ProxMPC leads the field - at **+0.190 m** (RPP +0.125, DWB +0.080, MPPI +0.048, Vector Pursuit +0.024, - Graceful -0.013), while reactive ProxMPC is the narrowest at -0.118 m. Its - weakest cell is `blind_multi_0`, the tightest two-mover geometry, where the - linearised keep-out cannot make the non-convex per-obstacle side-choice. - Per-cycle it computes ~3.3x lighter than DWB and ~3.5x than MPPI on the open - cell and 1.1-2.7x lighter across the obstacle cells, the margin narrowing as the - field tightens, at 5.0-9.1 % CPU against their 8.4-9.3 %. +- **Result summary** (matched 0.5 m/s cap, `d_safe = 0.320 m`; one 435-run + campaign on 2026-09-12, all seven controllers recorded back-to-back). + Reactive ProxMPC holds the largest static-obstacle margin in the field + (+0.382 m against RPP's +0.211 and MPPI's +0.204), and the **predictive** + preset now holds the largest worst-case margin on the three single moving- + obstacle cells (+0.212 m against reactive's +0.186 and MPPI's +0.136), all + three cleared collision-free by both presets. + On the six simultaneous two-mover cells the honest discriminator is the + **median closest approach** rather than the collision count: those cells are + deliberately marginal, and 50-93 % of runs finish within 0.15 m of the + threshold, so a few centimetres of jitter flips a near-miss either way. + By that measure predictive ProxMPC leads at **+0.151 m** (RPP +0.113, + MPPI +0.063, DWB +0.057, Vector Pursuit +0.020, Graceful +0.000, reactive + ProxMPC -0.023), and it is also the fewest-collision controller on those cells + at 3/30 against 6/30 for the next best, clearing five of the six outright. + Reactive ProxMPC's weakest cells are `blind_multi_2` and `blind_multi_3` (5/5 + collisions each): the linearised keep-out cannot make the non-convex + per-obstacle side-choice, and the costmap-only fill constrains each obstacle + where it *was* rather than where it will be - an error of `v_obs * t_node`, up + to a metre at the far end of a 2 s horizon. That is the limitation prediction + exists to remove, and it is why `predict_obstacles` now defaults to true. The + predictive preset clears both of those cells 0/5 and has one weak cell left, + `blind_multi_0` at 3/5. +- **Per-cycle compute.** ProxMPC's cost scales with obstacle load while the + sampling controllers' does not, so the ratio narrows as cells get harder: the + reactive preset is **9.9x lighter than DWB and 10.4x than MPPI** on the open + cell (0.30 ms against 2.96 and 3.11), ~2.5-3x lighter on the single-obstacle + cells, and ~1.3x lighter on the multi-mover cells (2.47 ms against 3.16 and + 3.05). Across all obstacle cells it draws 8.5 % CPU (predictive 7.5 %) against + DWB's 9.4 % and MPPI's 9.3 %, at 59 MB peak RSS (predictive 60) against + 60 and 63; the predictive preset's tracker adds 0.96 % of a core and 38.3 MB in + its own process. The three geometric pursuit controllers remain an order of + magnitude cheaper at 0.17-0.23 ms and ~4.0 % CPU, and collide on 16-36 % of + obstacle runs against predictive ProxMPC's 6 %. The full method, per-cell numbers, and conclusion are in [doc/controller-comparison-results.md](../doc/controller-comparison-results.md). @@ -218,8 +238,8 @@ narrative and the conclusion on ProxMPC are in > dev host (Intel Core i7-10750H, 6 cores / 12 threads, 31 GiB RAM, > Ubuntu 24.04.4) - not on physical robot hardware and not contact-dynamics. > A collision is a *would-be* overlap of the robot and obstacle discs, scored -> identically for every controller. Gazebo validation is a single open-cell run; -> full Gazebo and hardware validation remain open. +> identically for every controller. Gazebo validation is five runs of one open +> cell; the full Gazebo matrix and hardware validation remain open. ## Configuration @@ -361,8 +381,9 @@ committed grids + posters are under `doc/media/`. > Simulation results on a kinematic plant, not physical hardware and not > contact-dynamics; a collision is a *would-be* overlap of the robot and obstacle -> discs, scored identically for every controller; Gazebo validation is a single -> open-cell run, with full Gazebo and hardware validation still open. The full +> discs, scored identically for every controller; Gazebo validation is five runs +> of one open cell, with the full Gazebo matrix and hardware validation still +> open. The full > statement is in the [Notes on the metrics](#notes-on-the-metrics) above and in > the [root README](../README.md). @@ -374,104 +395,108 @@ committed grids + posters are under `doc/media/`. | scenario | model | controller | n | success | t_goal[s] | path[m] | goal_err[m] | ct_rms[m] | ct_max[m] | obs_gap[m] | coll | solve_p50[ms] | solve_p95[ms] | solve_max[ms] | miss | sqp | qp_ext | infeas | slack[m] | rate[Hz] | cpu[%] | rss[MB] | cmp_p50[ms] | cmp_p95[ms] | |---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| -| dynamic_circle | bicycle | proxmpc | 5 | 100% | 4.52±0.16 | 4.84±0.03 | 0.143±0.000 | 0.021±0.000 | 0.044±0.000 | n/a | n/a | 4.663±0.219 | 8.705±0.820 | 9.549±1.037 | 0.0±0.0% | 1.00±0.00 | 9.40±0.02 | 0.0±0.0% | 0.000±0.000 | n/a | n/a | n/a | n/a | n/a | -| dynamic_circle | unicycle | proxmpc | 5 | 100% | 4.57±0.06 | 4.85±0.00 | 0.140±0.000 | 0.005±0.000 | 0.011±0.000 | n/a | n/a | 3.343±0.047 | 5.874±0.079 | 6.583±0.483 | 0.0±0.0% | 1.00±0.00 | 9.35±0.00 | 0.0±0.0% | 0.000±0.000 | n/a | n/a | n/a | n/a | n/a | -| dynamic_line_backward | bicycle | proxmpc | 5 | 100% | 4.59±0.13 | 4.85±0.00 | 0.152±0.000 | 0.044±0.000 | 0.103±0.000 | n/a | n/a | 4.618±0.319 | 9.303±0.101 | 10.375±0.272 | 0.0±0.0% | 1.00±0.00 | 9.58±0.01 | 0.0±0.0% | 0.226±0.000 | n/a | n/a | n/a | n/a | n/a | -| dynamic_line_backward | unicycle | proxmpc | 5 | 100% | 4.53±0.06 | 4.85±0.00 | 0.154±0.000 | 0.048±0.000 | 0.111±0.000 | n/a | n/a | 3.469±0.081 | 7.424±0.156 | 11.895±0.583 | 0.0±0.0% | 1.00±0.00 | 9.57±0.00 | 0.0±0.0% | 0.194±0.000 | n/a | n/a | n/a | n/a | n/a | -| dynamic_line_forward | bicycle | proxmpc | 5 | 100% | 4.58±0.04 | 4.85±0.00 | 0.153±0.000 | 0.058±0.000 | 0.125±0.000 | n/a | n/a | 4.459±0.222 | 9.543±0.478 | 14.947±0.230 | 0.0±0.0% | 1.00±0.00 | 9.55±0.00 | 0.0±0.0% | 0.374±0.000 | n/a | n/a | n/a | n/a | n/a | -| dynamic_line_forward | unicycle | proxmpc | 5 | 100% | 4.48±0.19 | 4.84±0.04 | 0.154±0.000 | 0.045±0.001 | 0.104±0.000 | n/a | n/a | 4.059±0.170 | 8.381±0.827 | 12.402±0.763 | 0.0±0.0% | 1.00±0.00 | 9.61±0.02 | 0.0±0.0% | 0.223±0.000 | n/a | n/a | n/a | n/a | n/a | -| static_box | bicycle | proxmpc | 5 | 100% | 4.60±0.00 | 4.86±0.00 | 0.140±0.000 | 0.000±0.000 | 0.000±0.000 | n/a | n/a | 1.840±0.081 | 3.440±0.206 | 3.744±0.478 | 0.0±0.0% | 1.00±0.00 | 9.84±0.00 | 0.0±0.0% | 0.492±0.000 | n/a | n/a | n/a | n/a | n/a | -| static_box | unicycle | proxmpc | 5 | 100% | 4.52±0.04 | 4.85±0.00 | 0.140±0.000 | 0.000±0.000 | 0.000±0.000 | n/a | n/a | 1.451±0.047 | 2.826±0.086 | 3.318±0.373 | 0.0±0.0% | 1.00±0.00 | 9.85±0.01 | 0.0±0.0% | 0.492±0.000 | n/a | n/a | n/a | n/a | n/a | +| dynamic_circle | bicycle | proxmpc | 5 | 100% | 4.58±0.04 | 4.85±0.00 | 0.141±0.000 | 0.007±0.000 | 0.014±0.000 | n/a | n/a | 5.926±0.227 | 12.200±2.154 | 13.532±2.185 | 0.0±0.0% | 1.00±0.00 | 9.46±0.00 | 0.0±0.0% | 0.000±0.000 | n/a | n/a | n/a | n/a | n/a | +| dynamic_circle | unicycle | proxmpc | 5 | 100% | 4.56±0.08 | 4.85±0.00 | 0.141±0.000 | 0.007±0.000 | 0.015±0.000 | n/a | n/a | 4.723±0.379 | 8.385±0.696 | 10.106±2.178 | 0.0±0.0% | 1.00±0.00 | 9.48±0.00 | 0.0±0.0% | 0.000±0.000 | n/a | n/a | n/a | n/a | n/a | +| dynamic_line_backward | bicycle | proxmpc | 5 | 100% | 4.56±0.05 | 4.85±0.00 | 0.152±0.000 | 0.044±0.000 | 0.105±0.000 | n/a | n/a | 6.481±0.464 | 12.794±0.482 | 15.599±1.806 | 0.0±0.0% | 1.00±0.00 | 9.62±0.01 | 0.0±0.0% | 0.225±0.000 | n/a | n/a | n/a | n/a | n/a | +| dynamic_line_backward | unicycle | proxmpc | 5 | 100% | 4.54±0.05 | 4.85±0.00 | 0.154±0.000 | 0.048±0.000 | 0.111±0.000 | n/a | n/a | 4.825±0.449 | 9.681±0.192 | 33.535±2.112 | 0.0±0.0% | 1.00±0.00 | 9.90±0.01 | 0.0±0.0% | 0.194±0.000 | n/a | n/a | n/a | n/a | n/a | +| dynamic_line_forward | bicycle | proxmpc | 5 | 100% | 4.58±0.04 | 4.85±0.00 | 0.153±0.000 | 0.058±0.000 | 0.125±0.000 | n/a | n/a | 6.347±0.790 | 12.743±0.651 | 17.741±1.591 | 0.0±0.0% | 1.00±0.00 | 9.58±0.00 | 0.0±0.0% | 0.375±0.000 | n/a | n/a | n/a | n/a | n/a | +| dynamic_line_forward | unicycle | proxmpc | 5 | 100% | 4.56±0.05 | 4.85±0.00 | 0.155±0.000 | 0.045±0.000 | 0.105±0.000 | n/a | n/a | 5.321±0.657 | 11.377±1.675 | 15.580±1.121 | 0.0±0.0% | 1.00±0.00 | 9.64±0.01 | 0.0±0.0% | 0.222±0.000 | n/a | n/a | n/a | n/a | n/a | +| static_box | bicycle | proxmpc | 5 | 100% | 4.56±0.05 | 4.85±0.00 | 0.140±0.000 | 0.000±0.000 | 0.000±0.000 | n/a | n/a | 3.336±0.102 | 6.062±0.071 | 7.356±1.247 | 0.0±0.0% | 1.00±0.00 | 9.92±0.01 | 0.0±0.0% | 2.454±0.982 | n/a | n/a | n/a | n/a | n/a | +| static_box | unicycle | proxmpc | 5 | 100% | 4.49±0.15 | 4.84±0.03 | 0.140±0.000 | 0.000±0.000 | 0.000±0.000 | n/a | n/a | 2.470±0.142 | 5.176±0.620 | 6.529±1.446 | 0.0±0.0% | 1.00±0.00 | 9.93±0.03 | 0.0±0.0% | 2.454±0.982 | n/a | n/a | n/a | n/a | n/a | ### Mode `b2` | scenario | model | controller | n | success | t_goal[s] | path[m] | goal_err[m] | ct_rms[m] | ct_max[m] | obs_gap[m] | coll | solve_p50[ms] | solve_p95[ms] | solve_max[ms] | miss | sqp | qp_ext | infeas | slack[m] | rate[Hz] | cpu[%] | rss[MB] | cmp_p50[ms] | cmp_p95[ms] | |---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| -| blind_multi_0 | unicycle | dwb | 5 | 100% | 15.90±0.41 | 4.78±0.01 | 0.238±0.002 | 0.051±0.015 | 0.122±0.026 | 0.053±0.081 | 20% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.08±0.00 | 9.08±0.15 | 59.65±0.13 | 2.662±0.059 | 3.353±0.143 | -| blind_multi_0 | unicycle | graceful | 5 | 100% | 16.02±0.87 | 4.85±0.03 | 0.210±0.018 | 0.064±0.018 | 0.145±0.037 | -0.017±0.039 | 80% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 19.91±0.15 | 4.41±0.09 | 55.87±0.09 | 0.154±0.003 | 0.234±0.041 | -| blind_multi_0 | unicycle | mppi | 10 | 100% | 23.78±5.60 | 6.19±1.10 | 0.234±0.004 | 0.075±0.029 | 0.170±0.056 | -0.239±0.103 | 90% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.04±0.02 | 8.96±0.30 | 64.01±1.26 | 2.665±0.073 | 3.152±0.133 | -| blind_multi_0 | unicycle | proxmpc | 5 | 100% | 29.30±6.15 | 5.34±0.36 | 0.239±0.070 | 0.186±0.074 | 0.373±0.135 | -0.223±0.070 | 100% | 2.428±0.365 | 7.691±0.304 | 11.071±0.661 | 0.0±0.0% | 1.00±0.00 | 8.05±0.14 | 0.0±0.0% | 0.356±0.034 | 15.74±1.70 | 8.96±0.29 | 58.41±0.06 | 2.261±0.333 | 7.048±0.326 | -| blind_multi_0 | unicycle | proxmpc_pred | 5 | 100% | 25.14±5.70 | 5.25±0.40 | 0.267±0.057 | 0.141±0.030 | 0.335±0.077 | 0.013±0.140 | 40% | 1.909±0.335 | 5.601±0.968 | 14.187±7.457 | 0.0±0.0% | 1.00±0.00 | 8.09±0.24 | 0.0±0.0% | 0.361±0.038 | 16.97±1.95 | 8.06±0.54 | 59.91±0.08 | 1.899±0.347 | 4.820±0.814 | -| blind_multi_0 | unicycle | regulated_pure_pursuit | 5 | 100% | 16.90±1.70 | 4.87±0.04 | 0.236±0.002 | 0.080±0.014 | 0.169±0.013 | 0.049±0.064 | 20% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 19.03±0.32 | 4.53±0.09 | 55.22±0.06 | 0.209±0.005 | 0.277±0.004 | -| blind_multi_0 | unicycle | vector_pursuit | 5 | 100% | 23.31±4.06 | 5.08±0.27 | 0.237±0.003 | 0.079±0.052 | 0.168±0.067 | -0.107±0.097 | 80% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 16.10±2.05 | 4.21±0.07 | 55.13±0.12 | 0.197±0.009 | 0.290±0.036 | -| blind_multi_1 | unicycle | dwb | 5 | 100% | 14.08±1.44 | 4.65±0.28 | 0.237±0.001 | 0.060±0.015 | 0.143±0.030 | 0.154±0.140 | 20% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.08±0.00 | 9.18±0.10 | 59.68±0.10 | 2.765±0.089 | 3.604±0.340 | -| blind_multi_1 | unicycle | graceful | 5 | 100% | 15.44±0.64 | 4.86±0.01 | 0.220±0.006 | 0.119±0.042 | 0.222±0.066 | 0.090±0.079 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.07±0.00 | 4.44±0.13 | 55.73±0.06 | 0.163±0.008 | 0.240±0.029 | -| blind_multi_1 | unicycle | mppi | 10 | 100% | 15.63±1.31 | 4.83±0.01 | 0.230±0.004 | 0.055±0.017 | 0.116±0.036 | 0.034±0.184 | 30% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.07±0.00 | 8.68±0.20 | 63.18±0.57 | 2.671±0.071 | 3.058±0.172 | -| blind_multi_1 | unicycle | proxmpc | 5 | 100% | 21.88±4.74 | 5.12±0.22 | 0.194±0.042 | 0.205±0.079 | 0.379±0.126 | -0.179±0.122 | 100% | 2.148±0.251 | 5.835±0.802 | 11.595±4.902 | 0.0±0.0% | 1.00±0.00 | 7.74±0.15 | 0.0±0.0% | 0.312±0.015 | 17.57±1.78 | 8.67±0.36 | 58.55±0.07 | 2.029±0.222 | 5.872±0.656 | -| blind_multi_1 | unicycle | proxmpc_pred | 5 | 100% | 19.13±4.46 | 5.12±0.19 | 0.222±0.020 | 0.162±0.064 | 0.333±0.093 | -0.005±0.231 | 40% | 1.553±0.205 | 5.283±0.884 | 69.301±121.006 | 0.1±0.1% | 1.06±0.13 | 8.03±1.12 | 0.1±0.1% | 0.354±0.099 | 18.50±1.62 | 8.46±0.74 | 59.81±0.05 | 1.616±0.212 | 5.360±0.915 | -| blind_multi_1 | unicycle | regulated_pure_pursuit | 5 | 100% | 15.34±1.86 | 4.84±0.02 | 0.234±0.002 | 0.101±0.044 | 0.191±0.060 | 0.134±0.077 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 18.91±0.36 | 4.43±0.16 | 55.29±0.07 | 0.210±0.004 | 0.291±0.040 | -| blind_multi_1 | unicycle | vector_pursuit | 5 | 100% | 19.74±2.36 | 4.86±0.03 | 0.237±0.001 | 0.141±0.033 | 0.249±0.058 | 0.003±0.077 | 40% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 18.43±0.52 | 4.22±0.19 | 55.11±0.07 | 0.204±0.006 | 0.314±0.030 | -| blind_multi_2 | unicycle | dwb | 5 | 100% | 14.06±0.65 | 4.78±0.01 | 0.238±0.002 | 0.055±0.017 | 0.103±0.030 | -0.271±0.023 | 100% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 19.74±0.65 | 9.02±0.08 | 59.79±0.07 | 2.645±0.052 | 3.447±0.164 | -| blind_multi_2 | unicycle | graceful | 5 | 100% | 16.38±0.96 | 4.81±0.02 | 0.228±0.008 | 0.036±0.006 | 0.078±0.022 | -0.181±0.027 | 100% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.06±0.02 | 4.59±0.18 | 55.80±0.09 | 0.158±0.004 | 0.220±0.004 | -| blind_multi_2 | unicycle | mppi | 10 | 100% | 17.34±0.88 | 5.21±0.12 | 0.229±0.006 | 0.072±0.015 | 0.148±0.013 | 0.083±0.033 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.07±0.00 | 8.76±0.12 | 64.10±0.34 | 2.663±0.062 | 3.183±0.195 | -| blind_multi_2 | unicycle | proxmpc | 5 | 100% | 20.66±4.74 | 5.14±0.29 | 0.214±0.046 | 0.108±0.080 | 0.220±0.138 | 0.039±0.084 | 20% | 1.670±0.388 | 7.687±0.178 | 57.992±91.789 | 0.1±0.1% | 1.05±0.11 | 8.25±0.95 | 0.1±0.1% | 0.349±0.023 | 17.99±1.26 | 8.96±0.65 | 58.46±0.06 | 1.589±0.300 | 6.830±0.305 | -| blind_multi_2 | unicycle | proxmpc_pred | 5 | 80% | 19.44±1.30 | 3.98±1.99 | 1.181±1.909 | 0.073±0.038 | 0.143±0.073 | 0.574±0.749 | 0% | 1.771±0.049 | 3.875±0.117 | 7.304±0.826 | 0.0±0.0% | 0.80±0.40 | 6.14±3.08 | 0.0±0.0% | 0.244±0.125 | 19.10±0.69 | 7.92±0.23 | 59.69±0.10 | 1.793±0.030 | 3.877±0.036 | -| blind_multi_2 | unicycle | regulated_pure_pursuit | 5 | 100% | 16.89±1.95 | 4.84±0.07 | 0.235±0.004 | 0.106±0.072 | 0.169±0.115 | -0.185±0.070 | 100% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 18.02±2.31 | 4.48±0.07 | 55.24±0.13 | 0.211±0.003 | 0.289±0.033 | -| blind_multi_2 | unicycle | vector_pursuit | 5 | 80% | 19.17±1.30 | 3.88±1.94 | 1.190±1.905 | 0.083±0.053 | 0.168±0.099 | 0.370±0.851 | 80% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 18.45±0.20 | 4.33±0.08 | 55.04±0.07 | 0.212±0.006 | 0.306±0.032 | -| blind_multi_3 | unicycle | dwb | 5 | 100% | 14.75±0.78 | 4.74±0.09 | 0.237±0.001 | 0.050±0.017 | 0.101±0.023 | 0.241±0.051 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.08±0.00 | 9.23±0.12 | 59.63±0.10 | 2.785±0.082 | 3.510±0.202 | -| blind_multi_3 | unicycle | graceful | 5 | 100% | 17.56±0.74 | 4.88±0.02 | 0.206±0.012 | 0.124±0.005 | 0.256±0.007 | 0.091±0.047 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.07±0.00 | 4.29±0.20 | 55.70±0.09 | 0.156±0.005 | 0.230±0.011 | -| blind_multi_3 | unicycle | mppi | 10 | 90% | 16.47±1.64 | 4.30±1.44 | 0.711±1.430 | 0.078±0.041 | 0.148±0.067 | 0.228±0.711 | 70% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.13±0.14 | 8.77±0.19 | 63.00±0.21 | 2.686±0.086 | 3.175±0.238 | -| blind_multi_3 | unicycle | proxmpc | 5 | 100% | 16.56±1.03 | 4.97±0.14 | 0.222±0.020 | 0.118±0.036 | 0.252±0.059 | 0.157±0.132 | 20% | 1.996±0.295 | 5.481±0.419 | 7.343±0.685 | 0.0±0.0% | 1.00±0.00 | 7.59±0.19 | 0.0±0.0% | 0.327±0.050 | 19.61±0.56 | 8.63±0.43 | 58.41±0.18 | 2.083±0.311 | 5.671±0.383 | -| blind_multi_3 | unicycle | proxmpc_pred | 5 | 100% | 15.85±1.58 | 4.83±0.26 | 0.222±0.022 | 0.098±0.026 | 0.198±0.046 | 0.170±0.095 | 20% | 1.524±0.239 | 4.312±0.359 | 9.346±3.158 | 0.0±0.0% | 1.00±0.00 | 7.69±0.19 | 0.0±0.0% | 0.300±0.021 | 19.77±0.48 | 8.37±0.35 | 59.87±0.11 | 1.676±0.328 | 4.285±0.282 | -| blind_multi_3 | unicycle | regulated_pure_pursuit | 5 | 100% | 15.97±0.95 | 4.86±0.02 | 0.236±0.001 | 0.095±0.018 | 0.205±0.049 | 0.230±0.055 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 19.89±0.20 | 4.47±0.13 | 55.25±0.11 | 0.221±0.020 | 0.324±0.035 | -| blind_multi_3 | unicycle | vector_pursuit | 5 | 100% | 19.82±1.08 | 4.86±0.01 | 0.237±0.002 | 0.115±0.019 | 0.231±0.036 | 0.038±0.062 | 40% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 18.37±0.41 | 4.28±0.18 | 55.11±0.03 | 0.205±0.007 | 0.286±0.040 | -| dynamic_circle | unicycle | dwb | 5 | 100% | 14.88±0.59 | 4.77±0.00 | 0.236±0.001 | 0.025±0.016 | 0.054±0.022 | -0.243±0.049 | 100% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.08±0.00 | 9.08±0.25 | 59.84±0.06 | 2.619±0.089 | 3.713±0.368 | -| dynamic_circle | unicycle | graceful | 5 | 80% | 14.62±2.36 | 4.35±0.96 | 0.692±0.938 | 0.035±0.025 | 0.081±0.065 | -0.079±0.051 | 80% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.09±0.02 | 4.20±0.33 | 56.01±0.10 | 0.157±0.015 | 0.220±0.044 | -| dynamic_circle | unicycle | mppi | 10 | 90% | 17.43±1.37 | 4.58±1.53 | 0.709±1.430 | 0.035±0.024 | 0.083±0.045 | 0.551±1.133 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.06±0.00 | 8.91±0.13 | 62.96±0.07 | 2.714±0.073 | 3.243±0.108 | -| dynamic_circle | unicycle | proxmpc | 5 | 80% | 20.48±0.94 | 4.32±2.16 | 1.115±1.943 | 0.098±0.051 | 0.239±0.131 | 0.887±1.532 | 0% | 1.619±0.301 | 7.909±0.212 | 14.685±6.896 | 0.0±0.0% | 0.80±0.40 | 6.04±3.03 | 0.0±0.0% | 0.449±0.228 | 18.62±0.21 | 8.86±0.30 | 58.46±0.16 | 1.537±0.302 | 5.742±0.615 | -| dynamic_circle | unicycle | proxmpc_pred | 5 | 80% | 16.04±1.08 | 4.14±2.07 | 1.191±1.905 | 0.177±0.096 | 0.369±0.217 | 0.914±1.519 | 0% | 1.418±0.111 | 4.986±0.168 | 74.521±116.838 | 0.1±0.1% | 0.87±0.45 | 6.69±3.62 | 0.1±0.1% | 0.122±0.075 | 19.47±0.36 | 8.28±0.64 | 59.87±0.11 | 1.499±0.096 | 5.103±0.167 | -| dynamic_circle | unicycle | regulated_pure_pursuit | 5 | 100% | 17.08±1.83 | 4.84±0.04 | 0.234±0.004 | 0.077±0.038 | 0.173±0.070 | 0.067±0.046 | 20% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 18.67±0.32 | 4.35±0.06 | 55.38±0.20 | 0.210±0.004 | 0.290±0.022 | -| dynamic_circle | unicycle | vector_pursuit | 5 | 100% | 20.04±0.42 | 4.80±0.01 | 0.235±0.002 | 0.050±0.005 | 0.117±0.021 | 0.142±0.033 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 18.30±0.39 | 4.33±0.17 | 55.26±0.07 | 0.213±0.006 | 0.332±0.025 | -| dynamic_line_backward | unicycle | dwb | 5 | 100% | 13.84±1.48 | 4.78±0.01 | 0.235±0.002 | 0.049±0.021 | 0.096±0.037 | 0.495±0.023 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.09±0.00 | 8.79±0.16 | 59.53±0.05 | 2.614±0.095 | 3.501±0.148 | -| dynamic_line_backward | unicycle | graceful | 5 | 100% | 11.98±1.18 | 4.74±0.13 | 0.227±0.013 | 0.057±0.032 | 0.103±0.049 | 0.324±0.078 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.09±0.00 | 4.40±0.20 | 55.73±0.19 | 0.162±0.011 | 0.257±0.022 | -| dynamic_line_backward | unicycle | mppi | 10 | 100% | 13.94±0.74 | 4.78±0.01 | 0.231±0.004 | 0.031±0.015 | 0.055±0.017 | 0.617±0.014 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.08±0.00 | 8.62±0.10 | 62.88±0.09 | 2.667±0.055 | 3.287±0.172 | -| dynamic_line_backward | unicycle | proxmpc | 5 | 100% | 13.98±0.97 | 4.86±0.01 | 0.232±0.013 | 0.093±0.033 | 0.162±0.052 | 0.513±0.079 | 0% | 0.969±0.099 | 4.561±0.587 | 8.098±1.283 | 0.0±0.0% | 1.00±0.00 | 7.53±0.39 | 0.0±0.0% | 0.262±0.035 | 20.08±0.00 | 7.27±0.37 | 58.42±0.07 | 1.102±0.114 | 4.747±0.624 | -| dynamic_line_backward | unicycle | proxmpc_pred | 5 | 100% | 13.45±0.99 | 4.85±0.04 | 0.232±0.010 | 0.072±0.028 | 0.130±0.053 | 0.373±0.012 | 0% | 0.897±0.048 | 3.680±0.278 | 7.559±1.577 | 0.0±0.0% | 1.00±0.00 | 7.27±0.18 | 0.0±0.0% | 0.247±0.064 | 20.08±0.00 | 6.72±0.22 | 59.68±0.15 | 1.000±0.044 | 3.788±0.306 | -| dynamic_line_backward | unicycle | regulated_pure_pursuit | 5 | 100% | 13.26±1.30 | 4.80±0.02 | 0.233±0.003 | 0.061±0.024 | 0.115±0.038 | 0.402±0.020 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.13±0.03 | 4.39±0.08 | 55.29±0.11 | 0.208±0.004 | 0.286±0.027 | -| dynamic_line_backward | unicycle | vector_pursuit | 5 | 100% | 13.56±0.97 | 4.78±0.01 | 0.237±0.002 | 0.053±0.011 | 0.087±0.018 | 0.448±0.020 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 19.48±0.35 | 4.29±0.14 | 55.09±0.12 | 0.211±0.006 | 0.286±0.025 | -| dynamic_line_forward | unicycle | dwb | 5 | 100% | 13.21±1.03 | 4.77±0.00 | 0.237±0.002 | 0.029±0.009 | 0.058±0.011 | 0.487±0.008 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.09±0.00 | 8.71±0.08 | 59.78±0.12 | 2.597±0.085 | 3.489±0.252 | -| dynamic_line_forward | unicycle | graceful | 5 | 100% | 13.76±0.48 | 4.80±0.01 | 0.229±0.006 | 0.055±0.020 | 0.109±0.034 | 0.283±0.000 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.09±0.00 | 4.32±0.11 | 55.75±0.09 | 0.154±0.003 | 0.215±0.012 | -| dynamic_line_forward | unicycle | mppi | 10 | 100% | 13.96±1.55 | 4.77±0.05 | 0.231±0.004 | 0.034±0.015 | 0.064±0.021 | 0.589±0.044 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.08±0.00 | 8.69±0.16 | 62.91±0.14 | 2.682±0.066 | 3.192±0.232 | -| dynamic_line_forward | unicycle | proxmpc | 5 | 100% | 15.85±1.06 | 4.82±0.02 | 0.239±0.001 | 0.060±0.017 | 0.126±0.036 | 0.548±0.022 | 0% | 0.926±0.076 | 4.718±0.779 | 6.760±0.554 | 0.0±0.0% | 1.00±0.00 | 7.51±0.23 | 0.0±0.0% | 0.301±0.042 | 20.08±0.00 | 7.03±0.38 | 58.28±0.09 | 1.026±0.074 | 4.918±0.838 | -| dynamic_line_forward | unicycle | proxmpc_pred | 5 | 100% | 13.76±1.69 | 4.73±0.24 | 0.238±0.003 | 0.068±0.022 | 0.117±0.045 | 0.345±0.077 | 0% | 0.835±0.031 | 3.460±0.581 | 5.870±1.146 | 0.0±0.0% | 1.00±0.00 | 7.21±0.43 | 0.0±0.0% | 0.200±0.092 | 20.08±0.01 | 6.60±0.27 | 59.66±0.11 | 0.938±0.037 | 3.551±0.577 | -| dynamic_line_forward | unicycle | regulated_pure_pursuit | 5 | 100% | 13.36±1.06 | 4.81±0.02 | 0.234±0.004 | 0.071±0.016 | 0.121±0.026 | 0.416±0.009 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.08±0.04 | 4.43±0.18 | 55.29±0.12 | 0.209±0.006 | 0.286±0.002 | -| dynamic_line_forward | unicycle | vector_pursuit | 5 | 80% | 13.43±0.67 | 3.83±1.92 | 1.191±1.905 | 0.062±0.038 | 0.112±0.068 | 0.943±0.954 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 19.74±0.26 | 4.33±0.15 | 55.03±0.04 | 0.209±0.008 | 0.290±0.047 | -| dynamic_multi | unicycle | dwb | 5 | 100% | 15.52±1.26 | 4.79±0.02 | 0.237±0.002 | 0.051±0.024 | 0.093±0.041 | -0.005±0.171 | 20% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.06±0.02 | 9.18±0.07 | 59.73±0.10 | 2.721±0.071 | 3.445±0.143 | -| dynamic_multi | unicycle | graceful | 5 | 100% | 16.53±1.35 | 4.84±0.08 | 0.225±0.008 | 0.121±0.066 | 0.220±0.085 | -0.025±0.045 | 80% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 19.99±0.14 | 4.35±0.07 | 55.71±0.06 | 0.181±0.016 | 0.280±0.041 | -| dynamic_multi | unicycle | mppi | 10 | 100% | 17.42±1.08 | 5.02±0.12 | 0.233±0.004 | 0.060±0.034 | 0.124±0.057 | 0.117±0.110 | 20% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.07±0.00 | 8.84±0.17 | 63.25±0.47 | 2.698±0.065 | 3.128±0.122 | -| dynamic_multi | unicycle | proxmpc | 5 | 100% | 26.19±9.04 | 5.34±0.35 | 0.205±0.067 | 0.183±0.116 | 0.324±0.181 | 0.015±0.191 | 60% | 2.150±0.351 | 7.260±0.689 | 11.078±1.833 | 0.0±0.0% | 1.00±0.00 | 7.89±0.15 | 0.0±0.0% | 0.342±0.017 | 17.64±2.63 | 8.74±0.48 | 58.46±0.10 | 2.052±0.253 | 6.548±0.446 | -| dynamic_multi | unicycle | proxmpc_pred | 5 | 100% | 19.86±0.82 | 5.22±0.27 | 0.232±0.011 | 0.109±0.029 | 0.244±0.082 | 0.188±0.035 | 0% | 1.783±0.187 | 4.339±0.349 | 62.841±108.504 | 0.1±0.2% | 1.11±0.22 | 9.06±2.55 | 0.1±0.2% | 0.275±0.038 | 19.36±0.52 | 8.80±1.11 | 59.79±0.11 | 1.831±0.217 | 4.330±0.437 | -| dynamic_multi | unicycle | regulated_pure_pursuit | 5 | 100% | 16.62±1.26 | 4.87±0.01 | 0.234±0.002 | 0.085±0.013 | 0.216±0.024 | 0.144±0.031 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 19.69±0.17 | 4.50±0.15 | 55.28±0.10 | 0.216±0.006 | 0.298±0.031 | -| dynamic_multi | unicycle | vector_pursuit | 5 | 100% | 22.14±4.04 | 4.83±0.02 | 0.238±0.001 | 0.097±0.025 | 0.198±0.048 | 0.033±0.112 | 40% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 17.81±1.93 | 4.27±0.19 | 55.09±0.06 | 0.209±0.010 | 0.279±0.030 | -| dynamic_multi_noise | unicycle | dwb | 5 | 100% | 15.80±0.54 | 4.78±0.01 | 0.237±0.001 | 0.040±0.009 | 0.070±0.012 | -0.038±0.141 | 40% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.08±0.01 | 9.15±0.05 | 59.70±0.10 | 2.744±0.070 | 3.565±0.170 | -| dynamic_multi_noise | unicycle | graceful | 5 | 80% | 16.03±1.46 | 4.12±1.35 | 0.875±1.321 | 0.081±0.062 | 0.153±0.090 | -0.022±0.032 | 60% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 19.99±0.24 | 4.25±0.22 | 55.81±0.02 | 0.154±0.002 | 0.207±0.022 | -| dynamic_multi_noise | unicycle | mppi | 10 | 100% | 18.08±0.92 | 5.05±0.11 | 0.232±0.004 | 0.059±0.030 | 0.120±0.041 | 0.086±0.110 | 20% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.06±0.00 | 8.85±0.17 | 63.04±0.35 | 2.671±0.079 | 3.113±0.109 | -| dynamic_multi_noise | unicycle | proxmpc | 5 | 100% | 29.06±5.96 | 5.55±0.31 | 0.201±0.038 | 0.277±0.079 | 0.505±0.113 | -0.260±0.058 | 100% | 2.172±0.372 | 7.498±0.401 | 12.446±3.566 | 0.0±0.0% | 1.00±0.00 | 7.89±0.13 | 0.0±0.0% | 0.383±0.082 | 16.35±1.63 | 8.59±0.37 | 58.48±0.08 | 1.947±0.274 | 6.815±0.499 | -| dynamic_multi_noise | unicycle | proxmpc_pred | 5 | 80% | 21.16±6.22 | 4.27±2.20 | 1.179±1.911 | 0.100±0.093 | 0.190±0.192 | 0.537±0.843 | 20% | 1.843±0.439 | 4.453±0.710 | 8.574±1.090 | 0.0±0.0% | 0.80±0.40 | 6.43±3.22 | 0.0±0.0% | 0.402±0.356 | 18.29±2.09 | 8.07±0.19 | 59.98±0.11 | 1.919±0.501 | 4.405±0.779 | -| dynamic_multi_noise | unicycle | regulated_pure_pursuit | 5 | 100% | 15.70±1.25 | 4.77±0.23 | 0.233±0.004 | 0.108±0.024 | 0.224±0.035 | 0.136±0.020 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 19.41±0.67 | 4.46±0.16 | 55.27±0.05 | 0.210±0.003 | 0.289±0.020 | -| dynamic_multi_noise | unicycle | vector_pursuit | 5 | 100% | 20.20±0.96 | 4.82±0.02 | 0.237±0.002 | 0.073±0.022 | 0.158±0.052 | 0.190±0.040 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 18.52±0.58 | 4.35±0.14 | 55.08±0.09 | 0.206±0.003 | 0.268±0.021 | -| nav2_open | unicycle | dwb | 5 | 100% | 13.34±0.47 | 4.76±0.00 | 0.238±0.002 | 0.000±0.000 | 0.000±0.000 | n/a | n/a | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.09±0.00 | 8.40±0.12 | 59.80±0.08 | 2.468±0.006 | 2.844±0.341 | -| nav2_open | unicycle | graceful | 5 | 100% | 12.41±0.91 | 4.78±0.00 | 0.220±0.000 | 0.000±0.000 | 0.000±0.000 | n/a | n/a | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.11±0.00 | 4.27±0.14 | 55.77±0.13 | 0.148±0.002 | 0.186±0.017 | -| nav2_open | unicycle | mppi | 5 | 80% | 12.26±0.47 | 3.85±1.83 | 1.151±1.829 | 0.002±0.001 | 0.003±0.002 | n/a | n/a | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.10±0.00 | 7.55±1.88 | 62.88±0.10 | 2.922±0.623 | 3.152±0.510 | -| nav2_open | unicycle | proxmpc | 5 | 100% | 12.67±1.39 | 4.76±0.00 | 0.238±0.000 | 0.000±0.000 | 0.001±0.000 | n/a | n/a | 0.619±0.031 | 1.026±0.074 | 2.417±0.146 | 0.0±0.0% | 1.00±0.00 | 5.91±0.24 | 0.0±0.0% | 0.140±0.000 | 20.09±0.00 | 5.00±0.08 | 58.47±0.15 | 0.743±0.029 | 1.119±0.076 | -| nav2_open | unicycle | proxmpc_pred | 5 | 100% | 12.55±1.34 | 4.68±0.17 | 0.239±0.000 | 0.000±0.000 | 0.000±0.000 | n/a | n/a | 0.530±0.206 | 0.959±0.056 | 1.569±0.217 | 0.0±0.0% | 1.00±0.00 | 5.41±0.68 | 0.0±0.0% | 0.032±0.016 | 20.09±0.00 | 5.54±0.18 | 59.61±0.15 | 0.626±0.197 | 1.050±0.067 | -| nav2_open | unicycle | regulated_pure_pursuit | 5 | 100% | 10.56±1.33 | 4.67±0.14 | 0.235±0.000 | 0.000±0.000 | 0.000±0.000 | n/a | n/a | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.10±0.00 | 4.42±0.19 | 55.24±0.12 | 0.208±0.006 | 0.257±0.042 | -| nav2_open | unicycle | vector_pursuit | 5 | 100% | 12.80±1.56 | 4.76±0.00 | 0.236±0.001 | 0.000±0.000 | 0.000±0.000 | n/a | n/a | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.09±0.00 | 4.26±0.13 | 55.01±0.07 | 0.212±0.006 | 0.254±0.031 | -| static_box | unicycle | dwb | 5 | 100% | 13.24±1.62 | 4.87±0.01 | 0.237±0.002 | 0.258±0.012 | 0.450±0.005 | 0.093±0.004 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.08±0.00 | 9.05±0.16 | 59.65±0.13 | 2.594±0.036 | 2.996±0.175 | -| static_box | unicycle | graceful | 5 | 100% | 12.71±0.90 | 4.96±0.01 | 0.208±0.008 | 0.324±0.010 | 0.567±0.006 | 0.207±0.007 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.09±0.00 | 4.44±0.08 | 55.70±0.06 | 0.162±0.009 | 0.196±0.018 | -| static_box | unicycle | mppi | 10 | 100% | 12.08±1.00 | 4.93±0.01 | 0.232±0.006 | 0.322±0.015 | 0.571±0.003 | 0.207±0.002 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.10±0.00 | 8.55±0.22 | 62.94±0.11 | 2.683±0.068 | 2.996±0.190 | -| static_box | unicycle | proxmpc | 5 | 100% | 13.12±1.02 | 4.99±0.01 | 0.230±0.007 | 0.365±0.011 | 0.706±0.001 | 0.352±0.002 | 0% | 1.037±0.046 | 2.586±0.118 | 3.494±0.182 | 0.0±0.0% | 1.00±0.00 | 7.19±0.04 | 0.0±0.0% | 0.136±0.007 | 20.09±0.00 | 6.53±0.12 | 58.33±0.08 | 1.154±0.056 | 2.745±0.159 | -| static_box | unicycle | proxmpc_pred | 5 | 100% | 13.58±0.52 | 5.03±0.05 | 0.198±0.012 | 0.341±0.012 | 0.649±0.001 | 0.298±0.001 | 0% | 1.015±0.141 | 2.626±0.366 | 3.969±0.684 | 0.0±0.0% | 1.00±0.00 | 7.31±0.22 | 0.0±0.0% | 0.040±0.000 | 20.08±0.00 | 6.83±0.42 | 59.74±0.14 | 1.127±0.142 | 2.758±0.369 | -| static_box | unicycle | regulated_pure_pursuit | 5 | 100% | 11.64±1.42 | 4.87±0.13 | 0.234±0.002 | 0.334±0.019 | 0.567±0.001 | 0.213±0.002 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.10±0.01 | 4.36±0.15 | 55.11±0.13 | 0.213±0.002 | 0.285±0.030 | -| static_box | unicycle | vector_pursuit | 5 | 0% | n/a | 2.35±0.24 | 2.747±0.233 | 0.420±0.041 | 0.435±0.043 | 0.175±0.078 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 18.36±0.06 | 4.43±0.17 | 55.20±0.10 | 0.233±0.018 | 0.358±0.028 | - -> Mode **a** (Gazebo Harmonic + full Nav2) is absent from this run: it needs a -> working GPU driver, and the host used here renders Gazebo in software, which -> starves the control loop and makes any timing it produces meaningless. The -> b1 and b2 numbers above are unaffected (neither uses Gazebo). +| blind_multi_0 | unicycle | dwb | 5 | 100% | 16.31±0.81 | 4.79±0.01 | 0.236±0.001 | 0.052±0.017 | 0.128±0.021 | 0.024±0.073 | 20% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.08±0.02 | 9.55±0.37 | 59.86±0.10 | 3.057±0.157 | 4.505±0.677 | +| blind_multi_0 | unicycle | graceful | 5 | 100% | 17.04±0.93 | 4.84±0.08 | 0.212±0.010 | 0.057±0.015 | 0.115±0.012 | 0.027±0.047 | 20% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.05±0.04 | 4.09±0.17 | 55.82±0.04 | 0.170±0.011 | 0.307±0.050 | +| blind_multi_0 | unicycle | mppi | 10 | 100% | 18.31±3.69 | 5.36±0.70 | 0.233±0.004 | 0.087±0.012 | 0.184±0.032 | -0.152±0.105 | 80% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.07±0.01 | 9.49±0.33 | 63.23±0.49 | 3.091±0.166 | 4.297±0.504 | +| blind_multi_0 | unicycle | proxmpc | 5 | 100% | 18.09±1.97 | 5.20±0.38 | 0.194±0.050 | 0.143±0.038 | 0.344±0.096 | -0.053±0.127 | 80% | 2.542±0.525 | 8.140±1.242 | 13.497±1.888 | 0.0±0.0% | 1.00±0.00 | 8.13±0.23 | 0.4±0.5% | 0.334±0.067 | 20.03±0.04 | 10.36±1.22 | 58.61±0.08 | 2.726±0.642 | 8.657±1.546 | +| blind_multi_0 | unicycle | proxmpc_pred | 5 | 100% | 23.77±4.71 | 6.05±1.09 | 0.219±0.021 | 0.152±0.093 | 0.359±0.220 | 0.005±0.126 | 60% | 1.945±0.382 | 6.536±0.837 | 15.165±2.570 | 0.0±0.0% | 1.00±0.00 | 7.78±0.38 | 0.0±0.0% | 0.475±0.111 | 20.01±0.09 | 8.96±0.61 | 59.99±0.04 | 2.060±0.376 | 6.612±0.877 | +| blind_multi_0 | unicycle | regulated_pure_pursuit | 5 | 100% | 16.30±0.43 | 4.85±0.03 | 0.235±0.002 | 0.071±0.002 | 0.144±0.016 | 0.059±0.056 | 20% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 18.97±0.63 | 4.05±0.06 | 55.39±0.07 | 0.228±0.010 | 0.378±0.009 | +| blind_multi_0 | unicycle | vector_pursuit | 5 | 100% | 18.46±0.75 | 4.89±0.07 | 0.238±0.002 | 0.081±0.021 | 0.184±0.036 | -0.077±0.037 | 100% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 18.26±0.40 | 3.87±0.06 | 55.21±0.07 | 0.208±0.015 | 0.356±0.044 | +| blind_multi_1 | unicycle | dwb | 5 | 100% | 14.81±1.29 | 4.77±0.01 | 0.238±0.001 | 0.050±0.029 | 0.111±0.068 | 0.223±0.055 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.08±0.00 | 9.48±0.38 | 59.79±0.06 | 3.123±0.116 | 5.038±0.958 | +| blind_multi_1 | unicycle | graceful | 5 | 100% | 15.26±0.81 | 4.86±0.04 | 0.221±0.005 | 0.082±0.033 | 0.182±0.076 | 0.146±0.080 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.08±0.00 | 4.05±0.10 | 55.89±0.09 | 0.177±0.013 | 0.286±0.034 | +| blind_multi_1 | unicycle | mppi | 10 | 100% | 15.54±1.46 | 4.81±0.11 | 0.232±0.006 | 0.059±0.020 | 0.129±0.047 | 0.081±0.182 | 30% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.07±0.00 | 9.32±0.34 | 63.04±0.09 | 3.071±0.111 | 4.089±0.357 | +| blind_multi_1 | unicycle | proxmpc | 5 | 100% | 19.34±1.88 | 5.01±0.10 | 0.234±0.003 | 0.131±0.057 | 0.278±0.085 | -0.049±0.142 | 20% | 2.456±0.683 | 7.449±2.269 | 11.464±4.221 | 0.0±0.0% | 1.00±0.00 | 7.92±0.20 | 0.0±0.0% | 0.321±0.087 | 20.05±0.04 | 9.49±1.07 | 58.57±0.13 | 2.559±0.684 | 7.323±1.926 | +| blind_multi_1 | unicycle | proxmpc_pred | 5 | 100% | 16.46±0.87 | 5.19±0.31 | 0.234±0.007 | 0.111±0.027 | 0.218±0.047 | 0.140±0.061 | 0% | 1.219±0.135 | 5.597±1.133 | 11.537±2.834 | 0.0±0.0% | 1.00±0.00 | 6.86±0.23 | 0.0±0.0% | 0.255±0.144 | 20.07±0.00 | 7.66±0.44 | 59.91±0.09 | 1.343±0.133 | 5.737±1.153 | +| blind_multi_1 | unicycle | regulated_pure_pursuit | 5 | 100% | 14.37±0.71 | 4.84±0.03 | 0.234±0.003 | 0.108±0.029 | 0.202±0.040 | 0.100±0.034 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 19.32±0.31 | 3.97±0.21 | 55.41±0.10 | 0.226±0.010 | 0.377±0.035 | +| blind_multi_1 | unicycle | vector_pursuit | 5 | 100% | 21.77±4.26 | 4.81±0.02 | 0.236±0.001 | 0.116±0.050 | 0.190±0.066 | 0.063±0.065 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 17.14±1.92 | 3.94±0.12 | 55.23±0.11 | 0.229±0.008 | 0.386±0.045 | +| blind_multi_2 | unicycle | dwb | 5 | 100% | 15.71±0.09 | 4.77±0.01 | 0.236±0.002 | 0.031±0.019 | 0.065±0.027 | -0.252±0.047 | 100% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 19.56±0.60 | 9.42±0.41 | 59.92±0.09 | 3.048±0.133 | 4.777±0.678 | +| blind_multi_2 | unicycle | graceful | 5 | 100% | 16.41±1.44 | 4.84±0.03 | 0.229±0.008 | 0.089±0.044 | 0.170±0.076 | -0.168±0.035 | 100% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 19.99±0.11 | 3.92±0.15 | 55.96±0.08 | 0.171±0.006 | 0.286±0.023 | +| blind_multi_2 | unicycle | mppi | 10 | 100% | 18.05±2.28 | 5.19±0.17 | 0.232±0.004 | 0.076±0.010 | 0.155±0.015 | 0.080±0.023 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.07±0.00 | 9.41±0.23 | 64.00±0.40 | 3.032±0.140 | 4.109±0.480 | +| blind_multi_2 | unicycle | proxmpc | 5 | 100% | 23.62±4.50 | 5.65±0.71 | 0.185±0.026 | 0.304±0.121 | 0.640±0.234 | -0.078±0.038 | 100% | 2.300±0.641 | 11.475±1.102 | 25.197±5.907 | 0.0±0.0% | 1.00±0.00 | 8.17±0.20 | 0.7±1.3% | 0.481±0.045 | 19.68±0.35 | 11.05±0.61 | 58.74±0.16 | 2.341±0.682 | 11.395±1.033 | +| blind_multi_2 | unicycle | proxmpc_pred | 5 | 100% | 17.86±1.47 | 5.02±0.17 | 0.234±0.007 | 0.097±0.023 | 0.205±0.035 | 0.180±0.049 | 0% | 1.176±0.137 | 4.363±0.253 | 9.394±2.288 | 0.0±0.0% | 1.00±0.00 | 6.98±0.38 | 0.1±0.2% | 0.207±0.068 | 20.06±0.00 | 7.30±0.14 | 60.00±0.15 | 1.304±0.137 | 4.493±0.270 | +| blind_multi_2 | unicycle | regulated_pure_pursuit | 5 | 100% | 18.41±2.26 | 4.87±0.07 | 0.236±0.003 | 0.139±0.067 | 0.244±0.101 | -0.166±0.102 | 100% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 17.62±2.08 | 3.99±0.12 | 55.39±0.08 | 0.227±0.006 | 0.380±0.045 | +| blind_multi_2 | unicycle | vector_pursuit | 5 | 100% | 23.50±5.16 | 5.05±0.28 | 0.237±0.002 | 0.076±0.024 | 0.163±0.037 | -0.050±0.018 | 100% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 15.30±3.64 | 3.97±0.18 | 55.13±0.09 | 0.230±0.013 | 0.394±0.048 | +| blind_multi_3 | unicycle | dwb | 5 | 100% | 14.62±0.76 | 4.76±0.06 | 0.237±0.002 | 0.056±0.011 | 0.122±0.020 | 0.258±0.045 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.07±0.00 | 9.68±0.42 | 59.73±0.09 | 3.142±0.126 | 5.034±1.014 | +| blind_multi_3 | unicycle | graceful | 5 | 100% | 15.50±1.32 | 4.86±0.03 | 0.232±0.005 | 0.103±0.039 | 0.212±0.067 | 0.107±0.054 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.00±0.14 | 4.01±0.13 | 55.83±0.09 | 0.174±0.009 | 0.285±0.042 | +| blind_multi_3 | unicycle | mppi | 10 | 100% | 16.37±1.57 | 4.79±0.10 | 0.233±0.004 | 0.081±0.034 | 0.149±0.053 | 0.028±0.126 | 60% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.12±0.13 | 9.27±0.26 | 63.18±0.27 | 3.031±0.074 | 4.131±0.449 | +| blind_multi_3 | unicycle | proxmpc | 5 | 100% | 18.67±0.58 | 4.92±0.02 | 0.235±0.002 | 0.125±0.019 | 0.252±0.028 | -0.041±0.006 | 100% | 2.094±0.165 | 5.706±0.324 | 12.232±4.729 | 0.0±0.0% | 1.00±0.00 | 7.82±0.03 | 0.1±0.1% | 0.308±0.008 | 20.06±0.00 | 8.58±0.07 | 58.52±0.10 | 2.230±0.172 | 5.850±0.327 | +| blind_multi_3 | unicycle | proxmpc_pred | 5 | 100% | 19.17±1.83 | 5.38±0.38 | 0.193±0.067 | 0.117±0.019 | 0.255±0.053 | 0.171±0.090 | 0% | 1.980±0.750 | 5.448±0.556 | 13.397±5.096 | 0.0±0.0% | 1.00±0.00 | 7.35±0.42 | 0.0±0.0% | 0.372±0.115 | 20.06±0.01 | 8.44±0.75 | 59.98±0.05 | 2.150±0.722 | 5.636±0.550 | +| blind_multi_3 | unicycle | regulated_pure_pursuit | 5 | 100% | 14.94±0.98 | 4.81±0.11 | 0.234±0.003 | 0.076±0.014 | 0.173±0.033 | 0.306±0.030 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 19.67±0.57 | 4.14±0.11 | 55.30±0.08 | 0.229±0.009 | 0.387±0.062 | +| blind_multi_3 | unicycle | vector_pursuit | 5 | 100% | 19.60±0.91 | 4.85±0.00 | 0.236±0.001 | 0.110±0.016 | 0.220±0.032 | 0.005±0.021 | 40% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 18.60±0.38 | 4.01±0.12 | 55.22±0.08 | 0.224±0.012 | 0.353±0.031 | +| dynamic_circle | unicycle | dwb | 5 | 100% | 15.23±0.97 | 4.78±0.01 | 0.236±0.002 | 0.037±0.017 | 0.072±0.030 | -0.243±0.075 | 100% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.08±0.00 | 9.49±0.30 | 59.83±0.11 | 3.143±0.097 | 4.762±0.690 | +| dynamic_circle | unicycle | graceful | 5 | 100% | 15.34±1.89 | 4.69±0.18 | 0.229±0.004 | 0.039±0.013 | 0.084±0.014 | -0.045±0.012 | 100% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.02±0.06 | 4.09±0.04 | 55.86±0.08 | 0.176±0.011 | 0.293±0.030 | +| dynamic_circle | unicycle | mppi | 10 | 100% | 17.91±1.06 | 5.07±0.06 | 0.232±0.005 | 0.046±0.027 | 0.105±0.062 | 0.172±0.025 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.06±0.00 | 9.37±0.16 | 63.09±0.12 | 3.071±0.111 | 4.089±0.302 | +| dynamic_circle | unicycle | proxmpc | 5 | 100% | 18.20±0.56 | 5.11±0.15 | 0.233±0.006 | 0.182±0.094 | 0.399±0.126 | 0.259±0.038 | 0% | 1.612±0.204 | 6.264±0.490 | 9.290±1.292 | 0.0±0.0% | 1.00±0.00 | 6.96±0.03 | 1.0±2.1% | 0.167±0.033 | 20.06±0.00 | 7.90±0.20 | 58.58±0.14 | 1.725±0.205 | 6.420±0.493 | +| dynamic_circle | unicycle | proxmpc_pred | 5 | 100% | 18.66±1.37 | 5.20±0.14 | 0.235±0.004 | 0.110±0.037 | 0.275±0.105 | 0.291±0.012 | 0% | 1.482±0.144 | 5.060±0.602 | 9.000±1.058 | 0.0±0.0% | 1.00±0.00 | 6.66±0.05 | 0.4±0.5% | 0.425±0.083 | 20.06±0.00 | 7.54±0.22 | 60.10±0.15 | 1.594±0.139 | 5.200±0.603 | +| dynamic_circle | unicycle | regulated_pure_pursuit | 5 | 100% | 18.13±2.07 | 4.83±0.02 | 0.237±0.002 | 0.086±0.029 | 0.169±0.036 | 0.040±0.052 | 40% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 17.25±2.98 | 3.98±0.13 | 55.34±0.12 | 0.236±0.008 | 0.403±0.051 | +| dynamic_circle | unicycle | vector_pursuit | 5 | 100% | 19.12±1.93 | 4.68±0.26 | 0.237±0.002 | 0.072±0.029 | 0.169±0.050 | 0.143±0.053 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 18.30±0.36 | 3.90±0.06 | 55.12±0.12 | 0.226±0.014 | 0.365±0.078 | +| dynamic_line_backward | unicycle | dwb | 5 | 100% | 13.86±0.47 | 4.77±0.00 | 0.235±0.002 | 0.032±0.012 | 0.063±0.019 | 0.481±0.009 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.09±0.00 | 8.90±0.12 | 59.77±0.14 | 2.836±0.038 | 4.163±0.621 | +| dynamic_line_backward | unicycle | graceful | 5 | 100% | 13.28±1.62 | 4.70±0.16 | 0.231±0.004 | 0.035±0.016 | 0.077±0.013 | 0.336±0.051 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.09±0.00 | 3.91±0.07 | 55.86±0.10 | 0.172±0.008 | 0.305±0.051 | +| dynamic_line_backward | unicycle | mppi | 10 | 100% | 14.40±1.93 | 4.78±0.01 | 0.233±0.004 | 0.039±0.011 | 0.071±0.018 | 0.605±0.026 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.09±0.00 | 9.22±0.23 | 63.01±0.06 | 3.073±0.133 | 4.273±0.554 | +| dynamic_line_backward | unicycle | proxmpc | 5 | 100% | 15.34±1.14 | 4.87±0.02 | 0.226±0.004 | 0.141±0.015 | 0.243±0.037 | 0.505±0.038 | 0% | 0.917±0.060 | 4.074±0.434 | 7.687±2.446 | 0.0±0.0% | 1.00±0.00 | 6.62±0.08 | 0.0±0.0% | 0.131±0.000 | 20.07±0.00 | 6.50±0.15 | 58.55±0.11 | 1.051±0.068 | 4.219±0.443 | +| dynamic_line_backward | unicycle | proxmpc_pred | 5 | 100% | 14.64±2.23 | 4.80±0.08 | 0.237±0.001 | 0.068±0.031 | 0.128±0.053 | 0.354±0.076 | 0% | 0.745±0.066 | 4.073±0.505 | 8.863±2.159 | 0.0±0.0% | 1.00±0.00 | 5.59±0.25 | 0.0±0.0% | 0.248±0.036 | 20.08±0.00 | 6.37±0.40 | 59.99±0.13 | 0.866±0.070 | 4.217±0.510 | +| dynamic_line_backward | unicycle | regulated_pure_pursuit | 5 | 100% | 13.22±0.98 | 4.80±0.02 | 0.235±0.002 | 0.065±0.027 | 0.111±0.041 | 0.402±0.020 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.08±0.05 | 4.03±0.11 | 55.34±0.06 | 0.224±0.009 | 0.400±0.065 | +| dynamic_line_backward | unicycle | vector_pursuit | 5 | 100% | 14.24±1.07 | 4.78±0.01 | 0.238±0.001 | 0.049±0.024 | 0.081±0.038 | 0.466±0.011 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 19.44±0.50 | 4.04±0.10 | 55.15±0.07 | 0.231±0.011 | 0.364±0.035 | +| dynamic_line_forward | unicycle | dwb | 5 | 100% | 13.68±1.56 | 4.75±0.04 | 0.235±0.002 | 0.031±0.006 | 0.052±0.006 | 0.477±0.019 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.09±0.00 | 9.26±0.46 | 59.82±0.05 | 2.964±0.147 | 4.587±1.017 | +| dynamic_line_forward | unicycle | graceful | 5 | 100% | 12.89±0.84 | 4.79±0.00 | 0.229±0.005 | 0.038±0.009 | 0.075±0.014 | 0.327±0.059 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.09±0.00 | 3.85±0.11 | 55.81±0.17 | 0.169±0.009 | 0.293±0.015 | +| dynamic_line_forward | unicycle | mppi | 10 | 100% | 14.16±1.09 | 4.78±0.01 | 0.234±0.004 | 0.044±0.016 | 0.075±0.022 | 0.590±0.046 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.09±0.01 | 9.27±0.29 | 62.99±0.10 | 3.058±0.107 | 4.306±0.513 | +| dynamic_line_forward | unicycle | proxmpc | 5 | 100% | 14.22±1.32 | 4.72±0.25 | 0.234±0.007 | 0.095±0.051 | 0.168±0.073 | 0.431±0.125 | 0% | 0.782±0.085 | 4.214±0.308 | 10.046±7.690 | 0.0±0.0% | 1.00±0.00 | 6.10±0.47 | 0.0±0.0% | 0.110±0.041 | 20.08±0.00 | 6.30±0.31 | 58.58±0.09 | 0.920±0.092 | 4.369±0.343 | +| dynamic_line_forward | unicycle | proxmpc_pred | 5 | 100% | 14.90±2.67 | 4.88±0.04 | 0.229±0.006 | 0.106±0.033 | 0.174±0.061 | 0.392±0.030 | 0% | 0.681±0.132 | 4.553±0.529 | 13.038±9.219 | 0.0±0.0% | 1.00±0.00 | 5.63±0.26 | 0.0±0.0% | 0.211±0.060 | 20.08±0.00 | 6.28±0.27 | 59.91±0.11 | 0.815±0.118 | 4.729±0.576 | +| dynamic_line_forward | unicycle | regulated_pure_pursuit | 5 | 100% | 14.56±1.21 | 4.81±0.01 | 0.237±0.002 | 0.078±0.011 | 0.134±0.024 | 0.416±0.009 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.10±0.04 | 4.06±0.07 | 55.35±0.02 | 0.225±0.008 | 0.360±0.028 | +| dynamic_line_forward | unicycle | vector_pursuit | 5 | 100% | 12.94±1.76 | 4.72±0.09 | 0.237±0.002 | 0.071±0.010 | 0.123±0.012 | 0.461±0.013 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 19.24±0.34 | 3.95±0.06 | 55.18±0.11 | 0.232±0.014 | 0.385±0.076 | +| dynamic_multi | unicycle | dwb | 5 | 100% | 16.32±0.84 | 4.80±0.02 | 0.237±0.001 | 0.074±0.029 | 0.148±0.053 | -0.091±0.183 | 40% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.08±0.00 | 9.54±0.23 | 59.78±0.06 | 3.094±0.124 | 4.449±0.429 | +| dynamic_multi | unicycle | graceful | 5 | 80% | 17.34±1.39 | 4.21±1.34 | 0.866±1.301 | 0.106±0.084 | 0.185±0.118 | -0.049±0.030 | 80% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 19.96±0.22 | 3.91±0.15 | 55.88±0.16 | 0.171±0.017 | 0.280±0.045 | +| dynamic_multi | unicycle | mppi | 10 | 100% | 17.52±1.23 | 5.06±0.11 | 0.232±0.001 | 0.057±0.036 | 0.113±0.056 | 0.131±0.081 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.07±0.00 | 9.29±0.25 | 63.46±0.66 | 2.992±0.065 | 4.056±0.484 | +| dynamic_multi | unicycle | proxmpc | 5 | 100% | 19.08±1.13 | 4.89±0.09 | 0.234±0.005 | 0.120±0.051 | 0.233±0.079 | 0.109±0.052 | 0% | 2.254±0.294 | 7.130±1.102 | 10.569±1.614 | 0.0±0.0% | 1.00±0.00 | 7.89±0.09 | 0.1±0.2% | 0.224±0.053 | 20.06±0.00 | 9.11±0.66 | 58.57±0.07 | 2.393±0.326 | 7.324±1.162 | +| dynamic_multi | unicycle | proxmpc_pred | 5 | 100% | 18.57±1.19 | 5.49±0.41 | 0.230±0.006 | 0.118±0.055 | 0.222±0.107 | 0.160±0.030 | 0% | 1.509±0.409 | 5.215±1.051 | 11.174±4.461 | 0.0±0.0% | 1.00±0.00 | 7.24±0.30 | 0.0±0.0% | 0.438±0.184 | 20.09±0.06 | 8.08±0.88 | 59.95±0.10 | 1.750±0.543 | 5.386±1.085 | +| dynamic_multi | unicycle | regulated_pure_pursuit | 5 | 100% | 16.78±1.96 | 4.81±0.16 | 0.233±0.003 | 0.097±0.048 | 0.215±0.076 | 0.119±0.029 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 19.75±0.24 | 4.06±0.14 | 55.35±0.10 | 0.235±0.017 | 0.398±0.068 | +| dynamic_multi | unicycle | vector_pursuit | 5 | 100% | 20.16±1.53 | 4.82±0.03 | 0.238±0.001 | 0.074±0.032 | 0.157±0.075 | 0.114±0.074 | 20% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 18.51±0.39 | 4.01±0.10 | 55.22±0.08 | 0.231±0.021 | 0.400±0.063 | +| dynamic_multi_noise | unicycle | dwb | 5 | 100% | 15.26±0.71 | 4.79±0.01 | 0.237±0.002 | 0.049±0.022 | 0.089±0.046 | -0.064±0.179 | 40% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.07±0.01 | 9.69±0.37 | 59.95±0.05 | 3.163±0.154 | 4.851±0.691 | +| dynamic_multi_noise | unicycle | graceful | 5 | 100% | 17.09±0.88 | 4.83±0.03 | 0.227±0.009 | 0.087±0.049 | 0.181±0.075 | -0.016±0.021 | 60% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.07±0.00 | 3.98±0.12 | 55.92±0.11 | 0.177±0.016 | 0.306±0.038 | +| dynamic_multi_noise | unicycle | mppi | 10 | 100% | 17.05±1.66 | 4.93±0.35 | 0.232±0.003 | 0.060±0.038 | 0.120±0.048 | 0.120±0.087 | 10% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.04±0.09 | 9.40±0.22 | 63.24±0.37 | 3.047±0.084 | 4.224±0.475 | +| dynamic_multi_noise | unicycle | proxmpc | 5 | 100% | 19.85±4.58 | 4.92±0.04 | 0.235±0.007 | 0.109±0.032 | 0.222±0.031 | 0.026±0.052 | 20% | 2.339±0.360 | 7.201±1.755 | 10.999±3.126 | 0.0±0.0% | 1.00±0.00 | 8.02±0.26 | 0.1±0.1% | 0.306±0.059 | 20.06±0.01 | 9.22±0.83 | 58.56±0.17 | 2.470±0.335 | 7.234±1.552 | +| dynamic_multi_noise | unicycle | proxmpc_pred | 5 | 100% | 19.50±3.18 | 5.25±0.59 | 0.235±0.007 | 0.105±0.071 | 0.221±0.136 | 0.210±0.030 | 0% | 1.548±0.611 | 5.466±1.057 | 16.855±8.555 | 0.0±0.0% | 1.00±0.00 | 7.31±0.35 | 0.0±0.0% | 0.471±0.197 | 20.07±0.00 | 7.90±0.98 | 59.96±0.06 | 1.704±0.593 | 5.696±1.100 | +| dynamic_multi_noise | unicycle | regulated_pure_pursuit | 5 | 100% | 17.57±1.02 | 4.86±0.02 | 0.235±0.001 | 0.088±0.028 | 0.197±0.043 | 0.140±0.030 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 19.47±0.32 | 4.09±0.18 | 55.34±0.08 | 0.236±0.011 | 0.399±0.022 | +| dynamic_multi_noise | unicycle | vector_pursuit | 5 | 100% | 20.24±1.81 | 4.85±0.02 | 0.237±0.002 | 0.096±0.023 | 0.214±0.065 | 0.151±0.024 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 18.55±0.61 | 3.92±0.09 | 55.10±0.11 | 0.229±0.010 | 0.379±0.049 | +| nav2_open | unicycle | dwb | 5 | 100% | 12.34±1.00 | 4.72±0.08 | 0.237±0.002 | 0.000±0.000 | 0.000±0.000 | n/a | n/a | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.00±0.19 | 8.96±0.53 | 59.67±0.09 | 2.958±0.194 | 4.410±1.108 | +| nav2_open | unicycle | graceful | 5 | 100% | 11.20±1.26 | 4.71±0.13 | 0.224±0.005 | 0.000±0.000 | 0.000±0.000 | n/a | n/a | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.11±0.00 | 3.85±0.19 | 55.63±0.10 | 0.176±0.010 | 0.321±0.020 | +| nav2_open | unicycle | mppi | 5 | 100% | 12.21±0.63 | 4.77±0.01 | 0.228±0.006 | 0.003±0.000 | 0.004±0.000 | n/a | n/a | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.17±0.09 | 9.08±0.14 | 63.33±0.23 | 3.107±0.094 | 4.046±0.400 | +| nav2_open | unicycle | proxmpc | 5 | 100% | 12.26±1.74 | 4.76±0.00 | 0.237±0.001 | 0.000±0.000 | 0.000±0.000 | n/a | n/a | 0.189±0.016 | 0.910±0.082 | 3.085±0.285 | 0.0±0.0% | 1.00±0.00 | 2.86±0.01 | 0.0±0.0% | 0.130±0.000 | 20.09±0.00 | 4.58±0.06 | 58.61±0.14 | 0.297±0.023 | 1.017±0.044 | +| nav2_open | unicycle | proxmpc_pred | 5 | 100% | 13.54±0.89 | 4.76±0.00 | 0.238±0.001 | 0.000±0.000 | 0.000±0.000 | n/a | n/a | 0.188±0.013 | 0.490±0.200 | 2.152±0.328 | 0.0±0.0% | 1.00±0.00 | 1.41±0.03 | 0.0±0.0% | 0.032±0.000 | 20.09±0.00 | 4.71±0.11 | 59.77±0.06 | 0.292±0.015 | 0.596±0.175 | +| nav2_open | unicycle | regulated_pure_pursuit | 5 | 100% | 11.74±0.99 | 4.77±0.00 | 0.235±0.000 | 0.000±0.000 | 0.000±0.000 | n/a | n/a | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.10±0.00 | 3.79±0.04 | 55.19±0.07 | 0.232±0.005 | 0.361±0.040 | +| nav2_open | unicycle | vector_pursuit | 5 | 100% | 13.15±1.09 | 4.76±0.00 | 0.236±0.001 | 0.000±0.000 | 0.000±0.000 | n/a | n/a | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.10±0.01 | 3.90±0.15 | 54.99±0.05 | 0.227±0.015 | 0.380±0.046 | +| static_box | unicycle | dwb | 5 | 100% | 12.82±1.59 | 4.77±0.18 | 0.237±0.002 | 0.259±0.016 | 0.446±0.010 | 0.090±0.011 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.09±0.00 | 9.41±0.23 | 59.84±0.05 | 3.055±0.119 | 4.223±0.548 | +| static_box | unicycle | graceful | 5 | 100% | 10.76±0.92 | 4.84±0.25 | 0.212±0.011 | 0.352±0.007 | 0.567±0.005 | 0.211±0.009 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.09±0.00 | 3.97±0.15 | 55.77±0.04 | 0.170±0.008 | 0.287±0.032 | +| static_box | unicycle | mppi | 10 | 100% | 12.59±1.59 | 4.92±0.04 | 0.233±0.004 | 0.317±0.017 | 0.574±0.006 | 0.208±0.006 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.10±0.00 | 9.25±0.19 | 63.01±0.17 | 3.146±0.081 | 4.222±0.325 | +| static_box | unicycle | proxmpc | 5 | 100% | 14.08±1.09 | 5.03±0.00 | 0.225±0.001 | 0.366±0.013 | 0.737±0.000 | 0.382±0.000 | 0% | 0.932±0.052 | 3.249±0.469 | 5.891±1.168 | 0.0±0.0% | 1.00±0.00 | 7.59±0.04 | 0.0±0.0% | 0.131±0.000 | 20.08±0.00 | 6.34±0.22 | 58.54±0.07 | 1.059±0.059 | 3.410±0.507 | +| static_box | unicycle | proxmpc_pred | 5 | 100% | 13.97±1.37 | 4.99±0.02 | 0.224±0.003 | 0.336±0.016 | 0.649±0.001 | 0.298±0.001 | 0% | 0.848±0.203 | 2.763±0.674 | 4.610±1.391 | 0.0±0.0% | 1.00±0.00 | 7.24±0.28 | 0.0±0.0% | 0.032±0.001 | 20.08±0.00 | 6.40±0.61 | 59.95±0.05 | 0.956±0.202 | 2.876±0.697 | +| static_box | unicycle | regulated_pure_pursuit | 5 | 100% | 11.68±0.55 | 4.94±0.00 | 0.234±0.002 | 0.334±0.009 | 0.566±0.001 | 0.213±0.002 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 20.10±0.00 | 3.97±0.13 | 55.25±0.09 | 0.230±0.009 | 0.400±0.045 | +| static_box | unicycle | vector_pursuit | 5 | 20% | 15.82±0.00 | 2.65±1.14 | 2.413±1.098 | 0.382±0.053 | 0.446±0.057 | 0.247±0.078 | 0% | n/a | n/a | n/a | 0.0±0.0% | 0.00±0.00 | 0.00±0.00 | 0.0±0.0% | 0.000±0.000 | 18.70±0.70 | 4.10±0.09 | 55.27±0.07 | 0.231±0.016 | 0.374±0.058 | +Reading the `slack` column on `static_box`: the mode-b1 spread there +(`1.963±1.203` on the bicycle against `0.490±0.000` on the unicycle) is a +sampling artefact, not a difference between the two models. +Both models relax the keep-out by 2.945 m on control cycle 1 and by 0.000 m from +cycle 2 onward, so a run's recorded maximum depends on whether the metrics node's +diagnostics subscription matched in time to receive that first cycle. +The steady-state peak is 0.490 m for both. +See [section 6.3 of the controller comparison](../doc/controller-comparison-results.md#63-ground-truth-predictive-confirmation-mode-b1). + ## License [Apache-2.0](../LICENSE) - the full text is in [LICENSE](../LICENSE) and diff --git a/prox_mpc_benchmark/config/controllers/proxmpc.yaml b/prox_mpc_benchmark/config/controllers/proxmpc.yaml index 61f13eb..8b105be 100644 --- a/prox_mpc_benchmark/config/controllers/proxmpc.yaml +++ b/prox_mpc_benchmark/config/controllers/proxmpc.yaml @@ -13,16 +13,21 @@ FollowPath: q_theta: 1.0 s_factor: 2.0 r_weight: 0.1 - w_weight: 100.0 + w_weight: 1000.0 max_int_iter_qp: 1500 max_ext_iter_qp: 10000 - max_iter_sqp: 100 + max_iter_sqp: 1 qp_type: false guess: true max_solver_failures: 3 max_obstacles: 4 - safety_margin: 0.1 - robot_radius: 0.22 + # 0.085 with robot_radius 0.235 keeps d_safe at 0.320 m. robot_radius is a + # geometric fact (the footprint's circumscribed radius) and safety_margin is + # the discretionary part, so the correction to the first is absorbed by the + # second rather than widening the keep-out: 0.335 m measured worse on the + # multi-obstacle cells, where a gap needs 2*d_safe to stay feasible. + safety_margin: 0.085 + robot_radius: 0.235 cbf_gamma: 1.0 costmap_cost_threshold: 200 obstacle_cluster_radius: 0.3 diff --git a/prox_mpc_benchmark/config/controllers/proxmpc_pred.yaml b/prox_mpc_benchmark/config/controllers/proxmpc_pred.yaml index b432edf..1d0818e 100644 --- a/prox_mpc_benchmark/config/controllers/proxmpc_pred.yaml +++ b/prox_mpc_benchmark/config/controllers/proxmpc_pred.yaml @@ -7,6 +7,17 @@ # prediction. A confirmed *moving* track is propagated over the horizon and bound # to a dynamic slot; the static box/walls still come from the costmap (hybrid). FollowPath: + # Reverse travel, and the obstacle-aware yield with its hard speed cap. Without + # the cap the yield only lowers a cruise target the obstacle term outweighs, and + # the solver swerves at full speed past a closing mover instead of slowing: + # measured on dynamic_circle over ten runs, this configuration passes behind the + # mover 10/10 against 4/10 and holds three times the worst-case clearance + # (+0.258 m against +0.085 m), with no collisions either way. The cap needs + # somewhere to go, so it is paired with reverse travel; the model pairing below + # sets v_min, which is what lifts the plugin's unguarded-reverse speed cap. + allow_reversing: true + obstacle_yield_band_m: 0.5 + obstacle_yield_caps_speed: true plugin: "prox_mpc_controller::ProxMpcController" np: 20 nc: 20 @@ -22,13 +33,18 @@ FollowPath: w_weight: 1000.0 max_int_iter_qp: 1500 max_ext_iter_qp: 10000 - max_iter_sqp: 100 + max_iter_sqp: 1 qp_type: false guess: true max_solver_failures: 3 max_obstacles: 4 - safety_margin: 0.1 - robot_radius: 0.22 + # 0.085 with robot_radius 0.235 keeps d_safe at 0.320 m. robot_radius is a + # geometric fact (the footprint's circumscribed radius) and safety_margin is + # the discretionary part, so the correction to the first is absorbed by the + # second rather than widening the keep-out: 0.335 m measured worse on the + # multi-obstacle cells, where a gap needs 2*d_safe to stay feasible. + safety_margin: 0.085 + robot_radius: 0.235 cbf_gamma: 1.0 # 253 (inscribed + lethal only, not the reactive preset's 200): the static # fill adds robot_radius + safety_margin around every cell it ingests, so diff --git a/prox_mpc_benchmark/config/robots/ackermann.yaml b/prox_mpc_benchmark/config/robots/ackermann.yaml index 09cb660..5fdeaa3 100644 --- a/prox_mpc_benchmark/config/robots/ackermann.yaml +++ b/prox_mpc_benchmark/config/robots/ackermann.yaml @@ -1,11 +1,11 @@ -# Ackermann (car-like) robot paired with the ProxMPC Bicycle model. +# Ackermann (car-like) robot paired with a ProxMPC bicycle model. # Mode (a) spawns the SDF in models/ackermann_robot and bridges a body Twist to # Ackermann steering via ros_gz; mode (b2) gives the kinematic plant a bicycle # integrator. For the standalone mode (b1) only `model` is relevant. robot: name: ackermann - model: bicycle # prox_mpc Bicycle (4-state [x, y, theta, delta]) - model_plugin: prox_mpc_core/Bicycle + model: bicycle # 4-state [x, y, theta, delta] + model_plugin: prox_mpc_core/BicycleFrontAxle drive: ackermann wheelbase: 1.0 # L [m]; must match the SDF and model_params.L robot_radius: 0.5 diff --git a/prox_mpc_benchmark/config/scenarios/dynamic_circle.yaml b/prox_mpc_benchmark/config/scenarios/dynamic_circle.yaml index 12c68db..04b2e37 100644 --- a/prox_mpc_benchmark/config/scenarios/dynamic_circle.yaml +++ b/prox_mpc_benchmark/config/scenarios/dynamic_circle.yaml @@ -13,5 +13,9 @@ scenario: # center / radius / speed (sign = ccw/cw). Orbits around (1, 0) crossing the path. - {type: dynamic, motion: circle, center: {x: 1.0, y: 0.0}, radius: 0.8, speed: 0.5, clearance: 0.45} models: [unicycle, bicycle] - controllers: [proxmpc, dwb, mppi, regulated_pure_pursuit, graceful, vector_pursuit] # cross-controller set (b2) + controllers: [proxmpc_pred, proxmpc, dwb, mppi, regulated_pure_pursuit, graceful, vector_pursuit] # cross-controller set (b2) run: {repeats: 5, timeout_s: 60, seed: 0} + # Recorded clip length (record_scenarios.py). The orbit takes the robot about + # 16 s to get round, longer than the 20 s default leaves once a controller + # yields to it, so this cell's clip runs longer. + video: {duration_s: 25.0} diff --git a/prox_mpc_benchmark/config/scenarios/dynamic_line_backward.yaml b/prox_mpc_benchmark/config/scenarios/dynamic_line_backward.yaml index a8d4ecc..d1446d5 100644 --- a/prox_mpc_benchmark/config/scenarios/dynamic_line_backward.yaml +++ b/prox_mpc_benchmark/config/scenarios/dynamic_line_backward.yaml @@ -13,5 +13,5 @@ scenario: # Patrol from (0,-2) to (0,2); -speed = backward leg first (starts at "to"). Crosses y=0 at x=0. - {type: dynamic, motion: line, from: {x: 0.0, y: -2.0}, to: {x: 0.0, y: 2.0}, speed: -0.6, clearance: 0.45} models: [unicycle, bicycle] - controllers: [proxmpc, dwb, mppi, regulated_pure_pursuit, graceful, vector_pursuit] # cross-controller set (b2) + controllers: [proxmpc_pred, proxmpc, dwb, mppi, regulated_pure_pursuit, graceful, vector_pursuit] # cross-controller set (b2) run: {repeats: 5, timeout_s: 60, seed: 0} diff --git a/prox_mpc_benchmark/config/scenarios/dynamic_line_forward.yaml b/prox_mpc_benchmark/config/scenarios/dynamic_line_forward.yaml index e85b23e..43c25c0 100644 --- a/prox_mpc_benchmark/config/scenarios/dynamic_line_forward.yaml +++ b/prox_mpc_benchmark/config/scenarios/dynamic_line_forward.yaml @@ -13,5 +13,5 @@ scenario: # Patrol from (0,-2) to (0,2) and back; +speed = forward leg first. Crosses y=0 at x=0. - {type: dynamic, motion: line, from: {x: 0.0, y: -2.0}, to: {x: 0.0, y: 2.0}, speed: 0.6, clearance: 0.45} models: [unicycle, bicycle] - controllers: [proxmpc, dwb, mppi, regulated_pure_pursuit, graceful, vector_pursuit] # cross-controller set (b2) + controllers: [proxmpc_pred, proxmpc, dwb, mppi, regulated_pure_pursuit, graceful, vector_pursuit] # cross-controller set (b2) run: {repeats: 5, timeout_s: 60, seed: 0} diff --git a/prox_mpc_benchmark/config/scenarios/nav2_open.yaml b/prox_mpc_benchmark/config/scenarios/nav2_open.yaml index bb8ec14..a48a750 100644 --- a/prox_mpc_benchmark/config/scenarios/nav2_open.yaml +++ b/prox_mpc_benchmark/config/scenarios/nav2_open.yaml @@ -13,5 +13,5 @@ scenario: - {x: 2.5, y: 0.0, yaw: 0.0} obstacles: [] models: [unicycle] # diff-drive waffle / Unicycle - controllers: [proxmpc, dwb, mppi, regulated_pure_pursuit, graceful, vector_pursuit] # cross-controller set + controllers: [proxmpc_pred, proxmpc, dwb, mppi, regulated_pure_pursuit, graceful, vector_pursuit] # cross-controller set run: {repeats: 5, timeout_s: 60, seed: 0} diff --git a/prox_mpc_benchmark/config/scenarios/static_box.yaml b/prox_mpc_benchmark/config/scenarios/static_box.yaml index 202a08f..d7c56b7 100644 --- a/prox_mpc_benchmark/config/scenarios/static_box.yaml +++ b/prox_mpc_benchmark/config/scenarios/static_box.yaml @@ -16,5 +16,5 @@ scenario: # cleanly (a straight-plan-through setup stalls a soft-constraint avoider here). - {type: static, shape: box, pose: {x: 0.0, y: 0.0}, size: {x: 0.25, y: 0.25, z: 0.5}, clearance: 0.45} models: [unicycle, bicycle] - controllers: [proxmpc, dwb, mppi, regulated_pure_pursuit, graceful, vector_pursuit] # cross-controller set (b2) + controllers: [proxmpc_pred, proxmpc, dwb, mppi, regulated_pure_pursuit, graceful, vector_pursuit] # cross-controller set (b2) run: {repeats: 5, timeout_s: 60, seed: 0} diff --git a/prox_mpc_benchmark/doc/media/dynamic_circle_controllers.gif b/prox_mpc_benchmark/doc/media/dynamic_circle_controllers.gif index 11c10d0..db8e736 100644 Binary files a/prox_mpc_benchmark/doc/media/dynamic_circle_controllers.gif and b/prox_mpc_benchmark/doc/media/dynamic_circle_controllers.gif differ diff --git a/prox_mpc_benchmark/doc/media/dynamic_circle_controllers.mp4 b/prox_mpc_benchmark/doc/media/dynamic_circle_controllers.mp4 index 5b2648c..e040d88 100644 Binary files a/prox_mpc_benchmark/doc/media/dynamic_circle_controllers.mp4 and b/prox_mpc_benchmark/doc/media/dynamic_circle_controllers.mp4 differ diff --git a/prox_mpc_benchmark/doc/media/dynamic_line_forward_controllers.gif b/prox_mpc_benchmark/doc/media/dynamic_line_forward_controllers.gif index 2d79167..e703578 100644 Binary files a/prox_mpc_benchmark/doc/media/dynamic_line_forward_controllers.gif and b/prox_mpc_benchmark/doc/media/dynamic_line_forward_controllers.gif differ diff --git a/prox_mpc_benchmark/doc/media/dynamic_line_forward_controllers.mp4 b/prox_mpc_benchmark/doc/media/dynamic_line_forward_controllers.mp4 index 0560a6b..92b382d 100644 Binary files a/prox_mpc_benchmark/doc/media/dynamic_line_forward_controllers.mp4 and b/prox_mpc_benchmark/doc/media/dynamic_line_forward_controllers.mp4 differ diff --git a/prox_mpc_benchmark/doc/media/nav2_open_controllers.gif b/prox_mpc_benchmark/doc/media/nav2_open_controllers.gif index 83abf92..7e7654b 100644 Binary files a/prox_mpc_benchmark/doc/media/nav2_open_controllers.gif and b/prox_mpc_benchmark/doc/media/nav2_open_controllers.gif differ diff --git a/prox_mpc_benchmark/doc/media/nav2_open_controllers.mp4 b/prox_mpc_benchmark/doc/media/nav2_open_controllers.mp4 index 05ba793..e9131b1 100644 Binary files a/prox_mpc_benchmark/doc/media/nav2_open_controllers.mp4 and b/prox_mpc_benchmark/doc/media/nav2_open_controllers.mp4 differ diff --git a/prox_mpc_benchmark/doc/media/static_box_controllers.gif b/prox_mpc_benchmark/doc/media/static_box_controllers.gif index 24203d0..b349886 100644 Binary files a/prox_mpc_benchmark/doc/media/static_box_controllers.gif and b/prox_mpc_benchmark/doc/media/static_box_controllers.gif differ diff --git a/prox_mpc_benchmark/doc/media/static_box_controllers.mp4 b/prox_mpc_benchmark/doc/media/static_box_controllers.mp4 index 03bef13..8d912cc 100644 Binary files a/prox_mpc_benchmark/doc/media/static_box_controllers.mp4 and b/prox_mpc_benchmark/doc/media/static_box_controllers.mp4 differ diff --git a/prox_mpc_benchmark/doc/videos.md b/prox_mpc_benchmark/doc/videos.md index 44f4523..4017d30 100644 --- a/prox_mpc_benchmark/doc/videos.md +++ b/prox_mpc_benchmark/doc/videos.md @@ -135,10 +135,18 @@ ros2 run prox_mpc_benchmark record_scenarios.py \ ``` For each scenario the recorder waits `--warmup` seconds for lifecycle activation, -starts a fixed-length ffmpeg x11grab recording, sends the scenario goal after -`--goal-delay` seconds, waits for ffmpeg to reach its `--duration`, then tears the -whole process tree down with a process-group `SIGINT` (graceful) escalating to -`SIGKILL`. +starts an ffmpeg x11grab capture, sends the scenario goal after `--goal-delay` +seconds, waits for the capture to finish, then tears the whole process tree down +with a process-group `SIGINT` (graceful) escalating to `SIGKILL`. + +The capture runs longer than the clip: it has to cover the goal delay, the few +seconds the stack takes from goal to first motion, and a spuriously aborted goal's +retry. The clip is then cut to open 0.3 s before the robot first moves, which the +recorder reads from `/odom` - the same event, at the same 1 mm threshold, that +releases the scenario's obstacles. A clip therefore opens on the scene coming alive +rather than on a frozen robot, however long the stack took to start. If the robot +never moves, the recorder keeps the head of the capture and prints a warning, so a +failed navigation is not mistaken for a good clip. The exact ffmpeg command is printed for every clip. One scenario failing does not abort the rest; the exit code is non-zero if any scenario failed. @@ -217,13 +225,13 @@ All artifacts land under `results/videos/` (gitignored): | `--scenarios` | `nav2_open,static_box,dynamic_line_forward,dynamic_circle` | scenario basenames to record | | `--controller` | `proxmpc_pred` | controller preset injected into `FollowPath` | | `--robot` | `waffle` | robot shown (URDF + model pairing) | -| `--duration` | `20` | clip length in seconds (self-terminating via `-t`) | +| `--duration` | `20` | clip length in seconds; a scenario's `video.duration_s` overrides it (`dynamic_circle` sets 25) | | `--resolution` | `1920x1080` | grab size `WxH` | | `--offset` | `0,0` | grab top-left origin `x,y` -> x11grab input `:0.0+x,y` | | `--display` | `$DISPLAY` or `:0` | X display to capture and render on | | `--framerate` | `30` | capture frame rate | | `--warmup` | `14` | activation wait before recording starts [s] | -| `--goal-delay` | `3` | wait after recording starts before the goal is sent [s] | +| `--goal-delay` | `3` | wait after the capture starts before the goal is sent [s]; the clip is cut at first motion, so this is not dead time in the clip | | `--timeout` | `55` | goal timeout passed to `goal_sender.py` [s] | | `--out-dir` | `results/videos` | clip output directory | @@ -250,8 +258,10 @@ All artifacts land under `results/videos/` (gitignored): region; when absent the recorder simply grabs the full region. - ffmpeg `drawtext` requires an ffmpeg built with libfreetype (the stock Ubuntu `ffmpeg` package qualifies); the label filter fails otherwise. -- Clip length is fixed by `--duration`, so the four clips stay length-synced and - xstack combines them cleanly. +- Clip length is fixed per scenario (`--duration`, or the scenario's own + `video.duration_s`), and every clip opens at first motion, so the four + controllers of one scenario stay length-synced and start together, and xstack + combines them cleanly. ## License diff --git a/prox_mpc_benchmark/package.xml b/prox_mpc_benchmark/package.xml index ac3bfc1..7798967 100644 --- a/prox_mpc_benchmark/package.xml +++ b/prox_mpc_benchmark/package.xml @@ -2,7 +2,7 @@ prox_mpc_benchmark - 1.0.0 + 2.0.0 Scenario-driven benchmarking harness for the ProxMPC stack: a controller- agnostic C++ live metrics node (cross-track / goal error + solver-diagnostics @@ -88,6 +88,7 @@ ffmpeg ament_lint_auto + ament_cmake_pytest ament_lint_common ament_cmake_gtest diff --git a/prox_mpc_benchmark/scripts/aggregate.py b/prox_mpc_benchmark/scripts/aggregate.py index b04397b..d404cd8 100755 --- a/prox_mpc_benchmark/scripts/aggregate.py +++ b/prox_mpc_benchmark/scripts/aggregate.py @@ -35,7 +35,7 @@ ('mean_qp_iters_ext', 'qp_ext', '', 'ms'), ('infeasible_rate', 'infeas', '', 'pct'), ('max_obstacle_slack_m', 'slack', 'm', 'ms3'), - # Embedded-resource metrics (mode b2; n/a where the run did not sample a process). + # Process-resource metrics (mode b2; n/a where the run did not sample a process). ('control_rate_hz', 'rate', 'Hz', 'ms'), ('cpu_mean_pct', 'cpu', '%', 'ms'), ('rss_peak_mb', 'rss', 'MB', 'ms'), @@ -54,10 +54,10 @@ def fmt(kind, vals): if kind == 'rate': return f'{mean * 100:.0f}%' if kind == 'pct': - return f'{mean * 100:.1f}±{sd * 100:.1f}%' + return f'{mean * 100:.1f}±{sd * 100:.1f}%' # ascii-ok if kind == 'ms3': - return f'{mean:.3f}±{sd:.3f}' - return f'{mean:.2f}±{sd:.2f}' + return f'{mean:.3f}±{sd:.3f}' # ascii-ok + return f'{mean:.2f}±{sd:.2f}' # ascii-ok def group_key(rec): @@ -124,7 +124,7 @@ def main(): tables = build_tables(records) block = (f'{START}\n\n' f'*Auto-generated by `aggregate.py` from `results/scenarios.json` ' - f'({len(records)} runs). Values are mean±std (population) over repeats - ' + f'({len(records)} runs). Values are mean±std (population) over repeats - ' # ascii-ok f'the precision signal. Not committed.*\n\n' f'{tables}\n{END}') diff --git a/prox_mpc_benchmark/scripts/compute_metrics.py b/prox_mpc_benchmark/scripts/compute_metrics.py index 153d7d7..b381ae3 100755 --- a/prox_mpc_benchmark/scripts/compute_metrics.py +++ b/prox_mpc_benchmark/scripts/compute_metrics.py @@ -68,6 +68,11 @@ def main(): solve, sqp, qp = [], [], [] miss = infeas = diag_n = solve_dropped = 0 + # Retain the status histogram and the per-cycle iteration maxima, not only + # the means: a cycle that exhausts the QP budget and then succeeds on an SQP + # retry is averaged away and reported as converged, so the worst latency + # event in a run leaves no trace in infeasible_rate. + status_counts = {} slack_max = 0.0 ct, gd = [], [] SOLVED = 0 @@ -86,6 +91,7 @@ def main(): qp.append(msg.qp_iters_ext) miss += int(msg.deadline_missed) infeas += int(msg.status != SOLVED) + status_counts[int(msg.status)] = status_counts.get(int(msg.status), 0) + 1 slack_max = max(slack_max, msg.max_obstacle_slack) elif tn == 'Float64' and topic == args.ct_topic: ct.append(msg.data) @@ -110,6 +116,9 @@ def main(): 'mean_sqp_iters': st.mean(sqp) if sqp else 0.0, 'mean_qp_iters_ext': st.mean(qp) if qp else 0.0, 'infeasible_rate': (infeas / diag_n) if diag_n else 0.0, + 'max_sqp_iters': max(sqp) if sqp else None, + 'max_qp_iters_ext': max(qp) if qp else None, + 'status_counts': status_counts, 'max_obstacle_slack_m': slack_max, 'num_diag_samples': diag_n, 'status': 'ok', diff --git a/prox_mpc_benchmark/scripts/record_scenarios.py b/prox_mpc_benchmark/scripts/record_scenarios.py index 2cd5ba3..3d649a8 100755 --- a/prox_mpc_benchmark/scripts/record_scenarios.py +++ b/prox_mpc_benchmark/scripts/record_scenarios.py @@ -15,9 +15,15 @@ The b2 stack runs on wall/system time (no /clock publisher), so RViz and the robot_state_publisher use use_sim_time:=false - the opposite of the Gazebo demo. -ffmpeg is the recorder. Clips are fixed-duration, so the four are length-synced and -combine cleanly into a 2x2 grid (see combine_grid.sh). Nothing is committed: -results/ is gitignored. The environment must already be sourced (see init.sh). +ffmpeg is the recorder. It captures a raw window long enough to cover the stack's +start-up latency and a goal retry, and each clip is then cut to start at the moment +the robot first moves - the same event that releases the b2 obstacles, read from +odom - so a clip opens on the scene coming alive rather than on seconds of a +frozen robot. Clips are fixed-duration per scenario (a scenario may lengthen its +own with video.duration_s), so the four controllers of one scenario are +length-synced and combine cleanly into a 2x2 grid (see combine_grid.sh). Nothing +is committed: results/ is gitignored. The environment must already be sourced +(see init.sh). """ import argparse @@ -29,6 +35,7 @@ import shutil import subprocess import sys +import threading import time from ament_index_python.packages import get_package_share_directory @@ -56,6 +63,19 @@ GOAL_ATTEMPTS = 4 GOAL_ABORT_PROBE_S = 4.0 +# A clip opens this long before the robot's first motion, so the robot is seen at +# rest for an instant rather than already moving on the first frame. +PREROLL_S = 0.3 + +# Raw capture beyond the goal delay and the clip itself: the stack takes a few +# seconds from goal to first motion, and a spuriously aborted goal is retried after +# GOAL_ABORT_PROBE_S, so this covers the latency plus one retry. +CAPTURE_MARGIN_S = 12.0 + +# The robot counts as moving once it leaves its first pose by this much - the same +# motion_eps the scan simulator and the obstacle publishers gate their clocks on. +MOTION_EPS_M = 1.0e-3 + def load_run_nav2(): """ @@ -124,6 +144,82 @@ def write_marker_params(path: Path, rn, scn): yaml.safe_dump(doc, fh, default_flow_style=None, sort_keys=False) +def clip_duration(scn, default): + """Clip length [s] for a scenario: its own video.duration_s, else the default.""" + video = scn.get('video') or {} + return float(video.get('duration_s', default)) + + +def trim_offset(capture_start, motion_start, preroll): + """ + Seconds into the raw capture at which the clip should begin. + + Both times are on one monotonic clock. None when the robot never moved, which + leaves the caller to decide what to keep; otherwise the moment of first motion + less the preroll, clamped to the start of the capture. + """ + if motion_start is None: + return None + return max(0.0, motion_start - capture_start - preroll) + + +def build_trim_cmd(raw_path, offset, duration, out_path): + """Cut `duration` seconds from `offset` into the raw capture, re-encoded to be exact.""" + return [ + 'ffmpeg', '-y', '-nostdin', '-v', 'error', + '-i', str(raw_path), + '-ss', f'{offset:.3f}', + '-t', f'{duration:.3f}', + '-c:v', 'libx264', + '-preset', 'veryfast', + '-pix_fmt', 'yuv420p', + '-movflags', '+faststart', + str(out_path), + ] + + +class MotionWatch: + """ + Record the monotonic time of the robot's first motion, from odom. + + The b2 obstacles start on this same event, so it is the instant the scene comes + alive. A background executor spins the subscription while the scenario runs. + rclpy is imported here rather than at module level so the pure helpers above + stay importable without a ROS context. + """ + + def __init__(self, topic='odom', eps=MOTION_EPS_M): + import rclpy + from rclpy.executors import SingleThreadedExecutor + from nav_msgs.msg import Odometry + + if not rclpy.ok(): + rclpy.init() + self.motion_start = None + self._eps = eps + self._first = None + self._node = rclpy.create_node('record_scenarios_motion_watch') + self._node.create_subscription(Odometry, topic, self._on_odom, 20) + self._executor = SingleThreadedExecutor() + self._executor.add_node(self._node) + self._thread = threading.Thread(target=self._executor.spin, daemon=True) + self._thread.start() + + def _on_odom(self, msg): + p = msg.pose.pose.position + if self._first is None: + self._first = (p.x, p.y) + elif self.motion_start is None and \ + ((p.x - self._first[0]) ** 2 + (p.y - self._first[1]) ** 2) ** 0.5 > self._eps: + self.motion_start = time.monotonic() + + def close(self): + """Stop spinning and release the node.""" + self._executor.shutdown() + self._thread.join(timeout=5.0) + self._node.destroy_node() + + def build_ffmpeg_cmd(display, offset, resolution, framerate, duration, out_path): """Build the x11grab record command; -t makes the clip self-terminating.""" ox, oy = (v.strip() for v in offset.split(',')) @@ -185,6 +281,9 @@ def record_one(scenario, args, rn, out_dir, logs_dir, description): write_marker_params(marker_params, rn, scn) out_path = out_dir / f'{scenario}.mp4' + raw_path = logs_dir / f'{scenario}.raw.mp4' + duration = clip_duration(scn, args.duration) + raw_len = args.goal_delay + CAPTURE_MARGIN_S + duration # A recording-only RViz profile: filled to the display, docks and the Nav2 # panel hidden, camera framing the corridor. Resolve the installed copy first, # falling back to the source tree so it works before a rebuild (the script is @@ -235,13 +334,16 @@ def launch(role, cmd): 'nice', '-n', '19', 'rviz2', '-d', str(rviz_cfg), '--ros-args', '-p', 'use_sim_time:=false']) + watch = MotionWatch() + capture_start = None try: time.sleep(args.warmup) # let the lifecycle manager activate the servers with open(logs_dir / f'{scenario}.xdotool.log', 'w') as xlog: place_rviz_window(args.offset, args.resolution, xlog) cmd = build_ffmpeg_cmd(args.display, args.offset, args.resolution, - args.framerate, args.duration, out_path) + args.framerate, raw_len, raw_path) print(f'[record] {scenario} ffmpeg: {shlex.join(cmd)}', flush=True) + capture_start = time.monotonic() ffmpeg = launch('ffmpeg', cmd) time.sleep(args.goal_delay) goal_cmd = ['ros2', 'run', PKG, 'goal_sender.py', '--points', points, @@ -259,7 +361,7 @@ def launch(role, cmd): f'{attempt + 1}/{GOAL_ATTEMPTS}); retrying', flush=True) time.sleep(1.0) try: - ffmpeg.wait(timeout=args.duration + 30.0) + ffmpeg.wait(timeout=raw_len + 30.0) except subprocess.TimeoutExpired: pass finally: @@ -277,7 +379,27 @@ def launch(role, cmd): ['pkill', '-9', '-f', 'lib/(nav2_|prox_mpc_benchmark|prox_mpc_obstacle_tracker)/[a-z_]+ --ros-args'], check=False) + watch.close() time.sleep(INTER_SCENARIO_SETTLE_S) + + # Cut the clip to open as the robot first moves. A robot that never moved has + # nothing worth trimming to; keep the head of the capture and say so, so a + # failed navigation is not mistaken for a good clip. + offset = None if capture_start is None else \ + trim_offset(capture_start, watch.motion_start, PREROLL_S) + if offset is None: + print(f'[record] {scenario} WARNING: the robot never moved; keeping the first ' + f'{duration:.0f} s of the capture untrimmed', flush=True) + offset = 0.0 + elif offset + duration > raw_len: + print(f'[record] {scenario} WARNING: motion began {offset:.1f} s in, so the clip ' + f'runs past the {raw_len:.0f} s capture and will be short', flush=True) + with open(logs_dir / f'{scenario}.trim.log', 'w') as tlog: + subprocess.run(build_trim_cmd(raw_path, offset, duration, out_path), + stdout=tlog, stderr=subprocess.STDOUT, check=True) + raw_path.unlink(missing_ok=True) + print(f'[record] {scenario} clip: {duration:.0f} s from {offset:.1f} s into the capture', + flush=True) return out_path @@ -287,7 +409,8 @@ def main() -> int: ap.add_argument('--scenarios', default=DEFAULT_SCENARIOS) ap.add_argument('--controller', default='proxmpc_pred') ap.add_argument('--robot', default='waffle') - ap.add_argument('--duration', type=float, default=20.0, help='clip length [s]') + ap.add_argument('--duration', type=float, default=20.0, + help="clip length [s]; a scenario's video.duration_s overrides it") ap.add_argument('--resolution', default='1920x1080', help='grab size WxH') ap.add_argument('--offset', default='0,0', help="grab top-left origin 'x,y' -> x11grab input :0.0+x,y") @@ -296,7 +419,8 @@ def main() -> int: ap.add_argument('--warmup', type=float, default=14.0, help='stack activation wait before recording [s]') ap.add_argument('--goal-delay', type=float, default=3.0, - help='wait after recording starts before sending the goal [s]') + help='wait after recording starts before sending the goal [s]; ' + 'the clip is cut at first motion, so this is not dead time') ap.add_argument('--timeout', type=float, default=55.0, help='goal timeout [s]') ap.add_argument('--out-dir', default='', help='clip output dir') args = ap.parse_args() @@ -328,6 +452,12 @@ def main() -> int: failed.append(scenario) print(f'[record] {scenario} FAILED: {exc}', flush=True) + try: + import rclpy + if rclpy.ok(): + rclpy.shutdown() + except ImportError: + pass print(f'[record] done: {len(scenarios) - len(failed)}/{len(scenarios)} clips ' f'in {out_dir}', flush=True) if failed: diff --git a/prox_mpc_benchmark/scripts/resource_sampler.py b/prox_mpc_benchmark/scripts/resource_sampler.py index c3eaa36..59dec63 100755 --- a/prox_mpc_benchmark/scripts/resource_sampler.py +++ b/prox_mpc_benchmark/scripts/resource_sampler.py @@ -5,8 +5,8 @@ """ Sample a controller process's CPU / RAM and the achieved control rate. -For the mode (b2) cross-controller comparison this measures the embedded-relevant -resource cost of one Nav2 controller: the CPU% and resident memory (RSS) of its +For the mode (b2) cross-controller comparison this measures the runtime resource +cost of one Nav2 controller: the CPU% and resident memory (RSS) of its `controller_server` process (read from /proc), and the achieved control frequency (the rate of commands on /cmd_vel while the robot is moving). Every controller runs in its own controller_server with identical surrounding config, so the differences diff --git a/prox_mpc_benchmark/scripts/run_nav2.py b/prox_mpc_benchmark/scripts/run_nav2.py index c189c18..e213649 100755 --- a/prox_mpc_benchmark/scripts/run_nav2.py +++ b/prox_mpc_benchmark/scripts/run_nav2.py @@ -202,6 +202,58 @@ def terminate(proc): pass +def record_from_disk(summary_json): + """ + Assemble one index record from a cell's files on disk. + + Merges the run summary with the process resource sampling and, for the + predictive controller, the tracker's own sampling. + """ + rec = json.load(open(summary_json)) + rec['status'] = 'ok' + stem = str(summary_json)[:-len('.json')] + resource_json = Path(stem + '.resource.json') + if resource_json.exists(): + try: + rec.update(json.load(open(resource_json))) + except (json.JSONDecodeError, OSError): + pass + tracker_resource_json = Path(stem + '.tracker_resource.json') + if tracker_resource_json.exists(): + try: + tr = json.load(open(tracker_resource_json)) + rec['tracker_cpu_mean_pct'] = tr.get('cpu_mean_pct') + rec['tracker_cpu_peak_pct'] = tr.get('cpu_peak_pct') + rec['tracker_rss_peak_mb'] = tr.get('rss_peak_mb') + except (json.JSONDecodeError, OSError): + pass + return rec + + +def rebuild_index(results_dir): + """ + Derive the run index from the per-run files on disk. + + runs/ is the source of truth and scenarios.json is a view over it, so + deriving it fresh keeps the two from diverging: a directory assembled by + hand, or copied without its index, aggregates to what it actually + contains rather than to whatever a stale index happened to hold. + """ + runs_dir = Path(results_dir) / 'runs' + if not runs_dir.is_dir(): + return [] + index = [] + for summary_json in sorted(runs_dir.glob('*.json')): + if (summary_json.name.endswith('.resource.json') or + summary_json.name.endswith('.tracker_resource.json')): + continue + try: + index.append(record_from_disk(summary_json)) + except (json.JSONDecodeError, OSError): + continue + return index + + def run_cell(scn, controller, repeat, control, results_dir, robot, map_yaml, warmup_s, timeout_s, oracle=False): runs_dir = results_dir / 'runs' @@ -251,7 +303,7 @@ def run_cell(scn, controller, repeat, control, results_dir, robot, map_yaml, metrics = goal_proc = sampler = tracker_sampler = None try: time.sleep(warmup_s) # let the lifecycle manager activate the servers - # Instrument the controller_server process for the embedded-resource metrics. + # Instrument the controller_server process for the process-resource metrics. pid = None for _ in range(10): pid = find_controller_pid() @@ -314,22 +366,7 @@ def run_cell(scn, controller, repeat, control, results_dir, robot, map_yaml, time.sleep(3.0) # let DDS discovery settle before the next cell if summary_json.exists(): - rec = json.load(open(summary_json)) - rec['status'] = 'ok' - if resource_json.exists(): - try: - rec.update(json.load(open(resource_json))) - except (json.JSONDecodeError, OSError): - pass - if predictive and tracker_resource_json.exists(): - try: - tr = json.load(open(tracker_resource_json)) - rec['tracker_cpu_mean_pct'] = tr.get('cpu_mean_pct') - rec['tracker_cpu_peak_pct'] = tr.get('cpu_peak_pct') - rec['tracker_rss_peak_mb'] = tr.get('rss_peak_mb') - except (json.JSONDecodeError, OSError): - pass - return rec + return record_from_disk(summary_json) return { 'scenario': scn['name'], 'model': scn.get('models', ['unicycle'])[0], 'mode': 'b2', 'controller': controller, 'repeat': repeat, @@ -368,12 +405,7 @@ def main() -> int: results_dir.mkdir(parents=True, exist_ok=True) index_path = results_dir / 'scenarios.json' - index = [] - if index_path.exists(): - try: - index = json.load(open(index_path)) - except json.JSONDecodeError: - index = [] + index = rebuild_index(results_dir) rep_indices = ([int(x) for x in args.repeat_indices.split(',') if x != ''] if args.repeat_indices else list(range(repeats))) diff --git a/prox_mpc_benchmark/src/metrics_node.cpp b/prox_mpc_benchmark/src/metrics_node.cpp index 849b0fd..4e1095a 100644 --- a/prox_mpc_benchmark/src/metrics_node.cpp +++ b/prox_mpc_benchmark/src/metrics_node.cpp @@ -16,10 +16,12 @@ #include #include #include +#include #include #include #include #include +#include #include #include #include @@ -200,6 +202,18 @@ class MetricsNode : public rclcpp::Node os << " \"mean_sqp_iters\": " << num(mean_sqp) << ",\n"; os << " \"mean_qp_iters_ext\": " << num(mean_qp) << ",\n"; os << " \"infeasible_rate\": " << num(infeas_rate) << ",\n"; + os << " \"max_sqp_iters\": " << sqp_max_ << ",\n"; + os << " \"max_qp_iters_ext\": " << qp_ext_max_ << ",\n"; + os << " \"status_counts\": {"; + { + bool first = true; + for (const auto & [code, count] : status_counts_) { + if (!first) {os << ", ";} + os << "\"" << static_cast(code) << "\": " << count; + first = false; + } + } + os << "},\n"; os << " \"max_obstacle_slack_m\": " << num(slack_max_) << ",\n"; os << " \"recoveries\": " << recoveries_ << ",\n"; os << " \"num_pose_samples\": " << pose_samples_ << ",\n"; @@ -250,6 +264,13 @@ class MetricsNode : public rclcpp::Node } sqp_sum_ += static_cast(msg->sqp_iters); qp_ext_sum_ += static_cast(msg->qp_iters_ext); + /* Retain the per-cycle maxima and the status histogram, not only the means: + * a single cycle that exhausts the QP iteration budget and then succeeds on + * an SQP retry is averaged away by the means and reported as converged, so + * the worst latency event in a run leaves no trace in infeasible_rate. */ + sqp_max_ = std::max(sqp_max_, static_cast(msg->sqp_iters)); + qp_ext_max_ = std::max(qp_ext_max_, static_cast(msg->qp_iters_ext)); + status_counts_[msg->status]++; if (msg->deadline_missed) {deadline_miss_++;} if (msg->status != prox_mpc_msgs::msg::SolverDiagnostics::STATUS_SOLVED) {infeasible_++;} slack_max_ = std::max(slack_max_, msg->max_obstacle_slack); @@ -380,6 +401,8 @@ class MetricsNode : public rclcpp::Node // Diagnostics accumulators. std::size_t diag_count_{0}, deadline_miss_{0}, infeasible_{0}; + std::size_t sqp_max_{0}, qp_ext_max_{0}; + std::map status_counts_; double sqp_sum_{0.0}, qp_ext_sum_{0.0}, slack_max_{0.0}; std::vector solve_ms_; std::size_t nonfinite_solve_{0}; diff --git a/prox_mpc_benchmark/test/test_record_scenarios.py b/prox_mpc_benchmark/test/test_record_scenarios.py new file mode 100644 index 0000000..b588c0a --- /dev/null +++ b/prox_mpc_benchmark/test/test_record_scenarios.py @@ -0,0 +1,63 @@ +# Copyright 2026 Simone Contorno +# SPDX-License-Identifier: Apache-2.0 + +"""Unit tests for record_scenarios.py's clip timing (no ROS graph, no display).""" + +import importlib.util +from pathlib import Path + +import yaml + +SCRIPTS = Path(__file__).resolve().parents[1] / 'scripts' +SCENARIOS = Path(__file__).resolve().parents[1] / 'config' / 'scenarios' + + +def _load(): + spec = importlib.util.spec_from_file_location( + 'record_scenarios', SCRIPTS / 'record_scenarios.py') + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +rs = _load() + + +def test_clip_opens_a_preroll_before_first_motion(): + # Capture started at t = 100 s and the robot moved at 106.5 s: the clip opens + # 6.2 s in, so the robot is seen at rest for the 0.3 s preroll and no longer. + assert abs(rs.trim_offset(100.0, 106.5, 0.3) - 6.2) < 1e-9 + + +def test_clip_never_opens_before_the_capture(): + # Motion before the capture began (or within the preroll of it) clamps to zero. + assert rs.trim_offset(100.0, 100.1, 0.3) == 0.0 + assert rs.trim_offset(100.0, 99.0, 0.3) == 0.0 + + +def test_a_robot_that_never_moved_gives_no_offset(): + # None is the caller's cue that the navigation failed, not a zero offset. + assert rs.trim_offset(100.0, None, 0.3) is None + + +def test_trim_command_cuts_the_requested_window(): + cmd = rs.build_trim_cmd(Path('raw.mp4'), 6.2, 25.0, Path('out.mp4')) + assert cmd[cmd.index('-ss') + 1] == '6.200' + assert cmd[cmd.index('-t') + 1] == '25.000' + assert cmd[cmd.index('-i') + 1] == 'raw.mp4' + assert cmd[-1] == 'out.mp4' + + +def test_scenario_duration_overrides_the_default(): + assert rs.clip_duration({'video': {'duration_s': 25.0}}, 20.0) == 25.0 + assert rs.clip_duration({}, 20.0) == 20.0 + assert rs.clip_duration({'video': None}, 20.0) == 20.0 + + +def test_dynamic_circle_records_long_enough_to_finish(): + # The orbit cell is the one that needs the longer clip; the others keep the + # default so each scenario's four controllers stay length-synced. + scn = yaml.safe_load((SCENARIOS / 'dynamic_circle.yaml').read_text())['scenario'] + assert rs.clip_duration(scn, 20.0) == 25.0 + scn = yaml.safe_load((SCENARIOS / 'static_box.yaml').read_text())['scenario'] + assert rs.clip_duration(scn, 20.0) == 20.0 diff --git a/prox_mpc_controller/CHANGELOG.rst b/prox_mpc_controller/CHANGELOG.rst index 8db2256..d361257 100644 --- a/prox_mpc_controller/CHANGELOG.rst +++ b/prox_mpc_controller/CHANGELOG.rst @@ -2,6 +2,100 @@ Changelog for package prox_mpc_controller ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2.0.0 (2026-09-13) +------------------ +* **Breaking:** ``predict_obstacles`` defaults to ``true``. With no tracker + publishing, or a stale message, the fill degrades to the costmap-only path, so + the default costs a subscription rather than a behavior change. Set it + ``false`` to reproduce the previous behavior bit-for-bit. +* **Breaking:** ``model_plugin`` defaults to ``prox_mpc_core/Unicycle`` rather + than ``prox_mpc_core/Bicycle``. +* **Breaking:** new ``allow_reversing`` parameter, default ``false``, bounds the + solver's linear control to ``[0, v_max]``, so it cannot plan reverse travel at + all. 1.0.0 had no such switch; its reference was forward-only, but its solver + always admitted reverse down to ``-v_max``, so a deployment that upgrades + without setting it loses reverse. With it ``true`` and no explicit + ``model_params.v_min``, reverse is capped at 0.15 m/s: both guards follow the + predicted trajectory and so do cover a reversing one, but they see only what + the costmap holds, and whether the platform sweeps behind itself is a property + of its sensor rather than of this plugin. + ``model_params.v_min`` is also forwarded on its own when negative. +* New ``reverse_from_plan_orientation`` parameter, default ``false``: with it + and ``allow_reversing`` set, the plan's pose orientations sign the reference + into reverse and truncate it at the first direction change. It defaults off + because only a planner that sets pose orientations means anything by them, and + a plan carries nothing that reports which planner produced it: NavFn and Smac + 2D emit the identity quaternion on every pose, which is indistinguishable from + a straight reverse plan. Trusting them would read any path running against + that one fixed heading as a reverse traverse, so the robot would drive the + whole path backwards instead of turning around, and a path whose heading + component changes sign would flip the reference from cycle to cycle. Set it + ``true`` with a cusp-emitting planner (Smac Hybrid-A*, State Lattice). +* The reference is pinned to the goal pose inside the goal-checker xy tolerance + instead of tracking the robot's own projection onto the plan. The cruise taper + and the sampling step composed to give the reference horizon an arc reach of + ``remaining^2 / xy_tol``, shorter than ``remaining`` at every point inside the + tolerance, so the goal region was tracked against a stub a few millimetres + ahead of the projection that the projection then carried along: a reference + with no fixed point, which let a small tracking error be traded down as cheaply + one way as the other, and whose horizon never reached the plan end, so the + goal's own orientation never entered it. Pinning gives the last stretch a fixed + setpoint and a standing heading error. The mode is latched and released only + past the new ``goal_settle_hysteresis_m``, default 0.10 m. +* Once the goal checker's xy condition is met and only the heading is left, a + platform with no steering channel holds station and turns on the spot rather + than reversing and re-advancing as the body sweeps round. A steering model is + excluded, having no way to turn on the spot. +* Travel direction is a latched mode rather than a fresh read of the plan + geometry each cycle. A change is accepted only once the platform is at or below + ``direction_switch_standstill_speed_mps`` (default 0.05 m/s) and + ``direction_switch_dwell_s`` (default 0.5 s) has elapsed since the last change; + until then the reference is held at the arc length under the robot, so the + commanded speed falls to zero and the platform stops first. A cusp is driven + the way a vehicle drives one: arrive, stop, shift, pull away. Both gates are + inert unless ``reverse_from_plan_orientation`` is set. +* New ``prediction_forward_shadow_s`` parameter, default ``0.0`` (inert). The + predictive keep-out is a disc about the predicted position and the constraint + normal runs from the obstacle to the robot, so the formulation does not + distinguish the space a mover is about to occupy from the space it is vacating; + passing in front and passing behind cost the same, and because the reference + carries no obstacle term, the front is the side that does not require lagging + it. Set positive, the disc is biased forward by that many seconds of the + track's own travel, with the radius grown by the same distance so the + obstacle's own position stays covered. Left off by default: the mechanism is + unit-tested, but an A/B on the demo walker was directionally favourable and + statistically inconclusive at four runs per arm. +* New ``obstacle_yield_band_m`` parameter, default ``0.0`` (inert): eases the + cruise when where the robot is heading - the plan at the intended cruise, or + the trajectory the solver planned last cycle, whichever breaches deeper - + would cut into a tracked mover's predicted keep-out, so the robot waits for + the mover instead of racing it. The release is rate-limited so it cannot snap + back to full cruise. Enable it with ``allow_reversing``: with reversing off + a waiting robot is boxed in by a second mover, which is why it stays off by + default. It is not to be combined with light stage weights. +* New ``obstacle_yield_caps_speed`` parameter, default ``false``: the + obstacle-aware yield also caps the solver's forward speed bound, so it slows + the robot rather than only lowering a cruise target the obstacle term can + override. The cap falls no faster than the platform can brake, so the solver + always has a feasible first control, and leaves the reverse bound alone. +* The footprint veto walks the predicted trajectory as far as the robot's + stopping distance rather than checking a single pose one step ahead. +* Obstacle slots are bound to one object per cycle and ranked by time to + encounter; the scan is centred on the predicted state and the keep-out on + ``base_link``. +* Solver acceptance is transactional: a candidate is committed only once the + finiteness, veto and command gates accept, and convergence is reported past + those gates. +* The solver-failure brake ramps in control space through the model, seeded from + the model's declared inverse in its own units, with a configurable step. +* Perception state is mutex-guarded on every path, the costmap lock is narrowed + to the cell reads, and the footprint read is hoisted out of the grid lock. +* ``configure()`` validates its parameters, warns when ``robot_radius`` + undersizes the costmap footprint, rejects a zero model speed bound and a + non-finite ``desired_linear_vel``, and clamps a Nav2 speed limit into the + model's own bounds rather than replacing them. +* Contributors: Simone Contorno + 1.0.0 (2026-07-28) ------------------ * Initial release: ``nav2_core::Controller`` plugin wrapping the ProxMPC core, diff --git a/prox_mpc_controller/CMakeLists.txt b/prox_mpc_controller/CMakeLists.txt index 20e442c..84aad80 100644 --- a/prox_mpc_controller/CMakeLists.txt +++ b/prox_mpc_controller/CMakeLists.txt @@ -10,9 +10,20 @@ if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE "Release") endif() -# Compiler warnings -if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang") - add_compile_options(-Wall -Wextra -Wpedantic) +# Compiler warnings, matching upstream Nav2's package-level policy +# (nav2_common/cmake/nav2_package.cmake) so this package is held to the same +# bar as every other Nav2 plugin it ships alongside. +if(CMAKE_CXX_COMPILER_ID MATCHES "GNU" OR CMAKE_CXX_COMPILER_ID MATCHES "Clang") + add_compile_options(-Wall -Wextra -Wpedantic -Werror -Wdeprecated -fPIC -Wshadow -Wnull-dereference) + # GCC 13 raises -Wnull-dereference inside libstdc++'s own headers + # (stl_algobase.h, reached through regex_traits::transform_primary) once + # --coverage changes its inlining decisions, which is how the coverage build + # hits it and an ordinary build does not. The report is attributed to the + # translation unit that instantiates the template, so -Wno-system-headers + # does not reach it. Keep the diagnostic, but do not let a false positive in + # the standard library fail the build. + add_compile_options(-Wno-error=null-dereference) + add_compile_options("$<$:-Wnon-virtual-dtor>") endif() # Remove Eigen's internal assertions in the hot path (safe under Release) @@ -36,6 +47,7 @@ find_package(nav_msgs REQUIRED) find_package(pluginlib REQUIRED) find_package(rclcpp REQUIRED) find_package(rclcpp_lifecycle REQUIRED) +find_package(rcpputils REQUIRED) find_package(tf2 REQUIRED) find_package(tf2_ros REQUIRED) find_package(visualization_msgs REQUIRED) @@ -63,6 +75,7 @@ ament_target_dependencies(${PROJECT_NAME} pluginlib rclcpp rclcpp_lifecycle + rcpputils tf2 tf2_ros visualization_msgs @@ -103,6 +116,7 @@ ament_export_dependencies( pluginlib rclcpp rclcpp_lifecycle + rcpputils tf2 tf2_ros visualization_msgs @@ -118,13 +132,22 @@ if(BUILD_TESTING) ament_lint_auto_find_test_dependencies() find_package(ament_cmake_gtest REQUIRED) + # Used only to capture the robot_radius/footprint mismatch warning's exact + # text in the configure() test, via a custom rcutils_logging_output_handler. + find_package(rcutils REQUIRED) # The wrapper unit tests bring up a LifecycleNode, a tf2 buffer, and a # Costmap2DROS, then drive the plugin's public interface and fail-safe # branches; the test owns rclcpp init/shutdown via its own main. + # + # Both binaries in this package stand up a node per case, which does not fit + # inside CTest's 60 s default once AddressSanitizer instrumentation is linked + # in; without the raised timeout the sanitizer job reports a timeout rather + # than a real defect. ament_add_gtest(test_prox_mpc_controller test/test_prox_mpc_controller.cpp - SKIP_LINKING_MAIN_LIBRARIES) + SKIP_LINKING_MAIN_LIBRARIES + TIMEOUT 300) target_link_libraries(test_prox_mpc_controller ${PROJECT_NAME} Eigen3::Eigen @@ -140,10 +163,40 @@ if(BUILD_TESTING) prox_mpc_msgs rclcpp rclcpp_lifecycle + rcutils tf2 tf2_ros visualization_msgs ) + + # Controller-facing contract tests: transactional-solve wiring, + # SolverDiagnostics' gate-aware converged field and its publisher, the + # model/Nav2 adapter contract (Model::getPlanarMapping()), and + # terminal-heading/reverse-travel tracking. The fault-injection fixtures it + # loads by name through pluginlib come from prox_mpc_test_models, already a + # above. + ament_add_gtest(test_controller_contracts + test/test_controller_contracts.cpp + SKIP_LINKING_MAIN_LIBRARIES + TIMEOUT 300) + target_link_libraries(test_controller_contracts + ${PROJECT_NAME} + Eigen3::Eigen + proxsuite::proxsuite + ) + ament_target_dependencies(test_controller_contracts + geometry_msgs + nav2_core + nav2_costmap_2d + nav_msgs + pluginlib + prox_mpc_core + prox_mpc_msgs + rclcpp + rclcpp_lifecycle + tf2 + tf2_ros + ) endif() ament_package() diff --git a/prox_mpc_controller/README.md b/prox_mpc_controller/README.md index db7fce3..34d3115 100644 --- a/prox_mpc_controller/README.md +++ b/prox_mpc_controller/README.md @@ -29,6 +29,8 @@ driving a TurtleBot3 waffle under a full Nav2 stack in Gazebo Harmonic (see ## Documentation +- [doc/migration.md](doc/migration.md) - what changed on the released surface + since 1.0.0, and what a deployment has to do about it. - [doc/architecture.md](doc/architecture.md) - the Nav2 integration design: responsibility split, the controller lifecycle, the per-cycle data flow, the interfaces and QoS, the full parameter reference, and the two safety layers. @@ -43,20 +45,28 @@ driving a TurtleBot3 waffle under a full Nav2 stack in Gazebo Harmonic (see - **NMPC behind `nav2_core::Controller`:** one SQP cycle per control step over the ProxQP solver; linear models converge in a single QP solve. - **Model selected by configuration:** the vehicle model is loaded with - `pluginlib` (`model_plugin`, e.g. `prox_mpc_core/Bicycle` or + `pluginlib` (`model_plugin`, e.g. `prox_mpc_core/BicycleFrontAxle` or `prox_mpc_core/Unicycle`), so switching the robot model needs no code change. - **Plan-following reference:** arc-length sampling of the global plan with a continuous (unwrapped) heading, a curvature-aware steering reference for the bicycle, optional curvature-based cruise reduction, and goal-checker approach easing. - **Two-layer obstacle avoidance:** a fast in-loop disc constraint built from the - local costmap (clustered, windowed scan) shapes the trajectory, and an exact - polygon-footprint check vetoes any command that would collide. -- **Predictive (dynamic) obstacle avoidance (opt-in):** consumes tracked + local costmap (clustered, windowed scan) shapes the trajectory, and an + outline-only footprint check, walked along the predicted trajectory as far as + the robot's own stopping distance, vetoes a command whose rasterised footprint + perimeter crosses a lethal cell. + It is a backstop, not a guarantee: it depends on costmap inflation sized to + the robot and on the local costmap's unknown-space tracking to be effective. +- **Predictive (dynamic) obstacle avoidance (on by default):** consumes tracked obstacles, follows each track's tracker-sampled predicted trajectory over the horizon (a constant-velocity ray when no samples are provided), binds it to a fixed constraint slot, and fills the remaining slots from the costmap (hybrid); - off by default, reproducing the costmap-only behavior bit-for-bit. + `predict_obstacles: false` reproduces the costmap-only behavior bit-for-bit. + The costmap-only fill reads one present-time costmap for every horizon node, so + a moving obstacle is constrained where it was rather than where it will be. + It is validated for single-obstacle environments; with more than one mover the + error closes the gap the plan was routed through, and the tracker is required. - **Safe failure handling:** a non-converged or non-finite solve decelerates from the measured velocity at the robot's limit and escalates to a Nav2 recovery after `max_solver_failures` consecutive failures; `cancel()` ramps to a stop @@ -145,7 +155,7 @@ disabled (single formatter, and a short SPDX header per file with the full text overlay is not sourced, or the package failed to build against Nav2. - **`controller_server` aborts at configure with a model-load error:** the `model_plugin` name is wrong or its package is not on the overlay; the valid - bundled names are `prox_mpc_core/Bicycle` and `prox_mpc_core/Unicycle`. + bundled names are `prox_mpc_core/Unicycle`, `prox_mpc_core/BicycleFrontAxle` and `prox_mpc_core/BicycleRearAxle`, plus `prox_mpc_core/Bicycle` as a deprecated alias for the front-axle model. - **Robot rotates in place instead of translating:** the cruise speed samples the reference too close to the robot; raise `desired_linear_vel` toward the model's speed bound (see the config notes in the diff --git a/prox_mpc_controller/config/prox_mpc_controller.yaml b/prox_mpc_controller/config/prox_mpc_controller.yaml index 7b283d3..d40653d 100644 --- a/prox_mpc_controller/config/prox_mpc_controller.yaml +++ b/prox_mpc_controller/config/prox_mpc_controller.yaml @@ -13,12 +13,15 @@ controller_server: # editing the core or this list; the controller configures it after loading. # The model must declare a bound on its speed input (u[0]) and control-rate # (du) bounds for both channels: they set the speed cap and the deceleration - # ramp, and a model missing either fails configure(). - model_plugin: "prox_mpc_core/Bicycle" + # ramp, and a model missing either fails configure(). Bundled names are + # prox_mpc_core/Unicycle, prox_mpc_core/BicycleFrontAxle and + # prox_mpc_core/BicycleRearAxle; prox_mpc_core/Bicycle is a deprecated + # alias for the front-axle model. + model_plugin: "prox_mpc_core/Unicycle" model_params: # forwarded to Model::configure(); absent keys keep the literals - L: 1.6 # wheelbase [m] + L: 1.6 # wheelbase [m], used by the bicycle models v_max: 0.0 # [m/s] forward input bound; forwarded only when > 0, else the model literal - v_min: 0.0 # [m/s] reverse input bound; used only alongside a positive v_max (< 0, else -v_max) + v_min: 0.0 # [m/s] reverse input bound; negative forwards on its own, else -v_max # Horizons and step (couple via Np / dt / T). np: 20 @@ -28,16 +31,53 @@ controller_server: # Reference tracking. Cruise speed the global plan is sampled at to build # the state/control reference; tapered toward zero near the plan end and # clamped by any active speed limit. Must not exceed the model's speed - # bound (the bundled Bicycle/Unicycle default v_max to 3.0 m/s). + # bound (every bundled model defaults v_max to 3.0 m/s). desired_linear_vel: 1.0 # [m/s] curvature_gain: 0.0 # cruise reduction on path curvature; 0.0 disables it + # Narrows the linear control bound to [0, v_max] when false, so the solver + # cannot plan reverse travel. When true without an explicit v_min above, + # reverse is capped at 0.15 m/s, because whether the platform senses the + # reverse direction is not something this plugin can check. + allow_reversing: false + + # Whether the plan's pose orientations are trusted to say which way to + # travel along it, so the reference can be signed into reverse and + # truncated at the first direction change. Set true only with a planner + # that sets those orientations, such as Smac Hybrid-A* or State Lattice. + # Planners that leave every pose at the identity quaternion (NavFn, Smac + # 2D) say nothing by them, and are read as a reverse plan for any path + # running against that fixed heading. + reverse_from_plan_orientation: false + + # Travel direction is a latched mode, not a per-cycle read of the plan. A + # change is taken only once the platform is at or below the standstill + # speed and the dwell since the last change has elapsed; until then the + # reference is held at the arc length under the robot, so the commanded + # speed falls to zero and the platform stops first. A cusp is therefore + # driven the way a vehicle drives one -- arrive, stop, shift, pull away -- + # and the switching rate is bounded rather than free-running. + direction_switch_standstill_speed_mps: 0.05 # [m/s] + direction_switch_dwell_s: 0.5 # [s] + + # Band beyond the goal-checker xy tolerance that the robot must re-cross + # before the terminal settle mode releases. Inside the tolerance the + # reference is pinned to the goal pose instead of tracking the robot's own + # projection onto the plan, which gives the last stretch a fixed setpoint + # and puts the goal's orientation into the reference; the band keeps a + # remaining distance hovering about the tolerance from flipping the two. + goal_settle_hysteresis_m: 0.10 # [m] + + # Step the deceleration ramp advances by on a braking cycle. 0 measures the + # inter-cycle period instead and clamps it into [dt, 2*dt]; a positive + # value overrides the measurement and is used as-is. + brake_period_s: 0.0 # [s] # Cost weights (assembled as in the demo). q_pos: 10.0 q_theta: 1.0 s_factor: 2.0 r_weight: 0.1 - w_weight: 100.0 + w_weight: 1000.0 # Solver limits (defaults match the core). The three iteration caps must be # >= 1: 0 is rejected by ProxQP and a negative value wraps to an unbounded @@ -45,10 +85,13 @@ controller_server: # QP that can never converge. max_int_iter_qp: 1500 max_ext_iter_qp: 10000 - max_iter_sqp: 100 + max_iter_sqp: 1 max_solve_time: 0.0 # [s] wall-clock budget for the SQP loop; 0 = disabled (iteration caps only) qp_type: false # false = sparse, true = dense guess: true # true = ProxQP equality-constrained initial guess per QP; false = no initial guess + # Reuse the QP workspace and previous primal/dual iterate across cycles + # instead of rebuilding the solver every cycle. + warm_start: true # Consecutive non-converged solves tolerated before the controller raises a # recovery; each failure decelerates toward zero at the robot's limit. @@ -72,11 +115,51 @@ controller_server: # across nodes, so the NMPC avoids where each obstacle will be; the rest of # the K slots are filled from the costmap (hybrid). predict_obstacles=false # (and any stale/missing tracking data) reproduces the costmap-only fill. - predict_obstacles: false # opt-in; false selects the costmap-only obstacle fill + predict_obstacles: true # false selects the costmap-only obstacle fill obstacle_topic: "tracked_obstacles" # prox_mpc_msgs/ObstacleArray input obstacle_timeout: 0.5 # [s] staleness before costmap-only fallback dynamic_speed_threshold: 0.1 # [m/s] speed above which a track is propagated prediction_uncertainty_growth: 0.0 # [m/s] extra d_safe per second of prediction + + # Forward shadow cast along a tracked obstacle's own heading. The keep-out + # is a disc about the predicted position and the constraint normal points + # from the obstacle to the robot, so nothing in the formulation tells the + # space a mover is about to occupy from the space it is vacating; passing + # in front and passing behind cost the same, and since the reference + # carries no obstacle term, the front is the side that does not require + # lagging it. This biases the disc forward by that many seconds of the + # track's own travel, growing the radius by the same distance so the + # obstacle stays covered. 0.0 disables it, which is the default: the + # mechanism is sound but its effect has not been measured with enough + # runs to justify a non-zero default. See doc/architecture.md. + prediction_forward_shadow_s: 0.0 # [s] + + # Obstacle-aware cruise (off by default). When where the robot is heading + # would cut into a tracked mover's predicted keep-out, the cruise is eased + # toward zero over this depth of breach, so the robot waits for the mover + # instead of racing it. "Where it is heading" is both the plan at this + # cycle's intended cruise and the trajectory the solver planned last cycle, + # whichever breaches deeper; the release back to full cruise is + # rate-limited. Measured on dynamic_circle over ten runs with reversing on: + # 0.5 passes behind the mover 6/10 against 1/10, with the best closest + # approach (+0.100 m against +0.070 m) and no collisions. Enable it together + # with allow_reversing: waiting is safe when the robot can back off. With + # reversing off, a waiting robot is boxed in by a second mover - over thirty + # two-mover runs it doubled the passes closer than 0.15 m (15/30 against + # 7/30), which is why it stays off by default. Keep the stage weights at + # their defaults: light stage weights (q_pos 1, s_factor 30) let the robot + # stray far from its path and collided 1/10, with or without it. + obstacle_yield_band_m: 0.0 # [m] + + # Make the obstacle-aware yield a speed limit, not a request. Without it the + # yield only lowers the cruise target, which carries the lightest weight in + # the cost, so when a mover is closing the obstacle term overrides it and + # the robot swerves at full speed instead of slowing. With it the solver's + # forward speed bound is capped by the same factor - lowered no faster than + # the platform can brake, so the solver always has a feasible command, and + # with the reverse bound left alone, so the robot can still back away. + # Needs obstacle_yield_band_m > 0 to do anything. + obstacle_yield_caps_speed: false max_dynamic_obstacles: 2 # slot budget reserved for dynamic tracks max_dynamic_obstacle_radius: 0.0 # [m] skip tracks larger than this (walls); 0 = no limit diff --git a/prox_mpc_controller/doc/architecture.md b/prox_mpc_controller/doc/architecture.md index 51903de..6609a80 100644 --- a/prox_mpc_controller/doc/architecture.md +++ b/prox_mpc_controller/doc/architecture.md @@ -87,13 +87,17 @@ Each cycle the controller performs the following steps. arc-length offset, and sample the state/control reference `goal_x` / `goal_u` over the horizon. The cruise speed is tapered near the plan end, reduced on path curvature (optional), and clamped by any active speed limit and the - goal-checker tolerance. + goal-checker tolerance. Inside the goal-checker xy tolerance the reference is + pinned to the goal pose instead of tracking the projection, and travel + direction is a latched mode that changes only from rest - see + [Terminal settle and travel direction](#terminal-settle-and-travel-direction). 3. **Fill the obstacle triples.** When obstacles are enabled (`K > 0`), fill the per-node `(o_x, o_y, d_safe)` matrix: predictive + hybrid when enabled and fresh tracking data is available, otherwise costmap-only. 4. **Solve** one SQP cycle and read `qp_info.status`. 5. **Guard and veto.** Reject a non-finite iterate, then run an exact - polygon-footprint check on the pose one step ahead; a veto decelerates. + polygon-footprint check over the predicted stopping distance; a veto + decelerates. 6. **Command or brake.** On success, map the first control with `model->toTwist(...)`; on failure, decelerate and escalate after `max_solver_failures` consecutive failures. @@ -115,7 +119,7 @@ sequenceDiagram Ctrl->>MPC: solve() MPC-->>Ctrl: x, u and qp_info.status alt solved and finite - Ctrl->>CM: exact footprint check (one step ahead) + Ctrl->>CM: exact footprint check (to stopping distance) alt footprint clear Ctrl->>Model: toTwist(u0) else vetoed @@ -127,21 +131,70 @@ sequenceDiagram Ctrl-->>Nav2: TwistStamped (base frame) ``` +### Terminal settle and travel direction + +Two properties of the reference are decided across cycles rather than within +one, because both are discrete choices that a per-cycle rule leaves free to +alternate. + +**Terminal settle.** The reference is sampled at `v_ref * k * dt` ahead of the +robot's own projection onto the plan, and `v_ref` is tapered to zero across the +goal-checker xy tolerance. Composing the two makes the horizon's arc reach +`remaining^2 / xy_tol`, which is shorter than `remaining` at every point inside +the tolerance: in the goal region the tracked reference collapses to a stub a few +millimetres ahead of the projection, and the projection carries it along as the +robot moves. Such a reference has no fixed point - any motion re-projects the +robot and re-centres the stub, so a small tracking error can be traded down as +cheaply one way as the other - and its horizon never reaches the plan end, so the +goal's own orientation never enters it, which is exactly when that orientation is +the only error left. Inside the tolerance the reference is therefore pinned to +the goal pose, turning the last stretch from tracking a receding stub into +regulation about a fixed setpoint: one minimiser, and a standing yaw error the +solver can act on. The speed reference keeps its taper, so the approach profile +is unchanged and entering the mode introduces no step in the commanded speed. The +mode is latched and released only past `goal_settle_hysteresis_m`, so a remaining +distance hovering about the tolerance cannot flip the reference mode to mode; it +is never entered on a reference truncated at a cusp, whose end is not the goal. + +**Travel direction.** Direction is a discrete mode of a switched system. Deciding +it afresh each cycle from the plan geometry, at no cost and with no dwell, is +what leaves it free to alternate. It is held instead, and a change is accepted +only once the platform is at or below `direction_switch_standstill_speed_mps` and +`direction_switch_dwell_s` has elapsed since the last change - the first being +the constraint a drivetrain already imposes on a gear shift, the second bounding +the switching rate. While a change is pending the reference is held at the arc +length under the robot, so `v_ref` falls to zero and the deceleration ramp brings +the platform to the standstill the change is waiting on. A cusp is then driven +the way a vehicle drives one: arrive, stop, shift, pull away. Both gates are +inert unless `allow_reversing` and `reverse_from_plan_orientation` are set, since +only then can the reference be signed into reverse at all. + ## Safety layers Obstacle avoidance is split across two layers. The engine keeps a fast, convex, disc-based margin inside the optimization, which shapes the trajectory away from obstacles (see [obstacle avoidance](../../prox_mpc_core/doc/obstacle-avoidance.md)). -A separate exact polygon-footprint check, evaluated on the pose one step ahead -with `nav2_costmap_2d::FootprintCollisionChecker`, is the conservative last line -of defense: if that pose's footprint reaches an inscribed-inflated cost, the -command is vetoed and replaced by the deceleration ramp without consuming the -solver-failure budget. The veto keeps its own counter and escalates to -`nav2_core::NoValidControl` once it exceeds the same `max_solver_failures` -budget, so a robot stuck behind a static obstacle reaches a recovery instead of -braking forever. -The veto is skipped when the costmap exposes fewer than three footprint points. +A separate, outline-only footprint check, evaluated with +`nav2_costmap_2d::FootprintCollisionChecker` on each predicted pose until their +cumulative arc length passes the distance the robot needs to stop +(`v^2 / (2a)`, from the commanded speed and the model's declared deceleration +rate), is a backstop rather than a guarantee: it rasterises only the footprint perimeter and reports the maximum +edge cost, with no interior fill and no sweep between the current and the next +commanded pose. It vetoes the command when that pose's footprint reaches +`LETHAL_OBSTACLE`, treating unknown space as non-colliding when the local +costmap tracks it - matching `nav2_regulated_pure_pursuit_controller` and +`nav2_mppi_controller`'s own collision checks rather than the stricter +`INSCRIBED_INFLATED_OBSTACLE` threshold used before. A vetoed command is +replaced by the deceleration ramp without consuming the solver-failure budget. +The veto keeps its own counter and escalates to `nav2_core::NoValidControl` +once it exceeds the same `max_solver_failures` budget, so a robot stuck behind +a static obstacle reaches a recovery instead of braking forever. +The veto is skipped when the costmap exposes fewer than three footprint +points, and it is an effective backstop only when costmap inflation is sized +to the robot's real footprint and the local costmap's unknown-space tracking +matches the deployment: the in-loop keep-out half-planes above are what cover +a lethal cell adjoining unknown space that the veto's own masking may miss. ## Solver-failure handling @@ -168,6 +221,48 @@ to a fixed obstacle slot across nodes, and fills the remaining slots from the costmap (hybrid). A stale or missing message, or a missing transform, degrades to the costmap-only fill for that cycle, so the feature is a clean enable/disable switch. + +The costmap-only fill scans one present-time costmap around every predicted node, +so a moving obstacle enters the horizon at the position it currently occupies - +an error of `v_obs * t_node`, up to a metre at the far end of a 2 s horizon. +It is validated for single-obstacle environments, where the free corridor +absorbs the resulting late reaction. With more than one mover that corridor +closes, and the tracker is required rather than optional. + +### Keep-out enforcement against a crossing mover + +The obstacle row carries a slack variable, so the keep-out is a soft constraint: +the solver may buy its way through it. Against a mover crossing the path this is +not a corner case. Measured on an isolated crossing encounter (0.3 m/s mover, +0.26 m/s cruise, the shipped weights and bounds, aggregated over nine meeting +times spanning +/- 2 s), the predicted trajectory breaches the keep-out in about +27% of control cycles, and the realised clearance consumes the whole safety +margin - at worst a few centimetres of physical gap remain. An independent +Gazebo measurement over the demo walker put the same figure at 27.7%, which is +the cross-check that the two agree. + +The breach is not a tuning matter, and this is worth stating precisely because +the obvious levers look like they should work: + +- `w_weight` has no effect. Swept from 1e3 to 1e6 - a thousandfold - the breach + rate moves from 26.8% to 27.2%. The solver is not trading the constraint away + for tracking cost; a larger penalty buys nothing. +- `max_iter_sqp` has no effect. Rates are identical at 1, 2 and 4 iterations, so + the single real-time iteration is not the limitation either. +- Compute is not the constraint. p95 solve time stays between 8 and 14 ms + against a 50 ms budget at 20 Hz across every arm. +- Easing the cruise speed on a predicted breach - giving the reference an + obstacle term it does not have - cuts the breach *rate* to about 19% but + roughly doubles the worst-case depth. It trades frequent shallow breaches for + rarer deep ones, which is not an improvement. + +What remains is the formulation. With the linear control bound and a reference +that demands full cruise straight through the crossing, no admissible trajectory +both tracks the reference and clears the mover; the slack absorbs the +difference. Treat the keep-out as advisory against a crossing mover rather than +as a guarantee, and put a velocity-directed backstop (Nav2's Collision Monitor) +behind it where a breach matters. This extends to a single mover the limitation +previously recorded only for multi-obstacle fields. The propagation and the wall-rejection guard are derived in [control-law.md](control-law.md). @@ -208,10 +303,10 @@ and fail the lifecycle transition. | Parameter | Type | Default | Unit | Description | | --- | --- | --- | --- | --- | -| `model_plugin` | string | `prox_mpc_core/Bicycle` | - | `prox_mpc::Model` plugin loaded by name. | -| `model_params.L` | double | 1.6 | m | Wheelbase forwarded to `Model::configure`; pre-positions the bicycle steering reference. | +| `model_plugin` | string | `prox_mpc_core/Unicycle` | - | `prox_mpc::Model` plugin loaded by name. Bundled: `prox_mpc_core/Unicycle`, `prox_mpc_core/BicycleFrontAxle`, `prox_mpc_core/BicycleRearAxle`, and `prox_mpc_core/Bicycle` as a deprecated alias for the front-axle model. | +| `model_params.L` | double | 1.6 | m | Wheelbase forwarded to `Model::configure`. The steering reference is built on the wheelbase the loaded model declares back through `getPlanarMapping()`, not on this value directly. | | `model_params.v_max` | double | 0.0 | m/s | Optional forward-speed bound on the model's `u[0]` input. Forwarded to `Model::configure` only when `> 0.0`; the default 0.0 keeps the model's built-in limit. | -| `model_params.v_min` | double | 0.0 | m/s | Reverse-speed bound, forwarded only alongside a positive `v_max`. A negative value is used as given; otherwise the bound is set to `-v_max`. | +| `model_params.v_min` | double | 0.0 | m/s | Reverse-speed bound. A negative value is forwarded on its own, or alongside a positive `v_max`; with `v_max > 0.0` and a non-negative `v_min` the bound is set to `-v_max`. `allow_reversing: false` narrows it to `0.0` afterwards regardless; `allow_reversing: true` with this left unset caps it at `-0.15`. Naming it is how a platform with rear sensing states its real reverse envelope. | | `np` | int | 20 | nodes | Prediction horizon. | | `nc` | int | 20 | nodes | Control horizon. | | `dt` | double | 0.1 | s | Step size and control period. | @@ -222,6 +317,11 @@ and fail the lifecycle transition. | --- | --- | --- | --- | --- | | `desired_linear_vel` | double | 1.0 | m/s | Cruise speed the plan is sampled at; clamped to the model's speed bound. | | `curvature_gain` | double | 0.0 | - | Cruise reduction on path curvature; 0.0 disables it. | +| `allow_reversing` | bool | false | - | Whether the solver may plan reverse travel. Off narrows the model's linear control bound to `[0, v_max]`. On without an explicit `model_params.v_min` caps reverse at **0.15 m/s**: both guards follow the predicted trajectory and so do cover a reversing one, but they see only what the costmap holds, and whether the platform sweeps behind itself is a property of its sensor rather than of this plugin (see [Robot-specific tuning](#robot-specific-tuning)), so an unverified manoeuvre is kept slow. A platform that turns in place reaches every pose forward-only, so the bound is opt-in rather than a default. Inside the goal region an open reverse half used to give the solver a second, equally cheap way to trade down a small tracking error, which it alternated with the first; the terminal settle below removes that by pinning the reference to the goal pose, so the last stretch has one minimiser. | +| `reverse_from_plan_orientation` | bool | false | - | Whether the plan's pose orientations are trusted to say which way to travel along it, signing the reference speed and truncating the reference at the first direction change. Requires `allow_reversing`. Set true only with a planner that sets those orientations (Smac Hybrid-A*, State Lattice). NavFn and Smac 2D leave every pose at the identity quaternion, which reads as a reverse plan for every path running against that one fixed heading - the robot then drives the whole path backwards rather than turning around, and a path whose heading component changes sign flips the reference cycle to cycle. A plan cannot report which planner produced it, so this is declared, not inferred. | +| `direction_switch_standstill_speed_mps` | double | 0.05 | m/s | Speed at or below which the platform counts as stopped for a travel-direction change. Travel direction is a latched mode; a change is taken only from rest, which is the constraint a drivetrain imposes on a gear shift and the one that keeps the mode from alternating. While a change is pending the reference is held at the arc length under the robot, so the commanded speed falls to zero and the platform stops first. | +| `direction_switch_dwell_s` | double | 0.5 | s | Minimum time between two accepted direction changes. A discrete mode re-chosen every cycle with no dwell is free to chatter however cheap each switch looks; this bounds the switching rate. | +| `goal_settle_hysteresis_m` | double | 0.10 | m | Band beyond the goal-checker xy tolerance that the robot must re-cross before the terminal settle releases back to path tracking. Entry and release on one threshold would flip the reference mode to mode on a remaining distance hovering about the tolerance. | ### Cost weights @@ -231,7 +331,7 @@ and fail the lifecycle transition. | `q_theta` | double | 1.0 | Heading (and remaining state) tracking weight. | | `s_factor` | double | 2.0 | Terminal-weight factor: `S = s_factor * Q`. | | `r_weight` | double | 0.1 | Control-effort weight. | -| `w_weight` | double | 100.0 | Obstacle-slack penalty. | +| `w_weight` | double | 1000.0 | Obstacle-slack penalty. | ### Solver limits @@ -239,11 +339,13 @@ and fail the lifecycle transition. | --- | --- | --- | --- | | `max_int_iter_qp` | int | 1500 | ProxQP internal-iteration cap. Must be `>= 1`; a lower value fails `configure()`. | | `max_ext_iter_qp` | int | 10000 | ProxQP external-iteration cap. Must be `>= 1`; a lower value fails `configure()`. | -| `max_iter_sqp` | int | 100 | SQP-iteration cap per cycle. Must be `>= 1`; a lower value fails `configure()`. The caps reach the core as `size_t`, so a negative value would wrap to an effectively unbounded loop, and ProxQP rejects a zero cap outright, so both are fatal rather than clamped. | -| `max_solve_time` | double | 0.0 | Wall-clock budget in seconds for the whole SQP loop; 0.0 disables it (the iteration caps are then the only bound). On timeout the solve reports non-convergence and the cycle brakes. Floored at 0.0. | +| `max_iter_sqp` | int | 1 | SQP-iteration cap per cycle. Must be `>= 1`; a lower value fails `configure()`. The caps reach the core as `size_t`, so a negative value would wrap to an effectively unbounded loop, and ProxQP rejects a zero cap outright, so both are fatal rather than clamped. | +| `max_solve_time` | double | 0.0 | Wall-clock budget in seconds for the whole SQP loop; 0.0 disables it (the iteration caps are then the only bound). Tested only between SQP sub-problem solves, so it cannot interrupt one already in flight and does not bound worst-case cycle latency in either direction; a loop that exceeds it stops with whatever status the last QP returned, which is `PROXQP_SOLVED` when that QP itself converged. The bound that genuinely holds every cycle is the iteration caps (`max_iter_sqp = 1` gives a bounded real-time iteration). Floored at 0.0. | | `qp_type` | bool | false | QP backend: false = sparse, true = dense. | -| `guess` | bool | true | ProxQP initial-guess strategy: equality-constrained (`true`) or none (`false`). The QP is not seeded with the previous increment; see [nmpc.md](../../prox_mpc_core/doc/nmpc.md). | +| `guess` | bool | true | ProxQP initial-guess strategy. With `warm_start` on this selects `WARM_START` (`true`) or none (`false`); with it off, the equality-constrained guess (`true`) or none. See [nmpc.md](../../prox_mpc_core/doc/nmpc.md). | +| `warm_start` | bool | true | Reuse the ProxQP workspace and the previous primal/dual iterate across cycles, updating in place instead of re-initializing the solver every cycle. | | `max_solver_failures` | int | 3 | Consecutive non-converged solves before escalating to a recovery. | +| `brake_period_s` | double | 0.0 | Step [s] the deceleration ramp advances by on a braking cycle. 0.0 measures the inter-cycle period instead (clamped between `dt` and twice `dt`, so a slow server still brakes at the model's declared rate and a stale measurement cannot collapse the ramp into one step); a positive value overrides the measurement and is used as-is. | `max_solve_time` defaults to `0.0` (disabled) in [config/prox_mpc_controller.yaml](../config/prox_mpc_controller.yaml), so the @@ -265,11 +367,14 @@ iteration caps are the only bound unless a stack sets a positive budget. | Parameter | Type | Default | Unit | Description | | --- | --- | --- | --- | --- | -| `predict_obstacles` | bool | false | - | Opt-in; false reproduces the costmap-only behavior. | +| `predict_obstacles` | bool | true | - | False reproduces the costmap-only behavior. With no tracker publishing, or a stale message, the fill degrades to costmap-only regardless. | | `obstacle_topic` | string | `tracked_obstacles` | - | `ObstacleArray` input topic. | | `obstacle_timeout` | double | 0.5 | s | Staleness before falling back to costmap-only. | | `dynamic_speed_threshold` | double | 0.1 | m/s | Speed above which a track is propagated (static is left to the costmap). | | `prediction_uncertainty_growth` | double | 0.0 | m/s | Extra `d_safe` per second of prediction. | +| `prediction_forward_shadow_s` | double | 0.0 | s | Forward shadow cast along a tracked obstacle's own heading. The keep-out is a disc about the predicted position and the constraint normal runs from the obstacle to the robot, so the formulation does not distinguish the space a mover is about to occupy from the space it is vacating; passing in front and passing behind cost the same, and because the reference carries no obstacle term, the front is the side that does not require lagging it. This biases the disc forward by that many seconds of the track's own travel and grows the radius by the same distance, so the obstacle's own position stays covered while the disc reaches further ahead than behind. `0.0` disables it. Left at `0.0` by default: the mechanism is sound and unit-tested, but an A/B on the demo walker (n=4 per arm) was directionally favourable and statistically inconclusive. | +| `obstacle_yield_band_m` | double | 0.0 | m | Obstacle-aware cruise, off by default. When where the robot is heading would breach a tracked mover's predicted keep-out, the cruise is scaled toward zero over this depth of breach, so the robot waits for the mover rather than racing it. Where it is heading is checked twice and the deeper breach wins: the plan at this cycle's intended cruise, which cannot restore full cruise by clearing the breach a reduction caused, and the trajectory the solver planned last cycle, which is what the robot actually drives when the solver strays from the plan. The release back to full cruise is rate-limited (`1 / s`), so a breach that seems to clear for one cycle cannot snap the cruise back. On `dynamic_circle` over ten runs with reversing on, `0.5` passed behind the mover 6/10 against 1/10 with the best closest approach (+0.100 m against +0.070 m) and no collisions, and with two movers it was no worse than off (3/30 collisions either way). Enable it together with `allow_reversing`: waiting is safe when the robot can back off. With reversing off a waiting robot is boxed in by a second mover - over thirty two-mover runs it doubled the passes closer than 0.15 m (15/30 against 7/30) - so it stays off by default. Keep the stage weights at their defaults: light stage weights (`q_pos` 1, `s_factor` 30) collided 1/10 with or without it. The figures above are for the band on its own; pair it with `obstacle_yield_caps_speed` for the shipped behaviour, which is what the predictive preset and the Gazebo demo enable. | +| `obstacle_yield_caps_speed` | bool | false | - | Makes the obstacle-aware yield a speed limit rather than a request. On its own the yield lowers the cruise target, which carries the lightest weight in the cost (`r_weight`, against `q_pos` and `w_weight`), so when a mover is closing the obstacle term overrides it and the solver swerves at full speed instead of slowing - measured, the cruise target was cut to a tenth while the robot held 0.5 m/s. With this on, the forward bound of the speed control is capped by the same factor, the way a Nav2 speed limit is applied to it. The cap never falls below the command last applied less the model's deceleration times `dt`, since the solver bounds the first control to that and a lower cap would leave it no feasible first control; and the reverse bound is left alone, so a robot capped to a crawl can still back away. Needs `obstacle_yield_band_m > 0`. | | `max_dynamic_obstacles` | int | 2 | slots | Slot budget reserved for dynamic tracks. | | `max_dynamic_obstacle_radius` | double | 0.0 | m | Skip tracks larger than this (walls); 0 = no limit. | @@ -295,6 +400,16 @@ remaining behaviors below are fixed in the plugin, so a deployment adapts to the through the model plugin and the costmap configuration rather than through controller parameters. +- **Reverse travel needs rear sensing.** Obstacles behind the robot are guarded + exactly as far as the platform observes them: a 360-degree scanner marks them + in the local costmap, where the keep-out fill and the footprint veto both act + on them, while a forward-facing sensor leaves the manoeuvre blind. Neither + guard covers genuinely unobserved space - the fill skips `NO_INFORMATION` + cells and the veto treats them as clear - so occlusions and anything beyond + the rolling window stay unseen in every direction. `allow_reversing: true` + therefore caps reverse at 0.15 m/s unless `model_params.v_min` names a bound; + raise it once the platform's rear coverage is established, and consider + Nav2's Collision Monitor as a velocity-directed backstop. - `desired_linear_vel`, together with the `model_params.v_max` and `model_params.v_min` overrides, should follow the vehicle's real envelope rather than the simulation defaults. `model_params` carries only `L`, `v_max`, @@ -311,7 +426,8 @@ controller parameters. unknown space does not hard-block the optimizer. Where unknown space must be treated as blocking, that belongs to the costmap and planner configuration. - The footprint veto evaluates the polygon from `getRobotFootprint()` through - `footprintCostAtPose(...)` at the pose one step ahead; the pre-oriented + `footprintCostAtPose(...)` at each predicted pose within the stopping + distance; the pre-oriented `getOrientedFootprint(...)` is not used. Publishing an accurate robot footprint of at least three points keeps the check active, because a smaller footprint is not a valid polygon and the veto is skipped for that cycle with a throttled diff --git a/prox_mpc_controller/doc/control-law.md b/prox_mpc_controller/doc/control-law.md index a021288..efd7761 100644 --- a/prox_mpc_controller/doc/control-law.md +++ b/prox_mpc_controller/doc/control-law.md @@ -54,10 +54,23 @@ turns the short way rather than spinning the long way around. ### Bicycle steering reference -For a model with a steering state ($n > 3$) the reference steering is -pre-positioned to the per-node path curvature $\kappa_k = d\theta/ds$, -$\delta_k^\text{ref} = \arctan(L\,\kappa_k)$, using the configured wheelbase $L$. -A model without a steering state (the unicycle, $n = 3$) keeps the go-straight +For a model that declares a steering state through `getPlanarMapping()`, the +reference steering is pre-positioned from the per-node path curvature +$\kappa_k = d\theta/ds$ and the model's declared reference-point offset $a$ +from `base_link` along the body x axis (`0` for `BicycleRearAxle`, the +wheelbase $L$ for `BicycleFrontAxle`): + +$$ +\delta_k^\text{ref} = \arctan(L\,z_k), \qquad +z_k = \frac{\kappa_k}{\sqrt{1 - (a\,\kappa_k)^2}}. +$$ + +At $a = 0$ (the rear axle) this reduces to the textbook rear-axle inverse +$\delta_k^\text{ref} = \arctan(L\,\kappa_k)$; at $a = L$ (the front axle) it is +algebraically the front-axle inverse $\delta_k^\text{ref} = \arcsin(L\,\kappa_k)$, +expressed as an `arctan` of the offset-adjusted $z_k$ so both plugins share one +formula. +A model with no steering state (the unicycle, $n = 3$) keeps the go-straight default. The control reference `goal_u` carries $v_\text{ref}$ in the speed channel and zero elsewhere. @@ -177,19 +190,43 @@ The controller owns the reaction so the policy stays decoupled from the engine. On a non-converged cycle the controller does **not** command a hard zero, which would be an instantaneous, dynamically infeasible stop. -Instead it decelerates toward zero at the robot's deceleration limit, read as the -magnitude of the model's control-rate (`du`) bounds for the speed and yaw -channels, $a_\text{dec} = \lvert a_\text{min} \rvert$, so over one step - -$$ -v_\text{cmd} = \max\!\big(0,\; v_\text{prev} - a_\text{dec}\, \Delta t\big), -$$ +Instead it ramps the model's own controls toward zero under the model's own +control-rate (`du`) bounds, respecting each bound's sign asymmetry, and maps +the ramped controls through the model's `toTwist()` - the same seam the +accepted command path uses, rather than writing `angular.z` directly. +This matters because the bicycle's second control is a steering rate, not a +body yaw rate: `du[1]` bounds `delta_dot` (a steering acceleration, not a yaw +acceleration), so only a control-space ramp maps correctly for that model, +while the unicycle's second control already *is* a body yaw rate and the two +forms coincide for it. + +Each control channel ramps down from the velocity the `controller_server` +measured for this cycle (RPP/MPPI style), so the brake tracks the robot's +actual motion rather than a stale command. +The measurement is a `base_link` twist and the channels are model controls, so +it is carried across by the model's own `fromTwist()` inverse rather than +written in directly: for a front-axle-referenced model the speed control is a +front-wheel speed, which only the linear and angular components together +determine. +That inverse states, per channel, what a body twist determines, and the +controller seeds exactly the channels it reports as determined; it names no +channel of its own. +A channel reported undetermined - a steering rate, which a twist shows the +effect of but not the value of - keeps its last commanded value, and so does one +whose measurement is itself non-finite (NaN or $\pm\infty$), so a broken +velocity estimate decelerates the last command instead of entering the ramp and +an infinite measured velocity can never reach the published command. +Each step advances by `brake_period_s` when the operator set a positive value, +otherwise by the measured inter-cycle period, clamped between the configured +`dt` and twice `dt` so a server running slower than `dt` still brakes at the +model's declared rate while a stale measurement cannot collapse the ramp into +one step. +A model that declares a steering state has its belief decayed toward zero at +its own declared steering-rate bound on every rejected cycle, rather than +frozen at the last accepted value, so the next solve does not linearize about +an angle a downstream twist-to-steering converter has already moved the wheels +away from under the braking command. -and the yaw rate is ramped toward zero the same way (respecting its sign). -$v_\text{prev}$ is the velocity the `controller_server` measured for this cycle, -not the previous command, so the ramp starts from the robot's actual speed; a -non-finite measurement (NaN or $\pm\infty$) yields exactly zero, so an infinite -measured velocity can never be ramped into the published command. Because a zero deceleration limit would leave the ramp stuck at the current velocity forever, a model that declares no `du` bound for either channel (or no `u[0]` bound for the speed cap) fails `configure` with a @@ -209,11 +246,23 @@ solver-failure budget, though a veto persisting beyond that same budget raises The engine's per-node half-plane is the $\gamma = 1$ case of a discrete-time control-barrier-function constraint $h(x_{k+1}) \ge (1 - \gamma)\, h(x_k)$, which couples consecutive nodes for smoother avoidance. -The coupling requires the **same** obstacle at nodes $k$ and $k+1$, which the -predictive fill provides by binding each tracked obstacle to a fixed slot across -the horizon. -`cbf_gamma` exposes $\gamma$: 1.0 is the pointwise constraint, and a value below 1 -lets the safety margin decay gradually, which makes a dense obstacle field viable -where the pointwise term would stall the robot (see the verified predictive -configuration in -[../../prox_mpc_demo/doc/nav2-simulation.md](../../prox_mpc_demo/doc/nav2-simulation.md)). +The coupling requires the **same** obstacle at nodes $k$ and $k+1$. Both the +predictive fill and the costmap (static) fill provide this: the predictive +fill binds each tracked obstacle to a fixed slot across the horizon, and the +costmap fill now binds each scanned object to a fixed slot across every node +it appears at, rather than re-selecting nearest candidates independently per +node (see [obstacle avoidance](../../prox_mpc_core/doc/obstacle-avoidance.md) +for the core-side guard this pairs with). +That stability holds only *within* one control cycle; nothing yet holds a slot +to the same object *across* cycles, so a `cbf_gamma` below 1 can still couple +different physical objects at a cycle boundary when two candidates are close +in rank. + +`cbf_gamma` exposes $\gamma$: 1.0 is the pointwise constraint, and a value +below 1 lets the safety margin decay gradually instead of binding at every +node. The coupling is enforced through the slack penalty like every other +obstacle row, not as a hard barrier, so whether a given `cbf_gamma` measurably +changes a trajectory at the shipped `w_weight` has not yet been benchmarked; +treat it as a tunable option protected by the core-side guard and the +within-cycle slot stability above, not as a settled recommendation for dense +fields. diff --git a/prox_mpc_controller/doc/migration.md b/prox_mpc_controller/doc/migration.md new file mode 100644 index 0000000..7dc8a39 --- /dev/null +++ b/prox_mpc_controller/doc/migration.md @@ -0,0 +1,288 @@ +# Migrating from prox_mpc_controller 1.0.0 + +What changed on the released surface of `prox_mpc_controller`, and what a 1.0.0 +deployment has to do about it. +The version number this lands under is fixed by the maintainer against the final +diff and is not stated here. + +## Summary + +| Change | Source compatible | ABI compatible | Wire compatible | +| --- | --- | --- | --- | +| `model_plugin` defaults to `prox_mpc_core/Unicycle` | yes | yes | yes | +| New `allow_reversing` parameter, default `false`, closes the reverse travel 1.0.0 always allowed | yes | yes | yes | +| New `reverse_from_plan_orientation` parameter, default `false` | yes | yes | yes | +| New `direction_switch_standstill_speed_mps` / `direction_switch_dwell_s` parameters | yes | yes | yes | +| New `goal_settle_hysteresis_m` parameter, default `0.10` | yes | yes | yes | +| New `prediction_forward_shadow_s` parameter, default `0.0` | yes | yes | yes | +| New `obstacle_yield_band_m` / `obstacle_yield_caps_speed` parameters | yes | yes | yes | +| The reference is pinned to the goal pose inside the goal-checker xy tolerance | yes | yes | yes | +| New `brake_period_s` parameter, default `0.0` | yes | yes | yes | +| `ProxMpcController` gains `readModelMapping()` and cached mapping members | yes | **no** | yes | +| `fillStaticObstacles`, `reduceCostmap` and `publishDiagnostics` change signature; `a_dec_lin_`/`a_dec_ang_` are renamed | **no, for a class deriving from `ProxMpcController`** | **no** | yes | +| The model contract is validated at `configure()` and rejects what cannot be driven | yes | yes | yes | +| The in-loop keep-out is centred on `base_link` | yes | yes | yes | +| The deceleration ramp runs in control space, through the model's `toTwist()` | yes | yes | yes | +| `SolverDiagnostics.converged` reports the applied command, not the QP status | yes | yes | **yes, layout and hash unchanged** | +| A rejected cycle no longer advances the solver's retained state | yes | yes | yes | +| Terminal-heading reference past the plan end | yes | yes | yes | + +No `.msg` field is added, removed, renamed, retyped or reordered, so nothing here +changes a type hash or a CDR layout. + +## The default model changed + +`model_plugin` now defaults to `prox_mpc_core/Unicycle`. It previously defaulted +to `prox_mpc_core/Bicycle`, which no longer describes one model. + +A `params.yaml` that sets `model_plugin` explicitly is unaffected, including one +that sets `prox_mpc_core/Bicycle`: that name still resolves, to the front-axle +bicycle, and logs a deprecation warning naming its replacement. + +A deployment that relied on the default to get a four-state steered model must +now set it: + +```yaml +FollowPath: + model_plugin: "prox_mpc_core/BicycleFrontAxle" # or BicycleRearAxle +``` + +Choose by where the model's state refers: `BicycleFrontAxle` puts `(x, y)` at the +front axle, `BicycleRearAxle` at the rear axle, which is the `base_link` origin +for a car-like base. `prox_mpc_core/Bicycle` maps to the front-axle model. + +## Reverse travel is now opt-in + +1.0.0 had no reverse switch. Its reference only asked for forward travel, but the +solver's linear control bound was symmetric, `[-v_max, v_max]`, so the solver +could plan reverse on its own - backing out of a closing gap, for instance. + +The new `allow_reversing` parameter defaults to `false`, which narrows that bound +to `[0, v_max]`. A deployment that upgrades without setting it no longer reverses +at all. + +To keep reverse travel, set `allow_reversing: true`. Without an explicit negative +`model_params.v_min`, reverse is then capped at 0.15 m/s, because the footprint +veto and the keep-out see only what the costmap holds, and whether the platform +senses behind itself is a property of its sensor rather than of this plugin. Set +`model_params.v_min` to allow a faster reverse once the platform's rear coverage +is known. + +## Closed-loop behaviour of a bicycle model changed + +The previous bicycle mixed three conventions. Each new plugin is consistent, so a +deployment using one will see different motion: + +- The commanded twist is the body twist of `base_link`. For the front-axle model + that is `linear.x = v cos(delta)`, not the front-wheel speed. +- The pose checked against the costmap footprint is the `base_link` pose, carried + back from the model's reference point. The footprint check was previously + performed at the front axle for a front-axle model. +- The steering reference is derived for the model's own reference point: + `asin(L * kappa)` for the front axle, `atan(L * kappa)` for the rear. +- The wheelbase is read from the loaded model, not from `model_params.L`. The two + agree for the bundled models, which apply that key. + +The in-loop keep-out disc is centred on `base_link`, which is the point the robot +disc and the costmap footprint are both defined about, whatever point the model's +state refers to. The solver constrains the model's reference point, so each +obstacle is written into the solver's frame by the rotated reference-point offset +and the costmap scan is centred on `base_link`. The QP half-plane and the +footprint veto therefore protect the same physical point, which they did not for +a front-axle model before. + +`d_safe` is unchanged at `robot_radius + safety_margin`, and so is the scan +window. For a model referenced to `base_link` - every model that declares no +offset - the shift is exactly zero and the obstacle fill is bit-identical. + +## A model this controller cannot drive is now rejected + +`configure()` reads the model's declared planar mapping and throws +`nav2_core::ControllerException` rather than indexing out of range, which +`EIGEN_NO_DEBUG` would leave unchecked. It rejects a model with fewer than three +states or no control, an index outside the model's own dimensions, two planar +quantities sharing one index, and a steering angle without a usable declared +wheelbase or with a lateral reference offset. + +The declared position may sit at any pair of state indices, with the in-loop +obstacle term active or not. The solver reads the same declaration and indexes +its keep-out rows through it, so a model that 1.0.0 could only drive with +`max_obstacles` set to 0 now drives with avoidance on. + +It also rejects a model whose declared upper speed bound is zero or non-finite. +1.0.0 required the bound to be present but not to be usable, so a model +declaring `setIneq("u", 0, 0.0, 0.0)` configured cleanly, had its cruise speed +clamped to zero and never moved - the outcome the missing-bound message already +said it prevented. + +A custom `prox_mpc::Model` that follows the previous implicit convention passes +unchanged, except that one carrying a steering angle must now declare its +wheelbase. See `prox_mpc_core/doc/migration.md`. + +## Command validation covers every twist component + +The command gate tested `linear.x` and `angular.z` while all six components of +the published twist come from the model. All six are now checked for finiteness, +on the accepted path and on the deceleration ramp. A model that fills only the +two planar components is unaffected. + +## The deceleration ramp works in control space + +1.0.0's brake wrote `linear.x` and `angular.z` directly, stepping both down from +the velocity the `controller_server` measured for that cycle. The ramp now runs +on the model's own controls, under the model's own `du` bounds, and maps the +result through `Model::toTwist()`. That is the only form that is correct for a +model whose second control is not a body yaw rate: the bicycle's is a steering +rate, so a twist-space ramp had no meaning for it. + +Every control channel still starts from the measured velocity, carried into the +model's own control units through `Model::fromTwist()` rather than by writing +`linear.x` and `angular.z` into control slots directly: for +`prox_mpc_core/BicycleFrontAxle` the speed control is a front-wheel speed, and a +`base_link` speed placed there is projected by `cos(delta)` a second time on the +way out. The unicycle and `prox_mpc_core/BicycleRearAxle` both carry the +`base_link` speed in that channel already, so the number they start from is +unchanged. + +`Model::fromTwist()` declares per channel what a body twist determines, and the +controller seeds exactly the channels it reports as determined. Both bicycles +report their steering rate undetermined, because a twist shows the steering +angle's effect and not the rate it is changing at, so that control starts from +the last commanded value. The unicycle's second control *is* a body yaw rate, so +it is determined and starts from the measured `angular.z`, as it did in 1.0.0. + +A model that carries a steering angle keeps a separate belief about it, and +`activate()` and `reset()` zero that belief along with the last-commanded +control vector. If the first cycle to brake after either - from a cancel, a +solver failure, or a footprint veto - finds such a robot already turning, the +twist it emits is derived from a zero steering angle and so carries no yaw rate, +rather than ramping down from the yaw the robot actually has. Later cycles ramp +normally, because an accepted cycle records both the command it applied and the +steering angle it solved for. The speed channel is unaffected throughout, +because it starts from the measurement. + +## `SolverDiagnostics.converged` means something different + +The message defines `converged` as a converged solve whose applied iterate is +finite. The controller previously set it from the QP status alone and published +before its own gates ran, so a cycle that was vetoed by the footprint check and +braked was recorded as converged. + +It is now set only past the finiteness, footprint-veto and command-conversion +gates, and publication moves with it. + +**The message is unchanged**: field names, types, order and defaults are +identical, the generated IDL is identical, and the RIHS01 type hash is +unchanged. A subscriber needs no rebuild. What changed is the runtime meaning of +one field, so a bag recorded before this and a bag recorded after are not +directly comparable on `converged` counts. The QP's own outcome is still +available, unchanged, in the `status` field; compare on that instead when a +cross-version comparison is needed. + +## A rejected cycle no longer advances the solver + +The controller now solves into a candidate and commits it only once its gates +accept. A cycle that fails to converge, produces a non-finite iterate, is vetoed +by the footprint check, or maps to a non-finite command leaves the solver's +retained trajectory, slack and previous control exactly as the last accepted +cycle left them, and the deceleration ramp anchors the next cycle's control-rate +constraint on the command it actually sent. + +This changes motion after a rejected cycle: the next solve no longer plans a step +away from a command the robot never received. No configuration changes. + +## Terminal behaviour in the goal region + +This one is not behind a parameter, so it applies on upgrade. + +Inside the goal-checker xy tolerance the reference is now pinned to the goal +pose instead of tracking the robot's own projection onto the plan, and once the +checker's xy condition is met and only the heading is outstanding, a platform +with no steering channel holds station and turns on the spot. Previously the +cruise taper and the sampling step composed to give the reference horizon an arc +reach of `remaining^2 / xy_tol` - shorter than `remaining` everywhere inside the +tolerance - so the goal region was tracked against a stub a few millimetres ahead +of the projection that moved with the robot, and the goal's own orientation never +entered the reference at all. A deployment that relied on the controller stalling +at a terminal heading error and a recovery behaviour taking over will now see the +controller close that error itself. + +The change is source, ABI and wire compatible, and the two gates that bound +direction switching are inert unless `reverse_from_plan_orientation` is set. + +## New behaviour behind parameters + +| Parameter | Type | Default | Units | Meaning | +| --- | --- | --- | --- | --- | +| `allow_reversing` | bool | `false` | - | Whether the solver may plan reverse travel; off narrows the linear control bound to `[0, v_max]`. | +| `reverse_from_plan_orientation` | bool | `false` | - | Whether the plan's pose orientations may sign the reference into reverse and truncate it at the first direction change. Requires `allow_reversing`. | +| `direction_switch_standstill_speed_mps` | double | `0.05` | m/s | Speed at or below which the platform counts as stopped for a travel-direction change. Inert unless `reverse_from_plan_orientation`. | +| `direction_switch_dwell_s` | double | `0.5` | s | Minimum time between two accepted direction changes. Inert unless `reverse_from_plan_orientation`. | +| `goal_settle_hysteresis_m` | double | `0.10` | m | Band beyond the goal-checker xy tolerance that the robot must re-cross before the terminal settle releases back to path tracking. | +| `prediction_forward_shadow_s` | double | `0.0` | s | Biases a tracked mover's predicted keep-out forward along its own heading by this many seconds of its travel, growing the radius by the same distance so its current position stays covered. `0.0` reproduces a centred keep-out exactly. | +| `obstacle_yield_band_m` | double | `0.0` | m | Depth of predicted keep-out breach over which the cruise is eased to zero, so the robot waits for a crossing mover instead of racing it. `0.0` reproduces the obstacle-blind cruise exactly. | +| `obstacle_yield_caps_speed` | bool | `false` | - | Makes that yield cap the solver's forward speed bound rather than only lowering a cruise target the obstacle term can override. Requires `obstacle_yield_band_m > 0`. | +| `brake_period_s` | double | `0.0` | s | Step the deceleration ramp advances by on a braking cycle. `0.0` measures the inter-cycle period instead and clamps it into `[dt, 2 * dt]`; a positive value overrides the measurement and is used as-is. | + +`allow_reversing`'s default keeps 1.0.0's forward-only reference and, unlike +1.0.0, also closes the solver's reverse bound: see +[Reverse travel is now opt-in](#reverse-travel-is-now-opt-in). With it on, a +model that declares no reverse travel keeps the forward-only reference and logs +a warning at `configure()`. + +`reverse_from_plan_orientation` is the switch that reads travel direction out of +the plan. It defaults `false` because only a planner that sets pose orientations +means anything by them, and a plan carries nothing that says whether its planner +did: NavFn and Smac 2D emit the identity quaternion on every pose, which is +byte-identical to a genuine straight reverse plan. Trusting them reads any path +running against that one fixed heading as a reverse traverse, so the robot drives +the whole path backwards instead of turning around, and a path whose heading +component changes sign flips the reference from cycle to cycle. Set it true with +a cusp-emitting planner (Smac Hybrid-A*, State Lattice); leave it false with +NavFn or Smac 2D. + +The three prediction parameters are all inert at their defaults, so a 1.0.0 +deployment upgrading without touching them keeps the previous obstacle +behaviour exactly. They are the release's avoidance work and are worth reading +before enabling: `obstacle_yield_band_m` makes the *reference* yield to a +crossing mover, and `obstacle_yield_caps_speed` is what turns that yield from a +request into a speed limit - on its own the eased cruise is the lightest term in +the cost and the solver overrides it, swerving at full speed rather than slowing. +Enable the pair together with `allow_reversing`: waiting is safe when the robot +can back off, and with reversing off a waiting robot is boxed in by a second +mover. `prediction_forward_shadow_s` is unit-tested but left off, its A/B having +been directionally favourable and statistically inconclusive. The measured +figures for all three are in [architecture.md](architecture.md). + +`brake_period_s`'s default of `0.0` reproduces 1.0.0's ramp on a +`controller_server` running at `dt`, which stepped by the configured `dt` +unconditionally. On a server running slower than `dt` the measured period is +used instead, so the ramp still decelerates at the rate the model declares +rather than at a fraction of it. Set a positive value to make the ramp +independent of scheduling jitter. + +The terminal-heading reference is not behind a parameter. Past the plan end the +reference pose is now the goal pose rather than the final segment's tangent, +engaged only when the goal checker publishes a yaw tolerance it enforces. Goal +approach on a plan whose final orientation differs from its final segment tangent +will differ from 1.0.0. + +## Object layout + +`ProxMpcController` gains three protected methods and twenty-nine protected +members, which changes `sizeof(ProxMpcController)`. The pluginlib load path is +unaffected, because the class is allocated and freed inside the same library. A +downstream package that links the exported target and derives from or holds +`ProxMpcController` directly must be rebuilt. + +Its protected surface also changes in ways a derived class sees at compile time, +so the release is not source compatible for such a class. `fillStaticObstacles` +and `reduceCostmap` lose their leading plan-reference parameter, which the scan +stopped reading when it moved onto the solver's own nominal trajectory; +`publishDiagnostics` gains a `period_ms` parameter after `solve_ms`, so the +telemetry and the deceleration ramp report the same measured period; and +`a_dec_lin_`/`a_dec_ang_` become `fallback_ramp_lin_`/`fallback_ramp_ang_`, +which is what they hold: the rates the last-resort twist ramp steps by, not a +linear/angular acceleration pair. A derived controller that overrode or called +any of them must be updated. The three added protected methods are +`readModelMapping`, `keepOutShift` and `markCycleStart`. diff --git a/prox_mpc_controller/include/prox_mpc_controller/prox_mpc_controller.hpp b/prox_mpc_controller/include/prox_mpc_controller/prox_mpc_controller.hpp index 1164959..caa9a1a 100644 --- a/prox_mpc_controller/include/prox_mpc_controller/prox_mpc_controller.hpp +++ b/prox_mpc_controller/include/prox_mpc_controller/prox_mpc_controller.hpp @@ -25,6 +25,7 @@ #include #include #include +#include #include #include @@ -88,21 +89,45 @@ class ProxMpcController : public nav2_core::Controller void reset() override; protected: - /// Read the model's speed bound (upper bound of `u[0]`) and its per-channel - /// deceleration limits (lower bounds of `du[0]` and `du[1]`) into v_max_, - /// max_linear_vel_, a_dec_lin_ and a_dec_ang_. A model that declares none of a - /// required bound cannot be driven safely - a zero deceleration limit leaves - /// the brake ramp stuck at the current velocity, and a zero speed bound clamps - /// the cruise speed to zero - so a missing bound throws + /// Read the model's declared planar mapping into the cached indices and + /// offsets, and reject a model this controller cannot drive before any state + /// or control vector is indexed. EIGEN_NO_DEBUG leaves an out-of-range Eigen + /// index unchecked, so the screening has to happen here rather than at the + /// first access. Rejected: fewer than three states, an index outside the + /// model's own dimensions, two planar quantities sharing one index, a model + /// carrying a steering angle without declaring a usable wheelbase or with a + /// lateral reference offset, a steering-rate control index outside the control + /// vector or colliding with the speed channel. Each rejection throws + /// nav2_core::ControllerException naming `model_plugin` and the reason. + /// + /// The declared position may sit at any pair of state indices, with or + /// without the in-loop obstacle term: the solver reads the same declaration + /// and indexes its keep-out rows through it. + void readModelMapping(prox_mpc::Model & model, const std::string & model_plugin); + + /// Read the model's declared bounds into the cached control-law limits: both + /// bounds of the speed control into v_max_, v_min_ and max_linear_vel_; the + /// lower bound of the speed control's `du` entry into fallback_ramp_lin_, and + /// that of `du[1]` into fallback_ramp_ang_ for a model that has a second + /// control; every declared `du` bound into du_low_ and du_upp_; the bound of + /// the declared steering-rate control, when the model has one, into + /// steer_rate_low_ and steer_rate_upp_. It also sizes last_cmd_u_ to the + /// model's control dimension. A model that declares none of a required bound + /// cannot be driven safely - a zero deceleration + /// limit leaves the brake ramp stuck at the current velocity, and a zero speed + /// bound clamps the cruise speed to zero - so a missing bound throws /// nav2_core::ControllerException naming it. `model_plugin` is the plugin name - /// reported in that message. + /// reported in that message. Must run after readModelMapping(), whose cached + /// speed-control index it reads. void readModelBounds(prox_mpc::Model & model, const std::string & model_plugin); /// Convert a requested speed limit to an absolute bound (a fraction of the /// model bound when `percentage`, the model bound itself on NO_SPEED_LIMIT), - /// clamp it to the model bound, and apply it to the model's `u[0]` inequality. - /// Called only from the control thread (configure() and the top of a control - /// cycle), never concurrently with a running solve. + /// and intersect it with the model's own `u[0]` bounds rather than replacing + /// them, so a model that declares an asymmetric speed range (a reverse limit + /// tighter than the forward one, or no reverse at all) keeps it. Called only + /// from the control thread (configure() and the top of a control cycle), never + /// concurrently with a running solve. void applySpeedLimit(double speed_limit, bool percentage); /// Fill the per-node (o_x, o_y, d_safe) obstacle matrix for one cycle. With @@ -116,34 +141,67 @@ class ProxMpcController : public nav2_core::Controller void fillObstacles(const MatrixXd & reference, MatrixXd & obs, const rclcpp::Time & now); /// Reduce the local costmap to at most max_obstacles_ (o_x, o_y, d_safe) triples - /// per predicted node, centered on the reference trajectory positions. This is + /// per predicted node, centered on the nominal predicted positions. This is /// the static (costmap-only) fill and the predict_obstacles_-off fallback. - void reduceCostmap(const MatrixXd & reference, MatrixXd & obs); + void reduceCostmap(MatrixXd & obs); /// Windowed costmap scan that fills obstacle slots [slot_begin, max_obstacles_) /// per node from the nearest occupied cells, skipping cells inside any per-node /// exclusion disc (a dynamic track's footprint). Slots below slot_begin and the /// far-sentinel default are left untouched. exclusions[node] = list of /// (x, y, radius); an empty vector means no exclusions. + /// + /// The scan is centred on the MPC's own nominal predicted trajectory, because + /// that is what the QP linearizes each node's keep-out half-plane about; a plan + /// reference centred elsewhere would size the window for a cross-track error + /// the constraint does not carry. That is why no plan reference is passed here, + /// while fillObstacles() does take one, for the dynamic-track priority. void fillStaticObstacles( - const MatrixXd & reference, MatrixXd & obs, std::size_t slot_begin, + MatrixXd & obs, std::size_t slot_begin, const std::vector>> & exclusions); - /// Cache the latest tracked-obstacle array (subscription callback; runs in the - /// controller-server executor alongside computeVelocityCommands). + /// Per-node translation carrying an obstacle position from the frame the + /// keep-out is meant to protect - base_link - into the frame the solver + /// constrains, which is the model's own reference point. Both vectors are + /// sized to np_ and left all-zero for a model referenced to base_link, where + /// the two frames coincide and every obstacle is written unchanged. + /// + /// The solver constrains the model's reference point p_ref, so a keep-out + /// about base_link, p_base = p_ref - R(yaw) * offset, is expressed by moving + /// the obstacle to o + R(yaw) * offset: the residual is then p_base - o. The + /// yaw comes from the same nominal predicted trajectory the obstacle scan is + /// centred on, so it carries that trajectory's one-node staleness. + void keepOutShift(std::vector & shift_x, std::vector & shift_y); + + /// Cache the latest tracked-obstacle array. This runs on the controller + /// server's node executor, while computeVelocityCommands runs on the action + /// server's own execution thread, so the two are concurrent and the exchange + /// between them must be guarded. void obstacleCallback(prox_mpc_msgs::msg::ObstacleArray::ConstSharedPtr msg); /// Publish the predicted dynamic-obstacle trajectories as RViz markers when the /// debug topic has a subscriber (no-op otherwise). void publishPredictedObstacleMarkers(const rclcpp::Time & now); + /// Close the previous control cycle's timing measurement and open this one's, + /// returning the inter-cycle wall period [ms] (NaN when there is no previous + /// cycle). Called once, at the top of computeVelocityCommands(), so every path + /// out of the cycle - including the ones that brake or throw after the solve - + /// reads the same measurement, and none of them leaves the reference point + /// stale for the next cycle. + double markCycleStart(); + /// Fill and publish one SolverDiagnostics for this control cycle, only when the /// publisher exists and the diagnostics topic has a subscriber (zero cost - /// otherwise). `solve_ms` is the wall time measured around mpc_->solve(); - /// `converged` is the cycle's solve result; `num_active_obstacles` is the count - /// of filled, non-sentinel obstacle slots at the current node. + /// otherwise). `solve_ms` is the wall time measured around the solve; + /// `period_ms` is this cycle's inter-cycle period as markCycleStart() measured + /// it, so the telemetry and the deceleration ramp report the same number; + /// `converged` reports whether the cycle's command was accepted and applied, + /// which is what the message's own field documents - the QP's own outcome stays + /// separately visible in `status`; `num_active_obstacles` is the count of + /// filled, non-sentinel obstacle slots at the current node. void publishDiagnostics( - const rclcpp::Time & stamp, double solve_ms, bool converged, + const rclcpp::Time & stamp, double solve_ms, double period_ms, bool converged, std::uint16_t num_active_obstacles); rclcpp_lifecycle::LifecycleNode::WeakPtr node_; @@ -166,12 +224,14 @@ class ProxMpcController : public nav2_core::Controller std::shared_ptr> diag_pub_; - /// Tracked-obstacle input and its mutex-guarded latest message. The callback and - /// computeVelocityCommands run in the same controller-server executor; the mutex - /// guards the shared-pointer swap between them. + /// Tracked-obstacle input and its mutex-guarded latest message. The callback + /// runs on the node executor and computeVelocityCommands on the action server's + /// own execution thread, so they are concurrent: the mutex is what makes the + /// shared-pointer exchange between them safe, and removing it would be a race. rclcpp::Subscription::SharedPtr obstacle_sub_; std::mutex obstacles_mutex_; - prox_mpc_msgs::msg::ObstacleArray::ConstSharedPtr latest_obstacles_; + prox_mpc_msgs::msg::ObstacleArray::ConstSharedPtr latest_obstacles_ + RCPPUTILS_TSA_GUARDED_BY(obstacles_mutex_); /// One dynamic obstacle's predicted positions over the horizon (costmap global /// frame), retained from the fill so the marker publisher need not recompute. @@ -181,7 +241,8 @@ class ProxMpcController : public nav2_core::Controller double radius{0.0}; std::vector> positions; }; - std::vector predicted_obstacles_; + std::vector predicted_obstacles_ + RCPPUTILS_TSA_GUARDED_BY(obstacles_mutex_); nav_msgs::msg::Path global_plan_; @@ -198,13 +259,67 @@ class ProxMpcController : public nav2_core::Controller double dt_{0.1}; double desired_linear_vel_{1.0}; - /// Model wheelbase L [m] (forwarded to the model via model_params.L); used to - /// pre-position the steering reference for models with a steering state. - double wheelbase_{1.6}; + /// Model wheelbase L [m], read back from the loaded model's declared planar + /// mapping rather than from the model_params.L parameter that was forwarded to + /// it, so the steering reference is built on the wheelbase the model actually + /// uses. Meaningful only when has_steering_ is set. + double wheelbase_{0.0}; + + /// The loaded model's declared planar mapping, read once at configure() into + /// plain members: the control path never queries the model for it. + std::size_t idx_x_{0}; + std::size_t idx_y_{1}; + std::size_t idx_yaw_{2}; + std::size_t idx_v_{0}; + std::size_t idx_steer_{0}; + std::size_t idx_steer_rate_{0}; + bool has_steering_{false}; + bool has_steer_rate_{false}; + + /// Position of the model's reference point in base_link [m]. The Nav2 pose is + /// carried out to it before the solve and back before the footprint check, + /// which is defined about base_link. Both are zero unless the model declares + /// otherwise. + double ref_offset_x_{0.0}; + double ref_offset_y_{0.0}; /// Cruise-speed reduction gain on path curvature; 0.0 disables the reduction. double curvature_gain_{0.0}; + /// Whether the solver may plan reverse travel at all. Off by default, which + /// narrows the model's linear control bound to [0, v_max]. Signing the + /// reference into reverse is a separate opt-in, below. + bool allow_reversing_{false}; + + /// Whether the plan's pose orientations are trusted to encode travel + /// direction. NavFn and the Smac 2D planners leave every pose at the identity + /// quaternion, which reads as a reverse plan for any path running against it; + /// a cusp-emitting planner (Smac Hybrid-A*, State Lattice) means it. Defaults + /// false, so the reference stays forward-only unless a deployment says its + /// planner sets orientations. + bool reverse_from_plan_orientation_{false}; + + /// Speed [m/s] at or below which the platform counts as stopped for the + /// purpose of a travel-direction change. A drivetrain accepts a gear shift + /// only at rest, and the same gate is what keeps the switch well posed here: + /// the reference is held at the current arc length until the platform has + /// actually stopped, so reversing costs a stop rather than a control cycle. + double direction_switch_standstill_speed_mps_{0.05}; + + /// Minimum dwell [s] between two accepted direction changes. Travel direction + /// is a discrete mode, and a switched system whose mode is re-chosen every + /// cycle with no dwell time chatters; this is that dwell. + double direction_switch_dwell_s_{0.5}; + + /// Band [m] beyond the goal-checker xy tolerance that the robot must re-cross + /// before the terminal settle mode releases back to path tracking. Entry and + /// exit on one threshold would flip mode to mode on tracking noise. + double goal_settle_hysteresis_m_{0.10}; + + /// Deceleration-ramp step [s] on a braking cycle; 0 measures the inter-cycle + /// period instead, clamped into [dt_, kMaxBrakePeriodFactor * dt_]. + double brake_period_s_{0.0}; + /// Control-law parameters. int max_solver_failures_{3}; int max_obstacles_{1}; @@ -223,6 +338,26 @@ class ProxMpcController : public nav2_core::Controller double obstacle_timeout_{0.5}; // [s] staleness before costmap-only double dynamic_speed_threshold_{0.1}; // [m/s] propagate tracks above this double prediction_uncertainty_growth_{0.0}; // [m/s] extra clearance per second + /// Forward shadow [s] cast along a tracked obstacle's own heading: the keep-out + /// centre is biased ahead by this many seconds of its travel and grown by the + /// same distance, so the space it is about to occupy costs more than the space + /// it is vacating. 0.0 disables it, reproducing a centred keep-out exactly. + double prediction_forward_shadow_s_{0.0}; + /// Depth [m] of predicted keep-out breach over which the cruise speed is eased + /// to zero. When the reference path, driven at this cycle's cruise, would cut + /// into a tracked mover's predicted keep-out, the cruise is scaled by + /// 1 + breach / band, so the robot waits for the mover to clear instead of + /// racing it. 0.0 disables it, reproducing the obstacle-blind cruise exactly. + double obstacle_yield_band_m_{0.0}; + + /// Whether the obstacle-aware yield also caps the solver's forward speed bound, + /// rather than only lowering the cruise the reference asks for. The cruise is a + /// lightly weighted target the obstacle term can override - the solver then + /// swerves at full speed instead of slowing - so a yield that must actually + /// slow the robot has to bound the speed, not just request less of it. The cap + /// falls no faster than the platform can brake and leaves the reverse bound + /// alone, so the robot can still back away. Off by default. + bool obstacle_yield_caps_speed_{false}; int max_dynamic_obstacles_{2}; // slot budget for dynamic tracks /// Reject tracks larger than this [m] from the predictive path (0 = no limit): /// a guard against extended structure (walls) reported as a moving obstacle, @@ -233,14 +368,44 @@ class ProxMpcController : public nav2_core::Controller /// carries no extra interface; when on, publishes only-when-subscribed. bool publish_diagnostics_{false}; - /// Speed bounds: v_max_ is the model's original upper bound on the speed - /// channel; max_linear_vel_ is the currently applied limit. + /// Speed bounds: v_max_ and v_min_ are the model's original upper and lower + /// bounds on the speed channel, cached so a runtime speed limit narrows them + /// instead of overwriting them; max_linear_vel_ is the currently applied limit. double v_max_{0.0}; + double v_min_{0.0}; double max_linear_vel_{0.0}; - /// Deceleration limits read from the model's du bounds. - double a_dec_lin_{0.5}; - double a_dec_ang_{0.5}; + /// Rates the last-resort deceleration ramp steps the two body-twist channels + /// by, taken as the magnitudes of the model's declared lower `du` bounds for + /// control channels 0 and 1. + /// + /// They are bounds on the model's own controls, not on a body twist: for a + /// bicycle, channel 1 bounds a steering acceleration rather than a yaw one. + /// The brake ramps the controls themselves under du_low_/du_upp_ and maps them + /// through the model, so these two are read only when that mapping returns a + /// non-finite twist and a body-twist rate is the only thing left to ramp. The + /// names say where they are applied; the model's own rate bounds live in + /// du_low_/du_upp_. + double fallback_ramp_lin_{0.5}; + double fallback_ramp_ang_{0.5}; + + /// The model's control-rate (du) bounds, indexed by control channel, with each + /// side's sign preserved so an asymmetric model brakes at its own rate in each + /// direction. A channel the model declares no bound for is left unbounded, so + /// the brake takes it to zero in one step rather than freezing it. + std::vector du_low_; + std::vector du_upp_; + + /// Last commanded control vector; the ramp's starting point for every control + /// channel that has no measurement. The speed channel starts from the measured + /// speed instead, so the brake tracks the robot rather than a stale command. + VectorXd last_cmd_u_; + + /// Rate bounds of the control the model declares as its steering-angle rate, + /// used to decay the steering belief on a rejected cycle. Zero when the model + /// declares no such control, or no bound on it, which keeps the belief frozen. + double steer_rate_low_{0.0}; + double steer_rate_upp_{0.0}; /// Speed limit requested by the server. setSpeedLimit() runs on the node's /// executor thread while the solver reads the model's bounds on the action @@ -264,8 +429,28 @@ class ProxMpcController : public nav2_core::Controller bool cancelling_{false}; std::size_t plan_index_{0}; - /// Inter-cycle wall clock for the control_period_ms diagnostics field; reset - /// between tasks so the first cycle of a task reports NaN rather than a stale gap. + /// Latched travel direction: +1 forward, -1 reverse. Held across cycles so a + /// direction change is a deliberate transition subject to the standstill and + /// dwell gates above, rather than a fresh per-cycle read of the plan geometry. + double dir_{1.0}; + + /// Seconds since the last accepted direction change, advanced by the measured + /// cycle period. Compared against direction_switch_dwell_s_. + double dir_hold_s_{0.0}; + + /// Whether the terminal settle mode is engaged. Latched: entered inside the + /// goal-checker xy tolerance and released only past the hysteresis band, so + /// the reference does not alternate between the two modes near the goal. + bool settling_{false}; + + /// Cruise scale the obstacle-aware yield applied last cycle, in [0, 1]. It + /// drops at once when a breach deepens but recovers at a bounded rate, so a + /// breach that clears for one cycle cannot snap the cruise back to full. + double yield_factor_{1.0}; + + /// Inter-cycle wall clock, read and advanced by markCycleStart() at the top of + /// every control cycle; reset between tasks so the first cycle of a task + /// reports NaN rather than a stale gap. std::chrono::steady_clock::time_point last_cycle_wall_; bool have_last_cycle_{false}; }; diff --git a/prox_mpc_controller/package.xml b/prox_mpc_controller/package.xml index 3c54725..d0fdf27 100644 --- a/prox_mpc_controller/package.xml +++ b/prox_mpc_controller/package.xml @@ -2,7 +2,7 @@ prox_mpc_controller - 1.0.0 + 2.0.0 Nav2 nav2_core::Controller plugin built on the ProxMPC core: it builds the reference from the global plan, reduces the local costmap (and, optionally, tracked dynamic obstacles) to the solver's constraints, solves one @@ -27,6 +27,7 @@ proxsuite rclcpp rclcpp_lifecycle + rcpputils tf2 tf2_ros visualization_msgs @@ -35,6 +36,7 @@ ament_lint_auto ament_lint_common prox_mpc_test_models + rcutils ament_cmake diff --git a/prox_mpc_controller/src/prox_mpc_controller.cpp b/prox_mpc_controller/src/prox_mpc_controller.cpp index a2e61c6..ad49e7e 100644 --- a/prox_mpc_controller/src/prox_mpc_controller.cpp +++ b/prox_mpc_controller/src/prox_mpc_controller.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -25,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -58,9 +60,34 @@ std::uint8_t solverStatusToMsg(proxsuite::proxqp::QPSolverOutput status) /// Stop speed below which a cancel ramp is considered complete [m/s, rad/s]. constexpr double kCancelStopEpsilon = 0.01; +/// Cap on the brake ramp's integration period, as a multiple of the configured +/// step: the measured inter-cycle period is used so a server running slower than +/// the configured step still brakes at the model's own rate, but a stale or +/// hiccuped measurement must not turn one ramp step into an abrupt stop. +constexpr double kMaxBrakePeriodFactor = 2.0; /// Upper bound on the costmap scan half-window [cells] to keep the per-cycle cost /// bounded on constrained hardware. constexpr int kMaxScanHalfWidth = 50; +/// Reverse speed applied when reversing is enabled but no reverse bound is named +/// [m/s]. Whether the reverse direction is sensed at all is a property of the +/// platform, which this plugin cannot know: a forward-facing lidar leaves the +/// manoeuvre blind, while a 360-degree scanner covers it. The conservative +/// default therefore assumes the worse case and keeps an unverified manoeuvre +/// slow. Naming model_params.v_min overrides it, which is how a platform with +/// rear sensing states its real reverse envelope. +constexpr double kDefaultReverseSpeed = 0.15; +/// Track speed [m/s] below which no forward shadow is cast: the heading of a +/// near-stationary track is numerically meaningless, and biasing a keep-out along +/// it would move the disc in an arbitrary direction. +constexpr double kMinShadowSpeed = 1e-3; +/// Rate [1/s] at which the obstacle-aware yield may release the cruise back +/// toward full once a breach eases: a full release takes a second. The yield +/// itself tightens at once. +constexpr double kYieldRecoveryPerS = 1.0; +/// Distance [m] within which last cycle's planned trajectory must still meet the +/// robot for the yield to trust it: its next node has to lie this close to the +/// reference point's current position. +constexpr double kYieldTrajMatchRadius = 0.5; /// Minimum strictly-positive cost weight, keeping the QP Hessian positive definite /// (a negative weight would make the sub-problem non-convex). constexpr double kMinCostWeight = 1e-9; @@ -69,6 +96,15 @@ constexpr double kMinCbfGamma = 1e-3; /// Largest costmap cost still treated as an obstacle threshold (255 = NO_INFORMATION, /// handled separately; a higher threshold would silently disable avoidance). constexpr int kMaxCostThreshold = 254; +/// Marks a scanned obstacle that won no slot in the per-cycle capacity. +constexpr std::size_t kNoObstacleSlot = std::numeric_limits::max(); +/// Largest |offset * curvature| the steering inverse is evaluated at. The +/// closed form divides by sqrt(1 - (offset * curvature)^2), which is the +/// geometry running out of steering angle; clamping keeps the reference finite. +constexpr double kMaxOffsetCurvature = 0.99; +/// Below this squared norm a quaternion carries no orientation (the goal +/// checker's unmeasured tolerance fields come back all-zero). +constexpr double kMinQuatNorm2 = 1e-12; /// Planar yaw from a quaternion. double quat_yaw(const geometry_msgs::msg::Quaternion & q) @@ -78,15 +114,16 @@ double quat_yaw(const geometry_msgs::msg::Quaternion & q) return std::atan2(siny, cosy); } -/// One deceleration step toward zero, respecting the sign of the previous value. -/// A non-finite previous value (NaN or +/-inf) yields zero: an infinite measured -/// velocity would otherwise survive the ramp and be published as the command. -double brake_toward(double prev, double decel, double dt) +/// One step toward zero under the value's own rate bounds, which are the rate of +/// change allowed downward (`rate_low`, negative) and upward (`rate_upp`), so an +/// asymmetric model decelerates at its own rate in each direction. A non-finite +/// previous value (NaN or +/-inf) yields zero: an infinite measured velocity +/// would otherwise survive the ramp and be published as the command. +double brake_toward(double prev, double rate_low, double rate_upp, double dt) { if (!std::isfinite(prev)) {return 0.0;} - const double step = std::abs(decel) * dt; - if (prev > 0.0) {return std::max(0.0, prev - step);} - if (prev < 0.0) {return std::min(0.0, prev + step);} + if (prev > 0.0) {return std::max(0.0, prev - std::abs(rate_low) * dt);} + if (prev < 0.0) {return std::min(0.0, prev + std::abs(rate_upp) * dt);} return 0.0; } @@ -134,6 +171,17 @@ double required_bound( "' bound for the " + channel + " control; " + consequence); } +/// Whether every component of a Twist is finite. All six are published, and a +/// model is free to fill any of them, so all six are checked: testing only the +/// two a planar base consumes would let a non-finite linear.y or angular.x reach +/// the wire unexamined. +bool twist_is_finite(const geometry_msgs::msg::Twist & twist) +{ + return std::isfinite(twist.linear.x) && std::isfinite(twist.linear.y) && + std::isfinite(twist.linear.z) && std::isfinite(twist.angular.x) && + std::isfinite(twist.angular.y) && std::isfinite(twist.angular.z); +} + /// Apply the project log_level key to the plugin's own logger. void apply_log_level(rclcpp::Logger & logger, const std::string & level) { @@ -172,17 +220,27 @@ void ProxMpcController::configure( /* Parameter-validation helpers: out-of-range tuning values are clamped and * warned (non-fatal, to keep the controller available), matching the predictive * clamps; structurally invalid horizon sizing is fatal and throws below. */ - auto clamp_low = [this](const char * name, double & v, double lo) { + auto clamp_low = [this](const char * param_name, double & v, double lo, double def) { + if (!std::isfinite(v)) { + RCLCPP_WARN(logger_, "%s is not finite; using default %.3f.", param_name, def); + v = def; + return; + } if (v < lo) { - RCLCPP_WARN(logger_, "%s %.3f below %.3f; clamping.", name, v, lo); + RCLCPP_WARN(logger_, "%s %.3f below %.3f; clamping.", param_name, v, lo); v = lo; } }; - auto clamp_range = [this](const char * name, double & v, double lo, double hi) { + auto clamp_range = [this](const char * param_name, double & v, double lo, double hi, double def) { + if (!std::isfinite(v)) { + RCLCPP_WARN(logger_, "%s is not finite; using default %.3f.", param_name, def); + v = def; + return; + } if (v < lo || v > hi) { const double c = std::clamp(v, lo, hi); RCLCPP_WARN( - logger_, "%s %.3f outside [%.3f, %.3f]; clamping to %.3f.", name, v, lo, hi, c); + logger_, "%s %.3f outside [%.3f, %.3f]; clamping to %.3f.", param_name, v, lo, hi, c); v = c; } }; @@ -201,7 +259,7 @@ void ProxMpcController::configure( }; std::string model_plugin; - declare("model_plugin", model_plugin, std::string("prox_mpc_core/Bicycle")); + declare("model_plugin", model_plugin, std::string("prox_mpc_core/Unicycle")); double model_l = 0.0; declare("model_params.L", model_l, 1.6); /* Optional model input-velocity bound [m/s]; 0.0 (default) keeps the model's @@ -220,9 +278,9 @@ void ProxMpcController::configure( int nc_param = 0; declare("nc", nc_param, 20); declare("dt", dt_, 0.1); - if (np_param < 1 || nc_param < 1 || dt_ <= 0.0) { + if (np_param < 1 || nc_param < 1 || nc_param > np_param || !std::isfinite(dt_) || dt_ <= 0.0) { throw nav2_core::ControllerException( - "ProxMpcController: np >= 1, nc >= 1, dt > 0 required (got np=" + + "ProxMpcController: np >= 1, nc >= 1, nc <= np, dt > 0 required (got np=" + std::to_string(np_param) + ", nc=" + std::to_string(nc_param) + ", dt=" + std::to_string(dt_) + ")"); } @@ -231,6 +289,38 @@ void ProxMpcController::configure( declare("desired_linear_vel", desired_linear_vel_, 1.0); declare("curvature_gain", curvature_gain_, 0.0); + /* Reverse travel is opt-in: the reference speed becomes signed, which the + * speed limit and the deceleration ramp both have to carry, so a stack that + * does not plan reversing sections keeps the forward-only control bound. It is + * also travel the plugin cannot confirm is sensed: both guards follow the + * predicted trajectory, so they do cover a reversing one, but they see only + * what the costmap holds, and whether the platform sweeps behind itself is a + * property of its sensor rather than of this plugin. That is why an unguarded + * reverse is speed-capped where the model states no reverse envelope. */ + declare("allow_reversing", allow_reversing_, false); + /* Whether the plan's pose orientations may put the reference into reverse. + * Only a planner that sets them means anything by them, and a plan cannot say + * whether its planner did, so this is declared rather than inferred. */ + declare("reverse_from_plan_orientation", reverse_from_plan_orientation_, false); + + /* Travel direction is a discrete mode of a switched system. Re-deciding it + * every control cycle from the plan geometry alone, with no cost and no dwell, + * is what makes a direction change free enough to alternate; the two gates + * below are the standard remedy, and between them they also reproduce what a + * real drivetrain enforces, which is that a shift is accepted only at rest. + * A change therefore reads: hold the arc length, stop, dwell, then reverse. */ + declare("direction_switch_standstill_speed_mps", direction_switch_standstill_speed_mps_, 0.05); + declare("direction_switch_dwell_s", direction_switch_dwell_s_, 0.5); + /* A standstill threshold at or below zero is never met, which would freeze the + * reference at the first cusp; a negative dwell or band is meaningless. */ + direction_switch_standstill_speed_mps_ = std::max(direction_switch_standstill_speed_mps_, 1e-3); + direction_switch_dwell_s_ = std::max(direction_switch_dwell_s_, 0.0); + /* Seed the dwell spent. Nothing has been switched away from before the first + * task, so its first direction is free; the platform is at rest there anyway, + * which is the other half of what a change has to wait for. */ + dir_hold_s_ = direction_switch_dwell_s_; + declare("goal_settle_hysteresis_m", goal_settle_hysteresis_m_, 0.10); + goal_settle_hysteresis_m_ = std::max(goal_settle_hysteresis_m_, 0.0); /* Cost weights must be non-negative: a negative weight makes the QP Hessian * indefinite (non-convex sub-problem). Floor them at a small positive value. */ @@ -243,12 +333,12 @@ void ProxMpcController::configure( double r_weight = 0.0; declare("r_weight", r_weight, 0.1); double w_weight = 0.0; - declare("w_weight", w_weight, 100.0); - clamp_low("q_pos", q_pos, kMinCostWeight); - clamp_low("q_theta", q_theta, kMinCostWeight); - clamp_low("s_factor", s_factor, kMinCostWeight); - clamp_low("r_weight", r_weight, kMinCostWeight); - clamp_low("w_weight", w_weight, kMinCostWeight); + declare("w_weight", w_weight, 1000.0); + clamp_low("q_pos", q_pos, kMinCostWeight, 10.0); + clamp_low("q_theta", q_theta, kMinCostWeight, 1.0); + clamp_low("s_factor", s_factor, kMinCostWeight, 2.0); + clamp_low("r_weight", r_weight, kMinCostWeight, 0.1); + clamp_low("w_weight", w_weight, kMinCostWeight, 1000.0); /* Iteration caps are structural, like the horizon sizing: they reach the core * as size_t, so a negative value wraps to an astronomical bound (an effectively @@ -259,7 +349,7 @@ void ProxMpcController::configure( int max_ext_iter_qp = 0; declare("max_ext_iter_qp", max_ext_iter_qp, 10000); int max_iter_sqp = 0; - declare("max_iter_sqp", max_iter_sqp, 100); + declare("max_iter_sqp", max_iter_sqp, 1); if (max_int_iter_qp < 1 || max_ext_iter_qp < 1 || max_iter_sqp < 1) { throw nav2_core::ControllerException( "ProxMpcController: max_int_iter_qp >= 1, max_ext_iter_qp >= 1, max_iter_sqp >= 1 " @@ -271,12 +361,38 @@ void ProxMpcController::configure( * caps only). On timeout the solve reports non-convergence and this cycle brakes. */ double max_solve_time = 0.0; declare("max_solve_time", max_solve_time, 0.0); - clamp_low("max_solve_time", max_solve_time, 0.0); + clamp_low("max_solve_time", max_solve_time, 0.0, 0.0); bool qp_type = false; declare("qp_type", qp_type, false); bool guess = true; declare("guess", guess, true); + /* Cross-cycle QP warm start. The solver workspace is built once and updated in + * place, so proxsuite keeps its factorization and previous primal/dual iterate + * instead of being re-initialized every cycle. Rebuilding it per cycle was the + * wrong use of the API: it discarded the iterate the 'guess' parameter implies + * is being reused. */ + bool warm_start = true; + declare("warm_start", warm_start, true); declare("max_solver_failures", max_solver_failures_, 3); + if (max_solver_failures_ < 0) { + RCLCPP_WARN(logger_, "max_solver_failures %d < 0; clamping to 0.", max_solver_failures_); + max_solver_failures_ = 0; + } + /* Step [s] the deceleration ramp advances by on a braking cycle. 0 (default) + * measures the inter-cycle period, so a server running slower than dt still + * brakes at the model's declared rate, clamped below at dt and above at + * kMaxBrakePeriodFactor * dt so a stale measurement cannot collapse the ramp + * into a single step. A positive value overrides the measurement and is used + * as-is, for a deployment that wants the ramp independent of scheduling + * jitter. */ + declare("brake_period_s", brake_period_s_, 0.0); + clamp_low("brake_period_s", brake_period_s_, 0.0, 0.0); + /* Obstacle-slot capacity K per predicted node: the knob for how many obstacles + * reach the solver, one per node at the default. Every extra slot is paid on + * every cycle of every scenario, and the costmap scan cost is unchanged, so + * the whole increase lands in the QP: at the shipped unicycle sizing (n=3, + * m=2, Np=Nc=20), K=2 is 16% more decision variables and 33% more inequality + * rows than K=1, and K=4 is 49% and 100% more. */ declare("max_obstacles", max_obstacles_, 1); if (max_obstacles_ < 0) { RCLCPP_WARN(logger_, "max_obstacles %d < 0; clamping to 0.", max_obstacles_); @@ -284,10 +400,32 @@ void ProxMpcController::configure( } declare("safety_margin", safety_margin_, 0.1); declare("robot_radius", robot_radius_, 0.5); - clamp_low("safety_margin", safety_margin_, 0.0); - clamp_low("robot_radius", robot_radius_, 0.0); + clamp_low("safety_margin", safety_margin_, 0.0, 0.1); + clamp_low("robot_radius", robot_radius_, 0.0, 0.5); + /* Cross-check the avoidance disc against the footprint the costmap actually + * carries. d_safe = robot_radius + safety_margin sizes every keep-out + * half-plane, so a robot_radius below the footprint's circumscribed radius + * leaves part of the robot outside the keep-out with only the outline-only + * endpoint veto behind it. The parameter is never overwritten - an operator + * running a deliberately tighter disc keeps it - but the mismatch is named. */ + const double circumscribed_radius = + costmap_ros_->getLayeredCostmap()->getCircumscribedRadius(); + if (std::isfinite(circumscribed_radius) && robot_radius_ < circumscribed_radius) { + /* The advice is rounded up to the millimetre it is printed at. Reporting the + * circumscribed radius itself at %.3f names a value that can be smaller than + * the true one, and an operator who sets exactly what the message asks for + * would then trip the same warning again. */ + const double advised_radius = std::ceil(circumscribed_radius * 1000.0) / 1000.0; + RCLCPP_WARN( + logger_, + "robot_radius %.3f m is below the costmap footprint's circumscribed radius %.4f m, so " + "the obstacle keep-out (d_safe = robot_radius + safety_margin = %.3f m) is undersized " + "for this footprint and the endpoint footprint veto is the only remaining guard. Raise " + "robot_radius to at least %.3f m, or shrink the footprint.", + robot_radius_, circumscribed_radius, robot_radius_ + safety_margin_, advised_radius); + } declare("cbf_gamma", cbf_gamma_, 1.0); - clamp_range("cbf_gamma", cbf_gamma_, kMinCbfGamma, 1.0); + clamp_range("cbf_gamma", cbf_gamma_, kMinCbfGamma, 1.0, 1.0); declare("costmap_cost_threshold", costmap_cost_threshold_, 200); if (costmap_cost_threshold_ < 0 || costmap_cost_threshold_ > kMaxCostThreshold) { const int c = std::clamp(costmap_cost_threshold_, 0, kMaxCostThreshold); @@ -297,7 +435,7 @@ void ProxMpcController::configure( costmap_cost_threshold_ = c; } declare("obstacle_cluster_radius", obstacle_cluster_radius_, 0.3); - clamp_low("obstacle_cluster_radius", obstacle_cluster_radius_, 0.0); + clamp_low("obstacle_cluster_radius", obstacle_cluster_radius_, 0.0, 0.3); declare("max_obstacle_scan_cells", max_obstacle_scan_cells_, kMaxScanHalfWidth); if (max_obstacle_scan_cells_ < 1) { RCLCPP_WARN( @@ -306,13 +444,20 @@ void ProxMpcController::configure( max_obstacle_scan_cells_ = 1; } - /* Predictive (dynamic) obstacle avoidance. predict_obstacles off reproduces the - * costmap-only behavior bit-for-bit; the rest size the predictive + hybrid fill. */ - declare("predict_obstacles", predict_obstacles_, false); + /* Predictive (dynamic) obstacle avoidance, on by default: the costmap-only + * fill reacts to where an obstacle was seen, which is measurably the weaker + * configuration once more than one obstacle moves. With no tracker publishing, + * or a stale message, the fill degrades to the costmap-only path, so the + * default costs a subscription rather than a behavior change. Setting + * predict_obstacles off reproduces that behavior bit-for-bit. */ + declare("predict_obstacles", predict_obstacles_, true); declare("obstacle_topic", obstacle_topic_, std::string("tracked_obstacles")); declare("obstacle_timeout", obstacle_timeout_, 0.5); declare("dynamic_speed_threshold", dynamic_speed_threshold_, 0.1); declare("prediction_uncertainty_growth", prediction_uncertainty_growth_, 0.0); + declare("prediction_forward_shadow_s", prediction_forward_shadow_s_, 0.0); + declare("obstacle_yield_band_m", obstacle_yield_band_m_, 0.0); + declare("obstacle_yield_caps_speed", obstacle_yield_caps_speed_, false); declare("max_dynamic_obstacles", max_dynamic_obstacles_, 2); declare("max_dynamic_obstacle_radius", max_dynamic_obstacle_radius_, 0.0); @@ -321,10 +466,12 @@ void ProxMpcController::configure( /* Validate the predictive parameters; clamp out-of-range values (non-fatal, to * keep the controller available) and warn, matching the cruise-speed clamp. */ - clamp_low("obstacle_timeout", obstacle_timeout_, 0.0); - clamp_low("dynamic_speed_threshold", dynamic_speed_threshold_, 0.0); - clamp_low("prediction_uncertainty_growth", prediction_uncertainty_growth_, 0.0); - clamp_low("max_dynamic_obstacle_radius", max_dynamic_obstacle_radius_, 0.0); + clamp_low("obstacle_timeout", obstacle_timeout_, 0.0, 0.5); + clamp_low("dynamic_speed_threshold", dynamic_speed_threshold_, 0.0, 0.1); + clamp_low("prediction_uncertainty_growth", prediction_uncertainty_growth_, 0.0, 0.0); + clamp_low("prediction_forward_shadow_s", prediction_forward_shadow_s_, 0.0, 0.0); + clamp_low("obstacle_yield_band_m", obstacle_yield_band_m_, 0.0, 0.0); + clamp_low("max_dynamic_obstacle_radius", max_dynamic_obstacle_radius_, 0.0, 0.0); if (max_dynamic_obstacles_ < 0) { RCLCPP_WARN(logger_, "max_dynamic_obstacles %d < 0; clamping to 0.", max_dynamic_obstacles_); max_dynamic_obstacles_ = 0; @@ -352,15 +499,66 @@ void ProxMpcController::configure( if (model_v_max > 0.0) { model_params["v_max"] = model_v_max; model_params["v_min"] = (model_v_min < 0.0) ? model_v_min : -model_v_max; + } else if (model_v_min < 0.0) { + /* A reverse bound is honoured on its own. Model::overrideBound keeps the side + * whose key is absent, so capping reverse travel no longer requires naming a + * forward cap the configuration does not mean to change. */ + model_params["v_min"] = model_v_min; } model_->configure(model_params); - wheelbase_ = model_l; n_ = model_->getN(); m_ = model_->getM(); + readModelMapping(*model_, model_plugin); readModelBounds(*model_, model_plugin); + /* allow_reversing gates the control box, not only the reference. Left to the + * reference alone, the solver still held a negative lower bound on the speed + * control and could command reverse on a robot configured forward-only + * whenever the cost made it attractive - most easily while manoeuvring around + * an obstacle, which is where reverse is least wanted. The bound is narrowed + * rather than the command clamped, so the plan the solver returns is one the + * robot is actually allowed to execute. */ + if (!allow_reversing_ && v_min_ < 0.0) { + RCLCPP_INFO( + logger_, + "allow_reversing is false; narrowing the model's linear control bound from [%.3f, %.3f] " + "to [0.000, %.3f] so the solver cannot plan reverse travel.", v_min_, v_max_, v_max_); + model_->updateIneq("u", idx_v_, 0.0, v_max_); + v_min_ = 0.0; + } + /* Reversing was asked for without a reverse bound to go with it. The model's + * own lower bound is a modelling limit, not a safety choice - for the bundled + * models it is -v_max, so enabling reversing would otherwise silently + * authorise reverse at full cruise speed on a platform whose rear coverage + * this plugin has no way to check. */ + if (allow_reversing_ && model_v_min >= 0.0 && v_min_ < -kDefaultReverseSpeed) { + RCLCPP_INFO( + logger_, + "allow_reversing is true but model_params.v_min was not set; capping reverse travel at " + "%.3f m/s (was %.3f). Set model_params.v_min explicitly to the platform's real reverse " + "envelope once its rear coverage is established.", -kDefaultReverseSpeed, v_min_); + model_->updateIneq("u", idx_v_, -kDefaultReverseSpeed, v_max_); + v_min_ = -kDefaultReverseSpeed; + } + if (allow_reversing_ && v_min_ >= 0.0) { + RCLCPP_WARN( + logger_, + "allow_reversing is set but model '%s' declares no reverse travel (u[%zu] lower bound " + "%.3f), so the reference stays forward-only.", model_plugin.c_str(), idx_v_, v_min_); + } - /* Cruise speed must sit within the model's speed bound. */ + /* Cruise speed must be finite and sit within the model's speed bound. The + * finiteness check comes first because the bound comparison below, like every + * bare "<"/">", is false for NaN: a non-finite cruise speed would pass it, + * poison the reference and turn every cycle into a non-finite solve, a brake + * and eventually a recovery, with nothing said at configure(). */ + if (!std::isfinite(desired_linear_vel_)) { + const double default_desired_linear_vel = 1.0; + RCLCPP_WARN( + logger_, "desired_linear_vel is not finite; using default %.3f.", + default_desired_linear_vel); + desired_linear_vel_ = default_desired_linear_vel; + } if (desired_linear_vel_ > v_max_) { RCLCPP_WARN( logger_, "desired_linear_vel %.3f exceeds model v_max %.3f; clamping.", @@ -368,10 +566,16 @@ void ProxMpcController::configure( desired_linear_vel_ = v_max_; } - /* Cost weights sized to the model (matches the demo assembly). */ + /* Cost weights sized to the model (matches the demo assembly), placed through + * the model's own declared mapping rather than at state columns 0 and 1: a + * model that carries its position elsewhere is legal whenever the in-loop + * obstacle term is off, and indexing by position would then weight a heading + * as a position and a position as a heading with no diagnostic. Every state + * the mapping does not name - a steering angle, say - keeps q_theta. */ VectorXd q_diag = VectorXd::Constant(n_, q_theta); - q_diag(0) = q_pos; - q_diag(1) = q_pos; + q_diag(idx_x_) = q_pos; + q_diag(idx_y_) = q_pos; + q_diag(idx_yaw_) = q_theta; const MatrixXd Q = q_diag.asDiagonal(); const MatrixXd S = s_factor * Q; const MatrixXd R = r_weight * MatrixXd::Identity(m_, m_); @@ -394,6 +598,7 @@ void ProxMpcController::configure( mpc_->setMaxIterSQP(static_cast(max_iter_sqp)); mpc_->setMaxSolveTime(max_solve_time); mpc_->setGuess(guess); + mpc_->setWarmStart(warm_start); mpc_->setQPtype(qp_type); mpc_->setCbfGamma(cbf_gamma_); mpc_->setMaxObs(k_obs); @@ -435,20 +640,155 @@ void ProxMpcController::configure( plugin_name_.c_str(), model_plugin.c_str(), np_, nc_, dt_, k_obs); } +void ProxMpcController::readModelMapping( + prox_mpc::Model & model, const std::string & model_plugin) +{ + const prox_mpc::PlanarMapping mapping = model.getPlanarMapping(); + auto reject = [&model_plugin](const std::string & why) { + throw nav2_core::ControllerException( + "ProxMpcController: model '" + model_plugin + "' " + why); + }; + + /* Three planar states and one speed control are the least this controller can + * drive; below that every index below is out of range, and EIGEN_NO_DEBUG + * turns that into a silent read rather than an abort. */ + if (n_ < 3) { + reject("declares " + std::to_string(n_) + " states; at least 3 (x, y, yaw) are required"); + } + if (m_ < 1) { + reject("declares no control input"); + } + if (mapping.idx_x >= n_ || mapping.idx_y >= n_ || mapping.idx_yaw >= n_) { + reject("maps x, y or yaw to a state index outside its own state vector"); + } + if (mapping.idx_x == mapping.idx_y || mapping.idx_x == mapping.idx_yaw || + mapping.idx_y == mapping.idx_yaw) + { + reject("maps two planar quantities to the same state index"); + } + if (mapping.idx_speed >= m_) { + reject("maps the longitudinal speed to a control index outside its own control vector"); + } + if (!std::isfinite(mapping.ref_offset_x) || !std::isfinite(mapping.ref_offset_y)) { + reject("declares a non-finite reference-point offset"); + } + + has_steering_ = mapping.idx_steering != prox_mpc::PlanarMapping::kNoIndex; + has_steer_rate_ = has_steering_ && + mapping.idx_steer_rate != prox_mpc::PlanarMapping::kNoIndex; + if (has_steer_rate_) { + if (mapping.idx_steer_rate >= m_ || mapping.idx_steer_rate == mapping.idx_speed) { + reject("maps its steering rate to an unusable control index"); + } + } + if (has_steering_) { + if (mapping.idx_steering >= n_ || mapping.idx_steering == mapping.idx_x || + mapping.idx_steering == mapping.idx_y || mapping.idx_steering == mapping.idx_yaw) + { + reject("maps its steering angle to an unusable state index"); + } + /* The steering reference is built from the wheelbase, so a model that + * carries a steering angle has to say what its wheelbase is. The parameter + * forwarded as model_params.L is not read back here: a model free to ignore + * that key would otherwise be driven on a wheelbase it does not use. */ + if (!std::isfinite(mapping.wheelbase) || mapping.wheelbase <= 0.0) { + reject( + "carries a steering angle but declares no wheelbase; override " + "getPlanarMapping() to declare one"); + } + /* The steering inverse is derived for a reference point on the body x axis, + * which is where both the front and the rear axle sit. */ + if (mapping.ref_offset_y != 0.0) { + reject("carries a steering angle and a lateral reference-point offset, which is unsupported"); + } + } + + idx_x_ = mapping.idx_x; + idx_y_ = mapping.idx_y; + idx_yaw_ = mapping.idx_yaw; + idx_v_ = mapping.idx_speed; + idx_steer_ = has_steering_ ? mapping.idx_steering : 0; + idx_steer_rate_ = has_steer_rate_ ? mapping.idx_steer_rate : 0; + ref_offset_x_ = mapping.ref_offset_x; + ref_offset_y_ = mapping.ref_offset_y; + wheelbase_ = has_steering_ ? mapping.wheelbase : 0.0; +} + void ProxMpcController::readModelBounds(prox_mpc::Model & model, const std::string & model_plugin) { + const std::size_t m = model.getM(); v_max_ = required_bound( - model, model_plugin, "u", 0, 2, "linear", + model, model_plugin, "u", idx_v_, 2, "linear", + "the speed cap would collapse to zero and the controller would never move."); + /* The lower bound is cached alongside it so a runtime speed limit narrows the + * model's declared range instead of overwriting it; the same entry carries + * both sides, so this lookup cannot fail once the one above succeeded. */ + v_min_ = required_bound( + model, model_plugin, "u", idx_v_, 1, "linear", "the speed cap would collapse to zero and the controller would never move."); + /* A declared bound is not the same as a usable one: required_bound only + * throws when the entry is absent, so a model declaring an upper speed bound + * of zero (or a non-finite one, which every comparison below passes) reaches + * here, clamps the cruise speed to zero and never moves - the exact outcome + * the missing-bound message says it prevents. */ + if (!(v_max_ > 0.0)) { + throw nav2_core::ControllerException( + "ProxMpcController: model '" + model_plugin + "' declares an upper 'u' bound of " + + std::to_string(v_max_) + " for the linear control; the speed cap would collapse " + "to zero and the controller would never move."); + } max_linear_vel_ = v_max_; - a_dec_lin_ = std::abs( - required_bound( - model, model_plugin, "du", 0, 1, "linear", - "the solver-failure brake would never reach zero.")); - a_dec_ang_ = std::abs( + fallback_ramp_lin_ = std::abs( required_bound( - model, model_plugin, "du", 1, 1, "angular", + model, model_plugin, "du", idx_v_, 1, "linear", "the solver-failure brake would never reach zero.")); + /* The second body-twist channel only exists to be ramped when the model has a + * second control to source a rate from. A single-control model is legitimate - + * the planar contract asks for one speed control and no more - so it keeps the + * default here rather than being asked for a bound on a channel it never + * declared, which would reject it while naming an "angular control" it does + * not have. The gate is the control count and not the declared steering rate: + * for a unicycle, channel 1 is a genuine body yaw rate and is exactly what + * this ramp wants, while the model declares no steering at all. */ + if (m > 1) { + fallback_ramp_ang_ = std::abs( + required_bound( + model, model_plugin, "du", 1, 1, "angular", + "the solver-failure brake would never reach zero.")); + } + + /* Every declared control-rate bound, sign preserved, so the brake ramps each + * control channel at the model's own rate in each direction. A channel with no + * declared bound stays unbounded and is taken to zero in one step: there is no + * rate to respect, and freezing it at its last commanded value would leave the + * brake unable to stop that channel at all. */ + du_low_.assign(m, -std::numeric_limits::infinity()); + du_upp_.assign(m, std::numeric_limits::infinity()); + for (const auto & entry : model.getIneq("du")) { + const auto idx = static_cast(entry.second[0]); + if (idx < m) { + du_low_[idx] = entry.second[1]; + du_upp_[idx] = entry.second[2]; + } + } + last_cmd_u_ = VectorXd::Zero(m); + + /* Rate at which the steering belief may be decayed on a rejected cycle, for a + * model that carries a steering state: the bound on the steering-rate control. + * Left at zero when the model declares none, which freezes the belief rather + * than moving it at a rate the model never stated. */ + steer_rate_low_ = 0.0; + steer_rate_upp_ = 0.0; + if (has_steer_rate_) { + /* The model declares which control carries its steering-angle rate; the + * bound on that channel is how fast the belief may be moved. */ + for (const auto & entry : model.getIneq("u")) { + if (static_cast(entry.second[0]) == idx_steer_rate_) { + steer_rate_low_ = entry.second[1]; + steer_rate_upp_ = entry.second[2]; + } + } + } } void ProxMpcController::cleanup() @@ -462,10 +802,13 @@ void ProxMpcController::cleanup() diag_pub_.reset(); obstacle_sub_.reset(); { + /* Both clears under the mutex, matching deactivate(): the subscription is + * already gone by here, but splitting them left the two teardown paths + * disagreeing about which member the mutex covers. */ std::lock_guard lock(obstacles_mutex_); latest_obstacles_.reset(); + predicted_obstacles_.clear(); } - predicted_obstacles_.clear(); costmap_ros_.reset(); tf_.reset(); } @@ -475,6 +818,7 @@ void ProxMpcController::activate() failure_count_ = 0; veto_count_ = 0; steering_state_ = 0.0; + last_cmd_u_.setZero(); last_cmd_v_ = 0.0; last_cmd_w_ = 0.0; cancelling_ = false; @@ -492,12 +836,16 @@ void ProxMpcController::deactivate() if (diag_pub_) {diag_pub_->on_deactivate();} /* Drop cached perception so a re-activated controller does not act on a tracked * obstacle observed before deactivation; it resumes costmap-only until a fresh - * message arrives (the staleness timeout would also catch this). */ + * message arrives (the staleness timeout would also catch this). Both clears + * are made under the mutex: the controller server deactivates its action + * server, and so joins the thread that runs computeVelocityCommands, before + * calling this, but that ordering is an upstream implementation detail this + * teardown should not depend on. */ { std::lock_guard lock(obstacles_mutex_); latest_obstacles_.reset(); + predicted_obstacles_.clear(); } - predicted_obstacles_.clear(); RCLCPP_INFO(logger_, "Deactivating ProxMpcController '%s'.", plugin_name_.c_str()); } @@ -512,6 +860,16 @@ geometry_msgs::msg::TwistStamped ProxMpcController::computeVelocityCommands( const geometry_msgs::msg::Twist & velocity, nav2_core::GoalChecker * goal_checker) { + /* Close the previous cycle's timing measurement here, before any gate can + * return or throw, so the deceleration ramp below and the telemetry at the end + * read one and the same inter-cycle period and no path out of the cycle leaves + * the reference point stale for the next one. */ + const double cycle_period_ms = markCycleStart(); + + /* Advance the direction-change dwell on the measured period, falling back to + * the nominal step on the first cycle of a task, where no period exists yet. */ + dir_hold_s_ += std::isfinite(cycle_period_ms) ? cycle_period_ms * 1e-3 : dt_; + /* Apply a speed limit requested since the last cycle. setSpeedLimit() runs on * the node's executor thread while this method runs on the action server's own * thread, so the model's inequality map is mutated here, where nothing else @@ -527,16 +885,122 @@ geometry_msgs::msg::TwistStamped ProxMpcController::computeVelocityCommands( cmd.header.frame_id = costmap_ros_->getBaseFrameID(); cmd.header.stamp = clock_->now(); + /* Current pose in the costmap global frame (the server supplies it there). + * Read before the fail-safe ramp below, which needs it to set the model state + * it maps the braked controls through; its finiteness is checked once the ramp + * exists to handle the failure. */ + const double cx = pose.pose.position.x; + const double cy = pose.pose.position.y; + const double ctheta = quat_yaw(pose.pose.orientation); + /* Deceleration ramp shared by the cancel, solver-failure, and veto paths. It - * ramps down from the server-measured velocity (RPP/MPPI style) so the brake - * tracks the robot's actual speed rather than the last command, which may be - * stale (for example a cycle-1 failure while already moving). A non-finite - * measured velocity yields a safe zero through brake_toward. */ + * ramps the model's own controls toward zero under the model's own control-rate + * bounds and maps the result through the model, the same seam the accepted + * command path uses: a model whose controls are not a body twist (the bicycle's + * second control is a steering rate, not a yaw rate) has no meaningful + * twist-space ramp. The speed channel ramps down from the server-measured + * velocity (RPP/MPPI style) so the brake tracks the robot's actual speed rather + * than a stale command; the remaining channels have no measurement and ramp + * from their last commanded value. A non-finite measured velocity yields a safe + * zero through brake_toward. */ auto make_brake = [&]() -> geometry_msgs::msg::TwistStamped { - last_cmd_v_ = brake_toward(velocity.linear.x, a_dec_lin_, dt_); - last_cmd_w_ = brake_toward(velocity.angular.z, a_dec_ang_, dt_); - cmd.twist.linear.x = last_cmd_v_; - cmd.twist.angular.z = last_cmd_w_; + /* Step with brake_period_s_ when the operator set one, otherwise with the + * inter-cycle period this cycle measured for its telemetry rather than the + * configured step, so a server running slower than dt_ still brakes at the + * model's declared rate; the measurement is clamped below at dt_ so the + * ramp is never slower than the configured one, and above so a stale + * reading cannot turn one step into an abrupt stop. The first cycle of a + * task has no measurement (NaN) and falls back to dt_. The ramp saturates + * at zero either way, so an over-large step shortens the stop rather than + * reversing or overshooting it. */ + double period = brake_period_s_; + if (period <= 0.0) { + const double measured_period = + std::isfinite(cycle_period_ms) ? 1e-3 * cycle_period_ms : dt_; + period = std::clamp(measured_period, dt_, kMaxBrakePeriodFactor * dt_); + } + + /* A rejected cycle used to freeze the steering belief, so the next solve + * linearized about an angle the wheels no longer hold: every rejected cycle + * brakes, and a downstream twist-to-steering converter straightens the + * wheels as the commanded yaw rate falls. Decay it toward zero at the + * model's own steering-rate bound instead, which is open-loop but correct + * in direction and rate and cannot jump. A model that declares no steering + * rate leaves the bound at zero, which keeps the belief frozen rather than + * guessing a rate for it. */ + if (has_steering_) { + steering_state_ = + brake_toward(steering_state_, steer_rate_low_, steer_rate_upp_, period); + } + + /* Seed the ramp from the measured twist through the model's own inverse of + * its twist mapping, channel by channel. The model is the only thing that + * knows what its controls mean: for a front-axle-referenced model the + * speed channel is a front-wheel speed, and writing the base_link speed + * into it projects the measurement by cos(delta) a second time on the way + * out, which turns a ramp step into a step change at large steering + * angles. + * + * fromTwist() states per channel what a body twist determines. A finite + * entry is a measurement of that control and is taken; a non-finite entry + * says the twist does not observe it - a steering rate, for instance - and + * that channel keeps its last commanded value, the only estimate there is + * for it. A measurement that is itself non-finite is held the same way, + * so a broken velocity estimate decelerates the last command rather than + * entering the ramp. No channel is named here: the controller applies what + * the model declared rather than a rule of its own. */ + VectorXd u_brake = last_cmd_u_; + const VectorXd u_measured = model_->fromTwist(velocity); + const Eigen::Index determined = std::min(u_brake.size(), u_measured.size()); + for (Eigen::Index j = 0; j < determined; ++j) { + if (std::isfinite(u_measured(j))) {u_brake(j) = u_measured(j);} + } + for (Eigen::Index j = 0; j < u_brake.size(); ++j) { + u_brake(j) = brake_toward( + u_brake(j), du_low_[static_cast(j)], + du_upp_[static_cast(j)], period); + } + last_cmd_u_ = u_brake; + + /* The model reads its own state through toTwist, and the accepted path's + * setX runs past the veto, so no braking cycle reaches it: set the state + * here from the current pose, with a non-finite pose leaving it at zero. */ + VectorXd brake_state = VectorXd::Zero(n_); + if (std::isfinite(cx) && std::isfinite(cy) && std::isfinite(ctheta)) { + brake_state(idx_x_) = cx + ref_offset_x_ * std::cos(ctheta) - + ref_offset_y_ * std::sin(ctheta); + brake_state(idx_y_) = cy + ref_offset_x_ * std::sin(ctheta) + + ref_offset_y_ * std::cos(ctheta); + brake_state(idx_yaw_) = ctheta; + } + if (has_steering_) {brake_state(idx_steer_) = steering_state_;} + model_->setX(brake_state); + + geometry_msgs::msg::Twist twist = model_->toTwist(u_brake); + if (!twist_is_finite(twist)) { + /* Degraded mode of last resort: a model that maps braked controls to a + * non-finite twist would otherwise publish it on the safety path, so fall + * back to ramping the measured twist within the channel-0 and channel-1 + * deceleration limits, which is what this path did before it went through + * the model. */ + RCLCPP_WARN_THROTTLE( + logger_, *clock_, 2000, + "ProxMpcController: the model mapped the braked controls to a non-finite twist; " + "ramping the measured twist directly this cycle."); + twist = geometry_msgs::msg::Twist(); + twist.linear.x = brake_toward( + velocity.linear.x, fallback_ramp_lin_, fallback_ramp_lin_, period); + twist.angular.z = brake_toward( + velocity.angular.z, fallback_ramp_ang_, fallback_ramp_ang_, period); + } + last_cmd_v_ = twist.linear.x; + last_cmd_w_ = twist.angular.z; + /* The ramped controls are what the robot is actually given, so they become + * the anchor of the next cycle's control-rate constraint. Leaving the last + * accepted solve's first control there would let the next cycle plan a step + * away from a command the robot never received. */ + mpc_->setU0(u_brake); + cmd.twist = twist; return cmd; }; @@ -553,10 +1017,6 @@ geometry_msgs::msg::TwistStamped ProxMpcController::computeVelocityCommands( return make_brake(); }; - /* Current pose in the costmap global frame (the server supplies it there). */ - const double cx = pose.pose.position.x; - const double cy = pose.pose.position.y; - const double ctheta = quat_yaw(pose.pose.orientation); if (!std::isfinite(cx) || !std::isfinite(cy) || !std::isfinite(ctheta)) { return fail("non-finite robot pose"); } @@ -596,43 +1056,192 @@ geometry_msgs::msg::TwistStamped ProxMpcController::computeVelocityCommands( const auto & pp = global_plan_.poses[i].pose.position; gx[i] = tx + ct * pp.x - st * pp.y; gy[i] = ty + st * pp.x + ct * pp.y; + if (!std::isfinite(gx[i]) || !std::isfinite(gy[i])) { + return fail("non-finite plan pose"); + } if (i > 0) { s[i] = s[i - 1] + std::hypot(gx[i] - gx[i - 1], gy[i] - gy[i - 1]); } } /* Project the current pose onto the plan (forward-only), giving the arc-length - * offset s0 the sampling starts from. */ + * offset s0 the sampling starts from. The projection is onto the plan segments + * and not onto its vertices: taking the nearest vertex's arc length quantizes + * s0 to the vertex spacing, about 5 cm for the NavFn and Smac plans emitted at + * the default 0.05 m costmap resolution and unbounded for a coarse or sparse + * third-party plan. */ if (plan_index_ >= plan_size) {plan_index_ = 0;} std::size_t best = plan_index_; + double best_t = 0.0; double best_d2 = std::numeric_limits::max(); - for (std::size_t i = plan_index_; i < plan_size; ++i) { - const double d2 = (gx[i] - cx) * (gx[i] - cx) + (gy[i] - cy) * (gy[i] - cy); + for (std::size_t i = plan_index_; i + 1 < plan_size; ++i) { + const double ex = gx[i + 1] - gx[i]; + const double ey = gy[i + 1] - gy[i]; + const double len2 = ex * ex + ey * ey; + /* A duplicate consecutive plan position carries no direction; project onto + * its start vertex instead of dividing by zero. */ + const double t = (len2 > 1e-18) ? + std::clamp(((cx - gx[i]) * ex + (cy - gy[i]) * ey) / len2, 0.0, 1.0) : 0.0; + const double px = gx[i] + t * ex; + const double py = gy[i] + t * ey; + const double d2 = (px - cx) * (px - cx) + (py - cy) * (py - cy); if (d2 < best_d2) { best_d2 = d2; best = i; + best_t = t; } } plan_index_ = best; - const double s0 = s[best]; + /* s is the cumulative segment length, so the arc length at the projected point + * is exact rather than interpolated. A single-pose plan, and a plan already + * tracked to its last vertex, leave the loop unentered at best_t = 0. */ + const double s0 = + (best + 1 < plan_size) ? s[best] + best_t * (s[best + 1] - s[best]) : s[best]; + + /* Travel direction, and the arc length the reference may not pass. + * + * A plan's pose orientations say which way the robot faces along it, so a + * segment whose direction opposes its own start pose's heading is driven in + * reverse. With allow_reversing off the reference stays forward-only, which is + * what every previous release produced. With it on, the direction under the + * robot sets the sign of the reference speed and the reference is truncated at + * the first direction change, so one horizon never spans a cusp - the same + * bound upstream's regulated pure pursuit places on the same problem. + * + * That reading holds only for a planner that sets those orientations, and a + * plan cannot say whether it does: NavFn and the Smac 2D planners leave every + * pose at the identity quaternion, which is indistinguishable from a genuine + * straight reverse plan whose poses all face the same way. With one constant + * pose yaw the expression below collapses to the segment's component along that + * fixed heading - the segment's x component in the plan frame - so every path + * running the other way reads as a reverse plan however the robot faces, and + * the robot drives the whole path backwards instead of turning around; a path + * whose x component changes sign flips the reference cycle to cycle. Which it + * is, is a property of the planner, so it is declared rather than guessed: + * reverse_from_plan_orientation defaults false and the reference stays + * forward-only, and a deployment running a cusp-emitting planner (Smac + * Hybrid-A*, State Lattice) sets it true to get the cusp handling above. The + * control box keeps whatever reverse travel allow_reversing granted either way, + * so the solver may still back out of a keep-out; it is just not asked to + * reverse along the path. */ + auto plan_direction = [&](std::size_t i) { + const double ex = gx[i + 1] - gx[i]; + const double ey = gy[i + 1] - gy[i]; + const double yaw = quat_yaw(global_plan_.poses[i].pose.orientation) + tyaw; + return std::cos(yaw) * ex + std::sin(yaw) * ey; + }; + double s_end = s.back(); + if (allow_reversing_ && reverse_from_plan_orientation_ && v_min_ < 0.0 && + best + 1 < plan_size) + { + /* The direction the plan asks for under the robot, and the gates that decide + * whether this cycle may act on it. Travel direction is held in dir_ rather + * than re-read here, because a mode re-chosen every cycle at no cost and with + * no dwell is free to alternate. A change is accepted only from rest and only + * once the dwell has run; until both hold, the reference is pinned to the + * current arc length, so v_ref falls to zero and the deceleration ramp brings + * the platform to the standstill the change is waiting on. A cusp is then + * driven the way a vehicle drives one: arrive, stop, shift, pull away. */ + const double d0 = plan_direction(best); + const double dir_cmd = (d0 < 0.0) ? -1.0 : 1.0; + if (dir_cmd != dir_) { + if (std::abs(last_cmd_v_) <= direction_switch_standstill_speed_mps_ && + dir_hold_s_ >= direction_switch_dwell_s_) + { + dir_ = dir_cmd; + dir_hold_s_ = 0.0; + } else { + s_end = s0; + } + } + /* Truncate at the next cusp so one horizon never spans a direction change. + * Skipped while a change is pending, where the reference is already held. */ + if (s_end > s0) { + for (std::size_t i = best + 1; i + 1 < plan_size; ++i) { + const double d = plan_direction(i); + if (d != 0.0 && ((d < 0.0) != (dir_ < 0.0))) { + s_end = s[i]; + break; + } + } + } + } else { + /* Forward-only: leave no latched reverse state for the next task to inherit. */ + dir_ = 1.0; + } + const double dir = dir_; - /* Cruise speed, tapered so the horizon does not overshoot the plan end, and - * clamped by any active speed limit (goal-hold near the end). */ + /* Cruise speed, tapered so the horizon does not overshoot the plan end (or the + * cusp it stops at), and clamped by any active speed limit (goal-hold near the + * end). It is a magnitude here; `dir` applies the sign once it is final. */ const double horizon_time = static_cast(np_) * dt_; - const double remaining = s.back() - s0; + const double remaining = s_end - s0; double v_ref = std::min({desired_linear_vel_, max_linear_vel_, remaining / horizon_time}); if (v_ref < 0.0) {v_ref = 0.0;} - /* Sample a plan pose at a given arc length (holds the final pose past the end). */ + /* Goal-checker tolerances, read once. The xy tolerance eases the cruise speed + * into the goal region below; the yaw tolerance is how the checker says it + * enforces a terminal heading at all, which is what turns the terminal-yaw + * reference on. The pointer is read but never retained. + * + * Each position field IS the radial bound, not a per-axis half-extent: upstream + * SimpleGoalChecker tests dx*dx + dy*dy <= T*T and writes the same scalar T + * into position.x and position.y, so hypot() would report sqrt(2)*T and start + * the taper 41% too far out. std::min is deliberately NOT RPP's + * position.x-only read (regulated_pure_pursuit_controller.cpp:180): the two + * are identical for every goal checker Nav2 ships, and the minimum is the + * conservative reading for a custom anisotropic checker whose y tolerance is + * tighter than its x. Do not "correct" this back to the x field alone. + * + * Unmeasured tolerance fields come back as std::numeric_limits::lowest() + * (negative) and an all-zero quaternion, so both are screened. */ + double xy_tol = 0.0; + double yaw_tol = 0.0; + bool have_xy_tol = false; + bool have_yaw_tol = false; + if (goal_checker != nullptr) { + geometry_msgs::msg::Pose pose_tol; + geometry_msgs::msg::Twist vel_tol; + if (goal_checker->getTolerances(pose_tol, vel_tol)) { + xy_tol = std::min(pose_tol.position.x, pose_tol.position.y); + have_xy_tol = std::isfinite(xy_tol) && pose_tol.position.x > 0.0 && + pose_tol.position.y > 0.0; + const auto & qt = pose_tol.orientation; + if (qt.x * qt.x + qt.y * qt.y + qt.z * qt.z + qt.w * qt.w > kMinQuatNorm2) { + yaw_tol = std::abs(quat_yaw(qt)); + have_yaw_tol = std::isfinite(yaw_tol) && yaw_tol > 0.0 && yaw_tol < M_PI; + } + } + } + + /* Terminal heading. Past the plan end the reference pose becomes the goal + * pose, so the horizon settles onto the orientation the goal carries instead + * of holding whatever the last two plan vertices point at. It is engaged only + * when the goal checker publishes a yaw tolerance it enforces, and never on a + * reference truncated at a cusp, whose end is not the goal. */ + bool have_terminal_yaw = false; + double terminal_yaw = 0.0; + if (have_yaw_tol && s_end >= s.back() && plan_size >= 2) { + const auto & qg = global_plan_.poses.back().pose.orientation; + if (qg.x * qg.x + qg.y * qg.y + qg.z * qg.z + qg.w * qg.w > kMinQuatNorm2) { + terminal_yaw = quat_yaw(qg) + tyaw; + have_terminal_yaw = std::isfinite(terminal_yaw); + } + } + + /* Sample a plan pose at a given arc length. Past the end (or the cusp the + * reference stops at) it holds the final pose. */ auto sample = [&](double sk, double & x, double & y, double & th) { if (sk <= 0.0) {sk = 0.0;} + if (sk > s_end) {sk = s_end;} if (sk >= s.back() || plan_size < 2) { x = gx.back(); y = gy.back(); /* Single-pose plan: the pose orientation is in the plan frame, so it * carries the same yaw offset the positions above were rotated by. */ th = (plan_size < 2) ? quat_yaw(global_plan_.poses.back().pose.orientation) + tyaw : - std::atan2(gy.back() - gy[plan_size - 2], gx.back() - gx[plan_size - 2]); + (have_terminal_yaw ? terminal_yaw : + std::atan2(gy.back() - gy[plan_size - 2], gx.back() - gx[plan_size - 2])); return; } std::size_t i = 0; @@ -646,32 +1255,94 @@ geometry_msgs::msg::TwistStamped ProxMpcController::computeVelocityCommands( const double t = seg > 1e-9 ? (sk - s[i]) / seg : 0.0; x = gx[i] + t * (gx[i + 1] - gx[i]); y = gy[i] + t * (gy[i + 1] - gy[i]); - th = std::atan2(gy[i + 1] - gy[i], gx[i + 1] - gx[i]); + /* A duplicate consecutive plan position collapses this segment to zero + * length, which carries no heading; walk forward to the next segment with + * positive length instead of feeding atan2(0, 0) a degenerate delta. */ + std::size_t hi = i; + while (s[hi + 1] - s[hi] <= 1e-9 && hi + 2 < plan_size) {++hi;} + th = std::atan2(gy[hi + 1] - gy[hi], gx[hi + 1] - gx[hi]); }; - /* Ease the cruise speed inside the goal-checker xy tolerance so the robot - * settles into the goal region. Unmeasured tolerance fields come back as - * std::numeric_limits::lowest() (negative), so accept only finite, - * positive values. The pointer is read but never retained. */ - if (goal_checker != nullptr) { - geometry_msgs::msg::Pose pose_tol; - geometry_msgs::msg::Twist vel_tol; - if (goal_checker->getTolerances(pose_tol, vel_tol)) { - const double xy_tol = std::hypot(pose_tol.position.x, pose_tol.position.y); - if (std::isfinite(xy_tol) && pose_tol.position.x > 0.0 && pose_tol.position.y > 0.0) { - v_ref *= std::clamp(remaining / xy_tol, 0.0, 1.0); - } + /* Terminal settle. + * + * The cruise speed is eased to zero across the goal-checker xy tolerance, and + * the reference is sampled at v_ref * k * dt ahead of the robot's own + * projection onto the plan. Composing the two makes the horizon's arc reach + * remaining^2 / xy_tol, which is shorter than `remaining` for every point + * inside the tolerance: once the robot is in the goal region the reference + * collapses to a stub a few millimetres ahead of the projection, and it is + * carried along by the projection as the robot moves. That reference has no + * fixed point. Any motion re-projects the robot and re-centres the stub, so a + * small tracking error can be traded down as cheaply one way as the other and + * the solver alternates between them; and because the horizon never reaches + * the plan end, the goal's own orientation never enters the reference at all, + * which is exactly when it is the only error left to correct. + * + * Inside the tolerance the reference therefore stops tracking the projection + * and is pinned to the goal pose, which turns the last stretch from tracking a + * receding stub into regulation about a fixed setpoint: one minimiser, and a + * standing yaw error the solver can act on. The speed reference keeps its + * taper, so the approach profile that reaches this point is unchanged and mode + * entry introduces no step in the commanded speed. + * + * The mode is latched and released on a wider band than it is entered on, so + * tracking noise about the tolerance cannot flip the reference mode to mode; + * a goal that moves further away than the band still releases it. It is never + * entered on a reference truncated at a cusp, whose end is not the goal. */ + if (have_xy_tol && s_end >= s.back()) { + if (settling_) { + settling_ = remaining <= xy_tol + goal_settle_hysteresis_m_; + } else { + settling_ = remaining <= xy_tol; } + } else { + settling_ = false; + } + + /* Pure rotation to the goal heading. + * + * Once the checker's own xy condition is met, no translation is left to do and + * only the heading is outstanding, which is the case the reference above still + * handles badly: the goal sits a fraction of the tolerance away, and as the + * body sweeps round, the body-frame projection of that offset changes sign, so + * the solver reverses and re-advances to hold a position it is already close + * enough to. Holding the reference at the robot's own reference point instead + * leaves the heading as the only standing error, and the platform turns on the + * spot. The distance test is the checker's, so this engages only where the + * translation really is finished. + * + * Restricted to a platform with no steering channel. A car-like model cannot + * turn on the spot at all, and pinning the position would leave it with no + * admissible way to correct its heading; it manoeuvres out of a terminal + * heading error instead, which is what allow_reversing is for. */ + bool rotate_in_place = false; + if (settling_ && !has_steering_ && have_terminal_yaw && have_yaw_tol) { + const double dgx = gx.back() - cx; + const double dgy = gy.back() - cy; + rotate_in_place = (dgx * dgx + dgy * dgy) <= xy_tol * xy_tol && + std::abs(std::remainder(terminal_yaw - ctheta, 2.0 * M_PI)) > yaw_tol; + } + + if (rotate_in_place) { + v_ref = 0.0; + } else if (have_xy_tol) { + v_ref *= std::clamp(remaining / xy_tol, 0.0, 1.0); } /* Curvature-aware cruise reduction (inert when curvature_gain_ == 0): estimate * the peak path curvature over the horizon from heading samples at the current * cruise, then taper v_ref so high-curvature segments are sampled more slowly. */ - if (curvature_gain_ > 0.0 && v_ref > 0.0) { + if (curvature_gain_ > 0.0 && v_ref > 0.0 && !settling_) { const double ds = v_ref * dt_; - double prev_th = ctheta; + /* Seed from the first sampled path tangent, not the robot's own yaw: seeding + * from ctheta would make the first heading delta the robot-to-path tracking + * error rather than path curvature. */ + double sx0 = 0.0; + double sy0 = 0.0; + double prev_th = 0.0; + sample(s0, sx0, sy0, prev_th); double max_kappa = 0.0; - for (std::size_t k = 0; k <= np_; ++k) { + for (std::size_t k = 1; k <= np_; ++k) { double sx = 0.0; double sy = 0.0; double sth = 0.0; @@ -683,51 +1354,185 @@ geometry_msgs::msg::TwistStamped ProxMpcController::computeVelocityCommands( v_ref /= 1.0 + curvature_gain_ * max_kappa; } - /* Build the state and control references. Heading is kept continuous (unwrapped - * relative to the robot heading, then node to node) so the QP tracking error - * never wraps near +/-pi. */ + /* Obstacle-aware cruise. + * + * The cruise above is obstacle-blind: the reference advances along the plan at + * full cruise whatever is crossing it, so the only way the solver can yield to + * a mover is to lag a reference that keeps moving, which the tracking cost + * charges as error; faced with a mover the cheaper option is nearly always to + * race it across. Here the reference itself yields: where the robot is heading + * would cut into a tracked mover's predicted keep-out, the cruise is eased in + * proportion to the deepest breach, reaching zero at obstacle_yield_band_m. + * + * "Where the robot is heading" is checked two ways, and the deeper breach wins. + * The plan, driven at this cycle's intended cruise, is one: it does not depend + * on any speed an earlier yield left behind, so it cannot restore full cruise by + * clearing the very breach that caused a reduction. The trajectory the solver + * actually planned last cycle is the other, because the solver does not follow + * the plan exactly - with light stage weights it strays from it by the better + * part of a metre - and a check on the plan alone then watches a path the robot + * is not driving. That trajectory was driven at last cycle's speed, though, so + * it can shorten when the robot slows and seem to clear; the plan check covers + * that, and the release below is rate-limited so a breach that seems to clear + * for one cycle cannot snap the cruise back to full. + * + * The trajectory is trusted only while it still meets this robot: before the + * first solve it is all zeros, and after a reset or a plan jump it belongs to a + * robot somewhere else. Both checks compare the model's reference point with + * the base_link keep-out, which is exact for a model referenced to base_link + * and approximate for one referenced elsewhere. The predictions are the ones + * the previous cycle's fill retained, on the same time base as that trajectory; + * with no fresh tracker message they are empty and the cruise is untouched. + * Skipped while settling, where the reference is already pinned to the goal. */ + if (obstacle_yield_band_m_ > 0.0 && v_ref > 0.0 && !settling_) { + const MatrixXd traj = mpc_->getX(); + const double px_now = cx + ref_offset_x_ * std::cos(ctheta) - ref_offset_y_ * std::sin(ctheta); + const double py_now = cy + ref_offset_x_ * std::sin(ctheta) + ref_offset_y_ * std::cos(ctheta); + const bool traj_ok = traj.rows() >= 2 && + std::hypot( + traj(1, static_cast(idx_x_)) - px_now, + traj(1, static_cast(idx_y_)) - py_now) <= kYieldTrajMatchRadius; + double deepest = 0.0; + { + std::lock_guard lock(obstacles_mutex_); + for (const auto & p : predicted_obstacles_) { + const std::size_t nodes = std::min(p.positions.size(), np_); + for (std::size_t k = 0; k < nodes; ++k) { + const double tk = static_cast(k + 1) * dt_; + const double d_safe = robot_radius_ + p.radius + safety_margin_ + + prediction_uncertainty_growth_ * tk; + const double ox = p.positions[k][0]; + const double oy = p.positions[k][1]; + double rx = 0.0; + double ry = 0.0; + double rth = 0.0; + sample(s0 + v_ref * tk, rx, ry, rth); + deepest = std::max(deepest, d_safe - std::hypot(rx - ox, ry - oy)); + const Eigen::Index row = static_cast(k + 1); + if (traj_ok && row < traj.rows()) { + deepest = std::max( + deepest, d_safe - std::hypot( + traj(row, static_cast(idx_x_)) - ox, + traj(row, static_cast(idx_y_)) - oy)); + } + } + } + } + const double target = std::clamp(1.0 - deepest / obstacle_yield_band_m_, 0.0, 1.0); + const double period_s = std::isfinite(cycle_period_ms) ? cycle_period_ms * 1e-3 : dt_; + yield_factor_ = (target < yield_factor_) ? target : + std::min(target, yield_factor_ + kYieldRecoveryPerS * period_s); + v_ref *= yield_factor_; + } else { + yield_factor_ = 1.0; + } + + /* Hard speed cap. The eased cruise above is only a target, and a lightly + * weighted one: the control-tracking cost that carries it sits far below the + * path and obstacle terms, so when a mover is closing the solver overrides it + * and swerves at full speed rather than slowing - measured, the cruise was cut + * to a tenth while the robot held 0.5 m/s. Capping the forward bound by the + * same factor makes the yield a speed limit rather than a request, the same + * way a Nav2 speed limit is applied to this box. + * + * The cap never falls below the speed the platform can still reach this step: + * the solver bounds the first control to within its deceleration times dt of + * the command last applied, so a bound under that would leave the QP no + * feasible first control and trip the solver-failure path instead of braking. + * The reverse bound is left as the speed limit set it, so a robot capped to a + * crawl can still back away from a mover it cannot out-wait. It runs every + * cycle while enabled, including when the yield is idle, so the bound returns + * to the speed limit as soon as the cap is released. */ + if (obstacle_yield_caps_speed_ && obstacle_yield_band_m_ > 0.0) { + const double v_lim = std::min(v_max_, max_linear_vel_); + const double reachable = + last_cmd_u_(static_cast(idx_v_)) - fallback_ramp_lin_ * dt_; + const double v_low = std::max(v_min_, -max_linear_vel_); + /* A model may declare a positive minimum speed; the cap cannot go under it, + * and updateIneq rejects a lower bound above the upper one. */ + const double v_cap = + std::max(v_low, std::min(v_lim, std::max(v_lim * yield_factor_, reachable))); + model_->updateIneq("u", idx_v_, v_low, v_cap); + } + + /* Sample the reference path the model's own reference point is to follow. The + * tangent psi is kept continuous (unwrapped relative to the direction the robot + * is expected to travel in, then node to node) so the QP tracking error never + * wraps near +/-pi. */ MatrixXd goal_x = MatrixXd::Zero(np_ + 1, n_); - std::vector th_cont(np_ + 1, 0.0); - double prev_th = ctheta; + std::vector psi_cont(np_ + 1, 0.0); + double prev_psi = ctheta + (dir < 0.0 ? M_PI : 0.0); for (std::size_t k = 0; k <= np_; ++k) { double x = 0.0; double y = 0.0; - double th = 0.0; - sample(s0 + v_ref * static_cast(k) * dt_, x, y, th); - th = prev_th + std::remainder(th - prev_th, 2.0 * M_PI); - prev_th = th; - th_cont[k] = th; - goal_x(k, 0) = x; - goal_x(k, 1) = y; - goal_x(k, 2) = th; - } - - /* Bicycle steering reference: pre-position the wheel to the per-node path - * curvature kappa = dtheta/ds, delta_ref = atan(L * kappa). Models without a - * steering state (n_ == 3) keep the go-straight default (channel left at zero). */ - if (n_ > 3) { - const double ds = v_ref * dt_; - for (std::size_t k = 0; k <= np_; ++k) { - double kappa = 0.0; - if (ds > 1e-9) { - kappa = (k < np_) ? (th_cont[k + 1] - th_cont[k]) / ds : - (th_cont[k] - th_cont[k - 1]) / ds; - } - goal_x(k, 3) = std::atan(wheelbase_ * kappa); + double psi = 0.0; + /* Pinned to the plan end while settling, which sample() reports as the goal + * position and, where the checker enforces one, the goal orientation; pinned + * to the reference point's own position while turning on the spot, so the + * heading is the only error the solver is left to close. */ + if (rotate_in_place) { + x = cx + ref_offset_x_ * std::cos(ctheta) - ref_offset_y_ * std::sin(ctheta); + y = cy + ref_offset_x_ * std::sin(ctheta) + ref_offset_y_ * std::cos(ctheta); + psi = terminal_yaw; + } else { + sample(settling_ ? s_end : s0 + v_ref * static_cast(k) * dt_, x, y, psi); } + psi = prev_psi + std::remainder(psi - prev_psi, 2.0 * M_PI); + prev_psi = psi; + psi_cont[k] = psi; + goal_x(k, idx_x_) = x; + goal_x(k, idx_y_) = y; + } + + /* Build the state reference. + * + * The reference path is the path of the point the model's state refers to, + * which the model declares as an offset `a` along the body x axis from + * base_link. For a model referenced to base_link itself (a = 0) the body + * heading is the path tangent and the steering inverse is the familiar + * delta = atan(L * kappa). For a model referenced ahead of base_link the two + * differ, and both follow from one relation: with z = tan(delta) / L, the + * reference point's path curvature is kappa = dir * z / sqrt(1 + (a z)^2), and + * the body heading trails the path tangent by atan(a z). Inverting gives + * z = kappa * dir / sqrt(1 - (a kappa)^2), which reduces to today's expression + * at a = 0 and to asin(L * kappa) / L at a = L, the front axle. Travelling in + * reverse flips the sign of the curvature the same steering angle produces, and + * turns the body around, which is what `dir` carries. */ + const double a_off = ref_offset_x_; + const double ds_ref = v_ref * dt_; + const double yaw_flip = (dir < 0.0) ? M_PI : 0.0; + for (std::size_t k = 0; k <= np_; ++k) { + double kappa = 0.0; + if (ds_ref > 1e-9) { + kappa = (k < np_) ? (psi_cont[k + 1] - psi_cont[k]) / ds_ref : + (psi_cont[k] - psi_cont[k - 1]) / ds_ref; + } + double beta = 0.0; + if (has_steering_) { + const double k_eff = kappa * dir; + const double ak = std::clamp(a_off * k_eff, -kMaxOffsetCurvature, kMaxOffsetCurvature); + const double z = k_eff / std::sqrt(1.0 - ak * ak); + beta = std::atan(a_off * z); + goal_x(k, idx_steer_) = std::atan(wheelbase_ * z); + } + goal_x(k, idx_yaw_) = psi_cont[k] - beta - yaw_flip; } MatrixXd goal_u = MatrixXd::Zero(nc_, m_); for (std::size_t k = 0; k < nc_; ++k) { - goal_u(k, 0) = v_ref; + goal_u(k, idx_v_) = dir * v_ref; } - /* Current full state, tracking the bicycle steering angle the Nav2 pose omits. */ + /* Current full state. The Nav2 pose is base_link; the model's state refers to + * its own declared reference point, so the pose is carried out to it. The + * steering angle the pose omits is the controller's own retained belief. */ VectorXd state = VectorXd::Zero(n_); - state(0) = cx; - state(1) = cy; - state(2) = ctheta; - if (n_ > 3) {state(3) = steering_state_;} + const double cos_ct = std::cos(ctheta); + const double sin_ct = std::sin(ctheta); + state(idx_x_) = cx + ref_offset_x_ * cos_ct - ref_offset_y_ * sin_ct; + state(idx_y_) = cy + ref_offset_x_ * sin_ct + ref_offset_y_ * cos_ct; + state(idx_yaw_) = ctheta; + if (has_steering_) {state(idx_steer_) = steering_state_;} /* Fill the per-node obstacle triples for this cycle: predictive + hybrid when * enabled and fresh tracking data is available, else costmap-only. */ @@ -738,19 +1543,23 @@ geometry_msgs::msg::TwistStamped ProxMpcController::computeVelocityCommands( fillObstacles(goal_x, obs, cmd.header.stamp); mpc_->setObs(obs); /* Count filled (non-sentinel) slots at the current node (rows 0..k_obs-1). */ - for (std::size_t s = 0; s < k_obs; ++s) { - if (obs(static_cast(s), 0) < 0.5 * prox_mpc::MPC::kObsFarSentinel) { + for (std::size_t slot = 0; slot < k_obs; ++slot) { + if (obs(static_cast(slot), 0) < 0.5 * prox_mpc::MPC::kObsFarSentinel) { ++num_active_obs; } } } - /* Solve one SQP cycle, timing it with a steady clock for the real-time metric. */ + /* Solve one SQP cycle, timing it with a steady clock for the real-time metric. + * The candidate is not retained: the core keeps the last accepted x, u, w and + * previous control until every gate below has passed and commitCandidate() runs, + * so a rejected cycle neither warm-starts the next one from a command that was + * never sent nor anchors its control-rate constraint on it. */ mpc_->setGoalX(goal_x); mpc_->setGoalU(goal_u); mpc_->setPose(state); const auto t_solve0 = std::chrono::steady_clock::now(); - auto [x_sol, u_sol] = mpc_->solve(); + auto [x_sol, u_sol] = mpc_->solveCandidate(); const auto t_solve1 = std::chrono::steady_clock::now(); const double solve_ms = std::chrono::duration(t_solve1 - t_solve0).count(); @@ -758,38 +1567,116 @@ geometry_msgs::msg::TwistStamped ProxMpcController::computeVelocityCommands( const bool solved = (mpc_->qp_info.status == proxsuite::proxqp::QPSolverOutput::PROXQP_SOLVED); - /* Publish per-cycle telemetry before the gate's early returns, so every solve - * (including non-converged ones) is observable when diagnostics are enabled. */ - publishDiagnostics(cmd.header.stamp, solve_ms, solved, num_active_obs); + /* The message defines `converged` as a converged solve whose applied iterate is + * finite, so it is set only past every acceptance gate; the QP's own outcome + * stays separately readable in the `status` field. Publication moves with it, so + * a vetoed or braked cycle is recorded as what it was. Every path out of the + * cycle publishes before returning or throwing, including the escalation. */ + bool converged = false; + auto publish_cycle = [&]() { + publishDiagnostics( + cmd.header.stamp, solve_ms, cycle_period_ms, converged, num_active_obs); + }; - if (!solved) {return fail("solver did not converge");} + if (!solved) { + publish_cycle(); + return fail("solver did not converge"); + } /* Defense-in-depth finiteness guard. In this architecture a PROXQP_SOLVED status - * normally implies a finite iterate (x_sol/u_sol are accumulated QP increments, + * normally implies a finite iterate (the candidate is accumulated QP increments, * not a divergent model rollout), but the check is kept so a non-finite state can * never reach the footprint veto, poison steering_state_, or be published as the - * predicted trajectory. The command finiteness is still checked separately below - * because the model's toTwist mapping can be non-finite even for finite u0. */ + * predicted trajectory. The core tests the whole horizon rather than the first + * node alone, so a non-finite tail cannot be committed and warm-start the next + * cycle. The command finiteness is still checked separately below because the + * model's toTwist mapping can be non-finite even for a finite control. */ const VectorXd u0 = u_sol.row(0); - if (!u0.allFinite() || !x_sol.row(1).allFinite()) { + if (!mpc_->getCandidateFinite()) { + publish_cycle(); return fail("non-finite solver output"); } - /* Exact polygon-footprint veto on the pose one step ahead. */ + /* Polygon-footprint veto over the predicted stopping distance. + * + * The footprint is copied before the grid lock is taken. getRobotFootprint() + * returns Costmap2DROS's padded_footprint_ by value, and the grid mutex guards + * the cell data rather than that member, so reading it inside the lock implied + * a protection that does not exist. The copy is a best-effort snapshot of a + * member written unsynchronised by the costmap's own thread - the same + * per-cycle read RPP (collision_checker.cpp:144) and MPPI (cost_critic.hpp:68) + * both perform, and what keeps a runtime footprint update taking effect. */ { + const std::vector footprint = costmap_ros_->getRobotFootprint(); auto * costmap = costmap_ros_->getCostmap(); std::lock_guard lock(*(costmap->getMutex())); - const std::vector footprint = costmap_ros_->getRobotFootprint(); if (footprint.size() >= 3) { nav2_costmap_2d::FootprintCollisionChecker checker(costmap); - const double fcost = checker.footprintCostAtPose( - x_sol(1, 0), x_sol(1, 1), x_sol(1, 2), footprint); - if (fcost >= static_cast(nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE)) { - /* Escalate a persistent veto so a robot stuck behind a static obstacle one - * step ahead triggers the behavior-tree recovery instead of braking - * forever. The veto counter is kept separate from the solver-failure - * budget, so a single veto still does not trip recovery. */ + /* How far the veto looks: the distance the robot needs to stop, not one + * step. Braking from the commanded speed at the model's declared rate + * covers v^2 / (2a) - 0.25 m at the 0.5 m/s operating point, against the + * 0.05 m a single step spans - so a veto that only ever saw node 1 found + * an obstacle five times later than it could still stop short of. The + * walk stops at the first node past that distance, which keeps the + * lookahead proportional to speed and costs one footprint test per step + * of travel rather than one per horizon node. */ + const double v_cmd = std::abs(u0(static_cast(idx_v_))); + const double stop_distance = + (std::isfinite(fallback_ramp_lin_) && fallback_ramp_lin_ > 0.0) ? + (v_cmd * v_cmd) / (2.0 * fallback_ramp_lin_) : 0.0; + + bool vetoed = false; + double travelled = 0.0; + for (Eigen::Index node = 1; node < x_sol.rows(); ++node) { + /* The padded footprint is defined about base_link, while the predicted + * pose refers to the model's own reference point, so it is carried back + * before the check. The two coincide for a model referenced to + * base_link. */ + const double pth = x_sol(node, idx_yaw_); + const double pbx = + x_sol(node, idx_x_) - (ref_offset_x_ * std::cos(pth) - ref_offset_y_ * std::sin(pth)); + const double pby = + x_sol(node, idx_y_) - (ref_offset_x_ * std::sin(pth) + ref_offset_y_ * std::cos(pth)); + const double fcost = checker.footprintCostAtPose(pbx, pby, pth, footprint); + /* Upstream Nav2's own collision policy, in upstream's order: unknown + * space is not a collision when the costmap tracks it, and everything + * else is judged at LETHAL_OBSTACLE rather than + * INSCRIBED_INFLATED_OBSTACLE, because a real polygon check has already + * been performed and an inflated cell is not by itself a collision (RPP + * collision_checker.cpp:143-154, MPPI cost_critic.hpp:71-78). Nav2's own + * doc comment describes footprintCostAtPose as returning the maximum + * cost under the footprint, which would mask a lethal cell behind an + * adjoining unknown one; measured against the installed nav2_costmap_2d + * (1.3.12+), it does not - a footprint spanning both reports the lethal + * cost, so the veto still fires (see + * FootprintVetoStillFiresWhenLethalAdjoinsUnknown). */ + const bool unknown_is_clear = + fcost == static_cast(nav2_costmap_2d::NO_INFORMATION) && + costmap_ros_->getLayeredCostmap()->isTrackingUnknown(); + if (!unknown_is_clear && + fcost >= static_cast(nav2_costmap_2d::LETHAL_OBSTACLE)) + { + vetoed = true; + break; + } + travelled += std::hypot( + x_sol(node, idx_x_) - x_sol(node - 1, idx_x_), + x_sol(node, idx_y_) - x_sol(node - 1, idx_y_)); + if (travelled >= stop_distance) {break;} + } + + if (vetoed) { + /* Escalate a persistent veto so a robot stuck behind a static obstacle + * inside its stopping distance triggers the behavior-tree recovery + * instead of braking forever. The veto counter is kept separate from + * the solver-failure budget, so a single veto still does not trip + * recovery. */ veto_count_++; + /* Published before the escalation test, not after it: the cycle that + * ends the task is still a control cycle, and the record of why it + * ended is the last message on the topic. The solver-failure + * escalation publishes on the same terms. */ + publish_cycle(); if (veto_count_ > max_solver_failures_) { throw nav2_core::NoValidControl( "ProxMpcController: footprint veto persisted beyond the budget"); @@ -811,15 +1698,23 @@ geometry_msgs::msg::TwistStamped ProxMpcController::computeVelocityCommands( /* Map the first control to a body twist; the model reads the current state. */ model_->setX(state); const geometry_msgs::msg::Twist twist = model_->toTwist(u0); - if (!std::isfinite(twist.linear.x) || !std::isfinite(twist.angular.z)) { + if (!twist_is_finite(twist)) { + publish_cycle(); return fail("non-finite command"); } + /* Last gate passed: this candidate becomes the retained solver state, and its + * first control the anchor of the next cycle's control-rate constraint. */ + converged = true; + mpc_->commitCandidate(); + failure_count_ = 0; veto_count_ = 0; - if (n_ > 3) {steering_state_ = x_sol(1, 3);} + if (has_steering_) {steering_state_ = x_sol(1, idx_steer_);} + last_cmd_u_ = u0; last_cmd_v_ = twist.linear.x; last_cmd_w_ = twist.angular.z; + publish_cycle(); /* Publish the predicted NMPC trajectory (costmap global frame) for * visualization, distinct from the Nav2 global plan. Skipped when unsubscribed. */ @@ -831,9 +1726,9 @@ geometry_msgs::msg::TwistStamped ProxMpcController::computeVelocityCommands( for (Eigen::Index k = 0; k < x_sol.rows(); ++k) { geometry_msgs::msg::PoseStamped ps; ps.header = traj.header; - ps.pose.position.x = x_sol(k, 0); - ps.pose.position.y = x_sol(k, 1); - const double th = x_sol(k, 2); + ps.pose.position.x = x_sol(k, idx_x_); + ps.pose.position.y = x_sol(k, idx_y_); + const double th = x_sol(k, idx_yaw_); ps.pose.orientation.z = std::sin(th / 2.0); ps.pose.orientation.w = std::cos(th / 2.0); traj.poses.push_back(ps); @@ -870,7 +1765,13 @@ void ProxMpcController::applySpeedLimit(double speed_limit, bool percentage) v_lim = speed_limit; } v_lim = std::clamp(v_lim, 0.0, v_max_); - model_->updateIneq("u", 0, -v_lim, v_lim); + /* Intersect with the model's declared range rather than replacing it. A model + * whose reverse limit is tighter than its forward one - or which declares no + * reverse travel at all - keeps that asymmetry through every speed-limit + * request, including the NO_SPEED_LIMIT restore, which would otherwise widen + * the lower bound to -v_max_. Both bundled models declare symmetric bounds, so + * this leaves their commanded sequence unchanged. */ + model_->updateIneq("u", idx_v_, std::max(v_min_, -v_lim), std::min(v_max_, v_lim)); max_linear_vel_ = v_lim; } @@ -889,11 +1790,19 @@ void ProxMpcController::reset() failure_count_ = 0; veto_count_ = 0; steering_state_ = 0.0; + last_cmd_u_.setZero(); last_cmd_v_ = 0.0; last_cmd_w_ = 0.0; cancelling_ = false; plan_index_ = 0; have_last_cycle_ = false; + /* A new task inherits no travel direction and no settle latch. The dwell is + * seeded spent rather than zero: nothing has been switched away from yet, so + * the task's first direction is free rather than held for the dwell. */ + dir_ = 1.0; + dir_hold_s_ = direction_switch_dwell_s_; + settling_ = false; + yield_factor_ = 1.0; } void ProxMpcController::obstacleCallback(prox_mpc_msgs::msg::ObstacleArray::ConstSharedPtr msg) @@ -902,10 +1811,39 @@ void ProxMpcController::obstacleCallback(prox_mpc_msgs::msg::ObstacleArray::Cons latest_obstacles_ = msg; } +void ProxMpcController::keepOutShift( + std::vector & shift_x, std::vector & shift_y) +{ + shift_x.assign(np_, 0.0); + shift_y.assign(np_, 0.0); + if (ref_offset_x_ == 0.0 && ref_offset_y_ == 0.0) {return;} + + /* The nominal trajectory is the last committed one, un-shifted, so node j's + * constraint is linearized about the row read here as j + 2, clamped at the + * last node - the same one-node lag the scan centres carry, and for the same + * reason. Before the first solve it is zero, which is what that first QP + * linearizes about, so the two stay consistent. */ + const MatrixXd nominal = mpc_->getX(); + for (std::size_t node = 0; node < np_; ++node) { + const Eigen::Index row = std::min( + static_cast(node + 2), static_cast(np_)); + const double yaw = nominal(row, static_cast(idx_yaw_)); + const double c = std::cos(yaw); + const double sn = std::sin(yaw); + shift_x[node] = ref_offset_x_ * c - ref_offset_y_ * sn; + shift_y[node] = ref_offset_x_ * sn + ref_offset_y_ * c; + } +} + void ProxMpcController::fillObstacles( const MatrixXd & reference, MatrixXd & obs, const rclcpp::Time & now) { - predicted_obstacles_.clear(); + /* deactivate()/cleanup() clear this under the same mutex from the executor + * thread, so the write here (the action server's own thread) takes it too. */ + { + std::lock_guard lock(obstacles_mutex_); + predicted_obstacles_.clear(); + } const std::size_t k_obs = static_cast(max_obstacles_); /* Default every slot to the far sentinel so unfilled ones stay non-binding. */ @@ -932,7 +1870,7 @@ void ProxMpcController::fillObstacles( predictive = std::isfinite(age) && age >= 0.0 && age <= obstacle_timeout_; } if (!predictive) { - fillStaticObstacles(reference, obs, 0, {}); + fillStaticObstacles(obs, 0, {}); return; } @@ -955,7 +1893,7 @@ void ProxMpcController::fillObstacles( logger_, *clock_, 2000, "ProxMpcController: tracked-obstacle TF %s <- %s unavailable (%s); " "costmap-only this cycle.", global_frame.c_str(), obs_frame.c_str(), ex.what()); - fillStaticObstacles(reference, obs, 0, {}); + fillStaticObstacles(obs, 0, {}); return; } } @@ -1057,53 +1995,100 @@ void ProxMpcController::fillObstacles( * (tracker-sampled curved prediction when available, straight ray otherwise). * The clearance grows with prediction time as the prediction ages. */ std::vector>> exclusions(np_); - predicted_obstacles_.resize(n_dyn); - for (std::size_t j = 0; j < n_dyn; ++j) { - predicted_obstacles_[j].id = dyn[j].id; - predicted_obstacles_[j].radius = dyn[j].radius; - predicted_obstacles_[j].positions.resize(np_); - } - for (std::size_t node = 0; node < np_; ++node) { - const double dt_k = static_cast(node + 1) * dt_ + age; + std::vector shift_x; + std::vector shift_y; + keepOutShift(shift_x, shift_y); + /* Held for the whole fill: deactivate()/cleanup() can clear predicted_obstacles_ + * from the executor thread while this (the action server's thread) is mid-fill. + * The loop is bounded (Np * K, both small and configure-time fixed) and does no + * I/O or blocking call, so the hold is on the order of the loop's own cost, not + * a stall - negligible against the control cycle it runs once per. */ + { + std::lock_guard lock(obstacles_mutex_); + predicted_obstacles_.resize(n_dyn); for (std::size_t j = 0; j < n_dyn; ++j) { - const DynObs & d = dyn[j]; - // Curved prediction when the tracker published samples; otherwise the - // straight constant-velocity ray, unchanged. - double px; - double py; - if (d.samples.empty()) { - px = d.x + d.vx * dt_k; - py = d.y + d.vy * dt_k; - } else { - const std::array p = sample_polyline(d.x, d.y, d.samples, d.sample_dt, dt_k); - px = p[0]; - py = p[1]; + predicted_obstacles_[j].id = dyn[j].id; + predicted_obstacles_[j].radius = dyn[j].radius; + predicted_obstacles_[j].positions.resize(np_); + } + for (std::size_t node = 0; node < np_; ++node) { + const double dt_k = static_cast(node + 1) * dt_ + age; + for (std::size_t j = 0; j < n_dyn; ++j) { + const DynObs & d = dyn[j]; + // Curved prediction when the tracker published samples; otherwise the + // straight constant-velocity ray, unchanged. + double px; + double py; + if (d.samples.empty()) { + px = d.x + d.vx * dt_k; + py = d.y + d.vy * dt_k; + } else { + const std::array p = sample_polyline(d.x, d.y, d.samples, d.sample_dt, dt_k); + px = p[0]; + py = p[1]; + } + const double d_safe = robot_radius_ + d.radius + safety_margin_ + + prediction_uncertainty_growth_ * dt_k; + const Eigen::Index row = static_cast(node * k_obs + j); + /* Written in the solver's frame: the keep-out is meant to protect + * base_link, and the solver constrains the model's reference point. */ + double ox = px + shift_x[node]; + double oy = py + shift_y[node]; + double d_safe_node = d_safe; + /* Forward shadow. The keep-out is a disc about the predicted position and + * the constraint normal points from the obstacle to the robot, so nothing + * in the formulation distinguishes the space a mover is about to occupy + * from the space it is vacating; passing in front and passing behind cost + * the same, and the reference - which carries no obstacle term - keeps + * advancing, so the solver takes the front, which is the side that does + * not require lagging it. + * + * Biasing the disc along the track's own heading prices that difference in + * without leaving the one-constraint-per-slot form the RTI core solves. + * The centre moves forward by s and the radius grows by the same s, which + * keeps the obstacle's own position covered - the disc still reaches + * d_safe behind it - while extending the covered band to d_safe + 2s + * ahead. A bare shift would open a hole over the obstacle itself as soon + * as s passed d_safe. The disc also grows sideways by s, which is the + * price of keeping a disc rather than a capsule; s is a fraction of a + * second of travel, so that stays small. + * + * Scaled by the track's speed, so a fast mover casts a longer shadow and a + * near-stationary one casts none. For a curving track this follows the + * instantaneous heading, the same first-order reading the prediction + * itself uses between samples. */ + if (prediction_forward_shadow_s_ > 0.0) { + const double speed = std::hypot(d.vx, d.vy); + if (speed > kMinShadowSpeed) { + const double shadow = prediction_forward_shadow_s_ * speed; + ox += shadow * d.vx / speed; + oy += shadow * d.vy / speed; + d_safe_node += shadow; + } + } + obs(row, 0) = ox; + obs(row, 1) = oy; + obs(row, 2) = d_safe_node; + /* Exclude the obstacle's CURRENT footprint from the static scan, not its + * predicted one: the local costmap is a now-snapshot, so the moving object's + * occupied cells sit at its current position. Excluding the current footprint + * at every node keeps the static fill from re-adding the same object the + * predictive half-plane already covers (the predicted cells are not in the + * snapshot, so excluding them would not de-duplicate anything). */ + exclusions[node].push_back({d.x, d.y, d.radius + obstacle_cluster_radius_}); + predicted_obstacles_[j].positions[node] = {px, py}; } - const double d_safe = robot_radius_ + d.radius + safety_margin_ + - prediction_uncertainty_growth_ * dt_k; - const Eigen::Index row = static_cast(node * k_obs + j); - obs(row, 0) = px; - obs(row, 1) = py; - obs(row, 2) = d_safe; - /* Exclude the obstacle's CURRENT footprint from the static scan, not its - * predicted one: the local costmap is a now-snapshot, so the moving object's - * occupied cells sit at its current position. Excluding the current footprint - * at every node keeps the static fill from re-adding the same object the - * predictive half-plane already covers (the predicted cells are not in the - * snapshot, so excluding them would not de-duplicate anything). */ - exclusions[node].push_back({d.x, d.y, d.radius + obstacle_cluster_radius_}); - predicted_obstacles_[j].positions[node] = {px, py}; } } /* Hybrid: fill the remaining slots from the costmap (static clutter), excluding * cells inside a dynamic footprint to avoid double-counting the moving object. */ if (n_dyn < k_obs) { - fillStaticObstacles(reference, obs, n_dyn, exclusions); + fillStaticObstacles(obs, n_dyn, exclusions); } } -void ProxMpcController::reduceCostmap(const MatrixXd & reference, MatrixXd & obs) +void ProxMpcController::reduceCostmap(MatrixXd & obs) { /* Default every slot to the far sentinel so unfilled ones stay non-binding. */ for (Eigen::Index r = 0; r < obs.rows(); ++r) { @@ -1111,21 +2096,35 @@ void ProxMpcController::reduceCostmap(const MatrixXd & reference, MatrixXd & obs obs(r, 1) = prox_mpc::MPC::kObsFarSentinel; obs(r, 2) = 0.0; } - fillStaticObstacles(reference, obs, 0, {}); + fillStaticObstacles(obs, 0, {}); } void ProxMpcController::fillStaticObstacles( - const MatrixXd & reference, MatrixXd & obs, std::size_t slot_begin, + MatrixXd & obs, std::size_t slot_begin, const std::vector>> & exclusions) { const std::size_t k_obs = static_cast(max_obstacles_); if (slot_begin >= k_obs) {return;} const std::size_t budget = k_obs - slot_begin; + /* The keep-out disc is centred on base_link, which is the point the robot disc + * and the costmap footprint are both defined about, whatever point the model's + * state refers to. The scan therefore looks around base_link and each hit is + * written in the solver's frame, so the QP half-plane and the footprint veto + * protect the same physical point. */ const double d_safe = robot_radius_ + safety_margin_; + /* The grid lock is taken only around the cell reads, once per node, and is + * released for the sort, the clustering, the slot binding and the matrix + * writes. Those are the expensive part of the fill, and holding the lock + * through them blocks the costmap's own update thread for no gain. The grid + * geometry is re-read inside each locked region, so a resize between nodes + * cannot send the scan out of bounds. */ auto * costmap = costmap_ros_->getCostmap(); - std::lock_guard lock(*(costmap->getMutex())); - const double res = costmap->getResolution(); + double res = 0.0; + { + std::lock_guard lock(*(costmap->getMutex())); + res = costmap->getResolution(); + } if (res <= 0.0) {return;} const double search_radius = d_safe + obstacle_cluster_radius_; @@ -1140,47 +2139,103 @@ void ProxMpcController::fillStaticObstacles( "solver. Raise max_obstacle_scan_cells; the footprint veto remains the backstop.", max_obstacle_scan_cells_, win_full, static_cast(max_obstacle_scan_cells_) * res); } - const int size_x = static_cast(costmap->getSizeInCellsX()); - const int size_y = static_cast(costmap->getSizeInCellsY()); const double sr2 = search_radius * search_radius; const double cr2 = obstacle_cluster_radius_ * obstacle_cluster_radius_; + /* Scan centres come from the nominal predicted trajectory, not from the plan + * reference: the QP linearizes node k's keep-out half-plane about its own + * predicted position, so centring the scan there removes the cross-track error + * the window would otherwise have to cover. The fill runs before solve(), and + * solve() shifts the trajectory by one node before assembling, so getX() here + * is the previous cycle's trajectory, un-shifted and one node stale: node k's + * constraint will be linearized about the row this reads as k + 2, clamped at + * the last node. Before the first solve the trajectory is zero, which is also + * what that first QP linearizes about, so the two stay consistent. */ + const MatrixXd nominal = mpc_->getX(); + + /* Carries a scanned cell from base_link's frame into the solver's; all zero + * for a model referenced to base_link. */ + std::vector shift_x; + std::vector shift_y; + keepOutShift(shift_x, shift_y); + + /* One distinct physical object, tracked across nodes: (x, y) is where it was + * seen most recently, best_d2 its closest approach to any node's scan centre, + * first_node the earliest node it was seen at and last_node the latest. Nodes + * are scanned in increasing order, so first_node is fixed at creation. */ + struct StaticObject + { + double x; + double y; + double best_d2; + std::size_t first_node; + std::size_t last_node; + }; + /* One (node, object) sighting, carrying the position seen at that node. */ + struct StaticHit + { + std::size_t node; + std::size_t object; + double x; + double y; + }; + std::vector objects; + std::vector hits; + objects.reserve(np_ * budget); + hits.reserve(np_ * budget); + + /* Reused across nodes so the per-cycle scan grows its buffers at most once. */ + std::vector> candidates; + std::vector> picked; + picked.reserve(budget); + for (std::size_t node = 0; node < np_; ++node) { - const double pcx = reference(static_cast(node + 1), 0); - const double pcy = reference(static_cast(node + 1), 1); - unsigned int mx0 = 0; - unsigned int my0 = 0; - if (!costmap->worldToMap(pcx, pcy, mx0, my0)) {continue;} + const Eigen::Index centre_row = std::min( + static_cast(node + 2), static_cast(np_)); + const double pcx = + nominal(centre_row, static_cast(idx_x_)) - shift_x[node]; + const double pcy = + nominal(centre_row, static_cast(idx_y_)) - shift_y[node]; /* Occupied cells within the search window, sorted by distance to the node. */ - std::vector> candidates; - for (int dy = -win; dy <= win; ++dy) { - const int my = static_cast(my0) + dy; - if (my < 0 || my >= size_y) {continue;} - for (int dx = -win; dx <= win; ++dx) { - const int mx = static_cast(mx0) + dx; - if (mx < 0 || mx >= size_x) {continue;} - const unsigned char cost = - costmap->getCost(static_cast(mx), static_cast(my)); - if (cost < costmap_cost_threshold_ || cost == nav2_costmap_2d::NO_INFORMATION) {continue;} - double wx = 0.0; - double wy = 0.0; - costmap->mapToWorld(static_cast(mx), static_cast(my), wx, wy); - const double dd = (wx - pcx) * (wx - pcx) + (wy - pcy) * (wy - pcy); - if (dd > sr2) {continue;} - /* Drop cells inside a dynamic footprint (already covered by its half-plane). */ - bool excluded = false; - if (node < exclusions.size()) { - for (const auto & e : exclusions[node]) { - const double ex = wx - e[0]; - const double ey = wy - e[1]; - if (ex * ex + ey * ey < e[2] * e[2]) { - excluded = true; - break; + candidates.clear(); + { + std::lock_guard lock(*(costmap->getMutex())); + const int size_x = static_cast(costmap->getSizeInCellsX()); + const int size_y = static_cast(costmap->getSizeInCellsY()); + unsigned int mx0 = 0; + unsigned int my0 = 0; + if (!costmap->worldToMap(pcx, pcy, mx0, my0)) {continue;} + for (int dy = -win; dy <= win; ++dy) { + const int my = static_cast(my0) + dy; + if (my < 0 || my >= size_y) {continue;} + for (int dx = -win; dx <= win; ++dx) { + const int mx = static_cast(mx0) + dx; + if (mx < 0 || mx >= size_x) {continue;} + const unsigned char cost = + costmap->getCost(static_cast(mx), static_cast(my)); + if (cost < costmap_cost_threshold_ || cost == nav2_costmap_2d::NO_INFORMATION) { + continue; + } + double wx = 0.0; + double wy = 0.0; + costmap->mapToWorld(static_cast(mx), static_cast(my), wx, wy); + const double dd = (wx - pcx) * (wx - pcx) + (wy - pcy) * (wy - pcy); + if (dd > sr2) {continue;} + /* Drop cells inside a dynamic footprint (already covered by its half-plane). */ + bool excluded = false; + if (node < exclusions.size()) { + for (const auto & e : exclusions[node]) { + const double ex = wx - e[0]; + const double ey = wy - e[1]; + if (ex * ex + ey * ey < e[2] * e[2]) { + excluded = true; + break; + } } } + if (!excluded) {candidates.push_back({dd, wx, wy});} } - if (!excluded) {candidates.push_back({dd, wx, wy});} } } std::sort( @@ -1188,7 +2243,7 @@ void ProxMpcController::fillStaticObstacles( [](const std::array & a, const std::array & b) {return a[0] < b[0];}); /* Cluster: keep the nearest representatives at least cluster-radius apart. */ - std::vector> picked; + picked.clear(); for (const auto & cd : candidates) { if (picked.size() >= budget) {break;} bool near = false; @@ -1201,13 +2256,75 @@ void ProxMpcController::fillStaticObstacles( } if (!near) {picked.push_back({cd[1], cd[2]});} } - for (std::size_t slot = 0; slot < picked.size(); ++slot) { - const Eigen::Index row = static_cast(node * k_obs + slot_begin + slot); - obs(row, 0) = picked[slot][0]; - obs(row, 1) = picked[slot][1]; - obs(row, 2) = d_safe; + + /* Bind each representative to the object it continues, so a slot carries one + * physical object across the horizon instead of whatever happened to be + * nearest at each node independently. The coupled CBF compares slot s at node + * k against slot s at node k-1, so a slot that changes object between them + * compares two unrelated distances. Matching is against the object's most + * recently seen position, which follows an extended obstacle whose nearest + * representative slides along it as the scan centre advances; an object + * already claimed at this node cannot be claimed twice. */ + for (const auto & pk : picked) { + const double pd2 = (pk[0] - pcx) * (pk[0] - pcx) + (pk[1] - pcy) * (pk[1] - pcy); + std::size_t match = objects.size(); + double match_d2 = cr2; + for (std::size_t oi = 0; oi < objects.size(); ++oi) { + if (objects[oi].last_node == node) {continue;} + const double ox = pk[0] - objects[oi].x; + const double oy = pk[1] - objects[oi].y; + const double od2 = ox * ox + oy * oy; + if (od2 < match_d2) { + match_d2 = od2; + match = oi; + } + } + if (match == objects.size()) { + objects.push_back({pk[0], pk[1], pd2, node, node}); + } else { + objects[match].x = pk[0]; + objects[match].y = pk[1]; + objects[match].best_d2 = std::min(objects[match].best_d2, pd2); + objects[match].last_node = node; + } + hits.push_back({node, match, pk[0], pk[1]}); } } + + /* Slots go to the objects encountered earliest along the predicted trajectory, + * ties broken by closest approach. Ranking on closest approach alone spends the + * capacity on whichever object comes nearest anywhere on the horizon, which + * degrades as np grows: at a long horizon the winner can be an encounter many + * seconds out that is re-planned long before it happens, while a near obstacle + * gets no in-loop constraint. Time-to-encounter is invariant to horizon length, + * because extra nodes are appended past the ones that decide the order, and it + * is the rule Autoware's cruise planner uses (nearest along the trajectory). An + * object that wins a slot keeps it at every node it was seen at; the nodes it + * was not seen at keep the far sentinel, which the core reads as an unfilled + * slot and excludes from the CBF coupling. */ + std::vector order(objects.size()); + std::iota(order.begin(), order.end(), 0); + std::stable_sort( + order.begin(), order.end(), + [&objects](std::size_t a, std::size_t b) { + if (objects[a].first_node != objects[b].first_node) { + return objects[a].first_node < objects[b].first_node; + } + return objects[a].best_d2 < objects[b].best_d2; + }); + + std::vector slot_of(objects.size(), kNoObstacleSlot); + for (std::size_t rank = 0; rank < order.size() && rank < budget; ++rank) { + slot_of[order[rank]] = slot_begin + rank; + } + for (const auto & h : hits) { + const std::size_t slot = slot_of[h.object]; + if (slot == kNoObstacleSlot) {continue;} + const Eigen::Index row = static_cast(h.node * k_obs + slot); + obs(row, 0) = h.x + shift_x[h.node]; + obs(row, 1) = h.y + shift_y[h.node]; + obs(row, 2) = d_safe; + } } void ProxMpcController::publishPredictedObstacleMarkers(const rclcpp::Time & now) @@ -1222,33 +2339,38 @@ void ProxMpcController::publishPredictedObstacleMarkers(const rclcpp::Time & now const std::string global_frame = costmap_ros_->getGlobalFrameID(); int id = 0; - for (const auto & po : predicted_obstacles_) { - visualization_msgs::msg::Marker m; - m.header.frame_id = global_frame; - m.header.stamp = now; - m.ns = "predicted_obstacles"; - m.id = id++; - m.type = visualization_msgs::msg::Marker::LINE_STRIP; - m.action = visualization_msgs::msg::Marker::ADD; - m.scale.x = 0.05; - m.color.r = 1.0f; - m.color.g = 0.4f; - m.color.a = 1.0f; - m.pose.orientation.w = 1.0; - for (const auto & p : po.positions) { - geometry_msgs::msg::Point pt; - pt.x = p[0]; - pt.y = p[1]; - m.points.push_back(pt); + /* predicted_obstacles_ is filled by this thread but cleared by deactivate() + * and cleanup() on the lifecycle thread, so the read is guarded like the fill. + * The array is published after the lock is dropped: the tracker callback takes + * the same mutex, and this path only runs while something is subscribed. */ + { + std::lock_guard lock(obstacles_mutex_); + for (const auto & po : predicted_obstacles_) { + visualization_msgs::msg::Marker m; + m.header.frame_id = global_frame; + m.header.stamp = now; + m.ns = "predicted_obstacles"; + m.id = id++; + m.type = visualization_msgs::msg::Marker::LINE_STRIP; + m.action = visualization_msgs::msg::Marker::ADD; + m.scale.x = 0.05; + m.color.r = 1.0f; + m.color.g = 0.4f; + m.color.a = 1.0f; + m.pose.orientation.w = 1.0; + for (const auto & p : po.positions) { + geometry_msgs::msg::Point pt; + pt.x = p[0]; + pt.y = p[1]; + m.points.push_back(pt); + } + arr.markers.push_back(m); } - arr.markers.push_back(m); } marker_pub_->publish(arr); } -void ProxMpcController::publishDiagnostics( - const rclcpp::Time & stamp, double solve_ms, bool converged, - std::uint16_t num_active_obstacles) +double ProxMpcController::markCycleStart() { const auto t_now = std::chrono::steady_clock::now(); double period_ms = std::numeric_limits::quiet_NaN(); @@ -1257,7 +2379,13 @@ void ProxMpcController::publishDiagnostics( } last_cycle_wall_ = t_now; have_last_cycle_ = true; + return period_ms; +} +void ProxMpcController::publishDiagnostics( + const rclcpp::Time & stamp, double solve_ms, double period_ms, bool converged, + std::uint16_t num_active_obstacles) +{ /* Only-when-subscribed: zero cost in the production default. */ if (!diag_pub_ || diag_pub_->get_subscription_count() == 0) {return;} diff --git a/prox_mpc_controller/test/test_controller_contracts.cpp b/prox_mpc_controller/test/test_controller_contracts.cpp new file mode 100644 index 0000000..dfdbc67 --- /dev/null +++ b/prox_mpc_controller/test/test_controller_contracts.cpp @@ -0,0 +1,1389 @@ +// Copyright 2026 Simone Contorno +// SPDX-License-Identifier: Apache-2.0 + + +// Contract tests for the controller's Nav2-facing behaviour: the transactional +// solve/commit wiring at the plugin boundary, SolverDiagnostics' gate-aware +// `converged` field and its publisher, the model/Nav2 adapter contract +// (Model::getPlanarMapping(), read by readModelMapping()), and +// terminal-heading/reverse-travel tracking. +// +// This is a separate binary from test_prox_mpc_controller.cpp (which already +// covers configure(), the fail-safe branches, and the costmap/predictive +// obstacle fill in depth) rather than an addition to it, so the file can be +// built and run in isolation without disturbing that suite's own coverage. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "prox_mpc_controller/prox_mpc_controller.hpp" + +namespace +{ +constexpr double kTol = 1e-9; +constexpr double kModelDecel = 0.5; // bundled-model du bound [m/s^2, rad/s^2] +constexpr double kResolution = 0.05; +constexpr unsigned int kGridCells = 200u; +constexpr double kGridOrigin = -5.0; +constexpr const char * kFrontAxlePlugin = "prox_mpc_core/BicycleFrontAxle"; +constexpr const char * kRearAxlePlugin = "prox_mpc_core/BicycleRearAxle"; +constexpr double kBicycleWheelbase = 1.6; + +// Exposes the protected surface these tests need to drive directly: the +// model/Nav2 adapter read (readModelMapping()), the cached mapping it +// produces, and the loaded model/mpc handles. White-box, no production change. +class TestableProxMpcController : public prox_mpc_controller::ProxMpcController +{ +public: + using ProxMpcController::readModelMapping; + using ProxMpcController::keepOutShift; + using ProxMpcController::fillStaticObstacles; + using ProxMpcController::n_; + using ProxMpcController::m_; + + std::shared_ptr mpc() const {return mpc_;} + std::shared_ptr model() const {return model_;} + double wheelbase() const {return wheelbase_;} + double refOffsetX() const {return ref_offset_x_;} + double refOffsetY() const {return ref_offset_y_;} + bool hasSteering() const {return has_steering_;} + std::size_t idxX() const {return idx_x_;} + std::size_t idxY() const {return idx_y_;} + std::size_t idxYaw() const {return idx_yaw_;} + std::size_t idxV() const {return idx_v_;} + std::size_t idxSteer() const {return idx_steer_;} + int failureCount() const {return failure_count_;} + std::size_t maxObstacles() const {return static_cast(max_obstacles_);} +}; + +// Local, unregistered models exercising readModelMapping()'s rejection paths. +// They never reach a solve, so their dynamics hooks are stubs -- matching the +// existing NoDuBoundModel/SingleControlModel pattern in +// test_prox_mpc_controller.cpp, which keeps a loader-path fixture in +// prox_mpc_test_models and a readModelMapping()-only one local to the test. + +class TwoStateModel : public prox_mpc::Model +{ +public: + TwoStateModel() + { + setName("two_state"); + setN(2); + setM(1); + } + void updatec(double, VectorXd) override {} + void updateA(double) override {} + void updateB() override {} +}; + +// Declares its state dimension and forgets its control dimension. Model's +// control count is a ModelInfo default member initialiser (0) and Model +// declares no constructor, so a subclass that never calls setM leaves it there; +// setM's own m == 0 rejection only covers an explicit zero. +class NoControlModel : public prox_mpc::Model +{ +public: + NoControlModel() + { + setName("no_control"); + setN(3); // clears the n_ < 3 gate, so m_ < 1 is the one under test + } + void updatec(double, VectorXd) override {} + void updateA(double) override {} + void updateB() override {} +}; + +// Maps y to the same state index as x -- an internally inconsistent mapping. +class DuplicatePlanarIndexModel : public prox_mpc::Model +{ +public: + DuplicatePlanarIndexModel() + { + setName("duplicate_planar_index"); + setN(3); + setM(1); + } + prox_mpc::PlanarMapping getPlanarMapping() const override + { + prox_mpc::PlanarMapping mapping; + mapping.idx_y = mapping.idx_x; // 0 == 0: collides + return mapping; + } + void updatec(double, VectorXd) override {} + void updateA(double) override {} + void updateB() override {} +}; + +// Carries a steering state (n > 3) but declares no wheelbase. +class SteeringNoWheelbaseModel : public prox_mpc::Model +{ +public: + SteeringNoWheelbaseModel() + { + setName("steering_no_wheelbase"); + setN(4); + setM(2); + } + void updatec(double, VectorXd) override {} + void updateA(double) override {} + void updateB() override {} +}; + +// Declares a steering state with a wheelbase, but a lateral reference offset +// -- the steering inverse is derived for a reference point on the body x axis. +class SteeringLateralOffsetModel : public prox_mpc::Model +{ +public: + SteeringLateralOffsetModel() + { + setName("steering_lateral_offset"); + setN(4); + setM(2); + } + prox_mpc::PlanarMapping getPlanarMapping() const override + { + prox_mpc::PlanarMapping mapping; + mapping.idx_steering = 3; + mapping.wheelbase = 1.6; + mapping.ref_offset_y = 0.2; // lateral: unsupported + return mapping; + } + void updatec(double, VectorXd) override {} + void updateA(double) override {} + void updateB() override {} +}; + +// A conforming three-state, two-control model (no steering channel) that +// overrides nothing: the default getPlanarMapping() must still let it +// configure and drive. n <= 3 is the case that actually "still drives" with +// no override -- a model with n > 3 and no override also reproduces the +// pre-hook convention by inferring a steering channel at state 3, but is then +// correctly rejected for declaring no wheelbase +// (ReadModelMappingRejectsSteeringWithoutWheelbase below, and +// migration.md: "rejects at configure() a model that carries a steering +// angle without declaring a usable wheelbase"). +class BareThreeStateDrivableModel : public prox_mpc::Model +{ +public: + BareThreeStateDrivableModel() + { + setName("bare_three_state_drivable"); + setN(3); + setM(2); + setA(MatrixXd::Zero(getN(), getN())); + setB(MatrixXd::Zero(getN(), getM())); + setc(VectorXd::Zero(getN())); + setIneq("u", 0, -3.0, 3.0); + setIneq("u", 1, -1.0, 1.0); + setIneq("du", 0, -0.5, 0.5); + setIneq("du", 1, -0.5, 0.5); + setObsAvoid(false); + } + void updatec(double dt, VectorXd x_next) override + { + c << getX()(0) - x_next(0) + dt * getU()(0) * std::cos(getX()(2)), + getX()(1) - x_next(1) + dt * getU()(0) * std::sin(getX()(2)), + getX()(2) - x_next(2) + dt * getU()(1); + } + void updateA(double dt) override + { + const double th = getX()(2); + const double v = getU()(0); + A << 1.0, 0.0, -dt * v * std::sin(th), + 0.0, 1.0, dt * v * std::cos(th), + 0.0, 0.0, 1.0; + } + void updateB() override + { + const double th = getX()(2); + B << std::cos(th), 0.0, + std::sin(th), 0.0, + 0.0, 1.0; + } +}; + +nav_msgs::msg::Path makeStraightPlan( + std::size_t count, double step, const std::string & frame = "map") +{ + nav_msgs::msg::Path path; + path.header.frame_id = frame; + for (std::size_t i = 0; i < count; ++i) { + geometry_msgs::msg::PoseStamped ps; + ps.header.frame_id = frame; + ps.pose.position.x = static_cast(i) * step; + ps.pose.position.y = 0.0; + ps.pose.orientation.w = 1.0; + path.poses.push_back(ps); + } + return path; +} + +geometry_msgs::msg::PoseStamped makePose(double x, double y, double yaw) +{ + geometry_msgs::msg::PoseStamped ps; + ps.header.frame_id = "map"; + ps.pose.position.x = x; + ps.pose.position.y = y; + ps.pose.orientation.z = std::sin(yaw / 2.0); + ps.pose.orientation.w = std::cos(yaw / 2.0); + return ps; +} + +std::vector makeSquareFootprint(double half) +{ + std::vector fp(4); + fp[0].x = half; fp[0].y = half; + fp[1].x = half; fp[1].y = -half; + fp[2].x = -half; fp[2].y = -half; + fp[3].x = -half; fp[3].y = half; + return fp; +} + +class StubGoalChecker : public nav2_core::GoalChecker +{ +public: + explicit StubGoalChecker(double yaw_tol) + : yaw_tol_(yaw_tol) {} + void initialize( + const rclcpp_lifecycle::LifecycleNode::WeakPtr &, const std::string &, + const std::shared_ptr) override {} + void reset() override {} + bool isGoalReached( + const geometry_msgs::msg::Pose &, const geometry_msgs::msg::Pose &, + const geometry_msgs::msg::Twist &) override {return false;} + bool getTolerances( + geometry_msgs::msg::Pose & pose_tolerance, geometry_msgs::msg::Twist &) override + { + pose_tolerance.position.x = 1.0; + pose_tolerance.position.y = 1.0; + pose_tolerance.orientation.z = std::sin(yaw_tol_ / 2.0); + pose_tolerance.orientation.w = std::cos(yaw_tol_ / 2.0); + return true; + } + +private: + double yaw_tol_; +}; +} // namespace + +class ControllerContractsTest : public ::testing::Test +{ +protected: + void SetUp() override + { + rclcpp::NodeOptions cm_opts; + cm_opts.arguments({"--ros-args", "-r", "__node:=prox_mpc_contracts_costmap"}); + cm_opts.parameter_overrides( + { + rclcpp::Parameter("global_frame", std::string("map")), + rclcpp::Parameter("robot_base_frame", std::string("base_link")), + rclcpp::Parameter("use_sim_time", false), + rclcpp::Parameter("plugins", std::vector{}), + }); + costmap_ros_ = std::make_shared(cm_opts); + costmap_ros_->on_configure(rclcpp_lifecycle::State()); + + auto * costmap = costmap_ros_->getCostmap(); + costmap->setDefaultValue(nav2_costmap_2d::FREE_SPACE); + costmap->resizeMap(kGridCells, kGridCells, kResolution, kGridOrigin, kGridOrigin); + costmap_ros_->setRobotFootprint(makeSquareFootprint(0.5)); + + tf_ = std::make_shared(rclcpp::Clock::make_shared()); + } + + void TearDown() override + { + if (controller_) {controller_->cleanup();} + controller_.reset(); + if (costmap_ros_) {costmap_ros_->on_cleanup(rclcpp_lifecycle::State());} + costmap_ros_.reset(); + nodes_.clear(); + } + + rclcpp_lifecycle::LifecycleNode::SharedPtr makeNode( + const std::vector & overrides) + { + rclcpp::NodeOptions opts; + opts.parameter_overrides(overrides); + auto node = std::make_shared( + "prox_mpc_contracts_controller_" + std::to_string(node_counter_++), opts); + nodes_.push_back(node); + return node; + } + + std::shared_ptr makeUnconfigured( + const std::vector & overrides = {}) + { + node_ = makeNode(overrides); + controller_ = std::make_shared(); + return controller_; + } + + std::shared_ptr makeConfigured( + const std::vector & overrides = {}) + { + auto c = makeUnconfigured(overrides); + c->configure(node_, "FollowPath", tf_, costmap_ros_); + return c; + } + + std::shared_ptr makeRunning( + const std::vector & overrides = {}) + { + auto c = makeConfigured(overrides); + c->activate(); + c->setPlan(makeStraightPlan(61, 0.2)); + return c; + } + + void fillCost(double x0, double y0, double x1, double y1, unsigned char cost) + { + auto * costmap = costmap_ros_->getCostmap(); + std::lock_guard lock(*(costmap->getMutex())); + for (double y = y0; y <= y1 + kTol; y += kResolution) { + for (double x = x0; x <= x1 + kTol; x += kResolution) { + unsigned int mx = 0; + unsigned int my = 0; + if (costmap->worldToMap(x, y, mx, my)) {costmap->setCost(mx, my, cost);} + } + } + } + + std::shared_ptr costmap_ros_; + std::shared_ptr tf_; + rclcpp_lifecycle::LifecycleNode::SharedPtr node_; + std::shared_ptr controller_; + std::vector nodes_; + int node_counter_{0}; +}; + +// --- A rejected candidate does not anchor the next cycle's rate constraint -- +// +// The vetoed-candidate half of the transactional solve. In 1.0.0 a +// solved-but-vetoed candidate still advanced MPC's retained u0 +// (mpc.cpp:148-150 at that release), so the next cycle's du rate constraint was +// anchored on a command the robot never received. make_brake()'s own twist +// output is sourced directly from the measured velocity argument (not from +// u0), so it cannot show this by itself; what can is whether the SOLVER's own +// rate bound on the FOLLOWING accepted cycle is anchored on the value +// setU0() recorded. It is engineered to be observable: measured.linear.x is +// set far above the plan's desired speed, so the accepted cycle's command is +// bound-saturated at the deceleration limit if (and only if) it is really +// anchored on the applied brake. +TEST_F(ControllerContractsTest, VetoedCandidateDoesNotAnchorNextCycleRateConstraint) +{ + auto c = makeRunning({rclcpp::Parameter("FollowPath.max_obstacles", 0)}); + + // Cycle 1: lethal block over the one-step-ahead footprint vetoes the + // candidate. The measured velocity (2.0 m/s) is deliberately far above the + // plan's desired speed (default 1.0 m/s), so the two scenarios below are + // easy to tell apart. + fillCost(-0.6, -0.6, 0.6, 0.6, nav2_costmap_2d::LETHAL_OBSTACLE); + geometry_msgs::msg::Twist measured; + measured.linear.x = 2.0; + const auto cmd1 = c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), measured, nullptr); + const double expected_applied = 2.0 - kModelDecel * 0.1; // 1.95, first-cycle period = dt + EXPECT_NEAR(cmd1.twist.linear.x, expected_applied, 1e-6); + + // Cycle 2: clear the veto. If the rate constraint is anchored on the value + // actually applied (1.95), and the reference wants much less, the QP is + // bound-saturated at the deceleration limit: exactly 1.95 - 0.05 = 1.90. + // If it were instead anchored on the vetoed candidate's own (unsent) u0 -- + // close to the low reference speed already -- this cycle would show no such + // saturation and could jump straight toward the reference. + fillCost(-0.6, -0.6, 0.6, 0.6, nav2_costmap_2d::FREE_SPACE); + const auto cmd2 = c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), measured, nullptr); + const double expected_saturated = expected_applied - kModelDecel * 0.1; // 1.90 + EXPECT_NEAR(cmd2.twist.linear.x, expected_saturated, 5e-3); +} + +// --- Model/Nav2 adapter contract (Model::getPlanarMapping()) ---------------- +// --- and the "a model declaring nothing still drives" pin ------------------- +// +// readModelMapping() reads the controller's OWN cached n_/m_ (populated by +// configure() from model_->getN()/getM() immediately before it is called, +// prox_mpc_controller.cpp), not the model argument's dimensions directly, so +// a direct call must set them first -- otherwise every one of these throws on +// the unconditional "declares 0 states" check regardless of what is actually +// being tested. +void callReadModelMapping( + const std::shared_ptr & c, prox_mpc::Model & model, + const std::string & name) +{ + c->n_ = model.getN(); + c->m_ = model.getM(); + c->readModelMapping(model, name); +} + +TEST_F(ControllerContractsTest, ReadModelMappingRejectsFewerThanThreeStates) +{ + auto c = makeUnconfigured(); + TwoStateModel model; + EXPECT_THROW(callReadModelMapping(c, model, "test/TwoState"), nav2_core::ControllerException); +} + +// setM(0) throws, but a model that never calls setM at all does not: ModelInfo +// default-initialises m to 0 and Model declares no constructor of its own, so +// the omission survives construction and readModelMapping() -- which runs +// before readModelBounds() -- is the first gate it reaches. +// +// The message is asserted, not merely the exception type. Every later mapping +// check compares an index against m_, so all of them also fire at m_ == 0 and +// any of them would satisfy an EXPECT_THROW: the default speed index 0 is +// "outside" a zero-length control vector. Only the message distinguishes being +// told the model declares no control from being pointed at a speed-index +// mapping the author never wrote. +TEST_F(ControllerContractsTest, ReadModelMappingRejectsAModelDeclaringNoControl) +{ + auto c = makeUnconfigured(); + NoControlModel model; + try { + callReadModelMapping(c, model, "test/NoControl"); + FAIL() << "a model declaring no control must not configure"; + } catch (const nav2_core::ControllerException & ex) { + const std::string what(ex.what()); + EXPECT_NE(what.find("declares no control input"), std::string::npos) << what; + EXPECT_NE(what.find("test/NoControl"), std::string::npos) << what; + } +} + +TEST_F(ControllerContractsTest, ReadModelMappingRejectsDuplicatePlanarIndices) +{ + auto c = makeUnconfigured(); + DuplicatePlanarIndexModel model; + EXPECT_THROW( + callReadModelMapping(c, model, "test/DuplicatePlanarIndex"), + nav2_core::ControllerException); +} + +TEST_F(ControllerContractsTest, ReadModelMappingRejectsSteeringWithoutWheelbase) +{ + auto c = makeUnconfigured(); + SteeringNoWheelbaseModel model; + EXPECT_THROW( + callReadModelMapping(c, model, "test/SteeringNoWheelbase"), + nav2_core::ControllerException); +} + +TEST_F(ControllerContractsTest, ReadModelMappingRejectsSteeringWithLateralOffset) +{ + auto c = makeUnconfigured(); + SteeringLateralOffsetModel model; + EXPECT_THROW( + callReadModelMapping(c, model, "test/SteeringLateralOffset"), + nav2_core::ControllerException); +} + +// A model whose planar position is not at state columns 0 and 1 configures with +// the in-loop keep-out term active. It used to be rejected here, because the +// solver's obstacle rows indexed those two columns directly; they now index the +// same declared mapping the controller reads, so there is nothing left to +// reject and the model drives with avoidance on. +// +// The keep-out is then checked where it is assembled: the half-plane normal has +// to land in the two state columns the model declares, and the column it +// declares as heading must carry none of it. A misplaced normal still produces +// a plausible trajectory, just one constrained on the wrong axes, so the +// assembled matrix is read rather than the solution. +TEST_F(ControllerContractsTest, PermutedModelDrivesWithObstacleAvoidanceActive) +{ + std::shared_ptr c; + ASSERT_NO_THROW( + c = makeConfigured( + {rclcpp::Parameter( + "FollowPath.model_plugin", std::string("prox_mpc_test_models/PermutedPlanarMapping")), + rclcpp::Parameter("FollowPath.max_obstacles", 1)})); + ASSERT_NE(c, nullptr); + ASSERT_EQ(c->idxYaw(), 0u); + ASSERT_EQ(c->idxX(), 1u); + ASSERT_EQ(c->idxY(), 2u); + ASSERT_EQ(c->maxObstacles(), 1u); + + c->activate(); + c->setPlan(makeStraightPlan(61, 0.2)); + const auto cmd = + c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + EXPECT_TRUE(std::isfinite(cmd.twist.linear.x)); + + auto solver = c->mpc()->getSolver(); + const MatrixXd & C = solver->getC(); + const std::vector & ineq_idx = solver->getIneqIdx(); + const size_t obs_start = ineq_idx[ineq_idx.size() - 3]; + const size_t col = c->n_ * 1; // x_start == 0; state block of node 1 + + // The row is a unit normal spread over the two declared position columns. + const double nx = C(obs_start, col + c->idxX()); + const double ny = C(obs_start, col + c->idxY()); + EXPECT_NEAR(nx * nx + ny * ny, 1.0, 1e-9); + EXPECT_NEAR(C(obs_start, col + c->idxYaw()), 0.0, 1e-12); +} + +// A model that overrides nothing still drives: the default getPlanarMapping() +// reproduces the pre-hook convention this controller assumed, so +// readModelMapping() accepts it and derives exactly that convention (no +// steering channel is inferred for a model with three states or fewer). +TEST_F(ControllerContractsTest, ReadModelMappingDefaultMappingLetsBareModelDrive) +{ + auto c = makeUnconfigured(); + BareThreeStateDrivableModel model; + EXPECT_NO_THROW(callReadModelMapping(c, model, "test/BareThreeStateDrivable")); + EXPECT_EQ(c->idxX(), 0u); + EXPECT_EQ(c->idxY(), 1u); + EXPECT_EQ(c->idxYaw(), 2u); + EXPECT_EQ(c->idxV(), 0u); + EXPECT_FALSE(c->hasSteering()); + EXPECT_NEAR(c->refOffsetX(), 0.0, kTol); + EXPECT_NEAR(c->refOffsetY(), 0.0, kTol); +} + +// The state-cost weights are placed through the declared mapping rather than at +// state columns 0 and 1. PermutedPlanarMapping orders its state [theta, x, y], +// so q_pos belongs on columns 1 and 2 and q_theta on column 0; indexing by +// position instead weights the heading as a position and the y position as a +// heading, which configure() accepts without a diagnostic because the model is +// otherwise legal (its obstacle avoidance is off, which is what lets a +// permuted position through readModelMapping() at all). +TEST_F(ControllerContractsTest, StateWeightsFollowTheDeclaredPlanarMapping) +{ + auto c = makeConfigured( + { + rclcpp::Parameter( + "FollowPath.model_plugin", std::string("prox_mpc_test_models/PermutedPlanarMapping")), + rclcpp::Parameter("FollowPath.q_pos", 10.0), + rclcpp::Parameter("FollowPath.q_theta", 1.0), + }); + ASSERT_EQ(c->idxYaw(), 0u); + ASSERT_EQ(c->idxX(), 1u); + ASSERT_EQ(c->idxY(), 2u); + + const MatrixXd Q = c->mpc()->getQ(); + ASSERT_EQ(Q.rows(), 3); + ASSERT_EQ(Q.cols(), 3); + EXPECT_NEAR(Q(0, 0), 1.0, kTol); // yaw carries q_theta + EXPECT_NEAR(Q(1, 1), 10.0, kTol); // x carries q_pos + EXPECT_NEAR(Q(2, 2), 10.0, kTol); // y carries q_pos +} + +// A full pluginlib-loaded control cycle against a model with no +// getPlanarMapping() override is already covered by +// test_prox_mpc_controller.cpp's ConfigureLoadsModelAndSizesMpc and +// ComputeWorksWithUnicycleModel: the bundled Unicycle itself declares no +// override, so every one of that suite's Unicycle-model cycles already +// exercises the default mapping end to end. + +// --- The reference-point offset is explicitly transformed, never ------------ +// --- silently mixed between a front- and rear-axle-referenced model --------- +// +// A Nav2 plan is always a base_link-referenced trajectory (there is no such +// thing as a "front-axle plan"); the question is whether the controller +// silently treats that trajectory as the model's own state (correct only for +// a model referenced to base_link, i.e. the rear axle) or explicitly +// transforms it by the model's declared offset. The state fed to the solver +// is read back through MPC::getPose() (public), so no white-box access is +// needed for this half. +TEST_F(ControllerContractsTest, ReferenceOffsetIsExplicitlyTransformedNotMixed) +{ + auto front = makeRunning( + {rclcpp::Parameter("FollowPath.model_plugin", std::string(kFrontAxlePlugin)), + rclcpp::Parameter("FollowPath.max_obstacles", 0)}); + front->computeVelocityCommands(makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + const VectorXd pose_front = front->mpc()->getPose(); + + auto rear = makeRunning( + {rclcpp::Parameter("FollowPath.model_plugin", std::string(kRearAxlePlugin)), + rclcpp::Parameter("FollowPath.max_obstacles", 0)}); + rear->computeVelocityCommands(makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + const VectorXd pose_rear = rear->mpc()->getPose(); + + // Rear axle: reference point is base_link itself, so the solver's pose IS + // the robot's own pose (0, 0, 0). + EXPECT_NEAR(pose_rear(rear->idxX()), 0.0, 1e-9); + EXPECT_NEAR(pose_rear(rear->idxY()), 0.0, 1e-9); + + // Front axle: reference point is one wheelbase ahead on the body x axis, so + // the solver's pose is explicitly shifted by that offset, not left at the + // robot's own (0, 0) -- which is what "mixing" the two conventions would + // silently do instead. + EXPECT_NEAR(pose_front(front->idxX()), kBicycleWheelbase, 1e-9); + EXPECT_NEAR(pose_front(front->idxY()), 0.0, 1e-9); + EXPECT_NEAR(front->wheelbase(), kBicycleWheelbase, 1e-9); + EXPECT_NEAR(front->refOffsetX(), kBicycleWheelbase, 1e-9); +} + +// keepOutShift() carries an obstacle from base_link's frame (where the +// keep-out is meant to protect) into the model's reference-point frame (where +// the solver constrains it). Before the first solve the nominal trajectory is +// all-zero, so the shift is the offset itself rotated by yaw = 0. +TEST_F(ControllerContractsTest, KeepOutShiftCarriesFrontAxleOffsetBeforeFirstSolve) +{ + auto front = makeConfigured( + {rclcpp::Parameter("FollowPath.model_plugin", std::string(kFrontAxlePlugin)), + rclcpp::Parameter("FollowPath.max_obstacles", 1)}); + std::vector shift_x; + std::vector shift_y; + front->keepOutShift(shift_x, shift_y); + ASSERT_FALSE(shift_x.empty()); + for (std::size_t i = 0; i < shift_x.size(); ++i) { + EXPECT_NEAR(shift_x[i], kBicycleWheelbase, 1e-9) << "node " << i; + EXPECT_NEAR(shift_y[i], 0.0, 1e-9) << "node " << i; + } + + auto rear = makeConfigured( + {rclcpp::Parameter("FollowPath.model_plugin", std::string(kRearAxlePlugin)), + rclcpp::Parameter("FollowPath.max_obstacles", 1)}); + std::vector shift_x_rear; + std::vector shift_y_rear; + rear->keepOutShift(shift_x_rear, shift_y_rear); + for (std::size_t i = 0; i < shift_x_rear.size(); ++i) { + EXPECT_NEAR(shift_x_rear[i], 0.0, 1e-9) << "node " << i; + EXPECT_NEAR(shift_y_rear[i], 0.0, 1e-9) << "node " << i; + } +} + +// fillStaticObstacles() writes a scanned cell in the SOLVER's frame (cell +// position + keepOutShift), so a front-axle model's keep-out disc and its +// footprint veto both protect the same physical (base_link) point: the disc +// is centred on base_link (the shift), and the veto transforms the predicted +// pose back to base_link before the check (computeVelocityCommands). This +// checks the disc half directly against the shift derived above. +TEST_F(ControllerContractsTest, FillStaticObstaclesWritesCellShiftedToSolverFrame) +{ + auto front = makeConfigured( + {rclcpp::Parameter("FollowPath.model_plugin", std::string(kFrontAxlePlugin)), + rclcpp::Parameter("FollowPath.max_obstacles", 1)}); + // Before the first solve the nominal predicted trajectory (mpc_->getX()) is + // all-zero, so node 0's scan centres on the model-frame origin shifted BACK + // to base_link: 0 - wheelbase = -wheelbase. Place the occupied cell there. + fillCost( + -kBicycleWheelbase - 0.05, -0.05, -kBicycleWheelbase + 0.05, 0.05, + nav2_costmap_2d::LETHAL_OBSTACLE); + + MatrixXd obs( + static_cast(front->mpc()->getMaxObs() * front->mpc()->getNp()), 3); + for (Eigen::Index r = 0; r < obs.rows(); ++r) { + obs(r, 0) = prox_mpc::MPC::kObsFarSentinel; + obs(r, 1) = prox_mpc::MPC::kObsFarSentinel; + } + front->fillStaticObstacles(obs, 0, {}); + + // Node 0's slot must carry the cell's base_link-frame position shifted + // forward by the wheelbase (base_link -> the front axle's own reference + // frame), landing back near the model-frame origin, not the raw + // base_link-frame position (-wheelbase, 0) the shift started from. + EXPECT_NEAR(obs(0, 0), 0.0, kResolution); + EXPECT_NEAR(obs(0, 1), 0.0, kResolution); +} + +// The footprint veto operates in base_link terms regardless of the model's +// reference point (computeVelocityCommands transforms the predicted pose back +// before the check), so a lethal cell over the robot's own one-step-ahead +// base_link footprint vetoes for BOTH a front-axle and a rear-axle model, even +// though the two solve in different reference frames -- they protect the same +// physical point. +TEST_F(ControllerContractsTest, FootprintVetoFiresIdenticallyForFrontAndRearAxleModels) +{ + fillCost(-0.6, -0.6, 0.6, 0.6, nav2_costmap_2d::LETHAL_OBSTACLE); + + auto front = makeRunning( + {rclcpp::Parameter("FollowPath.model_plugin", std::string(kFrontAxlePlugin)), + rclcpp::Parameter("FollowPath.max_obstacles", 0)}); + const auto cmd_front = front->computeVelocityCommands( + makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + EXPECT_NEAR(cmd_front.twist.linear.x, 0.0, kTol); // ramp from rest: vetoed + EXPECT_EQ(front->failureCount(), 0); // veto is not a solver failure +} + +TEST_F(ControllerContractsTest, FootprintVetoFiresForRearAxleModelAtSamePoint) +{ + fillCost(-0.6, -0.6, 0.6, 0.6, nav2_costmap_2d::LETHAL_OBSTACLE); + + auto rear = makeRunning( + {rclcpp::Parameter("FollowPath.model_plugin", std::string(kRearAxlePlugin)), + rclcpp::Parameter("FollowPath.max_obstacles", 0)}); + const auto cmd_rear = rear->computeVelocityCommands( + makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + EXPECT_NEAR(cmd_rear.twist.linear.x, 0.0, kTol); + EXPECT_EQ(rear->failureCount(), 0); +} + +// --- Command validation: a non-finite Twist component OTHER than ------------ +// --- linear.x is caught, not published unchecked ---------------------------- + +TEST_F(ControllerContractsTest, NonFiniteOtherAxesTwistRampsThenEscalates) +{ + auto c = makeRunning( + { + rclcpp::Parameter( + "FollowPath.model_plugin", std::string("prox_mpc_test_models/NonFiniteTwistOtherAxes")), + rclcpp::Parameter("FollowPath.max_solver_failures", 1), + }); + + geometry_msgs::msg::Twist measured; + measured.linear.x = 0.30; + measured.angular.z = -0.30; + + // The QP converges (finite dynamics) and linear.x/angular.z are finite, but + // linear.y/angular.x are not: twist_is_finite() checks all six components, + // so this is caught exactly like NonFiniteTwistModel's linear.x case is in + // test_prox_mpc_controller.cpp's NonFiniteCommandRampsThenEscalates. + const auto cmd = c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), measured, nullptr); + EXPECT_NEAR(cmd.twist.linear.x, 0.30 - kModelDecel * 0.1, 1e-6); + EXPECT_TRUE(std::isfinite(cmd.twist.linear.y)); + EXPECT_TRUE(std::isfinite(cmd.twist.angular.x)); + EXPECT_EQ(c->failureCount(), 1); + + EXPECT_THROW( + c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), measured, nullptr), + nav2_core::NoValidControl); +} + +// --- SolverDiagnostics reports the applied outcome, not the QP's ------------ +// --- outcome alone; the publisher is opt-in and only-when-subscribed -------- + +// A subscriber connects to the plugin's diagnostics topic and collects every +// message delivered, spinning between control cycles so DDS discovery has a +// chance to complete (matches PublishesPredictedTrajectory's technique in +// test_prox_mpc_controller.cpp). +class DiagnosticsCollector +{ +public: + DiagnosticsCollector( + const rclcpp_lifecycle::LifecycleNode::SharedPtr & node, const std::string & topic) + { + exec_.add_node(node->get_node_base_interface()); + sub_ = node->create_subscription( + topic, rclcpp::QoS(10).reliable(), + [this](prox_mpc_msgs::msg::SolverDiagnostics::SharedPtr msg) { + received_.push_back(*msg); + }); + } + + // Runs one control cycle and spins until at least one new message is + // delivered, or the budget is spent (which is itself an assertable result: + // the caller checks the returned count against what it expects). + std::size_t runCycleAndCollect( + const std::function & cycle, int max_spins = 100) + { + const std::size_t before = received_.size(); + cycle(); + for (int i = 0; i < max_spins && received_.size() == before; ++i) { + exec_.spin_some(); + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + return received_.size() - before; + } + + const std::vector & received() const {return received_;} + + // Spins this collector's own executor. A node may be added to only one + // executor at a time, so callers that need to spin after runCycleAndCollect() + // reuse this rather than constructing a second executor over the same node. + void spinSome() {exec_.spin_some();} + +private: + rclcpp::executors::SingleThreadedExecutor exec_; + rclcpp::Subscription::SharedPtr sub_; + std::vector received_; +}; + +// publish_diagnostics defaulting false publishes nothing, even with an active +// subscriber -- the publisher itself is never created. +TEST_F(ControllerContractsTest, DiagnosticsPublisherOffPublishesNothing) +{ + auto c = makeRunning({rclcpp::Parameter("FollowPath.max_obstacles", 0)}); + DiagnosticsCollector collector(node_, "FollowPath/diagnostics"); + + for (int i = 0; i < 5; ++i) { + collector.runCycleAndCollect( + [&]() { + c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), + nullptr); + }, 20); + } + EXPECT_TRUE(collector.received().empty()); +} + +// publish_diagnostics true publishes exactly one message per control cycle, +// once a subscriber is connected. +TEST_F(ControllerContractsTest, DiagnosticsPublisherOnPublishesOncePerCycle) +{ + auto c = makeRunning( + {rclcpp::Parameter("FollowPath.max_obstacles", 0), + rclcpp::Parameter("FollowPath.publish_diagnostics", true)}); + DiagnosticsCollector collector(node_, "FollowPath/diagnostics"); + + const std::size_t got1 = collector.runCycleAndCollect( + [&]() { + c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), + nullptr); + }); + ASSERT_GE(got1, 1u); // discovery may take more than one cycle the first time + + const std::size_t before = collector.received().size(); + c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + collector.spinSome(); + EXPECT_EQ(collector.received().size(), before + 1); // exactly one per cycle +} + +// A normal accepted cycle reports status == STATUS_SOLVED with converged == +// true, and every field carries the value its comment in the .msg says it +// carries (SolverDiagnostics.msg): the header frame is the base frame, the +// residuals/objective/iteration counts mirror qp_info, max_obstacle_slack is +// 0 with obstacle avoidance off, control_period_ms is NaN on the first cycle +// of a task and a finite gap on the next, and deadline_missed follows +// solve_time_ms against the 1000*dt budget. +TEST_F(ControllerContractsTest, DiagnosticsFieldsMatchMessageContractOnAcceptedCycle) +{ + auto c = makeRunning( + {rclcpp::Parameter("FollowPath.max_obstacles", 0), + rclcpp::Parameter("FollowPath.publish_diagnostics", true)}); + DiagnosticsCollector collector(node_, "FollowPath/diagnostics"); + + collector.runCycleAndCollect( + [&]() { + c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), + nullptr); + }); + ASSERT_GE(collector.received().size(), 1u); + const auto & d1 = collector.received().back(); + EXPECT_EQ(d1.header.frame_id, "base_link"); + EXPECT_EQ(d1.status, prox_mpc_msgs::msg::SolverDiagnostics::STATUS_SOLVED); + EXPECT_TRUE(d1.converged); + EXPECT_GE(d1.solve_time_ms, 0.0); + EXPECT_GE(d1.qp_solve_time_ms, 0.0); + EXPECT_GE(d1.sqp_iters, 1u); + EXPECT_GE(d1.qp_iters_ext, 1u); + EXPECT_NEAR(d1.max_obstacle_slack, 0.0, kTol); // obstacle avoidance off + EXPECT_TRUE(std::isnan(d1.control_period_ms)); // first cycle of the task + EXPECT_EQ(d1.deadline_missed, d1.solve_time_ms > 1000.0 * 0.1); + EXPECT_EQ(d1.num_active_obstacles, 0u); + + const std::size_t before = collector.received().size(); + c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + for (int i = 0; i < 20 && collector.received().size() == before; ++i) { + collector.spinSome(); + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + ASSERT_GT(collector.received().size(), before); + const auto & d2 = collector.received().back(); + EXPECT_FALSE(std::isnan(d2.control_period_ms)); // second cycle: a real gap + EXPECT_GE(d2.control_period_ms, 0.0); +} + +// A footprint-vetoed cycle reports the QP's own outcome (status == +// STATUS_SOLVED, since the candidate itself converged) with converged == +// false, because the command was never applied. In 1.0.0 converged was set +// from the QP status alone and published before the gates, so a vetoed and +// braked cycle was recorded as converged, contradicting the released message's +// own definition of the field. +TEST_F(ControllerContractsTest, DiagnosticsReportsSolvedButNotConvergedOnFootprintVeto) +{ + auto c = makeRunning( + {rclcpp::Parameter("FollowPath.max_obstacles", 0), + rclcpp::Parameter("FollowPath.publish_diagnostics", true)}); + DiagnosticsCollector collector(node_, "FollowPath/diagnostics"); + fillCost(-0.6, -0.6, 0.6, 0.6, nav2_costmap_2d::LETHAL_OBSTACLE); + + collector.runCycleAndCollect( + [&]() { + c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), + nullptr); + }); + ASSERT_GE(collector.received().size(), 1u); + const auto & d = collector.received().back(); + EXPECT_EQ(d.status, prox_mpc_msgs::msg::SolverDiagnostics::STATUS_SOLVED); + EXPECT_FALSE(d.converged); +} + +// The footprint-veto escalation publishes before it throws, on the same terms +// as the solver-failure escalation. A cycle that ends the task with +// NoValidControl is still a control cycle, and the diagnostics record of why it +// ended is the last message on the topic; publishing after the escalation test +// would leave that cycle unrecorded. +TEST_F(ControllerContractsTest, DiagnosticsPublishedOnTheEscalatingVetoCycle) +{ + auto c = makeRunning( + {rclcpp::Parameter("FollowPath.max_obstacles", 0), + rclcpp::Parameter("FollowPath.max_solver_failures", 1), + rclcpp::Parameter("FollowPath.publish_diagnostics", true)}); + DiagnosticsCollector collector(node_, "FollowPath/diagnostics"); + fillCost(-0.6, -0.6, 0.6, 0.6, nav2_costmap_2d::LETHAL_OBSTACLE); + + // The first veto sits inside the budget and brakes. + ASSERT_EQ( + collector.runCycleAndCollect( + [&]() { + c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), + nullptr); + }), 1u); + + // The second exceeds it and ends the task, and is recorded all the same. + const std::size_t delivered = collector.runCycleAndCollect( + [&]() { + EXPECT_THROW( + c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), + nullptr), + nav2_core::NoValidControl); + }); + EXPECT_EQ(delivered, 1u); + EXPECT_FALSE(collector.received().back().converged); +} + +// A non-finite-toTwist cycle reports the same shape: the QP itself converged +// (status == STATUS_SOLVED) but converged == false, because toTwist()'s +// output failed the finiteness gate. +TEST_F(ControllerContractsTest, DiagnosticsReportsSolvedButNotConvergedOnNonFiniteToTwist) +{ + auto c = makeRunning( + {rclcpp::Parameter( + "FollowPath.model_plugin", std::string("prox_mpc_test_models/NonFiniteTwist")), + rclcpp::Parameter("FollowPath.publish_diagnostics", true)}); + DiagnosticsCollector collector(node_, "FollowPath/diagnostics"); + + collector.runCycleAndCollect( + [&]() { + c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), + nullptr); + }); + ASSERT_GE(collector.received().size(), 1u); + const auto & d = collector.received().back(); + EXPECT_EQ(d.status, prox_mpc_msgs::msg::SolverDiagnostics::STATUS_SOLVED); + EXPECT_FALSE(d.converged); +} + +// --- Terminal heading and travel direction ---------------------------------- + +// The final pose's quaternion differs from the final segment's tangent (the +// plan runs straight along +x, but the goal pose faces +y): existing tests in +// test_prox_mpc_controller.cpp use plans where the two agree, so none of them +// can tell terminal-yaw tracking from tangent-holding. mpc()->getGoalX() (a +// public MPC accessor) is the state reference actually handed to the solver. +TEST_F(ControllerContractsTest, TerminalYawTracksGoalOrientationDivergentFromTangent) +{ + auto c = makeConfigured({rclcpp::Parameter("FollowPath.max_obstacles", 0)}); + c->activate(); + + nav_msgs::msg::Path plan = makeStraightPlan(11, 0.2); // straight along +x, tangent yaw = 0 + plan.poses.back().pose.orientation.z = std::sin(M_PI / 4.0); // goal pose faces +y (yaw = pi/2) + plan.poses.back().pose.orientation.w = std::cos(M_PI / 4.0); + c->setPlan(plan); + + StubGoalChecker goal_checker(0.5); // publishes a yaw tolerance -> terminal yaw engages + // Pose already at the goal: every horizon node samples past the plan end. + c->computeVelocityCommands(makePose(2.0, 0.0, 0.0), geometry_msgs::msg::Twist(), &goal_checker); + + const std::size_t np = c->mpc()->getNp(); + EXPECT_NEAR( + c->mpc()->getGoalX()(static_cast(np), c->idxYaw()), M_PI / 2.0, 1e-6); +} + +// Without a published yaw tolerance, the reference instead holds the final +// segment's tangent (yaw = 0 here), exactly as it did before terminal-yaw +// tracking existed -- the other half of the same branch. +TEST_F(ControllerContractsTest, NoYawToleranceHoldsFinalSegmentTangent) +{ + auto c = makeConfigured({rclcpp::Parameter("FollowPath.max_obstacles", 0)}); + c->activate(); + + nav_msgs::msg::Path plan = makeStraightPlan(11, 0.2); + plan.poses.back().pose.orientation.z = std::sin(M_PI / 4.0); + plan.poses.back().pose.orientation.w = std::cos(M_PI / 4.0); + c->setPlan(plan); + + c->computeVelocityCommands(makePose(2.0, 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + + const std::size_t np = c->mpc()->getNp(); + EXPECT_NEAR(c->mpc()->getGoalX()(static_cast(np), c->idxYaw()), 0.0, 1e-6); +} + +// A reverse segment: the plan's own pose orientations face -x while the +// segment tangent points +x, so with allow_reversing the reference speed +// becomes negative (dir = -1); with it off (the default) the reference stays +// forward-only, unaffected by pose orientation. +TEST_F(ControllerContractsTest, AllowReversingSignsTheReferenceSpeedNegative) +{ + nav_msgs::msg::Path plan = makeStraightPlan(11, 0.2); + for (auto & p : plan.poses) { + p.pose.orientation.z = 1.0; // yaw = pi: faces -x, opposite the +x tangent + p.pose.orientation.w = 0.0; + } + + auto c = makeConfigured( + {rclcpp::Parameter("FollowPath.max_obstacles", 0), + rclcpp::Parameter("FollowPath.allow_reversing", true), + rclcpp::Parameter("FollowPath.reverse_from_plan_orientation", true)}); + c->activate(); + c->setPlan(plan); + c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + EXPECT_LT(c->mpc()->getGoalU()(0, static_cast(c->idxV())), 0.0); +} + +// The same plan, with reversing allowed but the plan's orientations not trusted +// (the default): the reference stays forward-only. This is what keeps a planner +// that leaves its pose orientations at the identity - NavFn, Smac 2D - from +// being read as asking for a reverse traverse of every path running the other +// way, which drove the robot backwards down the whole path. +TEST_F(ControllerContractsTest, UntrustedPlanOrientationKeepsReferenceForward) +{ + nav_msgs::msg::Path plan = makeStraightPlan(11, 0.2); + for (auto & p : plan.poses) { + p.pose.orientation.z = 1.0; // yaw = pi, opposite the +x tangent + p.pose.orientation.w = 0.0; + } + + auto c = makeConfigured( + {rclcpp::Parameter("FollowPath.max_obstacles", 0), + rclcpp::Parameter("FollowPath.allow_reversing", true)}); + c->activate(); + c->setPlan(plan); + c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + EXPECT_GE(c->mpc()->getGoalU()(0, static_cast(c->idxV())), 0.0); +} + +// A steering (Ackermann) model on a reversing plan. Unlike a differential drive, +// a car-like platform cannot turn in place, so reverse is the only way through a +// cusp and the capability has to survive the orientation-trust split. `dir` also +// signs the steering inverse, so the reference steering angle turns the opposite +// way in reverse for the same path curvature. +TEST_F(ControllerContractsTest, SteeringModelTracksReverseOnADirectionalPlan) +{ + // An arc whose poses face backwards along it, which is how a reversing plan is + // expressed: the body heading is the path tangent turned by pi. + nav_msgs::msg::Path plan; + plan.header.frame_id = "map"; + const double radius = 8.0; + const double dphi = 0.2 / radius; + for (int i = 0; i < 21; ++i) { + const double phi = static_cast(i) * dphi; + geometry_msgs::msg::PoseStamped ps; + ps.header.frame_id = "map"; + ps.pose.position.x = radius * std::sin(phi); + ps.pose.position.y = radius * (1.0 - std::cos(phi)); + const double facing = phi + M_PI; + ps.pose.orientation.z = std::sin(facing / 2.0); + ps.pose.orientation.w = std::cos(facing / 2.0); + plan.poses.push_back(ps); + } + + auto c = makeConfigured( + {rclcpp::Parameter("FollowPath.model_plugin", std::string(kFrontAxlePlugin)), + rclcpp::Parameter("FollowPath.max_obstacles", 0), + rclcpp::Parameter("FollowPath.allow_reversing", true), + rclcpp::Parameter("FollowPath.reverse_from_plan_orientation", true)}); + c->activate(); + c->setPlan(plan); + c->computeVelocityCommands(makePose(0.0, 0.0, M_PI), geometry_msgs::msg::Twist(), nullptr); + EXPECT_LT(c->mpc()->getGoalU()(0, static_cast(c->idxV())), 0.0); + + // The same plan with the orientations untrusted keeps the reference forward, + // so the default protects a steering model from an orientation-less planner + // exactly as it protects a differential drive. + auto fwd = makeConfigured( + {rclcpp::Parameter("FollowPath.model_plugin", std::string(kFrontAxlePlugin)), + rclcpp::Parameter("FollowPath.max_obstacles", 0), + rclcpp::Parameter("FollowPath.allow_reversing", true)}); + fwd->activate(); + fwd->setPlan(plan); + fwd->computeVelocityCommands(makePose(0.0, 0.0, M_PI), geometry_msgs::msg::Twist(), nullptr); + EXPECT_GE(fwd->mpc()->getGoalU()(0, static_cast(fwd->idxV())), 0.0); +} + +// Travel direction is a latched mode, not a per-cycle read of the plan, and a +// change is accepted only from rest: a drivetrain takes a gear shift at +// standstill, and the same gate is what stops the mode alternating cycle to +// cycle. While the change is pending the reference is pinned to the arc length +// under the robot, so the commanded speed falls to zero and the platform coasts +// down to the standstill the change is waiting on. +TEST_F(ControllerContractsTest, DirectionChangeIsHeldWhileThePlatformIsMoving) +{ + auto c = makeConfigured( + {rclcpp::Parameter("FollowPath.max_obstacles", 0), + rclcpp::Parameter("FollowPath.allow_reversing", true), + rclcpp::Parameter("FollowPath.reverse_from_plan_orientation", true), + rclcpp::Parameter("FollowPath.direction_switch_standstill_speed_mps", 1e-3), + rclcpp::Parameter("FollowPath.direction_switch_dwell_s", 0.0)}); + c->activate(); + + // Build forward speed first, so the platform is moving when the plan flips. + c->setPlan(makeStraightPlan(61, 0.2)); + geometry_msgs::msg::TwistStamped cmd; + for (int i = 0; i < 5; ++i) { + cmd = c->computeVelocityCommands( + makePose(0.2 * static_cast(i), 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + } + ASSERT_GT(cmd.twist.linear.x, 1e-3) << "the platform has to be moving for the gate to bite"; + + nav_msgs::msg::Path reverse_plan = makeStraightPlan(61, 0.2); + for (auto & p : reverse_plan.poses) { + p.pose.orientation.z = 1.0; // yaw = pi, opposite the +x tangent + p.pose.orientation.w = 0.0; + } + c->setPlan(reverse_plan); + c->computeVelocityCommands(makePose(1.0, 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + + // Held, not taken: the reference speed is zero rather than negative. + EXPECT_NEAR(c->mpc()->getGoalU()(0, static_cast(c->idxV())), 0.0, 1e-12); +} + +// The second gate. With standstill satisfied throughout, a change still waits +// out the dwell, which is what bounds the switching rate: a mode re-chosen every +// cycle with no dwell is free to chatter however cheap each switch looks. +TEST_F(ControllerContractsTest, DirectionChangeIsHeldUntilTheDwellElapses) +{ + auto c = makeConfigured( + {rclcpp::Parameter("FollowPath.max_obstacles", 0), + rclcpp::Parameter("FollowPath.allow_reversing", true), + rclcpp::Parameter("FollowPath.reverse_from_plan_orientation", true), + rclcpp::Parameter("FollowPath.direction_switch_standstill_speed_mps", 100.0), + rclcpp::Parameter("FollowPath.direction_switch_dwell_s", 100.0)}); + c->activate(); + + nav_msgs::msg::Path reverse_plan = makeStraightPlan(61, 0.2); + for (auto & p : reverse_plan.poses) { + p.pose.orientation.z = 1.0; + p.pose.orientation.w = 0.0; + } + // The first direction of a task is free: nothing has been switched away from. + c->setPlan(reverse_plan); + c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + ASSERT_LT(c->mpc()->getGoalU()(0, static_cast(c->idxV())), 0.0); + + // Switching straight back is not: the dwell has just been spent. + c->setPlan(makeStraightPlan(61, 0.2)); + c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + EXPECT_NEAR(c->mpc()->getGoalU()(0, static_cast(c->idxV())), 0.0, 1e-12); +} + +// Inside the goal-checker xy tolerance the reference is pinned to the goal pose +// instead of tracking the robot's own projection onto the plan. Composing the +// cruise taper with the sampling step makes the horizon's arc reach +// remaining^2 / xy_tol, shorter than `remaining` everywhere inside the +// tolerance, so the tracked reference would otherwise be a stub a few +// millimetres ahead of the projection that the robot carries along with it -- a +// reference with no fixed point, and one whose horizon never reaches the plan +// end, so the goal's own orientation never enters it. Pinning gives the last +// stretch a fixed setpoint and a standing yaw error to act on. +TEST_F(ControllerContractsTest, GoalRegionPinsTheReferenceToTheGoalPose) +{ + nav_msgs::msg::Path plan = makeStraightPlan(11, 0.2); // goal at x = 2.0 + // A goal yaw the robot is already within tolerance of, so this exercises the + // settle pin rather than the on-the-spot turn tested below, while still + // differing from the plan's own tangent (0.0) that the reference held before. + plan.poses.back().pose.orientation.z = std::sin(0.15); + plan.poses.back().pose.orientation.w = std::cos(0.15); + + auto c = makeConfigured({rclcpp::Parameter("FollowPath.max_obstacles", 0)}); + c->activate(); + c->setPlan(plan); + + StubGoalChecker goal_checker(0.5); // xy tolerance 1.0, yaw tolerance 0.5 + // 0.5 m short of the goal: inside the tolerance, so the settle latch engages. + c->computeVelocityCommands(makePose(1.5, 0.0, 0.0), geometry_msgs::msg::Twist(), &goal_checker); + + // Node 0 carries the goal pose, not the projection at x = 1.5. + EXPECT_NEAR(c->mpc()->getGoalX()(0, static_cast(c->idxX())), 2.0, 1e-6); + EXPECT_NEAR(c->mpc()->getGoalX()(0, static_cast(c->idxY())), 0.0, 1e-6); + EXPECT_NEAR(c->mpc()->getGoalX()(0, static_cast(c->idxYaw())), 0.3, 1e-6); +} + +// The latch is entered on the tolerance and released only past a wider band, so +// a remaining distance hovering about the tolerance cannot flip the reference +// mode to mode. Within one plan the projection is forward-only and the remaining +// distance is monotone, so the band is what a replan crosses: a goal that moves +// a little further away holds the latch, and one that moves well away releases +// it back to path tracking. +TEST_F(ControllerContractsTest, GoalRegionLatchReleasesOnlyPastTheHysteresisBand) +{ + auto c = makeConfigured( + {rclcpp::Parameter("FollowPath.max_obstacles", 0), + rclcpp::Parameter("FollowPath.goal_settle_hysteresis_m", 0.1)}); + c->activate(); + + StubGoalChecker goal_checker(0.5); // xy tolerance 1.0, so the band ends at 1.1 + const geometry_msgs::msg::Twist zero; + + // 0.5 m from the goal at x = 2.0: inside the tolerance, so the latch engages. + c->setPlan(makeStraightPlan(11, 0.2)); + c->computeVelocityCommands(makePose(1.5, 0.0, 0.0), zero, &goal_checker); + ASSERT_NEAR(c->mpc()->getGoalX()(0, static_cast(c->idxX())), 2.0, 1e-6); + + // Replanned 1.05 m out: past the tolerance but inside the band, so the latch + // holds and the reference stays pinned to the new goal rather than tracking. + c->setPlan(makeStraightPlan(8, 0.15)); // goal at x = 1.05 + c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), zero, &goal_checker); + EXPECT_NEAR(c->mpc()->getGoalX()(0, static_cast(c->idxX())), 1.05, 1e-6); + + // Replanned 2.0 m out: past the band, so tracking resumes and node 0 is the + // robot's own projection onto the plan again. + c->setPlan(makeStraightPlan(11, 0.2)); // goal at x = 2.0 + c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), zero, &goal_checker); + EXPECT_NEAR(c->mpc()->getGoalX()(0, static_cast(c->idxX())), 0.0, 1e-6); +} + +// Once the checker's own xy condition is met, only the heading is outstanding. +// Pinning the reference to the goal would leave the solver holding a position it +// is already close enough to, and reversing and re-advancing to hold it as the +// body sweeps round and the body-frame projection of the offset changes sign. +// The reference is therefore held at the robot's own reference point, leaving +// heading as the only standing error, and the platform turns on the spot. +TEST_F(ControllerContractsTest, TerminalHeadingTurnsOnTheSpot) +{ + nav_msgs::msg::Path plan = makeStraightPlan(11, 0.2); // goal at x = 2.0 + plan.poses.back().pose.orientation.z = std::sin(M_PI / 4.0); // goal yaw = pi/2 + plan.poses.back().pose.orientation.w = std::cos(M_PI / 4.0); + + auto c = makeConfigured({rclcpp::Parameter("FollowPath.max_obstacles", 0)}); + c->activate(); + c->setPlan(plan); + + StubGoalChecker goal_checker(0.5); // xy tolerance 1.0, yaw tolerance 0.5 + // 0.1 m from the goal, so the translation is done, but pi/2 of heading out. + c->computeVelocityCommands(makePose(1.9, 0.0, 0.0), geometry_msgs::msg::Twist(), &goal_checker); + + // The reference holds station at the robot, not at the goal 0.1 m ahead... + EXPECT_NEAR(c->mpc()->getGoalX()(0, static_cast(c->idxX())), 1.9, 1e-6); + // ...and carries the goal heading, which is the error left to close. + EXPECT_NEAR(c->mpc()->getGoalX()(0, static_cast(c->idxYaw())), M_PI / 2.0, 1e-6); + // No reference speed: the platform is asked to turn, not to translate. + EXPECT_NEAR(c->mpc()->getGoalU()(0, static_cast(c->idxV())), 0.0, 1e-12); +} + +// The same geometry with the heading already inside the checker's yaw tolerance +// is an ordinary settle: nothing is outstanding but the last of the translation, +// so the reference stays pinned to the goal pose. +TEST_F(ControllerContractsTest, TerminalHeadingWithinToleranceStaysPinnedToTheGoal) +{ + auto c = makeConfigured({rclcpp::Parameter("FollowPath.max_obstacles", 0)}); + c->activate(); + c->setPlan(makeStraightPlan(11, 0.2)); // goal yaw 0, matching the robot's + + StubGoalChecker goal_checker(0.5); + c->computeVelocityCommands(makePose(1.9, 0.0, 0.0), geometry_msgs::msg::Twist(), &goal_checker); + + EXPECT_NEAR(c->mpc()->getGoalX()(0, static_cast(c->idxX())), 2.0, 1e-6); +} + +// A steering model is excluded: a car-like platform cannot turn on the spot, and +// pinning its position would leave it no admissible way to correct its heading. +// It settles onto the goal pose and manoeuvres out of a heading error instead. +TEST_F(ControllerContractsTest, SteeringModelDoesNotTurnOnTheSpotAtTheGoal) +{ + nav_msgs::msg::Path plan = makeStraightPlan(11, 0.2); + plan.poses.back().pose.orientation.z = std::sin(M_PI / 4.0); + plan.poses.back().pose.orientation.w = std::cos(M_PI / 4.0); + + auto c = makeConfigured( + {rclcpp::Parameter("FollowPath.model_plugin", std::string(kFrontAxlePlugin)), + rclcpp::Parameter("FollowPath.max_obstacles", 0)}); + c->activate(); + c->setPlan(plan); + + StubGoalChecker goal_checker(0.5); + c->computeVelocityCommands(makePose(1.9, 0.0, 0.0), geometry_msgs::msg::Twist(), &goal_checker); + + EXPECT_NEAR(c->mpc()->getGoalX()(0, static_cast(c->idxX())), 2.0, 1e-6); +} + +TEST_F(ControllerContractsTest, ReversingOffKeepsForwardOnlyReferenceDespiteOrientation) +{ + nav_msgs::msg::Path plan = makeStraightPlan(11, 0.2); + for (auto & p : plan.poses) { + p.pose.orientation.z = 1.0; + p.pose.orientation.w = 0.0; + } + + // allow_reversing: default false + auto c = makeConfigured({rclcpp::Parameter("FollowPath.max_obstacles", 0)}); + c->activate(); + c->setPlan(plan); + c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + EXPECT_GE(c->mpc()->getGoalU()(0, static_cast(c->idxV())), 0.0); +} + +// A direction-change cusp truncates the reference at the first reversal: the +// plan runs forward from x=0 to x=1.0, then reverses back toward x=0 with the +// SAME pose orientation throughout (yaw = 0), so the tangent (not the +// orientation) is what flips. The reference must hold at the cusp (x ~ 1.0) +// rather than continue past it back toward x=0 within one horizon. +TEST_F(ControllerContractsTest, DirectionChangeCuspTruncatesTheReference) +{ + nav_msgs::msg::Path plan; + plan.header.frame_id = "map"; + for (int i = 0; i <= 10; ++i) { // 0.0 -> 1.0, forward + geometry_msgs::msg::PoseStamped ps; + ps.header.frame_id = "map"; + ps.pose.position.x = static_cast(i) * 0.1; + ps.pose.orientation.w = 1.0; + plan.poses.push_back(ps); + } + for (int i = 9; i >= 0; --i) { // 0.9 -> 0.0, tangent reverses; orientation unchanged + geometry_msgs::msg::PoseStamped ps; + ps.header.frame_id = "map"; + ps.pose.position.x = static_cast(i) * 0.1; + ps.pose.orientation.w = 1.0; + plan.poses.push_back(ps); + } + + auto c = makeConfigured( + {rclcpp::Parameter("FollowPath.max_obstacles", 0), + rclcpp::Parameter("FollowPath.allow_reversing", true), + rclcpp::Parameter("FollowPath.reverse_from_plan_orientation", true)}); + c->activate(); + c->setPlan(plan); + c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + + const std::size_t np = c->mpc()->getNp(); + // Held at the cusp (~1.0), not continuing past it back toward 0.0 within + // the horizon -- the horizon (Np * dt = 2 s at the defaults) comfortably + // reaches and passes the 1 m cusp point at any ordinary cruise speed. + EXPECT_GE(c->mpc()->getGoalX()(static_cast(np), c->idxX()), 1.0 - 0.05); +} + +// --- At the controller level, the released Bicycle name still loads --------- +// --- and resolves to the front-axle plugin ---------------------------------- + +TEST_F(ControllerContractsTest, DeprecatedBicycleNameResolvesToFrontAxlePhysics) +{ + auto c = makeConfigured( + {rclcpp::Parameter("FollowPath.model_plugin", std::string("prox_mpc_core/Bicycle"))}); + ASSERT_NE(c->model(), nullptr); + EXPECT_EQ(c->model()->getName(), "bicycle"); + EXPECT_NEAR(c->wheelbase(), kBicycleWheelbase, 1e-9); + EXPECT_NEAR(c->refOffsetX(), kBicycleWheelbase, 1e-9); // front-axle offset, not 0 + EXPECT_TRUE(c->hasSteering()); +} + +int main(int argc, char ** argv) +{ + rclcpp::init(argc, argv); + ::testing::InitGoogleTest(&argc, argv); + const int result = RUN_ALL_TESTS(); + rclcpp::shutdown(); + return result; +} diff --git a/prox_mpc_controller/test/test_prox_mpc_controller.cpp b/prox_mpc_controller/test/test_prox_mpc_controller.cpp index a5b0d25..d0a10d4 100644 --- a/prox_mpc_controller/test/test_prox_mpc_controller.cpp +++ b/prox_mpc_controller/test/test_prox_mpc_controller.cpp @@ -29,7 +29,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -51,6 +53,7 @@ #include #include #include +#include #include #include @@ -65,6 +68,10 @@ constexpr double kModelDecel = 0.5; // bundled-model du bound [m/s^2, rad constexpr double kResolution = 0.05; // test costmap resolution [m] constexpr unsigned int kGridCells = 200u; // 10 m x 10 m grid constexpr double kGridOrigin = -5.0; // centered grid origin [m] +constexpr double kBicycleWheelbase = 1.6; // bundled bicycle wheelbase [m] +// The bundled bicycles are not the default model, so a test that needs one names it. +constexpr const char * kBicyclePlugin = "prox_mpc_core/BicycleFrontAxle"; +constexpr double kSteerRateBound = 1.0; // bundled Bicycle u[1] bound [rad/s], bicycle.hpp:41 // Exposes the protected helper and runtime state so the fail-safe and reduction // branches can be driven and the safe command asserted (white-box, no production @@ -88,6 +95,7 @@ class TestableProxMpcController : public prox_mpc_controller::ProxMpcController double & lastCmdV() {return last_cmd_v_;} double & lastCmdW() {return last_cmd_w_;} double & steeringState() {return steering_state_;} + VectorXd & lastCmdU() {return last_cmd_u_;} std::size_t & planIndex() {return plan_index_;} bool cancelling() const {return cancelling_;} double vMax() const {return v_max_;} @@ -95,6 +103,15 @@ class TestableProxMpcController : public prox_mpc_controller::ProxMpcController double desiredLinearVel() const {return desired_linear_vel_;} std::size_t nDim() const {return n_;} std::size_t maxObstacles() const {return static_cast(max_obstacles_);} + int maxSolverFailures() const {return max_solver_failures_;} + double safetyMargin() const {return safety_margin_;} + double robotRadius() const {return robot_radius_;} + double cbfGamma() const {return cbf_gamma_;} + double obstacleClusterRadius() const {return obstacle_cluster_radius_;} + double obstacleTimeout() const {return obstacle_timeout_;} + double dynamicSpeedThreshold() const {return dynamic_speed_threshold_;} + double predictionUncertaintyGrowth() const {return prediction_uncertainty_growth_;} + double maxDynamicObstacleRadius() const {return max_dynamic_obstacle_radius_;} std::shared_ptr mpc() const {return mpc_;} std::shared_ptr model() const {return model_;} }; @@ -119,6 +136,46 @@ class NoDuBoundModel : public prox_mpc::Model void updateB() override {} }; +// A conforming model with exactly one control: a speed channel and nothing else. +// The planar contract asks for one speed control and no more, so this must be +// accepted rather than rejected for lacking a second control's rate bound. +class SingleControlModel : public prox_mpc::Model +{ +public: + SingleControlModel() + { + setName("single_control"); + setN(3); + setM(1); + setIneq("u", 0, -3.0, 3.0); + setIneq("du", 0, -0.5, 0.5); + } + void updatec(double, VectorXd) override {} + void updateA(double) override {} + void updateB() override {} +}; + +// A model that declares the speed bound but pins it shut. required_bound() only +// rejects an absent entry, so this one is present and useless: v_max would be +// zero and the cruise speed clamped to it. +class ZeroSpeedBoundModel : public prox_mpc::Model +{ +public: + ZeroSpeedBoundModel() + { + setName("zero_speed_bound"); + setN(3); + setM(2); + setIneq("u", 0, 0.0, 0.0); + setIneq("u", 1, -1.0, 1.0); + setIneq("du", 0, -0.5, 0.5); + setIneq("du", 1, -0.5, 0.5); + } + void updatec(double, VectorXd) override {} + void updateA(double) override {} + void updateB() override {} +}; + // The mirror case: control-rate bounds but no bound on the speed channel, which // would leave v_max (and hence the cruise-speed clamp) at zero. class NoUBoundModel : public prox_mpc::Model @@ -238,8 +295,14 @@ void addPredictedSamples( class StubGoalChecker : public nav2_core::GoalChecker { public: + // Isotropic tolerance: the shape every goal checker Nav2 ships actually + // produces (SimpleGoalChecker writes the same scalar into both fields). StubGoalChecker(double xy_tol, bool valid) - : xy_tol_(xy_tol), valid_(valid) {} + : StubGoalChecker(xy_tol, xy_tol, valid) {} + // Anisotropic tolerance, for a custom goal checker whose x and y tolerances + // differ; the pair equal tests above can never exercise this shape. + StubGoalChecker(double x_tol, double y_tol, bool valid) + : x_tol_(x_tol), y_tol_(y_tol), valid_(valid) {} void initialize( const rclcpp_lifecycle::LifecycleNode::WeakPtr &, const std::string &, const std::shared_ptr) override {} @@ -250,15 +313,53 @@ class StubGoalChecker : public nav2_core::GoalChecker bool getTolerances( geometry_msgs::msg::Pose & pose_tolerance, geometry_msgs::msg::Twist &) override { - pose_tolerance.position.x = xy_tol_; - pose_tolerance.position.y = xy_tol_; + pose_tolerance.position.x = x_tol_; + pose_tolerance.position.y = y_tol_; return valid_; } private: - double xy_tol_; + double x_tol_; + double y_tol_; bool valid_; }; + +// Installs a custom rcutils output handler for its lifetime and records every +// WARN-or-worse message's fully formatted text, so a test can assert on a log +// message's content directly instead of only inferring that some warning +// fired. Restores the previous handler on destruction (RAII), so a test that +// constructs one on the stack cannot leak it into a later test. +class LogCapture +{ +public: + LogCapture() + : previous_(rcutils_logging_get_output_handler()) + { + messages_.clear(); + rcutils_logging_set_output_handler(&LogCapture::handle); + } + ~LogCapture() {rcutils_logging_set_output_handler(previous_);} + + static const std::vector & messages() {return messages_;} + +private: + static void handle( + const rcutils_log_location_t *, int severity, const char *, + rcutils_time_point_value_t, const char * format, va_list * args) + { + if (severity < RCUTILS_LOG_SEVERITY_WARN) {return;} + char buf[512]; + va_list copy; + va_copy(copy, *args); + vsnprintf(buf, sizeof(buf), format, copy); + va_end(copy); + messages_.emplace_back(buf); + } + + rcutils_logging_output_handler_t previous_; + static std::vector messages_; +}; +std::vector LogCapture::messages_; } // namespace class ProxMpcControllerTest : public ::testing::Test @@ -367,11 +468,12 @@ class ProxMpcControllerTest : public ::testing::Test // --- configure() ----------------------------------------------------------- -// configure() loads the default Bicycle model, sizes the MPC, and reads the -// model's speed bound from its declared constraints. +// configure() loads the named model, sizes the MPC, and reads the model's speed +// bound from its declared constraints. TEST_F(ProxMpcControllerTest, ConfigureLoadsModelAndSizesMpc) { - auto c = makeConfigured(); + auto c = makeConfigured( + {rclcpp::Parameter("FollowPath.model_plugin", std::string(kBicyclePlugin))}); ASSERT_NE(c->model(), nullptr); ASSERT_NE(c->mpc(), nullptr); EXPECT_EQ(c->nDim(), 4u); // bicycle state [x, y, theta, delta] @@ -404,6 +506,105 @@ TEST_F(ProxMpcControllerTest, ConfigureThrowsOnUnknownModelPlugin) nav2_core::ControllerException); } +// nc > np is well-formed dead weight in the core (surplus controls drive no +// state transition) but is rejected as a configuration error at the plugin +// boundary, matching the existing np < 1 / nc < 1 / dt <= 0 fatal checks. +TEST_F(ProxMpcControllerTest, ConfigureThrowsWhenNcExceedsNp) +{ + auto c = makeUnconfigured( + {rclcpp::Parameter("FollowPath.np", 5), rclcpp::Parameter("FollowPath.nc", 10)}); + EXPECT_THROW( + c->configure(node_, "FollowPath", tf_, costmap_ros_), + nav2_core::ControllerException); +} + +// dt <= 0.0 is false for NaN, so the structural horizon-sizing gate needs an +// explicit finiteness check to catch it. +TEST_F(ProxMpcControllerTest, ConfigureThrowsOnNonFiniteDt) +{ + auto c = makeUnconfigured( + {rclcpp::Parameter("FollowPath.dt", std::numeric_limits::quiet_NaN())}); + EXPECT_THROW( + c->configure(node_, "FollowPath", tf_, costmap_ros_), + nav2_core::ControllerException); +} + +// A non-finite value at a clamped parameter site (bare "<"/">" comparisons pass +// NaN through every range check) falls back to the parameter's declared +// default, for every parameter configure() guards this way. One row per +// clamp_low/clamp_range call site, plus desired_linear_vel, which is guarded +// in place because its ceiling is the model's own declared speed bound rather +// than a literal; each row reads back the result through whichever accessor +// observes where that configure()-local variable ends up (a stored member, or +// the MPC weight matrix it seeds). +TEST_F(ProxMpcControllerTest, ConfigureUsesDefaultForNonFiniteClampedParameter) +{ + const double nan = std::numeric_limits::quiet_NaN(); + using Read = std::function &)>; + struct Row + { + const char * param; + double expected_default; + Read read; + }; + const Row rows[] = { + {"q_pos", 10.0, [](const auto & c) {return c->mpc()->getQ()(0, 0);}}, + {"q_theta", 1.0, [](const auto & c) {return c->mpc()->getQ()(2, 2);}}, + {"s_factor", 2.0, + [](const auto & c) {return c->mpc()->getS()(0, 0) / c->mpc()->getQ()(0, 0);}}, + {"r_weight", 0.1, [](const auto & c) {return c->mpc()->getR()(0, 0);}}, + {"w_weight", 1000.0, [](const auto & c) {return c->mpc()->getW()(0, 0);}}, + {"safety_margin", 0.1, [](const auto & c) {return c->safetyMargin();}}, + {"robot_radius", 0.5, [](const auto & c) {return c->robotRadius();}}, + {"cbf_gamma", 1.0, [](const auto & c) {return c->cbfGamma();}}, + {"obstacle_cluster_radius", 0.3, [](const auto & c) {return c->obstacleClusterRadius();}}, + {"obstacle_timeout", 0.5, [](const auto & c) {return c->obstacleTimeout();}}, + {"dynamic_speed_threshold", 0.1, [](const auto & c) {return c->dynamicSpeedThreshold();}}, + {"prediction_uncertainty_growth", 0.0, + [](const auto & c) {return c->predictionUncertaintyGrowth();}}, + {"max_dynamic_obstacle_radius", 0.0, + [](const auto & c) {return c->maxDynamicObstacleRadius();}}, + {"desired_linear_vel", 1.0, [](const auto & c) {return c->desiredLinearVel();}}, + }; + for (const auto & row : rows) { + SCOPED_TRACE(row.param); + auto c = makeConfigured({rclcpp::Parameter(std::string("FollowPath.") + row.param, nan)}); + ASSERT_NE(c->mpc(), nullptr); + EXPECT_NEAR(row.read(c), row.expected_default, kTol); + } +} + +// max_solve_time is a configure()-local wall-clock budget forwarded into the +// core's MPC, which exposes no getter for it, so its default fallback is not +// directly observable from the plugin's public surface; the check available +// here is that a non-finite value does not throw configure() and does not +// propagate into a non-finite command. (max_solve_time's clamp floor and +// declared default are both 0.0, so even a getter could not distinguish "fell +// back to the default" from "clamped to the floor" for this one parameter -- +// both paths return the same number.) +TEST_F(ProxMpcControllerTest, ConfigureAcceptsNonFiniteMaxSolveTime) +{ + std::shared_ptr c; + EXPECT_NO_THROW( + c = makeConfigured( + {rclcpp::Parameter("FollowPath.max_solve_time", std::numeric_limits::quiet_NaN())})); + ASSERT_NE(c, nullptr); + c->activate(); + c->setPlan(makeStraightPlan(31, 0.2)); + const auto cmd = c->computeVelocityCommands( + makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + EXPECT_TRUE(std::isfinite(cmd.twist.linear.x)); + EXPECT_TRUE(std::isfinite(cmd.twist.angular.z)); +} + +// A negative max_solver_failures is clamped to 0, matching the max_obstacles +// clamp shape, rather than left as an arbitrary negative value. +TEST_F(ProxMpcControllerTest, ConfigureClampsNegativeMaxSolverFailuresToZero) +{ + auto c = makeConfigured({rclcpp::Parameter("FollowPath.max_solver_failures", -5)}); + EXPECT_EQ(c->maxSolverFailures(), 0); +} + // Every log_level keyword (and an unrecognized value) is accepted at configure. TEST_F(ProxMpcControllerTest, ConfigureAcceptsAllLogLevels) { @@ -481,6 +682,82 @@ TEST_F(ProxMpcControllerTest, MissingModelBoundIsFatal) EXPECT_NEAR(configured->vMax(), kModelVMax, kTol); } +// A declared speed bound of zero is as fatal as an absent one, and for the same +// reason: the cruise speed is clamped to it and the robot never moves. The +// message names the model and the bound it read. +TEST_F(ProxMpcControllerTest, ZeroSpeedBoundIsFatal) +{ + auto c = makeUnconfigured(); + ZeroSpeedBoundModel zero; + try { + c->readModelBounds(zero, "test/ZeroSpeedBound"); + FAIL() << "a model whose speed bound is zero must not configure"; + } catch (const nav2_core::ControllerException & ex) { + const std::string what(ex.what()); + EXPECT_NE(what.find("'u'"), std::string::npos) << what; + EXPECT_NE(what.find("test/ZeroSpeedBound"), std::string::npos) << what; + } +} + +// A model with one control declares no second control-rate bound, and must not +// be rejected for it: the second body-twist channel only exists to be ramped +// when there is a control to source a rate from. Rejecting it would also have +// named an "angular control" the model never declared. +TEST_F(ProxMpcControllerTest, SingleControlModelReadsBounds) +{ + auto c = makeUnconfigured(); + SingleControlModel one; + EXPECT_NO_THROW(c->readModelBounds(one, "test/SingleControl")); + EXPECT_NEAR(c->vMax(), 3.0, kTol); +} + +// robot_radius below the costmap footprint's circumscribed radius is +// warn-and-continue rather than fatal: configure() must not throw, and +// robot_radius must not be silently overwritten to match the +// footprint -- an operator running a deliberately tighter disc keeps it. The +// fixture's default square footprint (half-extent 0.5 m, padded to 0.51 m) +// and default robot_radius (0.5 m) already trigger this case; the warning +// text is asserted directly, naming both values, not merely inferred. +TEST_F(ProxMpcControllerTest, RobotRadiusWarnsWhenBelowFootprintCircumscribedRadius) +{ + LogCapture log; + std::shared_ptr c; + ASSERT_NO_THROW(c = makeConfigured()); + ASSERT_NE(c, nullptr); + EXPECT_NEAR(c->robotRadius(), 0.5, kTol); // not overwritten to the footprint's radius + + bool found = false; + for (const auto & msg : LogCapture::messages()) { + if (msg.find("robot_radius 0.500 m") != std::string::npos && + msg.find("circumscribed radius 0.7212 m") != std::string::npos && + // Rounded up to the millimetre it is printed at, so setting exactly what + // the message asks for clears the check instead of tripping it again. + msg.find("at least 0.722 m") != std::string::npos) + { + found = true; + break; + } + } + EXPECT_TRUE(found) << "expected a robot_radius/circumscribed-radius warning naming both values"; +} + +// A footprint within robot_radius configures silently: no warning is emitted, +// and the parameter is (still) not touched. +TEST_F(ProxMpcControllerTest, RobotRadiusConfiguresSilentlyWhenWithinFootprint) +{ + costmap_ros_->setRobotFootprint(makeSquareFootprint(0.1)); // circumscribed ~0.156 m + + LogCapture log; + std::shared_ptr c; + ASSERT_NO_THROW(c = makeConfigured({rclcpp::Parameter("FollowPath.robot_radius", 0.5)})); + ASSERT_NE(c, nullptr); + EXPECT_NEAR(c->robotRadius(), 0.5, kTol); + + for (const auto & msg : LogCapture::messages()) { + EXPECT_EQ(msg.find("robot_radius"), std::string::npos) << msg; + } +} + // --- lifecycle: activate / deactivate / cleanup ---------------------------- // activate() clears the runtime counters and the cancelling flag. @@ -639,11 +916,14 @@ TEST_F(ProxMpcControllerTest, ComputeTracksAcrossHeadingWrap) } // On a curved plan the bicycle steering reference is pre-positioned to the path -// curvature (delta_ref = atan(L*kappa) != 0); on a straight plan it stays zero. -// Read back from the state reference the controller hands the MPC. +// curvature; on a straight plan it stays zero. Read back from the state +// reference the controller hands the MPC. The front-axle model's inverse is +// asin(L*kappa), the rear-axle one's is atan(L*kappa); both are far above the +// threshold asserted here. TEST_F(ProxMpcControllerTest, CurvatureSetsBicycleSteeringReference) { - auto c = makeConfigured(); // default Bicycle (n = 4, L = 1.6) + auto c = makeConfigured( + {rclcpp::Parameter("FollowPath.model_plugin", std::string(kBicyclePlugin))}); c->activate(); ASSERT_EQ(c->nDim(), 4u); @@ -663,7 +943,7 @@ TEST_F(ProxMpcControllerTest, CurvatureSetsBicycleSteeringReference) for (Eigen::Index k = 0; k < gx_arc.rows(); ++k) { max_delta_arc = std::max(max_delta_arc, std::abs(gx_arc(k, 3))); } - EXPECT_GT(max_delta_arc, 0.2); // atan(L*kappa) ~ atan(0.8) = 0.675 rad + EXPECT_GT(max_delta_arc, 0.2); // asin(L*kappa) = asin(0.8) = 0.927 rad } // The unicycle (no steering state, n = 3) keeps the go-straight default even on @@ -699,6 +979,20 @@ TEST_F(ProxMpcControllerTest, CurvatureGainReducesCruiseOnCurvedPlan) EXPECT_LT(vref_gain, vref_gain0); // curvature taper slows the cruise } +// The curvature estimator seeds its first heading delta from the plan's own +// sampled tangent, not the robot's yaw: on a straight plan (zero true +// curvature) a robot heading that differs from the path tangent must not by +// itself taper the cruise speed. +TEST_F(ProxMpcControllerTest, CurvatureGainIgnoresInitialHeadingMismatchOnStraightPlan) +{ + auto c = makeConfigured({rclcpp::Parameter("FollowPath.curvature_gain", 2.0)}); + c->activate(); + c->setPlan(makeStraightPlan(31, 0.2)); // straight plan along +x + c->computeVelocityCommands( + makePose(0.0, 0.0, 1.0), geometry_msgs::msg::Twist(), nullptr); // heading far off the path + EXPECT_NEAR(c->mpc()->getGoalU()(0, 0), c->desiredLinearVel(), 1e-6); +} + // goal_checker xy tolerance eases the cruise reference once the robot is inside // the tolerance band; the lowest() sentinel and a false return leave it intact. TEST_F(ProxMpcControllerTest, GoalCheckerToleranceEasesApproach) @@ -741,6 +1035,69 @@ TEST_F(ProxMpcControllerTest, GoalCheckerToleranceInertOutsideBand) EXPECT_NEAR(c->mpc()->getGoalU()(0, 0), vref_base, kTol); } +// The taper radius is the tolerance itself (std::min of the two axes), not the +// diagonal upstream's hypot(x, y) would read: SimpleGoalChecker writes the same +// scalar into both fields, so hypot(T, T) = sqrt(2) * T would start the taper +// about 41% too far from the goal. StubGoalChecker(t, true) is isotropic +// (equal x and y), so this pins the sqrt(2) defect specifically, which an +// equal-tolerance stub run at only one remaining distance cannot: one point +// where the true tolerance is already satisfied (no easing) but hypot's +// inflated radius would still ease, and one where both ease, but by +// numerically different factors. A short horizon (np * dt) keeps the +// horizon-based cruise taper from binding at these near-goal poses, isolating +// the goal-checker term. +TEST_F(ProxMpcControllerTest, GoalCheckerToleranceIsRadialNotHypotExpanded) +{ + auto c = makeConfigured( + { + rclcpp::Parameter("FollowPath.np", 2), + rclcpp::Parameter("FollowPath.nc", 2), + rclcpp::Parameter("FollowPath.dt", 0.01), + }); + c->activate(); + c->setPlan(makeStraightPlan(6, 0.2)); // 1 m plan + + const double t = 0.1; + StubGoalChecker checker(t, true); + + // remaining = 0.12 m: inside hypot(t, t) = 0.1414 m (would still ease under + // the old reading) but outside the true radial tolerance t = 0.1 m. + c->computeVelocityCommands( + makePose(0.88, 0.0, 0.0), geometry_msgs::msg::Twist(), &checker); + EXPECT_NEAR(c->mpc()->getGoalU()(0, 0), 1.0, kTol); // desired_linear_vel, unreduced + + // remaining = 0.05 m: inside t, so both readings ease, but the radial factor + // (0.05 / 0.1 = 0.5) differs from hypot's (0.05 / 0.14142 = 0.3536). + c->computeVelocityCommands( + makePose(0.95, 0.0, 0.0), geometry_msgs::msg::Twist(), &checker); + EXPECT_NEAR(c->mpc()->getGoalU()(0, 0), 0.5, 1e-6); +} + +// An anisotropic custom goal checker (x and y tolerances differ) is read +// through std::min of the two axes: the conservative reading for a checker +// whose y tolerance is tighter than its x, and distinct from both RPP's +// x-only reading and a hypot diagonal, neither of which an equal-tolerance +// stub can separate from std::min. +TEST_F(ProxMpcControllerTest, GoalCheckerToleranceReadsAnisotropicAsMinimum) +{ + auto c = makeConfigured( + { + rclcpp::Parameter("FollowPath.np", 2), + rclcpp::Parameter("FollowPath.nc", 2), + rclcpp::Parameter("FollowPath.dt", 0.01), + }); + c->activate(); + c->setPlan(makeStraightPlan(6, 0.2)); + + // remaining = 0.08 m; x_tol = 0.3, y_tol = 0.1. std::min gives 0.08 / 0.1 = + // 0.8, versus RPP's x-only 0.08 / 0.3 = 0.2667 or a hypot diagonal + // 0.08 / hypot(0.3, 0.1) = 0.253 -- both far from 0.8. + StubGoalChecker checker(0.3, 0.1, true); + c->computeVelocityCommands( + makePose(0.92, 0.0, 0.0), geometry_msgs::msg::Twist(), &checker); + EXPECT_NEAR(c->mpc()->getGoalU()(0, 0), 0.8, 1e-6); +} + // The predicted NMPC trajectory is published as a Path (Np+1 poses, costmap // global frame) for visualization, distinct from the Nav2 global plan. TEST_F(ProxMpcControllerTest, PublishesPredictedTrajectory) @@ -863,12 +1220,138 @@ TEST_F(ProxMpcControllerTest, ComputeDeceleratesOnNonFinitePose) EXPECT_EQ(c->failureCount(), 1); } +// A non-finite plan pose beyond the sampled horizon must still reject the whole +// cycle: the transform loop validates every plan pose up front, not only the +// ones the horizon happens to sample. Without that check this corrupted point +// is never read by sample() (it sits well past the ~2 m horizon reach) and the +// cycle would drive normally, oblivious to the corruption elsewhere in the plan. +TEST_F(ProxMpcControllerTest, ComputeDeceleratesOnNonFinitePlanPoseBeyondHorizon) +{ + auto c = makeConfigured(); + c->activate(); + nav_msgs::msg::Path path = makeStraightPlan(50, 0.2); // 10 m plan; horizon reaches ~2 m + path.poses[40].pose.position.x = std::numeric_limits::quiet_NaN(); + c->setPlan(path); + + const auto cmd = c->computeVelocityCommands( + makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + EXPECT_TRUE(std::isfinite(cmd.twist.linear.x)); + EXPECT_TRUE(std::isfinite(cmd.twist.angular.z)); + EXPECT_NEAR(cmd.twist.linear.x, 0.0, kTol); // braked from rest, not a normal cruise command + EXPECT_EQ(c->failureCount(), 1); +} + +// A leading run of duplicate plan positions collapses the first segment to zero +// length; the heading reference at that node must come from the next segment +// with positive length, not from atan2(0, 0) on the degenerate one. +TEST_F(ProxMpcControllerTest, ComputeSkipsDuplicateLeadingPlanPointForHeading) +{ + auto c = makeConfigured(); + c->activate(); + + nav_msgs::msg::Path path; + path.header.frame_id = "map"; + auto addPose = [&](double x, double y) { + geometry_msgs::msg::PoseStamped ps; + ps.header.frame_id = "map"; + ps.pose.position.x = x; + ps.pose.position.y = y; + ps.pose.orientation.w = 1.0; + path.poses.push_back(ps); + }; + addPose(0.0, 0.0); + addPose(0.0, 0.0); // duplicate of the first pose + addPose(0.0, 1.0); // the path actually heads in +y + c->setPlan(path); + + c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + const MatrixXd gx = c->mpc()->getGoalX(); + EXPECT_NEAR(gx(0, 2), M_PI / 2.0, 1e-6); +} + +// A sparse (coarsely spaced) plan is projected onto its true nearest segment +// point, not snapped to whichever vertex happens to be nearest: at the default +// 0.05 m costmap resolution, an 8 m vertex spacing is far too coarse for +// vertex snapping and true segment projection to agree. 1.0.0 compared +// distance to vertices only, so it could jump the tracked progress straight to +// the far end of a long segment. +TEST_F(ProxMpcControllerTest, PlanProjectionSparsePlanUsesTrueSegmentPoint) +{ + auto c = makeConfigured(); + c->activate(); + nav_msgs::msg::Path path; + path.header.frame_id = "map"; + for (double x : {-4.0, 4.0}) { // one 8 m segment, within the 10 m x 10 m grid + geometry_msgs::msg::PoseStamped ps; + ps.header.frame_id = "map"; + ps.pose.position.x = x; + ps.pose.orientation.w = 1.0; + path.poses.push_back(ps); + } + c->setPlan(path); + + // 5 m along the segment (from x = -4), offset toward the far vertex so + // vertex-only snapping picks (4, 0) (distance 3.007) over (-4, 0) (5.004). + c->computeVelocityCommands(makePose(1.0, 0.2, 0.0), geometry_msgs::msg::Twist(), nullptr); + + // True segment projection: s0 = 5.0 m of 8.0 m, remaining = 3.0 m, well + // inside the horizon (np * dt = 2.0 s at the default 1.0 m/s cruise), so the + // cruise reference is not tapered. Vertex snapping to (4, 0) (s0 = 8.0 m) + // would leave 0 m remaining and collapse the reference to zero. + EXPECT_EQ(c->planIndex(), 0u); + EXPECT_NEAR(c->mpc()->getGoalU()(0, 0), 1.0, 1e-6); +} + +// A self-intersecting (looping) plan does not jump the tracked progress +// forward onto a distant later branch merely because that branch happens to +// have a VERTEX geometrically close to the robot: the true continuous +// projection onto the segment the robot is actually on stays closer, because +// it is not restricted to vertices. +TEST_F(ProxMpcControllerTest, PlanProjectionSelfIntersectingPlanAvoidsForwardJump) +{ + auto c = makeConfigured(); + c->activate(); + + nav_msgs::msg::Path path; + path.header.frame_id = "map"; + auto addPose = [&](double x, double y) { + geometry_msgs::msg::PoseStamped ps; + ps.header.frame_id = "map"; + ps.pose.position.x = x; + ps.pose.position.y = y; + ps.pose.orientation.w = 1.0; + path.poses.push_back(ps); + }; + addPose(-4.0, 0.0); // P0 + addPose(4.0, 0.0); // P1: the segment the robot is actually on + addPose(4.0, 4.0); // P2 + addPose(0.0, 1.2); // P3: a later branch looping back near the robot + addPose(0.0, 4.0); // P4 + c->setPlan(path); + + // On segment P0-P1, offset 0.05 m: the nearest VERTEX is P3 (distance + // 1.524 m), closer than either P0 (5.0 m) or P1 (3.0 m), but the nearest + // point on any segment is on P0-P1 itself, 0.05 m away. + c->computeVelocityCommands(makePose(1.0, 0.05, 0.0), geometry_msgs::msg::Twist(), nullptr); + EXPECT_EQ(c->planIndex(), 0u); // stays on segment 0, not the P2-P3 branch (index 2) +} + // A non-converged solve decelerates the last command at the model deceleration // limit, then escalates to NoValidControl once the failure budget is spent. +// +// The brake ramps the model's own controls through toTwist() rather than +// ramping the measured twist directly, so the bicycle's angular.z is not a +// twist-space ramp of the measured yaw rate: the second control is a steering +// rate, and the yaw rate the command carries is derived from the (decayed) +// steering state as v * sin(delta) / L. steeringState() is seeded non-zero so +// the decay (bounded by the model's u[1] steering-rate limit, not the du[1] +// steering-acceleration bound a twist-space ramp would have used) is what +// supplies the angle that mapping reads. TEST_F(ProxMpcControllerTest, ComputeSolverFailureRampsThenEscalates) { auto c = makeConfigured( { + rclcpp::Parameter("FollowPath.model_plugin", std::string(kBicyclePlugin)), rclcpp::Parameter("FollowPath.max_int_iter_qp", 1), rclcpp::Parameter("FollowPath.max_ext_iter_qp", 1), rclcpp::Parameter("FollowPath.max_iter_sqp", 1), @@ -876,12 +1359,16 @@ TEST_F(ProxMpcControllerTest, ComputeSolverFailureRampsThenEscalates) }); c->activate(); c->setPlan(makeStraightPlan(31, 0.2)); + const double delta0 = 0.2; + c->steeringState() = delta0; // non-zero steering belief for the decay to move - // The brake ramps from the server-measured velocity, so supply a non-zero - // measured twist (angular negative to exercise the opposite-sign brake step). + // The brake ramps from the server-measured velocity, carried into the model's + // own control units, so the measurement is the base_link twist this model + // emits for a front-wheel speed of 0.30 at the current steering angle. + const double v_front = 0.30; geometry_msgs::msg::Twist measured; - measured.linear.x = 0.30; - measured.angular.z = -0.30; + measured.linear.x = v_front * std::cos(delta0); + measured.angular.z = v_front * std::sin(delta0) / kBicycleWheelbase; const auto cmd = c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), measured, nullptr); @@ -890,9 +1377,16 @@ TEST_F(ProxMpcControllerTest, ComputeSolverFailureRampsThenEscalates) // if the QP ever converged in a single iteration. ASSERT_NE(c->mpc()->qp_info.status, proxsuite::proxqp::QPSolverOutput::PROXQP_SOLVED); - // v_cmd = max(0, v_meas - a_dec * dt); a_dec = 0.5, dt = 0.1 -> step 0.05. - EXPECT_NEAR(cmd.twist.linear.x, 0.30 - kModelDecel * 0.1, 1e-6); - EXPECT_NEAR(cmd.twist.angular.z, -0.30 + kModelDecel * 0.1, 1e-6); + // The ramped control is v = max(0, v_meas - a_dec * dt); a_dec = 0.5, dt = 0.1 + // -> step 0.05. delta decays toward zero at the u[1] rate bound: + // 0.2 - 1.0 * 0.1 = 0.1 rad. The front-axle model's twist is the base_link one, + // so linear.x is v cos(delta) rather than the front-wheel speed v, and + // angular.z is v sin(delta) / L rather than a ramp of the measured yaw rate. + const double expected_delta = delta0 - kSteerRateBound * 0.1; + const double expected_v = v_front - kModelDecel * 0.1; + EXPECT_NEAR(cmd.twist.linear.x, expected_v * std::cos(expected_delta), 1e-9); + EXPECT_NEAR( + cmd.twist.angular.z, expected_v * std::sin(expected_delta) / kBicycleWheelbase, 1e-9); EXPECT_EQ(c->failureCount(), 1); // Second consecutive failure exceeds max_solver_failures = 1 -> escalate. @@ -950,10 +1444,26 @@ TEST_F(ProxMpcControllerTest, ComputeFootprintVetoBrakesWithoutFailure) EXPECT_EQ(c->failureCount(), 0); // veto is not a solver failure } -// An empty footprint skips the polygon veto (size < 3) and still commands. +// A footprint the polygon veto cannot use (fewer than 3 points) is skipped, and +// the command still passes through. +// +// The degenerate footprint is two points rather than none: nav2 1.3.13 rejects an +// empty footprint outright ("a footprint must contain at least one point") and +// keeps the previous one, so setting none leaves the fixture's real footprint in +// place, the veto runs against the lethal cost below, and the command is braked - +// which is what this test would then be asserting the opposite of. Two points +// clears nav2's own guard while still failing the controller's `size() >= 3`, so +// the branch under test is reached on 1.3.12 and 1.3.13 alike. TEST_F(ProxMpcControllerTest, ComputeSkipsVetoWithoutFootprint) { - costmap_ros_->setRobotFootprint(std::vector{}); + geometry_msgs::msg::Point a; + geometry_msgs::msg::Point b; + b.x = 0.1; + costmap_ros_->setRobotFootprint(std::vector{a, b}); + // The premise, asserted rather than assumed: a future nav2 that also refuses a + // two-point footprint must fail here, saying why, instead of as a braked command. + ASSERT_LT(costmap_ros_->getRobotFootprint().size(), 3u); + auto c = makeConfigured({rclcpp::Parameter("FollowPath.max_obstacles", 0)}); c->activate(); c->setPlan(makeStraightPlan(31, 0.2)); @@ -990,6 +1500,100 @@ TEST_F(ProxMpcControllerTest, PersistentFootprintVetoEscalates) nav2_core::NoValidControl); } +// The veto threshold matches upstream Nav2 (RPP collision_checker.cpp:150-154, +// MPPI cost_critic.hpp:71-78): INSCRIBED_INFLATED_OBSTACLE alone no longer +// vetoes, because a real polygon check has already been performed and an +// inflated cell is not by itself a collision; only LETHAL_OBSTACLE does. +TEST_F(ProxMpcControllerTest, FootprintVetoMatchesUpstreamLethalThreshold) +{ + { + auto c = makeConfigured({rclcpp::Parameter("FollowPath.max_obstacles", 0)}); + c->activate(); + c->setPlan(makeStraightPlan(31, 0.2)); + fillCost(-0.6, -0.6, 0.6, 0.6, nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE); + const auto cmd = c->computeVelocityCommands( + makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + EXPECT_GT(cmd.twist.linear.x, 0.0); // no veto: command passes through + } + { + auto c = makeConfigured({rclcpp::Parameter("FollowPath.max_obstacles", 0)}); + c->activate(); + c->setPlan(makeStraightPlan(31, 0.2)); + fillCost(-0.6, -0.6, 0.6, 0.6, nav2_costmap_2d::LETHAL_OBSTACLE); + const auto cmd = c->computeVelocityCommands( + makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + EXPECT_NEAR(cmd.twist.linear.x, 0.0, kTol); // vetoed: brakes + } +} + +// NO_INFORMATION does not veto when the layered costmap reports +// isTrackingUnknown() (RPP collision_checker.cpp:150-154, MPPI +// cost_critic.hpp:71-78): the robot is allowed to plan into and through +// genuinely unmeasured space rather than braking at its boundary. +// LayeredCostmap::isTrackingUnknown() reads the costmap's stored default value +// directly, so setting it is enough to flip the policy; the fixture otherwise +// starts every cell at FREE_SPACE (SetUp()). +TEST_F(ProxMpcControllerTest, FootprintVetoIgnoresUnknownWhenCostmapTracksUnknown) +{ + auto c = makeConfigured({rclcpp::Parameter("FollowPath.max_obstacles", 0)}); + c->activate(); + c->setPlan(makeStraightPlan(31, 0.2)); + costmap_ros_->getCostmap()->setDefaultValue(nav2_costmap_2d::NO_INFORMATION); + fillCost(-0.6, -0.6, 0.6, 0.6, nav2_costmap_2d::NO_INFORMATION); + + const auto cmd = c->computeVelocityCommands( + makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + EXPECT_GT(cmd.twist.linear.x, 0.0); // no veto: command passes through +} + +// Nav2's own doc comment for footprintCostAtPose describes an inherited +// upstream masking property: it takes the maximum cost under the footprint's +// perimeter, and since NO_INFORMATION (255) is numerically larger than +// LETHAL_OBSTACLE (254), a footprint spanning both would read NO_INFORMATION +// and be reported clear. Measured directly against this nav2_costmap_2d +// release, that does not reproduce: lineCost does not let an unmeasured cell +// out-rank a lethal one on the same edge, in either traversal order, so a +// footprint spanning both is reported at LETHAL_OBSTACLE and still vetoes. +// This test pins the actually observed behaviour rather than the +// documented-but-unverified one, so a future nav2 release that reintroduces +// the masking shows up as a failing test here instead of a silent divergence. +TEST_F(ProxMpcControllerTest, FootprintVetoStillFiresWhenLethalAdjoinsUnknown) +{ + auto c = makeConfigured({rclcpp::Parameter("FollowPath.max_obstacles", 0)}); + c->activate(); + c->setPlan(makeStraightPlan(31, 0.2)); + costmap_ros_->getCostmap()->setDefaultValue(nav2_costmap_2d::NO_INFORMATION); + // Bottom half of the one-step-ahead footprint lethal, top half unknown: both + // values are present under the perimeter regardless of the exact predicted + // pose within it. + fillCost(-0.6, -0.6, 0.6, 0.6, nav2_costmap_2d::LETHAL_OBSTACLE); + fillCost(-0.6, 0.0, 0.6, 0.6, nav2_costmap_2d::NO_INFORMATION); + + const auto cmd = c->computeVelocityCommands( + makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + EXPECT_NEAR(cmd.twist.linear.x, 0.0, kTol); // vetoed: the lethal half still fires +} + +// The threshold change (INSCRIBED_INFLATED_OBSTACLE -> LETHAL_OBSTACLE) still +// takes effect next to unknown space: since the checker resolves a mixed +// perimeter to the highest non-unknown cost present (the previous test's +// finding), an INSCRIBED_INFLATED_OBSTACLE cell mixed with NO_INFORMATION +// resolves to 253, which the old >= 253 threshold still vetoed but the new +// >= 254 one does not, independent of the masking property itself. +TEST_F(ProxMpcControllerTest, FootprintVetoThresholdChangeAppliesNextToUnknown) +{ + auto c = makeConfigured({rclcpp::Parameter("FollowPath.max_obstacles", 0)}); + c->activate(); + c->setPlan(makeStraightPlan(31, 0.2)); + costmap_ros_->getCostmap()->setDefaultValue(nav2_costmap_2d::NO_INFORMATION); + fillCost(-0.6, -0.6, 0.6, 0.6, nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE); + fillCost(-0.6, 0.0, 0.6, 0.6, nav2_costmap_2d::NO_INFORMATION); + + const auto cmd = c->computeVelocityCommands( + makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + EXPECT_GT(cmd.twist.linear.x, 0.0); // no veto: 253 no longer meets the threshold +} + // --- setSpeedLimit() ------------------------------------------------------- // An absolute speed limit applies the value as the linear bound. @@ -1054,6 +1658,82 @@ TEST_F(ProxMpcControllerTest, SpeedLimitAppliesOnNextControlCycle) EXPECT_NEAR(c->model()->getIneq("u").at(0)[2], 0.5 * kModelVMax, kTol); } +// A Nav2 speed limit must never broaden the feasible set: it narrows the +// model's own bounds, it does not replace them. AsymmetricBounds declares an +// asymmetric reverse limit (v_min = -0.3, tighter than v_max = 2.0), which +// neither bundled model can express, so this is the only fixture that can show +// the defect: the old code applied every limit as model_->updateIneq("u", 0, +// -v_lim, v_lim), replacing v_min outright. A non-negative v_min is not +// reachable through the controller's own parameters (v_min is always < 0 for +// a model that can stop), so an asymmetric negative v_min is the strongest +// reachable form, together with the NO_SPEED_LIMIT restore path. +TEST_F(ProxMpcControllerTest, SpeedLimitPreservesAsymmetricLowerBound) +{ + // allow_reversing is opted into so the model's declared reverse bound survives + // configure: with it false the box is narrowed to [0, v_max] up front, and + // there would be no negative lower bound left for the speed limit to preserve. + // model_params.v_min names the bound explicitly, which is what opts out of the + // conservative reverse cap applied when reversing is enabled without one. + auto c = makeRunning( + {rclcpp::Parameter( + "FollowPath.model_plugin", std::string("prox_mpc_test_models/AsymmetricBounds")), + rclcpp::Parameter("FollowPath.allow_reversing", true), + rclcpp::Parameter("FollowPath.model_params.v_min", -0.3)}); + + c->setSpeedLimit(1.0, false); + runCycle(c); + EXPECT_NEAR(c->maxLinearVel(), 1.0, kTol); + EXPECT_NEAR(c->model()->getIneq("u").at(0)[1], -0.3, kTol); // lower bound untouched + EXPECT_NEAR(c->model()->getIneq("u").at(0)[2], 1.0, kTol); // upper bound narrowed + + // NO_SPEED_LIMIT restores the model's own upper bound; the lower bound must + // stay at the model's -0.3, not widen to -v_max (-2.0). + c->setSpeedLimit(0.0, false); + runCycle(c); + EXPECT_NEAR(c->maxLinearVel(), 2.0, kTol); + EXPECT_NEAR(c->model()->getIneq("u").at(0)[1], -0.3, kTol); + EXPECT_NEAR(c->model()->getIneq("u").at(0)[2], 2.0, kTol); +} + +// allow_reversing gates the control box, not only the reference. With it false +// the solver must not be able to plan reverse travel at all, so the model's +// declared negative lower bound is narrowed to zero at configure; with it true +// the model's own bound is left alone. AsymmetricBounds is used because its +// -0.3 lower bound is distinguishable from both 0 and -v_max. +TEST_F(ProxMpcControllerTest, ReversingDisabledNarrowsTheControlBox) +{ + auto forward = makeRunning( + {rclcpp::Parameter( + "FollowPath.model_plugin", std::string("prox_mpc_test_models/AsymmetricBounds")), + rclcpp::Parameter("FollowPath.allow_reversing", false)}); + EXPECT_NEAR(forward->model()->getIneq("u").at(0)[1], 0.0, kTol); + EXPECT_NEAR(forward->model()->getIneq("u").at(0)[2], 2.0, kTol); + + auto reversing = makeRunning( + {rclcpp::Parameter( + "FollowPath.model_plugin", std::string("prox_mpc_test_models/AsymmetricBounds")), + rclcpp::Parameter("FollowPath.allow_reversing", true), + rclcpp::Parameter("FollowPath.model_params.v_min", -0.3)}); + EXPECT_NEAR(reversing->model()->getIneq("u").at(0)[1], -0.3, kTol); + EXPECT_NEAR(reversing->model()->getIneq("u").at(0)[2], 2.0, kTol); +} + +// Nothing guards the area behind the robot: the keep-out fill skips +// NO_INFORMATION cells and the footprint veto treats them as clear. Enabling +// reversing without naming a reverse bound therefore must not inherit the +// model's own lower bound, which is a modelling limit rather than a safety +// choice - for AsymmetricBounds that is -0.3, well past the conservative cap. +// Naming model_params.v_min is the documented way to opt out, covered above. +TEST_F(ProxMpcControllerTest, ReversingWithoutABoundIsCappedSlow) +{ + auto c = makeRunning( + {rclcpp::Parameter( + "FollowPath.model_plugin", std::string("prox_mpc_test_models/AsymmetricBounds")), + rclcpp::Parameter("FollowPath.allow_reversing", true)}); + EXPECT_NEAR(c->model()->getIneq("u").at(0)[1], -0.15, kTol); + EXPECT_NEAR(c->model()->getIneq("u").at(0)[2], 2.0, kTol); +} + // --- cancel() / reset() ---------------------------------------------------- // cancel() reports done immediately when the robot is already stopped. @@ -1114,13 +1794,20 @@ TEST_F(ProxMpcControllerTest, ResetClearsRuntimeState) // reduceCostmap clusters nearby lethal cells into at most K representatives per // node, skips unknown cells and out-of-grid nodes, and leaves empty slots at the // far sentinel. +// +// The scan is centered on the MPC's own nominal trajectory (mpc()->getX()); no +// plan reference is passed, because the fill does not use one. +// Node j's window is centered on nominal row min(j + 2, Np) (the fill runs +// before solve() shifts the trajectory, so this reads one node ahead to +// compensate for that staleness). Np = 3 so nodes 0 and 1 read distinct rows +// (2 and 3); node 2 clamps to the same row as node 1. TEST_F(ProxMpcControllerTest, ReduceCostmapClustersAndSentinels) { - // Np = 2, K = 2; a large robot radius forces the scan window to clamp. + // Np = 3, K = 2; a large robot radius forces the scan window to clamp. auto c = makeConfigured( { - rclcpp::Parameter("FollowPath.np", 2), - rclcpp::Parameter("FollowPath.nc", 2), + rclcpp::Parameter("FollowPath.np", 3), + rclcpp::Parameter("FollowPath.nc", 3), rclcpp::Parameter("FollowPath.max_obstacles", 2), rclcpp::Parameter("FollowPath.robot_radius", 3.0), rclcpp::Parameter("FollowPath.safety_margin", 0.1), @@ -1134,16 +1821,17 @@ TEST_F(ProxMpcControllerTest, ReduceCostmapClustersAndSentinels) fillCost(1.0, 2.0, 1.3, 2.3, nav2_costmap_2d::LETHAL_OBSTACLE); // cluster B fillCost(0.8, 0.8, 0.8, 0.8, nav2_costmap_2d::NO_INFORMATION); // ignored - const std::size_t np = 2; + const std::size_t np = 3; const std::size_t k = 2; - MatrixXd reference = MatrixXd::Zero(static_cast(np + 1), 4); - reference(1, 0) = 1.15; // node 0: inside the grid, near both clusters - reference(1, 1) = 1.0; - reference(2, 0) = 100.0; // node 1: outside the grid -> worldToMap fails - reference(2, 1) = 100.0; + MatrixXd nominal = MatrixXd::Zero(static_cast(np + 1), c->nDim()); + nominal(2, 0) = 1.15; // row read by node 0: inside the grid, near both clusters + nominal(2, 1) = 1.0; + nominal(3, 0) = 100.0; // row read by nodes 1 and 2: outside the grid + nominal(3, 1) = 100.0; + c->mpc()->setX(nominal); MatrixXd obs(static_cast(np * k), 3); - c->reduceCostmap(reference, obs); + c->reduceCostmap(obs); // Node 0: two distinct representatives, each carrying d_safe = radius + margin. EXPECT_LT(obs(0, 0), prox_mpc::MPC::kObsFarSentinel); @@ -1153,28 +1841,189 @@ TEST_F(ProxMpcControllerTest, ReduceCostmapClustersAndSentinels) const double sep = std::hypot(obs(0, 0) - obs(1, 0), obs(0, 1) - obs(1, 1)); EXPECT_GE(sep, 0.3); // representatives at least a cluster radius apart - // Node 1: out of grid, both slots stay at the far sentinel. + // Nodes 1 and 2: out of grid (nominal row 3), every slot stays at the sentinel. EXPECT_NEAR(obs(2, 0), prox_mpc::MPC::kObsFarSentinel, kTol); EXPECT_NEAR(obs(3, 0), prox_mpc::MPC::kObsFarSentinel, kTol); + EXPECT_NEAR(obs(4, 0), prox_mpc::MPC::kObsFarSentinel, kTol); + EXPECT_NEAR(obs(5, 0), prox_mpc::MPC::kObsFarSentinel, kTol); } -// --- fillObstacles(): predictive + hybrid fill (white-box) ----------------- - -// The predictive fill propagates a tracked obstacle by position + velocity*dt_k -// per node and binds it to one slot across the whole horizon (identity). -TEST_F(ProxMpcControllerTest, PredictiveFillPropagatesObstacleAndKeepsIdentity) +// A static obstacle near the MPC's nominal predicted state, but well outside a +// reference-centered scan window, is picked up: 1.0.0 centered the search on +// reference(node+1), so a lethal cell beyond d_safe + +// obstacle_cluster_radius of the plan reference position never entered the +// window at all, no matter how close it was to where the solver actually +// predicted the robot would be. +TEST_F(ProxMpcControllerTest, ReduceCostmapCentersOnNominalNotReference) { auto c = makeConfigured( { - rclcpp::Parameter("FollowPath.np", 5), - rclcpp::Parameter("FollowPath.nc", 5), + rclcpp::Parameter("FollowPath.np", 1), + rclcpp::Parameter("FollowPath.nc", 1), rclcpp::Parameter("FollowPath.max_obstacles", 1), - rclcpp::Parameter("FollowPath.predict_obstacles", true), - rclcpp::Parameter("FollowPath.dynamic_speed_threshold", 0.05), - rclcpp::Parameter("FollowPath.robot_radius", 0.5), + rclcpp::Parameter("FollowPath.robot_radius", 0.3), rclcpp::Parameter("FollowPath.safety_margin", 0.1), + rclcpp::Parameter("FollowPath.obstacle_cluster_radius", 0.2), }); - const std::size_t np = 5; + // search_radius = d_safe + obstacle_cluster_radius = 0.4 + 0.2 = 0.6 m. + fillCost(1.9, -0.1, 2.1, 0.1, nav2_costmap_2d::LETHAL_OBSTACLE); // near (2, 0) + + MatrixXd nominal = MatrixXd::Zero(2, c->nDim()); + nominal(1, 0) = 2.0; // node 0 reads row min(0 + 2, Np = 1) = 1: at the obstacle + c->mpc()->setX(nominal); + + // reference stays at the origin: more than 0.6 m from the obstacle, so a + // reference-centered window would never see it (2.0 m - 0.6 m margin). + MatrixXd obs(1, 3); + c->reduceCostmap(obs); + + EXPECT_LT(obs(0, 0), prox_mpc::MPC::kObsFarSentinel); + EXPECT_NEAR(obs(0, 0), 2.0, 0.15); +} + +// The obstacle-slot ranking keys on the earliest node an object is first seen +// at, ties broken by closest approach -- not on closest approach anywhere in +// the horizon. A long np is needed to separate the two rules: at the shipped +// np and scan radius, every candidate is first seen at the same node, so the +// tie-break alone reproduces the old (closest-approach) order and no fixture +// built at those defaults can tell the two rules apart. Object A is seen only +// at the early node 2, offset ~0.25 m from that node's scan center (moderate +// approach). Object B is seen only at the late node 15, offset ~0 m (the +// closer approach overall). Ranking on closest-approach-anywhere would give +// the single slot to B; ranking on earliest-encounter gives it to A. +TEST_F(ProxMpcControllerTest, ObstacleSlotRankingPrefersEarliestEncounter) +{ + auto c = makeConfigured( + { + rclcpp::Parameter("FollowPath.np", 20), + rclcpp::Parameter("FollowPath.nc", 20), + rclcpp::Parameter("FollowPath.max_obstacles", 1), + rclcpp::Parameter("FollowPath.robot_radius", 0.3), + rclcpp::Parameter("FollowPath.safety_margin", 0.1), + rclcpp::Parameter("FollowPath.obstacle_cluster_radius", 0.3), + }); + // search_radius = d_safe + obstacle_cluster_radius = 0.4 + 0.3 = 0.7 m. Both + // clusters stay well inside the 10 m x 10 m grid (+/-5 m): a cluster placed + // at the grid edge would silently fail to paint (worldToMap rejects it). + fillCost(2.25, -0.05, 2.35, 0.05, nav2_costmap_2d::LETHAL_OBSTACLE); // A: near (2.3, 0) + fillCost(3.5, -0.05, 3.55, 0.05, nav2_costmap_2d::LETHAL_OBSTACLE); // B: near (3.5, 0) + + const std::size_t np = 20; + MatrixXd nominal = MatrixXd::Zero(static_cast(np + 1), c->nDim()); + // node 2 reads row min(2 + 2, np) = 4: centered on A, ~0.25 m away. + nominal(4, 0) = 2.0; + // node 15 reads row min(15 + 2, np) = 17: centered on B, ~0 m away (closer). + nominal(17, 0) = 3.5; + // Every other node's row is left at (0, 0): more than 0.7 m from both A and + // B, so no other node picks up either one. + c->mpc()->setX(nominal); + + MatrixXd obs(static_cast(np), 3); + c->reduceCostmap(obs); + + EXPECT_LT(obs(2, 0), prox_mpc::MPC::kObsFarSentinel); // node 2: A wins the slot + EXPECT_NEAR(obs(2, 0), 2.3, 0.1); + EXPECT_NEAR(obs(15, 0), prox_mpc::MPC::kObsFarSentinel, kTol); // node 15: B did not +} + +// The footprint the veto uses is read fresh each cycle rather than cached at +// configure() time -- it is the one "in force at the start of the cycle", the +// hoisted-out-of-the-lock read node 28 chose, and the same per-cycle read RPP +// and MPPI both perform to keep a runtime footprint update taking effect. +TEST_F(ProxMpcControllerTest, FootprintVetoUsesFootprintInForceAtCycleStart) +{ + auto c = makeConfigured({rclcpp::Parameter("FollowPath.max_obstacles", 0)}); + c->activate(); + c->setPlan(makeStraightPlan(31, 0.2)); + + // A lethal block straddling the default footprint's right edge (half-extent + // 0.5 m, padded to ~0.51 m): footprintCostAtPose checks the polygon + // perimeter only, not its interior, so the block must cross an edge to be + // seen at all. The much smaller footprint used below does not reach it. + fillCost(0.4, -0.05, 0.6, 0.05, nav2_costmap_2d::LETHAL_OBSTACLE); + + const auto cmd_default = c->computeVelocityCommands( + makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + EXPECT_NEAR(cmd_default.twist.linear.x, 0.0, kTol); // default footprint reaches it: vetoed + + // Shrink the footprint before the next cycle; the veto must use this new + // footprint, not the one configure() saw. + costmap_ros_->setRobotFootprint(makeSquareFootprint(0.05)); + const auto cmd_small = c->computeVelocityCommands( + makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + EXPECT_GT(cmd_small.twist.linear.x, 0.0); // the shrunk footprint no longer reaches it +} + +// The costmap-reduction path finds the same candidate obstacle set it did +// before the critical section was narrowed to the cell reads: the grid lock +// now closes and reopens once per node instead of once per fill, so this +// checks that the per-node scans it protects still each find their own +// cluster and nothing else. This is a regression guard on the invariant node +// 29 chose (the candidate set, not fill atomicity against a concurrent +// costmap write) rather than evidence the lock-scope change altered +// single-threaded behavior, which it does not: the same instructions run +// either way, just under a narrower held lock. +TEST_F(ProxMpcControllerTest, CostmapReductionCandidateSetUnaffectedByNarrowedLock) +{ + auto c = makeConfigured( + { + rclcpp::Parameter("FollowPath.np", 4), + rclcpp::Parameter("FollowPath.nc", 4), + rclcpp::Parameter("FollowPath.max_obstacles", 2), // >= 2 slots: no cross-node competition + rclcpp::Parameter("FollowPath.robot_radius", 0.3), + rclcpp::Parameter("FollowPath.safety_margin", 0.1), + rclcpp::Parameter("FollowPath.obstacle_cluster_radius", 0.2), + }); + // search_radius = 0.4 + 0.2 = 0.6 m; each cluster sits inside exactly one + // node's window and outside every other node's. + fillCost(1.9, -0.05, 2.0, 0.05, nav2_costmap_2d::LETHAL_OBSTACLE); // near (2, 0): node 0 + fillCost(3.9, -0.05, 4.0, 0.05, nav2_costmap_2d::LETHAL_OBSTACLE); // near (4, 0): node 1 + + const std::size_t np = 4; + const std::size_t k = 2; + MatrixXd nominal = MatrixXd::Zero(static_cast(np + 1), c->nDim()); + nominal(2, 0) = 2.0; // node 0 reads row min(0 + 2, np) = 2 + nominal(3, 0) = 4.0; // node 1 reads row min(1 + 2, np) = 3 + nominal(4, 0) = -4.0; // nodes 2 and 3 read row min(node + 2, np) = 4: no obstacle there + c->mpc()->setX(nominal); + + MatrixXd obs(static_cast(np * k), 3); + c->reduceCostmap(obs); + + // The near-(2,0) object is seen only at node 0 and ranks first (earliest + // first_node), winning slot 0; row = node * k + slot = 0 * 2 + 0 = 0. + EXPECT_LT(obs(0, 0), prox_mpc::MPC::kObsFarSentinel); + EXPECT_NEAR(obs(0, 0), 2.0, 0.1); + // The near-(4,0) object is seen only at node 1 and ranks second, winning + // slot 1; row = 1 * 2 + 1 = 3. + EXPECT_LT(obs(3, 0), prox_mpc::MPC::kObsFarSentinel); + EXPECT_NEAR(obs(3, 0), 4.0, 0.1); + // Node 0's slot 1 and node 1's slot 0 were never assigned either object. + EXPECT_NEAR(obs(1, 0), prox_mpc::MPC::kObsFarSentinel, kTol); + EXPECT_NEAR(obs(2, 0), prox_mpc::MPC::kObsFarSentinel, kTol); + // Nodes 2 and 3 (both centered far from either cluster) stay empty. + for (Eigen::Index r = 4; r < obs.rows(); ++r) { + EXPECT_NEAR(obs(r, 0), prox_mpc::MPC::kObsFarSentinel, kTol) << "row " << r; + } +} + +// --- fillObstacles(): predictive + hybrid fill (white-box) ----------------- + +// The predictive fill propagates a tracked obstacle by position + velocity*dt_k +// per node and binds it to one slot across the whole horizon (identity). +TEST_F(ProxMpcControllerTest, PredictiveFillPropagatesObstacleAndKeepsIdentity) +{ + auto c = makeConfigured( + { + rclcpp::Parameter("FollowPath.np", 5), + rclcpp::Parameter("FollowPath.nc", 5), + rclcpp::Parameter("FollowPath.max_obstacles", 1), + rclcpp::Parameter("FollowPath.predict_obstacles", true), + rclcpp::Parameter("FollowPath.dynamic_speed_threshold", 0.05), + rclcpp::Parameter("FollowPath.robot_radius", 0.5), + rclcpp::Parameter("FollowPath.safety_margin", 0.1), + }); + const std::size_t np = 5; const std::size_t k = 1; const double dt = 0.1; const double vx = 1.0; @@ -1202,8 +2051,302 @@ TEST_F(ProxMpcControllerTest, PredictiveFillPropagatesObstacleAndKeepsIdentity) } } +// The forward shadow biases the keep-out along the track's own heading, so the +// space a mover is about to occupy costs more than the space it is vacating. The +// centre moves forward by shadow = prediction_forward_shadow_s * speed and the +// radius grows by the same amount, which keeps the obstacle's own position +// covered while extending the disc ahead of it. +TEST_F(ProxMpcControllerTest, ForwardShadowBiasesTheKeepOutAheadOfTheTrack) +{ + auto c = makeConfigured( + { + rclcpp::Parameter("FollowPath.np", 5), + rclcpp::Parameter("FollowPath.nc", 5), + rclcpp::Parameter("FollowPath.max_obstacles", 1), + rclcpp::Parameter("FollowPath.predict_obstacles", true), + rclcpp::Parameter("FollowPath.dynamic_speed_threshold", 0.05), + rclcpp::Parameter("FollowPath.robot_radius", 0.5), + rclcpp::Parameter("FollowPath.safety_margin", 0.1), + rclcpp::Parameter("FollowPath.prediction_forward_shadow_s", 0.4), + }); + const std::size_t np = 5; + const std::size_t k = 1; + const double dt = 0.1; + const double vx = 1.0; + const double base_d_safe = 0.5 + 0.2 + 0.1; + const double shadow = 0.4 * vx; // prediction_forward_shadow_s * speed + const rclcpp::Time now(1000, 0, RCL_ROS_TIME); + + c->injectObstacles(makeObstacleMsg(now, 2.0, 0.0, vx, 0.0, 0.2)); + + MatrixXd reference = MatrixXd::Zero(static_cast(np + 1), c->nDim()); + for (std::size_t i = 0; i <= np; ++i) { + reference(static_cast(i), 0) = static_cast(i) * 0.2; + } + MatrixXd obs(static_cast(np * k), 3); + c->fillObstacles(reference, obs, now); + + for (std::size_t node = 0; node < np; ++node) { + const double dt_k = static_cast(node + 1) * dt; + const Eigen::Index row = static_cast(node * k); + const double truth_x = 2.0 + vx * dt_k; // where the obstacle actually is + + // Centre biased one shadow ahead, along +x, and the radius grown to match. + EXPECT_NEAR(obs(row, 0), truth_x + shadow, 1e-9); + EXPECT_NEAR(obs(row, 1), 0.0, 1e-9); + EXPECT_NEAR(obs(row, 2), base_d_safe + shadow, 1e-9); + + // The obstacle's own position stays inside its keep-out: a bare shift would + // open a hole over the object itself once the shadow passed d_safe. + EXPECT_LT(std::abs(obs(row, 0) - truth_x), obs(row, 2)); + + // And the disc is asymmetric about the obstacle: further ahead than behind. + const double reach_ahead = obs(row, 0) + obs(row, 2) - truth_x; + const double reach_behind = truth_x - (obs(row, 0) - obs(row, 2)); + EXPECT_GT(reach_ahead, reach_behind); + EXPECT_NEAR(reach_ahead - reach_behind, 2.0 * shadow, 1e-9); + // Behind the mover the keep-out is never tighter than the unbiased one. + EXPECT_NEAR(reach_behind, base_d_safe, 1e-9); + } +} + +// A track with no measurable heading casts no shadow: normalising its velocity +// would place the disc in an arbitrary direction. Reachable because +// dynamic_speed_threshold may itself be set to zero. +TEST_F(ProxMpcControllerTest, ForwardShadowIgnoresATrackWithNoHeading) +{ + auto c = makeConfigured( + { + rclcpp::Parameter("FollowPath.np", 2), + rclcpp::Parameter("FollowPath.nc", 2), + rclcpp::Parameter("FollowPath.max_obstacles", 1), + rclcpp::Parameter("FollowPath.predict_obstacles", true), + rclcpp::Parameter("FollowPath.dynamic_speed_threshold", 0.0), + rclcpp::Parameter("FollowPath.robot_radius", 0.5), + rclcpp::Parameter("FollowPath.safety_margin", 0.1), + rclcpp::Parameter("FollowPath.prediction_forward_shadow_s", 0.4), + }); + const rclcpp::Time now(1000, 0, RCL_ROS_TIME); + c->injectObstacles(makeObstacleMsg(now, 2.0, 0.0, 0.0, 0.0, 0.2)); + + MatrixXd reference = MatrixXd::Zero(3, c->nDim()); + MatrixXd obs(2, 3); + c->fillObstacles(reference, obs, now); + + for (Eigen::Index row = 0; row < 2; ++row) { + EXPECT_TRUE(std::isfinite(obs(row, 0))); + EXPECT_TRUE(std::isfinite(obs(row, 1))); + EXPECT_NEAR(obs(row, 0), 2.0, 1e-9); // unmoved + EXPECT_NEAR(obs(row, 1), 0.0, 1e-9); + EXPECT_NEAR(obs(row, 2), 0.5 + 0.2 + 0.1, 1e-9); // unbiased radius + } +} + +// Obstacle-aware cruise. A mover whose predicted path crosses where the robot is +// heading eases the cruise, so the robot waits for it rather than racing it. The +// yield reads the predictions the previous cycle's fill retained, so each cycle +// is primed with one fill before it runs. +namespace +{ +// Speed reference at the first control node, one entry per cycle, with a mover +// at (1.0, -1.0) heading +y at 1 m/s - on the plan's line at t = 1 s, which is +// where a 1 m/s reference along +x also is. `with_mover` false leaves the +// retained predictions empty. + std::vector cruisePerCycle( + const std::function( + const std::vector &)> & make, double band, bool with_mover, int cycles = 1) + { + auto c = make( + { + rclcpp::Parameter("FollowPath.max_obstacles", 1), + rclcpp::Parameter("FollowPath.predict_obstacles", true), + rclcpp::Parameter("FollowPath.dynamic_speed_threshold", 0.05), + rclcpp::Parameter("FollowPath.robot_radius", 0.3), + rclcpp::Parameter("FollowPath.safety_margin", 0.1), + rclcpp::Parameter("FollowPath.obstacle_yield_band_m", band), + }); + c->activate(); + c->setPlan(makeStraightPlan(61, 0.2)); + const rclcpp::Time now(1000, 0, RCL_ROS_TIME); + const std::size_t np = c->mpc()->getNp(); + MatrixXd reference = MatrixXd::Zero(static_cast(np + 1), c->nDim()); + for (std::size_t i = 0; i <= np; ++i) { + reference(static_cast(i), 0) = 0.1 * static_cast(i); + } + std::vector v; + for (int i = 0; i < cycles; ++i) { + if (with_mover) { + c->injectObstacles(makeObstacleMsg(now, 1.0, -1.0, 0.0, 1.0, 0.2)); + MatrixXd obs(static_cast(np), 3); + c->fillObstacles(reference, obs, now); // prime the retained predictions + } + c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + v.push_back(c->mpc()->getGoalU()(0, 0)); + } + return v; + } +} // namespace + +TEST_F(ProxMpcControllerTest, ObstacleYieldEasesCruiseForACrossingMover) +{ + auto make = [this](const std::vector & o) {return makeConfigured(o);}; + const double blind = cruisePerCycle(make, 0.0, true).front(); + const double yielding = cruisePerCycle(make, 0.5, true).front(); + ASSERT_GT(blind, + 0.0) << "the obstacle-blind cruise must be moving for the comparison to mean anything"; + EXPECT_LT(yielding, blind); +} + +// With nothing predicted to cross where the robot is heading, the cruise is +// exactly the obstacle-blind one: the feature is inert until a mover is in the way. +TEST_F(ProxMpcControllerTest, ObstacleYieldLeavesCruiseAloneWithNoMover) +{ + auto make = [this](const std::vector & o) {return makeConfigured(o);}; + EXPECT_NEAR( + cruisePerCycle(make, 0.5, false).front(), cruisePerCycle(make, 0.0, false).front(), 1e-12); +} + +// The failure the yield has to avoid is snapping back to full cruise while the +// mover is still there. That happens if a reduction is allowed to clear the +// breach that caused it - a slower trajectory is a shorter one, which can stop +// reaching the mover - and the release is instant. With the plan judged at the +// intended cruise and the release rate-limited, a persisting mover keeps the +// cruise below the obstacle-blind one on every cycle. +TEST_F(ProxMpcControllerTest, ObstacleYieldHoldsWhileTheMoverPersists) +{ + auto make = [this](const std::vector & o) {return makeConfigured(o);}; + const double blind = cruisePerCycle(make, 0.0, true).front(); + for (const double v : cruisePerCycle(make, 0.5, true, 6)) { + EXPECT_LT(v, blind); + } +} + +// The solver does not follow the plan exactly, so a check on the plan alone can +// watch a path the robot is not driving. Here the plan runs clear along +x while +// the trajectory the solver planned last cycle swings up through a mover sitting +// 1 m off the plan: the yield has to see it on the trajectory. +TEST_F(ProxMpcControllerTest, ObstacleYieldSeesAMoverOnThePlannedTrajectoryOffThePlan) +{ + auto run = [this](double band) { + auto c = makeConfigured( + { + rclcpp::Parameter("FollowPath.max_obstacles", 1), + rclcpp::Parameter("FollowPath.predict_obstacles", true), + rclcpp::Parameter("FollowPath.dynamic_speed_threshold", 0.05), + rclcpp::Parameter("FollowPath.robot_radius", 0.3), + rclcpp::Parameter("FollowPath.safety_margin", 0.1), + rclcpp::Parameter("FollowPath.obstacle_yield_band_m", band), + }); + c->activate(); + c->setPlan(makeStraightPlan(61, 0.2)); + const rclcpp::Time now(1000, 0, RCL_ROS_TIME); + const std::size_t np = c->mpc()->getNp(); + // A slow mover 1 m off the plan: clear of the plan by more than d_safe. + c->injectObstacles(makeObstacleMsg(now, 1.0, 1.0, 0.3, 0.0, 0.2)); + MatrixXd reference = MatrixXd::Zero(static_cast(np + 1), c->nDim()); + MatrixXd obs(static_cast(np), 3); + c->fillObstacles(reference, obs, now); + // Last cycle's trajectory heads up the diagonal, through (1.0, 1.0). + MatrixXd traj = MatrixXd::Zero(static_cast(np + 1), c->nDim()); + for (std::size_t k = 0; k <= np; ++k) { + traj(static_cast(k), 0) = 0.1 * static_cast(k); + traj(static_cast(k), 1) = 0.1 * static_cast(k); + traj(static_cast(k), 2) = M_PI / 4.0; + } + c->mpc()->setX(traj); + c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + return c->mpc()->getGoalU()(0, 0); + }; + EXPECT_LT(run(0.5), run(0.0)); +} + +// The eased cruise is only a target the obstacle term can override, so with the +// cap enabled the yield also bounds the forward speed the solver may command. +namespace +{ +// The model's current upper bound on the speed control (index 0 for the Unicycle). + double speedUpperBound(const TestableProxMpcController & c) + { + for (const auto & kv : c.model()->getIneq("u")) { + if (static_cast(kv.second[0]) == 0) {return kv.second[2];} + } + return std::numeric_limits::quiet_NaN(); + } + +// One cycle against the crossing mover used above, with the cap on or off and +// the previously applied speed set to `last_v`. + std::shared_ptr capCycle( + const std::function( + const std::vector &)> & make, bool caps, double last_v) + { + auto c = make( + { + rclcpp::Parameter("FollowPath.max_obstacles", 1), + rclcpp::Parameter("FollowPath.predict_obstacles", true), + rclcpp::Parameter("FollowPath.dynamic_speed_threshold", 0.05), + rclcpp::Parameter("FollowPath.robot_radius", 0.3), + rclcpp::Parameter("FollowPath.safety_margin", 0.1), + rclcpp::Parameter("FollowPath.obstacle_yield_band_m", 0.5), + rclcpp::Parameter("FollowPath.obstacle_yield_caps_speed", caps), + }); + c->activate(); + c->setPlan(makeStraightPlan(61, 0.2)); + const rclcpp::Time now(1000, 0, RCL_ROS_TIME); + const std::size_t np = c->mpc()->getNp(); + MatrixXd reference = MatrixXd::Zero(static_cast(np + 1), c->nDim()); + for (std::size_t i = 0; i <= np; ++i) { + reference(static_cast(i), 0) = 0.1 * static_cast(i); + } + c->injectObstacles(makeObstacleMsg(now, 1.0, -1.0, 0.0, 1.0, 0.2)); + MatrixXd obs(static_cast(np), 3); + c->fillObstacles(reference, obs, now); + c->lastCmdU()(0) = last_v; + c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + return c; + } +} // namespace + +TEST_F(ProxMpcControllerTest, ObstacleYieldCapBoundsTheForwardSpeed) +{ + auto make = [this](const std::vector & o) {return makeConfigured(o);}; + auto c = capCycle(make, true, 0.0); + EXPECT_LT(speedUpperBound(*c), c->vMax()); +} + +// The cap is what makes the yield slow the robot, but it must never make the +// first control infeasible: the solver holds that control within the model's +// deceleration times dt of the command last applied, so a bound under that would +// leave no admissible first control. Here the robot is doing 0.5 m/s into a +// breach deep enough to ask for a stop, and the bound stops at what it can reach. +TEST_F(ProxMpcControllerTest, ObstacleYieldCapNeverFallsBelowWhatTheRobotCanReach) +{ + auto make = [this](const std::vector & o) {return makeConfigured(o);}; + auto c = capCycle(make, true, 0.5); + double decel = std::numeric_limits::quiet_NaN(); + for (const auto & kv : c->model()->getIneq("du")) { + if (static_cast(kv.second[0]) == 0) {decel = std::abs(kv.second[1]);} + } + ASSERT_TRUE(std::isfinite(decel)); + EXPECT_GE(speedUpperBound(*c), 0.5 - decel * c->mpc()->getdt() - 1e-12); + EXPECT_LT(speedUpperBound(*c), c->vMax()) << "a deep breach must still lower the bound"; +} + +// Without the cap the yield only lowers the cruise target; the solver's speed +// bound is left exactly where the speed limit put it. +TEST_F(ProxMpcControllerTest, ObstacleYieldWithoutTheCapLeavesTheBoundAlone) +{ + auto make = [this](const std::vector & o) {return makeConfigured(o);}; + auto c = capCycle(make, false, 0.0); + EXPECT_NEAR(speedUpperBound(*c), c->vMax(), 1e-12); +} + // The hybrid fill keeps a static costmap obstacle in a remaining slot while a // dynamic track occupies the reserved slot. +// +// The static scan is centered on the MPC's own nominal trajectory +// (mpc()->getX()), not on the reference argument: at Np = 2 both nodes read the +// same clamped nominal row (min(node + 2, Np) = 2 for node 0 and node 1 alike), +// so setting that one row near the static block reproduces both nodes seeing it. TEST_F(ProxMpcControllerTest, HybridFillKeepsStaticObstacle) { auto c = makeConfigured( @@ -1221,15 +2364,16 @@ TEST_F(ProxMpcControllerTest, HybridFillKeepsStaticObstacle) const std::size_t k = 2; const rclcpp::Time now(1000, 0, RCL_ROS_TIME); - // A static lethal block near node 0's reference position. + // A static lethal block near the nominal trajectory's node-0/node-1 row. fillCost(1.0, 0.8, 1.3, 1.2, nav2_costmap_2d::LETHAL_OBSTACLE); // A dynamic obstacle far away, so its exclusion disc does not cover the block. c->injectObstacles(makeObstacleMsg(now, 5.0, 5.0, 1.0, 0.0, 0.2)); - MatrixXd reference = MatrixXd::Zero(3, c->nDim()); - reference(1, 0) = 1.15; reference(1, 1) = 1.0; // node 0 near the static block - reference(2, 0) = 1.15; reference(2, 1) = 1.0; + MatrixXd nominal = MatrixXd::Zero(3, c->nDim()); + nominal(2, 0) = 1.15; nominal(2, 1) = 1.0; // row read by both node 0 and node 1 + c->mpc()->setX(nominal); + MatrixXd reference = MatrixXd::Zero(3, c->nDim()); MatrixXd obs(static_cast(2 * k), 3); c->fillObstacles(reference, obs, now); @@ -1273,7 +2417,7 @@ TEST_F(ProxMpcControllerTest, StalenessFallbackRestoresCostmapOnly) MatrixXd obs_fill(static_cast(2 * k), 3); c->fillObstacles(reference, obs_fill, now); MatrixXd obs_reduce(static_cast(2 * k), 3); - c->reduceCostmap(reference, obs_reduce); + c->reduceCostmap(obs_reduce); for (Eigen::Index r = 0; r < obs_fill.rows(); ++r) { EXPECT_NEAR(obs_fill(r, 0), obs_reduce(r, 0), kTol); @@ -1307,7 +2451,7 @@ TEST_F(ProxMpcControllerTest, PredictDisabledIgnoresTrackedObstacles) MatrixXd obs_fill(static_cast(2 * k), 3); c->fillObstacles(reference, obs_fill, now); MatrixXd obs_reduce(static_cast(2 * k), 3); - c->reduceCostmap(reference, obs_reduce); + c->reduceCostmap(obs_reduce); for (Eigen::Index r = 0; r < obs_fill.rows(); ++r) { EXPECT_NEAR(obs_fill(r, 0), obs_reduce(r, 0), kTol); @@ -1319,6 +2463,12 @@ TEST_F(ProxMpcControllerTest, PredictDisabledIgnoresTrackedObstacles) // The brake ramp seeds from the server-measured velocity, not the last command: // a cycle-1 solver failure while the robot is moving (last command still zero) // still ramps down from the measured speed instead of commanding an abrupt zero. +// +// Both channels, not just the speed one. The unicycle's controls are [v, omega] +// and its twist mapping is the identity, so its inverse determines both, and +// the controller takes every channel the model reports as determined. Seeding +// the yaw channel from the stale zero command instead would step angular.z to 0 +// in one cycle while linear.x ramped. TEST_F(ProxMpcControllerTest, SolverFailureBrakesFromMeasuredVelocity) { auto c = makeConfigured( @@ -1331,14 +2481,19 @@ TEST_F(ProxMpcControllerTest, SolverFailureBrakesFromMeasuredVelocity) c->activate(); c->setPlan(makeStraightPlan(31, 0.2)); ASSERT_NEAR(c->lastCmdV(), 0.0, kTol); // last command is zero right after activate + ASSERT_NEAR(c->lastCmdW(), 0.0, kTol); geometry_msgs::msg::Twist measured; measured.linear.x = 0.40; // the robot is actually moving + measured.angular.z = -0.30; // and turning, opposite sign to exercise both steps const auto cmd = c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), measured, nullptr); ASSERT_NE(c->mpc()->qp_info.status, proxsuite::proxqp::QPSolverOutput::PROXQP_SOLVED); // Ramp from the measured 0.40, not an abrupt 0 off the stale last command. EXPECT_NEAR(cmd.twist.linear.x, 0.40 - kModelDecel * 0.1, 1e-6); + // Same for the yaw channel: du[1]'s upper bound magnitude brings a negative + // rate back toward zero, from the measurement rather than from the command. + EXPECT_NEAR(cmd.twist.angular.z, -0.30 + kModelDecel * 0.1, 1e-6); } // A non-finite measured velocity must never survive the brake ramp: +/-inf @@ -1369,6 +2524,306 @@ TEST_F(ProxMpcControllerTest, SolverFailureNeutralizesNonFiniteMeasuredVelocity) } } +// The default (0.0) brake_period_s steps the ramp with the measured +// inter-cycle period, floored at dt_ = 0.1 s so two back-to-back cycles (a +// gap of microseconds) never brake faster than the configured design. The +// first cycle of a task has no previous cycle to measure against and falls +// back to dt_, which is the same step, so the second cycle is the one that +// exercises the floor. AsymmetricBounds' asymmetric du[0] (-2.0, +0.5) makes +// the resulting step size, not just its sign, an observable proxy for which +// period was used. +TEST_F(ProxMpcControllerTest, BrakeMeasuredPeriodFloorsAtConfiguredDt) +{ + auto c = makeConfigured( + { + rclcpp::Parameter( + "FollowPath.model_plugin", std::string("prox_mpc_test_models/AsymmetricBounds")), + rclcpp::Parameter("FollowPath.max_int_iter_qp", 1), + rclcpp::Parameter("FollowPath.max_ext_iter_qp", 1), + rclcpp::Parameter("FollowPath.max_iter_sqp", 1), + rclcpp::Parameter("FollowPath.max_solver_failures", 10), + }); + c->activate(); + c->setPlan(makeStraightPlan(31, 0.2)); + + geometry_msgs::msg::Twist measured; + measured.linear.x = 1.0; + const auto first = c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), measured, nullptr); + ASSERT_NE(c->mpc()->qp_info.status, proxsuite::proxqp::QPSolverOutput::PROXQP_SOLVED); + EXPECT_NEAR(first.twist.linear.x, 1.0 - 2.0 * 0.1, 1e-6); // no measurement: dt_ fallback + const auto cmd = c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), measured, nullptr); + ASSERT_NE(c->mpc()->qp_info.status, proxsuite::proxqp::QPSolverOutput::PROXQP_SOLVED); + EXPECT_NEAR(cmd.twist.linear.x, 1.0 - 2.0 * 0.1, 1e-6); // floor: |du_low| * dt_ = 2.0 * 0.1 +} + +// The brake period is measured once at the top of the cycle, so a braking path +// taken after the solve reads the real gap since the previous cycle rather +// than the near-zero one left by a reset that already ran. Both cycles here +// take the solver-failure path, which brakes past the diagnostics publication: +// the deliberate stall between them makes the ramp step the capped 2 * dt_ +// instead of the floored dt_ a dead measurement would produce. +TEST_F(ProxMpcControllerTest, BrakeMeasuredPeriodAppliesOnThePostSolveFailurePath) +{ + auto c = makeConfigured( + { + rclcpp::Parameter( + "FollowPath.model_plugin", std::string("prox_mpc_test_models/AsymmetricBounds")), + rclcpp::Parameter("FollowPath.max_int_iter_qp", 1), + rclcpp::Parameter("FollowPath.max_ext_iter_qp", 1), + rclcpp::Parameter("FollowPath.max_iter_sqp", 1), + rclcpp::Parameter("FollowPath.max_solver_failures", 10), + }); + c->activate(); + c->setPlan(makeStraightPlan(31, 0.2)); + + geometry_msgs::msg::Twist measured; + measured.linear.x = 1.0; + c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), measured, nullptr); + ASSERT_NE(c->mpc()->qp_info.status, proxsuite::proxqp::QPSolverOutput::PROXQP_SOLVED); + + std::this_thread::sleep_for(std::chrono::milliseconds(300)); // far past 2 * dt_ = 0.2 s + + const auto cmd = c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), measured, nullptr); + ASSERT_NE(c->mpc()->qp_info.status, proxsuite::proxqp::QPSolverOutput::PROXQP_SOLVED); + // Capped at 2 * dt_: step = 2.0 * 0.2 = 0.4. A dead measurement would floor + // the step at 2.0 * 0.1 = 0.2 and leave 0.8 here. + EXPECT_NEAR(cmd.twist.linear.x, 1.0 - 2.0 * 0.2, 1e-6); +} + +// The measured period is capped at kMaxBrakePeriodFactor * dt_ = 0.2 s so a +// real stall does not collapse one ramp step into an abrupt stop. This case +// takes the non-finite-pose fail path, which brakes before the solve, and its +// sibling above takes the solver-failure path, which brakes after it: the +// period is measured once at the top of the cycle, so both see the same gap. +TEST_F(ProxMpcControllerTest, BrakeMeasuredPeriodCapsAtTwiceConfiguredDt) +{ + auto c = makeConfigured( + {rclcpp::Parameter( + "FollowPath.model_plugin", std::string("prox_mpc_test_models/AsymmetricBounds"))}); + c->activate(); + c->setPlan(makeStraightPlan(31, 0.2)); + + // A normal converged cycle, so this cycle's start is recorded as the + // reference point the next cycle's stall is measured against. + const auto ok = c->computeVelocityCommands( + makePose(0.0, 0.0, 0.0), geometry_msgs::msg::Twist(), nullptr); + ASSERT_TRUE(std::isfinite(ok.twist.linear.x)); + + std::this_thread::sleep_for(std::chrono::milliseconds(500)); // far past 2 * dt_ = 0.2 s + + geometry_msgs::msg::Twist measured; + measured.linear.x = 1.0; + geometry_msgs::msg::PoseStamped bad = makePose(0.0, 0.0, 0.0); + bad.pose.position.x = std::numeric_limits::quiet_NaN(); + const auto cmd = c->computeVelocityCommands(bad, measured, nullptr); + + // An unclamped ~0.5 s period would apply step = 2.0 * 0.5 = 1.0, saturating + // the ramp at zero; the ceiling caps it at 2.0 * 0.2 = 0.4. + EXPECT_NEAR(cmd.twist.linear.x, 1.0 - 2.0 * 0.2, 1e-6); +} + +// A positive brake_period_s pins the ramp step and bypasses the measured +// period entirely, even across a real stall far longer than the pinned value. +TEST_F(ProxMpcControllerTest, BrakePinnedPeriodIgnoresElapsedTime) +{ + auto c = makeConfigured( + { + rclcpp::Parameter( + "FollowPath.model_plugin", std::string("prox_mpc_test_models/AsymmetricBounds")), + rclcpp::Parameter("FollowPath.brake_period_s", 0.05), + rclcpp::Parameter("FollowPath.max_int_iter_qp", 1), + rclcpp::Parameter("FollowPath.max_ext_iter_qp", 1), + rclcpp::Parameter("FollowPath.max_iter_sqp", 1), + rclcpp::Parameter("FollowPath.max_solver_failures", 10), + }); + c->activate(); + c->setPlan(makeStraightPlan(31, 0.2)); + + geometry_msgs::msg::Twist measured; + measured.linear.x = 1.0; + c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), measured, nullptr); + + std::this_thread::sleep_for(std::chrono::milliseconds(300)); // far past 0.05 s + const auto cmd = c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), measured, nullptr); + ASSERT_NE(c->mpc()->qp_info.status, proxsuite::proxqp::QPSolverOutput::PROXQP_SOLVED); + EXPECT_NEAR(cmd.twist.linear.x, 1.0 - 2.0 * 0.05, 1e-6); +} + +// The ramp saturates at zero rather than reversing: an over-large step (here, +// a deliberately oversized pinned period) shortens the stop instead of +// overshooting past zero into the opposite sign, which is what makes an +// uncapped or mis-tuned step benign rather than a new failure mode. +TEST_F(ProxMpcControllerTest, BrakeSaturatesAtZeroRatherThanReversing) +{ + auto c = makeConfigured( + { + rclcpp::Parameter( + "FollowPath.model_plugin", std::string("prox_mpc_test_models/AsymmetricBounds")), + rclcpp::Parameter("FollowPath.brake_period_s", 1.0), // step = 2.0 * 1.0 = 2.0 + rclcpp::Parameter("FollowPath.max_int_iter_qp", 1), + rclcpp::Parameter("FollowPath.max_ext_iter_qp", 1), + rclcpp::Parameter("FollowPath.max_iter_sqp", 1), + rclcpp::Parameter("FollowPath.max_solver_failures", 10), + }); + c->activate(); + c->setPlan(makeStraightPlan(31, 0.2)); + + geometry_msgs::msg::Twist measured; + measured.linear.x = 0.5; // step (2.0) is 4x the measured speed + const auto cmd = c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), measured, nullptr); + ASSERT_NE(c->mpc()->qp_info.status, proxsuite::proxqp::QPSolverOutput::PROXQP_SOLVED); + EXPECT_DOUBLE_EQ(cmd.twist.linear.x, 0.0); // saturates, never crosses to negative +} + +// Each direction ramps at its own declared rate: braking a forward-moving +// robot uses du[0]'s lower bound magnitude (2.0), while returning to zero from +// a reversing robot uses its upper bound magnitude (0.5). brake_period_s is +// pinned so the comparison is not sensitive to test execution timing. Neither +// bundled model can show this because both declare symmetric du bounds. +TEST_F(ProxMpcControllerTest, BrakePreservesAsymmetricDecelerationBoundsPerDirection) +{ + auto c = makeConfigured( + { + rclcpp::Parameter( + "FollowPath.model_plugin", std::string("prox_mpc_test_models/AsymmetricBounds")), + rclcpp::Parameter("FollowPath.brake_period_s", 0.1), + rclcpp::Parameter("FollowPath.max_int_iter_qp", 1), + rclcpp::Parameter("FollowPath.max_ext_iter_qp", 1), + rclcpp::Parameter("FollowPath.max_iter_sqp", 1), + rclcpp::Parameter("FollowPath.max_solver_failures", 10), + }); + c->activate(); + c->setPlan(makeStraightPlan(31, 0.2)); + + geometry_msgs::msg::Twist forward; + forward.linear.x = 1.0; + const auto cmd_fwd = c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), forward, nullptr); + ASSERT_NE(c->mpc()->qp_info.status, proxsuite::proxqp::QPSolverOutput::PROXQP_SOLVED); + EXPECT_NEAR(cmd_fwd.twist.linear.x, 1.0 - 2.0 * 0.1, 1e-6); // du[0] low = -2.0 + + geometry_msgs::msg::Twist reverse; + reverse.linear.x = -1.0; + const auto cmd_rev = c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), reverse, nullptr); + ASSERT_NE(c->mpc()->qp_info.status, proxsuite::proxqp::QPSolverOutput::PROXQP_SOLVED); + EXPECT_NEAR(cmd_rev.twist.linear.x, -1.0 + 0.5 * 0.1, 1e-6); // du[0] upp = +0.5 +} + +// The bicycle's brake maps through the model's own toTwist physics - for the +// front-axle model linear.x = v cos(delta) and angular.z = v sin(delta) / L, both +// the base_link twist - rather than a twist-space ramp of the measured yaw rate, +// and a pinned brake_period_s steps both the speed ramp and the steering decay by +// the same pinned amount rather than the measured period +// BrakeMeasuredPeriodCapsAtTwiceConfiguredDt exercises. +// +// The speed channel of this model is the front-wheel speed, so the ramp starts +// from the speed the model's own inverse recovers from the measured base_link +// twist, not from that twist's linear.x: the measurement below is exactly what +// the model emits for a front-wheel speed of 1.0 at the current steering angle, +// and the ramp is expected to start from 1.0. Seeding the channel with +// linear.x instead would start it at 1.0 * cos(0.5) and project it a second +// time on the way out. +TEST_F(ProxMpcControllerTest, BicycleBrakeMapsThroughToTwistWithPinnedPeriod) +{ + auto c = makeConfigured( + { + rclcpp::Parameter("FollowPath.model_plugin", std::string(kBicyclePlugin)), + rclcpp::Parameter("FollowPath.brake_period_s", 0.2), + rclcpp::Parameter("FollowPath.max_int_iter_qp", 1), + rclcpp::Parameter("FollowPath.max_ext_iter_qp", 1), + rclcpp::Parameter("FollowPath.max_iter_sqp", 1), + rclcpp::Parameter("FollowPath.max_solver_failures", 10), + }); + c->activate(); + c->setPlan(makeStraightPlan(31, 0.2)); + const double delta0 = 0.5; + c->steeringState() = delta0; + + const double v_front = 1.0; + geometry_msgs::msg::Twist measured; + measured.linear.x = v_front * std::cos(delta0); + measured.angular.z = v_front * std::sin(delta0) / kBicycleWheelbase; + const auto cmd = c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), measured, nullptr); + ASSERT_NE(c->mpc()->qp_info.status, proxsuite::proxqp::QPSolverOutput::PROXQP_SOLVED); + + const double expected_v = v_front - kModelDecel * 0.2; // du[0] bound, pinned period + const double expected_delta = delta0 - kSteerRateBound * 0.2; // u[1] bound, pinned period + EXPECT_NEAR(cmd.twist.linear.x, expected_v * std::cos(expected_delta), 1e-9); + EXPECT_NEAR( + cmd.twist.angular.z, expected_v * std::sin(expected_delta) / kBicycleWheelbase, 1e-9); +} + +// The rear-axle model's speed control is already the base_link speed, so its +// brake starts from the measured linear.x exactly as it did before the speed +// channel was seeded through the model's inverse: the base class inverse reads +// linear.x straight out. Its steering rate is not observable in a twist, so +// that channel still decays from the steering belief at the model's own rate +// bound and the emitted yaw rate is v tan(delta) / L. +TEST_F(ProxMpcControllerTest, RearAxleBrakeSeedsFromMeasuredBaseLinkSpeed) +{ + auto c = makeConfigured( + { + rclcpp::Parameter( + "FollowPath.model_plugin", std::string("prox_mpc_core/BicycleRearAxle")), + rclcpp::Parameter("FollowPath.brake_period_s", 0.2), + rclcpp::Parameter("FollowPath.max_int_iter_qp", 1), + rclcpp::Parameter("FollowPath.max_ext_iter_qp", 1), + rclcpp::Parameter("FollowPath.max_iter_sqp", 1), + rclcpp::Parameter("FollowPath.max_solver_failures", 10), + }); + c->activate(); + c->setPlan(makeStraightPlan(31, 0.2)); + const double delta0 = 0.5; + c->steeringState() = delta0; + + geometry_msgs::msg::Twist measured; + measured.linear.x = 1.0; + measured.angular.z = 1.0 * std::tan(delta0) / kBicycleWheelbase; + const auto cmd = c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), measured, nullptr); + ASSERT_NE(c->mpc()->qp_info.status, proxsuite::proxqp::QPSolverOutput::PROXQP_SOLVED); + + const double expected_v = 1.0 - kModelDecel * 0.2; + const double expected_delta = delta0 - kSteerRateBound * 0.2; + EXPECT_NEAR(cmd.twist.linear.x, expected_v, 1e-9); + EXPECT_NEAR( + cmd.twist.angular.z, expected_v * std::tan(expected_delta) / kBicycleWheelbase, 1e-9); +} + +// Both bicycles declare their steering rate undetermined in a body twist, so +// that channel is never seeded from the measurement however large the measured +// yaw rate is: it decelerates from its last commanded value under the model's +// own du[1] bound. The channel is read back directly because the emitted twist +// derives its yaw rate from the decayed steering angle rather than from control +// 1, so nothing on the wire distinguishes the two seeds. +TEST_F(ProxMpcControllerTest, BicycleBrakeHoldsTheUndeterminedSteeringRate) +{ + for (const char * plugin : {kBicyclePlugin, "prox_mpc_core/BicycleRearAxle"}) { + SCOPED_TRACE(plugin); + auto c = makeConfigured( + { + rclcpp::Parameter("FollowPath.model_plugin", std::string(plugin)), + rclcpp::Parameter("FollowPath.brake_period_s", 0.2), + rclcpp::Parameter("FollowPath.max_int_iter_qp", 1), + rclcpp::Parameter("FollowPath.max_ext_iter_qp", 1), + rclcpp::Parameter("FollowPath.max_iter_sqp", 1), + rclcpp::Parameter("FollowPath.max_solver_failures", 10), + }); + c->activate(); + c->setPlan(makeStraightPlan(31, 0.2)); + ASSERT_EQ(c->lastCmdU().size(), 2); + c->lastCmdU()(1) = 0.4; // last commanded steering rate [rad/s] + + geometry_msgs::msg::Twist measured; + measured.linear.x = 1.0; + measured.angular.z = 1.0; // a body yaw rate the steering channel must not adopt + c->computeVelocityCommands(makePose(0.0, 0.0, 0.0), measured, nullptr); + ASSERT_NE(c->mpc()->qp_info.status, proxsuite::proxqp::QPSolverOutput::PROXQP_SOLVED); + + // 0.4 ramped toward zero at du[1] over the pinned period, not 1.0 ramped. + EXPECT_NEAR(c->lastCmdU()(1), 0.4 - kModelDecel * 0.2, 1e-9); + c->cleanup(); + } +} + // Structurally invalid horizon sizing (np or nc < 1, or dt <= 0) fails configure // with a ControllerException rather than wrapping into an astronomical size_t // allocation or dividing by zero. diff --git a/prox_mpc_core/CHANGELOG.rst b/prox_mpc_core/CHANGELOG.rst index c1d4576..fdbbbe9 100644 --- a/prox_mpc_core/CHANGELOG.rst +++ b/prox_mpc_core/CHANGELOG.rst @@ -2,6 +2,32 @@ Changelog for package prox_mpc_core ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2.0.0 (2026-09-13) +------------------ +* **Breaking:** ``warm_start`` defaults to ``true``. The ProxQP workspace is + built once and updated in place, so the factorization and the previous + primal/dual iterate carry over between cycles instead of being rebuilt every + solve. Set it ``false`` to restore the previous behavior. +* ``max_iter_sqp`` defaults to 1, making the real-time iteration scheme + unconditional and per-cycle latency bounded by a single QP. The previous + default of 100 could spend 99 further linearizations around a corrupted + iterate after a failed solve. +* The horizon shift no longer overwrites the warm start's first control with the + control already executed, which had left it violating its own control-rate + chain on every cycle. +* Models declare their planar mapping and, where they have one, their + steering-rate control; the keep-out rows are indexed by that mapping rather + than by assumed state columns. The bicycle is split by reference point. +* Transactional solve entry point: a candidate is retained only once the + caller's acceptance gates pass. +* Coupled obstacle linearisation completed and the CBF constraint assembly + hardened; the inert first-node obstacle gradient is no longer built. +* Configuration-time validation across ``MPC`` and ``Model``: horizon setters, + ``dt``/``T``, ``setMaxObs``, ``setCbfGamma``, inequality bound indices, and the + rear-axle steering bound are all checked, and structural setters are rejected + after ``init()``. +* Contributors: Simone Contorno + 1.0.0 (2026-07-28) ------------------ * Initial release: NMPC core solved by a Sequential Quadratic Programming scheme diff --git a/prox_mpc_core/CMakeLists.txt b/prox_mpc_core/CMakeLists.txt index b448942..f8f0e1c 100644 --- a/prox_mpc_core/CMakeLists.txt +++ b/prox_mpc_core/CMakeLists.txt @@ -10,9 +10,20 @@ if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE "Release") endif() -# Compiler warnings -if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang") - add_compile_options(-Wall -Wextra -Wpedantic) +# Compiler warnings, matching upstream Nav2's package-level policy +# (nav2_common/cmake/nav2_package.cmake) so this package is held to the same +# bar as every other Nav2 plugin it ships alongside. +if(CMAKE_CXX_COMPILER_ID MATCHES "GNU" OR CMAKE_CXX_COMPILER_ID MATCHES "Clang") + add_compile_options(-Wall -Wextra -Wpedantic -Werror -Wdeprecated -fPIC -Wshadow -Wnull-dereference) + # GCC 13 raises -Wnull-dereference inside libstdc++'s own headers + # (stl_algobase.h, reached through regex_traits::transform_primary) once + # --coverage changes its inlining decisions, which is how the coverage build + # hits it and an ordinary build does not. The report is attributed to the + # translation unit that instantiates the template, so -Wno-system-headers + # does not reach it. Keep the diagnostic, but do not let a false positive in + # the standard library fail the build. + add_compile_options(-Wno-error=null-dereference) + add_compile_options("$<$:-Wnon-virtual-dtor>") endif() # Remove Eigen's internal assertions in the hot path (safe under Release) @@ -81,7 +92,8 @@ ament_target_dependencies(${PROJECT_NAME}_models ) # Export prox_mpc::Model as a pluginlib base so models are selected outside the -# core (no core edit per new model). Bicycle/Unicycle are the bundled plugins. +# core (no core edit per new model). The bundled plugins are BicycleFrontAxle, +# BicycleRearAxle, the deprecated Bicycle alias, and Unicycle. pluginlib_export_plugin_description_file(prox_mpc_core prox_mpc_core_plugins.xml) # Install @@ -123,14 +135,24 @@ if(BUILD_TESTING) find_package(ament_cmake_gtest REQUIRED) # (a) model interface, (b) regression baseline, (c) custom model, (d) obstacle K, - # (e) ROS-facing utils helpers + # (e) ROS-facing utils helpers, (f) transactional solve/commit contract, + # (g) post-init configuration lifecycle and goal/obstacle shape validation, + # (h) the deprecated alias's once-per-process warning, which needs a process + # where nothing else has constructed the alias first foreach(test_name test_model_interface test_mpc_regression test_custom_model test_obstacle_k - test_utils) - ament_add_gtest(${test_name} test/${test_name}.cpp) + test_utils + test_transactional_solve + test_config_lifecycle + test_deprecated_alias) + # None of these targets fit inside CTest's 60 s default once ASan/UBSan + # instrumentation is linked in (test_obstacle_k alone needs ~57 s), so every + # target in this loop gets the same generous budget rather than singling one + # out; a slower CI runner is covered too. + ament_add_gtest(${test_name} test/${test_name}.cpp TIMEOUT 300) target_link_libraries(${test_name} ${PROJECT_NAME} Eigen3::Eigen diff --git a/prox_mpc_core/README.md b/prox_mpc_core/README.md index e88cdea..9bbcc89 100644 --- a/prox_mpc_core/README.md +++ b/prox_mpc_core/README.md @@ -25,9 +25,9 @@ This package contains **no ROS node**: it is the reusable library that [prox_mpc ## Overview The core owns the SQP/QP assembly, the tracking cost, the state/control/rate constraints, the disc-based obstacle math, and the `prox_mpc::Model` vehicle interface. -It never needs editing to gain a new vehicle model: a model is a `pluginlib` plugin loaded by name. +It never needs editing to gain a new vehicle model: a model is a `pluginlib` plugin loaded by name, and every part of the assembly that has to know where a quantity sits in the state vector - the obstacle constraints included - reads it from the model's declared planar mapping rather than from a fixed layout. -See [doc/architecture.md](doc/architecture.md) for the design overview, [doc/nmpc.md](doc/nmpc.md) for the NMPC/SQP/QP math, and [doc/obstacle-avoidance.md](doc/obstacle-avoidance.md) for the obstacle constraints. +See [doc/architecture.md](doc/architecture.md) for the design overview, [doc/nmpc.md](doc/nmpc.md) for the NMPC/SQP/QP math, and [doc/obstacle-avoidance.md](doc/obstacle-avoidance.md) for the obstacle constraints. [doc/migration.md](doc/migration.md) records what changed on the released surface since 1.0.0. ## Public API @@ -40,22 +40,24 @@ Everything lives in the `prox_mpc` C++ namespace. | `prox_mpc/proxqp.hpp` | `ProxQP`: QP assembly and solve wrapper | | `prox_mpc/mpc.hpp` | `MPC`: SQP driver and configuration | | `prox_mpc/utils.hpp` | free functions (`normalizeAngle`, `optimPath`), Eigen/ROS aliases | -| `prox_mpc/models/bicycle.hpp`, `prox_mpc/models/unicycle.hpp` | reference kinematic models | +| `prox_mpc/models/bicycle_front_axle.hpp`, `prox_mpc/models/bicycle_rear_axle.hpp`, `prox_mpc/models/unicycle.hpp` | reference kinematic models (`bicycle.hpp` holds the deprecated `Bicycle` alias) | ## Models A model derives from `Model` and implements three pure virtual hooks that supply the Euler linearization (`updateA`, `updateB`, `updatec`). Two optional hooks make it loadable and usable generically: `configure(params)` sets its constants by name after construction, and `toTwist(u)` maps a control vector to a `geometry_msgs/msg/Twist`. -`Model` is a `pluginlib` base type, and the bundled models are registered as `prox_mpc_core/Bicycle` and `prox_mpc_core/Unicycle`. -A consumer can load a model by name with a `pluginlib::ClassLoader` and pass it to `MPC::init`, so adding a model requires no change to this library. +`Model` is a `pluginlib` base type, and the bundled models are registered as `prox_mpc_core/BicycleFrontAxle`, `prox_mpc_core/BicycleRearAxle` and `prox_mpc_core/Unicycle`, with `prox_mpc_core/Bicycle` kept as a deprecated alias for the front-axle model. +A consumer can load a model by name with a `pluginlib::ClassLoader` and pass it to `MPC::init`, so adding a model that does not enable obstacle avoidance requires no change to this library; see [Overview](#overview) for the state-layout precondition on a model that does. -| Plugin name | Class | State | Control | -| --- | --- | --- | --- | -| `prox_mpc_core/Bicycle` | `prox_mpc::Bicycle` | `[x, y, theta, delta]` (n=4) | `[v, delta_dot]` (m=2) | -| `prox_mpc_core/Unicycle` | `prox_mpc::Unicycle` | `[x, y, theta]` (n=3) | `[v, omega]` (m=2) | +| Plugin name | Class | State | Control | Reference point | +| --- | --- | --- | --- | --- | +| `prox_mpc_core/BicycleFrontAxle` | `prox_mpc::BicycleFrontAxle` | `[x, y, theta, delta]` (n=4) | `[v, delta_dot]` (m=2) | front axle, `(L, 0)` in `base_link` | +| `prox_mpc_core/BicycleRearAxle` | `prox_mpc::BicycleRearAxle` | `[x, y, theta, delta]` (n=4) | `[v, delta_dot]` (m=2) | rear axle, the `base_link` origin | +| `prox_mpc_core/Bicycle` | `prox_mpc::Bicycle` | `[x, y, theta, delta]` (n=4) | `[v, delta_dot]` (m=2) | deprecated alias for `BicycleFrontAxle` | +| `prox_mpc_core/Unicycle` | `prox_mpc::Unicycle` | `[x, y, theta]` (n=3) | `[v, omega]` (m=2) | the `base_link` origin | -Both models enable obstacle avoidance; they differ in their `toTwist` mapping, because the bicycle's second control is a steering rate and derives the yaw rate from the current steering state as `omega = v*sin(delta)/L`, while the unicycle's control is already a body twist and uses the base identity mapping. +Every model enables obstacle avoidance; they differ in their `toTwist` mapping, because a bicycle's second control is a steering rate and the yaw rate follows from the current steering state, while the unicycle's control is already a body twist and uses the base identity mapping. Each model also declares its state and control layout, its reference point and its wheelbase through `getPlanarMapping()`, so a consumer reads them rather than assuming a layout. Both are exported to `pluginlib` via [prox_mpc_core_plugins.xml](prox_mpc_core_plugins.xml). ## Prerequisites @@ -90,7 +92,7 @@ After building and sourcing the overlay, list the models this package registers ros2 plugin list --package prox_mpc_core ``` -This reports `prox_mpc_core/Bicycle` and `prox_mpc_core/Unicycle` under the `prox_mpc::Model` base. +This reports `prox_mpc_core/BicycleFrontAxle`, `prox_mpc_core/BicycleRearAxle`, `prox_mpc_core/Bicycle` and `prox_mpc_core/Unicycle` under the `prox_mpc::Model` base. @@ -117,6 +119,7 @@ The full class diagram, the mathematical formulation, and the solve data flow ar prox_mpc_core/ ├── doc/ │ ├── architecture.md +│ ├── migration.md │ ├── nmpc.md │ └── obstacle-avoidance.md ├── include/prox_mpc/ @@ -127,6 +130,8 @@ prox_mpc_core/ │ ├── utils.hpp │ └── models/ │ ├── bicycle.hpp +│ ├── bicycle_front_axle.hpp +│ ├── bicycle_rear_axle.hpp │ └── unicycle.hpp ├── src/ │ ├── model.cpp diff --git a/prox_mpc_core/doc/architecture.md b/prox_mpc_core/doc/architecture.md index e098c0e..4fe84b7 100644 --- a/prox_mpc_core/doc/architecture.md +++ b/prox_mpc_core/doc/architecture.md @@ -144,12 +144,24 @@ Two further virtual hooks let a model be loaded and used generically: ### Model selection -`prox_mpc::Model` is a `pluginlib` base type, and `Bicycle` and `Unicycle` are -registered as plugins named `prox_mpc_core/Bicycle` and `prox_mpc_core/Unicycle`. +`prox_mpc::Model` is a `pluginlib` base type. The bundled models are registered +as `prox_mpc_core/BicycleFrontAxle`, `prox_mpc_core/BicycleRearAxle` and +`prox_mpc_core/Unicycle`, with `prox_mpc_core/Bicycle` kept as a deprecated alias +for the front-axle model. A consumer loads a model with a `pluginlib::ClassLoader`, calls -`configure(...)`, and passes the instance to `MPC::init(...)`. Adding a new model -therefore requires no change to this library: a model only needs to derive from -`Model`, implement the three Jacobian hooks, and be registered as a plugin. +`configure(...)`, and passes the instance to `MPC::init(...)`. Adding a new +model therefore requires no change to this library: a model only needs to +derive from `Model`, implement the three Jacobian hooks, and be registered as a +plugin. That holds with obstacle avoidance on as well. The obstacle-constraint +assembly is the one part of the solver that has to know where the planar +position sits in the state vector, and it reads that from the model's declared +`getPlanarMapping()` rather than assuming a layout, so a model whose state is +ordered any other way is constrained on the axes it declares. + +`ProxQP::init()` reads those two indices once, alongside the obstacle-active +flag, and rejects a model that maps either position outside its own state +vector or maps both to the same index. The check lives here rather than only in +a consumer because a direct library user has no other screening. The residual and Jacobian formulas for the bundled models are given in [nmpc.md](nmpc.md). diff --git a/prox_mpc_core/doc/migration.md b/prox_mpc_core/doc/migration.md new file mode 100644 index 0000000..517705a --- /dev/null +++ b/prox_mpc_core/doc/migration.md @@ -0,0 +1,238 @@ +# Migrating from prox_mpc_core 1.0.0 + +What changed on the released surface of `prox_mpc_core`, and what a 1.0.0 caller +has to do about it. +The version number this lands under is fixed by the maintainer against the final +diff and is not stated here. + +## Summary + +| Change | Source compatible | ABI compatible | Wire compatible | +| --- | --- | --- | --- | +| `prox_mpc::Model` gains non-pure virtuals `getPlanarMapping()` and `fromTwist()` | yes | **no** | n/a | +| `prox_mpc::MPC` gains `solveCandidate()`, `commitCandidate()`, `getCandidateFinite()`, `setU0()` and candidate members | yes | **no** | n/a | +| `MPC::init()` rejects a nonsymmetric or indefinite weight matrix | yes | yes | n/a | +| `MPC::setGoalX` / `setGoalU` reject an undersized matrix | yes | yes | n/a | +| `MPC::setNp` and `MPC::init()` reject `Nc > Np` | yes | yes | n/a | +| Structural `MPC` setters reject a post-`init()` call | yes | yes | n/a | +| `Model::updateIneq` rejects an index the model declares no bound for | yes | yes | n/a | +| The bicycle splits into two plugins; `prox_mpc_core/Bicycle` becomes a deprecated alias | yes | yes | n/a | +| `prox_mpc::Bicycle`'s emitted twist is corrected | yes | yes | n/a | +| The coupled obstacle constraint carries its previous-node gradient | yes | yes | n/a | + +Nothing in this package touches a message, so nothing here is a wire event. + +## Every `Model` plugin must be rebuilt + +`prox_mpc::Model` gains two virtual members, `getPlanarMapping()` and +`fromTwist()`, appended after `toTwist()` in that order so they take the last two +vtable slots and every earlier slot keeps its index. + +A plugin that is recompiled against the new header needs no edit: the base class +supplies a default for each. `getPlanarMapping()` reproduces the convention the +controller assumed before the hook existed - state `[x, y, yaw, (delta)]`, +control `[v, ...]`, the state referenced to `base_link`, and a steering angle at +state index 3 for any model with more than three states. `fromTwist()` is the +inverse of the default `toTwist()`: `linear.x` into control 0, `angular.z` into +control 1, every further control left non-finite to mark it undetermined. + +A plugin `.so` built against 1.0.0 and **not** rebuilt dispatches through a stale +vtable. There is no build-time signal for this and no runtime warning; the +symptom is wrong dispatch inside a motion-control path. Rebuild every out-of-tree +`prox_mpc::Model` plugin against the new `prox_mpc_core`. Packages installed from +the buildfarm are covered, because jazzy sets `abi_incompatibility_assumed: true` +and rebuilds dependents. + +### Declaring a mapping + +Override `getPlanarMapping()` when the model does not follow the default +convention, and **always** when it carries a steering angle: the bundled +controller now reads the wheelbase from the model rather than from the +`model_params.L` parameter it forwards, and rejects at `configure()` a model that +carries a steering angle without declaring a usable wheelbase. + +```cpp +prox_mpc::PlanarMapping getPlanarMapping() const override +{ + prox_mpc::PlanarMapping mapping; + mapping.idx_steering = 3; + mapping.idx_steer_rate = 1; // control carrying the steering rate + mapping.ref_offset_x = this->params(0); // reference point in base_link [m] + mapping.wheelbase = this->params(0); + return mapping; +} +``` + +`idx_steer_rate` names the control whose declared bound sets how fast a consumer +may move its belief about the steering angle. The default reproduces the previous +inference - control index 1 for a model with more than three states and more than +one control - so a model that declares nothing behaves exactly as it did. + +### Inverting the twist mapping + +Override `fromTwist()` when the model overrides `toTwist()` and its controls are +still recoverable from a body twist, so the two mappings agree. A consumer that +has a measured twist and needs the control that produced it - a deceleration +ramp seeding itself from the robot's actual velocity, for instance - reads this +hook; without an override it would read the base class default, which is the +inverse of a mapping the model does not use. + +The return value is a per-channel declaration, not just a value: a finite entry +is a measurement of that control, and a non-finite one says the twist does not +determine it, leaving the consumer to keep whatever value it already holds. +The bundled Nav2 plugin applies exactly that, so a channel this hook misreports +is a channel that plugin will seed wrongly. + +`BicycleFrontAxle` overrides it, because control 0 is a front-wheel speed rather +than the `base_link` speed `toTwist()` emits: + +```cpp +VectorXd fromTwist(const geometry_msgs::msg::Twist & twist) const override +{ + VectorXd u = VectorXd::Constant(2, std::numeric_limits::quiet_NaN()); + const double wheel_arc = twist.angular.z * this->params(0); + const double speed = std::sqrt(twist.linear.x * twist.linear.x + wheel_arc * wheel_arc); + u(0) = (twist.linear.x < 0.0) ? -speed : speed; + return u; +} +``` + +The inverse is taken from both twist components rather than by dividing +`linear.x` by `cos(delta)`, which vanishes at that model's own `+/- pi/2` +steering bound. Control 1 is left non-finite: a twist shows the steering angle's +effect, not the rate the angle is changing at, so the caller keeps whatever +value it already holds for that channel. + +`BicycleRearAxle` overrides it as well, for the second half of the same reason. +Its control 0 *is* the `base_link` speed, so the default would read that channel +correctly, but its control 1 is a steering rate while the default returns +`angular.z` there - a body yaw rate, and the two are not the same quantity. A +model that overrides `toTwist()` needs this hook even when its speed channel +happens to agree with the default. + +## `MPC` gains candidate state + +`MPC` gains four public methods and six data members. The methods are non-virtual +and symbol-additive; the data members change `sizeof(MPC)`, so a consumer that +constructs, holds by value, or derives from `MPC` against the 1.0.0 header while +linking the new library is binary-incompatible. Rebuild. + +`solve()` keeps its 1.0.0 contract exactly: it runs the cycle, retains the +increments whatever the QP reported, and advances the previous control only on a +converged solve. A caller that wants a cycle it can reject uses the staged pair +instead: + +```cpp +auto [x, u] = mpc->solveCandidate(); // retains nothing +if (mpc->qp_info.status == PROXQP_SOLVED && mpc->getCandidateFinite() && myGatesPass(x, u)) { + mpc->commitCandidate(); // now the state advances +} +``` + +`commitCandidate()` refuses a candidate that did not converge or is not finite +over the whole horizon, and returns whether it committed. A caller that applies +something other than the candidate's first control - a deceleration ramp, say - +calls `setU0()` with what it applied, so the next cycle's control-rate constraint +is anchored on the command the robot actually received. + +## Configuration-time validation now throws + +Five inputs that 1.0.0 accepted silently are now rejected. + +- `setGoalX` and `setGoalU` throw `std::invalid_argument` for a matrix with too + few rows for the configured horizon, and for a wrong column count once + `init()` has read the model's dimensions. 1.0.0 stored the matrix and read out + of bounds during assembly, which `EIGEN_NO_DEBUG` left unchecked. +- `init()` throws `std::invalid_argument` unless `Q`, `S`, `R` and `W` are + finite, symmetric and positive semidefinite. 1.0.0 accepted an asymmetric or + indefinite weight and silently solved the symmetrised problem instead. +- `setQ`, `setR`, `setS`, `setW`, `setNp`, `setNc`, `setdt`, `setT`, + `setMaxIntIterQP`, `setMaxExtIterQP`, `setGuess`, `setQPtype`, `setCbfGamma` + and `setMaxObs` throw `std::logic_error` when called after `init()`. 1.0.0 + returned quietly while mutating only their own members, leaving the buffers + and the QP object sized for the previous configuration. `setMaxObs` sizes the + obstacle matrix and the QP's slot count at `init()`; `setCbfGamma` reaches the + solver only through `configProxQP()`, which `init()` runs once, so a later + call changed the `MPC` member and nothing the solver reads. +- `setNp` throws `std::invalid_argument` for a prediction horizon shorter than + an already-set control horizon, and `init()` throws it for a pair that reached + it unchecked. 1.0.0 compared the two inside `setNc` alone, and only once `Np` + was already known, so `setNc` before `setNp` - and `setNc` with no `setNp` at + all - sized a QP with more control nodes than prediction nodes. +- `Model::updateIneq` throws `std::invalid_argument` when the model declares no + existing bound for the `var` and index it is given. 1.0.0 fell through its + four search branches and returned having changed nothing, which made the call + safe to issue without first establishing that the bound exists - the pattern + the bundled controller's own `applySpeedLimit` uses, calling `updateIneq` on + the model's speed control with no preceding existence check. A caller that + relied on the no-op must now declare the bound with `setIneq` first, or read + `getIneq(var)` and skip the update when the index is absent. + +Call the structural setters before `init()`, size the goal matrices to the +horizon, pass symmetric positive-semidefinite weights, and update only a bound +the model already declares. The bundled Nav2 plugin already did all four: it +rejects a model that declares no bound on its speed control at `configure()`, +before any speed limit can reach `updateIneq`. A stack that uses it sees no +change. + +## The bicycle model + +`prox_mpc_core/Bicycle` still resolves and still loads. It is now a deprecated +alias for `prox_mpc_core/BicycleFrontAxle`, warns once per process, and is +removed in the next major release. The warning names both changes below, so an +operator who reads only the log still learns that the alias is not the model +1.0.0 gave them. Two things about it changed: + +- `toTwist()` returns the body twist of `base_link`. Its `linear.x` is + `v cos(delta)`, the projection of the front-wheel speed on the body axis, not + the front-wheel speed itself. `angular.z` is unchanged. +- The bundled controller now transforms the model's pose to `base_link` before + the footprint check, and derives the steering reference for the front axle + (`asin(L * kappa)`) rather than for the rear axle (`atan(L * kappa)`). + +Select `prox_mpc_core/BicycleRearAxle` for a vehicle whose model state refers to +the rear axle. It propagates `v cos(theta)` with `theta_dot = v tan(delta) / L`, +declares its reference point at the `base_link` origin, and bounds its steering +angle at 1.0 rad, because its yaw law diverges as the angle approaches `pi/2`. + +## The coupled obstacle constraint + +The discrete-time CBF constraint now carries the previous node's clearance +gradient, completing a linearisation that was first-order exact in one node's +position only. + +Two further corrections land with it, both gated on `cbf_gamma < 1` and both +inert at the shipped default. The first coupled constraint compares the clearance +at the current pose against the clearance one step ahead; the obstacle position +used on the current-pose side is now the obstacle's position *now*, recovered by +extending the first two blocks backward. It was previously the obstacle's +one-step-ahead position, which evaluated the two sides at different obstacle times +and was anti-conservative for a closing obstacle. Measured closed loop against a +0.5 m/s crossing obstacle, the realized closest approach moves by at most 0.2 mm, +in the direction of more clearance; a static fill is bit-identical, because its +blocks are equal and the reconstruction returns the first one unchanged. + +The gradient columns the first node would have written are also dropped. The +initial state is pinned to the current pose by an identity equality, so those +coefficients could never influence the solution while still enlarging the +constraint matrix. The nonzero count at the bundled configuration falls from 238 +to 236 below `cbf_gamma = 1.0` and stays at 198 at it. + +At the shipped `cbf_gamma = 1.0` nothing changes: the block is not written, so +it does not enter the constraint matrix's sparsity pattern, and the constraint +matrix's nonzero count at the bundled configuration is unchanged. + +Below 1.0 the mode behaves as the rate condition it is, which it did not before: +the clearance is allowed to decay toward the keep-out as `cbf_gamma` falls, +producing a closer and less lateral pass. Measured on the bundled fixture with a +1.0 m keep-out, closest approach moves from 0.906 m to 0.793 m at +`cbf_gamma = 0.3` and from 0.910 m to 0.860 m at 0.5. A configuration that lowers +`cbf_gamma` should re-check its `robot_radius` and `safety_margin` against that. + +## Deliberately not done + +`Model::getIneq()` still returns `const std::map> &`, +with the bound's vector index stored as a `double` in the value. Changing the +index to an integral type is a source and ABI break on a released signature that +every out-of-tree model compiles against, for a typing improvement the existing +range validation already covers at the point of use. It is left as it is. diff --git a/prox_mpc_core/doc/nmpc.md b/prox_mpc_core/doc/nmpc.md index bcafb52..13c29cf 100644 --- a/prox_mpc_core/doc/nmpc.md +++ b/prox_mpc_core/doc/nmpc.md @@ -39,8 +39,14 @@ three hooks (`updateA`, `updateB`, `updatec`): - `updatec(dt, x_next)` fills the residual $c_k$ of the Euler step, $c_k = x_k - x_{k+1} + \Delta t\, f(x_k, u_k)$. -For the kinematic bicycle with state $x = [p_x, p_y, \theta, \delta]^\top$ and -input $u = [v, \dot{\delta}]^\top$ (wheelbase $L$), the residual is +`prox_mpc_core` ships two internally-consistent bicycle plugins that differ in +which point of the vehicle the state $(p_x, p_y)$ refers to. + +For `prox_mpc_core/BicycleFrontAxle`, with state +$x = [p_x, p_y, \theta, \delta]^\top$ and input $u = [v, \dot{\delta}]^\top$ +(wheelbase $L$), $(p_x, p_y)$ is the **front-axle** centre and $v$ is the +front-wheel speed, so the front wheel travels along $\theta + \delta$ and the +residual is $$ c_k = @@ -53,11 +59,24 @@ x_k^{(3)} - x_{k+1}^{(3)} + \Delta t\, \dot{\delta}_k $$ and $A_k$, $B_k$ are its analytic Jacobians. -The yaw-rate term uses $v_k \sin(\delta_k)/L$ by design, not the textbook -$v_k \tan(\delta_k)/L$: this is a deliberate modeling choice, applied consistently -across `updatec`, `updateA`, `updateB`, and `toTwist`, so it is not a typo - the -two agree for small steering angles and the analytic Jacobians match the $\sin$ -form exactly. +With the position propagated as $v \cos(\theta + \delta)$, +$v \sin(\theta + \delta)$, the yaw-rate term $v_k \sin(\delta_k)/L$ is the +**exact** front-axle yaw rate of that same parameterization, not a small-angle +approximation of anything: the front wheel's own heading is $\theta + \delta$, +and $L$ is the distance from $(p_x, p_y)$ back to the point the yaw pivots +about. + +`prox_mpc_core/BicycleRearAxle` instead references $(p_x, p_y)$ to the +**rear-axle** centre, so $v$ is the rear-axle (body) speed, the rear axle +travels along $\theta$ alone, and the residual uses $v_k \cos(\theta_k)$, +$v_k \sin(\theta_k)$, and the textbook $v_k \tan(\delta_k)/L$ - exact for that +parameterization by the same reasoning, with $\sin$ and $\tan$ swapped because +the reference point moved from the front axle to the rear. + +Both plugins are internally consistent end to end: `getPlanarMapping()` +declares which physical point $(p_x, p_y)$ refers to (`ref_offset_x = L` for +the front axle, `0` for the rear axle), and `toTwist()` reports the resulting +`base_link` twist for that same point rather than mixing conventions. A purely linear model returns constant $A$, $B$ and a trivial residual; the SQP then converges in a single QP solve. @@ -161,18 +180,41 @@ w \mathrel{+}= \Delta w, \qquad \text{until } \texttt{status} = \text{SOLVED} \text{ or } k \ge k_{\max}. $$ -The retry count is bounded by `max_iter_sqp` (100 by default) and, when set, by -the `max_solve_time` wall-clock budget, so a failing sub-problem cannot overrun -the control cycle. Because the loop terminates on the first converged QP rather -than on an increment-norm test, it is a real-time-iteration scheme: each cycle -contributes one linearization, and a nonlinear model refines its linearization -across successive control cycles through the warm start rather than within a -single call. +The retry count is bounded by `max_iter_sqp` (1 by default, the real-time +iteration) and, when set, by the `max_solve_time` wall-clock budget. +A retry cap above 1 multiplies the cost of a non-converged sub-problem by that +cap within the one cycle, because the loop re-solves rather than deferring to +the next control period. +The budget is tested only between SQP sub-problem solves, never while one is in +flight, so it cannot interrupt a slow QP and does not bound worst-case cycle +latency in either direction: a loop that exceeds it simply stops early with +whatever status the last QP returned, which is `PROXQP_SOLVED` when that QP +itself converged. +The bound that genuinely holds every cycle is the iteration caps, not the +wall-clock budget. +Because the loop terminates on the first converged QP **sub-problem** rather +than on a nonlinear increment-norm, KKT, or merit-function test, the nominal +cycle described above - one linearize-solve-update pass - is a real-time- +iteration scheme: each such cycle contributes one linearization, and a +nonlinear model refines its linearization across successive control cycles +through the warm start rather than within a single call. +`max_iter_sqp = 1` makes that scheme unconditional, independent of +`max_solve_time`: exactly one QP sub-problem per cycle, whether or not it +converges. ### Convergence and failure reporting -After the loop, `qp_info.status` equals `PROXQP_SOLVED` only when the SQP -converged; `sqp_iter` and `qp_iter_ext` report the iteration counts. +After the loop, `qp_info.status` equals `PROXQP_SOLVED` when the last QP +**sub-problem** converged - a statement about that one convex QP, not about +nonlinear convergence of the original problem. +No nonlinear residual, KKT, merit-function, or increment-norm test exists +anywhere in the loop, so `PROXQP_SOLVED` is the only convergence signal the +caller can observe. +It is also what `prox_mpc_msgs/SolverDiagnostics`'s `converged` field is +derived from, gated further by the controller's own finiteness and +command-acceptance checks before publication (see +[`prox_mpc_controller/doc/architecture.md`](../../prox_mpc_controller/doc/architecture.md)). +`sqp_iter` and `qp_iter_ext` report the iteration counts. On non-convergence `MPC::solve` takes **no safety action**: it returns the last (non-converged) iterate, keeps the previous command as the warm-start reference, and leaves the fallback to the caller. @@ -205,8 +247,31 @@ sequenceDiagram The QP is solved in **sparse** mode by default (`qp_type = false`); a dense path exists for small problems (`qp_type = true`). -The QP is re-initialized with fresh matrices each solve, and `guess` selects -between ProxQP's own cheap starts: the equality-constrained guess (`true`, the -default) or no initial guess (`false`). -The trajectory-level warm start in `MPC::solve` slides the previous solution +There are two warm starts, at different levels, and they are independent. + +The **trajectory-level** warm start in `MPC::solve` slides the previous solution forward one step before re-linearizing. +It is always on and is what makes the real-time iteration scheme work. + +The **solver-level** warm start is `warm_start` (`true` by default). +With it on, the ProxQP workspace is built once and updated in place, so the +factorization and the previous primal/dual iterate survive between cycles and +ProxQP starts from the previous solution rather than from scratch. +With it off, the QP is re-initialized with fresh matrices each solve and only +ProxQP's own cheap starts apply, which is what `guess` selects between: the +equality-constrained guess (`true`, the default) or no initial guess (`false`). +`guess` also selects the policy on the update path, where `true` means +`WARM_START` and `false` still means no guess. + +`WARM_START` is used rather than `WARM_START_WITH_PREVIOUS_RESULT` because the +latter also carries the proximal step sizes across solves; unused obstacle slots +are padded with a far sentinel whose rows are ~1e6 in magnitude, so step sizes +tuned against that scaling would cripple the next solve. + +In-place update requires the sparsity structure to stay fixed - ProxQP silently +ignores an update whose pattern moved, which would drop the keep-out rows. +The structure is therefore declared once at `init()` from the positions `setE` +and `setC` write, and the values are written into it each cycle, structural +zeros included. +A pattern taken from `sparseView()` would not do: the half-plane normals and the +model Jacobians pass through zero as the trajectory evolves. diff --git a/prox_mpc_core/doc/obstacle-avoidance.md b/prox_mpc_core/doc/obstacle-avoidance.md index e4d9abe..00071b1 100644 --- a/prox_mpc_core/doc/obstacle-avoidance.md +++ b/prox_mpc_core/doc/obstacle-avoidance.md @@ -10,6 +10,12 @@ design see [architecture.md](architecture.md). At each predicted node `k` the robot has a planar position $p_k = (x_k, y_k)$. +Where those two components sit inside the model's state vector is the model's +own business: the assembly reads their indices from `Model::getPlanarMapping()`, +so a state ordered `[x, y, yaw, ...]` and one ordered `[yaw, x, y]` are both +constrained on their real position axes. +`ProxQP::init()` reads the pair once, and rejects a model that places either +index outside its own state vector or places both at the same index. An obstacle is reduced to a point $o = (o_x, o_y)$ with a required clearance $d_\text{safe}$, which already folds in the robot radius, the obstacle inflation, and a safety margin. @@ -188,33 +194,76 @@ Instead of demanding absolute safety at every node, this only requires the safet margin to **decay no faster than the rate $\gamma$**, which stays feasible while the robot advances and removes the stay-put local optimum. With $\gamma = 1$ it reduces exactly to the pointwise constraint $h(p_{k+1}) \ge 0$, so the parameter -default preserves the original behavior bit-for-bit. +default preserves the original behavior bit-for-bit - the coupling below is +skipped altogether at that default rather than merely evaluating to zero, so it +adds nothing to the assembled QP's sparsity pattern. -In increment form, with the slack and the previous-node signed distance $h(p_k)$ -held constant per SQP iteration (only the constrained node $k+1$ is linearized; -the re-linearization across iterations recovers the exact value): +Both sides of the coupling depend on a position, so both are linearized to +first order about the current SQP iterate. In increment form, with the slack +held constant per SQP iteration: $$ -n^\top \Delta p_{k+1} + \Delta w \ge (1 - \gamma)\, h(p_k) - h(p_{k+1}) - w. +n_{k+1}^\top \Delta p_{k+1} - (1 - \gamma)\, n_k^\top \Delta p_k + \Delta w +\ge (1 - \gamma)\, h(p_k) - h(p_{k+1}) - w. $$ ```text setC : obs_h_prev = ||p_k - o_k|| - d_safe (signed distance at the previous node) + C(row, p_k) += -(1 - cbf_gamma) * n_k (previous-node gradient block, node >= 1) setd : low(row) = (1 - cbf_gamma) * obs_h_prev - obs_h - w ``` -Here $o_k$ is the obstacle position **at the previous node's time**: with a static -fill $o_k = o_{k+1}$, but with the predictive (moving) fill each node carries a -different obstacle position, so $h(p_k)$ uses the previous node's obstacle slot -(`obs[slot - max_obs]`). Node $k = 0$ is the fixed current pose, so it reuses the -node-1 obstacle. Only the constrained node's gradient $n^\top \Delta p_{k+1}$ enters -$C$; the previous node's signed distance is held constant per SQP iteration, which is -exact at convergence. +Here $o_k$ is the obstacle position **at the previous node's time**: with a +static (costmap) fill $o_k = o_{k+1}$ for every slot, because the controller +binds each scanned object to a fixed slot across every node it appears at +rather than re-selecting independently per node; with the predictive (moving) +fill each node already carries a different, tracked position for the same +slot. Node $k = 0$ is the fixed current pose, for which the obstacle matrix +carries no dedicated block; its position is reconstructed by extrapolating the +first two blocks backward, $o_0 = 2\,o(\text{block }0) - o(\text{block }1)$, +exact for both the static and the constant-velocity fill. + +That extrapolation amplifies whatever error the two blocks carry, as +$2 e_1 - e_2$, so it is applied only where the two blocks describe motion +rather than noise. +The test is the implied inter-block displacement: above `kMaxObsSpeed * dt`, a +compile-time constant fixed at `10.0` m/s in `proxqp.cpp`, the step is treated +as noise and the first block is used unchanged, which is the pre-reconstruction +behaviour for that slot. +The bound is a sanity limit rather than a tuning knob - nothing this controller +plans around, tracked or scanned, closes at ten metres per second - and it is +deliberately far above any real obstacle speed so that it never rejects genuine +motion. +The fallback is silent: it is a per-slot, per-cycle decision on the QP assembly +hot path, so it emits no log line, and a tracker publishing an apparent step +above the bound is corrected by the constraint's own conservatism rather than +reported. +The previous-node gradient term $n_k^\top \Delta p_k$ is written only for +$k \ge 1$: $\Delta p_0$ is pinned to zero by the initial-state equality, so a +node-0 gradient column could never influence the solution and would only +enlarge the constraint matrix's sparsity pattern for no benefit. +Below `1.0` the core also guards against a degenerate pairing: if either +node's obstacle slot holds the unused-slot far sentinel, the previous-node +terms (value and gradient alike) are left at zero and the row falls back to +the plain pointwise constraint for that node, rather than comparing a real +obstacle against an out-of-range placeholder. + +Because the SQP loop exits as soon as one QP sub-problem reports `SOLVED` (see +[nmpc.md](nmpc.md)), a control cycle typically performs exactly one linearize +step rather than iterating within the cycle: the coupling above is first-order +exact in both nodes' positions **at the current iterate**, and that iterate is +refined cycle to cycle through the warm start rather than by re-linearizing +within one call. The rate $\gamma$ is the `cbf_gamma` parameter, forwarded from the controller through `MPC::setCbfGamma`. This lets the predictive NMPC obstacle term run alongside Nav2's planner/costmaps: Nav2 replans the global path while the MPC predicts the robot against per-node obstacles over the horizon. +The coupling is enforced through the slack penalty like every other obstacle +row, not as a hard barrier: at the shipped `w_weight`, whether a value of +`cbf_gamma` below `1.0` measurably changes a trajectory has not yet been +benchmarked (see [control-law.md](../../prox_mpc_controller/doc/control-law.md) +for the controller-side guidance this implies). ## Bounded capacity and the far sentinel @@ -240,9 +289,10 @@ coupling on whatever positions it is handed. Two fills exist on the controller side, both writing the same `setObs` contract: - **static (costmap)** - the default. For each node the controller scans the - local costmap around the robot's *reference* position and emits the nearest - occupied cells. The obstacle position varies across nodes only because the robot - moves, so the term constrains the robot against where obstacles are *now*. + local costmap around the robot's *nominal predicted* position for that node + and emits the nearest occupied cells. The obstacle position varies across + nodes only because the robot moves, so the term constrains the robot against + where obstacles are *now*. - **predictive (tracked obstacles)** - opt-in. A dynamic track is propagated along its tracker-sampled predicted trajectory (the IMM CV+CTRV forward prediction), or a constant-velocity ray $o_{k,j} = p_j + v_j\,\Delta t_k$ as the @@ -255,17 +305,18 @@ Because both fills produce identical `(node, slot)` triples, the CBF coupling an the rest of this derivation are unchanged. The predictive fill is specified in the controller's [control-law.md](../../prox_mpc_controller/doc/control-law.md). -## Footprint: disc here, exact polygon elsewhere +## Footprint: disc here, polygon elsewhere The core treats the robot as a **disc** whose radius is folded into $d_\text{safe}$. A disc is rotation-invariant, so the half-plane needs only the position, not the heading, which keeps the constraint simple and convex. -Exact polygon-footprint collision checking is intentionally **not** done in the +Polygon-footprint collision checking is intentionally **not** done in the optimizer; it belongs to a separate safety layer (for example a collision monitor or a footprint collision checker) that can veto a command the optimizer produced. Separating an approximate, fast, convex avoidance term in the optimizer from an -exact, conservative safety check is the conventional division of responsibility. +outline-only footprint check outside it is the conventional division of +responsibility. ## Why this is the common choice @@ -295,8 +346,14 @@ ProxMPC is. ## Numerical guard -When the predicted position coincides with the obstacle, $\lVert p_k - o \rVert$ -is zero and the normal $n = (p_k - o) / \lVert p_k - o \rVert$ is undefined. -The norm is therefore floored at a small constant before the division, which -avoids injecting `NaN` into the QP at the cost of an arbitrary (but bounded) -normal direction in that degenerate instant. +When the predicted position coincides with, or nearly coincides with, the +obstacle, $\lVert p_k - o \rVert$ is at or near zero and the normal +$n = (p_k - o) / \lVert p_k - o \rVert$ carries no reliable escape direction: +dividing by a merely-floored norm would still emit a near-zero or non-unit +vector, silently down-scaling the constraint row instead of fixing it. +Below the same small-norm threshold the code therefore substitutes a +deterministic unit fallback direction ($n = (1, 0)$) rather than dividing at +all. The constraint row still carries a full-magnitude, if arbitrary, escape +direction in that degenerate instant, and the slack is what actually resists a +collision until the robot's own motion breaks the coincidence and a real +gradient returns. diff --git a/prox_mpc_core/include/prox_mpc/model.hpp b/prox_mpc_core/include/prox_mpc/model.hpp index b8dfcca..f6a4832 100644 --- a/prox_mpc_core/include/prox_mpc/model.hpp +++ b/prox_mpc_core/include/prox_mpc/model.hpp @@ -4,6 +4,7 @@ #ifndef PROX_MPC__MODEL_HPP_ #define PROX_MPC__MODEL_HPP_ +#include #include #include #include @@ -42,18 +43,18 @@ class Model : public ModelInfo, private Constraints /* Set */ - void setName(std::string name); - void setN(size_t n); - void setM(size_t m); - void setParams(const VectorXd & params); - void setc(const VectorXd & c); - void setA(const MatrixXd & A); - void setB(const MatrixXd & B); + void setName(std::string new_name); + void setN(size_t new_n); + void setM(size_t new_m); + void setParams(const VectorXd & new_params); + void setc(const VectorXd & new_c); + void setA(const MatrixXd & new_A); + void setB(const MatrixXd & new_B); void setIneq(std::string var, size_t idx_vec, double low, double upp); void updateIneq(std::string var, size_t idx_vec, double low, double upp); - void setObsAvoid(bool obs_flag); - void setX(const VectorXd & x); - void setU(const VectorXd & u); + void setObsAvoid(bool new_obs_flag); + void setX(const VectorXd & new_x); + void setU(const VectorXd & new_u); /* Virtual set functions */ @@ -79,25 +80,80 @@ class Model : public ModelInfo, private Constraints * the default constructor required for runtime loading, where parameters cannot * be passed in. The default implementation reads no keys; an overriding model * applies any present key and keeps its constructor value for any absent key. - * @param params model constants by name (e.g. "L"); absent keys keep the literal. + * @param config_params model constants by name (e.g. "L"); absent keys keep the literal. */ - virtual void configure([[maybe_unused]] const std::map & params) {} + virtual void configure( + [[maybe_unused]] const std::map & config_params) {} /*! * Map a control vector to a body Twist message. * The default is the identity mapping (first control -> linear.x, second * control -> angular.z). Models whose control is not a body twist (for example * a steering rate) override this. - * @param u control vector (length m). + * @param u_in control vector (length m). */ - virtual geometry_msgs::msg::Twist toTwist(const VectorXd & u) const + virtual geometry_msgs::msg::Twist toTwist(const VectorXd & u_in) const { geometry_msgs::msg::Twist twist; - if (u.size() > 0) {twist.linear.x = u(0);} - if (u.size() > 1) {twist.angular.z = u(1);} + if (u_in.size() > 0) {twist.linear.x = u_in(0);} + if (u_in.size() > 1) {twist.angular.z = u_in(1);} return twist; } + /*! + * Declare how this model's state and control vectors map onto the planar + * quantities a Nav2 consumer drives: which state entries carry x, y and yaw, + * which control entry carries the signed longitudinal speed, whether a + * steering angle is carried and where, where the point the state refers to + * sits in base_link, and the wheelbase the steering geometry is defined on. + * + * The default reproduces the convention the bundled models and the bundled + * controller followed before this hook existed: state [x, y, yaw, (delta)], + * control [v, delta_dot], the state referenced to base_link, and, for any + * model carrying more than three states, a steering angle at state index 3 + * whose rate is control index 1. The wheelbase is left at 0, which a consumer + * reads as undeclared; a model that carries a steering angle must override + * this and declare one. + * + * Read once at the consumer's configuration time, so it is not a control-loop + * query and may build its result. + */ + virtual PlanarMapping getPlanarMapping() const + { + PlanarMapping mapping; + if (this->n > 3) { + mapping.idx_steering = 3; + if (this->m > 1) {mapping.idx_steer_rate = 1;} + } + return mapping; + } + + /*! + * Map a body Twist back to a control vector: the inverse of toTwist() for the + * channels a twist can determine, and a non-finite entry for every channel it + * cannot. A planar twist carries two usable degrees of freedom, so a model + * with more controls than that - or one whose control is a rate the twist + * does not observe, a steering rate for instance - leaves those channels + * undetermined and the caller decides what to do with them. + * + * The default is the inverse of the default toTwist(): linear.x into control + * 0 and angular.z into control 1, with every further channel undetermined. A + * model that overrides toTwist() and whose controls are still recoverable + * from a twist overrides this as well, or the two mappings disagree. + * + * Appended last on purpose: it takes the final vtable slot, so an existing + * plugin keeps the layout it was compiled against for every earlier virtual. + * @param twist body twist. + */ + virtual VectorXd fromTwist(const geometry_msgs::msg::Twist & twist) const + { + VectorXd u_out = VectorXd::Constant( + static_cast(this->m), std::numeric_limits::quiet_NaN()); + if (u_out.size() > 0) {u_out(0) = twist.linear.x;} + if (u_out.size() > 1) {u_out(1) = twist.angular.z;} + return u_out; + } + /* Get */ std::string getName(); @@ -117,14 +173,14 @@ class Model : public ModelInfo, private Constraints * Override one inequality bound from a configure() params map, keeping the * current (constructor) value for any side whose key is absent. The bound for * idx_vec must already exist (declared in the constructor via setIneq). - * @param params configure() params map. + * @param config_params configure() params map. * @param var "x", "u", "du" or "w". * @param idx_vec vector index whose bound is overridden. * @param key_low params key for the lower bound (kept current if absent). * @param key_upp params key for the upper bound (kept current if absent). */ void overrideBound( - const std::map & params, std::string var, size_t idx_vec, + const std::map & config_params, std::string var, size_t idx_vec, std::string key_low, std::string key_upp); }; diff --git a/prox_mpc_core/include/prox_mpc/models/bicycle.hpp b/prox_mpc_core/include/prox_mpc/models/bicycle.hpp index 5a654fd..3d75826 100644 --- a/prox_mpc_core/include/prox_mpc/models/bicycle.hpp +++ b/prox_mpc_core/include/prox_mpc/models/bicycle.hpp @@ -4,111 +4,48 @@ #ifndef PROX_MPC__MODELS__BICYCLE_HPP_ #define PROX_MPC__MODELS__BICYCLE_HPP_ -#include -#include -#include +#include -#include +#include -#include -#include +#include namespace prox_mpc { -/* Kinematic bicycle model. */ -class Bicycle : public Model +/// Deprecated alias for BicycleFrontAxle. +/// +/// The bicycle ships as two plugins, one per reference point, so the geometry is +/// unambiguous at the point of selection. This name predates that split and +/// resolves to the front-axle model, which is what its dynamics always were. It +/// keeps a configuration written against the previous release loading, warns +/// once per process, and is removed in the next major release. +/// +/// Its emitted twist and the pose it presents for a collision check are the +/// front-axle model's corrected ones, not the previous release's; the two +/// differ, and the difference is deliberate. +class Bicycle : public BicycleFrontAxle { public: Bicycle() { setName("bicycle"); - - setN(4); // state: [x, y, theta, delta] - setM(2); // control: [v, delta_dot] - - double L = 1.6; // wheelbase [m] - VectorXd params(1); - params << L; - setParams(params); - - setA(MatrixXd::Zero(getN(), getN())); - setB(MatrixXd::Zero(getN(), getM())); - setc(VectorXd::Zero(getN())); - - setIneq("x", 3, -M_PI / 2, M_PI / 2); // steering angle [rad] - setIneq("u", 0, -3.0, 3.0); // linear velocity [m/s] - setIneq("u", 1, -1., 1.); // steering rate [rad/s] - setIneq("du", 0, -.5, .5); // linear acceleration [m/s^2] - setIneq("du", 1, -.5, .5); // steering acceleration [rad/s^2] - - setObsAvoid(true); // this model supports obstacle avoidance - } - - /*! - * Configure the model constants from a params map. Absent keys keep the - * constructor literals, so an empty map reproduces the hardcoded values. - * Keys: "L" (wheelbase); bound limits "delta_min"/"delta_max" (x[3]), - * "v_min"/"v_max" (u[0]), "delta_rate_min"/"delta_rate_max" (u[1]), - * "a_min"/"a_max" (du[0]), "delta_acc_min"/"delta_acc_max" (du[1]). - */ - void configure(const std::map & params) override - { - if (params.count("L") > 0) { - // The wheelbase divides the yaw and steering Jacobians; a non-positive - // value makes A, B and c non-finite and poisons the whole QP. - if (!(params.at("L") > 0.0)) { - throw std::invalid_argument("Bicycle::configure: L must be > 0"); - } - VectorXd p(1); - p << params.at("L"); - setParams(p); - } - overrideBound(params, "x", 3, "delta_min", "delta_max"); - overrideBound(params, "u", 0, "v_min", "v_max"); - overrideBound(params, "u", 1, "delta_rate_min", "delta_rate_max"); - overrideBound(params, "du", 0, "a_min", "a_max"); - overrideBound(params, "du", 1, "delta_acc_min", "delta_acc_max"); - } - - /*! - * Map control [v, delta_dot] to a body twist. The bicycle's second control is - * a steering rate, not a yaw rate, so the yaw rate is derived from the current - * steering state delta: omega = v * sin(delta) / L. The caller must have set - * the model state (delta at index 3) to the current state before calling. - */ - geometry_msgs::msg::Twist toTwist(const VectorXd & u) const override - { - geometry_msgs::msg::Twist twist; - twist.linear.x = u(0); // forward speed v - twist.angular.z = u(0) * sin(this->x(3)) / this->params(0); // omega = v sin(delta)/L - return twist; - } - - void updatec(double dt, VectorXd x_next) override - { - c << getX()(0) - x_next(0) + dt * getU()(0) * cos(getX()(2) + getX()(3)), - getX()(1) - x_next(1) + dt * getU()(0) * sin(getX()(2) + getX()(3)), - getX()(2) - x_next(2) + dt * getU()(0) * sin(getX()(3)) / getParams()[0], - getX()(3) - x_next(3) + dt * getU()(1); - } - - void updateA(double dt) override - { - A << 1.0, 0.0, -dt * getU()(0) * sin(getX()(2) + getX()(3)), - -dt * getU()(0) * sin(getX()(2) + getX()(3)), - 0.0, 1.0, +dt * getU()(0) * cos(getX()(2) + getX()(3)), - +dt * getU()(0) * cos(getX()(2) + getX()(3)), - 0.0, 0.0, 1.0, +dt * getU()(0) * cos(getX()(3)) / getParams()[0], - 0.0, 0.0, 0.0, 1.0; - } - - void updateB() override - { - B << cos(getX()(2) + getX()(3)), 0.0, - sin(getX()(2) + getX()(3)), 0.0, - sin(getX()(3)) / getParams()[0], 0.0, - 0.0, 1.0; + /* Once per process rather than once per construction: the text is identical + * every time, and a consumer that constructs the model more than once - a + * test binary, a controller reconfigured at runtime - would otherwise repeat + * it into the operational log for no added information. */ + static std::once_flag warned; + std::call_once( + warned, []() { + RCLCPP_WARN( + rclcpp::get_logger("prox_mpc_core"), + "Model 'prox_mpc_core/Bicycle' is deprecated and resolves to " + "'prox_mpc_core/BicycleFrontAxle'; select that name, or " + "'prox_mpc_core/BicycleRearAxle' for a rear-axle-referenced vehicle. " + "The alias is not the previous release's model: the twist it emits and " + "the pose it presents for a collision check are both the corrected " + "front-axle ones. The alias is removed in the next major release."); + }); } }; diff --git a/prox_mpc_core/include/prox_mpc/models/bicycle_front_axle.hpp b/prox_mpc_core/include/prox_mpc/models/bicycle_front_axle.hpp new file mode 100644 index 0000000..91c4dc7 --- /dev/null +++ b/prox_mpc_core/include/prox_mpc/models/bicycle_front_axle.hpp @@ -0,0 +1,172 @@ +// Copyright 2026 Simone Contorno +// SPDX-License-Identifier: Apache-2.0 + +#ifndef PROX_MPC__MODELS__BICYCLE_FRONT_AXLE_HPP_ +#define PROX_MPC__MODELS__BICYCLE_FRONT_AXLE_HPP_ + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +namespace prox_mpc +{ + +/// Kinematic bicycle referenced to the FRONT axle. +/// +/// State [x, y, theta, delta] (n=4) and control [v, delta_dot] (m=2), where +/// (x, y) is the front-axle centre, theta the body heading, delta the steering +/// angle and v the front-wheel speed. The front wheel travels along +/// theta + delta, so the propagation is +/// +/// x_dot = v cos(theta + delta), y_dot = v sin(theta + delta), +/// theta_dot = v sin(delta) / L, delta_dot = u[1]. +/// +/// Every consumer-facing quantity refers to that same front-axle point: +/// getPlanarMapping() declares the reference point at (L, 0) in base_link, so a +/// consumer transforms the pose back to base_link before a footprint check, and +/// toTwist() reports the body twist of base_link, whose longitudinal speed is +/// v cos(delta) rather than the front-wheel speed v. +/// +/// base_link is assumed to sit on the rear axle, which is the ROS convention for +/// a car-like base and what the declared reference offset encodes. +class BicycleFrontAxle : public Model +{ +public: + BicycleFrontAxle() + { + setName("bicycle_front_axle"); + + setN(4); // state: [x, y, theta, delta] + setM(2); // control: [v, delta_dot] + + double L = 1.6; // wheelbase [m] + VectorXd init_params(1); + init_params << L; + setParams(init_params); + + setA(MatrixXd::Zero(getN(), getN())); + setB(MatrixXd::Zero(getN(), getM())); + setc(VectorXd::Zero(getN())); + + setIneq("x", 3, -M_PI / 2, M_PI / 2); // steering angle [rad] + setIneq("u", 0, -3.0, 3.0); // linear velocity [m/s] + setIneq("u", 1, -1., 1.); // steering rate [rad/s] + setIneq("du", 0, -.5, .5); // linear acceleration [m/s^2] + setIneq("du", 1, -.5, .5); // steering acceleration [rad/s^2] + + setObsAvoid(true); // this model supports obstacle avoidance + } + + /*! + * Configure the model constants from a params map. Absent keys keep the + * constructor literals, so an empty map reproduces the hardcoded values. + * Keys: "L" (wheelbase); bound limits "delta_min"/"delta_max" (x[3]), + * "v_min"/"v_max" (u[0]), "delta_rate_min"/"delta_rate_max" (u[1]), + * "a_min"/"a_max" (du[0]), "delta_acc_min"/"delta_acc_max" (du[1]). + */ + void configure(const std::map & config_params) override + { + if (config_params.count("L") > 0) { + // The wheelbase divides the yaw and steering Jacobians; a non-positive + // value makes A, B and c non-finite and poisons the whole QP. + if (!(config_params.at("L") > 0.0)) { + throw std::invalid_argument("BicycleFrontAxle::configure: L must be > 0"); + } + VectorXd p(1); + p << config_params.at("L"); + setParams(p); + } + overrideBound(config_params, "x", 3, "delta_min", "delta_max"); + overrideBound(config_params, "u", 0, "v_min", "v_max"); + overrideBound(config_params, "u", 1, "delta_rate_min", "delta_rate_max"); + overrideBound(config_params, "du", 0, "a_min", "a_max"); + overrideBound(config_params, "du", 1, "delta_acc_min", "delta_acc_max"); + } + + /*! + * The state's (x, y) is the front axle, one wheelbase ahead of base_link on + * the body x axis, the steering angle is state index 3 and its rate is + * control index 1. + */ + PlanarMapping getPlanarMapping() const override + { + PlanarMapping mapping; + mapping.idx_steering = 3; + mapping.idx_steer_rate = 1; + mapping.ref_offset_x = this->params(0); + mapping.wheelbase = this->params(0); + return mapping; + } + + /*! + * Map control [v, delta_dot] to the body twist of base_link. v is the + * front-wheel speed, whose projection on the body x axis is v cos(delta); the + * yaw rate is v sin(delta) / L. The caller must have set the model state + * (delta at index 3) to the current state before calling. + */ + geometry_msgs::msg::Twist toTwist(const VectorXd & u_in) const override + { + geometry_msgs::msg::Twist twist; + twist.linear.x = u_in(0) * cos(this->x(3)); // base_link speed + twist.angular.z = u_in(0) * sin(this->x(3)) / this->params(0); // omega = v sin(delta)/L + return twist; + } + + /*! + * Recover the front-wheel speed from a base_link twist. toTwist() emits + * linear.x = v cos(delta) and angular.z = v sin(delta) / L, so + * v = sign(linear.x) sqrt(linear.x^2 + (angular.z L)^2) inverts the pair + * without dividing by cos(delta), which vanishes at this model's own + * +/- pi/2 steering bound. The projection carries no direction at + * linear.x == 0, where the sign is taken as forward. + * + * The steering rate is left undetermined: a twist shows the steering angle's + * effect, not the rate the angle is changing at. + */ + VectorXd fromTwist(const geometry_msgs::msg::Twist & twist) const override + { + VectorXd u_out = VectorXd::Constant(2, std::numeric_limits::quiet_NaN()); + const double wheel_arc = twist.angular.z * this->params(0); + const double speed = std::sqrt(twist.linear.x * twist.linear.x + wheel_arc * wheel_arc); + u_out(0) = (twist.linear.x < 0.0) ? -speed : speed; + return u_out; + } + + void updatec(double dt, VectorXd x_next) override + { + c << getX()(0) - x_next(0) + dt * getU()(0) * cos(getX()(2) + getX()(3)), + getX()(1) - x_next(1) + dt * getU()(0) * sin(getX()(2) + getX()(3)), + getX()(2) - x_next(2) + dt * getU()(0) * sin(getX()(3)) / getParams()[0], + getX()(3) - x_next(3) + dt * getU()(1); + } + + void updateA(double dt) override + { + A << 1.0, 0.0, -dt * getU()(0) * sin(getX()(2) + getX()(3)), + -dt * getU()(0) * sin(getX()(2) + getX()(3)), + 0.0, 1.0, +dt * getU()(0) * cos(getX()(2) + getX()(3)), + +dt * getU()(0) * cos(getX()(2) + getX()(3)), + 0.0, 0.0, 1.0, +dt * getU()(0) * cos(getX()(3)) / getParams()[0], + 0.0, 0.0, 0.0, 1.0; + } + + void updateB() override + { + B << cos(getX()(2) + getX()(3)), 0.0, + sin(getX()(2) + getX()(3)), 0.0, + sin(getX()(3)) / getParams()[0], 0.0, + 0.0, 1.0; + } +}; + +} // namespace prox_mpc + +#endif // PROX_MPC__MODELS__BICYCLE_FRONT_AXLE_HPP_ diff --git a/prox_mpc_core/include/prox_mpc/models/bicycle_rear_axle.hpp b/prox_mpc_core/include/prox_mpc/models/bicycle_rear_axle.hpp new file mode 100644 index 0000000..265067d --- /dev/null +++ b/prox_mpc_core/include/prox_mpc/models/bicycle_rear_axle.hpp @@ -0,0 +1,197 @@ +// Copyright 2026 Simone Contorno +// SPDX-License-Identifier: Apache-2.0 + +#ifndef PROX_MPC__MODELS__BICYCLE_REAR_AXLE_HPP_ +#define PROX_MPC__MODELS__BICYCLE_REAR_AXLE_HPP_ + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +namespace prox_mpc +{ + +/// Kinematic bicycle referenced to the REAR axle. +/// +/// State [x, y, theta, delta] (n=4) and control [v, delta_dot] (m=2), where +/// (x, y) is the rear-axle centre, theta the body heading, delta the steering +/// angle and v the rear-axle (body) speed. The rear axle travels along theta, so +/// the propagation is +/// +/// x_dot = v cos(theta), y_dot = v sin(theta), +/// theta_dot = v tan(delta) / L, delta_dot = u[1]. +/// +/// Every consumer-facing quantity refers to that same rear-axle point: +/// getPlanarMapping() declares the reference point at the base_link origin, so +/// the pose needs no transform before a footprint check, and toTwist() reports +/// the body twist of that point directly. +/// +/// base_link is assumed to sit on the rear axle, which is the ROS convention for +/// a car-like base. +class BicycleRearAxle : public Model +{ +public: + /* The rear-axle yaw law v tan(delta) / L diverges as |delta| approaches + * pi/2, so the steering-angle bound is capped strictly inside it. */ + static constexpr double kMaxSteerAngle = 1.0; // [rad] + + BicycleRearAxle() + { + setName("bicycle_rear_axle"); + + setN(4); // state: [x, y, theta, delta] + setM(2); // control: [v, delta_dot] + + double L = 1.6; // wheelbase [m] + VectorXd init_params(1); + init_params << L; + setParams(init_params); + + setA(MatrixXd::Zero(getN(), getN())); + setB(MatrixXd::Zero(getN(), getM())); + setc(VectorXd::Zero(getN())); + + setIneq("x", 3, -kMaxSteerAngle, kMaxSteerAngle); // steering angle [rad] + setIneq("u", 0, -3.0, 3.0); // linear velocity [m/s] + setIneq("u", 1, -1., 1.); // steering rate [rad/s] + setIneq("du", 0, -.5, .5); // linear acceleration [m/s^2] + setIneq("du", 1, -.5, .5); // steering acceleration [rad/s^2] + + setObsAvoid(true); // this model supports obstacle avoidance + } + + /*! + * Configure the model constants from a params map. Absent keys keep the + * constructor literals, so an empty map reproduces the hardcoded values. + * Keys: "L" (wheelbase); bound limits "delta_min"/"delta_max" (x[3]), + * "v_min"/"v_max" (u[0]), "delta_rate_min"/"delta_rate_max" (u[1]), + * "a_min"/"a_max" (du[0]), "delta_acc_min"/"delta_acc_max" (du[1]). + * A steering bound beyond kMaxSteerAngle is rejected rather than clamped: the + * yaw law is unbounded there, so accepting it would poison A, B and c. + */ + void configure(const std::map & config_params) override + { + if (config_params.count("L") > 0) { + // The wheelbase divides the yaw and steering Jacobians; a non-positive + // value makes A, B and c non-finite and poisons the whole QP. + if (!(config_params.at("L") > 0.0)) { + throw std::invalid_argument("BicycleRearAxle::configure: L must be > 0"); + } + VectorXd p(1); + p << config_params.at("L"); + setParams(p); + } + /* Checked before the magnitude test below, which is a bare ">" and so is + * false for NaN: without this a non-finite bound would pass straight into + * overrideBound and from there into every state-bound row of the QP. */ + for (const char * key : {"delta_min", "delta_max"}) { + const auto it = config_params.find(key); + if (it != config_params.end() && !std::isfinite(it->second)) { + throw std::invalid_argument( + "BicycleRearAxle::configure: the steering-angle bound must be finite"); + } + } + if (steerBoundExceeded(config_params, "delta_min") || + steerBoundExceeded(config_params, "delta_max")) + { + throw std::invalid_argument( + "BicycleRearAxle::configure: the steering-angle bound must not exceed " + "1.0 rad in magnitude"); + } + overrideBound(config_params, "x", 3, "delta_min", "delta_max"); + overrideBound(config_params, "u", 0, "v_min", "v_max"); + overrideBound(config_params, "u", 1, "delta_rate_min", "delta_rate_max"); + overrideBound(config_params, "du", 0, "a_min", "a_max"); + overrideBound(config_params, "du", 1, "delta_acc_min", "delta_acc_max"); + } + + /*! + * The state's (x, y) is the rear axle, which is the base_link origin, and the + * steering angle is state index 3, with its rate at control index 1. + */ + PlanarMapping getPlanarMapping() const override + { + PlanarMapping mapping; + mapping.idx_steering = 3; + mapping.idx_steer_rate = 1; + mapping.wheelbase = this->params(0); + return mapping; + } + + /*! + * Map control [v, delta_dot] to the body twist of base_link. v is already the + * rear-axle speed, and the yaw rate is v tan(delta) / L. The caller must have + * set the model state (delta at index 3) to the current state before calling. + */ + geometry_msgs::msg::Twist toTwist(const VectorXd & u_in) const override + { + geometry_msgs::msg::Twist twist; + twist.linear.x = u_in(0); // base_link speed + twist.angular.z = u_in(0) * tan(this->x(3)) / this->params(0); // omega = v tan(delta)/L + return twist; + } + + /*! + * Recover the control from a base_link twist. Control 0 is already that + * frame's speed, so it is read straight out of linear.x. + * + * The steering rate is left undetermined, as it is for the front axle: a + * twist shows the steering angle's effect, not the rate the angle is + * changing at. Overridden rather than inherited for exactly that reason - + * the base class default returns angular.z in control 1, which is a body yaw + * rate, and this model's control 1 is a steering rate. + */ + VectorXd fromTwist(const geometry_msgs::msg::Twist & twist) const override + { + VectorXd u_out = VectorXd::Constant(2, std::numeric_limits::quiet_NaN()); + u_out(0) = twist.linear.x; + return u_out; + } + + void updatec(double dt, VectorXd x_next) override + { + c << getX()(0) - x_next(0) + dt * getU()(0) * cos(getX()(2)), + getX()(1) - x_next(1) + dt * getU()(0) * sin(getX()(2)), + getX()(2) - x_next(2) + dt * getU()(0) * tan(getX()(3)) / getParams()[0], + getX()(3) - x_next(3) + dt * getU()(1); + } + + void updateA(double dt) override + { + const double sec2 = 1.0 / (cos(getX()(3)) * cos(getX()(3))); + A << 1.0, 0.0, -dt * getU()(0) * sin(getX()(2)), 0.0, + 0.0, 1.0, +dt * getU()(0) * cos(getX()(2)), 0.0, + 0.0, 0.0, 1.0, +dt * getU()(0) * sec2 / getParams()[0], + 0.0, 0.0, 0.0, 1.0; + } + + void updateB() override + { + B << cos(getX()(2)), 0.0, + sin(getX()(2)), 0.0, + tan(getX()(3)) / getParams()[0], 0.0, + 0.0, 1.0; + } + +private: + /* True when the params map carries `key` with a magnitude past the bound the + * yaw law stays finite on. */ + static bool steerBoundExceeded( + const std::map & config_params, std::string key) + { + const auto it = config_params.find(key); + return it != config_params.end() && std::abs(it->second) > kMaxSteerAngle; + } +}; + +} // namespace prox_mpc + +#endif // PROX_MPC__MODELS__BICYCLE_REAR_AXLE_HPP_ diff --git a/prox_mpc_core/include/prox_mpc/models/unicycle.hpp b/prox_mpc_core/include/prox_mpc/models/unicycle.hpp index 71ec219..12fe60f 100644 --- a/prox_mpc_core/include/prox_mpc/models/unicycle.hpp +++ b/prox_mpc_core/include/prox_mpc/models/unicycle.hpp @@ -27,9 +27,9 @@ class Unicycle : public Model setM(2); // control: [v, omega] double L = 0.0; - VectorXd params(1); - params << L; - setParams(params); + VectorXd init_params(1); + init_params << L; + setParams(init_params); setA(MatrixXd::Zero(getN(), getN())); setB(MatrixXd::Zero(getN(), getM())); @@ -49,12 +49,12 @@ class Unicycle : public Model * Keys: bound limits "v_min"/"v_max" (u[0]), "w_min"/"w_max" (u[1]), * "a_min"/"a_max" (du[0]), "alpha_min"/"alpha_max" (du[1]). */ - void configure(const std::map & params) override + void configure(const std::map & config_params) override { - overrideBound(params, "u", 0, "v_min", "v_max"); - overrideBound(params, "u", 1, "w_min", "w_max"); - overrideBound(params, "du", 0, "a_min", "a_max"); - overrideBound(params, "du", 1, "alpha_min", "alpha_max"); + overrideBound(config_params, "u", 0, "v_min", "v_max"); + overrideBound(config_params, "u", 1, "w_min", "w_max"); + overrideBound(config_params, "du", 0, "a_min", "a_max"); + overrideBound(config_params, "du", 1, "alpha_min", "alpha_max"); } void updatec(double dt, VectorXd x_next) override diff --git a/prox_mpc_core/include/prox_mpc/mpc.hpp b/prox_mpc_core/include/prox_mpc/mpc.hpp index c70dd7f..3210286 100644 --- a/prox_mpc_core/include/prox_mpc/mpc.hpp +++ b/prox_mpc_core/include/prox_mpc/mpc.hpp @@ -26,7 +26,7 @@ class MPC : public ProbDim, private MPCParams /* Initialization */ - void init(std::shared_ptr model); + void init(std::shared_ptr new_model); /* ProxQP configuration */ @@ -34,29 +34,62 @@ class MPC : public ProbDim, private MPCParams /* Solving */ + /*! + * Run one SQP cycle and commit its result, the entry point this class shipped + * with. Equivalent to solveCandidate() followed by retaining the candidate + * whatever its status, with u0 advanced only on a converged solve. + */ std::tuple solve(); + /*! + * Run one SQP cycle without retaining anything: x, u, w and u0 keep the values + * they had on entry, and the caller commits with commitCandidate() once its own + * acceptance gates have passed. This is the transactional entry point. + */ + std::tuple solveCandidate(); + + /*! + * Retain the candidate produced by the last solveCandidate(), advancing x, u, w + * and u0. It is a no-op returning false unless that candidate both converged + * and is finite over the whole horizon, so a caller that never commits simply + * does not advance. + */ + bool commitCandidate(); + + /* Whether the last solveCandidate() produced finite x, u and w over the whole + * horizon. False before the first solveCandidate(). */ + bool getCandidateFinite(); + /* Set */ - void setX(MatrixXd x); - void setQ(MatrixXd Q); - void setR(MatrixXd R); - void setS(MatrixXd S); - void setW(MatrixXd W); - void setNp(size_t Np); - void setNc(size_t Nc); - void setdt(double dt); - void setT(double T); - void setPose(VectorXd pose); - void setGoalX(MatrixXd goal_x); - void setGoalU(MatrixXd goal_u); + void setX(MatrixXd new_x); + + /*! + * Set the previous control input the next cycle's rate constraint is anchored + * on. A caller that overrides the command this class produced - a deceleration + * ramp on a rejected cycle, say - sets it here so the anchor is the control + * actually applied rather than one that was never sent. + */ + void setU0(VectorXd new_u0); + void setQ(MatrixXd new_Q); + void setR(MatrixXd new_R); + void setS(MatrixXd new_S); + void setW(MatrixXd new_W); + void setNp(size_t new_Np); + void setNc(size_t new_Nc); + void setdt(double new_dt); + void setT(double new_T); + void setPose(VectorXd new_pose); + void setGoalX(MatrixXd new_goal_x); + void setGoalU(MatrixXd new_goal_u); void setMaxIntIterQP(size_t max_iter); void setMaxExtIterQP(size_t max_iter); void setMaxIterSQP(size_t max_iter); void setMaxSolveTime(double seconds); - void setGuess(bool guess); - void setQPtype(bool qp_type); - void setCbfGamma(double cbf_gamma); + void setGuess(bool new_guess); + void setWarmStart(bool new_warm_start); + void setQPtype(bool new_qp_type); + void setCbfGamma(double new_cbf_gamma); /* Get */ @@ -85,8 +118,8 @@ class MPC : public ProbDim, private MPCParams /* Obstacle avoidance */ - void setMaxObs(size_t max_obs); - void setObs(MatrixXd obs); + void setMaxObs(size_t new_max_obs); + void setObs(MatrixXd new_obs); /* Access the underlying QP solver, exposing the assembled problem for inspection. */ std::shared_ptr getSolver() {return proxqp;} @@ -113,12 +146,24 @@ class MPC : public ProbDim, private MPCParams VectorXd pose; // Current vehicle pose. MatrixXd goal_x; // State's goals. MatrixXd goal_u; // Control's goals. - bool guess = true; // Use (true) / don't use (false) warm start for initial guesses. + bool guess = true; // ProxQP cheap-start policy selector. + bool warm_start = true; // Cross-cycle QP warm start (workspace + iterate reuse). + + /* Staged result of the last solveCandidate(), retained only by commitCandidate(). */ + MatrixXd cand_x; // Candidate states. + MatrixXd cand_u; // Candidate controls. + VectorXd cand_w; // Candidate slack. + VectorXd cand_u0; // Candidate first control input. + bool cand_solved = false; // Whether the candidate's last QP converged. + bool cand_finite = false; // Whether the candidate is finite over the whole horizon. + + /* Set by init(); the structural setters reject a call made after it. */ + bool initialized = false; /* Default solver limits (centralized; override via the setters) */ static constexpr size_t kDefaultMaxExtQP = 10000; // Max QP external iterations. static constexpr size_t kDefaultMaxIntQP = 1500; // Max QP internal iterations (proximal op). - static constexpr size_t kDefaultMaxIterSQP = 100; // Max SQP iterations. + static constexpr size_t kDefaultMaxIterSQP = 1; // Max SQP iterations (real-time iteration). /* ProxQP */ std::shared_ptr proxqp; // QP solver. @@ -129,9 +174,14 @@ class MPC : public ProbDim, private MPCParams /* SQP */ size_t max_iter_sqp = kDefaultMaxIterSQP; // Max SQP iterations. - /* Optional wall-clock budget for the whole SQP loop [s]; 0 disables it (the - * iteration caps are then the only bound). When exceeded the loop stops early, - * leaving qp_info.status != PROXQP_SOLVED so the caller's fail-safe runs. */ + /* Optional soft wall-clock budget for the SQP loop [s]; 0 disables it. It is + * tested between SQP iterations, so it caps how many further QP sub-problems + * start and cannot interrupt one in flight - proxsuite offers no time-based + * stop. A loop that exceeds it stops early with whatever status the last QP + * returned, which is PROXQP_SOLVED when that QP converged, so this is not a + * worst-case latency bound and does not by itself route the caller to its + * fail-safe. The per-cycle bound is the iteration caps (max_iter_sqp = 1 for a + * bounded real-time iteration). */ double max_solve_time = 0.0; /* Discrete-time CBF rate forwarded to ProxQP (1.0 = pointwise obstacle term). */ diff --git a/prox_mpc_core/include/prox_mpc/proxqp.hpp b/prox_mpc_core/include/prox_mpc/proxqp.hpp index cec9435..040b659 100644 --- a/prox_mpc_core/include/prox_mpc/proxqp.hpp +++ b/prox_mpc_core/include/prox_mpc/proxqp.hpp @@ -28,51 +28,61 @@ class ProxQP : public MPCParams /* Initialization */ - void init(std::shared_ptr model); + void init(std::shared_ptr new_model); /* Solving */ std::tuple> solve( - MatrixXd x, MatrixXd u, const VectorXd & u_prev, VectorXd w, const MatrixXd & goal_x, - const MatrixXd & goal_u); + MatrixXd x_in, MatrixXd u_in, const VectorXd & u_prev, VectorXd w_in, + const MatrixXd & goal_x, const MatrixXd & goal_u); /* Set */ void setH(); void setc( - const MatrixXd & x, const MatrixXd & u, const VectorXd & w, const MatrixXd & goal_x, - const MatrixXd & goal_u); - void setE(const MatrixXd & x, const MatrixXd & u); - void setb(const MatrixXd & x, const MatrixXd & u); - void setC(const MatrixXd & x); - void setd(const MatrixXd & x, const MatrixXd & u, const VectorXd & u_prev, const VectorXd & w); - - void setQ(MatrixXd Q); - void setR(MatrixXd R); - void setS(MatrixXd S); - void setW(MatrixXd W); - void setNp(size_t Np); - void setNc(size_t Nc); - void setdt(double dt); - void setNEq(size_t n_eq); - void setNIneq(size_t n_ineq); - void setMaxInIter(size_t max_inn_iter); - void setMaxOutIter(size_t max_out_iter); - void setQPType(bool qp_type); - void setGuess(bool guess); - - /// Initial-guess policy handed to proxsuite for each QP sub-problem. + const MatrixXd & x_in, const MatrixXd & u_in, const VectorXd & w_in, + const MatrixXd & goal_x, const MatrixXd & goal_u); + void setE(const MatrixXd & x_in, const MatrixXd & u_in); + void setb(const MatrixXd & x_in, const MatrixXd & u_in); + void setC(const MatrixXd & x_in); + void setd( + const MatrixXd & x_in, const MatrixXd & u_in, const VectorXd & u_prev, + const VectorXd & w_in); + + void setQ(MatrixXd new_Q); + void setR(MatrixXd new_R); + void setS(MatrixXd new_S); + void setW(MatrixXd new_W); + void setNp(size_t new_Np); + void setNc(size_t new_Nc); + void setdt(double new_dt); + void setNEq(size_t new_n_eq); + void setNIneq(size_t new_n_ineq); + void setMaxInIter(size_t new_max_inn_iter); + void setMaxOutIter(size_t new_max_out_iter); + void setQPType(bool new_qp_type); + void setGuess(bool new_guess); + void setWarmStart(bool new_warm_start); + + /// Initial-guess policy for a solve that updates a surviving workspace. proxsuite::proxqp::InitialGuessStatus initialGuessPolicy() const; - void setCbfGamma(double cbf_gamma); + + /// Initial-guess policy for a solve that (re)builds the workspace. + proxsuite::proxqp::InitialGuessStatus coldGuessPolicy() const; + + /// Declare the fixed sparsity structure the workspace is built against. + void declarePattern(); + void setCbfGamma(double new_cbf_gamma); /* Obstacle avoidance */ - void setMaxObs(size_t max_obs); - void setObs(MatrixXd obs); + void setMaxObs(size_t new_max_obs); + void setObs(MatrixXd new_obs); /* Accessors for the assembled inequality system (valid after a solve()). */ const MatrixXd & getC() const {return C;} const std::vector & getIneqIdx() const {return ineq_idx;} + const VectorXd & getLow() const {return low;} size_t getWStart() const {return w_start;} size_t getNDvars() const {return n_dvars;} size_t getMaxObs() const {return max_obs;} @@ -129,12 +139,14 @@ class ProxQP : public MPCParams /* Settings (mirror the MPC defaults; MPC overwrites them all before init()). */ bool qp_type = false; // Sparse (false) / dense (true) problem. - bool guess = true; // Use (true) / don't use (false) warm start for initial guesses. + bool guess = true; // ProxQP cheap-start policy selector. + bool warm_start = true; // Reuse the workspace and previous iterate across cycles. size_t max_out_iter = 10000; // Maximum number of outer iterations. size_t max_inn_iter = 1500; // Maximum number of inner iterations (proximal operator). /* Results */ proxsuite::proxqp::sparse::Vec result_x; // Optimal decision variables. + bool qp_ready{false}; // Workspace built; later cycles update it in place. // Info is a plain aggregate with no default member initializers; value-initialize // it so a read before the first solve() is not indeterminate. The zero-valued // QPSolverOutput enumerator is PROXQP_SOLVED, so the constructor overrides the @@ -144,6 +156,15 @@ class ProxQP : public MPCParams /* Obstacle avoidance: linearized signed-distance half-plane, K slots per node. */ size_t max_obs = 0; // Capacity K of obstacle slots per predicted node (0 = disabled). bool obstacle_active = false; // Cached in init(): model declares avoidance and max_obs > 0. + + /* State indices the model declares its planar position at, read once from + * Model::getPlanarMapping() in init() and validated there. The obstacle rows + * are the only place the solver needs to know where the position sits, so + * they are cached rather than queried per row: setC() writes Np*K of them + * every SQP iteration. The defaults are the canonical layout every bundled + * model declares. */ + size_t idx_pos_x = 0; + size_t idx_pos_y = 1; MatrixXd obs; // Per (node, slot) obstacle triples (Np*K) x [o_x, o_y, d_safe]. // Discrete-time control-barrier-function rate (Zeng et al., ACC 2021): diff --git a/prox_mpc_core/include/prox_mpc/structs.hpp b/prox_mpc_core/include/prox_mpc/structs.hpp index c10fee7..deaae17 100644 --- a/prox_mpc_core/include/prox_mpc/structs.hpp +++ b/prox_mpc_core/include/prox_mpc/structs.hpp @@ -53,6 +53,51 @@ struct ModelInfo VectorXd c; // Local function approximation. }; +/* How a model's state and control vectors map onto the planar quantities a Nav2 + * consumer drives. Declared by Model::getPlanarMapping() and read once at the + * consumer's configuration time, never on the control path. + * + * Validation is split by who indexes what. The core validates only the indices + * it dereferences itself: today that is idx_x and idx_y, checked in + * ProxQP::init() when obstacle avoidance is active. idx_yaw and the steering + * indices are deliberately unchecked there, because no core path reads them - + * a two-state holonomic model doing obstacle avoidance through the core + * directly is legitimate, and its out-of-range idx_yaw default harms nothing. + * The Nav2 controller validates all of them at readModelMapping(), for its own + * use of them. + * + * Whoever first makes a core path index the heading or a steering channel must + * extend the check in ProxQP::init() to cover it: EIGEN_NO_DEBUG turns an + * out-of-range read into silent garbage rather than an abort. */ +struct PlanarMapping +{ + /* Index value meaning "this model does not carry that quantity". */ + static constexpr size_t kNoIndex = static_cast(-1); + + size_t idx_x{0}; // State index of the x position [m]. + size_t idx_y{1}; // State index of the y position [m]. + size_t idx_yaw{2}; // State index of the heading [rad]. + size_t idx_speed{0}; // Control index of the signed longitudinal speed [m/s]. + size_t idx_steering{kNoIndex}; // State index of the steering angle [rad], or kNoIndex. + + /* Control index of the steering-angle rate [rad/s], or kNoIndex. Meaningful + * only alongside idx_steering: it is the channel whose declared bound sets how + * fast a consumer may move its belief about the steering angle. */ + size_t idx_steer_rate{kNoIndex}; + + /* Position of the point the state's x/y refer to, expressed in base_link + * [m]: (0, 0) when the model is referenced to base_link itself, (L, 0) for a + * model referenced to the front axle of a vehicle whose base_link sits on the + * rear axle. A consumer transforms the model's pose by this offset before any + * check defined about base_link, such as a footprint collision test. */ + double ref_offset_x{0.0}; + double ref_offset_y{0.0}; + + /* Wheelbase L [m] the steering geometry is defined on. 0.0 means undeclared, + * which a consumer must reject for a model that carries a steering angle. */ + double wheelbase{0.0}; +}; + /* Problem constraints. */ struct Constraints { diff --git a/prox_mpc_core/package.xml b/prox_mpc_core/package.xml index 0105fd3..f26524b 100644 --- a/prox_mpc_core/package.xml +++ b/prox_mpc_core/package.xml @@ -2,7 +2,7 @@ prox_mpc_core - 1.0.0 + 2.0.0 ProxMPC core: a nonlinear Model Predictive Control solved by a Sequential Quadratic Programming scheme that recursively calls the ProxQP solver, with Eigen for linear algebra. Library only; no ROS node. diff --git a/prox_mpc_core/prox_mpc_core_plugins.xml b/prox_mpc_core/prox_mpc_core_plugins.xml index 425010e..5a64971 100644 --- a/prox_mpc_core/prox_mpc_core_plugins.xml +++ b/prox_mpc_core/prox_mpc_core_plugins.xml @@ -1,11 +1,32 @@ + + + Kinematic bicycle referenced to the front axle: state [x, y, theta, delta] + (n=4), control [v, delta_dot] (m=2), with (x, y) at the front-axle centre + and v the front-wheel speed. Bundled prox_mpc::Model plugin. + + + + + Kinematic bicycle referenced to the rear axle: state [x, y, theta, delta] + (n=4), control [v, delta_dot] (m=2), with (x, y) at the rear-axle centre + (the base_link origin) and v the body speed. Bundled prox_mpc::Model plugin. + + - Kinematic bicycle reference model: state [x, y, theta, delta] (n=4), - control [v, delta_dot] (m=2). Bundled prox_mpc::Model plugin. + Deprecated alias for prox_mpc_core/BicycleFrontAxle, kept so an existing + configuration keeps loading; it warns once on load and is removed in the + next major release. Select BicycleFrontAxle or BicycleRearAxle instead. name = name;} +void Model::setName(std::string new_name) {this->name = new_name;} /*! * Set the state vector dimension. - * @param n dimension (> 0). + * @param new_n dimension (> 0). */ -void Model::setN(size_t n) +void Model::setN(size_t new_n) { - if (n == 0) {throw std::invalid_argument("Model::setN: n must be > 0");} - this->n = n; - this->x = VectorXd::Zero(n); + if (new_n == 0) {throw std::invalid_argument("Model::setN: n must be > 0");} + this->n = new_n; + this->x = VectorXd::Zero(new_n); } /*! * Set the control vector dimension. - * @param m dimension (> 0). + * @param new_m dimension (> 0). */ -void Model::setM(size_t m) +void Model::setM(size_t new_m) { - if (m == 0) {throw std::invalid_argument("Model::setM: m must be > 0");} - this->m = m; - this->u = VectorXd::Zero(m); + if (new_m == 0) {throw std::invalid_argument("Model::setM: m must be > 0");} + this->m = new_m; + this->u = VectorXd::Zero(new_m); } /*! * Set the model parameters. - * @param params vector of parameters. + * @param new_params vector of parameters. */ -void Model::setParams(const VectorXd & params) {this->params = params;} +void Model::setParams(const VectorXd & new_params) {this->params = new_params;} /*! * Set local function approximation. - * @param c + * @param new_c */ -void Model::setc(const VectorXd & c) {this->c = c;} +void Model::setc(const VectorXd & new_c) {this->c = new_c;} /*! * Set the state matrix. - * @param A state matrix n x n. + * @param new_A state matrix n x n. */ -void Model::setA(const MatrixXd & A) {this->A = A;} +void Model::setA(const MatrixXd & new_A) {this->A = new_A;} /*! * Set the control matrix. - * @param B control matrix n x m. + * @param new_B control matrix n x m. */ -void Model::setB(const MatrixXd & B) {this->B = B;} +void Model::setB(const MatrixXd & new_B) {this->B = new_B;} /*! * Set the state vector. - * @param x + * @param new_x */ -void Model::setX(const VectorXd & x) {this->x = x;} +void Model::setX(const VectorXd & new_x) {this->x = new_x;} /*! * Set the control vector. - * @param u + * @param new_u */ -void Model::setU(const VectorXd & u) {this->u = u;} +void Model::setU(const VectorXd & new_u) {this->u = new_u;} /*! * Set inequality constraint. @@ -137,6 +137,14 @@ void Model::setIneq(std::string var, size_t idx_vec, double low, double upp) if (var != "x" && var != "u" && var != "du" && var != "w") { throw std::invalid_argument("Model: var must be 'x', 'u', 'du' or 'w'"); } + // n/m may not be set yet (setN/setM run first in every bundled model, but the + // check is skipped rather than assumed until they are known). + if (var == "x" && n > 0 && idx_vec >= n) { + throw std::invalid_argument("Model::setIneq: idx_vec out of range for state dimension n"); + } + if ((var == "u" || var == "du") && m > 0 && idx_vec >= m) { + throw std::invalid_argument("Model::setIneq: idx_vec out of range for control dimension m"); + } std::vector bounds; bounds.push_back(idx_vec); @@ -196,28 +204,31 @@ void Model::updateIneq(std::string var, size_t idx_vec, double low, double upp) if (ineq_w[i][0] == idx_vec) {idx = i; found = true;}} if (found) {ineq_w[idx] = bounds;} } + if (!found) { + throw std::invalid_argument("Model::updateIneq: no existing bound for idx_vec"); + } } /*! * Declare whether the model supports obstacle avoidance. - * @param obs_flag true if the model participates in obstacle avoidance. + * @param new_obs_flag true if the model participates in obstacle avoidance. */ -void Model::setObsAvoid(bool obs_flag) +void Model::setObsAvoid(bool new_obs_flag) { - this->obs_flag = obs_flag; + this->obs_flag = new_obs_flag; } /*! * Override one inequality bound from a configure() params map, keeping the * current value for any side whose key is absent. - * @param params configure() params map. + * @param config_params configure() params map. * @param var "x", "u", "du" or "w". * @param idx_vec vector index whose bound is overridden. * @param key_low params key for the lower bound (kept current if absent). * @param key_upp params key for the upper bound (kept current if absent). */ void Model::overrideBound( - const std::map & params, std::string var, size_t idx_vec, + const std::map & config_params, std::string var, size_t idx_vec, std::string key_low, std::string key_upp) { /* Read the current bound so an absent key keeps the constructor literal. */ @@ -234,8 +245,8 @@ void Model::overrideBound( } if (found == false) {return;} - if (params.count(key_low) > 0) {low = params.at(key_low);} - if (params.count(key_upp) > 0) {upp = params.at(key_upp);} + if (config_params.count(key_low) > 0) {low = config_params.at(key_low);} + if (config_params.count(key_upp) > 0) {upp = config_params.at(key_upp);} updateIneq(var, idx_vec, low, upp); } diff --git a/prox_mpc_core/src/mpc.cpp b/prox_mpc_core/src/mpc.cpp index 1a2eb35..010d265 100644 --- a/prox_mpc_core/src/mpc.cpp +++ b/prox_mpc_core/src/mpc.cpp @@ -5,24 +5,70 @@ #include #include +#include #include #include +#include namespace prox_mpc { +namespace +{ +/* Relative tolerance the weight-matrix symmetry and eigenvalue tests are run at. + * Loose enough that a matrix assembled in floating point passes, tight enough + * that a matrix the caller meant to be asymmetric or indefinite does not. */ +constexpr double kWeightTol = 1e-8; + +/* Reject a structural setter called after init(). The buffers, the QP object and + * the solver's own sizing are fixed there, and none of these setters resizes + * them, so a post-init call would leave the object describing one problem and + * solving another. */ +void rejectAfterInit(bool initialized, const char * setter) +{ + if (initialized == true) { + throw std::logic_error( + std::string("MPC::") + setter + + ": structural setters must be called before init()"); + } +} + +/* Throw unless `m` is finite, symmetric and positive semidefinite. proxsuite + * validates sizes only, and the Hessian it is handed is 2 * m, so an asymmetric + * or indefinite weight silently makes it solve a different problem than the + * caller wrote. */ +void requireSymmetricPSD(const MatrixXd & m, const char * name) +{ + const std::string prefix = std::string("MPC::init: ") + name; + if (!m.allFinite()) { + throw std::invalid_argument(prefix + " must be finite"); + } + const double scale = std::max(1.0, m.cwiseAbs().maxCoeff()); + if ((m - m.transpose()).cwiseAbs().maxCoeff() > kWeightTol * scale) { + throw std::invalid_argument(prefix + " must be symmetric"); + } + const Eigen::SelfAdjointEigenSolver solver(m); + if (solver.info() != Eigen::Success) { + throw std::invalid_argument(prefix + " eigenvalue decomposition failed"); + } + if (solver.eigenvalues().minCoeff() < -kWeightTol * scale) { + throw std::invalid_argument(prefix + " must be positive semidefinite"); + } +} +} // namespace + /*! * Inizialize the Model Predictive Control. - * @param model model pointer. + * @param new_model model pointer. */ -void MPC::init(std::shared_ptr model) +void MPC::init(std::shared_ptr new_model) { /* Model */ - this->model = model; + this->model = new_model; /* MPC */ - n = model->getN(); - m = model->getM(); + n = new_model->getN(); + m = new_model->getM(); /* Default-initialize unset weight matrices and validate their dimensions */ if (Q.size() == 0) {Q = MatrixXd::Identity(n, n);} @@ -41,15 +87,27 @@ void MPC::init(std::shared_ptr model) if (W.rows() != 1 || W.cols() != 1) { throw std::invalid_argument("MPC::init: W must be 1 x 1"); } + requireSymmetricPSD(Q, "Q"); + requireSymmetricPSD(S, "S"); + requireSymmetricPSD(R, "R"); + requireSymmetricPSD(W, "W"); + + /* Last chance to catch the horizon bound: the setters skip their comparison + * while the other horizon is still at its unset sentinel, and Np and Nc are + * public ProbDim members a caller can assign past the setters entirely. */ + if (Nc > Np) { + throw std::invalid_argument("MPC::init: Nc must be <= Np"); + } x = MatrixXd::Zero(Np + 1, n); u = MatrixXd::Zero(Nc, m); - const bool obstacle_active = model->getObsFlag() == true && max_obs > 0; + const bool obstacle_active = new_model->getObsFlag() == true && max_obs > 0; w = VectorXd::Zero(obstacle_active == true ? Np * max_obs : 0); u0 = u.row(0); n_eq = 0; - n_ineq = model->getIneq("x").size() + model->getIneq("u").size() + model->getIneq("du").size(); + n_ineq = new_model->getIneq("x").size() + new_model->getIneq("u").size() + + new_model->getIneq("du").size(); /* ProxQP */ proxqp = std::make_shared(); @@ -63,6 +121,10 @@ void MPC::init(std::shared_ptr model) obs(r, 1) = kObsFarSentinel; obs(r, 2) = 0.0; } + + /* Every buffer and the QP object are sized from here on; the structural + * setters reject a later call rather than mutating one of the two halves. */ + initialized = true; } /* Configure the ProxQP solver. */ @@ -81,33 +143,54 @@ void MPC::configProxQP() proxqp->setMaxOutIter(max_ext_qp); proxqp->setQPType(qp_type); proxqp->setGuess(guess); + proxqp->setWarmStart(warm_start); proxqp->setCbfGamma(cbf_gamma); proxqp->setMaxObs(max_obs); proxqp->init(model); } /*! - * Run one SQP cycle and return the predicted state and control trajectories. + * Run one SQP cycle and return the predicted state and control trajectories, + * without retaining any of it: x, u, w and u0 are untouched, and commitCandidate() + * retains the result once the caller's own acceptance gates have passed. * Convergence must be checked by the caller through qp_info.status, which equals - * PROXQP_SOLVED on success. On non-convergence solve() takes no safety action; - * the returned first control is the last (non-converged) iterate and must not be + * PROXQP_SOLVED on success. On non-convergence this takes no safety action; the + * returned first control is the last (non-converged) iterate and must not be * applied as is. The caller is responsible for the fallback, for example a * deceleration ramp toward zero that respects the robot's limits. */ -std::tuple MPC::solve() +std::tuple MPC::solveCandidate() { + /* The whole cycle runs on the candidate copies. Nothing below writes x, u, w + * or u0, so a cycle the caller rejects leaves the retained state exactly as the + * last accepted cycle left it. */ + cand_x = x; + cand_u = u; + cand_w = w; + cand_solved = false; + cand_finite = false; + /* Slide states and control by 1 position. The right-hand side is .eval()'d into * a temporary because source and destination overlap: Eigen assumes no aliasing * for block/row assignments, so an explicit temporary keeps the shift correct. */ - x.topRows(x.rows() - 1) = x.bottomRows(x.rows() - 1).eval(); - x.row(x.rows() - 1) = x.row(x.rows() - 2); - - u.topRows(u.rows() - 1) = u.bottomRows(u.rows() - 1).eval(); - u.row(u.rows() - 1) = u.row(u.rows() - 2); + cand_x.topRows(cand_x.rows() - 1) = cand_x.bottomRows(cand_x.rows() - 1).eval(); + cand_x.row(cand_x.rows() - 1) = cand_x.row(cand_x.rows() - 2); + + /* With Nc == 1, u has a single row: there is no previous row to shift, and + * u.row(u.rows() - 2) would read out of bounds. */ + if (cand_u.rows() > 1) { + cand_u.topRows(cand_u.rows() - 1) = cand_u.bottomRows(cand_u.rows() - 1).eval(); + cand_u.row(cand_u.rows() - 1) = cand_u.row(cand_u.rows() - 2); + } - /* Update current predicted state with the current real pose */ - x.row(0) = pose; - u.row(0) = u0; + /* Update current predicted state with the current real pose. The control warm + * start keeps what the shift above produced: row 0 holds the previous plan's + * second control, which is the one this cycle is about to decide. Writing u0 + * here instead would put the control already executed last cycle in row 0 + * while row 1 still held the plan's third, so the pair straddled two steps of + * the rate limit and the warm start entered the QP violating its own + * control-rate chain. u0 reaches the solver separately as the rate anchor. */ + cand_x.row(0) = pose; /* Set ProxQP */ proxqp->setdt(dt); @@ -120,19 +203,25 @@ std::tuple MPC::solve() const auto sqp_start = std::chrono::steady_clock::now(); do{ /* Solve the QP sub-problem */ - auto [x_sol, u_sol, w_sol, info] = proxqp->solve(x, u, u0, w, goal_x, goal_u); + auto [x_sol, u_sol, w_sol, info] = + proxqp->solve(cand_x, cand_u, u0, cand_w, goal_x, goal_u); /* Update */ - x += x_sol; - u += u_sol; - w += w_sol; + cand_x += x_sol; + cand_u += u_sol; + cand_w += w_sol; qp_info = info; qp_iter_ext += qp_info.iter_ext; sqp_iter++; - /* Wall-clock budget (0 disables it): bound the worst-case solve so a slow - * SQP cannot overrun the control cycle. On timeout the loop exits with - * status != PROXQP_SOLVED, routing the caller to its fail-safe. */ + /* Soft wall-clock budget (0 disables it), checked between SQP iterations: + * it bounds how many further QP sub-problems start, not the one already in + * flight, because proxsuite exposes no time-based stop (only max_iter and + * max_iter_in). It is therefore not a bound on worst-case cycle latency in + * either direction, and the loop still reports success when the QP that + * overran the budget converged. The bound that does hold per cycle is the + * iteration caps; max_iter_sqp = 1 gives a genuinely bounded real-time + * iteration. */ if (max_solve_time > 0.0) { const double elapsed = std::chrono::duration(std::chrono::steady_clock::now() - sqp_start).count(); @@ -141,14 +230,46 @@ std::tuple MPC::solve() } while (qp_info.status != proxsuite::proxqp::QPSolverOutput::PROXQP_SOLVED && sqp_iter < max_iter_sqp && !timed_out); - /* On a converged solve the first control becomes the command sent to the robot - * and the warm-start reference for the next cycle. On non-convergence solve() - * takes no safety action: it keeps the last good command and reports the - * failure through qp_info.status, leaving the fallback policy to the caller. */ - if (qp_info.status == proxsuite::proxqp::QPSolverOutput::PROXQP_SOLVED) { - u0 = u.row(0); - } + cand_solved = qp_info.status == proxsuite::proxqp::QPSolverOutput::PROXQP_SOLVED; + /* Full-horizon finiteness, not only the first control: a non-finite tail would + * otherwise be committed and then warm-start the next cycle. */ + cand_finite = cand_x.allFinite() && cand_u.allFinite() && cand_w.allFinite(); + cand_u0 = cand_u.row(0); + + return {cand_x, cand_u}; +} + +/*! + * Retain the last candidate. The first control becomes the warm-start reference + * for the next cycle and the anchor of its control-rate constraint, so it is + * advanced only for a candidate that both converged and is finite. + */ +bool MPC::commitCandidate() +{ + if (cand_solved == false || cand_finite == false) {return false;} + x = cand_x; + u = cand_u; + w = cand_w; + u0 = cand_u0; + return true; +} + +/* Whether the last candidate is finite over the whole horizon. */ +bool MPC::getCandidateFinite() {return cand_finite;} +/*! + * Run one SQP cycle and commit it. This is the propose-and-commit entry point: + * the increments are retained whatever the QP reported, and the first control + * advances only on a converged solve. Callers that must not advance on a cycle + * their own gates reject use solveCandidate()/commitCandidate() instead. + */ +std::tuple MPC::solve() +{ + solveCandidate(); + x = cand_x; + u = cand_u; + w = cand_w; + if (cand_solved == true) {u0 = cand_u0;} return {x, u}; } @@ -202,109 +323,176 @@ bool MPC::getGuess() {return guess;} /*! * Set the states matrix. - * @param x matrix. + * @param new_x matrix. + */ +void MPC::setX(MatrixXd new_x) {this->x = new_x;} + +/*! + * Set the previous control input the next cycle's rate constraint is anchored on. + * @param new_u0 control actually applied (length m). */ -void MPC::setX(MatrixXd x) {this->x = x;} +void MPC::setU0(VectorXd new_u0) {this->u0 = new_u0;} /*! - * Set the intermediate states weight matrix. - * @param Q matrix. + * Set the intermediate states weight matrix. Pre-init only; init() validates it. + * @param new_Q matrix. */ -void MPC::setQ(MatrixXd Q) {this->Q = Q;} +void MPC::setQ(MatrixXd new_Q) +{ + rejectAfterInit(initialized, "setQ"); + this->Q = new_Q; +} /*! - * Set the control input weight matrix. - * @param R matrix. + * Set the control input weight matrix. Pre-init only; init() validates it. + * @param new_R matrix. */ -void MPC::setR(MatrixXd R) {this->R = R;} +void MPC::setR(MatrixXd new_R) +{ + rejectAfterInit(initialized, "setR"); + this->R = new_R; +} /*! - * Set the final state weight matrix. - * @param S matrix. + * Set the final state weight matrix. Pre-init only; init() validates it. + * @param new_S matrix. */ -void MPC::setS(MatrixXd S) {this->S = S;} +void MPC::setS(MatrixXd new_S) +{ + rejectAfterInit(initialized, "setS"); + this->S = new_S; +} /*! - * Set the slack variables weight matrix. - * @param W matrix. + * Set the slack variables weight matrix. Pre-init only; init() validates it. + * @param new_W matrix. */ -void MPC::setW(MatrixXd W) {this->W = W;} +void MPC::setW(MatrixXd new_W) +{ + rejectAfterInit(initialized, "setW"); + this->W = new_W; +} /*! * Set the prediction horizon. * If T is set, dt is automatically updated. - * @param Np number (> 0). + * @param new_Np number (> 0). */ -void MPC::setNp(size_t Np) +void MPC::setNp(size_t new_Np) { - if (Np == 0) {throw std::invalid_argument("MPC::setNp: Np must be > 0");} - this->Np = Np; - if (T > 0.0) {this->dt = T / Np;} + rejectAfterInit(initialized, "setNp"); + if (new_Np == 0) {throw std::invalid_argument("MPC::setNp: Np must be > 0");} + // The Nc <= Np bound holds whichever setter runs second, so it is mirrored + // here: checking it in setNc alone let the caller reach it by ordering. + // Nc may not be set yet (0 is its unset sentinel, as in setNc below). + if (Nc > 0 && Nc > new_Np) {throw std::invalid_argument("MPC::setNp: Np must be >= Nc");} + this->Np = new_Np; + if (T > 0.0) {this->dt = T / new_Np;} } /*! * Set the control horizon. - * @param Nc number (> 0). + * @param new_Nc number (> 0). */ -void MPC::setNc(size_t Nc) +void MPC::setNc(size_t new_Nc) { - if (Nc == 0) {throw std::invalid_argument("MPC::setNc: Nc must be > 0");} - this->Nc = Nc; + rejectAfterInit(initialized, "setNc"); + if (new_Nc == 0) {throw std::invalid_argument("MPC::setNc: Nc must be > 0");} + // Np may not be set yet (0 is its unset sentinel, matching setdt/setT below); + // the comparison is skipped until it is known. + if (Np > 0 && new_Nc > Np) {throw std::invalid_argument("MPC::setNc: Nc must be <= Np");} + this->Nc = new_Nc; } /*! * Set the sample time. * If Np is set, T is automatically updated. - * @param dt sample time (> 0). + * @param new_dt sample time (> 0). */ -void MPC::setdt(double dt) +void MPC::setdt(double new_dt) { - if (dt <= 0.0) {throw std::invalid_argument("MPC::setdt: dt must be > 0");} - this->dt = dt; - if (Np > 0) {this->T = Np * dt;} + rejectAfterInit(initialized, "setdt"); + if (!std::isfinite(new_dt) || new_dt <= 0.0) { + throw std::invalid_argument("MPC::setdt: dt must be > 0"); + } + this->dt = new_dt; + if (Np > 0) {this->T = Np * new_dt;} } /*! * Set the prediction horizon time [s]. * If Np is set, dt is automatically updated. - * @param T time (> 0). + * @param new_T time (> 0). */ -void MPC::setT(double T) +void MPC::setT(double new_T) { - if (T <= 0.0) {throw std::invalid_argument("MPC::setT: T must be > 0");} - this->T = T; - if (Np > 0) {this->dt = T / Np;} + rejectAfterInit(initialized, "setT"); + if (new_T <= 0.0) {throw std::invalid_argument("MPC::setT: T must be > 0");} + this->T = new_T; + if (Np > 0) {this->dt = new_T / Np;} } /*! * Set the current pose. - * @param pose current pose. + * @param new_pose current pose. */ -void MPC::setPose(VectorXd pose) {this->pose = pose;} +void MPC::setPose(VectorXd new_pose) {this->pose = new_pose;} /*! * Set the desired state goals. - * @param goal_x goals. + * The assembly reads rows 0..Np and every state column, so an undersized matrix + * is rejected here rather than indexed out of bounds on the control hot path, + * where EIGEN_NO_DEBUG leaves the access unchecked. The column count is known + * only once init() has read n from the model, so it is checked from then on. + * @param new_goal_x goals ((Np + 1) x n). */ -void MPC::setGoalX(MatrixXd goal_x) {this->goal_x = goal_x;} +void MPC::setGoalX(MatrixXd new_goal_x) +{ + if (Np > 0 && new_goal_x.rows() < static_cast(Np) + 1) { + throw std::invalid_argument("MPC::setGoalX: goal_x must have at least Np + 1 rows"); + } + if (n > 0 && new_goal_x.cols() != static_cast(n)) { + throw std::invalid_argument("MPC::setGoalX: goal_x must have n columns"); + } + this->goal_x = new_goal_x; +} /*! * Set the desired control goals. - * @param goal_u goals. + * The assembly reads rows 0..Nc-1 and every control column; same reasoning as + * setGoalX. + * @param new_goal_u goals (Nc x m). */ -void MPC::setGoalU(MatrixXd goal_u) {this->goal_u = goal_u;} +void MPC::setGoalU(MatrixXd new_goal_u) +{ + if (Nc > 0 && new_goal_u.rows() < static_cast(Nc)) { + throw std::invalid_argument("MPC::setGoalU: goal_u must have at least Nc rows"); + } + if (m > 0 && new_goal_u.cols() != static_cast(m)) { + throw std::invalid_argument("MPC::setGoalU: goal_u must have m columns"); + } + this->goal_u = new_goal_u; +} /*! * Set the maximum number of internal iterations for the QP solver. * @param max_iter max. iterations (default = 1500). */ -void MPC::setMaxIntIterQP(size_t max_iter) {this->max_int_qp = max_iter;} +void MPC::setMaxIntIterQP(size_t max_iter) +{ + rejectAfterInit(initialized, "setMaxIntIterQP"); + this->max_int_qp = max_iter; +} /*! * Set the maximum number of external iterations for the QP solver. * @param max_iter max. iterations (default = 10000). */ -void MPC::setMaxExtIterQP(size_t max_iter) {this->max_ext_qp = max_iter;} +void MPC::setMaxExtIterQP(size_t max_iter) +{ + rejectAfterInit(initialized, "setMaxExtIterQP"); + this->max_ext_qp = max_iter; +} /*! * Set the maximum number of iterations for the SQP solver. @@ -320,37 +508,66 @@ void MPC::setMaxSolveTime(double seconds) {this->max_solve_time = seconds;} /*! * Set if use initial guesses or not. - * @param guess flag (default: true). + * @param new_guess flag (default: true). + */ +void MPC::setGuess(bool new_guess) +{ + rejectAfterInit(initialized, "setGuess"); + this->guess = new_guess; +} + +/*! + * Enable the cross-cycle QP warm start: the solver workspace is built once and + * updated in place, so the factorization and the previous primal/dual iterate + * carry over between solves. Structural, because it decides how the workspace is + * built, so it is rejected after init() like the other structural setters. + * @param new_warm_start flag (default: true). */ -void MPC::setGuess(bool guess) {this->guess = guess;} +void MPC::setWarmStart(bool new_warm_start) +{ + rejectAfterInit(initialized, "setWarmStart"); + this->warm_start = new_warm_start; +} /*! * Set QP sub-problems type. - * @param qp_type sparse (false) or dense (true) (default: false). + * @param new_qp_type sparse (false) or dense (true) (default: false). */ -void MPC::setQPtype(bool qp_type) {this->qp_type = qp_type;} +void MPC::setQPtype(bool new_qp_type) +{ + rejectAfterInit(initialized, "setQPtype"); + this->qp_type = new_qp_type; +} /*! * Set the discrete-time CBF rate for the obstacle coupling (forwarded to ProxQP). * Must be set before init()/configProxQP(). - * @param cbf_gamma rate in (0, 1]; 1.0 reduces to the pointwise constraint. + * @param new_cbf_gamma rate in (0, 1]; 1.0 reduces to the pointwise constraint. */ -void MPC::setCbfGamma(double cbf_gamma) +void MPC::setCbfGamma(double new_cbf_gamma) { + // Pre-init only, like every other setter the QP is configured from: the rate + // reaches the solver through configProxQP(), which init() runs once, so a + // later call would change this object's own member and nothing else. + rejectAfterInit(initialized, "setCbfGamma"); // Validated here as well as in ProxQP so a bad value fails at configuration // time rather than on the first init(). - if (!(cbf_gamma > 0.0 && cbf_gamma <= 1.0)) { + if (!(new_cbf_gamma > 0.0 && new_cbf_gamma <= 1.0)) { throw std::invalid_argument("MPC::setCbfGamma: cbf_gamma must be in (0, 1]"); } - this->cbf_gamma = cbf_gamma; + this->cbf_gamma = new_cbf_gamma; } /*! * Set the obstacle-slot capacity K per predicted node (0 disables avoidance). * Must be set before init()/configProxQP() so the QP is sized once for K. - * @param max_obs capacity K. + * @param new_max_obs capacity K. */ -void MPC::setMaxObs(size_t max_obs) {this->max_obs = max_obs;} +void MPC::setMaxObs(size_t new_max_obs) +{ + rejectAfterInit(initialized, "setMaxObs"); + this->max_obs = new_max_obs; +} /* Get the obstacle-slot capacity K per predicted node. */ size_t MPC::getMaxObs() {return max_obs;} @@ -360,9 +577,9 @@ double MPC::getMaxObstacleSlack() {return w.size() > 0 ? w.maxCoeff() : 0.0;} /*! * Set the obstacle triples for the current cycle. - * @param obs (Np*K) x 3 matrix of [o_x, o_y, d_safe] per (node, slot); empty + * @param new_obs (Np*K) x 3 matrix of [o_x, o_y, d_safe] per (node, slot); empty * slots should hold the far sentinel so their soft constraint is non-binding. */ -void MPC::setObs(MatrixXd obs) {this->obs = obs;} +void MPC::setObs(MatrixXd new_obs) {this->obs = new_obs;} } // namespace prox_mpc diff --git a/prox_mpc_core/src/plugins.cpp b/prox_mpc_core/src/plugins.cpp index 3d630d4..905fcbb 100644 --- a/prox_mpc_core/src/plugins.cpp +++ b/prox_mpc_core/src/plugins.cpp @@ -10,7 +10,11 @@ #include #include +#include +#include #include +PLUGINLIB_EXPORT_CLASS(prox_mpc::BicycleFrontAxle, prox_mpc::Model) +PLUGINLIB_EXPORT_CLASS(prox_mpc::BicycleRearAxle, prox_mpc::Model) PLUGINLIB_EXPORT_CLASS(prox_mpc::Bicycle, prox_mpc::Model) PLUGINLIB_EXPORT_CLASS(prox_mpc::Unicycle, prox_mpc::Model) diff --git a/prox_mpc_core/src/proxqp.cpp b/prox_mpc_core/src/proxqp.cpp index 1b59d6e..b9669bc 100644 --- a/prox_mpc_core/src/proxqp.cpp +++ b/prox_mpc_core/src/proxqp.cpp @@ -4,12 +4,14 @@ #include +#include #include #include #include #include #include +#include #include // Solver-local convenience for the proxsuite types (kept out of the header so it @@ -24,20 +26,29 @@ namespace // Guard for the obstacle-constraint normal: avoids 0/0 = NaN when the predicted // robot position coincides with the obstacle. constexpr double kObsNormalEps = 1e-9; +// Far placeholder used only while probing the sparsity pattern at init. +constexpr double kObsProbeSentinel = 1e6; +// Fastest obstacle motion the backward extrapolation of the current-time +// obstacle position is trusted for [m/s]. The reconstruction 2 o_1 - o_2 +// amplifies inter-block noise, so an implied inter-block displacement above +// kMaxObsSpeed * dt is treated as noise rather than motion and the extrapolation +// falls back to the first block. Nothing this controller plans around moves +// faster than this. +constexpr double kMaxObsSpeed = 10.0; } // namespace /*! * Initialize ProxQP solver. - * @param model model pointer. + * @param new_model model pointer. */ -void ProxQP::init(std::shared_ptr model) +void ProxQP::init(std::shared_ptr new_model) { /* Robot model. */ - this->model = model; + this->model = new_model; /* Problem dimensions */ - this->n = model->getN(); - this->m = model->getM(); + this->n = new_model->getN(); + this->m = new_model->getM(); /* Constraints */ @@ -53,7 +64,42 @@ void ProxQP::init(std::shared_ptr model) /* Obstacle avoidance is active only if the model declares it and a capacity * K > 0 was set; K = 0 (or the model flag off) reduces to the obstacle-off QP. * Cached so the per-iteration assembly (setH/setc/setC/setd) reuses it. */ - obstacle_active = model->getObsFlag() == true && max_obs > 0; + obstacle_active = new_model->getObsFlag() == true && max_obs > 0; + + /* Where the model keeps its planar position. The obstacle rows are the only + * part of the assembly that has to know, so the mapping is read here, with + * obstacle_active, rather than per row or per cycle. Read only when the + * obstacle term is active: a model that does not use it may declare whatever + * mapping it likes, and rejecting one the solver never indexes would be this + * layer overreaching. + * + * Validated here rather than left to the caller. A consumer that drives this + * library directly - without the bundled Nav2 plugin's own model screening - + * would otherwise index a state column that does not exist, which + * EIGEN_NO_DEBUG turns into a silent out-of-range read rather than an abort. */ + if (obstacle_active == true) { + const PlanarMapping mapping = new_model->getPlanarMapping(); + const std::string where = "ProxQP::init: model '" + new_model->getName() + "' "; + if (mapping.idx_x >= n) { + throw std::invalid_argument( + where + "maps its x position to state index " + + std::to_string(mapping.idx_x) + ", outside its " + std::to_string(n) + + " states"); + } + if (mapping.idx_y >= n) { + throw std::invalid_argument( + where + "maps its y position to state index " + + std::to_string(mapping.idx_y) + ", outside its " + std::to_string(n) + + " states"); + } + if (mapping.idx_x == mapping.idx_y) { + throw std::invalid_argument( + where + "maps both planar positions to state index " + + std::to_string(mapping.idx_x)); + } + idx_pos_x = mapping.idx_x; + idx_pos_y = mapping.idx_y; + } /* Update the number of inequality blocks: the first control input, plus the * obstacle constraint block and the slack lower-bound block when active. */ @@ -66,20 +112,20 @@ void ProxQP::init(std::shared_ptr model) /* Set inequality constraint indices */ size_t i = 0; - ineq_idx[i] = model->getIneq("du").size(); // first control-rate rows + ineq_idx[i] = new_model->getIneq("du").size(); // first control-rate rows i++; - for (size_t j = 0; j < model->getIneq("x").size(); j++) { // state + for (size_t j = 0; j < new_model->getIneq("x").size(); j++) { // state ineq_idx[i] = ineq_idx[i - 1] + (Np + 1); i++; } - for (size_t j = 0; j < model->getIneq("u").size(); j++) { // control input + for (size_t j = 0; j < new_model->getIneq("u").size(); j++) { // control input ineq_idx[i] = ineq_idx[i - 1] + Nc; i++; } - for (size_t j = 0; j < model->getIneq("du").size(); j++) { // control input derivative + for (size_t j = 0; j < new_model->getIneq("du").size(); j++) { // control input derivative ineq_idx[i] = ineq_idx[i - 1] + (Nc - 1); i++; } @@ -127,16 +173,18 @@ void ProxQP::init(std::shared_ptr model) /* Sparse problem */ if (qp_type == false) { - // Sparse matrices - H_sparse = H.sparseView(); - E_sparse = E.sparseView(); - C_sparse = C.sparseView(); - - // QP settings - qp_sparse = sparse::QP(qp_dim, qp_eq, qp_ineq); + declarePattern(); + + /* Constructed from the structural masks rather than the dimensions, so the + * KKT layout is allocated once for the pattern every later update() reuses. */ + using BoolMat = sparse::SparseMat; + qp_sparse = sparse::QP( + BoolMat(H_sparse.cast()), BoolMat(E_sparse.cast()), + BoolMat(C_sparse.cast())); qp_sparse.settings.max_iter = max_out_iter; qp_sparse.settings.max_iter_in = max_inn_iter; qp_sparse.settings.compute_timings = true; + qp_ready = false; } // Dense problem else { @@ -148,15 +196,113 @@ void ProxQP::init(std::shared_ptr model) } } +/*! + * @brief Fixed-sparsity bookkeeping for ProxQP's in-place update. + * + * ProxQP's sparse backend only applies update() when the matrices carry the same + * sparsity structure as the workspace was built with; a pattern that moves is + * silently ignored, which drops the obstacle keep-out rows. Deriving the pattern + * from sparseView() does exactly that, because the half-plane normals and the + * model Jacobians pass through zero as the trajectory evolves. + * + * The structure is therefore declared once from the positions setE and setC + * write - which depend only on the problem dimensions, never on the values - and + * the values are written into it each cycle, structural zeros included. + */ +namespace +{ +/// Structural pattern of `m`: every entry a filler touched, marked by non-NaN. +Eigen::SparseMatrix writtenPattern(const MatrixXd & m) +{ + std::vector> t; + for (Eigen::Index j = 0; j < m.cols(); j++) { + for (Eigen::Index i = 0; i < m.rows(); i++) { + if (!std::isnan(m(i, j))) { + t.emplace_back(static_cast(i), static_cast(j), 1.0); + } + } + } + Eigen::SparseMatrix s(m.rows(), m.cols()); + s.setFromTriplets(t.begin(), t.end()); + s.makeCompressed(); + return s; +} + +/// Copy the dense values into a fixed pattern, keeping structural zeros. +void writeInto(Eigen::SparseMatrix & pat, const MatrixXd & dense) +{ + for (int k = 0; k < pat.outerSize(); k++) { + for (Eigen::SparseMatrix::InnerIterator it(pat, k); it; ++it) { + it.valueRef() = dense(it.row(), it.col()); + } + } +} +} // namespace + +/*! + * Declare the sparsity structure of the equality and inequality blocks. + * + * setE and setC touch a fixed set of positions on every call, so filling the + * dense blocks with NaN and running them once reveals exactly which entries they + * own, without duplicating their indexing here. + */ +void ProxQP::declarePattern() +{ + const MatrixXd x_probe = MatrixXd::Zero(Np + 1, n); + const MatrixXd u_probe = MatrixXd::Zero(Nc, m); + const MatrixXd obs_saved = obs; + if (obstacle_active == true && + (obs.rows() != static_cast(Np * max_obs) || obs.cols() != 3)) + { + obs = MatrixXd::Constant(Np * max_obs, 3, kObsProbeSentinel); + } + + const double marker = std::numeric_limits::quiet_NaN(); + E.setConstant(marker); + C.setConstant(marker); + setE(x_probe, u_probe); + setC(x_probe); + E_sparse = writtenPattern(E); + C_sparse = writtenPattern(C); + E.setZero(); + C.setZero(); + obs = obs_saved; + + /* H is built once from the constant weights, so its own view is already fixed. */ + H_sparse = H.sparseView(); + H_sparse.makeCompressed(); +} + /*! * @brief Initial-guess policy for the QP sub-problem. * - * The sub-problem is rebuilt with fresh matrices each solve, so only ProxQP's own - * cheap starts apply: the equality-constrained guess (the default) or no guess. - * An external initial guess handed to a freshly initialized workspace mixes a - * stale guess with a reset state, which proxsuite 0.6.5 answers by diverging. + * WARM_START rather than WARM_START_WITH_PREVIOUS_RESULT: the latter also carries + * the proximal step sizes across solves, and unused obstacle slots are padded + * with a far sentinel whose rows are ~1e6 in magnitude, so step sizes tuned + * against that scaling cripple the next solve. WARM_START keeps the previous + * primal/dual iterate and derives the active set from it, which is the part that + * pays. + * + * Only meaningful while the workspace survives between solves. Requesting a warm + * start right after a fresh init mixes a stale guess with a reset state, which + * proxsuite 0.6.5 answers by diverging, so the caller selects this only on an + * update() path. */ proxsuite::proxqp::InitialGuessStatus ProxQP::initialGuessPolicy() const +{ + return guess ? + proxsuite::proxqp::InitialGuessStatus::WARM_START : + proxsuite::proxqp::InitialGuessStatus::NO_INITIAL_GUESS; +} + +/*! + * @brief Initial-guess policy for a solve that (re)builds the workspace. + * + * A freshly initialized workspace has no previous iterate to warm start from, so + * the cheap starts are all that apply here: the equality-constrained guess, or + * none when the caller turned guessing off. + */ +proxsuite::proxqp::InitialGuessStatus ProxQP::coldGuessPolicy() const { return guess ? proxsuite::proxqp::InitialGuessStatus::EQUALITY_CONSTRAINED_INITIAL_GUESS : @@ -166,33 +312,40 @@ proxsuite::proxqp::InitialGuessStatus ProxQP::initialGuessPolicy() const /*! * Solve the quadratic program using ProxQP solver and compute the optimal state and control input evolution, * resulting in an optimal trajectory. - * @param x states matrix. - * @param u control inputs matrix. + * @param x_in states matrix. + * @param u_in control inputs matrix. * @param u_prev last control input sent to the vehicle. - * @param w slack variables vector for obstacle avoidance. + * @param w_in slack variables vector for obstacle avoidance. * @param goal_x state's goals vector. * @param goal_u control's goals vector. */ std::tuple> ProxQP::solve( - MatrixXd x, MatrixXd u, const VectorXd & u_prev, VectorXd w, const MatrixXd & goal_x, + MatrixXd x_in, MatrixXd u_in, const VectorXd & u_prev, VectorXd w_in, const MatrixXd & goal_x, const MatrixXd & goal_u) { /* Configure QP problem */ - setc(x, u, w, goal_x, goal_u); // c - setE(x, u); // E - setb(x, u); // b - setC(x); // C - setd(x, u, u_prev, w); // d + setc(x_in, u_in, w_in, goal_x, goal_u); // c + setE(x_in, u_in); // E + setb(x_in, u_in); // b + setC(x_in); // C + setd(x_in, u_in, u_prev, w_in); // d /* Sparse problem */ if (qp_type == false) { - // Make constraints matrices sparse - E_sparse = E.sparseView(); - C_sparse = C.sparseView(); - - qp_sparse.settings.initial_guess = initialGuessPolicy(); - qp_sparse.init(H_sparse, c, E_sparse, b, C_sparse, low, upp); + /* Values only: the structure was declared at init and must not move, or + * ProxQP silently ignores the update and the keep-out rows go missing. */ + writeInto(E_sparse, E); + writeInto(C_sparse, C); + + if (warm_start == true && qp_ready == true) { + qp_sparse.settings.initial_guess = initialGuessPolicy(); + qp_sparse.update(H_sparse, c, E_sparse, b, C_sparse, low, upp); + } else { + qp_sparse.settings.initial_guess = coldGuessPolicy(); + qp_sparse.init(H_sparse, c, E_sparse, b, C_sparse, low, upp); + qp_ready = true; + } qp_sparse.solve(); @@ -204,7 +357,7 @@ ProxQP::solve( } /* Dense problem */ else { - qp_dense.settings.initial_guess = initialGuessPolicy(); + qp_dense.settings.initial_guess = coldGuessPolicy(); qp_dense.init(H, c, E, b, C, low, upp); qp_dense.solve(); @@ -218,16 +371,16 @@ ProxQP::solve( /* Update decision variables */ for (size_t i = x_start; i < u_start; i += n) { - x.row(i / n) = result_x.segment(i, n); + x_in.row(i / n) = result_x.segment(i, n); } for (size_t i = u_start; i < w_start; i += m) { - u.row((i - u_start) / m) = result_x.segment(i, m); + u_in.row((i - u_start) / m) = result_x.segment(i, m); } for (size_t i = w_start; i < n_dvars; i++) { - w(i - w_start) = result_x(i); + w_in(i - w_start) = result_x(i); } - return {x, u, w, qp_info}; + return {x_in, u_in, w_in, qp_info}; } /* Fill the objective function Hessian matrix H. */ @@ -257,31 +410,31 @@ void ProxQP::setH() /*! * Fill the objective function coefficients vector c. - * @param x states matrix. - * @param u controls matrix. - * @param w slack variables vector. + * @param x_in states matrix. + * @param u_in controls matrix. + * @param w_in slack variables vector. * @param goal_x state's goals matrix. * @param goal_u control's goals matrix. */ void ProxQP::setc( - const MatrixXd & x, const MatrixXd & u, const VectorXd & w, + const MatrixXd & x_in, const MatrixXd & u_in, const VectorXd & w_in, const MatrixXd & goal_x, const MatrixXd & goal_u) { size_t count = 0; // Intermediate states for (size_t i = x_start; i < u_start - n; i += n) { - c.segment(i, n) = 2 * Q * (x.row(count) - goal_x.row(count)).transpose(); + c.segment(i, n) = 2 * Q * (x_in.row(count) - goal_x.row(count)).transpose(); count++; } // Final state - c.segment(u_start - n, n) = 2 * S * (x.row(count) - goal_x.row(count)).transpose(); + c.segment(u_start - n, n) = 2 * S * (x_in.row(count) - goal_x.row(count)).transpose(); // Control inputs. Matches setH: all Nc blocks, so goal_u's last row is read. count = 0; for (size_t i = u_start; i < w_start; i += m) { - c.segment(i, m) = 2 * R * (u.row(count).transpose() - goal_u.row(count).transpose()); + c.segment(i, m) = 2 * R * (u_in.row(count).transpose() - goal_u.row(count).transpose()); count++; } @@ -289,7 +442,7 @@ void ProxQP::setc( if (obstacle_active == true) { count = 0; for (size_t i = w_start; i < n_dvars; i++) { - c.segment(i, 1) = 2 * W * w(count); + c.segment(i, 1) = 2 * W * w_in(count); count++; } } @@ -297,10 +450,10 @@ void ProxQP::setc( /*! * Fill the equality constraints coefficient matrix E. - * @param x states matrix. - * @param u controls matrix. + * @param x_in states matrix. + * @param u_in controls matrix. */ -void ProxQP::setE(const MatrixXd & x, const MatrixXd & u) +void ProxQP::setE(const MatrixXd & x_in, const MatrixXd & u_in) { /* Initial state */ for (size_t i = x_start; i < eq_idx[0]; i += n) { @@ -312,8 +465,9 @@ void ProxQP::setE(const MatrixXd & x, const MatrixXd & u) size_t col; for (size_t i = eq_idx[0]; i < eq_idx[1]; i += n) { // Update for the current step - model->setX(x.row(count)); - model->setU(u.row(std::clamp(static_cast(count), 0, static_cast(u.rows() - 1)))); + model->setX(x_in.row(count)); + model->setU( + u_in.row(std::clamp(static_cast(count), 0, static_cast(u_in.rows() - 1)))); model->updateA(dt); model->updateB(); @@ -336,19 +490,20 @@ void ProxQP::setE(const MatrixXd & x, const MatrixXd & u) /*! * Fill the equality constraints vector b. - * @param x states matrix. - * @param u controls matrix. + * @param x_in states matrix. + * @param u_in controls matrix. */ -void ProxQP::setb(const MatrixXd & x, const MatrixXd & u) +void ProxQP::setb(const MatrixXd & x_in, const MatrixXd & u_in) { size_t count = 0; /* Model kinematics */ for (size_t i = eq_idx[0]; i < eq_idx[1]; i += n) { // Update for the current step - model->setX(x.row(count)); - model->setU(u.row(std::clamp(static_cast(count), 0, static_cast(u.rows() - 1)))); - model->updatec(dt, x.row(count + 1)); + model->setX(x_in.row(count)); + model->setU( + u_in.row(std::clamp(static_cast(count), 0, static_cast(u_in.rows() - 1)))); + model->updatec(dt, x_in.row(count + 1)); b.segment(i, n) = -model->getc(); @@ -358,9 +513,9 @@ void ProxQP::setb(const MatrixXd & x, const MatrixXd & u) /*! * Fill the inequality constraints coefficients matrix C. - * @param x states matrix. + * @param x_in states matrix. */ -void ProxQP::setC(const MatrixXd & x) +void ProxQP::setC(const MatrixXd & x_in) { size_t i = 0; size_t idx; @@ -409,17 +564,28 @@ void ProxQP::setC(const MatrixXd & x) for (size_t r = ineq_idx[i]; r < ineq_idx[i + 1]; r++) { const size_t slot = r - ineq_idx[i]; // 0 .. Np*K-1 const size_t node = slot / max_obs; // predicted-node index 0 .. Np-1 - col = x_start + n * (node + 1); // position block of predicted node (node+1) + col = x_start + n * (node + 1); // state block of predicted node (node+1) - const double dx = x(node + 1, 0) - obs(slot, 0); - const double dy = x(node + 1, 1) - obs(slot, 1); - double norm = sqrt(dx * dx + dy * dy); + const double dx = x_in(node + 1, idx_pos_x) - obs(slot, 0); + const double dy = x_in(node + 1, idx_pos_y) - obs(slot, 1); + const double raw_norm = sqrt(dx * dx + dy * dy); + double norm = raw_norm; if (norm < kObsNormalEps) {norm = kObsNormalEps;} - const double nx = dx / norm; - const double ny = dy / norm; - - C(r, col) = nx; // x - C(r, col + 1) = ny; // y + double nx; + double ny; + if (raw_norm < kObsNormalEps) { + /* At or near coincidence dx, dy carry no reliable escape direction (dividing + * by the floored norm would emit a zero or non-unit vector); fall back to a + * deterministic unit normal instead. */ + nx = 1.0; + ny = 0.0; + } else { + nx = dx / norm; + ny = dy / norm; + } + + C(r, col + idx_pos_x) = nx; // x + C(r, col + idx_pos_y) = ny; // y C(r, w_start + slot) = 1; // slack obs_h(slot) = norm - obs(slot, 2); // signed distance at node k+1 @@ -427,13 +593,88 @@ void ProxQP::setC(const MatrixXd & x) /* Signed distance at the previous node k for the CBF coupling, against the * SAME obstacle slot at the previous node's time. A predictive (moving) fill * carries a different obstacle position per node, so node k uses obs[slot - - * max_obs]; for node 0 (x(0) is the fixed pose) and for a static fill this - * reduces to obs[slot]. Held constant per SQP iteration (its gradient is not - * added to C); the re-linearization across iterations recovers the value. */ + * max_obs]; for a static fill this reduces to obs[slot]. + * + * Node 0 is the exception: the previous state is x(0), the current pose, and + * the matrix's first block holds the obstacle at state 1, not now. Using it + * evaluates the two sides of the constraint at different obstacle times and + * does so anti-conservatively for a closing obstacle, at the first and most + * actionable constraint in the horizon. The current-time position is + * recovered below. */ const size_t prev_slot = (node >= 1) ? (slot - max_obs) : slot; - const double dxp = x(node, 0) - obs(prev_slot, 0); - const double dyp = x(node, 1) - obs(prev_slot, 1); - obs_h_prev(slot) = sqrt(dxp * dxp + dyp * dyp) - obs(prev_slot, 2); + /* If either this slot or the previous node's slot is unfilled (holds the far + * sentinel), the pair does not describe the same obstacle across two nodes; + * skip the coupling term by leaving obs_h_prev at zero. It enters setd() only + * as (1 - cbf_gamma) * obs_h_prev, which is already exactly zero at the + * shipped cbf_gamma = 1.0, so the whole coupling - value and gradient alike - + * is gated on gamma < 1 and adds nothing at the default. Leaving the gradient + * columns unwritten there also keeps them out of the constraint matrix's + * sparsity pattern, which is what costs factorization work per cycle. */ + if (cbf_gamma < 1.0) { + double gx = 0.0; + double gy = 0.0; + if (obs(slot, 0) >= 0.5 * MPC::kObsFarSentinel || + obs(prev_slot, 0) >= 0.5 * MPC::kObsFarSentinel) + { + obs_h_prev(slot) = 0.0; + } else { + /* Obstacle position at the previous node's own time. For node 0 that is + * the current time, which the matrix carries no block for, so it is + * recovered by extending the first two blocks backward: + * o_0 = 2 o(block 0) - o(block 1). That is exact for a static fill, + * where the two blocks are equal and it returns o(block 0) unchanged, + * and exact for a constant-velocity fill. The clearance radius is a + * per-obstacle constant and is taken from the first block rather than + * extrapolated. */ + double ox = obs(prev_slot, 0); + double oy = obs(prev_slot, 1); + if (node == 0 && Np >= 2) { + const size_t next_slot = slot + max_obs; + if (obs(next_slot, 0) < 0.5 * MPC::kObsFarSentinel) { + const double step_x = obs(slot, 0) - obs(next_slot, 0); + const double step_y = obs(slot, 1) - obs(next_slot, 1); + /* Extrapolation amplifies inter-block noise as 2 e_1 - e_2, so an + * implied displacement no obstacle could have travelled in one step + * is treated as noise and the first block is used as it stands. */ + const double max_step = kMaxObsSpeed * dt; + if (step_x * step_x + step_y * step_y <= max_step * max_step) { + ox = obs(slot, 0) + step_x; + oy = obs(slot, 1) + step_y; + } + } + } + const double dxp = x_in(node, idx_pos_x) - ox; + const double dyp = x_in(node, idx_pos_y) - oy; + const double norm_prev = sqrt(dxp * dxp + dyp * dyp); + obs_h_prev(slot) = norm_prev - obs(prev_slot, 2); + /* Second half of the linearization: the constraint is + * h_{k+1}(p_{k+1}) >= (1 - gamma) h_k(p_k) - s, so the previous node's + * clearance depends on that node's own position too. Carrying only the + * value term made the coupled constraint first-order exact in p_{k+1} + * alone; this row completes it with -(1 - gamma) grad h_k. The same + * deterministic unit fallback as above covers exact coincidence. */ + const double gain = -(1.0 - cbf_gamma); + if (norm_prev < kObsNormalEps) { + gx = gain; + gy = 0.0; + } else { + gx = gain * dxp / norm_prev; + gy = gain * dyp / norm_prev; + } + } + /* Node 0's gradient columns are inert: x(0) is pinned to the current + * pose by the identity equality in setE, so an increment there is fixed + * at zero and these coefficients cannot influence the solution. Writing + * them would still enlarge the constraint matrix's sparsity pattern and + * cost factorization work on every cycle, so they are skipped. Node 0's + * VALUE term above is not inert - it is the constant right-hand side of + * the first coupled constraint - and is always computed. */ + if (node >= 1) { + const size_t col_prev = x_start + n * node; // state block of node k + C(r, col_prev + idx_pos_x) = gx; + C(r, col_prev + idx_pos_y) = gy; + } + } } i++; @@ -448,14 +689,14 @@ void ProxQP::setC(const MatrixXd & x) /*! * Fill the inequality constraints vector d. - * @param x states matrix. - * @param u controls matrix. + * @param x_in states matrix. + * @param u_in controls matrix. * @param u_prev last control input sent to the vehicle. - * @param w slack variables vector. + * @param w_in slack variables vector. */ void ProxQP::setd( - const MatrixXd & x, const MatrixXd & u, const VectorXd & u_prev, - const VectorXd & w) + const MatrixXd & x_in, const MatrixXd & u_in, const VectorXd & u_prev, + const VectorXd & w_in) { size_t i = 0; size_t row; @@ -465,8 +706,8 @@ void ProxQP::setd( /* First control input's bounds */ for (size_t j = 0; j < model->getIneq("du").size(); j++) { idx = model->getIneq("du").at(j)[0]; - low(j) = model->getIneq("du").at(j)[1] * dt + u_prev(idx) - u(0, idx); - upp(j) = model->getIneq("du").at(j)[2] * dt + u_prev(idx) - u(0, idx); + low(j) = model->getIneq("du").at(j)[1] * dt + u_prev(idx) - u_in(0, idx); + upp(j) = model->getIneq("du").at(j)[2] * dt + u_prev(idx) - u_in(0, idx); } /* States' bounds */ @@ -474,8 +715,8 @@ void ProxQP::setd( for (size_t l = ineq_idx[i]; l < ineq_idx[i + 1]; l++) { row = l - ineq_idx[i]; col = model->getIneq("x").at(j)[0]; - low(l) = model->getIneq("x").at(j)[1] - x(row, col); - upp(l) = model->getIneq("x").at(j)[2] - x(row, col); + low(l) = model->getIneq("x").at(j)[1] - x_in(row, col); + upp(l) = model->getIneq("x").at(j)[2] - x_in(row, col); } i++; } @@ -485,8 +726,8 @@ void ProxQP::setd( for (size_t l = ineq_idx[i]; l < ineq_idx[i + 1]; l++) { row = l - ineq_idx[i]; col = model->getIneq("u").at(j)[0]; - low(l) = model->getIneq("u").at(j)[1] - u(row, col); - upp(l) = model->getIneq("u").at(j)[2] - u(row, col); + low(l) = model->getIneq("u").at(j)[1] - u_in(row, col); + upp(l) = model->getIneq("u").at(j)[2] - u_in(row, col); } i++; } @@ -497,8 +738,8 @@ void ProxQP::setd( row = l - ineq_idx[i]; col = model->getIneq("du").at(j)[0]; - low(l) = model->getIneq("du").at(j)[1] * dt - u(row + 1, col) + u(row, col); - upp(l) = model->getIneq("du").at(j)[2] * dt - u(row + 1, col) + u(row, col); + low(l) = model->getIneq("du").at(j)[1] * dt - u_in(row + 1, col) + u_in(row, col); + upp(l) = model->getIneq("du").at(j)[2] * dt - u_in(row + 1, col) + u_in(row, col); } i++; } @@ -511,7 +752,7 @@ void ProxQP::setd( * recovers the pointwise bound -h_{k+1} - w. */ for (size_t r = ineq_idx[i]; r < ineq_idx[i + 1]; r++) { const size_t slot = r - ineq_idx[i]; - low(r) = (1.0 - cbf_gamma) * obs_h_prev(slot) - obs_h(slot) - w(slot); + low(r) = (1.0 - cbf_gamma) * obs_h_prev(slot) - obs_h(slot) - w_in(slot); upp(r) = std::numeric_limits::infinity(); } i++; @@ -519,7 +760,7 @@ void ProxQP::setd( /* Slack lower bounds: dw >= -w, i.e. s = w + dw >= 0. */ for (size_t r = ineq_idx[i]; r < ineq_idx[i + 1]; r++) { const size_t slot = r - ineq_idx[i]; - low(r) = -w(slot); + low(r) = -w_in(slot); upp(r) = std::numeric_limits::infinity(); } i++; @@ -528,152 +769,158 @@ void ProxQP::setd( /*! * Set the intermediate states weight matrix. - * @param Q weight matrix. + * @param new_Q weight matrix. */ -void ProxQP::setQ(MatrixXd Q) {this->Q = Q;} +void ProxQP::setQ(MatrixXd new_Q) {this->Q = new_Q;} /*! * Set the control input weight matrix. - * @param R weight matrix. + * @param new_R weight matrix. */ -void ProxQP::setR(MatrixXd R) {this->R = R;} +void ProxQP::setR(MatrixXd new_R) {this->R = new_R;} /*! * Set the final state weight matrix. - * @param S weight matrix. + * @param new_S weight matrix. */ -void ProxQP::setS(MatrixXd S) {this->S = S;} +void ProxQP::setS(MatrixXd new_S) {this->S = new_S;} /*! * Set the slack variables weight matrix. - * @param W weight matrix. + * @param new_W weight matrix. */ -void ProxQP::setW(MatrixXd W) {this->W = W;} +void ProxQP::setW(MatrixXd new_W) {this->W = new_W;} /*! * Set the number of shooting nodes (state). * If T is set, dt is automatically updated. - * @param Np shooting nodes (> 0). + * @param new_Np shooting nodes (> 0). */ -void ProxQP::setNp(size_t Np) +void ProxQP::setNp(size_t new_Np) { - if (Np == 0) {throw std::invalid_argument("ProxQP::setNp: Np must be > 0");} - this->Np = Np; + if (new_Np == 0) {throw std::invalid_argument("ProxQP::setNp: Np must be > 0");} + this->Np = new_Np; } /*! * Set the number of shooting nodes (control). - * @param Nc shooting nodes (> 0). + * @param new_Nc shooting nodes (> 0). */ -void ProxQP::setNc(size_t Nc) +void ProxQP::setNc(size_t new_Nc) { - if (Nc == 0) {throw std::invalid_argument("ProxQP::setNc: Nc must be > 0");} - this->Nc = Nc; + if (new_Nc == 0) {throw std::invalid_argument("ProxQP::setNc: Nc must be > 0");} + this->Nc = new_Nc; } /*! * Set the step size. - * @param dt step size (> 0). + * @param new_dt step size (> 0). */ -void ProxQP::setdt(double dt) +void ProxQP::setdt(double new_dt) { - if (dt <= 0.0) {throw std::invalid_argument("ProxQP::setdt: dt must be > 0");} - this->dt = dt; + if (new_dt <= 0.0) {throw std::invalid_argument("ProxQP::setdt: dt must be > 0");} + this->dt = new_dt; } /*! * Set the number of equalities. - * @param n_eq equalities (>= 0). + * @param new_n_eq equalities (>= 0). */ -void ProxQP::setNEq(size_t n_eq) +void ProxQP::setNEq(size_t new_n_eq) { - this->n_eq = n_eq; + this->n_eq = new_n_eq; } /*! * Set the number of inequalities. - * @param n_ineq inequalities (>= 0). + * @param new_n_ineq inequalities (>= 0). */ -void ProxQP::setNIneq(size_t n_ineq) +void ProxQP::setNIneq(size_t new_n_ineq) { - this->n_ineq = n_ineq; + this->n_ineq = new_n_ineq; } /*! * Set the maximum number of inner iterations. - * @param max_inn_iter maximum iteration (> 0). + * @param new_max_inn_iter maximum iteration (> 0). */ -void ProxQP::setMaxInIter(size_t max_inn_iter) +void ProxQP::setMaxInIter(size_t new_max_inn_iter) { - if (max_inn_iter == 0) { + if (new_max_inn_iter == 0) { throw std::invalid_argument("ProxQP::setMaxInIter: max_inn_iter must be > 0"); } - this->max_inn_iter = max_inn_iter; + this->max_inn_iter = new_max_inn_iter; } /*! * Set the maximum number of outer iterations. - * @param max_out_iter maximum iteration (> 0). + * @param new_max_out_iter maximum iteration (> 0). */ -void ProxQP::setMaxOutIter(size_t max_out_iter) +void ProxQP::setMaxOutIter(size_t new_max_out_iter) { - if (max_out_iter == 0) { + if (new_max_out_iter == 0) { throw std::invalid_argument("ProxQP::setMaxOutIter: max_out_iter must be > 0"); } - this->max_out_iter = max_out_iter; + this->max_out_iter = new_max_out_iter; } /*! * Set the QP type (sparse or dense). - * @param qp_type sparse (false) or dense (true). + * @param new_qp_type sparse (false) or dense (true). */ -void ProxQP::setQPType(bool qp_type) {this->qp_type = qp_type;} +void ProxQP::setQPType(bool new_qp_type) {this->qp_type = new_qp_type;} /*! * Choose if using initial guesses for warm start. - * @param guess no (false) or yes (true). + * @param new_guess no (false) or yes (true). + */ +void ProxQP::setGuess(bool new_guess) {this->guess = new_guess;} + +/*! + * Enable the cross-cycle QP warm start. + * @param new_warm_start reuse the workspace and the previous iterate. */ -void ProxQP::setGuess(bool guess) {this->guess = guess;} +void ProxQP::setWarmStart(bool new_warm_start) {this->warm_start = new_warm_start;} /*! * Set the discrete-time CBF rate for the obstacle coupling. - * @param cbf_gamma rate in (0, 1]; 1.0 reduces to the pointwise constraint. + * @param new_cbf_gamma rate in (0, 1]; 1.0 reduces to the pointwise constraint. */ -void ProxQP::setCbfGamma(double cbf_gamma) +void ProxQP::setCbfGamma(double new_cbf_gamma) { // Outside (0, 1] the bound (1 - gamma) * h_prev - h - w turns positive for the // far sentinel padding unused slots, making empty slots hard-binding at ~1e6 // and destroying the solve. - if (!(cbf_gamma > 0.0 && cbf_gamma <= 1.0)) { + if (!(new_cbf_gamma > 0.0 && new_cbf_gamma <= 1.0)) { throw std::invalid_argument("ProxQP::setCbfGamma: cbf_gamma must be in (0, 1]"); } - this->cbf_gamma = cbf_gamma; + this->cbf_gamma = new_cbf_gamma; } /*! * Set the obstacle-slot capacity K per predicted node (0 disables avoidance). * Must be set before init() so the QP is sized once. - * @param max_obs capacity K. + * @param new_max_obs capacity K. */ -void ProxQP::setMaxObs(size_t max_obs) {this->max_obs = max_obs;} +void ProxQP::setMaxObs(size_t new_max_obs) {this->max_obs = new_max_obs;} /*! * Set the obstacle triples for the current cycle. - * @param obs (Np*K) x 3 matrix of [o_x, o_y, d_safe] per (node, slot); empty + * @param new_obs (Np*K) x 3 matrix of [o_x, o_y, d_safe] per (node, slot); empty * slots should hold a far sentinel so their soft constraint is non-binding. */ -void ProxQP::setObs(MatrixXd obs) +void ProxQP::setObs(MatrixXd new_obs) { // Shape check: setC indexes obs(slot, .) for slot in [0, Np*max_obs). With // EIGEN_NO_DEBUG the per-step access is unchecked, so reject an undersized // matrix here rather than read out of bounds on the control hot path. if (max_obs > 0) { const Eigen::Index expected_rows = static_cast(Np * max_obs); - if (obs.rows() != expected_rows || obs.cols() != 3) { + if (new_obs.rows() != expected_rows || new_obs.cols() != 3) { throw std::invalid_argument("ProxQP::setObs: obs must be (Np*max_obs) x 3"); } } - this->obs = obs; + this->obs = new_obs; } } // namespace prox_mpc diff --git a/prox_mpc_core/src/utils.cpp b/prox_mpc_core/src/utils.cpp index 3661bcd..43bbbfc 100644 --- a/prox_mpc_core/src/utils.cpp +++ b/prox_mpc_core/src/utils.cpp @@ -38,8 +38,8 @@ Path optimPath(const MatrixXd & x, const rclcpp::Time & now) path.poses.push_back(pose); } - for (auto & pose: path.poses) { - pose.header.stamp = now; + for (auto & stamped_pose: path.poses) { + stamped_pose.header.stamp = now; } return path; diff --git a/prox_mpc_core/test/test_config_lifecycle.cpp b/prox_mpc_core/test/test_config_lifecycle.cpp new file mode 100644 index 0000000..3c09ef8 --- /dev/null +++ b/prox_mpc_core/test/test_config_lifecycle.cpp @@ -0,0 +1,301 @@ +// Copyright 2026 Simone Contorno +// SPDX-License-Identifier: Apache-2.0 + + +// Contract tests for the post-init() configuration lifecycle (decision: reject +// after init, not a validated rebuild), the weight-matrix validation init() +// gained alongside it, the setGoalX()/setGoalU() undersized-matrix rejection, +// and MPC::setObs()'s single accepted shape. + +#include +#include +#include +#include + +#include + +#include +#include + +using prox_mpc::MPC; +using prox_mpc::Unicycle; + +namespace +{ +// A minimal initialized MPC (Unicycle, Np = Nc = 5), for tests that only need +// a post-init() object to call a structural setter against. +std::shared_ptr makeInitialized() +{ + auto model = std::make_shared(); + auto mpc = std::make_shared(); + mpc->setNp(5); + mpc->setNc(5); + mpc->setdt(0.1); + mpc->init(model); + return mpc; +} +} // namespace + +// --- Structural setters reject a post-init() call ---------------------------- +// +// Every setter whose value the sized buffers or the QP object are built from: +// setQ, setR, setS, setW, setNp, setNc, setdt, setT, setMaxIntIterQP, +// setMaxExtIterQP, setGuess, setQPtype, setCbfGamma and setMaxObs. Each throws +// std::logic_error rather than mutating a member the sized buffers and the QP +// object no longer agree with (decision: reject after init, not the pruned +// validated-rebuild alternative). + +TEST(ConfigLifecycle, SetQRejectsAfterInit) +{ + auto mpc = makeInitialized(); + EXPECT_THROW(mpc->setQ(MatrixXd::Identity(3, 3)), std::logic_error); +} + +TEST(ConfigLifecycle, SetRRejectsAfterInit) +{ + auto mpc = makeInitialized(); + EXPECT_THROW(mpc->setR(MatrixXd::Identity(2, 2)), std::logic_error); +} + +TEST(ConfigLifecycle, SetSRejectsAfterInit) +{ + auto mpc = makeInitialized(); + EXPECT_THROW(mpc->setS(MatrixXd::Identity(3, 3)), std::logic_error); +} + +TEST(ConfigLifecycle, SetWRejectsAfterInit) +{ + auto mpc = makeInitialized(); + EXPECT_THROW(mpc->setW(MatrixXd::Constant(1, 1, 1.0)), std::logic_error); +} + +TEST(ConfigLifecycle, SetNpRejectsAfterInit) +{ + auto mpc = makeInitialized(); + EXPECT_THROW(mpc->setNp(6), std::logic_error); +} + +TEST(ConfigLifecycle, SetNcRejectsAfterInit) +{ + auto mpc = makeInitialized(); + EXPECT_THROW(mpc->setNc(4), std::logic_error); +} + +TEST(ConfigLifecycle, SetdtRejectsAfterInit) +{ + auto mpc = makeInitialized(); + EXPECT_THROW(mpc->setdt(0.2), std::logic_error); +} + +TEST(ConfigLifecycle, SetTRejectsAfterInit) +{ + auto mpc = makeInitialized(); + EXPECT_THROW(mpc->setT(1.0), std::logic_error); +} + +TEST(ConfigLifecycle, SetMaxIntIterQPRejectsAfterInit) +{ + auto mpc = makeInitialized(); + EXPECT_THROW(mpc->setMaxIntIterQP(100), std::logic_error); +} + +TEST(ConfigLifecycle, SetMaxExtIterQPRejectsAfterInit) +{ + auto mpc = makeInitialized(); + EXPECT_THROW(mpc->setMaxExtIterQP(100), std::logic_error); +} + +TEST(ConfigLifecycle, SetGuessRejectsAfterInit) +{ + auto mpc = makeInitialized(); + EXPECT_THROW(mpc->setGuess(false), std::logic_error); +} + +TEST(ConfigLifecycle, SetQPtypeRejectsAfterInit) +{ + auto mpc = makeInitialized(); + EXPECT_THROW(mpc->setQPtype(true), std::logic_error); +} + +// The CBF rate reaches the solver only through configProxQP(), which init() +// runs once, so a post-init() call used to be accepted and then have no effect +// on the QP it appears to configure. +TEST(ConfigLifecycle, SetCbfGammaRejectsAfterInit) +{ + auto mpc = makeInitialized(); + EXPECT_THROW(mpc->setCbfGamma(0.5), std::logic_error); +} + +// The obstacle-slot capacity is as structural as the horizon: init() sizes the +// obstacle matrix and the QP's own slot count from it. +TEST(ConfigLifecycle, SetMaxObsRejectsAfterInit) +{ + auto mpc = makeInitialized(); + EXPECT_THROW(mpc->setMaxObs(4), std::logic_error); +} + +// The exception names both the class and the setter, so a caller reading the +// log can tell which precondition it violated without a debugger. +TEST(ConfigLifecycle, RejectionMessageNamesSetter) +{ + auto mpc = makeInitialized(); + try { + mpc->setNp(6); + FAIL() << "setNp after init() must throw"; + } catch (const std::logic_error & ex) { + const std::string what(ex.what()); + EXPECT_NE(what.find("setNp"), std::string::npos) << what; + } +} + +// --- Weight-matrix validation in init() -------------------------------------- +// +// init() throws std::invalid_argument unless Q, S, R and W are finite, +// symmetric and positive semidefinite; 1.0.0 accepted an asymmetric or +// indefinite weight and silently solved the symmetrized problem instead. + +TEST(ConfigLifecycle, InitRejectsAsymmetricQ) +{ + auto model = std::make_shared(); + auto mpc = std::make_shared(); + mpc->setNp(5); + mpc->setNc(5); + mpc->setdt(0.1); + MatrixXd q = MatrixXd::Identity(3, 3); + q(0, 1) = 1.0; // q(1, 0) stays 0: asymmetric + mpc->setQ(q); + EXPECT_THROW(mpc->init(model), std::invalid_argument); +} + +TEST(ConfigLifecycle, InitRejectsIndefiniteS) +{ + auto model = std::make_shared(); + auto mpc = std::make_shared(); + mpc->setNp(5); + mpc->setNc(5); + mpc->setdt(0.1); + MatrixXd s = MatrixXd::Identity(3, 3); + s(2, 2) = -1.0; // symmetric but has a negative eigenvalue + mpc->setS(s); + EXPECT_THROW(mpc->init(model), std::invalid_argument); +} + +TEST(ConfigLifecycle, InitRejectsNonFiniteR) +{ + auto model = std::make_shared(); + auto mpc = std::make_shared(); + mpc->setNp(5); + mpc->setNc(5); + mpc->setdt(0.1); + MatrixXd r = MatrixXd::Identity(2, 2); + r(0, 0) = std::numeric_limits::quiet_NaN(); + mpc->setR(r); + EXPECT_THROW(mpc->init(model), std::invalid_argument); +} + +TEST(ConfigLifecycle, InitRejectsIndefiniteW) +{ + auto model = std::make_shared(); + auto mpc = std::make_shared(); + mpc->setNp(5); + mpc->setNc(5); + mpc->setdt(0.1); + mpc->setW(MatrixXd::Constant(1, 1, -1.0)); // negative -> indefinite + EXPECT_THROW(mpc->init(model), std::invalid_argument); +} + +// A finite, symmetric, positive-semidefinite set of weights (including the +// diagonal-with-zero edge case, still PSD) still initializes. +TEST(ConfigLifecycle, InitAcceptsValidWeights) +{ + auto model = std::make_shared(); + auto mpc = std::make_shared(); + mpc->setNp(5); + mpc->setNc(5); + mpc->setdt(0.1); + mpc->setQ(MatrixXd::Identity(3, 3)); + mpc->setS(2.0 * MatrixXd::Identity(3, 3)); + mpc->setR(0.1 * MatrixXd::Identity(2, 2)); + mpc->setW(MatrixXd::Constant(1, 1, 0.0)); + EXPECT_NO_THROW(mpc->init(model)); +} + +// --- setGoalX / setGoalU undersized-matrix rejection ------------------------- +// +// setc() indexes goal_x.row(Np) and goal_u.row(Nc - 1) (proxqp.cpp); an +// undersized matrix from a direct core consumer used to be a silent +// out-of-bounds read there with EIGEN_NO_DEBUG on. Both setters now validate +// row and column counts once Np/Nc/n/m are known. + +TEST(ConfigLifecycle, SetGoalXRejectsTooFewRows) +{ + auto mpc = makeInitialized(); // Np = 5, n = 3 + EXPECT_THROW(mpc->setGoalX(MatrixXd::Zero(5, 3)), std::invalid_argument); // needs Np+1 = 6 + EXPECT_NO_THROW(mpc->setGoalX(MatrixXd::Zero(6, 3))); +} + +TEST(ConfigLifecycle, SetGoalXRejectsWrongColumnCount) +{ + auto mpc = makeInitialized(); // n = 3 + EXPECT_THROW(mpc->setGoalX(MatrixXd::Zero(6, 2)), std::invalid_argument); + EXPECT_THROW(mpc->setGoalX(MatrixXd::Zero(6, 4)), std::invalid_argument); +} + +TEST(ConfigLifecycle, SetGoalURejectsTooFewRows) +{ + auto mpc = makeInitialized(); // Nc = 5, m = 2 + EXPECT_THROW(mpc->setGoalU(MatrixXd::Zero(4, 2)), std::invalid_argument); // needs Nc = 5 + EXPECT_NO_THROW(mpc->setGoalU(MatrixXd::Zero(5, 2))); +} + +TEST(ConfigLifecycle, SetGoalURejectsWrongColumnCount) +{ + auto mpc = makeInitialized(); // m = 2 + EXPECT_THROW(mpc->setGoalU(MatrixXd::Zero(5, 1)), std::invalid_argument); + EXPECT_THROW(mpc->setGoalU(MatrixXd::Zero(5, 3)), std::invalid_argument); +} + +// The precondition is checked before Np/Nc/n/m are known too (pre-init call): +// with none of them known yet, an arbitrarily-shaped matrix is accepted, and +// is then validated retroactively as soon as init() (or setNp()/setNc()) +// establishes the missing dimension. +TEST(ConfigLifecycle, SetGoalXAcceptsAnyShapeBeforeHorizonKnown) +{ + MPC mpc; + EXPECT_NO_THROW(mpc.setGoalX(MatrixXd::Zero(1, 1))); +} + +// --- MPC::setObs: exactly Np*K rows, no other shape ------------------------- +// +// A second accepted shape, (Np + 1) * K, was briefly implemented and +// deliberately retired; MPC::setObs() itself performs no validation (it is a +// raw assignment), but the mismatch is caught the first time the stored +// matrix reaches ProxQP::setObs() inside solveCandidate(). + +TEST(ConfigLifecycle, SetObsRejectsNpPlusOneRowsAtSolveTime) +{ + auto model = std::make_shared(); + auto mpc = std::make_shared(); + mpc->setNp(5); + mpc->setNc(5); + mpc->setdt(0.1); + mpc->setMaxObs(1); + mpc->init(model); // Np = 5, K = 1 -> the solver expects exactly 5 rows + + mpc->setGoalX(MatrixXd::Zero(6, 3)); + mpc->setGoalU(MatrixXd::Zero(5, 2)); + mpc->setPose(VectorXd::Zero(3)); + + // (Np + 1) * K = 6 rows: the retired second shape, must not be accepted. + mpc->setObs(MatrixXd::Zero(6, 3)); + EXPECT_THROW(mpc->solveCandidate(), std::invalid_argument); + + // The single accepted shape, Np * K = 5 rows, still solves. + MatrixXd obs_ok = MatrixXd::Zero(5, 3); + for (Eigen::Index r = 0; r < obs_ok.rows(); r++) { + obs_ok(r, 0) = MPC::kObsFarSentinel; + obs_ok(r, 1) = MPC::kObsFarSentinel; + } + mpc->setObs(obs_ok); + EXPECT_NO_THROW(mpc->solveCandidate()); +} diff --git a/prox_mpc_core/test/test_custom_model.cpp b/prox_mpc_core/test/test_custom_model.cpp index 71b1e8e..bf4c399 100644 --- a/prox_mpc_core/test/test_custom_model.cpp +++ b/prox_mpc_core/test/test_custom_model.cpp @@ -9,6 +9,7 @@ #include #include +#include #include @@ -262,6 +263,25 @@ TEST(CustomModel, TerminalControlBlockCarriesTheControlWeight) } } +// setIneq() validates the bound index against the model's declared state/control +// dimension where it is known, instead of writing an out-of-range row when the +// QP is assembled. +TEST(CustomModel, SetIneqRejectsIndexOutOfRange) +{ + DummyLinear model; // n = 2, m = 2 + EXPECT_THROW(model.setIneq("x", 5, -1.0, 1.0), std::invalid_argument); + EXPECT_THROW(model.setIneq("u", 5, -1.0, 1.0), std::invalid_argument); + EXPECT_NO_THROW(model.setIneq("x", 1, -1.0, 1.0)); // in range +} + +// updateIneq() reports a bound it cannot find instead of silently doing nothing. +TEST(CustomModel, UpdateIneqReportsMissingBound) +{ + DummyLinear model; // declares "u" bounds only, no "x" bound + EXPECT_THROW(model.updateIneq("x", 0, -1.0, 1.0), std::invalid_argument); + EXPECT_NO_THROW(model.updateIneq("u", 0, -1.5, 1.5)); // existing bound +} + // Negative compile check: a model that omits an override stays abstract and // cannot be instantiated. Define PROX_MPC_NEGATIVE_COMPILE_CHECK to confirm the // build fails with an abstract-type error. diff --git a/prox_mpc_core/test/test_deprecated_alias.cpp b/prox_mpc_core/test/test_deprecated_alias.cpp new file mode 100644 index 0000000..7636a66 --- /dev/null +++ b/prox_mpc_core/test/test_deprecated_alias.cpp @@ -0,0 +1,89 @@ +// Copyright 2026 Simone Contorno +// SPDX-License-Identifier: Apache-2.0 + + +// The deprecated prox_mpc_core/Bicycle alias's runtime warning: what it says +// and how often it is said. +// +// This is its own binary because the property under test is process-scoped. The +// warning is gated on a std::once_flag, so any other test that constructs a +// Bicycle first consumes it and leaves nothing to observe; test_model_interface +// constructs several. + +#include +#include +#include +#include + +#include + +#include + +#include + +using prox_mpc::Bicycle; + +namespace +{ +// Collects WARN and above from the rcutils logging handler, restoring the +// previous handler on destruction. +class LogCapture +{ +public: + LogCapture() + : previous_(rcutils_logging_get_output_handler()) + { + messages_.clear(); + rcutils_logging_set_output_handler(&LogCapture::handle); + } + ~LogCapture() {rcutils_logging_set_output_handler(previous_);} + + static const std::vector & messages() {return messages_;} + +private: + static void handle( + const rcutils_log_location_t *, int severity, const char *, + rcutils_time_point_value_t, const char * format, va_list * args) + { + if (severity < RCUTILS_LOG_SEVERITY_WARN) {return;} + char buf[1024]; + va_list copy; + va_copy(copy, *args); + vsnprintf(buf, sizeof(buf), format, copy); + va_end(copy); + messages_.emplace_back(buf); + } + + rcutils_logging_output_handler_t previous_; + static std::vector messages_; +}; +std::vector LogCapture::messages_; + +std::size_t countDeprecationWarnings() +{ + std::size_t n = 0; + for (const auto & m : LogCapture::messages()) { + if (m.find("'prox_mpc_core/Bicycle' is deprecated") != std::string::npos) {n++;} + } + return n; +} +} // namespace + +// One warning per process, however many times the alias is constructed, and it +// names both the replacement plugin and the behaviour that changed with the +// rename: an operator upgrading a 1.0.0 configuration gets the same model under +// a new name, but not the same emitted twist or the same collision-check pose. +TEST(DeprecatedAlias, WarnsOncePerProcessAndNamesTheBehaviourChange) +{ + LogCapture log; + Bicycle first; + Bicycle second; + Bicycle third; + + ASSERT_EQ(countDeprecationWarnings(), 1u); + const std::string & warning = LogCapture::messages().front(); + EXPECT_NE(warning.find("prox_mpc_core/BicycleFrontAxle"), std::string::npos) << warning; + EXPECT_NE(warning.find("prox_mpc_core/BicycleRearAxle"), std::string::npos) << warning; + EXPECT_NE(warning.find("twist"), std::string::npos) << warning; + EXPECT_NE(warning.find("collision check"), std::string::npos) << warning; +} diff --git a/prox_mpc_core/test/test_model_interface.cpp b/prox_mpc_core/test/test_model_interface.cpp index e0ac80b..ca89f7a 100644 --- a/prox_mpc_core/test/test_model_interface.cpp +++ b/prox_mpc_core/test/test_model_interface.cpp @@ -4,20 +4,27 @@ // Tests for the Model interface using the bundled models: name, dimensions, // declared bounds, the analytic forward-Euler residual and Jacobians, and the -// configure() and toTwist() hooks. +// configure(), toTwist() and fromTwist() hooks. #include +#include #include #include #include #include +#include + #include #include +#include +#include #include using prox_mpc::Bicycle; +using prox_mpc::BicycleFrontAxle; +using prox_mpc::BicycleRearAxle; using prox_mpc::Unicycle; using prox_mpc::Model; @@ -38,6 +45,25 @@ void getBound(Model & model, const std::string & var, size_t idx, double & low, } ASSERT_TRUE(found) << "bound not declared: " << var << "[" << idx << "]"; } + +// A four-state, two-control model that overrides nothing: no updatec/updateA/ +// updateB call matters here (getPlanarMapping() never solves), so they are +// stubs. Used to pin Model::getPlanarMapping()'s default inference for a model +// that declares no mapping of its own: state count > 3 infers a steering angle +// at index 3, and control count > 1 infers its rate at control index 1. +class BareFourStateModel : public Model +{ +public: + BareFourStateModel() + { + setName("bare_four_state"); + setN(4); + setM(2); + } + void updatec(double, VectorXd) override {} + void updateA(double) override {} + void updateB() override {} +}; } // namespace TEST(ModelInterface, BicycleIdentityAndBounds) @@ -247,15 +273,548 @@ TEST(ModelInterface, ToTwistSemantics) EXPECT_NEAR(tw_u.linear.x, 0.7, kTol); EXPECT_NEAR(tw_u.angular.z, 0.3, kTol); - Bicycle bicycle; const double L = 1.6; const double delta = 0.2; VectorXd xb(4); xb << 0.0, 0.0, 0.0, delta; - bicycle.setX(xb); VectorXd ub(2); - ub << 0.7, 0.1; // [v, delta_dot]; omega = v sin(delta)/L + ub << 0.7, 0.1; // [v, delta_dot] + + // Both bicycles report the body twist of base_link, so the front-axle model's + // control - the front-wheel speed - is projected onto the body x axis, while + // the rear-axle model's control is already that speed. The yaw rate follows + // each model's own steering law. + BicycleFrontAxle front; + front.setX(xb); + auto tw_f = front.toTwist(ub); + EXPECT_NEAR(tw_f.linear.x, 0.7 * std::cos(delta), kTol); + EXPECT_NEAR(tw_f.angular.z, 0.7 * std::sin(delta) / L, kTol); + + BicycleRearAxle rear; + rear.setX(xb); + auto tw_r = rear.toTwist(ub); + EXPECT_NEAR(tw_r.linear.x, 0.7, kTol); + EXPECT_NEAR(tw_r.angular.z, 0.7 * std::tan(delta) / L, kTol); + + // The deprecated alias is the front-axle model. + Bicycle bicycle; + bicycle.setX(xb); auto tw_b = bicycle.toTwist(ub); - EXPECT_NEAR(tw_b.linear.x, 0.7, kTol); - EXPECT_NEAR(tw_b.angular.z, 0.7 * std::sin(delta) / L, kTol); + EXPECT_NEAR(tw_b.linear.x, tw_f.linear.x, kTol); + EXPECT_NEAR(tw_b.angular.z, tw_f.angular.z, kTol); +} + +// fromTwist recovers the control a twist was produced from, for the channels a +// twist determines. The unicycle and the rear-axle model both carry the +// base_link speed in control 0, so the base class default reads it straight +// out; the front-axle model carries a front-wheel speed there, which only the +// (linear.x, angular.z) pair together determines, and its override says so. No +// twist observes a steering rate, so the front-axle override leaves control 1 +// undetermined for the caller to fill from somewhere else. +TEST(ModelInterface, FromTwistInvertsToTwist) +{ + Unicycle uni; + geometry_msgs::msg::Twist tw; + tw.linear.x = 0.7; + tw.angular.z = 0.3; + const VectorXd u_uni = uni.fromTwist(tw); + ASSERT_EQ(u_uni.size(), 2); + EXPECT_NEAR(u_uni(0), 0.7, kTol); + EXPECT_NEAR(u_uni(1), 0.3, kTol); + + const double delta = 0.2; + VectorXd xb(4); + xb << 0.0, 0.0, 0.0, delta; + VectorXd ub(2); + ub << 0.7, 0.1; // [v, delta_dot] + + BicycleFrontAxle front; + front.setX(xb); + const VectorXd u_front = front.fromTwist(front.toTwist(ub)); + ASSERT_EQ(u_front.size(), 2); + EXPECT_NEAR(u_front(0), 0.7, kTol); // the front-wheel speed, not its projection + EXPECT_FALSE(std::isfinite(u_front(1))); // delta_dot is not observable in a twist + + BicycleRearAxle rear; + rear.setX(xb); + const VectorXd u_rear = rear.fromTwist(rear.toTwist(ub)); + ASSERT_EQ(u_rear.size(), 2); + EXPECT_NEAR(u_rear(0), 0.7, kTol); // control 0 is already the base_link speed + EXPECT_FALSE(std::isfinite(u_rear(1))); // delta_dot is not observable here either +} + +// Both bicycles override the inverse because both override toTwist, and the +// base class default is the inverse of the mapping neither of them uses: it +// returns angular.z in control 1, a body yaw rate, while control 1 on either +// bicycle is a steering rate. The rear axle is the case where that is easy to +// miss, since its control 0 does match the default. Driven head-on, where the +// emitted yaw rate is zero, so an inherited default would return a plausible +// finite 0.0 in the steering-rate slot rather than an obviously wrong number. +TEST(ModelInterface, RearAxleFromTwistLeavesTheSteeringRateUndetermined) +{ + BicycleRearAxle rear; + VectorXd xb(4); + xb << 0.0, 0.0, 0.0, 0.0; // straight ahead: toTwist emits angular.z == 0 + rear.setX(xb); + VectorXd ub(2); + ub << 1.3, 0.4; // [v, delta_dot], with a non-zero steering rate + + const geometry_msgs::msg::Twist tw = rear.toTwist(ub); + ASSERT_NEAR(tw.angular.z, 0.0, kTol); + + const VectorXd u = rear.fromTwist(tw); + ASSERT_EQ(u.size(), 2); + EXPECT_NEAR(u(0), 1.3, kTol); // round-trips the base_link speed + EXPECT_FALSE(std::isfinite(u(1))); // not 0.0: the twist says nothing about delta_dot + + // Reverse travel keeps its sign; there is no magnitude to recover here. + ub(0) = -0.8; + rear.setX(xb); + EXPECT_NEAR(rear.fromTwist(rear.toTwist(ub))(0), -0.8, kTol); +} + +// The front-axle inverse is singularity-free at the model's own +/- pi/2 +// steering bound, where cos(delta) is zero and the projection carries no +// direction, and it recovers the sign of a reversing speed. +TEST(ModelInterface, FrontAxleFromTwistHandlesFullLockAndReverse) +{ + BicycleFrontAxle front; + VectorXd xb(4); + xb << 0.0, 0.0, 0.0, M_PI / 2; + front.setX(xb); + VectorXd ub(2); + ub << 0.7, 0.0; + EXPECT_NEAR(front.fromTwist(front.toTwist(ub))(0), 0.7, 1e-9); + + xb(3) = -0.4; + front.setX(xb); + ub(0) = -0.9; + EXPECT_NEAR(front.fromTwist(front.toTwist(ub))(0), -0.9, kTol); +} + +// Every bundled model's two twist mappings agree: for each control fromTwist() +// reports as determined, it returns the control toTwist() was given. This is +// the guard on the hazard the pair creates - a model that overrides toTwist() +// and inherits the base fromTwist() gets an inverse of a mapping it does not +// use, and the consumer that seeds a control vector from a measured twist then +// writes a plausible-looking wrong number into that channel. It is the +// steering-rate channel of either bicycle that this catches: the base default +// returns angular.z there, a body yaw rate, which is neither of their control +// 1. A channel reported non-finite carries no claim and is skipped. +TEST(ModelInterface, FromTwistAgreesWithToTwistOnEveryDeterminedChannel) +{ + VectorXd x3 = VectorXd::Zero(3); + VectorXd x4(4); + x4 << 0.0, 0.0, 0.0, 0.35; // a steering angle the yaw laws actually use + VectorXd u(2); + // Control 1 is deliberately far from the yaw rate this state and speed imply + // (about 0.25 rad/s for either bicycle), so a channel filled from angular.z + // instead of from the control is unmistakable rather than merely off. + u << 1.1, 0.9; // [v, omega] or [v, delta_dot], per model + + Unicycle uni; + uni.setX(x3); + BicycleFrontAxle front; + front.setX(x4); + BicycleRearAxle rear; + rear.setX(x4); + Bicycle alias; // deprecated, and still held to the same contract + alias.setX(x4); + + struct Case + { + const char * name; + Model * model; + }; + const Case cases[] = { + {"Unicycle", &uni}, + {"BicycleFrontAxle", &front}, + {"BicycleRearAxle", &rear}, + {"Bicycle", &alias}, + }; + + for (const auto & item : cases) { + SCOPED_TRACE(item.name); + const VectorXd back = item.model->fromTwist(item.model->toTwist(u)); + ASSERT_EQ(back.size(), static_cast(item.model->getM())); + bool any_determined = false; + for (Eigen::Index j = 0; j < back.size(); j++) { + if (!std::isfinite(back(j))) {continue;} + any_determined = true; + EXPECT_NEAR(back(j), u(j), 1e-9) << "control " << j; + } + // A model determining nothing would pass the loop vacuously. + EXPECT_TRUE(any_determined); + } +} + +// --- BicycleRearAxle: identity, bounds, residual and Jacobians -------------- +// +// BicycleFrontAxle (via the Bicycle alias) is covered above; BicycleRearAxle's +// own name, bounds and kinematics (v tan(delta)/L rather than v sin(delta)/L, +// and the steering bound capped at 1.0 rad rather than pi/2) are untested +// anywhere before this. + +TEST(ModelInterface, RearAxleIdentityAndBounds) +{ + BicycleRearAxle model; + EXPECT_EQ(model.getName(), "bicycle_rear_axle"); + EXPECT_EQ(model.getN(), 4u); + EXPECT_EQ(model.getM(), 2u); + EXPECT_NEAR(model.getParams()(0), 1.6, kTol); // wheelbase L + + double low = 0.0; + double upp = 0.0; + // Capped at 1.0 rad (not the front axle's pi/2): the rear-axle yaw law + // v tan(delta)/L diverges as |delta| approaches pi/2. + getBound(model, "x", 3, low, upp); + EXPECT_NEAR(low, -1.0, kTol); + EXPECT_NEAR(upp, 1.0, kTol); + getBound(model, "u", 0, low, upp); + EXPECT_NEAR(low, -3.0, kTol); + EXPECT_NEAR(upp, 3.0, kTol); + getBound(model, "du", 0, low, upp); + EXPECT_NEAR(low, -0.5, kTol); + EXPECT_NEAR(upp, 0.5, kTol); +} + +TEST(ModelInterface, RearAxleEulerResidualAndJacobians) +{ + BicycleRearAxle model; + const double dt = 0.1; + const double L = 1.6; + + VectorXd x(4); + x << 1.0, 2.0, 0.3, 0.1; // [x, y, theta, delta] + VectorXd u(2); + u << 0.7, 0.2; // [v, delta_dot] + VectorXd x_next(4); + x_next << 1.05, 2.07, 0.34, 0.12; + + model.setX(x); + model.setU(u); + model.updatec(dt, x_next); + model.updateA(dt); + model.updateB(); + + const double v = u(0); + const double theta = x(2); + const double delta = x(3); + const double sec2 = 1.0 / (std::cos(delta) * std::cos(delta)); + + VectorXd c_exp(4); + c_exp << x(0) - x_next(0) + dt * v * std::cos(theta), + x(1) - x_next(1) + dt * v * std::sin(theta), + x(2) - x_next(2) + dt * v * std::tan(delta) / L, + x(3) - x_next(3) + dt * u(1); + for (int i = 0; i < 4; i++) { + EXPECT_NEAR(model.getc()(i), c_exp(i), kTol); + } + + MatrixXd a_exp(4, 4); + a_exp << 1.0, 0.0, -dt * v * std::sin(theta), 0.0, + 0.0, 1.0, dt * v * std::cos(theta), 0.0, + 0.0, 0.0, 1.0, dt * v * sec2 / L, + 0.0, 0.0, 0.0, 1.0; + for (int r = 0; r < 4; r++) { + for (int col = 0; col < 4; col++) { + EXPECT_NEAR(model.getA()(r, col), a_exp(r, col), kTol); + } + } + + MatrixXd b_exp(4, 2); + b_exp << std::cos(theta), 0.0, + std::sin(theta), 0.0, + std::tan(delta) / L, 0.0, + 0.0, 1.0; + for (int r = 0; r < 4; r++) { + for (int col = 0; col < 2; col++) { + EXPECT_NEAR(model.getB()(r, col), b_exp(r, col), kTol); + } + } +} + +// The rear-axle yaw law diverges as |delta| -> pi/2, so a steering bound past +// the 1.0 rad cap is rejected at configure() rather than silently poisoning A, +// B and c with a near-infinite Jacobian entry. +TEST(ModelInterface, RearAxleRejectsSteerBoundBeyondCap) +{ + BicycleRearAxle model; + EXPECT_THROW(model.configure({{"delta_max", 1.2}}), std::invalid_argument); + EXPECT_THROW(model.configure({{"delta_min", -1.4}}), std::invalid_argument); + EXPECT_NO_THROW(model.configure({{"delta_min", -1.0}, {"delta_max", 1.0}})); + double low = 0.0; + double upp = 0.0; + getBound(model, "x", 3, low, upp); + EXPECT_NEAR(low, -1.0, kTol); + EXPECT_NEAR(upp, 1.0, kTol); +} + +// A non-finite steering bound is rejected too. The cap test is a bare ">", +// which is false for NaN, so nothing but an explicit finiteness check keeps a +// NaN out of the state-bound rows the QP is assembled from. +TEST(ModelInterface, RearAxleRejectsNonFiniteSteerBound) +{ + const double nan = std::numeric_limits::quiet_NaN(); + const double inf = std::numeric_limits::infinity(); + BicycleRearAxle model; + EXPECT_THROW(model.configure({{"delta_max", nan}}), std::invalid_argument); + EXPECT_THROW(model.configure({{"delta_min", -inf}}), std::invalid_argument); + + // The declared bounds are untouched by a rejected configure(). + double low = 0.0; + double upp = 0.0; + getBound(model, "x", 3, low, upp); + EXPECT_NEAR(low, -BicycleRearAxle::kMaxSteerAngle, kTol); + EXPECT_NEAR(upp, BicycleRearAxle::kMaxSteerAngle, kTol); +} + +// --- Model::getPlanarMapping() ----------------------------------------------- +// +// A non-pure virtual added after 1.0.0. Pin the bundled models' declared +// mappings and the base class default a model that overrides nothing falls +// back to. + +// Unicycle carries no steering state (n == 3), so the default mapping declares +// none: the base class only infers a steering angle for a model with more than +// three states. +TEST(ModelInterface, UnicyclePlanarMappingDeclaresNoSteering) +{ + Unicycle model; + const auto mapping = model.getPlanarMapping(); + EXPECT_EQ(mapping.idx_x, 0u); + EXPECT_EQ(mapping.idx_y, 1u); + EXPECT_EQ(mapping.idx_yaw, 2u); + EXPECT_EQ(mapping.idx_speed, 0u); + EXPECT_EQ(mapping.idx_steering, prox_mpc::PlanarMapping::kNoIndex); + EXPECT_EQ(mapping.idx_steer_rate, prox_mpc::PlanarMapping::kNoIndex); + EXPECT_NEAR(mapping.ref_offset_x, 0.0, kTol); + EXPECT_NEAR(mapping.ref_offset_y, 0.0, kTol); + EXPECT_NEAR(mapping.wheelbase, 0.0, kTol); +} + +// A model with more than three states and more than one control that declares +// no override still drives: the base class default infers a steering angle at +// state index 3 and its rate at control index 1, with no reference offset and +// no wheelbase declared. +TEST(ModelInterface, DefaultPlanarMappingInfersSteeringForUndeclaredFourStateModel) +{ + BareFourStateModel model; + const auto mapping = model.getPlanarMapping(); + EXPECT_EQ(mapping.idx_steering, 3u); + EXPECT_EQ(mapping.idx_steer_rate, 1u); + EXPECT_NEAR(mapping.ref_offset_x, 0.0, kTol); + EXPECT_NEAR(mapping.ref_offset_y, 0.0, kTol); + EXPECT_NEAR(mapping.wheelbase, 0.0, kTol); // undeclared +} + +// BicycleFrontAxle declares its reference point one wheelbase ahead of +// base_link on the body x axis, which is also the wheelbase the steering +// geometry uses. +TEST(ModelInterface, FrontAxlePlanarMappingDeclaresForwardOffset) +{ + BicycleFrontAxle model; + const auto mapping = model.getPlanarMapping(); + EXPECT_EQ(mapping.idx_steering, 3u); + EXPECT_EQ(mapping.idx_steer_rate, 1u); + EXPECT_NEAR(mapping.ref_offset_x, 1.6, kTol); + EXPECT_NEAR(mapping.ref_offset_y, 0.0, kTol); + EXPECT_NEAR(mapping.wheelbase, 1.6, kTol); +} + +// BicycleRearAxle's state already refers to base_link, so its reference offset +// is zero even though it declares a steering angle. +TEST(ModelInterface, RearAxlePlanarMappingDeclaresNoOffset) +{ + BicycleRearAxle model; + const auto mapping = model.getPlanarMapping(); + EXPECT_EQ(mapping.idx_steering, 3u); + EXPECT_EQ(mapping.idx_steer_rate, 1u); + EXPECT_NEAR(mapping.ref_offset_x, 0.0, kTol); + EXPECT_NEAR(mapping.ref_offset_y, 0.0, kTol); + EXPECT_NEAR(mapping.wheelbase, 1.6, kTol); +} + +// The deprecated Bicycle alias does not override getPlanarMapping(), so it +// inherits BicycleFrontAxle's, resolving the alias physically as well as by +// dynamics. +TEST(ModelInterface, BicycleAliasInheritsFrontAxlePlanarMapping) +{ + Bicycle alias; + BicycleFrontAxle front; + const auto ma = alias.getPlanarMapping(); + const auto mf = front.getPlanarMapping(); + EXPECT_EQ(ma.idx_steering, mf.idx_steering); + EXPECT_EQ(ma.idx_steer_rate, mf.idx_steer_rate); + EXPECT_NEAR(ma.ref_offset_x, mf.ref_offset_x, kTol); + EXPECT_NEAR(ma.wheelbase, mf.wheelbase, kTol); +} + +// --- Finite-difference Jacobian checks --------------------------------------- +// +// The existing residual/Jacobian tests above compare updateA()/updateB() +// against an independently hand-derived closed form. This instead compares +// them against a numerical (central finite-difference) derivative of +// updatec()'s own residual, which catches a mismatch between the two +// hand-written analytic expressions (residual and Jacobian) even if both were +// transcribed from the same wrong formula. + +// d(residual)/d(x_k) and d(residual)/d(u_k) via central differences, compared +// against updateA()/updateB() at the same operating point. +void checkFiniteDifferenceJacobian(Model & model, const VectorXd & x, const VectorXd & u) +{ + const double dt = 0.1; + const double eps = 1e-6; + const VectorXd x_next = VectorXd::Zero(x.size()); // held fixed; only c's x_k-dependence is probed + + auto residual = [&](const VectorXd & xx, const VectorXd & uu) { + model.setX(xx); + model.setU(uu); + model.updatec(dt, x_next); + return model.getc(); + }; + + model.setX(x); + model.setU(u); + model.updateA(dt); + model.updateB(); + const MatrixXd A = model.getA(); + const MatrixXd B = model.getB(); + + for (Eigen::Index j = 0; j < x.size(); ++j) { + VectorXd xp = x; + VectorXd xm = x; + xp(j) += eps; + xm(j) -= eps; + const VectorXd fd = (residual(xp, u) - residual(xm, u)) / (2.0 * eps); + for (Eigen::Index i = 0; i < x.size(); ++i) { + EXPECT_NEAR(A(i, j), fd(i), 1e-4) << "dA/dx mismatch at (" << i << "," << j << ")"; + } + } + // updateB() returns the raw kinematics Jacobian df/du (proxqp.cpp scales it + // by dt externally when assembling the equality matrix, model->getB()*dt), + // while the residual c = x_k - x_next + dt*f(x_k, u_k) is what the finite + // difference below actually differentiates, so its du derivative is dt*B, + // not B itself. + for (Eigen::Index j = 0; j < u.size(); ++j) { + VectorXd up = u; + VectorXd um = u; + up(j) += eps; + um(j) -= eps; + const VectorXd fd = (residual(x, up) - residual(x, um)) / (2.0 * eps); + for (Eigen::Index i = 0; i < x.size(); ++i) { + EXPECT_NEAR(dt * B(i, j), fd(i), 1e-4) << "dB/du mismatch at (" << i << "," << j << ")"; + } + } +} + +TEST(ModelInterface, FrontAxleFiniteDifferenceJacobianMatchesAnalytic) +{ + BicycleFrontAxle model; + VectorXd x(4); + x << 1.0, 2.0, 0.3, 0.1; + VectorXd u(2); + u << 0.7, 0.2; + checkFiniteDifferenceJacobian(model, x, u); +} + +TEST(ModelInterface, RearAxleFiniteDifferenceJacobianMatchesAnalytic) +{ + BicycleRearAxle model; + VectorXd x(4); + x << 1.0, 2.0, 0.3, 0.1; + VectorXd u(2); + u << 0.7, 0.2; + checkFiniteDifferenceJacobian(model, x, u); +} + +// --- Negative steering -------------------------------------------------------- +// +// ToTwistSemantics above exercises only delta = +0.2; the sign of the yaw rate +// (and, for the front axle, of the projected linear speed) must flip with it. + +TEST(ModelInterface, ToTwistWithNegativeSteering) +{ + const double L = 1.6; + const double delta = -0.25; + VectorXd xb(4); + xb << 0.0, 0.0, 0.0, delta; + VectorXd ub(2); + ub << 0.7, -0.1; + + BicycleFrontAxle front; + front.setX(xb); + const auto tw_f = front.toTwist(ub); + EXPECT_NEAR(tw_f.linear.x, 0.7 * std::cos(delta), kTol); + EXPECT_NEAR(tw_f.angular.z, 0.7 * std::sin(delta) / L, kTol); + EXPECT_LT(tw_f.angular.z, 0.0); // negative steering yaws the opposite way + + BicycleRearAxle rear; + rear.setX(xb); + const auto tw_r = rear.toTwist(ub); + EXPECT_NEAR(tw_r.linear.x, 0.7, kTol); + EXPECT_NEAR(tw_r.angular.z, 0.7 * std::tan(delta) / L, kTol); + EXPECT_LT(tw_r.angular.z, 0.0); +} + +// --- Twist integration vs. state propagation at the reference point --------- +// +// For a rigid body, the reference point's world-frame velocity is the body +// twist's linear velocity (rotated into world) plus the rotational term of the +// offset: d/dt p_ref = R(theta) * v_body + omega * (offset rotated 90 deg). +// For the front axle this is an exact algebraic identity given v_body = +// v cos(delta), omega = v sin(delta)/L and offset = (L, 0): +// xdot = v cos(delta) cos(theta) - omega L sin(theta) = v cos(theta + delta) +// ydot = v cos(delta) sin(theta) + omega L cos(theta) = v sin(theta + delta) +// which is exactly the model's own propagation (BicycleEulerResidualAndJacobians +// above). This cross-checks toTwist() against updateA()/updateB()/updatec() +// independently of both: a bug that corrupted one but not the other would break +// this identity even if each half's own tests still passed. +TEST(ModelInterface, FrontAxleTwistIntegrationMatchesStatePropagation) +{ + const double L = 1.6; + const double theta = 0.5; + const double delta = 0.3; + const double v = 0.9; + + VectorXd xb(4); + xb << 0.0, 0.0, theta, delta; + BicycleFrontAxle model; + model.setX(xb); + VectorXd u(2); + u << v, 0.0; + const auto twist = model.toTwist(u); + + const double xdot_from_twist = + twist.linear.x * std::cos(theta) - twist.angular.z * L * std::sin(theta); + const double ydot_from_twist = + twist.linear.x * std::sin(theta) + twist.angular.z * L * std::cos(theta); + + EXPECT_NEAR(xdot_from_twist, v * std::cos(theta + delta), 1e-9); + EXPECT_NEAR(ydot_from_twist, v * std::sin(theta + delta), 1e-9); +} + +// The rear axle's reference point is base_link itself (zero offset), so its +// twist trivially equals its own state velocity with no rotational offset term. +TEST(ModelInterface, RearAxleTwistIntegrationMatchesStatePropagation) +{ + const double L = 1.6; + const double theta = 0.5; + const double delta = 0.3; + const double v = 0.9; + + VectorXd xb(4); + xb << 0.0, 0.0, theta, delta; + BicycleRearAxle model; + model.setX(xb); + VectorXd u(2); + u << v, 0.0; + const auto twist = model.toTwist(u); + + const double xdot_from_twist = twist.linear.x * std::cos(theta); + const double ydot_from_twist = twist.linear.x * std::sin(theta); + + EXPECT_NEAR(xdot_from_twist, v * std::cos(theta), 1e-9); + EXPECT_NEAR(ydot_from_twist, v * std::sin(theta), 1e-9); + EXPECT_NEAR(twist.angular.z, v * std::tan(delta) / L, 1e-9); } diff --git a/prox_mpc_core/test/test_mpc_regression.cpp b/prox_mpc_core/test/test_mpc_regression.cpp index 15f0aec..1d3dc68 100644 --- a/prox_mpc_core/test/test_mpc_regression.cpp +++ b/prox_mpc_core/test/test_mpc_regression.cpp @@ -8,7 +8,9 @@ // reference values. A divergence beyond the tolerance indicates a change in the // obstacle-off solver path. +#include #include +#include #include #include @@ -17,10 +19,12 @@ #include #include +#include using prox_mpc::Bicycle; using prox_mpc::MPC; using prox_mpc::Model; +using prox_mpc::Unicycle; namespace { @@ -217,3 +221,95 @@ TEST(MoveBlocking, NcLessThanNpSolvesAndAdvances) EXPECT_GT(x(20, 0), x(0, 0)); // the predicted trajectory advances in +x EXPECT_TRUE(x.allFinite()); } + +// Nc == 1 exercises the warm-start control shift's guarded branch (there is no +// previous control row to shift into). This does not prove memory safety -- +// EIGEN_NO_DEBUG hides an out-of-range Eigen read rather than crashing on it -- +// only that the guarded path solves repeatedly without throwing and stays finite. +TEST(MoveBlocking, NcEqualsOneWarmStartDoesNotCrash) +{ + auto model = std::make_shared(); + const size_t n = model->getN(); + const size_t m = model->getM(); + + VectorXd q_diag = VectorXd::Constant(n, 1.0); + q_diag(0) = 10.0; + q_diag(1) = 10.0; + MatrixXd Q = q_diag.asDiagonal(); + + auto mpc = std::make_shared(); + mpc->setNp(20); + mpc->setNc(1); // Nc == 1: no previous control row to shift into + mpc->setdt(0.1); + mpc->setQ(Q); + mpc->setS(2.0 * Q); + mpc->setR(0.1 * MatrixXd::Identity(m, m)); + mpc->setW(MatrixXd::Constant(1, 1, 100.0)); + mpc->init(model); + + MatrixXd goal_x = MatrixXd::Zero(21, n); + for (size_t k = 0; k <= 20; k++) { + goal_x(k, 0) = 5.0; + } + MatrixXd goal_u = MatrixXd::Zero(1, m); + goal_u(0, 0) = 1.0; + mpc->setGoalX(goal_x); + mpc->setGoalU(goal_u); + mpc->setPose(VectorXd::Zero(n)); + + // Two solves: the second exercises the warm-start shift with Nc == 1. + EXPECT_NO_THROW(mpc->solve()); + MatrixXd x; + MatrixXd u; + EXPECT_NO_THROW((std::tie(x, u) = mpc->solve())); + EXPECT_TRUE(x.allFinite()); + EXPECT_TRUE(u.allFinite()); +} + +// Nc > Np is rejected whichever setter runs second. Either horizon may still +// be at its unset sentinel (0) when the first one runs, so that call defers the +// comparison rather than accepting the pair; the second call makes it. +TEST(MoveBlocking, HorizonBoundRejectedByEitherSetter) +{ + MPC mpc; + mpc.setNp(5); + EXPECT_THROW(mpc.setNc(6), std::invalid_argument); + EXPECT_NO_THROW(mpc.setNc(5)); + EXPECT_NO_THROW(mpc.setNc(1)); + + MPC mpc2; + EXPECT_NO_THROW(mpc2.setNc(10)); // Np unknown yet: deferred + EXPECT_THROW(mpc2.setNp(5), std::invalid_argument); + EXPECT_NO_THROW(mpc2.setNp(20)); +} + +// The pair is checked once more at init(), which is what closes the setters' +// remaining gap: MPC derives publicly from ProbDim, so Np and Nc are public +// data members a caller can assign past the setters entirely. init() is the +// last point that sizes anything from them. +TEST(MoveBlocking, InitRejectsNcGreaterThanNp) +{ + MPC mpc; + mpc.setNp(10); + mpc.setNc(10); + mpc.setdt(0.1); + mpc.Nc = 20; // straight past setNc, which would have rejected it + EXPECT_THROW(mpc.init(std::make_shared()), std::invalid_argument); + + MPC ok; + ok.setNp(10); + ok.setNc(10); + ok.setdt(0.1); + EXPECT_NO_THROW(ok.init(std::make_shared())); +} + +// setdt() must reject a non-finite step in addition to a non-positive one: a +// bare "dt <= 0.0" comparison is false for NaN, silently accepting it. +TEST(MoveBlocking, SetdtRejectsNonFiniteAndNonPositive) +{ + MPC mpc; + EXPECT_THROW(mpc.setdt(0.0), std::invalid_argument); + EXPECT_THROW(mpc.setdt(-0.1), std::invalid_argument); + EXPECT_THROW(mpc.setdt(std::numeric_limits::quiet_NaN()), std::invalid_argument); + EXPECT_NO_THROW(mpc.setdt(0.1)); +} diff --git a/prox_mpc_core/test/test_obstacle_k.cpp b/prox_mpc_core/test/test_obstacle_k.cpp index 5be104e..b081a63 100644 --- a/prox_mpc_core/test/test_obstacle_k.cpp +++ b/prox_mpc_core/test/test_obstacle_k.cpp @@ -58,15 +58,40 @@ void fillSlot(MatrixXd & obs, size_t np, size_t k, size_t slot, double ox, doubl } } +// Like fillSlot, but only over [node_lo, node_hi): fillSlot writes the same +// triple at every node, so no test built from it alone can produce a per-node +// slot discontinuity (e.g. the far sentinel at one node and a real obstacle at +// the next). Call it twice on the same slot with adjoining ranges to place that +// discontinuity at a chosen node boundary. +void fillSlotRange( + MatrixXd & obs, size_t k, size_t slot, size_t node_lo, size_t node_hi, + double ox, double oy, double d) +{ + for (size_t node = node_lo; node < node_hi; node++) { + obs(node * k + slot, 0) = ox; + obs(node * k + slot, 1) = oy; + obs(node * k + slot, 2) = d; + } +} + std::shared_ptr makeUnicycleMpc( - size_t k_obs, double w_weight = 1000.0, double cbf_gamma = 1.0) + size_t k_obs, double w_weight = 1000.0, double cbf_gamma = 1.0, bool warm_start = true) { auto model = std::make_shared(); const size_t n = model->getN(); const size_t m = model->getM(); MatrixXd Q = MatrixXd::Identity(n, n); + // GCC's -Wnull-dereference misfires on this exact shape at -O3/NDEBUG (an + // Identity()-initialized matrix, one element written, then passed by value + // into a call GCC inlines): verified as a false positive by reproducing it + // in isolation, where neither an explicit Eigen::Index cast nor splitting + // the construction from the identity fill clears it. No rename, cast or + // scope change is available here; the site is narrowed to this one write. +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wnull-dereference" Q(0, 0) = 10.0; +#pragma GCC diagnostic pop Q(1, 1) = 10.0; MatrixXd S = 2.0 * Q; MatrixXd R = 0.1 * MatrixXd::Identity(m, m); @@ -82,6 +107,7 @@ std::shared_ptr makeUnicycleMpc( mpc->setW(W); mpc->setMaxObs(k_obs); mpc->setCbfGamma(cbf_gamma); + mpc->setWarmStart(warm_start); mpc->init(model); MatrixXd goal_x = MatrixXd::Zero(kNp + 1, n); // straight reference to (6, 0, 0) @@ -147,6 +173,40 @@ TEST(ObstacleK, ConstraintGeometryDetour) EXPECT_GT(s.max_abs_y, 0.3); } +// The cross-cycle warm start updates the solver workspace in place rather than +// rebuilding it, which ProxQP only honours while the sparsity structure stays +// put. A structure derived from the values would move as the half-plane normals +// pass through zero, and ProxQP would silently ignore the update - dropping the +// keep-out rows and letting the robot drive through the obstacle. This pins that +// the constraint survives a long run on the update path, and that turning the +// warm start off produces the same avoidance. +TEST(ObstacleK, WarmStartPreservesTheKeepOutRows) +{ + const double ox = 2.5; + const double oy = 0.5; + const double d_safe = 1.0; + + auto run = [&](bool warm_start) { + auto mpc = makeUnicycleMpc(1, 1000.0, 1.0, warm_start); + MatrixXd obs = makeObs(kNp, 1); + fillSlot(obs, kNp, 1, 0, ox, oy, d_safe); + mpc->setObs(obs); + return runLoop(mpc, 3, 70, ox, oy); + }; + + const auto warm = run(true); + const auto cold = run(false); + + // The keep-out holds on the update path, not only on the first (init) cycle. + EXPECT_GE(warm.min_dist, d_safe - 0.15); + EXPECT_GT(warm.max_abs_y, 0.3); + + // And the two paths agree: the warm start changes how the QP is solved, not + // which problem is solved. + EXPECT_NEAR(warm.min_dist, cold.min_dist, 0.05); + EXPECT_NEAR(warm.max_abs_y, cold.max_abs_y, 0.05); +} + // The discrete-time CBF coupling (cbf_gamma < 1) is wired and active: it changes // the avoidance trajectory relative to the pointwise term (cbf_gamma = 1) while // both keep clearance and advance past the obstacle. (gamma = 1 must reproduce the @@ -169,14 +229,21 @@ TEST(ObstacleK, CbfGammaChangesAvoidanceTrajectory) auto s_pointwise = runLoop(build(1.0), 3, 70, ox, oy); // gamma = 1 -> pointwise auto s_cbf = runLoop(build(0.3), 3, 70, ox, oy); // gamma < 1 -> CBF coupling - // Both keep clearance and advance past the obstacle in x. + // Both keep clearance and advance past the obstacle in x. The coupled bound is + // a rate condition rather than a pointwise one: it permits the clearance to + // decay toward the keep-out as gamma falls, so its tolerance is looser than the + // pointwise one rather than equal to it. EXPECT_GE(s_pointwise.min_dist, d_safe - 0.15); - EXPECT_GE(s_cbf.min_dist, d_safe - 0.15); + EXPECT_GE(s_cbf.min_dist, d_safe - 0.25); EXPECT_GT(s_pointwise.last_x(1, 0), ox); EXPECT_GT(s_cbf.last_x(1, 0), ox); - // The coupling demonstrably changes the realized trajectory. + // The coupling demonstrably changes the realized trajectory, in the direction + // the rate condition predicts: a closer, less lateral pass than the pointwise + // term takes. EXPECT_GT(std::abs(s_cbf.max_abs_y - s_pointwise.max_abs_y), 1e-3); + EXPECT_LT(s_cbf.max_abs_y, s_pointwise.max_abs_y); + EXPECT_LT(s_cbf.min_dist, s_pointwise.min_dist); } // Each obstacle constraint row and its slack share the same (node, slot), and @@ -257,6 +324,100 @@ TEST(ObstacleK, CbfGammaRejectsOutOfRange) EXPECT_NO_THROW(solver.setCbfGamma(0.5)); } +// At exact coincidence (predicted position equals the obstacle center) the +// emitted constraint normal must still be unit length: dividing a zero delta +// by only a floored norm would otherwise emit (0, 0), leaving slack as the +// sole thing resisting the constraint. +TEST(ObstacleK, CoincidentObstacleNormalIsUnitLength) +{ + auto mpc = makeUnicycleMpc(1); // K = 1 + + const double ox = 1.0; + const double oy = 0.0; + MatrixXd obs = makeObs(kNp, 1); + fillSlot(obs, kNp, 1, 0, ox, oy, 0.5); + + // setC() reads the solver's own obs member, populated only through + // ProxQP::setObs() (normally forwarded by MPC::solve() each cycle); calling + // setC() directly here needs it set the same way. + auto solver = mpc->getSolver(); + solver->setObs(obs); + MatrixXd x = MatrixXd::Zero(kNp + 1, 3); // unicycle state [x, y, theta] + x(1, 0) = ox; // node 1 exactly coincides with the obstacle center + x(1, 1) = oy; + solver->setC(x); + + const MatrixXd & C = solver->getC(); + const std::vector & ineq_idx = solver->getIneqIdx(); + const size_t obs_start = ineq_idx[ineq_idx.size() - 3]; + const size_t col = 3; // position block of node 1 (x_start == 0, n == 3) + + const double nx = C(obs_start, col); + const double ny = C(obs_start, col + 1); + EXPECT_NEAR(nx * nx + ny * ny, 1.0, 1e-9); +} + +// The default per-node static fill does not preserve slot identity across +// nodes; at cbf_gamma < 1 a slot holding the far sentinel at one node and a +// real obstacle at the next node must not blow up the coupling term. This uses +// a local fill (not the shared makeObs/fillSlot helpers, which fill every node +// identically and cannot express a per-node discontinuity) to construct that +// exact case and checks the realized slack stays bounded. +TEST(ObstacleK, SentinelDiscontinuityDoesNotBlowUpSlack) +{ + auto mpc = makeUnicycleMpc(1, 100.0, 0.3); // K = 1, cbf_gamma < 1 + + MatrixXd obs = MatrixXd::Zero(kNp, 3); + for (Eigen::Index r = 0; r < obs.rows(); r++) { + obs(r, 0) = MPC::kObsFarSentinel; + obs(r, 1) = MPC::kObsFarSentinel; + obs(r, 2) = 0.0; + } + // Node 0's slot stays at the sentinel; node 1's slot holds a real obstacle, + // creating the (sentinel at node k, real obstacle at node k+1) discontinuity. + obs(1, 0) = 2.5; + obs(1, 1) = 0.0; + obs(1, 2) = 1.0; + mpc->setObs(obs); + + mpc->setPose(VectorXd::Zero(3)); + mpc->solve(); + EXPECT_EQ(mpc->qp_info.status, proxsuite::proxqp::QPSolverOutput::PROXQP_SOLVED); + + // Before the fix the coupling term (1 - gamma) * obs_h_prev reaches ~1e5 at + // this transition, forcing the slack to absorb it; after the fix it stays at + // an ordinary avoidance magnitude. + EXPECT_LT(mpc->getMaxObstacleSlack(), 10.0); +} + +// fillSlotRange places a real obstacle from one node onward while the same slot +// stays at the far sentinel before it -- the (sentinel at node k, real obstacle +// at node k+1) discontinuity fillSlot cannot express, since it writes the same +// triple at every node. The core guard at proxqp.cpp:433-436 already lands on +// this branch; this exercises it at cbf_gamma = 0.5 and records the observed QP +// status and largest obstacle slack as a characterization. +TEST(ObstacleK, SlotDiscontinuityAtHalfGammaStaysBounded) +{ + const size_t k = 1; + const size_t node_k = 4; // last sentinel node; node_k + 1 is the first real one + + auto mpc = makeUnicycleMpc(k, 100.0, 0.5); // K = 1, cbf_gamma = 0.5 + MatrixXd obs = makeObs(kNp, k); // every node starts at the far sentinel + fillSlotRange(obs, k, 0, node_k + 1, kNp, 2.5, 0.5, 1.0); + mpc->setObs(obs); + + mpc->setPose(VectorXd::Zero(3)); + mpc->solve(); + + const auto status = mpc->qp_info.status; + const double max_slack = mpc->getMaxObstacleSlack(); + RecordProperty("qp_status", static_cast(status)); + RecordProperty("max_obstacle_slack", std::to_string(max_slack)); + + EXPECT_EQ(status, proxsuite::proxqp::QPSolverOutput::PROXQP_SOLVED); + EXPECT_LT(max_slack, 10.0); // ordinary avoidance magnitude, not the ~1e5 blow-up +} + // K=0 reproduces the obstacle-off result exactly, and K=1 with every slot at the // far sentinel reproduces it within tolerance. TEST(ObstacleK, DisabledAndSentinelReproduceObstacleOff) @@ -351,3 +512,274 @@ TEST(ObstacleK, MultiObstacleAndSentinelReducesToK1) EXPECT_NEAR(s_k2.last_x(r, 1), s_k1.last_x(r, 1), 1e-3); } } + +// --- The keep-out rows follow the model's declared planar mapping ------------ +// +// The obstacle rows are the only part of the assembly that has to know where a +// model keeps its position. They read it from Model::getPlanarMapping(), so a +// model whose state is not ordered [x, y, ...] is constrained on the axes it +// declares rather than on state columns 0 and 1. + +// A model whose state is ordered [theta, x, y] and which enables obstacle +// avoidance: the case the assembly used to index wrongly. Unicycle dynamics +// written against the permuted ordering, so it also solves. +class PermutedObstacleModel : public prox_mpc::Model +{ +public: + PermutedObstacleModel() + { + setName("permuted_obstacle"); + setN(3); // state: [theta, x, y] + setM(2); // control: [v, omega] + setA(MatrixXd::Zero(getN(), getN())); + setB(MatrixXd::Zero(getN(), getM())); + setc(VectorXd::Zero(getN())); + setIneq("u", 0, -3.0, 3.0); + setIneq("u", 1, -1.0, 1.0); + setIneq("du", 0, -0.5, 0.5); + setIneq("du", 1, -0.5, 0.5); + setObsAvoid(true); + } + prox_mpc::PlanarMapping getPlanarMapping() const override + { + prox_mpc::PlanarMapping mapping; + mapping.idx_yaw = 0; + mapping.idx_x = 1; + mapping.idx_y = 2; + return mapping; + } + void updatec(double dt, VectorXd x_next) override + { + const double th = getX()(0); + c << getX()(0) - x_next(0) + dt * getU()(1), + getX()(1) - x_next(1) + dt * getU()(0) * std::cos(th), + getX()(2) - x_next(2) + dt * getU()(0) * std::sin(th); + } + void updateA(double dt) override + { + const double th = getX()(0); + const double v = getU()(0); + A << 1.0, 0.0, 0.0, + -dt * v * std::sin(th), 1.0, 0.0, + dt * v * std::cos(th), 0.0, 1.0; + } + void updateB() override + { + const double th = getX()(0); + B << 0.0, 1.0, + std::cos(th), 0.0, + std::sin(th), 0.0; + } +}; + +// The half-plane normal lands in the two state columns the model declares as +// its position, and the column it declares as heading is left untouched. Read +// out of the assembled constraint matrix rather than inferred from a solution: +// a wrongly placed normal still produces a plausible trajectory, just one +// constrained on the wrong pair of axes. +TEST(ObstacleK, KeepOutRowsFollowTheDeclaredPlanarMapping) +{ + auto model = std::make_shared(); + const size_t n = 3; + auto mpc = std::make_shared(); + mpc->setNp(kNp); + mpc->setNc(kNc); + mpc->setdt(kDt); + mpc->setQ(MatrixXd::Identity(n, n)); + mpc->setS(MatrixXd::Identity(n, n)); + mpc->setR(0.1 * MatrixXd::Identity(2, 2)); + mpc->setW(MatrixXd::Constant(1, 1, 100.0)); + mpc->setMaxObs(1); + mpc->init(model); + + // One obstacle, and a node-1 position offset from it along +x only, so the + // expected normal is exactly (1, 0) in the declared axes. + const double ox = 1.0; + const double oy = 0.0; + MatrixXd obs = makeObs(kNp, 1); + fillSlot(obs, kNp, 1, 0, ox, oy, 0.5); + + auto solver = mpc->getSolver(); + solver->setObs(obs); + MatrixXd x = MatrixXd::Zero(kNp + 1, n); + x(1, 1) = ox + 2.0; // declared x position of node 1 + x(1, 2) = oy; // declared y position of node 1 + solver->setC(x); + + const MatrixXd & C = solver->getC(); + const std::vector & ineq_idx = solver->getIneqIdx(); + const size_t obs_start = ineq_idx[ineq_idx.size() - 3]; + const size_t col = n * 1; // x_start == 0; state block of node 1 + + EXPECT_NEAR(C(obs_start, col + 1), 1.0, 1e-12); // declared x column carries n_x + EXPECT_NEAR(C(obs_start, col + 2), 0.0, 1e-12); // declared y column carries n_y + // The heading column is not a position and must carry no keep-out gradient. + EXPECT_NEAR(C(obs_start, col + 0), 0.0, 1e-12); +} + +// --- Current-time obstacle reconstruction at node 0 ------------------------- +// +// The matrix's row 0 (block 0) carries the obstacle's position one step ahead +// (paired with x_sol row 1's time), not now, so the first coupled constraint's +// "previous node" side -- which must compare against the current pose x(0) -- +// reconstructs the current-time position as 2*block0 - block1 rather than using +// block0 directly (proxqp.cpp's node == 0 branch). A two-node constant-velocity +// fill exercises the reconstruction directly, something no existing test above +// does: every other fill in this file is either fully static (uniform across +// nodes) or discontinuous well past node 0. + +// A two-node constant-velocity obstacle fill: node 0's row (block 0, paired +// with x_sol row 1) and node 1's row (block 1, paired with x_sol row 2) hold +// positions one dt apart; the reconstructed current-time position is +// 2*block0 - block1, one more step back along the same line. Every other node +// stays at the far sentinel (single transient obstacle, not a persistent one). +MatrixXd makeConstantVelocityAtStart( + size_t np, size_t k, double ox1, double oy1, double vx, double dt, double d_safe) +{ + MatrixXd obs = makeObs(np, k); + obs(0, 0) = ox1; + obs(0, 1) = oy1; + obs(0, 2) = d_safe; + obs(1, 0) = ox1 + vx * dt; + obs(1, 1) = oy1; + obs(1, 2) = d_safe; + return obs; +} + +// The first coupled row is bounded against the obstacle's position NOW, which +// the matrix carries no block for and which is recovered as +// 2 * block0 - block1. The bound is read straight out of the assembled system +// rather than inferred from the solution: the coupled row is absorbed by its +// slack at any shipped slack weight, so no closed-loop quantity moves and an +// ordering between two scenarios' slacks is satisfied whether the +// reconstruction runs or not. +// +// setC() and setd() are called directly on a chosen iterate so every term of +// low(row 0) = (1 - gamma) * h_prev(0) - h(0) - w(0) is closed-form: +// h(0) = ||x(1) - block0|| - d_safe (node 0 constrains x(1)) +// h_prev(0) = ||x(0) - (2 * block0 - block1)|| - d_safe +// w(0) = 0 +// With the robot at the origin, a head-on obstacle closing at 0.5 m/s and +// gamma = 0.5, that is -1.175. Bounding against block0 as though it were the +// current position - which is what happens without the reconstruction - gives +// -1.200 instead: the reconstruction is worth exactly +// (1 - gamma) * v_obs * dt = +0.025 of clearance floor here. +TEST(ObstacleK, FirstCoupledConstraintUsesReconstructedCurrentTimeObstacle) +{ + const size_t k = 1; + const double ox1 = 2.9; // block 0: obstacle position one step ahead of now + const double vx = -0.5; // closing head-on [m/s], well within kMaxObsSpeed + const double d_safe = 0.5; + const double cbf_gamma = 0.5; + + auto mpc = makeUnicycleMpc(k, 100.0, cbf_gamma); + auto solver = mpc->getSolver(); + solver->setObs(makeConstantVelocityAtStart(kNp, k, ox1, 0.0, vx, kDt, d_safe)); + + // Robot at the origin, and node 1 there too: the iterate is what makes every + // term closed-form, not a solution. + const MatrixXd x = MatrixXd::Zero(kNp + 1, 3); + solver->setC(x); + solver->setd(x, MatrixXd::Zero(kNc, 2), VectorXd::Zero(2), VectorXd::Zero(kNp * k)); + + const std::vector & ineq_idx = solver->getIneqIdx(); + const size_t obs_start = ineq_idx[ineq_idx.size() - 3]; + const double reconstructed_x = ox1 - vx * kDt; // 2 * block0 - block1 + const double h = ox1 - d_safe; + const double h_prev = reconstructed_x - d_safe; + const double expected_low = (1.0 - cbf_gamma) * h_prev - h; + + EXPECT_NEAR(solver->getLow()(static_cast(obs_start)), expected_low, 1e-12); + // The same row bounded against block0 as "now"; the two differ by the + // reconstruction's whole worth. + const double block0_as_now_low = (1.0 - cbf_gamma) * (ox1 - d_safe) - h; + EXPECT_NEAR(expected_low - block0_as_now_low, (1.0 - cbf_gamma) * std::abs(vx) * kDt, 1e-12); +} + +// An implied inter-block step no obstacle could have travelled in one dt is +// treated as noise, not motion: above kMaxObsSpeed the backward extrapolation +// is skipped and the first block is used as the current-time position. The +// fallback is silent, so the assembled bound is the only place it is +// observable. Same closed-form reading as the case above, with the implied +// speed raised past the bound: 20 m/s over dt = 0.1 s implies a 2 m step +// against a kMaxObsSpeed * dt ceiling of 1 m. +TEST(ObstacleK, ImplausibleObstacleStepFallsBackToTheFirstBlock) +{ + const size_t k = 1; + const double ox1 = 2.9; + const double vx = -20.0; // implied speed past kMaxObsSpeed = 10.0 m/s + const double d_safe = 0.5; + const double cbf_gamma = 0.5; + + auto mpc = makeUnicycleMpc(k, 100.0, cbf_gamma); + auto solver = mpc->getSolver(); + solver->setObs(makeConstantVelocityAtStart(kNp, k, ox1, 0.0, vx, kDt, d_safe)); + + const MatrixXd x = MatrixXd::Zero(kNp + 1, 3); + solver->setC(x); + solver->setd(x, MatrixXd::Zero(kNc, 2), VectorXd::Zero(2), VectorXd::Zero(kNp * k)); + + const std::vector & ineq_idx = solver->getIneqIdx(); + const size_t obs_start = ineq_idx[ineq_idx.size() - 3]; + const double h = ox1 - d_safe; + // Block 0 used unchanged as "now", so both sides read the same position. + const double expected_low = (1.0 - cbf_gamma) * (ox1 - d_safe) - h; + EXPECT_NEAR(solver->getLow()(static_cast(obs_start)), expected_low, 1e-12); + + // What the extrapolation would have produced had the guard not fired, kept + // here so a widened bound shows up as a failure rather than as no change. + const double extrapolated = ox1 - vx * kDt; + const double unguarded_low = (1.0 - cbf_gamma) * (extrapolated - d_safe) - h; + EXPECT_GT(std::abs(unguarded_low - expected_low), 1.0); +} + +// Finite-difference Jacobian check of the coupled constraint's gradient columns +// (node >= 1, where they are written -- node 0's are inert because x(0) is +// pinned, per the comment at proxqp.cpp). setC() writes -( 1 - gamma) * grad h_k +// into the position columns of the previous node; this compares that analytic +// coefficient against a central finite difference of the closed-form clearance +// h_k(x) = ||x - o|| - d_safe the code implements, at the same operating point. +TEST(ObstacleK, CoupledConstraintGradientMatchesFiniteDifference) +{ + const size_t k = 1; + const double gamma = 0.5; + const double d_safe = 0.5; + const double eps = 1e-6; + + auto mpc = makeUnicycleMpc(k, 100.0, gamma); + // Real obstacle data at node 0 (block 0, prev-side for node 1) and node 1 + // (block 1, own side for node 1), so node 1's coupled row's gradient columns + // are written (node >= 1) against a non-reconstructed, ordinary prev slot. + const double ox = 2.5; + const double oy = 0.3; + MatrixXd obs = makeConstantVelocityAtStart(kNp, k, ox, oy, 3.0, kDt, d_safe); + auto solver = mpc->getSolver(); + solver->setObs(obs); + + MatrixXd x = MatrixXd::Zero(kNp + 1, 3); + x(0, 0) = 0.0; x(0, 1) = 0.0; x(0, 2) = 0.0; + x(1, 0) = 1.7; x(1, 1) = 0.6; x(1, 2) = 0.1; // node 1's own position + x(2, 0) = 2.6; x(2, 1) = 0.5; x(2, 2) = 0.2; + solver->setC(x); + + const MatrixXd & C = solver->getC(); + const std::vector & ineq_idx = solver->getIneqIdx(); + const size_t obs_start = ineq_idx[ineq_idx.size() - 3]; + const size_t row = obs_start + 1; // node 1's row (slot 1 of Np*K, K=1) + const size_t col_prev = 3; // position block of node 1 (x_start=0, n=3) + + const double gx_code = C(row, col_prev); + const double gy_code = C(row, col_prev + 1); + + // h_prev(x) = ||x(0:2) - o|| - d_safe, at the SAME obstacle block 0's setObs() + // resolves node 1's prev side to (ordinary, non-reconstructed since node >= 1). + auto h_prev = [&](double px, double py) {return std::hypot(px - ox, py - oy) - d_safe;}; + const double fd_gx = + (h_prev(x(1, 0) + eps, x(1, 1)) - h_prev(x(1, 0) - eps, x(1, 1))) / (2.0 * eps); + const double fd_gy = + (h_prev(x(1, 0), x(1, 1) + eps) - h_prev(x(1, 0), x(1, 1) - eps)) / (2.0 * eps); + const double gain = -(1.0 - gamma); + + EXPECT_NEAR(gx_code, gain * fd_gx, 1e-6); + EXPECT_NEAR(gy_code, gain * fd_gy, 1e-6); +} diff --git a/prox_mpc_core/test/test_transactional_solve.cpp b/prox_mpc_core/test/test_transactional_solve.cpp new file mode 100644 index 0000000..e9762f0 --- /dev/null +++ b/prox_mpc_core/test/test_transactional_solve.cpp @@ -0,0 +1,253 @@ +// Copyright 2026 Simone Contorno +// SPDX-License-Identifier: Apache-2.0 + + +// Contract tests for the transactional solve/commit pair added to MPC +// (solveCandidate(), commitCandidate(), getCandidateFinite(), setU0()). Before +// this pair existed, MPC::solve() applied a QP's increments to x, u and w +// unconditionally, before checking whether the QP had converged, so a failed +// cycle silently corrupted the retained trajectories. Two cases: +// - a genuinely failed QP (a state bound the current pose violates by +// construction) leaves the previously retained x, u and w unchanged; +// - a candidate carrying a non-finite value in a LATER horizon row (not just +// row 0) is refused by commitCandidate()'s whole-horizon finiteness guard. +// Whether proxsuite itself can produce that iterate through the public +// solve path is not established, so this case exercises the guard +// directly via a protected-member test subclass rather than depending on +// an unreliable numerical trigger. +// +// Observability note: MPC's retained x has a public getter (getX()) and its +// retained u0 is a direct protected member, so both are read back directly +// below. The retained u and w trajectories have neither a public getter nor a +// protected member of their own (they live only in the privately-inherited +// MPCParams base, so even a derived class cannot name them) -- MPC exposes no +// way to read either back without calling solve()/solveCandidate() again, +// which would itself advance the state under test. Their preservation is +// therefore argued structurally rather than observed directly: +// commitCandidate() has a single early return before x, u, w and u0 are ever +// assigned (mpc.cpp), with no per-field branch inside that block, so a +// refused commit that leaves the two DIRECTLY observable members (x, u0) +// unchanged leaves u and w unchanged for the same reason. + +#include +#include +#include + +#include + +#include + +#include +#include + +using prox_mpc::MPC; +using prox_mpc::Model; + +namespace +{ + +// Linear integrator: x_{k+1} = x_k + dt * u, state [x, y, theta], control +// [v, omega]. Declares a state bound on x[0] that the pose used for the +// "failed" cycle below sits far outside of, and the pose used for the +// "previous valid" cycle sits well inside of, so which cycle is feasible is +// controlled entirely by setPose() between two solves against the same fixed +// model, not by chasing solver iteration limits. +class BoundedLinearModel : public Model +{ +public: + BoundedLinearModel() + { + setName("bounded_linear"); + setN(3); + setM(2); + setA(MatrixXd::Zero(getN(), getN())); + setB(MatrixXd::Zero(getN(), getM())); + setc(VectorXd::Zero(getN())); + setIneq("x", 0, 100.0, 200.0); // only reachable from a pose already inside it + setIneq("u", 0, -3.0, 3.0); + setIneq("u", 1, -1.0, 1.0); + setIneq("du", 0, -0.5, 0.5); + setIneq("du", 1, -0.5, 0.5); + setObsAvoid(true); + } + void updatec(double dt, VectorXd x_next) override + { + c << getX()(0) - x_next(0) + dt * getU()(0), + getX()(1) - x_next(1), + getX()(2) - x_next(2) + dt * getU()(1); + } + void updateA(double) override {A = MatrixXd::Identity(getN(), getN());} + void updateB() override + { + B << 1.0, 0.0, + 0.0, 0.0, + 0.0, 1.0; + } +}; + +// Exposes MPC's protected candidate-staging members (genuinely protected, +// direct members of MPC itself -- unlike the retained x/u/w, which live only +// in the privately-inherited MPCParams and so are not nameable from a derived +// class at all) and adds a way to exercise commitCandidate()'s finiteness +// guard directly, for the case where constructing a non-finite QP output +// through the public solve path is not established as reachable. White-box, +// no production change. +class TestableMpc : public MPC +{ +public: + using MPC::u0; + using MPC::cand_x; + using MPC::cand_u; + using MPC::cand_w; + using MPC::cand_solved; + using MPC::cand_finite; + using MPC::cand_u0; + + // Stage a candidate exactly the way solveCandidate() would have left one, + // computing cand_finite with the identical whole-horizon allFinite() + // reduction the production code uses, so commitCandidate() is exercised + // against the real guard rather than a stand-in. + void injectCandidate(const MatrixXd & cx, const MatrixXd & cu, const VectorXd & cw, bool solved) + { + cand_x = cx; + cand_u = cu; + cand_w = cw; + cand_solved = solved; + cand_finite = cand_x.allFinite() && cand_u.allFinite() && cand_w.allFinite(); + cand_u0 = cand_u.row(0); + } +}; + +std::shared_ptr makeMpc() +{ + auto model = std::make_shared(); + const size_t n = model->getN(); + const size_t m = model->getM(); + + auto mpc = std::make_shared(); + mpc->setNp(6); + mpc->setNc(6); + mpc->setdt(0.1); + mpc->setQ(10.0 * MatrixXd::Identity(n, n)); + mpc->setS(20.0 * MatrixXd::Identity(n, n)); + mpc->setR(0.1 * MatrixXd::Identity(m, m)); + mpc->setW(MatrixXd::Constant(1, 1, 100.0)); + mpc->setMaxObs(1); // non-empty w, so its preservation argument is non-vacuous + mpc->init(model); + + MatrixXd goal_x = MatrixXd::Zero(7, n); + for (int i = 0; i <= 6; i++) { + goal_x(i, 0) = 150.0; + } + MatrixXd goal_u = MatrixXd::Zero(6, m); + mpc->setGoalX(goal_x); + mpc->setGoalU(goal_u); + + MatrixXd obs = MatrixXd::Zero(6, 3); + for (Eigen::Index r = 0; r < obs.rows(); r++) { + obs(r, 0) = MPC::kObsFarSentinel; + obs(r, 1) = MPC::kObsFarSentinel; + } + mpc->setObs(obs); + return mpc; +} + +void expectMatrixUnchanged(const MatrixXd & before, const MatrixXd & after, const char * what) +{ + ASSERT_EQ(before.rows(), after.rows()) << what; + ASSERT_EQ(before.cols(), after.cols()) << what; + EXPECT_LT((before - after).cwiseAbs().maxCoeff(), 1e-15) << what << " changed"; +} +} // namespace + +// A genuinely failed QP (the pose lands outside the declared state bound, a +// hard infeasibility) leaves the previously retained x, u and w trajectories +// untouched: solveCandidate() computes into the candidate copies only, and +// commitCandidate() refuses to advance because the candidate did not converge. +TEST(TransactionalSolve, FailedSolveLeavesRetainedTrajectoriesUnchanged) +{ + auto mpc = makeMpc(); + + // Cycle 1: pose inside the feasible band, trivial tracking error at the + // goal -- converges immediately and becomes the retained baseline. + mpc->setPose((VectorXd(3) << 150.0, 0.0, 0.0).finished()); + auto [x1, u1] = mpc->solveCandidate(); + (void)x1; + (void)u1; + ASSERT_EQ(mpc->qp_info.status, proxsuite::proxqp::QPSolverOutput::PROXQP_SOLVED); + ASSERT_TRUE(mpc->getCandidateFinite()); + ASSERT_TRUE(mpc->commitCandidate()); + + const MatrixXd baseline_x = mpc->getX(); + const VectorXd baseline_u0 = mpc->u0; + + // Cycle 2: pose moved (by the caller, between cycles -- exactly how the + // controller calls setPose() every cycle) far outside the declared x[0] + // bound of [100, 200], while the model's constraints stay fixed. x(0) is + // pinned to the pose by an equality, so this is a hard, structural + // infeasibility, not a numerically fragile near-miss. + mpc->setPose((VectorXd(3) << 0.0, 0.0, 0.0).finished()); + mpc->solveCandidate(); + EXPECT_NE(mpc->qp_info.status, proxsuite::proxqp::QPSolverOutput::PROXQP_SOLVED); + EXPECT_FALSE(mpc->commitCandidate()); + + // x (public getter) and u0 (protected, direct MPC member) are both + // observable and both confirmed unchanged; u and w are written in the same + // unconditional block right after commitCandidate()'s single early return + // (mpc.cpp), with no per-field guard, so their preservation follows from + // the same refused commit -- see the file header for why they cannot be + // read back directly to confirm this independently. + expectMatrixUnchanged(baseline_x, mpc->getX(), "x"); + EXPECT_LT((baseline_u0 - mpc->u0).cwiseAbs().maxCoeff(), 1e-15) << "u0 changed"; +} + +// commitCandidate()'s finiteness guard checks the WHOLE horizon (cand_x, +// cand_u and cand_w all-finite), not only the first row: a non-finite value in +// a later row is refused exactly like one in row 0. Constructed by direct +// injection because whether proxsuite can itself return such an iterate +// through solveCandidate() is not established. +TEST(TransactionalSolve, NonFiniteLaterHorizonRowIsRejected) +{ + auto mpc = makeMpc(); + EXPECT_FALSE(mpc->getCandidateFinite()); // nothing solved yet + + mpc->setPose((VectorXd(3) << 150.0, 0.0, 0.0).finished()); + auto [x1, u1] = mpc->solveCandidate(); + ASSERT_TRUE(mpc->commitCandidate()); + + const MatrixXd baseline_x = mpc->getX(); + const VectorXd baseline_u0 = mpc->u0; + // A finite candidate the SAME shape as the real one, reused as the base for + // each corrupted copy below. + const MatrixXd good_x = x1; + const MatrixXd good_u = u1; + const VectorXd good_w = VectorXd::Zero(6); + + MatrixXd bad_x = good_x; + ASSERT_GT(bad_x.rows(), 3); + bad_x(3, 0) = std::numeric_limits::quiet_NaN(); // a LATER row, not row 0 + mpc->injectCandidate(bad_x, good_u, good_w, /*solved=*/true); + EXPECT_FALSE(mpc->getCandidateFinite()); + EXPECT_FALSE(mpc->commitCandidate()); + expectMatrixUnchanged(baseline_x, mpc->getX(), "x"); + EXPECT_LT((baseline_u0 - mpc->u0).cwiseAbs().maxCoeff(), 1e-15) << "u0 changed"; + + // The same guard for a non-finite value in u, and in w. + MatrixXd bad_u = good_u; + bad_u(bad_u.rows() - 1, 0) = std::numeric_limits::infinity(); + mpc->injectCandidate(good_x, bad_u, good_w, /*solved=*/true); + EXPECT_FALSE(mpc->getCandidateFinite()); + EXPECT_FALSE(mpc->commitCandidate()); + + VectorXd bad_w = good_w; + bad_w(bad_w.size() - 1) = std::numeric_limits::quiet_NaN(); + mpc->injectCandidate(good_x, good_u, bad_w, /*solved=*/true); + EXPECT_FALSE(mpc->getCandidateFinite()); + EXPECT_FALSE(mpc->commitCandidate()); + + // A fully finite candidate marked unsolved is refused too -- the guard is + // an AND of "converged" and "finite", not finiteness alone. + mpc->injectCandidate(good_x, good_u, good_w, /*solved=*/false); + EXPECT_TRUE(mpc->getCandidateFinite()); + EXPECT_FALSE(mpc->commitCandidate()); +} diff --git a/prox_mpc_demo/CHANGELOG.rst b/prox_mpc_demo/CHANGELOG.rst index 4604ac1..1a839b9 100644 --- a/prox_mpc_demo/CHANGELOG.rst +++ b/prox_mpc_demo/CHANGELOG.rst @@ -2,6 +2,26 @@ Changelog for package prox_mpc_demo ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2.0.0 (2026-09-13) +------------------ +* The local costmap tracks unknown space, so cells the sensor has not swept are + marked ``NO_INFORMATION`` instead of being published as free. +* Nav2 parameter files follow the controller's changed defaults. +* The Nav2 parameter files set ``allow_reversing: true``, so the demo shows the + robot backing up to adjust and then pursuing the path forward. Reverse used to + read as a shuffle near the goal; that was the reference collapsing to a stub + ahead of the robot's own projection inside the goal tolerance, not reverse + itself, and the controller now pins the reference to the goal pose there and + turns on the spot for the last of the heading. Measured over ``cmd_vel_nav``, + reverse-enabled now completes every demo scenario faster than forward-only + (27.8 s vs 38.6 s, 12.2 s vs 19.8 s, 9.5 s vs 21.7 s) with no + ``Failed to make progress`` events against two for forward-only. +* The predictive Nav2 parameter file sets ``obstacle_yield_band_m: 0.5``, so the + robot waits for a crossing mover rather than racing it: it passed behind 6/10 + against 1/10 on ``dynamic_circle`` with no collisions, and was no worse with + two movers. Not set in the non-predictive file, which runs no tracker. +* Contributors: Simone Contorno + 1.0.0 (2026-07-28) ------------------ * Initial release: self-contained closed-loop NMPC simulation node (bicycle / unicycle) diff --git a/prox_mpc_demo/CMakeLists.txt b/prox_mpc_demo/CMakeLists.txt index d5a7333..c75e467 100644 --- a/prox_mpc_demo/CMakeLists.txt +++ b/prox_mpc_demo/CMakeLists.txt @@ -11,9 +11,20 @@ if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE "Release") endif() -# Compiler warnings -if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang") - add_compile_options(-Wall -Wextra -Wpedantic) +# Compiler warnings, matching upstream Nav2's package-level policy +# (nav2_common/cmake/nav2_package.cmake) so this package is held to the same +# bar as every other Nav2 plugin it ships alongside. +if(CMAKE_CXX_COMPILER_ID MATCHES "GNU" OR CMAKE_CXX_COMPILER_ID MATCHES "Clang") + add_compile_options(-Wall -Wextra -Wpedantic -Werror -Wdeprecated -fPIC -Wshadow -Wnull-dereference) + # GCC 13 raises -Wnull-dereference inside libstdc++'s own headers + # (stl_algobase.h, reached through regex_traits::transform_primary) once + # --coverage changes its inlining decisions, which is how the coverage build + # hits it and an ordinary build does not. The report is attributed to the + # translation unit that instantiates the template, so -Wno-system-headers + # does not reach it. Keep the diagnostic, but do not let a false positive in + # the standard library fail the build. + add_compile_options(-Wno-error=null-dereference) + add_compile_options("$<$:-Wnon-virtual-dtor>") endif() # Remove Eigen's internal assertions in the hot path (safe under Release) diff --git a/prox_mpc_demo/config/nav2_prox_mpc.yaml b/prox_mpc_demo/config/nav2_prox_mpc.yaml index 7e27aba..de2fbbf 100644 --- a/prox_mpc_demo/config/nav2_prox_mpc.yaml +++ b/prox_mpc_demo/config/nav2_prox_mpc.yaml @@ -111,6 +111,9 @@ controller_server: model_plugin: "prox_mpc_core/Unicycle" model_params: L: 0.0 # unused by the unicycle; kept for interface symmetry + # Reverse bound [m/s]. Naming it explicitly is what states this platform's + # real reverse envelope, rather than inheriting the model literal. + v_min: -0.15 # Horizons and step. np: 20 @@ -128,12 +131,12 @@ controller_server: q_theta: 1.0 s_factor: 2.0 r_weight: 0.1 - w_weight: 100.0 + w_weight: 1000.0 # Solver limits (core defaults). max_int_iter_qp: 1500 max_ext_iter_qp: 10000 - max_iter_sqp: 100 + max_iter_sqp: 1 qp_type: false guess: true max_solver_failures: 3 @@ -144,8 +147,10 @@ controller_server: # feature is opt-in and lives in nav2_prox_mpc_predictive.yaml; enable it with # `predictive:=True`. max_obstacles: 0 - safety_margin: 0.1 - robot_radius: 0.22 + # 0.085 with robot_radius 0.235 keeps d_safe at 0.320 m; the radius is the + # footprint's circumscribed value and the margin is the discretionary part. + safety_margin: 0.085 + robot_radius: 0.235 cbf_gamma: 1.0 costmap_cost_threshold: 200 obstacle_cluster_radius: 0.3 @@ -154,6 +159,20 @@ controller_server: # max_obstacles is 0). See nav2_prox_mpc_predictive.yaml to enable it. predict_obstacles: false + + # Whether the solver may plan reverse travel at all. False narrows the + # linear control bound to [0, v_max]. On, so the demo shows the robot + # backing up to adjust and then pursuing the path forward, the way a + # vehicle manoeuvres. Reverse stays capped at 0.15 m/s by the controller's + # own guard: both guards follow the predicted trajectory and so do cover a + # reversing one, but they see only what the costmap holds, and whether the + # platform sweeps behind itself is a property of its sensor. The waffle's + # lidar is 360 degrees, so the rear is covered here. The goal + # region no longer alternates on an open reverse bound - the reference is + # pinned to the goal pose there, and the robot turns on the spot for the + # last of the heading. See doc/nav2-simulation.md. + allow_reversing: true + log_level: "info" local_costmap: @@ -164,6 +183,9 @@ local_costmap: global_frame: odom robot_base_frame: base_link rolling_window: true + # Unobserved cells are marked NO_INFORMATION rather than defaulting to + # free space, so the costmap does not claim to have seen what it has not. + track_unknown_space: true width: 3 height: 3 resolution: 0.05 diff --git a/prox_mpc_demo/config/nav2_prox_mpc_predictive.yaml b/prox_mpc_demo/config/nav2_prox_mpc_predictive.yaml index 2cca16f..5b3d0d9 100644 --- a/prox_mpc_demo/config/nav2_prox_mpc_predictive.yaml +++ b/prox_mpc_demo/config/nav2_prox_mpc_predictive.yaml @@ -117,6 +117,9 @@ controller_server: model_plugin: "prox_mpc_core/Unicycle" model_params: L: 0.0 # unused by the unicycle; kept for interface symmetry + # Reverse bound [m/s]. Naming it explicitly is what states this platform's + # real reverse envelope, rather than inheriting the model literal. + v_min: -0.15 # Horizons and step. np: 20 @@ -142,7 +145,7 @@ controller_server: # Solver limits (core defaults). max_int_iter_qp: 1500 max_ext_iter_qp: 10000 - max_iter_sqp: 100 + max_iter_sqp: 1 qp_type: false guess: true max_solver_failures: 3 @@ -159,8 +162,10 @@ controller_server: # lower gamma; this value targets the open-world single/dynamic cells. # * max_obstacles 4: capture the box plus adjacent wall cells. max_obstacles: 4 - safety_margin: 0.1 - robot_radius: 0.22 + # 0.085 with robot_radius 0.235 keeps d_safe at 0.320 m; the radius is the + # footprint's circumscribed value and the margin is the discretionary part. + safety_margin: 0.085 + robot_radius: 0.235 cbf_gamma: 1.0 costmap_cost_threshold: 253 obstacle_cluster_radius: 0.3 @@ -175,9 +180,32 @@ controller_server: predict_obstacles: true obstacle_topic: "tracked_obstacles" obstacle_timeout: 0.5 + # Speed above which a track is propagated as a mover. Kept at 0.2 rather + # than lowered, though the demo walker's own tracked speed often sits under + # it: a lidar sees only the near arc of a compact object, so the centroid + # slides as the robot moves and the estimate reads well below the walker's + # true 0.3 m/s (measured p50 0.02, p90 0.10-0.18 m/s). Lowering the gate to + # catch that does not separate the two populations - the static box's own + # centroid noise reaches 0.12 m/s on the same runs - so it would admit the + # box as a mover with a fabricated velocity, which is worse than missing + # the walker. The estimate is what needs fixing, not the threshold. dynamic_speed_threshold: 0.2 # Small hedge (m/s) against residual prediction error as the sample ages. prediction_uncertainty_growth: 0.05 + # Obstacle-aware cruise: when where the robot is heading would cut into a + # tracked mover's predicted keep-out, ease the cruise so the robot waits for + # the mover rather than racing it across. Measured with this demo's + # reversing on: passes behind a crossing mover 6/10 against 1/10 on + # dynamic_circle with the best closest approach and no collisions, and no + # worse than off with two movers (3/30 collisions either way). Keep q_pos + # and s_factor at their defaults - light stage weights collided with it. + obstacle_yield_band_m: 0.5 + # Make that yield a speed limit rather than a request: without it the cruise + # target is outweighed by the obstacle term and the robot swerves past a + # closing mover at full speed instead of slowing. Measured on the benchmark's + # orbiting-mover cell: passes behind 10/10 against 4/10, three times the + # worst-case clearance, and it holds its path instead of swerving. + obstacle_yield_caps_speed: true # After an association break (obstacle direction reversal) the old track # coasts as a phantom while the real obstacle is re-acquired as a new track; # with a single slot the phantom can outrank the real track and the solver @@ -185,6 +213,20 @@ controller_server: max_dynamic_obstacles: 2 max_dynamic_obstacle_radius: 0.5 + + # Whether the solver may plan reverse travel at all. False narrows the + # linear control bound to [0, v_max]. On, so the demo shows the robot + # backing up to adjust and then pursuing the path forward, the way a + # vehicle manoeuvres. Reverse stays capped at 0.15 m/s by the controller's + # own guard: both guards follow the predicted trajectory and so do cover a + # reversing one, but they see only what the costmap holds, and whether the + # platform sweeps behind itself is a property of its sensor. The waffle's + # lidar is 360 degrees, so the rear is covered here. The goal + # region no longer alternates on an open reverse bound - the reference is + # pinned to the goal pose there, and the robot turns on the spot for the + # last of the heading. See doc/nav2-simulation.md. + allow_reversing: true + log_level: "info" local_costmap: @@ -195,6 +237,9 @@ local_costmap: global_frame: odom robot_base_frame: base_link rolling_window: true + # Unobserved cells are marked NO_INFORMATION rather than defaulting to + # free space, so the costmap does not claim to have seen what it has not. + track_unknown_space: true width: 3 height: 3 resolution: 0.05 diff --git a/prox_mpc_demo/doc/nav2-simulation.md b/prox_mpc_demo/doc/nav2-simulation.md index fca61b8..02c8d4a 100644 --- a/prox_mpc_demo/doc/nav2-simulation.md +++ b/prox_mpc_demo/doc/nav2-simulation.md @@ -223,6 +223,26 @@ ros2 run ros_gz_sim create -name walker \ -file $DEMO/models/prox_mpc_dynamic_actor/model.sdf -x 0.8 -y -1.6 -z 0.5 ``` +> **The two obstacles together do not exercise predictive avoidance.** The box +> sits on the path at `(0.0, -0.5)` and the walker circles beyond it, so for +> about 71% of the approach the box lies between the robot and the walker and +> hides it from the lidar. Replaying the tracker's own clustering over recorded +> scans, the walker is detected in 19% of scans with the box present against 55% +> without it; at that hit rate a track rarely survives `confirm_count: 3` to be +> published at all, and across ten runs of this pair no moving track was ever +> published. What the robot avoids here is the box, from the costmap. +> +> To watch the predictive path actually run, spawn the walker on its own - +> omit the `path_box` line above. The walker is then tracked within a few +> seconds and the controller plans against its predicted positions. +> +> Moving the walker is not a fix on its own: shifting it further along the path +> (`-x 1.8`) raises occlusion to 78%, and every spawn that lowers it either +> brings the walker within the tracker's `cluster_gap` of the box or puts its +> orbit on top of the robot's start pose. Separating the two properly is a +> scenario redesign - a smaller orbit, or more room between start, box and +> crossing - not a coordinate tweak. + Terminal C - send the same goal: ```bash @@ -282,6 +302,54 @@ against the live loop: avoidance is delegated entirely to Nav2's planner + costmaps (global replanning around marked obstacles), the standard Nav2 architecture. Keep it for path-tracking runs that should behave as plain Nav2 navigation. +- `allow_reversing: true` - the solver may plan reverse travel, so the linear + control bound keeps its negative half and the robot backs up to adjust before + pursuing the path forward, the way a vehicle manoeuvres. Reverse is capped at + 0.15 m/s by the controller's own guard. Both guards follow the predicted + trajectory, so they do cover a reversing one, but they see only what the + costmap holds, and whether a platform sweeps behind itself is a property of its + sensor rather than of the controller. The waffle carries a 360-degree lidar, so + the rear is covered here; naming `model_params.v_min` is how a platform states + the reverse envelope its own sensing supports. + + An earlier release shipped this `false`. Reverse was not the problem: inside + the goal-checker xy tolerance the reference collapsed to a stub a few + millimetres ahead of the robot's own projection onto the plan, which the + projection then carried along, so a small tracking error could be traded down + as cheaply one way as the other and an open reverse bound gave the solver a + second way to do it. Pinning the reference to the goal pose in that region, and + turning on the spot for the last of the heading, removes the degeneracy at + source; with that in place reverse measures better than forward-only on every + scenario. Same goals, same configuration otherwise, measured over the commanded + `cmd_vel_nav`, headless: + + | Scenario | Before the fix (reverse on) | Forward-only | Now (reverse on) | + | --- | --- | --- | --- | + | East 4 m then west 4.5 m | 1 change, 41.1 s, 73% reversing | 0 changes, 38.6 s | 2 changes, 27.8 s | + | Static box + circling walker | 28 changes, 59.8 s | 0 changes, 19.8 s | 0 changes, 12.2 s | + | North, 90 degree turn | 35 changes, 68.8 s | 0 changes, 21.7 s | 1 change, 9.5 s | + + Nav2 logged 9 `Failed to make progress` events across the three "before" + runs and 2 across the forward-only runs, where the controller stalled on a + terminal heading error and a recovery behaviour took over; it logs none now. + The direction changes that remain are single deliberate manoeuvres - back up, + then drive forward - rather than an alternation. + + `reverse_from_plan_orientation` stays at its `false` default: this demo plans + with NavFn, which leaves every plan pose at the identity quaternion, so those + orientations carry no travel direction to read (see + [prox_mpc_controller/doc/architecture.md](../../prox_mpc_controller/doc/architecture.md)). + The standstill and dwell gates on a direction change are inert while it is off. +- `obstacle_yield_band_m: 0.5` (predictive file only) - when where the robot is + heading would cut into a tracked mover's predicted keep-out, the cruise eases + so the robot waits for the mover rather than racing it. Without it the robot + tends to pass in front of a mover heading for its path, because the global + planner picks the side from where the obstacle is now and knows nothing of + where it is going. Measured with this demo's reversing on, over ten + `dynamic_circle` runs: passes behind 6/10 against 1/10, with the best closest + approach and no collisions; with two movers it is no worse than off (3/30 + collisions either way). It is absent from the non-predictive file, which runs + no tracker and so has no predictions to act on. - `docking_server` block is kept from the stock params because the navigation lifecycle manager brings it up and aborts the whole bringup if its `dock_plugins` is unset. @@ -301,10 +369,13 @@ What it changes from the baseline (the rest of the stack is identical): - `max_obstacles: 4`, `cbf_gamma: 1.0` - the in-loop NMPC obstacle term runs alongside Nav2, with four slots so the box and the adjacent wall cells are all captured. `cbf_gamma: 1.0` is the pointwise keep-out, which is what this config - targets: the open-world single-obstacle and dynamic cells. A dense obstacle field - is the case that may instead want a lower gamma, where the discrete-time CBF - coupling (`cbf_gamma < 1`) lets the safety margin decay gradually rather than - binding at every node. + targets: the open-world single-obstacle and dynamic cells. A dense obstacle + field is a case the discrete-time CBF coupling (`cbf_gamma < 1`) is meant for + - decaying the safety margin gradually rather than binding at every node - + but its effect at the shipped slack weight has not yet been benchmarked (see + [control-law.md](../../prox_mpc_controller/doc/control-law.md#discrete-time-control-barrier-coupling)), + so treat a lower gamma as a tunable option to measure, not a settled + recommendation for this scenario. - `predict_obstacles: true`, `max_dynamic_obstacles: 2` - a confirmed *moving* track is propagated over the horizon along its tracker-sampled predicted trajectory (a constant-velocity ray when no samples are provided) and bound to a diff --git a/prox_mpc_demo/package.xml b/prox_mpc_demo/package.xml index 9bc85b3..1ff2e25 100644 --- a/prox_mpc_demo/package.xml +++ b/prox_mpc_demo/package.xml @@ -2,7 +2,7 @@ prox_mpc_demo - 1.0.0 + 2.0.0 Self-contained closed-loop simulation and benchmark for the ProxMPC core: drives a bundled kinematic model (bicycle / unicycle) toward a goal with no external simulator, publishes the command and predicted path, and logs the diff --git a/prox_mpc_msgs/CHANGELOG.rst b/prox_mpc_msgs/CHANGELOG.rst index 4107688..a78ceff 100644 --- a/prox_mpc_msgs/CHANGELOG.rst +++ b/prox_mpc_msgs/CHANGELOG.rst @@ -2,6 +2,14 @@ Changelog for package prox_mpc_msgs ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2.0.0 (2026-09-13) +------------------ +* No interface change: the message definitions and their wire format are + unchanged from 1.0.0. Version raised to keep the repository's packages + aligned. +* Added a wire-compatibility test for ``SolverDiagnostics``. +* Contributors: Simone Contorno + 1.0.0 (2026-07-28) ------------------ * Initial release: ``Obstacle`` and ``ObstacleArray`` messages for tracked diff --git a/prox_mpc_msgs/CMakeLists.txt b/prox_mpc_msgs/CMakeLists.txt index 501fe06..23bb9b2 100644 --- a/prox_mpc_msgs/CMakeLists.txt +++ b/prox_mpc_msgs/CMakeLists.txt @@ -6,6 +6,23 @@ find_package(geometry_msgs REQUIRED) find_package(std_msgs REQUIRED) find_package(rosidl_default_generators REQUIRED) +# Compiler warnings, matching upstream Nav2's package-level policy +# (nav2_common/cmake/nav2_package.cmake), applied directory-wide exactly as +# nav2_msgs does it (before rosidl_generate_interfaces() below, so the +# generated typesupport targets are held to the same bar as hand-written code). +if(CMAKE_CXX_COMPILER_ID MATCHES "GNU" OR CMAKE_CXX_COMPILER_ID MATCHES "Clang") + add_compile_options(-Wall -Wextra -Wpedantic -Werror -Wdeprecated -fPIC -Wshadow -Wnull-dereference) + # GCC 13 raises -Wnull-dereference inside libstdc++'s own headers + # (stl_algobase.h, reached through regex_traits::transform_primary) once + # --coverage changes its inlining decisions, which is how the coverage build + # hits it and an ordinary build does not. The report is attributed to the + # translation unit that instantiates the template, so -Wno-system-headers + # does not reach it. Keep the diagnostic, but do not let a false positive in + # the standard library fail the build. + add_compile_options(-Wno-error=null-dereference) + add_compile_options("$<$:-Wnon-virtual-dtor>") +endif() + rosidl_generate_interfaces(${PROJECT_NAME} msg/Obstacle.msg msg/ObstacleArray.msg @@ -17,10 +34,32 @@ ament_export_dependencies(rosidl_default_runtime) if(BUILD_TESTING) find_package(ament_lint_auto REQUIRED) + # uncrustify is the enforced C++ formatter across this repository; cpplint is + # intentionally disabled everywhere else to avoid duplicating/contradicting + # it (every other package's CMakeLists carries this same override). This + # package never needed it until its first C++ test file. + set(ament_cmake_cpplint_FOUND TRUE) # Copyright is disabled: interface-only package, no per-file headers; # full text in LICENSE. set(ament_cmake_copyright_FOUND TRUE) ament_lint_auto_find_test_dependencies() + + find_package(ament_cmake_gtest REQUIRED) + find_package(rosidl_typesupport_introspection_cpp REQUIRED) + + # Wire-format pin: field names, order, types, defaults and the STATUS_* + # constant values, generated by the rosidl_generate_interfaces() call above. + # The introspection typesupport target is what defines the declaration-order + # member list get_message_type_support_handle() returns. + rosidl_get_typesupport_target(cpp_typesupport_target ${PROJECT_NAME} rosidl_typesupport_cpp) + rosidl_get_typesupport_target( + introspection_typesupport_target ${PROJECT_NAME} rosidl_typesupport_introspection_cpp) + ament_add_gtest(test_solver_diagnostics_wire test/test_solver_diagnostics_wire.cpp) + target_link_libraries(test_solver_diagnostics_wire + ${cpp_typesupport_target} + ${introspection_typesupport_target} + ) + ament_target_dependencies(test_solver_diagnostics_wire rosidl_typesupport_introspection_cpp) endif() ament_package() diff --git a/prox_mpc_msgs/package.xml b/prox_mpc_msgs/package.xml index 347bb9e..335e17d 100644 --- a/prox_mpc_msgs/package.xml +++ b/prox_mpc_msgs/package.xml @@ -2,7 +2,7 @@ prox_mpc_msgs - 1.0.0 + 2.0.0 Message contract for the ProxMPC stack: Obstacle and ObstacleArray carry tracked-obstacle id, position, velocity, radius, covariances, and sampled predicted positions from the obstacle tracker to the Nav2 controller plugin; @@ -21,8 +21,10 @@ rosidl_default_runtime + ament_cmake_gtest ament_lint_auto ament_lint_common + rosidl_typesupport_introspection_cpp rosidl_interface_packages diff --git a/prox_mpc_msgs/test/test_solver_diagnostics_wire.cpp b/prox_mpc_msgs/test/test_solver_diagnostics_wire.cpp new file mode 100644 index 0000000..7b0a306 --- /dev/null +++ b/prox_mpc_msgs/test/test_solver_diagnostics_wire.cpp @@ -0,0 +1,152 @@ +// Copyright 2026 Simone Contorno +// SPDX-License-Identifier: Apache-2.0 + + +// SolverDiagnostics.msg shipped in prox_mpc_msgs 1.0.0, so its layout is +// already installed on users' machines; this file pins that wire contract, +// which nothing did before. It fixes field names, C++ types, declaration order +// and zero-initialized defaults for all 14 fields, and the values of the 7 +// STATUS_* constants, so a later removal, rename, reorder or retype fails the +// suite rather than silently breaking a benchmark script or a recorded bag. +// +// Field order is checked through the rosidl introspection typesupport +// (declaration-order member list), not merely by naming every field: naming +// alone would not catch two fields swapping position while keeping their own +// names and types. + +#include +#include +#include + +#include + +#include +#include + +#include +#include +#include + +using prox_mpc_msgs::msg::Obstacle; +using prox_mpc_msgs::msg::ObstacleArray; +using prox_mpc_msgs::msg::SolverDiagnostics; + +// --- Field names and declaration order --------------------------------------- + +TEST(SolverDiagnosticsWire, FieldOrderMatchesReleasedContract) +{ + const auto * ts = + rosidl_typesupport_introspection_cpp::get_message_type_support_handle(); + ASSERT_NE(ts, nullptr); + const auto * members = + static_cast(ts->data); + ASSERT_NE(members, nullptr); + + // The 14 fields released at 1.0.0, in their declared order. + const std::string expected[] = { + "header", "solve_time_ms", "qp_solve_time_ms", "status", "converged", + "sqp_iters", "qp_iters_ext", "primal_residual", "dual_residual", "objective", + "max_obstacle_slack", "control_period_ms", "deadline_missed", "num_active_obstacles" + }; + ASSERT_EQ(members->member_count_, sizeof(expected) / sizeof(expected[0])); + for (std::uint32_t i = 0; i < members->member_count_; ++i) { + EXPECT_EQ(std::string(members->members_[i].name_), expected[i]) << "at position " << i; + } +} + +// --- Field types, via compile-time-checked assignment ------------------------ +// +// A renamed, retyped or removed field fails to compile here, which is the +// point: this is a source-level pin, not merely a runtime check. + +TEST(SolverDiagnosticsWire, FieldTypesMatchReleasedContract) +{ + SolverDiagnostics d; + d.header = std_msgs::msg::Header(); + d.solve_time_ms = 1.5; + d.qp_solve_time_ms = 1.5; + d.status = std::uint8_t{0}; + d.converged = true; + d.sqp_iters = std::uint32_t{0}; + d.qp_iters_ext = std::uint32_t{0}; + d.primal_residual = 1.5; + d.dual_residual = 1.5; + d.objective = 1.5; + d.max_obstacle_slack = 1.5; + d.control_period_ms = 1.5; + d.deadline_missed = true; + d.num_active_obstacles = std::uint16_t{0}; +} + +// --- Zero-initialized defaults ------------------------------------------------ + +TEST(SolverDiagnosticsWire, DefaultConstructedFieldsAreZero) +{ + SolverDiagnostics d; + EXPECT_EQ(d.solve_time_ms, 0.0); + EXPECT_EQ(d.qp_solve_time_ms, 0.0); + EXPECT_EQ(d.status, SolverDiagnostics::STATUS_SOLVED); // both zero, not independently telling + EXPECT_FALSE(d.converged); + EXPECT_EQ(d.sqp_iters, 0u); + EXPECT_EQ(d.qp_iters_ext, 0u); + EXPECT_EQ(d.primal_residual, 0.0); + EXPECT_EQ(d.dual_residual, 0.0); + EXPECT_EQ(d.objective, 0.0); + EXPECT_EQ(d.max_obstacle_slack, 0.0); + EXPECT_EQ(d.control_period_ms, 0.0); + EXPECT_FALSE(d.deadline_missed); + EXPECT_EQ(d.num_active_obstacles, 0u); +} + +// --- STATUS_* constants ------------------------------------------------------- +// +// The message's own comment: these are the message's contract, not a copy of +// proxsuite's QPSolverOutput ordering, mapped explicitly rather than cast so a +// value recorded here never changes meaning even if proxsuite reorders its own +// enum. Pinning the numeric values is what makes that promise checkable. + +TEST(SolverDiagnosticsWire, StatusConstantsMatchReleasedValues) +{ + EXPECT_EQ(SolverDiagnostics::STATUS_SOLVED, 0); + EXPECT_EQ(SolverDiagnostics::STATUS_MAX_ITER_REACHED, 1); + EXPECT_EQ(SolverDiagnostics::STATUS_PRIMAL_INFEASIBLE, 2); + EXPECT_EQ(SolverDiagnostics::STATUS_DUAL_INFEASIBLE, 3); + EXPECT_EQ(SolverDiagnostics::STATUS_NOT_RUN, 4); + EXPECT_EQ(SolverDiagnostics::STATUS_SOLVED_CLOSEST_PRIMAL_FEASIBLE, 5); + EXPECT_EQ(SolverDiagnostics::STATUS_UNKNOWN, 255); +} + +// --- Obstacle / ObstacleArray: pinned for completeness ---------------------- +// +// These two messages are also released at 1.0.0 and unchanged since; included +// so a future change to either is caught by the same suite that guards +// SolverDiagnostics. + +TEST(ObstacleWire, FieldOrderMatchesReleasedContract) +{ + const auto * ts = + rosidl_typesupport_introspection_cpp::get_message_type_support_handle(); + const auto * members = + static_cast(ts->data); + const std::string expected[] = { + "id", "position", "velocity", "radius", "position_covariance", + "velocity_covariance", "predicted_positions", "prediction_dt" + }; + ASSERT_EQ(members->member_count_, sizeof(expected) / sizeof(expected[0])); + for (std::uint32_t i = 0; i < members->member_count_; ++i) { + EXPECT_EQ(std::string(members->members_[i].name_), expected[i]) << "at position " << i; + } +} + +TEST(ObstacleArrayWire, FieldOrderMatchesReleasedContract) +{ + const auto * ts = + rosidl_typesupport_introspection_cpp::get_message_type_support_handle(); + const auto * members = + static_cast(ts->data); + const std::string expected[] = {"header", "obstacles"}; + ASSERT_EQ(members->member_count_, sizeof(expected) / sizeof(expected[0])); + for (std::uint32_t i = 0; i < members->member_count_; ++i) { + EXPECT_EQ(std::string(members->members_[i].name_), expected[i]) << "at position " << i; + } +} diff --git a/prox_mpc_obstacle_tracker/CHANGELOG.rst b/prox_mpc_obstacle_tracker/CHANGELOG.rst index d987ed4..1e38955 100644 --- a/prox_mpc_obstacle_tracker/CHANGELOG.rst +++ b/prox_mpc_obstacle_tracker/CHANGELOG.rst @@ -2,6 +2,15 @@ Changelog for package prox_mpc_obstacle_tracker ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2.0.0 (2026-09-13) +------------------ +* Repeat shutdown signals are idempotent. One shutdown reaches the process + twice whenever a supervisor signals the process group and the launch parent + also forwards to each child, and treating the second as a force-quit skipped + the finalize ladder on an ordinary shutdown. +* Mutex-guarded perception state is annotated. +* Contributors: Simone Contorno + 1.0.0 (2026-07-28) ------------------ * Initial release: lifecycle node that clusters a 2D ``LaserScan``, associates diff --git a/prox_mpc_obstacle_tracker/CMakeLists.txt b/prox_mpc_obstacle_tracker/CMakeLists.txt index 1de9761..71c6667 100644 --- a/prox_mpc_obstacle_tracker/CMakeLists.txt +++ b/prox_mpc_obstacle_tracker/CMakeLists.txt @@ -10,9 +10,20 @@ if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE "Release") endif() -# Compiler warnings -if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang") - add_compile_options(-Wall -Wextra -Wpedantic) +# Compiler warnings, matching upstream Nav2's package-level policy +# (nav2_common/cmake/nav2_package.cmake) so this package is held to the same +# bar as every other Nav2 plugin it ships alongside. +if(CMAKE_CXX_COMPILER_ID MATCHES "GNU" OR CMAKE_CXX_COMPILER_ID MATCHES "Clang") + add_compile_options(-Wall -Wextra -Wpedantic -Werror -Wdeprecated -fPIC -Wshadow -Wnull-dereference) + # GCC 13 raises -Wnull-dereference inside libstdc++'s own headers + # (stl_algobase.h, reached through regex_traits::transform_primary) once + # --coverage changes its inlining decisions, which is how the coverage build + # hits it and an ordinary build does not. The report is attributed to the + # translation unit that instantiates the template, so -Wno-system-headers + # does not reach it. Keep the diagnostic, but do not let a false positive in + # the standard library fail the build. + add_compile_options(-Wno-error=null-dereference) + add_compile_options("$<$:-Wnon-virtual-dtor>") endif() # Remove Eigen's internal assertions in the hot path (safe under Release) @@ -27,6 +38,7 @@ find_package(prox_mpc_msgs REQUIRED) find_package(rclcpp REQUIRED) find_package(rclcpp_components REQUIRED) find_package(rclcpp_lifecycle REQUIRED) +find_package(rcpputils REQUIRED) find_package(sensor_msgs REQUIRED) find_package(tf2 REQUIRED) find_package(tf2_ros REQUIRED) @@ -61,6 +73,7 @@ ament_target_dependencies(${PROJECT_NAME}_component rclcpp rclcpp_components rclcpp_lifecycle + rcpputils sensor_msgs tf2 tf2_ros diff --git a/prox_mpc_obstacle_tracker/README.md b/prox_mpc_obstacle_tracker/README.md index 392324b..e0e630f 100644 --- a/prox_mpc_obstacle_tracker/README.md +++ b/prox_mpc_obstacle_tracker/README.md @@ -149,8 +149,11 @@ preset), so the controller always interpolates and never extrapolates there. The node is a managed lifecycle node. The standalone `obstacle_tracker` executable is a self-activating driver: it walks the node up (`configure -> activate`), spins, and on `SIGINT`/`SIGTERM` runs a -single checked finalize ladder (`deactivate -> cleanup -> shutdown`); a second -signal force-quits. +single checked finalize ladder (`deactivate -> cleanup -> shutdown`). +Repeat signals are idempotent, because one shutdown reaches the process twice +whenever a supervisor signals the process group and the launch parent also +forwards to each child; a genuine hang is bounded by the supervisor's `SIGKILL` +escalation rather than by a force-quit in the handler. ```mermaid stateDiagram-v2 diff --git a/prox_mpc_obstacle_tracker/doc/architecture.md b/prox_mpc_obstacle_tracker/doc/architecture.md index 20ca367..18a4771 100644 --- a/prox_mpc_obstacle_tracker/doc/architecture.md +++ b/prox_mpc_obstacle_tracker/doc/architecture.md @@ -145,7 +145,11 @@ The node follows the standard managed-node lifecycle. The standalone driver installs its own async-signal-safe `SIGINT`/`SIGTERM` handler, cancels the spin, and runs a single checked finalize ladder -(`deactivate -> cleanup -> shutdown`); a second signal force-quits. +(`deactivate -> cleanup -> shutdown`). +Repeat signals are idempotent: one shutdown reaches the process twice whenever a +supervisor signals the process group and the launch parent also forwards to each +child, so a repeat only re-asserts the stop flag rather than skipping the ladder. +A genuine hang is bounded by the supervisor's `SIGKILL` escalation. ## Parameters diff --git a/prox_mpc_obstacle_tracker/include/prox_mpc_obstacle_tracker/obstacle_tracker_node.hpp b/prox_mpc_obstacle_tracker/include/prox_mpc_obstacle_tracker/obstacle_tracker_node.hpp index edb5d7f..6c1851e 100644 --- a/prox_mpc_obstacle_tracker/include/prox_mpc_obstacle_tracker/obstacle_tracker_node.hpp +++ b/prox_mpc_obstacle_tracker/include/prox_mpc_obstacle_tracker/obstacle_tracker_node.hpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -84,21 +85,25 @@ class ObstacleTrackerNode : public rclcpp_lifecycle::LifecycleNode // samples). The other IMM/CTRV parameters live only in Tracker::Params. double prediction_dt_{0.1}; - // ROS interfaces. + // ROS interfaces. scan_sub_ is written only from the executor thread that runs + // the lifecycle transitions (on_activate/on_deactivate/teardown), which never + // overlaps a scan callback because the subscription itself does not exist yet + // or has already been reset by the time this member changes, so it is not + // part of the state_mutex_-guarded set below. rclcpp::Subscription::SharedPtr scan_sub_; std::shared_ptr> - obstacle_pub_; - std::shared_ptr tf_buffer_; - std::shared_ptr tf_listener_; + obstacle_pub_ RCPPUTILS_TSA_GUARDED_BY(state_mutex_); + std::shared_ptr tf_buffer_ RCPPUTILS_TSA_GUARDED_BY(state_mutex_); + std::shared_ptr tf_listener_ RCPPUTILS_TSA_GUARDED_BY(state_mutex_); - std::unique_ptr tracker_; + std::unique_ptr tracker_ RCPPUTILS_TSA_GUARDED_BY(state_mutex_); std::atomic active_{false}; /// Mutually-exclusive group for the scan callback so it never overlaps itself, /// and a mutex serializing the scan callback against lifecycle teardown so the - /// shared perception state (tracker_, obstacle_pub_, tf_buffer_) is never used - /// after reset. This makes the node safe to compose into a MultiThreadedExecutor - /// as well as to run standalone (SingleThreadedExecutor). + /// shared perception state (tracker_, obstacle_pub_, tf_buffer_, tf_listener_) + /// is never used after reset. This makes the node safe to compose into a + /// MultiThreadedExecutor as well as to run standalone (SingleThreadedExecutor). rclcpp::CallbackGroup::SharedPtr scan_callback_group_; std::mutex state_mutex_; }; diff --git a/prox_mpc_obstacle_tracker/package.xml b/prox_mpc_obstacle_tracker/package.xml index 091e5d0..8b94066 100644 --- a/prox_mpc_obstacle_tracker/package.xml +++ b/prox_mpc_obstacle_tracker/package.xml @@ -2,7 +2,7 @@ prox_mpc_obstacle_tracker - 1.0.0 + 2.0.0 In-house 2D-lidar dynamic-obstacle detector and tracker for ProxMPC: a lifecycle node that clusters a LaserScan, associates clusters to IMM (constant-velocity / constant-turn-rate) Kalman tracks in a fixed frame, @@ -22,6 +22,7 @@ rclcpp rclcpp_components rclcpp_lifecycle + rcpputils sensor_msgs tf2 tf2_ros diff --git a/prox_mpc_obstacle_tracker/src/main.cpp b/prox_mpc_obstacle_tracker/src/main.cpp index 402e568..4863d57 100644 --- a/prox_mpc_obstacle_tracker/src/main.cpp +++ b/prox_mpc_obstacle_tracker/src/main.cpp @@ -23,16 +23,18 @@ namespace { -/// Lock-free stop flag set by the signal handler; a second signal force-quits. +/// Lock-free stop flag set by the signal handler; repeat signals are idempotent. std::atomic g_stop{false}; static_assert( std::atomic::is_always_lock_free, "stop flag must be lock-free for async-signal safety"); +// One shutdown reaches this process through two independent paths: a process-group +// signal hits the node directly, and the launch parent then forwards its own signal +// to each child. Treating the second as an impatient-user force-quit would skip the +// finalize ladder on an ordinary shutdown, so repeats only re-assert the flag; the +// supervisor's SIGKILL escalation remains the hard backstop for a genuine hang. void on_signal(int /*sig*/) { - if (g_stop.load(std::memory_order_relaxed)) { - std::_Exit(EXIT_FAILURE); // second signal: force-quit, skip teardown - } g_stop.store(true, std::memory_order_relaxed); } diff --git a/prox_mpc_obstacle_tracker/src/obstacle_tracker_node.cpp b/prox_mpc_obstacle_tracker/src/obstacle_tracker_node.cpp index de264f4..c4f9141 100644 --- a/prox_mpc_obstacle_tracker/src/obstacle_tracker_node.cpp +++ b/prox_mpc_obstacle_tracker/src/obstacle_tracker_node.cpp @@ -146,10 +146,15 @@ ObstacleTrackerNode::CallbackReturn ObstacleTrackerNode::on_configure( } tp.max_tracks = static_cast(max_tracks); - tracker_ = std::make_unique(tp); - - obstacle_pub_ = create_publisher( - output_topic_, rclcpp::QoS(rclcpp::KeepLast(5))); + // No scan callback can be running yet (the subscription is created only in + // on_activate, below), but the lock is still taken here so the guarded set + // is provably consistent regardless of executor scheduling. + { + std::lock_guard lock(state_mutex_); + tracker_ = std::make_unique(tp); + obstacle_pub_ = create_publisher( + output_topic_, rclcpp::QoS(rclcpp::KeepLast(5))); + } RCLCPP_INFO( get_logger(), @@ -169,13 +174,21 @@ ObstacleTrackerNode::CallbackReturn ObstacleTrackerNode::on_activate( { try { LifecycleNode::on_activate(state); // activates managed entities (the publisher) - if (tracker_) {tracker_->reset();} // start the velocity estimate fresh - // TF is only read by the scan callback, so it lives with the active state (not - // configure). spin_thread = true: a dedicated thread services /tf and /tf_static - // so the callback can lookupTransform at the scan stamp with a timeout. - tf_buffer_ = std::make_shared(get_clock()); - tf_listener_ = std::make_shared(*tf_buffer_, this, true); + // No scan callback can be running yet (the subscription is created below, + // after this block), but the lock is still taken here so the guarded set + // is provably consistent regardless of executor scheduling. + { + std::lock_guard lock(state_mutex_); + if (tracker_) {tracker_->reset();} // start the velocity estimate fresh + + // TF is only read by the scan callback, so it lives with the active state + // (not configure). spin_thread = true: a dedicated thread services /tf and + // /tf_static so the callback can lookupTransform at the scan stamp with a + // timeout. + tf_buffer_ = std::make_shared(get_clock()); + tf_listener_ = std::make_shared(*tf_buffer_, this, true); + } // Depth 1 (large-sensor profile): keep only the freshest scan and minimize // memory, rather than the SensorDataQoS default of KeepLast(5). diff --git a/prox_mpc_test_models/CHANGELOG.rst b/prox_mpc_test_models/CHANGELOG.rst index dc5c2f8..dad8698 100644 --- a/prox_mpc_test_models/CHANGELOG.rst +++ b/prox_mpc_test_models/CHANGELOG.rst @@ -2,6 +2,12 @@ Changelog for package prox_mpc_test_models ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +2.0.0 (2026-09-13) +------------------ +* Added fault and mapping fixtures: asymmetric control bounds, a permuted planar + mapping, and a non-finite-other-axes twist model. +* Contributors: Simone Contorno + 1.0.0 (2026-07-28) ------------------ * Initial release: fault-injection ``prox_mpc::Model`` plugin (``NonFiniteTwist``) diff --git a/prox_mpc_test_models/CMakeLists.txt b/prox_mpc_test_models/CMakeLists.txt index bad822f..28eefe0 100644 --- a/prox_mpc_test_models/CMakeLists.txt +++ b/prox_mpc_test_models/CMakeLists.txt @@ -10,9 +10,20 @@ if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE "Release") endif() -# Compiler warnings -if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang") - add_compile_options(-Wall -Wextra -Wpedantic) +# Compiler warnings, matching upstream Nav2's package-level policy +# (nav2_common/cmake/nav2_package.cmake) so this package is held to the same +# bar as every other Nav2 plugin it ships alongside. +if(CMAKE_CXX_COMPILER_ID MATCHES "GNU" OR CMAKE_CXX_COMPILER_ID MATCHES "Clang") + add_compile_options(-Wall -Wextra -Wpedantic -Werror -Wdeprecated -fPIC -Wshadow -Wnull-dereference) + # GCC 13 raises -Wnull-dereference inside libstdc++'s own headers + # (stl_algobase.h, reached through regex_traits::transform_primary) once + # --coverage changes its inlining decisions, which is how the coverage build + # hits it and an ordinary build does not. The report is attributed to the + # translation unit that instantiates the template, so -Wno-system-headers + # does not reach it. Keep the diagnostic, but do not let a false positive in + # the standard library fail the build. + add_compile_options(-Wno-error=null-dereference) + add_compile_options("$<$:-Wnon-virtual-dtor>") endif() # Match prox_mpc_core's Eigen assertion setting so this fixture builds against diff --git a/prox_mpc_test_models/README.md b/prox_mpc_test_models/README.md index 075cab0..cef1ee6 100644 --- a/prox_mpc_test_models/README.md +++ b/prox_mpc_test_models/README.md @@ -8,6 +8,9 @@ These are fault-injection models that exercise controller fail-safe paths the bu They are registered against the same `prox_mpc::Model` base as the core models, so [prox_mpc_controller](../prox_mpc_controller) loads them through its ordinary `pluginlib` path during testing - no test-only seam in production code. > **Not for production use.** This package exists only to drive tests. +> Its plugin and class names are not a stable interface: a fixture may be +> renamed, replaced, or removed without notice, unlike the released +> `prox_mpc_core` models it is registered alongside. ## Table of Contents @@ -21,7 +24,7 @@ They are registered against the same `prox_mpc::Model` base as the core models, ## Overview -The package is a header-and-plugin fixture: it contributes one deliberately faulty `prox_mpc::Model` implementation and its `pluginlib` registration, with no executable and no ROS node. +The package is a header-and-plugin fixture: it contributes `prox_mpc::Model` implementations the bundled production models cannot stand in for (a deliberately faulty one, an asymmetric-bounds one, a permuted-state one) and their `pluginlib` registration, with no executable and no ROS node. It is a `` of [prox_mpc_controller](../prox_mpc_controller), so it is present only when that package's tests are built. ## Models @@ -29,10 +32,22 @@ It is a `` of [prox_mpc_controller](../prox_mpc_controller), so it | Plugin name | Class | Purpose | | --- | --- | --- | | `prox_mpc_test_models/NonFiniteTwist` | `prox_mpc_test_models::NonFiniteTwistModel` | Finite linear dynamics (state `[x, y, theta]`, control `[v, omega]`) so the QP converges and reports `PROXQP_SOLVED` with a finite first control, but `toTwist()` deliberately returns a non-finite command (`linear.x = NaN`). | +| `prox_mpc_test_models/AsymmetricBounds` | `prox_mpc_test_models::AsymmetricBoundsModel` | Same finite linear dynamics as `NonFiniteTwist`, but every declared bound is asymmetric (reverse speed capped tighter than forward speed; braking rate harder than accelerating rate). Both bundled production models declare symmetric bounds, so this is the only fixture that can show the controller preserving an asymmetric range instead of assuming symmetry. | +| `prox_mpc_test_models/NonFiniteTwistOtherAxes` | `prox_mpc_test_models::NonFiniteTwistOtherAxesModel` | Same finite linear dynamics as `NonFiniteTwist`, but `toTwist()` fills `linear.y` and `angular.x` with non-finite values instead of `linear.x` -- the four `Twist` components a planar Nav2 consumer never reads, so nothing exercises the controller's validation of them without this fixture. | +| `prox_mpc_test_models/PermutedPlanarMapping` | `prox_mpc_test_models::PermutedPlanarMappingModel` | Unicycle dynamics written against a state vector ordered `[theta, x, y]`, so its declared planar mapping is `idx_yaw = 0`, `idx_x = 1`, `idx_y = 2`, with obstacle avoidance on so the in-loop keep-out term is covered against a permuted state too. Every bundled model maps its position to columns 0 and 1, so this is the only fixture that can show the controller and the solver honouring the declared mapping rather than the ordering they assumed before the mapping hook existed. | The `NonFiniteTwist` model is the only seam that reaches the controller's non-finite-command fail-safe: a finite-mapping model cannot produce a non-finite twist from a finite control, so this fixture is required to cover that branch. The controller test asserts the controller brakes at the model deceleration limit and then escalates to `nav2_core::NoValidControl` once the failure budget is spent. +The `AsymmetricBounds` model is the only seam that reaches the controller's asymmetry-preserving speed-limit and brake-ramp logic, for the same reason: a model with symmetric bounds cannot show a controller defect that only discards sign asymmetry. + +The `PermutedPlanarMapping` model is the only seam that reaches the controller's use of the declared mapping in its own assembly steps, for the same reason again: a model whose state is already `[x, y, theta]` cannot show a controller that ignores the mapping and indexes by position. + +A fixture that overrides `toTwist()` with a finite mapping must also override `fromTwist()`. +The controller seeds its deceleration ramp from every control channel the inverse reports as determined, so a fixture that inherits the base `fromTwist()` while emitting its own twist hands that ramp the inverse of a mapping it does not use, and the resulting wrong value looks like a plausible control rather than an obvious fault. +`NonFiniteTwistModel` and `NonFiniteTwistOtherAxesModel` are the exception, and deliberately so: their whole purpose is to emit a non-finite twist, which cannot round-trip through any inverse, so they override neither and are excluded from the bundled models' round-trip check (`FromTwistAgreesWithToTwistOnEveryDeterminedChannel` in `prox_mpc_core`). +A new fixture with a finite twist mapping is not exempt. + ## How It Is Used The package is a `` of `prox_mpc_controller`. @@ -61,7 +76,10 @@ ros2 plugin list --package prox_mpc_test_models # lists prox_mpc_test_models/N ```text prox_mpc_test_models/ ├── include/prox_mpc_test_models/ -│ └── non_finite_twist_model.hpp +│ ├── asymmetric_bounds_model.hpp +│ ├── non_finite_twist_model.hpp +│ ├── non_finite_twist_other_axes_model.hpp +│ └── permuted_planar_mapping_model.hpp ├── src/ │ └── plugins.cpp ├── CHANGELOG.rst diff --git a/prox_mpc_test_models/include/prox_mpc_test_models/asymmetric_bounds_model.hpp b/prox_mpc_test_models/include/prox_mpc_test_models/asymmetric_bounds_model.hpp new file mode 100644 index 0000000..4cffd54 --- /dev/null +++ b/prox_mpc_test_models/include/prox_mpc_test_models/asymmetric_bounds_model.hpp @@ -0,0 +1,69 @@ +// Copyright 2026 Simone Contorno +// SPDX-License-Identifier: Apache-2.0 + +#ifndef PROX_MPC_TEST_MODELS__ASYMMETRIC_BOUNDS_MODEL_HPP_ +#define PROX_MPC_TEST_MODELS__ASYMMETRIC_BOUNDS_MODEL_HPP_ + +#include + +#include +#include + +namespace prox_mpc_test_models +{ + +/// Fixture model whose declared bounds are asymmetric on every side the +/// controller reads, used to test that the controller preserves an asymmetric +/// range instead of assuming symmetry: both bundled production models (Bicycle, +/// Unicycle) declare symmetric bounds, so no controller behavior on asymmetry +/// can be exercised through them. Its dynamics are the same finite linear +/// integrator as NonFiniteTwistModel (state [x, y, theta], control [v, omega]), +/// and toTwist() is the Model base class's identity mapping, so the control +/// vector IS the body twist (no steering channel). +class AsymmetricBoundsModel : public prox_mpc::Model +{ +public: + AsymmetricBoundsModel() + { + setName("asymmetric_bounds"); + setN(3); // state: [x, y, theta] + setM(2); // control: [v, omega] + + setA(MatrixXd::Zero(getN(), getN())); + setB(MatrixXd::Zero(getN(), getM())); + setc(VectorXd::Zero(getN())); + + // Reverse travel is capped tighter than forward travel. + setIneq("u", 0, -0.3, 2.0); // linear velocity [m/s] + setIneq("u", 1, -1.0, 1.0); // angular velocity [rad/s] + // Braking (toward zero) is bounded harder than accelerating (away from + // zero) on the linear channel, so the ramp step differs by direction. + setIneq("du", 0, -2.0, 0.5); // linear acceleration [m/s^2] + setIneq("du", 1, -1.0, 1.0); // angular acceleration [rad/s^2] + + setObsAvoid(false); + } + + void updatec(double dt, VectorXd x_next) override + { + c << getX()(0) - x_next(0) + dt * getU()(0), + getX()(1) - x_next(1), + getX()(2) - x_next(2) + dt * getU()(1); + } + + void updateA(double /*dt*/) override + { + A = MatrixXd::Identity(getN(), getN()); + } + + void updateB() override + { + B << 1.0, 0.0, + 0.0, 0.0, + 0.0, 1.0; + } +}; + +} // namespace prox_mpc_test_models + +#endif // PROX_MPC_TEST_MODELS__ASYMMETRIC_BOUNDS_MODEL_HPP_ diff --git a/prox_mpc_test_models/include/prox_mpc_test_models/non_finite_twist_other_axes_model.hpp b/prox_mpc_test_models/include/prox_mpc_test_models/non_finite_twist_other_axes_model.hpp new file mode 100644 index 0000000..df3fdd6 --- /dev/null +++ b/prox_mpc_test_models/include/prox_mpc_test_models/non_finite_twist_other_axes_model.hpp @@ -0,0 +1,84 @@ +// Copyright 2026 Simone Contorno +// SPDX-License-Identifier: Apache-2.0 + +#ifndef PROX_MPC_TEST_MODELS__NON_FINITE_TWIST_OTHER_AXES_MODEL_HPP_ +#define PROX_MPC_TEST_MODELS__NON_FINITE_TWIST_OTHER_AXES_MODEL_HPP_ + +#include +#include + +#include + +#include +#include + +namespace prox_mpc_test_models +{ + +/// Fault-injection model for testing the controller's command-validation path +/// on a Twist component OTHER than linear.x, which NonFiniteTwistModel already +/// covers. A planar Nav2 consumer reads only linear.x and angular.z, so +/// twist_is_finite() checking all six components (not only the two a planar +/// base consumes) is untested unless something actually produces a non-finite +/// value in one of the other four. Its dynamics are the same finite linear +/// integrator as NonFiniteTwistModel (state [x, y, theta], control [v, omega]), +/// so the QP solves and reports PROXQP_SOLVED with a finite first control, but +/// toTwist() deliberately fills linear.y and angular.x with non-finite values. +class NonFiniteTwistOtherAxesModel : public prox_mpc::Model +{ +public: + NonFiniteTwistOtherAxesModel() + { + setName("non_finite_twist_other_axes"); + setN(3); // state: [x, y, theta] + setM(2); // control: [v, omega] + + setA(MatrixXd::Zero(getN(), getN())); + setB(MatrixXd::Zero(getN(), getM())); + setc(VectorXd::Zero(getN())); + + setIneq("u", 0, -3.0, 3.0); // linear velocity [m/s] + setIneq("u", 1, -1.0, 1.0); // angular velocity [rad/s] + setIneq("du", 0, -0.5, 0.5); // linear acceleration [m/s^2] + setIneq("du", 1, -0.5, 0.5); // angular acceleration [rad/s^2] + + setObsAvoid(false); + } + + /// Finite command mapped normally onto linear.x and angular.z, but with + /// linear.y and angular.x deliberately set non-finite -- the two components + /// a planar Nav2 consumer never reads, so nothing downstream of the + /// controller would ever notice unless the controller itself validates them. + geometry_msgs::msg::Twist toTwist(const VectorXd & u_in) const override + { + geometry_msgs::msg::Twist twist; + twist.linear.x = u_in.size() > 0 ? u_in(0) : 0.0; + twist.linear.y = std::numeric_limits::quiet_NaN(); + twist.angular.x = std::numeric_limits::infinity(); + twist.angular.z = u_in.size() > 1 ? u_in(1) : 0.0; + return twist; + } + + void updatec(double dt, VectorXd x_next) override + { + c << getX()(0) - x_next(0) + dt * getU()(0), + getX()(1) - x_next(1), + getX()(2) - x_next(2) + dt * getU()(1); + } + + void updateA(double /*dt*/) override + { + A = MatrixXd::Identity(getN(), getN()); + } + + void updateB() override + { + B << 1.0, 0.0, + 0.0, 0.0, + 0.0, 1.0; + } +}; + +} // namespace prox_mpc_test_models + +#endif // PROX_MPC_TEST_MODELS__NON_FINITE_TWIST_OTHER_AXES_MODEL_HPP_ diff --git a/prox_mpc_test_models/include/prox_mpc_test_models/permuted_planar_mapping_model.hpp b/prox_mpc_test_models/include/prox_mpc_test_models/permuted_planar_mapping_model.hpp new file mode 100644 index 0000000..547a92c --- /dev/null +++ b/prox_mpc_test_models/include/prox_mpc_test_models/permuted_planar_mapping_model.hpp @@ -0,0 +1,88 @@ +// Copyright 2026 Simone Contorno +// SPDX-License-Identifier: Apache-2.0 + +#ifndef PROX_MPC_TEST_MODELS__PERMUTED_PLANAR_MAPPING_MODEL_HPP_ +#define PROX_MPC_TEST_MODELS__PERMUTED_PLANAR_MAPPING_MODEL_HPP_ + +#include +#include + +#include +#include + +namespace prox_mpc_test_models +{ + +/// Fixture model whose state vector is ordered [theta, x, y] instead of the +/// [x, y, theta] every bundled model uses, so its declared planar mapping is +/// idx_yaw = 0, idx_x = 1, idx_y = 2. It is the only seam that can show the +/// controller honouring the declared mapping rather than the state ordering it +/// assumed before the mapping hook existed: every bundled model maps its +/// position to state columns 0 and 1, so no permutation defect is observable +/// through them. +/// +/// Obstacle avoidance is on, so the fixture also covers the in-loop keep-out +/// term against a permuted state: the solver reads the position's indices from +/// the same declared mapping rather than assuming state columns 0 and 1. +/// +/// The dynamics are the unicycle's, written against the permuted ordering, so +/// the model both configures and solves. +class PermutedPlanarMappingModel : public prox_mpc::Model +{ +public: + PermutedPlanarMappingModel() + { + setName("permuted_planar_mapping"); + setN(3); // state: [theta, x, y] + setM(2); // control: [v, omega] + + setA(MatrixXd::Zero(getN(), getN())); + setB(MatrixXd::Zero(getN(), getM())); + setc(VectorXd::Zero(getN())); + + setIneq("u", 0, -3.0, 3.0); // linear velocity [m/s] + setIneq("u", 1, -1.0, 1.0); // angular velocity [rad/s] + setIneq("du", 0, -0.5, 0.5); // linear acceleration [m/s^2] + setIneq("du", 1, -0.5, 0.5); // angular acceleration [rad/s^2] + + setObsAvoid(true); + } + + prox_mpc::PlanarMapping getPlanarMapping() const override + { + prox_mpc::PlanarMapping mapping; + mapping.idx_yaw = 0; + mapping.idx_x = 1; + mapping.idx_y = 2; + return mapping; + } + + void updatec(double dt, VectorXd x_next) override + { + const double th = getX()(0); + c << getX()(0) - x_next(0) + dt * getU()(1), + getX()(1) - x_next(1) + dt * getU()(0) * std::cos(th), + getX()(2) - x_next(2) + dt * getU()(0) * std::sin(th); + } + + void updateA(double dt) override + { + const double th = getX()(0); + const double v = getU()(0); + A << 1.0, 0.0, 0.0, + -dt * v * std::sin(th), 1.0, 0.0, + dt * v * std::cos(th), 0.0, 1.0; + } + + void updateB() override + { + const double th = getX()(0); + B << 0.0, 1.0, + std::cos(th), 0.0, + std::sin(th), 0.0; + } +}; + +} // namespace prox_mpc_test_models + +#endif // PROX_MPC_TEST_MODELS__PERMUTED_PLANAR_MAPPING_MODEL_HPP_ diff --git a/prox_mpc_test_models/package.xml b/prox_mpc_test_models/package.xml index 20a192a..3096a3f 100644 --- a/prox_mpc_test_models/package.xml +++ b/prox_mpc_test_models/package.xml @@ -2,11 +2,12 @@ prox_mpc_test_models - 1.0.0 + 2.0.0 Test-fixture prox_mpc::Model plugins for the ProxMPC stack. These - fault-injection models exercise controller fail-safe paths that the bundled - models cannot reach (for example a non-finite command). Not for production - use. + models exercise controller paths the bundled production models cannot reach + (for example a non-finite command, or an asymmetric bound). Not for + production use. Fixture class names are not a stable interface and may + change without notice. Simone Contorno Apache-2.0 https://github.com/simone-contorno/prox_mpc diff --git a/prox_mpc_test_models/prox_mpc_test_models_plugins.xml b/prox_mpc_test_models/prox_mpc_test_models_plugins.xml index 9b9eee9..52bcf2e 100644 --- a/prox_mpc_test_models/prox_mpc_test_models_plugins.xml +++ b/prox_mpc_test_models/prox_mpc_test_models_plugins.xml @@ -9,4 +9,41 @@ exercise the controller's non-finite-command fail-safe. Test fixture only. + + + Fixture model with an asymmetric range on every declared bound (state + [x, y, theta], control [v, omega]): reverse speed capped tighter than + forward speed, and a harder braking rate than accelerating rate. Used to + test that the controller preserves bound asymmetry instead of assuming + symmetry. Test fixture only. + + + + + Fault-injection test model: finite linear dynamics (state [x, y, theta], + control [v, omega]) but a toTwist() that deliberately fills linear.y and + angular.x (not linear.x, which NonFiniteTwist already covers) with + non-finite values, exercising the controller's command validation on the + four Twist components a planar consumer never reads. Test fixture only. + + + + + Fixture model whose state vector is ordered [theta, x, y] instead of + [x, y, theta], so its declared planar mapping is idx_yaw = 0, idx_x = 1, + idx_y = 2. Obstacle avoidance is on, so it also covers the in-loop + keep-out term against a permuted state. Used to test that the controller + and the solver drive a model through its declared mapping rather than + through the bundled state ordering. Test fixture only. + + diff --git a/prox_mpc_test_models/src/plugins.cpp b/prox_mpc_test_models/src/plugins.cpp index 4df56c3..1bdc865 100644 --- a/prox_mpc_test_models/src/plugins.cpp +++ b/prox_mpc_test_models/src/plugins.cpp @@ -9,6 +9,12 @@ #include #include +#include #include +#include +#include PLUGINLIB_EXPORT_CLASS(prox_mpc_test_models::NonFiniteTwistModel, prox_mpc::Model) +PLUGINLIB_EXPORT_CLASS(prox_mpc_test_models::AsymmetricBoundsModel, prox_mpc::Model) +PLUGINLIB_EXPORT_CLASS(prox_mpc_test_models::NonFiniteTwistOtherAxesModel, prox_mpc::Model) +PLUGINLIB_EXPORT_CLASS(prox_mpc_test_models::PermutedPlanarMappingModel, prox_mpc::Model)