Orthogonal Collocation on Finite Elements

Learning outcomes

  • Write the collocation equations for one finite element with three Radau points and check the matrix by its row sums.
  • Relate the number of collocation points and elements to the order of accuracy and the size of the nonlinear program.
  • Compare simultaneous, multiple shooting and single shooting methods by problem size, sparsity and behavior on unstable plants.

Book chapter: Feedforward, Cascade, and Ratio Control (Volume 3), Chapter 10, Commanding an Attitude Instead of a Force in a Rocket Landing Simulator (PDF).
Practice in 15 minutes: 15 · A Constrained Landing Trajectory, 21 · MPC on the Unstable Branch of a Nonlinear Reactor
Model: Any differential-algebraic model, physics-based or data-driven; collocation is how it enters the optimizer.
Decision: The solver chooses states and inputs at every collocation point together, so the model holds only at the converged solution.
Learning: A trained network written as algebraic equations is discretized the same way, so a learned model can sit inside the collocation problem.

Discretization of a continuous time representation allow large-scale nonlinear programming (NLP) solvers to find solutions at specified intervals in a time horizon.

from gekko import GEKKO
m = GEKKO(remote=False) # create GEKKO model
y = m.Var(5.0,name='y') # create GEKKO variable
m.Equation(y.dt()==-y)  # create GEKKO equation
m.time = [0,1,2,3]      # time points
m.options.IMODE = 4     # simulation mode
m.options.NODES = 4     # set NODES=4
m.options.CSV_WRITE=2   # write results_all.json
                        #   with internal nodes
m.solve(disp=False)     # solve

import numpy as np
N = np.array([[0.436,-0.281, 0.121], \
              [0.614, 0.064, 0.0461], \
              [0.603, 0.230, 0.167]])

time = np.array([0.0, \
                 0.5-np.sqrt(5)/10.0, \
                 0.5+np.sqrt(5)/10.0, \
                 1.0])

from gekko import GEKKO
m = GEKKO()
y0 = 5
y  = m.Array(m.Var,3,value=0)
dy = m.Array(m.Var,3,value=0)

Ndy = np.dot(N,dy)
m.Equations([Ndy[i]==(y[i]-y0) for i in range(3)])
m.Equations([dy[i]+y[i]==0 for i in range(3)])
m.solve(disp=False)
print(y)

import numpy as np
N = np.array([[0.436,-0.281, 0.121], \
              [0.614, 0.064, 0.0461], \
              [0.603, 0.230, 0.167]])

time = np.array([0.0, \
                 0.5-np.sqrt(5)/10.0, \
                 0.5+np.sqrt(5)/10.0, \
                 1.0])

from scipy.optimize import fsolve

y0 = 5
zGuess = np.zeros(6) # y1-y3 and dydt1-dydt3

def myFunction(z):
    y  = z[0:3]
    dy = z[3:6]

    F = np.empty(6)
    F[0:3] = np.dot(N,dy) - (y-y0)
    F[3:7] = dy + y
    return F

z = fsolve(myFunction,zGuess)
print(z)

There are many names and related techniques for obtaining mathematical relationships between derivatives and non-derivative values. Some of the terms that are relevant to this discussion include orthogonal collocation on finite elements, direct transcription, Gauss pseudospectral method, Gaussian quadrature, Lobatto quadrature, Radau collocation, Legendre polynomials, Chebyshev polynomials, Jacobi polynomials, Laguerre polynomials, any many more. There are many papers that discuss the details of the derivation and theory behind these methods1-5. The purpose of this section is to give a practical introduction to orthogonal collocation on finite elements with Lobatto quadrature for the numerical solution of differential algebraic equations. See the documentation on Nodes for additional details on displaying the internal nodes.


The Collocation Equations

On one finite element of length `\Delta t`, the state is a polynomial through the starting value `x_0` and the values `x_1, \ldots, x_K` at `K` collocation points `\tau_1, \ldots, \tau_K` (fractions of the element). One matrix ties the derivatives at those points to the values, which turns the differential equation into algebraic equations:

$$\begin{gathered} \Delta t \; M \begin{bmatrix} \dot x_1 \\ \vdots \\ \dot x_K \end{bmatrix} = \begin{bmatrix} x_1 - x_0 \\ \vdots \\ x_K - x_0 \end{bmatrix}, \\ \dot x_i = f(x_i, u_i), \\ M_{ij} = \int_0^{\tau_i} \ell_j(\tau)\, d\tau \end{gathered}$$

