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.
- Solves
- Trajectory generation
- Time
- Θ(n) worst
- Space
- Θ(n) extra
- Where
- n = the number of axes
- Model
- Real RAM
- Properties
- deterministicexactonlinenot randomized
- Evidence
- Proof sketchCode in 1 languages
- 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 , the target state , and limits and with . Output: a motion of least duration from the current state to the target state with and throughout. In the online setting this is solved again in every cycle of length , from the state that the last cycle reached, and the target may change at any cycle.
For 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 . An optimal profile has at most three pieces: acceleration , then cruise at velocity (possibly of zero length), then acceleration , with . If the profile does not cruise, its peak velocity satisfies
MIN-TIME-PROFILE(p0, v0, pT, vT, V, A) ▷ D = pT - p0- 1
C ← the candidates built by lines L2 to L8 - 2
for σ in (+1, -1) - 3
r ← σAD + (v0² + vT²)/2; if r < 0 then skip this σ - 4
for vp in (+√r, -√r) - 5
if σ(vp - v0) < 0 or σ(vp - vT) < 0 then skip this vp - 6
if |vp| ≤ V then pieces ← [(σ(vp - v0)/A, σA), (σ(vp - vT)/A, -σA)] - 7
else vc ← σV; t2 ← (D - ramp distance)/vc; pieces ← [(σ(vc - v0)/A, σA), (t2, 0), (σ(vc - vT)/A, -σA)] - 8
add (sum of durations, pieces) to C - 9
return the candidate in C with the least time OTG-STEP(p, v, pT, vT, V, A, Δt) ▷ one control cycle- 10
(T, pieces) ← MIN-TIME-PROFILE(p, v, pT, vT, V, A) - 11
if T ≤ Δt then return (pT, vT) - 12
return 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 and the last piece decelerates. Line L6 builds the two-piece profile. If the peak would exceed , line L7 caps it at and inserts a cruise that covers the rest of the distance; the ramp distance is . Line L9 picks the fastest candidate. Lines L10 to L12 are one control cycle.
Example
Moving start. , , , , , , all in SI units. For , line L3 gives , and , so line L7 builds a cruise profile: accelerate for s, the ramps cover m, cruise for s, decelerate for s. s. For , , so there is no other candidate. A rest-to-rest trapezoid from the same point would take s; the initial speed saves time.
Too fast for the target. , , , , , . Braking at once stops the axis at , past the target. For , , and both roots fail line L5. For , , and only passes: brake for s through zero velocity to , then accelerate back for s and stop exactly at the target. s.
Online. The tests run the loop of lines L10 to L12 with s. It follows the one-shot profile within , 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 exists if and only if and lies between the areas under two envelopes, the fastest and the slowest admissible velocity curves. At the least feasible duration , 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 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 , the limits and , the current state and the target state , with and . Let . A motion of duration is admissible if its velocity on is Lipschitz with constant , stays in , has and , and . The proof is in exact arithmetic.
The set of reachable times
Let . For define the envelopes
and , .
Lemma 1. A motion of duration exists if and only if and .
Proof. If is admissible, then , so . The Lipschitz bound gives and , and , so ; in the same way . Integrating gives .
Conversely, let . Each of the three functions in is Lipschitz with constant and at least , so is too, and . At , and , so ; in the same way . So is an admissible velocity profile except for the distance, and so is , and so is every convex combination . Its distance takes every value in between.
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 of reachable times has a least element , and or .
Proof. and are continuous in , so is closed. For large , and on most of , so and , and is not empty. Let . If , then is the single ramp from to , so both equalities hold. If and , then by continuity a slightly smaller is in , a contradiction.
Every candidate is admissible
Lines L2 to L8 build, for and for each root of that passes line L5, a profile with acceleration , then , then .
Lemma 3. Each candidate is an admissible motion of duration equal to its returned time.
Proof. Line L6 (): the durations and are not negative by line L5. The velocity moves monotonically from to and then from to , all in , and ends at . The distance is
Line L7 (): with , the ramps take and and cover . Since , , so the cruise time is positive, and the distance is .
The best candidate is optimal
Theorem 1. Line L9 returns a motion of duration .
Proof. By Lemma 3, every candidate time is in , so it is at least . By Lemma 2, say ; the other case is the mirror image with . Then is an optimal velocity profile. It rises with slope , may stay at for a time , and falls with slope .
If , its peak satisfies , and , and its distance is , so for . So is one of the two roots of line L4, it passes line L5, and line L6 builds exactly this profile.
If , the peak is and , so . The root passes line L5, and line L7 builds exactly this profile. (The root fails line L5, because .)
So a candidate has time , and line L9 returns a candidate of time .
The online cycle
Line L10 plans from the current state, and line L12 moves the state by along the plan. Let be the minimum time from state to the fixed target.
Theorem 2. If the target does not change, of the new state is whenever . So the loop reaches the target after cycles, which is the time of the one-shot profile rounded up to a whole cycle.
Proof. The rest of the optimal profile from is admissible from the new state and takes , so . If , the first of the profile followed by an optimal motion from would reach the target from in less than , a contradiction. In the last cycle, , and line L11 sets the state to the target.
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 and changes by at most . 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 per cycle. For axes, computing all minimum times and the common time costs . 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 , , or 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 . The code accepts small negative values in line L5.
- States outside the limits. If , 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.
# 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
- 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)
- Torsten Kroger, On-Line Trajectory Generation in Robotic Systems, Springer Tracts in Advanced Robotics 58, Springer, 2010, the whole book
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag T2ZEJ5 Edit this page History Report an error Markdown