The preceding chapters formulated and optimized trajectories through discrete transition maps. Physical models are often given instead by ordinary differential equations, so their states and controls are functions of time. A finite-dimensional optimizer cannot choose an entire function directly. Continuous-time trajectory optimization therefore begins by replacing those functions and their differential equations with finitely many variables and constraints on those variables.
How can that replacement preserve enough of the differential equation to make the resulting trajectory meaningful between the stored time points?
This replacement is called transcription, and the resulting finite optimization problem is a nonlinear program (NLP).
Direct collocation performs this replacement by storing state and control values at selected times and interpolating between them with low-degree polynomials. The differential equation is enforced at selected points on each time interval. This chapter develops that construction from one simple example through Euler, trapezoidal, and Hermite--Simpson transcriptions, then applies it to the motion of an overhead crane.
A One-Interval Example¶
How can a constraint on four endpoint values ensure that the chosen control produces the required displacement?
Consider a point that must move from to . Its velocity is the control, so
and the objective penalizes squared control effort,
Both and are unknown functions. As a first finite approximation, retain only their endpoint values and let the control vary linearly between and . Integrating means that the change in state equals the area under this control. The shaded region below is a unit-width trapezoid. Its area is the average of its two endpoint heights, and , multiplied by the width.
Figure 1:Drag the endpoint controls or play the accumulation from left to right. The shaded rectangle and triangle sum to the state change implied by . Setting the interval width to gives the state-change relation .
Figure 2:A linear control connects and across an interval of width . The rectangle and triangle sum to . Because , this area equals .
The optimizer must choose endpoint states and controls that agree with this area calculation. Otherwise, it could choose and while setting both controls to zero: the endpoint conditions would hold, but zero velocity could not produce the displacement. To exclude such choices, the stored state change must equal the change predicted by integrating the control. Moving both quantities to the left gives the constraint
The left-hand side measures the mismatch between these two changes and is called the defect. Requiring that mismatch to vanish gives a defect constraint, which enforces the dynamics within the chosen approximation. The equation is algebraic because it relates the four numbers through arithmetic operations; there is no unknown function to differentiate or integrate when evaluating it. An optimizer can therefore check the constraint directly for each candidate set of endpoint values.
Approximating the running-cost integral by the average of its endpoint values gives the finite nonlinear program
The boundary conditions reduce the defect to . Substituting into the objective gives
The squared term is minimized at , which also gives . The resulting interpolation is the exact solution and .
This example already contains the main ingredients of direct collocation. The function values became optimization variables, integration became a weighted sum, and the differential equation became an equality constraint. The remaining sections construct these operations systematically for nonlinear vector dynamics and higher-degree polynomials.
From a Continuous Problem to a Finite NLP¶
How do nodal state and control values, quadrature weights, and defect equations assemble into one nonlinear program?
We retain the earlier notation for the state, for the control, and for cost. Here is continuous physical time, while will index mesh intervals. The running cost is a cost per unit time; integrating it over an interval produces the counterpart of the discrete stage cost . The terminal cost is written because the final physical time is . Scalar examples omit boldface.
With inequalities and equalities , the continuous-time Bolza problem is
Here is the state, is the control, is a terminal cost, and is a running cost. The equality imposes endpoint conditions, while represents constraints that must hold along the path. Setting gives the Mayer special case, while setting gives the Lagrange special case. All three forms use the same transcription machinery.
Two transcription strategies differ in which values become decision variables and in how they impose the differential equation:
| Strategy | Finite decision variables | Treatment of the ODE |
|---|---|---|
| Shooting | Control parameters and, in multiple shooting, selected boundary states | A time integrator advances the state sequentially inside each shooting interval |
| Direct collocation | State and control values at selected nodes | Algebraic defect equations enforce the ODE simultaneously |
Shooting and collocation are therefore distinct transcription strategies. A collocation method may reproduce a familiar integration formula, but it exposes the state values to the NLP rather than hiding every state update inside a simulation. The term direct indicates that the continuous problem is converted directly into an optimization problem, without first deriving necessary conditions such as the Pontryagin equations.
Let
be a mesh with . We write and for values at mesh time , as in the earlier discrete-time chapters; the subscript is an index, not a physical time. On each interval, the normalized coordinate is , or equivalently
Every physical interval is thereby mapped to the same reference interval . Differentiation and integration formulas can be constructed once on this reference interval; the length then supplies the physical-time scaling. If the final time is also optimized, the interval lengths become variables or fixed fractions of the variable horizon; the reference-interval operators remain unchanged.
One Polynomial, Two Coordinate Systems¶
Should a polynomial trajectory be stored by its coefficients or by its values at support nodes, and how are the two descriptions related?
The opening example represented a line by its two endpoint values. Higher-order collocation uses the same idea with more values. The polynomials of degree at most form the space
This space, denoted by , has dimension . Choosing a basis gives coefficient coordinates
The monomial choice is familiar, but it is only a coordinate system. The polynomial is the function , not its particular list of coefficients.
The same polynomial can instead be identified by its values. Choose distinct points
and record
These points are called support nodes: once the degree is restricted to at most , the stored values determine the whole polynomial. Storing values is useful for trajectory optimization because a bound on the state at a node then becomes a bound on a decision variable. To evaluate the dynamics between nodes, however, we need a formula that reconstructs the polynomial from those values.
For degree one, take the support nodes 0 and 1. A line has the form . The first endpoint condition gives , and the second gives , so . Substitution and regrouping give
The weights and enforce the two endpoint conditions: at 0, the formula returns , and at 1, it returns . Between the endpoints, the weights vary continuously; at , for example, the value is . This is the unique line through the two prescribed values. Without the degree restriction, other curves could pass through them. Even for this same line, is an equivalent representation. The weighted form is convenient because each stored value has its own function that determines its contribution throughout the interval.
With more nodes, the same construction needs one weight function per stored value . To recover at its own node without altering the values at the other nodes, must equal one at and zero at every other support node. A polynomial with those zeros contains the factors for all . Dividing their product by its value at makes the value there equal to one. This constructs the Lagrange cardinal function
At a support node , one factor in the numerator is zero unless . When , every numerator equals its corresponding denominator. Consequently,
where the Kronecker delta is shorthand for one when and zero otherwise. This identity specifies the values at the nodes only. At any other , the product formula gives a smoothly varying polynomial weight, which can be negative or exceed one for higher degrees. Thus, unlike a line between two endpoint values, a higher-degree interpolant can take values outside the range of its stored values. The cardinal functions reconstruct the polynomial throughout the interval by
At a node , all terms except vanish. Between nodes, the weighted sum supplies the intervening values. Changing one stored value by changes the curve by , so the same function describes how that variable affects the entire polynomial.
The uniqueness of this reconstruction follows from a basic root-counting argument. If two polynomials in have the same nodal values, their difference has distinct roots. A nonzero polynomial of degree at most cannot have that many roots, so the two polynomials must be identical.
For a scalar polynomial, collect the coefficients and values into column vectors and . The coefficient and nodal descriptions are related by the evaluation matrix
Distinct support nodes make invertible by the same root-counting argument. Thus and are two coordinate vectors for one polynomial, rather than two different approximations.
For example, take and the nodes . In monomial coordinates,
whereas the nodal coordinates are
Both vectors describe exactly the same quadratic. Direct collocation uses coordinates like : state values and control values at meaningful points. It does not ask the NLP solver to choose monomial coefficients. Software may use coefficient calculations when it constructs fixed operators, but those calculations remain outside the NLP.
Figure 3:One quadratic, two coordinate systems. Evaluating the monomial coefficients at the support nodes gives . Direct collocation stores the nodal vector ; the fixed operators and then return its nodal derivatives and exact integral without adding optimization variables.
Matplotlib is building the font cache; this may take a moment.

