Algorithm Search⌘K

Algorithmadvanced

Sequential convex trajectory optimization

Also called TrajOpt.

Schulman's method that convexifies collision constraints with signed distance at each step and solves trust region convex programs.

Time
O(I N n m) worst
Space
O(n m) extra
Where
I = the number of convex subproblems solved; N = the number of Newton steps per subproblem; m = the number of obstacles; n = the number of waypoints
Properties
deterministicnot exactofflinenot randomized

Sequential convex trajectory optimization, known by the name of its software, TrajOpt, treats collision avoidance as a constraint: the signed distance between the robot and each obstacle must stay above a safety margin. The constraint is not convex, so the method replaces it, at the current trajectory, by its linearization, and solves the resulting convex problem only inside a trust region, a box around the current trajectory where the linearization is trusted. It moves to the new trajectory only if the true merit improves enough compared with the improvement the convex model predicted, and it adjusts the box from that comparison. Violated constraints are charged by an ℓ1\ell_1 penalty whose weight grows until they hold. Like all methods for trajectory optimization, it is local: it finds a stationary point near its start.

In plain words

Bend a wire from start to goal so that it is short and keeps a safe distance from every obstacle. Near the current wire, the rule "stay away from this obstacle" is replaced by a simpler rule, "stay on this side of a straight fence", which is easy to obey exactly. Solve the easy version, but only allow the wire to move a little. Then check the real obstacles. If the move helped as much as the easy version promised, keep it and allow bigger moves next time; if not, undo it and allow smaller moves. When nothing helps, check whether the wire is safe; if not, make safety more important and continue. The result is a good wire near the start, not always the best one.

The problem

Input: a start q0q_0 and a goal qn+1q_{n+1}, nn free waypoints x=(x1,…,xn)x = (x_1, \dots, x_n), signed distance functions sdj\mathrm{sd}_j for the obstacles, and a margin dsafed_{\text{safe}}. Minimize

f(x)=∑t=0n∥xt+1−xt∥2subject tosdj(xt)≥dsafe for all t,j,f(x) = \sum_{t=0}^n \|x_{t+1} - x_t\|^2 \quad \text{subject to} \quad \mathrm{sd}_j(x_t) \ge d_{\text{safe}} \text{ for all } t, j,

with x0=q0x_0 = q_0 and xn+1=qn+1x_{n+1} = q_{n+1}. The papers handle robot arms, where xtx_t is a vector of joint angles and the signed distance is computed between convex parts of the robot and of the scene; they also add joint limits, other costs and constraints, and a continuous-time version of the collision constraint. This page uses a point robot in the plane with signed distances given as functions, which keeps the code short.

For a penalty weight μ\mu, the merit function is

φ(x)=f(x)+μ∑t,jmax⁡(0, dsafe−sdj(xt)).\varphi(x) = f(x) + \mu \sum_{t, j} \max\bigl(0,\ d_{\text{safe}} - \mathrm{sd}_j(x_t)\bigr).

The algorithm

  1. SCP(x, μ_0, Δ_0)
  2. 1μ ← μ_0; Δ ← Δ_0
  3. 2for j ← 1 to J do ▷ penalty loop
  4. 3repeat ▷ trust region loop
  5. 4v_k ← sd_k(x_{t_k}); g_k ← ∇sd_k(x_{t_k}) for every constraint k
  6. 5δ ← argmin φ̂(δ) subject to ‖δ‖∞ ≤ Δ ▷ convex subproblem
  7. 6pred ← φ(x) - φ̂(δ); if pred ≤ xtol then leave the loop
  8. 7ρ ← (φ(x) - φ(x + δ)) / pred
  9. 8if ρ ≥ c then x ← x + δ; Δ ← τ₊Δ else Δ ← τ₋Δ
  10. 9until Δ < Δ_min
  11. 10if every constraint holds within ctol then return x
  12. 11μ ← k_μ μ
  13. 12return x ▷ constraints not met

Line L4 linearizes every constraint at the current trajectory: sdk(xtk+δtk)≈vk+gkTδtk\mathrm{sd}_k(x_{t_k} + \delta_{t_k}) \approx v_k + g_k^{\mathsf T}\delta_{t_k}. For a disc obstacle gkg_k is the unit vector from the center to the waypoint. For a robot arm, gkg_k is the normal at the closest points between two convex shapes, found for example with GJK, mapped to joint space by the Jacobian.

Line L5 minimizes the convex model

φ^(δ)=f(x+δ)+μ∑kmax⁡(0, dsafe−vk−gkTδtk)\hat\varphi(\delta) = f(x + \delta) + \mu \sum_k \max\bigl(0,\ d_{\text{safe}} - v_k - g_k^{\mathsf T}\delta_{t_k}\bigr)

over the box ∥δ∥∞≤Δ\|\delta\|_\infty \le \Delta. With one slack variable per hinge it is a quadratic program. The code solves it with a barrier method: Newton steps on the objective plus logarithms of all constraint values, with the weight of the objective raised by a factor 20 until the gap bound is 10−810^{-8}. The slacks enter each Newton system in a diagonal block, so they can be eliminated, which leaves a block tridiagonal system with 2×22 \times 2 blocks, solved in O(n)O(n).

