Algorithm Search⌘K

Algorithmresearch

Control-limited differential dynamic programming

Also called box-constrained DDP.

Tassa's differential dynamic programming that keeps the controls in a box by solving a small box-constrained quadratic program in each backward step.

Time
O(I N (n^3 + p m^3 + F)) worst
Space
O(N n m + n^2) extra
Where
F = the time to evaluate the dynamics and their Jacobians once; I = the number of iterations; N = the number of time steps; m = the control dimension; n = the state dimension; p = the number of iterations of the box solver per stage
Properties
deterministicnot exactofflinenot randomized

Differential dynamic programming (DDP) improves a control sequence for a nonlinear system by a backward pass and a forward pass. The backward pass builds a quadratic model of the cost-to-go at each time step, from the last step to the first, and gets from it a change of the control and a feedback gain; the forward pass simulates the system with the new controls. The control-limited version of Tassa, Mansard and Todorov keeps every control inside a box lo≤u≤hilo \le u \le hi. At each step of the backward pass it solves a small quadratic program with box constraints, and the feedback gain acts only on the controls that are not at a bound. The cost goes down at every accepted iteration and the controls stay in the box, but the method is local: it finds a solution near its start, with no guarantee of a global minimum.

In plain words

Imagine you drive a car along a planned route and want to improve the plan. Start at the end of the route and work backward: at each moment, ask how the remaining cost would change if you steered a little differently, and write down the best small correction together with a rule for how to react if the car is a bit off course. Then drive the route again with these corrections. Repeat until nothing improves. The control-limited version respects the limits of the car. If the best correction wants more steering than the wheel allows, it uses the full lock instead, and the reaction rule stops using that wheel, because it cannot turn any further. The result keeps every command within its limits and is a good plan near the first guess, not always the best plan overall.

The problem

Input: discrete dynamics xk+1=f(xk,uk)x_{k+1} = f(x_k, u_k) with a start x0∈Rnx_0 \in \mathbb R^n, a horizon of NN steps, a running cost ℓ(x,u)\ell(x, u) and a final cost ℓf(x)\ell_f(x), and bounds lo≤hilo \le hi in Rm\mathbb R^m. Output: controls u0,…,uN−1u_0, \dots, u_{N-1} with lo≤uk≤hilo \le u_k \le hi that make

J(U)=∑k=0N−1ℓ(xk,uk)+ℓf(xN)J(U) = \sum_{k=0}^{N-1} \ell(x_k, u_k) + \ell_f(x_N)

small. This is a trajectory optimization problem with box limits on the controls, such as torque limits of motors. Without the box and with linear dynamics and quadratic costs it is the LQR problem.

The code uses the quadratic cost ℓ(x,u)=12(x−g)TQ(x−g)+12uTRu\ell(x, u) = \frac12 (x - g)^{\mathsf T} Q (x - g) + \frac12 u^{\mathsf T} R u and ℓf(x)=12(x−g)TQf(x−g)\ell_f(x) = \frac12 (x - g)^{\mathsf T} Q_f (x - g). It uses only the first derivatives Ak=fxA_k = f_x and Bk=fuB_k = f_u of the dynamics, the Gauss-Newton form that is often called iLQR; the full second-order form adds terms with second derivatives of ff to the quadratic model, and the handling of the box is the same.

The algorithm

  1. CONTROL-LIMITED-DDP(x_0, U, lo, hi)
  2. 1X ← simulate U from x_0; μ ← 0
  3. 2repeat
  4. 3V_x ← ∇ℓ_f(x_N); V_xx ← ∇²ℓ_f(x_N)
  5. 4for k ← N - 1 down to 0 do
  6. 5form Q_x, Q_u, Q_xx, Q_uu, Q_ux at (x_k, u_k); H ← Q_uu + μI (if H is not positive definite: μ ← max(10μ, μ_min), go to L2)
  7. 6k_k, F ← minimize ½ δᵀHδ + Q_uᵀδ subject to lo - u_k ≤ δ ≤ hi - u_k; F ← the free indices
  8. 7K_k ← rows F: -H_FF⁻¹ (Q_ux)_F; other rows: 0
  9. 8V_x ← Q_x + K_kᵀQ_uu k_k + K_kᵀQ_u + Q_uxᵀk_k; V_xx ← Q_xx + K_kᵀQ_uu K_k + K_kᵀQ_ux + Q_uxᵀK_k
  10. 9if -ΔV(1) < tol then stop
  11. 10for α ← 1, 1/2, 1/4, … (at most 12 values) do
  12. 11x̂_0 ← x_0; û_k ← clamp(u_k + α k_k + K_k (x̂_k - x_k)); x̂_{k+1} ← f(x̂_k, û_k)
  13. 12if J(Û) - J(U) ≤ c ΔV(α) then U, X ← Û, X̂; μ ← μ/10 (0 below μ_min); go to L2
  14. 13μ ← max(10μ, μ_min)
  15. 14return U, X

Here ΔV(α)=∑k(α kkTQu+12α2kkTHkk)\Delta V(\alpha) = \sum_k \bigl(\alpha\, k_k^{\mathsf T} Q_u + \frac12 \alpha^2 k_k^{\mathsf T} H k_k\bigr) is the change of the cost that the quadratic models predict, and the code uses c=0.1c = 0.1, μmin⁡=10−6\mu_{\min} = 10^{-6} and tol=10−10tol = 10^{-10}. The expansions of line L5 are Qx=ℓx+ATVxQ_x = \ell_x + A^{\mathsf T} V_x, Qu=ℓu+BTVxQ_u = \ell_u + B^{\mathsf T} V_x, Qxx=ℓxx+ATVxxAQ_{xx} = \ell_{xx} + A^{\mathsf T} V_{xx} A, Quu=ℓuu+BTVxxBQ_{uu} = \ell_{uu} + B^{\mathsf T} V_{xx} B and Qux=ℓux+BTVxxAQ_{ux} = \ell_{ux} + B^{\mathsf T} V_{xx} A, with Vx,VxxV_x, V_{xx} from the step after.

