Algorithm Search⌘K

Algorithmadvanced

Bobrow-Dubowsky-Gibson algorithm

Also called Shin-McKay algorithm, numerical integration method for TOPP.

Finds the fastest timing along a fixed robot path by integrating maximum acceleration and deceleration curves in the phase plane and joining them at switch points.

Time
O(k b m^2 / h) worst
Space
O(k / h) extra
Where
b = the number of bisection steps per switch; h = the integration step in s; k = the number of switch points; m = the number of constraint rows
Properties
deterministicnot exactofflinenot randomized

The Bobrow-Dubowsky-Gibson algorithm finds the fastest way to move along a fixed path when the forces that drive the motion are limited. A robot arm that must follow a given curve, a machine tool that must cut a given contour, or a vehicle that must stay on a given road all have this problem: the shape of the motion is decided, and only the timing is free. The algorithm describes the timing by one number at each point of the path, the speed along the path, and draws it as a curve in the "phase plane" of position against speed. The limits on the forces give, at each point and speed, a largest and a smallest allowed acceleration, and above a certain speed, the maximum velocity curve, no acceleration is allowed at all. The fastest timing always uses the largest or the smallest acceleration, and it changes from one to the other only at a few switch points. The algorithm integrates these extreme curves numerically and searches for the switch points where a braking curve just touches the maximum velocity curve. It was published in 1985 by Bobrow, Dubowsky and Gibson and, independently, by Shin and McKay. It is the classical solution of time-optimal path parameterization, and it is fast, but finding switch points numerically is fragile.

In plain words

A driver must follow a winding mountain road as fast as possible. On each part of the road the car can speed up only so hard and brake only so hard, and in tight bends there is a top speed above which the car slides off. The fastest drive never cruises gently: at every moment the driver either floors it or brakes as hard as possible. The only question is where to switch. Start at the finish line and work out the last hard braking run that ends at a stop. Then start at the beginning and floor it. If you hit a bend's top speed first, find the braking run that just touches that top speed without going over, use it to slow down in time, and floor it again after the bend. Repeat until the speeding-up curve meets the last braking run.

The problem

Input: a path q(s)q(s) in joint space, s∈[0,1]s \in [0, 1], and limits that are linear in s¨\ddot s and s˙2\dot s^2 at each ss. For an arm with torque limits τmin⁡≤τ≤τmax⁡\tau_{\min} \le \tau \le \tau_{\max} the manipulator equation gives along the path

τ=M(q)qs s¨+(M(q)qss+C(q,qs)qs)s˙2+g(q),\tau = M(q) q_s\, \ddot s + \left(M(q) q_{ss} + C(q, q_s) q_s\right) \dot s^2 + g(q),

with qs=dq/dsq_s = dq/ds. This page writes x=s˙2x = \dot s^2 and u=s¨u = \ddot s, so that each limit is a row ℓ≤au+bx+c≤h\ell \le a u + b x + c \le h, and dx/ds=2udx/ds = 2u. At each (s,x)(s, x) the rows give an interval [L(s,x),U(s,x)][L(s, x), U(s, x)] of admissible uu. The maximum velocity curve MVC(s)\mathrm{MVC}(s) is the largest xx where L≤UL \le U. Output: a profile x(s)x(s) from (0,0)(0, 0) to (1,0)(1, 0) that stays at or below the MVC, has 2L≤dx/ds≤2U2L \le dx/ds \le 2U, and has the least traversal time T=∫01ds/xT = \int_0^1 ds/\sqrt{x}. Lynch and Park draw the same plane with the speed s˙\dot s on the vertical axis; using xx makes the curves easier to integrate, because dx/dsdx/ds does not blow up at s˙=0\dot s = 0.

The algorithm

  1. TOPP-INTEGRATE(path, limits)
  2. 1F ← integrate dx/ds = 2L backward from (1, 0) until it leaves the region below the MVC
  3. 2(s_i, x_i) ← (0, 0); switches ← empty list
  4. 3repeat
  5. 4A ← integrate dx/ds = 2U forward from (s_i, x_i) until it crosses F or the MVC
  6. 5if A crosses F then add the crossing (U to L) to switches; return A then F, and switches
  7. 6(s_lim, x_lim) ← the point where A crosses the MVC
  8. 7binary search x in [0, x_lim] for the largest x whose forward L curve from (s_lim, x) stays below the MVC
  9. 8(s_tan, x_tan) ← the point where that L curve touches the MVC
  10. 9D ← integrate dx/ds = 2L backward from (s_tan, x_tan) until it crosses A
  11. 10add the crossing of D and A (U to L) and (s_tan, x_tan) (L to U) to switches
  12. 11(s_i, x_i) ← (s_tan, x_tan)

