Algorithm Search⌘K

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.

Time
Θ(d m³) worst
Space
Θ(m²) extra
Where
d = the number of coordinates; m = the number of segments
Properties
deterministicexactofflinenot randomized
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 w0,…,wmw_0, \dots, w_m of one coordinate and segment durations T1,…,Tm>0T_1, \dots, T_m > 0. Output: polynomials p1,…,pmp_1, \dots, p_m of degree at most 7, with pip_i defined on [0,Ti][0, T_i] in local time, that minimize

f=∑i=1m∫0Ti(pi(4)(t))2 dtf = \sum_{i=1}^m \int_0^{T_i} \big(p_i^{(4)}(t)\big)^2\, dt

subject to pi(0)=wi−1p_i(0) = w_{i-1} and pi(Ti)=wip_i(T_i) = w_i; zero first, second and third derivatives at the start of p1p_1 and the end of pmp_m; and pi(k)(Ti)=pi+1(k)(0)p_i^{(k)}(T_i) = p_{i+1}^{(k)}(0) for k=1,2,3k = 1, 2, 3 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 ci∈R8c_i \in \mathbb R^8 for the coefficients of pip_i and c=(c1,…,cm)c = (c_1, \dots, c_m). Then f=cTQcf = c^{\mathsf T} Q c with QQ block diagonal, and the constraints are Ac=bAc = b with 5m+35m + 3 rows.

  1. MIN-SNAP(w0..wm, T1..Tm)
  2. 1for each segment i = 1..m
  3. 2put 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
  4. 3for each segment i: add the rows pi(0) = w(i-1) and pi(Ti) = wi
  5. 4for k = 1, 2, 3: add the rows p1^(k)(0) = 0 and pm^(k)(Tm) = 0
  6. 5for each inner waypoint i and k = 1, 2, 3: add the row pi^(k)(Ti) - p(i+1)^(k)(0) = 0
  7. 6solve [2Q Aᵀ; A 0] (c, λ) = (0, b) ▷ the KKT system
  8. 7return c split into the m segments

Lines L1 and L2 build the cost: the integral of the product of the fourth derivatives of trt^r and tst^s. 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 (p,p′,p′′,p′′′)(p, p', p'', p''') 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 00 to 11 in time 11, the constraints fix all eight coefficients, and

p(t)=35t4−84t5+70t6−20t7,p(t) = 35t^4 - 84t^5 + 70t^6 - 20t^7,

with cost 100800100800 and peak velocity p′(1/2)=35/16=2.1875p'(1/2) = 35/16 = 2.1875. For a distance DD and a time TT the cost is 100800 D2/T7100800\, D^2/T^7.

Out and back. Waypoints 0,1,00, 1, 0 with T1=T2=1T_1 = T_2 = 1 s. The solution is

p1(t)=14t4−1265t5+775t6−165t7,p2(t)=1−215t2+7t4−7t6+165t7.p_1(t) = 14t^4 - \tfrac{126}{5}t^5 + \tfrac{77}{5}t^6 - \tfrac{16}{5}t^7, \qquad p_2(t) = 1 - \tfrac{21}{5}t^2 + 7t^4 - 7t^6 + \tfrac{16}{5}t^7.

At the inner waypoint the velocity is 00 and the jerk is 00, by symmetry, the acceleration is −42/5-42/5, and the snap is 168168 from both sides. The cost is 3225632256. Stopping at the waypoint with two one-segment moves would cost 2⋅100800=2016002 \cdot 100800 = 201600, more than six times as much. These numbers are exact, computed by the code with fractions.

Durations matter. With T1=1T_1 = 1 and T2=2T_2 = 2 instead, the velocity at the inner waypoint is 7/47/4, not 00, and the cost drops to about 43064306. 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 QQ is positive definite on the null space of AA. 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 m≥1m \ge 1 segments with durations T1,…,Tm>0T_1, \dots, T_m > 0 and waypoints w0,…,wmw_0, \dots, w_m of one coordinate. Segment ii is a polynomial pip_i of degree at most 7 in local time t∈[0,Ti]t \in [0, T_i], with coefficient vector ci∈R8c_i \in \mathbb R^8, and c=(c1,…,cm)∈R8mc = (c_1, \dots, c_m) \in \mathbb R^{8m}. The cost is

