Algorithm Search⌘K

Algorithmresearch

Time-optimal path parameterization by reachability analysis

Also called TOPP-RA.

Discretizes the path and solves small two-variable LPs, backward for the controllable sets and forward for the greedy profile; no switch points to find.

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

TOPP-RA computes the fastest way to move a robot along a fixed path when the motors have torque, velocity or acceleration limits. It cuts the path into NN short pieces and works with the squared path speed x=s˙2x = \dot s^2 at the grid points. A backward pass finds, at each grid point, the interval KiK_i of speeds from which the robot can still reach the end of the path without breaking a limit; each interval is the projection of a polygon and costs one small linear program in two variables. A forward pass then starts at rest and, at each grid point, takes the largest acceleration that keeps the next speed inside the next interval. The result is an admissible profile whenever one exists (a theorem), and it is time-optimal for the discretized problem when the grid is fine enough and the path has no zero-inertia points (a theorem with these conditions). Unlike the integration method of Bobrow, it never has to find switch points or follow singular arcs, which is where integration codes fail. It is the method of Pham and Pham (2018). The path itself is an input and is not changed.

In plain words

A robot must drive along a fixed road as fast as it can. Its engine and brakes are limited, and the limits change along the road. Work backward from the finish: at each mile marker, find the range of speeds from which the robot can still slow down in time for every later marker. Near the finish this range is small; further back it is larger. Then drive forward from the start. At each marker, press the pedal as hard as you can, but not so hard that you land outside the safe range at the next marker. Because each range was built to guarantee a safe future, the robot never gets stuck, and the greedy choice gives a fast profile. Each range comes from a tiny geometry problem with two unknowns, so the method is fast and does not depend on delicate root finding.

The problem

Input: a path q(s)q(s) in joint space with s∈[0,1]s \in [0, 1], a grid 0=s0<s1<⋯<sN=10 = s_0 < s_1 < \dots < s_N = 1 with steps Δi=si+1−si\Delta_i = s_{i+1} - s_i, the squared speeds xstartx_{\text{start}} and xendx_{\text{end}} at the ends (zero for rest to rest), and at each grid point a set of constraint rows

ℓ≤a u+b x+c≤h,\ell \le a\, u + b\, x + c \le h,

where u=s¨u = \ddot s is the path acceleration and x=s˙2x = \dot s^2. The admissible set Ωi\Omega_i is the polygon of pairs (u,x)(u, x) that meet every row at sis_i and have x≥0x \ge 0. Joint torque limits have this form: along the path the manipulator equation gives τ=Mqsu+(Mqss+C(q,qs)qs)x+g(q)\tau = M q_s u + (M q_{ss} + C(q, q_s) q_s) x + g(q), with qs=dq/dsq_s = dq/ds. A joint velocity limit is the row qs,j2x≤vj2q_{s,j}^2 x \le v_j^2, and a joint acceleration limit is ∣qs,ju+qss,jx∣≤aj|q_{s,j} u + q_{ss,j} x| \le a_j.

The control is constant on each interval, so xi+1=xi+2Δiuix_{i+1} = x_i + 2\Delta_i u_i, which is the exact relation d(s˙2)/ds=2s¨d(\dot s^2)/ds = 2\ddot s. Output: an admissible profile (ui,xi)(u_i, x_i) with (ui,xi)∈Ωi(u_i, x_i) \in \Omega_i and the given end speeds, with a traversal time T=∑i2Δi/(xi+xi+1)T = \sum_i 2\Delta_i / (\sqrt{x_i} + \sqrt{x_{i+1}}) that is as small as the method can make it, or "infeasible". Checking the limits only at the grid points is the collocation discretization of the paper; between grid points the limits hold only up to an error of O(Δ)O(\Delta).

The algorithm

  1. TOPP-RA(s_0..s_N, Ω_0..Ω_N, x_start, x_end)
  2. 1K_N ← [x_end, x_end]
  3. 2for i ← N-1 down to 0 do
  4. 3K_i ← { x : some u has (u, x) ∈ Ω_i and x + 2Δ_i u ∈ K_{i+1} } ▷ two LPs
  5. 4if K_i = ∅ then return INFEASIBLE
  6. 5if x_start ∉ K_0 then return INFEASIBLE
  7. 6x_0 ← x_start
  8. 7for i ← 0 to N-1 do
  9. 8u_i ← max { u : (u, x_i) ∈ Ω_i and x_i + 2Δ_i u ∈ K_{i+1} }
  10. 9x_{i+1} ← x_i + 2Δ_i u_i
  11. 10return (u, x)

