---
title: Model predictive control
heading: Optimizing the next few moves at every sample, with the limits built in
eyebrow: S9 · Lesson 40 · Model predictive control
xp: 50
---

::: hook
Lesson 38's LQR finds the best linear feedback for an infinite future, but it knows nothing about limits: when the actuator saturates (lesson 43), the optimal law isn't optimal anymore, and may not even be stable. Chemical plants, power converters, autonomous cars and data-center cooling are full of limits on valves, currents and temperatures. **Model predictive control** handles them directly: at every sample, use a model to predict the next $N$ steps, solve an optimization for the best input sequence that respects every constraint, apply only the first input, and repeat at the next sample with fresh measurements. Without constraints and with a long enough horizon, it reproduces LQR; with them, it does what no fixed gain can.
:::

::: play
- Feedback gains for the scalar system $x_{k+1} = ax_k + 0.5u_k$ with state weight 1, against the input weight $r$. The solid curve is the infinite-horizon LQR gain, from the closed-form solution of the scalar Riccati equation; the dashed curve is a one-step MPC, $ab/(r + b^2)$.
- When inputs are cheap (small $r$) the two agree; as $r$ grows, the one-step controller under-reacts, because it can't see that a little effort now saves a lot later. A longer horizon closes the gap.
- Push $a$ above 1 (an unstable plant) and watch the one-step gain fall below what stability needs, $|a - bK| < 1$, for large $r$.
:::

```sim plot
view: graph
x: r = 0.01..10 log
y: K = 0..5
slider: a = 0.8..2 step 0.05 = 1.1
plot: a*0.5*((-(r*(1 - a^2) - 0.25) + sqrt((r*(1 - a^2) - 0.25)^2 + r))/0.5)/(r + 0.25*((-(r*(1 - a^2) - 0.25) + sqrt((r*(1 - a^2) - 0.25)^2 + r))/0.5)) | label: LQR gain
plot: a*0.5/(r + 0.25) | dashed | color: ch2 | label: one-step MPC gain
plot: (a - 1)/0.5 + 0*r | color: ch3 | label: smallest stabilizing gain
```

::: predict
## For $x_{k+1} = 1.1x_k + 0.5u_k$ with cost $x_{k+1}^2 + 0.1u_k^2$ over one step, what input does MPC apply when $x_k$ = 1?

- [ ] −2.2
- [x] About −1.57
- [ ] −1.1
- [ ] 0

::: reveal
Minimizing $(1.1 + 0.5u)^2 + 0.1u^2$: the derivative $2 \times 0.5(1.1 + 0.5u) + 0.2u = 0$ gives $u = -0.55/0.35$ = −1.571. It doesn't cancel the state completely (that would be −2.2), because the input costs something. The closed loop becomes $x_{k+1} = 0.314x_k$: stable.
:::
:::

::: nameit
## The receding horizon