Lines L3 to L8 are the backward pass. Without bounds, line L6 would give kk=−H−1Quk_k = -H^{-1} Q_u and line L7 the gain Kk=−H−1QuxK_k = -H^{-1} Q_{ux}, and the backward pass would be the Riccati recursion of finite-horizon LQR applied to the local model. With bounds, line L6 is a quadratic program over a box in Rm\mathbb R^m. The code solves it with a projected Newton method: it fixes the variables that sit at a bound with the gradient pushing outward, takes a Newton step in the others, projects onto the box, and backtracks until the value goes down. It starts at δ=0\delta = 0, which is always in the box, so the solution is never worse than no change.

Line L7 is the key idea of the method. A control that is clamped at a bound cannot react to a small state deviation, so its row of the gain is zero, and the gain of the free controls is computed with the free block of HH only. Under strict complementarity this is exactly the derivative of the solution of line L6 with respect to the state (proof, Lemma 2). Line L8 then passes the cost-to-go model to the previous step.

Lines L10 to L12 are the forward pass with a backtracking line search on the feedforward part. Line L11 clamps the controls again, because the feedback term can push a control out of the box when the state differs from the old trajectory. Line L12 accepts the new trajectory only if the cost goes down by at least a fraction of the predicted change. The regularization μ\mu makes HH positive definite when QuuQ_{uu} is not, and shortens the steps when the model is poor; it grows after a failure and shrinks after a success.

Example

A pendulum swings up with a weak motor. The state is the angle θ\theta, with θ=0\theta = 0 hanging down, and the angular velocity ω\omega. The dynamics are θ¨=u−9.81sin⁡θ−0.1 θ˙\ddot\theta = u - 9.81 \sin\theta - 0.1\,\dot\theta, stepped by the explicit Euler method with Δt=0.05\Delta t = 0.05 for N=80N = 80 steps (4 seconds). The running cost is 0.0025 u20.0025\,u^2 per step, and the final cost is 12(100(θN−π)2+10 ωN2)\frac12\bigl(100(\theta_N - \pi)^2 + 10\,\omega_N^2\bigr). The torque limit is ∣u∣≤3|u| \le 3, much less than the 9.819.81 needed to hold the pendulum level, so it must pump energy by swinging. The start is u=0u = 0, which leaves the pendulum hanging.

iteration cost accepted step α\alpha
0 493.4802
1 142.2482 0.5
2 57.3002 0.5
5 2.1554 1
10 0.9548 1
20 0.8580 1
50 0.8549 1
60 0.8549 1

After 60 accepted iterations the predicted change is below the tolerance and the loop stops with cost 0.8548630.854863. The pendulum ends at θN=3.1368\theta_N = 3.1368 and ωN=0.0135\omega_N = 0.0135, close to upright. It first swings to one side, then back through the bottom, and then up. Nineteen of the 80 controls sit exactly at the limit, and every control lies in the box. The cost went down at every iteration. At the result, the derivative of JJ with respect to each free control is below 10−610^{-6}, and each derivative at a bound points out of the box, so the result is a first-order point.

Without the limit the same problem reaches cost 0.8487920.848792 with a largest torque of 3.6183.618, so the limit costs a little. With a limit of 22 the method stops after 7 iterations at cost 14.39214.392, with 79 of 80 controls at the limit and the pendulum at θN=2.647\theta_N = 2.647: the result is again a first-order point, but four seconds of pumping at this torque do not bring it to the top from this start.

Correctness

The proof shows four things. The controls stay in the box, because line L11 clamps them. Every accepted iteration lowers the cost, because the box solver of line L6 starts at zero, so each stage model has a value at most zero and the predicted change is negative. For linear dynamics and quadratic costs with no active bound, one iteration with μ=0\mu = 0 gives the exact optimum, because the backward pass is then the Riccati recursion. If the backward pass returns zero changes, the controls satisfy the first-order conditions of the problem with the box: the derivative of the cost is zero for free controls and points out of the box for clamped ones; for convex problems this is the global optimum. The proof also shows that the gain of line L7 is the derivative of the clamped solution. It does not prove convergence for nonlinear systems, and the method finds only a local solution.

Proof: Control-limited DDP keeps the controls in the box, lowers the cost at every accepted iteration, is exact for linear-quadratic problems, and stops only near a first-order pointfull

We use the notation of the page and of the code. The problem is to minimize J(U)=∑k=0N−1ℓ(xk,uk)+ℓf(xN)J(U) = \sum_{k=0}^{N-1} \ell(x_k, u_k) + \ell_f(x_N) subject to xk+1=f(xk,uk)x_{k+1} = f(x_k, u_k) with x0x_0 given and lo≤uk≤hilo \le u_k \le hi. The cost is ℓ(x,u)=12(x−g)TQ(x−g)+12uTRu\ell(x, u) = \frac12 (x - g)^{\mathsf T} Q (x - g) + \frac12 u^{\mathsf T} R u and ℓf(x)=12(x−g)TQf(x−g)\ell_f(x) = \frac12 (x - g)^{\mathsf T} Q_f (x - g) with Q,QfQ, Q_f positive semidefinite and RR positive definite. At stage kk, Ak=fx(xk,uk)A_k = f_x(x_k, u_k) and Bk=fu(xk,uk)B_k = f_u(x_k, u_k). The stage model of line L6 is

qk(δ)=12δTHkδ+Qu,kTδ,Hk=Quu,k+μI,q_k(\delta) = \tfrac12 \delta^{\mathsf T} H_k \delta + Q_{u,k}^{\mathsf T} \delta, \qquad H_k = Q_{uu,k} + \mu I,

over the box Bk={δ:lo−uk≤δ≤hi−uk}\mathcal B_k = \{\delta : lo - u_k \le \delta \le hi - u_k\}, and the expected change of line L9 is ΔV(α)=∑k(α kkTQu,k+12α2kkTHkkk)=∑kqk(αkk)\Delta V(\alpha) = \sum_k \bigl(\alpha\, k_k^{\mathsf T} Q_{u,k} + \frac12 \alpha^2 k_k^{\mathsf T} H_k k_k\bigr) = \sum_k q_k(\alpha k_k).

