Algorithm Search⌘K

Algorithmresearch

Convex time-optimal path parameterization

Also called Verscheure's method.

Uses the squared path speed as the variable, so that the fastest timing along a fixed path under torque limits becomes one convex program, solved globally.

Time
O(K N m) worst
Space
Θ(N m) extra
Where
K = the number of Newton steps; N = the number of grid intervals; m = the number of constraint rows at a grid point
Properties
deterministicnot exactofflinenot randomized

Convex time-optimal path parameterization finds the fastest way to move along a fixed path when the forces that drive the motion are limited, by solving a single convex optimization problem. A robot arm that must follow a given curve can choose only its timing, and with the speed along the path as the unknown, the limits on the motor torques are nonlinear. Verscheure, Demeulenaere, Swevers, De Schutter and Diehl (2009) observed that with the square of the path speed as the unknown, b=s˙2b = \dot s^2, every torque limit becomes linear and the traversal time becomes a convex function. After the path is cut into NN pieces, the problem is a convex program with about NN variables, so a standard interior point method finds the global optimum of the discretized problem to any accuracy. There are no switch points to find, unlike in the integration method of Bobrow. Because the problem is a general convex program, the objective can also include other convex terms, such as a penalty on torque or a smoothness term, which neither the integration method nor the reachability method allows.

In plain words

Choosing how fast to drive along a fixed road is hard to write down well if you think in terms of speed: the limits on the engine and the brakes depend on the speed in a curved way. If you think in terms of the square of the speed, the same limits become straight lines, and the travel time becomes a bowl-shaped function. Finding the bottom of a bowl inside a region bounded by straight lines is a problem that computers solve reliably: there is only one bottom, and a standard method finds it. So the method cuts the road into many short pieces, writes one unknown per piece, and hands the whole problem to such a solver. The answer is the best timing for that set of pieces, not just a good one.

The problem

Input: a path q(s)q(s) with s∈[0,1]s \in [0, 1], a grid 0=s0<⋯<sN=10 = s_0 < \dots < s_N = 1 with steps Δk\Delta_k, and at each grid point the constraint rows ℓ≤Aa+Bb+c≤h\ell \le A a + B b + c \le h in the path acceleration a=s¨a = \ddot s and the squared path speed b=s˙2b = \dot s^2. Torque limits have this form: along the path the manipulator equation gives τ=Mqsa+(Mqss+C(q,qs)qs)b+g(q)\tau = M q_s a + (M q_{ss} + C(q, q_s) q_s) b + g(q). Rest to rest means b0=bN=0b_0 = b_N = 0.

The acceleration is constant on each piece, so bb is affine in ss there and ak=(bk+1−bk)/(2Δk)a_k = (b_{k+1} - b_k)/(2\Delta_k). Substituting this removes the aka_k, and the problem is:

min⁡b T(b)=∑k=0N−12Δkbk+bk+1subject toℓ≤Akbk+1−bk2Δk+Bkbk+ck≤h,  bk≥0.\min_{b} \ T(b) = \sum_{k=0}^{N-1} \frac{2\Delta_k}{\sqrt{b_k} + \sqrt{b_{k+1}}} \quad \text{subject to}\quad \ell \le A_k \frac{b_{k+1} - b_k}{2\Delta_k} + B_k b_k + c_k \le h,\ \ b_k \ge 0.

T(b)T(b) is the exact traversal time of the piecewise-constant acceleration profile. The constraints are linear and TT is convex, so this is a convex program. Verscheure et al. rewrite it as a second-order cone program with auxiliary variables; this page solves the direct form with a barrier method.

The algorithm

  1. CONVEX-TOPP(grid, rows, ε)
  2. 1b ← (0, δ, ..., δ, 0) with δ halved until every limit holds strictly
  3. 2t ← t_0
  4. 3repeat
  5. 4repeat ▷ Newton's method on t T(b) - Σ log(slack_j)
  6. 5form the gradient and the Hessian of t T(b) - Σ_j log(-g_j(b)) ▷ tridiagonal
  7. 6solve H d = -gradient by the Thomas algorithm
  8. 7λ² ← -gradient · d; if λ²/2 ≤ η then leave the inner loop
  9. 8step ← 1, halved until b + step d is strictly feasible and the barrier value decreases enough
  10. 9b ← b + step d
  11. 10if M / t < ε then return b and a_k = (b_{k+1} - b_k)/(2Δ_k)
  12. 11t ← μ t