KiK_i is the controllable set at sis_i: the squared speeds from which some admissible sequence of controls reaches xendx_{\text{end}} at sNs_N. Line L1 starts with the single end speed. Line L3 computes KiK_i from Ki+1K_{i+1}. The set of (u,x)(u, x) in Ωi\Omega_i that land in Ki+1K_{i+1} is a convex polygon, and KiK_i is its shadow on the xx axis, so KiK_i is an interval whose ends are the solutions of two linear programs in (u,x)(u, x): minimize xx and maximize xx. The code finds both ends at once by Fourier-Motzkin elimination of uu: every pair of a lower and an upper bound on uu gives one linear inequality in xx. Line L4 stops if a set is empty, line L5 if the start speed cannot be controlled to the end. The upper end of KiK_i is never above the maximum velocity curve, and it is lower wherever the robot must already brake for a later part of the path.

The forward pass, lines L6 to L9, is greedy. Line L8 picks the largest uu that is admissible at the current state and keeps the next state controllable. This is a linear program in one variable: an intersection of intervals of uu. Because xi∈Kix_i \in K_i, the set is never empty, so the forward pass cannot get stuck.

Example

One axis, trapezoid. The path q(s)=sq(s) = s with ∣q˙∣≤1|\dot q| \le 1 and ∣q¨∣≤2|\ddot q| \le 2 gives the rows ∣u∣≤2|u| \le 2 and x≤1x \le 1. On the grid si=i/4s_i = i/4, rest to rest:

ii sis_i KiK_i (backward) xix_i (forward) uiu_i
0 0 [0,1][0, 1] 0 2
1 0.25 [0,1][0, 1] 1 0
2 0.5 [0,1][0, 1] 1 0
3 0.75 [0,1][0, 1] 1 −2-2
4 1 [0,0][0, 0] 0

At i=3i = 3 the next set is {0}\{0\}, so line L3 needs x+0.5u=0x + 0.5u = 0 with ∣u∣≤2|u| \le 2, which allows x≤1x \le 1. Going forward, line L8 at i=0i = 0 takes u=2u = 2 and reaches the speed limit x=1x = 1; at i=1i = 1 and i=2i = 2 any u>0u > 0 would leave Ki+1K_{i+1}, so u=0u = 0; at i=3i = 3 the only choice is u=−2u = -2. The time is 0.5+0.25+0.25+0.5=1.50.5 + 0.25 + 0.25 + 0.5 = 1.5, which is exactly the minimum time of the trapezoidal velocity profile with D=1D = 1, V=1V = 1, A=2A = 2. Without the velocity limit the result is the triangle with T=2≈1.41421T = \sqrt 2 \approx 1.41421 on any even grid.

A 2R arm. The planar arm with unit links, unit point masses at the link ends and no gravity has M=[[3+2cos⁡q2,1+cos⁡q2],[1+cos⁡q2,1]]M = [[3 + 2\cos q_2, 1 + \cos q_2], [1 + \cos q_2, 1]]. It moves on 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. The times on uniform grids are:

NN 10 20 50 100 200 1000 2000
TT 1.47772 1.49564 1.50580 1.50846 1.50961 1.51046 1.51056

The time grows toward about 1.5106 because a coarse grid checks the limits at fewer points and is therefore optimistic. On the grid with N=200N = 200 the profile accelerates until s≈0.24s \approx 0.24, brakes to touch the maximum velocity curve at s=0.35s = 0.35 (where x=1.1556x = 1.1556, a corner of the curve), moves with a small acceleration until s≈0.73s \approx 0.73, and then brakes to rest. The largest violation of a torque limit at a grid point is about 4⋅10−154 \cdot 10^{-15}, and multiplying the profile by 1.01 breaks a limit.

Correctness

Theorem (Pham and Pham 2018, Theorem 1): the algorithm returns an admissible profile of the discretized problem if one exists, and "infeasible" otherwise. The proof shows by backward induction that KiK_i is exactly the set of speeds with an admissible future, and that line L3 computes it exactly because the shadow of a polygon is given by Fourier-Motzkin elimination. The forward pass keeps xi∈Kix_i \in K_i, so line L8 always has a choice, and the last state is xendx_{\text{end}}. See the proof.

Optimality is a separate result. Pham and Pham prove (Theorem 2) that if the path has no zero-inertia points, which are points where the coefficient aa of uu in a torque row is zero, then there is a step threshold below which the greedy profile is time-optimal for the discretized problem; with zero-inertia points the excess time is O(Δ)O(\Delta) (Theorem 3). The greedy pass is not optimal for every grid. On the 2R example with N=10N = 10, the convex formulation of the same discretized problem reaches T=1.46762T = 1.46762, which is 0.7% faster than the greedy 1.477721.47772; with N=50N = 50 the gap is 0.02%, and with N=200N = 200 it is about 10−510^{-5} (measurements). The tests compare it with a brute force over a lattice of states with a margin of a few percent and check exact values only on the single axis.

Proof: TOPP-RA returns an admissible parameterization of the discretized path if and only if one existsfull

