Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,8 +164,12 @@ 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
That predictive configuration is the one to deploy. Only prediction itself is on
by default (`predict_obstacles: true`): the result above also relies on the
obstacle-aware yield and its speed cap (`obstacle_yield_band_m`,
`obstacle_yield_caps_speed`) and on `allow_reversing`, all off by default and set
in the [predictive preset](prox_mpc_benchmark/config/controllers/proxmpc_pred.yaml).
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
Expand Down
Binary file modified doc/media/prox_mpc_demo_grid.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified doc/media/prox_mpc_demo_grid.mp4
Binary file not shown.
5 changes: 5 additions & 0 deletions prox_mpc_benchmark/CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ Changelog for package prox_mpc_benchmark
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.
* ``record_scenarios.py --gpu-offload`` renders RViz on the NVIDIA GPU through
PRIME render offload, set for the RViz process alone; it needs a real X server
running the NVIDIA driver. ``--fullscreen`` starts RViz fullscreen and skips
the window placement, which keeps a desktop session's panels and the window's
title bar out of the capture. Both are off by default.
* 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
Expand Down
1 change: 1 addition & 0 deletions prox_mpc_benchmark/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,7 @@ controller into its own folder, then combine per scenario:
```bash
for c in proxmpc_pred dwb mppi regulated_pure_pursuit; do
ros2 run prox_mpc_benchmark record_scenarios.py --controller "$c" \
--display :0 --resolution 2560x1440 --fullscreen --gpu-offload \
--out-dir results/videos/"$c"
done
ros2 run prox_mpc_benchmark combine_grid.sh \
Expand Down
Binary file modified prox_mpc_benchmark/doc/media/dynamic_circle_controllers.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified prox_mpc_benchmark/doc/media/dynamic_circle_controllers.mp4
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file not shown.
Binary file modified prox_mpc_benchmark/doc/media/nav2_open_controllers.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified prox_mpc_benchmark/doc/media/nav2_open_controllers.mp4
Binary file not shown.
Binary file modified prox_mpc_benchmark/doc/media/static_box_controllers.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified prox_mpc_benchmark/doc/media/static_box_controllers.mp4
Binary file not shown.
31 changes: 25 additions & 6 deletions prox_mpc_benchmark/doc/videos.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,25 @@ default on Ubuntu 24.04) the X server is rootless `Xwayland`: the compositor dra
each window through Wayland, so the grabbable X root stays **black** and every clip
records black regardless of what is on screen. Pick one of:

- **Xorg session (simplest, GPU-rendered):** log in via the GDM gear menu as
"Ubuntu on Xorg", then run the recorder unchanged (it captures `$DISPLAY`, `:0`).
- **Virtual Xvfb display (headless, scriptable - how the bundled clips were made):**
- **Xorg session (GPU-rendered - how the bundled clips are made):** log in via the
GDM gear menu as "Ubuntu on Xorg". On a desktop session RViz has to run
fullscreen - the window manager keeps a normal window off its panels, so a
windowed capture picks up the dock, the top bar and the title bar - and the grab
has to cover the whole screen; the grid combiner scales each clip to its cell. On a
hybrid-graphics laptop add `--gpu-offload` so RViz renders on the NVIDIA GPU:

```bash
ros2 run prox_mpc_benchmark record_scenarios.py --display :0 \
--resolution 2560x1440 --fullscreen --gpu-offload
```

Set `--resolution` to your screen size. The capture includes the mouse pointer and
anything that appears on screen, so leave the desktop alone while it records.
- **Virtual Xvfb display (headless, scriptable, no screen taken over):**
start a virtual X server sized to the capture, then point the recorder at it with
`--display`. RViz falls back to software GL (llvmpipe), which renders correctly:
`--display`. RViz falls back to software GL (llvmpipe), which renders correctly but
on the CPU: alongside the Nav2 stack it draws well below the capture rate, so
frames repeat and the clips look choppy:

```bash
Xvfb :99 -screen 0 1920x1080x24 +extension GLX +render -nolisten tcp &
Expand All @@ -111,10 +125,12 @@ Xvfb :99 -screen 0 1920x1080x24 +extension GLX +render -nolisten tcp &
ros2 run prox_mpc_benchmark record_scenarios.py --display :99
```

On a native Xorg session the no-argument form captures `:0` directly:
On a native Xorg desktop session record fullscreen over the whole screen, adding
`--gpu-offload` on a hybrid-graphics laptop:

```bash
ros2 run prox_mpc_benchmark record_scenarios.py
ros2 run prox_mpc_benchmark record_scenarios.py --display :0 \
--resolution 2560x1440 --fullscreen --gpu-offload
```

The equivalent fully-explicit invocation:
Expand Down Expand Up @@ -193,6 +209,7 @@ mode (the four paths and four cell labels, top-left -> bottom-right):
# one folder per controller (the tracker starts only for proxmpc_pred)
for c in proxmpc_pred dwb mppi regulated_pure_pursuit; do
ros2 run prox_mpc_benchmark record_scenarios.py --controller "$c" \
--display :0 --resolution 2560x1440 --fullscreen --gpu-offload \
--out-dir results/videos/"$c"
done

Expand Down Expand Up @@ -234,6 +251,8 @@ All artifacts land under `results/videos/` (gitignored):
| `--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 |
| `--gpu-offload` | off | render RViz on the NVIDIA GPU through PRIME render offload (`__NV_PRIME_RENDER_OFFLOAD=1`, `__GLX_VENDOR_LIBRARY_NAME=nvidia`, set for RViz alone); needs a real X server running the NVIDIA driver and does not work on a virtual Xvfb display, which has no hardware GL |
| `--fullscreen` | off | start RViz fullscreen and skip the window placement; on a desktop session this is what keeps the panels and the window's title bar out of the capture, so pair it with `--resolution` set to the full screen size |

