MPPI as an (f, h) System

Model Predictive Path Integral control (MPPI) is a sampling-based form of MPC. Instead of solving an optimization problem with a gradient or QP solver (see the previous tutorial, MPC as an (f, h) System), MPPI

  1. keeps a nominal input sequence \(U\) over a horizon of \(T\) steps,

  2. perturbs it with \(K\) random noise sequences and simulates each perturbed sequence forward with the model,

  3. scores every rollout with a cost \(S^{(k)}\), and

  4. averages the noise, weighted by \(\exp(-S^{(k)}/\lambda)\), to improve \(U\).

No gradients are needed, so the model may be nonlinear and the cost may be non-convex or even discontinuous — an obstacle penalty, for example.

The second half of this tutorial is concrete: we take the MPPI controller that drives a TurtleBot4 to a goal around a circular obstacle (the gracemppi repository, mppi_obstacle/mpc_node.py) and show, piece by piece, how it is an (f, h) system. The code below reproduces that controller’s numbers (config.yaml) exactly.

Outline

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle

from dynamicalnodes import DynamicalSystem

The MPPI algorithm

Let the plant be \(x_{k+1} = f_{\text{plant}}(x_k, u_k)\). At time \(k\), with measured state \(x_k\) and nominal sequence \(U = [u_0,\dots,u_{T-1}]\):

  1. Draw noise \(\varepsilon^{(i)} = [\varepsilon^{(i)}_0,\dots,\varepsilon^{(i)}_{T-1}]\) with \(\varepsilon^{(i)}_t \sim \mathcal N(0,\Sigma)\) for \(i=1,\dots,K\).

  2. Roll out each sample from \(x_k\): \(\;\tilde u^{(i)}_t = \operatorname{clip}\big(u_t + \varepsilon^{(i)}_t\big)\), \(\;x^{(i)}_{t+1} = f_{\text{plant}}(x^{(i)}_t, \tilde u^{(i)}_t)\).

  3. Total cost of each rollout: \(S^{(i)} = \sum_{t} c(x^{(i)}_{t+1}, \tilde u^{(i)}_t) + c_T(x^{(i)}_T)\).

  4. Weights (a soft-min, shifted by \(\beta=\min_i S^{(i)}\) for numerical stability):

\[w^{(i)} = \frac{\exp\!\big(-(S^{(i)}-\beta)/\lambda\big)}{\sum_j \exp\!\big(-(S^{(j)}-\beta)/\lambda\big)} .\]
  1. Update the nominal sequence with the weighted average noise: \(\;U \leftarrow U + \sum_i w^{(i)}\varepsilon^{(i)}\).

  2. Send the first input \(u_0\) to the plant, then shift the sequence, \(U \leftarrow [u_1,\dots,u_{T-1},\,0]\), so the next step starts from a good guess (a warm start).

The temperature \(\lambda\) sets how greedy the average is: small \(\lambda\) lets the best rollout dominate; large \(\lambda\) averages all of them.

From the ROS node to (f, h)

The feature that distinguishes MPPI from the stateless MPC of the previous tutorial is step 6: the controller remembers \(U\) between calls. That memory is the controller’s state. Matching the pieces of MPPIController / MPCNode to the formalism:

gracemppi (mpc_node.py)

(f, h) formalism

unicycle update inside rollout and the TurtleBot itself

plant: \(f_{\text{plant}}\), \(h_{\text{plant}}\) — the same \(f\) is the prediction model

mocap PoseStamped on the pose topic

plant output \(y_k = h_{\text{plant}}(x_k)\), the controller’s measurement

navigation.goal from the config

reference \(r_k\) from a \((*, h)\) block

np.random.normal(...) in update

noise source: a \((*, h)\) block, output \(\varepsilon_k\)

self.U (the nominal sequence, T × [v, w])

controller state \(o_k = U_k\)

rollout, softmin weights, self.U += dU

the shared computation of \(f_{\text{mppi}}\) and \(h_{\text{mppi}}\)

