Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

iLQR and Differential Dynamic Programming

A boat approaching a quay must arrive in the right place, face along the berth, and lose its remaining momentum. A sequence of thrust commands determines all three outcomes. The shooting formulation turns this task into an optimization over those commands: simulate a candidate sequence, measure its cost, and improve it. How can an optimizer use the time structure of the simulation when computing that improvement?

Linearizing the dynamics along the current trajectory and quadratically approximating its costs gives a problem whose controls can be eliminated backward, one time step at a time. The resulting correction is then tested through the nonlinear simulator. Repeating these operations gives the iterative linear-quadratic regulator, or iLQR. Keeping additional curvature from the dynamics gives differential dynamic programming, or DDP. Both methods compute corrections around a nominal trajectory. Their backward recursions follow from substitution and quadratic minimization.

Learning Goals

After working through the derivations and examples, you should be able to:

Prerequisites

The chapter uses the finite-horizon optimal-control formulation, single shooting, and first and second derivatives. The sequential-methods discussion introduces general SQP subproblems, and the initial-value-problem appendix reviews numerical integration. Neither dynamic programming nor a previous derivation of LQR is required.

A Docking Problem

Docking requires the boat to reach the berth, align with the quay, and shed its momentum. A trajectory that reaches the right position with appreciable translational or angular velocity will carry the boat away again.

Consider a two-metre boat moving in the horizontal plane. Its state and control are

x=(px,py,ψ,vx,vy,ω),u=(uL,uR)∈[−1,1]2.\mathbf x=(p_x,p_y,\psi,v_x,v_y,\omega),\qquad \mathbf u=(u_L,u_R)\in[-1,1]^2.

The position and velocity are measured in fixed world coordinates, ψ\psi is the heading, and ω\omega is the angular velocity. Each control is a fraction of maximum thrust. Positive commands push forward and negative commands push backward. Unequal thrusts turn the boat. There is no directly commanded sideways force, so an approach with sideways momentum requires a maneuver.

Let e(ψ)=(cos⁡ψ,sin⁡ψ)⊤\mathbf e(\psi)=(\cos\psi,\sin\psi)^\top point along the boat and n(ψ)=(−sin⁡ψ,cos⁡ψ)⊤\mathbf n(\psi)=(-\sin\psi,\cos\psi)^\top point across it. The simplified inertial model is

p˙=v,ψ˙=ω,mv˙=Fmax⁡(uL+uR)e−d∥(e⊤v)e−d⊥(n⊤v)n,Iω˙=bFmax⁡(uR−uL)−dωω.\begin{aligned} \dot{\mathbf p}&=\mathbf v,&\qquad \dot\psi&=\omega,\\ m\dot{\mathbf v} &=F_{\max}(u_L+u_R)\mathbf e -d_\parallel(\mathbf e^\top\mathbf v)\mathbf e -d_\perp(\mathbf n^\top\mathbf v)\mathbf n,\\ I\dot\omega&=bF_{\max}(u_R-u_L)-d_\omega\omega. \end{aligned}

The drag opposes velocity along each boat axis, with stronger resistance to sideways motion. Thrust changes acceleration, so releasing the controls does not stop the boat immediately. These equations are a synthetic teaching model for calm water, with neither contact forces nor waves.

QuantityValue
Mass mm50 kg50\ \mathrm{kg}
Angular inertia II20 kg m220\ \mathrm{kg\,m^2}
Thruster lever arm bb0.4 m0.4\ \mathrm m
Maximum force per thruster Fmax⁡F_{\max}25 N25\ \mathrm N
Longitudinal drag d∥d_\parallel8 N s/m8\ \mathrm{N\,s/m}
Lateral drag d⊥d_\perp30 N s/m30\ \mathrm{N\,s/m}
Angular drag dωd_\omega10 N m s10\ \mathrm{N\,m\,s}
Rectangular hull length and width2 m2\ \mathrm m, 0.8 m0.8\ \mathrm m

The quay occupies py≤0p_y\leq0, and the desired arrival state is x⋆=(0,1,0,0,0,0)\mathbf x_\star=(0,1,0,0,0,0). The boat should lie parallel to the quay with its center one metre from the edge. The angled approach starts from (−8,5,−0.5,0.2,−0.1,0)(-8,5,-0.5,0.2,-0.1,0). The sideways-drift case changes only vyv_y to −0.5 m/s-0.5\ \mathrm{m/s}. Angles are in radians. Both experiments use T−1=200T-1=200 piecewise-constant controls, each held for h=0.1 sh=0.1\ \mathrm s, for a total of 20 seconds. Thus x1\mathbf x_1 is the initial state and xT\mathbf x_T is the arrival state, as in the preceding chapters. One fourth-order Runge--Kutta step gives xt+1=ft(xt,ut)\mathbf x_{t+1}=\mathbf f_t(\mathbf x_t,\mathbf u_t) for t=1,…,T−1t=1,\ldots,T-1.

To discourage the hull from approaching the quay, let yj(x)y_j(\mathbf x) be the world-coordinate height of rectangular corner jj. With a desired buffer a=0.2 ma=0.2\ \mathrm m and smoothing length s=0.08 ms=0.08\ \mathrm m, define

ρ(z)=slog⁡(1+exp⁡(z/s)),P(x)=200∑j=14ρ(a−yj(x))2.\rho(z)=s\log(1+\exp(z/s)),\qquad \mathcal P(\mathbf x)=200\sum_{j=1}^4\rho(a-y_j(\mathbf x))^2.

This is a smooth penalty for violating the buffer. Its finite weight permits violations, so the final trajectories will also undergo a separate geometric clearance check. The full rectangle is used for that check, including the area outside the pointed boat icon in the figures.

