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.
- Solves
- Trajectory optimization
- 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
- Model
- Real RAM
- Properties
- deterministicnot exactofflinenot randomized
- Evidence
- Proof sketchCode in 1 languages
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 . 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 with a start , a horizon of steps, a running cost and a final cost , and bounds in . Output: controls with that make
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 and . It uses only the first derivatives and of the dynamics, the Gauss-Newton form that is often called iLQR; the full second-order form adds terms with second derivatives of to the quadratic model, and the handling of the box is the same.
The algorithm
CONTROL-LIMITED-DDP(x_0, U, lo, hi)- 1
X ← simulate U from x_0; μ ← 0 - 2
repeat - 3
V_x ← ∇ℓ_f(x_N); V_xx ← ∇²ℓ_f(x_N) - 4
for k ← N - 1 down to 0 do - 5
form 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) - 6
k_k, F ← minimize ½ δᵀHδ + Q_uᵀδ subject to lo - u_k ≤ δ ≤ hi - u_k; F ← the free indices - 7
K_k ← rows F: -H_FF⁻¹ (Q_ux)_F; other rows: 0 - 8
V_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 - 9
if -ΔV(1) < tol then stop - 10
for α ← 1, 1/2, 1/4, … (at most 12 values) do - 11
x̂_0 ← x_0; û_k ← clamp(u_k + α k_k + K_k (x̂_k - x_k)); x̂_{k+1} ← f(x̂_k, û_k) - 12
if J(Û) - J(U) ≤ c ΔV(α) then U, X ← Û, X̂; μ ← μ/10 (0 below μ_min); go to L2 - 13
μ ← max(10μ, μ_min) - 14
return U, X
Here is the change of the cost that the quadratic models predict, and the code uses , and . The expansions of line L5 are , , , and , with from the step after.
Lines L3 to L8 are the backward pass. Without bounds, line L6 would give and line L7 the gain , 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 . 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 , 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 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 makes positive definite when 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 , with hanging down, and the angular velocity . The dynamics are , stepped by the explicit Euler method with for steps (4 seconds). The running cost is per step, and the final cost is . The torque limit is , much less than the needed to hold the pendulum level, so it must pump energy by swinging. The start is , which leaves the pendulum hanging.
| iteration | cost | accepted step |
|---|---|---|
| 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 . The pendulum ends at and , 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 with respect to each free control is below , 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 with a largest torque of , so the limit costs a little. With a limit of the method stops after 7 iterations at cost , with 79 of 80 controls at the limit and the pendulum at : 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 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 subject to with given and . The cost is and with positive semidefinite and positive definite. At stage , and . The stage model of line L6 is
over the box , and the expected change of line L9 is .
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 be positive definite. (a) The problem over a box has exactly one minimizer, and a feasible is that minimizer if and only if, with , for each : if is strictly inside its bounds, if is at its lower bound, and if it is at its upper bound. (b) The solver box_qp started at returns a feasible point with .
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 for every 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 , which lies in because lies in the box (Lemma 3).
When the solver meets its stopping test, the conditions of (a) hold up to the tolerance, so 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 minimize over , where is a state deviation. Suppose that at each bound that is active has (strict complementarity), and let be the set of free indices. Then for all small , with as in line L7: the rows in are and the other rows are zero.
Proof. At the clamped coordinates have with the sign of (a), and the free coordinates are strictly inside their bounds or have ; by strict complementarity they are strictly inside. Put with the clamped coordinates fixed at their bounds and the free ones given by . At this is , and . By continuity, for small the free coordinates stay strictly inside their bounds and the clamped gradients keep their strict signs, so meets the conditions of Lemma 1(a) and equals .
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 , and 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.
Theorem 1: every accepted iteration lowers the cost
Claim. If line L9 does not stop, then for every , and an iteration accepted in line L12 has . So the costs of the accepted iterates strictly decrease.
Proof. By Lemma 1(b), for every . The function is convex with , so . Summing, . Line L9 continues only if , so . Line L12 accepts only if with , which is negative.
Theorem 2: one iteration is exact for an unconstrained linear-quadratic problem
Claim. Let (or that depend on only), let , 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, equals the true change of the cost, and the forward pass with returns the optimal control sequence.
Proof. Let be the optimal cost-to-go from state at stage . We show by induction, from down, that with the that the backward pass holds after stage , that is positive semidefinite, and that the optimal control at is . At this is the Taylor expansion of the quadratic (line L3). For the step, the dynamics are linear, so
is exactly the quadratic with the coefficients of line L5 plus a constant. is positive definite. Its minimizer over is ; no bound is active by assumption, so the box solver returns it at (Lemma 1(a)), and line L7 gives . Substituting gives a quadratic in whose linear and quadratic coefficients are exactly the two formulas of line L8, and whose constant is the old constant plus . As a minimum over of a quadratic that is jointly convex in , it is convex, so is positive semidefinite. This is the Riccati recursion.
At the constant of stage is , so . The forward pass with applies the optimal policy from , and no clamp acts by assumption. Its cost is , so the actual change equals for , and line L12 accepts.
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 or any , the backward pass returns at every stage and that is the exact minimizer of every stage model. Then satisfies the first-order conditions of over the box: for each and , where is strictly inside its bounds, at its lower bound and at its upper bound. If is convex, for example for linear dynamics, is a global minimizer.
Proof. With the formula of line L8 becomes . By Lemma 1(a) applied at , , and a free index has : 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 . The rows of for clamped indices are zero. So and with . This is the adjoint recursion, so is the derivative of the cost from stage on with respect to , and by the chain rule
The regularization does not enter . So the conditions of Lemma 1(a) at are the stated conditions for . For convex on a convex set they imply a global minimum. Only first derivatives of enter, so dropping the second derivatives of the dynamics does not change this result.
The code stops when , which is a small version of : by Lemma 1(a) and strict convexity, , so every 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 per step for the products with , for the box solver with iterations, and for the dynamics and their Jacobians, so in total; the terms and are at most . A forward pass costs , and the line search tries at most a constant number of step sizes. So one iteration costs , and iterations cost times that. The memory holds the trajectory and the gains, , and the matrices of one step, .
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 , because each step solves only problems of size and .
- 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 by a smooth function of a free variable, such as , removes the box, but the gradient of the cost with respect to vanishes at the limits, and convergence slows down there.
- Second-order DDP. Adding the second derivatives of the dynamics to , and 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 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 of line L5 grows without bound, the steps become tiny and the method stalls; a bound on is needed, and the code stops when exceeds .
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.
# 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
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag DH08X0 Edit this page History Report an error Markdown