f(c)=∑i=1m∫0Tipi(4)(t)2 dt=cTQc,f(c) = \sum_{i=1}^m \int_0^{T_i} p_i^{(4)}(t)^2\, dt = c^{\mathsf T} Q c,

with QQ block diagonal (lines L1 and L2). Lines L3 to L5 collect the linear constraints Ac=bAc = b: pi(0)=wi−1p_i(0) = w_{i-1} and pi(Ti)=wip_i(T_i) = w_i; p1(k)(0)=0p_1^{(k)}(0) = 0 and pm(k)(Tm)=0p_m^{(k)}(T_m) = 0 for k=1,2,3k = 1, 2, 3; and pi(k)(Ti)=pi+1(k)(0)p_i^{(k)}(T_i) = p_{i+1}^{(k)}(0) for i<mi < m and k=1,2,3k = 1, 2, 3. That is 2m+6+3(m−1)=5m+32m + 6 + 3(m - 1) = 5m + 3 rows. The proof is in exact arithmetic.

Hermite data

Lemma 1. For T>0T > 0, the map from the 8 coefficients of a polynomial of degree at most 7 to the values (p,p′,p′′,p′′′)(p, p', p'', p''') at 00 and at TT is a bijection.

Proof. It is a linear map between spaces of dimension 8. If all 8 values are zero, then 00 and TT are roots of multiplicity at least 4, so t4(t−T)4t^4 (t - T)^4, of degree 8, divides pp, and p=0p = 0. So the map is injective, hence bijective. □\square

So a piecewise polynomial that meets all the constraints is the same thing as a choice of knot data (p,p′,p′′,p′′′)(p, p', p'', p''') 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 1,2,31, 2, 3 at the m−1m - 1 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. AA has full row rank.

Proof. Let bb be any right-hand side. Choose knot data as follows: positions and end derivatives as bb prescribes, any values for the derivatives at the right end of segment i<mi < m, and the left end values of segment i+1i + 1 equal to those minus the prescribed difference. Lemma 1 builds segments with this data, and they satisfy Ac=bAc = b. So AA maps onto R5m+3\mathbb R^{5m+3}. □\square

Lemma 3. If Ac=0Ac = 0 and cTQc=0c^{\mathsf T} Q c = 0, then c=0c = 0.

Proof. cTQc=0c^{\mathsf T} Q c = 0 means pi(4)=0p_i^{(4)} = 0 on each segment, so each pip_i is a cubic. A cubic is fixed by (p,p′,p′′,p′′′)(p, p', p'', p''') at its left end. Ac=0Ac = 0 gives p1(0)=0p_1(0) = 0 and p1′(0)=p1′′(0)=p1′′′(0)=0p_1'(0) = p_1''(0) = p_1'''(0) = 0, so p1=0p_1 = 0. If pi=0p_i = 0, then pi+1(0)=0p_{i+1}(0) = 0 by the position row and pi+1(k)(0)=pi(k)(Ti)=0p_{i+1}^{(k)}(0) = p_i^{(k)}(T_i) = 0 for k=1,2,3k = 1, 2, 3 by the continuity rows, so pi+1=0p_{i+1} = 0. □\square

Theorem 1. The matrix K=(2QATA0)K = \begin{pmatrix} 2Q & A^{\mathsf T} \\ A & 0 \end{pmatrix} of line L6 is nonsingular. Its solution (c∗,λ)(c^*, \lambda) gives the unique minimizer c∗c^* of ff subject to Ac=bAc = b.

