3.10. A SIR epidemic model#

3.10.1. Question:#

Simulate the step response of the SIR epidemic model using an ODE solver in Python.

3.10.2. Mathematical model:#

Mathematical SIR model equation

3.10.3. Solution: Transfer function model: #

3.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 linearize 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)\):

(3.60)#\[\begin{align} \dot x_1(t) &=& g_1(x_1(t), \ldots,x_n(t),u_1(t), \ldots,u_m(t)) \\ \vdots \\ \dot x_n(t) &=& g_n(x_1(t), \ldots,x_n(t),u_1(t), \ldots,u_m(t )) \end{align}\]

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

(3.61)#\[\begin{align} \dot x_1(t) &= g_1(x_1(t), \ldots,x_n(t),u_1(t), \ldots,u_m(t)) \\ &\approx g_1(x_{1}^0,\ldots,x_{n}^0,u_{1}^0,\ldots,u_{m}^0) + \left. \frac{\partial g_1}{\partial x_1} \right\|_{x=x_{1}^0\ldots,x_{n}^0,u=u_{1}^0, \ldots , u_{m}^0} (x_1(t)-x_{1}^0) + \dots + \left. \frac{\partial g_1}{\partial x_n} \right\|_{x=x_{1}^0, \ldots,x_{n}^0,u=u_{1}^0, \ldots , u_{m}^0} (x_n(t)-x_{n}^0) \\ & \ + \left. \frac{\partial g_1}{\partial u_1} \right\|_{x=x_{1}^0, \ldots,x_{n}^0,u_{1}^0, \ldots , u_{m}^0} (x_1(t)-u_{1}^0) + \dots + \left. \frac{\partial g_1}{\partial u_m} \right\|_{x=x_{1}^0, \ldots,x_{n}^0,u=u_{1}^0, \ldots , u_{m}^0} (u_m(t)-u_{m}^0) \\ & \vdots \\ \dot x_n(t) &= g_n(x_1(t), \ldots,x_n(t),u_1(t), \ldots,u_m(t)) \\ &\approx g_n(x_{1}^0,\ldots,x_{n}^0,u_{1}^0,\ldots,u_{m}^0) + \left. \frac{\partial g_n}{\partial x_1} \right\|_{x=x_{1}^0\ldots,x_{n}^0,u_{1}^0, \ldots , u_{m}^0} (x_1(t)-x_{1}^0) + \dots + \left. \frac{\partial g_n}{\partial x_n} \right\|_{x=x_{1}^0, \ldots,x_{n}^0,u=u_{1}^0, \ldots , u_{m}^0} (x_n(t)-x_{n}^0) \\ & \ + \left. \frac{\partial g_n}{\partial u_1} \right\|_{x=x_{1}^0, \ldots,x_{n}^0,u=u_{1}^0, \ldots , u_{m}^0} (x_1(t)-u_{1}^0) + \dots + \left. \frac{\partial g_n}{\partial u_m} \right\|_{x=x_{1}^0, \ldots,x_{n}^0,u=u_{1}^0, \ldots , u_{m}^0} (u_m(t)-u_{m}^0) \end{align}\]

When we transform the variables to introduce new state variables:

(3.62)#\[\begin{align} x'_1(t) &= x_1(t)-x_{1}^0\\ &\vdots \\ x'_n(t) &= x_n(t)-x_{n}^0 \end{align}\]

and for the input variables

(3.63)#\[\begin{align} u'_1 &= u_1(t)-u_{1}^0\\ &\vdots \\ u'_m &= u_m(t)-u_{m}^0. \end{align}\]

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:

(3.64)#\[\begin{align} x'^0_1 &= g_1(x_{1}^0,\ldots,x_{n}^0,u_{1}^0,\ldots,u_{m}^0) \\ &\vdots \\ x'^0_n &= g_n(x_{1}^0,\ldots,x_{n}^0,u_{1}^0,\ldots,u_{m}^0). \end{align}\]

When we then substitute the state derivative by

(3.65)#\[\begin{align} \dot x'_1(t) &= \dot x_1(t)-\dot x'^0_{1}\\ &\vdots \\ \dot x'_n(t) &= \dot x_n(t)-\dot x'^0_{n} \end{align}\]

we obtain a set of linear differential equations without an offset

