14.6 Optimal Control, LQR, and Model Predictive Control
Dynamic programming (Section 14.2) solved the slippery lake by sweeping a table of sixteen state values until Bellman's optimality equation held at every cell, and every method since, from Q-learning to behavior cloning, has kept one table row per state. What happens when the state is a continuous vector of positions, angles, and velocities, as in the vehicle of Section 14.1, and the action is a continuous control that acts through known dynamics ? Grids do not scale: partitioning each of coordinates into bins produces cells, Bellman's curse of dimensionality (Bellman, 1957).
Control theory solved this problem in continuous state and action spaces long before deep reinforcement learning, starting from an algebraic observation due to Kalman (1960). When the transition dynamics are linear in the state and control, and the one-step cost is quadratic in both, Bellman's backward dynamic programming preserves the quadratic form of the value function at every step. Instead of a table of entries, the exact value function is parameterized by a symmetric matrix with independent numbers. The Bellman backup reduces to the Riccati recursion, and the optimal policy is a linear state-feedback law : the Linear-Quadratic Regulator (LQR) (Kalman, 1960; Anderson and Moore, 2007).
Most physical systems are nonlinear, and actuators saturate. Two ideas extend LQR to nonlinear continuous control and form the backbone of modern trajectory optimization and robotics (Tedrake, 2023; Bertsekas, 2025). First, iterative LQR (iLQR) (Li and Todorov, 2004) repeatedly linearizes the nonlinear dynamics and quadratizes the cost around a candidate trajectory, solving a time-varying LQR problem in the backward pass to improve the trajectory in the forward pass. Second, Model Predictive Control (MPC) (Rawlings et al., 2017) turns finite-horizon trajectory optimization into a closed-loop policy: at every step , it re-solves the control problem over a receding lookahead horizon from the current measured state , applies only the first control , and re-plans at step . This section develops LQR, iLQR, and receding-horizon MPC, showing where local linear feedback suffices, where nonlinear energy pumping is required, and how MPC sets the stage for planning with learned neural dynamics in Section 15.6.
14.6.1 Linear-Quadratic Regulation#
14.6.1.1 State-Space Dynamics and Quadratic Costs#
In control notation, a continuous state is written and an action (or control input) is written . Whereas reinforcement learning maximizes a reward , optimal control minimizes a stage cost . A discrete-time linear system evolves as
where is the state-transition matrix and is the control-input matrix (the discrete-time counterpart of the linear ODEs in Section 26.1). The target state is the origin . Over a finite horizon of steps, we minimize the total quadratic cost
where and are symmetric positive-semidefinite state-cost matrices, and is a symmetric positive-definite control-cost matrix. Requiring ensures that large control efforts always carry a positive penalty, so the one-step minimization over has a unique finite solution.
14.6.1.2 Exact Continuous Dynamic Programming and the Riccati Recursion#
Let be the optimal cost-to-go from state at step . At the terminal step , no control remains and with . Moving backward from to , the finite-horizon form of Bellman's optimality equation (Section 14.2) states that
Suppose by backward induction that for a symmetric positive-semidefinite matrix . Substituting expands the bracketed action-value function into a strictly convex quadratic in :
Setting the gradient with respect to to zero,
yields the unique optimal control in closed form:
Substituting back into confirms that remains purely quadratic, where obeys the backward discrete-time Riccati recursion:
The recursion runs backward once, from , and needs no state to do so. Running the system is then cheap: at each step the controller measures and multiplies it by a stored gain, as Figure 14.6.1 shows.
LQR in closed loop. The controller multiplies the measured state by the gain , the system (the plant, in control terms) responds with the next state, and that state is measured in turn. All gains are computed by the backward Riccati recursion before the loop starts.
Three properties of (14.6.5) and (14.6.6) deserve emphasis:
- No curse of dimensionality: Each Bellman backup replaces a minimization over an infinite action space and all states by matrix operations on .
- Linear feedback gain: The optimal policy is linear in the state, and the gain matrix depends only on , not on the initial state .
- Certainty equivalence: Even if zero-mean independent noise with covariance is added to the transition (), the cross term vanishes, adding only the constant to the value function while leaving the optimal feedback matrix unchanged (exercise 2).
As the horizon (under standard controllability and observability conditions), converges to a stationary solution of the Discrete Algebraic Riccati Equation (DARE), and the time-invariant controller stabilizes the closed-loop dynamics so that every eigenvalue of lies strictly inside the unit circle, .
14.6.1.3 The Double Integrator#
We test riccati_lqr on the vehicle from the state-augmentation example of Section 14.1: a unit mass moving along a line with state (position and velocity), control (acceleration), and time step . By Newton's laws, and . We penalize position and velocity deviations with and sweep the control-effort weight in :
def riccati_lqr(A, B, Q, R, H=100):
"""Backward Riccati recursion for horizon H; returns (Ps, Ks) from t=0..H."""
P = Q.copy()
Ps, Ks = [P], []
for _ in range(H):
BtP = B.T @ P
K = np.linalg.solve(R + BtP @ B, BtP @ A)
P = Q + A.T @ P @ (A - B @ K)
Ks.append(K)
Ps.append(P)
return Ps[::-1], Ks[::-1]
dt = 0.1
A_di = np.array([[1.0, dt], [0.0, 1.0]])
B_di = np.array([[0.5 * dt**2], [dt]])
Q_di = np.diag([1.0, 0.1])
for ru in (0.01, 0.10, 1.00):
Ps, Ks = riccati_lqr(A_di, B_di, Q_di, np.array([[ru]]), H=100)
K_inf, P_inf = Ks[0][0], Ps[0]
rho = np.abs(np.linalg.eigvals(A_di - B_di @ Ks[0])).max()
print(f'R={ru:4.2f} K_inf=[{K_inf[0]:5.3f}, {K_inf[1]:5.3f}] '
f'P_00={P_inf[0, 0]:5.2f} rho(A - B K)={rho:.3f}')R=0.01 K_inf=[7.613, 4.585] P_00= 6.02 rho(A - B K)=0.761
R=0.10 K_inf=[2.762, 2.508] P_00= 9.08 rho(A - B K)=0.874
R=1.00 K_inf=[0.930, 1.395] P_00=15.00 rho(A - B K)=0.930
We can also plot the closed-loop position trajectories starting from under the three control-effort penalties:
trajs, steps_di = [], np.arange(51) * dt
for ru in (0.01, 0.10, 1.00):
_, Ks = riccati_lqr(A_di, B_di, Q_di, np.array([[ru]]), H=100)
x, xs_di = np.array([1.0, 0.0]), [1.0]
for _ in range(50):
x = (A_di - B_di @ Ks[0]) @ x
xs_di.append(x[0])
trajs.append(xs_di)
d2l.plot(steps_di, trajs, 'time (s)', 'position $p_t$',
legend=['R = 0.01', 'R = 0.10', 'R = 1.00'], figsize=(5, 3))Look at the two components of the stationary feedback law : dynamic programming has automatically derived a proportional-derivative (PD) controller, pushing back against the position error with gain and damping the velocity with gain . When control effort is cheap (), LQR chooses aggressive gains that contract the state norm at rate per step; when control effort is expensive (), it uses gentle accelerations with contraction rate and a higher cumulative cost ( vs. ).
14.6.2 Linearizing a Nonlinear System Around an Equilibrium#
14.6.2.1 Analytical Linearization of Pendulum-v1#
Now consider a physical benchmark that will accompany us through the rest of this chapter and Chapter 15: the inverted pendulum (Pendulum-v1). A rigid rod of mass and length is pivoted at one end under gravity and driven by a bounded motor torque . Its continuous state is , where is the angle measured from the upright vertical ( upright, hanging straight down) and is the angular velocity. Because the peak gravitational torque at the horizontal () is , the motor is underactuated: it cannot lift the rod directly from the bottom to the top in a single push. Over one simulator step of , the semi-implicit Euler transition is
with angular velocity clipped to . Each step incurs the quadratic stage cost (with wrapped to , corresponding to and ), or equivalently emits the reward . Standard benchmark episodes run for steps (): an uncontrolled pendulum scores around to , whereas a controller that swings the rod up and balances it upright averages about or better over the benchmark's random starting states. Here we plan directly with the known equations of motion (14.6.7); Section 14.9, Section 15.5, and Section 15.6 will return to this exact pendulum benchmark when the agent must act or learn a dynamics model without knowing the physics.
The upright posture with zero torque is a fixed point, . Near any reference pair , a first-order Taylor expansion approximates the nonlinear transition by a local linear model in the deviations and :
Differentiating (14.6.7) with respect to and yields and :
def pendulum_jacobians(th, dt=0.05, g=10.0):
"""Exact Jacobians (A, B) of Pendulum-v1 at angle th."""
dthdot_dth = 1.5 * g * np.cos(th) * dt
dthdot_du = 3.0 * dt
A = np.array([[1.0 + dthdot_dth * dt, dt], [dthdot_dth, 1.0]])
B = np.array([[dthdot_du * dt], [dthdot_du]])
return A, B
A_p, B_p = pendulum_jacobians(0.0)
Q_p, R_p = np.diag([1.0, 0.1]), np.array([[0.001]])
Ps_p, Ks_p = riccati_lqr(A_p, B_p, Q_p, R_p, H=200)
K_lqr = Ks_p[0][0]
eigs_open = np.linalg.eigvals(A_p).real
eigs_closed = np.linalg.eigvals(A_p - B_p @ Ks_p[0]).real
print(f'A at upright:\n{A_p}')
print(f'open-loop eigenvalues: {eigs_open[0]:.4f}, {eigs_open[1]:.4f}')
print(f'LQR gain K_inf: [{K_lqr[0]:.3f}, {K_lqr[1]:.3f}]')
print(f'closed-loop eigenvalues: {eigs_closed[0]:.4f}, {eigs_closed[1]:.4f}')A at upright:
[[1.0375 0.05 ]
[0.75 1. ]]
open-loop eigenvalues: 1.2133, 0.8242
LQR gain K_inf: [19.693, 5.263]
closed-loop eigenvalues: 0.8537, 0.2467
At the upright fixed point, the open-loop Jacobian has an unstable eigenvalue : any small tilt grows exponentially at over per step, as seen in the phase portrait of Section 26.1. Solving the Riccati recursion with Pendulum-v1's cost matrices and produces the feedback gain , which pulls both closed-loop eigenvalues inside the unit circle ().
14.6.2.2 Torque Saturation and the Basin of Attraction#
How far from the top can this linear controller catch the pendulum when the motor torque is clipped to ? The gravitational torque pulling the pendulum down is , whereas the motor supplies at most . Once (), gravity exceeds the peak holding torque of the motor. We test the clipped LQR policy on the full nonlinear pendulum from five starting angles at rest:
def wrap(th):
return ((th + np.pi) % (2 * np.pi)) - np.pi
def pendulum_step(x, u, dt=0.05, g=10.0):
"""One step of nonlinear Pendulum-v1 dynamics in (theta, thetadot)."""
th, thdot = x
u_c = float(np.clip(u, -2.0, 2.0))
newthdot = float(np.clip(thdot + (1.5 * g * np.sin(th) + 3.0 * u_c) * dt,
-8.0, 8.0))
newth = th + newthdot * dt
cost = wrap(th)**2 + 0.1 * thdot**2 + 0.001 * u_c**2
return np.array([newth, newthdot]), cost
for th0 in (0.20, 0.40, 0.50, 0.60, np.pi):
x, total_cost = np.array([th0, 0.0]), 0.0
for _ in range(200):
u = -(K_lqr[0] * wrap(x[0]) + K_lqr[1] * x[1])
x, c = pendulum_step(x, u)
total_cost += c
print(f'th0={th0:4.2f} rad: 200-step return={-total_cost:8.2f}, '
f'final theta={wrap(x[0]):+6.3f} rad')th0=0.20 rad: 200-step return= -0.32, final theta=+0.000 rad
th0=0.40 rad: 200-step return= -2.97, final theta=+0.000 rad
th0=0.50 rad: 200-step return= -770.94, final theta=+2.592 rad
th0=0.60 rad: 200-step return= -546.37, final theta=+0.001 rad
th0=3.14 rad: 200-step return=-1471.86, final theta=-2.249 rad
Inside the static holding threshold ( and ), linear LQR drives the pendulum straight to upright () with near-zero cost (returns and ). Just outside that threshold (), full negative torque cannot arrest the fall, and the rod is still swinging through the bottom after 200 steps (return ). Beyond the threshold the outcome is no longer monotone in . From the rod falls just the same, but after a few more swings it happens to come up slowly enough for the clipped controller to catch it (return ). This is luck, not control. From the bottom () the linear controller earns and never reaches the top. Because the motor is underactuated (), swinging up from requires energy pumping: pushing in one direction, reversing torque as the pendulum swings back through the bottom to build kinetic and potential energy, and only switching to upright stabilization once the rod climbs into the top catch basin.
14.6.3 Nonlinear Trajectory Optimization via Iterative LQR#
14.6.3.1 Linearizing Along a Trajectory#
A single linearization at knows nothing about the nonlinear sin curvature along a swing from . Iterative Linear-Quadratic Regulation (iLQR) (Li and Todorov, 2004), a Gauss–Newton variant of Differential Dynamic Programming (Mayne, 1966), instead linearizes around an entire nominal trajectory.
To enforce the torque bound smoothly without hard-clipping kinks, we parameterize via an unconstrained control variable . Given any nominal control sequence and its forward rollout under the true nonlinear dynamics (without the velocity clip, which the swing-up below never reaches), each iteration of iLQR performs two passes:
- Backward Riccati pass along : At each step , compute the local Jacobians and , and form a second-order Taylor approximation of the action-value perturbation from the stage cost gradients , Hessians , and the next step's value gradient and Hessian :
where is a Levenberg–Marquardt damping term. Minimizing over gives an open-loop feedforward step and a local linear feedback gain . 2. Forward rollout with backtracking line search: Because the linear model is only accurate near , we roll out the true nonlinear dynamics with step size ,
and accept the first that decreases the true nonlinear trajectory cost.
One design detail of the trajectory cost is instructive. To pump energy from , the pendulum must first swing to on the opposite side before whipping back toward . If we place a heavy quadratic penalty on every early step , a local gradient method refuses to swing away from because increases during the back-swing. Weighting the state cost lightly during the swing phase ( for ) and heavily during the final capture window ( for ) lets iLQR use the early steps to pump energy and the final steps to lock the rod at :
def step_tanh(x, v, dt=0.05, g=10.0):
"""Nonlinear step and analytical Jacobians (A_t, B_t) for u = 2 tanh(v)."""
th, thdot = x[0], x[1]
th_v = np.tanh(v)
u = 2.0 * th_v
du_dv = 2.0 * (1.0 - th_v**2)
newthdot = thdot + (1.5 * g * np.sin(th) + 3.0 * u) * dt
newth = th + newthdot * dt
dthdot_dth = 1.5 * g * np.cos(th) * dt
dthdot_dv = 3.0 * dt * du_dv
A = np.array([[1.0 + dthdot_dth * dt, dt], [dthdot_dth, 1.0]])
B = np.array([[dthdot_dv * dt], [dthdot_dv]])
return np.array([newth, newthdot]), A, B, u
def ilqr_swingup(x0, H=80, iters=35, q_run=0.02, r_v=0.02, q_T=100.0,
vs_init=None):
"""iLQR trajectory optimization from x0 over horizon H."""
vs = (np.array(vs_init, dtype=float) if vs_init is not None
else np.array([0.2 if t < 15 else 0.0 for t in range(H)]))
Q_base = np.diag([1.0, 0.1])
for _ in range(iters):
xs, As, Bs, us, cost = [np.array(x0, dtype=float)], [], [], [], 0.0
for t in range(H):
x_next, A, B, u = step_tanh(xs[-1], vs[t])
As.append(A); Bs.append(B); us.append(u)
w = q_T if t >= H - 20 else q_run
cost += w * (xs[-1] @ Q_base @ xs[-1]) + r_v * vs[t]**2
xs.append(x_next)
cost += q_T * (xs[-1] @ Q_base @ xs[-1])
Vx = 2.0 * q_T * (Q_base @ xs[-1])
Vxx = 2.0 * q_T * Q_base
ks, Ks = np.zeros(H), np.zeros((H, 2))
for t in range(H - 1, -1, -1):
w = q_T if t >= H - 20 else q_run
A, B = As[t], Bs[t]
Qx = 2.0 * w * (Q_base @ xs[t]) + A.T @ Vx
Qv = 2.0 * r_v * vs[t] + (B.T @ Vx).item()
Qxx = 2.0 * w * Q_base + A.T @ Vxx @ A
Qvv = 2.0 * r_v + 1e-2 + (B.T @ Vxx @ B).item()
Qvx = (B.T @ Vxx @ A).ravel()
ks[t], Ks[t] = -Qv / Qvv, -Qvx / Qvv
Vx = Qx + Qvx * ks[t]
Vxx = Qxx + np.outer(Qvx, Ks[t])
for alpha in (1.0, 0.5, 0.25, 0.1, 0.03):
x_new, vs_new, c_new = np.array(x0, dtype=float), np.zeros(H), 0.0
for t in range(H):
v_t = vs[t] + alpha * ks[t] + Ks[t] @ (x_new - xs[t])
vs_new[t] = v_t
w = q_T if t >= H - 20 else q_run
c_new += w * (x_new @ Q_base @ x_new) + r_v * v_t**2
x_new, _, _, _ = step_tanh(x_new, v_t)
c_new += q_T * (x_new @ Q_base @ x_new)
if c_new < cost:
vs = vs_new
break
return np.array(xs), np.array(us), vs, Ks, cost
xs_nom, us_nom, vs_nom, Ks_nom, _ = ilqr_swingup([np.pi, 0.0], H=80, iters=35)
for t in range(0, 81, 10):
u_t = us_nom[t] if t < 80 else 0.0
print(f't={t:2d} theta={xs_nom[t, 0]:7.4f} '
f'thetadot={xs_nom[t, 1]:7.4f} u={u_t:+6.3f}')
d2l.plot(np.arange(80) * 0.05, [xs_nom[:-1, 0], xs_nom[:-1, 1], us_nom],
'time (s)', 'angle / velocity / torque',
legend=[r'angle $\vartheta_t$', r'velocity $\dot{\vartheta}_t$',
r'torque $u_t$'], figsize=(5.5, 3.2))t= 0 theta= 3.1416 thetadot= 0.0000 u=-1.782
t=10 theta= 2.6515 thetadot=-1.0260 u=+0.965
t=20 theta= 3.5453 thetadot= 3.3225 u=+1.681
t=30 theta= 4.0383 thetadot=-2.6013 u=-1.807
t=40 theta= 1.5668 thetadot=-4.4402 u=-1.832
t=50 theta= 0.3746 thetadot=-1.3417 u=-1.209
t=60 theta= 0.0009 thetadot=-0.0132 u=+0.066
t=70 theta= 0.0002 thetadot=-0.0006 u=-0.000
t=80 theta= 0.0001 thetadot=-0.0000 u=+0.000
Look at the trajectory that iLQR discovers in 35 iterations from the bottom :
- Steps 0 to 10 (initial back-swing): It pushes left () to .
- Steps 10 to 30 (energy pump): It reverses torque (), driving the pendulum through the bottom to on the other side to store gravitational potential energy.
- Steps 30 to 60 (whip and catch): It reverses torque again (), passing the bottom at up to and still moving at as it climbs past the horizontal () into the upright catch basin () and brakes smoothly to rest at the top (, , ).
This plan is a local optimum, and we should not mistake it for the best swing-up. Each iLQR iteration improves the trajectory it was given, so the result depends on the initial control sequence. ilqr_swingup starts from a small push over the first 15 steps () and nothing after, and with a fixed damping . The push matters: started from , the same 35 iterations do not bring the rod to rest at the top. The dependence on the initial guess returns below, where it decides whether a controller recovers from a knock.
14.6.4 Receding-Horizon Model Predictive Control#
14.6.4.1 Open-Loop Plans, Local Feedback Tubes, and Online Re-Planning#
An optimal trajectory is not yet a robust controller. We can execute the plan in three ways:
- Open-loop execution: Apply the precomputed sequence blind to the actual state . Because the upright posture is an unstable saddle, even a small disturbance or numerical drift pushes the trajectory off course.
- Time-varying LQR (TV-LQR) tracking: Use the local feedback matrices computed during the final backward pass of iLQR, applying . This surrounds the nominal trajectory with a local linear feedback tube at zero online planning cost, but fails if a strong knock pushes out of the tube into a region where a fresh swing-up pump is needed.
- Receding-horizon Model Predictive Control (MPC): At every time step , observe the true state , re-solve the finite-horizon control problem over a lookahead window starting from (warm-started by shifting the previous step's plan by one step), apply only the first control , and repeat at (Rawlings et al., 2017).
Our mpc_action settles two details of the third scheme. The first is the length of the window. The shifted plan is one step shorter than the plan before it, so the window starts at the 80 steps of the nominal plan and shrinks with it. Once H_min steps are left, the plan is padded with zeros and the window recedes at that length. The second detail is what to do when the warm start fails. Because iLQR is a local method, a warm-started plan stays near the old trajectory even when that trajectory no longer leads to the top. If the re-optimized plan ends more than from upright, mpc_action discards it and plans a fresh swing-up over H_mpc steps (), from the initial push that ilqr_swingup uses by default.
We compare all three controllers over steps from when an external angular-velocity impulse strikes the pendulum at step , just as it climbs past the horizontal toward the upright catch basin:
T = 120
xs_pad = np.vstack([xs_nom, np.zeros((T - 80, 2))])
vs_pad = np.concatenate([vs_nom, np.zeros(T - 80)])
us_pad = np.concatenate([us_nom, np.zeros(T - 80)])
Ks_pad = np.vstack([Ks_nom, np.tile(Ks_nom[-1], (T - 80, 1))])
def mpc_action(x, vs_warm, H_mpc=60, H_min=25):
"""One MPC step: re-optimize the shifted plan (at least H_min steps) from x;
if it no longer ends at the top, plan afresh over H_mpc steps."""
H = max(H_min, len(vs_warm))
warm = np.concatenate([vs_warm, np.zeros(H)])[:H]
xs_w, us_w, vs_w, _, _ = ilqr_swingup(x, H=H, iters=18, vs_init=warm)
if abs(xs_w[-1, 0]) > 0.2: # warm plan missed the top: re-seed
_, us_s, vs_s, _, _ = ilqr_swingup(x, H=H_mpc, iters=25)
return us_s[0], vs_s[0], vs_s[1:]
return us_w[0], vs_w[0], vs_w[1:]
for impulse in (0.0, 0.5, 2.2):
x_ol, x_tv, x_mpc = [np.array([np.pi, 0.0]) for _ in range(3)]
ret_ol = ret_tv = ret_mpc = 0.0
th_ol, th_tv, th_mpc = [], [], []
vs_warm = vs_nom.copy()
for t in range(T):
if t == 45:
for x in (x_ol, x_tv, x_mpc):
x[1] += impulse
th_ol.append(wrap(x_ol[0]))
th_tv.append(wrap(x_tv[0]))
th_mpc.append(wrap(x_mpc[0]))
# 1. Open-loop
ret_ol -= wrap(x_ol[0])**2 + 0.1 * x_ol[1]**2 + 0.001 * us_pad[t]**2
x_ol, _, _, _ = step_tanh(x_ol, vs_pad[t])
# 2. Time-varying LQR tracking
v_tv = vs_pad[t] + Ks_pad[t] @ (x_tv - xs_pad[t])
u_tv = 2.0 * np.tanh(v_tv)
ret_tv -= wrap(x_tv[0])**2 + 0.1 * x_tv[1]**2 + 0.001 * u_tv**2
x_tv, _, _, _ = step_tanh(x_tv, v_tv)
# 3. Receding-horizon MPC
u_m, v_m, vs_warm = mpc_action(x_mpc, vs_warm)
ret_mpc -= wrap(x_mpc[0])**2 + 0.1 * x_mpc[1]**2 + 0.001 * u_m**2
x_mpc, _, _, _ = step_tanh(x_mpc, v_m)
print(f'impulse={impulse:+.1f} rad/s at t=45:')
print(f' Open-loop: final theta={wrap(x_ol[0]):+6.3f}, return={ret_ol:6.1f}')
print(f' TV-LQR: final theta={wrap(x_tv[0]):+6.3f}, return={ret_tv:6.1f}')
print(f' MPC (iLQR): final theta={wrap(x_mpc[0]):+6.3f}, return={ret_mpc:6.1f}')
d2l.plot(np.arange(T) * 0.05, [th_ol, th_tv, th_mpc],
'time (s)', r'wrapped angle $\vartheta_t$ (rad)',
legend=['Open-loop', 'TV-LQR', 'MPC (iLQR)'], figsize=(5.5, 3.2))impulse=+0.0 rad/s at t=45:
Open-loop: final theta=+0.075, return=-333.6
TV-LQR: final theta=+0.000, return=-333.7
MPC (iLQR): final theta=+0.000, return=-331.6
impulse=+0.5 rad/s at t=45:
Open-loop: final theta=-2.939, return=-502.3
TV-LQR: final theta=-0.001, return=-333.9
MPC (iLQR): final theta=+0.000, return=-331.7
impulse=+2.2 rad/s at t=45:
Open-loop: final theta=+2.941, return=-621.1
TV-LQR: final theta=+1.959, return=-797.9
MPC (iLQR): final theta=-0.000, return=-558.2
Figure 14.6.2 places the three stages of this section side by side: the local LQR value contours and torque-saturation boundary around the upright equilibrium, the iLQR energy-pumping trajectory in the phase plane, and the disturbance-rejection trajectories under the strong impulse at .
Optimal control from local LQR to receding-horizon MPC. (a) Upright LQR cost-to-go contours and the static holding boundary (dotted): starting from converges to the origin (blue), whereas saturates the motor torque and falls away (orange dashed). (b) The 80-step iLQR swing-up trajectory in the phase plane, pumping from to before whipping through the bottom to the upright equilibrium . (c) Wrapped angle when an impulse strikes at (, vertical dotted line): open-loop and TV-LQR fail, while receding-horizon MPC plans a new swing-up and returns to .
The three disturbance levels on our pendulum benchmark separate the three controllers cleanly:
- No disturbance (): All three swing the pendulum up, earning returns between and over the 120 steps. These lie below the quoted for the benchmark, for two reasons. We start from the bottom, the worst state, whereas the benchmark averages over random starts. And iLQR minimizes its own trajectory cost, with a light state weight during the swing, not the pendulum reward that scores the return. Over the final 40 steps after , open-loop begins to drift to at the unstable saddle, while TV-LQR and MPC hold .
- Moderate disturbance (): Open-loop execution is knocked off its precomputed schedule, falls back down, and ends at (return ). Both TV-LQR (, return ) and MPC (, return ) absorb the push and lock the rod upright.
- Strong disturbance (): The knock arrests the upward climb and sends the pendulum falling back toward the bottom. TV-LQR's linear feedback around the old nominal trajectory saturates its torque and fails (, return ), because recovering requires a new swing-up pump that does not exist in a linear neighborhood of the old trajectory. MPC restores the pendulum to the upright equilibrium (, return ), and it owes this to the re-seed rule. At the step of the knock the warm-started plan misses the top, so
mpc_actionplans a fresh swing-up from the post-disturbance state and follows it from there. Re-planning from the warm start alone would not recover, because the warm-started plan stays near the old trajectory.
14.6.4.2 From Classical Control to Reinforcement Learning#
Table 14.6.1 summarizes the dictionary between classical optimal control and reinforcement learning, and shows how the upcoming sections of this chapter and Chapter 15 relax each assumption of LQR and iLQR:
| Concept | Classical Optimal Control | Reinforcement Learning |
|---|---|---|
| Variables | state , control | state , action |
| Objective | minimize cumulative cost | maximize expected discounted return |
| Value function | cost-to-go (LQR) | state value or action value |
| Bellman backup | Riccati recursion (14.6.6) | Bellman expectation / optimality operator (Section 14.2) |
| Known nonlinear physics | gradient-based trajectory optimization (iLQR / DDP) + MPC | tree search or sampling-based MPC (Section 15.6) |
| Unknown dynamics, learned | system identification + certainty-equivalent MPC | model-based RL with random shooting / CEM (Section 15.6) |
| Unknown dynamics, no model | model-free adaptive control | policy gradient (Section 14.7, Section 14.9), PPO (Section 15.2), DQN (Section 15.4), SAC (Section 15.5) |
When the dynamics are unknown and must be acted on without fitting a transition model, we cannot compute the Jacobians and required by the backward Riccati pass. Section 14.7 shows how a stochastic policy bypasses these unknown derivatives by differentiating the log-probability of its own sampled actions instead.
14.6.5 Summary#
For linear dynamics and quadratic costs , Bellman's backward dynamic programming has an exact closed-form solution in continuous space: the cost-to-go is quadratic, , where obeys the backward Riccati recursion, and the optimal policy is the linear feedback controller (LQR). Linearizing a nonlinear system around an unstable fixed point via its analytical Jacobians stabilizes states inside the actuator-limited catch basin, but fails outside it when underactuated swing-up pumping is needed. Iterative LQR (iLQR) repeatedly linearizes the dynamics and quadratizes the cost around a nominal trajectory, discovering multi-phase energy-pumping trajectories via backward Riccati passes and forward nonlinear rollouts. Executing an open-loop plan fails under disturbances, and time-varying LQR feedback around a fixed trajectory handles only small perturbations; receding-horizon Model Predictive Control (MPC) re-solves the finite-horizon problem from the current state at each step and recovers even when large disturbances force a completely new trajectory.
14.6.6 Exercises#
- Completing the square in the Riccati backup. Write and .
- Show by expanding the product that for every and ,
where is given by (14.6.6).
- Use and to conclude that , that is the unique global minimizer of , and that .
- Verify the Joseph stabilized form
and explain why every term on the right-hand side is manifestly positive semidefinite even when is replaced by an arbitrary feedback matrix .
-
Certainty equivalence under additive Gaussian noise. Suppose the linear dynamics (14.6.1) are perturbed by independent zero-mean noise vectors with covariance , so that .
- Prove by backward induction that the optimal cost-to-go is , where obeys the exact same deterministic Riccati recursion (14.6.6) and .
- Conclude that the optimal feedback policy does not depend on the noise covariance . Where does this certainty-equivalence property break down if the noise is multiplicative, ?
-
[code] Controllability and the infinite-horizon limit. A linear system with states is controllable if the controllability matrix has full row rank .
- Show that starting from , the state reached after steps equals , so full row rank of is necessary and sufficient to reach every target state in in steps.
- Compute and for the double integrator and for the linearized upright pendulum .
- Set on the first coordinate of a decoupled unstable system , and run
riccati_lqrfor . Which entry of diverges as , and why?
-
[code] Energy shaping vs. trajectory optimization. Classical nonlinear control often swings a pendulum up by controlling its total mechanical energy , which equals at the upright rest equilibrium and at the bottom (Tedrake, 2023).
- Show that along continuous-time frictionless trajectories (), the time rate of change of energy is , so applying torque with drives monotonically downward whenever .
- Implement a hybrid controller on
pendulum_stepthat applies clipped energy pumping (with a tiny initial kick ) when , and switches to the upright LQR controller once . Compare its 200-step return from with iLQR's return.
-
[code] Horizon length and terminal cost in MPC.
mpc_actionre-optimizes the shifted plan over at leastH_minsteps and, when that plan misses the top, plans a fresh swing-up overH_mpcsteps ().- Repeat the experiment of this section with
H_mpc. For which horizons does MPC bring the pendulum back to the top? Compare them with the number of steps the nominal swing-up needs to reach the top, and explain why a short horizon traps the planner near the bottom. - Replace the terminal cost matrix in
ilqr_swingupby the infinite-horizon DARE matrix computed byriccati_lqrat the upright equilibrium. Show that for initial states already within the upright basin (), a receding-horizon LQR controller with terminal cost produces the exact infinite-horizon optimal control even when the lookahead is a single step, .
- Repeat the experiment of this section with
-
Pontryagin costates and value gradients. Let be a smooth deterministic system and . Introduce Lagrange multipliers (called costates or adjoints) for the constraints .
- Differentiate the Lagrangian with respect to and to derive the backward adjoint equation
and the gradient (Pontryagin et al., 1962).
- Compare the backward adjoint recursion with the first-order vectors and in the backward pass of
ilqr_swingup(and with backpropagation through time in Section 8.5). What does iLQR's second-order Hessian recursion add beyond first-order backpropagation through time?