For ep=p−(0,1)⊤\mathbf e_p=\mathbf p-(0,1)^\top, the running and terminal costs are

ct(x,u)=h[0.03∥ep∥2+0.1(1−cos⁡ψ)+0.1∥v∥2+0.1ω2+0.2∥u∥2+P(x)],cT(x)=300∥ep∥2+100(1−cos⁡ψ)+200∥v∥2+100ω2+P(x).\begin{aligned} c_t(\mathbf x,\mathbf u) &=h\big[0.03\|\mathbf e_p\|^2+0.1(1-\cos\psi) +0.1\|\mathbf v\|^2+0.1\omega^2 +0.2\|\mathbf u\|^2+\mathcal P(\mathbf x)\big],\\ c_T(\mathbf x) &=300\|\mathbf e_p\|^2+100(1-\cos\psi) +200\|\mathbf v\|^2+100\omega^2+\mathcal P(\mathbf x). \end{aligned}

These numerical weights apply to the stated SI coordinates and dimensionless thrust commands. The periodic heading penalty assigns the same cost to angles that differ by a full turn. The simulator retains an unwrapped angle; it does not insert a discontinuity at ±π\pm\pi into the differentiated transition.

The initial control sequence is zero, so the boat coasts and slows under drag. It stops far from the berth. Successive control updates can first bring it closer and then adjust the arrival heading and velocity.

Accepted iLQR iterates for the angled approach. Every curve is a nonlinear
rollout from the same initial state. Boat outlines are spaced four seconds
apart; their overlap indicates slow motion. The dotted outline marks the
desired berth. The first update reduces the position error substantially,
while later updates refine the turn and stopping maneuver.

Figure 1:Accepted iLQR iterates for the angled approach. Every curve is a nonlinear rollout from the same initial state. Boat outlines are spaced four seconds apart; their overlap indicates slow motion. The dotted outline marks the desired berth. The first update reduces the position error substantially, while later updates refine the turn and stopping maneuver.

Taylor Models of Dynamics and Cost

The local model describes the change in cost caused by a small change in the thrust sequence. Start from the finite-horizon problem

min⁡UJ(U):=cT(xT)+∑t=1T−1ct(xt,ut),s.t.xt+1=ft(xt,ut),t=1,…,T−1,x1=xinit.\begin{aligned} \min_{\mathbf U}\quad &J(\mathbf U) :=c_T(\mathbf x_T)+\sum_{t=1}^{T-1}c_t(\mathbf x_t,\mathbf u_t),\\ \text{s.t.}\quad &\mathbf x_{t+1}=\mathbf f_t(\mathbf x_t,\mathbf u_t), \quad t=1,\ldots,T-1,\\ &\mathbf x_1=\mathbf x_{\mathrm{init}}. \end{aligned}

Here U=(u1,…,uT−1)\mathbf U=(\mathbf u_1,\ldots,\mathbf u_{T-1}) is the complete control sequence. Its rollout determines every later state.

Set aside the control bounds while deriving the local correction. Roll out a nominal control sequence Uˉ\bar{\mathbf U} to obtain states satisfying xˉt+1=ft(xˉt,uˉt)\bar{\mathbf x}_{t+1}=\mathbf f_t(\bar{\mathbf x}_t,\bar{\mathbf u}_t). For a nearby trajectory, write δxt=xt−xˉt\delta\mathbf x_t=\mathbf x_t-\bar{\mathbf x}_t and δut=ut−uˉt\delta\mathbf u_t=\mathbf u_t-\bar{\mathbf u}_t, and stack them as δzt=(δxt,δut)\delta\mathbf z_t=(\delta\mathbf x_t,\delta\mathbf u_t). Taylor expansion of the discrete transition at the nominal state and control gives

ft(xˉt+δxt,uˉt+δut)=xˉt+1+Atδxt+Btδut+O(∥δzt∥2),At=∂ft∂x∣(xˉt,uˉt),Bt=∂ft∂u∣(xˉt,uˉt).\begin{aligned} \mathbf f_t(\bar{\mathbf x}_t+\delta\mathbf x_t, \bar{\mathbf u}_t+\delta\mathbf u_t) &=\bar{\mathbf x}_{t+1} +A_t\delta\mathbf x_t+B_t\delta\mathbf u_t +O(\|\delta\mathbf z_t\|^2),\\ A_t&=\left.\frac{\partial\mathbf f_t}{\partial\mathbf x} \right|_{(\bar{\mathbf x}_t,\bar{\mathbf u}_t)},\\ B_t&=\left.\frac{\partial\mathbf f_t}{\partial\mathbf u} \right|_{(\bar{\mathbf x}_t,\bar{\mathbf u}_t)}. \end{aligned}

Subtracting xˉt+1\bar{\mathbf x}_{t+1} and dropping the quadratic remainder gives the linearized dynamics δxt+1=Atδxt+Btδut\delta\mathbf x_{t+1}=A_t\delta\mathbf x_t+B_t\delta\mathbf u_t. Both rollouts start from the same state, so δx1=0\delta\mathbf x_1=\mathbf0. There is no constant defect because the nominal trajectory satisfies the discrete dynamics. Independently chosen state guesses would generally leave such a defect. We write Ft=[At Bt]F_t=[A_t\ B_t] for the combined Jacobian.

Taylor expansion of the running cost to second order gives

ct(xˉt+δxt,uˉt+δut)=cˉt+[cx,tcu,t] ⁣⊤δzt+12δzt⊤[cxx,tcxu,tcux,tcuu,t]δzt+o(∥δzt∥2).c_t(\bar{\mathbf x}_t+\delta\mathbf x_t, \bar{\mathbf u}_t+\delta\mathbf u_t) = \bar c_t+ \begin{bmatrix}c_{x,t}\\c_{u,t}\end{bmatrix}^{\!\top}\delta\mathbf z_t +\frac12\delta\mathbf z_t^\top \begin{bmatrix}c_{xx,t}&c_{xu,t}\\c_{ux,t}&c_{uu,t}\end{bmatrix} \delta\mathbf z_t+o(\|\delta\mathbf z_t\|^2).

