Algorithm Search⌘K

Algorithmintro

Trapezoidal velocity profile

Also called linear segment with parabolic blends, LSPB.

Moves one axis from rest to rest in minimum time under velocity and acceleration limits: accelerate, cruise, decelerate, or a triangle if short.

Time
Θ(n) worst
Space
Θ(n) extra
Where
n = the number of axes
Properties
deterministicexactofflinenot randomized

A trapezoidal velocity profile moves one axis, such as a robot joint or a machine slide, over a distance DD from rest to rest in the least possible time when the speed is at most VV and the acceleration is at most AA in size. It accelerates at AA, cruises at VV, and decelerates at AA, so the velocity plotted against time is a trapezoid. If the move is too short to reach VV, that is if D<V2/AD < V^2/A, the cruise phase disappears and the profile is a triangle that peaks at AD\sqrt{AD}. The position is a parabola during the ramps and a straight line during the cruise, which is where the robotics name "linear segment with parabolic blends" comes from. The profile is the cheapest time-optimal motion there is, but its acceleration jumps between 00 and ±A\pm A, so the jerk is infinite at four instants. The double-S velocity profile adds a jerk limit for this reason, and feedrate scheduling in machine tools uses both.

In plain words

A car must go from one red light to the next as fast as possible, without going over the speed limit and without pressing the pedals harder than a fixed amount. The best plan is the obvious one: floor it, hold the speed limit, then brake as late as possible so the car stops exactly at the light. Plot the speed over time and you see a ramp up, a flat top and a ramp down, a trapezoid. If the lights are close, the car never reaches the limit: it speeds up until half way and then brakes, and the plot is a triangle. The page shows why no other plan is faster, and how to stretch the plan so that several axes arrive at the same moment.

The problem

Input: a distance D>0D > 0, a velocity limit V>0V > 0 and an acceleration limit A>0A > 0. Output: a motion s(t)s(t) on [0,T][0, T] with s(0)=0s(0) = 0, s(T)=Ds(T) = D, s′(0)=s′(T)=0s'(0) = s'(T) = 0, ∣s′∣≤V|s'| \le V and ∣s′′∣≤A|s''| \le A, with TT as small as possible. This is the rest-to-rest case on one axis. A signed move from q0q_0 to q1q_1 uses D=∣q1−q0∣D = |q_1 - q_0| and the sign of q1−q0q_1 - q_0. Moves that start or end at a nonzero velocity are the job of online trajectory generation.

The algorithm

  1. TRAPEZOID(D, V, A) ▷ D, V, A > 0
  2. 1if D·A ≥ V² then ▷ the move is long enough to reach V
  3. 2Ta ← V / A; vp ← V
  4. 3T ← D / V + V / A
  5. else ▷ triangle
  6. 4Ta ← √(D / A); vp ← A·Ta
  7. 5T ← 2 Ta
  8. 6return (Ta, vp, T)
  9. SAMPLE(D, Ta, vp, T, t) ▷ A = vp / Ta
  10. 7if t < Ta then return (A t²/2, A t, A)
  11. 8if t ≤ T - Ta then return (vp (t - Ta/2), vp, 0)
  12. 9if t < T then r ← T - t; return (D - A r²/2, A r, -A)

Line L1 compares DD with V2/AV^2/A, the distance needed to ramp up to VV and back down. Lines L2 and L3 give the trapezoid: each ramp takes V/AV/A and covers V2/(2A)V^2/(2A), and the cruise covers the rest, D−V2/AD - V^2/A, at speed VV. Lines L4 and L5 give the triangle: each half takes TaT_a and covers ATa2/2=D/2AT_a^2/2 = D/2. Lines L7 to L9 give the position, the velocity and the acceleration in the three phases.

Several axes. If nn axes must start and stop together, compute the minimum time TkT_k of each axis and take T=max⁡kTkT = \max_k T_k. Every other axis then covers its distance in the longer time TT with a slower trapezoid. Keeping the acceleration AA, its ramp time is the smaller root of D=ATa(T−Ta)D = A T_a (T - T_a):