Polynomial space, basis, and nodes are different choices¶
The construction separates three decisions that are easy to conflate:
The polynomial space specifies which functions are available.
The basis specifies coordinates for a member of that space. Monomial and Lagrange bases span the same .
The nodes specify where values, residuals, or integrals are evaluated.
Changing the basis does not change the exact polynomial space, although it can change numerical conditioning. Changing the nodes changes the interpolation and the operators built from it. The higher-order node families introduced later can still use Lagrange nodal coordinates in the NLP; choosing those nodes does not require optimizing orthogonal-polynomial coefficients.
Polynomial Interpolation and Least-Squares Regression¶
When nodal values do not determine an exact interpolant, which projection recovers a polynomial that best matches the available samples?
Interpolation and polynomial regression impose different requirements on the same data. Six values at six distinct nodes determine one polynomial of degree at most five that passes through every point. If the values are noisy observations and the aim is to estimate a quadratic trend, a quadratic will generally be unable to pass through all six. Least-squares regression then chooses its three coefficients to minimize the sum of squared discrepancies. The figure below applies both choices to the same six points. Write for the matrix obtained by evaluating the chosen polynomial basis at the supplied input points. The two algebraic problems are then compared below.
| Polynomial interpolation | Least-squares regression | |
|---|---|---|
| Input | Exact value conditions | Usually noisy or overdetermined observations |
| Algebraic problem | Satisfy exactly | Minimize |
| Residual | Zero when the value conditions uniquely determine a polynomial | Generally nonzero |
| Typical purpose | Represent a function from exact nodal data | Estimate a trend or conditional mean |
If is square and invertible, least squares happens to return the exact interpolant with zero residual. That special overlap does not erase the conceptual distinction.
Figure 4:Two polynomials fitted to the same six points (black dots). The solid blue degree-five interpolant passes through every point. The dashed orange quadratic regression minimizes the sum of squared residuals, shown as gray vertical segments. The polynomial degrees differ because a quadratic generally cannot satisfy all six value conditions exactly.

