-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathS7_Text.Rmd
1584 lines (1179 loc) · 45.2 KB
/
S7_Text.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: "S7 Appendix"
output:
pdf_document:
number_sections: true
header-includes:
- \usepackage{booktabs}
bibliography: bibliography.bib
---
This appendix aims to illustrate the inference process applied to DGP3. This
structure consists of nine candidate deterministic process models (PM3) and an
observational or measurement model (OM2) that accounts for the daily COVID-19
cases detected in Ireland's first wave. We envision this inference process in a
Bayesian context, where the predicted values stem from DGP3's expected value,
which is approximated using Hamiltonian Monte Carlo (HMC).
\tableofcontents
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE)
library(bayesplot)
library(cmdstanr)
library(dplyr)
library(extraDistr)
library(imputeTS)
library(kableExtra)
library(lubridate)
library(Metrics)
library(posterior)
library(purrr)
library(readr)
library(readsdr)
library(readxl)
library(reshape2)
library(rstan)
library(stringr)
library(tictoc)
library(tidyr)
source("./R_scripts/data.R")
source("./R_scripts/helpers.R")
source("./R_scripts/par_summary.R")
source("./R_scripts/plots.R")
source("./R_scripts/R_estimates.R")
folder <- "./Saved_objects/SEI3R_SMTH"
stan_folder <- "./Stan_files"
data_list <- get_data()
obs_df <- data_list[["Daily"]]
```
\newpage
# DGP3 - Adaptive expectations
## Process model (PM3)
\begin{equation}
\frac{dS}{dt} = - S_t \lambda_t
\end{equation}
\begin{equation}
\frac{dE}{dt} = S_t \lambda_t - \sigma E_t
\end{equation}
\begin{equation}
\frac{dP}{dt} = \omega \sigma E_t - \eta P_t
\end{equation}
\begin{equation}
\frac{dI}{dt} = \eta P_t - \gamma I_t
\end{equation}
\begin{equation}
\frac{dA}{dt} = (1-\omega) \sigma E_t - \kappa A_t
\end{equation}
\begin{equation}
\frac{dR}{dt} = \kappa A_t + \gamma I_t
\end{equation}
\begin{equation}
\lambda_t = \frac{ \beta_t(I(_t + P_t + \mu A_t)}{N_t}
\end{equation}
\begin{equation}
\beta_t = \zeta Z^1_t
\end{equation}
\begin{equation}
\frac{dZ^i}{dt} = \begin{cases}
\frac{(\upsilon - Z^i_t)}{(\nu^{-1}/n)} \quad \textrm{for} \quad i = n\\
\\
\frac{(Z^{i+1}_t - Z^i_t)}{(\nu^{-1}/n)} \quad \textrm{for} \quad i < n \end{cases}
\end{equation}
Where $i \in (\mathbb{Z_+})^n$ denotes each of the stages in an $n$-order
information delay structure.
## Measurement model candidates (OM2)
\begin{equation}
\frac{dC}{dt} = \eta P_t - C_t\delta(t \, mod \, 1)
\end{equation}
### Poisson
\begin{equation}
y_d^1\sim Pois(C_t)
\end{equation}
### Negative binomial
\begin{equation}
y_d^1\sim NBin(C_t, \phi^{-1})
\end{equation}
\newpage
# Inference (Poisson)
## Priors
For all of the nine candidate models, we adopt the following priors:
\hfill
```{r, fig.height = 5}
source("./R_scripts/plots.R")
plot_priors()
```
```{r inference_lists}
source("./R_scripts/stan_utils.R")
source("./R_scripts/write_SEI3R_model.R")
n_orders <- 9
pars <- c("zeta", "nu", "upsilon", "P_0")
posterior_list <- vector("list", n_orders)
sim_incidences_list <- vector("list", n_orders)
Z_list <- vector("list", n_orders)
ll_list <- vector("list", n_orders)
time_list <- vector("list", n_orders)
time_list_nb <- vector("list", n_orders)
```
## Sampling
```{r}
stan_d <- list(n_obs = nrow(obs_df),
y1 = obs_df$y1,
n_params = 3,
n_difeq = NA,
t0 = 0,
ts = 1:nrow(obs_df))
```
For validation purposes, we show the results from the sampling algorithm (HMC)
by means of trace plots. These visualisation tools are time-series of the draws
for a particular parameter. Here, _time_ refers to the order in which the draws
were sampled. These plots suggest that there are no issues in the sampling
procedure. Further diagnostics (see the Github repository) indicate that no
_pathological behaviour_ was observed during the process, and adequate
Effective Sample Sizes and potential scale reduction factors
($\widehat{R} < 1.01$) were obtained. These outcomes suggest that the Markov
chains converged to the posterior distribution.
### 1st order delay
```{r}
dly_o <- 1 # delay order
mdl_path <- str_glue("./models/SEI3R_order_{dly_o}.stmx")
mdl <- read_xmile(mdl_path)
stocks <- sd_stocks(mdl)
stan_path <- str_glue("./Stan_files/SEI3R_{dly_o}_smth.stan")
write_SEI3R_model(mdl_path, stan_path)
```
```{r fit_SMTH_1}
stan_d <- nrow(stocks)
fit_options <- list(stan_d = stan_d,
seed = 931918239,
warmup = 4000,
sampling = 2000,
adapt_delta = 0.90,
step_size = 0.0001) # default
results <- run_stan_file(dly_o, fit_options, folder, stan_folder)
time_list[[dly_o]] <- calculate_time(results$time)
sf <- results$sf
```
```{r, fig.height = 3.5}
plot_traces(sf, pars)
```
```{r}
posterior_df <- as.data.frame(sf)
posterior_list[[dly_o]] <- posterior_df
sim_incidences_list[[dly_o]] <- construct_incidence_df(posterior_df, dly_o)
Z_list[[dly_o]] <- extract_timeseries_stock("Z", posterior_df,
stocks, "o")
ll_list[[dly_o]] <- posterior_df |> select(log_lik)
```
### 2nd order delay
```{r}
dly_o <- 2 # delay order
mdl_path <- str_glue("./models/SEI3R_order_{dly_o}.stmx")
mdl <- read_xmile(mdl_path)
stocks <- sd_stocks(mdl)
stan_path <- str_glue("./Stan_files/SEI3R_{dly_o}_smth.stan")
write_SEI3R_model(mdl_path, stan_path)
```
```{r fit_SMTH_2}
stan_d <- nrow(stocks)
fit_options <- list(stan_d = stan_d,
seed = 693132317,
warmup = 2000,
sampling = 2000,
adapt_delta = 0.95, # default
step_size = 0.0001)
results <- run_stan_file(dly_o, fit_options, folder, stan_folder)
time_list[[dly_o]] <- calculate_time(results$time)
sf <- results$sf
```
```{r, fig.height = 3.5}
plot_traces(sf, pars)
```
```{r}
posterior_df <- as.data.frame(sf)
posterior_list[[dly_o]] <- posterior_df
sim_incidences_list[[dly_o]] <- construct_incidence_df(posterior_df, dly_o)
Z_list[[dly_o]] <- extract_timeseries_stock("Z", posterior_df,
stocks, "o")
ll_list[[dly_o]] <- posterior_df |> select(log_lik)
```
### 3rd order delay
```{r}
dly_o <- 3 # delay order
mdl_path <- str_glue("./models/SEI3R_order_{dly_o}.stmx")
mdl <- read_xmile(mdl_path)
stocks <- sd_stocks(mdl)
stan_path <- "./Stan_files/SEI3R_3_smth.stan"
write_SEI3R_model(mdl_path, stan_path)
```
```{r fit_SMTH_3}
stan_d <- nrow(stocks)
fit_options <- list(stan_d = stan_d,
seed = 477626707,
warmup = 2000,
sampling = 2000,
step_size = 0.0001,
adapt_delta = 0.95) # default
results <- run_stan_file(dly_o, fit_options, folder, stan_folder)
time_list[[dly_o]] <- calculate_time(results$time)
sf <- results$sf
```
```{r, fig.height = 3.5}
plot_traces(sf, pars)
```
```{r}
posterior_df <- as.data.frame(sf)
posterior_list[[dly_o]] <- posterior_df
sim_incidences_list[[dly_o]] <- construct_incidence_df(posterior_df, dly_o)
Z_list[[dly_o]] <- extract_timeseries_stock("Z", posterior_df,
stocks, "o")
ll_list[[dly_o]] <- posterior_df |> select(log_lik)
```
### 4th order delay
```{r}
dly_o <- 4 # delay order
mdl_path <- str_glue("./models/SEI3R_order_{dly_o}.stmx")
mdl <- read_xmile(mdl_path)
stocks <- sd_stocks(mdl)
stan_path <- str_glue("./Stan_files/SEI3R_{dly_o}_smth.stan")
write_SEI3R_model(mdl_path, stan_path)
```
```{r fit_SMTH_4}
stan_d <- nrow(stocks)
fit_options <- list(stan_d = stan_d,
seed = 986614638,
warmup = 2000,
sampling = 2000,
step_size = 0.001,
adapt_delta = 0.8) # default
results <- run_stan_file(dly_o, fit_options, folder, stan_folder)
time_list[[dly_o]] <- calculate_time(results$time)
sf <- results$sf
```
```{r, fig.height = 3.5}
plot_traces(sf, pars)
```
```{r}
posterior_df <- as.data.frame(sf)
posterior_list[[dly_o]] <- posterior_df
sim_incidences_list[[dly_o]] <- construct_incidence_df(posterior_df, dly_o)
Z_list[[dly_o]] <- extract_timeseries_stock("Z", posterior_df,
stocks, "o")
ll_list[[dly_o]] <- posterior_df |> select(log_lik)
```
### 5th order delay
```{r}
dly_o <- 5 # delay order
mdl_path <- str_glue("./models/SEI3R_order_{dly_o}.stmx")
mdl <- read_xmile(mdl_path)
stocks <- sd_stocks(mdl)
stan_path <- str_glue("./Stan_files/SEI3R_{dly_o}_smth.stan")
write_SEI3R_model(mdl_path, stan_path)
```
```{r fit_SMTH_5}
stan_d <- nrow(stocks)
fit_options <- list(stan_d = stan_d,
seed = 549943389,
warmup = 2000,
sampling = 2000,
step_size = 0.001,
adapt_delta = 0.8) # default
results <- run_stan_file(dly_o, fit_options, folder, stan_folder)
time_list[[dly_o]] <- calculate_time(results$time)
sf <- results$sf
```
```{r, fig.height = 3.5}
plot_traces(sf, pars)
```
```{r}
posterior_df <- as.data.frame(sf)
posterior_list[[dly_o]] <- posterior_df
sim_incidences_list[[dly_o]] <- construct_incidence_df(posterior_df, dly_o)
Z_list[[dly_o]] <- extract_timeseries_stock("Z", posterior_df,
stocks, "o")
S_df <- extract_timeseries_stock("S", posterior_df,
stocks, "o")
ll_list[[dly_o]] <- posterior_df |> select(log_lik)
```
### 6th order delay
```{r}
dly_o <- 6 # delay order
mdl_path <- str_glue("./models/SEI3R_order_{dly_o}.stmx")
mdl <- read_xmile(mdl_path)
stocks <- sd_stocks(mdl)
stan_path <- str_glue("./Stan_files/SEI3R_{dly_o}_smth.stan")
write_SEI3R_model(mdl_path, stan_path)
```
```{r fit_SMTH_6}
stan_d <- nrow(stocks)
fit_options <- list(stan_d = stan_d,
seed = 846206826,
warmup = 2000,
sampling = 2000,
adapt_delta = 0.90, # default
step_size = 0.001)
results <- run_stan_file(dly_o, fit_options, folder, stan_folder)
time_list[[dly_o]] <- calculate_time(results$time)
sf <- results$sf
```
```{r, fig.height = 3.5}
plot_traces(sf, pars)
```
```{r}
posterior_df <- as.data.frame(sf)
posterior_list[[dly_o]] <- posterior_df
sim_incidences_list[[dly_o]] <- construct_incidence_df(posterior_df, dly_o)
Z_list[[dly_o]] <- extract_timeseries_stock("Z", posterior_df,
stocks, "o")
ll_list[[dly_o]] <- posterior_df |> select(log_lik)
```
### 7th order delay
```{r}
dly_o <- 7 # delay order
mdl_path <- str_glue("./models/SEI3R_order_{dly_o}.stmx")
mdl <- read_xmile(mdl_path)
stocks <- sd_stocks(mdl)
stan_path <- str_glue("./Stan_files/SEI3R_{dly_o}_smth.stan")
write_SEI3R_model(mdl_path, stan_path)
```
```{r fit_SMTH_7}
stan_d <- nrow(stocks)
fit_options <- list(stan_d = stan_d,
seed = 373573480,
warmup = 2000,
sampling = 2000,
adapt_delta = 0.95, # default
step_size = 0.0001)
results <- run_stan_file(dly_o, fit_options, folder, stan_folder)
time_list[[dly_o]] <- calculate_time(results$time)
sf <- results$sf
```
```{r, fig.height = 3.5}
plot_traces(sf, pars)
```
```{r}
posterior_df <- as.data.frame(sf)
posterior_list[[dly_o]] <- posterior_df
sim_incidences_list[[dly_o]] <- construct_incidence_df(posterior_df, dly_o)
Z_list[[dly_o]] <- extract_timeseries_stock("Z", posterior_df,
stocks, "o")
ll_list[[dly_o]] <- posterior_df |> select(log_lik)
```
### 8th order delay
```{r}
dly_o <- 8 # delay order
mdl_path <- str_glue("./models/SEI3R_order_{dly_o}.stmx")
mdl <- read_xmile(mdl_path)
stocks <- sd_stocks(mdl)
stan_path <- str_glue("./Stan_files/SEI3R_{dly_o}_smth.stan")
write_SEI3R_model(mdl_path, stan_path)
```
```{r fit_SMTH_8}
stan_d <- nrow(stocks)
fit_options <- list(stan_d = stan_d,
seed = 107900538,
warmup = 4000,
sampling = 2000,
adapt_delta = 0.80, # default
step_size = 0.001)
results <- run_stan_file(dly_o, fit_options, folder, stan_folder)
time_list[[dly_o]] <- calculate_time(results$time)
sf <- results$sf
```
```{r, fig.height = 3.5}
plot_traces(sf, pars)
```
```{r}
posterior_df <- as.data.frame(sf)
posterior_list[[dly_o]] <- posterior_df
sim_incidences_list[[dly_o]] <- construct_incidence_df(posterior_df, dly_o)
Z_list[[dly_o]] <- extract_timeseries_stock("Z", posterior_df,
stocks, "o")
ll_list[[dly_o]] <- posterior_df |> select(log_lik)
```
### 9th order delay
```{r}
dly_o <- 9 # delay order
mdl_path <- str_glue("./models/SEI3R_order_{dly_o}.stmx")
mdl <- read_xmile(mdl_path)
stocks <- sd_stocks(mdl)
stan_path <- str_glue("./Stan_files/SEI3R_{dly_o}_smth.stan")
write_SEI3R_model(mdl_path, stan_path)
```
```{r fit_SMTH_9}
stan_d <- nrow(stocks)
fit_options <- list(stan_d = stan_d,
seed = 790975884,
warmup = 4000,
sampling = 2000,
adapt_delta = 0.80, # default
step_size = 0.001)
results <- run_stan_file(dly_o, fit_options, folder, stan_folder)
time_list[[dly_o]] <- calculate_time(results$time)
sf <- results$sf
```
```{r, fig.height = 3.5}
plot_traces(sf, pars)
```
```{r}
posterior_df <- as.data.frame(sf)
posterior_list[[dly_o]] <- posterior_df
sim_incidences_list[[dly_o]] <- construct_incidence_df(posterior_df, dly_o)
Z_list[[dly_o]] <- extract_timeseries_stock("Z", posterior_df,
stocks, "o")
ll_list[[dly_o]] <- posterior_df |> select(log_lik)
```
\newpage
## Expected values
### Predicted incidence compared to daily case counts
\hfill
```{r inc_fits_g, fig.height = 7}
data_df <- rename(obs_df, y = y1)
plot_daily_fit_by_order(sim_incidences_list, data_df, data_shape = 18, "C[t]")
```
```{r, fig.height = 7}
set.seed(19860618)
map_df(sim_incidences_list, function(df) {
sample_iters <- sample.int(8000, 100)
df <- df |> filter(iter %in% sample_iters)
}) -> sample_incidences
imap_dfr(Z_list, function(df, i) {
sample_iters <- sample.int(8000, 100)
df <- df |> filter(iter %in% sample_iters) |>
mutate(order = i)
}) -> sample_Z
df_labels <- data.frame(x = 6, y = 750,
label = str_glue("Order: {1:9}"),
order = 1:9)
y_lab <- "C[t]"
x_lab <- "Time since the first reported case [Days]"
data_df <- rename(obs_df, y = y1)
g1 <- plot_fits_by_order(sample_incidences, data_df, df_labels, 18, x_lab,
y_lab = y_lab)
data_df <- rename(obs_df, y = y2)
df_labels <- df_labels |> mutate(x = 75, y = 0.85)
y_lab <- "Z[t]"
x_lab <- "Time since the first reported case [Days]"
g2 <- plot_fits_by_order(sample_Z, data_df, df_labels, 16,
x_lab, y_lab)
ggsave("./paper_plots/Fig_06_GSB.pdf",
plot = g1 + g2, height = 7, width = 5)
ggsave("./paper_plots/Fig_06_GSB.eps",
plot = g1 + g2, height = 7, width = 5, device = cairo_ps)
```
\newpage
### Predicted relative contact rate compared to mobility indexes
\hfill
```{r mob_fits_g, fig.height = 7}
data_df <- rename(obs_df, y = y2)
plot_daily_fit_by_order(Z_list, data_df, 16, "Z[t]")
```
\newpage
### Likelihood by delay order
\hfill
```{r, fig.height = 4}
ll_df <- imap_dfr(ll_list, function(df, i) mutate(df, order = i))
plot_ll_by_order(ll_df)
```
\hfill
```{r}
ll_df |> rename(value = log_lik) |>
var_quantiles_by_order(rnd = 1) -> kable_df
knitr::kable(kable_df, "latex", booktabs = TRUE)
```
\newpage
### Accuracy
To measure the accuracy of the predicted values, we calculate the Mean absolute
scale error (MASE) for each trajectory (incidence and relative
transmission rate) generated from the sampling procedure. Incidence trajectories
are compared to daily case counts, whereas relative transmission rates are
contrasted to mobility indexes. We present the results graphically (violin
plots) and numerically (tables). Dotted lines in the plots indicate the
performance threshold (1). Values below the unity indicate good performance.
\hfill
```{r}
mase_inc <- imap_dfr(sim_incidences_list, mase_per_iter,
data_vector = obs_df$y1)
summary_mase <- mase_inc |> group_by(order) |>
summarise(mean = mean(mase),
q_val = quantile(mase, c(0.025, 0.25, 0.5, 0.75, 0.975)),
q_type = c("q2.5", "q25", "q50", "q75", "q97.5")) |>
ungroup()
ggplot(mase_inc, aes(x = order, y = mase)) +
geom_violin(aes(group = order), colour = STH_colour) +
scale_x_continuous(breaks = 1:9) +
scale_y_continuous(limits = c(0.95, 1.01)) +
stat_smooth(data = summary_mase, aes(x = order, y = mean),
geom = 'line', alpha = 0.25, se = FALSE,
colour = STH_colour, size = 0.5, linetype = "dashed") +
geom_hline(yintercept = 1, linetype = "dotted", colour = "grey50") +
theme_pubr() +
labs(subtitle = "Incidence prediction accuracy",
y = "MASE [Unitless]",
x = "Delay order")
```
\hfill
```{r}
wide_smy_mase <- summary_mase |>
mutate(q_val = round(q_val, 3),
mean = round(mean, 3)) |>
pivot_wider(names_from = q_type, values_from = q_val)
knitr::kable(wide_smy_mase, "latex", booktabs = TRUE)
```
```{r, fig.height = 3.5}
mase_mob <- imap_dfr(Z_list, mase_per_iter,
data_vector = obs_df$y2)
summary_mase_mob <- mase_mob |> group_by(order) |>
summarise(mean = mean(mase),
q_val = quantile(mase, c(0.025, 0.25, 0.5, 0.75, 0.975)),
q_type = c("q2.5", "q25", "q50", "q75", "q97.5")) |>
ungroup()
ggplot(mase_mob, aes(x = order, y = mase)) +
geom_violin(aes(group = order), colour = STH_colour) +
scale_x_continuous(breaks = 1:9) +
stat_smooth(data = summary_mase_mob, aes(x = order, y = mean),
geom = 'line', alpha = 0.5, se = FALSE,
colour = STH_colour, size = 0.5, linetype = "dashed") +
geom_hline(yintercept = 1, linetype = "dotted", colour = "grey50") +
theme_pubr() +
labs(subtitle = "Accuracy of the predicted transmission rate",
x = "Delay order",
y = "MASE [Unitless]")
```
\hfill
```{r}
wide_smy_mob <- summary_mase_mob |>
mutate(q_val = round(q_val, 3),
mean = round(mean, 3)) |>
pivot_wider(names_from = q_type, values_from = q_val)
knitr::kable(wide_smy_mob, "latex", booktabs = TRUE)
```
\newpage
## Posterior distribution
This section summarises the parameter samples obtained from the HMC algorithm.
The first summary corresponds to violin plots by parameter and the order of the
delay. The second summary corresponds to a table that shows parameter means and
standard deviations (in parenthesis) by delay order. Here, we notice that
standard deviations are significantly small compared to the average value
(mean). In other words, the probability mass is located in a low-volume and
high-density region of the parameter space.
\hfill
```{r, fig.height = 5}
imap_dfr(posterior_list, function(df, i) {
df |> select(zeta, P_0, nu, upsilon) |>
mutate(R_0 = estimate_r(zeta), iter = row_number(), order = i) |>
pivot_longer(c(-iter, -order))
}) -> tidy_pars
ggplot(tidy_pars, aes(x = as.factor(order), y = value)) +
geom_violin(aes(group = order), colour = STH_colour) +
facet_wrap(~name, scales = "free", labeller = label_parsed) +
labs(x = "Delay order", y = "Value") +
theme_pubr()
```
\hfill
```{r estimate_summary_t}
pars_summary_pois <- tidy_pars |> group_by(order, name) |>
summarise(mean = sprintf("%04.2f", mean(value)),
sd = sprintf("%05.3f", sd(value))) |> ungroup()
summary_est <- pars_summary_pois |> mutate(value = str_glue("{mean} ({sd})")) |>
select(-mean, -sd) |>
pivot_wider(names_from = name, values_from = value)
kable_df <- summary_est
kable_df <- kable_df[, c("order", "R_0", "zeta", "nu", "upsilon", "P_0")]
colnames(kable_df) <- c("Order", "R(0)", "$\\zeta$", "$\\nu$", "$\\upsilon$", "P(0)")
knitr::kable(kable_df, "latex", booktabs = TRUE, escape = FALSE)
```
## Candidate selection
In the preceding sections, we estimated performance metrics to ascertain which
model candidate (delay order) explains the observed dynamics more accurately.
On the one hand, metrics of incidence accuracy (MASE) show that increasing the
delay order leads to marginal better fits, but it also decreases the
log-likelihood. On the other hand, the mobility data's best fit (MASE) occurs
when the delay order is equal to **four**.
# Computational time
```{r}
imap_dfr(time_list, function(time_val, order) {
data.frame(order = order, time = time_val)
}) -> time_df
tt <- sum(time_df$time) |> round(0)
plot_time_comparison(time_df, tt)
```
\newpage
# Inference (Negative binomial)
## Five unknowns
Misspecification in the measurement model, such as unaccounted overdispersion
and unmodelled variability, can lead to overly confident conclusions
[@Breto_2018] or biased estimates. In the preceding section, we employed a
stringent measurement model (Poisson), which ties the observation mean and
variance. In this section, we replace the Poisson model with the
_Negative Binomial_ (NBin) one, a structure that allows the DGP to handle
overdispersion (if present) in the observations. Although the Nbin framework is
more flexible, it also increases the DGP's complexity by adding a new parameter:
$\phi$. The reader should recall that as $\phi \rightarrow 0$, NBin converges
to the Poisson distribution.
In order to understand these new parameter spaces, we fit the daily incidence
data to the nine process model candidates, which are coupled with the NBin
observational model. Here, we assume $\zeta$, $\nu$, $\upsilon$, $\phi$ and
$P_0$ as unknown parameters. For each model, we run (via Stan) **eight** Markov
chains from different starting points.
```{r}
folder <- "./Saved_objects/SEI3R_SMTH/neg_binom/bimodal/"
stan_folder <- "./Stan_files/neg_binom/bimodal"
walk(1:9, function(dly_o) {
stan_path <- str_glue("{stan_folder}/SEI3R_{dly_o}_smth.stan")
mdl_path <- str_glue("./models/SEI3R_order_{dly_o}.stmx")
write_SEI3R_model2(mdl_path, stan_path)
})
```
```{r fit_SMTH_neg_binom}
seeds <- c(270343005, 37169835, 416027131, 438666980, 305525729, 63772175,
746136248, 344908351, 730557202)
map_list <- lapply(1:9, function(dly_o) {
mdl_path <- str_glue("./models/SEI3R_order_{dly_o}.stmx")
mdl <- read_xmile(mdl_path)
stocks <- sd_stocks(mdl)
stan_d <- list(n_obs = nrow(obs_df),
y1 = obs_df$y1,
n_params = 3,
n_difeq = nrow(stocks),
t0 = 0,
ts = 1:nrow(obs_df))
set.seed(seeds[[dly_o]])
inits_df <- data.frame(zeta = rlnorm(8),
nu = rhnorm(8, 0.1),
upsilon = rhnorm(8, 0.1),
P_0 = rlnorm(8),
phi = rexp(8, 6))
inits <- transpose(inits_df)
fit_options <- list(stan_d = stan_d,
seed = seeds[[dly_o]],
warmup = 2000,
sampling = 2000,
chains = 8,
init = inits)
results <- run_stan_file(dly_o, fit_options, folder, stan_folder)
sf <- results$sf
})
```
### 1st order delay
#### Trace plot
\hfill
The results indicate that the 1st-order information delay structure coupled
with the Nbin measurement model yields a complex bimodal posterior distribution.
That is, chains reach either of two equilibrium regions. We support this
assessment by the distinct pattern observed in trace plots. Light-coloured
chains settle on a high-density (log-likelihood) but low-volume region
(narrow-band chains). Conversely, dark-coloured chains settle on
a low-density but high-volume region. In addition to this, Stan diagnostics
(See Github repository) confirm such pathological behaviour in this parameter
space by signalling the occurrence of divergent transitions and abnormal
_energies_. Interestingly, Stan only detects divergences and abnormal
energy values in the low-density/high-volume region. We thus refer to chains
in the high-density region as _well-behaved_ chains.
\hfill
```{r, fig.height = 3.5}
color_scheme_set("teal")
set.seed(123)
demo_sf <- posterior::as_draws_array(map_list[[1]])
row_samples <- sample.int(dim(demo_sf)[[1]], 250, replace = FALSE)
demo_sf <- demo_sf[row_samples,,]
mcmc_trace_highlight(demo_sf , pars = c("zeta", "phi", "nu", "upsilon"),
highlight = 4, facet_args = list(labeller = label_parsed)) +
theme(legend.position = "top")
```
\newpage
#### Posterior predictive checks
\hfill
Further, we consider posterior predictive checks as a more immediate appraisal.
That is, we compare the predicted incidence against the actual data,
discriminating by chain type. Here, it can be seen that, unlike the other
chains, samples from Chain 4 do not fit the data.
\hfill
```{r}
posterior_df <- as.data.frame(map_list[[1]])
sim_inc_df <- construct_incidence_df(posterior_df, 1) |>
mutate(fit = ifelse(iter >= 6001 & iter <= 8000, "no", "yes"))
```
```{r, fig.height = 3.5}
set.seed(500)
data_df <- rename(obs_df, y = y1)
plot_fit_by_chain_type(sim_inc_df, data_df, 1)
```
```{r}
vars <- c("zeta", "nu", "upsilon", "phi", "P_0", "log_lik")
summary_var <- imap_dfr(map_list, function(sf,i) {
map_df(vars, function(var) {
var_matrix <- extract_variable_matrix(sf, var)
melt(var_matrix) |> mutate(var = var)
}) |> mutate(order = i)
}) |> mutate(id = paste0(order, chain))
log_lik_df <- summary_var |> filter(var == "log_lik") |>
mutate(converges = ifelse(value < -480, "no", "yes")) |>
select(chain, order, converges) |> unique() |>
mutate(id = paste0(order, chain))
summary_var <- left_join(summary_var,
log_lik_df[, c("id", "converges")], by = "id")
```
### All delay orders
The parameter space of the other models (2nd-order to 9th-order) also
exhibit pathological behaviour. Below, we show the posterior
distribution by parameter, delay order, and chain via boxplots. In these graphs,
we see the clear-cut difference between the two probability mass regions. If we
look at parameter $\phi$, we notice that chains settle either on low
overdispersion (near zero) or high overdispersion values (between 2 and 3). This
division also corresponds to high and low-density regions (see log-lik boxplot),
respectively.
```{r, fig.height = 7}
plot_bp_by_par(summary_var, vars[[1]])
```
```{r, fig.height = 7}
plot_bp_by_par(summary_var, vars[[2]])
```
```{r, fig.height = 7}
plot_bp_by_par(summary_var, vars[[3]])
```
```{r, fig.height = 7}
plot_bp_by_par(summary_var, vars[[4]])
```
```{r, fig.height = 7}
plot_bp_by_par(summary_var, vars[[5]])
```
```{r, fig.height = 7}
plot_bp_by_par(summary_var, vars[[6]])
```
\newpage
### Exploratory estimates
With the purpose of exploring the information provided by high-density
regions, we calculate, from the chains that fit the incidence data,
summary statistics for the unknown parameters. The table below presents
mean values and standard deviations (in parenthesis). When compared to the
values calculated from the Poisson distribution (see Section 2.4), we notice
similar insights. For instance, both distributions yield notably _thin_
estimates for $\nu$ & $\upsilon$, which determine the dynamics of the relative
effective contact rate. Similarly, $\zeta$, whose uncertainty contributes to
the uncertainty in the effective contact rate, is also narrow, albeit there is
a slight bias in estimates from the Poisson distribution, which tend to
overestimate $\Re_0$.
It should be remarked that ignoring pathological chains is not a sound approach.
Namely, we cannot assume that the parameter space is well-behaved when the
evidence tells otherwise. Thus, we employ such estimated values for comparison
and exploration purposes rather than for a inference one.
\hfill
```{r}
summary_var |> filter(var == "zeta") |>
mutate(value = estimate_r(value),