`combine_grid.sh`:

Expand Down
55 changes: 44 additions & 11 deletions prox_mpc_benchmark/scripts/record_scenarios.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,31 @@ def build_trim_cmd(raw_path, offset, duration, out_path):
]


# NVIDIA PRIME render offload for a single process on a hybrid-graphics host, whose X
# server otherwise renders every GL client on the integrated GPU.
GPU_OFFLOAD_ENV = ('__NV_PRIME_RENDER_OFFLOAD=1', '__GLX_VENDOR_LIBRARY_NAME=nvidia')


def rviz_command(rviz_cfg, gpu_offload, fullscreen):
"""
Return the RViz launch argv, at the lowest scheduling priority.

With gpu_offload the PRIME offload variables are set for RViz alone through
env(1), so only the renderer moves to the discrete GPU and the Nav2 stack keeps
its environment. Offload needs a real X server running the NVIDIA driver; a
virtual display such as Xvfb has no hardware GL for it to reach.

With fullscreen RViz covers the whole screen, which on a desktop session is the
only way to keep the window manager's panels and the window's own title bar out
of the capture: a managed window cannot be moved over them.
"""
cmd = ['nice', '-n', '19', 'rviz2', '-d', str(rviz_cfg)]
if fullscreen:
cmd.append('--fullscreen')
cmd += ['--ros-args', '-p', 'use_sim_time:=false']
return ['env', *GPU_OFFLOAD_ENV, *cmd] if gpu_offload else cmd