The barrier term −∑jlog⁡(−gj(b))-\sum_j \log(-g_j(b)) is finite only where every one of the MM limits holds strictly, so it keeps the iterates inside. Line L1 needs a strictly feasible start; a small constant speed works when every limit holds strictly at rest. Each term of TT and each limit involves only bkb_k and bk+1b_{k+1}, so the Hessian of line L5 is tridiagonal and line L6 solves it in O(N)O(N) time by the Thomas algorithm. Line L7 measures the Newton decrement, line L8 is a backtracking line search, and lines L10 and L11 raise the weight tt of the time against the barrier until the duality gap bound M/tM/t is below ε\varepsilon. The code uses t0=1t_0 = 1, μ=20\mu = 20 and ε=10−9\varepsilon = 10^{-9}.

Example

One axis. q(s)=sq(s) = s with ∣q˙∣≤1|\dot q| \le 1 and ∣q¨∣≤2|\ddot q| \le 2 on the grid sk=k/4s_k = k/4. The optimum is b=(0,1,1,1,0)b = (0, 1, 1, 1, 0) and a=(2,0,0,−2)a = (2, 0, 0, -2), the trapezoidal profile with T=1.5T = 1.5. The barrier method reaches it to within 2⋅10−102 \cdot 10^{-10} in 49 Newton steps. Without the velocity limit, on 8 intervals, it returns the triangle with T=2T = \sqrt 2.

A 2R arm. The planar arm with unit links, unit point masses at the link ends and no gravity follows the straight joint path from (0,0)(0, 0) to (2,−3)(2, -3) with ∣τ1∣≤10|\tau_1| \le 10 and ∣τ2∣≤4|\tau_2| \le 4. On 10 intervals the optimum and the greedy profile of TOPP-RA, for the same discretization, are:

kk 0 1 2 3 4 5 6 7 8 9 10
bkb_k (convex) 0 0.500 1.028 1.165 0.877 1.408 1.031 1.029 0.829 0.324 0
xkx_k (TOPP-RA) 0 0.500 1.028 1.260 1.218 0.826 0.990 1.010 0.829 0.324 0

The convex optimum takes T=1.46762T = 1.46762 and the greedy profile 1.477721.47772. The optimum gives up speed at k=3k = 3 and k=4k = 4 to be much faster at k=5k = 5, which the greedy pass cannot see. On 50 intervals the optimum is 1.505551.50555 (115 Newton steps) and on 200 intervals 1.509601.50960 (235 Newton steps), where the two methods agree to about 10−510^{-5}. The zigzag at k=4k = 4 and k=5k = 5 is an effect of the coarse grid, not of the robot.

Correctness

Theorem (Verscheure et al. 2009): with b=s˙2b = \dot s^2 the discretized problem is convex. The proof shows that the sum bk+bk+1\sqrt{b_k} + \sqrt{b_{k+1}} is concave, so its reciprocal is convex, and that the limits are linear in bb once aa is eliminated. The barrier method then gives a point that meets every limit strictly and whose time is within M/tM/t of the optimum: at the minimizer of the barrier problem, the numbers 1/(t⋅slackj)1/(t \cdot \text{slack}_j) are Lagrange multipliers that certify this bound by weak duality. See the proof. The theorem assumes exact centering; the code stops when the Newton decrement is small, which adds an error of the same order.

The result is the global optimum of the discretized problem, not of the continuous one. Limits hold at the grid points, and the error between grid points is O(Δ)O(\Delta).

Proof: The discretized time-optimal problem in b = s'^2 is convex, and the barrier method returns a feasible point within M / t of the optimumfull

We use the notation of the page. The grid is s0<⋯<sNs_0 < \dots < s_N with steps Δk>0\Delta_k > 0. The variables are b0,…,bNb_0, \dots, b_N with b0=bN=0b_0 = b_N = 0, and ak=(bk+1−bk)/(2Δk)a_k = (b_{k+1} - b_k)/(2\Delta_k) for k<Nk < N. The constraints are bk≥0b_k \ge 0 and, for each row (A,B,c,ℓ,h)(A, B, c, \ell, h) at sks_k, ℓ≤Aak+Bbk+c≤h\ell \le A a_k + B b_k + c \le h. Substituting aka_k, each of these is an affine inequality gj(b)≤0g_j(b) \le 0 in bb; there are MM of them. The objective is

T(b)=∑k=0N−12Δkbk+bk+1.T(b) = \sum_{k=0}^{N-1} \frac{2\Delta_k}{\sqrt{b_k} + \sqrt{b_{k+1}}}.