(3.66)#\[\begin{align} \dot x'_1(t) &\approx \left. \frac{\partial g_1}{\partial x_1} \right\|_{x=x_{1}^0\ldots,x_{n}^0,u_{1}^0, \ldots , u_{m}^0} x'_1(t) + \dots + \left. \frac{\partial g_1}{\partial x_n} \right\|_{x=x_{1}^0, \ldots,x_{n}^0,u_{1}^0, \ldots , u_{m}^0} x'_n(t) \\ & + \left. \frac{\partial g_1}{\partial u_1} \right\|_{x=x_{1}^0, \ldots,x_{n}^0,u_{1}^0, \ldots , u_{m}^0} u'_1(t) + \dots + \left. \frac{\partial g_1}{\partial u_m} \right\|_{x=x_{1}^0, \ldots,x_{n}^0,u_{1}^0, \ldots , u_{m}^0} u'_m(t) \\ &\approx a_1^1 x'_1 + \ldots + a_n^1 x'_{n} + b_1^1 u'_1 + \ldots + b_m^1 u'_{m}\\ & \vdots \\ \dot x'_n(t) &\approx \left. \frac{\partial g_n}{\partial x_1} \right\|_{x=x_{1}^0\ldots,x_{n}^0,u_{1}^0, \ldots , u_{m}^0} x'_1(t) + \dots + \left. \frac{\partial g_n}{\partial x_n} \right\|_{x=x_{1}^0, \ldots,x_{n}^0,u_{1}^0, \ldots , u_{m}^0} x'_n(t) \\ & + \left. \frac{\partial g_n}{\partial u_1} \right\|_{x=x_{1}^0, \ldots,x_{n}^0,u_{1}^0, \ldots , u_{m}^0} u'_1(t) + \dots + \left. \frac{\partial g_n}{\partial u_m} \right\|_{x=x_{1}^0, \ldots,x_{n}^0,u_{1}^0, \ldots , u_{m}^0} u'_m(t) \\ &\approx a_1^n x'_1 + \ldots + a_n^n x'_{n} + b_1^n u'_1 + \ldots + b_m^n u'_{m} \end{align}\]

This set of linear differential equations can now be rewritten using a matrix notation:

(3.67)#\[\begin{align} \begin{bmatrix} \dot x'_1 \\ \vdots \\ \dot x'_n \end{bmatrix} &= \begin{bmatrix} a_1^1 & \dots& a_n^1 \\ \vdots& \vdots& \vdots \\ a_1^n& \dots& a_n^n \end{bmatrix} \begin{bmatrix} \dot x'_1 \\ \vdots \\ \dot x'_n \end{bmatrix} + \begin{bmatrix} b_1^1 & \dots& b_m^1 \\ \vdots& \vdots& \vdots \\ b_1^n& \dots& b_m^n \end{bmatrix} \begin{bmatrix} u'_1 \\ \vdots \\ u'_m \end{bmatrix} \\ &= A \begin{bmatrix} \dot x'_1 \\ \vdots \\ \dot x'_n \end{bmatrix} + B \begin{bmatrix} u'_1 \\ \vdots \\ u'_m \end{bmatrix} \label{eq:Lin_model} \end{align}\]

3.10.3.1.1. Determine the transfer function model:#

