Simulation of Dynamic Systems

Learning outcomes

  • Derive the stability condition of explicit Euler, |1 + hλ| ≤ 1, and the largest stable step for a given eigenvalue.
  • Explain why a stiff model needs an implicit or simultaneous method.
  • Compute the eigenvalues of a model linearized at a steady state and read its time constants from them.

Book chapter: Process Dynamics, Modeling, and Identification (Volume 1), Chapter 2, Gravity-Drained Tank Laboratory for Level Loops With a Moving Time Constant (PDF).
Practice in 15 minutes: 1 · A Physics-Based Model With a Moving Time Constant, 21 · MPC on the Unstable Branch of a Nonlinear Reactor
Model: Physics-based state-space and nonlinear models, from the 747 on this page to a gravity-drained tank.
Decision: The step size and method, chosen so the simulation is accurate and stable; the later optimizer relies on the same discretization.
Learning: Linearization at an operating point gives the local model that identification estimates from data.

Simulation of dynamic systems is the process of finding a numerical solution to a set of differential and algebraic equations (DAEs) with given initial conditions (x0). A mathematical expression of an Initial Value Problem (IVP) is shown below.

 0 = f(dx/dt,x,p)
 0 < g(dx/dt,x,p)
 Given x0 and p

The DAE can be solved with a variety of analytic or numeric methods. Analytic approaches are possible for simple systems such as systems with one or two equations. Numeric methods are used with more complicated systems but these methods have approximation errors that may deviate from the exact solution. A first step in model development is to draw a schematic, list the assumptions, and write the differential and algebraic equations that describe the system.

Two numerical methods reviewed are sequential and simultaneous simulation techniques.

Sequential Simulation

Sequential simulation methods take successive time steps in the simulation horizon and often refine the size of each step to meet a specified error tolerance. Euler's method is the most basic method for sequential simulation while other methods generally offer improved accuracy and therefore allow larger step sizes.

Stiffness and Step Size

Explicit Euler takes a step of length `h` with the derivative at the start of the step:

$$x_{k+1} = x_k + h\, f(x_k, u_k)$$

For the test equation `dx/dt = \lambda x` this gives `x_{k+1} = (1 + h\lambda)\, x_k`, which stays bounded only when

$$|1 + h\lambda| \le 1$$

For a real eigenvalue `\lambda < 0` the step must satisfy `h \le 2/|\lambda|`. Implicit Euler uses the derivative at the end of the step, `x_{k+1} = x_k + h\, f(x_{k+1}, u_{k+1})`, which gives `x_{k+1} = x_k/(1 - h\lambda)` and is stable for every `h` when `\mathrm{Re}\,\lambda < 0`. A model is stiff when its eigenvalues are far apart, `\max_i |\mathrm{Re}\,\lambda_i| \gg \min_i |\mathrm{Re}\,\lambda_i|`: the fastest mode limits an explicit step long after it has died out, while the slowest mode sets how long the simulation must run. Implicit integrators (BDF, as in ode15s) and simultaneous collocation solve a nonlinear system each step and take steps sized for accuracy, not stability.

Linearization and Time Constants

Near a steady state `(x_s, u_s)` a nonlinear model `dx/dt = f(x, u)` behaves like its linearization in the deviations `\delta x = x - x_s` and `\delta u = u - u_s`:

$$\begin{gathered} \frac{d\,\delta x}{dt} = A\,\delta x + B\,\delta u, \\ A = \left.\frac{\partial f}{\partial x}\right|_{x_s, u_s}, \\ B = \left.\frac{\partial f}{\partial u}\right|_{x_s, u_s}, \\ \tau_i = -\frac{1}{\mathrm{Re}\,\lambda_i(A)} \end{gathered}$$

For a gravity-drained tank with cross-section `A_c` and outlet coefficient `c_v`, the single eigenvalue moves with the level:

$$A_c \frac{dh}{dt} = q_{in} - c_v \sqrt{h} \quad\Rightarrow\quad \lambda = -\frac{c_v}{2 A_c \sqrt{h_s}}, \qquad \tau = \frac{2 A_c \sqrt{h_s}}{c_v}$$

The tank is slower when full. A linear model identified at one level is too fast or too slow at another, which is the subject of the Tank Level Control Studio app.

