python SIR模型代码
时间: 2023-10-16 16:05:40 浏览: 47
下面是一个简单的Python SIR模型代码,可以用来模拟传染病的传播过程:
```python
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
# 定义SIR模型
def SIR(y, t, N, beta, gamma):
S, I, R = y
dSdt = -beta * S * I / N
dIdt = beta * S * I / N - gamma * I
dRdt = gamma * I
return dSdt, dIdt, dRdt
# 设置初始参数
N = 1000
I0, R0 = 1, 0
S0 = N - I0 - R0
beta, gamma = 0.2, 1/10
t = np.linspace(0, 200, 200)
# 求解ODE方程
y0 = S0, I0, R0
ret = odeint(SIR, y0, t, args=(N, beta, gamma))
S, I, R = ret.T
# 绘制图像
fig = plt.figure(facecolor='w')
ax = fig.add_subplot(111, facecolor='#dddddd', axisbelow=True)
ax.plot(t, S/N, 'b', alpha=0.5, lw=2, label='Susceptible')
ax.plot(t, I/N, 'r', alpha=0.5, lw=2, label='Infectious')
ax.plot(t, R/N, 'g', alpha=0.5, lw=2, label='Recovered with immunity')
ax.set_xlabel('Time (days)')
ax.set_ylabel('Proportion of Population')
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()
```
其中,`SIR`函数定义了SIR模型的微分方程,`odeint`函数用于求解ODE方程,`S, I, R`分别表示易感者、感染者和康复者的数量随时间的变化。通过调整初始参数和传染率和治愈率等参数,可以模拟不同疫情情况下的传播趋势。