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
keeps a nominal input sequence \(U\) over a horizon of \(T\) steps,
perturbs it with \(K\) random noise sequences and simulates each perturbed sequence forward with the model,
scores every rollout with a cost \(S^{(k)}\), and
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}]\):
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\).
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)\).
Total cost of each rollout: \(S^{(i)} = \sum_{t} c(x^{(i)}_{t+1}, \tilde u^{(i)}_t) + c_T(x^{(i)}_T)\).
Weights (a soft-min, shifted by \(\beta=\min_i S^{(i)}\) for numerical stability):
Update the nominal sequence with the weighted average noise: \(\;U \leftarrow U + \sum_i w^{(i)}\varepsilon^{(i)}\).
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:
|
|
|---|---|
unicycle update inside |
plant: \(f_{\text{plant}}\), \(h_{\text{plant}}\) — the same \(f\) is the prediction model |
mocap |
plant output \(y_k = h_{\text{plant}}(x_k)\), the controller’s measurement |
|
reference \(r_k\) from a \((*, h)\) block |
|
noise source: a \((*, h)\) block, output \(\varepsilon_k\) |
|
controller state \(o_k = U_k\) |
|
the shared computation of \(f_{\text{mppi}}\) and \(h_{\text{mppi}}\) |
|
\(h_{\text{mppi}}\): the output \(u_k\) |
|
\(f_{\text{mppi}}\): the state update \(U_{k+1}\) |
|
parameters \(\theta\) |
|
the loop that calls |
The controller block is therefore a full \((f, h)\) pair:
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 keepsfandhdeterministic functions, which is exactly what makes the block easy to test (and to generate as a ROS node).handfshare one computation.DynamicalSystem.stepevaluates \(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\),
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)\),
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:
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:
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
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
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.
houtputs the first improved input;foutputs the shifted improved sequence as the warm start for the next step.Randomness, the reference, and the plant are separate blocks, so
fandhare deterministic and testable; the loop is an ordinaryforloop.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.