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

  1. model a plant as a DynamicalSystem,

  2. derive the MPC optimization problem for a linear plant,

  3. cast the controller itself as a DynamicalSystem — it is a block with an h and no f, i.e. \((*, h)\),

  4. 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:

\[\dot p = v, \qquad \dot v = u .\]

Forward-Euler discretization with step \(\Delta t\) gives the discrete-time system

\[\begin{split}x_{k+1} = \underbrace{\begin{bmatrix}1 & \Delta t\\ 0 & 1\end{bmatrix}}_{A} x_k + \underbrace{\begin{bmatrix}0\\ \Delta t\end{bmatrix}}_{B} u_k, \qquad y_k = x_k .\end{split}\]

In the (f, h) formalism this is a plant with

\[f_{\text{plant}}(x_k, u_k, \Delta t) = A x_k + B u_k, \qquad h_{\text{plant}}(x_k) = x_k .\]
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

\[\min_{u_0,\dots,u_{N-1}} \;\; \sum_{i=1}^{N-1} (x_i - r)^\top Q\,(x_i - r) \;+\; (x_N - r)^\top P\,(x_N - r) \;+\; \sum_{j=0}^{N-1} R\,u_j^2\]

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}]\),

\[X = \Phi\, x_k + \Gamma\, U ,\]

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,

\[J(U) = \tfrac12 U^\top H\,U + q^\top U + \text{const}, \qquad H = 2(\Gamma^\top \bar Q\,\Gamma + \bar R), \quad q = 2\,\Gamma^\top \bar Q\,(\Phi x_k - \bar r),\]

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:

\[u_k = h_{\text{mpc}}(x_k, r_k, \theta_{\text{mpc}}) = \big[\operatorname*{arg\,min}_{U}\; J(U;\,x_k, r_k)\big]_0 .\]

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,

\[y_k = h_{\text{plant}}(x_k), \qquad u_k = h_{\text{mpc}}(y_k, r_k), \qquad x_{k+1} = f_{\text{plant}}(x_k, u_k) .\]

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)

Hide code cell source

t = dt * np.arange(steps + 1)
fig, ax = plt.subplots(3, 1, figsize=(7, 6), sharex=True)
ax[0].plot(t, xs[:, 0]); ax[0].axhline(r[0], color="gray", ls="--"); ax[0].set_ylabel("position p")
ax[1].plot(t, xs[:, 1]); ax[1].set_ylabel("velocity v")
ax[2].step(t[:-1], us, where="post"); ax[2].axhline(1, color="gray", ls=":"); ax[2].axhline(-1, color="gray", ls=":")
ax[2].set_ylabel("input u"); ax[2].set_xlabel("time [s]")
fig.tight_layout(); plt.show()
../../_images/1914999c4aea1b372ed22f6c548654af326cdfa3958631c5ebf86fd022f8b3c1.png

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)

Hide code cell source

fig, ax = plt.subplots(2, 1, figsize=(7, 4.5), sharex=True)
ax[0].plot(t, xs[:, 0], label=r"$|u|\leq 1$"); ax[0].plot(t, xs_free[:, 0], label="unconstrained")
ax[0].axhline(r[0], color="gray", ls="--"); ax[0].set_ylabel("position p"); ax[0].legend()
ax[1].step(t[:-1], us, where="post"); ax[1].step(t[:-1], us_free, where="post")
ax[1].set_ylabel("input u"); ax[1].set_xlabel("time [s]")
fig.tight_layout(); plt.show()
../../_images/99491b8e2a157a645e15a44e2ade07f2b8722a2a4260a92f91e23a043f6363df.png

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.

Hide code cell source

fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(t, xs[:, 0], "k", lw=2, label="actual")
for k in (0, 8, 16, 24):
    U_star = solve_ocp(xs[k], r, theta_mpc)
    X = (theta_mpc["Phi"] @ xs[k] + theta_mpc["Gamma"] @ U_star).reshape(-1, 2)
    tp = t[k] + dt * np.arange(1, len(X) + 1)
    ax.plot(np.r_[t[k], tp], np.r_[xs[k, 0], X[:, 0]], "--", label=f"prediction at k={k}")
    ax.plot(t[k], xs[k, 0], "o", color="k")
ax.axhline(r[0], color="gray", ls=":"); ax.set_xlabel("time [s]"); ax.set_ylabel("position p")
ax.legend(); fig.tight_layout(); plt.show()
../../_images/3daf2cdd8d8199e10fa580569d0406c34e876c011b8df1bd889f45ef6c49a0c2.png

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 (f, h) formalism

Plant

DynamicalSystem(f=fplant, h=hplant)

Prediction model

the plant’s f (here as the matrices \(\Phi,\Gamma\))

Cost, horizon, constraints

parameters \(\theta_{\text{mpc}}\)

Optimizer + “apply first input”

inside \(h_{\text{mpc}}\)

Controller

\((*, h)\): DynamicalSystem(f=None, h=hmpc)

Receding horizon

calling h again at the next step

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.