Model Predictive Control as an (f, h) System
Model Predictive Control (MPC) picks the control input by solving an optimization problem at every time step: predict the plant forward over a short horizon, find the input sequence that minimizes a cost, apply only the first input, then repeat from the newly measured state. That repeat-from-the-new-state step is called the receding horizon.
In this tutorial we
model a plant as a
DynamicalSystem,derive the MPC optimization problem for a linear plant,
cast the controller itself as a
DynamicalSystem— it is a block with anhand nof, i.e. \((*, h)\),close the loop and watch the receding horizon at work, with and without input constraints.
Outline
The next tutorial, MPPI as an (f, h) System, replaces the optimizer with sampling so that nonlinear dynamics and non-convex costs become easy.
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize
from dynamicalnodes import DynamicalSystem
The plant
We control a unit mass sliding on a frictionless line. The state is position and velocity, \(x = [p,\; v]^\top\), and the input \(u\) is a force:
Forward-Euler discretization with step \(\Delta t\) gives the discrete-time system
In the (f, h) formalism this is a plant with
def fplant(xk, uk, dt):
p, v = xk
return np.array([p + dt * v, v + dt * uk])
def hplant(xk):
return xk
plant = DynamicalSystem(f=fplant, h=hplant)
dt = 0.1
# one step from rest with a unit push
x_next, y = plant.step(xk=np.array([0.0, 0.0]), uk=1.0, dt=dt)
print("x_{k+1} =", x_next, " y_k =", y)
x_{k+1} = [0. 0.1] y_k = [0. 0.]
The MPC problem
At time \(k\) we measure \(x_k\) and want a reference \(r\) (a target position, so \(r_k = [r,\,0]^\top\)) reached with little control effort. Over a horizon of \(N\) steps we solve
subject to the model \(x_{i+1} = A x_i + B u_i\) with \(x_0 = x_k\), and the input limits \(u_{\min}\le u_j\le u_{\max}\).
Because the model is linear we can eliminate the predicted states. Stacking \(X = [x_1;\dots;x_N]\) and \(U=[u_0;\dots;u_{N-1}]\),
where \(\Phi\) stacks \(A, A^2, \dots, A^N\) and \(\Gamma\) is block lower-triangular with entries \(A^{i-j-1}B\). The cost becomes a quadratic in \(U\) alone,
a convex quadratic program with box constraints on \(U\). The matrices \(\Phi\), \(\Gamma\) and \(H\) do not depend on \(x_k\), so we build them once and treat them as parameters \(\theta_{\text{mpc}}\). Only \(q\) changes from step to step.
def build_theta_mpc(dt, N, Q, P, R, umin, umax):
A = np.array([[1.0, dt], [0.0, 1.0]])
B = np.array([[0.0], [dt]])
Phi = np.vstack([np.linalg.matrix_power(A, i + 1) for i in range(N)]) # (2N, 2)
Gamma = np.zeros((2 * N, N))
for i in range(N):
for j in range(i + 1):
Gamma[2 * i : 2 * i + 2, j] = (np.linalg.matrix_power(A, i - j) @ B).ravel()
Qbar = np.kron(np.eye(N), Q)
Qbar[-2:, -2:] = P # terminal weight
Rbar = R * np.eye(N)
H = 2 * (Gamma.T @ Qbar @ Gamma + Rbar)
return dict(N=N, Phi=Phi, Gamma=Gamma, Qbar=Qbar, H=H, umin=umin, umax=umax)
def solve_ocp(xk, rk, theta_mpc, U0=None):
# Solve the box-constrained QP for the optimal input sequence U*.
th = theta_mpc
N = th["N"]
q = 2 * th["Gamma"].T @ th["Qbar"] @ (th["Phi"] @ xk - np.tile(rk, N))
H = th["H"]
res = minimize(
lambda U: 0.5 * U @ H @ U + q @ U,
np.zeros(N) if U0 is None else U0,
jac=lambda U: H @ U + q,
bounds=[(th["umin"], th["umax"])] * N,
method="L-BFGS-B",
)
return res.x
MPC as an (f, h) block
The controller takes in the measured state \(x_k\) and a reference \(r_k\) and returns an input \(u_k\). If we ignore warm starting, it keeps no state of its own: every call solves the optimization from scratch. A system with no state evolution is exactly the \((*, h)\) case:
The optimizer lives inside h. The “receding horizon” is not a special mechanism: it is just the fact that the closed loop calls h again at the next step, from the new state.
def hmpc(xk, rk, theta_mpc):
U_star = solve_ocp(xk, rk, theta_mpc)
return U_star[0] # apply only the first input
mpc = DynamicalSystem(f=None, h=hmpc)
Both blocks bind their arguments by name, so plant and mpc can be given the same keyword arguments without any glue code. A single call on its own:
theta_mpc = build_theta_mpc(dt, N=20, Q=np.diag([10.0, 1.0]), P=np.diag([100.0, 10.0]),
R=0.1, umin=-1.0, umax=1.0)
_, u0 = mpc.step(xk=np.array([0.0, 0.0]), rk=np.array([1.0, 0.0]), theta_mpc=theta_mpc)
print("first MPC input from rest, 1 m from target:", float(u0))
first MPC input from rest, 1 m from target: 1.0
Closing the loop
The diagram is the usual feedback loop: the plant’s output \(y_k\) is the controller’s measurement, and the controller’s output \(u_k\) drives the plant,
In code that is an ordinary for loop. We start at \(p=0\) and ask for \(p=1\).
def simulate(theta_mpc, x0, r, steps):
xk, uk = x0.copy(), 0.0
xs, us = [xk], []
for k in range(steps):
_, uk = mpc.step(xk=xk, rk=r, theta_mpc=theta_mpc) # controller: u_k = h_mpc(x_k, r)
xk, _ = plant.step(xk=xk, uk=uk, dt=dt) # plant: x_{k+1} = f_plant(x_k, u_k)
xs.append(xk); us.append(uk)
return np.array(xs), np.array(us)
r = np.array([1.0, 0.0])
x0 = np.array([0.0, 0.0])
steps = 80
xs, us = simulate(theta_mpc, x0, r, steps)
The mass accelerates at the input limit, then brakes so as to stop on the target. The controller never saw an explicit “brake now” rule: braking emerges because the prediction shows that overshooting costs more than slowing early.
Constraints
What makes MPC attractive over, say, a PID or LQR controller is that limits on the input (or state) are part of the problem rather than an afterthought. Here we compare against the same controller with the input bounds removed.
theta_free = build_theta_mpc(dt, N=20, Q=np.diag([10.0, 1.0]), P=np.diag([100.0, 10.0]),
R=0.1, umin=-np.inf, umax=np.inf)
xs_free, us_free = simulate(theta_free, x0, r, steps)
The unconstrained controller demands a large force at the start and gets to the target faster; the constrained controller is forced to plan around its limit, because it knows it cannot brake harder than \(u_{\min}\). Neither run required changing hmpc — only the parameter set \(\theta_{\text{mpc}}\).
The receding horizon
At every step the MPC block plans \(N\) moves but executes one. To see this, we re-solve the problem at a few steps of the constrained run and draw the predicted position trajectory against what the plant actually did.
Each dashed curve is a plan made from the dot at its start. Here the prediction model is exactly the plant, so the plans lie on top of the actual trajectory. In general they would not: only the first input of each plan is applied before the next measurement replaces it, so model errors and disturbances are corrected at the next solve. That feedback is where the robustness of MPC comes from.
Summary
Piece of MPC |
In the |
|---|---|
Plant |
|
Prediction model |
the plant’s |
Cost, horizon, constraints |
parameters \(\theta_{\text{mpc}}\) |
Optimizer + “apply first input” |
inside \(h_{\text{mpc}}\) |
Controller |
\((*, h)\): |
Receding horizon |
calling |
Solving a QP only works this neatly for linear models and convex costs. For a nonlinear robot with obstacles, the optimizer can be replaced by random sampling — that is MPPI, and its controller does carry state. Continue with MPPI as an (f, h) System.