Step 1: T is the traversal time

Lemma 1. If the path acceleration s¨\ddot s is the constant aka_k on [sk,sk+1][s_k, s_{k+1}] and s˙2=bk\dot s^2 = b_k at sks_k, then s˙2=bk+1\dot s^2 = b_{k+1} at sk+1s_{k+1} exactly when ak=(bk+1−bk)/(2Δk)a_k = (b_{k+1} - b_k)/(2\Delta_k), and the time to cross the interval is 2Δk/(bk+bk+1)2\Delta_k / (\sqrt{b_k} + \sqrt{b_{k+1}}).

Proof. d(s˙2)/ds=2s˙s¨/s˙=2s¨d(\dot s^2)/ds = 2\dot s \ddot s / \dot s = 2\ddot s, so s˙2\dot s^2 is affine in ss on the interval: β(s)=bk+2ak(s−sk)\beta(s) = b_k + 2a_k (s - s_k), which gives the first claim. The time is ∫sksk+1ds/β(s)\int_{s_k}^{s_{k+1}} ds / \sqrt{\beta(s)}. If ak≠0a_k \ne 0 this is (bk+1−bk)/ak=2Δk(bk+1−bk)/(bk+1−bk)=2Δk/(bk+bk+1)(\sqrt{b_{k+1}} - \sqrt{b_k})/a_k = 2\Delta_k (\sqrt{b_{k+1}} - \sqrt{b_k})/(b_{k+1} - b_k) = 2\Delta_k/(\sqrt{b_k} + \sqrt{b_{k+1}}). If ak=0a_k = 0 then bk=bk+1b_k = b_{k+1} and the time is Δk/bk\Delta_k/\sqrt{b_k}, the same value. □\square

So the program "minimize T(b)T(b) subject to gj(b)≤0g_j(b) \le 0" is exactly the discretized time-optimal path parameterization.

Step 2: the program is convex

Lemma 2. TT is convex on {b≥0}\{b \ge 0\}, with the value +∞+\infty where some term has a zero denominator.

Proof. For one term, σ(x,y)=x+y\sigma(x, y) = \sqrt x + \sqrt y is concave on [0,∞)2[0, \infty)^2 as a sum of concave functions, and ϕ(z)=1/z\phi(z) = 1/z is convex and decreasing on (0,∞)(0, \infty). For points p,qp, q and θ∈[0,1]\theta \in [0, 1], concavity gives σ(θp+(1−θ)q)≥θσ(p)+(1−θ)σ(q)\sigma(\theta p + (1 - \theta) q) \ge \theta \sigma(p) + (1 - \theta)\sigma(q); because ϕ\phi is decreasing and then convex,

ϕ(σ(θp+(1−θ)q))≤ϕ(θσ(p)+(1−θ)σ(q))≤θϕ(σ(p))+(1−θ)ϕ(σ(q)).\phi(\sigma(\theta p + (1 - \theta) q)) \le \phi(\theta \sigma(p) + (1 - \theta)\sigma(q)) \le \theta \phi(\sigma(p)) + (1 - \theta)\phi(\sigma(q)).

With ϕ(0)=+∞\phi(0) = +\infty the inequality also holds when a denominator is zero. A sum of convex functions with positive weights 2Δk2\Delta_k is convex. □\square

The constraints are affine, so the feasible set is a convex polyhedron, and every local minimum of TT on it is a global minimum.

Step 3: the iterates stay strictly feasible

Line L1 accepts a start only if every slack −gj-g_j is positive. Line L8 accepts a step only if the barrier value is finite, that is, only if every slack of the new point is positive. So every iterate bb, and the returned point, has gj(b)<0g_j(b) < 0 for all jj: it meets every limit and has bk>0b_k > 0 at the interior grid points.

Step 4: the gap bound

For t>0t > 0 let Φt(b)=t T(b)−∑jlog⁡(−gj(b))\Phi_t(b) = t\,T(b) - \sum_j \log(-g_j(b)) on the open set D={b:gj(b)<0 for all j}D = \{b : g_j(b) < 0 \text{ for all } j\}, and let b(t)b(t) be its minimizer (the "central point").

Lemma 3. If b(t)b(t) exists, then T(b(t))−T∗≤M/tT(b(t)) - T^* \le M/t, where T∗T^* is the least value of TT on the feasible set.

Proof. At b(t)b(t) the gradient of Φt\Phi_t is zero:

t∇T(b(t))+∑j1−gj(b(t))∇gj=0.t \nabla T(b(t)) + \sum_j \frac{1}{-g_j(b(t))} \nabla g_j = 0.