Here cˉt=ct(xˉt,uˉt)\bar c_t=c_t(\bar{\mathbf x}_t,\bar{\mathbf u}_t) and cx,t=∇xct(xˉt,uˉt)c_{x,t}=\nabla_{\mathbf x}c_t(\bar{\mathbf x}_t,\bar{\mathbf u}_t); the other gradient and Hessian blocks are evaluated at the same nominal pair. We denote the stacked gradient by cz,tc_{z,t} and the displayed block Hessian by czz,tc_{zz,t}. Gradients are column vectors, matching the convention of the preceding chapters. We retain the linear terms: individual stage gradients need not vanish even at an optimal trajectory because the dynamics couple stages, and at a non-optimal nominal trajectory they also drive its correction. The cxu,tc_{xu,t} block measures how the marginal cost of a control changes with the state. Even if the running cost has no such cross term, eliminating later controls can create one in the quadratic tail.

The terminal cost has the same expansion, with no control coordinate:

cT(xˉT+δxT)=cT(xˉT)+pT⊤δxT+12δxT⊤PTδxT+o(∥δxT∥2),pT=∇xcT(xˉT),PT=∇xx2cT(xˉT).\begin{aligned} c_T(\bar{\mathbf x}_T+\delta\mathbf x_T) &=c_T(\bar{\mathbf x}_T)+p_T^\top\delta\mathbf x_T\\ &\quad+\frac12\delta\mathbf x_T^\top P_T\delta\mathbf x_T +o(\|\delta\mathbf x_T\|^2),\\ p_T&=\nabla_{\mathbf x}c_T(\bar{\mathbf x}_T),\qquad P_T=\nabla^2_{\mathbf x\mathbf x}c_T(\bar{\mathbf x}_T). \end{aligned}

Dropping the remainders in these Taylor expansions yields a quadratic cost subject to linearized transitions. The state at one step couples only to its neighbors. This is the local problem solved by backward elimination. A general SQP method also forms local quadratic subproblems, but its exact Lagrangian Hessian includes terms from dynamics curvature. Those terms enter below when we develop DDP.

Backward Elimination

The last control affects only its own stage and the terminal state when its starting state is fixed. Eliminating it first leaves a shorter quadratic problem of the same form. Repeating that step works backward through the horizon.

A two-step calculation

Consider a scalar example with T=3T=3, initial state x1=0x_1=0, dynamics xt+1=xt+utx_{t+1}=x_t+u_t, and cost

J=12u12+12u22+12(x3−1)2.J=\frac12u_1^2+\frac12u_2^2+\frac12(x_3-1)^2.

Treat x2x_2 as given while eliminating u2u_2. Substitution of x3=x2+u2x_3=x_2+u_2 gives

12u22+12(x2+u2−1)2=u22+(x2−1)u2+12(x2−1)2.\frac12u_2^2+\frac12(x_2+u_2-1)^2 =u_2^2+(x_2-1)u_2+\frac12(x_2-1)^2.

Differentiating with respect to u2u_2 gives 2u2+x2−1=02u_2+x_2-1=0, so u2=(1−x2)/2u_2=(1-x_2)/2. Substituting this expression back into the last two terms of the cost leaves (x2−1)2/4(x_2-1)^2/4. Since x2=u1x_2=u_1, the remaining problem is

min⁡u1 12u12+14(u1−1)2.\min_{u_1}\ \frac12u_1^2+\frac14(u_1-1)^2.

Its derivative is u1+(u1−1)/2u_1+(u_1-1)/2, giving u1=1/3u_1=1/3. Forward substitution then gives x2=1/3x_2=1/3, u2=1/3u_2=1/3, x3=2/3x_3=2/3, and J=1/6J=1/6. The final position is short of one because the objective trades terminal error against effort; arrival was penalized, not imposed as an equality.

The expression u2=(1−x2)/2u_2=(1-x_2)/2 also carries information that a single number would discard: if the state reaching the last step changes, the minimizing last control changes with it. This dependence becomes the matrix feedback correction in the general calculation.

Eliminating a vector control

Suppose all controls after time tt have already been eliminated from the local problem. Write the remaining quadratic tail as

St+1(δxt+1)=st+1+pt+1⊤δxt+1+12δxt+1⊤Pt+1δxt+1.S_{t+1}(\delta\mathbf x_{t+1}) =s_{t+1}+p_{t+1}^\top\delta\mathbf x_{t+1} +\frac12\delta\mathbf x_{t+1}^\top P_{t+1}\delta\mathbf x_{t+1}.

At the terminal step, STS_T is the quadratic Taylor polynomial of cTc_T, so sT=cT(xˉT)s_T=c_T(\bar{\mathbf x}_T) and its other coefficients are the pT,PTp_T,P_T defined above. At earlier steps, St+1S_{t+1} is obtained by elimination from a finite optimization problem. This construction does not require a function over all states of the nonlinear system.

Substitute δxt+1=Atδxt+Btδut\delta\mathbf x_{t+1}=A_t\delta\mathbf x_t+B_t\delta\mathbf u_t into this tail and add the stage cost. With Ft=[At Bt]F_t=[A_t\ B_t], the new linear and quadratic coefficients are

qt=cz,t+Ft⊤pt+1,Mt=czz,t+Ft⊤Pt+1Ft.q_t=c_{z,t}+F_t^\top p_{t+1},\qquad M_t=c_{zz,t}+F_t^\top P_{t+1}F_t.

