Algorithm Search⌘K

Algorithmadvanced

Online trajectory generation

Also called Kroger-Wahl online trajectory generation.

Computes in each control cycle a time-optimal motion from the current state, whatever it is, to a target state, under velocity, acceleration and often jerk limits.

Time
Θ(n) worst
Space
Θ(n) extra
Where
n = the number of axes
Properties
deterministicexactonlinenot randomized
Origin
Torsten Kroger, Friedrich M. Wahl, 2010

Online trajectory generation computes, in every cycle of a robot controller, a new motion from the current state of the robot to a target state, and the controller follows the first cycle of it. The current state can be anything: the robot may be moving fast, even away from the target, because a sensor event or a new command arrived in the middle of a motion. The motion must respect limits on the velocity and the acceleration, and in the general method also on the jerk, and it should take the least possible time. Because the computation must finish within one cycle, often a millisecond, it uses closed-form cases rather than iterative optimization. Kroger and Wahl (2010) set up the problem and classified it by "type": Type II has velocity and acceleration limits and the state is (position, velocity), and Type IV adds a jerk limit and the acceleration to the state. Their main algorithm is Type IV. This page explains the method and gives code for one axis of Type II, where the whole case analysis fits on a page; the double-S velocity profile shows what the jerk adds.

In plain words

A robot arm is moving toward a box when a camera reports that the box has moved. The arm cannot stop and start over, because it is already moving. It needs a new plan that starts from exactly where it is and how fast it is going right now, and that reaches the new box as fast as its motors allow. The controller makes a new plan like that every thousandth of a second, so any change of target is handled at once. Each plan is short: push hard one way, maybe coast at top speed, push hard the other way. Sometimes the arm is going too fast toward a nearby target and must overshoot, turn back, and come in again.

The problem

One axis, Type II. Input: the current state (p0,v0)(p_0, v_0), the target state (pT,vT)(p_T, v_T), and limits V>0V > 0 and A>0A > 0 with ∣v0∣,∣vT∣≤V|v_0|, |v_T| \le V. Output: a motion of least duration T∗T^* from the current state to the target state with ∣v∣≤V|v| \le V and ∣v˙∣≤A|\dot v| \le A throughout. In the online setting this is solved again in every cycle of length Δt\Delta t, from the state that the last cycle reached, and the target may change at any cycle.

For nn axes that must arrive at the same time, the time-optimal duration of each axis is computed first, and the slowest one sets the common time. The other axes are then stretched to that time. This step is the hard one, because the set of feasible durations of one axis need not be an interval: Kroger and Wahl call the gaps inoperative time intervals.

The algorithm

Let D=pT−p0D = p_T - p_0. An optimal profile has at most three pieces: acceleration σA\sigma A, then cruise at velocity σV\sigma V (possibly of zero length), then acceleration −σA-\sigma A, with σ=±1\sigma = \pm 1. If the profile does not cruise, its peak velocity vpv_p satisfies

vp2=r=σAD+12(v02+vT2).v_p^2 = r = \sigma A D + \tfrac12 (v_0^2 + v_T^2).
  1. MIN-TIME-PROFILE(p0, v0, pT, vT, V, A) ▷ D = pT - p0
  2. 1C ← the candidates built by lines L2 to L8
  3. 2for σ in (+1, -1)
  4. 3r ← σAD + (v0² + vT²)/2; if r < 0 then skip this σ
  5. 4for vp in (+√r, -√r)
  6. 5if σ(vp - v0) < 0 or σ(vp - vT) < 0 then skip this vp
  7. 6if |vp| ≤ V then pieces ← [(σ(vp - v0)/A, σA), (σ(vp - vT)/A, -σA)]
  8. 7else vc ← σV; t2 ← (D - ramp distance)/vc; pieces ← [(σ(vc - v0)/A, σA), (t2, 0), (σ(vc - vT)/A, -σA)]
  9. 8add (sum of durations, pieces) to C
  10. 9return the candidate in C with the least time
  11. OTG-STEP(p, v, pT, vT, V, A, Δt) ▷ one control cycle
  12. 10(T, pieces) ← MIN-TIME-PROFILE(p, v, pT, vT, V, A)
  13. 11if T ≤ Δt then return (pT, vT)
  14. 12return the state of the profile at time Δt