Simultaneous Simulation

Simultaneous simulation methods are used to converge all of the state variable predictions together instead of one step at a time. Orthogonal collocation on finite elements is a popular method to convert the DAE into a Nonlinear Programming (NLP) problem for solution by efficient solvers.

 0 = f(x,p)
 0 < g(x,p)
 Given x0 and p

Further details on orthogonal collocation are provided at the following references.

  • Nonlinear Modeling, Estimation and Predictive Control in APMonitor, Hedengren, J. D. and Asgharzadeh Shishavan, R., Powell, K.M., and Edgar, T.F., Computers and Chemical Engineering, Volume 70, pg. 133–148, 2014. Available at: https://dx.doi.org/10.1016/j.compchemeng.2014.04.013

Exercise

This exercise involves the simulation of a Boeing 747 airplane at a cruising altitude of 40,000 ft. In this application1, a model of the process is desired to relate the elevator (e) and thrust (t) to the airspeed and climb rate. The model equations are shown below in state space form that relates elevator angle in centi-radians and thrust to four states including airspeed in the horizontal direction (u - u w), airspeed in the vertical direction (w - w w), rotation of the aircraft (q), and angle of the aircraft (theta).

$$\begin{bmatrix} \dot{u} \\ \dot{w} \\ \dot{q} \\ \dot{\theta} \\ \end{bmatrix} = \begin{bmatrix} -0.003 & 0.039 & 0 & -0.322 \\ -0.065 & -0.319 & 7.74 & 0 \\ 0.020 & -0.101 & -0.429 & 0 \\ 0 & 0 & 1 & 0 \\ \end{bmatrix} \begin{bmatrix} u - u_w \\ w - w_w \\ q \\ \theta \\ \end{bmatrix} + \begin{bmatrix} 0.010 & 1 \\ -0.18 & -0.04 \\ -1.16 & 0.598 \\ 0 & 0 \\ \end{bmatrix} \begin{bmatrix} e \\ t \\ \end{bmatrix}$$

$$\begin{bmatrix} y_1 \\ y_2 \\ \end{bmatrix} = \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & -1 & 0 & 7.74 \\ \end{bmatrix} \begin{bmatrix} u - u_w \\ w - w_w \\ q \\ \theta \\ \end{bmatrix}$$

The wind speeds are given in the horizontal (u w) and vertical (w w) directions with a nominal velocity of the aircraft of u0=774 ft/sec (0.8 Mach speed). The output y1 is the air speed and y2 is the climb rate.

Simulate step responses of the aircraft with respect to the elevator angle and thrust. Design a model predictive controller to respond to set point changes in the air speed and climb rate of the aircraft. Explain the coordinated movement of the manipulated variables to achieve the desired set points of the controlled variables.

Solution

from gekko import GEKKO
import numpy as np

## Linear model of a Boeing 747
#  Level flight at 40,000 ft elevation
#  Velocity at 774 ft/sec (0.80 Mach)

# States
#  u - uw (ft/sec) - horizontal velocity - horizontal wind
#  w - ww (ft/sec) - vertical velocity - vertical wind
#  q (crad/sec) - angular velocity
#  theta (crad) - angle from horizontal
# note: crad = 0.01 rad

# Inputs
#  e - elevator
#  t - throttle

# Outputs
#  u - uw (ft/sec) - horizontal airspeed
#  hdot = -w + u0 * theta with u0 = 774 ft/sec


A = np.array([[-.003, 0.039, 0, -0.322],
              [-0.065, -0.319, 7.74, 0],
              [0.020, -0.101, -0.429, 0],
              [0, 0, 1, 0]])

B = np.array([[0.01, 1],
              [-0.18, -0.04],
              [-1.16, 0.598],
              [0, 0]])

C = np.array([[1, 0, 0, 0],
              [0, -1, 0, 7.74]])

#%% Build GEKKO State Space model
m = GEKKO()
x,y,u = m.state_space(A,B,C,D=None)

m.time = [0, 0.1, 0.2, 0.4, 1, 1.5, 2, 3, 4, 5, 6, 7, 8, 10, 12, 15]
m.options.imode = 6
m.options.nodes = 3

