Trajectory optimization: turning a motion plan into a nonlinear program
轨迹优化
How direct methods transcribe an optimal control problem into a finite optimisation: single and multiple shooting, direct transcription, trapezoidal and Hermite–Simpson collocation, sparsity and conditioning, adjoint gradients, iLQR, initial guesses and error checks, and why the result needs feedback, checked on Kelly's block-move problem and an unstable toy plant.
trajectory-optimizationOne good motion from one starting point
Trajectory optimization finds the best motion for a robot or vehicle from one known starting point. It writes the motion as numbers over time and lets an optimiser adjust them until the cost is lowest and the physics and every limit are obeyed. A classic textbook example moves a block one unit of distance in one second with the least effort.
A robot arm must swing a load from rest at one position to rest at another in one second, using as little effort as possible. There is no need for a controller that works from every possible state; one good motion from this starting point is enough. Trajectory optimization computes exactly that. It returns a state trajectory (positions and velocities over time) and a control trajectory (forces or torques over time). Together they minimise a cost while obeying the dynamics and every constraint. Kelly defines it as finding the best trajectory, typically by choosing the controls as functions of time. Definition
Compare this with feedback design, which solves for a controller on the whole state space. Doing that on a mesh, for example with dynamic programming (working backwards to find the best action at every state), scales badly beyond about four or five state dimensions. A trajectory needs a parameterisation in time only, so the number of unknowns grows linearly rather than exponentially with the state dimension. The drawback is that the answer is valid only from one initial condition. Chapter introduction
The same trade-off appears from the other side. Dynamic programming yields a policy for every state, and in basic forms the global optimum, but scales exponentially. Trajectory optimization returns an open-loop solution, a fixed plan in time that does not react to where the system actually is. It must be combined with a stabilising controller, and it may fail to converge or find only a local optimum. Open loop vs closed loop
This article states the problem and explains how direct methods turn it into a finite nonlinear program (an optimisation with finitely many unknowns and nonlinear equations). It compares the main transcriptions, the different ways of making that conversion. It then lists the practical issues that decide whether a solver succeeds. A synthetic program then checks the claims on Kelly’s block-move problem and on an unstable toy plant. The continuous-time optimality conditions are covered in optimal control, and the stabilising feedback in LQR and model predictive control.
The problem and the two families of methods
This section states the problem and sorts the solution methods into families. A general single-phase problem has a boundary term and an integral term, the Bolza form:
In words: choose the start and end times, the state path and the control path that make a final-state cost plus an accumulated running cost as small as possible, while obeying the dynamics and the path limits. J is the boundary (Mayer) term, w the integrand (Lagrange term), f the dynamics and h the path constraints. Kelly’s full statement adds boundary constraints, bounds on state and control, and bounds on the initial and final times and states. Problem (1.1)–(1.9)
Rawlings, Mayne and Diehl group numerical methods for continuous-time optimal control into three families. Methods based on the Hamilton–Jacobi–Bellman equation are practical only for small state dimensions, say fewer than five, or for unconstrained linear-quadratic problems. Indirect methods “first optimise, then discretise”: they derive the optimality conditions and solve the resulting boundary-value problem. Direct methods “first discretise, then optimise”, and are the ones most widely used in MPC. Three families Kelly adds that indirect methods tend to be more accurate, with more reliable error estimates, but have smaller regions of convergence, need guesses for the adjoint variables and require deriving the optimality conditions analytically; a common strategy is to solve with a direct method first and use the result to start an indirect one. Direct vs indirect
A direct method converts the problem into a finite nonlinear program (NLP); the conversion is called transcription. If all constraints are linear and the objective linear or quadratic, the result is an LP or QP, which is much easier to solve. Transcription The KKT conditions of that program are those of constrained optimisation and KKT; NLP solvers use Newton-type steps such as SQP or interior-point iterations, built on Newton’s method.
Linear systems. For x[n+1] = Ax[n] + Bu[n], direct transcription keeps both x[·] and u[·] as decision variables and imposes the dynamics as linear equality constraints. With linear inequalities and a linear or quadratic objective, the problem is a convex LP or QP that can be solved to global optimality at large scale; Tedrake notes such problems are now commonly solved online in high-rate feedback. Direct transcription Direct shooting eliminates the states by forward simulation,
and remains convex with fewer decision variables and constraints. In words: every state is fixed by the start state and the inputs before it. Direct shooting Tedrake gives three reasons to still prefer transcription. Shooting involves Aⁿ for large n, which he likens to the tail wagging the dog and says reflects a real property of the problem, not only of the formulation. State constraints are easier to write when states are variables. Constraint evaluations can run in parallel. Transcription also produces a banded sparsity pattern, the same structure that Riccati recursions exploit. Computational considerations
Shooting, multiple shooting and collocation
This section compares the main ways of turning the problem into a finite optimisation. Direct single shooting parameterises the control, often as piecewise constant on N intervals. It obtains the states by numerical simulation and optimises over the control parameters only (possibly plus the initial state). It is a fully sequential approach, and its NLP is usually dense. Single shooting Kelly notes that shooting gives small, dense NLPs, struggles with path constraints because intermediate states are not variables, and has highly nonlinear relations between variables and constraints. Shooting
Direct multiple shooting also keeps the states s_i at the interval boundaries as variables and links the intervals by continuity constraints,
In words: the simulated end of each interval must match the start of the next one. Here x̃_i is the simulated trajectory on interval i from state s_i with control parameters q_i. It has (N + 1)n + Nm variables instead of n + Nm, but the two problems are equivalent. The integrations decouple and can run in parallel, state guesses can initialise the solver, and Newton-type iterations often contract faster for nonlinear and unstable systems. Multiple shooting Kelly says multiple shooting tends to be much more robust than single shooting. Multiple shooting Rawlings, Mayne and Diehl’s rule of thumb: the sequential approach suits solvers that cannot exploit sparsity and systems that are stable; the simultaneous approach suits unstable nonlinear systems, problems with state constraints, and systems needing implicit simulation. Rule of thumb
Direct collocation represents state and control by their values at collocation (knot) points and enforces the dynamics through a quadrature rule between neighbouring points. Trapezoidal collocation uses
In words: the change of state over a segment equals the segment length times the average of the slopes at its two ends, and the cost integral is approximated the same way. Here h_k is the segment length and f_k the dynamics at knot k. Constraints are imposed at the knots; after solving, the control is interpolated as a linear spline and the state as a quadratic spline. Trapezoidal collocation Hermite–Simpson collocation uses Simpson’s rule with a midpoint state:
In words: the state change uses a weighted average of the slopes at the start, middle and end of the segment, with the middle counted four times, and the midpoint state comes from a cubic fit. Hermite–Simpson is more accurate than trapezoidal collocation, its state is a cubic Hermite spline with a continuous first derivative, and it can be written in a “compressed” form (midpoint state eliminated as above) or a “separated” form (midpoint as a variable). Hermite–Simpson Tedrake describes direct collocation, citing Hargraves and Paris (1987), as a linear control and cubic state spline whose only decision variables are the knot values, with the dynamics imposed at the segment midpoints; this gives third-order-accurate integration with effectively two dynamics evaluations per segment. Direct collocation That description matches the Hermite–Simpson scheme in Kelly’s naming; the identification is ours, and the 1987 paper was not read.
Rawlings, Mayne and Diehl view direct collocation as an implicit Runge–Kutta method imposed as equality constraints, typically with low stage order (two or three) and large N (100 or 1000, for example), giving a large but sparse NLP that is very efficient when the sparsity is exploited. Pseudospectral methods instead use one interval with a high-order polynomial, gaining accuracy for smooth trajectories but losing sparsity. Collocation and pseudospectral Orthogonal collocation places the points at roots of orthogonal polynomials (Chebyshev or Legendre) and can converge exponentially in polynomial order for sufficiently smooth functions. Orthogonal collocation
Gradients and iLQR. For direct shooting without state constraints, the gradient of the cost with respect to every input costs one forward simulation and one backward adjoint recursion:
In words: λ carries the cost’s sensitivity backward one step at a time, and each input’s gradient combines its direct cost with that sensitivity. Tedrake notes that this is exactly backpropagation, that is, reverse-mode automatic differentiation. Adjoint gradients Iterative LQR linearises the dynamics and quadratises the cost around the current trajectory, solves a time-varying LQR problem backward, simulates forward, and repeats. It handles only unconstrained problems through its Riccati solution, so constraints are usually added as penalties or through an augmented Lagrangian. Differential dynamic programming (DDP) differs by using a second-order model of the dynamics. iLQR and DDP Kelly describes DDP as similar to direct shooting, because it also simulates the system forward before optimising. DDP Tedrake also notes that gradient-free methods such as the cross-entropy method and model-predictive path-integral control are popular for trajectory optimisation in model-based reinforcement learning, mainly because they parallelise trivially on GPUs and are somewhat robust to local minima. Zero-order optimisation
What decides whether the solver succeeds
This section lists the practical issues that most often decide whether a solver finds a usable answer. Initial guesses and local minima. NLP solvers need an initial guess and return only locally optimal solutions. Simple guesses, such as a straight line in state space from start to goal, often work; harder problems can be solved through a sequence of simplified problems, each warm-starting the next. Initialisation Tedrake adds three points. A solver’s “infeasible” report cannot be distinguished from being stuck in a local minimum. Shooting accepts a guess only for u(·), while transcription and collocation also accept one for x(·). For Acrobot and cart-pole swing-up, a straight-line state guess was enough, and necessary. Good solutions in practice Some constraints are fundamentally nonconvex, such as choosing to pass left or right of an obstacle. Nonconvex constraints
Consistent functions. Solvers such as SNOPT, IPOPT and FMINCON expect smooth, deterministic, branch-free functions. abs, min, max, variable-step integrators, iterative root finding with a variable iteration count and linear table lookup all break this; the remedies are slack variables, smoothing, fixed-step integrators and fixed iteration counts. Consistent functions
Non-unique and non-smooth optima. Non-unique optima, often with singular arcs, prevent convergence; a small regularisation such as the integral of control squared makes the solution unique. Discontinuous optimal controls, such as bang-bang solutions, are hard for polynomial splines; remedies are mesh refinement, smoothing or a multi-phase formulation. Singular arcs and bang-bang Hybrid systems such as walking robots use multi-phase or through-contact formulations. Multi-phase
Checking the answer. Collocation constraints act like implicit Runge–Kutta integration, so the solution is only as accurate as the mesh. Kelly’s error check evaluates the dynamics residual ε(t) = ẋ(t) − f(t, x(t), u(t)) along the interpolated solution: it is zero at the collocation points and nonzero between them, and its integral over each segment guides mesh refinement (hp-adaptive meshing re-solves with finer segments or higher order where the error is large). Mesh refinement and error
Which method. Kelly’s guide: shooting suits problems with accurate dynamics and simple controls, such as a spacecraft with occasional burns; multiple shooting is generally preferred over single shooting; collocation suits problems where dynamics and control need similar accuracy and the control structure is unknown, such as robot joint torques. There is no single best method. Which method is best
Block move and an unstable plant
This section checks the claims above on two small problems. The program below is original, synthetic and deterministic. Part 1 solves Kelly’s block-move problem: a unit mass with ẍ = u, starting at rest at x = 0 and ending at rest at x = 1 after one second, minimising the integral of u². Its analytic solution is
In words: move the block from rest at 0 to rest at 1 in one second with the least squared force; the best force falls linearly from 6 to −6. Block move (2.1)–(2.4) The cost J* = ∫(6 − 12t)² dt = 36 − 72 + 48 = 12 is our arithmetic. Because the constraints are linear and the objective quadratic, every transcription is an equality-constrained QP, solved exactly through its KKT linear system. The program compares single shooting (piecewise-constant u, exact integration), trapezoidal collocation, and Hermite–Simpson in compressed form with a separate midpoint control. It then replays each trapezoidal control, interpolated linearly, through the exact dynamics with an RK4 integrator whose steps align with the knots, so a piecewise-linear control is integrated exactly.
Part 2 takes an unstable plant ẍ = 25x + u (open-loop eigenvalues ±5), discretises it exactly with a zero-order hold on N = 50 intervals over a horizon T, and builds the KKT matrix of the terminal-state-constrained minimum-effort problem twice: once with shooting (inputs only) and once with direct transcription (states and inputs). It prints the largest entry of the shooting map and both condition numbers.
The first lines set OPENBLAS_NUM_THREADS=1 (unless already set) before importing numpy; this only limits the number of BLAS threads, which keeps these small solves fast, and does not change the method or the printed results.
import os
os.environ.setdefault("OPENBLAS_NUM_THREADS", "1") # small matrices: avoid thread overhead
import numpy as np
# Synthetic, deterministic illustration of direct trajectory optimization.
# Block move: x'' = u, x(0)=0, v(0)=0, x(1)=1, v(1)=0, minimise integral u^2.
# Known optimum: x*(t) = 3t^2 - 2t^3, u*(t) = 6 - 12t, cost 12.
def kkt(Hq, Aeq):
p = Aeq.shape[0]
return np.block([[Hq, Aeq.T], [Aeq, np.zeros((p, p))]])
def eq_qp(Hq, Aeq, beq):
# Solve min 0.5 z'Hz s.t. Aeq z = beq through its KKT system.
n = Hq.shape[0]
sol = np.linalg.solve(kkt(Hq, Aeq), np.concatenate([np.zeros(n), beq]))
return sol[:n]
def single_shooting(N):
# Piecewise-constant u, exact integration; states are not variables.
h = 1.0 / N
G = np.zeros((2, N))
for k in range(N):
rest = 1.0 - (k + 1) * h
G[0, k] = h * h / 2 + h * rest
G[1, k] = h
u = eq_qp(2 * h * np.eye(N), G, np.array([1.0, 0.0]))
return u, h * np.sum(u * u)
def trapezoid(N):
# Variables per knot k: x_k, v_k, u_k (index 3k, 3k+1, 3k+2).
h = 1.0 / N
nz = 3 * (N + 1)
Hq = np.zeros((nz, nz))
rows, rhs = [], []
for k in range(N):
i, j = 3 * k, 3 * (k + 1)
Hq[i + 2, i + 2] += h
Hq[j + 2, j + 2] += h
r = np.zeros(nz); r[j] = 1; r[i] = -1; r[i + 1] = -h / 2; r[j + 1] = -h / 2
rows.append(r); rhs.append(0.0)
r = np.zeros(nz); r[j + 1] = 1; r[i + 1] = -1; r[i + 2] = -h / 2; r[j + 2] = -h / 2
rows.append(r); rhs.append(0.0)
for idx, val in ((0, 0.0), (1, 0.0), (3 * N, 1.0), (3 * N + 1, 0.0)):
r = np.zeros(nz); r[idx] = 1; rows.append(r); rhs.append(val)
z = eq_qp(Hq, np.array(rows), np.array(rhs))
u = z[2::3]
cost = sum(h / 2 * (u[k] ** 2 + u[k + 1] ** 2) for k in range(N))
return u, cost
def hermite_simpson(N):
# Knot variables x_k, v_k, u_k plus a midpoint control m_k per segment.
h = 1.0 / N
nk = 3 * (N + 1)
nz = nk + N
Hq = np.zeros((nz, nz))
rows, rhs = [], []
for k in range(N):
i, j, c = 3 * k, 3 * (k + 1), nk + k
Hq[i + 2, i + 2] += h / 3
Hq[j + 2, j + 2] += h / 3
Hq[c, c] += 4 * h / 3
# v_mid = (v_k + v_k1)/2 + h/8 (u_k - u_k1)
vm = np.zeros(nz)
vm[i + 1] = 0.5; vm[j + 1] = 0.5; vm[i + 2] = h / 8; vm[j + 2] = -h / 8
r = -h / 6 * (4 * vm)
r[j] += 1; r[i] -= 1; r[i + 1] -= h / 6; r[j + 1] -= h / 6
rows.append(r); rhs.append(0.0)
r = np.zeros(nz)
r[j + 1] = 1; r[i + 1] = -1; r[i + 2] = -h / 6; r[c] = -4 * h / 6; r[j + 2] = -h / 6
rows.append(r); rhs.append(0.0)
for idx, val in ((0, 0.0), (1, 0.0), (3 * N, 1.0), (3 * N + 1, 0.0)):
r = np.zeros(nz); r[idx] = 1; rows.append(r); rhs.append(val)
z = eq_qp(Hq, np.array(rows), np.array(rhs))
u, m = z[2:nk:3], z[nk:]
cost = sum(h / 6 * (u[k] ** 2 + 4 * m[k] ** 2 + u[k + 1] ** 2) for k in range(N))
return u, m, cost
def replay(control, steps=320):
# RK4 on the true dynamics; steps align with every knot grid used here,
# so a piecewise-linear control is integrated exactly.
dt = 1.0 / steps
s = np.array([0.0, 0.0])
f = lambda t, s: np.array([s[1], control(t)])
for n in range(steps):
t = n * dt
k1 = f(t, s)
k2 = f(t + dt / 2, s + dt / 2 * k1)
k3 = f(t + dt / 2, s + dt / 2 * k2)
k4 = f(t + dt, s + dt * k3)
s = s + dt / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
return s
print("Part 1: block move, optimal cost 12")
for N in (4, 8, 16, 32):
t = np.linspace(0, 1, N + 1)
us, Js = single_shooting(N)
ut, Jt = trapezoid(N)
uh, mh, Jh = hermite_simpson(N)
err_t = np.abs(ut - (6 - 12 * t)).max()
err_h = np.abs(uh - (6 - 12 * t)).max()
end_t = replay(lambda s: np.interp(s, t, ut))
print(f" N={N:2d} shooting J={Js:.4f} trapezoid J={Jt:.4f} (max|u-u*|={err_t:.1e},"
f" replay x(1)={end_t[0]:.5f}) Hermite-Simpson J={Jh:.6f} (max|u-u*|<1e-12: {err_h < 1e-12})")
print()
print("Part 2: unstable plant x'' = 25 x + u, N = 50 intervals, KKT conditioning")
a = 5.0
for T in (1.0, 2.0, 3.0, 4.0):
N = 50
h = T / N
Ac = np.array([[0.0, 1.0], [a * a, 0.0]])
w, V = np.linalg.eig(Ac)
Ad = (V @ np.diag(np.exp(w * h)) @ np.linalg.inv(V)).real
Bd = np.linalg.solve(Ac, (Ad - np.eye(2)) @ np.array([0.0, 1.0]))
# Shooting: terminal state = Ad^N x0 + sum Ad^(N-1-k) Bd u_k.
G = np.zeros((2, N))
P = np.eye(2)
for k in range(N - 1, -1, -1):
G[:, k] = P @ Bd
P = Ad @ P
c_shoot = np.linalg.cond(kkt(2 * h * np.eye(N), G))
# Transcription: states and inputs are variables, dynamics are constraints.
nz = 2 * (N + 1) + N
Hq = np.zeros((nz, nz))
Hq[2 * (N + 1):, 2 * (N + 1):] = 2 * h * np.eye(N)
rows = []
for k in range(N):
r = np.zeros((2, nz))
r[:, 2 * (k + 1):2 * (k + 2)] = np.eye(2)
r[:, 2 * k:2 * k + 2] = -Ad
r[:, 2 * (N + 1) + k] = -Bd
rows.append(r)
E = np.zeros((4, nz)); E[0, 0] = 1; E[1, 1] = 1; E[2, 2 * N] = 1; E[3, 2 * N + 1] = 1
Aeq = np.vstack(rows + [E])
c_tran = np.linalg.cond(kkt(Hq, Aeq))
print(f" T={T:.0f}s max|entry of shooting map|={np.abs(G).max():.2e}"
f" cond(KKT) shooting={c_shoot:.2e} transcription={c_tran:.2e}")
Recorded output
Part 1: block move, optimal cost 12
N= 4 shooting J=12.8000 trapezoid J=15.0588 (max|u-u*|=7.6e-01, replay x(1)=1.05882) Hermite-Simpson J=12.000000 (max|u-u*|<1e-12: True)
N= 8 shooting J=12.1905 trapezoid J=12.7205 (max|u-u*|=4.3e-01, replay x(1)=1.01449) Hermite-Simpson J=12.000000 (max|u-u*|<1e-12: True)
N=16 shooting J=12.0471 trapezoid J=12.1814 (max|u-u*|=2.9e-01, replay x(1)=1.00372) Hermite-Simpson J=12.000000 (max|u-u*|<1e-12: True)
N=32 shooting J=12.0117 trapezoid J=12.0460 (max|u-u*|=1.7e-01, replay x(1)=1.00095) Hermite-Simpson J=12.000000 (max|u-u*|<1e-12: True)
Part 2: unstable plant x'' = 25 x + u, N = 50 intervals, KKT conditioning
T=1s max|entry of shooting map|=1.41e+00 cond(KKT) shooting=1.86e+03 transcription=8.31e+03
T=2s max|entry of shooting map|=3.99e+02 cond(KKT) shooting=3.79e+05 transcription=5.50e+03
T=3s max|entry of shooting map|=8.47e+04 cond(KKT) shooting=6.84e+07 transcription=5.02e+03
T=4s max|entry of shooting map|=1.60e+07 cond(KKT) shooting=1.17e+10 transcription=5.02e+03Convergence. All three transcriptions approach the optimum 12. Single shooting gives 12.8000, 12.1905, 12.0471 and 12.0117 for N = 4, 8, 16 and 32; these values equal 12N²/(N² − 1), an observation from the printed numbers rather than a claim from the sources. Trapezoidal collocation gives 15.0588, 12.7205, 12.1814 and 12.0460. For both, the error shrinks by roughly a factor of four each time the step halves. The largest knot error of the trapezoidal control, 7.6e-01, 4.3e-01, 2.9e-01 and 1.7e-01, falls more slowly, because the largest errors sit at or next to the end knots, which lag behind the interior.
Dynamics hold only at the knots. Replaying the trapezoidal control through the exact dynamics lands at x(1) = 1.05882 for N = 4, then 1.01449, 1.00372 and 1.00095, instead of 1. The collocated trajectory satisfies the dynamics at the collocation points, not between them; that is exactly what Kelly’s residual check measures, and why an optimised trajectory replayed open loop drifts.
Hermite–Simpson is exact here, for a special reason. Hermite–Simpson prints J = 12.000000 for every N, and its knot controls match u* to better than 10⁻¹². This is not evidence that Hermite–Simpson has no discretisation error. The true optimum has a linear control and a cubic state, which Hermite–Simpson’s quadratic control, cubic state spline and Simpson’s rule represent exactly. For general nonlinear dynamics the method has discretisation error, and the residual check and mesh refinement are still needed.
Conditioning.| T | max entry of shooting map | cond(KKT), shooting | cond(KKT), transcription |
|---|---|---|---|
| 1 s | 1.41e+00 | 1.86e+03 | 8.31e+03 |
| 2 s | 3.99e+02 | 3.79e+05 | 5.50e+03 |
| 3 s | 8.47e+04 | 6.84e+07 | 5.02e+03 |
| 4 s | 1.60e+07 | 1.17e+10 | 5.02e+03 |
The sensitivity of the final state to early inputs grows like e^(5T), and the shooting KKT condition number grows with it, from 1.86e+03 to 1.17e+10. Transcription stays between 5.02e+03 and 8.31e+03, because each constraint links only neighbouring time steps. At T = 1 s, however, shooting is the better-conditioned formulation, so the advantage is not universal; it appears as the horizon lengthens on an unstable plant, in line with the rule of thumb above. These are unscaled KKT matrices of a toy problem; real solvers scale variables and exploit structure, so the table shows a sensitivity trend, not a solver benchmark.
An open-loop answer to one question
This section explains why an optimised trajectory is not yet a controller, and what the examples do not show. A trajectory optimiser answers one question: the best motion from one initial state under one model. Replayed open loop, the trajectory can diverge from the plan. The optimisation uses coarser integration than a simulator or the real system, and solvers typically satisfy the dynamics constraints only to a tolerance such as 10⁻⁶. Tedrake recommends a feedback controller that regulates back to the trajectory, such as time-varying LQR on the linearisation along it, or MPC. Trajectory feedback The replay in Part 1 shows the same effect without any model error at all.
For nonlinear dynamics the NLP is nonconvex. The solver may return a local minimum, report infeasibility while a solution exists, or fail without a good initial guess; there is no certificate of global optimality. Problems with path constraints are much harder than those without. Path constraints
Both examples are linear, so their transcriptions are QPs solved exactly in one linear solve; they show discretisation error and conditioning, not the behaviour of an NLP solver on a nonlinear robot. The Hermite–Simpson result is special to a polynomial optimum, and the condition numbers are an unscaled trend. Kelly’s tutorial was read as the author’s 2017 PDF; the typeset SIAM Review version was not consulted, so no volume or page numbers are given here.
Exercises
These exercises test understanding, a hand calculation, a counterexample, evidence judgment and a design choice.
-
Why is a trajectory optimization result called open-loop, and what must be added before running it on a robot?
Answer: It is a single time-indexed u(t), with its x(t), computed from one initial state. Model error, disturbances, coarse integration and solver tolerance make the real state drift; even without model error, Part 1’s replay ends at x(1) = 1.05882 for trapezoidal collocation with N = 4. Feedback is needed: time-varying LQR around the trajectory, or re-solving in an MPC loop (LQR, model predictive control).
-
Block move with N = 2 (h = 0.5). (a) With trapezoidal collocation, find x₁, ν₁, the controls and the discrete cost. (b) With single shooting and piecewise-constant u, find the controls and the cost.
Answer: (a) Position constraints: x₁ − 0 = 0.25(0 + ν₁) and 1 − x₁ = 0.25(ν₁ + 0), so x₁ = 0.5 and ν₁ = 2. Velocity constraints: 2 = 0.25(u₀ + u₁) and −2 = 0.25(u₁ + u₂), so u₀ = 8 − u₁ and u₂ = −8 − u₁. The cost 0.25(u₀² + u₁²) + 0.25(u₁² + u₂²) = 0.25(128 + 4u₁²) is smallest at u₁ = 0: u = (8, 0, −8) and J = 32, against the analytic 12 and u* = (6, 0, −6). (b) Final velocity 0.5(u₀ + u₁) = 0 gives u₁ = −u₀; final position 0.375u₀ + 0.125u₁ = 0.25u₀ = 1 gives u₀ = 4, and J = 0.5(16 + 16) = 16. Both approach 12 as N grows, as Part 1 shows.
-
(a) Show that trapezoidal collocation of the block move is infeasible with N = 1. (b) “Hermite–Simpson hit J = 12 exactly at N = 4, so it has no discretisation error.” What is wrong?
Answer: (a) With one segment, x₁ − x₀ = ½·1·(ν₀ + ν₁) = 0 because both velocities are fixed at zero, while the boundary conditions demand x₁ − x₀ = 1; the constraints contradict each other and the KKT matrix is singular. (b) The exactness comes from the optimum being a cubic state with a linear control, which Hermite–Simpson represents exactly. For general nonlinear dynamics it has discretisation error, and one must check the dynamics residual ε(t) and refine the mesh.
-
Someone compares formulations by condition number at T = 1 s only and concludes that “shooting is better conditioned than transcription”. Judge the evidence.
Answer: At T = 1 s the numbers do favour shooting (1.86e+03 vs 8.31e+03). But for this unstable plant the shooting condition number grows to 1.17e+10 at T = 4 s while transcription stays at 5.02e+03. The conclusion depends on horizon and stability. One toy plant and unscaled KKT matrices are weak evidence about solver behaviour in general.
-
Plan a swing-up for an unstable underactuated robot with joint limits and an obstacle, given a decent model. Which transcription would you choose, and what else would you do?
Answer: Prefer a simultaneous method, direct collocation or multiple shooting, because the system is unstable and has state constraints. Supply a straight-line state guess, make all model functions smooth, and expect local minima and nonconvex obstacle constraints, so try several initialisations. After solving, check the dynamics residual and refine the mesh, then stabilise the trajectory with time-varying LQR or MPC. Single shooting would suit a smooth, stable system with simple controls.
Further reading
This section points to the three sources for deeper reading. Kelly’s tutorial is a practical, self-contained introduction to trapezoidal and Hermite–Simpson collocation, with sections on initialisation, mesh refinement, debugging and method choice. Kelly tutorial Tedrake’s chapter covers convex formulations for linear systems, nonconvex direct methods, gradients, iLQR and the feedback needed to execute a trajectory. Underactuated Robotics Chapter 8 of Rawlings, Mayne and Diehl treats numerical optimal control from the MPC side: single and multiple shooting, collocation, condensing and online algorithms. Numerical optimal control
Related topics: optimal control for Pontryagin’s principle and the continuous-time conditions behind indirect methods, LQR for trajectory stabilisation and iLQR’s inner step, model predictive control for re-solving the problem in a loop, differential equations for numerical integration, recursion and dynamic programming and value iteration for the policy-based alternative, robot dynamics for the dynamics f(x, u) of robots, sampling-based planners such as rapidly-exploring random trees for a geometric, global alternative, legged locomotion for multi-phase and contact-rich problems, and model-based RL for planning with learned models.
Make a prediction, then check
In the example, the unstable plant ẍ = 25x + u is solved for a terminal-constrained minimum-effort problem on 50 intervals. As T grows from 1 s to 4 s, single shooting's KKT condition number rises from 1.86e3 to 1.17e10 while direct transcription stays near 5e3. Which conclusion fits best?
Learning objectives
- State a trajectory optimization problem with dynamics, path and boundary constraints, distinguish direct from indirect methods, and say which quantities single shooting, multiple shooting and direct collocation keep as decision variables.
- Transcribe a simple problem with trapezoidal and Hermite–Simpson collocation and check discretization error, choose a transcription by stability, state constraints, sparsity and initial guesses, and explain why an open-loop trajectory needs feedback stabilization.
Prerequisites & connections
Explore related knowledge →References
- An Introduction to Trajectory Optimization: How to Do Your Own Direct Collocation (author PDF) — scoped
Matthew Kelly · 2017 - Underactuated Robotics — chapter “Trajectory Optimization” (book/trajopt.html at commit 1e1402f) — scoped
Russ Tedrake · 2024 - Model Predictive Control: Theory, Computation, and Design, 2nd ed. (fifth printing, 2024 electronic copy) — scoped
James B. Rawlings; David Q. Mayne; Moritz M. Diehl · 2017
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Claude · 2026-12-03 · Independent AI check (Claude subagent, not the author; not a human or expert review). Gemini-app style edits logged in gemini-edits-016a.json were applied to the opening sections before this check; research was done by a separate research subagent (facts.md) and the prose by a writer subagent. I first made readability (D012) edits to the intuition section and section openings in both languages, then checked the edited text. I ran example.py with the pinned interpreter (numpy 1.26.4) with OPENBLAS_NUM_THREADS unset, set to 1 and set to 4; output was identical to example.stdout.txt each time, which supports the article's statement that the setting only limits BLAS threads and does not change results. I confirmed the python block in en.mdx and zh.mdx is byte-identical to example.py and matched every quoted number. I re-derived J* = 12, the 12N²/(N²−1) pattern, the Hermite–Simpson and trapezoid formulas, and exercises 2 and 3 (trapezoid N = 2 gives J = 32, shooting N = 2 gives 16, trapezoid N = 1 is singular), and checked these with the program's own functions. I downloaded Kelly's 2017 author PDF (44 pp., created 2017-01-04) and read §1 (definition, (1.1)–(1.9), transcription, LP/QP remark), §2–4 (block move (2.4), trapezoidal and Hermite–Simpson collocation, compressed/separated forms), §5 (initialisation, mesh refinement and implicit Runge–Kutta remark, error ε(t), singular arcs, consistent functions) and §9.2–9.11. I fetched Tedrake's book/trajopt.html at commit 1e1402f and read the introduction, convex formulations, direct shooting and computational considerations, direct collocation, gradients and the adjoint equation, penalty methods, zero-order optimisation, 'Getting good solutions', local trajectory feedback and the iLQR/DDP text (checking that none of the cited passages sits inside HTML comments). From the Rawlings–Mayne–Diehl PDF (printed page = PDF page − 50) I read pp. 491–493 and 530–542. I compared zh and en section by section and checked data.json IDs against src/data/catalogue.txt. Not checked: the SIAM Review typeset version (the article gives no volume or pages), Hargraves and Paris (1987) and other cited originals, and Kelly §6–8 beyond the openings.
- The example run with the pinned interpreter matches example.stdout.txt and gives the same output for different OPENBLAS_NUM_THREADS values; both code blocks are byte-identical to example.py; every quoted number matches the output.
- Hermite–Simpson's exactness here is tied to the optimum being a linear control with a cubic state, with a note that general nonlinear dynamics still have discretisation error; the condition numbers are presented as an unscaled trend, not a solver benchmark.
- Kelly claims were checked against the 2017 author PDF and no SIAM volume or pages are given; the Tedrake trajectory-optimization chapter claims were checked at the pinned commit.
- zh and en match section by section in definitions, numbers, exercises, answers and caveats; data.json prerequisite and related IDs exist in the catalogue and the quiz answer is correct.
Source locations checked:
- An Introduction to Trajectory Optimization: How to Do Your Own Direct Collocation (author PDF) — scoped · pdftotext of MatthewKelly_IntroTrajectoryOptimization_SIAM_Review_2017.pdf (44 pp., created 2017-01-04). Read: abstract and §1.1–1.6 pp. 1–4 (definition, notation, block-move example, Bolza/Lagrange/Mayer forms, constraints (1.2)–(1.9), direct vs indirect, transcription, NLP (1.10), LP/QP remark); §2 pp. 4–6 (problem (2.1)–(2.3), analytic solution (2.4), trapezoidal collocation (2.5)–(2.8), initialization (2.9)–(2.12), QP remark, interpolation); §3 pp. 6–8 ((3.1)–(3.10), path constraints harder, quadratic state spline); §4 pp. 8–10 (Simpson quadrature, (4.3)–(4.4), compressed vs separated, interpolants (4.9)–(4.13)); §5 pp. 10–14 (initialization, mesh refinement, hp-adaptive, error ε(t) and η_k, debugging, singular arcs, regularization, non-smooth controls, consistent functions, slack variables, simulators); §6 opening pp. 14–15 (cart-pole dynamics and objective only); §8 opening p. 22 (minimum-work bang-bang); §9 and §10 pp. 27–31 (trajectory vs parameter optimization, open- vs closed-loop, curse of dimensionality, discrete-time systems, indirect methods, single and multiple shooting, orthogonal collocation, DDP, multi-phase, through-contact, which method is best, Tables 1–2); Appendix B opening p. 31. NOT read: §6 beyond the dynamics, §7 (five-link biped), §8 body, Appendices C–F, the electronic supplement, and every cited reference (Betts, Hargraves & Paris, Bryson & Ho, etc.). Journal (SIAM Review) version not consulted; no volume/page details are claimed.
- Underactuated Robotics — chapter “Trajectory Optimization” (book/trajopt.html at commit 1e1402f) — scoped · raw book/trajopt.html at commit 1e1402ff50ca9de7bebaf6849a59114085393d2b, tags stripped (identical to the live page text on 2026-12-03). Read: chapter intro; 'Problem Formulation'; 'Convex Formulations for Linear Systems' ('Direct Transcription', 'Trajectory optimization for the Double Integrator' incl. slack-variable and obstacle remarks, 'Direct Shooting', 'Computational Considerations', 'Continuous Time', 'Exact solutions to the double integrator'); 'Nonconvex Trajectory Optimization' ('Direct Transcription and Direct Shooting', 'Direct Collocation', 'Direct Collocation for the Pendulum, Acrobot, and Cart-Pole', opening of 'Pseudo-spectral Methods'); 'Solution techniques', 'Efficiently computing gradients', 'The special case of direct shooting without state constraints', 'Penalty methods and the Augmented Lagrangian', 'Zero-order optimization', 'Getting good solutions... in practice.'; 'Local Trajectory Feedback Design', 'Finite-horizon LQR', 'Model-Predictive Control' and its subsections; 'Pontryagin's Minimum Principle' opening and 'Lagrange multiplier derivation of the adjoint equations', 'Necessary conditions for optimality in continuous time' (skimmed); 'Iterative LQR and Differential Dynamic Programming'. NOT read: rest of pseudo-spectral and implicit-dynamics sections, perching case study, differential flatness, combinatorial/GCS sections, explicit MPC, exercises, interactive code, and the cited papers (Hargraves87, Betts, Li04, Jacobson70, etc.). Author notes/commented-out drafts in the HTML are not used.
- Model Predictive Control: Theory, Computation, and Design, 2nd ed. (fifth printing, 2024 electronic copy) — scoped · pdftotext -layout of the 5th-printing PDF; printed page = PDF page − 50. Read for this topic: §8.1 pp. 485–495 (inexact solutions, discrete OCP (8.1), convex vs nonconvex and Example 8.1, simultaneous vs sequential incl. condensing and the rule of thumb on p. 492, Example 8.2, continuous OCP (8.5), HJB / indirect / direct families p. 493, Euler transcription (8.6) p. 494, start of §8.2); end of Example on p. 530 and §8.5 pp. 530–542 (direct parameterizations (8.20)–(8.21), single shooting (8.22) and initial-value embedding, multiple shooting (8.23) with variable counts and comparison, exact LQ expressions, direct transcription and collocation (8.24)–(8.28), pseudospectral methods); p. 567 (state-constrained problems favour simultaneous approaches). NOT read for this topic: §8.2–8.4 (integrators, Newton methods, derivatives) beyond the first page of §8.2, §8.6–8.8, §8.10–8.12, Chapter 8 exercises (including the direct single-shooting and collocation exercises behind Figs. 8.9–8.11), and cited originals.
Related topics