We use MtM_t for the local Hessian because HtH_t denoted the Hamiltonian in the Pontryagin chapter. Partition qtq_t and MtM_t according to the state and control coordinates. Apart from a constant, the expression to minimize is

qx⊤δx+qu⊤δu+12δx⊤Mxxδx+δu⊤Muxδx+12δu⊤Muuδu.q_x^\top\delta\mathbf x+q_u^\top\delta\mathbf u +\frac12\delta\mathbf x^\top M_{xx}\delta\mathbf x +\delta\mathbf u^\top M_{ux}\delta\mathbf x +\frac12\delta\mathbf u^\top M_{uu}\delta\mathbf u.

The time index is suppressed within this one-step calculation. When MuuM_{uu} is positive definite, setting the control derivative to zero gives

Muuδu+qu+Muxδx=0,δu=k+Kδx,M_{uu}\delta\mathbf u+q_u+M_{ux}\delta\mathbf x=0, \qquad \delta\mathbf u=k+K\delta\mathbf x,

where

k=−Muu−1qu,K=−Muu−1Mux.k=-M_{uu}^{-1}q_u,\qquad K=-M_{uu}^{-1}M_{ux}.

Restoring the time index gives the affine correction δut=kt+Ktδxt\delta\mathbf u_t=k_t+K_t\delta\mathbf x_t. The vector kk changes the nominal command even at zero state deviation. The matrix KK adjusts that change for a different state arriving from the earlier steps. In code, these formulas are linear solves with MuuM_{uu}; an explicit matrix inverse is unnecessary.

Substituting the minimizing control back into the quadratic expression gives the coefficients needed by the preceding step:

pt=qx−Mux⊤Muu−1qu,Pt=Mxx−Mux⊤Muu−1Mux.\begin{aligned} p_t&=q_x-M_{ux}^\top M_{uu}^{-1}q_u,\\ P_t&=M_{xx}-M_{ux}^\top M_{uu}^{-1}M_{ux}. \end{aligned}

The subtracted term in PtP_t is the Schur complement associated with eliminating the control block. Repeat this operation from T−1T-1 to one, starting with the terminal coefficients. A subsequent forward substitution recovers the state and control changes. For fixed state and control dimensions, the number of these elimination steps grows linearly with the horizon.

For linear dynamics and quadratic costs, this procedure solves the original unconstrained problem exactly when its control minimizations are well posed. That problem is called the linear-quadratic regulator problem, and the matrix recursion for PtP_t is a Riccati recursion. Along a nonlinear trajectory, AtA_t, BtB_t, and the cost derivatives describe only a local approximation. They must be recomputed after the trajectory changes.

Nonlinear Rollouts and iLQR

The backward pass minimizes a quadratic approximation. A large correction can make its linearized state prediction inaccurate, so a proposed control sequence must be evaluated through the original discrete simulator before it is accepted.

Starting from the same initial state, form a nonlinear trial trajectory using

x1+=xinit,ut+=uˉt+αkt+Kt(xt+−xˉt),xt+1+=ft(xt+,ut+).\begin{aligned} \mathbf x_1^+&=\mathbf x_{\mathrm{init}},\\ \mathbf u_t^+&=\bar{\mathbf u}_t+\alpha k_t +K_t(\mathbf x_t^+-\bar{\mathbf x}_t),\\ \mathbf x_{t+1}^+&=\mathbf f_t(\mathbf x_t^+,\mathbf u_t^+). \end{aligned}

The step size α\alpha scales the feedforward change. The feedback term responds to the state deviation that actually occurs during this trial. Its gain is not multiplied by α\alpha. At α=0\alpha=0, induction through these equations recovers the nominal trajectory, because each state deviation is then zero. For an exact linear-quadratic problem, α=1\alpha=1 gives the complete solution derived by elimination.

A line search first tries α=1\alpha=1, then successively smaller values. Each trial has its own nonlinear states and cost. The implementation uses 1,1/2,…,2−111,1/2,\ldots,2^{-11} and accepts a strictly lower finite cost with a small sufficient-decrease check. If

d1=∑t=1T−1qu,t⊤kt,d2=12∑t=1T−1kt⊤Muu,tkt,d_1=\sum_{t=1}^{T-1}q_{u,t}^\top k_t,\qquad d_2=\frac12\sum_{t=1}^{T-1}k_t^\top M_{uu,t}k_t,

the backward pass estimates a reduction Δ^J(α)=−αd1−α2d2\widehat\Delta J(\alpha)=-\alpha d_1-\alpha^2d_2. Acceptance requires J(Uˉ)−J(U+)≥10−4max⁡(Δ^J(α),0)J(\bar{\mathbf U})-J(\mathbf U^+)\geq10^{-4}\max(\widehat\Delta J(\alpha),0) as well as a strict decrease. This estimate guides acceptance; it does not replace evaluation of the original objective.

The control curvature may be indefinite or nearly singular. Replace the matrix used in the control solve by Muu+μIM_{uu}+\mu I, where μ>0\mu>0. Increasing μ\mu makes the correction more conservative and can make the solve positive definite. The code checks a Cholesky factorization, increases μ\mu after a failed backward pass or line search, and decreases it after an accepted step. The numerical defaults start at 10-4, multiply by ten after failure, and divide by three after acceptance, with a floor of 10-9.

When regularization changes kk and KK, the simplified Schur-complement formulas above no longer describe substitution into the original quadratic model. The implementation therefore uses the full expressions

pt=qx+Mux⊤k+K⊤qu+K⊤Muuk,Pt=Mxx+Mux⊤K+K⊤Mux+K⊤MuuK.\begin{aligned} p_t&=q_x+M_{ux}^\top k+K^\top q_u+K^\top M_{uu}k,\\ P_t&=M_{xx}+M_{ux}^\top K+K^\top M_{ux}+K^\top M_{uu}K. \end{aligned}

