SEIR模型的Python代码
时间: 2024-05-13 08:11:36 浏览: 218
SEIR模型是一种常见的传染病模型,它将人群分为四个类别:易感者(S),潜伏期感染者(E),感染者(I)和康复者(R)。下面是SEIR模型的Python代码:
```
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
# Total population, N.
N = 10000
# Initial number of infected and recovered individuals, I0 and R0.
I0, R0 = 1, 0
# Everyone else, S0, is susceptible to infection initially.
S0 = N - I0 - R0
# Contact rate, beta, and mean recovery rate, gamma, (in 1/days).
beta, gamma = 0.2, 1./10
# A time grid of days
t = np.linspace(0, 160, 160)
# The SEIR model differential equations.
def deriv(y, t, N, beta, gamma):
S, E, I, R = y
dSdt = -beta * S * I / N
dEdt = beta * S * I / N - gamma * E
dIdt = gamma * E - gamma * I
dRdt = gamma * I
return dSdt, dEdt, dIdt, dRdt
# Initial conditions vector
y0 = S0, I0, R0
# Integrate the SEIR equations over the time grid, t.
ret = odeint(deriv, y0, t, args=(N, beta, gamma))
S, E, I, R = ret.T
# Plot the data on three separate curves for S(t), E(t), I(t) and R(t)
fig = plt.figure(facecolor='w')
ax = fig.add_subplot(111, facecolor='#dddddd', axisbelow=True)
ax.plot(t, S/1000, 'b', alpha=0.5, lw=2, label='Susceptible')
ax.plot(t, E/1000, 'y', alpha=0.5, lw=2, label='Exposed')
ax.plot(t, I/1000, 'r', alpha=0.5, lw=2, label='Infected')
ax.plot(t, R/1000, 'g', alpha=0.5, lw=2, label='Recovered with immunity')
ax.set_xlabel('Time /days')
ax.set_ylabel('Number (1000s)')
ax.set_ylim(0,N/1000)
ax.yaxis.set_tick_params(length=0)
ax.xaxis.set_tick_params(length=0)
ax.grid(b=True, which='major', c='w', lw=2, ls='-')
legend = ax.legend()
legend.get_frame().set_alpha(0.5)
plt.show()
```
该代码使用SciPy库中的odeint函数求解微分方程,将结果绘制成图表展示出来。你可以根据实际需要调整参数或绘图方式,以满足不同的应用需求。
阅读全文