2.8. A SIR epidemic model#
2.8.1. Question:#
Simulate the step response of the SIR epidemic model using an ODE solver in Python.
2.8.2. Mathematical model:#
2.8.3. Solution: Numerical ODE-solver simulation: #
2.8.3.1. Generic solution:#
he 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.8.3.2. Detailed 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
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
then you need to declare the ODEFUN function to make it usable for your numerical solver:
def ODEFUN(t, y, beta, gamma):
s, i, r = y
dsdt = -beta * s * i
didt = beta * s * i - gamma * i
drdt = gamma * i
return dsdt, didt, drdt
We assume the parameter valuers for β (contact rate) and γ (recovery rate):
For initial conditions, we assume 1 infected (I0) and no recovered persons (R0). Everyone else, S0, is susceptible to infection initially. Then the initial condition value and vector equals
# parameter values
R0 = 2.4 #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
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
We will generate a solution in the interval 0 <= t <= 2000 days. Therefore the timespan is:
TSPAN = [0,2000]
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).
sol = solve_ivp(ODEFUN, TSPAN, y0, args=(beta,gamma), 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.
We can select 1000 discrete time steps between 0 and 175
t = np.linspace(0, 175, 1000)
We select the outputs [s(t),i(t),r(t)] of the solver at the corresponding time steps
z = sol.sol(t)
s, i, r = z
Finally we plot the resulted simulated values for z as a function of time (t)
import matplotlib.pyplot as plt
def plotdata(t, s, i, e=None):
# plot the data
fig = plt.figure(figsize=(12,6))
ax = [fig.add_subplot(221, axisbelow=True),
fig.add_subplot(223),
fig.add_subplot(122)]
ax[0].plot(t, s, lw=3, label='Fraction Susceptible')
ax[0].plot(t, i, lw=3, label='Fraction Infective')
ax[0].plot(t, r, lw=3, label='Recovered')
ax[0].set_title('Susceptible and Recovered Populations')
ax[0].set_xlabel('Time /days')
ax[0].set_ylabel('Fraction')
ax[1].plot(t, i, lw=3, label='Infective')
ax[1].set_title('Infectious Population')
if e is not None: ax[1].plot(t, e, lw=3, label='Exposed')
ax[1].set_ylim(0, 0.3)
ax[1].set_xlabel('Time /days')
ax[1].set_ylabel('Fraction')
ax[2].plot(s, i, lw=3, label='s, i trajectory')
ax[2].plot([1/R0, 1/R0], [0, 1], '--', lw=3, label='di/dt = 0')
ax[2].plot(s[0], i[0], '.', ms=20, label='Initial Condition')
ax[2].plot(s[-1], i[-1], '.', ms=20, label='Final Condition')
ax[2].set_title('State Trajectory')
ax[2].set_aspect('equal')
ax[2].set_ylim(0, 1.05)
ax[2].set_xlim(0, 1.05)
ax[2].set_xlabel('Susceptible')
ax[2].set_ylabel('Infectious')
for a in ax:
a.grid(True)
a.legend()
plt.tight_layout()
plotdata(t, s, i)