At each sample $k$, with the current state $x_k$ measured or estimated (lesson 39's Kalman filter):

1. Predict the states over a horizon of $N$ steps for any candidate inputs $u_k, \ldots, u_{k+N-1}$, using the model.
2. Choose the inputs that minimize a cost, typically $\sum_{i=0}^{N-1}(x_{k+i}^TQx_{k+i} + u_{k+i}^TRu_{k+i}) + x_{k+N}^TPx_{k+N}$, subject to constraints such as $|u| \le u_{max}$ and $|x| \le x_{max}$.
3. Apply only $u_k$. At the next sample, measure again and re-solve.

## Without constraints

For a linear model and quadratic cost, the optimal inputs follow from a backward Riccati recursion over the horizon, $P_N = P$ (terminal weight), and

$$P_i = Q + A^TP_{i+1}A - A^TP_{i+1}B(R + B^TP_{i+1}B)^{-1}B^TP_{i+1}A$$

The first input is $u_k = -K_0x_k$ with $K_0 = (R + B^TP_1B)^{-1}B^TP_1A$. As $N$ grows, $P_1$ converges to the solution of lesson 38's Riccati equation and MPC becomes LQR.

## With constraints

Bounds on inputs and states turn each step into a **quadratic program**: a convex optimization with $N \times m$ variables ($m$ inputs). Clipping the unconstrained answer isn't the same: the optimizer plans ahead, for example braking early because it knows the actuator will saturate. Solvers for small QPs run in microseconds, fast enough for power converters; larger problems use slower sample rates.

## Practical issues

- **Stability:** a short horizon without a terminal cost can be unstable even when each optimization succeeds; a terminal weight equal to the LQR solution, or a long horizon, guarantees it.
- **Feasibility:** if a disturbance makes the constraints impossible to meet, the solver fails; soft constraints with penalties keep it answering.
- **Model error and offset:** MPC is only as good as its model; integral action comes from estimating a disturbance state and including it in the model.
:::

::: example
## For $x_{k+1} = 1.1x_k + 0.5u_k$ with $q$ = 1 and $r$ = 0.1, compare the one-step MPC gain and the LQR gain, and the closed-loop poles.

::: solution
1. **One-step MPC gain.** With terminal weight $q$:
   $$\begin{aligned} K &= \frac{qab}{r + qb^2} \\ &= 0.55/0.35 \\ &= 1.571 \end{aligned}$$
2. **Its closed loop.**
   $$\begin{aligned} a - bK &= 1.1 - 0.5 \times 1.571 \\ &= 0.314 \end{aligned}$$
3. **LQR Riccati equation.** Iterating
   $$P = q + a^2P - \frac{(abP)^2}{r + b^2P}$$
   converges to P = 1.375.
4. **LQR gain.**
   $$\begin{aligned} K &= \frac{abP}{r + b^2P} \\ &= 1.704 \end{aligned}$$
   with the closed loop at 0.248.
5. **Compare.** The one-step controller is a little less aggressive; with a horizon of a few steps the MPC gain matches LQR.

**Answer:** the one-step MPC gain is 1.571 (pole at 0.314) and the LQR gain is 1.704 (pole at 0.248).
:::
:::

::: example
## The same plant starts at $x_0$ = 4 with the input limited to $|u| \le 2$. What does the LQR law command at the first step, and what happens if the command is simply clipped?

::: solution
1. **What LQR commands.**
   $$-1.704 \times 4 = -6.8$$
   far beyond the limit.
2. **Clip it.** Clipped to −2, the state goes to
   $$1.1 \times 4 - 1 = 3.4$$
3. **The next step.** LQR then asks for −5.8, clipped to −2 again:
   $$1.1 \times 3.4 - 1 = 2.74$$
   and so on, recovering only slowly.
4. **Compare MPC.** Here clipping happens to give the same first moves an MPC would choose, since saturating as hard as possible is the best anyone can do.
5. **Where they differ.** With state constraints, or plants where an early move prevents a later violation, MPC's planned inputs differ from clipped LQR.
6. **A more unstable plant.** If $a > 1 + b \times 2/|x|$, no input sequence could recover from large states: the limits define a region of attraction, which MPC makes explicit.

**Answer:** LQR commands −6.8; clipped to −2, the state goes from 4 to 3.4 to 2.74 and recovers only slowly.
:::
:::

::: example
## An MPC for a three-phase converter has 2 inputs, a horizon of 10 steps and runs at 20 kHz. How many decision variables does each QP have, and how long does the solver get?

::: solution
1. **Decision variables.**
   $$2 \times 10 = 20$$
   per solve.
2. **Time per sample.**
   $$1/20\ \text{kHz} = 50\ \mu\text{s}$$
   minus the time to measure and apply: perhaps 30 µs for the solver.
3. **Is that enough?** A dense QP of that size takes a few thousand floating-point operations per iteration and converges in tens of iterations on a microcontroller or an FPGA, which is why short horizons are common in power electronics.

**Answer:** 20 decision variables, with perhaps 30 µs of each 50 µs sample for the solver.
:::
:::

::: check
given: a = 0.9 | 1.1 | 1.5; b = 0.5 | 2; q = 1 | 2; r = 0.1 | 1
answer: q*a*b/(r + q*b^2)
tolerance: 0.5%

## A one-step MPC for $x_{k+1} = \given{a}x_k + \given{b}u_k$ minimizes $\given{q}x_{k+1}^2 + \given{r}u_k^2$. What feedback gain $K$ (with $u = -Kx$) does it apply?

::: right
Right. $K = qab/(r + qb^2)$ = {answer}.
:::

::: misses
- [a/b] That's deadbeat control, ignoring the input's cost.
- [q*a*b/(r + q*b)] The input enters $x_{k+1}$ times $b$, so its effect on the cost is $qb^2$.
- [any] Not yet. Set the derivative of $q(ax + bu)^2 + ru^2$ to zero.
:::
:::

::: check
given: a = 1.1 | 1.5 | 2; b = 0.5 | 2; q = 1 | 2; r = 0.1 | 1
answer: a - b*q*a*b/(r + q*b^2)
tolerance: 0.5%

## With that one-step MPC gain, where is the closed-loop pole of $x_{k+1} = \given{a}x_k + \given{b}u_k$ (weights $q$ = {q}, $r$ = {r})?

::: right
Right. $a - bK$ = {answer}.
:::

::: misses
- [a + b*q*a*b/(r + q*b^2)] With $u = -Kx$ the pole is $a - bK$.
- [any] Not yet. Substitute $u = -Kx$ into the model.
:::
:::

::: check
given: m = 2 | 4; N = 5 | 10 | 30
answer: m*N
tolerance: 0.5%

## An MPC has {m} inputs and a horizon of {N} steps. How many decision variables does each optimization have?

::: right
Right: {answer}, one per input per step.
:::

::: misses
- [m + N] Each step has its own value for every input.
- [N] Multiply by the number of inputs.
- [any] Not yet. Inputs × horizon.
:::
:::

::: check
given: a = 1.05 | 1.2 | 1.4; b = 0.5 | 2; um = 1 | 2
answer: b*um/(a - 1)
tolerance: 0.5%

## An unstable plant $x_{k+1} = \given{a}x_k + \given{b}u_k$ has its input limited to $|u| \le$ {um}. Beyond what $|x|$ can no input sequence bring it back?

::: right
Right. Recovery needs $|ax + bu| < |x|$ with $|u| = u_{max}$, so $|x| < bu_{max}/(a - 1)$ = {answer}.
:::

::: misses
- [b*um/a] Compare the drift $(a - 1)x$ with the input's reach $bu_{max}$.
- [um/(a - 1)] Include $b$: the input moves the state by $bu$.
- [any] Not yet. Solve $ax - bu_{max} = x$.
:::
:::

::: check
kind: choice

## Why does MPC apply only the first input of its optimized sequence instead of the whole sequence?

- [x] Re-solving at every sample with the newest measurement corrects for disturbances and model errors that the open-loop plan can't anticipate: it makes the controller a feedback law
- [ ] The later inputs are always zero
- [ ] Applying the whole sequence would violate constraints
- [ ] The solver only computes one input

::: right
Right. The receding horizon closes the loop: each new measurement updates the plan.
:::

::: misses
- [2] They're usually nonzero; they're simply replanned.
- [3] The plan satisfies the constraints; the issue is that the world doesn't follow the plan exactly.
- [4] It computes the whole sequence, then discards all but the first.
:::
:::

::: check
kind: python
given: a = 1.1 | 1.3; b = 0.5 | 1; r = 0.05 | 0.5

## Compute MPC gains by the backward Riccati recursion for $x_{k+1} = \given{a}x + \given{b}u$, $q$ = 1, terminal weight $P_N = q$, input weight `r` = {r}. Write `k0(N)`, the first-step gain for horizon `N`. Set `K_lqr` (iterate the recursion 10 000 times), `N_match`, the smallest horizon with $|K_0 - K_{lqr}| < 10^{-6}$, and `K1 = k0(1)`.

```python starter
def k0(N):
    return a / b
K_lqr = K1 = k0(1)
N_match = 1
```

```python solution
q = 1.0
def k0(N):
    P = q
    K = 0.0
    for _ in range(N):
        K = a * b * P / (r + b * b * P)
        P = q + a * a * P - (a * b * P) ** 2 / (r + b * b * P)
    return K
P = q
for _ in range(10000):
    P = q + a * a * P - (a * b * P) ** 2 / (r + b * b * P)
K_lqr = a * b * P / (r + b * b * P)
N_match = next(N for N in range(1, 1000) if abs(k0(N) - K_lqr) < 1e-6)
K1 = k0(1)
```

```python tests
q = 1.0
def kk(N):
    P, K = q, 0.0
    for _ in range(N):
        K = a * b * P / (r + b * b * P); P = q + a * a * P - (a * b * P) ** 2 / (r + b * b * P)
    return K
P = q
for _ in range(10000): P = q + a * a * P - (a * b * P) ** 2 / (r + b * b * P)
KL = a * b * P / (r + b * b * P)
assert abs(K1 - q * a * b / (r + q * b * b)) < 1e-12, "With N = 1 the gain is qab/(r + qb²)."
assert abs(K_lqr - KL) < 1e-9, f"The LQR gain is {KL:.6f}."
assert N_match == next(N for N in range(1, 1000) if abs(kk(N) - KL) < 1e-6), "N_match is the first horizon within 1e-6 of LQR."
```

::: right
Right. The horizon at which MPC matches LQR is short when control is cheap and longer when $r$ is large; with a terminal weight equal to the LQR solution it matches at any horizon.
:::
:::

::: explain
## A building's chiller plant is controlled by MPC with a 24-hour horizon and electricity prices that change by the hour. Explain why MPC can save money where a PID loop on each chiller can't.

::: model
A PID loop reacts only to the current error: it holds each zone's temperature at its setpoint and runs chillers whenever cooling is needed, whatever the electricity costs at that hour. MPC uses a model of the building's thermal mass, a forecast of weather and occupancy, and the price schedule to plan the whole day's cooling as an optimization: it can precool the building in the cheap early hours, letting temperatures drift up within their allowed band during expensive afternoon peaks, while respecting every constraint on comfort and equipment capacity. It applies the first hour's plan, then replans with new measurements and forecasts, which corrects for model and forecast errors. The savings come from planning with knowledge of the future and of the limits, which a feedback loop with fixed gains doesn't have.
:::
:::

::: practice

::: check
given: a = 0.8 | 1.2; b = 0.5 | 2; r = 0.2 | 1
answer: a*b/(r + b^2)
tolerance: 0.5%

## What is the one-step MPC gain for $x^+ = \given{a}x + \given{b}u$ with weights 1 and {r}?

::: misses
- [a/b] That's deadbeat; include the input weight.
- [any] $ab/(r + b^2)$.
:::
:::

::: check
given: m = 3 | 6; N = 8 | 20
answer: m*N
tolerance: 0.5%

## How many variables does an MPC with {m} inputs and an {N}-step horizon optimize?

::: misses
- [m + N] One per input per step.
- [any] $mN$.
:::
:::
:::