Ta=12(T−T2−4D/A),T_a = \tfrac12\left(T - \sqrt{T^2 - 4D/A}\right),

which is real when T≥2D/AT \ge 2\sqrt{D/A}, and its peak ATaAT_a is at most VV (proof, Lemma 4). Biagiotti and Melchiorri (Section 3.2.3) also give versions that scale the velocity and the acceleration together.

Example

Trapezoid. D=1D = 1 m, V=1V = 1 m/s, A=2A = 2 m/s². Line L1: DA=2≥V2=1D A = 2 \ge V^2 = 1, so lines L2 and L3 give Ta=0.5T_a = 0.5 s and T=1+0.5=1.5T = 1 + 0.5 = 1.5 s. The axis accelerates for 0.5 s and covers 0.25 m, cruises for 0.5 s and covers 0.5 m, and brakes for 0.5 s over the last 0.25 m.

Triangle. D=0.25D = 0.25 m with the same limits. Line L1: 0.5<10.5 < 1, so lines L4 and L5 give Ta=0.125≈0.3536T_a = \sqrt{0.125} \approx 0.3536 s, a peak of 0.70710.7071 m/s, and T≈0.7071T \approx 0.7071 s.

Two axes. Axis 1 moves 1 m and axis 2 moves 0.5 m, both with V=1V = 1 and A=2A = 2. Alone, axis 2 would take 0.5+0.5=10.5 + 0.5 = 1 s. Both must take T=1.5T = 1.5 s, so axis 2 uses Ta=(1.5−2.25−1)/2≈0.1910T_a = (1.5 - \sqrt{2.25 - 1})/2 \approx 0.1910 s and peaks at 0.38200.3820 m/s. Check: 2⋅0.1910⋅(1.5−0.1910)≈0.52 \cdot 0.1910 \cdot (1.5 - 0.1910) \approx 0.5.

Machine tool numbers. With the example of feedrate scheduling, D=100D = 100 mm, V=50V = 50 mm/s, A=500A = 500 mm/s², the trapezoid takes 100/50+50/500=2.1100/50 + 50/500 = 2.1 s. The double-S profile with a jerk limit of 10410^4 mm/s³ takes 2.152.15 s.

Correctness

Theorem: the profile is admissible, covers exactly DD, and no admissible motion is faster. The proof bounds the velocity of any admissible motion of duration TT by the envelope min⁡(At,V,A(T−t))\min(At, V, A(T - t)), because the velocity starts and ends at zero and cannot change faster than AA. The area under the envelope is the most distance that time TT allows, and it grows strictly with TT. The profile of lines L1 to L5 is the envelope itself, with area exactly DD, so any shorter time covers less than DD. In optimal control terms, the acceleration is "bang-bang": it is always +A+A or −A-A, except while the speed limit is active, where it is 00. The proof gives the four lemmas and the synchronization formula.

Proof: The trapezoidal profile covers the distance within the limits, and no rest-to-rest motion of one axis is fasterfull

We use the notation of the page. One axis moves the distance D>0D > 0 from rest to rest. An admissible motion on [0,T][0, T] is a function ss with s(0)=0s(0) = 0, s(T)=Ds(T) = D, s′(0)=s′(T)=0s'(0) = s'(T) = 0, an absolutely continuous velocity v=s′v = s', ∣v∣≤V|v| \le V and ∣v′∣≤A|v'| \le A almost everywhere. Lines L1 to L5 choose the ramp time TaT_a, the peak velocity vpv_p and the time TT; the velocity of the profile rises with slope AA for TaT_a, stays at vpv_p, and falls with slope AA for the last TaT_a.

The profile is admissible and covers D

Lemma 1. The profile of lines L1 to L6 is admissible and covers exactly DD.