Put λj=1/(t⋅(−gj(b(t))))>0\lambda_j = 1/(t \cdot (-g_j(b(t)))) > 0. Dividing by tt, ∇T(b(t))+∑jλj∇gj=0\nabla T(b(t)) + \sum_j \lambda_j \nabla g_j = 0, so b(t)b(t) is a stationary point of the Lagrangian L(b)=T(b)+∑jλjgj(b)\mathcal L(b) = T(b) + \sum_j \lambda_j g_j(b). L\mathcal L is convex (Lemma 2, plus affine terms), so b(t)b(t) minimizes L\mathcal L over the open set where it is differentiable, and by continuity of L\mathcal L with values in (−∞,+∞](-\infty, +\infty], also over its closure. For any feasible b^\hat b, gj(b^)≤0g_j(\hat b) \le 0 and λj>0\lambda_j > 0, so

T(b^)≥T(b^)+∑jλjgj(b^)=L(b^)≥L(b(t))=T(b(t))+∑jλjgj(b(t))=T(b(t))−Mt,T(\hat b) \ge T(\hat b) + \sum_j \lambda_j g_j(\hat b) = \mathcal L(\hat b) \ge \mathcal L(b(t)) = T(b(t)) + \sum_j \lambda_j g_j(b(t)) = T(b(t)) - \frac{M}{t},

because each λjgj(b(t))=−1/t\lambda_j g_j(b(t)) = -1/t. Taking the infimum over feasible b^\hat b gives T∗≥T(b(t))−M/tT^* \ge T(b(t)) - M/t. □\square

Theorem

Theorem. Assume the start of line L1 is strictly feasible and each centering loop (lines L4 to L9) ends at the central point b(t)b(t). Then the algorithm returns a point bb that meets every limit strictly, and T(b)≤T∗+εT(b) \le T^* + \varepsilon.

Proof. Feasibility is Step 3. The algorithm returns at line L10 with M/t<εM/t < \varepsilon, at the central point b(t)b(t), so Lemma 3 gives T(b)≤T∗+M/t<T∗+εT(b) \le T^* + M/t < T^* + \varepsilon. ■\blacksquare

Remarks

The code stops each centering loop when half the squared Newton decrement λ2/2\lambda^2/2 is below a tolerance η\eta. For a self-concordant barrier problem, Φt(b)−Φt(b(t))≤λ2\Phi_t(b) - \Phi_t(b(t)) \le \lambda^2 when λ\lambda is small (Boyd and Vandenberghe, Chapter 9), so the gap bound becomes M/t+O(η/t)M/t + O(\eta/t). The function 1/(x+y)1/(\sqrt x + \sqrt y) is not known to be self-concordant, so the classical bound on the number of Newton steps does not apply to this direct form. Verscheure et al. (2009) write the problem as a second-order cone program with auxiliary variables, for which the barrier is self-concordant and an interior point method needs O(Mlog⁡(M/ε))O(\sqrt M \log(M/\varepsilon)) Newton steps. The step counts reported on the page are measurements.

Complexity

One Newton step forms the tridiagonal system in O(Nm)O(Nm) time for mm rows per point, solves it in O(N)O(N), and each trial of the line search costs O(Nm)O(Nm). For the second-order cone form, interior point theory bounds the number of Newton steps by O(Nm log⁡(Nm/ε))O(\sqrt{Nm}\, \log(Nm/\varepsilon)), which gives O((Nm)1.5log⁡(Nm/ε))O((Nm)^{1.5} \log(Nm/\varepsilon)) in total. The direct form used here has no such proven bound, because its barrier is not known to be self-concordant; the measured counts are 49 to 235 steps for NN from 4 to 200. Memory is Θ(Nm)\Theta(Nm) for the rows. A general solver that does not use the band structure pays more per step; Pham and Pham (2018) compare the costs of the approaches.

Properties

  • Globally optimal for the discretization. A theorem: the program is convex, so any local optimum is global.
  • Strictly feasible output. Every iterate meets every limit with a positive margin.
  • Flexible objective. Any convex term can be added, for example ∑∥τk∥2\sum \|\tau_k\|^2 to save energy, or a bound on the rate of change of the torque written in bb.
  • No switch points. Velocity limits, singular arcs and zero-inertia points need no special treatment.
  • Slower than the reachability method. For pure minimum time on a fine grid, TOPP-RA gives nearly the same answer with O(N)O(N) tiny linear programs.