We use the notation of the page. The grid is s0<s1<⋯<sNs_0 < s_1 < \dots < s_N with steps Δi=si+1−si>0\Delta_i = s_{i+1} - s_i > 0. At grid point ii the admissible set Ωi\Omega_i is the set of pairs (u,x)(u, x) with x≥0x \ge 0 and ℓ≤au+bx+c≤h\ell \le a u + b x + c \le h for every row (a,b,c,ℓ,h)(a, b, c, \ell, h) at sis_i. It is an intersection of finitely many closed half-planes, so it is a closed convex polygon (possibly unbounded or empty). The end states xstartx_{\text{start}} and xendx_{\text{end}} are given and are not negative.

Definition. An admissible parameterization is a sequence x0,…,xNx_0, \dots, x_N and u0,…,uN−1u_0, \dots, u_{N-1} with x0=xstartx_0 = x_{\text{start}}, xN=xendx_N = x_{\text{end}}, (ui,xi)∈Ωi(u_i, x_i) \in \Omega_i and xi+1=xi+2Δiuix_{i+1} = x_i + 2\Delta_i u_i for i<Ni < N.

The controllable sets are defined backward: KN={xend}K_N = \{x_{\text{end}}\}, and for i<Ni < N

Ki={x:there is u with (u,x)∈Ωi and x+2Δiu∈Ki+1}.K_i = \{x : \text{there is } u \text{ with } (u, x) \in \Omega_i \text{ and } x + 2\Delta_i u \in K_{i+1}\}.

Line L1 sets KNK_N, and line L3 computes KiK_i from Ki+1K_{i+1}.

The sets are intervals and line L3 computes them exactly

Lemma 1. Each KiK_i is empty or a closed interval [ℓi,hi][\ell_i, h_i] with 0≤ℓi0 \le \ell_i. If Ki+1K_{i+1} is a closed interval, one_step_set returns exactly KiK_i, or "empty" when KiK_i is empty.

Proof. By backward induction. KN=[xend,xend]K_N = [x_{\text{end}}, x_{\text{end}}]. Let Ki+1=[ℓ,h]K_{i+1} = [\ell, h]. The set

P=Ωi∩{(u,x):ℓ≤x+2Δiu≤h}P = \Omega_i \cap \{(u, x) : \ell \le x + 2\Delta_i u \le h\}

is an intersection of finitely many closed half-planes αu+βx≤γ\alpha u + \beta x \le \gamma, and KiK_i is its projection on the xx axis. For a fixed xx, the half-planes with α>0\alpha > 0 give upper bounds u≤(γ−βx)/αu \le (\gamma - \beta x)/\alpha, those with α<0\alpha < 0 give lower bounds u≥(γ−βx)/αu \ge (\gamma - \beta x)/\alpha, and those with α=0\alpha = 0 do not involve uu and say βx≤γ\beta x \le \gamma. A uu exists if and only if every row with α=0\alpha = 0 holds and every lower bound is at most every upper bound. For a pair with αi>0>αj\alpha_i > 0 > \alpha_j, multiply the first inequality by −αj>0-\alpha_j > 0 and the second by αi>0\alpha_i > 0; the condition "lower bound ≤\le upper bound" becomes

(αiβj−αjβi) x≤αiγj−αjγi,(\alpha_i \beta_j - \alpha_j \beta_i)\, x \le \alpha_i \gamma_j - \alpha_j \gamma_i,

which is the row that _x_interval forms (Fourier-Motzkin elimination of uu). The two rows from Ki+1K_{i+1} have α=2Δi>0\alpha = 2\Delta_i > 0 and α=−2Δi<0\alpha = -2\Delta_i < 0, so both kinds of bound are always present. So x∈Kix \in K_i if and only if xx meets finitely many rows of the form cx≤dc x \le d. Their solution set is a closed interval or empty, and _x_interval intersects them: a row with c>0c > 0 lowers the upper end, a row with c<0c < 0 raises the lower end, and a row with c=0c = 0 and d<0d < 0 makes the set empty. The row x≥0x \ge 0 is always present, so ℓi≥0\ell_i \ge 0. □\square

Lemma 2. x∈Kix \in K_i if and only if there are ui,…,uN−1u_i, \dots, u_{N-1} such that the states xi=xx_i = x, xj+1=xj+2Δjujx_{j+1} = x_j + 2\Delta_j u_j satisfy (uj,xj)∈Ωj(u_j, x_j) \in \Omega_j for i≤j<Ni \le j < N and xN=xendx_N = x_{\text{end}}.