Proof. Case DA≥V2DA \ge V^2 (lines L2 and L3). Ta=V/AT_a = V/A and T=D/V+V/AT = D/V + V/A, so the cruise time is T−2Ta=D/V−V/AT - 2T_a = D/V - V/A, which is not negative because DA≥V2DA \ge V^2. The velocity is at most vp=Vv_p = V and its slope is 00 or ±A\pm A. The area under the velocity is that of a trapezoid, vp(T−Ta)=V⋅D/V=Dv_p (T - T_a) = V \cdot D/V = D.

Case DA<V2DA < V^2 (lines L4 and L5). Ta=D/AT_a = \sqrt{D/A}, T=2TaT = 2T_a and there is no cruise. The peak is vp=ATa=DA<Vv_p = A T_a = \sqrt{DA} < V. The area of the triangle is vpTa=ATa2=Dv_p T_a = A T_a^2 = D.

In both cases the velocity starts and ends at 0. □\square

No admissible motion is faster

Lemma 2. If ss is admissible on [0,T][0, T], then v(t)≤eT(t)=min⁡(At,V,A(T−t))v(t) \le e_T(t) = \min(At, V, A(T - t)) for all t∈[0,T]t \in [0, T].

Proof. v(t)=v(0)+∫0tv′≤Atv(t) = v(0) + \int_0^t v' \le At, and v(t)=v(T)−∫tTv′≤A(T−t)v(t) = v(T) - \int_t^T v' \le A(T - t), and v(t)≤Vv(t) \le V by the velocity limit. □\square

Let E(T)=∫0TeT(t) dtE(T) = \int_0^T e_T(t)\, dt, the area of the envelope.

Lemma 3. EE is strictly increasing in TT.

Proof. Let T1<T2T_1 < T_2. For t∈[0,T1]t \in [0, T_1], eT1(t)≤eT2(t)e_{T_1}(t) \le e_{T_2}(t) because A(T1−t)<A(T2−t)A(T_1 - t) < A(T_2 - t). On (T1,T2)(T_1, T_2) the function eT2e_{T_2} is positive. So E(T2)≥E(T1)+∫T1T2eT2>E(T1)E(T_2) \ge E(T_1) + \int_{T_1}^{T_2} e_{T_2} > E(T_1). □\square

Theorem 1. Let T∗T^* be the time of line L3 or line L5. No admissible motion covers DD in a time T<T∗T < T^*.

Proof. The velocity of the profile of Lemma 1 is exactly eT∗e_{T^*}. In the first case this is clear from the shape. In the second case AtA t and A(T∗−t)A(T^* - t) are both at most AT∗/2=DA<VA T^*/2 = \sqrt{DA} < V where they are the minimum, so the term VV never acts. So E(T∗)=DE(T^*) = D by Lemma 1. If an admissible motion covered DD in time T<T∗T < T^*, then by Lemma 2 and Lemma 3, D=∫0Tv≤E(T)<E(T∗)=DD = \int_0^T v \le E(T) < E(T^*) = D, a contradiction. □\square

The proof uses rest at both ends and one axis. With nonzero end velocities, or with several axes that share one path, the envelope is different and the profile of lines L1 to L5 is in general not the fastest.

A longer prescribed time

Lemma 4. Let T≥T∗T \ge T^*. Then Ta=(T−T2−4D/A)/2T_a = (T - \sqrt{T^2 - 4D/A})/2 gives a trapezoid with acceleration AA that covers DD in exactly TT with peak velocity at most VV.

Proof. A trapezoid with ramp time Ta≤T/2T_a \le T/2 and slope AA has peak ATaA T_a and area ATa(T−Ta)A T_a (T - T_a). The equation ATa(T−Ta)=DA T_a (T - T_a) = D is Ta2−TTa+D/A=0T_a^2 - T T_a + D/A = 0. Its discriminant T2−4D/AT^2 - 4D/A is not negative because T≥T∗≥2D/AT \ge T^* \ge 2\sqrt{D/A}, and the given root is the smaller one, so Ta≤T/2T_a \le T/2. The smaller root decreases as TT grows. At T=T∗T = T^* it is the ramp time of Lemma 1 (in the first case V/AV/A solves the equation and is at most T∗/2T^*/2), whose peak is at most VV. So for T≥T∗T \ge T^* the peak ATaA T_a is at most VV. □\square

