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 xt∈Rd\mathbf{x}_t \in \mathbb{R}^d of positions, angles, and velocities, as in the vehicle of Section 14.1, and the action is a continuous control ut∈Rm\mathbf{u}_t \in \mathbb{R}^m that acts through known dynamics xt+1=f(xt,ut)\mathbf{x}_{t+1} = f(\mathbf{x}_t, \mathbf{u}_t)? Grids do not scale: partitioning each of dd coordinates into 100100 bins produces 100d100^d 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 100d100^d entries, the exact value function Vt(x)=x⊤PtxV_t(\mathbf{x}) = \mathbf{x}^\top \mathbf{P}_t \mathbf{x} is parameterized by a symmetric d×dd \times d matrix Pt\mathbf{P}_t with d(d+1)/2d(d+1)/2 independent numbers. The Bellman backup reduces to the Riccati recursion, and the optimal policy is a linear state-feedback law ut∗=−Ktxt\mathbf{u}_t^* = -\mathbf{K}_t \mathbf{x}_t: 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 tt, it re-solves the control problem over a receding lookahead horizon from the current measured state xt\mathbf{x}_t, applies only the first control ut∣t∗\mathbf{u}_{t|t}^*, and re-plans at step t+1t+1. 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 xt∈Rd\mathbf{x}_t \in \mathbb{R}^d and an action (or control input) is written ut∈Rm\mathbf{u}_t \in \mathbb{R}^m. Whereas reinforcement learning maximizes a reward r(xt,ut)r(\mathbf{x}_t, \mathbf{u}_t), optimal control minimizes a stage cost c(xt,ut)=−r(xt,ut)c(\mathbf{x}_t, \mathbf{u}_t) = -r(\mathbf{x}_t, \mathbf{u}_t). A discrete-time linear system evolves as

xt+1=Axt+But,(14.6.1)\mathbf{x}_{t+1} = \mathbf{A}\mathbf{x}_t + \mathbf{B}\mathbf{u}_t, \tag{14.6.1}

where A∈Rd×d\mathbf{A} \in \mathbb{R}^{d \times d} is the state-transition matrix and B∈Rd×m\mathbf{B} \in \mathbb{R}^{d \times m} is the control-input matrix (the discrete-time counterpart of the linear ODEs in Section 26.1). The target state is the origin x=0\mathbf{x} = \mathbf{0}. Over a finite horizon of HH steps, we minimize the total quadratic cost

J(x0,u0:H−1)=∑t=0H−1(xt⊤Qxt+ut⊤Rut)+xH⊤QHxH,(14.6.2)J(\mathbf{x}_0, \mathbf{u}_{0:H-1}) = \sum_{t=0}^{H-1} \big(\mathbf{x}_t^\top \mathbf{Q}\mathbf{x}_t + \mathbf{u}_t^\top \mathbf{R}\mathbf{u}_t\big) + \mathbf{x}_H^\top \mathbf{Q}_H \mathbf{x}_H, \tag{14.6.2}

where Q⪰0\mathbf{Q} \succeq \mathbf{0} and QH⪰0\mathbf{Q}_H \succeq \mathbf{0} are symmetric positive-semidefinite d×dd \times d state-cost matrices, and R≻0\mathbf{R} \succ \mathbf{0} is a symmetric positive-definite m×mm \times m control-cost matrix. Requiring R≻0\mathbf{R} \succ \mathbf{0} ensures that large control efforts always carry a positive penalty, so the one-step minimization over ut\mathbf{u}_t has a unique finite solution.

14.6.1.2 Exact Continuous Dynamic Programming and the Riccati Recursion#

Let Vt(x)V_t(\mathbf{x}) be the optimal cost-to-go from state x\mathbf{x} at step t∈{0,…,H}t \in \{0, \ldots, H\}. At the terminal step t=Ht = H, no control remains and VH(x)=x⊤PHxV_H(\mathbf{x}) = \mathbf{x}^\top \mathbf{P}_H \mathbf{x} with PH=QH\mathbf{P}_H = \mathbf{Q}_H. Moving backward from t+1t+1 to tt, the finite-horizon form of Bellman's optimality equation (Section 14.2) states that

Vt(x)=min⁡u∈Rm{x⊤Qx+u⊤Ru+Vt+1(Ax+Bu)}.(14.6.3)V_t(\mathbf{x}) = \min_{\mathbf{u} \in \mathbb{R}^m} \Big\{ \mathbf{x}^\top \mathbf{Q}\mathbf{x} + \mathbf{u}^\top \mathbf{R}\mathbf{u} + V_{t+1}(\mathbf{A}\mathbf{x} + \mathbf{B}\mathbf{u}) \Big\}. \tag{14.6.3}

Suppose by backward induction that Vt+1(x′)=x′⊤Pt+1x′V_{t+1}(\mathbf{x}') = {\mathbf{x}'}^\top \mathbf{P}_{t+1} \mathbf{x}' for a symmetric positive-semidefinite matrix Pt+1⪰0\mathbf{P}_{t+1} \succeq \mathbf{0}. Substituting x′=Ax+Bu\mathbf{x}' = \mathbf{A}\mathbf{x} + \mathbf{B}\mathbf{u} expands the bracketed action-value function Qt(x,u)Q_t(\mathbf{x}, \mathbf{u}) into a strictly convex quadratic in u\mathbf{u}:

Qt(x,u)=x⊤(Q+A⊤Pt+1A)x+2u⊤B⊤Pt+1Ax+u⊤(R+B⊤Pt+1B)u.\begin{aligned} Q_t(\mathbf{x}, \mathbf{u}) &= \mathbf{x}^\top(\mathbf{Q} + \mathbf{A}^\top \mathbf{P}_{t+1}\mathbf{A})\mathbf{x} + 2\mathbf{u}^\top \mathbf{B}^\top \mathbf{P}_{t+1}\mathbf{A}\mathbf{x} \\ &\quad + \mathbf{u}^\top(\mathbf{R} + \mathbf{B}^\top \mathbf{P}_{t+1}\mathbf{B})\mathbf{u}. \end{aligned}