The method is local. Nothing below says that it converges to a global minimum, or that the line search of line L10 always succeeds.

Lemma 1: the box quadratic program

Claim. Let HH be positive definite. (a) The problem min⁡12δTHδ+cTδ\min \frac12 \delta^{\mathsf T} H \delta + c^{\mathsf T}\delta over a box has exactly one minimizer, and a feasible δ\delta is that minimizer if and only if, with γ=Hδ+c\gamma = H\delta + c, for each ii: γi=0\gamma_i = 0 if δi\delta_i is strictly inside its bounds, γi≥0\gamma_i \ge 0 if δi\delta_i is at its lower bound, and γi≤0\gamma_i \le 0 if it is at its upper bound. (b) The solver box_qp started at 0∈Bk0 \in \mathcal B_k returns a feasible point with qk(kk)≤qk(0)=0q_k(k_k) \le q_k(0) = 0.

Proof. (a) The objective is strictly convex and the box is compact, convex and not empty, so a minimizer exists and is unique. The listed conditions say that γT(y−δ)≥0\gamma^{\mathsf T}(y - \delta) \ge 0 for every yy in the box, coordinate by coordinate; for a convex differentiable function on a convex set this variational inequality holds exactly at the minimizers. (b) Every point of the solver is a projection onto the box, so it is feasible. A step is taken only if the value does not go up (the acceptance test of the solver has a right side at most the current value). The start is 00, which lies in Bk\mathcal B_k because uku_k lies in the box (Lemma 3). □\square

When the solver meets its stopping test, the conditions of (a) hold up to the tolerance, so kkk_k is the minimizer up to that tolerance. The test of the page compares it with all active sets.

Lemma 2: the feedback gain is the derivative of the clamped solution

Claim. Let δ∗(y)\delta^*(y) minimize 12δTHδ+(Qu+Quxy)Tδ\frac12 \delta^{\mathsf T} H \delta + (Q_u + Q_{ux} y)^{\mathsf T}\delta over Bk\mathcal B_k, where yy is a state deviation. Suppose that at y=0y = 0 each bound that is active has γi≠0\gamma_i \ne 0 (strict complementarity), and let FF be the set of free indices. Then for all small yy, δ∗(y)=kk+Kky\delta^*(y) = k_k + K_k y with KkK_k as in line L7: the rows in FF are −HFF−1(Qux)F-H_{FF}^{-1} (Q_{ux})_F and the other rows are zero.

Proof. At y=0y = 0 the clamped coordinates have γi≠0\gamma_i \ne 0 with the sign of (a), and the free coordinates are strictly inside their bounds or have γi=0\gamma_i = 0; by strict complementarity they are strictly inside. Put δ(y)\delta(y) with the clamped coordinates fixed at their bounds and the free ones given by HFFδF=−(Qu+Quxy)F−HFCδCH_{FF}\delta_F = -(Q_u + Q_{ux} y)_F - H_{FC}\delta_C. At y=0y = 0 this is kkk_k, and δF(y)=(kk)F−HFF−1(Qux)F y\delta_F(y) = (k_k)_F - H_{FF}^{-1}(Q_{ux})_F\, y. By continuity, for small yy the free coordinates stay strictly inside their bounds and the clamped gradients keep their strict signs, so δ(y)\delta(y) meets the conditions of Lemma 1(a) and equals δ∗(y)\delta^*(y). □\square

So the feedback of line L11 follows the solution of the box problem to first order, and a clamped control does not react to state deviations. Without strict complementarity the active set can change for arbitrarily small yy, and KkK_k is one of the one-sided derivatives.

Lemma 3: the controls stay in the box

Claim. Every control sequence that the algorithm holds or returns lies in the box.

Proof. The input is clamped before line L1, and line L11 clamps every control of a forward pass. Only such sequences are accepted in line L12. □\square

Theorem 1: every accepted iteration lowers the cost

Claim. If line L9 does not stop, then ΔV(α)<0\Delta V(\alpha) < 0 for every α∈(0,1]\alpha \in (0, 1], and an iteration accepted in line L12 has J(U^)<J(U)J(\hat U) < J(U). So the costs of the accepted iterates strictly decrease.

Proof. By Lemma 1(b), qk(kk)≤0q_k(k_k) \le 0 for every kk. The function qkq_k is convex with qk(0)=0q_k(0) = 0, so qk(αkk)≤(1−α)qk(0)+αqk(kk)=αqk(kk)q_k(\alpha k_k) \le (1 - \alpha) q_k(0) + \alpha q_k(k_k) = \alpha q_k(k_k). Summing, ΔV(α)≤αΔV(1)\Delta V(\alpha) \le \alpha \Delta V(1). Line L9 continues only if −ΔV(1)≥tol>0-\Delta V(1) \ge tol > 0, so ΔV(α)≤−α tol<0\Delta V(\alpha) \le -\alpha\, tol < 0. Line L12 accepts only if J(U^)−J(U)≤c ΔV(α)J(\hat U) - J(U) \le c\,\Delta V(\alpha) with c>0c > 0, which is negative. □\square

Theorem 2: one iteration is exact for an unconstrained linear-quadratic problem

Claim. Let f(x,u)=Ax+Buf(x, u) = Ax + Bu (or Ak,BkA_k, B_k that depend on kk only), let μ=0\mu = 0, and suppose that the box is so large that no bound is active in line L6 and no clamp acts in line L11 (for example, no bounds at all). Then the backward pass is the Riccati recursion of the finite-horizon LQR problem, ΔV(1)\Delta V(1) equals the true change of the cost, and the forward pass with α=1\alpha = 1 returns the optimal control sequence.

Proof. Let Vk(x)V_k(x) be the optimal cost-to-go from state xx at stage kk. We show by induction, from k=Nk = N down, that Vk(xk+y)=Vk(xk)+VxTy+12yTVxxyV_k(x_k + y) = V_k(x_k) + V_{x}^{\mathsf T} y + \frac12 y^{\mathsf T} V_{xx} y with the Vx,VxxV_x, V_{xx} that the backward pass holds after stage kk, that VxxV_{xx} is positive semidefinite, and that the optimal control at xk+yx_k + y is uk+kk+Kkyu_k + k_k + K_k y. At k=Nk = N this is the Taylor expansion of the quadratic ℓf\ell_f (line L3). For the step, the dynamics are linear, so