where the integrand is the Lagrange polynomial that is one at `\tau_j` and zero at the other points. For three Radau points, `\tau = (4-\sqrt{6})/10,\; (4+\sqrt{6})/10,\; 1 \approx 0.155,\; 0.645,\; 1`:

$$M = \begin{bmatrix} 0.1968 & -0.0655 & 0.0238 \\ 0.3944 & 0.2921 & -0.0415 \\ 0.3764 & 0.5125 & 0.1111 \end{bmatrix}$$

Each row sums to its `\tau_i`, because a constant derivative must give `x_i - x_0 = \tau_i \Delta t\, \dot x`. The matrix `N` in the code above is built the same way for the points `0.5 \mp \sqrt{5}/10` and 1. The last point sits at the element end, so `x_K` is the starting value of the next element. Solving the three equations for `5\,dx/dt = -x^2 + u` with `x_0 = 0`, `u = 4` on one element of length 1 gives `x(1) = 0.75990` against the exact `2\tanh(0.4) = 0.75990`.

Order of accuracy. With `K` Radau points the error at the element ends falls as `\Delta t^{2K-1}` (fifth order for three points), and at the interior points as `\Delta t^{K}`. Every added point or element adds one set of states and equations to the nonlinear program, so accuracy is bought with problem size.

Three ways to put a model in an optimizer.

 Single shootingMultiple shootingSimultaneous (collocation)
Decision variablesinputs onlyinputs plus the states at each segment startinputs plus the states at every collocation point
Problem size and sparsitysmall and densemedium, block structuredlarge and sparse
Model equationssolved by an integrator at every iterationintegrated within segments; continuity is a constraintequality constraints, met only at convergence
Unstable plantsfails as errors grow along the horizonworks when segments are shortworks, since states are bounded at every point
State path constraintsonly at integrator output timesat segment boundariesat every collocation point

Exercise 1

Objective: Solve a differential equation with orthogonal collocation on finite elements. Create a MATLAB or Python script to simulate and display the results. Estimated Time: 2-3 hours

Solve the following differential equation from time 0 to 1 with orthogonal collocation on finite elements with 4 nodes for discretization in time.

 5 dx/dt = -x2 + u

Specify the initial condition for x as 0 and the value of the input, u, as 4. Compare the solution result with 2-6 time points (nodes). Report the solution at the final time for each and comment on how the solution changes with an increase in the number of nodes.

Solution 1

import numpy as np
from scipy.optimize import fsolve
from scipy.integrate import odeint
import matplotlib.pyplot as plt

# final time
tf = 1.0

# solve with ODEINT (for comparison)
def model(x,t):
    u = 4.0
    return (-x**2 + u)/5.0
t = np.linspace(0,tf,20)
y0 = 0
y = odeint(model,y0,t)
plt.figure(1)
plt.plot(t,y,'r-',label='ODEINT')

# ----------------------------------------------------
# Approach #1 - Write the model equations in Python
# ----------------------------------------------------
# define collocation matrices
def colloc(n):
    if (n==2):
        NC = np.array([[1.0]])
    if (n==3):
        NC = np.array([[0.75,-0.25], \
                       [1.00, 0.00]])
    if (n==4):
        NC = np.array([[0.436,-0.281, 0.121], \
                       [0.614, 0.064, 0.0461], \
                       [0.603, 0.230, 0.167]])
    if (n==5):
        NC = np.array([[0.278, -0.202, 0.169, -0.071], \
                       [0.398,  0.069, 0.064, -0.031], \
                       [0.387,  0.234, 0.278, -0.071], \
                       [0.389,  0.222, 0.389,  0.000]])
    if (n==6):
        NC = np.array([[0.191, -0.147, 0.139, -0.113, 0.047],
                       [0.276,  0.059, 0.051, -0.050, 0.022],
                       [0.267,  0.193, 0.252, -0.114, 0.045],
                       [0.269,  0.178, 0.384,  0.032, 0.019],
                       [0.269,  0.181, 0.374,  0.110, 0.067]])
    return NC