Lines L6 to L9 are the trust region logic. The predicted decrease is what the model promises; the true decrease is measured on φ\varphi. A step is accepted when the ratio is at least c=0.1c = 0.1, and then the box grows by τ+=1.5\tau_+ = 1.5; otherwise it shrinks by τ−=0.5\tau_- = 0.5. Lines L10 and L11 raise the penalty by kμ=10k_\mu = 10 when the trajectory still violates a constraint.

Example

A point moves from (−1,0)(-1, 0) to (1,0)(1, 0) with n=9n = 9 waypoints. One disc of radius 0.50.5 has its center at (0,−0.15)(0, -0.15), so the straight start line cuts it 0.350.35 deep. The margin is dsafe=0.1d_{\text{safe}} = 0.1, μ=10\mu = 10 and Δ0=0.1\Delta_0 = 0.1.

step Δ\Delta predicted decrease true decrease merit φ\varphi smallest clearance height of the middle waypoint
0 15.3560 −0.350-0.350 0.000
1 0.1 6.3416 6.4133 8.9427 −0.250-0.250 0.100
2 0.15 6.3581 6.3581 2.5846 −0.100-0.100 0.250
3 0.225 2.0728 2.0728 0.5118 0.100 0.450
4 0.3375 0.0236 0.0236 0.4882 0.100 0.450
5 0.5063 0.0004 0.0004 0.4878 0.100 0.450

In the first two steps the trust region limits the move: the middle waypoint rises by exactly Δ\Delta. After step 3 the trajectory is feasible and the remaining steps only spread the waypoints. The next predicted decrease is 3.4⋅10−63.4 \cdot 10^{-6}, below xtol=10−4\mathrm{xtol} = 10^{-4}; all constraints hold, so the method returns with μ=10\mu = 10, five accepted steps and none rejected. The result has f=0.48781f = 0.48781, ten equal segments, and length 2.20862.2086.

The true decrease is never below the predicted one here. That is no accident: the distance to a disc is a convex function, so its linearization is below it, and the model is an upper bound on the merit (proof, Theorem 2). The shortest continuous path that keeps a distance of 0.60.6 from the center is 2.21152.2115 long, longer than the result. The difference is the pitfall of discrete constraints: the segments between waypoints cut the corner, and the smallest clearance along the segments is 0.08950.0895, below the margin.

Correctness

The proof shows three things. First, for a fixed penalty weight, every accepted step lowers the merit by more than c⋅xtolc \cdot \mathrm{xtol}, so there are finitely many of them, and the number of rejected steps is bounded too, because each one halves Δ\Delta and the loop ends below Δmin⁡\Delta_{\min}. So the method always ends, and the merit never increases while μ\mu is fixed. Second, if every signed distance is convex in the variables, as for a point robot among convex obstacles, the convex model is an upper bound on the merit, so every step is accepted. Third, if the subproblem is solved exactly and predicts no decrease, then no direction decreases the merit to first order: the point is a stationary point of the penalized problem. With robot arms the signed distance is not convex in the joint angles, steps can be rejected, and the first and third results still hold. None of this says that the result is a global minimum or that it satisfies the constraints; line L10 checks that, and the method is local.

Proof: The trust region loop terminates with a merit that never increases, every step is accepted for convex obstacles, and a stop with zero predicted decrease is a stationary pointfull

We use the notation of the page and of the code. The free waypoints are x=(x1,…,xn)x = (x_1, \dots, x_n) with fixed ends x0=q0x_0 = q_0 and xn+1=qn+1x_{n+1} = q_{n+1}. The constraints are indexed by kk; constraint kk asks sdk(xtk)≥dsafe\mathrm{sd}_k(x_{t_k}) \ge d_{\text{safe}} for a waypoint tkt_k and a signed distance function sdk\mathrm{sd}_k. For a penalty weight μ>0\mu > 0 the merit is

φ(x)=f(x)+μ∑kmax⁡(0, dsafe−sdk(xtk)),f(x)=∑t=0n∥xt+1−xt∥2.\varphi(x) = f(x) + \mu \sum_k \max\bigl(0,\ d_{\text{safe}} - \mathrm{sd}_k(x_{t_k})\bigr), \qquad f(x) = \sum_{t=0}^n \|x_{t+1} - x_t\|^2.

At the current point xˉ\bar x, line L4 computes vk=sdk(xˉtk)v_k = \mathrm{sd}_k(\bar x_{t_k}) and a vector gkg_k (the gradient where it exists, and 00 at the center of a disc). The model of line L5 is

φ^(δ)=f(xˉ+δ)+μ∑kmax⁡(0, dsafe−vk−gkTδtk),\hat\varphi(\delta) = f(\bar x + \delta) + \mu \sum_k \max\bigl(0,\ d_{\text{safe}} - v_k - g_k^{\mathsf T}\delta_{t_k}\bigr),