ℓ(xk+y,uk+δ)+Vk+1(xk+1+Ay+Bδ)\ell(x_k + y, u_k + \delta) + V_{k+1}\bigl(x_{k+1} + A y + B\delta\bigr)

is exactly the quadratic with the coefficients Qx,Qu,Qxx,Quu,QuxQ_x, Q_u, Q_{xx}, Q_{uu}, Q_{ux} of line L5 plus a constant. Quu=R+BTVxxBQ_{uu} = R + B^{\mathsf T} V_{xx} B is positive definite. Its minimizer over δ\delta is −Quu−1(Qu+Quxy)-Q_{uu}^{-1}(Q_u + Q_{ux} y); no bound is active by assumption, so the box solver returns it at y=0y = 0 (Lemma 1(a)), and line L7 gives Kk=−Quu−1QuxK_k = -Q_{uu}^{-1} Q_{ux}. Substituting δ=kk+Kky\delta = k_k + K_k y gives a quadratic in yy whose linear and quadratic coefficients are exactly the two formulas of line L8, and whose constant is the old constant plus qk(kk)q_k(k_k). As a minimum over δ\delta of a quadratic that is jointly convex in (y,δ)(y, \delta), it is convex, so VxxV_{xx} is positive semidefinite. This is the Riccati recursion.

At y=0y = 0 the constant of stage kk is ℓ(xk,uk)+Vk+1(xk+1)+qk(kk)\ell(x_k, u_k) + V_{k+1}(x_{k+1}) + q_k(k_k), so V0(x0)=J(U)+∑kqk(kk)=J(U)+ΔV(1)V_0(x_0) = J(U) + \sum_k q_k(k_k) = J(U) + \Delta V(1). The forward pass with α=1\alpha = 1 applies the optimal policy uk+kk+Kkyu_k + k_k + K_k y from x0x_0, and no clamp acts by assumption. Its cost is V0(x0)V_0(x_0), so the actual change equals ΔV(1)≤c ΔV(1)\Delta V(1) \le c\,\Delta V(1) for c≤1c \le 1, and line L12 accepts. □\square

With active bounds the cost-to-go is only piecewise quadratic, and one iteration is no longer enough; the test of the page checks the result of several iterations against an independent solver of the same convex problem.

Theorem 3: a stop in line L9 happens only near a first-order point

Claim. Suppose that, with μ=0\mu = 0 or any μ\mu, the backward pass returns kk=0k_k = 0 at every stage and that 00 is the exact minimizer of every stage model. Then UU satisfies the first-order conditions of min⁡J(U)\min J(U) over the box: for each kk and ii, ∂J/∂uk,i=0\partial J/\partial u_{k,i} = 0 where uk,iu_{k,i} is strictly inside its bounds, ≥0\ge 0 at its lower bound and ≤0\le 0 at its upper bound. If JJ is convex, for example for linear dynamics, UU is a global minimizer.

Proof. With kk=0k_k = 0 the formula of line L8 becomes Vx=Qx+KkTQuV_x = Q_x + K_k^{\mathsf T} Q_u. By Lemma 1(a) applied at δ=0\delta = 0, γ=Qu\gamma = Q_u, and a free index has Qu,i=0Q_{u,i} = 0: if it is strictly inside, by (a); if it sits at a bound, it is free only when the gradient does not push outward, and (a) then forces Qu,i=0Q_{u,i} = 0. The rows of KkK_k for clamped indices are zero. So KkTQu=0K_k^{\mathsf T} Q_u = 0 and Vx,k=∇xℓ(xk,uk)+AkTVx,k+1V_{x,k} = \nabla_x \ell(x_k, u_k) + A_k^{\mathsf T} V_{x,k+1} with Vx,N=∇ℓf(xN)V_{x,N} = \nabla \ell_f(x_N). This is the adjoint recursion, so Vx,k+1V_{x,k+1} is the derivative of the cost from stage k+1k + 1 on with respect to xk+1x_{k+1}, and by the chain rule

∂J∂uk=∇uℓ(xk,uk)+BkTVx,k+1=Qu,k.\frac{\partial J}{\partial u_k} = \nabla_u \ell(x_k, u_k) + B_k^{\mathsf T} V_{x,k+1} = Q_{u,k}.

The regularization μ\mu does not enter QuQ_u. So the conditions of Lemma 1(a) at δ=0\delta = 0 are the stated conditions for ∂J/∂uk\partial J/\partial u_k. For convex JJ on a convex set they imply a global minimum. Only first derivatives of ff enter, so dropping the second derivatives of the dynamics does not change this result. ■\blacksquare

The code stops when −ΔV(1)<tol-\Delta V(1) < tol, which is a small version of kk=0k_k = 0: by Lemma 1(a) and strict convexity, −qk(kk)≥12λmin⁡(Hk)∥kk∥2-q_k(k_k) \ge \frac12 \lambda_{\min}(H_k)\|k_k\|^2, so every kkk_k is small. The test of the page measures the first-order conditions of the returned controls directly.

Complexity

The backward pass of one iteration costs O(n3)O(n^3) per step for the products with VxxV_{xx}, O(p m3)O(p\,m^3) for the box solver with pp iterations, and O(F)O(F) for the dynamics and their Jacobians, so O(N(n3+p m3+F))O(N(n^3 + p\,m^3 + F)) in total; the terms n2mn^2 m and nm2n m^2 are at most n3+m3n^3 + m^3. A forward pass costs O(N(nm+F))O(N(nm + F)), and the line search tries at most a constant number of step sizes. So one iteration costs O(N(n3+p m3+F))O(N(n^3 + p\,m^3 + F)), and II iterations cost II times that. The memory holds the trajectory and the gains, O(Nnm)O(Nnm), and the matrices of one step, O(n2)O(n^2).