Complexity

In the real RAM with a square root, lines L1 to L6 take Θ(1)\Theta(1) operations and lines L7 to L9 take Θ(1)\Theta(1) per sample. Synchronizing nn axes costs Θ(n)\Theta(n) time and space. This is why the profile is used in controllers with cycle times of a millisecond or less.

Properties

  • Time-optimal. A theorem, for one axis, rest to rest, under velocity and acceleration limits.
  • Two shapes. Trapezoid if D≥V2/AD \ge V^2/A, triangle otherwise. The time is D/V+V/AD/V + V/A or 2D/A2\sqrt{D/A}, a continuous function of DD.
  • Velocity continuous, acceleration not. The acceleration takes the values AA, 00 and −A-A and jumps between them, so the jerk is unbounded at the switching times. This excites vibration in elastic machines.
  • Symmetric. The deceleration phase mirrors the acceleration phase.
  • Several axes. Stretching every axis to the slowest one gives the least common time for the separate limits ∣qk′∣≤Vk|q_k'| \le V_k, ∣qk′′∣≤Ak|q_k''| \le A_k, because no axis can be faster than alone. It does not handle limits that couple the axes, such as a limit on the speed of the tool along its path, and the axes then do not move along a straight line in joint space unless their profiles are scaled copies of each other.

Variants and improvements

  • Double S. A jerk limit JJ replaces each jump of the acceleration by a ramp: the double-S velocity profile, with up to seven phases.
  • Nonzero end velocities. From an arbitrary current state, the minimum-time motion can overshoot or have the opposite sign of acceleration first; this is the job of online trajectory generation (Type II in the terms of Kroger and Wahl).
  • Along a path. The same "accelerate as hard as you may, as late as you may brake" idea along a curved path, with limits that depend on the position, gives time-optimal path parameterization.
  • Cam laws. In cam design the same profile is the constant acceleration law, one of the cam follower motion laws.
  • Via points. In the robotics form "linear segments with parabolic blends", straight segments in each joint are joined by parabolic blends. The blends round the corners, so the joint passes near the via points but in general not through them.

When to use it

Use the trapezoid for point-to-point moves of motors and slides that must be fast and simple, where the drives can absorb the jumps of the acceleration: pick and place, axis jogging, conveyor indexing, and as the default move of many motion controllers. Use the triangle formula for short moves; do not cap a short move at VV if it cannot reach it. Use the double-S profile when vibration matters, and a cubic or a quintic when the duration is fixed in advance and the limits are loose.

Pitfalls

  • Forgetting the triangle case. Using T=D/V+V/AT = D/V + V/A for D<V2/AD < V^2/A gives a profile that never reaches the cruise and does not cover DD.
  • Rounding at the switch times. In floating point, sample at tt near TaT_a or T−TaT - T_a with care: test intervals as lines L7 to L9 do, and clamp the last sample to (D,0,0)(D, 0, 0).
  • Nonzero start velocity. The formulas are for rest to rest. Starting a new trapezoid from a moving state with these formulas causes a jump of the velocity.
  • Different limits in each direction. Some drives brake harder than they accelerate. Then the two ramps have different times, and the formulas change.
  • Jerk. The jump of the acceleration is a real force jump. On light or elastic machines it causes ringing at the end of the move.

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.

trapezoidal_velocity_profile.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/trapezoidal-velocity-profile/. The authors are listed in prov/E287FS.jsonl.
"""Trapezoidal velocity profile: rest-to-rest motion of one axis.

trapezoid(D, V, A) returns (Ta, vp, T): the time of the acceleration ramp,
the peak velocity and the total time of the fastest motion over the
distance D > 0 with |velocity| <= V and |acceleration| <= A. When
D < V^2 / A the profile is a triangle and vp < V.

trapezoid_sample(D, Ta, vp, T, t) returns (s, s', s'') at time t.
trapezoid_fixed_time(D, A, T) returns the ramp time of a profile that
covers D in the longer time T, with the same acceleration A. It is used to
make several axes end at the same time.
"""