Here MuuM_{uu} is the original curvature block; regularization was used to choose the correction. These expressions also remain applicable when some controls are fixed at their bounds.

Alternating local linear-quadratic approximation, backward elimination, and nonlinear rollout gives iLQR Li & Todorov, 2004. The iteration uses second derivatives of the costs but only first derivatives of the dynamics. It is often described as a Gauss--Newton approximation to DDP. That terminology should not obscure what is approximated: the omitted terms come from dynamics curvature. If a nonlinear cost is itself a sum of squared residuals, replacing its Hessian by a residual-Jacobian product would be a further approximation; the docking code uses the exact cost Hessian.

The returned gains describe a neighborhood of the final nominal trajectory. The docking animation below executes one stored plan. The gains used inside the optimizer do not imply that the animation replans as the boat moves.

Dynamics Curvature and DDP

iLQR drops the quadratic remainder in the transition’s first-order Taylor expansion. For a turning boat, a change in heading changes the direction of thrust, so products of state and control changes can affect the next state. DDP retains these second-order terms in the backward calculation.

For component ii of the transition, Taylor expansion one order further gives

δxt+1,i=(Ftδzt)i+12δzt⊤fzz,tiδzt+o(∥δzt∥2).\delta x_{t+1,i} =(F_t\delta\mathbf z_t)_i +\frac12\delta\mathbf z_t^\top f^i_{zz,t}\delta\mathbf z_t +o(\|\delta\mathbf z_t\|^2).

Here fzz,tif^i_{zz,t} is the Hessian of the iith component of ft\mathbf f_t with respect to the stacked state and control, evaluated at the nominal pair. Substitute this expression into the same quadratic tail St+1S_{t+1}. Its linear term pt+1⊤δxt+1p_{t+1}^\top\delta\mathbf x_{t+1} now contributes an additional quadratic term. Its quadratic term contributes 12δzt⊤Ft⊤Pt+1Ftδzt\tfrac12\delta\mathbf z_t^\top F_t^\top P_{t+1}F_t\delta\mathbf z_t; products involving the second-order part of the transition there are of order three or higher and are discarded. Consequently,

qtDDP=cz,t+Ft⊤pt+1,MtDDP=czz,t+Ft⊤Pt+1Ft+∑i=1nxpt+1,ifzz,ti.\begin{aligned} q_t^{\mathrm{DDP}}&=c_{z,t}+F_t^\top p_{t+1},\\ M_t^{\mathrm{DDP}}&=c_{zz,t}+F_t^\top P_{t+1}F_t +\sum_{i=1}^{n_x}p_{t+1,i}f^i_{zz,t}. \end{aligned}

The extra contraction weights curvature of each next-state component by its linear coefficient in the eliminated tail. At a given backward stage, this is the second-order chain rule for composing the transition with that tail. In block form, the differences from iLQR are

Mxx,tDDP=cxx,t+At⊤Pt+1At+∑ipt+1,ifxx,ti,Mux,tDDP=cux,t+Bt⊤Pt+1At+∑ipt+1,ifux,ti,Muu,tDDP=cuu,t+Bt⊤Pt+1Bt+∑ipt+1,ifuu,ti.\begin{aligned} M_{xx,t}^{\mathrm{DDP}}&=c_{xx,t}+A_t^\top P_{t+1}A_t +\sum_i p_{t+1,i} f^i_{xx,t},\\ M_{ux,t}^{\mathrm{DDP}}&=c_{ux,t}+B_t^\top P_{t+1}A_t +\sum_i p_{t+1,i} f^i_{ux,t},\\ M_{uu,t}^{\mathrm{DDP}}&=c_{uu,t}+B_t^\top P_{t+1}B_t +\sum_i p_{t+1,i} f^i_{uu,t}. \end{aligned}

Setting those three sums to zero recovers the iLQR construction. Retaining them and using the same quadratic elimination and nonlinear line search gives DDP Tassa et al., 2014. The two methods share an algorithmic structure; the curvature choice can change both the direction of a step and the amount of regularization needed to accept it. This derivation does not require solving a subproblem with quadratic dynamics constraints.

For the boat, even the continuous acceleration contains a state--control cross derivative: ∂2v˙x/(∂ψ ∂uL)=−(Fmax⁡/m)sin⁡ψ\partial^2\dot v_x/(\partial\psi\,\partial u_L) =-(F_{\max}/m)\sin\psi. The discrete derivatives used by the solver also include how heading and velocity change within the RK4 step. Automatic differentiation is applied through that complete step. A differential equation that is affine in its controls need not yield a numerical transition whose second control derivatives vanish.

The extra curvature costs computation and can be indefinite. DDP therefore still needs regularization and nonlinear acceptance tests. Neither method guarantees the globally best docking maneuver. For affine dynamics the transition Hessians are zero, so the two backward constructions coincide when all other choices agree.

Thruster Limits and Stopping Criteria

The boat’s controls must remain in [−1,1]2[-1,1]^2, even when the unconstrained correction asks for more thrust. At zero state deviation, the feedforward step is the solution of the box-constrained quadratic problem

min⁡k qu⊤k+12k⊤(Muu+μI)k,−1−uˉt≤k≤1−uˉt.\min_k\ q_u^\top k+\frac12k^\top(M_{uu}+\mu I)k, \qquad -\mathbf1-\bar{\mathbf u}_t\leq k\leq\mathbf1-\bar{\mathbf u}_t.

For two controls, each coordinate is either free, fixed at its lower bound, or fixed at its upper bound. The teaching implementation checks the nine combinations, minimizes over each face, and keeps the best feasible candidate. Positive-definite curvature makes this a strictly convex QP. Larger systems can use an active-set solver rather than enumerate all combinations Tassa et al., 2014.