## MV tuning
# lower and upper bounds for elevator pitch
# lower and upper bounds for thrust
# delta MV movement cost
for i in range(len(u)):
    u[i].lower = -5
    u[i].upper = 5
    u[i].dcost = 1
    u[i].status = 1

## CV tuning
# tau = first order time constant for trajectories
y[0].tau = 5
y[1].tau = 8
# tr_init = 0 (dead-band)
#         = 1 (first order trajectory)
#         = 2 (first order traj, re-center with each cycle)
y[0].tr_init = 2
y[1].tr_init = 2
# targets (dead-band needs upper and lower values)
# SPHI = upper set point
# SPLO = lower set point
y[0].sphi= -8.5
y[0].splo= -9.5
y[1].sphi= 5.4
y[1].splo= 4.6

y[0].status = 1
y[1].status = 1


m.solve()

# get additional solution information (trajectories)
import json
with open(m.path+'//results.json') as f:
    results = json.load(f)
# get internal GEKKO variable names
air_speed = y[0].name
climb_rate = y[1].name

#%% plot results
import matplotlib.pyplot as plt
plt.figure(1)
plt.subplot(311)
plt.plot(m.time,u[0],'b-',lw=2.0)
plt.plot(m.time,u[1],'g:',lw=2.0)
plt.legend(['Elevator','Thrust'])
plt.ylabel('MV Action')

plt.subplot(312)
plt.plot(m.time,y[0],'r-',lw=2.0)
plt.plot(m.time,results[air_speed+'.tr_hi'],'k:')
plt.plot(m.time,results[air_speed+'.tr_lo'],'k:')
plt.legend(['Air Speed','Upper Trajectory','Lower Trajectory'])
plt.ylabel('Air Speed')

plt.subplot(313)
plt.plot(m.time,y[1],'r-',lw=2.0)
plt.plot(m.time,results[climb_rate+'.tr_hi'],'k:')
plt.plot(m.time,results[climb_rate+'.tr_lo'],'k:')
plt.legend(['Climb Rate','Upper Trajectory','Lower Trajectory'])
plt.ylabel('Climb Rate')

plt.show()

Generative AI Learning

"For the 747 state-space model on this page, compute the eigenvalues of the A matrix, the time constant of each mode, and the largest explicit Euler step that stays stable. Then tell me whether the model is stiff."

Check the answer: Compute the eigenvalues yourself with numpy.linalg.eig and compare. For each complex pair, |1 + hλ| ≤ 1 gives h ≤ -2 Re(λ)/|λ|², and the smallest of these is the limit. An answer that uses h ≤ 2/|λ| for complex eigenvalues allows a step that is far too large; for the lightly damped slow mode the difference is more than a factor of 100.

References

  1. Camacho, E.F. and Bordons, C., Model Predictive Control, 2nd Edition, Advanced Textbooks in Control and Signal Processing, Springer, 2004.

Discussion Questions

  1. Sequential simulation adapts its step size to meet an error tolerance; simultaneous (collocation) simulation commits to a time grid up front. For a stiff system with a fast initial transient, what does each approach do well and badly - and which one silently loses accuracy rather than slowing down?
  2. In the 747 exercise, the MPC moves elevator and thrust together in ways a single-loop pilot (or PID pair) would not. What information does the multivariable model give the optimizer that makes coordinated moves optimal, and why does airspeed transiently move the "wrong" way when climb rate is commanded?
  3. A simulation with zero degrees of freedom is a square problem: equations = variables. What goes wrong, mathematically and diagnostically, when a model intended for simulation accidentally carries one extra degree of freedom?
  4. Modern guidance stacks (e.g., propulsive rocket landing) simulate the vehicle both sequentially (high-fidelity check) and simultaneously (inside the optimizer). Why do both, and what does agreement between the two actually certify?

Tip: Predict-then-verify prompt: "Before I simulate a step in {input} for {system}, here is my sketched prediction of every state: {describe}. Ask me two questions that test the physics behind the sketch, then after I paste the simulation, grade my prediction."

Course Information

TCLab

Project

Applications

Advanced Control Exercises

Exams

Modeling

Machine Learning

Estimation

Control

Reinforcement Learning

Related Courses

Admin