The number of iterations has no general bound. The 60 iterations of the example are a measurement for this problem and start; near the end the cost changes only in the sixth digit, and a looser tolerance stops much earlier.

Properties

  • Feasible controls. Every control sequence the method holds, including all intermediate ones, lies in the box.
  • Monotone. The cost goes down at every accepted iteration.
  • Local. The result depends on the start; a swing-up can end at a different local solution from a different first guess.
  • Feedback. Besides the controls, the method returns time-varying gains, which a controller can use near the trajectory; the gains of clamped controls are zero.
  • Linear in the horizon. The work grows linearly with NN, because each step solves only problems of size mm and nn.
  • Only control bounds. The box is handled exactly; bounds on states and general constraints need other tools.

Variants and improvements

  • Clamping in the forward pass only. The simplest approach ignores the box in the backward pass and clamps in line L11. The gains then still try to use clamped controls, and the predicted change of the cost is wrong when many controls sit at a bound.
  • Squashing. Replacing uu by a smooth function of a free variable, such as u=tanh⁡(v)u = \tanh(v), removes the box, but the gradient of the cost with respect to vv vanishes at the limits, and convergence slows down there.
  • Second-order DDP. Adding the second derivatives of the dynamics to QxxQ_{xx}, QuuQ_{uu} and QuxQ_{ux} gives the original method of Mayne, with faster local convergence and a higher cost per iteration.
  • State constraints. Augmented Lagrangian and penalty terms in the cost, or a barrier, handle constraints on the states; this gives methods that combine DDP with constrained optimization.
  • Receding horizon. Running a few iterations at every control cycle, with the solution of the last cycle shifted as the start, gives a nonlinear MPC controller with torque limits.

When to use it

Use control-limited DDP when the only constraints are bounds on the controls, the horizon is long, and the dynamics are smooth and cheap to differentiate, as for torque-limited robot arms, swing-up tasks and receding-horizon control. It is simple, its memory is small, and it returns feedback gains. When there are obstacles or other state constraints, use a method that handles general constraints, such as sequential convex optimization. When contacts switch on and off, see contact-implicit trajectory optimization. For a convex problem with linear dynamics, a general quadratic programming solver over the whole horizon also works and gives the global optimum.

Pitfalls

  • Ignoring the clamp in the gain. If line L7 uses the full HH even for clamped controls, the feedback acts on controls that cannot move, and the forward pass of line L11 clamps them anyway, so the model and the simulation disagree and the line search fails often.
  • Forgetting the clamp in the forward pass. Without the clamp of line L11 the feedback term can push a control out of the box when the state differs from the old trajectory.
  • A poor start. Starting from zero controls at an equilibrium can give zero gradients for some problems. Here the final cost has a nonzero gradient, but a different start, for example with the pendulum already swinging, can lead to another local solution.
  • Stopping on a tolerance. The test of line L9 measures the predicted change of the cost, which depends on the scale of the cost; scale the tolerance with the problem.
  • Regularization. If μ\mu of line L5 grows without bound, the steps become tiny and the method stalls; a bound on μ\mu is needed, and the code stops when μ\mu exceeds 101010^{10}.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

control_limited_ddp.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/control-limited-ddp/. The authors are listed in prov/DH08X0.jsonl.
"""Control-limited differential dynamic programming (Tassa, Mansard and Todorov).

The problem is

    minimize   J(U) = sum_k l(x_k, u_k) + l_f(x_N)
    subject to x_(k+1) = f(x_k, u_k),  x_0 given,  lo <= u_k <= hi.

The cost here is quadratic: l(x, u) = 1/2 (x - g)' Q (x - g) + 1/2 u' R u and
l_f(x) = 1/2 (x - g)' Q_f (x - g). The dynamics are any smooth function that
returns the next state and its Jacobians A = f_x and B = f_u. The second
derivatives of f are dropped (the Gauss-Newton form of DDP, often called
iLQR); the box handling below is the same for the full second-order form.

In the backward pass, the feedforward step of each stage is the solution of
a small quadratic program with box constraints, solved by a projected Newton
method. The feedback gain is computed on the free controls only, and its
rows for the clamped controls are zero, so a clamped control does not react
to state deviations. The forward pass clamps every control to the box.
"""

import math


def zeros(r, c):
    return [[0.0] * c for _ in range(r)]


def matmul(a, b):
    return [[sum(a[i][k] * b[k][j] for k in range(len(b))) for j in range(len(b[0]))] for i in range(len(a))]


def matvec(a, v):
    return [sum(a[i][k] * v[k] for k in range(len(v))) for i in range(len(a))]


def transpose(a):
    return [list(r) for r in zip(*a)]


def madd(a, b, s=1.0):
    return [[a[i][j] + s * b[i][j] for j in range(len(a[0]))] for i in range(len(a))]


def vadd(a, b, s=1.0):
    return [a[i] + s * b[i] for i in range(len(a))]


def dot(a, b):
    return sum(x * y for x, y in zip(a, b))


def symmetrize(a):
    n = len(a)
    return [[0.5 * (a[i][j] + a[j][i]) for j in range(n)] for i in range(n)]


def cholesky(a):
    """Lower triangular L with L L' = a, or None if a is not positive definite."""
    n = len(a)
    low = zeros(n, n)
    for i in range(n):
        for j in range(i + 1):
            s = a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))
            if i == j:
                if s <= 0.0:
                    return None
                low[i][i] = math.sqrt(s)
            else:
                low[i][j] = s / low[j][j]
    return low


def chol_solve(low, b):
    n = len(low)
    y = [0.0] * n
    for i in range(n):
        y[i] = (b[i] - sum(low[i][k] * y[k] for k in range(i))) / low[i][i]
    x = [0.0] * n
    for i in reversed(range(n)):
        x[i] = (y[i] - sum(low[k][i] * x[k] for k in range(i + 1, n))) / low[i][i]
    return x


def clamp(v, lo, hi):
    return [min(max(v[i], lo[i]), hi[i]) for i in range(len(v))]