Proof. By backward induction on ii. For i=Ni = N both sides say x=xendx = x_{\text{end}}. For i<Ni < N: if x∈Kix \in K_i, take uiu_i from the definition; then xi+1∈Ki+1x_{i+1} \in K_{i+1} and the induction hypothesis gives the rest of the controls. Conversely, if such controls exist, then (ui,x)∈Ωi(u_i, x) \in \Omega_i and xi+1x_{i+1} has a valid tail, so xi+1∈Ki+1x_{i+1} \in K_{i+1} by the induction hypothesis and x∈Kix \in K_i by the definition. □\square

The algorithm reports infeasible only when nothing is admissible

Lemma 3. If the algorithm returns at line L4 or line L5, no admissible parameterization exists.

Proof. An admissible parameterization gives, by Lemma 2 with i=0i = 0, that xstart∈K0x_{\text{start}} \in K_0. If some KiK_i is empty, then Ki−1,…,K0K_{i-1}, \dots, K_0 are all empty by the definition, so K0K_0 is empty and the return at line L4 is correct. If xstart∉K0x_{\text{start}} \notin K_0, the return at line L5 is correct. (The check of xendx_{\text{end}} against the rows at sNs_N before line L1 is the same argument for the last point.) □\square

The forward pass stays in the controllable sets

Lemma 4. If the algorithm passes line L5, then for every ii the control uiu_i of line L8 exists, (ui,xi)∈Ωi(u_i, x_i) \in \Omega_i, and xi+1∈Ki+1x_{i+1} \in K_{i+1}.

Proof. We show xi∈Kix_i \in K_i for all ii by induction. x0=xstart∈K0x_0 = x_{\text{start}} \in K_0 by line L5. If xi∈Kix_i \in K_i, the set

Ui={u:(u,xi)∈Ωi, xi+2Δiu∈Ki+1}U_i = \{u : (u, x_i) \in \Omega_i,\ x_i + 2\Delta_i u \in K_{i+1}\}

is not empty by the definition of KiK_i. It is an intersection of closed intervals of uu (each row with a≠0a \ne 0 gives one, rows with a=0a = 0 hold because xix_i is the xx of a point of Ωi\Omega_i), and it is bounded above by (hi+1−xi)/(2Δi)(h_{i+1} - x_i)/(2\Delta_i). So it has a largest element, which greedy_control returns: it intersects the same intervals and returns the upper end. Then (ui,xi)∈Ωi(u_i, x_i) \in \Omega_i and xi+1=xi+2Δiui∈Ki+1x_{i+1} = x_i + 2\Delta_i u_i \in K_{i+1}. The clamp at 00 in line L9 does nothing, because Ki+1⊆[0,∞)K_{i+1} \subseteq [0, \infty) by Lemma 1. □\square

Theorem

Theorem. The algorithm returns an admissible parameterization of the discretized problem if one exists, and returns "infeasible" otherwise.

Proof. If no admissible parameterization exists, the algorithm cannot return a profile: by Lemma 4 any profile it returns is admissible, since xN∈KN={xend}x_N \in K_N = \{x_{\text{end}}\}. So it returns at line L4 or line L5. If an admissible parameterization exists, Lemma 3 shows that the algorithm does not return at lines L4 or L5, and Lemma 4 shows that the forward pass builds a profile with (ui,xi)∈Ωi(u_i, x_i) \in \Omega_i for all i<Ni < N and xN=xendx_N = x_{\text{end}}, which is admissible. ■\blacksquare

What this proof does not show

The theorem is about feasibility and admissibility. It does not say that the greedy forward pass gives the least traversal time of the discretized problem. Pham and Pham (2018) prove optimality separately (their Theorem 2), when the path has no zero-inertia points and the step is below a threshold, and they bound the excess time by O(Δ)O(\Delta) when zero-inertia points are present (their Theorem 3). The tests compare the result with a brute force over a lattice of states with a tolerance, not with equality, for this reason.

In floating point, the bounds of the sets have rounding errors. The code accepts a state that lies outside a set by at most a relative tolerance of 10−1210^{-12}, and the constraint violation of the returned profile is of the same order.

Complexity

The backward pass solves NN problems of the form "shadow of a polygon with m+3m + 3 edges". Fourier-Motzkin elimination of one variable forms O(m2)O(m^2) rows, so the code takes O(m2)O(m^2) per grid point. A two-variable linear program can be solved in O(m)O(m) time (Seidel's algorithm in expected time, or Megiddo's deterministic algorithm), which gives O(mN)O(mN) in total; Pham and Pham state O(mN)O(mN) for this reason and use a simplex solver in practice. The forward pass is O(m)O(m) per point. Memory is Θ(N)\Theta(N) for the sets and the profile, plus the rows. For comparison, the paper gives O(m2N)O(m^2 N) for the integration method and a higher cost for the convex formulation solved as one large program.

