4.10. A SIR epidemic model#
4.10.1. Question:#
Simulate the step response of the SIR epidemic model using a state space model in Python.
4.10.2. Mathematical model:#
4.10.3. Solution: Transfer function model: #
4.10.3.1. Generic solution:#
Why do we prefer linear systems?
An important and necessary condition for a linear system is superposition. When a system at rest is subjected to an excitation \(x_1(t)\), it exhibits a response \(y_1(t)\) and if it is subjected to an excitation \(x_2(t)\), it provides a corresponding response \(y_2(t)\). For a linear system, it is fundamental that the excitation \(x_1(t)+x_2(t)\) corresponds with a response \(y_1(t)+y_2(t)\). This important characteristic is called superposition.
Furthermore, it is necessary that a magnitude scale factor is preserved by a linear system. Meaning that an input of \(\beta\) times \(x_1(t)\) results in an response of \(\beta\) times the \(y_1(t)\). This is called the property of homogenity.
How do we linerize a system?
The linearity of many mechanical and electrical systems can be assumed over a reasonable large range of the variables. Almost all physical systems become non-linear as the variables are increased without limitations. One can linearize non-linear elements assuming small signal conditions.
Consider a set of non-linear ordinary differential equation (ODE) where \(\dot x_1(t), \ldots, \dot x_n(t)\) are functions of the state variables \(x_1(t), \ldots, x_n(t)\) and input variables \(u_1(t), \ldots, u_m(t)\):
where \(g(\ldots)\) represent a generalized function.
To perform a linearization we first need to determine an operation point based on the context. For a controlled system this implies the desired control values and for a simulation this implies the assumed working point of the system.
If we assume a operation point as \(x_{1}^0\), \(\ldots\) , \(x_{n}^0\) and \(u_{1}^0\), \(\ldots\) , \(u_{m}^0\) , then a Taylor series expansion around this operation point can be specified
When we transform the variables to introduce new state variables:
and for the input variables
The linearization point should be achievable therefore when we feed the operation point to our set of differential equations, then a linearization point for the state derivatives can be specified:
When we then substitute the state derivative by
we obtain a set of linear differential equations without an offset
This set of linear differential equations can now be rewritten using a matrix notation:
4.10.3.1.1. Determine the state space model:#
The state space model is specified as:
The previous equation directly specifies the dynamic equation of the state space model (matrices A,B). The other matrices (C,D) are defined based on the required output of the system.
4.10.3.1.2. Simulate the state space model:#
4.10.3.2. Numerical solution:#
First load the necessary libraries into Python:
the solve_ivp function that numerically integrates a system of ordinary differential equations 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
The SciPy library is one of the core packages that make up the SciPy stack. It provides many user-friendly and efficient numerical routines, such as routines for numerical integration, interpolation, optimization, linear algebra, and statistics. The signal processing toolbox currently contains some filtering functions, a limited set of filter design tools, and a few B-spline interpolation algorithms for 1- and 2-D data.
CAS_lib is a module library with custom made functions for this course
from sympy import Function, Matrix,symbols,solve,pprint,simplify,eye,Poly
import numpy as np
from scipy import signal
from CAS_lib import minreal
Specify the time as a variable
t = symbols('t')
we need to declare all time variable functions S(t), I(t) and R(t)
s = Function('s')(t)
i = Function('i')(t)
r = Function('r')(t)
Define β and γ as two input variables and put them
beta, gamma = symbols('beta gamma', Real=True)
U = Matrix ([ beta, gamma ])
Setup a vector dX consisting of all the differential equation in the ODE
dX = Matrix ([-beta*s*i, beta*s*i - gamma*i, gamma*i ])
specify a vector X with the time variable functions
X = Matrix ([ s,i,r ])
Calculate the jacobian of dX with respect to the time variables defined in X
A_sym = dX.jacobian(X)
pprint(A_sym)
⎡-β⋅i(t) -β⋅s(t) 0⎤
⎢ ⎥
⎢β⋅i(t) β⋅s(t) - γ 0⎥
⎢ ⎥
⎣ 0 γ 0⎦
Calculate the jacobian of dX with respect to the time variables defined in U
B_sym = dX.jacobian(U)
pprint(B_sym)
⎡-i(t)⋅s(t) 0 ⎤
⎢ ⎥
⎢i(t)⋅s(t) -i(t)⎥
⎢ ⎥
⎣ 0 i(t) ⎦
Linearize the set of equations around a chosen (not stable!!) linearisation point \(s^0,i^0,r^0\):
# parameter values
N=20000 #Number of people in the population
R0 = 0 #Initial reproduction number
t_infective = 5.1 + 3.3 #exponential time constant of the growth of infections (~exp(t/t_infective}))
# Working point for number of infected and recovered individuals
i_0 = 1/N #initial fraction of infected
r_0 = 0.00 #initial fraction of recovered
s_0 = 1 - i_0 - r_0 #initial fraction of susceptibles
y0 = s_0, i_0, r_0
gamma_0 = 1/t_infective #rate of recovery from infections [1/day].
beta_0=R0*gamma
We take \(\beta = 0\) and \(\gamma^0= 1/t_{infective}\) and \(i^{0}= 1/2000\),\(r^0=0\) resuting in \(s^0=1-1/2000-0\).
We now substitute these values in our symbolic matrices A and B
A=A_sym.subs(i,i_0).subs(beta,beta_0).subs(gamma,gamma_0).subs(s,s_0)
pprint(A)
⎡0 0 0⎤
⎢ ⎥
⎢0 -0.119047619047619 0⎥
⎢ ⎥
⎣0 0.119047619047619 0⎦
B=B_sym.subs(i,i_0).subs(beta,beta_0).subs(gamma,gamma_0).subs(s,s_0)
pprint(B)
⎡-4.99975e-5 0 ⎤
⎢ ⎥
⎢4.99975e-5 -5.0e-5⎥
⎢ ⎥
⎣ 0 5.0e-5 ⎦
Create a state space model from A and B with the number of infected persons I(t) as an output
A = np.array(A, dtype=float) # change dtype of matrix to get ss2tf to work
B = np.array(B, dtype=float) # change dtype of matrix to get ss2tf to work
C = np.matrix([[0,1,0]]) # Select I(t) as an output!
D = np.matrix([[0,0]])
sys = signal.StateSpace(A,B,C,D)
num,den =signal.ss2tf(A,B,C,D,0) # take the first input =0 => beta
TF = signal.TransferFunction(num,den)
TF= minreal(TF) # Eliminate equal poles and zeros!!
print(TF)
print(sys)
TransferFunctionContinuous(
array([4.99975e-05]),
array([1. , 0.11904762]),
dt: None
)
StateSpaceContinuous(
array([[ 0. , 0. , 0. ],
[ 0. , -0.11904762, 0. ],
[ 0. , 0.11904762, 0. ]]),
array([[-4.99975e-05, 0.00000e+00],
[ 4.99975e-05, -5.00000e-05],
[ 0.00000e+00, 5.00000e-05]]),
matrix([[0, 1, 0]]),
matrix([[0, 0]]),
dt: None
)
/builds/fet-edu-em/control-systems-and-applications-t4scs2/course-material/modeling-and-simulation-book/venv/lib/python3.8/site-packages/scipy/signal/_filter_design.py:1746: BadCoefficients: Badly conditioned filter coefficients (numerator): the results may be meaningless
warnings.warn("Badly conditioned filter coefficients (numerator): the "
Plot the response of the state space system to a unit step input for β (contact rate)
T=np.linspace(0,10,100)
x0=[0]
T, yout = signal.step(TF,x0,T)
import matplotlib.pyplot as plt # Load the pyplot object from the matplotlib library
fig, ax0 = plt.subplots()
ax0.plot(T, yout, 'r', label='TR:Infected-I0"') # plot the time signal and create a label for the legend
ax0.plot(T, yout+i_0, 'b', label='TR:Infected"') # 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='Number of persons') # label the y-axis
ax0.grid() # plot a grid
plt.show() # show the plot
Compare state space model simulation with ODE:
from scipy.integrate import solve_ivp
import numpy as np
import matplotlib
# parameter values
R0 = 0 #Initial reproduction number
t_infective = 5.1 + 3.3 #exponential time constant of the growth of infections (~exp(t/t_infective}))
# initial number of infected and recovered individuals taken from working point!!
i_initial = 1/20000 #initial fraction of infected
r_initial = 0.00 #initial fraction of recovered
s_initial = 1 - i_initial - r_initial #initial fraction of susceptibles
y0 = s_initial, i_initial, r_initial
gamma = 1/t_infective #rate of recovery from infections [1/day].
beta = R0*gamma # rate constant associated with transmission of the infection [1/day]
N=20000
def ODEFUN(t, y, beta, gamma):
s, i, r = y
if t>0:
beta=1
dsdt = -beta * s * i
didt = beta * s * i - gamma * i
drdt = gamma * i
return dsdt, didt, drdt
TSPAN = [0,2000]
sol = solve_ivp(ODEFUN, TSPAN, y0, args=(beta,gamma), dense_output=True)
t = np.linspace(0, 3, 1000)
z = sol.sol(t)
s, i, r = z
import matplotlib.pyplot as plt # Load the pyplot object from the matplotlib library
fig, ax1 = plt.subplots()
ax1.plot(T, yout, 'r', label='TF:Infected-I0"') # plot the time signal and create a label for the legend
ax1.plot(T, yout+i_0, 'b', label='TF:Infected"') # plot the time signal and create a label for the legend
ax1.plot(t, i, 'g', label='ODE:Infected"') # 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='Number of persons') # label the y-axis
ax1.grid() # plot a grid
plt.show() # show the plot