Variants and improvements

  • Second-order cone form. Verscheure et al. introduce auxiliary variables for the square roots and their reciprocals and obtain a second-order cone program, which off-the-shelf solvers accept.
  • Energy and smoothness. Adding a convex penalty on the torques gives a family of trade-offs between time and effort. Adding a penalty on the change of aka_k smooths the jumps of the acceleration.
  • Third-order limits. A limit on jerk or on the rate of change of torque is not convex in bb. Adding it needs a nonconvex method, for example a sequence of convex problems built around the one on this page.
  • Other methods for the same problem. The Bobrow integration method and the reachability method.

When to use it

Use the convex formulation when you need the guaranteed optimum of the discretized problem, when the objective has more than the time, or when a general convex solver is already in the system. For pure minimum time in a fast loop, TOPP-RA is cheaper. Combined with a path optimizer, the convex problem also serves as an inner step of trajectory optimization over both the path and the timing.

Pitfalls

  • No strictly feasible start. Line L1 needs a point where every limit holds with a margin. If some limit is active at rest, for example gravity that a motor can only just hold, the barrier is undefined there, and a phase-one problem must find the start.
  • Zigzag on a coarse grid. As the example shows, the optimum can oscillate from one grid point to the next, because the limits are checked only at grid points. Use a finer grid or limit the change of aka_k.
  • Hessian near zero speed. The terms bk−1/2b_k^{-1/2} next to the end points have second derivatives that grow like bk−5/2b_k^{-5/2}. Line L5 then has a large spread of values; the Thomas algorithm is stable here because the matrix is positive definite, but the line search of line L8 must still reject steps that make some bkb_k negative.
  • Stopping on the gap alone. Line L10 bounds the error only if each centering loop has converged. Stopping a centering loop early, after a fixed number of Newton steps, gives a point that may be farther from the optimum than M/tM/t.

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.

convex_time_optimal_path_parameterization.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/convex-time-optimal-path-parameterization/. The authors are listed in prov/KKZDAS.jsonl.
"""Time-optimal path parameterization as one convex program (Verscheure,
Demeulenaere, Swevers, De Schutter and Diehl 2009).

Grid s_0 < ... < s_N. Variables b_k = s'^2 at the grid points, with
b_0 = b_N = 0 (rest to rest). The path acceleration a_k = s'' is constant on
[s_k, s_(k+1)], so a_k = (b_(k+1) - b_k) / (2 Delta_k) is eliminated. The
constraint rows (A, B, c, lo, hi) at s_k mean lo <= A a_k + B b_k + c <= hi;
they are linear in b. The traversal time

    T(b) = sum_k 2 Delta_k / (sqrt(b_k) + sqrt(b_(k+1)))

is convex. The program is solved by a log-barrier interior point method:
Newton's method on t T(b) - sum log(slack), with t increased by a factor mu.
Each constraint and each term of T couples only b_k and b_(k+1), so the
Newton system is tridiagonal and costs O(N) to solve (Thomas algorithm).
One Newton step costs O(N m) for m rows per grid point.

The start point b_k = delta must be strictly feasible for a small delta;
this holds when every row is strictly met at zero speed (lo < c < hi).
"""

import math

INF = math.inf


def _constraints(grid, rows):
    """Linear inequalities p * b_k + q * b_(k+1) + r <= 0 over the full vector b."""
    n = len(grid) - 1
    out = []
    for k in range(n):
        d2 = 2.0 * (grid[k + 1] - grid[k])
        for a, bb, c, lo, hi in rows[k]:
            p, q = bb - a / d2, a / d2  # A a_k + B b_k = p b_k + q b_(k+1)
            if hi < INF:
                out.append((k, p, q, c - hi))
            if lo > -INF:
                out.append((k, -p, -q, lo - c))
    for k in range(1, n):
        out.append((k, -1.0, 0.0, 0.0))  # b_k > 0
    return out


def _slacks(cons, b):
    """Values -g_j(b) > 0 for a strictly feasible b, else None."""
    out = []
    for k, p, q, r in cons:
        v = -(p * b[k] + q * b[k + 1] + r)
        if v <= 0.0:
            return None
        out.append(v)
    return out


def traversal_time(grid, b):
    """T(b); infinite if two neighbours are both zero."""
    t = 0.0
    for k in range(len(grid) - 1):
        den = math.sqrt(max(b[k], 0.0)) + math.sqrt(max(b[k + 1], 0.0))
        if den == 0.0:
            return INF
        t += 2.0 * (grid[k + 1] - grid[k]) / den
    return t