u0 = self.U[0] (clipped)

\(h_{\text{mppi}}\): the output \(u_k\)

self.U[:-1] = self.U[1:]; self.U[-1] = 0 (shift)

\(f_{\text{mppi}}\): the state update \(U_{k+1}\)

config.yaml (dt, horizon, num_samples, lambda_, stds, limits, weights, obstacle)

parameters \(\theta\)

MPCNode.control_loop on a timer, publishing Twist

the loop that calls step; a ROSNode wrapper

The controller block is therefore a full \((f, h)\) pair:

\[\begin{split}\begin{aligned} U_{k+1} &= f_{\text{mppi}}(U_k,\, x_k,\, r_k,\, \varepsilon_k,\, \theta) &&\text{shift}\big(U_k + \textstyle\sum_i w^{(i)}\varepsilon^{(i)}_k\big)\\ u_k &= h_{\text{mppi}}(U_k,\, x_k,\, r_k,\, \varepsilon_k,\, \theta) &&\operatorname{clip}\big[U_k + \textstyle\sum_i w^{(i)}\varepsilon^{(i)}_k\big]_0 . \end{aligned}\end{split}\]

Two details are worth noting.

  • Randomness is an input. In the node the noise is drawn inside update. Both \(f\) and \(h\) need the same noise, so we pull the random draw out into its own \((*, h)\) block and pass \(\varepsilon_k\) to both. That keeps f and h deterministic functions, which is exactly what makes the block easy to test (and to generate as a ROS node).

  • h and f share one computation. DynamicalSystem.step evaluates \(h\) on the pre-update state \(U_k\). In the node the output is the first element of the updated sequence \(U_k + \sum_i w^{(i)}\varepsilon^{(i)}\), so \(h\) performs the update itself before reading \(u_0\), and \(f\) performs the same update before shifting. The extra evaluation is cheap.

The plant

The TurtleBot is modeled as a unicycle. The state is \(x = [x,\;y,\;\theta]^\top\) (position and heading) and the input is \(u=[v,\;\omega]^\top\) (forward speed and turn rate). With Euler step \(\Delta t\),

\[\begin{split}f_{\text{plant}}(x_k, u_k, \Delta t)= \begin{bmatrix} x + v\cos\theta\,\Delta t\\ y + v\sin\theta\,\Delta t\\ \theta + \omega\,\Delta t\end{bmatrix}, \qquad h_{\text{plant}}(x_k) = x_k ,\end{split}\]

where \(h_{\text{plant}}\) stands in for the OptiTrack pose measurement. We keep the two halves as separate blocks: the plant is \((f, *)\) and the sensor is \((*, h)\). The function is written with ... indexing so it works on a single state and on a whole batch of \(K\) states at once — we exploit that for the rollouts.

def fplant(xk, uk, dt):
    x, y, th = xk[..., 0], xk[..., 1], xk[..., 2]
    v, w = uk[..., 0], uk[..., 1]
    return np.stack([x + v * np.cos(th) * dt,
                     y + v * np.sin(th) * dt,
                     th + w * dt], axis=-1)


def hplant(xk):
    return xk


plant = DynamicalSystem(f=fplant, h=None)              # (f, *)
sensor = DynamicalSystem(f=None, h=hplant)             # (*, h): the mocap measurement

The reference

The goal pose \(r=[x_d,\,y_d,\,\theta_d]\) comes from navigation.goal in the config. A signal that is not driven by any state is a \((*, h)\) block, so the reference generator is one. In a ROS deployment this is the node that publishes the goal.

def href(goal):
    return np.array(goal)


reference = DynamicalSystem(f=None, h=href)

The noise source

Another \((*, h)\) block: it outputs a fresh noise tensor \(\varepsilon_k\) of shape \(K \times T \times 2\), with standard deviations v_std and w_std for the speed and turn-rate channels.

def hnoise(K, T, std, rng):
    return rng.normal(0.0, std, size=(K, T, 2))