a convex function of δ\delta: ff is a convex quadratic, and each penalty term is the maximum of 00 and an affine function. Note φ^(0)=φ(xˉ)\hat\varphi(0) = \varphi(\bar x). Line L5 returns some δ\delta with ∥δ∥∞<Δ\|\delta\|_\infty < \Delta: the barrier method keeps its iterates strictly inside the box. Line L6 computes pred=φ^(0)−φ^(δ)\mathrm{pred} = \hat\varphi(0) - \hat\varphi(\delta) for this δ\delta, and line L7 computes the ratio ρ=(φ(xˉ)−φ(xˉ+δ))/pred\rho = (\varphi(\bar x) - \varphi(\bar x + \delta))/\mathrm{pred}. The arguments below use only these definitions; they do not need δ\delta to be an exact minimizer, except in Theorem 3.

Theorem 1: termination and monotone merit

Claim. For a fixed μ\mu, every step accepted by line L8 satisfies φ(xˉ+δ)≤φ(xˉ)−c xtol\varphi(\bar x + \delta) \le \varphi(\bar x) - c\,\mathrm{xtol}. The loop of lines L3 to L9 ends after finitely many passes, and the whole method ends after at most outer values of μ\mu.

Proof. A step is tried only if pred>xtol\mathrm{pred} > \mathrm{xtol} (line L6), and accepted only if ρ≥c\rho \ge c (line L8). Then φ(xˉ)−φ(xˉ+δ)=ρ pred≥c pred>c xtol\varphi(\bar x) - \varphi(\bar x + \delta) = \rho\,\mathrm{pred} \ge c\,\mathrm{pred} > c\,\mathrm{xtol}. So the merit drops by more than c xtolc\,\mathrm{xtol} at each accepted step. The merit is a sum of nonnegative terms, so for a fixed μ\mu the number aa of accepted steps is less than φ(xstart)/(c xtol)+1\varphi(x^{\text{start}})/(c\,\mathrm{xtol}) + 1.

Each rejected step multiplies Δ\Delta by τ−=1/2\tau_- = 1/2, and each accepted step multiplies it by at most τ+=3/2\tau_+ = 3/2. The loop continues only while Δ≥Δmin⁡\Delta \ge \Delta_{\min}. Let Δs\Delta_s be the value of Δ\Delta when the loop starts. If there were r≥1r \ge 1 rejections, then after the first r−1r - 1 of them the loop was still running, so Δmin⁡≤Δ≤Δs(3/2)a2−(r−1)\Delta_{\min} \le \Delta \le \Delta_s (3/2)^a 2^{-(r-1)}, and r≤1+alog⁡2(3/2)+log⁡2(Δs/Δmin⁡)r \le 1 + a\log_2(3/2) + \log_2(\Delta_s/\Delta_{\min}). Both counts are finite, so the inner loop ends. The outer loop of lines L2 to L11 runs at most outer times. □\square

Theorem 2: convex obstacles give a model that is an upper bound

Claim. If every sdk\mathrm{sd}_k is convex and gkg_k is a subgradient of sdk\mathrm{sd}_k at xˉtk\bar x_{t_k}, then φ(xˉ+δ)≤φ^(δ)\varphi(\bar x + \delta) \le \hat\varphi(\delta) for every δ\delta. Hence ρ≥1\rho \ge 1 whenever pred>0\mathrm{pred} > 0, and with c≤1c \le 1 line L8 accepts every step that is tried.

Proof. The subgradient inequality gives sdk(xˉtk+δtk)≥vk+gkTδtk\mathrm{sd}_k(\bar x_{t_k} + \delta_{t_k}) \ge v_k + g_k^{\mathsf T}\delta_{t_k}. The map u↦max⁡(0,dsafe−u)u \mapsto \max(0, d_{\text{safe}} - u) is nonincreasing, so each true penalty term is at most the model penalty term. The smoothness part is the same function f(xˉ+δ)f(\bar x + \delta) in both. So φ(xˉ+δ)≤φ^(δ)\varphi(\bar x + \delta) \le \hat\varphi(\delta), which gives φ(xˉ)−φ(xˉ+δ)≥φ^(0)−φ^(δ)=pred\varphi(\bar x) - \varphi(\bar x + \delta) \ge \hat\varphi(0) - \hat\varphi(\delta) = \mathrm{pred}, that is, ρ≥1\rho \ge 1.

For a disc, sd(p)=∥p−o∥−r\mathrm{sd}(p) = \|p - o\| - r is convex as a norm minus a constant. Its gradient (p−o)/∥p−o∥(p - o)/\|p - o\| is a subgradient for p≠op \ne o, and at p=op = o the vector 00 is a subgradient because ∥p′−o∥≥0\|p' - o\| \ge 0. The code uses exactly these vectors. □\square

So for a point robot among disc obstacles, the trust region in this code never rejects a step; it only limits the step length. For constraints that are not convex, such as the inside of a circle (a concave sd\mathrm{sd}) or the distance between the links of a robot arm and an obstacle as a function of the joint angles, the model can be too optimistic and line L8 can reject steps. Theorem 1 covers that case too.

Theorem 3: what a stop with no predicted decrease means

Claim. Suppose that line L5 returns an exact minimizer of φ^\hat\varphi over the box ∥δ∥∞≤Δ\|\delta\|_\infty \le \Delta with Δ>0\Delta > 0, that pred=0\mathrm{pred} = 0, and that each sdk\mathrm{sd}_k is differentiable at xˉtk\bar x_{t_k} with gradient gkg_k. Then the one-sided directional derivative of φ\varphi at xˉ\bar x is nonnegative in every direction ww:

φ′(xˉ;w)=lim⁡s↓0φ(xˉ+sw)−φ(xˉ)s≥0.\varphi'(\bar x; w) = \lim_{s \downarrow 0} \frac{\varphi(\bar x + s w) - \varphi(\bar x)}{s} \ge 0.

Proof. pred=0\mathrm{pred} = 0 means that δ=0\delta = 0 minimizes φ^\hat\varphi over the box. For s>0s > 0 small enough, swsw is in the box, so φ^(sw)≥φ^(0)\hat\varphi(sw) \ge \hat\varphi(0), and hence φ^′(0;w)≥0\hat\varphi'(0; w) \ge 0.

Now compare the directional derivatives term by term. The smoothness terms are the same differentiable function. Take one penalty term and put ak=dsafe−vka_k = d_{\text{safe}} - v_k. In the model, the term is h(s)=max⁡(0,ak−s gkTwtk)h(s) = \max(0, a_k - s\, g_k^{\mathsf T} w_{t_k}); in the merit it is h~(s)=max⁡(0,ak−(sdk(xˉtk+swtk)−vk))\tilde h(s) = \max(0, a_k - (\mathrm{sd}_k(\bar x_{t_k} + s w_{t_k}) - v_k)), and sdk(xˉtk+swtk)−vk=s gkTwtk+o(s)\mathrm{sd}_k(\bar x_{t_k} + s w_{t_k}) - v_k = s\, g_k^{\mathsf T} w_{t_k} + o(s). If ak>0a_k > 0, both terms are positive for small ss, and both have the right derivative −gkTwtk-g_k^{\mathsf T} w_{t_k}. If ak<0a_k < 0, both are zero for small ss. If ak=0a_k = 0, then h(s)=smax⁡(0,−gkTwtk)h(s) = s \max(0, -g_k^{\mathsf T} w_{t_k}) and h~(s)=smax⁡(0,−gkTwtk)+o(s)\tilde h(s) = s\max(0, -g_k^{\mathsf T} w_{t_k}) + o(s), since u↦max⁡(0,u)u \mapsto \max(0, u) is 1-Lipschitz. So the right derivatives agree term by term, φ′(xˉ;w)=φ^′(0;w)≥0\varphi'(\bar x; w) = \hat\varphi'(0; w) \ge 0. ■\blacksquare

What is not proved

Theorem 3 is a first-order condition for the penalized merit, not for the constrained problem. If the final point still violates a constraint, line L10 fails and line L11 increases μ\mu; with a large enough μ\mu, an ℓ1\ell_1 penalty has the same local solutions as the constrained problem under standard regularity conditions, but this page does not prove that, and if no feasible trajectory is near, μ\mu only grows until the outer limit. Nothing says that the stationary point is a global minimum: the method is local, and a start line on the other side of an obstacle leads to a different answer. Finally, the constraints hold at the waypoints only; the segments between waypoints can still cut into an obstacle.

Complexity

Each Newton step of the subproblem assembles the system in O(nm)O(nm) and solves it in O(n)O(n) after eliminating the slacks; with dd joints instead of 2, the blocks are d×dd \times d and the cost is O(n(d3+md))O(n(d^3 + md)). So one subproblem costs O(Nnm)O(Nnm) for NN Newton steps, and the whole run costs O(INnm)O(INnm) for II subproblems, plus the evaluation of the signed distances at every pass. The memory is O(nm)O(nm). The theory of the barrier method bounds NN by a quantity that grows with the logarithm of the accuracy (see the barrier method page). There is no useful bound on II; the six subproblems of the example are a measurement.

Properties

  • Local. It converges to a stationary point of the penalized merit near the start.
  • Monotone for a fixed penalty. Accepted steps decrease the merit; rejected steps leave the trajectory unchanged.
  • Infeasible starts are allowed. The ℓ1\ell_1 penalty and the slacks make every subproblem feasible, even when the start is deep in collision.
  • Deterministic. The same input gives the same output.
  • Hard constraints in the end. Unlike CHOMP, which charges closeness to obstacles in the cost, the penalty weight grows until the constraints hold or the outer limit is reached.

Variants and improvements

  • Continuous-time collision. Constrain the convex hull of the robot at two consecutive waypoints, not only the waypoints, so that thin obstacles cannot slip between waypoints. The IJRR paper does this.
  • Only nearby obstacles. Linearize only the pairs closer than a threshold; pairs far away have zero penalty and zero effect on the model.
  • Equality constraints. Penalize ∣h(x)∣|h(x)| with the same ℓ1\ell_1 approach, for example for an end effector pose at the goal.
  • Other subproblem solvers. Any solver for convex quadratic programs works for line L5; an interior point method or an active set method is common. The software uses an external solver.
  • Related methods. CHOMP and GPMP2 use costs instead of constraints, and STOMP needs no gradients.

When to use it

Use it for robot arms when the motion must keep a guaranteed margin from obstacles and other constraints, such as joint limits and pose constraints, must hold exactly. It works from infeasible starts such as the straight line in joint space, and it is often fast enough for interactive planning. For problems where a local method fails, use a sampling planner first and this method to improve the result.