Line L1 builds the final braking curve: any admissible profile must be on or below it, because from a point above it even the hardest braking overshoots the end. Line L4 accelerates as hard as possible. If the acceleration curve meets the braking curve FF, the switch from UU to LL at their crossing finishes the profile (line L5). Otherwise the curve hits the MVC at slims_{\text{lim}} (line L6), and somewhere past slims_{\text{lim}} the profile must have braked. Lines L7 and L8 find where: a braking curve that starts high at slims_{\text{lim}} crosses the MVC, one that starts at zero falls to zero, and the boundary between the two touches the MVC at a tangent point. Line L9 integrates the braking curve backward from the tangent point until it meets the acceleration curve, which gives a switch from UU to LL. At the tangent point the profile switches back to UU, and the loop repeats from there (line L11). The code uses RK4 with a fixed step hh in ss, so each curve costs O(1/h)O(1/h) evaluations of the limits.

Example

One axis. For q(s)=sq(s) = s with ∣q¨∣≤2|\ddot q| \le 2, the limits are −2≤u≤2-2 \le u \le 2 and the MVC is infinite. Line L1 gives FF: x=4(1−s)x = 4(1 - s). Line L4 gives AA: x=4sx = 4s. They cross at s=1/2s = 1/2, x=2x = 2, which is the triangle profile with T=2≈1.41421T = \sqrt 2 \approx 1.41421, the minimum time of the trapezoidal velocity profile without a velocity limit. With different limits, −3≤u≤1-3 \le u \le 1, the curves cross at s=3/4s = 3/4, where the time to accelerate over 3/43/4 at rate 1 and to brake over 1/41/4 at rate 3 balance.

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 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. The MVC is infinite at s=0s = 0, where sin⁡q2=0\sin q_2 = 0, and has a sharp minimum of 1.15561.1556 at s=0.35s = 0.35, where the active torque limit changes. With h=0.001h = 0.001:

piece ss range control xx at the end
accelerate 0 to 0.2386 UU 1.325
brake 0.2386 to 0.349 LL 1.151 (tangent point, near the MVC minimum)
accelerate 0.349 to 0.7311 UU (negative up to s≈0.6s \approx 0.6) 1.059
brake 0.7311 to 1 LL (FF) 0

The traversal time is 1.510651.51065 (1.510441.51044 with h=0.01h = 0.01 and 1.510741.51074 with h=0.004h = 0.004). The reachability method on a grid of 2000 intervals gives 1.510561.51056 for the same problem.

Correctness

Theorem (Bobrow, Dubowsky and Gibson 1985; Shin and McKay 1985; Lynch and Park, Section 9.4): if the limits are continuous along the path and Lipschitz in the speed, and the algorithm finds each tangent point exactly, the profile is admissible and is at least as high as every admissible profile at every ss, so it is time-optimal. The proof uses a comparison lemma for differential inequalities. Any admissible profile that starts at or below an acceleration curve stays below it going forward, and one that ends at or below a braking curve stays below it going backward. Every acceleration piece of the result starts at (0,0)(0, 0) or on the MVC, and every braking piece ends at (1,0)(1, 0) or on the MVC, where no admissible profile can be higher. See the proof.

The conditions matter. The theorem is about the exact curves; the computed curves carry the error of the integrator, and the tangent point is found only to within one step hh (this is visible in the table, where the tangent point is at 0.349 or 0.348 rather than 0.35 for some hh).

Proof: The profile of the integration method lies above every admissible profile, so it is time-optimalfull

We use the notation of the page. The path parameter is s∈[0,1]s \in [0, 1], the state is x=s˙2≥0x = \dot s^2 \ge 0, and the control is u=s¨u = \ddot s, so that dx/ds=2udx/ds = 2u wherever x>0x > 0. At each (s,x)(s, x) the admissible controls form the interval [L(s,x),U(s,x)][L(s, x), U(s, x)], and the maximum velocity curve MVC(s)\mathrm{MVC}(s) is the largest xx with L(s,x)≤U(s,x)L(s, x) \le U(s, x).

Definition. An admissible profile is an absolutely continuous function x:[0,1]→[0,∞)x : [0, 1] \to [0, \infty) with x(0)=x(1)=0x(0) = x(1) = 0, x(s)≤MVC(s)x(s) \le \mathrm{MVC}(s) for all ss, and 2L(s,x(s))≤x′(s)≤2U(s,x(s))2L(s, x(s)) \le x'(s) \le 2U(s, x(s)) for almost every ss. Its traversal time is T(x)=∫01ds/x(s)T(x) = \int_0^1 ds / \sqrt{x(s)}.