Properties

  • Complete for the discretized problem. A theorem: it finds an admissible profile if one exists.
  • Optimal under conditions. A theorem with hypotheses: for a fine enough grid and no zero-inertia points; otherwise within O(Δ)O(\Delta).
  • No switch points. The method never searches for switch points or tangent points, and it treats velocity limits, singular arcs and zero-inertia points in the same way as any other constraint.
  • Controllable sets come for free. The sets KiK_i tell, for any state on the path, whether the robot can still stop in time. This is useful for replanning and for feedback.
  • Discretization error. Limits hold at the grid points only. A finer grid or the first-order interpolation scheme of the paper (Appendix D, error O(Δ2)O(\Delta^2)) reduces the error.
  • Measured performance. The paper reports a 100% success rate on its test paths. This is a measurement on their benchmarks, not a bound.

Variants and improvements

  • Interpolation discretization. Requiring the constraints also at the next grid point with the same control tightens each step and reduces the error from O(Δ)O(\Delta) to O(Δ2)O(\Delta^2) (Pham and Pham, Appendix D).
  • Admissible velocity propagation. The same sets, propagated forward instead of backward, give the range of final speeds that a path can reach. Planners that build paths piece by piece use this to prune, as in kinodynamic planning.
  • Second-order cone constraints. Limits on the norm of a vector of torques or forces, such as friction cones, make Ωi\Omega_i convex but not polygonal; each step is then a small second-order cone program.
  • Other methods for the same problem. The Bobrow integration method integrates the phase plane; the convex formulation of Verscheure et al. solves one large convex program for the whole grid.

When to use it

Use TOPP-RA when you need a reliable time-optimal parameterization of a given path in a robot controller or a planner: industrial arms with torque and velocity limits, paths with friction or contact constraints, and real-time retiming in the loop. Use the integration method when you want the switch points explicitly and the path has no singular arcs. Use the convex formulation when you want a different objective, such as time plus a penalty on torque, which TOPP-RA cannot handle because the greedy pass only maximizes speed.

Pitfalls

  • A coarse grid is optimistic. Line L3 checks the limits only at the grid points, so the true limits are broken between them. In the 2R example the time on 10 intervals is about 2% too small. Use a fine grid or the interpolation scheme, and check the final profile on a finer grid.
  • Rounding at the set bounds. In floating point, line L9 can land slightly above the upper end of Ki+1K_{i+1} or slightly below zero. Then line L8 at the next point finds an empty set. The code accepts a small relative tolerance and clamps xx at zero.
  • End speeds that are not admissible. xendx_{\text{end}} must satisfy the rows at sNs_N, and a nonzero xstartx_{\text{start}} must be in K0K_0. Line L5 returns "infeasible" for a start that is too fast to stop, which is the correct answer but can surprise a caller that expects a slower profile.
  • Taking any admissible uu in line L8. Every uu in the set keeps the profile admissible, but only the largest makes it fast. Picking the middle of the interval, for robustness, gives a valid but slow profile.
  • Expecting exact optimality. The greedy profile is optimal only under the conditions of Theorem 2. Near zero-inertia points it can be slower by O(Δ)O(\Delta).

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.

topp_reachability_analysis.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/topp-reachability-analysis/. The authors are listed in prov/HBHW2D.jsonl.
"""Time-optimal path parameterization by reachability analysis (TOPP-RA).

The path parameter s runs over the grid s_0 < s_1 < ... < s_N. At the grid
point s_i the state is x_i = s'^2 and the control is u_i = s'', held
constant on [s_i, s_(i+1)], so that x_(i+1) = x_i + 2 Delta_i u_i. The
constraints at s_i are rows (a, b, c, lo, hi) that mean

    lo <= a u + b x + c <= hi,

with lo = -inf or hi = +inf allowed. Joint velocity, joint acceleration and
joint torque limits along a path all have this form.

toppra(grid, rows, x_start, x_end) runs the backward pass (controllable
sets K_i, two small LPs per grid point) and the greedy forward pass. Each
LP has two variables (u, x); it is solved exactly by eliminating u
(Fourier-Motzkin), which costs O(m^2) for m rows. The whole algorithm costs
O(N m^2) arithmetic operations and O(N) memory for the sets and the
profile.

Helpers build the rows for one axis with velocity and acceleration limits
and for a planar 2R arm with torque limits along a straight joint path.
"""

import math

INF = math.inf
TOL = 1e-12


def _halfplanes(rows, x_lo=None):
    """Turn rows (a, b, c, lo, hi) into half-planes alpha u + beta x <= gamma."""
    out = []
    for a, b, c, lo, hi in rows:
        if hi < INF:
            out.append((a, b, hi - c))
        if lo > -INF:
            out.append((-a, -b, c - lo))
    out.append((0.0, -1.0, 0.0))  # x >= 0
    return out