The feedback rows of saturated controls are zero while their active set stays fixed. For the free coordinates F\mathcal F, solve (Muu+μI)FFKF=−(Mux)F(M_{uu}+\mu I)_{\mathcal F\mathcal F}K_{\mathcal F} =-(M_{ux})_{\mathcal F}. Use the full substitution formulas to update the quadratic tail. With bounds, this tail describes a neighborhood with the selected active sets; across active-set changes the minimized expression is generally piecewise quadratic. During the nonlinear trial, project the resulting control onto its box before simulation. This enforces the physical bounds when a trial leaves the neighborhood represented by the backward pass. The nonlinear cost check then decides whether that trial should be retained.

The stopping test is separate from docking success. Let g=∇UJg=\nabla_{\mathbf U}J be the gradient of the original shooting objective, computed by the adjoint recursion along the current nonlinear rollout. With normalized controls, the solver stops when

∥U−clip⁡(U−g,−1,1)∥∞≤10−5.\left\|\mathbf U-\operatorname{clip}(\mathbf U-g,-1,1)\right\|_\infty \leq10^{-5}.

At an interior optimum this reduces to a small control gradient. At a bound it also allows a gradient that points toward a forbidden improvement. The experiment permits at most 120 accepted updates. If regularization exceeds 1012 without an acceptable trial, the solver retains its last accepted trajectory and reports failure to make progress. A small residual certifies approximate first-order stationarity, not a globally optimal path or a successful arrival.

Docking Trajectories and Recorded Futures

Do the two curvature choices produce the same maneuver from the same starting plan? Both methods receive the coasting initialization, identical costs and control limits, and the same stopping settings. The following tables report their final nonlinear costs and arrival checks. Each final control sequence is also replayed with four RK4 substeps per control interval, giving a 0.025 s0.025\ \mathrm s validation grid.

ApproachMethodCostAccepted updates
Angled approachiLQR8.051518
Angled approachDDP11.987934
Sideways driftiLQR7.667413
Sideways driftDDP7.667445

The arrival checks below use the finer replay.

ApproachMethodPosition error (m)Heading error (°)Speed (m/s)Clearance (m)
Angled approachiLQR0.0001258.98e-056.89e-050.599
Angled approachDDP0.001250.1390.01440.352
Sideways driftiLQR3.89e-052.65e-064.25e-050.600
Sideways driftDDP3.89e-053.71e-064.25e-050.600

All four runs satisfy the stopping test and the docking checks: position error below 0.2 m0.2\ \mathrm m, heading error below 3∘3^\circ, speed below 0.05 m/s0.05\ \mathrm{m/s}, angular speed below 1∘/s1^\circ/\mathrm s, bounded thrust, and positive hull clearance. The maximum position difference between the planning trajectory and the finer replay is below 10−6 m10^{-6}\ \mathrm m in these runs. Clearance is checked on the finer grid; this remains a sampled validation, not a proof of continuous-time collision avoidance.

Final trajectories under the same initialization and objective. Solid blue
is iLQR and dashed orange is DDP; the dotted gray path is the initial coast.
Outlines show orientation every four seconds. DDP takes a different turning
maneuver in the angled approach. The two final paths nearly coincide in the
sideways-drift case.

Figure 2:Final trajectories under the same initialization and objective. Solid blue is iLQR and dashed orange is DDP; the dotted gray path is the initial coast. Outlines show orientation every four seconds. DDP takes a different turning maneuver in the angled approach. The two final paths nearly coincide in the sideways-drift case.

In the angled approach, iLQR reaches cost 8.0515 in 18 accepted updates, while DDP reaches a different stationary trajectory with cost 11.9879 in 34 updates. The DDP trajectory makes two full turns near the berth. Its final unwrapped heading is approximately 720∘720^\circ, which the periodic heading cost treats as the same orientation as zero. Reaching this stationary trajectory does not remove the extra motion accumulated on the way there. In the sideways-drift case, both reach cost 7.6674, with 13 accepted updates for iLQR and 45 for DDP. These are outcomes of two particular local solves, not a general ranking of the algorithms. The difference in the first case also shows why comparing iteration counts alone can hide a difference in the solutions obtained.

Actual nonlinear cost at every accepted iteration, including the initial
rollout at iteration zero. The vertical axis is logarithmic. Rejected trial
steps are excluded from the horizontal count; forward-evaluation and
backward-attempt counts are available in the downloadable diagnostics.

Figure 3:Actual nonlinear cost at every accepted iteration, including the initial rollout at iteration zero. The vertical axis is logarithmic. Rejected trial steps are excluded from the horizontal count; forward-evaluation and backward-attempt counts are available in the downloadable diagnostics.

Within one selected plan, simulation time has a different meaning from optimizer iteration. At two seconds, for example, the boat occupies the two-second state of that rollout. Its remaining states give a prediction of where it will go if the rest of the stored controls are applied. Outlines spaced equally in time spread apart while the boat is moving quickly and cluster as it comes to rest. Reverse thrust helps remove momentum before arrival.

The final iLQR plan for the angled approach. The filled boat marks the selected
simulation time; translucent outlines show future poses every two seconds.
The right panel gives speed and both physical thrusts. Negative thrust during
the approach brakes the boat. The vertical marker identifies the same time
as the filled boat.

Figure 4:The final iLQR plan for the angled approach. The filled boat marks the selected simulation time; translucent outlines show future poses every two seconds. The right panel gives speed and both physical thrusts. Negative thrust during the approach brakes the boat. The vertical marker identifies the same time as the filled boat.