Hypotheses. (H1) The constraint rows depend continuously on ss, so LL and UU are continuous on the region below the MVC. (H2) LL and UU are Lipschitz in xx there. Both hold for torque limits: for fixed ss, LL and UU are the largest and the smallest of finitely many affine functions of xx. (H3) The algorithm is run with exact integration and an exact binary search, and it returns a profile. That is, every curve it integrates exists on the interval it needs, each binary search ends at an LL curve that touches the MVC at a point (sk,MVC(sk))(s_k, \mathrm{MVC}(s_k)), and there are finitely many switches.

The proof does not use the RK4 step or the stopping tolerance of the code; their errors are discussed on the page.

Comparison of curves

Lemma 1 (forward comparison). Let AA solve A′=2U(s,A)A' = 2U(s, A) on [a,b][a, b] and let xx be admissible. If x(a)≤A(a)x(a) \le A(a), then x(s)≤A(s)x(s) \le A(s) for s∈[a,b]s \in [a, b].

Proof. Let w=x−Aw = x - A. Where w>0w > 0, we have w′≤2U(s,x)−2U(s,A)≤2λww' \le 2U(s, x) - 2U(s, A) \le 2\lambda w, with λ\lambda the Lipschitz constant of (H2). Suppose w(s1)>0w(s_1) > 0 for some s1s_1, and let s0=sup⁡{s≤s1:w(s)≤0}s_0 = \sup\{s \le s_1 : w(s) \le 0\}, so w(s0)=0w(s_0) = 0 and w>0w > 0 on (s0,s1](s_0, s_1]. Gronwall's inequality on (s0,s1](s_0, s_1] gives w(s1)≤w(s0)e2λ(s1−s0)=0w(s_1) \le w(s_0) e^{2\lambda(s_1 - s_0)} = 0, a contradiction. □\square

Lemma 2 (backward comparison). Let DD solve D′=2L(s,D)D' = 2L(s, D) on [a,b][a, b] and let xx be admissible. If x(b)≤D(b)x(b) \le D(b), then x(s)≤D(s)x(s) \le D(s) for s∈[a,b]s \in [a, b].

Proof. Put r=−sr = -s. Then dx/dr=−x′(s)≤−2L(s,x)dx/dr = -x'(s) \le -2L(s, x) and dD/dr=−2L(s,D)dD/dr = -2L(s, D), and −L-L is Lipschitz in xx. Lemma 1 applied in the variable rr from r=−br = -b gives the claim. □\square

The structure of the result

Under (H3) the returned profile x∗x^* is made of pieces of two kinds. The switch points of type "L to U" are 0=t0<t1<⋯<tk0 = t_0 < t_1 < \dots < t_k, where t0t_0 is the start and t1,…,tkt_1, \dots, t_k are the tangent points of line L8. The switch points of type "U to L" are σ1<⋯<σk+1\sigma_1 < \dots < \sigma_{k+1} with tj−1<σj≤tjt_{j-1} < \sigma_j \le t_j for j≤kj \le k and tk<σk+1≤1t_k < \sigma_{k+1} \le 1; they come from lines L10 and L5. On [tj−1,σj][t_{j-1}, \sigma_j] the profile is the UU curve that starts at (tj−1,x∗(tj−1))(t_{j-1}, x^*(t_{j-1})) (lines L4 and L11). On [σj,tj][\sigma_j, t_j] it is the LL curve that ends at the tangent point (line L9), and on [σk+1,1][\sigma_{k+1}, 1] it is the curve FF of line L1, an LL curve that ends at (1,0)(1, 0).

Lemma 3. x∗x^* is admissible.

Proof. x∗x^* is continuous, because each switch point is a point where the two curves meet (lines L5 and L10) and each tangent point is the end of one piece and the start of the next. Each piece solves x′=2Ux' = 2U or x′=2Lx' = 2L, so 2L≤x∗′≤2U2L \le x^{*\prime} \le 2U holds on each piece. Every integration stops when a curve goes above the MVC (lines L4, L7 and L9), and the pieces that are kept are the parts below it, so x∗≤MVCx^* \le \mathrm{MVC}. Finally x∗(0)=0x^*(0) = 0 and x∗(1)=0x^*(1) = 0. □\square

Optimality

Lemma 4. Every admissible profile xx satisfies x(s)≤x∗(s)x(s) \le x^*(s) for all s∈[0,1]s \in [0, 1].

Proof. At every left end of an acceleration piece, x≤x∗x \le x^*: at t0=0t_0 = 0 both are 00, and at a tangent point tjt_j we have x(tj)≤MVC(tj)=x∗(tj)x(t_j) \le \mathrm{MVC}(t_j) = x^*(t_j) because xx is admissible. Lemma 1 then gives x≤x∗x \le x^* on each [tj−1,σj][t_{j-1}, \sigma_j]. At every right end of a deceleration piece, x≤x∗x \le x^* for the same two reasons: at s=1s = 1 both are 00, and at tjt_j the MVC bounds xx. Lemma 2 then gives x≤x∗x \le x^* on each [σj,tj][\sigma_j, t_j] and on [σk+1,1][\sigma_{k+1}, 1]. These intervals cover [0,1][0, 1]. □\square

