Optimal Control & Model Predictive Control
LQR, trajectory optimization and replanning at every step.
Long before deep reinforcement learning, engineers steered aircraft, rockets and refineries with models and a simple principle: plan, act, measure, plan again. This lesson builds the two workhorses of optimal control. The linear–quadratic regulator's optimal policy is a matrix computed by a backward recursion; solved by hand for a one-dimensional system, it produces the golden ratio. Model predictive control re-solves a planning problem at every step. You'll see why short horizons are myopic, why replanning survives a wrong model, and why sampling planners struggle as plans get longer.
What you’ll learn
- Translate between RL and control vocabulary, and set up a discrete-time control problem with dynamics, stage cost and horizon.
- Derive the finite-horizon LQR solution, a quadratic cost-to-go with linear feedback given by the Riccati recursion, and compute it for a scalar system.
- Write the MPC loop, and explain why replanning from measured states tolerates model errors and why short horizons without a terminal cost are myopic.
- Implement shooting planners, random shooting and the cross-entropy method, and explain why random shooting degrades as the horizon grows.
- Describe where MPC is used in practice and what changes when the model is learned.
Control in the language of RL
Optimal control studies the problem RL studies, from the other side: the model is usually known, costs replace rewards, and the state is a vector of real numbers. In discrete time, a state and a control produce the next state , and the controller minimizes over a horizon , or the infinite sum.
The optimal cost-to-go satisfies the dynamic-programming recursion : the Bellman optimality equation for a deterministic model, with in place of .
| Reinforcement learning | Control |
|---|---|
| State | State |
| Action | Control, or input, |
| Reward | Cost |
| Transition probabilities | Dynamics , often plus noise |
| Policy | Controller, or feedback law |
| Optimal value | Optimal cost-to-go (with the sign flipped) |
| Planning with a model | Trajectory optimization; model predictive control |
In the cart above, a force applied at step first changes which state variable, and when?
- The position, at step
- The velocity at step ; the position only from step
- Both, at step
- Neither, until the force is removed
Show the answer
B. The velocity at step ; the position only from step
and : the force enters the velocity first, and the position responds one step later, through the velocity. This lag will matter when we plan only a step or two ahead.
LQR: quadratic costs stay quadratic
When the dynamics are linear, , and the cost is quadratic, with and , dynamic programming can be carried out exactly. The linear–quadratic regulator (LQR) rests on one fact: if the cost-to-go one step later is a quadratic form, so is the cost-to-go now.
Suppose with , which holds at with . The cost of applying in state is a quadratic function of :
Its gradient in is , and , so the unique minimizer is a linear function of the state:
Substitute it back. The terms in combine, and the cost-to-go is again quadratic, with the matrix given by the Riccati recursion:
Run it backward from . The optimal controller is linear feedback with time-varying gains , and the gains do not depend on the initial state, so they are computed before the first step. For long horizons settles to a fixed point , the solution of the algebraic Riccati equation, and the controller becomes a constant gain . When that happens, and the proof, are in The Linear–Quadratic Regulator.
Iterate the scalar recursion from . What is after three iterations?
Show the answer
1.6
, and the fourth iterate is : the iterates approach fast. Each iteration adds one step of horizon, so this is value iteration on quadratic cost-to-go functions.
import numpy as np
def lqr_gains(A, B, Q, R, Qf, H):
"""Finite-horizon LQR by the Riccati recursion: gains K_0..K_{H-1}, cost-to-go matrices P_0..P_H."""
P = [None] * (H + 1)
K = [None] * H
P[H] = Qf
for t in reversed(range(H)):
M = R + B.T @ P[t + 1] @ B
K[t] = np.linalg.solve(M, B.T @ P[t + 1] @ A) # K_t = M^{-1} B^T P_{t+1} A
P[t] = Q + A.T @ P[t + 1] @ A - A.T @ P[t + 1] @ B @ K[t]
return K, P
dt = 0.1
A = np.array([[1.0, dt], [0.0, 1.0]])
B = np.array([[0.0], [dt]])
K, P = lqr_gains(A, B, Q=np.eye(2), R=np.array([[1.0]]), Qf=np.zeros((2, 2)), H=600)
x0 = np.array([2.0, 0.0])
print(K[0], x0 @ P[0] @ x0) # first-step gain and optimal cost of a 600-step problemThe recursion for the cart with . Six hundred steps are enough for the first gain to equal, to three decimals, the infinite-horizon gain , and for the optimal cost from to be : the numbers the widget below shows.
LQR on the cart
The control cost sets the price of force against the price of being away from the target. The widget computes LQR's gain for the cart from the Riccati equation and simulates the result. Before you run it, use the cost-to-go matrix.
For the cost-to-go matrix is . What is the optimal total cost from the start , 2 m out and already moving toward the target at 1 m/s?
Show the answer
48.7
. The negative cross term rewards already moving the right way: from rest at the cost is 73.4. Drag the start to in the widget and check.
MPC: plan, apply the first control, replan
Most problems are not linear–quadratic: the dynamics are nonlinear, the controls are limited, the model is learned. Model predictive control (MPC) handles them by solving a finite-horizon problem online, from the current measured state, at every step:
MPC(model f̂, stage cost c, terminal cost c_H, horizon H):
at every time step t:
x ← measure the current state
plan u_0 … u_{H−1} minimizing Σ_k c(x_k, u_k) + c_H(x_H)
subject to x_0 = x, x_{k+1} = f̂(x_k, u_k) (and any limits on x and u)
apply u_0 only; keep u_1 … u_{H−1} to warm-start the next planThe receding horizon: the plan always looks steps ahead of the present, and only its first control is ever executed.
Two consequences follow. Myopia. With the planner sees only steps of cost. In the scalar example the first gain of an -step plan is , with from Riccati steps: for , for , for , approaching . With the controller never acts, since the only cost it can see is the control's own. On the cart it is worse: a force moves the position only two steps later, so a plan of two steps or fewer sees no benefit in moving a cart at rest. For linear dynamics and quadratic cost, MPC with is simply the first gain of an -step Riccati recursion, a fixed linear feedback that approaches LQR as grows.
Robustness. Every plan starts from a measured state, so whatever the model got wrong shows up in the next measurement and is taken into account by the next plan.
Planning by sampling: random shooting and CEM
For nonlinear or learned models the -step problem is solved numerically. Shooting methods treat the control sequence as the only unknown and obtain the states by simulating the model. Gradient-based shooting differentiates the simulated cost; the Fixed Point lesson derives the backward passes of iLQR and DDP. Sampling-based shooting needs only the ability to simulate. Random shooting samples control sequences at random, simulates each, and executes the first control of the cheapest. The cross-entropy method (CEM) does better by learning where to sample: it draws sequences from a Gaussian, keeps the cheapest few (the elites), refits the Gaussian to them, and repeats.
import numpy as np
def cem_plan(model, cost, x0, mu, sigma0=1.0, n=64, n_elite=8, iters=5, rng=None):
"""Plan H controls from state x0. model(x, u) -> next state; cost(x, u) -> float; mu: (H, m)."""
rng = rng or np.random.default_rng()
sigma = np.full(mu.shape, sigma0)
for _ in range(iters):
U = mu + sigma * rng.standard_normal((n, *mu.shape)) # n candidate plans
U[0] = mu # always keep the current mean
J = np.zeros(n)
for i in range(n): # simulate every plan in the model
x = x0
for t in range(mu.shape[0]):
J[i] += cost(x, U[i, t])
x = model(x, U[i, t])
elite = U[np.argsort(J)[:n_elite]] # the cheapest plans
mu, sigma = elite.mean(axis=0), elite.std(axis=0) + 1e-3
return mu # apply mu[0]; at the next step, warm-start with mu shifted by oneA minimal CEM planner. The widget's CEM uses the same sizes, 5 rounds of 64 plans with 8 elites (320 model rollouts per real step), warm-started from the previous plan, with forces limited to a fixed range and the spread kept above a floor; without a floor the spread can collapse before the plan is good.
Why does random shooting with a fixed budget of 1,000 plans get worse on the cart as the horizon grows from 10 to 60, even though its model is exact?
- The model's predictions compound errors over long horizons
- Longer horizons make the planner more myopic
- The planning problem stops being convex at long horizons
- A plan is a point in an -dimensional space, and a fixed number of random points covers a 60-dimensional space far more thinly than a 10-dimensional one
Show the answer
D. A plan is a point in an -dimensional space, and a fixed number of random points covers a 60-dimensional space far more thinly than a 10-dimensional one
If each of the controls must land within a fraction of its range around the best value, a uniform random plan succeeds with probability of roughly : for and , and far less for . CEM escapes by moving its sampling distribution toward good plans, round by round.
MPC in practice, and the Fixed Point lessons
MPC's main practical advantage over a fixed feedback law is that constraints enter the plan directly: actuator limits, safety margins, temperatures that must stay in range. With a linear model and quadratic cost, each step solves a convex quadratic program. That is why MPC, which grew up in refineries and chemical plants from the late 1970s, became the standard advanced control method of the process industries (Qin & Badgwell, 2003). Legged robots use it: the MIT Cheetah 3 ran dynamic gaits with convex MPC on a simplified model (Di Carlo et al., 2018). So do vehicles: sampling-based MPPI drove a scale car aggressively around a dirt track (Williams et al., 2016). In model-based RL the model is learned: PETS plans with CEM through an ensemble of networks (Uncertainty-Aware Models: PILCO & PETS), and TD-MPC plans in a learned latent space with a learned value at the horizon.
| Planner | Needs | Strength | Weakness |
|---|---|---|---|
| LQR | Linear model, quadratic cost | Exact; computed once, offline | Only linear–quadratic problems; no constraints |
| MPC with an exact solver | A tractable (for example convex) -step problem | Constraints; feedback from every measurement | An optimization at every step; myopic without a terminal cost |
| iLQR, DDP | Derivatives of the model and cost | Fast local convergence | Local minima; needs smooth dynamics |
| CEM, MPPI | Only the ability to simulate | Derivative-free; parallel | Samples needed grow with |
| Random shooting | Only the ability to simulate | Trivial to implement | Fails at long horizons |
Key takeaways
- Control is RL with costs, continuous states and usually known models: the cost-to-go satisfies the same dynamic-programming recursion as the value function.
- For linear dynamics and quadratic cost the cost-to-go stays quadratic; the Riccati recursion computes it backward, and the optimal policy is linear feedback , computed in advance. For with unit costs the gain tends to .
- MPC re-solves an -step problem from every measured state and applies only the first control. Replanning turns a model error into a slower correction instead of a permanent offset, but without a terminal cost short horizons are myopic: on the cart, never moves it.
- Sampling planners need only a simulator. Random shooting degrades as grows because plans live in an -dimensional space, while CEM refits its sampling distribution to elite plans and stays near the exact optimum.
- MPC's practical strength is constraints, which is why it runs refineries and legged robots; with learned models it powers agents such as PETS and TD-MPC.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
What form does the optimal controller of a finite-horizon LQR problem take?
- A nonlinear function of the state that must be optimized online
- A fixed control sequence chosen from the initial state
- Linear state feedback , with gains computed backward in advance and independent of the initial state
- Bang-bang control at the force limits
Show the answer
C. Linear state feedback , with gains computed backward in advance and independent of the initial state
Dynamic programming keeps the cost-to-go quadratic, and minimizing a quadratic in gives a linear function of . The Riccati recursion computes every offline; linearity is a theorem, not an assumption.
MPC with horizon and zero terminal cost controls with cost . What does it do?
- Applies forever: in a one-step problem a control can only add cost
- Applies the LQR gain 0.618
- Applies and reaches the target in one step
- Oscillates around the target
Show the answer
A. Applies forever: in a one-step problem a control can only add cost
The one-step problem minimizes ; is given and the next state's cost is not counted, so . Each extra step of horizon raises the gain: for , for , toward .
A model believes control is twice as effective as it really is (). Starting from , compare executing its one-step plan open loop with replanning it every step.
- Both reach the target; open loop is faster
- Open loop stops halfway and stays there; replanning halves the error every step and converges
- Both diverge
- Replanning overshoots and oscillates forever
Show the answer
B. Open loop stops halfway and stays there; replanning halves the error every step and converges
The plan achieves only half the intended correction. Open loop, nothing corrects that: the system rests at . Replanned, each step measures the remaining error and repeats the half correction, so . Feedback turns a model error into a slower convergence instead of a permanent offset.
What does the cross-entropy method do that random shooting does not?
- It uses gradients of the model
- It plans over a longer horizon
- It needs no model
- It refits its sampling distribution to the best plans and samples again, concentrating the search where good plans are
Show the answer
D. It refits its sampling distribution to the best plans and samples again, concentrating the search where good plans are
Both methods only simulate candidate plans. Random shooting samples once, uniformly; CEM refits a Gaussian to the elite plans over several rounds, so later samples land near good plans, which is why it stays close to the exact optimum where random shooting fails.
A reactor's temperature must stay within strict limits, and its model is nonlinear. Why do engineers use MPC rather than a fixed LQR gain?
- MPC can enforce the limits inside every plan and re-optimize as conditions change, while a fixed gain handles neither constraints nor nonlinearity
- MPC needs no model
- LQR cannot be computed for chemical processes
- MPC needs less computation
Show the answer
A. MPC can enforce the limits inside every plan and re-optimize as conditions change, while a fixed gain handles neither constraints nor nonlinearity
Constraints are MPC's main practical advantage: they enter each finite-horizon optimization directly. A fixed gain is optimal only for an unconstrained linear–quadratic problem.
Go deeper
- The Linear–Quadratic Regulator · The Riccati equation, certainty equivalence and LQR as a testbed for RL.
- Trajectory Optimization: iLQR, DDP & Sampling Planners · Iterative linearization, differential dynamic programming, CEM and MPPI.
- Planning with Learned Values: TD-MPC · Short-horizon planning with a learned value at the end.
Further reading
- D. P. Bertsekas, Dynamic Programming and Optimal Control, Vol. I (Athena Scientific, 4th ed., 2017).
- J. B. Rawlings, D. Q. Mayne & M. M. Diehl, Model Predictive Control: Theory, Computation, and Design (Nob Hill Publishing, 2nd ed., 2017).
- S. J. Qin & T. A. Badgwell, "A survey of industrial model predictive control technology," Control Engineering Practice 11, 733–764 (2003).
- P.-T. de Boer, D. P. Kroese, S. Mannor & R. Y. Rubinstein, "A tutorial on the cross-entropy method," Annals of Operations Research 134, 19–67 (2005).