def qp_value(h, g, x):
    return 0.5 * dot(x, matvec(h, x)) + dot(g, x)


def box_qp(h, g, lo, hi, x0=None, max_iter=100, tol=1e-12):
    """Minimize 1/2 x' h x + g' x subject to lo <= x <= hi, h positive definite.

    Projected Newton: fix the variables that sit at a bound with the gradient
    pushing outward, take a Newton step in the others, project onto the box,
    and backtrack until the value drops enough. The value never goes up, so
    the result is never worse than the projection of x0. Returns x and the
    list of free indices at x."""
    n = len(g)
    x = clamp(x0 if x0 is not None else [0.0] * n, lo, hi)
    for _ in range(max_iter):
        grad = vadd(matvec(h, x), g)
        free = [i for i in range(n) if not ((x[i] <= lo[i] and grad[i] > 0.0) or (x[i] >= hi[i] and grad[i] < 0.0))]
        if not free or math.sqrt(sum(grad[i] ** 2 for i in free)) < tol:
            break
        low = cholesky([[h[i][j] for j in free] for i in free])
        step_f = chol_solve(low, [-grad[i] for i in free])
        direction = [0.0] * n
        for a, i in enumerate(free):
            direction[i] = step_f[a]
        fx, t, moved = qp_value(h, g, x), 1.0, False
        while t > 1e-14:
            xn = clamp(vadd(x, direction, t), lo, hi)
            if qp_value(h, g, xn) <= fx + 0.1 * min(0.0, dot(grad, vadd(xn, x, -1.0))):
                moved = xn != x
                x = xn
                break
            t *= 0.5
        if not moved:
            break
    grad = vadd(matvec(h, x), g)
    free = [i for i in range(n) if not ((x[i] <= lo[i] and grad[i] > 0.0) or (x[i] >= hi[i] and grad[i] < 0.0))]
    return x, free


class Problem:
    """Dynamics dyn(x, u) -> (x_next, A, B) and a quadratic cost."""

    def __init__(self, dyn, x0, goal, q, r, qf, lo, hi):
        self.dyn, self.x0, self.goal = dyn, list(x0), list(goal)
        self.q, self.r, self.qf = q, r, qf
        self.lo, self.hi = list(lo), list(hi)

    def running(self, x, u):
        e = vadd(x, self.goal, -1.0)
        return 0.5 * dot(e, matvec(self.q, e)) + 0.5 * dot(u, matvec(self.r, u))

    def final(self, x):
        e = vadd(x, self.goal, -1.0)
        return 0.5 * dot(e, matvec(self.qf, e))

    def rollout(self, us):
        xs = [list(self.x0)]
        for u in us:
            xs.append(self.dyn(xs[-1], u)[0])
        return xs

    def cost(self, xs, us):
        return sum(self.running(x, u) for x, u in zip(xs, us)) + self.final(xs[-1])


def backward(prob, xs, us, mu):
    """One backward pass. Returns (ks, Ks, dv1, dv2) or None if some Q_uu + mu I is not positive definite."""
    n = len(xs[0])
    vx = matvec(prob.qf, vadd(xs[-1], prob.goal, -1.0))  # @line L3
    vxx = [row[:] for row in prob.qf]
    ks, gains = [None] * len(us), [None] * len(us)
    dv1 = dv2 = 0.0
    for k in reversed(range(len(us))):  # @line L4
        x, u = xs[k], us[k]
        _, a, b = prob.dyn(x, u)
        at, bt = transpose(a), transpose(b)
        qx = vadd(matvec(prob.q, vadd(x, prob.goal, -1.0)), matvec(at, vx))  # @line L5
        qu = vadd(matvec(prob.r, u), matvec(bt, vx))
        qxx = madd(prob.q, matmul(matmul(at, vxx), a))
        quu = madd(prob.r, matmul(matmul(bt, vxx), b))
        qux = matmul(matmul(bt, vxx), a)
        m = len(u)
        h = [[quu[i][j] + (mu if i == j else 0.0) for j in range(m)] for i in range(m)]
        if cholesky(h) is None:
            return None
        lo_k = [prob.lo[i] - u[i] for i in range(m)]
        hi_k = [prob.hi[i] - u[i] for i in range(m)]
        kff, free = box_qp(h, qu, lo_k, hi_k)  # @line L6
        gain = zeros(m, n)  # @line L7
        if free:
            low = cholesky([[h[i][j] for j in free] for i in free])
            for c in range(n):
                col = chol_solve(low, [-qux[i][c] for i in free])
                for a_, i in enumerate(free):
                    gain[i][c] = col[a_]
        ks[k], gains[k] = kff, gain
        dv1 += dot(kff, qu)
        dv2 += 0.5 * dot(kff, matvec(h, kff))
        kt = transpose(gain)
        vx = vadd(vadd(vadd(qx, matvec(kt, matvec(quu, kff))), matvec(kt, qu)), matvec(transpose(qux), kff))  # @line L8
        vxx = symmetrize(madd(madd(madd(qxx, matmul(matmul(kt, quu), gain)), matmul(kt, qux)), matmul(transpose(qux), gain)))
    return ks, gains, dv1, dv2


def forward(prob, xs, us, ks, gains, alpha):
    new_x, new_u = [list(prob.x0)], []
    for k in range(len(us)):
        dx = vadd(new_x[-1], xs[k], -1.0)
        u = clamp(vadd(vadd(us[k], ks[k], alpha), matvec(gains[k], dx)), prob.lo, prob.hi)  # @line L11
        new_u.append(u)
        new_x.append(prob.dyn(new_x[-1], u)[0])
    return new_x, new_u