Line L3 is the distance condition for a profile with no cruise. Line L5 keeps the root only if the first piece really accelerates in direction σ\sigma and the last piece decelerates. Line L6 builds the two-piece profile. If the peak would exceed VV, line L7 caps it at σV\sigma V and inserts a cruise that covers the rest of the distance; the ramp distance is σ(2V2−v02−vT2)/(2A)\sigma(2V^2 - v_0^2 - v_T^2)/(2A). Line L9 picks the fastest candidate. Lines L10 to L12 are one control cycle.

Example

Moving start. p0=0p_0 = 0, v0=0.5v_0 = 0.5, pT=1p_T = 1, vT=0v_T = 0, V=1V = 1, A=2A = 2, all in SI units. For σ=+1\sigma = +1, line L3 gives r=2+0.125=2.125r = 2 + 0.125 = 2.125, and r≈1.458>V\sqrt r \approx 1.458 > V, so line L7 builds a cruise profile: accelerate for (1−0.5)/2=0.25(1 - 0.5)/2 = 0.25 s, the ramps cover (2−0.25)/4=0.4375(2 - 0.25)/4 = 0.4375 m, cruise for 0.56250.5625 s, decelerate for 0.50.5 s. T=1.3125T = 1.3125 s. For σ=−1\sigma = -1, r=−2+0.125<0r = -2 + 0.125 < 0, so there is no other candidate. A rest-to-rest trapezoid from the same point would take 1.51.5 s; the initial speed saves time.

Too fast for the target. p0=0p_0 = 0, v0=1v_0 = 1, pT=0.1p_T = 0.1, vT=0v_T = 0, V=1V = 1, A=1A = 1. Braking at once stops the axis at 0.50.5, past the target. For σ=+1\sigma = +1, r=0.6r = 0.6, and both roots fail line L5. For σ=−1\sigma = -1, r=0.4r = 0.4, and only vp=−0.4≈−0.6325v_p = -\sqrt{0.4} \approx -0.6325 passes: brake for 1.63251.6325 s through zero velocity to −0.6325-0.6325, then accelerate back for 0.63250.6325 s and stop exactly at the target. T≈2.2649T \approx 2.2649 s.

Online. The tests run the loop of lines L10 to L12 with Δt=0.001\Delta t = 0.001 s. It follows the one-shot profile within 10−610^{-6}, and when the target jumps at cycle 100, the loop turns to the new target in the next cycle with no jump in the velocity.

Correctness

Theorem: line L9 returns a motion of least time. The proof first characterizes the reachable durations: a motion of duration TT exists if and only if T≥∣vT−v0∣/AT \ge |v_T - v_0|/A and DD lies between the areas under two envelopes, the fastest and the slowest admissible velocity curves. At the least feasible duration T∗T^*, DD equals one of the two areas, so the optimal velocity is an envelope: a ramp, possibly a cruise at the limit, and a ramp. Every such profile is among the candidates of lines L2 to L8, and every candidate is admissible. A second theorem: if the target does not change, re-planning in every cycle loses no time, because the remaining part of an optimal profile is optimal from the new state; the loop reaches the target after ⌈T∗/Δt⌉\lceil T^*/\Delta t \rceil cycles. The tests check the optimality against a brute-force test of the envelope condition for 150 random states.

Proof: The candidate enumeration returns a time-optimal motion, and the online cycle loses no timefull

We use the notation of the page. One axis has the state (p,v)(p, v), the limits ∣v∣≤V|v| \le V and ∣v˙∣≤A|\dot v| \le A, the current state (p0,v0)(p_0, v_0) and the target state (pT,vT)(p_T, v_T), with ∣v0∣≤V|v_0| \le V and ∣vT∣≤V|v_T| \le V. Let D=pT−p0D = p_T - p_0. A motion of duration TT is admissible if its velocity vv on [0,T][0, T] is Lipschitz with constant AA, stays in [−V,V][-V, V], has v(0)=v0v(0) = v_0 and v(T)=vTv(T) = v_T, and ∫0Tv=D\int_0^T v = D. The proof is in exact arithmetic.

The set of reachable times

Let T0=∣vT−v0∣/AT_0 = |v_T - v_0| / A. For T≥T0T \ge T_0 define the envelopes

