Andrea Amantini / Oct 11 2021
Observable Python SIR
SIR Model
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
N = 1 # Size of the population (so everything in proportions)
I0 = 0.01 # Initial proportion of the population infected
S0 = N - I0 # Initial proportion of the population susceptible
R0 = 0.0 # Initial proportion of the population recovered
maxT = 25 # max number of periods in simulation
beta = 0.5 # transmission rate
gamma = 0.1 # recovery rate
def SIR(y, t, beta, gamma):
'''the SIR model'''
S, I, R = y
dSdt = -beta*S*I
dIdt = beta*S*I - gamma*I
dRdt = gamma*I
return([dSdt, dIdt, dRdt])
SIR model config
1.7s
def plotSIR(beta = beta, gamma = gamma, maxT = maxT):
'''Solve differential equations in SIR and plot'''
t = np.linspace(0, maxT, 1000)
soln = odeint(SIR, [S0,I0,R0], t, args=(beta, gamma))
soln = np.array(soln)
plt.figure(figsize=[8,6])
plt.plot(t, soln[:,0], linewidth=3, label = 'S(t)')
plt.plot(t, soln[:,1], linewidth=3, label = 'I(t)')
plt.plot(t, soln[:,2], linewidth=3, label = 'R(t)')
plt.title("SIR model")
plt.xlabel("Time"); plt.ylabel("proportions")
plt.grid(); plt.legend()
0.0s
from IPython.display import display, HTML
# display(HTML("<h1>hello</h1>"))
123
0.0s
plotSIR(Beta:0.5, Gamma:0.5, MaxT:55)
0.3s
controls = {
const form = html`<form style="font: 12px var(--sans-serif);">
<span><em>SIR model parameters</em></span>
<label style="display: block;">
<input name=beta type=range min=0.0 max=1.0 step=0.05 style="width:180px;"/>
β = <output name=obeta></output>
</label>
<label style="display: block;">
<input name=gamma type=range min=0.0 max=1.0 step=0.05 style="width:180px;"/>
γ = <output name=ogamma></output>
</label>
<label style="display: block;">
<input name=maxt type=range min=5 max=100 step=5 style="width:180px;"/>
maxT = <output name=omaxt></output>
</label>
</form>`;
form.oninput = () => {
form.obeta.value = form.beta.valueAsNumber;
form.ogamma.value = form.gamma.valueAsNumber;
form.omaxt.value = form.maxt.valueAsNumber;
};
form.oninput();
return form;
}
Control Generators
Generators.input(controls.beta)
Beta
Generators.input(controls.gamma)
Gamma
Generators.input(controls.maxt)
MaxT