Choose a scenario and optimizer iteration, then scrub or play simulation time within that fixed plan. The path ahead and boat outlines display its remaining predicted states. Arrival errors and plots belong to the selected iteration, including intermediate plans that do not dock successfully.

The replay reads recorded simulations, so exploring it does not rerun an optimizer. Recomputing a plan from newly observed states is the additional step introduced in receding-horizon control.

Pulling Down a Thermoacoustic Refrigerator

A standing-wave thermoacoustic refrigerator has a loudspeaker at one end of a sealed tube and a stack of thin plates inside it. Oscillating gas parcels exchange heat with the plates as they compress and expand, carrying heat from the cold end of the stack toward the hot end. Heat exchangers connect those ends to a payload and to ambient air. How should the loudspeaker amplitude vary when acoustic energy and the payload temperature at a fixed deadline both matter?

We represent the cold payload and hot exchanger by two lumped temperatures, xt=(Tc,t,Th,t)\mathbf x_t=(T_{c,t},T_{h,t}), and control the normalized driver amplitude ut∈[0,1]u_t\in[0,1]. Let ΔT=Th−Tc\Delta T=T_h-T_c and η(ΔT)=1−ΔT/ΔT0\eta(\Delta T)=1-\Delta T/\Delta T_0. The continuous model is

Q˙c=kqu2η(ΔT),W˙=kwu2η(ΔT)+kvu2+k3u3,CcT˙c=−Q˙c+Qload,ChT˙h=Q˙c+W˙−UA(Th−Tamb).\begin{aligned} \dot Q_c &= k_q u^2\eta(\Delta T),& \dot W &= k_w u^2\eta(\Delta T)+k_vu^2+k_3u^3,\\ C_c\dot T_c &= -\dot Q_c+Q_{\mathrm{load}},& C_h\dot T_h &= \dot Q_c+\dot W-UA(T_h-T_{\mathrm{amb}}). \end{aligned}

Here Q˙c\dot Q_c is heat removed from the cold side, W˙\dot W is work supplied by the driver, and UAUA is the hot exchanger’s conductance to ambient. At positive work, the cooling coefficient of performance (COP) is Q˙c/W˙\dot Q_c/\dot W. The short-stack approximation motivates the u2u^2 terms and their dependence on the temperature span Swift, 1988Swift, 2017. The cubic term represents an additional loss at high amplitude. These coefficients are synthetic teaching values, not measurements of a particular device.

QuantityValue
Cold and hot heat capacities Cc,ChC_c,C_h20,50 J/K20,50\ \mathrm{J/K}
Hot conductance UAUA0.5 W/K0.5\ \mathrm{W/K}
Ambient temperature TambT_{\mathrm{amb}}20 ∘C20\ ^\circ\mathrm C
Parasitic cold-side load QloadQ_{\mathrm{load}}1 W1\ \mathrm W
Pumping coefficient kqk_q5 W5\ \mathrm W
Work and viscous coefficients kw,kvk_w,k_v4,1 W4,1\ \mathrm W
Cubic-loss coefficient k3k_32 W2\ \mathrm W
Critical temperature span ΔT0\Delta T_040 K40\ \mathrm K
Target temperature T⋆T^\star5 ∘C5\ ^\circ\mathrm C

Both temperatures begin at 20 ∘C20\ ^\circ\mathrm C. A fourth-order Runge--Kutta step of length h=1 sh=1\ \mathrm s defines the discrete transition xt+1=ft(xt,ut)\mathbf x_{t+1}=\mathbf f_t(\mathbf x_t,u_t) for T−1=300T-1=300 control intervals. The cost uses the same running-plus-terminal form as the docking problem:

ct(xt,ut)=h wEW˙(xt,ut),cT(xT)=wT(Tc,T−T⋆)2,wE=0.05,wT=10.c_t(\mathbf x_t,u_t)=h\,w_E\dot W(\mathbf x_t,u_t),\qquad c_T(\mathbf x_T)=w_T(T_{c,T}-T^\star)^2, \qquad w_E=0.05,\quad w_T=10.

There is no running temperature-tracking term: the target applies at the end of the five-minute pull-down, while the running cost measures energy use. The terminal penalty is soft, so a plan can trade some arrival error for lower energy. Both methods start from the constant sequence ut=0.5u_t=0.5 and use the same control box and stopping settings.

ExperimentMethodStatusAccepted updatesCostEnergy (J)Cold at 300 s (°C)
Baseline pull-downiLQRconverged2451.22410165.20
Baseline pull-downDDPconverged1251.22410165.20
No parasitic loadiLQRconverged2820.6524115.09
No parasitic loadDDPconverged820.6524115.09
Sluggish hot sideiLQRconverged2845.7169115.13
Sluggish hot sideDDPconverged1445.5859085.13
Amplitude-independent COPiLQRiteration_limit20033.3536665.08
Amplitude-independent COPDDPconverged2733.3536665.08
Target out of reach in 300 siLQRconverged2119.58214262.20
Target out of reach in 300 sDDPconverged10119.58214262.20

Costs are evaluated on the final accepted nonlinear trajectory. The iteration-limit row is a retained local plan, not a converged solve.

For comparison, constant full amplitude in the baseline case ends at 2.20 °C, uses 1426 J, and has cost 149.89.

Cold and hot temperatures under the baseline plan, with a constant
full-amplitude rollout for comparison. The lower panel shows their driver
amplitudes. The target line and temperature traces show the tradeoff between
energy use and final cold temperature.

Figure 6:Cold and hot temperatures under the baseline plan, with a constant full-amplitude rollout for comparison. The lower panel shows their driver amplitudes. The target line and temperature traces show the tradeoff between energy use and final cold temperature.