noise = DynamicalSystem(f=None, h=hnoise)

The cost and the rollout

All numbers below are the values in config.yaml; the parameters \(\theta\) are one dictionary.

theta = dict(
    dt=0.05, T=60, K=600, lam=1.0,                       # time step, horizon, samples, temperature
    std=np.array([0.05, 0.1]),                           # v_std, w_std
    v_max=0.3, w_max=1.8,
    wx=10.0, wy=12.0, wtheta=0.1, wv=0.1, ww=0.01, wo=100.0,
    obstacle=np.array([-0.59, -0.63, 0.245]),            # x, y, radius
    robot_radius=0.18,
)

Stage cost. For a rollout state \((x,y,\theta)\) reached with input \((v,\omega)\),

\[c = w_x (x-x_d)^2 + w_y (y-y_d)^2 + w_\theta(\theta-\theta_d)^2 + w_v v^2 + w_\omega \omega^2 + c_{\text{obs}} .\]

With \(d\) the distance to the obstacle centre, \(r_o\) its radius, \(r_r\) the robot radius and \(b = r_r + r_o + 0.75\) a buffer radius, the obstacle term is a smooth penalty inside the buffer and a huge one on collision:

\[c_{\text{obs}} = w_o\Big(\tfrac{b-d}{b}\Big)^2 \mathbb 1[d<b] \;+\; 10^6\, w_o\, \mathbb 1[d < r_o + r_r] .\]

The discontinuity is no problem for MPPI — it never differentiates the cost. The terminal cost adds \(3w_x(x_T-x_d)^2 + 3w_y(y_T-y_d)^2\) to the total, which the original code uses to reduce oscillation.

def stage_cost(xk, uk, rk, theta):
    x, y, th = xk[..., 0], xk[..., 1], xk[..., 2]
    xd, yd, thd = rk
    xo, yo, ro = theta["obstacle"]
    buffer_radius = theta["robot_radius"] + ro + 0.75

    S = (theta["wx"] * (x - xd) ** 2 + theta["wy"] * (y - yd) ** 2
         + theta["wtheta"] * (th - thd) ** 2
         + theta["wv"] * uk[..., 0] ** 2 + theta["ww"] * uk[..., 1] ** 2)

    d = np.hypot(x - xo, y - yo)
    S = S + np.where(d < buffer_radius, theta["wo"] * ((buffer_radius - d) / buffer_radius) ** 2, 0.0)
    S = S + np.where(d < ro + theta["robot_radius"], theta["wo"] * 1e6, 0.0)
    return S


def terminal_cost(xk, rk, theta):
    return (theta["wx"] * 3 * (xk[..., 0] - rk[0]) ** 2
            + theta["wy"] * 3 * (xk[..., 1] - rk[1]) ** 2)

Rollout. Simulate all \(K\) perturbed sequences at once. The model used for prediction is the plant’s own \(f\): fplant is called on a \(K\times 3\) batch of states. The commanded speed and turn rate are clipped to the actuator limits, and speed to \([0, v_{\max}]\) because the TurtleBot cannot reliably reverse.

def rollout(xk, Uk, eps, rk, theta):
    K, T, _ = eps.shape
    x = np.tile(xk, (K, 1))
    S = np.zeros(K)
    traj = []
    for t in range(T):
        u = Uk[t] + eps[:, t]
        u = np.stack([np.clip(u[:, 0], 0.0, theta["v_max"]),
                      np.clip(u[:, 1], -theta["w_max"], theta["w_max"])], axis=-1)
        x = fplant(x, u, theta["dt"])
        S += stage_cost(x, u, rk, theta)
        traj.append(x)
    S += terminal_cost(x, rk, theta)
    return np.stack(traj, axis=1), S          # (K, T, 3), (K,)

The MPPI block

First the shared computation: weights from the soft-min of the costs, and the improved sequence \(U_k + \sum_i w^{(i)}\varepsilon^{(i)}\).

