Algorithmintro
Cubic polynomial trajectory
Also called third-order polynomial time scaling.
Fits a cubic in time to given start and end positions and velocities, the simplest smooth point-to-point motion.
- Solves
- Trajectory generation
- Time
- Θ(n m) worst
- Space
- Θ(n m) extra
- Where
- m = the number of segments between via points; n = the number of joints
- Model
- Real RAM
- Properties
- deterministicexactofflinenot randomized
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Chun Shin Lin, Po Rong Chang, J. Y. S. Luh, 1983
A cubic polynomial trajectory moves one coordinate, such as a robot joint angle or one axis of a machine, from a start position to an end position in a given time along a polynomial of degree 3 in time. A cubic has four coefficients, and the four conditions are the position and the velocity at both ends. So the start and the end velocities can be set, for example to zero for a move from rest to rest, and the velocity is continuous when several moves are joined. The acceleration is not controlled: it is generally not zero at the ends, so it jumps when the motion starts and stops. The quintic polynomial trajectory adds the two end accelerations for this reason. The cubic is also the time scaling that is most often used to run along a fixed path, and among all motions with the same four end conditions it is the one with the least integral of squared acceleration.
In plain words
Suppose a joint is at 0 degrees and must be at 90 degrees two seconds later, and it must be at rest at both moments. A straight line in time would start and stop with a sudden jump in speed, which no motor can do. A cubic curve starts flat, rises, and ends flat. Its slope, the speed, starts at zero, grows to a peak in the middle, and falls to zero at the end. Four numbers describe the curve, and there are four wishes: where to start, how fast to start, where to end and how fast to end. So there is exactly one cubic that meets all four, and a short formula gives it. The price is that the push from the motor jumps from zero to a fixed value at the start, because the method has no number left to control it.
The problem
Input: a start position and velocity , an end position and velocity , and a duration . Output: the coefficients of
with , , and . For an arm with joints, each joint gets its own cubic with the same . For a move along a fixed path, the same formula with , and zero end velocities gives a time scaling , and the motion is (Lynch and Park, Section 9.2.2).
The algorithm
Let .
CUBIC(q0, v0, q1, v1, T) ▷ T > 0, h = q1 - q0- 1
a0 ← q0 - 2
a1 ← v0 - 3
a2 ← (3h - (2 v0 + v1) T) / T² - 4
a3 ← (-2h + (v0 + v1) T) / T³ - 5
return (a0, a1, a2, a3) CUBIC-EVAL(a, t)- 6
q ← a0 + t (a1 + t (a2 + t a3)) ▷ Horner's rule - 7
q' ← a1 + t (2 a2 + 3 a3 t) - 8
q'' ← 2 a2 + 6 a3 t - 9
return (q, q', q'')
Lines L1 and L2 read the start conditions off the polynomial at . Lines L3 and L4 solve the two remaining equations and , a linear system. Lines L6 to L8 evaluate the position, the velocity and the acceleration.
For via points at times with chosen velocities , call CUBIC once per interval with , in local time (Lynch and Park, Section 9.3). The velocities at the inner via points are a design choice: a common rule of thumb takes the mean of the slopes of the two neighboring intervals, or zero where the slope changes sign.
Example
The standard time scaling. With , , and , lines L3 and L4 give and :
The peak velocity is , at the middle, and the acceleration is at and at . For a distance and a time , these become and . A joint that turns rad in s reaches rad/s at s, and needs rad/s² at the start and the end.
Nonzero start velocity. Take m, m/s, m, and s, so .
- L3: .
- L4: .
So . Check: and . The velocity has its peak m/s at s, where m. The acceleration goes from m/s² at the start to m/s² at the end.
Via points. Through m at s with velocities m/s, the first cubic is and the second is in local time. Both have position 1 and velocity 1 at the via point, but the acceleration jumps there from to m/s².
Correctness
Putting and into the polynomial and its derivative and using the formulas of lines L3 and L4 gives back the four end conditions. No other polynomial of degree at most 3 meets them: the difference of two would have double roots at and , so it would be divisible by , of degree 4, and so zero.
The cubic is also optimal for a natural cost. Among all motions with the same four end conditions, it minimizes , and it is the only minimizer. If , two integrations by parts show that the cross term is zero, because and vanish at the ends and . So the cost of is the cost of plus the cost of . The proof gives every step. For the rest-to-rest move the minimum is .
Proof: The cubic meets the four end conditions, is the only cubic that does, and minimizes the integral of squared accelerationfull
We use the notation of the page. The input is and a duration , and . Lines L1 to L4 set
and the trajectory is on . The proof is in exact arithmetic.
The end conditions hold
Lemma 1. , , and .
Proof. and at once. Next,
so . Also
so .
Uniqueness
Lemma 2. No other polynomial of degree at most 3 meets the four conditions.
Proof. Let be the difference of two such polynomials. Then has degree at most 3 and . So and are double roots, and divides . This product has degree 4, so .
So the four conditions form a linear system in with a nonsingular matrix when , and Lemma 1 gives its solution.
Minimum squared acceleration
Theorem 1. Among all functions on with a square integrable second derivative and the same four end conditions, the cubic has the smallest value of , and it is the only minimizer.
Proof. Write . Then , and
Integrate the middle term by parts twice:
The two brackets are zero because and vanish at both ends, and because is a cubic. So . Equality needs almost everywhere, so is linear, and a linear function with is zero.
Via points
Theorem 2. For via points at times with chosen velocities , the piecewise cubic built by calling the method on each interval is continuous with a continuous first derivative.
Proof. By Lemma 1, the piece on ends with position and velocity , and the piece on starts with the same position and velocity.
The acceleration is not continuous at the via points in general. It is continuous only for the special choice of the inner velocities that a cubic spline makes.
Complexity
In the real RAM, one call of CUBIC costs a fixed number of operations, about 15, so time and space. One evaluation costs about 10 multiplications. An arm with joints and segments needs time and stores coefficients. This is the cheapest smooth trajectory, which is why controllers that replan every cycle often use it.
Properties
- Velocity continuous, acceleration not. Joined cubics are at via points. The acceleration jumps there, and it jumps from 0 at the start and the end of a rest-to-rest move.
- Minimum squared acceleration. A theorem: the cubic is the unique minimizer of for its four end conditions, so it uses the least "effort" in this sense.
- Symmetric rest-to-rest profile. For , with , and the path rises without overshoot, since .
- Linear in the data. The coefficients are linear in for a fixed . Scaling the time by divides the velocity by and the acceleration by .
- Overshoot with large end velocities. If or is large compared with , the cubic can leave the interval between and .
Variants and improvements
- Quintic. Add the end accelerations as two more conditions: the quintic polynomial trajectory. The rest-to-rest quintic is the minimum-jerk trajectory.
- Cubic splines. If only the via positions are given, choose the inner velocities so that the acceleration is also continuous. This gives a tridiagonal system, the cubic spline; Lin, Chang and Luh used it for joint trajectories. With the velocities given, the method on this page is the cubic Hermite spline.
- Linear segments with blends. For long moves, a constant velocity middle part with short blends is faster under the same limits: the trapezoidal velocity profile.
- Choosing T. For a rest-to-rest move under the limits and , the smallest feasible time is , because the peaks are and .
When to use it
Use a cubic for short point-to-point moves of a joint where the velocities at the ends matter and the acceleration jump is acceptable, for example in teaching, in simulation, and in simple controllers. Use it as the time scaling of a straight-line move in task space. If the robot is stiff or the load is heavy, the acceleration jump excites vibration; use a quintic or a double-S profile. If the move must be as fast as possible under velocity and acceleration limits, use a trapezoidal profile.
Pitfalls
- Jerk is infinite at the start and the end. The acceleration jumps from 0 to . Do not use a cubic where a smooth start matters.
- Different T per joint. If each joint gets its own duration, the joints do not finish together and the end-effector path is not straight. Use one for all joints, set by the slowest one.
- T too small. The formulas work for any , but the peaks grow as and . Check the limits after you choose .
- Wrong via velocities. Choosing the inner velocities badly makes the motion overshoot between via points.
- Local time. Each segment is written in its own local time . Mixing local and global time gives wrong values at every segment but the first.
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/cubic-polynomial-trajectory/. The authors are listed in prov/HEFVQT.jsonl.
"""Cubic polynomial trajectory of one joint.
cubic_coeffs(q0, v0, q1, v1, T) returns (a0, a1, a2, a3) of
q(t) = a0 + a1 t + a2 t^2 + a3 t^3 on [0, T], with q(0) = q0, q'(0) = v0,
q(T) = q1 and q'(T) = v1. The arithmetic is exact when the inputs are
fractions.Fraction values, and it works with float values too.
cubic_via(points, velocities, times) joins one cubic per interval, so
that the trajectory passes through each point with the given velocity.
"""
def cubic_coeffs(q0, v0, q1, v1, T):
"""Coefficients of the cubic that meets the four end conditions."""
if T <= 0:
raise ValueError("T must be positive")
h = q1 - q0
a0 = q0 # @line L1
a1 = v0 # @line L2
a2 = (3 * h - (2 * v0 + v1) * T) / (T * T) # @line L3
a3 = (-2 * h + (v0 + v1) * T) / (T * T * T) # @line L4
return (a0, a1, a2, a3) # @line L5
def cubic_eval(a, t):
"""Return (q, q', q'') of the cubic with coefficients a at time t."""
a0, a1, a2, a3 = a
q = a0 + t * (a1 + t * (a2 + t * a3)) # @line L6
dq = a1 + t * (2 * a2 + 3 * a3 * t) # @line L7
ddq = 2 * a2 + 6 * a3 * t # @line L8
return q, dq, ddq # @line L9
def cubic_via(points, velocities, times):
"""One cubic per interval [times[k], times[k+1]].
Returns a list of (t_start, coefficients) in local time t - t_start.
The velocity at each point is given, so the result has a continuous
velocity. Its acceleration jumps at the via points in general.
"""
if not (len(points) == len(velocities) == len(times)) or len(points) < 2:
raise ValueError("need at least two points, with one velocity and one time each")
out = []
for k in range(len(points) - 1):
T = times[k + 1] - times[k]
out.append((times[k], cubic_coeffs(points[k], velocities[k], points[k + 1], velocities[k + 1], T)))
return out
def via_eval(segments, t):
"""Evaluate a via point trajectory from cubic_via at time t."""
idx = 0
for k, (t0, _) in enumerate(segments):
if t >= t0:
idx = k
t0, a = segments[idx]
return cubic_eval(a, t - t0)
test_cubic_polynomial_trajectory.py 121 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cubic-polynomial-trajectory/. The authors are listed in prov/HEFVQT.jsonl.
"""Tests: exact end conditions, the check values, a second method, and the minimum acceleration property."""
import random
from fractions import Fraction as F
from cubic_polynomial_trajectory import cubic_coeffs, cubic_eval, cubic_via, via_eval
def solve(m, b):
"""Gauss-Jordan elimination in exact arithmetic (the second method)."""
n = len(m)
a = [[F(x) for x in m[i]] + [F(b[i])] for i in range(n)]
for c in range(n):
p = next(r for r in range(c, n) if a[r][c] != 0)
a[c], a[p] = a[p], a[c]
for r in range(n):
if r != c and a[r][c] != 0:
f = a[r][c] / a[c][c]
a[r] = [x - f * y for x, y in zip(a[r], a[c])]
return [a[i][n] / a[i][i] for i in range(n)]
def poly_mul(p, q):
out = [F(0)] * (len(p) + len(q) - 1)
for i, x in enumerate(p):
for j, y in enumerate(q):
out[i + j] += x * y
return out
def poly_der(p):
return [i * p[i] for i in range(1, len(p))] or [F(0)]
def integral_sq(p, T):
sq = poly_mul(p, p)
return sum(c * T ** (i + 1) / (i + 1) for i, c in enumerate(sq))
def test_end_conditions_exact():
rng = random.Random(1)
for _ in range(200):
q0, v0, q1, v1 = (F(rng.randint(-50, 50), rng.randint(1, 9)) for _ in range(4))
T = F(rng.randint(1, 40), rng.randint(1, 9))
a = cubic_coeffs(q0, v0, q1, v1, T)
s, ds, _ = cubic_eval(a, F(0))
e, de, _ = cubic_eval(a, T)
assert (s, ds, e, de) == (q0, v0, q1, v1)
def test_check_values():
a = cubic_coeffs(F(0), F(0), F(1), F(0), F(1))
assert a == (0, 0, 3, -2)
assert cubic_eval(a, F(1, 2))[1] == F(3, 2)
assert cubic_eval(a, F(0))[2] == 6
assert cubic_eval(a, F(1))[2] == -6
# The velocity is a parabola, so its maximum on a grid is at t = 1/2.
grid = [cubic_eval(a, F(k, 1000))[1] for k in range(1001)]
assert max(grid) == F(3, 2)
# Scaling: distance D in time T gives peak velocity 1.5 D / T and end acceleration 6 D / T^2.
a = cubic_coeffs(F(1), F(0), F(4), F(0), F(2))
assert cubic_eval(a, F(1))[1] == F(3, 2) * 3 / 2
assert cubic_eval(a, F(0))[2] == 6 * F(3) / 4
def test_against_linear_solve():
rng = random.Random(2)
for _ in range(100):
q0, v0, q1, v1 = (F(rng.randint(-20, 20)) for _ in range(4))
T = F(rng.randint(1, 10), rng.randint(1, 4))
m = [[1, 0, 0, 0], [0, 1, 0, 0], [1, T, T * T, T ** 3], [0, 1, 2 * T, 3 * T * T]]
assert list(cubic_coeffs(q0, v0, q1, v1, T)) == solve(m, [q0, v0, q1, v1])
def test_minimum_squared_acceleration():
# Any other C^1 path with the same end positions and velocities is q + eta,
# with eta = t^2 (T - t)^2 r(t). Its cost exceeds the cubic's cost by the cost of eta.
rng = random.Random(3)
for _ in range(40):
T = F(rng.randint(1, 5))
a = list(cubic_coeffs(F(rng.randint(-5, 5)), F(rng.randint(-5, 5)), F(rng.randint(-5, 5)), F(rng.randint(-5, 5)), T))
base = integral_sq(poly_der(poly_der(a)), T)
bump = poly_mul(poly_mul([F(0), F(0), F(1)], poly_mul([T, F(-1)], [T, F(-1)])), [F(rng.randint(-3, 3)) for _ in range(3)])
if all(c == 0 for c in bump):
continue
other = [x + y for x, y in zip(a + [F(0)] * (len(bump) - len(a)), bump)]
cost = integral_sq(poly_der(poly_der(other)), T)
assert cost == base + integral_sq(poly_der(poly_der(bump)), T)
assert cost > base
def test_float_inputs():
a = cubic_coeffs(0.0, 0.0, 1.0, 0.0, 2.0)
q, dq, _ = cubic_eval(a, 2.0)
assert abs(q - 1.0) < 1e-12 and abs(dq) < 1e-12
def test_via_points_continuity():
pts = [F(0), F(2), F(1), F(3)]
vel = [F(0), F(1), F(-1, 2), F(0)]
ts = [F(0), F(1), F(3), F(4)]
segs = cubic_via(pts, vel, ts)
for k in range(1, 3):
left = cubic_eval(segs[k - 1][1], ts[k] - ts[k - 1])
right = cubic_eval(segs[k][1], F(0))
assert left[0] == right[0] == pts[k]
assert left[1] == right[1] == vel[k]
assert via_eval(segs, F(4))[0] == 3
assert via_eval(segs, F(0))[0] == 0
def test_bad_input():
for bad in (0, -1):
try:
cubic_coeffs(0, 0, 1, 0, bad)
except ValueError:
pass
else:
raise AssertionError("T <= 0 must fail")
History
Polynomials in time were the standard way to plan joint trajectories in the first robot controllers, and the textbooks of the 1980s present the cubic for point-to-point moves and via points. Lin, Chang and Luh (1983) built joint trajectories from cubic splines through knots and gave an algorithm that chooses the time intervals between knots to minimize the total travel time under limits on the joint velocities, accelerations and jerks. Lynch and Park (2017) present the cubic as the third-order polynomial time scaling and as the building block of polynomial via point trajectories.
References
- 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) and Section 9.3 (polynomial via point trajectories)
- Luigi Biagiotti and Claudio Melchiorri, Trajectory Planning for Automatic Machines and Robots, Springer, 2008, Chapter 2 (analytic expressions of elementary trajectories, polynomial trajectories)
- Bruno Siciliano, Lorenzo Sciavicco, Luigi Villani and Giuseppe Oriolo, Robotics, Modelling, Planning and Control, Springer, 2009, the chapter on trajectory planning (joint space trajectories, point-to-point motion)
- Chun-Shin Lin, Po-Rong Chang and J. Y. S. Luh, Formulation and optimization of cubic polynomial joint trajectories for industrial robots, IEEE Transactions on Automatic Control 28(12), 1983, 1066-1074, the whole paper (cubic splines through joint knots, and the choice of the knot times)
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.
| 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 HEFVQT Edit this page History Report an error Markdown