def _x_interval(planes):
    """Return the projection [xmin, xmax] of a polygon in (u, x) on the x axis.

    The polygon is the set of alpha u + beta x <= gamma. Eliminating u
    (Fourier-Motzkin) leaves rows c x <= d. Return None if it is empty.
    """
    ups = [p for p in planes if p[0] > 0.0]
    downs = [p for p in planes if p[0] < 0.0]
    rows = [(p[1], p[2]) for p in planes if p[0] == 0.0]
    for ai, bi, gi in ups:
        for aj, bj, gj in downs:
            rows.append((-aj * bi + ai * bj, -aj * gi + ai * gj))
    lo, hi = -INF, INF
    for c, d in rows:
        scale = max(abs(c), abs(d), 1.0)
        if abs(c) <= TOL * scale:
            if d < -TOL * scale:
                return None
        elif c > 0.0:
            hi = min(hi, d / c)
        else:
            lo = max(lo, d / c)
    if lo > hi + TOL * max(1.0, abs(hi)):
        return None
    return (lo + 0.0, max(lo, hi) + 0.0)  # + 0.0 turns -0.0 into 0.0


def one_step_set(rows, delta, k_next):
    """Controllable set K_i: the x with some admissible u that lands in k_next."""
    planes = _halfplanes(rows)
    lo_next, hi_next = k_next
    planes.append((2.0 * delta, 1.0, hi_next))  # x + 2 delta u <= hi_next
    planes.append((-2.0 * delta, -1.0, -lo_next))  # x + 2 delta u >= lo_next
    return _x_interval(planes)


def greedy_control(rows, delta, x, k_next):
    """Largest u with (u, x) admissible and x + 2 delta u in k_next, or None."""
    u_lo = (k_next[0] - x) / (2.0 * delta)
    u_hi = (k_next[1] - x) / (2.0 * delta)
    for a, b, c, lo, hi in rows:
        r = b * x + c
        if a == 0.0:
            if r > hi + TOL * max(1.0, abs(hi)) or r < lo - TOL * max(1.0, abs(lo)):
                return None
            continue
        b1, b2 = (lo - r) / a, (hi - r) / a
        if a < 0.0:
            b1, b2 = b2, b1
        u_lo, u_hi = max(u_lo, b1), min(u_hi, b2)
    if u_lo > u_hi + TOL * max(1.0, abs(u_hi)):
        return None
    return u_hi


def toppra(grid, rows, x_start=0.0, x_end=0.0):
    """Return (u, x, K) or None if the path cannot be parameterized.

    grid: s_0 < ... < s_N. rows[i]: the constraint rows at s_i (the rows at
    s_N only restrict x_N). u has N entries and x has N + 1 entries. K is
    the list of controllable sets. Cost O(N m^2); memory O(N).
    """
    n = len(grid) - 1
    k = [None] * (n + 1)
    xs_end = _x_interval(_halfplanes(rows[n]))
    if xs_end is None or not (xs_end[0] - TOL <= x_end <= xs_end[1] + TOL):
        return None
    k[n] = (x_end, x_end)  # @line L1
    for i in range(n - 1, -1, -1):  # @line L2
        k[i] = one_step_set(rows[i], grid[i + 1] - grid[i], k[i + 1])  # @line L3
        if k[i] is None:  # @line L4
            return None
    if not (k[0][0] - TOL <= x_start <= k[0][1] + TOL):  # @line L5
        return None
    x = [0.0] * (n + 1)
    u = [0.0] * n
    x[0] = x_start  # @line L6
    for i in range(n):  # @line L7
        delta = grid[i + 1] - grid[i]
        ui = greedy_control(rows[i], delta, x[i], k[i + 1])  # @line L8
        if ui is None:
            return None  # cannot happen in exact arithmetic (Theorem 1)
        u[i] = ui
        x[i + 1] = max(0.0, x[i] + 2.0 * delta * ui)  # @line L9
    x[n] = x_end
    return u, x, k  # @line L10


def traversal_time(grid, x):
    """Time to run the profile when u is constant on each interval.

    On [s_i, s_(i+1)] the speed is sqrt of a linear x, so the time is
    exactly 2 Delta / (sqrt(x_i) + sqrt(x_(i+1))). Infinite if both are 0.
    """
    t = 0.0
    for i in range(len(grid) - 1):
        den = math.sqrt(max(x[i], 0.0)) + math.sqrt(max(x[i + 1], 0.0))
        if den == 0.0:
            return INF
        t += 2.0 * (grid[i + 1] - grid[i]) / den
    return t


def max_violation(rows, u, x):
    """Largest amount by which (u_i, x_i) breaks a row, over all i < N."""
    worst = 0.0
    for i in range(len(u)):
        for a, b, c, lo, hi in rows[i]:
            v = a * u[i] + b * x[i] + c
            worst = max(worst, v - hi, lo - v)
    return worst


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


