CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
AllenDowney

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: AllenDowney/ModSimPy
Path: blob/master/chap11.py
Views: 531
1
from modsim import *
2
3
def make_system(beta, gamma):
4
init = State(s=89, i=1, r=0)
5
init /= init.sum()
6
7
return System(init=init, t_end=7*14,
8
beta=beta, gamma=gamma)
9
10
from modsim import *
11
12
def update_func(t, state, system):
13
s, i, r = state.s, state.i, state.r
14
15
infected = system.beta * i * s
16
recovered = system.gamma * i
17
18
s -= infected
19
i += infected - recovered
20
r += recovered
21
22
return State(s=s, i=i, r=r)
23
24
from modsim import *
25
26
def plot_results(S, I, R):
27
S.plot(style='--', label='Susceptible')
28
I.plot(style='-', label='Infected')
29
R.plot(style=':', label='Recovered')
30
decorate(xlabel='Time (days)',
31
ylabel='Fraction of population')
32
33
from modsim import *
34
35
def run_simulation(system, update_func):
36
frame = TimeFrame(columns=system.init.index)
37
frame.loc[0] = system.init
38
39
for t in range(0, system.t_end):
40
frame.loc[t+1] = update_func(t, frame.loc[t], system)
41
42
return frame
43
44
45