-
Notifications
You must be signed in to change notification settings - Fork 1
/
08_StochasticIBM_solutions.qmd
377 lines (296 loc) · 11.8 KB
/
08_StochasticIBM_solutions.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
---
title: "08. Stochastic individual-based models (solutions)"
---
## Practical 1. An individual-based SEIR model of SARS-CoV-2 transmission
```{r, eval = FALSE, message = FALSE}
# Individual-based SARS-CoV-2 transmission model, practical 1
library(ggplot2)
## Model parameters
beta <- 0.5 # Transmission parameter
delta <- 1 / 2.5 # Rate of transitioning out of latent state
gamma <- 1 / 5 # Rate of transitioning out of infectious state
omega <- 1 / 180 # Rate of waning immunity
dt <- 1 # Time step of simulation (1 day)
days <- 365 # Duration of simulation (365 days)
steps <- days / dt # Total number of time steps
n <- 1000 # Population size
## Data frame to store simulation results
results <- data.frame(ts = 1:steps, S = 0, E = 0, I = 0, R = 0)
## Initialize simulation
# Set the seed for the pseudorandom number generator, for reproducibility
set.seed(12345)
# Since this is an individual-based model, we track the properties of all n
# individuals in the simulation. One kind of property we can track is a state,
# such as S (susceptible), E (exposed), I (infectious), or R (recovered). We
# will store each individual's state as a string, either "S", "E", "I", or "R".
state <- rep("S", n) # Each individual's state: start with all susceptible
state[1:10] <- "E" # Start 10 individuals in the "exposed" state
## Run simulation
# We'll use the built-in function txtProgressBar to track the simulation's
# progress. Really helps for planning coffee breaks! It needs to know the
# minimum and maximum values to expect, and style = 3 tells it to report the
# percentage complete.
bar <- txtProgressBar(min = 1, max = steps, style = 3)
# Loop over each time step . . .
for (ts in 1:steps) {
# Calculate the force of infection
lambda <- beta * sum(state == "I") / n
# Loop through each individual . . .
for (i in 1:n) {
if (state[i] == "S") {
# Transition S -> E (infection) at rate lambda
if (runif(1) < 1 - exp(-lambda * dt)) {
state[i] <- "E"
}
} else if (state[i] == "E") {
# Transition E -> I (latent to infectious) at rate delta
if (runif(1) < 1 - exp(-delta * dt)) {
state[i] <- "I"
}
} else if (state[i] == "I") {
# Transition I -> R (infectious to recovered) at rate gamma
if (runif(1) < 1 - exp(-gamma * dt)) {
state[i] <- "R"
}
} else if (state[i] == "R") {
# Transition R -> S (waning of immunity) at rate omega
if (runif(1) < 1 - exp(-omega * dt)) {
state[i] <- "S"
}
}
}
# Save population state for this time step
results[ts, "S"] <- sum(state == "S")
results[ts, "E"] <- sum(state == "E")
results[ts, "I"] <- sum(state == "I")
results[ts, "R"] <- sum(state == "R")
# Update progress bar; close progress bar if we are finished
setTxtProgressBar(bar, ts)
if (ts == steps) {
close(bar)
}
}
## Plot simulation results
ggplot(results) +
geom_line(aes(x = ts, y = S, colour = "S")) +
geom_line(aes(x = ts, y = E, colour = "E")) +
geom_line(aes(x = ts, y = I, colour = "I")) +
geom_line(aes(x = ts, y = R, colour = "R"))
```
## Practical 2. Adding more complex dynamics to the model
```{r, eval = FALSE, message = FALSE}
# Individual-based SARS-CoV-2 transmission model, practical 2
library(ggplot2)
## Model parameters
beta <- 0.5 # Transmission parameter
iota <- 1e-5 # Importation rate
wane <- 0.05 # Rate of antibody waning
dt <- 1 # Time step of simulation (1 day)
days <- 365 * 2 # Duration of simulation (2 years)
steps <- days / dt # Total number of time steps
n <- 1000 # Population size
## Some helper functions
# Calculates infectiousness as a function of state and age: zero if state is
# not "I"; nonzero if state is "I", and slightly decreasing with age
infectiousness <- function(state, age) {
ifelse(state == "I", 1.25 - age / 160, 0)
}
# Calculates susceptibility of individuals with antibody level(s) ab
susceptibility <- function(ab) {
pnorm(ab, 5, 1, lower.tail = FALSE)
}
# Generates n random delays from the latent-period distribution
# (approximately 2 days, on average)
latent_delay <- function(n) {
rlnorm(n, meanlog = 0.5, sdlog = 0.6)
}
# Generates n random delays from the infectious-period distribution
# (approximately 5 days, on average)
infectious_delay <- function(n) {
rlnorm(n, meanlog = 1.5, sdlog = 0.5)
}
# Generates n random increments to antibody levels following recovery
ab_increment <- function(n) {
rnorm(n, mean = 12, sd = 2)
}
## Data frame to store simulation results
results <- data.frame(ts = 1:steps, S = 0, E = 0, I = 0, AMeanU = 0, AMeanV = 0)
## Initialize simulation
# Set the seed for the pseudorandom number generator, for reproducibility
set.seed(12345)
# Initialize state variables
state <- rep("S", n) # Each individual's state: start with all susceptible
age <- runif(n, 0, 80) # Each individual's age: random distribution from 0 to 80
delay <- rep(0, n) # Delay for latent and infectious periods
antib <- rep(0, n) # Antibody concentration for each individual
vacc <- rep(FALSE, n) # Vaccinated status
state[1:10] <- "E" # Start 10 individuals in the "exposed" state
## Run simulation
# Initialize progress bar
bar <- txtProgressBar(min = 1, max = steps, style = 3)
# Loop over each time step . . .
for (ts in 1:steps) {
# Calculate the force of infection
lambda <- beta * sum(infectiousness(state, age)) / n + iota
# Loop through each individual . . .
for (i in 1:n) {
# Update individual i's non-state variables
# Time remaining in latent/infectious periods
delay[i] <- delay[i] - dt
# Antibody waning
antib[i] <- antib[i] - wane * dt
# Vaccination at time step 300 for over-40s
if ((ts == 300) && (age[i] >= 40)) {
vacc[i] <- TRUE
antib[i] <- antib[i] + 2 * ab_increment(1)
}
# Update individual i's state
if (state[i] == "S") {
# Transition S -> E (infection) at rate lambda
if (runif(1) < 1 - exp(-lambda * dt)) {
if (runif(1) < susceptibility(antib[i])) {
state[i] <- "E"
delay[i] <- latent_delay(1)
}
}
} else if (state[i] == "E") {
# Transition E -> I (latent to infectious)
if (delay[i] < 0) {
state[i] <- "I"
delay[i] <- infectious_delay(1)
}
} else if (state[i] == "I") {
# Transition I -> S (infectious to susceptible)
if (delay[i] < 0) {
state[i] <- "S"
antib[i] <- antib[i] + ab_increment(1)
}
}
}
# Save population state for this time step
results[ts, "S"] <- sum(state == "S")
results[ts, "E"] <- sum(state == "E")
results[ts, "I"] <- sum(state == "I")
results[ts, "AMeanU"] <- mean(antib[!vacc])
results[ts, "AMeanV"] <- mean(antib[vacc])
# Update progress bar; close progress bar if we are finished
setTxtProgressBar(bar, ts)
if (ts == steps) {
close(bar)
}
}
## Plot simulation results
ggplot(results) +
geom_line(aes(x = ts, y = S, colour = "S")) +
geom_line(aes(x = ts, y = E, colour = "E")) +
geom_line(aes(x = ts, y = I, colour = "I"))
ggplot(results) +
geom_line(aes(x = ts, y = AMeanU, colour = "Unvaccinated")) +
geom_line(aes(x = ts, y = AMeanV, colour = "Vaccinated")) +
labs(x = "Time step", y = "Mean antibody level")
```
## Practical 3. Optimizing the model to run faster
```{r, eval = FALSE, message = FALSE}
# Individual-based SARS-CoV-2 transmission model, practical 3
library(ggplot2)
## Model parameters
beta <- 0.5 # Transmission parameter
iota <- 1e-5 # Importation rate
wane <- 0.05 # Rate of antibody waning
dt <- 1 # Time step of simulation (1 day)
days <- 365 * 4 # Duration of simulation (4 years)
steps <- days / dt # Total number of time steps
n <- 5000 # Population size
## Some helper functions
# Calculates infectiousness as a function of state and age: zero if state is
# not "I"; nonzero if state is "I", and slightly decreasing with age
infectiousness <- function(state, age) {
ifelse(state == "I", 1.25 - age / 160, 0)
}
# Calculates susceptibility of individuals with antibody level(s) ab
susceptibility <- function(ab) {
pnorm(ab, 5, 1, lower.tail = FALSE)
}
# Generates n random delays from the latent-period distribution
# (approximately 2 days, on average)
latent_delay <- function(n) {
rlnorm(n, meanlog = 0.5, sdlog = 0.6)
}
# Generates n random delays from the infectious-period distribution
# (approximately 5 days, on average)
infectious_delay <- function(n) {
rlnorm(n, meanlog = 1.5, sdlog = 0.5)
}
# Generates n random increments to antibody levels following recovery
ab_increment <- function(n) {
rnorm(n, mean = 12, sd = 2)
}
## Data frame to store simulation results
results <- data.frame(ts = 1:steps, S = 0, E = 0, I = 0, AMeanU = 0, AMeanV = 0)
## Initialize simulation
# Set the seed for the pseudorandom number generator, for reproducibility
set.seed(12345)
# Initialize state variables
state <- rep("S", n) # Each individual's state: start with all susceptible
age <- runif(n, 0, 80) # Each individual's age: random distribution from 0 to 80
delay <- rep(0, n) # Delay for latent and infectious periods
antib <- rep(0, n) # Antibody concentration for each individual
vacc <- rep(FALSE, n) # Vaccinated status
state[1:10] <- "E" # Start 10 individuals in the "exposed" state
## Run simulation
# Initialize progress bar
bar <- txtProgressBar(min = 1, max = steps, style = 3)
# Loop over each time step . . .
for (ts in 1:steps) {
# Calculate the force of infection
lambda <- beta * sum(infectiousness(state, age)) / n + iota
##### NOTE - There is no inner loop over individuals anymore!
# Update non-state variables (for all individuals simultaneously)
# Time remaining in latent/infectious periods
delay <- delay - dt
# Antibody waning
antib <- antib - wane * dt
# Vaccination at time step 300 for over-40s
if (ts == 300) {
vacc[age >= 40] <- TRUE
antib[vacc] <- antib[vacc] + 2 * ab_increment(sum(vacc))
}
# Update state variables (for all individuals simultaneously)
##### trE selects all individuals who will transition states from S to E.
trE <- (state == "S") & (runif(n) < 1 - exp(-lambda * dt)) &
(runif(n) < susceptibility(antib))
trI <- (state == "E") & (delay < 0)
trS <- (state == "I") & (delay < 0)
# Do state transitions
# transition S -> E
state[trE] <- "E"
delay[trE] <- latent_delay(sum(trE))
# transition E -> I
state[trI] <- "I"
delay[trI] <- infectious_delay(sum(trI))
# transition I -> S
state[trS] <- "S"
antib[trS] <- antib[trS] + ab_increment(sum(trS))
# Save population state for this time step
results[ts, "S"] <- sum(state == "S")
results[ts, "E"] <- sum(state == "E")
results[ts, "I"] <- sum(state == "I")
results[ts, "AMeanU"] <- mean(antib[!vacc])
results[ts, "AMeanV"] <- mean(antib[vacc])
# Update progress bar; close progress bar if we are finished
setTxtProgressBar(bar, ts)
if (ts == steps) {
close(bar)
}
}
## Plot simulation results
ggplot(results) +
geom_line(aes(x = ts, y = S, colour = "S")) +
geom_line(aes(x = ts, y = E, colour = "E")) +
geom_line(aes(x = ts, y = I, colour = "I"))
ggplot(results) +
geom_line(aes(x = ts, y = AMeanU, colour = "Unvaccinated")) +
geom_line(aes(x = ts, y = AMeanV, colour = "Vaccinated")) +
labs(x = "Time step", y = "Mean antibody level")
```
**Return to the practical [here](08_StochasticIBM_practical.qmd).**