import math


def trapezoid(D, V, A):
    """Return (Ta, vp, T) of the minimum time rest-to-rest profile."""
    if D <= 0 or V <= 0 or A <= 0:
        raise ValueError("D, V and A must be positive")
    if D * A >= V * V:  # @line L1
        Ta = V / A  # @line L2
        vp = V
        T = D / V + V / A  # @line L3
    else:
        Ta = math.sqrt(D / A)  # @line L4
        vp = A * Ta
        T = 2 * Ta  # @line L5
    return Ta, vp, T  # @line L6


def trapezoid_sample(D, Ta, vp, T, t):
    """Return (s, s', s'') of the profile at time t in [0, T]."""
    A = vp / Ta
    if t <= 0:
        return 0 * D, 0 * D, 0 * D
    if t < Ta:  # @line L7
        return A * t * t / 2, A * t, A
    if t <= T - Ta:  # @line L8
        return vp * (t - Ta / 2), vp, 0 * D
    if t < T:  # @line L9
        r = T - t
        return D - A * r * r / 2, A * r, -A
    return D, 0 * D, 0 * D


def trapezoid_fixed_time(D, A, T):
    """Ramp time Ta of the profile with acceleration A that covers D in exactly T.

    It solves D = A Ta (T - Ta) for the smaller root. A solution exists if and
    only if T >= 2 sqrt(D / A).
    """
    disc = T * T - 4 * D / A
    if disc < 0:
        raise ValueError("T is shorter than the minimum time 2 sqrt(D / A)")
    return (T - math.sqrt(disc)) / 2


def move(q0, q1, V, A):
    """Signed version: a function t -> (q, q', q'') from q0 to q1, and the time T."""
    D = abs(q1 - q0)
    if D == 0:
        return (lambda t: (q0, 0.0, 0.0)), 0.0
    sign = 1 if q1 > q0 else -1
    Ta, vp, T = trapezoid(D, V, A)

    def f(t):
        s, ds, dds = trapezoid_sample(D, Ta, vp, T, t)
        return q0 + sign * s, sign * ds, sign * dds

    return f, T
test_trapezoidal_velocity_profile.py 94 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/trapezoidal-velocity-profile/. The authors are listed in prov/E287FS.jsonl.
"""Tests: check values, end conditions, limits on a grid, and minimum time by the envelope bound."""

import random
from fractions import Fraction as F

from trapezoidal_velocity_profile import move, trapezoid, trapezoid_fixed_time, trapezoid_sample


def envelope_distance(T, V, A, steps=4000):
    """Largest distance any rest-to-rest motion can cover in time T.

    Every admissible velocity satisfies v(t) <= min(A t, V, A (T - t)), so
    the integral of this envelope bounds the distance. Midpoint rule on a
    piecewise linear function with at most three kinks: error below
    A T^2 / steps^2.
    """
    h = T / steps
    return sum(min(A * (k + 0.5) * h, V, A * (T - (k + 0.5) * h)) for k in range(steps)) * h


def test_check_value_exact():
    Ta, vp, T = trapezoid(F(1), F(1), F(2))
    assert (Ta, vp, T) == (F(1, 2), 1, F(3, 2))
    assert trapezoid_sample(F(1), Ta, vp, T, T) == (1, 0, 0)
    assert trapezoid_sample(F(1), Ta, vp, T, Ta)[0] == F(1, 4)
    assert trapezoid_sample(F(1), Ta, vp, T, T - Ta)[0] == F(3, 4)


def test_triangle_case():
    Ta, vp, T = trapezoid(0.18, 1.0, 2.0)
    assert abs(Ta - 0.3) < 1e-12 and abs(vp - 0.6) < 1e-12 and abs(T - 0.6) < 1e-12
    # The boundary case D = V^2 / A is a triangle that just reaches V.
    Ta, vp, T = trapezoid(F(1, 2), F(1), F(2))
    assert (Ta, vp, T) == (F(1, 2), 1, 1)