In direct collocation, the nodal states are unknown decision variables rather than observations. Each candidate vector of nodal values defines one interpolating polynomial exactly. The optimizer selects a candidate whose ODE residual vanishes at the collocation nodes. A numerical solver may temporarily work with a scalar measure of constraint violation, but the collocation conditions remain equality constraints rather than a statistical regression loss.
Fixed Operators from Nodal Values¶
How can the stored values give us both the slopes and the integral of every candidate polynomial?
The nodal representation also turns differentiation and integration into matrix and vector products. Once the nodes are chosen, the required arrays can be computed once and reused for every candidate trajectory. The optimizer can then evaluate slopes and integrals as it changes the nodal values, without repeating symbolic differentiation or numerical integration. These operations are exact for the represented polynomial.
This is possible because the cardinal functions stay fixed while only their coefficients change. In the representation
each is constant with respect to , so differentiation acts only on . To obtain the slopes needed by the ODE, differentiate and then evaluate at a node :
while integration over the reference interval gives
The resulting differentiation matrix and integration weights depend only on the chosen nodes. Their entries record the derivatives and areas of the fixed cardinal functions. Multiplication by the current nodal values combines these contributions into the derivative or integral of the current polynomial. This is how the transcription supplies the calculus needed by the dynamics and cost through arithmetic on the decision variables.
For a concrete construction, suppose a quadratic is stored by its values at , where denotes the midpoint. The desired outputs are its slope at each of these nodes and its integral over . To build the arrays that return those outputs for any choice of the three values, first construct the three cardinal functions multiplying them:
These are the three contributions in . Their derivatives are , , and . At the left endpoint they give the weights , so . Evaluation at the midpoint and right endpoint supplies the other two rows of the differentiation matrix:
Thus a matrix-vector product turns the three stored values into the three nodal derivatives. Integrating the same cardinal functions gives
The row turns the same three values into the exact integral of their quadratic interpolant. The matrix differentiates every polynomial in exactly, and integrates every polynomial in that space exactly. “Fixed operator” means that these arrays remain constant while the NLP changes the nodal values.
A transcription may use nodes for three distinct purposes:
| Node role | What it does |
|---|---|
| Support node | Supplies coordinates that define a polynomial |
| Collocation node | Supplies a point where the ODE residual is constrained |
| Quadrature node | Supplies a point used to approximate an integral |
A method often reuses one set of points for two or three roles. That is a design choice, not a definition. For example, a state polynomial can be supported at one set of nodes and differentiated at different collocation nodes. The next section begins with slope values at collocation nodes and uses integration to recover state values.
From Nodal Slopes to Collocation Constraints¶
How do those fixed maps convert differential equations into algebraic constraints at the chosen collocation nodes?
A single polynomial can represent a trajectory over the entire horizon; the opening example’s solution already does so. Why introduce several pieces? Consider the same scalar dynamics , starting from , but now moving right at unit speed until and then left at unit speed:
The state is continuous, but its slope changes abruptly at the switching time. Two line segments represent it exactly. A single polynomial has a continuous derivative, so it cannot reproduce this corner exactly, although it can approximate the trajectory. The ODE here holds on either side of the switch; the control’s value at that one instant does not affect its integral.
Even when the trajectory is smooth, some portions may change much faster than others. Separate polynomial pieces let us shorten the mesh intervals near a rapid change while retaining longer intervals elsewhere. Increasing the degree of one global polynomial adds flexibility across the whole horizon. The local representation also gives the optimizer useful structure: each interval’s dynamics constraints involve only its own stage values and neighboring endpoint states. A global polynomial couples values across the horizon through its differentiation matrix.
For a trajectory that is smooth throughout the horizon, a single polynomial of sufficiently high degree can be an efficient choice. Piecewise polynomials give us local control over resolution, allow changes in slope at joins, and keep the constraint derivatives sparse. They require us to connect adjacent pieces explicitly so that the state remains continuous.
We therefore represent the trajectory by a separate polynomial on each mesh interval . The full approximation is piecewise polynomial. To construct the piece on interval , use its local coordinate , where , and write
Thus is the state at the start of this interval and is the state at its end. On the next interval, the local coordinate starts again at zero, and a different polynomial describes the trajectory. The reference interval and its integration weights can be reused even when the physical intervals have different lengths.
Choose collocation nodes on . On interval , node corresponds to the physical time . The state and control values there are and . This local evaluation point, together with its state and control values, is called a stage. At each stage, the differential equation prescribes the physical-time slope
for . Let be the Lagrange cardinal function associated with the nodes . Interpolating these slopes gives the physical-time derivative on this one interval:
This polynomial agrees with the ODE slope at every collocation node of interval . Integrating from its left endpoint, whose stored state is , constructs the entire state piece:
The factor converts integration in normalized time into integration in physical time: . For example, a constant physical slope acting from to acts for units of time and changes the state by . Without , the formula would treat every physical interval as having unit duration. Equivalently, the chain rule gives .
The stored stage state must lie on this polynomial at . Imposing gives the stage equations
Each row of integrates only as far as one stage within interval . These are simultaneous constraints on the stage values: the slopes on the right depend on the state and control variables being chosen. To reach the end of the interval instead, set and require the resulting value to equal the stored right endpoint :
The coefficients integrate the cardinal functions over the full reference interval. The endpoint equation is a defect constraint: it requires the stored endpoint to match the endpoint obtained by integrating the slopes of piece . The next piece starts from that same stored value, so the two pieces meet:
This shared variable enforces state continuity across the join. If an implementation stores separate endpoint variables for the two pieces, it must impose an equality between them. Choosing an endpoint as a collocation node does not by itself join the pieces. Continuity of the state also does not require continuity of its derivative; neighboring pieces can meet with different slopes.
Figure 5:A scalar trajectory consists of polynomial pieces joined at shared endpoint states (squares). The middle piece is shown in blue in both panels; only its time coordinate changes. The stage values (orange dots) lie at and . Tangent marks in the lower panel have slopes because that axis uses normalized time. The stage equations place the dots on the piece, and the endpoint defect makes it reach , where the next piece begins. This schematic uses quadratic state pieces and linear slope interpolants.
The running-cost integral can be treated by exactly the same construction. As in the earlier Bolza-to-Mayer reduction, introduce a scalar state that records the cost accumulated since :
The original objective is now . The augmented state has two rates of change: supplies the physical state rate and supplies the cost rate. Applying the same collocation method to this augmented ODE evaluates both rates at each stage’s state, control, and time. In particular, the cost rate at stage of interval is
Let and denote the accumulated-cost values at the interval’s left endpoint and at stage . Integrating the cost-rate interpolant to a stage and to the right endpoint gives
These are the same stage and endpoint equations as for , with in place of . The increase in accumulated cost across interval therefore supplies its contribution to the discrete objective:
Here is the piecewise control approximation. The single-index is an interval cost, whereas is a sampled cost rate; the factor gives them different units. The weighted sum integrates the polynomial interpolating the sampled cost rates exactly. It approximates the running-cost integral because the composed function need not itself be that polynomial. Such a weighted-sum approximation is called a quadrature rule.
Since , summing the interval increments gives . The accumulated-cost variables can therefore be eliminated and the sum used directly in the objective. Introducing explains why applying one collocation scheme to both rates uses the same nodes and weights; it does not require adding cost variables to the implementation. A different quadrature rule is also possible, with the state and control polynomials evaluated at that rule’s nodes.
Choosing a polynomial for the control¶
The state and control play different roles. The ODE constrains the state’s derivative, so integrating an interpolant of slopes gives a state polynomial of degree at most . There is no corresponding ODE for the control in this problem. Its representation is a separate choice: a constant command on each interval, a line between endpoint commands, or a higher-degree polynomial.
For example, with two endpoint slopes the state polynomial is quadratic. The control can still be the line
These degrees need not match. Also, substituting polynomial state and control curves into a nonlinear need not produce a polynomial. Collocation matches the state derivative to at the chosen nodes, rather than requiring the ODE to hold identically between them.
To make the control choice explicit, select distinct control support nodes and construct their cardinal functions . The decision variables are control values at these support nodes:
Thus the stage controls are computed from the control variables; they are independent variables only when the representation allows independent values at all those stages. For a constant control, and every entry of is one. For a linear control supported at , row of is .
Using more control support values than collocation stages leaves some control variations invisible to those stage samples. The examples below use ; a richer control representation needs additional sampling or other constraints to account for those variations.
The ODE requires continuous states, but it can admit controls that jump between intervals. Independent control polynomials therefore need no continuity constraint unless the model or chosen parameterization requires one. Sharing endpoint controls between neighboring linear pieces enforces continuity. With separate local variables, the equivalent equality is
At a jump, endpoint stages use the control belonging to their own interval. Finally, bounds on support values guarantee bounds throughout a constant or linear control segment, because its values are convex combinations of its endpoints. A higher-degree polynomial can overshoot those values, so support bounds alone no longer give that guarantee.
After all intervals are assembled, collect the nodal states and controls into the decision vector
Here stacks the listed vectors into one column, omitting duplicate variables when a stage shares a mesh endpoint. Stage controls are evaluated using , and any chosen control-continuity equalities are added to the constraints. If is optimized, it is included in as well. The resulting finite optimization problem has the form
In the preceding chapter’s NLP notation, is this scalar objective, stacks the stage, endpoint, and boundary equalities, and stacks the sampled path and bound inequalities. The slope is a vector, distinct from .
The original path and bound constraints apply at every continuous time. The finite NLP can impose them only at selected points, usually its support or collocation nodes. Feasibility at those nodes does not rule out a violation between them, so a continuous replay or dense residual check must follow the optimization.
Every interval constraint touches only local stage variables and neighboring endpoint states. Consequently, most derivatives of the constraints with respect to the decision variables are zero. With variables ordered by time, the nonzero blocks lie near the diagonal of the Jacobian, the matrix of constraint derivatives. NLP solvers can exploit this sparse, block-banded pattern. The arrays and are numerical constants computed before optimization.
Equivalent differentiation form¶
The slope-value construction starts from and integrates. Many implementations take the equivalent route of starting from nodal state values and differentiating. The integral of the degree- slope polynomial has degree at most , so take and choose support nodes for the state polynomial. Write for their cardinal functions to distinguish this support-node basis from the slope-node basis . Denote the support values by ; these need not be the stage values at :
At a collocation node , the state is a weighted sum of its support values, and its derivative with respect to is another weighted sum. The fixed arrays containing these weights are
Thus evaluates the state polynomial and differentiates it. Because , enforcing the ODE at node gives
The left side is the derivative with respect to normalized time, and the factor on the right converts the physical-time derivative accordingly. In matrix shorthand, all nodal constraints are . Here has support states as rows, and has stage slopes as rows; neither is a single state vector. Evaluation at the two ends connects this polynomial to the shared mesh states:
When support and collocation nodes coincide, the cardinal property makes select the corresponding stored state directly. The slope-value and state-value forms describe the same polynomial construction; one integrates nodal slopes, while the other differentiates nodal states.
This implementation pattern is standard in direct collocation Kelly, 2017Andersson et al., 2019. The official CasADi direct-collocation example constructs fixed differentiation, endpoint, and quadrature arrays from Lagrange polynomials, while the NLP variables remain state and control values.
Both algebraic forms follow the same sequence. Nodal values define a local polynomial, fixed arrays differentiate or integrate it, and equality constraints match the resulting slopes and endpoints to the dynamics. The choice between slope values and state values changes the implementation, not the represented collocation method.
Low-Order Transcriptions¶
Which familiar integration rules appear when the polynomial and node sets are reduced to their lowest-order choices?
The general construction becomes concrete when only one or two slope values are retained on each interval. These cases recover familiar integration formulas, but the formulas now appear as constraints inside an NLP. For the concrete problems below, fix the mesh and final time. The boundary map includes the prescribed initial state and any terminal conditions; includes path constraints and state/control bounds. Each displayed program specifies the points where those inequalities are imposed. Additional check points can be included, and a continuous replay still checks the result between nodes.
One slope value: explicit and implicit Euler¶
A single slope value determines a constant derivative on each interval. Choose a constant control on that interval as well: . Different intervals may use different constants. The state is linear even though the control is constant. The following exercise applies the preceding construction to recover the two Euler methods. The solution gives a recipe that also extends to multiple slope nodes.
Solution to Exercise 1
The derivation follows five steps: choose where the ODE is evaluated, interpolate its slope, integrate that interpolant, match the stored endpoint, and integrate the cost rate with the same weights.
Choose the stage and evaluate its slope. The left node uses the state, control, and time at the start of the interval; the right node uses those at its end:
Interpolate the physical-time derivative. With one node, the cardinal function is the constant , since it must equal one at that node. Hence throughout the interval. Its full-interval integration weight is .
Integrate from the left state. The reference-time derivative is . Integrating and imposing gives
Thus the state polynomial has degree at most one. The factor accounts for the physical duration of the interval.
Match the stored right endpoint. Setting gives the defect . Substituting the two slope choices yields
In forward simulation, explicit Euler computes the next state from known left-endpoint data. Implicit Euler places the unknown next state inside , so it generally requires solving an equation, which is nonlinear when the dynamics depend nonlinearly on that state. In direct transcription, both endpoints are optimization variables and either defect is imposed as an equality constraint.
Apply the same integration rule to the cost rate. The single sampled cost rate is constant in the approximation, so its integral is that rate multiplied by :
These are the left- and right-endpoint approximations to the interval running-cost integral. They use the same stage as the corresponding dynamics constraint.
With additional slope nodes, the sequence stays the same. The constant cardinal function is replaced by several cardinal polynomials, and their integrals supply the weights in the stage equations, endpoint defect, and cost contribution.
The complete Euler NLP¶
Let for explicit Euler and for implicit Euler. Both methods optimize the mesh states and the interval controls . There are no additional stage-state variables after identifying the sole stage with its endpoint:
Here selects an endpoint, not an intermediate time. The path constraints use the same endpoint as the dynamics; bounds required at the other endpoint can be imposed there too. The two NLPs differ only in where the slope and cost rate are evaluated. Both are solved for the entire trajectory simultaneously.
Endpoint slope values: trapezoidal transcription¶
Use continuous piecewise-linear controls, with shared endpoint variables . Choose the endpoint collocation nodes and , and abbreviate the two ODE slopes by
For this endpoint formula, label the cardinal functions by their locations, 0 and 1, rather than by the stage numbers 1 and 2:
The derivative interpolant is the line joining the two slopes:
It equals at and at . Integrating from the known left state gives the continuous state approximation
The state approximation is quadratic, even though an implementation may store only its endpoint states and slopes. Evaluating this polynomial at and equating it to the stored endpoint produces
The coefficients are the integrals of the two linear cardinal functions. This is the trapezoidal defect derived in the opening example. Applying the same endpoint weights to the running cost gives
The two endpoint costs are averaged and multiplied by the interval length. The degree bookkeeping follows directly from integration: a linear derivative interpolant produces a quadratic state interpolant. This distinction is emphasized in the direct-collocation derivation of Kelly (2017).
The complete trapezoidal NLP¶
The decision variables are the mesh states and controls. Write and for evaluated quantities, not additional optimization variables. Then the transcribed problem is
The state between endpoints is the quadratic obtained above, while the control is linear. Shared mesh states and controls connect adjacent pieces; no separate continuity equations are needed in this representation.
Hermite--Simpson Transcription¶
Can midpoint state and slope information raise the transcription order without requiring a high-degree polynomial over the whole horizon?
Hermite--Simpson extends the trapezoidal construction by adding the midpoint state . Retain the same piecewise-linear control, so its midpoint value is already determined:
Evaluate the midpoint ODE slope using that control:
The notation and denotes values at physical time , not another mesh endpoint.
The three stage nodes are , , and . We label their cardinal functions for left endpoint, midpoint, and right endpoint. The derivative interpolant is the quadratic built from the following three cardinal functions:
Integrating each function over the full reference interval gives
These are the familiar Simpson quadrature weights. Substituting them into the general endpoint equation produces the Simpson defect:
The midpoint state must also lie on the cubic obtained by integrating the quadratic derivative. Integration only to gives
This form still contains the midpoint slope. The endpoint defect gives
Substituting this expression into the midpoint equation and collecting the endpoint states and slopes yields
The midpoint state relation and the definition of together enforce the ODE at the midpoint. A quadratic derivative interpolant integrates to a cubic state interpolant, so Hermite--Simpson is not based on a quadratic state approximation. The name reflects its two ingredients: the state is a cubic Hermite interpolant determined by state and slope information, and its endpoint defect uses Simpson weights.
The complete Hermite--Simpson NLP¶
With linear controls, optimize mesh states, mesh controls, and midpoint states. For or , abbreviate and , with and the midpoint control given by the endpoint average. The complete program is
An alternative is to optimize the midpoint control independently. The three control values then define a quadratic on each interval; the midpoint-average relation is removed, and joins the decision vector. The two state equations and Simpson cost weights remain the same. This changes the admissible controls, so it can change the optimizer’s solution.
The resulting representations can be compared directly. All degrees are upper bounds on each interval; they are not claims about convergence order.
| Scheme used here | State degree | Control degree | Independent values beyond mesh states |
|---|---|---|---|
| Explicit or implicit Euler | 1 | 0 | One control per interval |
| Trapezoidal | 2 | 1 | Shared endpoint controls |
| Hermite--Simpson, linear control | 3 | 1 | Shared endpoint controls and midpoint states |
| Hermite--Simpson, quadratic control | 3 | 2 | Shared endpoint controls, midpoint states, and midpoint controls |
Constructing a Scheme from Its Nodes¶
How can a program generate these transcriptions from node choices without hand-deriving a new set of defect equations each time?
The same construction generates every scheme in the preceding table. Its inputs are the collocation nodes, the control support nodes, and a choice about control continuity. The number of collocation nodes determines the degree of the slope interpolant and hence the state polynomial. The control support nodes determine the control polynomial independently.
This recipe covers polynomial collocation obtained by interpolating slopes at distinct nodes and integrating them. It includes Gauss, Radau, and Lobatto collocation as well as the low-order examples. An arbitrary Runge--Kutta tableau need not come from such nodes, so specifying nodes does not generate every possible integration method.
The stage controls, slopes, and cost rates in step 3 are expressions in the decision variables. They are recomputed as the optimizer changes those variables; remain fixed. Automatic differentiation can supply the derivatives of the assembled expressions. If endpoint stages are retained as separate variables, the stage and endpoint equations connect them to the mesh states. Eliminating those copies produces the smaller low-order programs above; keeping both the copies and their defining equations is also valid. Identifying a copy with its endpoint requires removing the resulting duplicate or identically zero equation.
A reusable coefficient generator and residual evaluator¶
The following function computes by polynomial arithmetic. The same function accepts any distinct collocation and control support nodes:
def make_rule(nodes, control_nodes):
"""Precompute integration weights and control evaluation weights.
A[i,j] = integral from 0 to nodes[i] of slope basis j.
b[j] = integral from 0 to 1 of slope basis j.
B[j,r] = control basis r evaluated at collocation node j.
"""
slope_basis = cardinal_polynomials(nodes)
control_basis = cardinal_polynomials(control_nodes)
nodes = np.asarray(nodes, dtype=float)
antiderivatives = [polynomial.integ() for polynomial in slope_basis]
A = np.column_stack([p(nodes) - p(0.0) for p in antiderivatives])
b = np.array([p(1.0) - p(0.0) for p in antiderivatives])
B = np.column_stack([p(nodes) for p in control_basis])
return CollocationRule(
nodes=nodes,
control_nodes=np.asarray(control_nodes, dtype=float),
A=A,
b=b,
B=B,
control_left=np.array([p(0.0) for p in control_basis]),
control_right=np.array([p(1.0) for p in control_basis]),
)
For example, the choices below recover the four low-order constructions:
from collocation_transcription import make_rule
explicit_euler = make_rule([0.0], [0.0])
implicit_euler = make_rule([1.0], [0.0])
trapezoidal = make_rule([0.0, 1.0], [0.0, 1.0])
hermite_simpson = make_rule([0.0, 0.5, 1.0], [0.0, 1.0])
# An independent midpoint control changes B, not A or b:
hermite_simpson_quadratic_u = make_rule([0.0, 0.5, 1.0], [0.0, 0.5, 1.0])The implicit-Euler control support node can be 0 even though its collocation node is 1: a constant polynomial has the same value at both. For Hermite--Simpson with linear controls, the generated arrays are
The middle row of gives the midpoint stage equation before elimination; the middle row of gives the endpoint-average control. Supplying three control support nodes instead makes the identity, allowing an independent midpoint control while leaving the state construction unchanged.
The complete file also supplies transcribed_problem, which evaluates
from arrays of mesh states, stage states, and control support values.
Its default allows control jumps; continuous_control=True adds the
endpoint-matching equations used by the linear-control examples. A solver
wrapper flattens these arrays into and reshapes each candidate
before evaluation. The NumPy evaluator can be used with finite differences;
an automatic-differentiation implementation uses the same array operations
in its chosen backend. The returned inequality residuals use ;
negate them for a solver interface that expects nonnegative residuals.
Download the coefficient generator and NLP evaluator
Explicit polynomial coefficients keep this implementation readable at modest degrees. At high degrees, use numerically stable basis evaluation and integration routines; the NLP assembly remains the same.
Optional orientation: Gauss, Radau, and Lobatto nodes¶
Higher-order schemes often place their nodes at roots of Legendre polynomials or at roots of closely related equations that include prescribed endpoints. These placements produce accurate quadrature rules for a given number of function evaluations. Three names indicate which endpoints are included:
| Family | Endpoints included |
|---|---|
| Gauss | Neither endpoint |
| Radau | One endpoint |
| Lobatto | Both endpoints |
Gauss nodes exclude both endpoints, Radau nodes include one, and Lobatto nodes include both. This vocabulary describes node placement, not the coordinate basis used by the NLP. It also does not determine continuity. Adjacent state polynomials are continuous only when they share an endpoint state or are connected by an equality constraint. Endpoint inclusion can make that linkage convenient, but it does not automatically provide state continuity or slope continuity.
The detailed comparison of node families, convergence rates, and adaptive degree selection is deferred. Each family enters the present construction in the same way: its nodes define Lagrange functions, which in turn define fixed differentiation and quadrature operators.
Worked Example: Moving an Overhead Crane While Limiting Residual Sway¶
How do the nodal variables and trapezoidal defects behave in a constrained motion problem whose terminal state must suppress residual oscillation?
An overhead crane moves a trolley while a payload hangs from a cable. A precomputed trolley command can complete the move and still leave the payload swinging. The comparison uses three precomputed acceleration commands. The unshaped baseline moves the trolley without accounting for the payload. A zero-vibration input shaper modifies that baseline to cancel the nominal oscillation. Direct collocation instead chooses a command using the nonlinear payload dynamics and the motion constraints. All three commands are open loop: they are fixed before the move and do not respond to measurements during execution.
The state is , where and are trolley position and velocity, and and are payload angle and angular velocity. The scalar control is the commanded trolley acceleration . It enters the nonlinear dynamics as
Here is gravitational acceleration, is cable length, and is the damping coefficient. The first two equations describe trolley motion, while the last two describe a damped pendulum driven at its suspension point. Positive trolley acceleration makes the load lag behind, which accounts for the minus sign multiplying . The model treats the cable as a rigid, massless link and assumes that the trolley acceleration can be commanded directly.
The trolley and payload start at rest. The goal is to move the trolley 4 m, stop it, and leave the payload hanging vertically without swinging. The nominal cable length is m. Every command is limited to m/s, and every command is replayed on the same nonlinear continuous-time plant with a 0.02 s sampling interval. A second replay increases the cable length by without redesigning any command. This second plant tests sensitivity to a simple model mismatch.
Two open-loop baselines¶
The unshaped baseline uses a symmetric trapezoidal velocity profile, produced by constant acceleration, cruising, and constant deceleration. Its acceleration and deceleration phases excite the payload oscillation because their timing ignores the pendulum period.
An input shaper filters a command into weighted, delayed copies. The delays are chosen so that vibrations excited by the copies cancel one another. For a zero-vibration (ZV) shaper, begin by approximating and near the hanging equilibrium. The payload equation then becomes
Here is the undamped natural frequency and is the damping ratio. For the nominal parameters, rad/s and . The shaper splits the baseline command into two copies separated by half of the damped oscillation period:
The delay makes the vibration caused by the second copy oppose the vibration remaining from the first. Accounting for decay over the delay gives , , and . Here s and the two weights are approximately 0.505 and 0.495.
Nodal decision variables and trapezoidal defects¶
The third command is found by solving the trajectory-optimization problem. On intervals with step , the NLP decision vector contains the state
and acceleration at every mesh node. These are polynomial values, not monomial coefficients. Each interval contributes the trapezoidal defect
The objective trades payload motion against acceleration magnitude and rapid changes in acceleration. The state and acceleration penalties are collected in the nodal quantity
The coefficient on penalizes sway most strongly, while the smaller coefficients penalize angular velocity and acceleration. The smooth state-and-control cost uses trapezoidal endpoint weights. The final term penalizes acceleration slew, the rate at which the acceleration command changes. Because the control is piecewise linear, this rate is constant on each interval, giving
The boundary conditions impose and , so both the trolley and payload finish at rest. The nodal bounds impose m/s, m/s, and . Because these bounds are imposed only at nodes, a dense replay remains necessary to check the path between nodes.
The ZV shaper is tailored to one frequency, so it should leave the least residual sway when the cable length matches its design model. The collocation solution uses the full nonlinear nominal model and handles all constraints at once, but it is also open loop and has no explicit robustness guarantee. The cable-length test therefore measures sensitivity to one model mismatch; it does not establish that either method is robust in general.
Figure 6:All three commands move the trolley through the same four-metre task on the nonlinear plant. The unshaped command leaves a large oscillation. The ZV shaper nearly cancels the nominal mode, while direct collocation reaches the terminal state with a smoother, lower-effort command. The lower panel replays the unchanged commands after increasing cable length by 10 percent. Hatched bars denote the mismatched plant.

