-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathr-session-01.qmd
724 lines (594 loc) · 20.3 KB
/
r-session-01.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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
---
execute:
echo: false
---
# R Session 01
## Interactive Plot {#sec-interactive-plots}
```{ojs}
init_beta = 0.3
init_dur_inf = 6.0
init_I0 = 0.01
init_births = 0.0
init_tmax = 200
```
```{ojs}
function set(input, value) {
input.value = value;
input.dispatchEvent(new Event("input", {bubbles: true}));
}
```
```{ojs}
//| panel: sidebar
viewof reset = Inputs.button([
["Reset all sliders", () => {
set(viewof beta, init_beta)
set(viewof dur_inf, init_dur_inf)
set(viewof I0, init_I0)
set(viewof births, init_births)
set(viewof tmax, init_tmax)
}]
])
viewof beta = Inputs.range(
[0.0, 2.0],
{value: init_beta, step: 0.01, label: "Transmission rate (per day)"}
)
viewof dur_inf = Inputs.range(
[0.0, 20],
{value: init_dur_inf, step: 0.5, label: "Duration of Infection (days)"}
)
viewof I0 = Inputs.range(
[0.0, 1.0],
{value: init_I0, step: 0.01, label: "Initial fraction infected"}
)
viewof births = Inputs.range(
[0, 0.05],
{value: init_births, step: 0.001, label: "Birth rate"}
)
viewof tmax = Inputs.range(
[200, 600],
{value: init_tmax, step: 10.0, label: "Maximum simulation time (years)"}
)
viewof area = Inputs.toggle(
{label: "Cumulative Area plot", value: false}
)
md`${tex`R_0 = ${R0_str}`}`
{
if (births == 0){
var finalsize = sir_sol.get("R", sir_sol.numRows()-1)
var finalsize_str = finalsize.toLocaleString(undefined, {minimumFractionDigits: 2})
return md`${tex`\text{Final size} = ${finalsize_str}`}`
} else {
return md``
}
}
```
```{ojs}
gamma = 1 / dur_inf
dt = 0.01
```
```{ojs}
import {odeRK4} from '@rreusser/integration@3064'
import { aq, op } from '@uwdata/arquero'
```
```{ojs}
function sir(dydt, y, t) {
dydt[0] = - beta * y[0] * y[1] + births * (1 - y[0])
dydt[1] = beta * y[0] * y[1] - gamma * y[1] - births * y[1]
dydt[2] = gamma * y[1] - births * y[2]
}
```
```{ojs}
function simulate(f, t0, y0, dt, tmax) {
var t = t0
var y = y0
var i = 0
var tsim = [t0]
var ysim = [y0]
for (t = t0 + dt; t <= tmax; t += dt) {
ysim.push(odeRK4([], ysim[i], f, dt))
tsim.push(t)
i += 1
}
return aq.table({
Time: tsim,
S: ysim.map(d => d[0]),
I: ysim.map(d => d[1]),
R: ysim.map(d => d[2])
})
}
```
```{ojs}
sir_sol = simulate(sir, 0, [1.0-I0, I0, 0.0], dt, tmax)
sir_sol_long = sir_sol.fold(aq.not('Time'), {as: ['State', 'Fraction']})
```
```{ojs}
SIRcolors = ["#1f77b4", "#ff7f0e", "#FF3851"]
```
```{ojs}
R0 = beta / (gamma + births)
R0_str = R0.toLocaleString(undefined, {minimumFractionDigits: 2})
```
```{ojs}
function calculate_equil(R0){
if (births > 0) {
var eq_S = 1 / R0
var eq_I = births / beta * (R0 - 1)
var eq_R = 1 - (eq_S + eq_I)
const eq_vals = aq.table({
State: ["S", "I", "R"],
Fraction: [eq_S, eq_I, eq_R]
})
return eq_vals
} else {
return null
}
}
```
```{ojs}
eq_vals = calculate_equil(R0)
```
```{ojs}
//| panel: fill
Plot.plot({
color: {
legend: true,
domain: ["S", "I", "R"],
range: SIRcolors
},
style: {fontSize: "20px"},
marginLeft: 65,
marginTop: 40,
marginBottom: 55,
grid: true,
width: 800,
height: 670,
y: {domain: [0, 1]},
marks: [
area ?
Plot.areaY(sir_sol_long, {x: "Time", y: "Fraction", fill: "State"}) :
[
R0 >= 1.0 && births > 0 ?
Plot.ruleY(
eq_vals,
{y: "Fraction", stroke: "State", strokeWidth: 2, strokeDasharray: [10]}
) :
null,
Plot.lineY(
sir_sol_long,
{x: "Time", y: "Fraction", stroke: "State", strokeWidth: 6}
)
]
]
})
```
## Closed Population Model Intuition
We'll first get develop an intuition for the closed population model.
We'll then extend this intuition to the open population model.
When the `Birth rate` slider in the side panel of the interactive figure is set to 0, we have no births or deaths, so their is no replenishment of the susceptible population i.e., it is a closed population.
::: {.callout-note title="SET"}
Transmission rate = 1
Duration of infection = 4.
:::
### What is $R_0$? {#sec-whatisr0}
### What is epidemic final size?
### Does this make sense given our definition of $R_0$?
::: {.callout-note title="Instruction" appearance="minimal"}
Toggle on the cumulative area button and see what the epidemic final size is (approximately)
:::
### At approximately what time does the epidemic end?
::: {.callout-note title="SET"}
Duration of infection = 8 days
Transmission rate so you get the same $R_0$ in @sec-whatisr0
:::
### How does the epidemic final size compare?
### At what time (approx) does the epidemic end?
::: {.callout-note}
Size is determined by $R_0$, duration is determined by recovery rate $\left(\gamma = \frac{1}{\text{duration of infection}}\right)$
:::
Now, imagine that we have a drug (or vaccine) available to everyone that either reduced transmission OR shortened the duration of infection.
::: {.callout-note title="SET"}
Transmission rate = 1
Duration of infection = 8 days
:::
### Note the epidemic final size and the time until the epidemic is over.
Now, imagine everyone has access to the drug (unrealistic) that reduces transmission by $P \%$
### What happens to the final size and outbreak duration?
Now, imagine everyone has access to a drug that reduces the duration of infection from 8 to 2 days (75% reduction).
### What happens to the final size and outbreak duration?
### Which assumption would you prefer and why?
::: {.callout-note}
This is the only really open ended question, but should be pretty straightforward discussion
:::
## Demographic Model Intuition
::: {.callout-note title="SET"}
Transmission = 1
Duration = 8
Birth rate = .002
:::
### What is $R_0$? {#sec-demog-whatisr0}
### What is the equilibrium proportion that is susceptible?
### If you were to test for antibodies against infection in the population, what proportion would you expect to be positive?
::: {.callout-note}
Assume a perfectly accurate serological test
:::
### At what time (approximately) does the system reach equilibrium?
::: {.callout-note title="SET"}
Birth rate = 0.005
:::
### What is the new $R_0$? {#sec-demog-updatedr0}
### At what time (approximately) does the system reach equilibrium?
::: {.callout-note title="SET"}
Transmission rate so you get the same $R_0$ in @sec-demog-whatisr0
:::
### What is the new equilibrium proportion that is susceptible?
### What is different about the prevalence of infection (equilibrium proportion that is infected) in the scenarios @sec-demog-whatisr0 and @sec-demog-updatedr0 i.e. higher birth rate with the same $R_0$?
## Model Building With R
### Setting Up A Script
Now we have some intuition behind how the different parameters affect the dynamics of the SIR system, let's look at how we can implement this in R.
Below is some R code that implements the basic closed-population SIR model.
The purpose of the questions in this exercise is to guide you through the code and help you understand how it works so you can modify it to answer your own questions.
<a id="quarto-tips"></a>
::: {.callout-note title="Instruction" appearance="minimal"}
Copy the code below into a new R script.
This script should live in your SISMID directory, as described [previously](project-management.qmd).
Run it to check you get the same figure output as above.
:::
```{r}
#| echo: true
#| message: false
#| out-width: 100%
#| column: body
library(tidyverse)
library(deSolve)
theme_set(theme_minimal())
sir_model <- function(time, state, params, ... ){
transmission <- params["transmission"]
recovery <- 1 / params["duration"]
S <- state["S"]
I <- state["I"]
R <- state["R"]
dSdt <- -transmission * S * I
dIdt <- (transmission * S * I) - (recovery * I)
dRdt <- recovery * I
return(list(c(dSdt, dIdt, dRdt)))
}
sir_params <- c(transmission = 0.3, duration = 6)
sir_init_states <- c(S = 0.99, I = 0.01, R = 0)
sim_times <- seq(0, 200, by = 0.1)
sir_sol <- deSolve::ode(
y = sir_init_states,
times = sim_times,
func = sir_model,
parms = sir_params
)
# Turn the output from the ODE solver into a tibble (dataframe)
# so we can manipulate and plot it easily
sir_sol_df <- as_tibble(sir_sol) %>%
# Convert all columns to numeric (they are currently type
# deSolve so will produce warnings when plotting etc)
mutate(
# Rather than repeatedly type the same function for every
# column, use the across() function to apply the function
# to a selection of columns
across(
# The cols argument takes a selection of columns to apply
# a function to. Here, we want to apply the as.numeric()
# function to all columns, so we use the function
# everything() to select all columns.
.cols = everything(),
.fns = as.numeric
)
) %>%
# Convert the dataframe from wide to long format, so we have a
# column for the time, a column for the state, and a column
# for the proportion of the population in that state at that
# time
pivot_longer(
# Don't pivot the time column
cols = -time,
names_to = "state",
values_to = "proportion"
) %>%
# Update the state column to be a factor, so the plot will
# show the states in the correct order
mutate(state = factor(state, levels = c("S", "I", "R")))
SIRcolors <- c(S = "#1f77b4", I = "#ff7f0e", R = "#FF3851")
ggplot(sir_sol_df, aes(x = time, y = proportion, color = state)) +
geom_line(linewidth = 1.5) +
scale_color_manual(values = SIRcolors) +
labs(
x = "Time",
y = "Fraction",
color = "State"
) +
theme(legend.position = "top")
```
### Commenting the code {#sec-ex-commenting-code}
For this part of the exercise, go through the basic SIR code and add comments to each section of code explaining what it does.
To get you started, we've added some comments to the creating of the dataframe object `sir_sol_df` between lines 32-62 in the code block above, as some of the functions used there are a bit more complicated.
::: {.callout-note}
Normally you would not use nearly as extensive comments.
Here, we've gone overboard to help you understand what each line does, as some may not be familiar with all the functions used.
We've also broken up the comments into multiple lines so that it is easier to read on this website.
For your code that you view in RStudio (or some other text editor), use one line per sentence of the comment i.e., start a new comment line after each period.
Generally, you want to use comments to explain why you are doing something, not what you are doing.
Sometimes that is unavoidable (e.g., you had to look up how to do a particular thing in R and need the hints to be able to understand the code), but try to stick to this guideline where possible.
:::
As you're going through the code, if you don't understand what a particular function does, try looking up the documentation for it!
You can do this by clicking on the function within the website (as described [in the intro](index.qmd#tips-about-the-website)), or by typing `?function_name` into the R console (Google also is your friend here!).
### Adding in demographics {#sec-ex-add-demographics}
Now we have a better sense of how the code works, let's add in some demographic structure.
To recreate the demographic model from the interactive plot in @sec-interactive-plots, we just need to add births and deaths to the system.
Recall the equations for the demographic model:
$$
\begin{aligned}
\frac{dS}{dt} &= \mu N - \beta S I - \mu S \\
\frac{dI}{dt} &= \beta S I - \gamma I - \mu I \\
\frac{dR}{dt} &= \gamma I - \mu R
\end{aligned}
$$ {#eq-demographic-sir}
#### Create a new R script called `01_demographic-sir.R` and copy the code from `S01_basic-sir.R` into it.
#### Rename the function `sir_model()` to `demographic_sir_model()` in your new script (`S01_demographic-sir.R`).
#### Adapt the function `demographic_sir_model()` to match the above equations (@eq-demographic-sir).
::: {.callout-note title="SET"}
birth rate = 0.05
:::
#### Rename the variables to reflect that we are now working with a demographic model, not the basic SIR model.
#### Plot the results of your demographic model. Does it look like this?
```{r}
#| message: false
#| echo: false
#| out-width: 100%
#| column: body
sir_demog_model <- function(time, state, params, ... ){
transmission <- params["transmission"]
recovery <- 1 / params["duration"]
birth_rate <- params["birth_rate"]
S <- state["S"]
I <- state["I"]
R <- state["R"]
dSdt <- -transmission * S * I + (birth_rate * (1 - S))
dIdt <- (transmission * S * I) - (recovery * I) - (birth_rate * I)
dRdt <- (recovery * I) - (birth_rate * R)
return(list(c(dSdt, dIdt, dRdt)))
}
sir_demog_params <- c(sir_params, birth_rate = 0.05)
sir_demog_sol <- deSolve::ode(
y = sir_init_states,
times = sim_times,
func = sir_demog_model,
parms = sir_demog_params
)
sir_demog_sol_df <- as_tibble(sir_demog_sol) %>%
mutate(
across(
everything(),
as.numeric
)
) %>%
pivot_longer(
cols = -time,
names_to = "state",
values_to = "proportion"
) %>%
mutate(state = factor(state, levels = c("S", "I", "R")))
ggplot(sir_demog_sol_df, aes(x = time, y = proportion, color = state)) +
geom_line(linewidth = 1.5) +
scale_color_manual(values = SIRcolors) +
labs(
x = "Time",
y = "Fraction",
color = "State"
) +
theme(legend.position = "top")
```
#### Update the comments in your code to reflect the changes you have made.
## Exercise Solutions {.appendix}
::: {.callout-note}
Here, we're using the `{roxygen2}` package to create the comments for the functions we've created, i.e., `sir_model <- function(...)`.
This provides a consistent framework for commenting functions, and if we wanted, we could use the comments to create documentation for our functions.
The main benefit for our purposes is that the framework allows us to quickly understand exactly what the function does, as well as the context it should be used in.
:::
### @sec-ex-commenting-code: Commented basic SIR code
```{r}
#| message: false
#| echo: true
#| eval: false
#| code-fold: true
# Load packages
library(tidyverse)
library(deSolve)
# Set the ggplot2 theme
theme_set(theme_minimal())
#' Basic SIR model
#'
#' A basic SIR model with no demographic structure to be used in deSolve
#'
#' @param time deSolve passes the time parameter to the function.
#' @param state A vector of states.
#' @param params A vector of parameter values .
#' @param ... Other arguments passed by deSolve.
#'
#' @return A deSolve matrix of states at each time step.
#' @examples
#' sir_params <- c(transmission = 0.3, duration = 6)
#' sir_init_states <- c(S = 0.99, I = 0.01, R = 0)
#' sim_times <- seq(0, 200, by = 0.1)
#'
#' sir_sol <- deSolve::ode(
#' y = sir_init_states,
#' times = sim_times,
#' func = sir_model,
#' parms = sir_params
#' ))
sir_model <- function(time, state, params, ... ){
# Extract parameters for cleaner calculations
transmission <- params["transmission"]
recovery <- 1 / params["duration"]
# Extract states for cleaner calculations
S <- state["S"]
I <- state["I"]
R <- state["R"]
# Differential equations of the SIR model
dSdt <- -transmission * S * I
dIdt <- (transmission * S * I) - (recovery * I)
dRdt <- recovery * I
# Return a list whose first element is a vector of the
# state derivatives - must be in the same order as the
# state vector (S, I, R)
return(list(c(dSdt, dIdt, dRdt)))
}
# Create the parameter, initial state, and time vectors
sir_params <- c(transmission = 0.3, duration = 6)
sir_init_states <- c(S = 0.99, I = 0.01, R = 0)
sim_times <- seq(0, 200, by = 0.1)
# Solve the SIR model with deSolve's ode() function
sir_sol <- deSolve::ode(
y = sir_init_states,
times = sim_times,
func = sir_model,
parms = sir_params
)
# Turn the output from the ODE solver into a tibble (dataframe)
# so we can manipulate and plot it easily
sir_sol_df <- as_tibble(sir_sol) %>%
# Convert all columns to numeric (they are currently type
# deSolve so will produce warnings when plotting etc)
mutate(
# Rather than repeatedly type the same function for every
# column, use the across() function to apply the function
# to a selection of columns
across(
# The cols argument takes a selection of columns to apply
# a function to. Here, we want to apply the as.numeric()
# function to all columns, so we use the function
# everything() to select all columns.
.cols = everything(),
.fns = as.numeric
)
) %>%
# Convert the dataframe from wide to long format, so we have a
# column for the time, a column for the state, and a column
# for the proportion of the population in that state at that
# time
pivot_longer(
# Don't pivot the time column
cols = -time,
names_to = "state",
values_to = "proportion"
) %>%
# Update the state column to be a factor, so the plot will
# show the states in the correct order
mutate(state = factor(state, levels = c("S", "I", "R")))
# Save the colors to a vector
SIRcolors <- c(S = "#1f77b4", I = "#ff7f0e", R = "#FF3851")
# Plot the results
ggplot(sir_sol_df, aes(x = time, y = proportion, color = state)) +
geom_line(linewidth = 1.5) +
scale_color_manual(values = SIRcolors) +
labs(
x = "Time",
y = "Fraction",
color = "State"
) +
theme(legend.position = "top")
```
### @sec-ex-add-demographics: Commented demographic SIR code
```{r}
#| message: false
#| echo: true
#| eval: false
#| code-fold: true
# Load packages
library(tidyverse)
library(deSolve)
# Set the ggplot2 theme
theme_set(theme_minimal())
#' Demographic SIR model
#'
#' An SIR model with births and deaths (constant pop) to be used in deSolve
#'
#' @param time deSolve passes the time parameter to the function.
#' @param state A vector of states.
#' @param params A vector of parameter values .
#' @param ... Other arguments passed by deSolve.
#'
#' @return A deSolve matrix of states at each time step.
#' @examples
#' sir_params <- c(transmission = 0.3, duration = 6, birth_rate = 0.05)
#' sir_init_states <- c(S = 0.99, I = 0.01, R = 0)
#' sim_times <- seq(0, 200, by = 0.1)
#'
#' sir_sol <- deSolve::ode(
#' y = sir_init_states,
#' times = sim_times,
#' func = sir_demog_model,
#' parms = sir_params
#' ))
sir_demog_model <- function(time, state, params, ... ){
transmission <- params["transmission"]
recovery <- 1 / params["duration"]
birth_rate <- params["birth_rate"]
S <- state["S"]
I <- state["I"]
R <- state["R"]
dSdt <- birth_rate -transmission * S * I - (birth_rate * S)
dIdt <- (transmission * S * I) - (recovery * I) - (birth_rate * I)
dRdt <- (recovery * I) - (birth_rate * R)
return(list(c(dSdt, dIdt, dRdt)))
}
# Create the parameter, initial state, and time vector
sir_demog_params <- c(transmission = 0.3, duration = 6, birth_rate = 0.05)
sir_init_states <- c(S = 0.99, I = 0.01, R = 0)
sim_times <- seq(0, 200, by = 0.1)
# Solve the SIR model with deSolve's ode() function
sir_demog_sol <- deSolve::ode(
y = sir_init_states,
times = sim_times,
func = sir_demog_model,
parms = sir_demog_params
)
# Turn the output from the ODE solver into a tibble (dataframe)
# so we can manipulate and plot it easily
sir_demog_sol_df <- as_tibble(sir_demog_sol) %>%
# Convert all columns to numeric (they are currently type
# deSolve so will produce warnings when plotting etc)
mutate(
# Rather than repeatedly type the same function for every
# column, use the across() function to apply the function
# to a selection of columns
across(
# The cols argument takes a selection of columns to apply
# a function to. Here, we want to apply the as.numeric()
# function to all columns, so we use the function
# everything() to select all columns.
.cols = everything(),
.fns = as.numeric
)
) %>%
# Convert the dataframe from wide to long format, so we have a
# column for the time, a column for the state, and a column
# for the proportion of the population in that state at that
# time
pivot_longer(
# Don't pivot the time column
cols = -time,
names_to = "state",
values_to = "proportion"
) %>%
# Update the state column to be a factor, so the plot will
# show the states in the correct order
mutate(state = factor(state, levels = c("S", "I", "R")))
# Save the colors to a vector
SIRcolors <- c(S = "#1f77b4", I = "#ff7f0e", R = "#FF3851")
# Plot the results
ggplot(sir_demog_sol_df, aes(x = time, y = proportion, color = state)) +
geom_line(linewidth = 1.5) +
scale_color_manual(values = SIRcolors) +
labs(
x = "Time",
y = "Fraction",
color = "State"
) +
theme(legend.position = "top")
```