Pitfalls

  • Constraints at waypoints only. Line L4 constrains the waypoints, and the segments between them can cut into an obstacle, as in the example. Use the continuous-time version or check the segments.
  • A wrong trust region update. If line L8 accepts steps with a negative ratio, the merit can grow and the loop can cycle. Keep c>0c > 0.
  • The penalty is not the constraint. A stop in line L6 means a stationary point of the merit, not a feasible trajectory. Always check line L10 and report failure when line L12 is reached.
  • Gradients at singular points. At the center of a disc, or where two closest-point pairs switch, the gradient in line L4 is not defined or jumps. Then the subproblem sees a flat or wrong model and the method can stall.
  • Penalty growth. A large μ\mu in line L11 makes the subproblem badly scaled. If no feasible trajectory is near the start, μ\mu grows to the outer limit and the result still violates the constraints.

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.

sequential_convex_trajectory_optimization.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sequential-convex-trajectory-optimization/. The authors are listed in prov/7KE72T.jsonl.
"""Sequential convex trajectory optimization with an l1 penalty and a trust region.

A point robot moves in the plane from q_0 to q_(n+1) through n free
waypoints x_1, ..., x_n. Each constraint is a signed distance function
sd(p) that must stay at least d_safe at every waypoint. The merit is

    phi(x) = f(x) + mu * sum_t sum_j max(0, d_safe - sd_j(x_t)),
    f(x)   = sum_(t=0..n) |x_(t+1) - x_t|^2.

At the current x the signed distances are linearized, sd_j(x_t + d_t) ~
sd_j(x_t) + g_jt . d_t, and the convex model

    phi_hat(d) = f(x + d) + mu * sum max(0, d_safe - sd_j(x_t) - g_jt . d_t)

is minimized subject to |d|_inf <= Delta. The step is accepted when the
true decrease is at least a fraction c of the decrease predicted by the
model; the trust region Delta grows after an accepted step and shrinks
after a rejected one. When no more progress is possible, mu grows until the
constraints hold.

The convex subproblem is a quadratic program with one slack variable per
linearized constraint. It is solved by a log-barrier method with Newton
steps. The slacks are eliminated from each Newton system, which leaves a
block tridiagonal system with 2 x 2 blocks, solved in O(n) by block
elimination. Everything uses the standard library only.
"""

import math


# ---------- signed distance functions: each returns (value, gradient) ----------

def disc_sd(ox, oy, r):
    """Signed distance to a disc obstacle; convex in p. Gradient 0 at the center."""
    def sd(p):
        dx, dy = p[0] - ox, p[1] - oy
        rho = math.hypot(dx, dy)
        if rho == 0.0:
            return -r, (0.0, 0.0)
        return rho - r, (dx / rho, dy / rho)
    return sd


def inside_circle_sd(ox, oy, big_r):
    """Signed distance to the boundary of an allowed circular region; concave in p."""
    def sd(p):
        dx, dy = p[0] - ox, p[1] - oy
        rho = math.hypot(dx, dy)
        if rho == 0.0:
            return big_r, (0.0, 0.0)
        return big_r - rho, (-dx / rho, -dy / rho)
    return sd


# ---------- objective and merit ----------

def straight_line(q0, q1, n):
    return [[q0[d] + (q1[d] - q0[d]) * t / (n + 1) for d in range(2)] for t in range(1, n + 1)]


def smoothness(x, q0, q1):
    pts = [q0] + x + [q1]
    return sum((pts[t + 1][0] - pts[t][0]) ** 2 + (pts[t + 1][1] - pts[t][1]) ** 2 for t in range(len(pts) - 1))


def violation(x, sds, d_safe):
    return sum(max(0.0, d_safe - sd(p)[0]) for p in x for sd in sds)


def max_violation(x, sds, d_safe):
    return max([0.0] + [d_safe - sd(p)[0] for p in x for sd in sds])


def merit(x, q0, q1, sds, d_safe, mu):
    return smoothness(x, q0, q1) + mu * violation(x, sds, d_safe)


def add(x, d):
    return [[x[t][0] + d[2 * t], x[t][1] + d[2 * t + 1]] for t in range(len(x))]


# ---------- 2 x 2 helpers and the block tridiagonal solve ----------

def inv2(m):
    a, b, c, d = m[0][0], m[0][1], m[1][0], m[1][1]
    det = a * d - b * c
    return [[d / det, -b / det], [-c / det, a / det]]


def mul2(m, v):
    return [m[0][0] * v[0] + m[0][1] * v[1], m[1][0] * v[0] + m[1][1] * v[1]]


def block_tridiag_solve(diag, off, rhs):
    """Solve the system with 2 x 2 diagonal blocks diag[t] and off-diagonal blocks off * I."""
    n = len(diag)
    dprime, rprime = [None] * n, [None] * n
    dprime[0], rprime[0] = [row[:] for row in diag[0]], rhs[0][:]
    for t in range(1, n):
        iv = inv2(dprime[t - 1])
        dprime[t] = [[diag[t][i][j] - off * off * iv[i][j] for j in range(2)] for i in range(2)]
        w = mul2(iv, rprime[t - 1])
        rprime[t] = [rhs[t][i] - off * w[i] for i in range(2)]
    x = [None] * n
    x[n - 1] = mul2(inv2(dprime[n - 1]), rprime[n - 1])
    for t in range(n - 2, -1, -1):
        x[t] = mul2(inv2(dprime[t]), [rprime[t][i] - off * x[t + 1][i] for i in range(2)])
    return x