Theorem. Under (H1) to (H3), the profile x∗x^* returned by the algorithm is admissible and has the least traversal time among all admissible profiles.

Proof. Lemma 3 gives admissibility. By Lemma 4, 1/x∗(s)≤1/x(s)1/\sqrt{x^*(s)} \le 1/\sqrt{x(s)} wherever x(s)>0x(s) > 0, and where x(s)=0x(s) = 0 on a set of positive length, T(x)=∞T(x) = \infty. So T(x∗)≤T(x)T(x^*) \le T(x) for every admissible xx. ■\blacksquare

Remarks

The theorem is the optimality of the bang-bang structure: the fastest profile uses the largest or the smallest admissible acceleration at every point, and switches from the smallest to the largest only on the MVC. This is the result of Bobrow, Dubowsky and Gibson (1985) and of Shin and McKay (1985), in the form of Lynch and Park (Section 9.4).

Hypothesis (H3) is where the algorithm can fail. If the MVC has a flat part from a velocity limit, or a singular arc where the profile must follow the MVC with a control strictly between LL and UU, no LL curve touches the MVC at a single point, and the binary search of line L7 does not end at a tangent point. Pfeiffer and Johanni (1987) and Pham (2014) treat these cases. The proof also assumes exact integration. With RK4 at step hh, the computed curves differ from the exact ones by O(h4)O(h^4) where LL and UU are smooth, but only by O(h)O(h) near the corners of the MVC and near switch points, where the right-hand side is not smooth; the tangent point is found only to the resolution of the grid.

Complexity

Each curve takes at most 1/h1/h RK4 steps. Each step evaluates the limits four times, at O(m)O(m) for mm rows, and checks the MVC at O(m2)O(m^2), because the MVC is the smallest crossing of a lower and an upper bound on uu. Each switch costs a binary search of bb bisection steps, each one a full curve. The total is O(k b m2/h)O(k\, b\, m^2 / h) for kk switches, with b=O(log⁡(xlim/ε))b = O(\log(x_{\text{lim}} / \varepsilon)) for a tolerance ε\varepsilon. Memory is O(k/h)O(k/h) for the profile. The number of switches kk depends on the path and is not bounded in advance. Pham and Pham (2018) report O(m2N)O(m^2 N) for this method on a grid of NN points, with the MVC computed once per point.

Properties

  • Time-optimal under its hypotheses. A theorem for exact integration and isolated tangent points; see Correctness.
  • Bang-bang. The control is always LL or UU, which uses full torque on at least one joint at every point.
  • Profile, not grid. The result is a set of curves with explicit switch points, and the limits are checked along the curves, not only at grid points.
  • Fragile at singularities. Where the MVC is flat (velocity limits) or where the optimal profile must follow the MVC (singular arcs), the tangent search fails. This is a known weakness, studied by Pfeiffer and Johanni (1987) and by Pham (2014).

Variants and improvements

  • Finding switch points directly. Instead of a binary search from slims_{\text{lim}}, compute the candidate switch points on the MVC first: points where the MVC is not smooth, points where its slope equals the slope of the extreme curve, and zero-inertia points. Then integrate from them. Pfeiffer and Johanni (1987) and Pham (2014) work in this way.
  • Velocity limits. A joint velocity limit puts a flat part on the MVC. The optimal profile then follows the MVC with a control strictly between LL and UU. Implementations treat these parts as their own arcs (Pham 2014).
  • Acceleration limits instead of torque limits. For a kinematic robot with joint acceleration limits, the rows are ∣qs,ju+qss,jx∣≤aj|q_{s,j} u + q_{ss,j} x| \le a_j, and the same algorithm applies without a dynamic model.
  • Grid methods. The reachability method replaces the integration by small linear programs and avoids the switch-point search; the convex formulation solves one convex program.

When to use it

Use the integration method for paths with torque or acceleration limits and a smooth or piecewise smooth MVC, when you want a profile with explicit switch points and limits that hold along the whole path, not only at grid points. For paths with velocity limits, many contact constraints or near-singular dynamics, use a grid method such as TOPP-RA, which handles these cases without special code.