Setting the gradient with respect to u\mathbf{u} to zero,

∇uQt(x,u)=2(R+B⊤Pt+1B)u+2B⊤Pt+1Ax=0,(14.6.4)\nabla_{\mathbf{u}} Q_t(\mathbf{x}, \mathbf{u}) = 2(\mathbf{R} + \mathbf{B}^\top \mathbf{P}_{t+1}\mathbf{B})\mathbf{u} + 2\mathbf{B}^\top \mathbf{P}_{t+1}\mathbf{A}\mathbf{x} = \mathbf{0}, \tag{14.6.4}

yields the unique optimal control in closed form:

ut∗=−Ktxt,Kt=(R+B⊤Pt+1B)−1B⊤Pt+1A.(14.6.5)\mathbf{u}_t^* = -\mathbf{K}_t \mathbf{x}_t, \qquad \mathbf{K}_t = (\mathbf{R} + \mathbf{B}^\top \mathbf{P}_{t+1}\mathbf{B})^{-1} \mathbf{B}^\top \mathbf{P}_{t+1}\mathbf{A}. \tag{14.6.5}

Substituting u=−Ktx\mathbf{u} = -\mathbf{K}_t \mathbf{x} back into Qt(x,u)Q_t(\mathbf{x}, \mathbf{u}) confirms that Vt(x)=x⊤PtxV_t(\mathbf{x}) = \mathbf{x}^\top \mathbf{P}_t \mathbf{x} remains purely quadratic, where Pt\mathbf{P}_t obeys the backward discrete-time Riccati recursion:

Pt=Q+A⊤Pt+1A−A⊤Pt+1B(R+B⊤Pt+1B)−1B⊤Pt+1A.(14.6.6)\begin{aligned} \mathbf{P}_t &= \mathbf{Q} + \mathbf{A}^\top \mathbf{P}_{t+1}\mathbf{A} \\ &\quad - \mathbf{A}^\top \mathbf{P}_{t+1}\mathbf{B}(\mathbf{R} + \mathbf{B}^\top \mathbf{P}_{t+1}\mathbf{B})^{-1}\mathbf{B}^\top \mathbf{P}_{t+1}\mathbf{A}. \end{aligned} \tag{14.6.6}

The recursion runs backward once, from PH=QH\mathbf{P}_H = \mathbf{Q}_H, and needs no state to do so. Running the system is then cheap: at each step the controller measures xt\mathbf{x}_t and multiplies it by a stored gain, as Figure 14.6.1 shows.

Figure 14.6.1:

LQR in closed loop. The controller multiplies the measured state xt\mathbf{x}_t by the gain −Kt-\mathbf{K}_t, 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:

  1. No curse of dimensionality: Each Bellman backup replaces a minimization over an infinite action space Rm\mathbb{R}^m and all states Rd\mathbb{R}^d by O(d3+m3)O(d^3 + m^3) matrix operations on Pt+1\mathbf{P}_{t+1}.
  2. Linear feedback gain: The optimal policy πt∗(x)=−Ktx\pi_t^*(\mathbf{x}) = -\mathbf{K}_t \mathbf{x} is linear in the state, and the gain matrix Kt∈Rm×d\mathbf{K}_t \in \mathbb{R}^{m \times d} depends only on (A,B,Q,R)(\mathbf{A}, \mathbf{B}, \mathbf{Q}, \mathbf{R}), not on the initial state x0\mathbf{x}_0.
  3. Certainty equivalence: Even if zero-mean independent noise wt\mathbf{w}_t with covariance Σ\boldsymbol{\Sigma} is added to the transition (xt+1=Axt+But+wt\mathbf{x}_{t+1} = \mathbf{A}\mathbf{x}_t + \mathbf{B}\mathbf{u}_t + \mathbf{w}_t), the cross term E[wt⊤Pt+1(Axt+But)]\mathbb{E}[\mathbf{w}_t^\top \mathbf{P}_{t+1}(\mathbf{A}\mathbf{x}_t + \mathbf{B}\mathbf{u}_t)] vanishes, adding only the constant tr(Pt+1Σ)\textrm{tr}(\mathbf{P}_{t+1}\boldsymbol{\Sigma}) to the value function while leaving the optimal feedback matrix Kt\mathbf{K}_t unchanged (exercise 2).