def _time_derivs(grid, b):
    """Gradient and tridiagonal Hessian (diag, off) of T with respect to b."""
    n = len(grid) - 1
    g = [0.0] * (n + 1)
    dg = [0.0] * (n + 1)
    off = [0.0] * n  # off[k] couples b_k and b_(k+1)
    for k in range(n):
        w = 2.0 * (grid[k + 1] - grid[k])
        x, y = b[k], b[k + 1]
        if x == 0.0 or y == 0.0:  # one end fixed at 0: w * z^(-1/2)
            j, z = (k + 1, y) if x == 0.0 else (k, x)
            g[j] += -0.5 * w * z ** -1.5
            dg[j] += 0.75 * w * z ** -2.5
            continue
        p, q = math.sqrt(x), math.sqrt(y)
        s = p + q
        g[k] += -w / (2.0 * p * s * s)
        g[k + 1] += -w / (2.0 * q * s * s)
        dg[k] += w * (1.0 / (4.0 * p ** 3 * s * s) + 1.0 / (2.0 * p * p * s ** 3))
        dg[k + 1] += w * (1.0 / (4.0 * q ** 3 * s * s) + 1.0 / (2.0 * q * q * s ** 3))
        off[k] += w / (2.0 * p * q * s ** 3)
    return g, dg, off


def thomas(diag, off, rhs):
    """Solve a symmetric tridiagonal system (diag, off) x = rhs in O(n)."""
    n = len(diag)
    c = [0.0] * n
    d = [0.0] * n
    m = diag[0]
    c[0] = off[0] / m if n > 1 else 0.0
    d[0] = rhs[0] / m
    for i in range(1, n):
        m = diag[i] - off[i - 1] * c[i - 1]
        c[i] = off[i] / m if i < n - 1 else 0.0
        d[i] = (rhs[i] - off[i - 1] * d[i - 1]) / m
    x = [0.0] * n
    x[-1] = d[-1]
    for i in range(n - 2, -1, -1):
        x[i] = d[i] - c[i] * x[i + 1]
    return x


def convex_topp(grid, rows, eps=1e-9, t0=1.0, mu=20.0, newton_tol=1e-9, max_newton=60):
    """Return (b, a, info) with the optimal b_k = s'^2 and a_k = s'', or None.

    The barrier problem for each t is solved until half the squared Newton
    decrement is below newton_tol, or for at most max_newton steps.
    info: {"newton": total Newton steps, "gap": M / t at the end}.
    """
    n = len(grid) - 1
    cons = _constraints(grid, rows)
    m_total = len(cons)
    delta = 1.0
    b = None
    for _ in range(80):  # @line L1
        cand = [0.0] + [delta] * (n - 1) + [0.0]
        if _slacks(cons, cand) is not None:
            b = cand
            break
        delta *= 0.5
    if b is None:
        return None
    t = t0  # @line L2
    steps = 0
    while True:  # @line L3
        inner = 0
        while True:  # @line L4
            slack = _slacks(cons, b)
            g, dg, off = _time_derivs(grid, b)  # @line L5
            grad = [t * v for v in g]
            dia = [t * v for v in dg]
            offd = [t * v for v in off]
            for (k, p, q, r), sl in zip(cons, slack):
                grad[k] += p / sl
                grad[k + 1] += q / sl
                dia[k] += p * p / (sl * sl)
                dia[k + 1] += q * q / (sl * sl)
                offd[k] += p * q / (sl * sl)
            # interior variables 1..n-1 only (b_0 and b_n are fixed)
            step_dir = thomas(dia[1:n], offd[1:n - 1] + [0.0], [-v for v in grad[1:n]])  # @line L6
            lam2 = -sum(gv * dv for gv, dv in zip(grad[1:n], step_dir))  # @line L7
            if lam2 / 2.0 <= newton_tol or inner >= max_newton:
                break
            step = 1.0  # @line L8
            f0 = _barrier_value(grid, cons, b, t)
            while True:
                cand = [0.0] + [b[i] + step * step_dir[i - 1] for i in range(1, n)] + [0.0]
                f1 = _barrier_value(grid, cons, cand, t)
                if f1 is not None and f1 <= f0 - 0.25 * step * lam2:
                    break
                step *= 0.5
                if step < 1e-20:
                    break
            if step < 1e-20:
                break
            b = cand  # @line L9
            steps += 1
            inner += 1
        if m_total / t < eps:  # @line L10
            a = [(b[k + 1] - b[k]) / (2.0 * (grid[k + 1] - grid[k])) for k in range(n)]
            return b, a, {"newton": steps, "gap": m_total / t}
        t *= mu  # @line L11