def uniform_grid(n):
    """n + 1 equally spaced points on [0, 1]."""
    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_terms(q, dq):
    """Mass matrix rows times dq and the quadratic velocity term of the 2R arm.

    Links of length 1 with a point mass 1 at each link end, in a horizontal
    plane (no gravity). M = [[3 + 2 c2, 1 + c2], [1 + c2, 1]].
    Return (M dq, C(q, dq) dq).
    """
    c2, s2 = math.cos(q[1]), math.sin(q[1])
    m11, m12, m22 = 3.0 + 2.0 * c2, 1.0 + c2, 1.0
    mdq = [m11 * dq[0] + m12 * dq[1], m12 * dq[0] + m22 * dq[1]]
    cdq = [-s2 * (2.0 * dq[0] * dq[1] + dq[1] * dq[1]), s2 * dq[0] * dq[0]]
    return mdq, cdq


def arm2r_rows(grid, q0, q1, tau_max):
    """Torque rows of the 2R arm along q(s) = q0 + s (q1 - q0).

    tau = M q_s u + (M q_ss + C(q, q_s) q_s) x with q_ss = 0 here.
    """
    dq = [q1[0] - q0[0], q1[1] - q0[1]]
    rows = []
    for s in grid:
        q = [q0[0] + s * dq[0], q0[1] + s * dq[1]]
        a, b = arm2r_terms(q, dq)
        rows.append([(a[j], b[j], 0.0, -tau_max[j], tau_max[j]) for j in range(2)])
    return rows
test_topp_reachability_analysis.py 150 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/topp-reachability-analysis/. The authors are listed in prov/HBHW2D.jsonl.
import math
import random
import unittest

from topp_reachability_analysis import (
    INF,
    arm2r_rows,
    max_violation,
    one_step_set,
    single_axis_rows,
    toppra,
    traversal_time,
    uniform_grid,
)


def dp_oracle(grid, rows, levels, x_top):
    """Shortest traversal time over profiles with x_i on the lattice j * x_top / levels.

    A transition x_i -> x_(i+1) is allowed when u = (x_(i+1) - x_i) / (2 delta)
    meets every row at (u, x_i). This does not use the controllable sets.
    """
    n = len(grid) - 1
    xs = [j * x_top / levels for j in range(levels + 1)]
    best = [INF] * (levels + 1)
    best[0] = 0.0
    for i in range(n):
        delta = grid[i + 1] - grid[i]
        new = [INF] * (levels + 1)
        for j, xi in enumerate(xs):
            if best[j] == INF:
                continue
            ok_x = all(
                not (a == 0.0 and not (lo - 1e-12 <= b * xi + c <= hi + 1e-12))
                for a, b, c, lo, hi in rows[i]
            )
            if not ok_x:
                continue
            for k, xk in enumerate(xs):
                u = (xk - xi) / (2.0 * delta)
                if all(lo - 1e-12 <= a * u + b * xi + c <= hi + 1e-12 for a, b, c, lo, hi in rows[i]):
                    den = math.sqrt(xi) + math.sqrt(xk)
                    if den > 0.0:
                        t = best[j] + 2.0 * delta / den
                        if t < new[k]:
                            new[k] = t
        best = new
    return best[0]


class TestWorkedExample(unittest.TestCase):
    def test_single_axis_trapezoid(self):
        # D = 1, V = 1, A = 2: the trapezoid with Ta = 0.5 and T = 1.5.
        g = uniform_grid(4)
        u, x, k = toppra(g, single_axis_rows(g, 1.0, 1.0, 2.0))
        self.assertEqual(x, [0.0, 1.0, 1.0, 1.0, 0.0])
        self.assertEqual(u, [2.0, 0.0, 0.0, -2.0])
        self.assertEqual(k[:4], [(0.0, 1.0)] * 4)
        self.assertEqual(k[4], (0.0, 0.0))
        self.assertAlmostEqual(traversal_time(g, x), 1.5, places=12)

    def test_single_axis_triangle(self):
        # No velocity limit: bang-bang with the switch at s = 1/2, T = sqrt(2).
        for n in (2, 8, 16):
            g = uniform_grid(n)
            u, x, _ = toppra(g, single_axis_rows(g, 1.0, INF, 2.0))
            self.assertAlmostEqual(traversal_time(g, x), math.sqrt(2.0), places=12)
            self.assertAlmostEqual(max(x), 2.0, places=12)

    def test_arm_example(self):
        g = uniform_grid(200)
        rows = arm2r_rows(g, [0.0, 0.0], [2.0, -3.0], [10.0, 4.0])
        u, x, _ = toppra(g, rows)
        self.assertLess(max_violation(rows, u, x), 1e-9)
        self.assertAlmostEqual(traversal_time(g, x), 1.5096, places=3)
        # The profile touches the maximum velocity curve near s = 0.35.
        self.assertAlmostEqual(x[70], 1.1556, places=3)


