Algorithmadvanced
Minimum-snap trajectory
Also called Mellinger-Kumar minimum snap.
Piecewise polynomials through waypoints that minimize the integral of squared fourth derivative, found by a quadratic program.
- Solves
- Trajectory generation
- Time
- Θ(d m³) worst
- Space
- Θ(m²) extra
- Where
- d = the number of coordinates; m = the number of segments
- Model
- Real RAM
- Properties
- deterministicexactofflinenot randomized
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Daniel Mellinger, Vijay Kumar, 2011
A minimum-snap trajectory passes through a list of waypoints at given times and makes the integral of the squared fourth derivative of the position, the snap, as small as possible. Each segment between two waypoints is a polynomial of degree 7 in each coordinate. The waypoints fix the positions, the start and the end are at rest, and the first three derivatives are continuous at the inner waypoints. Everything else is chosen by the optimization. The cost is quadratic and the constraints are linear, so the coefficients come from a quadratic program, and with only equality constraints they come from one linear system. Mellinger and Kumar (2011) introduced the method for quadrotors. A quadrotor is differentially flat: its motor inputs are functions of the position, the yaw and their derivatives, and the moments that the motors must produce depend on the fourth derivative of the position. So a trajectory with small snap is one the vehicle can fly smoothly. The method is the four-derivative relative of the minimum-jerk trajectory.
In plain words
A drone must fly through a list of points, at given times, without stopping at each one. Its motors cannot change their speed instantly, so the flight path must be very smooth. Connect the points by curves, one curve per gap. Each curve is a polynomial with eight numbers per direction. Choose all those numbers at once so that the curves meet at the points without corners or kinks, and so that a measure of roughness, the snap, added up over the whole flight, is as small as possible. That choice is a standard optimization problem with a quadratic cost and straight-line rules, and a linear solver finds the exact answer.
The problem
Input: waypoints of one coordinate and segment durations . Output: polynomials of degree at most 7, with defined on in local time, that minimize
subject to and ; zero first, second and third derivatives at the start of and the end of ; and for at each inner waypoint. Several coordinates are independent problems with the same durations. Mellinger and Kumar also add inequality constraints, such as corridors around the straight segments; then the problem is a general quadratic program.
The algorithm
Write for the coefficients of and . Then with block diagonal, and the constraints are with rows.
MIN-SNAP(w0..wm, T1..Tm)- 1
for each segment i = 1..m - 2
put Qi into the diagonal block i of Q, with Qi[r][s] = r(r-1)(r-2)(r-3) s(s-1)(s-2)(s-3) Ti^(r+s-7) / (r+s-7) for r, s ≥ 4, else 0 - 3
for each segment i: add the rows pi(0) = w(i-1) and pi(Ti) = wi - 4
for k = 1, 2, 3: add the rows p1^(k)(0) = 0 and pm^(k)(Tm) = 0 - 5
for each inner waypoint i and k = 1, 2, 3: add the row pi^(k)(Ti) - p(i+1)^(k)(0) = 0 - 6
solve [2Q Aᵀ; A 0] (c, λ) = (0, b) ▷ the KKT system - 7
return c split into the m segments
Lines L1 and L2 build the cost: the integral of the product of the fourth derivatives of and . Lines L3 to L5 build the constraints. Line L6 solves the KKT conditions of the equality-constrained problem, with one Lagrange multiplier per constraint, by Gaussian elimination. The code also has a second method, after Richter, Bry and Roy: write each segment through the values at its two ends, fix the known ones, and minimize over the free derivatives at the inner waypoints, an unconstrained quadratic. Both give the same exact answer.
Example
One segment. From to in time , the constraints fix all eight coefficients, and
with cost and peak velocity . For a distance and a time the cost is .
Out and back. Waypoints with s. The solution is
At the inner waypoint the velocity is and the jerk is , by symmetry, the acceleration is , and the snap is from both sides. The cost is . Stopping at the waypoint with two one-segment moves would cost , more than six times as much. These numbers are exact, computed by the code with fractions.
Durations matter. With and instead, the velocity at the inner waypoint is , not , and the cost drops to about . The durations are inputs, and the result depends on them strongly.
Correctness
Theorem: the KKT matrix of line L6 is nonsingular, and its solution is the unique minimizer. The proof has three steps. A polynomial of degree 7 is fixed by its value and first three derivatives at both ends of its interval, a Hermite interpolation fact; this shows that the constraint matrix has full row rank. If a feasible direction had zero cost, every segment would be a cubic, and the zero data at the start would force all of them to zero, so is positive definite on the null space of . The standard argument then gives the unique minimum. A further theorem: although only the first three derivatives are forced to be continuous, the optimum also has continuous derivatives of orders 4, 5 and 6 at the inner waypoints, and it is optimal among all piecewise smooth functions with square-integrable fourth derivative, not only among polynomials of degree 7.
Proof: The KKT system of minimum snap is nonsingular, its solution is the unique minimizer, and the optimum is C6 at inner waypointsfull
We use the notation of the page. There are segments with durations and waypoints of one coordinate. Segment is a polynomial of degree at most 7 in local time , with coefficient vector , and . The cost is
with block diagonal (lines L1 and L2). Lines L3 to L5 collect the linear constraints : and ; and for ; and for and . That is rows. The proof is in exact arithmetic.
Hermite data
Lemma 1. For , the map from the 8 coefficients of a polynomial of degree at most 7 to the values at and at is a bijection.
Proof. It is a linear map between spaces of dimension 8. If all 8 values are zero, then and are roots of multiplicity at least 4, so , of degree 8, divides , and . So the map is injective, hence bijective.
So a piecewise polynomial that meets all the constraints is the same thing as a choice of knot data at each waypoint with the positions and the end derivatives fixed: build each segment from the data at its two ends by Lemma 1. The free values are the derivatives at the inner waypoints. Function _hermite_inverse computes the inverse map of Lemma 1, and min_snap_free_derivatives uses this parameterization.
The KKT system is nonsingular
Lemma 2. has full row rank.
Proof. Let be any right-hand side. Choose knot data as follows: positions and end derivatives as prescribes, any values for the derivatives at the right end of segment , and the left end values of segment equal to those minus the prescribed difference. Lemma 1 builds segments with this data, and they satisfy . So maps onto .
Lemma 3. If and , then .
Proof. means on each segment, so each is a cubic. A cubic is fixed by at its left end. gives and , so . If , then by the position row and for by the continuity rows, so .
Theorem 1. The matrix of line L6 is nonsingular. Its solution gives the unique minimizer of subject to .
Proof. Suppose , so and . Then . is positive semidefinite (it is a sum of integrals of squares), so , and Lemma 3 gives . Then , and Lemma 2 gives . So is nonsingular.
Let be feasible and , so . Then
because and . So , and by Lemma 3 equality holds only for .
The free-derivative method gives the same answer
min_snap_free_derivatives writes as a quadratic form in the knot data, fixes the known values, and solves the linear system that sets the gradient with respect to the free values to zero. By Lemma 1 the knot data parameterize exactly the feasible set, so this minimizes the same strictly convex function (Theorem 1) over the same set. The reduced matrix is positive definite by Lemma 3, so its system has one solution, and it is . The tests check that both methods return the same exact coefficients.
The optimum is smooth up to order 6
Theorem 2. At every inner waypoint, the derivatives of order 4, 5 and 6 of the optimum are continuous. Moreover the optimum minimizes the cost over all functions that are piecewise of class on the segments and meet the constraints, not only over polynomials of degree 7.
Proof. Let be a variation: on each segment a function with square-integrable fourth derivative, zero at every waypoint, with zero at both outer ends and continuous at inner waypoints. Write for the optimum and for the jump at inner waypoint . Integrating by parts four times on each segment and using and at the waypoints,
The outer end terms vanish because are zero there. Take to be a piecewise polynomial of degree 7 built by Lemma 1 from any values of at the inner waypoints. It is a feasible direction, so by Theorem 1 has its minimum at , and the left side is zero. Since the values at the waypoints are arbitrary, every jump is zero. Then the left side is zero for every variation , so the cost of is the cost of plus the cost of , as in Theorem 1.
The seventh derivative is not continuous in general; the tests show a jump. The code uses a local time per segment, which shifts the variable but does not change the derivatives at the waypoints.
Complexity
The KKT system has unknowns. Dense Gaussian elimination, as in the code, costs time and space per coordinate, so for coordinates; the matrix is the same for all coordinates, so one factorization can serve all of them. The matrix is banded when the unknowns are ordered by segment, and a banded solver takes time. With inequality constraints, a quadratic programming solver is needed, and its cost depends on the solver.
Properties
- Smooth. The optimum is at the inner waypoints (a theorem), although only is imposed. The seventh derivative jumps.
- Linear in the waypoints. For fixed durations, the coefficients are a linear function of the waypoints, so the same matrix serves every coordinate and every set of waypoints.
- No limits by default. The equality-constrained problem ignores velocity, acceleration and obstacle limits between waypoints. The path can bulge out between waypoints.
- Scaling in time. Stretching all durations by a factor divides the cost by and keeps the shape of the path.
- Durations are inputs. The cost decreases without bound as the durations grow, so they cannot be chosen by the same cost alone; Mellinger and Kumar fix the total time and redistribute it among segments by gradient descent.
Variants and improvements
- Inequality constraints. Corridor constraints at sample points keep the path near the straight segments (Mellinger and Kumar). This turns the linear system into a quadratic program.
- Free derivatives. Richter, Bry and Roy solve for the free derivatives at the waypoints in an unconstrained form, which is better conditioned for many segments, and they take the waypoints from a rapidly-exploring random tree run on a simpler model. They add segments where the polynomial path hits an obstacle.
- Other orders. Minimizing the third derivative gives the minimum-jerk trajectory through waypoints, with quintic segments. Yaw is often planned with a lower order cost.
- Other bases. The same problem can be written with B-splines or Bernstein polynomials, which give convex hull bounds useful for safety constraints.
- General optimization. With dynamics, limits and obstacles in one problem, use trajectory optimization.
When to use it
Use minimum snap for quadrotors and other differentially flat vehicles, where smooth position trajectories become feasible inputs, and as a smoothing step after a geometric planner has found waypoints. Check the velocity, acceleration and thrust limits after solving, and lengthen the durations if they are violated. Use a time-optimal method if the vehicle must fly at its limits.
Pitfalls
- Ill-conditioning. Coefficients in powers of give badly conditioned matrices for long segments or many segments. Scale time per segment, use the free-derivative form, or use exact arithmetic for small problems as the tests do.
- Bad durations. A short segment next to a long one makes the path overshoot. Estimate durations from distances and a nominal speed, then refine.
- Collisions between waypoints. Waypoints that are free do not make the polynomials free. Check the result and add waypoints or constraints.
- Too few constraints at the ends. If the end derivatives are left free, the problem changes; leaving out the zero-derivative rows at the ends gives a different, natural boundary optimum.
- Mixing local and global time. Each segment uses its own local time; the continuity rows of line L5 compare the end of one segment with the start of the next.
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/minimum-snap-trajectory/. The authors are listed in prov/GASDKD.jsonl.
"""Minimum-snap trajectory of one coordinate through waypoints at fixed times.
min_snap(w, T) takes waypoints w[0..m] and segment durations T[1..m] (a list
of length m), and returns m polynomials of degree 7, one per segment, in
local time t in [0, T_i]. The sum of the integrals of the squared fourth
derivative is minimal among all trajectories that pass through the
waypoints at the given times, start and end at rest (velocity,
acceleration and jerk zero), and have continuous derivatives up to order 3.
It solves the equality constrained quadratic program of Mellinger and
Kumar (2011) through its KKT system.
min_snap_free_derivatives(w, T) solves the same problem by the method of
Richter, Bry and Roy: the unknowns are the free derivatives at the inner
waypoints. Both functions are exact when the inputs are Fraction values.
Several coordinates (x, y, z, yaw) are independent: call once per coordinate.
"""
import math
DEG = 7 # degree of each polynomial
R = 4 # order of the derivative in the cost (snap)
NC = 3 # derivatives 1..NC fixed at the ends and continuous at inner waypoints
def solve(m, b):
"""Solve m x = b by Gauss-Jordan elimination with a nonzero pivot (exact for Fraction)."""
n = len(m)
a = [list(m[i]) + [b[i]] for i in range(n)]
for c in range(n):
p = max(range(c, n), key=lambda r: abs(a[r][c]))
if a[p][c] == 0:
raise ValueError("singular system")
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 deriv_row(t, d):
"""Row of the d-th derivative of (1, t, ..., t^DEG) at t."""
return [math.perm(k, d) * t ** (k - d) if k >= d else 0 * t for k in range(DEG + 1)]
def cost_matrix(T):
"""Q with c^T Q c = integral over [0, T] of the squared R-th derivative."""
n = DEG + 1
q = [[0 * T for _ in range(n)] for _ in range(n)]
for i in range(R, n):
for j in range(R, n):
e = i + j - 2 * R + 1
q[i][j] = math.perm(i, R) * math.perm(j, R) * T ** e / e
return q
def min_snap(w, T):
"""Coefficient lists (one per segment) of the minimum-snap trajectory, by the KKT system."""
m = len(T)
if len(w) != m + 1 or m < 1:
raise ValueError("need m + 1 waypoints for m segments")
zero = 0 * T[0]
n = (DEG + 1) * m
big_q = [[zero] * n for _ in range(n)]
for i in range(m): # @line L1
qi = cost_matrix(T[i])
for r in range(DEG + 1): # @line L2
for c in range(DEG + 1):
big_q[8 * i + r][8 * i + c] = qi[r][c]
rows, rhs = [], []
def put(seg, vec):
row = [zero] * n
for k, x in enumerate(vec):
row[8 * seg + k] += x
return row
for i in range(m): # @line L3
rows.append(put(i, deriv_row(zero, 0)))
rhs.append(w[i])
rows.append(put(i, deriv_row(T[i], 0)))
rhs.append(w[i + 1])
for d in range(1, NC + 1): # @line L4
rows.append(put(0, deriv_row(zero, d)))
rhs.append(zero)
rows.append(put(m - 1, deriv_row(T[m - 1], d)))
rhs.append(zero)
for i in range(m - 1): # @line L5
for d in range(1, NC + 1):
a = put(i, deriv_row(T[i], d))
b = put(i + 1, deriv_row(zero, d))
rows.append([x - y for x, y in zip(a, b)])
rhs.append(zero)
k = len(rows)
kkt = [[2 * big_q[i][j] for j in range(n)] + [rows[r][i] for r in range(k)] for i in range(n)] # @line L6
kkt += [rows[r] + [zero] * k for r in range(k)]
sol = solve(kkt, [zero] * n + rhs)
return [sol[8 * i: 8 * i + 8] for i in range(m)] # @line L7
def _hermite_inverse(T):
"""Inverse of the map from the 8 coefficients to (p, p', p'', p''') at 0 and at T."""
m = [deriv_row(0 * T, d) for d in range(4)] + [deriv_row(T, d) for d in range(4)]
cols = [solve(m, [(1 if i == j else 0) * (T / T) for i in range(8)]) for j in range(8)]
return [[cols[j][i] for j in range(8)] for i in range(8)]
def min_snap_free_derivatives(w, T):
"""The same trajectory, by optimizing over the free derivatives at the inner waypoints."""
m = len(T)
zero = 0 * T[0]
nv = 4 * (m + 1) # knot k holds (p, p', p'', p''') at variable 4k .. 4k + 3
g = [[zero] * nv for _ in range(nv)]
hinv = []
for i in range(m):
minv = _hermite_inverse(T[i])
hinv.append(minv)
q = cost_matrix(T[i])
qm = [[sum(q[r][s] * minv[s][c] for s in range(8)) for c in range(8)] for r in range(8)]
h = [[sum(minv[s][r] * qm[s][c] for s in range(8)) for c in range(8)] for r in range(8)]
idx = list(range(4 * i, 4 * i + 8))
for r in range(8):
for c in range(8):
g[idx[r]][idx[c]] += h[r][c]
fixed = {4 * k: w[k] for k in range(m + 1)}
for d in range(1, 4):
fixed[d] = zero
fixed[4 * m + d] = zero
free = [v for v in range(nv) if v not in fixed]
x = dict(fixed)
if free:
a = [[g[r][c] for c in free] for r in free]
b = [-sum(g[r][c] * val for c, val in fixed.items()) for r in free]
for v, val in zip(free, solve(a, b)):
x[v] = val
out = []
for i in range(m):
d = [x[v] for v in range(4 * i, 4 * i + 8)]
out.append([sum(hinv[i][r][c] * d[c] for c in range(8)) for r in range(8)])
return out
def poly_eval(c, t, d=0):
"""Value at t of the d-th derivative of the polynomial with coefficients c."""
return sum(x * y for x, y in zip(c, deriv_row(t, d)))
def snap_cost(coeffs, T):
"""Total cost: the sum over segments of c^T Q c."""
total = 0 * T[0]
for c, t in zip(coeffs, T):
q = cost_matrix(t)
total += sum(c[i] * q[i][j] * c[j] for i in range(8) for j in range(8))
return total
test_minimum_snap_trajectory.py 84 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minimum-snap-trajectory/. The authors are listed in prov/GASDKD.jsonl.
"""Tests: constraints, the one-segment closed form, the two methods agree, natural continuity, and perturbations."""
import random
from fractions import Fraction as F
from minimum_snap_trajectory import _hermite_inverse, min_snap, min_snap_free_derivatives, poly_eval, snap_cost
def test_one_segment_closed_form():
# Rest to rest from 0 to 1 in time 1: s = 35 t^4 - 84 t^5 + 70 t^6 - 20 t^7.
c = min_snap([F(0), F(1)], [F(1)])[0]
assert c == [0, 0, 0, 0, 35, -84, 70, -20]
assert snap_cost([c], [F(1)]) == 100800
assert poly_eval(c, F(1, 2), 1) == F(35, 16)
def test_constraints_exact():
w = [F(0), F(2), F(-1), F(3)]
T = [F(1), F(2), F(1)]
cs = min_snap(w, T)
for i, c in enumerate(cs):
assert poly_eval(c, F(0)) == w[i] and poly_eval(c, T[i]) == w[i + 1]
for d in (1, 2, 3):
assert poly_eval(cs[0], F(0), d) == 0 and poly_eval(cs[-1], T[-1], d) == 0
def test_natural_continuity_up_to_six():
# Only derivatives 1 to 3 are forced to be continuous; the optimum makes 4, 5 and 6 continuous too.
w = [F(0), F(1), F(3), F(2)]
T = [F(1), F(1), F(2)]
cs = min_snap(w, T)
for i in range(len(T) - 1):
for d in range(1, 7):
assert poly_eval(cs[i], T[i], d) == poly_eval(cs[i + 1], F(0), d)
# The seventh derivative jumps in general.
assert any(poly_eval(cs[i], T[i], 7) != poly_eval(cs[i + 1], F(0), 7) for i in range(2))
def test_two_methods_agree():
rng = random.Random(41)
for m in (1, 2, 3):
w = [F(rng.randint(-5, 5)) for _ in range(m + 1)]
T = [F(rng.randint(1, 3), rng.randint(1, 2)) for _ in range(m)]
assert min_snap(w, T) == min_snap_free_derivatives(w, T)
def test_perturbations_cost_more():
# Change the free derivatives at the inner waypoints: the cost grows.
w = [F(0), F(1), F(-1)]
T = [F(1), F(1)]
best = min_snap(w, T)
base = snap_cost(best, T)
rng = random.Random(42)
for _ in range(5):
dv, da, dj = (F(rng.randint(-3, 3), 4) for _ in range(3))
if not (dv or da or dj):
continue
# A feasible trajectory: Hermite segments with shifted inner derivatives.
knot = [poly_eval(best[0], T[0], d) for d in range(4)]
knot = [knot[0], knot[1] + dv, knot[2] + da, knot[3] + dj]
segs = []
ends = [[w[0], F(0), F(0), F(0)], knot, [w[2], F(0), F(0), F(0)]]
for i in range(2):
minv = _hermite_inverse(T[i])
d = ends[i] + ends[i + 1]
segs.append([sum(minv[r][c] * d[c] for c in range(8)) for r in range(8)])
assert snap_cost(segs, T) > base
def test_float_inputs():
cs = min_snap([0.0, 1.0, 0.5], [1.0, 1.5])
assert abs(poly_eval(cs[1], 1.5) - 0.5) < 1e-9
assert abs(poly_eval(cs[0], 1.0, 2) - poly_eval(cs[1], 0.0, 2)) < 1e-9
def test_bad_input():
try:
min_snap([F(0)], [F(1)])
except ValueError:
pass
else:
raise AssertionError("wrong number of waypoints must fail")
History
Polynomial splines that minimize an integrated squared derivative are an old idea of approximation theory: the natural cubic spline minimizes the integrated squared second derivative among all interpolants. Mellinger and Kumar (2011) chose the fourth derivative for quadrotors because of their differential flatness, set the problem as a quadratic program with corridor constraints, optimized the segment times, and flew aggressive trajectories with real vehicles. Richter, Bry and Roy (ISRR 2013, published 2016) gave the unconstrained formulation in the free derivatives and combined it with a sampling-based planner for flight in cluttered indoor spaces.
References
- Daniel Mellinger and Vijay Kumar, Minimum snap trajectory generation and control for quadrotors, IEEE International Conference on Robotics and Automation, 2011, 2520-2525, the whole paper (the snap cost, the quadratic program over the polynomial coefficients, corridor constraints and the choice of segment times)
- Charles Richter, Adam Bry and Nicholas Roy, Polynomial trajectory planning for aggressive quadrotor flight in dense indoor environments, Robotics Research (ISRR 2013), Springer Tracts in Advanced Robotics, 2016, 649-666, the whole paper (the unconstrained form in the free derivatives at the waypoints, and waypoints from a sampling-based planner)
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 GASDKD Edit this page History Report an error Markdown