As the horizon H→∞H \to \infty (under standard controllability and observability conditions), Pt\mathbf{P}_t converges to a stationary solution P∞\mathbf{P}_\infty of the Discrete Algebraic Riccati Equation (DARE), and the time-invariant controller ut=−K∞xt\mathbf{u}_t = -\mathbf{K}_\infty \mathbf{x}_t stabilizes the closed-loop dynamics xt+1=(A−BK∞)xt\mathbf{x}_{t+1} = (\mathbf{A} - \mathbf{B}\mathbf{K}_\infty)\mathbf{x}_t so that every eigenvalue of A−BK∞\mathbf{A} - \mathbf{B}\mathbf{K}_\infty lies strictly inside the unit circle, ρ(A−BK∞)<1\rho(\mathbf{A} - \mathbf{B}\mathbf{K}_\infty) \lt 1.

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 xt=(pt,vt)⊤\mathbf{x}_t = (p_t, v_t)^\top (position and velocity), control utu_t (acceleration), and time step Δt=0.1\Delta t = 0.1. By Newton's laws, pt+1=pt+vtΔt+12utΔt2p_{t+1} = p_t + v_t \Delta t + \frac{1}{2} u_t \Delta t^2 and vt+1=vt+utΔtv_{t+1} = v_t + u_t \Delta t. We penalize position and velocity deviations with Q=diag(1.0,0.1)\mathbf{Q} = \textrm{diag}(1.0, 0.1) and sweep the control-effort weight ru∈{0.01,0.10,1.00}r_u \in \{0.01, 0.10, 1.00\} in R=[ru]\mathbf{R} = [r_u]:

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 ptp_t starting from x0=(1,0)⊤\mathbf{x}_0 = (1, 0)^\top 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 ut∗=−kppt−kvvtu_t^* = -k_p p_t - k_v v_t: dynamic programming has automatically derived a proportional-derivative (PD) controller, pushing back against the position error ptp_t with gain kpk_p and damping the velocity vtv_t with gain kvk_v. When control effort is cheap (R=0.01R = 0.01), LQR chooses aggressive gains K∞=[7.613,4.585]\mathbf{K}_\infty = [7.613, 4.585] that contract the state norm at rate ρ(A−BK∞)=0.761\rho(\mathbf{A} - \mathbf{B}\mathbf{K}_\infty) = 0.761 per step; when control effort is expensive (R=1.00R = 1.00), it uses gentle accelerations K∞=[0.930,1.395]\mathbf{K}_\infty = [0.930, 1.395] with contraction rate ρ=0.930\rho = 0.930 and a higher cumulative cost V0(x0)=x0⊤P∞x0V_0(\mathbf{x}_0) = \mathbf{x}_0^\top \mathbf{P}_\infty \mathbf{x}_0 (P00=15.00P_{00} = 15.00 vs. 6.026.02).

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 m=1m = 1 and length l=1l = 1 is pivoted at one end under gravity g=10g = 10 and driven by a bounded motor torque ut∈[−2,2]u_t \in [-2, 2]. Its continuous state is xt=(ϑt,ϑ˙t)⊤\mathbf{x}_t = (\vartheta_t, \dot\vartheta_t)^\top, where ϑt\vartheta_t is the angle measured from the upright vertical (ϑ=0\vartheta = 0 upright, ϑ=π\vartheta = \pi hanging straight down) and ϑ˙t∈[−8,8]\dot\vartheta_t \in [-8, 8] is the angular velocity. Because the peak gravitational torque at the horizontal (ϑ=π/2\vartheta = \pi/2) is mgl/2=5>2mgl/2 = 5 > 2, 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 Δt=0.05 s\Delta t = 0.05\text{ s}, the semi-implicit Euler transition xt+1=f(xt,ut)\mathbf{x}_{t+1} = f(\mathbf{x}_t, u_t) is

ϑ˙t+1=ϑ˙t+(3g2lsin⁡ϑt+3ml2ut)Δt,ϑt+1=ϑt+ϑ˙t+1Δt,(14.6.7)\begin{aligned} \dot\vartheta_{t+1} &= \dot\vartheta_t + \Big(\frac{3g}{2l}\sin\vartheta_t + \frac{3}{ml^2}u_t\Big)\Delta t, \\ \vartheta_{t+1} &= \vartheta_t + \dot\vartheta_{t+1}\Delta t, \end{aligned} \tag{14.6.7}

with angular velocity clipped to [−8,8][-8, 8]. Each step incurs the quadratic stage cost c(ϑt,ϑ˙t,ut)=ϑt2+0.1 ϑ˙t2+0.001 ut2c(\vartheta_t, \dot\vartheta_t, u_t) = \vartheta_t^2 + 0.1\,\dot\vartheta_t^2 + 0.001\,u_t^2 (with ϑt\vartheta_t wrapped to [−π,π][-\pi, \pi], corresponding to Q=diag(1.0,0.1)\mathbf{Q} = \textrm{diag}(1.0, 0.1) and R=[[0.001]]\mathbf{R} = [[0.001]]), or equivalently emits the reward rt=−c(ϑt,ϑ˙t,ut)r_t = -c(\vartheta_t, \dot\vartheta_t, u_t). Standard benchmark episodes run for 200200 steps (10 s10\text{ s}): an uncontrolled pendulum scores around −1,200-1{,}200 to −1,500-1{,}500, whereas a controller that swings the rod up and balances it upright averages about −200-200 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 x∗=(0,0)⊤\mathbf{x}^* = (0, 0)^\top with zero torque u∗=0u^* = 0 is a fixed point, f(x∗,u∗)=x∗f(\mathbf{x}^*, u^*) = \mathbf{x}^*. Near any reference pair (xˉ,uˉ)(\bar{\mathbf{x}}, \bar{u}), a first-order Taylor expansion approximates the nonlinear transition by a local linear model in the deviations δxt=xt−xˉ\delta\mathbf{x}_t = \mathbf{x}_t - \bar{\mathbf{x}} and δut=ut−uˉ\delta u_t = u_t - \bar{u}:

f(xt,ut)−f(xˉ,uˉ)≈A(xˉ,uˉ) δxt+B(xˉ,uˉ) δut,A=∂f∂x(xˉ,uˉ),B=∂f∂u(xˉ,uˉ).(14.6.8)\begin{aligned} f(\mathbf{x}_t, u_t) - f(\bar{\mathbf{x}}, \bar{u}) &\approx \mathbf{A}(\bar{\mathbf{x}}, \bar{u})\,\delta\mathbf{x}_t + \mathbf{B}(\bar{\mathbf{x}}, \bar{u})\,\delta u_t, \\ \mathbf{A} &= \frac{\partial f}{\partial \mathbf{x}}(\bar{\mathbf{x}}, \bar{u}), \qquad \mathbf{B} = \frac{\partial f}{\partial u}(\bar{\mathbf{x}}, \bar{u}). \end{aligned} \tag{14.6.8}