The baseline plan drives relatively hard at first, eases off, then ramps to full amplitude near the deadline. Early driving uses the initially small temperature span, but it also warms the hot side and weakens later pumping. The fixed load adds the same total heat over every 300-second plan. Control timing still changes the temperature span and therefore the final cold temperature. Running at full amplitude throughout uses about 1426 J1426\ \mathrm J and reaches 2.20 ∘C2.20\ ^\circ\mathrm C; its nonlinear cost is 149.886, versus 51.224 for the baseline local plan. The soft terminal cost need not favor the coldest possible final state.

Final computed amplitude schedules for the baseline, no-load,
sluggish-hot-side, and no-cubic-loss cases. The first three are iLQR plans;
the no-cubic-loss plan is from DDP. Removing the cold-side load flattens the
schedule, while changing the hot-side dynamics produces a long ramp.

Figure 7:Final computed amplitude schedules for the baseline, no-load, sluggish-hot-side, and no-cubic-loss cases. The first three are iLQR plans; the no-cubic-loss plan is from DDP. Removing the cold-side load flattens the schedule, while changing the hot-side dynamics produces a long ramp.

Without the parasitic load, a nearly constant amplitude is economical. To see the tendency, temporarily hold the temperature span fixed and write v=u2v=u^2. Heat pumped is then proportional to vv, while the cubic loss is proportional to v3/2v^{3/2}, a convex function for v≥0v\geq0. For a fixed total amount of pumping, Jensen’s inequality favors spreading vv through time. The actual schedule is not exactly constant because the span and hot-side temperature still respond to the controls. With Ch=200 J/KC_h=200\ \mathrm{J/K} and UA=0.2 W/KUA=0.2\ \mathrm{W/K}, the amplitude rises through most of the horizon, then turns off for the final two intervals. Both thermal storage and heat rejection changed in that experiment, so it does not isolate the effect of either parameter.

The DDP curvature term also has a direct physical interpretation here. For the continuous cold-side equation,

∂2T˙c∂u ∂ΔT=2kquCcΔT0.\frac{\partial^2\dot T_c}{\partial u\,\partial\Delta T} =\frac{2k_qu}{C_c\Delta T_0}.

Increasing the temperature span weakens pumping, and this mixed derivative measures how that effect changes with amplitude. The solver differentiates the complete RK4 transition, whose Hessian also contains effects from the intermediate integration stages.

Actual nonlinear cost after each accepted update for iLQR and DDP in the
baseline and no-cubic-loss cases. The vertical axis is logarithmic. The
curves compare these local solves from the same initial control sequence,
not a general ranking of the methods.

Figure 8:Actual nonlinear cost after each accepted update for iLQR and DDP in the baseline and no-cubic-loss cases. The vertical axis is logarithmic. The curves compare these local solves from the same initial control sequence, not a general ranking of the methods.

When k3=0k_3=0, both pumping and work are quadratic in amplitude at a fixed temperature span. Their instantaneous ratio then no longer depends on amplitude, leaving weaker preferences among some schedules. In the recorded run, iLQR reaches its iteration limit while DDP satisfies the stopping test; both reach nearly the same final cost. For the sluggish hot side, DDP reaches a different, slightly lower-cost local plan than iLQR. Lowering the target to 0 ∘C0\ ^\circ\mathrm C produces a plan saturated at ut=1u_t=1 throughout the fixed horizon, exercising the box-constrained backward step. These outcomes depend on the initial sequence. Starting the baseline from constant amplitudes 0.1 and 0.9 leads to other local plans, so neither result certifies a global minimum.

Exercises

Computational Sources

The implementation separates the generic backward recursion from the physical models and artifact builders:

Run uv run python scripts/build_boat_docking_artifacts.py from the repository root to reproduce the solves, figures, results table, and browser data. Normal book builds read those artifacts. Tests independently check the derivatives, the composed DDP curvature, the scalar calculation, and agreement between backward elimination and a dense quadratic solve.

Run uv run python scripts/build_thermoacoustic_pulldown_artifacts.py to regenerate the refrigerator results table, figures, and diagnostics.

Summary and Outlook

A feasible nonlinear rollout supplies the point around which dynamics and costs are approximated. Backward elimination of a local quadratic problem then supplies both a feedforward change and a state-dependent correction. iLQR repeats that calculation with linearized dynamics; DDP includes the second-order chain-rule terms from the transition. Nonlinear rollouts, regularization, and acceptance tests connect these local calculations to a decreasing sequence of actual trajectory costs. The refrigerator applies the same calculation to a bounded driver amplitude, with energy use and terminal temperature competing in the objective.

The docking and refrigerator experiments both use discrete transitions obtained by integrating ordinary differential equations. Continuous-time transcription and collocation develops other ways to represent continuous trajectories inside a finite optimization problem. Later, finite-horizon dynamic programming gives a broader interpretation of the quadratic tail: in the linear-quadratic case, the function produced by elimination is the optimal cost-to-go.

References
  1. Li, W., & Todorov, E. (2004). Iterative Linear Quadratic Regulator Design for Nonlinear Biological Movement Systems. Proceedings of the First International Conference on Informatics in Control, Automation and Robotics, 1, 222–229. https://roboti.us/lab/papers/LiICINCO04.pdf
  2. Tassa, Y., Mansard, N., & Todorov, E. (2014). Control-Limited Differential Dynamic Programming. IEEE International Conference on Robotics and Automation, 1168–1175. 10.1109/ICRA.2014.6907001
  3. Swift, G. W. (1988). Thermoacoustic engines. The Journal of the Acoustical Society of America, 84(4), 1145–1180. 10.1121/1.396617
  4. Swift, G. W. (2017). Thermoacoustics: A Unifying Perspective for Some Engines and Refrigerators (2nd ed.). Springer Cham. 10.1007/978-3-319-66933-5