def improved_sequence(Uk, xk, rk, eps, theta):
    _, S = rollout(xk, Uk, eps, rk, theta)
    w = np.exp(-(S - S.min()) / theta["lam"])
    w /= w.sum()
    return Uk + np.einsum("k,ktj->tj", w, eps)

Now the two halves of the block. The state is the nominal sequence \(U_k\) (shape \(T \times 2\)).

  • \(f_{\text{mppi}}\) returns the shifted improved sequence — the warm start for the next call.

  • \(h_{\text{mppi}}\) returns the first improved input, clipped to the actuator limits.

def fmppi(Uk, xk, rk, eps, theta):
    U_new = improved_sequence(Uk, xk, rk, eps, theta)
    return np.vstack([U_new[1:], np.zeros((1, 2))])          # shift, pad with zeros


def hmppi(Uk, xk, rk, eps, theta):
    U_new = improved_sequence(Uk, xk, rk, eps, theta)
    return np.array([np.clip(U_new[0, 0], 0.0, theta["v_max"]),
                     np.clip(U_new[0, 1], -theta["w_max"], theta["w_max"])])


mppi = DynamicalSystem(f=fmppi, h=hmppi)

That is the whole controller. Everything in the original MPPIController — rollout, soft-min weights, noise-weighted update, clipping, shift — is in these functions, and nothing is hidden in an object: the only thing that persists between calls is the Uk that we pass in and get back.

Closing the loop

One iteration of the simulation is one pass around the diagram:

\[r_k = h_{\text{ref}},\quad \varepsilon_k = h_{\text{noise}},\quad y_k = h_{\text{plant}}(x_k),\quad (U_{k+1},\,u_k) = \text{mppi}(U_k, y_k, r_k, \varepsilon_k),\quad x_{k+1}=f_{\text{plant}}(x_k, u_k).\]

We start in the lower left and drive to \((2,\,1)\); the obstacle from the config sits close to the straight-line path.

rng = np.random.default_rng(0)
goal = [2.0, 1.0, 0.0]

xk = np.array([-2.0, -1.2, 0.0])          # plant state
Uk = np.zeros((theta["T"], 2))            # MPPI state: nominal input sequence

steps = 600
X, Us, U_hist = [xk], [], []
for k in range(steps):
    _, rk = reference.step(goal=goal)
    _, eps = noise.step(K=theta["K"], T=theta["T"], std=theta["std"], rng=rng)
    _, yk = sensor.step(xk=xk)                                                   # measurement y_k
    U_hist.append(Uk)
    Uk, uk = mppi.step(Uk=Uk, xk=yk, rk=rk, eps=eps, theta=theta)                # (U_{k+1}, u_k)
    xk, _ = plant.step(xk=xk, uk=uk, dt=theta["dt"])                             # x_{k+1}
    X.append(xk); Us.append(uk)
X, Us = np.array(X), np.array(Us)
print("final state:", np.round(X[-1], 3), "  distance to goal:", round(float(np.hypot(*(X[-1, :2] - goal[:2]))), 3))
final state: [1.985 0.993 0.039]   distance to goal: 0.017

Hide code cell source

xo, yo, ro = theta["obstacle"]
buffer_r = theta["robot_radius"] + ro + 0.75
t = theta["dt"] * np.arange(steps + 1)

fig = plt.figure(figsize=(10, 4.5))
ax = fig.add_subplot(1, 2, 1)
ax.add_patch(Circle((xo, yo), buffer_r, color="orange", alpha=0.15, label="buffer"))
ax.add_patch(Circle((xo, yo), ro, color="tab:red", alpha=0.6, label="obstacle"))
ax.plot(X[:, 0], X[:, 1], "k", label="path")
ax.plot(*X[0, :2], "go"); ax.plot(goal[0], goal[1], "b*", ms=14, label="goal")
ax.set_aspect("equal"); ax.set_xlabel("x [m]"); ax.set_ylabel("y [m]"); ax.legend(loc="upper left", fontsize=8)