Differentiating (14.6.7) with respect to (ϑt,ϑ˙t)(\vartheta_t, \dot\vartheta_t) and utu_t yields ∂ϑ˙t+1/∂ϑt=3g2lcos⁡(ϑt)Δt\partial\dot\vartheta_{t+1}/\partial\vartheta_t = \frac{3g}{2l}\cos(\vartheta_t)\Delta t and ∂ϑ˙t+1/∂ut=3ml2Δt\partial\dot\vartheta_{t+1}/\partial u_t = \frac{3}{ml^2}\Delta t:

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 A\mathbf{A} has an unstable eigenvalue λ1=1.2133>1\lambda_1 = 1.2133 > 1: any small tilt grows exponentially at over 21%21\% per step, as seen in the phase portrait of Section 26.1. Solving the Riccati recursion with Pendulum-v1's cost matrices Q=diag(1,0.1)\mathbf{Q} = \textrm{diag}(1, 0.1) and R=[[0.001]]\mathbf{R} = [[0.001]] produces the feedback gain K∞=[19.693,5.263]\mathbf{K}_\infty = [19.693, 5.263], which pulls both closed-loop eigenvalues inside the unit circle (λ1=0.8537,λ2=0.2467\lambda_1 = 0.8537, \lambda_2 = 0.2467).

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 [−2,2][-2, 2]? The gravitational torque pulling the pendulum down is 12mglsin⁡ϑ=5sin⁡ϑ\frac{1}{2}mgl\sin\vartheta = 5\sin\vartheta, whereas the motor supplies at most ∣u∣=2|u| = 2. Once ∣ϑ∣>arcsin⁡(2/5)≈0.412 rad|\vartheta| > \arcsin(2/5) \approx 0.412\text{ rad} (23.6∘23.6^\circ), gravity exceeds the peak holding torque of the motor. We test the clipped LQR policy ut=clip(−K∞xt,−2,2)u_t = \textrm{clip}(-\mathbf{K}_\infty \mathbf{x}_t, -2, 2) on the full nonlinear pendulum from five starting angles ϑ0\vartheta_0 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 (ϑ0=0.20\vartheta_0 = 0.20 and 0.40 rad0.40\text{ rad}), linear LQR drives the pendulum straight to upright (ϑ200=0.000\vartheta_{200} = 0.000) with near-zero cost (returns −0.32-0.32 and −2.97-2.97). Just outside that threshold (ϑ0=0.50 rad\vartheta_0 = 0.50\text{ rad}), full negative torque u=−2u = -2 cannot arrest the fall, and the rod is still swinging through the bottom after 200 steps (return −770.94-770.94). Beyond the threshold the outcome is no longer monotone in ϑ0\vartheta_0. From 0.60 rad0.60\text{ rad} 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 −546.37-546.37). This is luck, not control. From the bottom (ϑ0=π\vartheta_0 = \pi) the linear controller earns −1471.86-1471.86 and never reaches the top. Because the motor is underactuated (umax⁡=2<5u_{\max} = 2 \lt 5), swinging up from ϑ0=π\vartheta_0 = \pi 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 (0,0)(\mathbf{0}, 0) knows nothing about the nonlinear sin(ϑ)(\vartheta) curvature along a swing from ϑ0=π\vartheta_0 = \pi. 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 ut∈[−2,2]u_t \in [-2, 2] smoothly without hard-clipping kinks, we parameterize ut=2tanh⁡(vt)u_t = 2\tanh(v_t) via an unconstrained control variable vt∈Rv_t \in \mathbb{R}. Given any nominal control sequence vˉ0:H−1\bar{v}_{0:H-1} and its forward rollout xˉ0:H\bar{\mathbf{x}}_{0:H} under the true nonlinear dynamics xt+1=f(xt,vt)\mathbf{x}_{t+1} = f(\mathbf{x}_t, v_t) (without the velocity clip, which the swing-up below never reaches), each iteration of iLQR performs two passes:

  1. Backward Riccati pass along (xˉ0:H,vˉ0:H−1)(\bar{\mathbf{x}}_{0:H}, \bar{v}_{0:H-1}): At each step t=H−1,…,0t = H-1, \ldots, 0, compute the local Jacobians At=∂f∂x(xˉt,vˉt)\mathbf{A}_t = \frac{\partial f}{\partial \mathbf{x}}(\bar{\mathbf{x}}_t, \bar{v}_t) and Bt=∂f∂v(xˉt,vˉt)\mathbf{B}_t = \frac{\partial f}{\partial v}(\bar{\mathbf{x}}_t, \bar{v}_t), and form a second-order Taylor approximation of the action-value perturbation δQt(δxt,δvt)\delta Q_t(\delta\mathbf{x}_t, \delta v_t) from the stage cost gradients (ℓx,t,ℓv,t)(\boldsymbol{\ell}_{\mathbf{x},t}, \ell_{v,t}), Hessians (Lxx,t,ℓvv,t)(\mathbf{L}_{\mathbf{x}\mathbf{x},t}, \ell_{vv,t}), and the next step's value gradient vx,t+1\mathbf{v}_{\mathbf{x},t+1} and Hessian Vxx,t+1\mathbf{V}_{\mathbf{x}\mathbf{x},t+1}:
qx,t=ℓx,t+At⊤vx,t+1,qv,t=ℓv,t+Bt⊤vx,t+1,Qxx,t=Lxx,t+At⊤Vxx,t+1At,qvx,t=Bt⊤Vxx,t+1At,qvv,t=ℓvv,t+μ+Bt⊤Vxx,t+1Bt,\begin{aligned} \mathbf{q}_{\mathbf{x},t} &= \boldsymbol{\ell}_{\mathbf{x},t} + \mathbf{A}_t^\top \mathbf{v}_{\mathbf{x},t+1}, \qquad q_{v,t} = \ell_{v,t} + \mathbf{B}_t^\top \mathbf{v}_{\mathbf{x},t+1}, \\ \mathbf{Q}_{\mathbf{x}\mathbf{x},t} &= \mathbf{L}_{\mathbf{x}\mathbf{x},t} + \mathbf{A}_t^\top \mathbf{V}_{\mathbf{x}\mathbf{x},t+1}\mathbf{A}_t, \qquad \mathbf{q}_{v\mathbf{x},t} = \mathbf{B}_t^\top \mathbf{V}_{\mathbf{x}\mathbf{x},t+1}\mathbf{A}_t, \\ q_{vv,t} &= \ell_{vv,t} + \mu + \mathbf{B}_t^\top \mathbf{V}_{\mathbf{x}\mathbf{x},t+1}\mathbf{B}_t, \end{aligned}