Pitfalls

  • Flat MVC. With a velocity limit, line L7 cannot find a touching curve: every braking curve from just below the MVC crosses it or falls away along a flat ceiling, and the binary search shrinks to a point. The code in this page does not handle velocity limits for this reason.
  • Tangent point off by one step. Line L8 picks a grid point of the integrated curve. If the true tangent point lies between grid points, the switch is off by up to hh, and the profile may cross the MVC slightly. A smaller hh near the switch, or an explicit switch-point search, fixes this.
  • Integrating through corners. The right side 2U(s,x)2U(s, x) has corners where the active limit changes. RK4 loses its order there, so the error is O(h)O(h) near corners, not O(h4)O(h^4).
  • Starting at zero speed. At (0,0)(0, 0) the path may need a positive UU to start at all. If U(0,0)≤0U(0, 0) \le 0, the robot cannot leave the start, and the algorithm must stop (the code returns nothing).
  • Line L9 never meets A. If the braking curve from the tangent point falls to zero speed before it meets the acceleration curve, the path cannot be traversed with these limits. The code returns nothing; a general implementation must report this case.

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.

bobrow_time_optimal_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bobrow-time-optimal-algorithm/. The authors are listed in prov/BWJG6T.jsonl.
"""Time-optimal path parameterization by numerical integration (Bobrow,
Dubowsky and Gibson 1985; Shin and McKay 1985), in the form of Lynch and
Park, Modern Robotics, Section 9.4.

The path parameter s runs over [0, 1]. The code works with x = s'^2
instead of s', so the phase-plane equation s'' = u becomes dx/ds = 2 u.
rows_fn(s) returns the constraint rows (a, b, c, lo, hi) at s, which mean

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

Torque limits of an arm along a path have this form, with a = M q_s,
b = M q_ss + C(q, q_s) q_s and c = g(q). At each (s, x) the admissible
accelerations form an interval [L(s, x), U(s, x)]; the maximum velocity
curve (MVC) is the largest x where the interval is not empty.

bobrow(rows_fn, h) integrates the U and L curves with RK4 at a fixed step h
in s, finds the switch points (binary search for the L curve that touches
the MVC), and returns the profile as a list of (s, x) points and the switch
points. Cost: O(1 / h) RK4 steps per curve and O(log(1 / tol)) curves per
binary search, so O(k log(1 / tol) / h) evaluations of rows_fn for k
switches. Velocity limits, which make a flat MVC that the profile must
follow, are not handled; see the page.
"""

import math

INF = math.inf
TOL = 1e-12


def accel_bounds(rows, x):
    """Return (L, U), the least and the largest admissible u at the state x.

    Rows with a = 0 do not bound u; they only bound x and are checked by
    mvc. L > U means that x is above the MVC.
    """
    lo_u, hi_u = -INF, INF
    for a, b, c, lo, hi in rows:
        if a == 0.0:
            continue
        r = b * x + c
        b1, b2 = (lo - r) / a, (hi - r) / a
        if a < 0.0:
            b1, b2 = b2, b1
        lo_u, hi_u = max(lo_u, b1), min(hi_u, b2)
    return lo_u, hi_u


def mvc(rows):
    """Largest x >= 0 with L(x) <= U(x) and every a = 0 row met; INF if none.

    For a lower bound (lo - b x - c) / a and an upper bound (hi - b x - c) / a'
    the condition lower <= upper is linear in x, so the MVC is the least of
    finitely many ratios (this is Fourier-Motzkin elimination of u).
    """
    lowers, uppers, best = [], [], INF
    for a, b, c, lo, hi in rows:
        if a == 0.0:
            if b > 0.0 and hi < INF:
                best = min(best, (hi - c) / b)
            if b < 0.0 and lo > -INF:
                best = min(best, (lo - c) / b)
            continue
        # u >= (p - b x) / a style bounds written as (const, slope) / a
        for bound, is_upper in ((lo, False), (hi, True)):
            if abs(bound) == INF:
                continue
            k = ((bound - c) / a, -b / a)  # u bound = k0 + k1 x
            upper = is_upper if a > 0.0 else not is_upper
            (uppers if upper else lowers).append(k)
    for l0, l1 in lowers:
        for u0, u1 in uppers:
            # need l0 + l1 x <= u0 + u1 x, that is (l1 - u1) x <= u0 - l0
            slope, rhs = l1 - u1, u0 - l0
            if slope > 0.0:
                best = min(best, rhs / slope)
            elif rhs < 0.0 and slope == 0.0:
                return 0.0
    return max(best, 0.0)


def _rk4(rows_fn, s, x, h, pick):
    """One RK4 step of dx/ds = 2 u(s, x) with u = pick(L, U), step h (signed)."""

    def f(ss, xx):
        lo, hi = accel_bounds(rows_fn(ss), max(xx, 0.0))
        return 2.0 * (hi if pick == "U" else lo)

    k1 = f(s, x)
    k2 = f(s + h / 2.0, x + h * k1 / 2.0)
    k3 = f(s + h / 2.0, x + h * k2 / 2.0)
    k4 = f(s + h, x + h * k3)
    return x + h * (k1 + 2.0 * k2 + 2.0 * k3 + k4) / 6.0