class MotionWatch:
"""
Record the monotonic time of the robot's first motion, from odom.
Expand Down Expand Up @@ -324,22 +349,23 @@ def launch(role, cmd):
launch('obstacle_markers', [
'python3', str(markers_py),
'--ros-args', '--params-file', str(marker_params)])
# RViz renders on software GL under a virtual display (llvmpipe), which is
# CPU-heavy. Run it at the lowest scheduling priority so the time-sensitive Nav2
# servers (planner acknowledge, controller solve, costmap clearing) always win
# the CPU: at normal priority the contention starves the planner (goals abort on
# the bt_navigator action-acknowledge timeout) and the local costmap (obstacle
# clearing lags, leaving a moving-obstacle inflation trail).
launch('rviz', [
'nice', '-n', '19', 'rviz2', '-d', str(rviz_cfg),
'--ros-args', '-p', 'use_sim_time:=false'])
# RViz on a virtual display renders in software (llvmpipe), which is CPU-heavy, so
# it runs at the lowest scheduling priority and the time-sensitive Nav2 servers
# (planner acknowledge, controller solve, costmap clearing) always win the CPU: at
# normal priority the contention starves the planner (goals abort on the
# bt_navigator action-acknowledge timeout) and the local costmap (obstacle clearing
# lags, leaving a moving-obstacle inflation trail). --gpu-offload takes the
# rendering off the CPU entirely, on a real X server with the NVIDIA driver.
launch('rviz', rviz_command(rviz_cfg, args.gpu_offload, args.fullscreen))

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)
# A fullscreen window already covers the screen, so it is not moved or resized.
if not args.fullscreen:
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, raw_len, raw_path)
print(f'[record] {scenario} ffmpeg: {shlex.join(cmd)}', flush=True)
Expand Down Expand Up @@ -423,6 +449,13 @@ def main() -> int:
'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')
ap.add_argument('--gpu-offload', action='store_true',
help='render RViz on the NVIDIA GPU through PRIME render offload; '
'needs a real X server with the NVIDIA driver, not Xvfb')
ap.add_argument('--fullscreen', action='store_true',
help='start RViz fullscreen and skip the window placement, so the panels '
'of a desktop session stay out of the capture; set --resolution to '
'the full screen size')
args = ap.parse_args()

rn = load_run_nav2()
Expand Down
22 changes: 22 additions & 0 deletions prox_mpc_benchmark/test/test_record_scenarios.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,25 @@ def test_dynamic_circle_records_long_enough_to_finish():
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


def test_rviz_runs_at_the_lowest_priority_without_offload():
cmd = rs.rviz_command(Path('recording.rviz'), False, False)
assert cmd[:4] == ['nice', '-n', '19', 'rviz2']
assert not any(arg.startswith(('__NV_', '__GLX_')) for arg in cmd)
assert '--fullscreen' not in cmd


def test_gpu_offload_moves_only_rviz_to_the_nvidia_gpu():
cmd = rs.rviz_command(Path('recording.rviz'), True, False)
assert cmd[0] == 'env'
assert '__NV_PRIME_RENDER_OFFLOAD=1' in cmd
assert '__GLX_VENDOR_LIBRARY_NAME=nvidia' in cmd
# Apart from the offload variables it is the same niced RViz launch.
assert cmd[cmd.index('nice'):] == rs.rviz_command(Path('recording.rviz'), False, False)


def test_fullscreen_is_an_rviz_option_not_a_ros_argument():
cmd = rs.rviz_command(Path('recording.rviz'), True, True)
# RViz options have to precede --ros-args, which hands the rest to ROS.
assert cmd.index('--fullscreen') < cmd.index('--ros-args')
4 changes: 4 additions & 0 deletions prox_mpc_controller/CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,10 @@ Changelog for package prox_mpc_controller
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.
* ``reset()`` clears the predicted-obstacle markers. They were cleared only by
the next control cycle, and the controller server stops cycling when a task
ends, so RViz kept drawing the last prediction after the goal while the
obstacle moved on.
* ``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
Expand Down
2 changes: 1 addition & 1 deletion prox_mpc_controller/doc/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ The command itself is the `TwistStamped` returned from `computeVelocityCommands`
| --- | --- | --- | --- | --- | --- |
| `prox_mpc_local_plan` | `nav_msgs/msg/Path` | depth 1 | Published | always | Predicted NMPC trajectory (`Np+1` poses, costmap global frame), distinct from the Nav2 global plan; sent only when a subscriber is connected. |
| `tracked_obstacles` (configurable) | `prox_mpc_msgs/msg/ObstacleArray` | reliable, depth 5 | Subscribed | `predict_obstacles` only | Tracked dynamic obstacles for predictive avoidance. |
| `prox_mpc_predicted_obstacles` | `visualization_msgs/msg/MarkerArray` | depth 1 | Published | `predict_obstacles` only | Predicted dynamic-obstacle trajectories for RViz; sent only when a subscriber is connected. |
| `prox_mpc_predicted_obstacles` | `visualization_msgs/msg/MarkerArray` | depth 1 | Published | `predict_obstacles` only | Predicted dynamic-obstacle trajectories for RViz; sent only when a subscriber is connected, and cleared by `reset()` when a task ends. |
| `<plugin>/diagnostics` (e.g. `FollowPath/diagnostics`) | `prox_mpc_msgs/msg/SolverDiagnostics` | reliable, depth 10 | Published | `publish_diagnostics` only | Per-cycle NMPC/QP solver telemetry for benchmarking; sent only when a subscriber is connected. |

The published topics `prox_mpc_local_plan`, `prox_mpc_predicted_obstacles`, and
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,8 @@ class ProxMpcController : public nav2_core::Controller
/// Request a graceful stop; returns true only once the robot has decelerated.
bool cancel() override;

/// Clear runtime state between tasks (keeps owned handles intact).
/// Clear runtime state between tasks and remove the obstacle predictions the
/// last cycle drew (keeps owned handles intact).
void reset() override;

protected:
Expand Down
11 changes: 11 additions & 0 deletions prox_mpc_controller/src/prox_mpc_controller.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1803,6 +1803,17 @@ void ProxMpcController::reset()
dir_hold_s_ = direction_switch_dwell_s_;
settling_ = false;
yield_factor_ = 1.0;
/* The controller server stops cycling when a task ends, so the predictions the
* last cycle drew are cleared here; RViz would otherwise keep drawing them while
* the obstacles move on. The server also resets on deactivate, when the
* publisher is already inactive and a publish would only log a warning. */
{
std::lock_guard<std::mutex> lock(obstacles_mutex_);
predicted_obstacles_.clear();
}
if (marker_pub_ && marker_pub_->is_activated()) {
publishPredictedObstacleMarkers(clock_->now());
}
}

void ProxMpcController::obstacleCallback(prox_mpc_msgs::msg::ObstacleArray::ConstSharedPtr msg)
Expand Down
62 changes: 61 additions & 1 deletion prox_mpc_controller/test/test_prox_mpc_controller.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
// reduction, and the footprint veto;
// - setSpeedLimit(): absolute, percentage, clamping, NO_SPEED_LIMIT restore,
// the cache-before-model case, and the deferred apply-on-next-cycle contract;
// - cancel()/reset(): graceful-stop ramp and runtime-state clearing.
// - cancel()/reset(): graceful-stop ramp, runtime-state clearing, and the clear
// of the drawn obstacle predictions.
//
// Fail-safe branches each assert the safe command the plan specifies, not merely
// that the call returns: an empty plan throws nav2_core::InvalidPath; a TF
Expand Down Expand Up @@ -55,6 +56,8 @@
#include <rclcpp_lifecycle/lifecycle_node.hpp>
#include <rcutils/logging.h>
#include <tf2_ros/buffer.h>
#include <visualization_msgs/msg/marker.hpp>
#include <visualization_msgs/msg/marker_array.hpp>

#include <prox_mpc_msgs/msg/obstacle_array.hpp>

Expand Down Expand Up @@ -1789,6 +1792,63 @@ TEST_F(ProxMpcControllerTest, ResetClearsRuntimeState)
EXPECT_NE(c->model(), nullptr);
}

// reset() removes the obstacle predictions the last cycle drew: the controller
// server stops cycling when a task ends, so nothing else clears them from RViz. The
// server also resets on deactivate, when the inactive publisher must stay silent.
TEST_F(ProxMpcControllerTest, ResetClearsDrawnObstaclePredictions)
{
auto c = makeRunning(
{
rclcpp::Parameter("FollowPath.predict_obstacles", true),
rclcpp::Parameter("FollowPath.dynamic_speed_threshold", 0.05),
});

visualization_msgs::msg::MarkerArray received;
int count = 0;
auto sub = node_->create_subscription<visualization_msgs::msg::MarkerArray>(
"prox_mpc_predicted_obstacles", 10,
[&](visualization_msgs::msg::MarkerArray::SharedPtr msg) {received = *msg; ++count;});

rclcpp::executors::SingleThreadedExecutor exec;
exec.add_node(node_->get_node_base_interface());
const auto spin_for = [&](int iterations) {
for (int i = 0; i < iterations; ++i) {
exec.spin_some();
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
};
const auto drawn_predictions = [&]() {
std::size_t n = 0;
for (const auto & m : received.markers) {
if (m.action == visualization_msgs::msg::Marker::ADD && !m.points.empty()) {++n;}
}
return n;
};

// The publish is skipped until a subscriber connects, so re-drive the cycle with a
// fresh track until a drawn prediction is delivered, then drain in-flight arrays.
for (int i = 0; i < 100 && drawn_predictions() == 0u; ++i) {
c->injectObstacles(makeObstacleMsg(node_->get_clock()->now(), 2.0, 0.5, -0.5, 0.0, 0.2));
runCycle(c);
spin_for(1);
}
spin_for(20);
ASSERT_GT(drawn_predictions(), 0u);

c->reset();
for (int i = 0; i < 100 && received.markers.size() != 1u; ++i) {
spin_for(1);
}
ASSERT_EQ(received.markers.size(), 1u);
EXPECT_EQ(received.markers.front().action, visualization_msgs::msg::Marker::DELETEALL);

c->deactivate();
const int after_deactivate = count;
c->reset();
spin_for(20);
EXPECT_EQ(count, after_deactivate);
}

// --- reduceCostmap(): obstacle reduction (white-box) -----------------------

// reduceCostmap clusters nearby lethal cells into at most K representatives per
Expand Down
8 changes: 4 additions & 4 deletions prox_mpc_core/CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ Changelog for package prox_mpc_core
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.
* **Breaking:** ``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.
Expand Down