Based on the previous equation we can now specify a transfer function between a single input and a single output by taking all other in- and outputs values equal to zero. If we want to find the transfer function between \(x'_3(t)\) and \(u'_2(t)\) then we take all other input signals (\(u'_1(t), u'_3(t), \dots, u'_m(t)\)) equal to zero.
We can then create a transfer function model based on the previous result (\(\dot x' = A x' + Bu'\)):

(3.68)#\[\begin{align} H(s) &= \frac{X_3'(s)}{U'_2(s)} \end{align}\]

be eliminating all other states and input from equation \ref{eq:Lin_model}. Using a matrix library this elimination is performed by determining the inverse of a matrix.

(3.69)#\[\begin{align} s X'_1(s) &= a^1_1 X'_1(s) + \dots + a^1_n X'_n(s)+ b^1_2 U'(2) \\ \vdots &= \vdots \\ s X'_n(s) &= a^n_1 X'_1(s) + \dots + a^n_n X'_n(s)+ b^n_2 U'(2) \\ \end{align}\]

We can now solve this set of equation using some matrix operations:

\[\begin{split}\begin{bmatrix} \frac{X'_1(s)}{U_2(s)} \\ \vdots \\ \frac{X'_n(s)}{U_2(s)} \end{bmatrix} = \left ( sI - A \right )^{-1} \begin{bmatrix} b^1_2 \\ \vdots \\ b^n_2 \end{bmatrix} \end{split}\]

3.10.3.1.2. Simulate the transfer function model:#

3.10.3.2. Numerical solution:#

First load the necessary libraries into Python:

  • SymPy is a Python library for symbolic mathematics;

  • 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.

  • 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 sympy import Function, Matrix,symbols,solve,pprint,simplify,eye,Poly
from scipy import signal
import numpy as np 

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 in a matrix U

beta, gamma = symbols('beta gamma', Real=True)
U = Matrix ([ beta, gamma ])

Setup a vector dX consisting of all the differential equation in the ODE

(3.70)#\[\begin{align} \frac{ds}{dt} &= -\beta s i \\ \frac{di}{dt} &= \beta s i- \gamma i \\ \frac{dr}{dt} &=\gamma i \end{align}\]
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 transfer function model based on the previous result (\(\dot x' = A x' + Bu'\)) with for example as input β’(t) and as an output the number of infected I’(t):

(3.71)#\[\begin{align} H(s) &= \frac{I'(s)}{\beta'(s)} \end{align}\]

using equation (1) we can derive a transfer function if we assume \(x'_1(0)=\dots = x'_n(0) =0\) using the folowing equation:

(3.72)#\[\begin{align} s S(s) &= a^1_1 S(s) + a^1_2 I(s) + a^1_3 R(s) + b^1_3 \beta(s) \\ s I(s) &= a^2_1 S(s) + a^2_2 I(s) + a^2_3 R(s) + b^2_3 \beta(s) \\ s R(s) &= a^3_1 S(s) + a^3_2 I(s) + a^3_3 R(s) + b^3_3 \beta(s) \\ \end{align}\]

We can now solve this set of equation using some matrix operations:

\[\begin{split}\begin{bmatrix} \frac{S(s)}{\beta(s)} \\ \frac{I(s)}{\beta(s)} \\ \frac{R(s)}{\beta(s)} \end{bmatrix} = \left ( \begin{bmatrix} s & 0 & 0 \\ 0 & s & 0 \\ 0 & 0 & s \end{bmatrix} - \begin{bmatrix} a^1_1 & a^1_2 & a^1_3 \\ a^2_1 & a^2_2 & a^2_3 \\ a^3_1 & a^3_2 & a^3_3 \end{bmatrix} \right )^{-1} \begin{bmatrix} b^1_3 \\ b^2_3 \\ b^3_3 \end{bmatrix} \end{split}\]
s = symbols('s')
SIR =simplify((s*eye(3)-A).inv()*B[:,0]) #We take the first input (beta)
print(SIR[1]) # We take the second state as an output
n, d = SIR[1].as_numer_denom() # Take the second element in the list I(s)/β(s)
if s in n.free_symbols:
    num = Poly(n).all_coeffs()
    num = [float(item) for item in num] #convert all elements in the list to floating points
else:
    num = float(n) #Poly(n).all_coeffs() #collect the coefficients of the polynomial in s 

den = Poly(d).all_coeffs() #collect the coefficients of the polynomial in s
den = [float(item) for item in den] #convert all elements in the list to floating points
4.99975e-5/(1.0*s + 0.119047619047619)
H = signal.TransferFunction(num,den)
pprint(H)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
File /builds/fet-edu-em/control-systems-and-applications-t4scs2/course-material/modeling-and-simulation-book/venv/lib/python3.8/site-packages/sympy/core/cache.py:72, in __cacheit.<locals>.func_wrapper.<locals>.wrapper(*args, **kwargs)
     71 try:
---> 72     retval = cfunc(*args, **kwargs)
     73 except TypeError as e:

TypeError: unhashable type: 'numpy.ndarray'

During handling of the above exception, another exception occurred:

SympifyError                              Traceback (most recent call last)
Cell In[13], line 2
      1 H = signal.TransferFunction(num,den)
----> 2 pprint(H)

File /builds/fet-edu-em/control-systems-and-applications-t4scs2/course-material/modeling-and-simulation-book/venv/lib/python3.8/site-packages/sympy/printing/pretty/pretty.py:2917, in pretty_print(expr, **kwargs)
   2874 def pretty_print(expr, **kwargs):
   2875     """Prints expr in pretty form.
   2876 
   2877     pprint is just a shortcut for this function.
   (...)
   2915         Can be "i" (default) or "j".
   2916     """
-> 2917     print(pretty(expr, **kwargs))

File /builds/fet-edu-em/control-systems-and-applications-t4scs2/course-material/modeling-and-simulation-book/venv/lib/python3.8/site-packages/sympy/printing/printer.py:372, in _PrintFunction.__call__(self, *args, **kwargs)
    371 def __call__(self, *args, **kwargs):
--> 372     return self.__wrapped__(*args, **kwargs)

File /builds/fet-edu-em/control-systems-and-applications-t4scs2/course-material/modeling-and-simulation-book/venv/lib/python3.8/site-packages/sympy/printing/pretty/pretty.py:2869, in pretty(expr, **settings)
   2866 uflag = pretty_use_unicode(use_unicode)
   2868 try:
-> 2869     return pp.doprint(expr)
   2870 finally:
   2871     pretty_use_unicode(uflag)

File /builds/fet-edu-em/control-systems-and-applications-t4scs2/course-material/modeling-and-simulation-book/venv/lib/python3.8/site-packages/sympy/printing/pretty/pretty.py:66, in PrettyPrinter.doprint(self, expr)
     65 def doprint(self, expr):
---> 66     return self._print(expr).render(**self._settings)

File /builds/fet-edu-em/control-systems-and-applications-t4scs2/course-material/modeling-and-simulation-book/venv/lib/python3.8/site-packages/sympy/printing/printer.py:331, in Printer._print(self, expr, **kwargs)
    329     printmethod = getattr(self, printmethodname, None)
    330     if printmethod is not None:
--> 331         return printmethod(expr, **kwargs)
    332 # Unknown object, fall back to the emptyPrinter.
    333 return self.emptyPrinter(expr)

File /builds/fet-edu-em/control-systems-and-applications-t4scs2/course-material/modeling-and-simulation-book/venv/lib/python3.8/site-packages/sympy/printing/pretty/pretty.py:991, in PrettyPrinter._print_TransferFunction(self, expr)
    989 if not expr.num == 1:
    990     num, den = expr.num, expr.den
--> 991     res = Mul(num, Pow(den, -1, evaluate=False), evaluate=False)
    992     return self._print_Mul(res)
    993 else:

File /builds/fet-edu-em/control-systems-and-applications-t4scs2/course-material/modeling-and-simulation-book/venv/lib/python3.8/site-packages/sympy/core/cache.py:76, in __cacheit.<locals>.func_wrapper.<locals>.wrapper(*args, **kwargs)
     74     if not e.args or not e.args[0].startswith('unhashable type:'):
     75         raise
---> 76     retval = func(*args, **kwargs)
     77 return retval

File /builds/fet-edu-em/control-systems-and-applications-t4scs2/course-material/modeling-and-simulation-book/venv/lib/python3.8/site-packages/sympy/core/power.py:123, in Pow.__new__(cls, b, e, evaluate)
    120 if evaluate is None:
    121     evaluate = global_parameters.evaluate
--> 123 b = _sympify(b)
    124 e = _sympify(e)
    126 # XXX: This can be removed when non-Expr args are disallowed rather
    127 # than deprecated.

File /builds/fet-edu-em/control-systems-and-applications-t4scs2/course-material/modeling-and-simulation-book/venv/lib/python3.8/site-packages/sympy/core/sympify.py:514, in _sympify(a)
    488 def _sympify(a):
    489     """
    490     Short version of :func:`~.sympify` for internal usage for ``__add__`` and
    491     ``__eq__`` methods where it is ok to allow some things (like Python
   (...)
    512 
    513     """
--> 514     return sympify(a, strict=True)

File /builds/fet-edu-em/control-systems-and-applications-t4scs2/course-material/modeling-and-simulation-book/venv/lib/python3.8/site-packages/sympy/core/sympify.py:454, in sympify(a, locals, convert_xor, strict, rational, evaluate)
    451         return sympify(int(a))
    453 if strict:
--> 454     raise SympifyError(a)
    456 if iterable(a):
    457     try:

SympifyError: SympifyError: array([1.        , 0.11904762])

Plot the response of the state space system to a unit step input for β (contact rate)

T=np.linspace(0,100,100)
X0=[0]
T ,yout = signal.step(H,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 ODE result with transfer function result:

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