forked from arnold-c/SISMID-Module-01_2026
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathr-session-02.qmd
More file actions
2139 lines (1809 loc) · 62.7 KB
/
Copy pathr-session-02.qmd
File metadata and controls
2139 lines (1809 loc) · 62.7 KB
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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
subtitle: "Heterogeneity and Age Structure in SIR Models"
abstract-title: ""
abstract: |
*Materials adapted from Helen Wearing and Aaron King [@kingAgeStructuredModels2011]*
execute:
warning: false
metadata-files:
- metadata/matthewferrari.yml
- metadata/mathjax-packages.yml
---
# R Session 02
## Load Packages
```{r}
library(diagram)
library(deSolve)
library(tidyverse)
library(gt)
library(rio)
```
```{r}
theme_set(theme_minimal())
```
## A Model With 2 Classes
We'll start with the simplest mechanistic model of two classes we can think of, which has separate classes for two groups $a$ and $b$. These groups could represent different socioeconomic classes, for example.
```{r}
#| echo: false
#| column: body
#| out-width: 100%
elpos <- rbind(
Sa = c(2, 3),
Sb = c(3, 3),
Ia = c(2, 2),
Ib = c(3, 2),
Ra = c(2, 1),
Rb = c(3, 1)
)
elpos[, 1] <- (2 * elpos[, 1] - 1) / 8
elpos[, 2] <- (2 * elpos[, 2] - 1) / 6
fromto <- rbind(
SaIa = c(1, 3),
SbIb = c(2, 4),
IaRa = c(3, 5),
IbRb = c(4, 6)
)
op <- par(mar = c(1, 1, 1, 1))
diagram::openplotmat(asp = 0.9)
arrpos <- matrix(ncol = 2, nrow = nrow(fromto))
for (i in seq_len(nrow(fromto))) {
arrpos[i, ] <- diagram::straightarrow(
to = elpos[fromto[i, 2], ],
from = elpos[fromto[i, 1], ],
lwd = 2,
arr.pos = 0.65,
arr.length = 0.5
)
}
# Add labels to the boxes
purrr::walk(
c("Sa", "Sb", "Ia", "Ib", "Ra", "Rb"),
.f = function(.x) {
diagram::textrect(
elpos[.x, ],
0.07,
0.07,
lab = .x,
box.col = gray(0.7),
shadow.col = gray(0.4),
shadow.size = 0.01,
cex = 2
)
}
)
# Add labels to the arrows
purrr::pwalk(
.l = list(
state = 1:4,
xadjust = rep(0.05, 4),
yadjust = rep(-0.175, 4),
label = rep(c("lambda", "gamma"), each = 2),
label_subscript = rep(c("a", "b"), 2)
),
.f = function(state, xadjust, yadjust, label, label_subscript) {
text(
elpos[state, 1] + xadjust,
elpos[state, 2] + yadjust,
bquote(.(ensym(label))[.(label_subscript)]),
cex = 2
)
}
)
par(op)
```
Which can be written in equations as,
$$
\begin{aligned}
\frac{\dd{S_a}}{\dd{t}} &= -\lambda_a\,S_a \phantom{-\gamma\,I_b}\\
\frac{\dd{S_b}}{\dd{t}} &= -\lambda_b\,S_b \phantom{-\gamma\,I_b}\\
\frac{\dd{I_a}}{\dd{t}} &= \phantom{-}\lambda_a\,S_a -\gamma\,I_a\\
\frac{\dd{I_b}}{\dd{t}} &= \phantom{-}\lambda_b\,S_b-\gamma\,I_b\\
\frac{\dd{R_a}}{\dd{t}} &= \phantom{-\lambda_a\,S_b}+\gamma\,I_a\\
\frac{\dd{R_b}}{\dd{t}} &= \phantom{-\lambda_a\,S_b}+\gamma\,I_b\\
\end{aligned}
$$
The $\lambda$s denote the group-specific force of infections:
$$
\begin{aligned}
\lambda_a &= \beta_{aa}\,I_a+\beta_{ab}\,I_b\\
\lambda_b &= \beta_{ba}\,I_a+\beta_{bb}\,I_b
\end{aligned}
$$
In this model, each population can infect each other but the infection moves through the populations separately.
Let's simulate such a model.
To make things concrete, we'll assume that the transmission rates $\beta$ are greater within groups than between them.
```{r}
# Create a named parameter vector that we can index by name in the model
ab_params <- c(
beta_within = 0.025,
beta_between = 0.005,
recovery = 10
)
```
```{r}
# Here we set up the ODE model that matches the equations above
ab_model <- function(t, x, p, ...) {
# Unpack the state variables
Sa <- x["Sa"]
Sb <- x["Sb"]
Ia <- x["Ia"]
Ib <- x["Ib"]
# Unpack the parameters
beta_within <- p["beta_within"]
beta_between <- p["beta_between"]
recovery <- p["recovery"]
# group A force of infection
lambda_a <- beta_within * Ia + beta_between * Ib
# group B force of infection
lambda_b <- beta_within * Ib + beta_between * Ia
# The ODEs
dSadt <- -lambda_a * Sa
dSbdt <- -lambda_b * Sb
dIadt <- lambda_a * Sa - recovery * Ia
dIbdt <- lambda_b * Sb - recovery * Ib
dRadt <- recovery * Ia
dRbdt <- recovery * Ib
# Return the derivatives
list(c(
dSadt,
dSbdt,
dIadt,
dIbdt,
dRadt,
dRbdt
))
}
```
```{r}
# initial conditions
ab_yinit <- c(Sa = 1000, Sb = 2000, Ia = 1, Ib = 1, Ra = 0, Rb = 0)
# Run the ODE solver from the deSolve package
ab_sol <- deSolve::ode(
y = ab_yinit,
times = seq(0, 2, by = 0.001),
func = ab_model,
parms = ab_params,
)
```
```{r}
ab_df <- ab_sol %>%
# Convert the solution to a tibble for manipulation
as_tibble() %>%
# Create and modify columns
mutate(
# Convert all columns into type numeric
across(everything(), as.numeric),
# Create new columns to track pop sizes in each group
Na = Sa + Ia + Ra,
Nb = Sb + Ib + Rb
) %>%
# Go from a wide to long dataframe for ggplot
pivot_longer(
cols = -time,
names_to = c("state", "group"),
names_sep = 1,
values_to = "value"
) %>%
# Clean pivoted columns for ordered plots
mutate(
state = factor(state, levels = c("S", "I", "R", "N")),
group = paste("Group", str_to_upper(group))
)
```
```{r}
#| column: body
#| out-width: 100%
# Create a vector of colors to be used throughout the ggplots
SIRcolors <- c("#1f77b4", "#ff7f0e", "#FF3851", "#591099")
ggplot(ab_df, aes(x = time, y = value, color = state)) +
geom_line(linewidth = 1.5) +
facet_wrap(~group, scales = "free_y") +
scale_color_manual(
values = SIRcolors,
labels = c("Susceptible", "Infected", "Recovered", "Total")
) +
labs(
x = "Time",
y = "Number of individuals",
color = "State"
) +
theme(legend.position = "bottom")
```
::: {.callout-question}
Despite using the same transmission rates, the epidemic in group B is much larger than in group A.
Why do you think this is?
:::
Now let's plot the proportion of individuals in each state for the two groups.
```{r}
ab_df_props <- ab_df %>%
# Remove total pop count as we only want the group-specific values
filter(state != "N") %>%
mutate(
# Concatenate the state variable and the group letter for each row
state_group = paste0(state, str_extract_all(group, "[^Group ]")),
# Factor new variable for nicer plotting
state_group = factor(
state_group,
levels = c("RA", "RB", "IA", "IB", "SA", "SB")
)
) %>%
# Group by time and state_group so we can calculate the relevant
# proportions over time
group_by(time, state_group) %>%
mutate(
prop = value / sum(ab_yinit)
) %>%
ungroup()
```
```{r}
#| column: body
#| out-width: 100%
# Create new vectors of colors as using 6: one of each for A and J groups
Scolors <- RColorBrewer::brewer.pal(3, "Blues")[c(2, 3)]
Icolors <- RColorBrewer::brewer.pal(3, "Oranges")[c(2, 3)]
Rcolors <- RColorBrewer::brewer.pal(3, "Greens")[c(2, 3)]
ggplot(ab_df_props, aes(x = time, y = prop, fill = state_group)) +
geom_area() +
scale_fill_manual(
values = c(Scolors, Icolors, Rcolors),
limits = c("SA", "SB", "IA", "IB", "RA", "RB"),
) +
labs(
x = "Time",
y = "Proportion of individuals",
fill = "State"
) +
theme(legend.position = "bottom")
```
## A Model With 2 Age Classes
Note that age is a special kind of heterogeneity in an epidemic model because individuals necessarily move from one class (younger) to another class (older) in a directional fashion that is independent of the infection and recovery process.
We'll start by introducing age into the model above.
So now $a$ becomes juveniles and $b$ becomes adults.
And, independent of the disease process, juveniles (of any category) age into adults.
Additionally, new juveniles are added through births (always first susceptible) and old individuals are lost to death.
```{r}
#| echo: false
#| column: body
#| out-width: 100%
elpos <- rbind(
B = c(1, 3),
Sj = c(2, 3),
Sa = c(3, 3),
Ij = c(2, 2),
Ia = c(3, 2),
Rj = c(2, 1),
Ra = c(3, 1),
Ds = c(4, 3),
Di = c(4, 2),
Dr = c(4, 1)
)
elpos[, 2] <- (2 * elpos[, 2] - 1) / 6
elpos[, 1] <- (2 * elpos[, 1] - 1) / 8
fromto <- rbind(
BSj = c(1, 2),
RaD = c(7, 10),
SjSa = c(2, 3),
IjIa = c(4, 5),
RjRa = c(6, 7),
SjIj = c(2, 4),
SaIa = c(3, 5),
IjRj = c(4, 6),
IaRa = c(5, 7),
SaD = c(3, 8),
IaD = c(5, 9)
)
op <- par(mar = c(1, 1, 1, 1))
diagram::openplotmat(asp = 1.0)
arrpos <- matrix(ncol = 2, nrow = nrow(fromto))
for (i in seq_len(nrow(fromto))) {
arrpos[i, ] <- diagram::straightarrow(
to = elpos[fromto[i, 2], ],
from = elpos[fromto[i, 1], ],
lwd = 2,
arr.pos = 0.65,
arr.length = 0.5
)
}
purrr::walk(
c("B", "Sj", "Sa", "Ij", "Ia", "Rj", "Ra", "Ds", "Di", "Dr"),
.f = function(.x) {
diagram::textrect(
elpos[.x, ],
0.07,
0.07,
lab = .x,
box.col = gray(0.7),
shadow.col = gray(0.4),
shadow.size = 0.01,
cex = 2
)
}
)
purrr::pwalk(
.l = list(
state = c(seq(2, 7, by = 1), 2, 3, 4, 5),
xadjust = c(rep(0.125, 6), rep(0.05, 4)),
yadjust = c(rep(0.05, 6), rep(-0.175, 4)),
label = c(rep(c("alpha", "mu"), 3), rep("lambda", 2), rep("gamma", 2)),
label_subscript = c(rep("", 6), "J", "A", rep("", 2))
),
.f = function(state, xadjust, yadjust, label, label_subscript) {
text(
elpos[state, 1] + xadjust,
elpos[state, 2] + yadjust,
bquote(.(ensym(label))[.(label_subscript)]),
cex = 2
)
}
)
par(op)
```
We can do this very simply using the same ingredients that go into the basic SIR model.
In that model, the waiting times in the S and I classes are exponential.
Let's assume the same thing about the aging process.
We'll also add in births into the juvenile susceptible class and deaths from the adult classes.
$$
\begin{aligned}
\frac{\dd{S_J}}{\dd{t}} &= B -\lambda_J\,S_J \phantom{- \gamma\,I_A} -\alpha\,S_J \phantom{-\mu\,S_A}\\
\frac{\dd{S_A}}{\dd{t}} &= \phantom{B} - \lambda_A\,S_A \phantom{- \gamma\,I_A} +\alpha\,S_J -\mu\,S_A\\
\frac{\dd{I_J}}{\dd{t}} &= \phantom{B} +\lambda_J\,S_J - \gamma\,I_J -\alpha\,I_J \phantom{-\mu\,S_A}\\
\frac{\dd{I_A}}{\dd{t}} &= \phantom{B} +\lambda_A\,S_A - \gamma\,I_A + \alpha\,I_J - \mu\,I_A\\
\frac{\dd{R_J}}{\dd{t}} &= \phantom{B - \lambda_J\,S_A} + \gamma\,I_J - \alpha\,R_J \phantom{- \mu\,S_A}\\
\frac{\dd{R_A}}{\dd{t}} &= \phantom{B - \lambda_J\,S_A} + \gamma\,I_A + \alpha\,R_J -\mu\,R_A\\
\end{aligned}
$$
Now, let's simulate this model, under the same assumptions about transmission rates as above.
```{r}
# define the parameters for the demographic model
demog_params <- c(
beta_within = 0.004,
beta_between = 0.002,
recovery = 10,
births = 100,
# Width of age bands in years
age_band_j = 20,
age_band_a = 60
)
```
```{r}
demog_model <- function(t, x, p, ...) {
# Unpack states
Sj <- x["Sj"]
Sa <- x["Sa"]
Ij <- x["Ij"]
Ia <- x["Ia"]
Rj <- x["Rj"]
Ra <- x["Ra"]
# Unpack parameters from vector
beta_within <- p["beta_within"]
beta_between <- p["beta_between"]
recovery <- p["recovery"]
births <- p["births"]
# Calculate rate of aging from each age group
aging_j <- 1 / p["age_band_j"]
aging_a <- 1 / p["age_band_a"]
# juv. force of infection
lambda_j <- beta_within * Ij + beta_between * Ia
# adult. force of infection
lambda_a <- beta_within * Ia + beta_between * Ij
# Calculate the ODEs
dSjdt <- births - (lambda_j * Sj) - (aging_j * Sj)
dSadt <- -(lambda_a * Sa) + (aging_j * Sj) - (aging_a * Sa)
dIjdt <- (lambda_j * Sj) - (recovery * Ij) - (aging_j * Ij)
dIadt <- (lambda_a * Sa) - (recovery * Ia) + (aging_j * Ij) - (aging_a * Ia)
dRjdt <- (recovery * Ij) - (aging_j * Rj)
dRadt <- (recovery * Ia) + (aging_j * Rj) - (aging_a * Ra)
# Return the ODEs
list(c(
dSjdt,
dSadt,
dIjdt,
dIadt,
dRjdt,
dRadt
))
}
```
Note that in this function, $\mu=$ `aging_a` $=$ `1 / p["age_band_a"]`, i.e., death, is just like another age class.
```{r}
# initial conditions
demog_yinit <- c(Sj = 2000, Sa = 3000, Ij = 0, Ia = 1, Rj = 0, Ra = 1000)
# Solve the demographic model
demog_sol <- deSolve::ode(
y = demog_yinit,
times = seq(0, 200, by = 0.1),
func = demog_model,
parms = demog_params
)
demog_df <- demog_sol %>%
as_tibble() %>%
mutate(
across(everything(), as.numeric),
Nj = Sj + Ij + Rj,
Na = Sa + Ia + Ra,
# Calculate total population as need for proportional area plots
N = Nj + Na
) %>%
pivot_longer(
cols = -c(time, N),
names_to = c("state", "group"),
names_sep = 1,
values_to = "value"
) %>%
mutate(
state = factor(state, levels = c("S", "I", "R", "N")),
group = paste("Group", str_to_upper(group))
)
```
<div class="exercise">
### Exercise 1: Use this code to plot the number of susceptible, infected, and recovered individuals over time
</div>
```{r}
#| column: body
#| out-width: 100%
ggplot(demog_df, aes(x = time, y = value, color = state)) +
geom_line(linewidth = 1.5) +
facet_wrap(
~group,
nrow = 2,
scales = "free_y",
labeller = as_labeller(c(
`Group A` = "Adults",
`Group J` = "Juveniles"
))
) +
scale_color_manual(
values = SIRcolors,
labels = c("Susceptible", "Infected", "Recovered", "Total")
) +
labs(
x = "Time",
y = "Number of individuals",
color = "State"
) +
theme(legend.position = "bottom")
```
Note that now that births are replenishing susceptibles, infection persists. The results of the above are plotted here:
Now let's plot the proportion of individuals in each state for the two groups.
```{r}
# Calculate the proportions in each state and group at each time point
demog_df_props <- demog_df %>%
filter(state != "N") %>%
mutate(
state_group = paste0(state, str_extract_all(group, "[^Group ]")),
state_group = factor(
state_group,
levels = c("RJ", "RA", "IJ", "IA", "SJ", "SA")
)
) %>%
group_by(time, state_group) %>%
mutate(
# Calculate the proportion of the total population, not the group pop
prop = value / N
) %>%
ungroup()
```
```{r}
#| column: body
#| out-width: 100%
ggplot(demog_df_props, aes(x = time, y = prop, fill = state_group)) +
geom_area() +
scale_fill_manual(
values = c(Scolors, Icolors, Rcolors),
limits = c("SJ", "SA", "IJ", "IA", "RJ", "RA")
) +
labs(
x = "Time",
y = "Proportion of individuals",
fill = "State"
) +
theme(legend.position = "bottom")
```
Now let's plot the equilibrium seroprevalence for each age group.
```{r}
# Select the last row (time point) of the data frame
demog_equil_seroprev <- tail(demog_df) %>%
mutate(
# Calculate the proportion of individuals in each state and age group
prop = value / sum(value),
# Relabel groups for plots
group = case_when(group == "Group J" ~ "Juveniles", TRUE ~ "Adults"),
group = factor(group, levels = c("Juveniles", "Adults")),
.by = group
) %>%
filter(state == "R")
```
```{r}
#| column: body
#| out-width: 100%
# Create vector of colors to distinguish between age groups
age_group_colors <- c("#2980B9", "#154360")
ggplot(demog_equil_seroprev, aes(x = group, y = prop, fill = group)) +
geom_col(position = "identity") +
scale_fill_manual(
values = age_group_colors
) +
labs(
x = "Age group",
y = "Equilibrium seroprevalence",
fill = "Age group"
) +
theme(legend.position = "none")
```
One thing we are often interested in is the $R_0$ of a system.
The details are beyond the scope of this workshop and are not required to complete the exercises in this worksheet, but we have outlined them in @sec-simple-ngm, particularly in @eq-simple-ngm, at the end of this page.
```{r}
#| echo: false
# Calculate the rate of aging out of each age group
alpha <- 1 / demog_params["age_band_j"]
mu <- 1 / demog_params["age_band_a"]
# Calculate the dfe pop sizes
n <- demog_params["births"] / c(alpha, mu)
# Create the transmission matrix
beta_demog <- matrix(
c(
demog_params["beta_within"],
demog_params["beta_between"],
demog_params["beta_between"],
demog_params["beta_within"]
),
nrow = 2,
ncol = 2
)
# Calculate the next generation matrix
ba_ngm <- matrix(
c(
n[1] *
(beta_demog[1, 1] / (demog_params["recovery"] + alpha)) +
alpha /
(demog_params["recovery"] + mu) *
n[1] *
beta_demog[1, 2] /
(demog_params["recovery"] + mu),
n[2] *
beta_demog[2, 1] /
(demog_params["recovery"] + alpha) +
alpha /
(demog_params["recovery"] + mu) *
n[2] *
(beta_demog[2, 2] / (demog_params["recovery"] + mu)),
n[1] * beta_demog[1, 2] / (demog_params["recovery"] + mu),
n[2] * beta_demog[2, 2] / (demog_params["recovery"] + mu)
),
nrow = 2,
ncol = 2
)
# Calculate R0 by taking the **spectral trace** i.e., the largest non-negative Eigenvalue of the NGM
ba_ngm <- round(max(Re(eigen(ba_ngm, only.values = TRUE)$values)), digits = 2)
```
In our system, $R_0 =$ `r ba_ngm`.
## Getting more realistic: adding more age classes
In the models above, the aging process follows an exponential distribution, which means that whether an individual is 1\~year old or 10 years old, the chance of them becoming an adult is the same!
To improve on this, we can assume that the time a juvenile must wait before becoming an adult follows a gamma distribution.
This is equivalent to saying that the waiting time is a sum of some number of exponential distributions.
This suggests that we can achieve such a distribution by adding age classes to the model, so that becoming an adult means passing through some number of stages.
We'll use 30 age classes, and since they don't have to be of equal duration, we'll assume that they're not.
Specifically, we'll have 20 1-yr age classes to take us up to adulthood and break adults into 10 age classes of 5\~yr duration each. The last age class covers age 66-80.
Now, when we had just two age classes, we could write out each of the equations easily enough, but now that we're going to have 30, we'll need to be more systematic.
In particular, we'll need to think of $\beta$ as a matrix of transmission rates.
Let's see how to define such a matrix in `R`.
So that we don't change too many things all at once, let's keep the same contact structure as in the juvenile-adult model.
```{r}
# Set up the parameters for model that incorporates a more realistic age matrix
ages_params <- c(
beta_j = 0.02,
beta_a = 0.01,
beta_aj = 0.01 / 2,
recovery = 10,
births = 100
)
# Create a vector of ages
ages <- c(seq(1, 20, by = 1), seq(25, 65, by = 5), 80)
# Calculate the widths of the age bands
da_ages <- diff(c(0, ages))
# set up a matrix of contact rates between classes: more contact
# within juveniles and adults than between
ages_beta_mat <- matrix(nrow = 30, ncol = 30)
# transmission rate for juveniles
ages_beta_mat[1:20, 1:20] <- ages_params["beta_j"]
# transmission rate for adults
ages_beta_mat[21:30, 21:30] <- ages_params["beta_a"]
# lower transmission rate between juveniles and adults
ages_beta_mat[1:20, 21:30] <- ages_params["beta_aj"]
# lower transmission rate between juveniles and adults
ages_beta_mat[21:30, 1:20] <- ages_params["beta_aj"]
```
<a id="fig-beta-mat"></a>
```{r}
#| column: body
#| out-width: 100%
# Convert matrix to data frame
tile_df <- expand.grid(x = 1:30, y = 1:30)
tile_df$value <- as.vector(ages_beta_mat)
# Convert to factor to treat as discrete categories and define colors
tile_df$value <- factor(tile_df$value)
beta_colors <- c("0.005" = "#fcae91", "0.01" = "#de2d26", "0.02" = "#a50f15")
# Create tile plot with 3 betas
ggplot(tile_df, aes(x = x, y = y, fill = value)) +
geom_tile(color = "white") +
scale_fill_manual(values = beta_colors, name = expression(beta)) +
labs(x = "Age of Contactor", y = "Age of Contactee") +
scale_x_continuous(breaks = 1:30, labels = as.character(ages)) +
scale_y_continuous(breaks = 1:30, labels = as.character(ages))
```
We'll assume that, at the time of introduction, all children are susceptible, as are adults over 45, but that individuals aged 20--45 have seen the pathogen before and are immune.
The vector `yinit` expresses these initial conditions.
```{r}
# Create a long vector of initial states with only one
# initial infection in age 50
demog_yinit_ages <- c(
S = c(rep(100, 20), rep(0, 5), rep(200, 5)),
I = c(rep(0, 25), 1, rep(0, 4)),
R = c(rep(0, 20), rep(1000, 5), rep(0, 5))
)
```
Note that we're starting out with 1 infected individual in the 26th age class (age 50).
The codes that follow will be a bit easier to follow if we introduce some indexes that will allow us to pick out certain bits of the `yinit` vector.
```{r}
# Create vectors of indices relating to each state
# Note that there are are 30 age classes, 1-20 are 1 year wide, 21-30 are 5 years wide, taking us up to age
# (ordered S1-80, I1-80, R1-80)
sindex <- 1:30
iindex <- 31:60
rindex <- 61:90
# Create vectors of indices relating to age group
juvies <- 1:20
adults <- 21:30
```
Now, to capture the aging process, it's convenient to define another matrix to hold the rates of movement between age classes.
Generally, this matrix would look like this:
$$
\begin{pmatrix}
-\alpha_1 & 0 & 0 & \cdots & 0\\
\alpha_1 & -\alpha_2 & 0 & \cdots & 0\\
0 & \alpha_2 & -\alpha_3 & \cdots & 0\\
\vdots & & \ddots & \ddots & \vdots \\
0 & \cdots & & \alpha_{29} & -\alpha_{30}\\
\end{pmatrix}
$${#eq-aging-mat}
```{r}
# Create a diagonal matrix that holds the rates of aging out of each age class
# The rows represent the age class you're in, the columns represent the age
# class you're moving to
aging_mat <- diag(-1 / da_ages)
# Fill in the rates of aging into each age class
aging_mat[row(aging_mat) - col(aging_mat) == 1] <- 1 / head(da_ages, -1)
```
Have a look at the aging matrix, for example by doing:
```{r}
# Move fast through the 1-year age classes - negatives are moves out, positives
# are moves in. Cannot move between non-adjacent age classes
aging_mat[1:5, 1:5]
```
```{r}
# Move slowly between the wider age classes
aging_mat[25:30, 25:30]
```
```{r}
#| eval: false
#| echo: false
aging_mat %>%
as.data.frame.table() %>%
mutate(
age_recipient = rep(ages, 30),
# Repeat each age in ages vector 30 times before moving to next
age_source = rep(ages, each = 30)
) %>%
ggplot(aes(x = age_source, y = age_recipient, z = Freq)) +
geom_contour_filled() +
scale_fill_brewer(
palette = "RdBu",
drop = FALSE
) +
labs(x = "Source Age Group", y = "Recipient Age Group")
```
```{r}
#| column: body
#| out-width: 100%
aging_mat %>%
as.data.frame.table() %>%
mutate(
age_recipient = rep(ages, 30),
# Repeat each age in ages vector 30 times before moving to next
age_source = rep(ages, each = 30)
) %>%
ggplot(aes(
x = as.factor(age_source),
y = as.factor(age_recipient),
z = Freq
)) +
geom_tile(colour = "grey", size = 0.4, aes(fill = Freq)) +
scale_fill_gradientn(
colours = c("red", "white", "blue"),
breaks = c(-1, -0.2, 0, 0.2, 1),
labels = c("-1", "-0.2", "0", "0.2", "1")
) +
labs(x = "Source Age Group", y = "Recipient Age Group")
```
<div class="exercise">
### Exercise 2: What can you say about its structure? How are the different age groups in contact with each other?
</div>
Now we can put the pieces together to write a simulator for the age-structured SIR dynamics.
```{r}
# Using a list instead of a vector to hold the parameters, as ages_beta_mat and
# aging are both matrices, so we want to keep them as matrices, rather than
# flattening
multistage_params <- list(
beta_mat = ages_beta_mat,
recovery = ages_params["recovery"],
births = ages_params["births"],
aging_mat = aging_mat
)
multistage_model <- function(t, x, p, ...) {
# Unpack all states from the vector using the relevant indices
s <- x[sindex]
i <- x[iindex]
r <- x[rindex]
# Unpack parameters
beta_mat <- p[["beta_mat"]]
recovery <- p[["recovery"]]
births <- p[["births"]]
aging_mat <- p[["aging_mat"]]
# Calculate force of infection using matrix multiplication
lambda <- beta_mat %*% i
# Calculate the ODEs at every time step
# Note that R add element-wise for vectors i.e. lambda * s results
# in a vector length 30 (30 age groups), as does aging_mat %*% s,
# so v1[i] + v2[i] for i in 1:30
dsdt <- -lambda * s + aging_mat %*% s
didt <- lambda * s + aging_mat %*% i - recovery * i
drdt <- aging_mat %*% r + recovery * i
# Add the birth rate to the first age group
dsdt[1] <- dsdt[1] + births
# Return the ODEs in a list
list(c(dsdt, didt, drdt))
}
```
We can plug this into `ode` just as we did the simpler models to simulate an epidemic.
We'll then plot the epidemic curve.
```{r}
# Solve the model with a realistic age matrix
multistage_sol <- deSolve::ode(
y = demog_yinit_ages,
times = seq(0, 100, by = 0.1),
func = multistage_model,
parms = multistage_params
)
# Extract all infected age groups at all time points into a new vector
multistage_infecteds <- multistage_sol[, 1 + iindex]
```
```{r}
# Create a dataframe of the sum of infectious individuals in Juv/Adult age groups
# at each time point
multistage_df <- tibble(
# Get all times from model run
time = multistage_sol[, 1],
# At each timepoint, apply the sum function to all juvenile infected
# individuals
Juveniles = apply(multistage_infecteds[, juvies], 1, sum),
# At each timepoint, apply the sum function to all adult infected
# individuals
Adults = apply(multistage_infecteds[, adults], 1, sum)
) %>%
# Pivot to create a long dataframe that works with ggplot
pivot_longer(
cols = c(Juveniles, Adults),
names_to = "age_group",
values_to = "infections"
) %>%
# Turn new pivoted variable into a factor to plot nicely
mutate(
age_group = factor(age_group, levels = c("Juveniles", "Adults"))
)
```
```{r}
#| column: body
#| out-width: 100%
ggplot(multistage_df, aes(x = time, y = infections, color = age_group)) +
geom_line(linewidth = 1.5) +
scale_color_manual(
values = age_group_colors
) +
labs(
x = "Time",
y = "Number of infections",
color = "Age group"
)
```
Let's mimic a situation where we have cross-sectional seroprevalence data (e.g. measures of antibodies that tell you someone is in the R class).
In using such data, we'd typically assume that the system was at equilibrium.
<div class="exercise">
### Exercise 3: What does the equilibrium age-specific seroprevalence look like in this example? {#sec-ex-3}
</div>
Use the code below to display the age-specific seroprevalence (i.e., the seroprevalence for each age group at equilibrium)
```{r}
# Get the last values for all individuals. drop() removes the column name,
# [-1] removes the time value
multistage_equil <- drop(tail(multistage_sol, 1))[-1]
# Calculate the equilibrium pop sizes of each age group
multistage_equil_n <- multistage_equil[sindex] +
multistage_equil[iindex] +
multistage_equil[rindex]
# Calculate equilibrium seroprevalence for each age group
multistage_equil_seroprev <- multistage_equil[rindex] / multistage_equil_n
# Create a dataframe to store equilibrium seroprev for plotting
multistage_equil_seroprev_df <- tibble(
age = ages,
seroprev = multistage_equil_seroprev,
width = da_ages
)
```
```{r}
#| column: body
#| out-width: 100%
ggplot(multistage_equil_seroprev_df, aes(x = age, y = seroprev, fill = age)) +
# Set column width to width of age bands, and justify to start at
# lower bound
geom_col(
width = multistage_equil_seroprev_df$width,
just = 1.0,
color = "black"
) +
labs(
x = "Age",
y = "Seroprevalence"
) +
scale_x_continuous(breaks = seq(0, 80, 10)) +
scale_fill_continuous(
low = age_group_colors[1],