where μ>0\mu > 0 is a Levenberg–Marquardt damping term. Minimizing over δvt\delta v_t gives an open-loop feedforward step kt=−qv,t/qvv,tk_t = -q_{v,t}/q_{vv,t} and a local linear feedback gain Kt=−qvx,t/qvv,t\mathbf{K}_t = -\mathbf{q}_{v\mathbf{x},t}/q_{vv,t}. 2. Forward rollout with backtracking line search: Because the linear model is only accurate near (xˉt,vˉt)(\bar{\mathbf{x}}_t, \bar{v}_t), we roll out the true nonlinear dynamics with step size α∈{1,1/2,1/4,…}\alpha \in \{1, 1/2, 1/4, \ldots\},

vtnew=vˉt+α kt+Kt(xtnew−xˉt),xt+1new=f(xtnew,vtnew),(14.6.9)\begin{aligned} v_t^{\textrm{new}} &= \bar{v}_t + \alpha\, k_t + \mathbf{K}_t(\mathbf{x}_t^{\textrm{new}} - \bar{\mathbf{x}}_t), \\ \mathbf{x}_{t+1}^{\textrm{new}} &= f(\mathbf{x}_t^{\textrm{new}}, v_t^{\textrm{new}}), \end{aligned} \tag{14.6.9}

and accept the first α\alpha that decreases the true nonlinear trajectory cost.