uT(t)=min⁡(v0+At, V, vT+A(T−t)),lT(t)=max⁡(v0−At, −V, vT−A(T−t)),u_T(t) = \min(v_0 + At,\ V,\ v_T + A(T - t)), \qquad l_T(t) = \max(v_0 - At,\ -V,\ v_T - A(T - t)),

and Pmax⁡(T)=∫0TuTP_{\max}(T) = \int_0^T u_T, Pmin⁡(T)=∫0TlTP_{\min}(T) = \int_0^T l_T.

Lemma 1. A motion of duration TT exists if and only if T≥T0T \ge T_0 and Pmin⁡(T)≤D≤Pmax⁡(T)P_{\min}(T) \le D \le P_{\max}(T).

Proof. If vv is admissible, then ∣vT−v0∣≤AT|v_T - v_0| \le AT, so T≥T0T \ge T_0. The Lipschitz bound gives v(t)≤v0+Atv(t) \le v_0 + At and v(t)≤vT+A(T−t)v(t) \le v_T + A(T - t), and v(t)≤Vv(t) \le V, so v≤uTv \le u_T; in the same way v≥lTv \ge l_T. Integrating gives Pmin⁡(T)≤D≤Pmax⁡(T)P_{\min}(T) \le D \le P_{\max}(T).

Conversely, let T≥T0T \ge T_0. Each of the three functions in uTu_T is Lipschitz with constant AA and at least −V-V, so uTu_T is too, and uT≤Vu_T \le V. At t=0t = 0, v0≤Vv_0 \le V and vT+AT≥v0v_T + AT \ge v_0, so uT(0)=v0u_T(0) = v_0; in the same way uT(T)=vTu_T(T) = v_T. So uTu_T is an admissible velocity profile except for the distance, and so is lTl_T, and so is every convex combination (1−λ)lT+λuT(1 - \lambda) l_T + \lambda u_T. Its distance (1−λ)Pmin⁡(T)+λPmax⁡(T)(1 - \lambda) P_{\min}(T) + \lambda P_{\max}(T) takes every value in between. □\square

The set of reachable times need not be an interval: for some states a short motion and a long motion exist, but a motion of medium length does not. Kroger and Wahl call such gaps inoperative time intervals. The minimum still exists.

Lemma 2. The set FF of reachable times has a least element T∗T^*, and D=Pmax⁡(T∗)D = P_{\max}(T^*) or D=Pmin⁡(T∗)D = P_{\min}(T^*).

Proof. Pmax⁡P_{\max} and Pmin⁡P_{\min} are continuous in TT, so FF is closed. For large TT, uT=Vu_T = V and lT=−Vl_T = -V on most of [0,T][0, T], so Pmax⁡(T)→∞P_{\max}(T) \to \infty and Pmin⁡(T)→−∞P_{\min}(T) \to -\infty, and FF is not empty. Let T∗=min⁡FT^* = \min F. If T∗=T0T^* = T_0, then uT∗=lT∗u_{T^*} = l_{T^*} is the single ramp from v0v_0 to vTv_T, so both equalities hold. If T∗>T0T^* > T_0 and Pmin⁡(T∗)<D<Pmax⁡(T∗)P_{\min}(T^*) < D < P_{\max}(T^*), then by continuity a slightly smaller TT is in FF, a contradiction. □\square

Every candidate is admissible

Lines L2 to L8 build, for σ∈{+1,−1}\sigma \in \{+1, -1\} and for each root vp=±rv_p = \pm\sqrt{r} of vp2=r=σAD+(v02+vT2)/2v_p^2 = r = \sigma A D + (v_0^2 + v_T^2)/2 that passes line L5, a profile with acceleration σA\sigma A, then 00, then −σA-\sigma A.

Lemma 3. Each candidate is an admissible motion of duration equal to its returned time.

Proof. Line L6 (∣vp∣≤V|v_p| \le V): the durations t1=σ(vp−v0)/At_1 = \sigma(v_p - v_0)/A and t3=σ(vp−vT)/At_3 = \sigma(v_p - v_T)/A are not negative by line L5. The velocity moves monotonically from v0v_0 to vpv_p and then from vpv_p to vTv_T, all in [−V,V][-V, V], and ends at vp−(vp−vT)=vTv_p - (v_p - v_T) = v_T. The distance is