def control_limited_ddp(prob, us, iters=200, tol=1e-10, mu0=0.0, mu_min=1e-6, mu_max=1e10, c=0.1, log=None):
    """Returns (xs, us, info). info has the cost after every accepted iteration."""
    us = [clamp(u, prob.lo, prob.hi) for u in us]
    xs = prob.rollout(us)  # @line L1
    cost = prob.cost(xs, us)
    mu = mu0
    info = {"costs": [cost], "iterations": 0, "mu": mu}
    for _ in range(iters):  # @line L2
        out = backward(prob, xs, us, mu)
        if out is None:
            mu = max(mu * 10.0, mu_min)
            if mu > mu_max:
                break
            continue
        ks, gains, dv1, dv2 = out
        if -(dv1 + dv2) < tol:  # @line L9
            break
        accepted = False
        alpha = 1.0
        for _ in range(12):  # @line L10
            new_x, new_u = forward(prob, xs, us, ks, gains, alpha)
            new_cost = prob.cost(new_x, new_u)
            expected = alpha * dv1 + alpha * alpha * dv2
            if new_cost - cost <= c * expected:  # @line L12
                accepted = True
                break
            alpha *= 0.5
        if accepted:
            xs, us, cost = new_x, new_u, new_cost
            info["costs"].append(cost)
            info["iterations"] += 1
            mu = mu / 10.0 if mu / 10.0 >= mu_min else 0.0
            if log is not None:
                log.append((cost, alpha, mu))
        else:
            mu = max(mu * 10.0, mu_min)  # @line L13
            if mu > mu_max:
                break
    info["mu"] = mu
    return xs, us, info  # @line L14


def pendulum(dt=0.05, g=9.81, damping=0.1):
    """theta'' = u - g sin(theta) - damping * theta', explicit Euler. theta = 0 hangs down."""
    def dyn(x, u):
        th, om = x
        nx = [th + dt * om, om + dt * (u[0] - g * math.sin(th) - damping * om)]
        a = [[1.0, dt], [-dt * g * math.cos(th), 1.0 - dt * damping]]
        b = [[0.0], [dt]]
        return nx, a, b
    return dyn


def double_integrator(dt=0.1):
    def dyn(x, u):
        nx = [x[0] + dt * x[1], x[1] + dt * u[0]]
        return nx, [[1.0, dt], [0.0, 1.0]], [[0.0], [dt]]
    return dyn
test_control_limited_ddp.py 196 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/control-limited-ddp/. The authors are listed in prov/DH08X0.jsonl.
import itertools
import math
import random
import unittest

from control_limited_ddp import (
    Problem,
    backward,
    box_qp,
    control_limited_ddp,
    double_integrator,
    matvec,
    pendulum,
    qp_value,
    transpose,
    vadd,
)


def gradient(prob, us):
    """dJ/du_k for every k, by the adjoint recursion."""
    xs = prob.rollout(us)
    lam = matvec(prob.qf, vadd(xs[-1], prob.goal, -1.0))
    grads = [None] * len(us)
    for k in reversed(range(len(us))):
        _, a, b = prob.dyn(xs[k], us[k])
        grads[k] = vadd(matvec(prob.r, us[k]), matvec(transpose(b), lam))
        lam = vadd(matvec(prob.q, vadd(xs[k], prob.goal, -1.0)), matvec(transpose(a), lam))
    return grads


def flat(us):
    return [v for u in us for v in u]


def unflat(v, m):
    return [v[i:i + m] for i in range(0, len(v), m)]