def _above(rows_fn, s, x):
    return x > mvc(rows_fn(s)) * (1.0 + 1e-12) + TOL


def integrate(rows_fn, s0, x0, h, pick, forward, stop=None):
    """Integrate the U or L curve from (s0, x0) on the grid of step h.

    Stop when the curve goes above the MVC ("mvc"), reaches x <= 0 ("zero"),
    leaves [0, 1] ("end"), or when stop(s, x) is true ("stop"). Return
    (points, reason); the points stay below the MVC.
    """
    pts = [(s0, x0)]
    step = h if forward else -h
    n = int(round((1.0 - s0) / h)) if forward else int(round(s0 / h))
    s, x = s0, x0
    for k in range(1, n + 1):
        s_new = s0 + k * step
        x_new = _rk4(rows_fn, s, x, step, pick)
        if _above(rows_fn, s_new, x_new):
            return pts, "mvc"
        if x_new <= 0.0:
            pts.append((s_new, 0.0))
            return pts, "zero"
        pts.append((s_new, x_new))
        if stop is not None and stop(s_new, x_new):
            return pts, "stop"
        s, x = s_new, x_new
    return pts, "end"


def _interp(curve, s):
    """Value at s of a curve given by points with increasing s (linear)."""
    lo, hi = 0, len(curve) - 1
    if s <= curve[0][0]:
        return curve[0][1]
    if s >= curve[-1][0]:
        return curve[-1][1]
    while hi - lo > 1:
        mid = (lo + hi) // 2
        if curve[mid][0] <= s:
            lo = mid
        else:
            hi = mid
    (s1, x1), (s2, x2) = curve[lo], curve[hi]
    return x1 + (x2 - x1) * (s - s1) / (s2 - s1)


def _crossing(p1, p2, curve):
    """Point where the segment p1 p2 meets the curve, by linear interpolation."""
    d1 = p1[1] - _interp(curve, p1[0])
    d2 = p2[1] - _interp(curve, p2[0])
    t = d1 / (d1 - d2) if d1 != d2 else 0.0
    return (p1[0] + t * (p2[0] - p1[0]), p1[1] + t * (p2[1] - p1[1]))


def bobrow(rows_fn, h=1e-3, tol=1e-10, max_switches=50):
    """Return (profile, switches) or None if no admissible profile is found.

    profile: list of (s, x) points with increasing s from (0, 0) to (1, 0).
    switches: list of (s, kind) with kind "UL" (maximum to minimum
    acceleration) or "LU" (minimum to maximum).
    """
    if accel_bounds(rows_fn(0.0), 0.0)[1] <= 0.0:
        return None
    back, _ = integrate(rows_fn, 1.0, 0.0, h, "L", forward=False)  # @line L1
    final = back[::-1]
    s_i, x_i = 0.0, 0.0  # @line L2
    switches, pieces = [], []
    for _ in range(max_switches):  # @line L3
        f_start = final[0][0]

        def meets_final(s, x):
            return s >= f_start and x >= _interp(final, s)

        acc, why = integrate(rows_fn, s_i, x_i, h, "U", True, meets_final)  # @line L4
        if why == "stop":  # @line L5
            cross = _crossing(acc[-2], acc[-1], final)
            switches.append((cross[0], "UL"))
            pieces.append(acc[:-1] + [cross])
            pieces.append([p for p in final if p[0] > cross[0]])
            return [p for piece in pieces for p in piece], switches
        if why != "mvc":
            return None
        s_lim, x_lim = acc[-1]  # @line L6
        low, high = 0.0, x_lim  # @line L7
        best = None
        while high - low > tol * max(1.0, x_lim):
            mid = 0.5 * (low + high)
            test, why = integrate(rows_fn, s_lim, mid, h, "L", True)
            if why == "mvc":
                high = mid
            else:
                low, best = mid, test
        if best is None:
            return None
        s_tan, x_tan = min(best, key=lambda p: mvc(rows_fn(p[0])) - p[1])  # @line L8

        def meets_acc(s, x, acc=acc):
            return s <= acc[-1][0] and x >= _interp(acc, s)

        dec, why = integrate(rows_fn, s_tan, x_tan, h, "L", False, meets_acc)  # @line L9
        if why != "stop":
            return None
        sw = _crossing(dec[-2], dec[-1], acc)
        switches.append((sw[0], "UL"))  # @line L10
        switches.append((s_tan, "LU"))
        pieces.append([p for p in acc if p[0] < sw[0]] + [sw])
        pieces.append([p for p in dec[::-1] if p[0] > sw[0]])
        s_i, x_i = s_tan, x_tan  # @line L11
        pieces[-1] = pieces[-1][:-1]  # the next U curve starts at (s_tan, x_tan)
    return None