σ(vp2−v02)2A+σ(vp2−vT2)2A=σ(2r−v02−vT2)2A=D.\frac{\sigma(v_p^2 - v_0^2)}{2A} + \frac{\sigma(v_p^2 - v_T^2)}{2A} = \frac{\sigma(2r - v_0^2 - v_T^2)}{2A} = D.

Line L7 (∣vp∣>V|v_p| > V): with vc=σVv_c = \sigma V, the ramps take t1=(V−σv0)/A≥0t_1 = (V - \sigma v_0)/A \ge 0 and t3=(V−σvT)/A≥0t_3 = (V - \sigma v_T)/A \ge 0 and cover d=σ(2V2−v02−vT2)/(2A)d = \sigma(2V^2 - v_0^2 - v_T^2)/(2A). Since r>V2r > V^2, σD>(2V2−v02−vT2)/(2A)\sigma D > (2V^2 - v_0^2 - v_T^2)/(2A), so the cruise time t2=(D−d)/vc=(σD−(2V2−v02−vT2)/(2A))/Vt_2 = (D - d)/v_c = (\sigma D - (2V^2 - v_0^2 - v_T^2)/(2A))/V is positive, and the distance is d+vct2=Dd + v_c t_2 = D. □\square

The best candidate is optimal

Theorem 1. Line L9 returns a motion of duration T∗T^*.

Proof. By Lemma 3, every candidate time is in FF, so it is at least T∗T^*. By Lemma 2, say D=Pmax⁡(T∗)D = P_{\max}(T^*); the other case is the mirror image with σ=−1\sigma = -1. Then uT∗u_{T^*} is an optimal velocity profile. It rises with slope AA, may stay at VV for a time t2≥0t_2 \ge 0, and falls with slope AA.

If t2=0t_2 = 0, its peak vpv_p satisfies vp≥v0v_p \ge v_0, vp≥vTv_p \ge v_T and ∣vp∣≤V|v_p| \le V, and its distance is (2vp2−v02−vT2)/(2A)=D(2v_p^2 - v_0^2 - v_T^2)/(2A) = D, so vp2=rv_p^2 = r for σ=+1\sigma = +1. So vpv_p is one of the two roots of line L4, it passes line L5, and line L6 builds exactly this profile.

If t2>0t_2 > 0, the peak is VV and D=(2V2−v02−vT2)/(2A)+Vt2D = (2V^2 - v_0^2 - v_T^2)/(2A) + V t_2, so r=V2+AVt2>V2r = V^2 + AVt_2 > V^2. The root +r>V+\sqrt r > V passes line L5, and line L7 builds exactly this profile. (The root −r<−V-\sqrt r < -V fails line L5, because v0≥−Vv_0 \ge -V.)

So a candidate has time T∗T^*, and line L9 returns a candidate of time T∗T^*. □\square

The online cycle

Line L10 plans from the current state, and line L12 moves the state by Δt\Delta t along the plan. Let T∗(x)T^*(x) be the minimum time from state xx to the fixed target.

Theorem 2. If the target does not change, T∗T^* of the new state is T∗(x)−ΔtT^*(x) - \Delta t whenever T∗(x)>ΔtT^*(x) > \Delta t. So the loop reaches the target after ⌈T∗(x0)/Δt⌉\lceil T^*(x_0) / \Delta t \rceil cycles, which is the time of the one-shot profile rounded up to a whole cycle.