Proof. Suppose K(x,y)=0K (x, y) = 0, so 2Qx+ATy=02Qx + A^{\mathsf T} y = 0 and Ax=0Ax = 0. Then 2xTQx=−xTATy=−(Ax)Ty=02x^{\mathsf T} Q x = -x^{\mathsf T} A^{\mathsf T} y = -(Ax)^{\mathsf T} y = 0. QQ is positive semidefinite (it is a sum of integrals of squares), so xTQx=0x^{\mathsf T} Q x = 0, and Lemma 3 gives x=0x = 0. Then ATy=0A^{\mathsf T} y = 0, and Lemma 2 gives y=0y = 0. So KK is nonsingular.

Let cc be feasible and d=c−c∗d = c - c^*, so Ad=0Ad = 0. Then

f(c)=f(c∗)+2dTQc∗+dTQd=f(c∗)−dTATλ+dTQd=f(c∗)+dTQd,f(c) = f(c^*) + 2 d^{\mathsf T} Q c^* + d^{\mathsf T} Q d = f(c^*) - d^{\mathsf T} A^{\mathsf T} \lambda + d^{\mathsf T} Q d = f(c^*) + d^{\mathsf T} Q d,

because 2Qc∗=−ATλ2Qc^* = -A^{\mathsf T}\lambda and Ad=0Ad = 0. So f(c)≥f(c∗)f(c) \ge f(c^*), and by Lemma 3 equality holds only for d=0d = 0. □\square

The free-derivative method gives the same answer

min_snap_free_derivatives writes ff 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 c∗c^*. 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 H4H^4 on the segments and meet the constraints, not only over polynomials of degree 7.

Proof. Let η\eta be a variation: on each segment a function with square-integrable fourth derivative, zero at every waypoint, with η′,η′′,η′′′\eta', \eta'', \eta''' zero at both outer ends and continuous at inner waypoints. Write x∗x^* for the optimum and Δr(k)\Delta_r(k) for the jump x∗(r)(tk+)−x∗(r)(tk−)x^{*(r)}(t_k^+) - x^{*(r)}(t_k^-) at inner waypoint kk. Integrating by parts four times on each segment and using x∗(8)=0x^{*(8)} = 0 and η=0\eta = 0 at the waypoints,

∑i∫0Tix∗(4)η(4)=∑k=1m−1(−Δ4(k) η′′′(tk)+Δ5(k) η′′(tk)−Δ6(k) η′(tk)).\sum_i \int_0^{T_i} x^{*(4)} \eta^{(4)} = \sum_{k=1}^{m-1} \big( -\Delta_4(k)\, \eta'''(t_k) + \Delta_5(k)\, \eta''(t_k) - \Delta_6(k)\, \eta'(t_k) \big).

The outer end terms vanish because η′,η′′,η′′′\eta', \eta'', \eta''' are zero there. Take η\eta to be a piecewise polynomial of degree 7 built by Lemma 1 from any values of η′,η′′,η′′′\eta', \eta'', \eta''' at the inner waypoints. It is a feasible direction, so by Theorem 1 f(c∗+εη)f(c^* + \varepsilon \eta) has its minimum at ε=0\varepsilon = 0, and the left side is zero. Since the values at the waypoints are arbitrary, every jump Δ4,Δ5,Δ6\Delta_4, \Delta_5, \Delta_6 is zero. Then the left side is zero for every variation η\eta, so the cost of x∗+ηx^* + \eta is the cost of x∗x^* plus the cost of η\eta, as in Theorem 1. □\square

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 8m+5m+3=13m+38m + 5m + 3 = 13m + 3 unknowns. Dense Gaussian elimination, as in the code, costs Θ(m3)\Theta(m^3) time and Θ(m2)\Theta(m^2) space per coordinate, so Θ(dm3)\Theta(dm^3) for dd 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 Θ(m)\Theta(m) time. With inequality constraints, a quadratic programming solver is needed, and its cost depends on the solver.

Properties

  • Smooth. The optimum is C6C^6 at the inner waypoints (a theorem), although only C3C^3 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 kk divides the cost by k7k^7 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 tt 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.

minimum_snap_trajectory.pyI0RawGitHub
# 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

  1. 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)
  2. 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.

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
  • at least three sources
  • a scene preset for the example