The ZV shaper produces the smallest nominal residual sway because the simulated plant closely matches the single oscillatory mode used to design it. The collocation command uses less squared acceleration than either baseline and keeps residual sway below one degree in both replays. The unshaped command completes the trolley move but leaves several degrees of oscillation. Cable-length mismatch increases the ZV residual substantially, while the collocation command degrades more gradually for this particular perturbation.
The table reports continuous-plant measurements rather than node values from the nonlinear program. Residual sway is the largest absolute angle after the common command horizon.
The animation uses the same high-accuracy nonlinear validation trajectories as the figure. It does not replay the collocation polynomial itself.
Figure 7:Continuous nonlinear replay of the unshaped, zero-vibration-shaped, and direct-collocation commands. All panels use the same spatial and temporal scales.
Inspect the direct-transcription implementation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93def solve_direct_collocation( params: CraneParameters | None = None, *, intervals: int = 28, horizon: float | None = None, max_iterations: int = 350, ) -> CollocationSolution: """Solve a constrained nonlinear point-to-point transcription. States and accelerations at every node are decision variables. Trapezoidal defects enforce the nonlinear dynamics, while boundary and path constraints are imposed directly on the node values. """ params = params or CraneParameters() params.validate() if intervals < 8: raise ValueError("intervals must be at least eight") move = TrapezoidalMove( params.target_position, params.profile_acceleration, params.profile_max_speed, ) shaper = ZeroVibrationShaper.from_parameters(params) if horizon is None: horizon = move.duration + shaper.delay if horizon <= 0.0: raise ValueError("horizon must be positive") node_time = np.linspace(0.0, horizon, intervals + 1) step = horizon / intervals state_guess, acceleration_guess = _initial_guess(params, node_time, move, shaper) initial = _pack(state_guess, acceleration_guess) initial_state = np.zeros(4) terminal_state = np.array([params.target_position, 0.0, 0.0, 0.0]) def objective(vector: np.ndarray) -> float: state, acceleration = _unpack(vector, intervals) return _transcription_objective(state, acceleration, step) def equality(vector: np.ndarray) -> np.ndarray: state, acceleration = _unpack(vector, intervals) defects = np.empty((intervals, 4)) for k in range(intervals): left = crane_dynamics(state[k], acceleration[k], params) right = crane_dynamics(state[k + 1], acceleration[k + 1], params) defects[k] = state[k + 1] - state[k] - 0.5 * step * (left + right) return np.concatenate( [state[0] - initial_state, defects.ravel(), state[-1] - terminal_state] ) nodes = intervals + 1 lower_state = np.tile( np.array([-0.25, -params.velocity_limit, -params.sway_limit, -2.0]), (nodes, 1), ) upper_state = np.tile( np.array( [params.target_position + 0.25, params.velocity_limit, params.sway_limit, 2.0] ), (nodes, 1), ) lower = _pack(lower_state, np.full(nodes, -params.acceleration_limit)) upper = _pack(upper_state, np.full(nodes, params.acceleration_limit)) result = minimize( objective, initial, method="SLSQP", bounds=list(zip(lower, upper)), constraints={"type": "eq", "fun": equality}, options={"maxiter": max_iterations, "ftol": 2e-10, "disp": False}, ) state, acceleration = _unpack(result.x, intervals) max_defect = float(np.max(np.abs(equality(result.x)))) success = bool(result.success and max_defect < 2e-5) if not success: raise RuntimeError( "crane direct collocation failed: " f"{result.message}; maximum equality residual {max_defect:.3e}" ) return CollocationSolution( time=node_time, state=state, acceleration=acceleration, objective=float(result.fun), max_defect=max_defect, success=success, message=str(result.message), )
Download the complete crane experiment
The optimization checks algebraic defects, bounds, and endpoint conditions at the nodes. The separate nonlinear replay checks what happens between those nodes. A small nodal defect is evidence that the discrete NLP was solved accurately; it is not, by itself, evidence that the mesh resolves the continuous dynamics.
The comparison does not establish that collocation always outperforms input shaping. The ZV calculation is inexpensive and can nearly cancel residual vibration when a lightly damped mode is accurately known. Direct collocation becomes useful when several state and actuator constraints must be handled together. All three commands remain open loop here. Feedback or receding-horizon replanning would be needed to react to unmeasured disturbances during the move.
Exercises¶
Solution to Exercise 2
Solution to Exercise 3
Problems 1 and 4 are interpolation problems; the least-squares formulation in problem 4 has a zero-residual interpolating solution. Problem 2 is regression. Problem 3 is neither statistical regression nor interpolation of observations: the unknown nodal values define an interpolating polynomial, and collocation adds equality constraints that select those values.
Solution to Exercise 4
Solution to Exercise 5
One node gives the constant derivative interpolant or . Integration yields the explicit or implicit Euler defect and a degree-one state. With endpoint nodes, . Its integral at is , which gives the trapezoidal defect. The linear derivative integrates to a degree-two state.
Solution to Exercise 6
Three distinct slope values define a quadratic derivative interpolant. Integrating that quadratic adds one degree, so the state is cubic. Integrating the cardinal functions over gives and hence the Simpson defect. Integrating to gives ; eliminating the midpoint slope with the endpoint defect gives
Solution to Exercise 7
The NLP defect measures its equality constraints only at the selected nodes. A coarse polynomial can satisfy those constraints while failing to resolve rapid behavior between them. Evaluate the ODE residual and path constraints on a dense grid, preferably using an independent high-accuracy replay. Refine the offending intervals or raise the local approximation degree, then solve and validate again. Tightening an already small NLP tolerance does not fix representation error.
Summary and Outlook¶
Direct collocation turns an optimization over whole functions into an optimization over finitely many state and control values. These nodal values define polynomial segments. Algebraic defect constraints then require each segment to agree with the ODE at selected points.
Each polynomial has two equivalent descriptions: basis coefficients or values at nodes,
Direct collocation uses the nodal description because the stored values have an immediate physical meaning. Lagrange cardinal functions turn them into fixed operators for computing derivatives, endpoints, and integrals. Although this construction resembles polynomial fitting, the nodal values are optimization variables rather than noisy observations, and the ODE residual is an equality constraint rather than a regression loss.
Interpolating one left or right slope gives explicit or implicit Euler and a linear state approximation. Interpolating both endpoint slopes gives the trapezoidal defect and a quadratic state approximation. Adding the midpoint slope gives Simpson weights, the Hermite--Simpson midpoint relation, and a cubic state approximation.
Across many intervals, each defect involves only neighboring endpoints and local stage values. Most entries in the constraint Jacobian are therefore zero, which allows an NLP solver to exploit a sparse, block-banded structure. The overhead-crane example also shows why solving the NLP is not the final check: constraints that hold at the nodes may still be violated between them. A dense, independent simulation should therefore follow the optimization. Can the same finite-horizon problem respond when that replay reveals a state different from the prediction? Receding-horizon control turns the open-loop transcription into feedback by replanning from each measurement.
- Kelly, M. (2017). An Introduction to Trajectory Optimization: How to Do Your Own Direct Collocation. SIAM Review, 59(4), 849–904. 10.1137/16M1062569
- Andersson, J. A. E., Gillis, J., Horn, G., Rawlings, J. B., & Diehl, M. (2019). CasADi: A Software Framework for Nonlinear Optimization and Optimal Control. Mathematical Programming Computation, 11(1), 1–36. 10.1007/s12532-018-0139-4