def _barrier_value(grid, cons, b, t):
    """t T(b) - sum log(slack), or None if b is not strictly feasible."""
    slack = _slacks(cons, b)
    if slack is None:
        return None
    return t * traversal_time(grid, b) - sum(math.log(s) for s in slack)


def max_violation(rows, a, b):
    """Largest amount by which (a_k, b_k) breaks a row, over k < N."""
    worst = 0.0
    for k in range(len(a)):
        for aa, bb, c, lo, hi in rows[k]:
            v = aa * a[k] + bb * b[k] + c
            worst = max(worst, v - hi, lo - v)
    return max(worst, -min(b))


# ---------------------------------------------------------------- examples


def uniform_grid(n):
    return [i / n for i in range(n + 1)]


def single_axis_rows(grid, dist, vmax, amax):
    """q(s) = dist * s with |q'| <= vmax and |q''| <= amax."""
    rows = []
    for _ in grid:
        r = [(dist, 0.0, 0.0, -amax, amax)]
        if vmax < INF:
            r.append((0.0, dist * dist, 0.0, -INF, vmax * vmax))
        rows.append(r)
    return rows


def arm2r_rows(grid, q0, q1, tau_max):
    """Torque rows of the planar 2R arm (unit links, unit end masses, no
    gravity) along q(s) = q0 + s (q1 - q0): tau = M q_s a + C(q, q_s) q_s b."""
    dq = [q1[0] - q0[0], q1[1] - q0[1]]
    rows = []
    for s in grid:
        q2 = q0[1] + s * dq[1]
        c2, s2 = math.cos(q2), math.sin(q2)
        m11, m12 = 3.0 + 2.0 * c2, 1.0 + c2
        aa = [m11 * dq[0] + m12 * dq[1], m12 * dq[0] + dq[1]]
        bb = [-s2 * (2.0 * dq[0] * dq[1] + dq[1] * dq[1]), s2 * dq[0] * dq[0]]
        rows.append([(aa[j], bb[j], 0.0, -tau_max[j], tau_max[j]) for j in range(2)])
    return rows
test_convex_time_optimal_path_parameterization.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/convex-time-optimal-path-parameterization/. The authors are listed in prov/KKZDAS.jsonl.
import math
import random
import unittest

from convex_time_optimal_path_parameterization import (
    INF,
    arm2r_rows,
    convex_topp,
    max_violation,
    single_axis_rows,
    thomas,
    traversal_time,
    uniform_grid,
)


def admissible(grid, rows, b, tol=1e-12):
    n = len(grid) - 1
    a = [(b[k + 1] - b[k]) / (2.0 * (grid[k + 1] - grid[k])) for k in range(n)]
    return min(b) >= 0.0 and max_violation(rows, a, b) <= tol


def brute_force_3(grid, rows, top, steps):
    """Best time over a square lattice of (b_1, b_2) for a grid with N = 3."""
    best = INF
    for i in range(1, steps + 1):
        for j in range(1, steps + 1):
            b = [0.0, top * i / steps, top * j / steps, 0.0]
            if admissible(grid, rows, b):
                best = min(best, traversal_time(grid, b))
    return best


class TestWorkedExample(unittest.TestCase):
    def test_single_axis_trapezoid(self):
        g = uniform_grid(4)
        b, a, info = convex_topp(g, single_axis_rows(g, 1.0, 1.0, 2.0))
        for got, want in zip(b, [0.0, 1.0, 1.0, 1.0, 0.0]):
            self.assertAlmostEqual(got, want, delta=1e-6)
        self.assertAlmostEqual(traversal_time(g, b), 1.5, delta=1e-8)
        self.assertLess(info["gap"], 1e-9)

    def test_single_axis_triangle(self):
        g = uniform_grid(8)
        b, a, _ = convex_topp(g, single_axis_rows(g, 1.0, INF, 2.0))
        self.assertAlmostEqual(traversal_time(g, b), math.sqrt(2.0), delta=1e-8)

    def test_arm_example(self):
        g = uniform_grid(50)
        rows = arm2r_rows(g, [0.0, 0.0], [2.0, -3.0], [10.0, 4.0])
        b, a, _ = convex_topp(g, rows)
        self.assertLessEqual(max_violation(rows, a, b), 0.0)
        self.assertAlmostEqual(traversal_time(g, b), 1.50555, delta=1e-5)
        # The optimum is on the boundary: a profile 1% faster breaks a limit.
        self.assertGreater(max_violation(rows, [1.01 * v for v in a], [1.01 * v for v in b]), 1e-3)


