forked from UofUEpiBio/epiworldpy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
README.qmd
242 lines (183 loc) · 6.45 KB
/
README.qmd
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
---
format: gfm
title: "epiworldpy: Python bindings for epiworld"
---
[![](https://github.com/UofUEpiBio/epiworldpy/actions/workflows/pip.yaml/badge.svg)](https://github.com/UofUEpiBio/epiworldpy/actions/workflows/pip.yaml)
[![](https://img.shields.io/pypi/v/epiworldpy.svg)](https://pypi.org/project/epiworldpy)
This is a python wrapper of the [`epiworld c++` library][epiworld-git], an ABM
simulation engine. This is possible using the
[`pybind11`][] library (which rocks!).
The `epiworld` module is already
[implemented in R](https://github.com/UofUEpiBio/epiworldR){target="_blank"}.
# Installation
- clone this repository
- `pip install ./epiworldpy`
# API
You can find API documentation on the <a href="/api.html">API page</a>.
# Examples
## Basic
Here we show how to create a `SEIR` object and add terms to it. We will use the following data:
```{python}
# Loading the module
import epiworldpy as epiworld
# Create a SEIR model (susceptible, exposed, infectious, recovered), representing COVID-19.
covid19 = epiworld.ModelSEIRCONN(
name = 'covid-19',
n = 10000,
prevalence = .01,
contact_rate = 2.0,
transmission_rate = .1,
incubation_days = 7.0,
recovery_rate = 0.14
)
# Taking a look
covid19.print(False)
```
Let's run it and to see what we get:
```{python}
# Run for 100 days with a seed of 223.
covid19.run(100, 223)
# Print an overview.
covid19.print(False)
```
We can now visualize the model's compartments:
```{python}
#| label: series-visualization
#| fig-cap: ""
import numpy as np
import matplotlib.pyplot as plt
# Get the data from the database
history = covid19.get_db().get_hist_total()
# Extract unique states and dates
unique_states = np.unique(history['states'])
unique_dates = np.unique(history['dates'])
# Remove some data that will mess with scaling
unique_states = np.delete(unique_states, np.where(unique_states == 'Susceptible'))
# Initialize a dictionary to store time series data for each state
time_series_data = {state: [] for state in unique_states}
# Populate the time series data for each state
for state in unique_states:
for date in unique_dates:
# Get the count for the current state and date
mask = (history['states'] == state) & (history['dates'] == date)
count = history['counts'][mask][0]
time_series_data[state].append(count)
# Start the plotting!
plt.figure(figsize=(10, 6))
for state in unique_states:
plt.plot(unique_dates, time_series_data[state], label=state)
plt.xlabel('Day')
plt.ylabel('Count')
plt.title('COVID-19 SEIR Model Data')
plt.legend()
plt.grid(True)
plt.show()
```
We can get the effective reproductive number, over time, too:
```{python}
#| label: rt-visualization
#| fig-cap: ""
reproductive_data = covid19.get_db().get_reproductive_number()
# Start the plotting!
plt.figure(figsize=(10, 6))
for virus_id, virus_data in enumerate(reproductive_data):
average_rts = list()
for date_data in virus_data:
if not date_data:
continue
keys_array = np.array(list(date_data.values()), dtype=np.float64)
average_rts.append(np.mean(keys_array))
plt.plot(range(0, len(virus_data)-1), average_rts, label=f"Virus {virus_id}")
plt.xlabel('Date')
plt.ylabel('Effective Reproductive Rate')
plt.title('COVID-19 SEIR Model Effective Reproductive Rate')
plt.legend()
plt.grid(True)
plt.show()
```
Let's do the same for generation time:
```{python}
#| label: gentime-visualization
#| fig-cap: ""
from collections import defaultdict
generation_time = covid19.get_db().get_generation_time()
agents = generation_time['agents']
viruses = generation_time['viruses']
times = generation_time['times']
gentimes = generation_time['gentimes']
# Data formatting
unique_viruses = np.unique(viruses)
data = defaultdict(lambda: defaultdict(list))
for agent, virus, time, gentime in zip(agents, viruses, times, gentimes):
data[virus][time].append(gentime)
average_data = {virus: {} for virus in unique_viruses}
for virus, time_dict in data.items():
for time, gentime_list in time_dict.items():
average_data[virus][time] = np.mean(gentime_list)
# Plotting
plt.figure(figsize=(10, 6))
for virus, time_dict in average_data.items():
times = sorted(time_dict.keys())
gentimes = [time_dict[time] for time in times]
plt.plot(times, gentimes, label=f'Virus {virus}')
plt.xlabel('Date')
plt.ylabel('Generation Time')
plt.title('COVID-19 SEIR Model Generation Time')
plt.legend()
plt.grid(True)
plt.show()
```
Epiworld records agent-agent interactions, and we can graph those too. In the below example, we only track all cases stemming from a specific index case, despite the model having a prevalence of 0.01.
```{python}
#| label: contact-visualization
#| fig-cap: ""
#| eval: false
import networkx as nx
from matplotlib.animation import FuncAnimation
transmissions = covid19.get_db().get_transmissions()
start = transmissions['source_exposure_dates']
end = transmissions['dates']
source = transmissions['sources']
target = transmissions['targets']
days = max(end)
graph = nx.Graph()
fig, ax = plt.subplots(figsize=(6,4))
# Animation function
to_track = { source[0] }
def update(frame):
ax.clear()
agents_involved_today = set()
agents_relationships_we_care_about = []
# Get only the agents involved in the current frame.
for i in range(len(start)):
if start[i] <= frame <= end[i]:
agents_involved_today.add((source[i], target[i]))
# Get only today's agents who have some connection to agents
# we've seen before.
for agent in agents_involved_today:
if agent[0] in to_track or agent[1] in to_track:
to_track.add(agent[0])
to_track.add(agent[1])
graph.add_edge(agent[0], agent[1])
# Lay and space them out.
pos = nx.kamada_kawai_layout(graph)
options = {
"with_labels": True,
"node_size": 300,
"font_size": 6,
"node_color": "white",
"edgecolors": "white",
"linewidths": 1,
"width": 1,
}
# Graph!
nx.draw_networkx(graph, pos, **options)
ax.set_title(f"COVID-19 SEIR Model Agent Contact (Day {frame})")
ani = FuncAnimation(fig, update, frames=int(days/3), interval=200, repeat=False)
plt.show()
```
<!-- I couldn't figure out a way to get Quarto to do animations correctly so we're
hardcoding a GIF. -->
![](README_files/figure-markdown_strict/contact-visualization-output-1.gif)
[epiworld-git]: https://github.com/UofUEpiBio/epiworld/
[`pybind11`]: https://pybind11.readthedocs.io/en/stable/