# define collocation points from Lobatto quadrature
def tc(n):
    if (n==2):
        time = np.array([0.0,1.0])
    if (n==3):
        time = np.array([0.0,0.5,1.0])
    if (n==4):
        time = np.array([0.0, \
                         0.5-np.sqrt(5)/10.0, \
                         0.5+np.sqrt(5)/10.0, \
                         1.0])
    if (n==5):
        time = np.array([0.0,0.5-np.sqrt(21)/14.0, \
                         0.5,0.5+np.sqrt(21)/14.0, 1])
    if (n==6):
        time = np.array([0.0, \
                         0.5-np.sqrt((7.0+2.0*np.sqrt(7.0))/21.0)/2.0, \
                         0.5-np.sqrt((7.0-2.0*np.sqrt(7.0))/21.0)/2.0, \
                         0.5+np.sqrt((7.0-2.0*np.sqrt(7.0))/21.0)/2.0, \
                         0.5+np.sqrt((7.0+2.0*np.sqrt(7.0))/21.0)/2.0, \
                         1.0])
    return time*tf

# solve with SciPy fsolve
def myFunction(z,*param):
    n = param[0]
    m = param[1]
    # rename z as x and xdot variables
    x = np.empty(n-1)
    xdot = np.empty(n-1)
    x[0:n-1] = z[0:n-1]
    xdot[0:n-1] = z[n-1:m]

    # initial condition (x0)
    x0 = 0.0
    # input parameter (u)
    u = 4.0
    # final time
    tn = tf

    # function evaluation residuals
    F = np.empty(m)
    # nonlinear differential equations at each node
    # 5 dx/dt = -x^2 + u
    F[0:n-1] = 5.0 * xdot[0:n-1] + x[0:n-1]**2 - u
    # collocation equations
    # tn * NC * xdot = x - x0
    NC = colloc(n)
    F[n-1:m] = tn * np.dot(NC,xdot) - x + x0 * np.ones(n-1)
    return F

sol_py = np.empty(5) # store 5 results
for i in range(2,7):
    n = i
    m = (i-1)*2
    zGuess = np.ones(m)
    z = fsolve(myFunction,zGuess,args=(n,m))
    # add to plot
    yc = np.insert(z[0:n-1],0,0)
    plt.plot(tc(n),yc,'o',markersize=10)
    # store just the last x[n] value
    sol_py[i-2] = z[n-2]

# ----------------------------------------------------
# Approach #2 - Write model in APMonitor and let
#   modeling language create the collocation equations
# ----------------------------------------------------
# load APM package
from APMonitor.apm import *

s = 'https://byu.apmonitor.com'
a = 'node_test'

fid = open('collocation.apm','w')
# write model
fid.write('Parameters         \n')
fid.write(' u = 4             \n')
fid.write('Variables          \n')
fid.write(' x = 0             \n')
fid.write('Equations          \n')
fid.write(' 5 * $x = -x^2 + u \n')
# close file
fid.close()

fid = open('collocation.csv','w')
# write data file
fid.write('time \n')
fid.write('0 \n')
fid.write(str(tf)+'\n')
# close file
fid.close()

sol_apm = np.empty(5) # store 5 results
i = 0
for nodes in range(2,7):
    apm(s,a,'clear all') # clear prior application
    apm_load(s,a,'collocation.apm') # load model
    csv_load(s,a,'collocation.csv') # load data
    apm_option(s,a,'nlc.imode',4)   # imode = 4, simulation
    apm_option(s,a,'nlc.nodes',nodes) # nodes (2-6)
    apm(s,a,'solve') # solve problem
    y = apm_sol(s,a) # retrieve solution
    sol_apm[i] = y['x'][-1] # store solution (last point)
    i += 1

# print the solutions
print(sol_py)
print(sol_apm)

# show plot
plt.ylabel('x(t)')
plt.xlabel('time')
plt.show()

from __future__ import division
import numpy as np
from scipy.optimize import fsolve
from scipy.integrate import odeint
import matplotlib.pyplot as plt

# final time
tf = 1.0

# solve with ODEINT (for comparison)
def model(x,t):
    u = 4.0
    return (-x**2 + u)/5.0
t = np.linspace(0,tf,20)
y0 = 0
y = odeint(model,y0,t)
plt.figure(1)
plt.plot(t,y,'r-',label='ODEINT')

# ----------------------------------------------------
# Approach #1 - Write the model equations in Python
# ----------------------------------------------------
# define collocation matrices
def colloc(n):
    if (n==2):
        NC = np.array([[1.0]])
    if (n==3):
        NC = np.array([[0.75,-0.25], \
                       [1.00, 0.00]])
    if (n==4):
        NC = np.array([[0.436,-0.281, 0.121], \
                       [0.614, 0.064, 0.0461], \
                       [0.603, 0.230, 0.167]])
    if (n==5):
        NC = np.array([[0.278, -0.202, 0.169, -0.071], \
                       [0.398,  0.069, 0.064, -0.031], \
                       [0.387,  0.234, 0.278, -0.071], \
                       [0.389,  0.222, 0.389,  0.000]])
    if (n==6):
        NC = np.array([[0.191, -0.147, 0.139, -0.113, 0.047],
                       [0.276,  0.059, 0.051, -0.050, 0.022],
                       [0.267,  0.193, 0.252, -0.114, 0.045],
                       [0.269,  0.178, 0.384,  0.032, 0.019],
                       [0.269,  0.181, 0.374,  0.110, 0.067]])
    return NC