def traversal_time(profile):
    """Time of the profile, with x linear between points: sum of 2 ds / (sqrt + sqrt)."""
    t = 0.0
    for (s1, x1), (s2, x2) in zip(profile, profile[1:]):
        den = math.sqrt(max(x1, 0.0)) + math.sqrt(max(x2, 0.0))
        if s2 > s1:
            if den == 0.0:
                return INF
            t += 2.0 * (s2 - s1) / den
    return t


def profile_value(profile, s):
    """x of the profile at s (linear interpolation)."""
    return _interp(profile, s)


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


def single_axis(dist, amax):
    """rows_fn of q(s) = dist * s with |q''| <= amax."""
    return lambda s: [(dist, 0.0, 0.0, -amax, amax)]


def arm2r(q0, q1, tau_max):
    """rows_fn of the planar 2R arm (unit links, unit point masses at the
    link ends, horizontal plane) along q(s) = q0 + s (q1 - q0), torque limits.
    """
    dq = [q1[0] - q0[0], q1[1] - q0[1]]

    def rows_fn(s):
        q2 = q0[1] + s * dq[1]
        c2, s2 = math.cos(q2), math.sin(q2)
        m11, m12 = 3.0 + 2.0 * c2, 1.0 + c2
        a = [m11 * dq[0] + m12 * dq[1], m12 * dq[0] + dq[1]]
        b = [-s2 * (2.0 * dq[0] * dq[1] + dq[1] * dq[1]), s2 * dq[0] * dq[0]]
        return [(a[j], b[j], 0.0, -tau_max[j], tau_max[j]) for j in range(2)]

    return rows_fn
test_bobrow_time_optimal_algorithm.py 127 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bobrow-time-optimal-algorithm/. The authors are listed in prov/BWJG6T.jsonl.
import math
import random
import unittest

from bobrow_time_optimal_algorithm import (
    accel_bounds,
    arm2r,
    bobrow,
    mvc,
    profile_value,
    single_axis,
    traversal_time,
)


def grid_oracle(rows_fn, n):
    """Independent check: backward braking limit and forward greedy pass on a grid.

    y_i is the largest x <= MVC with x + 2 h L(s_i, x) <= y_(i+1), found by
    bisection; then x_(i+1) = min(x_i + 2 h U(s_i, x_i), y_(i+1)). Explicit
    Euler on the phase plane, error O(1 / n).
    """
    h = 1.0 / n
    s = [i * h for i in range(n + 1)]
    y = [0.0] * (n + 1)
    for i in range(n - 1, -1, -1):
        rows = rows_fn(s[i])
        top = min(mvc(rows), 1e6)
        ok = lambda x: x + 2.0 * h * accel_bounds(rows, x)[0] <= y[i + 1]
        if ok(top):
            y[i] = top
            continue
        lo, hi = 0.0, top
        for _ in range(60):
            mid = 0.5 * (lo + hi)
            if ok(mid):
                lo = mid
            else:
                hi = mid
        y[i] = lo
    x = [0.0] * (n + 1)
    for i in range(n):
        x[i + 1] = min(x[i] + 2.0 * h * accel_bounds(rows_fn(s[i]), x[i])[1], y[i + 1])
    return sum(2.0 * h / (math.sqrt(x[i]) + math.sqrt(x[i + 1])) for i in range(n))


def below_mvc(rows_fn, profile, rel):
    return all(x <= mvc(rows_fn(s)) * (1.0 + rel) + 1e-9 for s, x in profile)


class TestWorkedExample(unittest.TestCase):
    def test_single_axis_triangle(self):
        # q = s, |q''| <= 2: accelerate to s = 1/2, brake to s = 1, T = sqrt(2).
        prof, switches = bobrow(single_axis(1.0, 2.0), h=0.01)
        self.assertAlmostEqual(traversal_time(prof), math.sqrt(2.0), places=9)
        self.assertEqual(len(switches), 1)
        self.assertAlmostEqual(switches[0][0], 0.5, places=9)
        self.assertAlmostEqual(profile_value(prof, 0.5), 2.0, places=9)

    def test_arm_example(self):
        rows_fn = arm2r([0.0, 0.0], [2.0, -3.0], [10.0, 4.0])
        prof, switches = bobrow(rows_fn, h=0.004)
        kinds = [k for _, k in switches]
        self.assertEqual(kinds, ["UL", "LU", "UL"])
        self.assertAlmostEqual(switches[0][0], 0.2385, delta=2e-3)
        # The tangent point is found on the integration grid: within one step h.
        self.assertAlmostEqual(switches[1][0], 0.35, delta=0.0041)
        self.assertAlmostEqual(switches[2][0], 0.731, delta=2e-3)
        self.assertEqual(prof[0], (0.0, 0.0))
        self.assertEqual(prof[-1][1], 0.0)
        self.assertAlmostEqual(prof[-1][0], 1.0, places=12)
        self.assertTrue(all(b[0] > a[0] for a, b in zip(prof, prof[1:])))
        self.assertTrue(below_mvc(rows_fn, prof, 1e-6))
        t = traversal_time(prof)
        self.assertAlmostEqual(t, grid_oracle(rows_fn, 2000), delta=3e-3 * t)
        # The profile touches the MVC, so a profile 1% faster is above it.
        self.assertFalse(below_mvc(rows_fn, [(s, 1.01 * x) for s, x in prof], 0.0))


