2.5. A simplified Cruise Control Model#
2.5.1. Question:#
Simulate the step response of the cruise control model equations using an ODE solver in Python.
2.5.2. Mathematical model:#
2.5.3. Solution: Numerical ODE simulation: #
2.5.3.1. Generic solution:#
The Python programming language can be used for numerical computing. This implies that every differential equation is solved by performing a numerical approximation instead of specifying a symbolic or algebraic solution (like in for example Maple). This way one is able to solve a set of non-linear differential equations that are impossible to solve with a symbolic solver.
A widely used numerical differential equation solver is solve_ivp that is available in the open source scipy Python library. solve_ivp can be used to solve a system of first order Ordinary Differential Equations (ODEs) \(\frac{d\mathbf{y}}{dt} = \mathbf{f}(t, \mathbf{y})\) when the initial value \(\mathbf{y}_0\) are provided. The first order ODE model is determined by
were t is a 1-dimensional independent time variable , y(t) is an N-dimensional vector-valued function (state), and an N-dimensional vector-valued function f(t, y(t)). The goal is to find y(t) approximately satisfying the differential equations, given an initial value \(\mathbf{y}(t_0)=\mathbf{y}_0\).
The solve_ivp function can be used in Python by executing following command:
scipy.integrate.solve_ivp(ODEFUN,[T0, TFINAL] , \(\mathbf{y}_0\), method=‘RK45’, t_eval=None, dense_output=False, events=None, vectorized=False, args=None, options)
ODEFUN is a function handle that specifies the system of differential equations \(\frac{d\mathbf{y}}{dt} = \mathbf{f}(t, \mathbf{y})\).solve_ivp integrates this system of differential equations \(\frac{d\mathbf{y}}{dt} = \mathbf{f}(t, \mathbf{y})\) from time T0 to TFINAL with initial conditions \(\mathbf{y}_0\). All other inputs are optional. More information about this command can be found here.
(Note that one can also use the scipy.integrate.ode, i.e. a generic interface class to numeric integrators)
2.5.3.2. Detailed solution:#
First load the necessary libraries into Python:
the solve_ivp function that numerically integrates a system of first order ODEs given an initial value,
the numpy library adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays.
import psutil
L = psutil.Process().parent().cmdline()
if any("jupyter-notebook" in string for string in L):
%matplotlib notebook
elif any("jupyter-labhub" in string for string in L):
%matplotlib widget
else:
%matplotlib inline
from scipy.integrate import solve_ivp
import numpy as np
Next we you need to declare the ODEFUN function to make it usable for your numerical solver.
The first order ODE model for the simplified cruise control model was specified previously
when we take \(\mathbf{y}(t) = \left [ \begin{array}{c} x(t)\\ v(t) \end{array} \right ]\) and \(u(t)=u(t)\) then we can specify the differential equation using an ODEFUN in Python:
def ODEFUN(t, y, m, b,u ):
x,v = y
dx = v
dv = -b/m*v + u/m
return [dx,dv]
where t represent the time, \(\mathbf{y}\) the time varying state vector and u is the input signal. The mass m and the viscous damping coefficient b are defined as parameter (not time-dependent!). We assume the parameter values for m and b are 1000 kg and 1000 N/(m/s):
m=1000 #kg,
b=1000 #N/(m/s)
For initial conditions, we assume the initial car position x(0) =0 and the intial velocity is v(0) = 0. The input force is a step function of 6000 N.
Then the vector of initial conditions (y0) and the input value \(u\) are equal to
y0=[0,0] #Initial position of 0 [m] and initial velocity of 0 [m/s]
u=6000 #unit step input force [N]
We specify an array with start and stop time (0 <= t <= 30 [sec]) of our simulated solution:
TSPAN = [0,30]
To solve the first order ODE model we need to call the solve_ivp function with as an input the previously specifed ODEFUN,TSPAN and the initial values for the y. The parameters m,b are handed over using the args argument (be aware the args option is only implemented within Scipy version >1.4! Update this version if necessary).
y = solve_ivp(ODEFUN, TSPAN, y0, args=(m,b,u), dense_output=True)
The optional input dense_output=True make the integrator interpolate between internal time steps using the polynomial approximation constructed by the integrator. So when you query the output from the integrator (as it generates it in time) between internal time steps, what it is really doing is interpolating between these time steps to get the output.
The returned output y is a bunch object of the ODEResult type with the following fields defined:
t: ndarray, shape (n_points,)
Time points.y: ndarray, shape (n, n_points)
Values of the solution at t.sol: OdeSolution or None
Found solution as OdeSolution instance; None if dense_output was set to False.
If we specify an array of 10000 discrete time steps between 0 and 10 seconds
t = np.linspace(0, 10, 10000)
then we can calculate the output of the solver for the previous defined discrete time steps (t) and collect them in two new array’s one for the position (x) and a second one for the velocity (v):
x,v = y.sol(t)
Finally we plot the resulted simulated postions (x) and velocities (v) as a function of time (t)
import matplotlib.pyplot as plt # Load the pyplot object from the matplotlib library
fig, axes = plt.subplots(nrows=1, ncols=2)
ax0, ax1 = axes.flatten()
ax0.plot(t, x, 'b', label='Car position') # plot the time signal and create a label for the legend
ax0.legend(loc='best') # position the legend at a minimal overlapping position
ax0.set(xlabel='t[s]', ylabel='Car position [m]') # label the y-axis
ax0.grid() # plot a grid
ax1.plot(t, v, 'b', label='Car speed') # plot the time signal and create a label for the legend
ax1.legend(loc='best') # position the legend at a minimal overlapping position
ax1.set(xlabel='t[s]', ylabel='Car spped [m]') # label the y-axis
ax1.grid() # plot a grid
fig.tight_layout()
plt.show() # show the plot