def test_limits_and_ends_on_grid():
    rng = random.Random(5)
    for _ in range(200):
        D, V, A = rng.uniform(0.01, 3), rng.uniform(0.1, 2), rng.uniform(0.1, 5)
        Ta, vp, T = trapezoid(D, V, A)
        assert vp <= V + 1e-12
        prev = 0.0
        for k in range(201):
            s, ds, dds = trapezoid_sample(D, Ta, vp, T, T * k / 200)
            assert -1e-12 <= ds <= V + 1e-12 and abs(dds) <= A + 1e-12
            assert s >= prev - 1e-12
            prev = s
        s, ds, _ = trapezoid_sample(D, Ta, vp, T, T)
        assert abs(s - D) < 1e-12 and ds == 0
        # Position is continuous at the two switch times.
        for ts in (Ta, T - Ta):
            lo = trapezoid_sample(D, Ta, vp, T, ts - 1e-9)[0]
            hi = trapezoid_sample(D, Ta, vp, T, ts + 1e-9)[0]
            assert abs(lo - hi) < 1e-8


def test_minimum_time():
    rng = random.Random(6)
    for _ in range(40):
        D, V, A = rng.uniform(0.05, 3), rng.uniform(0.2, 2), rng.uniform(0.2, 5)
        T = trapezoid(D, V, A)[2]
        # The profile reaches the envelope bound at T ...
        assert abs(envelope_distance(T, V, A) - D) < 1e-5 * max(1.0, D)
        # ... and a profile 0.1 % faster would have to beat the bound.
        assert envelope_distance(0.999 * T, V, A) < D


def test_fixed_time_synchronization():
    # Axis 1 is the slowest; axis 2 is stretched to end at the same time.
    T1 = trapezoid(1.0, 1.0, 2.0)[2]
    Ta2 = trapezoid_fixed_time(0.4, 2.0, T1)
    vp2 = 2.0 * Ta2
    s, ds, _ = trapezoid_sample(0.4, Ta2, vp2, T1, T1)
    assert abs(s - 0.4) < 1e-12 and ds == 0
    assert abs(trapezoid_sample(0.4, Ta2, vp2, T1, T1 / 2)[0] - 0.2) < 1e-12
    try:
        trapezoid_fixed_time(1.0, 2.0, 1.0)
    except ValueError:
        pass
    else:
        raise AssertionError("T below 2 sqrt(D / A) must fail")


def test_signed_move():
    f, T = move(2.0, 1.0, 1.0, 2.0)
    assert abs(T - 1.5) < 1e-12
    q, dq, _ = f(T)
    assert abs(q - 1.0) < 1e-12 and dq == 0
    assert f(0.25)[1] < 0
    g, T0 = move(1.0, 1.0, 1.0, 2.0)
    assert T0 == 0.0 and g(0.0)[0] == 1.0

History

The profile is the bang-bang solution of the minimum-time problem for a double integrator with a bound on the input, extended by a cruise phase at the velocity bound; this is a classical result of optimal control (see bang-bang control). It became the default motion of point-to-point motor controllers and of the first robot controllers, and textbooks present it as "linear segments with parabolic blends". Biagiotti and Melchiorri (2008) treat it in detail, with its synchronized multi-axis versions.

References

  1. Luigi Biagiotti and Claudio Melchiorri, Trajectory Planning for Automatic Machines and Robots, Springer, 2008, Section 3.2 (trajectory with constant acceleration, the trapezoidal velocity profile), with Section 3.2.3 on synchronizing several axes
  2. Kevin M. Lynch and Frank C. Park, Modern Robotics, Mechanics, Planning, and Control, Cambridge University Press, 2017, Chapter 9, Section 9.2.2 (time scaling a straight-line path)
  3. Bruno Siciliano, Lorenzo Sciavicco, Luigi Villani and Giuseppe Oriolo, Robotics, Modelling, Planning and Control, Springer, 2009, the chapter on trajectory planning (joint space trajectories)

Where this leads

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