class TestEdgeCases(unittest.TestCase):
    def test_cannot_start(self):
        # u + 5 <= 1 forces u <= -4 at rest: the robot cannot start.
        rows_fn = lambda s: [(1.0, 0.0, 5.0, -INF_LIMIT, 1.0)]
        self.assertIsNone(bobrow(rows_fn, h=0.05))

    def test_mvc_of_rows(self):
        # |u + x| <= 1 and |u - x| <= 1 meet only for x <= 1.
        rows = [(1.0, 1.0, 0.0, -1.0, 1.0), (1.0, -1.0, 0.0, -1.0, 1.0)]
        self.assertAlmostEqual(mvc(rows), 1.0, places=15)
        self.assertEqual(accel_bounds(rows, 0.5), (-0.5, 0.5))
        self.assertEqual(mvc([(1.0, 0.0, 0.0, -2.0, 2.0)]), math.inf)
        # A pure velocity row: 4 x <= 1.
        self.assertAlmostEqual(mvc([(1.0, 0.0, 0.0, -2.0, 2.0), (0.0, 4.0, 0.0, -math.inf, 1.0)]), 0.25)

    def test_asymmetric_limits(self):
        # Accelerate at 1, brake at 3: switch where s / 1 = (1 - s) / 3, s = 3/4.
        rows_fn = lambda s: [(1.0, 0.0, 0.0, -3.0, 1.0)]
        prof, switches = bobrow(rows_fn, h=0.01)
        self.assertAlmostEqual(switches[0][0], 0.75, places=9)
        t = math.sqrt(2.0 * 0.75 / 1.0) + math.sqrt(2.0 * 0.25 / 3.0)
        self.assertAlmostEqual(traversal_time(prof), t, places=9)


INF_LIMIT = math.inf


class TestRandomized(unittest.TestCase):
    def test_against_grid_oracle(self):
        rng = random.Random(1985)
        done = 0
        while done < 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_fn = arm2r([0.0, 0.0], q1, tau)
            res = bobrow(rows_fn, h=0.005)
            self.assertIsNotNone(res)
            prof, _ = res
            self.assertTrue(below_mvc(rows_fn, prof, 1e-6))
            t = traversal_time(prof)
            self.assertAlmostEqual(t, grid_oracle(rows_fn, 1000), delta=5e-3 * t)
            done += 1


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

History

The problem arose in the early 1980s, when robot controllers began to follow planned paths. Bobrow, Dubowsky and Gibson (IJRR, 1985) and Shin and McKay (IEEE Transactions on Automatic Control, 1985) found the same solution at the same time: the optimal profile is bang-bang in the path acceleration, and its switch points lie on the velocity limit curve. Shin and McKay published a follow-up in 1986 (IEEE Transactions on Automatic Control 31, 491-500). Pfeiffer and Johanni (1987) studied the switch points and the singular cases. Many implementations followed, and many failed at singular points; Pham (2014) analyzed these failures and gave a robust implementation. Lynch and Park present the algorithm in their textbook in the form used on this page.

References

  1. James E. Bobrow, Steven Dubowsky and John S. Gibson, Time-optimal control of robotic manipulators along specified paths, The International Journal of Robotics Research 4(3), 1985, 3-17, the whole paper (the phase plane, the velocity limit, and the construction from acceleration and deceleration curves)
  2. Kang G. Shin and Neil D. McKay, Minimum-time control of robotic manipulators with geometric path constraints, IEEE Transactions on Automatic Control 30(6), 1985, 531-541, the whole paper (the same construction, found independently)
  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, the time-scaling algorithm, and its assumptions and caveats)
  4. Friedrich Pfeiffer and Rainer Johanni, A concept for manipulator trajectory planning, IEEE Journal of Robotics and Automation 3(2), 1987, 115-123, the whole paper (switch points where the maximum velocity curve is not smooth, and singular points)
  5. 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 (singular arcs, velocity limits, and a robust implementation)

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