class TestEdgeCases(unittest.TestCase):
    def test_infeasible_start(self):
        g = uniform_grid(4)
        # Braking from x = 10 at A = 2 needs a distance of 2.5 > 1.
        self.assertIsNone(toppra(g, single_axis_rows(g, 1.0, INF, 2.0), x_start=10.0))
        # Start above the velocity limit.
        self.assertIsNone(toppra(g, single_axis_rows(g, 1.0, 1.0, 2.0), x_start=4.0))

    def test_infeasible_path(self):
        # A row that needs a positive x at s_2 cannot be met.
        g = uniform_grid(4)
        rows = single_axis_rows(g, 1.0, 1.0, 2.0)
        rows[2] = rows[2] + [(0.0, 1.0, 0.0, 5.0, INF)]
        self.assertIsNone(toppra(g, rows))

    def test_nonzero_end_speed(self):
        g = uniform_grid(4)
        u, x, _ = toppra(g, single_axis_rows(g, 1.0, 1.0, 2.0), x_end=1.0)
        self.assertEqual(x, [0.0, 1.0, 1.0, 1.0, 1.0])

    def test_one_step_set_empty(self):
        # x + 2 delta u must reach [10, 10] but u <= 1 and x <= 1.
        rows = [(1.0, 0.0, 0.0, -1.0, 1.0), (0.0, 1.0, 0.0, -INF, 1.0)]
        self.assertIsNone(one_step_set(rows, 0.25, (10.0, 10.0)))
        self.assertEqual(one_step_set(rows, 0.25, (0.0, 1.0)), (0.0, 1.0))

    def test_scaled_profile_breaks_a_limit(self):
        g = uniform_grid(50)
        rows = arm2r_rows(g, [0.0, 0.0], [2.0, -3.0], [10.0, 4.0])
        u, x, _ = toppra(g, rows)
        self.assertGreater(max_violation(rows, [1.01 * v for v in u], [1.01 * v for v in x]), 1e-3)


class TestRandomized(unittest.TestCase):
    def test_against_lattice_dp(self):
        rng = random.Random(20260517)
        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)]
            g = uniform_grid(6)
            rows = arm2r_rows(g, [0.0, 0.0], q1, tau)
            res = toppra(g, rows)
            self.assertIsNotNone(res)
            u, x, k = res
            self.assertLess(max_violation(rows, u, x), 1e-9)
            t_ra = traversal_time(g, x)
            x_top = max(hi for _, hi in k) * 1.0001
            t_dp = dp_oracle(g, rows, 120, x_top)
            # The lattice only holds some profiles, so the DP time is an upper
            # bound on the best discrete time; TOPP-RA must not be worse by more
            # than a small margin and the lattice must not beat it.
            self.assertLessEqual(t_ra, t_dp * 1.02)
            self.assertLessEqual(t_dp, t_ra * 1.05)

    def test_dominates_random_admissible_profiles(self):
        # Any admissible profile with the same end points is no faster.
        rng = random.Random(7)
        g = uniform_grid(4)
        rows = single_axis_rows(g, 1.0, 1.0, 2.0)
        t_ra = traversal_time(g, toppra(g, rows)[1])
        for _ in range(300):
            x = [0.0] + [rng.uniform(0.0, 1.0) for _ in range(3)] + [0.0]
            u = [(x[i + 1] - x[i]) * 2.0 for i in range(4)]
            if max_violation(rows, u, x) <= 1e-12:
                self.assertGreaterEqual(traversal_time(g, x), t_ra - 1e-12)


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

History

The phase-plane method of Bobrow, Dubowsky and Gibson and of Shin and McKay (1985) solved the problem by integrating curves and finding switch points. Pfeiffer and Johanni (1987) and later Pham (2014) showed that the integration method needs special care at singular and zero-inertia points, where implementations often failed. Earlier, the convex formulation of Verscheure et al. (2009) removed the switch points at the cost of one large optimization. Hung Pham and Quang-Cuong Pham (2018) borrowed the idea of reachable and controllable sets from control theory and turned the problem into a sequence of tiny linear programs, which made it both robust and fast. Their open-source library is widely used to retime robot paths.

References

  1. 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 (arXiv 1707.07239), Algorithm 1 (TOPP-RA); Section IV-B, Theorem 1 (correctness); Section IV-C, Theorems 2 and 3 (optimality); Section IV-D (complexity); Section V (experiments)
  2. Quang-Cuong Pham, A general, fast, and robust implementation of the time-optimal path parameterization algorithm, IEEE Transactions on Robotics 30(6), 2014, 1533-1540, the whole paper (the integration method, its failure modes at singular points, and the velocity limits)
  3. Kevin M. Lynch and Frank C. Park, Modern Robotics, Mechanics, Planning, and Control, Cambridge University Press, 2017, Section 9.4 (time-optimal time scaling, the phase plane and the limits on s'')

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