# define collocation points from Lobatto quadrature
def tc(n):
    if (n==2):
        time = np.array([0.0,1.0])
    if (n==3):
        time = np.array([0.0,0.5,1.0])
    if (n==4):
        time = np.array([0.0, \
                         0.5-np.sqrt(5)/10.0, \
                         0.5+np.sqrt(5)/10.0, \
                         1.0])
    if (n==5):
        time = np.array([0.0,0.5-np.sqrt(21)/14.0, \
                         0.5,0.5+np.sqrt(21)/14.0, 1])
    if (n==6):
        time = np.array([0.0, \
                         0.5-np.sqrt((7.0+2.0*np.sqrt(7.0))/21.0)/2.0, \
                         0.5-np.sqrt((7.0-2.0*np.sqrt(7.0))/21.0)/2.0, \
                         0.5+np.sqrt((7.0-2.0*np.sqrt(7.0))/21.0)/2.0, \
                         0.5+np.sqrt((7.0+2.0*np.sqrt(7.0))/21.0)/2.0, \
                         1.0])
    return time*tf

# solve with SciPy fsolve
def myFunction(z,*param):
    n = param[0]
    m = param[1]
    # rename z as x and xdot variables
    x = np.empty(n-1)
    xdot = np.empty(n-1)
    x[0:n-1] = z[0:n-1]
    xdot[0:n-1] = z[n-1:m]

    # initial condition (x0)
    x0 = 0.0
    # input parameter (u)
    u = 4.0
    # final time
    tn = tf

    # function evaluation residuals
    F = np.empty(m)
    # nonlinear differential equations at each node
    # 5 dx/dt = -x^2 + u
    F[0:n-1] = 5.0 * xdot[0:n-1] + x[0:n-1]**2 - u
    # collocation equations
    # tn * NC * xdot = x - x0
    NC = colloc(n)
    F[n-1:m] = tn * np.dot(NC,xdot) - x + x0 * np.ones(n-1)
    return F

sol_py = np.empty(5) # store 5 results
for i in range(2,7):
    n = i
    m = (i-1)*2
    zGuess = np.ones(m)
    z = fsolve(myFunction,zGuess,args=(n,m))
    # add to plot
    yc = np.insert(z[0:n-1],0,0)
    plt.plot(tc(n),yc,'o',markersize=10,label='Nodes = '+str(i))
    # store just the last x[n] value
    sol_py[i-2] = z[n-2]
plt.legend(loc='best')

# ----------------------------------------------------
# Approach #2 - Write model in APMonitor and let
#   modeling language create the collocation equations
# ----------------------------------------------------
# load GEKKO
from gekko import GEKKO

sol_apm = np.empty(5) # store 5 results
i = 0
for nodes in range(2,7):
    m = GEKKO()

    u = m.Param(value=4)
    x = m.Var(value=0)
    m.Equation(5*x.dt() == -x**2 + u)

    m.time = [0,tf]

    m.options.imode = 4
    m.options.time_shift = 0
    m.options.nodes = nodes

    m.solve() # solve problem
    sol_apm[i] = x.value[-1] # store solution (last point)
    i += 1

# print the solutions
print(sol_py)
print(sol_apm)

# show plot
plt.ylabel('x(t)')
plt.xlabel('time')
plt.show()

Exercise 2

Compare orthogonal collocation on finite elements with 3 nodes with a numerical integrator (e.g. ODE15s in MATLAB or ODEINT in Python). Calculate the error at each of the solution points for the equation (same as for Exercise 1):

 5 dx/dt = -x2 + u

Solution 2