ax = fig.add_subplot(2, 2, 2)
ax.plot(t[:-1], Us[:, 0]); ax.set_ylabel("v [m/s]")
ax = fig.add_subplot(2, 2, 4)
ax.plot(t[:-1], Us[:, 1]); ax.set_ylabel(r"$\omega$ [rad/s]"); ax.set_xlabel("time [s]")
fig.tight_layout(); plt.show()
../../_images/a38fa368bf2d3218c7847d4025c13987dd4324fda04dfb977d156216c4f5b5d6.png

The robot skirts the obstacle, staying clear of its body, and settles on the goal, never being told how to go around — the avoidance emerges from sampling many rollouts and weighting the cheap ones.

Inside one MPPI step

To see what the soft-min is doing, we take step 60 of the run above and draw all \(K\) sampled rollouts, coloured by their weight \(w^{(i)}\). The thick line is the rollout of the updated nominal sequence.

k0 = 60
x0 = X[k0]
U_nom = U_hist[k0]                # the controller state at that step
rng2 = np.random.default_rng(1)

eps = rng2.normal(0, theta["std"], (theta["K"], theta["T"], 2))
traj, S = rollout(x0, U_nom, eps, np.array(goal), theta)
w = np.exp(-(S - S.min()) / theta["lam"]); w /= w.sum()
U_new = improved_sequence(U_nom, x0, np.array(goal), eps, theta)
traj_new, _ = rollout(x0, U_new, np.zeros_like(eps[:1]), np.array(goal), theta)
print("effective number of samples 1/sum(w^2):", round(float(1 / np.sum(w ** 2)), 1), "of", theta["K"])
effective number of samples 1/sum(w^2): 5.8 of 600

Hide code cell source

fig, ax = plt.subplots(figsize=(6.5, 5))
ax.add_patch(Circle((xo, yo), buffer_r, color="orange", alpha=0.15))
ax.add_patch(Circle((xo, yo), ro, color="tab:red", alpha=0.6))
order = np.argsort(w)
sc = None
for i in order:
    ax.plot(np.r_[x0[0], traj[i, :, 0]], np.r_[x0[1], traj[i, :, 1]], color=plt.cm.viridis(w[i] / w.max()),
            lw=0.5, alpha=0.3 + 0.7 * w[i] / w.max())
ax.plot(np.r_[x0[0], traj_new[0, :, 0]], np.r_[x0[1], traj_new[0, :, 1]], "r", lw=2.5, label="updated nominal")
ax.plot(*x0[:2], "ko"); ax.plot(goal[0], goal[1], "b*", ms=14)
ax.set_aspect("equal"); ax.set_xlabel("x [m]"); ax.set_ylabel("y [m]"); ax.legend()
ax.set_title("sampled rollouts, brighter = larger weight")
fig.tight_layout(); plt.show()
../../_images/5ba5d792770b29178735f847868c0877557cf4dbdc3a3b6726a100f6526eba25.png

Only a small fraction of the samples carry meaningful weight; the temperature \(\lambda\) controls that fraction (try changing theta["lam"] and re-running). The updated nominal sequence is the weighted blend of the good samples.

Summary

  • MPC (previous tutorial) is a \((*, h)\) block: the optimizer sits inside h.

  • MPPI is an \((f, h)\) block whose state is the nominal input sequence. h outputs the first improved input; f outputs the shifted improved sequence as the warm start for the next step.

  • Randomness, the reference, and the plant are separate blocks, so f and h are deterministic and testable; the loop is an ordinary for loop.

  • The prediction model is the plant’s own f, and the cost, weights, noise levels and obstacle are parameters \(\theta\) — changing the controller’s behaviour means changing \(\theta\) or the cost function, not the structure.

Because each block is a pair of plain named functions, mppi can be wrapped in a ROSNode and written out as an rclpy node (see the main tutorial), replacing the hand-written MPCNode — the subscription to the mocap pose, the goal and noise blocks, and the Twist publisher become the subs and pubs of the node rather than code you maintain.