def solve(a, b):
    """Gaussian elimination with partial pivoting."""
    n = len(b)
    m = [row[:] + [b[i]] for i, row in enumerate(a)]
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(m[r][c]))
        m[c], m[p] = m[p], m[c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            for j in range(c, n + 1):
                m[r][j] -= f * m[c][j]
    x = [0.0] * n
    for i in reversed(range(n)):
        x[i] = (m[i][n] - sum(m[i][j] * x[j] for j in range(i + 1, n))) / m[i][i]
    return x


def hessian_and_gradient(prob, n_steps, m):
    """For linear dynamics J is quadratic in U; columns of the Hessian are gradient differences."""
    zero = [[0.0] * m for _ in range(n_steps)]
    g0 = flat(gradient(prob, zero))
    h = []
    for j in range(n_steps * m):
        e = [0.0] * (n_steps * m)
        e[j] = 1.0
        h.append(vadd(flat(gradient(prob, unflat(e, m))), g0, -1.0))
    return transpose(h), g0


def kkt_residual(prob, us):
    """Largest violation of the first-order conditions of min J subject to the box."""
    worst = 0.0
    for u, g in zip(us, gradient(prob, us)):
        for i in range(len(u)):
            if u[i] <= prob.lo[i]:
                worst = max(worst, -g[i])
            elif u[i] >= prob.hi[i]:
                worst = max(worst, g[i])
            else:
                worst = max(worst, abs(g[i]))
    return worst


def random_linear(rng, n, m):
    a = [[(1.0 if i == j else 0.0) + rng.uniform(-0.2, 0.2) for j in range(n)] for i in range(n)]
    b = [[rng.uniform(-0.5, 0.5) for _ in range(m)] for _ in range(n)]

    def dyn(x, u):
        return vadd(matvec(a, x), matvec(b, u)), a, b
    return dyn


def diag(vals):
    return [[v if i == j else 0.0 for j in range(len(vals))] for i, v in enumerate(vals)]


class TestWorkedExample(unittest.TestCase):
    def test_pendulum_swing_up(self):
        dt, umax = 0.05, 3.0
        prob = Problem(pendulum(dt), [0.0, 0.0], [math.pi, 0.0], diag([0.0, 0.0]), [[0.1 * dt]],
                       diag([100.0, 10.0]), [-umax], [umax])
        xs, us, info = control_limited_ddp(prob, [[0.0]] * 80, iters=300)
        costs = info["costs"]
        self.assertAlmostEqual(costs[0], 493.4802, places=3)
        self.assertAlmostEqual(costs[1], 142.2482, places=3)
        self.assertAlmostEqual(costs[-1], 0.854863, places=5)
        self.assertEqual(info["iterations"], 60)
        self.assertTrue(all(costs[i + 1] < costs[i] for i in range(len(costs) - 1)))
        self.assertTrue(all(-umax <= u[0] <= umax for u in us))
        self.assertEqual(sum(1 for u in us if abs(u[0]) == umax), 19)
        self.assertLess(abs(xs[-1][0] - math.pi), 0.01)
        self.assertLess(abs(xs[-1][1]), 0.02)
        self.assertLess(kkt_residual(prob, us), 1e-4)


class TestExactCases(unittest.TestCase):
    def test_unconstrained_linear_quadratic_in_one_iteration(self):
        rng = random.Random(2014)
        n, m, steps = 3, 2, 10
        prob = Problem(random_linear(rng, n, m), [1.0, -0.5, 0.3], [0.0] * n, diag([1.0, 0.5, 0.2]),
                       diag([0.3, 0.1]), diag([5.0, 5.0, 5.0]), [-1e6] * m, [1e6] * m)
        h, g = hessian_and_gradient(prob, steps, m)
        best = unflat(solve(h, [-v for v in g]), m)
        _, us, info = control_limited_ddp(prob, [[0.0] * m] * steps, iters=1)
        self.assertEqual(info["iterations"], 1)
        for u, v in zip(us, best):
            for a, b in zip(u, v):
                self.assertAlmostEqual(a, b, places=8)
        # A second backward pass finds nothing left to do.
        _, _, dv1, dv2 = backward(prob, prob.rollout(us), us, 0.0)
        self.assertLess(abs(dv1 + dv2), 1e-12)

    def test_box_qp_against_all_active_sets(self):
        rng = random.Random(11)
        for _ in range(200):
            m = rng.randint(1, 3)
            p = [[rng.uniform(-1, 1) for _ in range(m)] for _ in range(m)]
            h = [[sum(p[k][i] * p[k][j] for k in range(m)) + (0.1 if i == j else 0.0) for j in range(m)] for i in range(m)]
            g = [rng.uniform(-3, 3) for _ in range(m)]
            lo = [rng.uniform(-2, 0) for _ in range(m)]
            hi = [rng.uniform(0, 2) for _ in range(m)]
            best = math.inf
            for pattern in itertools.product((0, 1, 2), repeat=m):
                x = [lo[i] if pattern[i] == 0 else hi[i] if pattern[i] == 2 else 0.0 for i in range(m)]
                free = [i for i in range(m) if pattern[i] == 1]
                if free:
                    rhs = [-(g[i] + sum(h[i][j] * x[j] for j in range(m) if j not in free)) for i in free]
                    sol = solve([[h[i][j] for j in free] for i in free], rhs)
                    for a, i in enumerate(free):
                        x[i] = sol[a]
                if all(lo[i] - 1e-12 <= x[i] <= hi[i] + 1e-12 for i in range(m)):
                    best = min(best, qp_value(h, g, x))
            x, _ = box_qp(h, g, lo, hi)
            self.assertTrue(all(lo[i] <= x[i] <= hi[i] for i in range(m)))
            self.assertAlmostEqual(qp_value(h, g, x), best, places=9)


class TestConstrainedLinear(unittest.TestCase):
    def check(self, prob, steps, m):
        h, g = hessian_and_gradient(prob, steps, m)
        # Accelerated projected gradient on the same convex problem, as an independent reference.
        lip = max(sum(abs(v) for v in row) for row in h)
        lo, hi = prob.lo * steps, prob.hi * steps
        x = [0.0] * (steps * m)
        y, t = x[:], 1.0
        for _ in range(1200):
            grad = vadd(matvec(h, y), g)
            xn = [min(max(y[i] - grad[i] / lip, lo[i]), hi[i]) for i in range(len(y))]
            tn = (1 + math.sqrt(1 + 4 * t * t)) / 2
            y = [xn[i] + (t - 1) / tn * (xn[i] - x[i]) for i in range(len(y))]
            x, t = xn, tn
        _, us, info = control_limited_ddp(prob, [[0.0] * m] * steps, iters=100)
        self.assertLess(kkt_residual(prob, us), 1e-6)
        costs = info["costs"]
        self.assertTrue(all(costs[i + 1] < costs[i] for i in range(len(costs) - 1)))
        self.assertAlmostEqual(costs[-1], qp_value(h, g, x) + costs[0], places=6)
        return us

    def test_double_integrator_with_a_small_box(self):
        prob = Problem(double_integrator(0.1), [1.0, 0.0], [0.0, 0.0], diag([0.1, 0.01]), [[0.01]],
                       diag([10.0, 10.0]), [-0.5], [0.5])
        us = self.check(prob, 30, 1)
        self.assertGreater(sum(1 for u in us if abs(u[0]) == 0.5), 5)

    def test_random_linear_systems(self):
        rng = random.Random(1966)
        for _ in range(2):
            n, m, steps = 2, 2, 10
            prob = Problem(random_linear(rng, n, m), [rng.uniform(-2, 2) for _ in range(n)], [0.0] * n,
                           diag([1.0, 1.0]), diag([0.1, 0.1]), diag([10.0, 10.0]), [-0.4, -0.4], [0.4, 0.4])
            self.check(prob, steps, m)


if __name__ == "__main__":
    unittest.main()

History

David Mayne introduced differential dynamic programming in 1966, as a second-order method for the optimal control of nonlinear discrete-time systems, and the book by David Jacobson and Mayne in 1970 developed its theory. The Gauss-Newton form that drops the second derivatives of the dynamics, known as iLQR, became popular in robotics in the 2000s, through the work of Weiwei Li and Emo Todorov among others. Yuval Tassa, Nicolas Mansard and Emo Todorov presented the control-limited version at ICRA 2014; its box-constrained backward pass and clamped gains made DDP practical for robots with torque limits.

References

  1. Yuval Tassa, Nicolas Mansard and Emo Todorov, Control-limited differential dynamic programming, IEEE International Conference on Robotics and Automation (ICRA), 2014, 1168-1175, the whole paper (the box-constrained backward pass and the clamped feedback gains)
  2. David Q. Mayne, A second-order gradient method for determining optimal trajectories of non-linear discrete-time systems, International Journal of Control 3(1), 1966, 85-95, the whole paper (the original method)
  3. David H. Jacobson and David Q. Mayne, Differential Dynamic Programming, American Elsevier, 1970, the book as a whole (the classical theory of the method)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • a scene preset for the example