-
Notifications
You must be signed in to change notification settings - Fork 3
/
S3.Rmd
1392 lines (1033 loc) · 38.9 KB
/
S3.Rmd
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
---
title: "S3 Appendix"
output:
pdf_document:
number_sections: true
urlcolor: blue
---
This appendix serves a dual purpose. On the one hand, it aims to demonstrate
the advantages of using fake/synthetic data to diagnose problems in calibration
algorithms. With synthetic data, we aim to answer: "Is it possible to estimate
the desired parameters with the available data if we have the correct model?".
On the other hand, we present a hypothetical example to illustrate the Bayesian
workflow presented in the main text.
\tableofcontents
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE)
library(bayesplot)
library(colorspace)
library(cmdstanr)
library(dplyr)
library(extraDistr)
library(GGally)
library(ggplot2)
library(ggpubr)
library(kableExtra)
library(MCMCpack)
library(Metrics)
library(parallel)
library(patchwork)
library(posterior)
library(purrr)
library(readsdr)
library(rstan)
library(scales)
library(stringr)
library(tictoc)
library(tidyr)
source("./R/helpers.R")
source("./R/plots.R")
```
\newpage
# Synthetic data
We hypothetically receive data (Figure 1) from an influenza outbreak (H1N1)
in Cumberland, Maryland. This outbreak occurred in 1918 when the population
size was 5234. From previous studies, we estimate the latent and infectious
periods at two days each.
```{r}
mdl_path <- "./models/SEIR.stmx"
N <- 5234
I_0 <- 2
R_0 <- 1570
stock_list <- list(S = N - I_0 - R_0,
E = 0,
I = I_0,
R = R_0,
C = I_0)
const_list <- list(rho = 0.77,
par_beta = 1.29,
N = N,
sigma = 0.5,
par_gamma = 0.5,
I0 = I_0,
R0 = R_0)
actual_pars <- data.frame(name = c("beta", "I(0)", "R(0)", "rho") ,
val = c(1.29, I_0, R_0, 0.77))
mdl <- read_xmile(mdl_path, stock_list = stock_list,
const_list = const_list)
```
```{r}
sim_output <- sd_simulate(mdl$deSolve_components, start_time = 0,
stop_time = 91, timestep = 1 / 128,
integ_method = "rk4")
set.seed(1924)
sim_inc <- sd_net_change(sim_output, "C") %>% dplyr::select(-var) %>%
rename(true_inc = value) %>%
mutate(measured_inc = rpois(nrow(.), true_inc))
actual_df <- sim_inc %>%
rename(x = true_inc,
y = measured_inc)
```
```{r, fig.cap = "Synthetic incidence", fig.height = 3}
ggplot(sim_inc, aes(x = time, y = true_inc)) +
geom_line(colour = "grey95") +
geom_point(data = sim_inc, aes(y = measured_inc), colour = "steelblue") +
labs(x = "Days since the first case reported",
y = "Incidence [New cases per day]") +
theme_pubr()
```
# Calibration
The goal of this exercise is the same as the one described in the main text. In
particular, we aim to estimate the basic reproduction number ($R_0$). To do so,
we fit, through Hamiltonian Monte Carlo, an SEIR model (see equations in the
main text) to the incidence data. By doing so, we can estimate parameter values
that best describe the given data, and from which we can approximate $R_0$.
```{r}
n_sims <- 500
pars_list <- vector(mode = "list", length = 3)
mase_list <- vector(mode = "list", length = 3)
```
## Case 1
After formulating a dynamic hypothesis, the next step in a calibration process
consists of determining which parameters are fixed within the dynamic structure,
and which parameters will be estimated using the MCMC algorithm. We start by
considering the case where the effective contact rate ($\beta$) and the initial infectious ($I(0)$) are unknown. Further, we assume that there is no
underreporting ($\rho = 1$) and that there is no previous immunity ($R(0) = 0$).
We adopt the priors described in the main text.
### Priors
#### Prior distributions
* $\beta \sim lognormal(0,1)$
* $I(0) \sim lognormal(0,1)$
#### Unmodelled predictors
\hfill
```{r}
data.frame(Predictor = c("$\\rho$", "$\\sigma$", "$\\gamma$", "E(0)", "R(0)", "N"),
Value = c(1, 0.5, 0.5, 0, 0, 5234)) -> df
kable(df, booktab = TRUE, escape = FALSE)
```
### Prior predictive checks
Then, we check that our prior information captures the data (Figure 2). Based on
the results below, we *accept the prior* and proceed to fit the model.
```{r case_1_prior_pred_checks}
fldr <- "./backup_objs/Synthetic_data/Case_1"
dir.create(fldr, showWarnings = FALSE, recursive = TRUE)
file_path <- file.path(fldr, "prior_sims.rds")
if(!file.exists(file_path)) {
stock_list <- list(E = 0,
R = 0)
const_list <- list(N = N,
sigma = 0.5,
par_gamma = 0.5,
rho = 1)
set.seed(2044)
beta_vals <- rlnorm(n_sims)
I0_vals <- rlnorm(n_sims)
mdl2 <- read_xmile(mdl_path, stock_list = stock_list,
const_list = const_list)
consts_df <- data.frame(par_beta = beta_vals)
stocks_df <- data.frame(I = I0_vals,
S = N - I0_vals,
C = I0_vals)
sens_o <- sd_sensitivity_run(mdl2$deSolve_components, start_time = 0,
stop_time = 91, timestep = 1 / 32,
multicore = TRUE, n_cores = 4,
integ_method = "rk4", stocks_df = stocks_df,
consts_df = consts_df)
saveRDS(sens_o, file_path)
} else {
sens_o <- readRDS(file_path)
}
sens_inc <- predictive_checks(n_sims, sens_o)
```
```{r, fig.cap = "Case 1.Prior predictive checks", fig.height = 3}
meas_df <- sim_inc %>% rename(y = measured_inc)
plot_predictive_checks(sens_inc, meas_df)
```
### Diagnostics
After validating the prior, we run four chains of 1,000 samples allocated
to each phase (_warm-up_ and _sampling_).
```{r}
pars_hat <- c("I0", "beta")
gamma <- 0.5
sigma <- 0.5
consts <- sd_constants(mdl)
ODE_fn <- "SEIR"
stan_fun <- stan_ode_function(mdl_path, ODE_fn, pars = consts$name[2],
const_list = list(N = N, par_gamma = gamma,
sigma = sigma, rho = 1))
fun_exe_line <- str_glue(" o = ode_rk45({ODE_fn}, x0, t0, ts, params);")
stan_data <- stan_data("y", type = "int", inits = FALSE)
stan_params <- paste(
"parameters {",
" real<lower = 0> beta;",
" real<lower = 0> I0;",
"}", sep = "\n")
stan_tp <- paste(
"transformed parameters{",
" vector[n_difeq] o[n_obs]; // Output from the ODE solver",
" real x[n_obs];",
" vector[n_difeq] x0;",
" real params[n_params];",
" x0[1] = 5234 - I0;",
" x0[2] = 0;",
" x0[3] = I0;",
" x0[4] = 0;",
" x0[5] = I0;",
" params[1] = beta;",
fun_exe_line,
" x[1] = o[1, 5] - x0[5];",
" for (i in 1:n_obs-1) {",
" x[i + 1] = o[i + 1, 5] - o[i, 5] + 1e-5;",
" }",
"}", sep = "\n")
stan_model <- paste(
"model {",
" beta ~ lognormal(0, 1);",
" I0 ~ lognormal(0, 1);",
" y ~ poisson(x);",
"}",
sep = "\n")
stan_text <- paste(stan_fun, stan_data, stan_params,
stan_tp, stan_model, sep = "\n")
stan_fldr <- "./Stan_files/Synthetic_data"
dir.create(stan_fldr, showWarnings = FALSE, recursive = TRUE)
stan_filepath <- file.path(stan_fldr, "Case_1.stan")
create_stan_file(stan_text, stan_filepath)
```
```{r fit_case_1, results = 'hide'}
fldr <- "./backup_objs/Synthetic_data/Case_1"
dir.create(fldr, showWarnings = FALSE, recursive = TRUE)
file_path <- file.path(fldr, "Case_1.rds")
if(!file.exists(file_path)) {
stan_d <- list(n_obs = nrow(sim_inc),
y = sim_inc$measured_inc,
n_params = 1,
n_difeq = 5,
t0 = 0,
ts = 1:length(sim_inc$measured_inc))
mod <- cmdstan_model(stan_filepath)
fit <- mod$sample(data = stan_d,
seed = 276203775,
chains = 4,
parallel_chains = 4,
iter_warmup = 1000,
iter_sampling = 1000,
refresh = 5,
save_warmup = FALSE,
output_dir = fldr)
fit$save_object(file_path)
} else {
fit <- readRDS(file_path)
}
```
#### HMC Diagnostics
\hfill
HMC diagnostics are satisfactory and indicate no pathological behaviour.
```{r, message = TRUE}
# We generated this file from $fit$cmdstan_diagnose()
fileName <- file.path(fldr, "diag_1.txt")
if(!file.exists(fileName)) {
diagnosis <- fit$cmdstan_diagnose()
writeLines(diagnosis$stdout, fileName)
} else {
readChar(fileName, file.info(fileName)$size) %>% cat()
}
```
#### Trace plots
\hfill
Furthermore, a visual inspection on trace plots (Figure 3) indicate that the
chains converge.
```{r, fig.height = 3, fig.cap = "Case 1. Trace plots"}
mcmc_trace(fit$draws(), pars_hat)
```
#### Metrics
\hfill
Finally, $\widehat{R}$ and $ESS_{bulk}$ are within the predetermined
thresholds (< 1.01 and > 400, respectively). Based on these diagnostics,
we *accept the computation* and move to the *posterior predictive checking*
stage.
\hfill
```{r}
par_matrices <- lapply(pars_hat, function(par) {
extract_variable_matrix(fit$draws(), par)
})
ess_vals <- map_dbl(par_matrices, ess_bulk)
r_hat_vals <- map_dbl(par_matrices, rhat)
smy_df <- data.frame(par = c("I(0)", "$\\beta$"),
ess_bulk = ess_vals,
rhat = r_hat_vals)
```
```{r, echo = FALSE}
colnames(smy_df) <- c("par", "$ESS_{bulk}$", "$\\widehat{R}$")
kable(smy_df, booktab = TRUE, escape = FALSE)
```
### Posterior predictive checking
However, when we compare the model's fit against the data (Figure 4), we observe
that the estimated trajectories overestimate the actual behaviour. Assuming no
underreporting and no previous immunity produce an inadequate
explanation of the observed data. In other words, it does not pass the stringent
validity test of model calibration. For this reason, we deem the model
*not trustworthy*.
```{r case1_fit, fig.height = 3, fig.cap = "Case 1. Fit"}
posterior_df <- fit$draws() %>% as_draws_df()
plot_ts_fit(posterior_df, actual_df)
```
```{r case1_MASE}
source("./R/Metrics_utils.R")
mase_list[[1]] <- get_mase_fit(posterior_df, sim_inc$measured_inc) %>%
mutate(Case = "1")
pars_df <- posterior_df[, pars_hat]
pars_list[[1]] <- pars_df %>% mutate(Case = "1",
iter = row_number())
```
\newpage
## Case 2
Since Case 1's setup does not yield satisfactory results, we consider
a more complex model. Specifically, $R(0)$ and $\rho$ are no longer assumed as
unmodelled predictors, resulting in a four-unknowns model. We adopt the priors
described in the main text. For $R(0)$, we choose a [weakly informative prior](https://github.com/stan-dev/stan/wiki/Prior-Choice-Recommendations).
### Priors
#### Prior distributions
* $\beta \sim lognormal(0,1)$
* $\rho \sim Beta(2,2)$
* $I(0) \sim lognormal(0,1)$
* $R(0) \sim Normal(0,1e4)$
#### Unmodelled predictors
\hfill
```{r}
data.frame(Predictor = c("$\\sigma$", "$\\gamma$", "E(0)", "N"),
Value = c(0.5, 0.5, 0, 5234)) -> df
kable(df, booktab = TRUE, escape = FALSE)
```
### Prior predictive checks
Again, we check that our prior information captures the data (Figure 5). Based
on the results below, we *accept the prior* and proceed to fit the model.
```{r case_2_prior_pred_checks}
fldr <- "./backup_objs/Synthetic_data/Case_2"
dir.create(fldr, showWarnings = FALSE, recursive = TRUE)
file_path <- file.path(fldr, "prior_sims.rds")
if(!file.exists(file_path)) {
stock_list <- list(E = 0)
const_list <- list(N = N,
sigma = 0.5,
par_gamma = 0.5)
set.seed(3181)
beta_vals <- rlnorm(n_sims)
rho_vals <- rbeta(n_sims, 2, 2)
R0_vals <- rhnorm(n_sims, 1e4)
I0_vals <- rlnorm(n_sims)
# This validations prevents that there are more infected individuals than
# population size
val_sum <- R0_vals + I0_vals
val_idx <- which(val_sum < 5234)
beta_vals <- beta_vals[val_idx]
rho_vals <- rho_vals[val_idx]
R0_vals <- R0_vals[val_idx]
I0_vals <- I0_vals[val_idx]
mdl2 <- read_xmile(mdl_path, stock_list = stock_list,
const_list = const_list)
consts_df <- data.frame(par_beta = beta_vals,
rho = rho_vals)
stocks_df <- data.frame(I = I0_vals,
S = N - I0_vals - R0_vals,
C = I0_vals,
R = R0_vals)
sens_o <- sd_sensitivity_run(mdl2$deSolve_components, start_time = 0,
stop_time = 91, timestep = 1 / 32,
multicore = TRUE, n_cores = 4,
integ_method = "rk4", stocks_df = stocks_df,
consts_df = consts_df)
saveRDS(sens_o, file_path)
} else {
sens_o <- readRDS(file_path)
}
sens_inc <- predictive_checks(n_sims, sens_o)
```
```{r, fig.cap = "Case 2. Prior predictive checks", fig.height = 3}
meas_df <- sim_inc %>% rename(y = measured_inc)
plot_predictive_checks(sens_inc, meas_df)
```
```{r}
pars_hat <- c("I0", "R0", "beta", "rho")
gamma <- 0.5
sigma <- 0.5
consts <- sd_constants(mdl)
ODE_fn <- "SEIR"
stan_fun <- stan_ode_function(mdl_path, ODE_fn, pars = consts$name[c(2, 1)],
const_list = list(N = N, par_gamma = gamma,
sigma = sigma))
fun_exe_line <- str_glue(" o = ode_rk45({ODE_fn}, x0, t0, ts, params);")
stan_data <- stan_data("y", type = "int", inits = FALSE)
stan_params <- paste(
"parameters {",
" real<lower = 0> beta;",
" real<lower = 0, upper = 1> rho;",
" real<lower = 0> I0;",
" real<lower = 0> R0;",
"}", sep = "\n")
stan_tp <- paste(
"transformed parameters{",
" vector[n_difeq] o[n_obs]; // Output from the ODE solver",
" real x[n_obs];",
" vector[n_difeq] x0;",
" real params[n_params];",
" x0[1] = 5234 - I0 - R0;",
" x0[2] = 0;",
" x0[3] = I0;",
" x0[4] = R0;",
" x0[5] = I0;",
" params[1] = beta;",
" params[2] = rho;",
fun_exe_line,
" x[1] = o[1, 5] - x0[5];",
" for (i in 1:n_obs-1) {",
" x[i + 1] = o[i + 1, 5] - o[i, 5] + 1e-4;",
" }",
"}", sep = "\n")
stan_model <- paste(
"model {",
" beta ~ lognormal(0, 1);",
" rho ~ beta(2, 2);",
" I0 ~ lognormal(0, 1);",
" R0 ~ normal(0, 1e4);",
" y ~ poisson(x);",
"}",
sep = "\n")
stan_text <- paste(stan_fun, stan_data, stan_params,
stan_tp, stan_model, sep = "\n")
stan_filepath <- "./Stan_files/Synthetic_data/Case_2.stan"
create_stan_file(stan_text, stan_filepath)
```
```{r}
stan_d <- list(n_obs = nrow(sim_inc),
y = sim_inc$measured_inc,
n_params = 2,
n_difeq = 5,
t0 = 0,
ts = 1:length(sim_inc$measured_inc))
```
### First calibration attempt
\hfill
Once we validate the prior, we run four chains of 1,000 samples allocated
to each phase (_warm-up_ and _sampling_).
```{r, results = 'hide'}
fldr <- "./backup_objs/Synthetic_data/Case_2/Case_2.1"
dir.create(fldr, showWarnings = FALSE, recursive = TRUE)
file_path <- file.path(fldr, "Case_2.1.rds")
if(!file.exists(file_path)) {
mod <- cmdstan_model(stan_filepath)
fit <- mod$sample(data = stan_d,
seed = 638588660,
chains = 4,
parallel_chains = 4,
iter_warmup = 1000,
iter_sampling = 1000,
refresh = 5,
save_warmup = FALSE,
output_dir = fldr)
fit$save_object(file_path)
} else {
fit <- readRDS(file_path)
}
```
#### HMC Diagnostics
\hfill
Stan informs that there are 98 divergent iterations, an indication of
pathological behaviour that may lead to biased results.
```{r, message = TRUE}
# We generated this file from $fit$cmdstan_diagnose()
fileName <- file.path(fldr, "diag_2.1.txt")
if(!file.exists(fileName)) {
diagnosis <- fit$cmdstan_diagnose()
writeLines(diagnosis$stdout, fileName)
} else {
readChar(fileName, file.info(fileName)$size) %>% cat()
}
```
#### Pairs-plot
\hfill
Thanks to the _bayesplot_ package, we can pinpoint the divergent iterations
(red crosses) in the parameter space (Figure 6).
```{r, fig.cap = "Case 2.1. Pairs-plot"}
np_cp <- nuts_params(fit)
mcmc_pairs(fit$draws(), np = np_cp, pars = pars_hat,
off_diag_args = list(size = 0.75))
```
#### Trace plots
\hfill
Interestingly, at first sight (Figure 7), chains appear to converge. There are
no evident trends, and they seem to mix.
```{r, fig.cap = "Case 2.2. Trace plots", fig.height = 3.5}
mcmc_trace(fit$draws(), pars_hat)
```
Upon further inspection (Figure 8), though, we identify the following issues in
$\beta$'s chains:
- *Chain 1*: Between samples 250 and 500, the chain is stuck,
as it does not exhibit the expected random behaviour (jumping up and down). On
the contrary, it stays in a similar location for several iterations.
- *Chain 2*: At the end of the sampling phase, the chain is stuck. The chain
around that point (~1.3) stays for several iterations.
```{r, fig.height = 3.5, fig.cap = "Case 2.1. Beta's trace plots"}
beta_draws <- extract_variable_matrix(fit$draws(), "beta") %>%
as.data.frame() %>%
mutate(id = row_number()) %>%
pivot_longer(-id, names_to = "Chain")
ggplot(beta_draws, aes(x = id, y = value)) +
geom_line(aes(colour = Chain)) +
scale_colour_manual(values = sequential_hcl(7, palette = "Blues 3")[1:4]) +
facet_wrap(~Chain) +
labs(subtitle = "Effective contact rate's chains") +
theme_pubr()
```
#### Metrics
\hfill
We confirm these findings with $\widehat{R}$ and $ESS_{bulk}$. All of the
four parameters show $\widehat{R}$ values higher than the recommended threshold
(1.01), indicating that convergence was not achieved. Likewise, only
one $ESS_{bulk}$ is above the threshold (400). Consequently, we deem the
computation as *not valid*.
```{r}
par_matrices <- lapply(pars_hat, function(par) {
extract_variable_matrix(fit$draws(), par)
})
ess_vals <- map_dbl(par_matrices, ess_bulk)
r_hat_vals <- map_dbl(par_matrices, rhat)
smy_df <- data.frame(par = c("I(0)", "R(0)", "$\\beta$", "$\\rho$"),
ess_bulk = ess_vals,
rhat = r_hat_vals)
```
```{r, echo = FALSE}
colnames(smy_df) <- c("par", "$ESS_{bulk}$", "$\\widehat{R}$")
kable(smy_df, booktab = TRUE, escape = FALSE)
```
### Second calibration attempt
According to the [Stan manual](https://mc-stan.org/misc/warnings.html), one
strategy to address divergent transitions is increasing the _adapt_delta_
parameter. It is the target average proposal acceptance probability during
Stan’s adaptation period, and increasing it will force Stan to take smaller
steps. We increase this parameter from its default value (0.8) to 0.99 and
re-run the sampling process.
```{r, results = 'hide'}
fldr <- "./backup_objs/Synthetic_data/Case_2/Case_2.2"
dir.create(fldr, showWarnings = FALSE, recursive = TRUE)
file_path <- file.path(fldr, "Case_2.2.rds")
if(!file.exists(file_path)) {
mod <- cmdstan_model(stan_filepath)
fit <- mod$sample(data = stan_d,
seed = 638588660,
chains = 4,
parallel_chains = 4,
iter_warmup = 1000,
iter_sampling = 1000,
adapt_delta = 0.99,
refresh = 5,
save_warmup = FALSE,
output_dir = fldr)
fit$save_object(file_path)
} else {
fit <- readRDS(file_path)
}
```
#### HMC Diagnostics
\hfill
By increasing _adapt_delta_, we eliminated the divergent transitions at the cost
of hitting the maximum treedepth threshold. Unlike divergent transitions,
this warning is not a validity concern but an efficiency indicator. Despite the
fact that this indicator informs us about the complexity of the posterior
explored, we could still use the samples for further analysis if the convergence
and efficiency metrics are satisfactory.
```{r, message = TRUE}
# We generated this file from $fit$cmdstan_diagnose()
fileName <- file.path(fldr, "diag_2.2.txt")
if(!file.exists(fileName)) {
diagnosis <- fit$cmdstan_diagnose()
writeLines(diagnosis$stdout, fileName)
} else {
readChar(fileName, file.info(fileName)$size) %>% cat()
}
```
#### Pairs-plot
\hfill
This updated pairs-plot (Figure 9) highlights the iterations where the algorithm
hit the maximum treedepth. That is, the maximum allowed number of steps taken
within an iteration.
```{r, fig.cap = "Case 2.2. Pairs-plot"}
np_cp <- nuts_params(fit)
mcmc_pairs(fit$draws(), np = np_cp, pars = pars_hat,
off_diag_args = list(size = 0.75),
max_treedepth = 9)
```
#### Trace plots
\hfill
Trace plots (Figure 10) do not reveal evident issues in convergence and
efficiency.
```{r, fig.cap = "Case 2.2. Trace plots", fig.height = 3.5}
mcmc_trace(fit$draws(), pars_hat)
```
#### Metrics
\hfill
$\widehat{R}$ confirms the visual inspection from the trace plots. That is, the
chains do converge. However, hitting the maximum treedepth affected efficiency,
considering that three (out of four) parameters barely exceeded the acceptable
threshold (> 400).
```{r}
par_matrices <- lapply(pars_hat, function(par) {
extract_variable_matrix(fit$draws(), par)
})
ess_vals <- map_dbl(par_matrices, ess_bulk)
r_hat_vals <- map_dbl(par_matrices, rhat)
smy_df <- data.frame(par = c("I(0)", "R(0)", "$\\beta$", "$\\rho$"),
ess_bulk = ess_vals,
rhat = r_hat_vals)
```
```{r, echo = FALSE}
colnames(smy_df) <- c("par", "$ESS_{bulk}$", "$\\widehat{R}$")
kable(smy_df, booktab = TRUE, escape = FALSE)
```
### Third calibration attempt
To guarantee that the effective sample size is well above its acceptable
threshold, we increase the maximum number of steps allowed per iteration and
double the number of samples in the _warm_up_ and _sampling_ phases.
```{r, results = 'hide'}
fldr <- "./backup_objs/Synthetic_data/Case_2/Case_2.3"
dir.create(fldr, showWarnings = FALSE, recursive = TRUE)
file_path <- file.path(fldr, "Case_2.3.rds")
if(!file.exists(file_path)) {
mod <- cmdstan_model(stan_filepath)
fit <- mod$sample(data = stan_d,
seed = 638588660,
chains = 4,
parallel_chains = 4,
iter_warmup = 2000,
iter_sampling = 2000,
adapt_delta = 0.99,
max_treedepth = 20,
refresh = 5,
save_warmup = FALSE,
output_dir = fldr)
fit$save_object(file_path)
} else {
fit <- readRDS(file_path)
}
```
#### HMC Diagnostics
\hfill
HMC diagnostics are satisfactory and indicate no pathological behaviour.
```{r, message = TRUE}
# We generated this file from fit$cmdstan_diagnose()
fileName <- file.path(fldr, "diag_2.3.txt")
if(!file.exists(fileName)) {
diagnosis <- fit$cmdstan_diagnose()
writeLines(diagnosis$stdout, fileName)
} else {
readChar(fileName, file.info(fileName)$size) %>% cat()
}
```
#### Trace plots
\hfill
Trace plots (Figure 11) do not reveal evident issues in convergence and
efficiency.
```{r, fig.height = 3, fig.cap = "Case 2.3. Trace plots"}
mcmc_trace(fit$draws(), pars_hat)
```
#### Metrics
\hfill
$\widehat{R}$ and $ESS_{bulk}$ are within the predetermined thresholds
(< 1.01 and > 400, respectively). Based on all of these diagnostics,
we *accept the computation* and move forward to the
*posterior predictive checking * stage.
\hfill
```{r}
par_matrices <- lapply(pars_hat, function(par) {
extract_variable_matrix(fit$draws(), par)
})
ess_vals <- map_dbl(par_matrices, ess_bulk)
r_hat_vals <- map_dbl(par_matrices, rhat)
smy_df <- data.frame(par = c("I(0)", "R(0)", "$\\beta$", "$\\rho$"),
ess_bulk = ess_vals,
rhat = r_hat_vals)
```
```{r, echo = FALSE}
colnames(smy_df) <- c("par", "$ESS_{bulk}$", "$\\widehat{R}$")
kable(smy_df, booktab = TRUE, escape = FALSE)
```
### Posterior predictive checking
By comparing simulated trajectories and the actual data (Figure 12), we see that
this structure is an adequate explanation of the observed incidence. Thus, we
_accept the model_ for parameter estimation.
```{r case2_fit, fig.height = 3, fig.cap = "Case 2. Fit"}
posterior_df <- fit$draws() %>% as_draws_df()
plot_ts_fit(posterior_df, actual_df)
```
### Parameter estimations
Before estimating marginal posterior uncertainty intervals, it is recommended
to check for the correlations among parameters (Figure 13). Here, we can
appreciate this model's complexity by looking at the large degree of
correlations in this parameter space.
```{r case_2_distributions, fig.cap = "Case 2. Marginal and joint distributions"}
pars_df <- posterior_df[, pars_hat]
pairs_posterior(pars_df, strip_text = 10)
pars_list[[2]] <- pars_df %>% mutate(Case = "2",
iter = row_number())
```
### Uncertainty intervals
```{r}
pars_df %>% mutate(id = row_number()) %>%
pivot_longer(-id) %>%
group_by(name) %>%
summarise(Mean = round(mean(value), 2),
bound_val = round(quantile(value, c(0.025, 0.975)),2),
bound_type = c("2.5\\%", "97.5\\%")) %>%
pivot_wider(names_from = bound_type, values_from = bound_val) -> est_df
```
```{r, echo = FALSE}
est_df$name <- c("$\\beta$", "I(0)", "R(0)","$\\rho$")
kable(est_df, booktab = TRUE, escape = FALSE)
```
```{r case2_MASE}
source("./R/Metrics_utils.R")
mase_list[[2]] <- get_mase_fit(posterior_df, sim_inc$measured_inc) %>%
mutate(Case = "2")
```
## Case 3
Although Case 2 is computationally satisfactory, the uncertainty around the
estimates could be improved with more data. Fortunately, a new preprint has just
been published. This study reports that 30 % of the population has antibodies
against this virus. In light of this new data, we update the calibration setup.
### Priors
#### Prior distributions
* $\beta \sim lognormal(0,1)$
* $\rho \sim Beta(2,2)$
* $I(0) \sim lognormal(0,1)$
#### Unmodelled predictors
\hfill
```{r}
data.frame(Predictor = c("$\\sigma$", "$\\gamma$", "E(0)", "R(0)", "N"),
Value = c(0.5, 0.5, 0, 1570, 5234)) -> df
kable(df, booktab = TRUE, escape = FALSE)
```
### Prior predictive checks
As in Cases 1 & 2, we check that our prior information captures the data. Based
on the results (Figure 14), we *accept the prior* and proceed to fit the model.
```{r case_3_prior_pred_checks}
fldr <- "./backup_objs/Synthetic_data/Case_3"
dir.create(fldr, showWarnings = FALSE, recursive = TRUE)
file_path <- file.path(fldr, "prior_sims.rds")
if(!file.exists(file_path)) {
stock_list <- list(E = 0,
R = 1570)
const_list <- list(N = N,
sigma = 0.5,
par_gamma = 0.5)
set.seed(2041)
beta_vals <- rlnorm(n_sims)
rho_vals <- rbeta(n_sims, 2, 2)
I0_vals <- rlnorm(n_sims)
mdl2 <- read_xmile(mdl_path, stock_list = stock_list,
const_list = const_list)
consts_df <- data.frame(par_beta = beta_vals,
rho = rho_vals)
stocks_df <- data.frame(I = I0_vals,
S = N - I0_vals - 1570,
C = I0_vals)
sens_o <- sd_sensitivity_run(mdl2$deSolve_components, start_time = 0,
stop_time = 91, timestep = 1 / 32,
multicore = TRUE, n_cores = 4,
integ_method = "rk4", stocks_df = stocks_df,