# ---------- the convex subproblem ----------

def model_value(x, q0, q1, lin, d_safe, mu, d):
    """phi_hat(d): exact smoothness plus the l1 penalty of the linearized constraints."""
    pen = sum(max(0.0, d_safe - v - g[0] * d[2 * t] - g[1] * d[2 * t + 1]) for t, v, g in lin)
    return smoothness(add(x, d), q0, q1) + mu * pen


def solve_subproblem(x, q0, q1, lin, d_safe, mu, delta, gap=1e-8):
    """Minimize phi_hat(d) subject to |d|_inf <= delta by a log-barrier method.

    Variables: d (2n entries) and s (one slack per linearized constraint k).
    Minimize f(x + d) + mu sum s subject to s_k >= 0,
    s_k + g_k . d_t - b_k >= 0 with b_k = d_safe - v_k, and -delta <= d <= delta.
    """
    n = len(x)
    nd, ns = 2 * n, len(lin)
    pts = [q0] + x + [q1]
    gf = [0.0] * nd  # gradient of f at d = 0; the Hessian of f is 2 (L kron I2)
    for t in range(n):
        for c in range(2):
            gf[2 * t + c] = 2.0 * (2.0 * pts[t + 1][c] - pts[t][c] - pts[t + 2][c])
    b = [d_safe - v for _, v, _ in lin]
    d = [0.0] * nd
    s = [max(0.0, bk) + 1.0 for bk in b]

    def hf(d, i, t):
        return 4.0 * d[i] - (2.0 * d[i - 2] if t > 0 else 0.0) - (2.0 * d[i + 2] if t < n - 1 else 0.0)

    def barrier(d, s, tau):
        q = sum(gf[i] * d[i] for i in range(nd))
        q += 0.5 * sum(d[2 * t + c] * hf(d, 2 * t + c, t) for t in range(n) for c in range(2))
        val = tau * (q + mu * sum(s))
        for k, (t, _, g) in enumerate(lin):
            lc = s[k] + g[0] * d[2 * t] + g[1] * d[2 * t + 1] - b[k]
            if s[k] <= 0.0 or lc <= 0.0:
                return math.inf
            val -= math.log(s[k]) + math.log(lc)
        for i in range(nd):
            if d[i] >= delta or d[i] <= -delta:
                return math.inf
            val -= math.log(delta - d[i]) + math.log(delta + d[i])
        return val

    m_c = 2 * ns + 2 * nd
    tau = 1.0
    while True:
        for _ in range(200):
            # gradient and Hessian of the barrier function, blocks per waypoint
            gd = [tau * (gf[i] + hf(d, i, i // 2)) for i in range(nd)]
            diag = [[[4.0 * tau, 0.0], [0.0, 4.0 * tau]] for _ in range(n)]
            for i in range(nd):
                v1, v2 = delta - d[i], delta + d[i]
                gd[i] += 1.0 / v1 - 1.0 / v2
                diag[i // 2][i % 2][i % 2] += 1.0 / (v1 * v1) + 1.0 / (v2 * v2)
            gs, hs, cross = [0.0] * ns, [0.0] * ns, [None] * ns
            for k, (t, _, g) in enumerate(lin):
                lc = s[k] + g[0] * d[2 * t] + g[1] * d[2 * t + 1] - b[k]
                w = 1.0 / (lc * lc)
                gs[k] = tau * mu - 1.0 / s[k] - 1.0 / lc
                gd[2 * t] -= g[0] / lc
                gd[2 * t + 1] -= g[1] / lc
                hs[k] = 1.0 / (s[k] * s[k]) + w
                cross[k] = [g[0] * w, g[1] * w]
                for p in range(2):
                    for q in range(2):
                        diag[t][p][q] += g[p] * g[q] * w
            # eliminate the slacks: Schur complement on the d blocks
            rhs = [[-gd[2 * t], -gd[2 * t + 1]] for t in range(n)]
            for k, (t, _, g) in enumerate(lin):
                cr = cross[k]
                for p in range(2):
                    rhs[t][p] -= cr[p] * (-gs[k]) / hs[k]
                    for q in range(2):
                        diag[t][p][q] -= cr[p] * cr[q] / hs[k]
            stepd_blocks = block_tridiag_solve(diag, -2.0 * tau, rhs)
            stepd = [stepd_blocks[i // 2][i % 2] for i in range(nd)]
            steps = [(-gs[k] - cross[k][0] * stepd[2 * t] - cross[k][1] * stepd[2 * t + 1]) / hs[k]
                     for k, (t, _, _) in enumerate(lin)]
            dec = -(sum(gd[i] * stepd[i] for i in range(nd)) + sum(gs[k] * steps[k] for k in range(ns)))
            if dec / 2.0 <= 1e-10:
                break
            alpha, cur = 1.0, barrier(d, s, tau)
            while alpha > 1e-12:
                nd_ = [d[i] + alpha * stepd[i] for i in range(nd)]
                ns_ = [s[k] + alpha * steps[k] for k in range(ns)]
                if barrier(nd_, ns_, tau) <= cur - 0.25 * alpha * dec:
                    d, s = nd_, ns_
                    break
                alpha *= 0.5
            else:
                break
        if m_c / tau <= gap:
            break
        tau *= 20.0
    return d


# ---------- the trust region loop ----------

def scp(q0, q1, n, sds, d_safe=0.1, mu0=10.0, delta0=0.1, c=0.1, tau_plus=1.5, tau_minus=0.5,
        delta_min=1e-4, xtol=1e-4, ctol=1e-4, k_mu=10.0, outer=5, x0=None, log=None):
    """Run the method. Returns (x, info) with info = dict(mu, accepted, rejected, merits)."""
    x = straight_line(q0, q1, n) if x0 is None else [list(p) for p in x0]
    mu, delta = mu0, delta0  # @line L1
    accepted = rejected = 0
    merits = []
    for _ in range(outer):  # @line L2
        while True:  # @line L3
            lin = []
            for t in range(n):
                for sd in sds:
                    v, g = sd(x[t])  # @line L4
                    lin.append((t, v, g))
            d = solve_subproblem(x, q0, q1, lin, d_safe, mu, delta)  # @line L5
            cur = merit(x, q0, q1, sds, d_safe, mu)
            pred = cur - model_value(x, q0, q1, lin, d_safe, mu, d)  # @line L6
            if pred <= xtol:
                break
            new = add(x, d)
            ratio = (cur - merit(new, q0, q1, sds, d_safe, mu)) / pred  # @line L7
            if log is not None:
                log.append((mu, delta, pred, ratio))
            if ratio >= c:  # @line L8
                x, delta = new, min(tau_plus * delta, 1.0)
                accepted += 1
                merits.append((mu, merit(x, q0, q1, sds, d_safe, mu)))
            else:
                delta *= tau_minus
                rejected += 1
            if delta < delta_min:  # @line L9
                break
        if max_violation(x, sds, d_safe) <= ctol:  # @line L10
            return x, dict(mu=mu, accepted=accepted, rejected=rejected, merits=merits)
        mu *= k_mu  # @line L11
    return x, dict(mu=mu, accepted=accepted, rejected=rejected, merits=merits)  # @line L12


def min_clearance(x, sds):
    return min(sd(p)[0] for p in x for sd in sds)


def path_length(x, q0, q1):
    pts = [q0] + x + [q1]
    return sum(math.hypot(pts[t + 1][0] - pts[t][0], pts[t + 1][1] - pts[t][1]) for t in range(len(pts) - 1))
test_sequential_convex_trajectory_optimization.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sequential-convex-trajectory-optimization/. The authors are listed in prov/7KE72T.jsonl.
import random
import unittest

from sequential_convex_trajectory_optimization import (
    add,
    block_tridiag_solve,
    disc_sd,
    inside_circle_sd,
    max_violation,
    merit,
    model_value,
    path_length,
    scp,
    smoothness,
    solve_subproblem,
    straight_line,
)

Q0, Q1 = [-1.0, 0.0], [1.0, 0.0]


def linearize(x, sds):
    return [(t, *sd(x[t])) for t in range(len(x)) for sd in sds]


class TestWorkedExample(unittest.TestCase):
    def test_disc_below_the_line(self):
        sds = [disc_sd(0.0, -0.15, 0.5)]
        log = []
        x, info = scp(Q0, Q1, 9, sds, log=log)
        self.assertAlmostEqual(merit(straight_line(Q0, Q1, 9), Q0, Q1, sds, 0.1, 10.0), 15.356, places=3)
        self.assertEqual((info["mu"], info["accepted"], info["rejected"]), (10.0, 5, 0))
        self.assertAlmostEqual(smoothness(x, Q0, Q1), 0.48781, places=4)
        self.assertAlmostEqual(path_length(x, Q0, Q1), 2.2086, places=3)
        self.assertLessEqual(max_violation(x, sds, 0.1), 1e-4)
        self.assertAlmostEqual(x[4][1], 0.45, places=3)
        values = [m for _, m in info["merits"]]
        self.assertTrue(all(b < a for a, b in zip(values, values[1:])))
        # Convex obstacles: the model is an upper bound, so every ratio is at least 1.
        self.assertTrue(all(r >= 1.0 - 1e-6 for _, _, _, r in log))


class TestEdgeCases(unittest.TestCase):
    def test_no_active_obstacle_keeps_the_line(self):
        sds = [disc_sd(0.0, 3.0, 0.5)]
        x, info = scp(Q0, Q1, 5, sds)
        self.assertEqual(info["accepted"], 0)
        self.assertEqual(x, straight_line(Q0, Q1, 5))

    def test_subproblem_against_grid_search(self):
        # One free waypoint, inside a disc; brute force over the trust region box.
        sds = [disc_sd(0.1, -0.2, 0.4)]
        x = [[0.0, 0.0]]
        lin = linearize(x, sds)
        delta, mu = 0.3, 5.0
        d = solve_subproblem(x, Q0, Q1, lin, 0.1, mu, delta)
        self.assertLessEqual(max(abs(v) for v in d), delta)
        got = model_value(x, Q0, Q1, lin, 0.1, mu, d)
        def m(p):
            return model_value(x, Q0, Q1, lin, 0.1, mu, p)
        h = delta / 30.0
        coarse = min(([delta * (i / 30.0 - 1.0), delta * (j / 30.0 - 1.0)] for i in range(61) for j in range(61)), key=m)
        fine = [[min(delta, max(-delta, coarse[0] + h * (i / 30.0 - 1.0))), min(delta, max(-delta, coarse[1] + h * (j / 30.0 - 1.0)))]
                for i in range(61) for j in range(61)]
        best = min(m(p) for p in fine)
        self.assertLessEqual(got, best + 1e-6)
        self.assertGreater(got, best - 1e-3)

    def test_ratio_test_rejects_and_shrinks(self):
        # A concave constraint (stay inside a circle) makes the model optimistic.
        sds = [inside_circle_sd(0.0, 0.9, 1.0)]
        a, b = [-0.9, 0.0], [0.9, 0.0]
        log = []
        x, info = scp(a, b, 5, sds, delta0=1.0, c=0.98, log=log)
        self.assertGreater(info["rejected"], 0)
        self.assertTrue(any(r < 0.98 for _, _, _, r in log))
        self.assertLessEqual(max_violation(x, sds, 0.1), 1e-4)
        rejected_deltas = [(d0, d1) for (_, d0, _, r), (_, d1, _, _) in zip(log, log[1:]) if r < 0.98]
        self.assertTrue(all(abs(d1 - 0.5 * d0) < 1e-12 for d0, d1 in rejected_deltas))
        values = [m for _, m in info["merits"]]
        self.assertTrue(all(b < a for a, b in zip(values, values[1:])))

    def test_block_tridiagonal_solve(self):
        rng = random.Random(5)
        n, off = 6, -0.7
        diag = []
        for _ in range(n):
            a, b, c = rng.uniform(-0.3, 0.3), rng.uniform(-0.3, 0.3), rng.uniform(-0.3, 0.3)
            diag.append([[3.0 + a, b], [b, 3.0 + c]])
        rhs = [[rng.uniform(-1.0, 1.0), rng.uniform(-1.0, 1.0)] for _ in range(n)]
        x = block_tridiag_solve(diag, off, rhs)
        for t in range(n):
            for i in range(2):
                v = diag[t][i][0] * x[t][0] + diag[t][i][1] * x[t][1]
                if t > 0:
                    v += off * x[t - 1][i]
                if t < n - 1:
                    v += off * x[t + 1][i]
                self.assertAlmostEqual(v, rhs[t][i], places=10)


class TestRandomized(unittest.TestCase):
    def test_random_subproblems_respect_the_box_and_improve_the_model(self):
        rng = random.Random(2013)
        for _ in range(5):
            x = [[rng.uniform(-0.5, 0.5), rng.uniform(-0.5, 0.5)] for _ in range(3)]
            sds = [disc_sd(rng.uniform(-0.5, 0.5), rng.uniform(-0.5, 0.5), rng.uniform(0.1, 0.4))]
            lin = linearize(x, sds)
            delta = rng.uniform(0.05, 0.5)
            d = solve_subproblem(x, Q0, Q1, lin, 0.1, 10.0, delta)
            self.assertLessEqual(max(abs(v) for v in d), delta)
            m0 = model_value(x, Q0, Q1, lin, 0.1, 10.0, [0.0] * 6)
            m1 = model_value(x, Q0, Q1, lin, 0.1, 10.0, d)
            self.assertLessEqual(m1, m0 + 1e-7)
            # The true merit is at most the model for convex obstacles.
            self.assertLessEqual(merit(add(x, d), Q0, Q1, sds, 0.1, 10.0), m1 + 1e-9)


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

History

John Schulman, Jonathan Ho, Alex Lee, Ibrahim Awwal, Henry Bradlow and Pieter Abbeel presented the method at Robotics: Science and Systems in 2013, with the TrajOpt software. The journal version of 2014 added the continuous-time collision constraint and more experiments. It followed CHOMP and STOMP, and differs from them in treating collision as a constraint with a signed distance computed between convex shapes. The trust region and ℓ1\ell_1 penalty framework is older and comes from nonlinear programming.

References

  1. John Schulman, Jonathan Ho, Alex Lee, Ibrahim Awwal, Henry Bradlow and Pieter Abbeel, Finding locally optimal, collision-free trajectories with sequential convex optimization, Robotics: Science and Systems IX, 2013, the whole paper (the original method)
  2. John Schulman, Yan Duan, Jonathan Ho, Alex Lee, Ibrahim Awwal, Henry Bradlow, Jia Pan, Sachin Patil, Ken Goldberg and Pieter Abbeel, Motion planning with sequential convex optimization and convex collision checking, The International Journal of Robotics Research 33(9), 2014, 1251-1270, the sequential convex optimization with l1 penalties and a trust region, and the linearized signed distance constraints
  3. Stephen Boyd and Lieven Vandenberghe, Convex Optimization, Cambridge University Press, 2004, Chapter 11 (the barrier method used for the subproblem)

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