forked from DataForScience/Epidemiology101
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEpiModel.py
251 lines (177 loc) · 7.27 KB
/
EpiModel.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
### −∗− mode : python ; −∗−
# @file EpiModel.py
# @author Bruno Goncalves
######################################################
import networkx as nx
import numpy as np
from numpy import linalg
from numpy import random
import scipy.integrate
import pandas as pd
import matplotlib.pyplot as plt
class EpiModel(object):
"""Simple Epidemic Model Implementation
Provides a way to implement and numerically integrate
"""
def __init__(self, compartments=None):
self.transitions = nx.MultiDiGraph()
if compartments is not None:
self.transitions.add_nodes_from([comp for comp in compartments])
def add_interaction(self, source, target, agent, rate):
self.transitions.add_edge(source, target, agent=agent, rate=rate)
def add_spontaneous(self, source, target, rate):
self.transitions.add_edge(source, target, rate=rate)
def _new_cases(self, population, time, pos):
"""Internal function used by integration routine"""
diff = np.zeros(len(pos))
N = np.sum(population)
for edge in self.transitions.edges(data=True):
source = edge[0]
target = edge[1]
trans = edge[2]
rate = trans['rate']*population[pos[source]]
if 'agent' in trans:
agent = trans['agent']
rate *= population[pos[agent]]/N
diff[pos[source]] -= rate
diff[pos[target]] += rate
return diff
def plot(self, title=None, normed=True, **kwargs):
"""Convenience function for plotting"""
try:
if normed:
N = self.values_.iloc[0].sum()
ax = (self.values_/N).plot(**kwargs)
else:
ax = self.values_.plot(**kwargs)
ax.set_xlabel('Time')
ax.set_ylabel('Population')
if title is not None:
ax.set_title(title)
return ax
except:
raise NotInitialized('You must call integrate() first')
def __getattr__(self, name):
"""Dynamic method to return the individual compartment values"""
if 'values_' in self.__dict__:
return self.values_[name]
else:
raise AttributeError("'EpiModel' object has no attribute '%s'" % name)
def simulate(self, timesteps, **kwargs):
"""Stochastically simulate the epidemic model"""
pos = {comp: i for i, comp in enumerate(kwargs)}
population=np.zeros(len(pos), dtype='int')
for comp in pos:
population[pos[comp]] = kwargs[comp]
values = []
values.append(population)
comps = list(self.transitions.nodes)
time = np.arange(1, timesteps, 1, dtype='int')
for t in time:
pop = values[-1]
new_pop = values[-1].copy()
N = np.sum(pop)
for comp in comps:
trans = list(self.transitions.edges(comp, data=True))
prob = np.zeros(len(comps), dtype='float')
for _, node_j, data in trans:
source = pos[comp]
target = pos[node_j]
rate = data['rate']
if 'agent' in data:
agent = pos[data['agent']]
rate *= pop[agent]/N
prob[target] = rate
prob[source] = 1-np.sum(prob)
delta = random.multinomial(pop[source], prob)
delta[source] = 0
changes = np.sum(delta)
if changes == 0:
continue
new_pop[source] -= changes
for i in range(len(delta)):
new_pop[i] += delta[i]
values.append(new_pop)
values = np.array(values)
self.values_ = pd.DataFrame(values[1:], columns=comps, index=time)
def integrate(self, timesteps, **kwargs):
"""Numerically integrate the epidemic model"""
pos = {comp: i for i, comp in enumerate(kwargs)}
population=np.zeros(len(pos))
for comp in pos:
population[pos[comp]] = kwargs[comp]
time = np.arange(1, timesteps, 1)
self.values_ = pd.DataFrame(scipy.integrate.odeint(self._new_cases, population, time, args=(pos,)), columns=pos.keys(), index=time)
def __repr__(self):
text = 'Epidemic Model with %u compartments and %u transitions:\n\n' % \
(self.transitions.number_of_nodes(),
self.transitions.number_of_edges())
for edge in self.transitions.edges(data=True):
source = edge[0]
target = edge[1]
trans = edge[2]
rate = trans['rate']
if 'agent' in trans:
agent = trans['agent']
text += "%s + %s = %s %f\n" % (source, agent, target, rate)
else:
text+="%s -> %s %f\n" % (source, target, rate)
text += "\nR0=%1.2f" % self.R0()
return text
def _get_susceptible(self):
degree = dict(self.transitions.in_degree())
for node in degree:
if degree[node] == 0:
return node
return None
def R0(self):
infected = set()
susceptible = self._get_susceptible()
for node_i, node_j, data in self.transitions.edges(data=True):
if "agent" in data:
infected.add(data['agent'])
infected.add(node_j)
infected = sorted(infected)
N_infected = len(infected)
F = np.zeros((N_infected, N_infected), dtype='float')
V = np.zeros((N_infected, N_infected), dtype='float')
pos = dict(zip(infected, np.arange(N_infected)))
for node_i, node_j, data in self.transitions.edges(data=True):
rate = data['rate']
if "agent" in data:
target = pos[node_j]
agent = pos[data['agent']]
if node_i == susceptible:
F[target, agent] = rate
else:
source = pos[node_i]
V[source, source] += rate
if node_j in pos:
target = pos[node_j]
V[target, source] -= rate
eig, v = linalg.eig(np.dot(F, linalg.inv(V)))
return eig.max()
if __name__ == '__main__':
SIR = EpiModel()
SIR.add_interaction('S', 'I', 'I', 0.2)
#SIR.add_interaction('S', 'E', 'Is', 0.2)
#SIR.add_spontaneous('E', 'Ia', 0.5*0.1)
#SIR.add_spontaneous('E', 'Is', 0.5*0.1)
#SIR.add_spontaneous('Ia', 'R', 0.1)
SIR.add_spontaneous('I', 'R', 0.1)
print("R0 =", SIR.R0())
N = 100000
fig, ax = plt.subplots(1)
values = []
Nruns = 100
for i in range(Nruns):
SIR.simulate(365, S=N-1, I=1, R=0)
ax.plot(SIR.I/N, lw=.1, c='b')
if SIR.I.max() > 10:
values.append(SIR.I)
ax.set_xlabel('Time')
ax.set_ylabel('Population')
values = pd.DataFrame(values).T
values.columns = np.arange(values.shape[1])
ax.plot(values.median(axis=1)/N, lw=1, c='r')
fig.savefig('SIR.png')