One design detail of the trajectory cost is instructive. To pump energy from ϑ0=π\vartheta_0 = \pi, the pendulum must first swing to ϑ>π\vartheta > \pi on the opposite side before whipping back toward ϑ=0\vartheta = 0. If we place a heavy quadratic penalty ϑt2\vartheta_t^2 on every early step tt, a local gradient method refuses to swing away from 00 because ϑt2\vartheta_t^2 increases during the back-swing. Weighting the state cost lightly during the swing phase (qrun=0.02q_{\textrm{run}} = 0.02 for t<H−20t \lt H - 20) and heavily during the final capture window (qT=100q_T = 100 for t≥H−20t \geq H - 20) lets iLQR use the early steps to pump energy and the final steps to lock the rod at (ϑ,ϑ˙)=(0,0)(\vartheta, \dot\vartheta) = (0, 0):

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 (π,0)(\pi, 0):

  • Steps 0 to 10 (initial back-swing): It pushes left (u0=−1.782u_0 = -1.782) to ϑ10=2.652 rad\vartheta_{10} = 2.652\text{ rad}.
  • Steps 10 to 30 (energy pump): It reverses torque (u10=+0.965→u20=+1.681u_{10} = +0.965 \to u_{20} = +1.681), driving the pendulum through the bottom to ϑ30=4.038 rad\vartheta_{30} = 4.038\text{ rad} on the other side to store gravitational potential energy.
  • Steps 30 to 60 (whip and catch): It reverses torque again (u30=−1.807→u40=−1.832u_{30} = -1.807 \to u_{40} = -1.832), passing the bottom at up to 5.7 rad/s5.7\text{ rad/s} and still moving at ϑ˙40=−4.440 rad/s\dot\vartheta_{40} = -4.440\text{ rad/s} as it climbs past the horizontal (ϑ40=1.567 rad\vartheta_{40} = 1.567\text{ rad}) into the upright catch basin (ϑ50=0.375 rad\vartheta_{50} = 0.375\text{ rad}) and brakes smoothly to rest at the top (ϑ60=0.0009 rad\vartheta_{60} = 0.0009\text{ rad}, ϑ80=0.0001 rad\vartheta_{80} = 0.0001\text{ rad}, u80=0.000u_{80} = 0.000).

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 (vˉt=0.2\bar{v}_t = 0.2) and nothing after, and with a fixed damping μ\mu. The push matters: started from vˉ=0\bar{v} = 0, 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 (xˉ0:H,uˉ0:H−1)(\bar{\mathbf{x}}_{0:H}, \bar{u}_{0:H-1}) is not yet a robust controller. We can execute the plan in three ways:

  1. Open-loop execution: Apply the precomputed sequence uˉt\bar{u}_t blind to the actual state xt\mathbf{x}_t. Because the upright posture is an unstable saddle, even a small disturbance or numerical drift pushes the trajectory off course.
  2. Time-varying LQR (TV-LQR) tracking: Use the local feedback matrices Kt\mathbf{K}_t computed during the final backward pass of iLQR, applying vt=vˉt+Kt(xt−xˉt)v_t = \bar{v}_t + \mathbf{K}_t(\mathbf{x}_t - \bar{\mathbf{x}}_t). This surrounds the nominal trajectory with a local linear feedback tube at zero online planning cost, but fails if a strong knock pushes xt\mathbf{x}_t out of the tube into a region where a fresh swing-up pump is needed.
  3. Receding-horizon Model Predictive Control (MPC): At every time step tt, observe the true state xt\mathbf{x}_t, re-solve the finite-horizon control problem over a lookahead window starting from xt\mathbf{x}_t (warm-started by shifting the previous step's plan by one step), apply only the first control ut∣t∗u_{t|t}^*, and repeat at t+1t+1 (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 =25= 25 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 0.2 rad0.2\text{ rad} from upright, mpc_action discards it and plans a fresh swing-up over H_mpc =60= 60 steps (3 s3\text{ s}), from the initial push that ilqr_swingup uses by default.

We compare all three controllers over T=120T = 120 steps from x0=(π,0)\mathbf{x}_0 = (\pi, 0) when an external angular-velocity impulse Δϑ˙∈{0.0,+0.5,+2.2} rad/s\Delta\dot\vartheta \in \{0.0, +0.5, +2.2\}\text{ rad/s} strikes the pendulum at step t=45t = 45, 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 (ϑ,ϑ˙)(\vartheta, \dot\vartheta) phase plane, and the disturbance-rejection trajectories under the strong impulse Δϑ˙=+2.2 rad/s\Delta\dot\vartheta = +2.2\text{ rad/s} at t=45t = 45.

Figure 14.6.2:

Optimal control from local LQR to receding-horizon MPC. (a) Upright LQR cost-to-go contours V∞(x)=x⊤P∞xV_\infty(\mathbf{x}) = \mathbf{x}^\top\mathbf{P}_\infty\mathbf{x} and the static holding boundary ∣ϑ∣≤arcsin⁡(2/5)≈0.412 rad|\vartheta| \leq \arcsin(2/5) \approx 0.412\text{ rad} (dotted): starting from ϑ0=0.40 rad\vartheta_0 = 0.40\text{ rad} converges to the origin (blue), whereas ϑ0=0.50 rad\vartheta_0 = 0.50\text{ rad} saturates the motor torque ∣u∣≤2|u| \leq 2 and falls away (orange dashed). (b) The 80-step iLQR swing-up trajectory in the (ϑ,ϑ˙)(\vartheta, \dot\vartheta) phase plane, pumping from (π,0)(\pi, 0) to ϑ30=4.04 rad\vartheta_{30} = 4.04\text{ rad} before whipping through the bottom to the upright equilibrium (0,0)(0, 0). (c) Wrapped angle ϑt\vartheta_t when an impulse Δϑ˙=+2.2 rad/s\Delta\dot\vartheta = +2.2\text{ rad/s} strikes at t=45t = 45 (2.25 s2.25\text{ s}, vertical dotted line): open-loop and TV-LQR fail, while receding-horizon MPC plans a new swing-up and returns to ϑ=0\vartheta = 0.

The three disturbance levels on our pendulum benchmark separate the three controllers cleanly:

  • No disturbance (Δϑ˙=0.0\Delta\dot\vartheta = 0.0): All three swing the pendulum up, earning returns between −332-332 and −334-334 over the 120 steps. These lie below the −200-200 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 t=80t=80, open-loop begins to drift to ϑ120=+0.075 rad\vartheta_{120} = +0.075\text{ rad} at the unstable saddle, while TV-LQR and MPC hold ϑ120=0.000 rad\vartheta_{120} = 0.000\text{ rad}.
  • Moderate disturbance (Δϑ˙=+0.5 rad/s\Delta\dot\vartheta = +0.5\text{ rad/s}): Open-loop execution is knocked off its precomputed schedule, falls back down, and ends at ϑ120=−2.939 rad\vartheta_{120} = -2.939\text{ rad} (return −502.3-502.3). Both TV-LQR (ϑ120=−0.001 rad\vartheta_{120} = -0.001\text{ rad}, return −333.9-333.9) and MPC (ϑ120=+0.000 rad\vartheta_{120} = +0.000\text{ rad}, return −331.7-331.7) absorb the push and lock the rod upright.
  • Strong disturbance (Δϑ˙=+2.2 rad/s\Delta\dot\vartheta = +2.2\text{ rad/s}): 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 (ϑ120=+1.959 rad\vartheta_{120} = +1.959\text{ rad}, return −797.9-797.9), 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 (ϑ120=0.000 rad\vartheta_{120} = 0.000\text{ rad}, return −558.2-558.2), and it owes this to the re-seed rule. At the step of the knock the warm-started plan misses the top, so mpc_action plans 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:

Table 14.6.1. The bridge between classical optimal control and reinforcement learning.
ConceptClassical Optimal ControlReinforcement Learning
Variablesstate xt∈Rd\mathbf{x}_t \in \mathbb{R}^d, control ut∈Rm\mathbf{u}_t \in \mathbb{R}^mstate st∈Ss_t \in \mathcal{S}, action at∈Aa_t \in \mathcal{A}
Objectiveminimize cumulative cost ∑tc(xt,ut)\sum_t c(\mathbf{x}_t, \mathbf{u}_t)maximize expected discounted return E[∑tγtr(st,at)]\mathbb{E}[\sum_t \gamma^t r(s_t, a_t)]
Value functioncost-to-go Vt(x)=x⊤PtxV_t(\mathbf{x}) = \mathbf{x}^\top \mathbf{P}_t \mathbf{x} (LQR)state value Vπ(s)V^\pi(s) or action value Qπ(s,a)Q^\pi(s, a)
Bellman backupRiccati recursion (14.6.6)Bellman expectation / optimality operator (Section 14.2)
Known nonlinear physics ffgradient-based trajectory optimization (iLQR / DDP) + MPCtree search or sampling-based MPC (Section 15.6)
Unknown dynamics, learned f^ϕ\hat{f}_\phisystem identification + certainty-equivalent MPCmodel-based RL with random shooting / CEM (Section 15.6)
Unknown dynamics, no modelmodel-free adaptive controlpolicy gradient (Section 14.7, Section 14.9), PPO (Section 15.2), DQN (Section 15.4), SAC (Section 15.5)

When the dynamics ff are unknown and must be acted on without fitting a transition model, we cannot compute the Jacobians At=∂f/∂x\mathbf{A}_t = \partial f/\partial \mathbf{x} and Bt=∂f/∂u\mathbf{B}_t = \partial f/\partial \mathbf{u} required by the backward Riccati pass. Section 14.7 shows how a stochastic policy πθ(a∣s)\pi_\theta(a \mid s) bypasses these unknown derivatives by differentiating the log-probability of its own sampled actions instead.

14.6.5 Summary#

For linear dynamics xt+1=Axt+But\mathbf{x}_{t+1} = \mathbf{A}\mathbf{x}_t + \mathbf{B}\mathbf{u}_t and quadratic costs x⊤Qx+u⊤Ru\mathbf{x}^\top\mathbf{Q}\mathbf{x} + \mathbf{u}^\top\mathbf{R}\mathbf{u}, Bellman's backward dynamic programming has an exact closed-form solution in continuous space: the cost-to-go is quadratic, Vt(x)=x⊤PtxV_t(\mathbf{x}) = \mathbf{x}^\top\mathbf{P}_t\mathbf{x}, where Pt\mathbf{P}_t obeys the backward Riccati recursion, and the optimal policy is the linear feedback controller ut∗=−Ktxt\mathbf{u}_t^* = -\mathbf{K}_t\mathbf{x}_t (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#

  1. Completing the square in the Riccati backup. Write St+1=R+B⊤Pt+1B\mathbf{S}_{t+1} = \mathbf{R} + \mathbf{B}^\top\mathbf{P}_{t+1}\mathbf{B} and Kt=St+1−1B⊤Pt+1A\mathbf{K}_t = \mathbf{S}_{t+1}^{-1}\mathbf{B}^\top\mathbf{P}_{t+1}\mathbf{A}.
    1. Show by expanding the product that for every x∈Rd\mathbf{x} \in \mathbb{R}^d and u∈Rm\mathbf{u} \in \mathbb{R}^m,
Qt(x,u)=x⊤Ptx+(u+Ktx)⊤St+1(u+Ktx),Q_t(\mathbf{x}, \mathbf{u}) = \mathbf{x}^\top\mathbf{P}_t\mathbf{x} + (\mathbf{u} + \mathbf{K}_t\mathbf{x})^\top \mathbf{S}_{t+1}(\mathbf{u} + \mathbf{K}_t\mathbf{x}),

where Pt\mathbf{P}_t is given by (14.6.6).

  1. Use R≻0\mathbf{R} \succ \mathbf{0} and Pt+1⪰0\mathbf{P}_{t+1} \succeq \mathbf{0} to conclude that St+1≻0\mathbf{S}_{t+1} \succ \mathbf{0}, that ut∗=−Ktx\mathbf{u}_t^* = -\mathbf{K}_t\mathbf{x} is the unique global minimizer of Qt(x,u)Q_t(\mathbf{x}, \mathbf{u}), and that Pt⪰0\mathbf{P}_t \succeq \mathbf{0}.
  2. Verify the Joseph stabilized form
Pt=Q+Kt⊤RKt+(A−BKt)⊤Pt+1(A−BKt),(14.6.10)\mathbf{P}_t = \mathbf{Q} + \mathbf{K}_t^\top\mathbf{R}\mathbf{K}_t + (\mathbf{A} - \mathbf{B}\mathbf{K}_t)^\top\mathbf{P}_{t+1}(\mathbf{A} - \mathbf{B}\mathbf{K}_t), \tag{14.6.10}

and explain why every term on the right-hand side is manifestly positive semidefinite even when Kt\mathbf{K}_t is replaced by an arbitrary feedback matrix K\mathbf{K}.

  1. Certainty equivalence under additive Gaussian noise. Suppose the linear dynamics (14.6.1) are perturbed by independent zero-mean noise vectors w0,…,wH−1\mathbf{w}_0, \ldots, \mathbf{w}_{H-1} with covariance E[wtwt⊤]=Σ\mathbb{E}[\mathbf{w}_t\mathbf{w}_t^\top] = \boldsymbol{\Sigma}, so that xt+1=Axt+But+wt\mathbf{x}_{t+1} = \mathbf{A}\mathbf{x}_t + \mathbf{B}\mathbf{u}_t + \mathbf{w}_t.

    1. Prove by backward induction that the optimal cost-to-go is Vt(x)=x⊤Ptx+ctV_t(\mathbf{x}) = \mathbf{x}^\top\mathbf{P}_t\mathbf{x} + c_t, where Pt\mathbf{P}_t obeys the exact same deterministic Riccati recursion (14.6.6) and ct=∑k=t+1Htr(PkΣ)c_t = \sum_{k=t+1}^{H} \textrm{tr}(\mathbf{P}_k \boldsymbol{\Sigma}).
    2. Conclude that the optimal feedback policy ut∗=−Ktxt\mathbf{u}_t^* = -\mathbf{K}_t\mathbf{x}_t does not depend on the noise covariance Σ\boldsymbol{\Sigma}. Where does this certainty-equivalence property break down if the noise is multiplicative, xt+1=(A+A~t)xt+(B+B~t)ut\mathbf{x}_{t+1} = (\mathbf{A} + \tilde{\mathbf{A}}_t)\mathbf{x}_t + (\mathbf{B} + \tilde{\mathbf{B}}_t)\mathbf{u}_t?
  2. [code] Controllability and the infinite-horizon limit. A linear system (A,B)(\mathbf{A}, \mathbf{B}) with dd states is controllable if the controllability matrix C=[B,AB,…,Ad−1B]\mathcal{C} = [\mathbf{B}, \mathbf{A}\mathbf{B}, \ldots, \mathbf{A}^{d-1}\mathbf{B}] has full row rank dd.

    1. Show that starting from x0=0\mathbf{x}_0 = \mathbf{0}, the state reached after dd steps equals xd=C [ud−1⊤,ud−2⊤,…,u0⊤]⊤\mathbf{x}_d = \mathcal{C}\,[\mathbf{u}_{d-1}^\top, \mathbf{u}_{d-2}^\top, \ldots, \mathbf{u}_0^\top]^\top, so full row rank of C\mathcal{C} is necessary and sufficient to reach every target state in Rd\mathbb{R}^d in dd steps.
    2. Compute rank(C)\textrm{rank}(\mathcal{C}) and det⁡(C)\det(\mathcal{C}) for the double integrator (Adi,Bdi)(\mathbf{A}_{\textrm{di}}, \mathbf{B}_{\textrm{di}}) and for the linearized upright pendulum (Ap,Bp)(\mathbf{A}_p, \mathbf{B}_p).
    3. Set Bun=[0,0]⊤\mathbf{B}_{\textrm{un}} = [0, 0]^\top on the first coordinate of a decoupled unstable system A=diag(1.2,0.8),B=[0,1]⊤\mathbf{A} = \textrm{diag}(1.2, 0.8), \mathbf{B} = [0, 1]^\top, and run riccati_lqr for H∈{10,50,100}H \in \{10, 50, 100\}. Which entry of P0\mathbf{P}_0 diverges as H→∞H \to \infty, and why?
  3. [code] Energy shaping vs. trajectory optimization. Classical nonlinear control often swings a pendulum up by controlling its total mechanical energy E(ϑ,ϑ˙)=16ml2ϑ˙2+12mglcos⁡ϑE(\vartheta, \dot\vartheta) = \frac{1}{6}ml^2\dot\vartheta^2 + \frac{1}{2}mgl\cos\vartheta, which equals E∗=12mgl=5E^* = \frac{1}{2}mgl = 5 at the upright rest equilibrium (ϑ=0,ϑ˙=0)(\vartheta=0, \dot\vartheta=0) and −5-5 at the bottom (ϑ=π,ϑ˙=0)(\vartheta=\pi, \dot\vartheta=0) (Tedrake, 2023).

    1. Show that along continuous-time frictionless trajectories (ϑ¨=3g2lsin⁡ϑ+3ml2u\ddot\vartheta = \frac{3g}{2l}\sin\vartheta + \frac{3}{ml^2}u), the time rate of change of energy is E˙=uϑ˙\dot E = u\dot\vartheta, so applying torque u=−kE(E−E∗)ϑ˙u = -k_E (E - E^*)\dot\vartheta with kE>0k_E > 0 drives (E−E∗)2(E - E^*)^2 monotonically downward whenever ϑ˙≠0\dot\vartheta \neq 0.
    2. Implement a hybrid controller on pendulum_step that applies clipped energy pumping u=clip(−kE(E−E∗)ϑ˙,−2,2)u = \textrm{clip}(-k_E (E - E^*)\dot\vartheta, -2, 2) (with a tiny initial kick u0=2u_0 = 2) when ∣wrap(ϑ)∣>0.35|\textrm{wrap}(\vartheta)| > 0.35, and switches to the upright LQR controller u=clip(−K∞x,−2,2)u = \textrm{clip}(-\mathbf{K}_\infty \mathbf{x}, -2, 2) once ∣wrap(ϑ)∣≤0.35|\textrm{wrap}(\vartheta)| \leq 0.35. Compare its 200-step return from (π,0)(\pi, 0) with iLQR's return.
  4. [code] Horizon length and terminal cost in MPC. mpc_action re-optimizes the shifted plan over at least H_min =25= 25 steps and, when that plan misses the top, plans a fresh swing-up over H_mpc =60= 60 steps (3 s3\text{ s}).

    1. Repeat the Δϑ˙=+2.2\Delta\dot\vartheta = +2.2 experiment of this section with H_mpc ∈{15,25,40,60}\in \{15, 25, 40, 60\}. 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.
    2. Replace the terminal cost matrix qTQbaseq_T \mathbf{Q}_{\textrm{base}} in ilqr_swingup by the infinite-horizon DARE matrix P∞\mathbf{P}_\infty computed by riccati_lqr at the upright equilibrium. Show that for initial states already within the upright basin (∣ϑ0∣≤0.35|\vartheta_0| \leq 0.35), a receding-horizon LQR controller with terminal cost xH⊤P∞xH\mathbf{x}_H^\top \mathbf{P}_\infty \mathbf{x}_H produces the exact infinite-horizon optimal control ut∗=−K∞xt\mathbf{u}_t^* = -\mathbf{K}_\infty \mathbf{x}_t even when the lookahead is a single step, H=1H = 1.
  5. Pontryagin costates and value gradients. Let xt+1=f(xt,ut)\mathbf{x}_{t+1} = f(\mathbf{x}_t, \mathbf{u}_t) be a smooth deterministic system and J=∑t=0H−1c(xt,ut)+cH(xH)J = \sum_{t=0}^{H-1} c(\mathbf{x}_t, \mathbf{u}_t) + c_H(\mathbf{x}_H). Introduce Lagrange multipliers (called costates or adjoints) λ1,…,λH∈Rd\boldsymbol{\lambda}_1, \ldots, \boldsymbol{\lambda}_H \in \mathbb{R}^d for the constraints xt+1−f(xt,ut)=0\mathbf{x}_{t+1} - f(\mathbf{x}_t, \mathbf{u}_t) = \mathbf{0}.

    1. Differentiate the Lagrangian L=J+∑t=0H−1λt+1⊤(f(xt,ut)−xt+1)\mathcal{L} = J + \sum_{t=0}^{H-1} \boldsymbol{\lambda}_{t+1}^\top (f(\mathbf{x}_t, \mathbf{u}_t) - \mathbf{x}_{t+1}) with respect to xt\mathbf{x}_t and ut\mathbf{u}_t to derive the backward adjoint equation
λH=∇xcH(xH),λt=∇xc(xt,ut)+At⊤λt+1,(14.6.11)\boldsymbol{\lambda}_H = \nabla_{\mathbf{x}} c_H(\mathbf{x}_H), \qquad \boldsymbol{\lambda}_t = \nabla_{\mathbf{x}} c(\mathbf{x}_t, \mathbf{u}_t) + \mathbf{A}_t^\top \boldsymbol{\lambda}_{t+1}, \tag{14.6.11}

and the gradient ∇utJ=∇uc(xt,ut)+Bt⊤λt+1\nabla_{\mathbf{u}_t} J = \nabla_{\mathbf{u}} c(\mathbf{x}_t, \mathbf{u}_t) + \mathbf{B}_t^\top \boldsymbol{\lambda}_{t+1} (Pontryagin et al., 1962).

  1. Compare the backward adjoint recursion with the first-order vectors vx,t\mathbf{v}_{\mathbf{x},t} and qv,tq_{v,t} in the backward pass of ilqr_swingup (and with backpropagation through time in Section 8.5). What does iLQR's second-order Hessian recursion Vxx,t\mathbf{V}_{\mathbf{x}\mathbf{x},t} add beyond first-order backpropagation through time?

Discussions