References

  1. Hedengren, J. D. and Asgharzadeh Shishavan, R., Powell, K.M., and Edgar, T.F., Nonlinear Modeling, Estimation and Predictive Control in APMonitor, Computers & Chemical Engineering, Volume 70, pg. 133–148, 2014. Available at: ScienceDirect or ResearchGate
  2. Cizniar, M., Salhi, D., Fikar, M., and Latifi, M.A., A Matlab Package for Orthogonal Collocations on Finite Elements in Dynamic Optimization, 15th Int. Conference Process Control, June 7-10, 2015. Article
  3. Renfro, J., Morshedi, A., Asbjornsen, O., Simultaneous Optimization and Solution of Systems Described by Differential/Algebraic Equations, Computers & Chemical Engineering, Volume 11, Number 5, pp. 503-517, 1987.
  4. Finlayson, B., Orthogonal Collocation on Finite Elements for PDE Discretization and Solution
  5. Biegler, L.T., Solution of Dynamic Optimization Problems by Successive Quadratic Programming and Orthogonal Collocation, Computers & Chemical Engineering, Volume 8, Number 3/4, pp. 243-248, 1984.
  6. Kameswaran, S., Biegler, L.T., Convergence rates for direct transcription of optimal control problems using collocation at Radau points, Computational Optimization and Applications, 41 (1), pp. 81-126, 2008, DOI: 10.1007/s10589-007-9098-9.

Discussion Questions

Bring written answers to class or test them against an AI tutor - make it grade you, not lecture you.

  1. A colleague claims "more collocation nodes is always better." When is that false, and what happens to the NLP size and conditioning as nodes increase?
  2. The collocation solution matches the true solution at the nodes but is a polynomial in between. What kinds of dynamics (stiff transients, discontinuous inputs) does a single low-order polynomial represent poorly, and what is the remedy within one finite element vs across elements?
  3. Why does simultaneous collocation succeed on open-loop unstable systems where single shooting fails? Consider what an integrator does with a small error in an unstable mode over a long horizon, and contrast with the state values being decision variables bounded at every node.
  4. Simultaneous methods are sometimes called "infeasible path" methods: the model equations are not satisfied until the solver converges. When is that a feature, and when does it bite (intermediate answers unusable, infeasible final status)?

Generative AI Learning

Use these prompts after completing the collocation exercises. Do the hand derivation yourself first - it is the point of the assignment.

"Act as a member of my graduate qualifying exam committee on numerical methods for dynamic optimization. Probe me, one question at a time, on: how orthogonal collocation on finite elements converts a DAE into an NLP, what the collocation matrix relates (derivatives to state values at Lobatto or Radau points), why collocation is preferred over single shooting for unstable or highly constrained systems, and how solution accuracy changes with the number of nodes vs the number of elements. Push follow-up questions when my answers are shallow. End with a pass/fail-style assessment and a list of gaps."
"I derived the collocation equations by hand for 5 dx/dt = -x^2 + u with x(0)=0, u=4 on t in [0,1] using {N} nodes, and got x(1) = {your value}. Do NOT re-derive first. Audit my attached derivation step by step: the node locations, the collocation matrix, and the nonlinear algebraic system I solved. Then compare my x(1) against the analytic solution x(t) = 2 tanh(2t/5) and ask me to explain the error trend as I increase from 2 to 6 nodes before you explain it."

Tip: The exact solution of the exercise ODE is $$x(t)=2\,\tanh(2t/5)$$, so $$x(1)=2\tanh(0.4)\approx 0.760$$ - verify your discretization against it before trusting any solver output.

"Build the collocation matrix for three Radau points on one finite element, then use it to solve 5 dx/dt = -x^2 + u with x(0) = 0 and u = 4 on one element of length 1. Show the matrix, the three algebraic equations and x(1)."

Check the answer: Check that each row of the matrix sums to its point (0.155, 0.645, 1), and compare x(1) with 2 tanh(0.4) = 0.760. A matrix whose rows do not sum to the points is wrong, whatever name the assistant gives it.

What to Turn In

Submit a short report (PDF, 1-2 pages) that curates your results into a demonstration of what you learned. You may use Generative AI to help write the report, but you must guide it to the correct derivations, justifications, and assumptions. Answer these questions:

  1. Show your hand derivation of the collocation equations for one node count, and tabulate x(1) for 2-6 nodes with the error against the analytic value 2 tanh(2/5).
  2. Include the comparison of 3-node collocation vs a sequential integrator (ODEINT) at each time point. Where is the largest error and why there?
  3. From the qualifying-exam prompt: which question exposed a gap, and what is your corrected answer on why collocation beats shooting for an unstable system?
  4. From the audit: did the AI find a real defect in your derivation, a spurious one, or none - and how did you verify which?

Course Information

TCLab

Project

Applications

Advanced Control Exercises

Exams

Modeling

Machine Learning

Estimation

Control

Reinforcement Learning

Related Courses

Admin