Proof. The rest of the optimal profile from xx is admissible from the new state x′x' and takes T∗(x)−ΔtT^*(x) - \Delta t, so T∗(x′)≤T∗(x)−ΔtT^*(x') \le T^*(x) - \Delta t. If T∗(x′)<T∗(x)−ΔtT^*(x') < T^*(x) - \Delta t, the first Δt\Delta t of the profile followed by an optimal motion from x′x' would reach the target from xx in less than T∗(x)T^*(x), a contradiction. In the last cycle, T∗≤ΔtT^* \le \Delta t, and line L11 sets the state to the target. □\square

If the target changes between two cycles, line L10 simply plans from the current state, which is admissible because every step of lines L10 to L12 keeps ∣v∣≤V|v| \le V and changes vv by at most AΔtA \Delta t. Lemma 1 then applies to the new target.

Complexity

In the real RAM with a square root, lines L1 to L9 examine at most four candidates, so one axis costs Θ(1)\Theta(1) per cycle. For nn axes, computing all minimum times and the common time costs Θ(n)\Theta(n). For Type IV, Kroger and Wahl use decision trees with many more cases, some solved with polynomial roots, but the number of operations per axis is still bounded by a constant. This is what makes the method fit into a cycle of one millisecond or less.

Properties

  • Time-optimal from any state. A theorem for the one-axis Type II problem: the result is the least time over all admissible motions, not only over profiles of a fixed shape.
  • Online. A new target can be given in any cycle, and the motion stays within the limits, with continuous velocity, in every cycle.
  • No lost time. With a fixed target, the receding plan reaches the target as fast as the one-shot plan, rounded up to a whole cycle (a theorem).
  • Bang-bang structure. The acceleration is +A+A, −A-A, or 00 while the speed limit is active; see bang-bang control.
  • Acceleration jumps in Type II. As with the trapezoid, the acceleration of a Type II profile jumps. Type IV removes the jumps by limiting the jerk.

Variants and improvements

  • Type IV, jerk limited. The state includes the acceleration and the jerk is bounded; the profiles have up to seven pieces, as the double S, and many more cases. Kroger and Wahl solve them with decision trees.
  • Arbitrary target states. Berscheid and Kroger (2021) extended the jerk-limited case to targets with nonzero velocity and acceleration, in the open-source library Ruckig. The earlier Reflexxes library offered Type II as open source and Type IV commercially.
  • Velocity targets. The target can be a velocity instead of a position, for jogging and for visual servoing.
  • Along a path. Online generation in each axis does not keep the robot on a given path. Along a fixed path, use time-optimal path parameterization.
  • With a model. Model predictive control also replans every cycle, with a model of the dynamics and a general cost, at a higher computing cost.

When to use it

Use online trajectory generation when the target can change during a motion: sensor-guided motion, visual servoing, human-robot collaboration, switching between controllers, and emergency stops from an arbitrary state. Use it to make any command stream smooth and feasible. Use an offline trapezoid or double S if every motion starts and ends at rest and the target is known in advance; the result is the same with simpler code.

Pitfalls

  • Ignoring the overshoot case. Code that only tries the direction of the target fails when the axis is moving too fast toward a close target, as in the second example.
  • Rounding at the boundaries. In floating point, line L5 needs a small tolerance, and a root near the limit can fall on either side of VV. The code accepts small negative values in line L5.
  • States outside the limits. If ∣v0∣>V|v_0| > V, for example after a limit was lowered, there is no admissible motion. Handle this case first, by braking to the limit.
  • Synchronizing several axes naively. Stretching each axis to the common time with a formula that assumes the feasible times form an interval fails inside an inoperative time interval.
  • Different cycle times. The profile is computed in continuous time; evaluating it at a time other than the real cycle time makes the state drift.

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.

online_trajectory_generation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/online-trajectory-generation/. The authors are listed in prov/T2ZEJ5.jsonl.
"""Online trajectory generation for one axis, with velocity and acceleration bounds.

This is the second-order case (Type II in the classification of Kroger and
Wahl): the state is (position, velocity), |v| <= V and |a| <= A. In each
control cycle, min_time_profile() computes the time-optimal motion from the
current state to the target state, and otg_step() moves the state along it
by one cycle time dt. The target may change between two cycles.

A profile is a list of (duration, acceleration) pieces with at most three
pieces: a ramp, a cruise at |v| = V (possibly of zero length), and a ramp.
"""

import math


def _candidates(p0, v0, pT, vT, V, A):
    """All bang-cruise-bang profiles that reach the target; each is (time, pieces)."""
    D = pT - p0
    out = []
    for sigma in (1, -1):  # @line L2
        r = sigma * A * D + (v0 * v0 + vT * vT) / 2  # @line L3
        if r < 0:
            continue
        for vp in (math.sqrt(r), -math.sqrt(r)):  # @line L4
            if sigma * (vp - v0) < -1e-12 or sigma * (vp - vT) < -1e-12:  # @line L5
                continue
            if abs(vp) <= V:  # @line L6
                t1 = max(0.0, sigma * (vp - v0) / A)
                t3 = max(0.0, sigma * (vp - vT) / A)
                pieces = [(t1, sigma * A), (0.0, 0.0), (t3, -sigma * A)]
            else:  # @line L7
                vc = sigma * V
                t1 = sigma * (vc - v0) / A
                t3 = sigma * (vc - vT) / A
                d_ramps = (2 * vc * vc - v0 * v0 - vT * vT) / (2 * sigma * A)
                t2 = (D - d_ramps) / vc
                pieces = [(t1, sigma * A), (t2, 0.0), (t3, -sigma * A)]
            out.append((sum(d for d, _ in pieces), pieces))  # @line L8
    return out


def min_time_profile(p0, v0, pT, vT, V, A):
    """Time-optimal profile from (p0, v0) to (pT, vT); returns (time, pieces)."""
    if V <= 0 or A <= 0:
        raise ValueError("V and A must be positive")
    if abs(v0) > V + 1e-12 or abs(vT) > V + 1e-12:
        raise ValueError("start and target velocities must satisfy |v| <= V")
    cands = _candidates(p0, v0, pT, vT, V, A)  # @line L1
    return min(cands, key=lambda c: c[0])  # @line L9


def evaluate(p0, v0, pieces, t):
    """State (p, v, a) at time t along the pieces (t beyond the end holds the final state)."""
    p, v = p0, v0
    for dur, a in pieces:
        h = min(dur, t)
        if h > 0:
            p += v * h + a * h * h / 2
            v += a * h
        t -= dur
        if t <= 0:
            return p, v, a
    return p, v, 0.0


def otg_step(p, v, pT, vT, V, A, dt):
    """One control cycle: plan from the current state, then move by dt along the plan."""
    T, pieces = min_time_profile(p, v, pT, vT, V, A)  # @line L10
    if T <= dt:
        return pT, vT, T  # @line L11
    p1, v1, _ = evaluate(p, v, pieces, dt)  # @line L12
    return p1, max(-V, min(V, v1)), T


def envelope_reachable(p0, v0, pT, vT, V, A, T, steps=2000):
    """Brute-force test: can (pT, vT) be reached at exactly time T?

    Every admissible velocity lies between l(t) = max(v0 - A t, -V, vT - A (T - t))
    and u(t) = min(v0 + A t, V, vT + A (T - t)). Both bounds are admissible
    when |v0 - vT| <= A T, and so is every convex combination. So the target is
    reachable at T exactly when p0 + integral(l) <= pT <= p0 + integral(u).
    """
    if abs(v0 - vT) > A * T + 1e-12:
        return False
    h = T / steps
    lo = hi = 0.0
    for k in range(steps):
        t = (k + 0.5) * h
        hi += min(v0 + A * t, V, vT + A * (T - t)) * h
        lo += max(v0 - A * t, -V, vT - A * (T - t)) * h
    return p0 + lo - 1e-9 <= pT <= p0 + hi + 1e-9
test_online_trajectory_generation.py 96 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/online-trajectory-generation/. The authors are listed in prov/T2ZEJ5.jsonl.
"""Tests: the profile reaches the target, respects the limits, is time-optimal, and the online loop reacts."""

import random

from online_trajectory_generation import envelope_reachable, evaluate, min_time_profile, otg_step


def check_profile(p0, v0, pT, vT, V, A):
    T, pieces = min_time_profile(p0, v0, pT, vT, V, A)
    assert abs(sum(d for d, _ in pieces) - T) < 1e-12
    assert all(d >= -1e-12 and abs(a) <= A + 1e-12 for d, a in pieces)
    p, v, _ = evaluate(p0, v0, pieces, T + 1)
    assert abs(p - pT) < 1e-9 and abs(v - vT) < 1e-9
    # The velocity stays within the limit at every piece boundary, and so inside each piece.
    t = 0.0
    for d, _ in pieces:
        t += d
        assert abs(evaluate(p0, v0, pieces, t)[1]) <= V + 1e-9
    return T


def test_worked_example():
    T = check_profile(0.0, 0.5, 1.0, 0.0, 1.0, 2.0)
    assert abs(T - 1.3125) < 1e-12


def test_rest_to_rest_matches_trapezoid():
    # D = 1, V = 1, A = 2: acceleration time 0.5, total 1.5. A short move gives a triangle.
    assert abs(check_profile(0.0, 0.0, 1.0, 0.0, 1.0, 2.0) - 1.5) < 1e-12
    assert abs(check_profile(0.0, 0.0, 0.25, 0.0, 1.0, 2.0) - 2 * (0.25 / 2) ** 0.5) < 1e-12
    assert abs(check_profile(3.0, 0.0, 2.0, 0.0, 1.0, 2.0) - 1.5) < 1e-12


def test_overshoot_case():
    # Fast toward a target that is close: the motion must pass it and come back.
    T, pieces = min_time_profile(0.0, 1.0, 0.1, 0.0, 1.0, 1.0)
    assert pieces[0][1] < 0
    check_profile(0.0, 1.0, 0.1, 0.0, 1.0, 1.0)


def test_random_states_against_brute_force():
    rng = random.Random(7)
    for _ in range(150):
        V = rng.uniform(0.5, 2.0)
        A = rng.uniform(0.5, 3.0)
        p0, pT = rng.uniform(-2, 2), rng.uniform(-2, 2)
        v0, vT = rng.uniform(-V, V), rng.uniform(-V, V)
        T = check_profile(p0, v0, pT, vT, V, A)
        # Reachable at T, and not reachable at any sampled earlier time.
        assert envelope_reachable(p0, v0, pT, vT, V, A, T, steps=400)
        for k in range(1, 40):
            t = T * k / 40 * 0.999
            assert not envelope_reachable(p0, v0, pT, vT, V, A, t, steps=400)


def test_online_loop_follows_the_one_shot_profile():
    p0, v0, pT, vT, V, A, dt = 0.0, 0.0, 2.0, 0.0, 1.0, 2.0, 0.01
    T, pieces = min_time_profile(p0, v0, pT, vT, V, A)
    p, v, t = p0, v0, 0.0
    for _ in range(1000):
        p, v, left = otg_step(p, v, pT, vT, V, A, dt)
        t += dt
        if left <= dt:
            break
        q, w, _ = evaluate(p0, v0, pieces, t)
        assert abs(p - q) < 1e-6 and abs(w - v) < 1e-6
    assert (p, v) == (pT, vT)
    assert abs(t - T) <= dt + 1e-9


def test_online_loop_reacts_to_new_target():
    V, A, dt = 1.0, 2.0, 0.005
    p, v = 0.0, 0.0
    target = 2.0
    steps = 0
    while (p, v) != (target, 0.0) and steps < 2000:
        if steps == 100:
            target = -1.0  # the target jumps while the axis moves at full speed
        prev = v
        p, v, _ = otg_step(p, v, target, 0.0, V, A, dt)
        assert abs(v) <= V + 1e-12
        assert abs(v - prev) <= A * dt + 1e-9
        steps += 1
    assert (p, v) == (-1.0, 0.0)


def test_bad_input():
    for args in ((0.0, 2.0, 1.0, 0.0, 1.0, 1.0), (0.0, 0.0, 1.0, 0.0, 0.0, 1.0)):
        try:
            min_time_profile(*args)
        except ValueError:
            pass
        else:
            raise AssertionError("bad input must fail")

History

Robot controllers long used offline trajectories that start and end at rest. Kroger and Wahl (2010) gave a general framework and decision-tree algorithms that compute synchronized time-optimal motions of several axes from any state within one control cycle, with Types I to IV realized; Kroger's book of the same year gives the full treatment. Their Reflexxes library made the method widely used. Berscheid and Kroger (2021) published Ruckig, which handles jerk-limited motions to arbitrary target states.

References

  1. Torsten Kroger and Friedrich M. Wahl, Online trajectory generation, basic concepts for instantaneous reactions to unforeseen events, IEEE Transactions on Robotics 26(1), 2010, 94-111, the whole paper (the types of online trajectory generation, the decision trees, inoperative time intervals and the synchronization of several axes)
  2. Torsten Kroger, On-Line Trajectory Generation in Robotic Systems, Springer Tracts in Advanced Robotics 58, Springer, 2010, the whole book
  3. Lars Berscheid and Torsten Kroger, Jerk-limited real-time trajectory generation with arbitrary target states, Robotics, Science and Systems, 2021, the whole paper (the Ruckig algorithm for jerk-limited motions to targets with nonzero velocity and acceleration)
  4. Luigi Biagiotti and Claudio Melchiorri, Trajectory Planning for Automatic Machines and Robots, Springer, 2008, Section 3.4.4 (online computation of the double S trajectory)

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
  • a scene preset for the example