class TestEdgeCases(unittest.TestCase):
    def test_no_strictly_feasible_start(self):
        # u >= 0 everywhere: the robot can never brake to rest.
        g = uniform_grid(4)
        rows = [[(1.0, 0.0, 0.0, 0.0, 2.0)] for _ in g]
        self.assertIsNone(convex_topp(g, rows))

    def test_thomas_against_dense(self):
        rng = random.Random(11)
        n = 6
        diag = [rng.uniform(3.0, 5.0) for _ in range(n)]
        off = [rng.uniform(-1.0, 1.0) for _ in range(n - 1)]
        rhs = [rng.uniform(-1.0, 1.0) for _ in range(n)]
        x = thomas(diag, off, rhs)
        for i in range(n):
            v = diag[i] * x[i]
            if i > 0:
                v += off[i - 1] * x[i - 1]
            if i < n - 1:
                v += off[i] * x[i + 1]
            self.assertAlmostEqual(v, rhs[i], places=12)

    def test_two_grid_intervals(self):
        # N = 2: one free variable; the optimum is b_1 = min(vmax^2, 2 a Delta * 2 / 2).
        g = uniform_grid(2)
        b, _, _ = convex_topp(g, single_axis_rows(g, 1.0, INF, 2.0))
        self.assertAlmostEqual(b[1], 2.0, delta=1e-6)


class TestRandomized(unittest.TestCase):
    def test_against_brute_force(self):
        rng = random.Random(2009)
        g = uniform_grid(3)
        for _ in range(3):
            q1 = [rng.uniform(-3.0, 3.0), rng.uniform(-3.0, 3.0)]
            tau = [rng.uniform(4.0, 12.0), rng.uniform(2.0, 6.0)]
            rows = arm2r_rows(g, [0.0, 0.0], q1, tau)
            b, a, _ = convex_topp(g, rows)
            self.assertLessEqual(max_violation(rows, a, b), 0.0)
            t = traversal_time(g, b)
            top = 1.2 * max(b)
            t_bf = brute_force_3(g, rows, top, 150)
            self.assertLessEqual(t, t_bf + 1e-9)
            self.assertLessEqual(t_bf, t * 1.02)

    def test_random_admissible_profiles_are_slower(self):
        # Random lattice profiles on a coarse grid: none beats the optimum.
        rng = random.Random(5)
        g = uniform_grid(4)
        rows = arm2r_rows(g, [0.0, 0.0], [1.5, 2.5], [10.0, 4.0])
        b, _, _ = convex_topp(g, rows)
        t = traversal_time(g, b)
        tried = 0
        for _ in range(3000):
            c = [0.0] + [rng.uniform(0.0, 1.2 * max(b)) for _ in range(3)] + [0.0]
            if admissible(g, rows, c):
                tried += 1
                self.assertGreaterEqual(traversal_time(g, c), t - 1e-9)
        self.assertGreater(tried, 10)


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

History

Time-optimal path parameterization was solved in 1985 by integration in the phase plane (Bobrow, Dubowsky and Gibson; Shin and McKay). The use of s˙2\dot s^2 as the state was already standard in that work. Verscheure, Demeulenaere, Swevers, De Schutter and Diehl (2009) showed that in this variable the whole discretized problem is convex, which allowed a general convex solver, a global optimum and additional convex objectives. Pham and Pham (2018) showed that for the pure minimum-time problem a much cheaper sequence of linear programs suffices.

References

  1. Diederik Verscheure, Bram Demeulenaere, Jan Swevers, Joris De Schutter and Moritz Diehl, Time-optimal path tracking for robots: a convex optimization approach, IEEE Transactions on Automatic Control 54(10), 2009, 2318-2327, the whole paper (the change of variables b = s'^2, the convexity of the problem, the discretization and the second-order cone form)
  2. Stephen Boyd and Lieven Vandenberghe, Convex Optimization, Cambridge University Press, 2004, Chapter 11 (interior-point methods, the barrier method and its duality gap) and Chapter 9 (Newton's method)
  3. Hung Pham and Quang-Cuong Pham, A new approach to time-optimal path parameterization based on reachability analysis, IEEE Transactions on Robotics 34(3), 2018, 645-659, Section IV-D (comparison of the cost of the convex approach with the reachability approach)

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