generated from CDCgov/template
-
Notifications
You must be signed in to change notification settings - Fork 6
/
process_model_outputs.R
1750 lines (1583 loc) · 51.4 KB
/
process_model_outputs.R
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
# Utils for simulation-based calibration analysis------------------------------
#' Get full parameter distribution
#' @description
#' This function takes in a fitted wastewater model and returns a long-format
#' tibble of the parameter values for all (or a subset of) draws.
#'
#' @param mcmc_fit CmdStanMCMC object
#' @param draw vector, which draws from the MCMC object do we want in the result?
#' If NULL, returns all. This can be a very large data frame!
#'
#' @return a tibble containing the posterior distribution of each
#' parameter and additional information,
#' namely its name, its temporal context, and its spatial context.
#' @export
get_param_samples_long_df <- function(mcmc_fit,
draw = NULL) {
if (!"CmdStanMCMC" %in% class(mcmc_fit)) {
stop("mcmc_fit must be of class `CmdStanMCMC`")
}
# Get information about the model's parameters
param_df <- get_model_param_df(mcmc_fit) %>%
filter(!generated_quantity)
# @TODO allow passing in only one variable at a time or a subset
# use custom param_df to do so
all_draws <- posterior::subset_draws(
# list is supposedly more RAM-friendly format
mcmc_fit$draws(format = "draws_list"),
draw = draw
)
# Get in long format
full_param_df <- lapply(param_df$param_name, function(p_name) {
.get_1_param(
param_df %>% filter(param_name == p_name),
all_draws
)
})
return(do.call(bind_rows, full_param_df))
}
#' Internal helper for get_param_samples_long_df
#' @description
#' This function makes a "long" data frame for a single parameter. This may be a
#' scalar-, vector-, or matrix-valued parameter.
#'
#'
#' @param param_info single-row data frame (or tibble), originating from get_model_param_df().
#' @param all_draws MCMC samples as a draws_array object
#'
#' @return data frame with parameter name, values, and (as applicable) information
#' about the spatiotemporal aspects of the parameter
#' @keywords internal
.get_1_param <- function(param_info, all_draws) {
out_df <- NULL
this_param <- param_info %>% pull(param_name)
t_var <- param_info %>% pull(time_varying)
ls_var <- param_info %>% pull(lab_or_site_varying)
# spread according to param type: scalar, vector, matrix
if (xor(t_var, ls_var)) {
spread_on <- .get_param_spreader_strings(param_info)
out_df <- all_draws %>%
tidybayes::spread_draws((!!sym(this_param))[!!sym(spread_on)])
} else if (t_var && ls_var) {
spread_on <- .get_param_spreader_strings(param_info)
out_df <- all_draws %>%
tidybayes::spread_draws(
(!!sym(this_param))[
!!sym(spread_on["place"]),
!!sym(spread_on["time"])
],
regex = TRUE
)
} else {
out_df <- all_draws %>%
tidybayes::spread_draws(!!sym(this_param))
}
out_df <- out_df %>%
mutate(
name = this_param,
) %>%
rename(
value = !!sym(this_param),
draw = `.draw`
) %>%
select(-`.chain`, -`.iteration`)
return(out_df)
}
#' Internal helper for .get_1_param
#' @description
#' Provides information required to spread() vector- or matrix-valued parameters.
#'
#' @param param_info single-row data frame (or tibble), originating from get_model_param_df().
#'
#' @return named vector,
#' @keywords internal
.get_param_spreader_strings <- function(param_info) {
time_names <- c("day", "week", "day_of_week")
names(time_names) <- rep("time", length(time_names))
place_names <- c("ww_lab_site", "ww_lab", "ww_site")
names(place_names) <- rep("place", length(place_names))
place_bool <- param_info %>%
select(c("per_lab_site", "per_lab", "per_site")) %>%
as.logical()
time_bool <- param_info %>%
select(c("daily", "weekly", "cyclic")) %>%
as.logical()
# At the moment all cyclic parameters are also daily
if (time_bool[3]) {
time_bool <- c(FALSE, FALSE, TRUE)
}
res <- c(
place_names[place_bool],
time_names[time_bool]
)
return(res)
}
#' Get full parameter distribution
#' @description
#' This function takes in vectors of parameters, grouped by their indexing,
#' and returns a tidy dataframe with all the draws of all the parameters and
#' the corresponding indices
#'
#'
#' @param all_draws draws from the stan object
#' @param static_params character vector of parameters that are static and
#' don't need any indexing
#' @param weekly_params character vector of parameters that are indexed by week
#' @param daily_ww_params character vector of parameters that are indexed by
#' day (t) and ww lab site
#' @param ww_lab_site_params character vector of parameters that are indexed by
#' unique combo of the wastewater lab and site
#' @param day_of_week_params character vector of parameters that are indexed by
#' day of week
#'
#' @return a dataframe containing the posterior distribution of each parameter
#' With indices corresponding to the parameters that have them
#' @export
#'
#' @examples
get_full_param_distrib <- function(all_draws,
static_params,
vector_params,
matrix_params = NA) {
# Get the static parameters
for (i in seq_along(static_params)) {
this_param <- static_params[i]
this_param_df <- all_draws %>%
spread_draws(!!sym(this_param)) %>%
mutate(
name = this_param,
value = !!sym(this_param),
index_rows = NA,
index_cols = NA
) %>%
select(
name, value, `.draw`,
index_rows, index_cols
)
if (i == 1) {
param_df <- this_param_df
} else {
param_df <- rbind(param_df, this_param_df)
}
}
# Get the vector parameters
for (i in seq_along(vector_params)) {
this_vector_param <- vector_params[i]
this_vector_param_df <- all_draws %>%
spread_draws((!!sym(this_vector_param))[!!sym("index_cols")],
regex = TRUE
) %>%
mutate(
name = this_vector_param,
value = !!sym(this_vector_param),
index_rows = NA
) %>%
select(
name, value, `.draw`,
index_rows, index_cols
)
if (i == 1) {
vector_param_df <- this_vector_param_df
} else {
vector_param_df <- rbind(vector_param_df, this_vector_param_df)
}
}
# Get the daily ww parameters
if (!is.na(matrix_params)) {
for (i in seq_along(matrix_params)) {
this_matrix_param <- matrix_params[i]
this_matrix_param_df <- all_draws %>%
spread_draws(
(!!sym(this_matrix_param))[
!!sym("index_rows"),
!!sym("index_cols")
],
regex = TRUE
) %>%
mutate(
name = this_matrix_param,
value = !!sym(this_matrix_param),
) %>%
select(
name, value, `.draw`,
index_rows, index_cols
)
if (i == 1) {
matrix_df <- this_matrix_param_df
} else {
matrix_df <- rbind(matrix_df, this_matrix_param_df)
}
}
}
if (!is.na(matrix_params)) {
full_param_df <- rbind(
param_df, vector_param_df, matrix_df
)
} else {
full_param_df <- rbind(
param_df, vector_param_df
)
}
# Rename draw for ease of calling it
full_param_df <- full_param_df %>%
rename(draw = `.draw`) %>%
left_join(
full_param_df %>%
group_by(index_rows, index_cols, name) %>%
summarise(median = quantile(value, 0.5, na.rm = TRUE)),
by = c("index_rows", "index_cols", "name")
)
return(full_param_df)
}
## Diagnostics------------------------------------------------------------------
#' Calculate low case count diagnostic flag
#'
#' The diagnostic flag is TRUE if either of the _last_ two weeks of the dataset
#' have fewer than an aggregate 10 hospital admissions per week.
#' This aggregation excludes the
#' count from confirmed outliers, which have been set to NA in the data.
#'
#' Adapted from https://github.com/cdcent/cfa-nnh-pipelines/blob/7f1c89d2eecfed89cc3f1be1771d93540ffd6eb4/NHSN/Rt/R/disease_process.R #nolint
#'
#' This function assumes that the `calib_data` input dataset has been
#' "completed": that any implicit missingness has been made explicit.
#'
#' @param calib_data A dataframe. It has `date` column of type `Date`,
#' `daily_hosp_admits` column of type numeric and `period`
#' column of type character.
#'
#' @return Returns TRUE if less than 10 hospital admissions in either of
#' the last two weeks
#' @export
get_low_case_count_diagnostic <- function(calib_data) {
# Sorts dates in ascending order and get the last
max_dates <- tail(sort(unique(
calib_data$date[calib_data$period == "calibration"]
)), 14)
case_data_flag <- calib_data %>%
ungroup() %>%
# Pull out the last two weeks. This assumes that the df is "complete", i.e.
# that all the nulls are made explicit.
filter(date %in% max_dates) %>%
# Are the dates in the first 7 days or the second 7 days?
mutate(week_rank = dense_rank(date) <= 7) %>%
group_by(week_rank) %>%
# Threshold of 10 cases in both of the last two weeks. The `na.rm = TRUE`
# ensures that missing data is treated as 0 for purposes of this diagnostic.
summarize(
n_weekly_cases_below_thresh = sum(daily_hosp_admits, na.rm = TRUE) < 10
) %>%
ungroup() %>%
pull(n_weekly_cases_below_thresh) %>%
# If either is TRUE, diagnostic is TRUE
any()
return(case_data_flag)
}
#' Get some basic flags on the wastewater data, for internal use and for
#' reporting out in our metadata
#'
#' @param calib_data The training data object susbetted to before the forecast
#' date
#' @param delay_thres The maximum number of days of delay between the last
#' wastewater data point and the forecat date, before we would flag a state as
#' having insufficient wastewater data to inform a forecast. Default is 21
#' @param n_dps_thres The threshold number of data points within a single site
#' within a state before we would flag the state as having insufficient
#' wastewater data to inform a forecast. Default is 5
#' @param prop_below_lod_thres The threshold proportion of wastewater data
#' points that can be below the LOD. If greater than this proportion of points
#' are below the LOD, we flag the state as having insufficient wastewater data.
#' Default is 0.5
#' @param sd_thres The minimum standard deviation between wastewater data points
#' within a site. This is intended to catch when a site reports all the same
#' values. Default is 0.1
#' @return a dataframe with 5 True or False flags corresponding to wastewater
#' data presence and quality
#' @export
#'
#' @examples
get_wastewater_diagnostic <- function(calib_data,
delay_thres = 21,
n_dps_thres = 5,
prop_below_lod_thres = 0.5,
sd_thres = 0.1,
mean_log_ww_value_thres = -4) {
# Flag if all wastewater data is missing
no_wastewater_data_flag <- all(is.na(calib_data$ww))
if (isFALSE(no_wastewater_data_flag)) {
# Flag if there isn't any wastewater data from the past 3 weeks
delayed_wastewater_data_flag <- all(is.na(
calib_data %>%
filter(date >= forecast_date - days(delay_thres)) %>%
pull(ww)
))
# Flag if there are less than 5 data points
insufficient_ww_data_flag <- (
calib_data %>%
filter(!is.na(ww)) %>%
group_by(lab_wwtp_unique_id) %>%
summarize(n_dps = n()) %>%
pull(n_dps) %>%
max()
) <= n_dps_thres
# Flag if most datapoints are below the LOD
most_below_lod <- (
calib_data %>%
filter(!is.na(ww)) %>%
summarize(
n_ww = n(),
n_below_LOD = sum(below_LOD)
) %>%
mutate(prop_below_LOD = n_below_LOD / n_ww) %>%
pull(prop_below_LOD)
) > prop_below_lod_thres
# Flag if most data points within a lab-site are flat
most_flat <- (
calib_data %>%
group_by(lab_wwtp_unique_id) %>%
summarise(sd_ww = sd(ww, na.rm = TRUE)) %>%
filter(!is.na(sd_ww)) %>%
ungroup() %>%
summarise(mean_sd = mean(sd_ww)) %>%
pull(mean_sd)
) <= sd_thres
wastewater_values_too_low <- (
calib_data %>%
summarise(mean_log_ww = mean(log(ww), na.rm = TRUE)) %>%
pull(mean_log_ww)
) <= mean_log_ww_value_thres
} else {
delayed_wastewater_data_flag <- NA
insufficient_ww_data_flag <- NA
most_below_lod <- NA
most_flat <- NA
wastewater_values_too_low <- NA
}
wastewater_diagnostic <- tibble(
no_wastewaster_data_flag = no_wastewater_data_flag,
delayed_wastewater_data_flag = delayed_wastewater_data_flag,
insufficient_ww_data_flag = insufficient_ww_data_flag,
most_below_lod = most_below_lod,
wastewater_values_too_low = wastewater_values_too_low,
most_flat = most_flat
)
return(wastewater_diagnostic)
}
#' Get the parameters that were flagged for diagnostics for the model run
#'
#' @param stan_fit_object CmdstanR object
#' @param rhat_threshold Max acceptable Rhat, above this number we flag that
#' parameter
#' @param ess_threshold this number times n chains is the minimum effective
#' sample size before we flag
#'
#' @return model_flags: a dataframe containing all the parameters that
#' are flagged for havign either high Rhat or low effective sample size
#' @export
#'
#' @examples
get_model_run_diagnostics <- function(stan_fit_object,
rhat_threshold = 1.05,
ess_threshold = 100) {
summary <- stan_fit_object$summary()
n_chains <- stan_fit_object$num_chains()
high_rhats <- summary |>
dplyr::filter(rhat > rhat_threshold) |>
arrange(-rhat) |>
mutate(
flag = "high_rhat"
)
low_ess_bulk <- summary |>
dplyr::filter(ess_bulk < ess_threshold * n_chains) |>
arrange(ess_bulk) |>
mutate(
flag = "low_ess_bulk"
)
low_ess_tail <- summary |>
dplyr::filter(ess_tail < ess_threshold * n_chains) |>
arrange(ess_tail) |>
mutate(
flag = "low_ess_tail"
)
model_flags <- rbind(high_rhats, low_ess_bulk, low_ess_tail)
return(model_flags)
}
#' Get a data frame of data and model fit diagnostics
#'
#' @param stan_fit_object The cmdstan object
#' @param train_data The dataframe containing hospital admissions and
#' wastewater data for callibration of the model
#' @param location The location the model is being run on
#' @param model_type The type of model
#' @param forecast_date The date of the forecast
#' @param ebmfi_tolerance tolerance for mean EBMFI, default of 0.2
#' @param divergences_tolerance tolerance for percent of iterations that
#' are divergent from an individual chain
#' @param p_high_rhat_tolerance tolerance for probability of high p_hat,
#' default 0.05
#' @param max_tree_depth_tol tolerance for number of draws that
#' hit the maximum tree depth, default to 0.01
#' @param ...
#'
#' @return Returns a dataframe containing diagnostic summaries
#' @export
#'
#' @examples
get_diagnostics <- function(stan_fit_object, train_data, location,
model_type, forecast_date,
ebmfi_tolerance = 0.2,
divergences_tolerance = 0.01,
p_high_rhat_tolerance = 0.05,
max_tree_depth_tol = 0.01,
...) {
calib_data <- train_data %>% filter(date <= forecast_date)
low_case_count_diagnostic <- get_low_case_count_diagnostic(calib_data)
if (!(model_type %in% c(
"hospital admissions only", "state-level aggregated wastewater"
))) {
wastewater_diagnostic <- get_wastewater_diagnostic(calib_data)
} else {
wastewater_diagnostic <- tibble(
no_wastewaster_data_flag = TRUE,
delayed_wastewater_data_flag = NA,
insufficient_ww_data_flag = NA,
most_below_lod = NA,
wastewater_values_too_low = NA,
most_flat = NA
)
}
data_df <- tibble(
diagnostic = c(
"low_case_count_flag",
"no_wastewater_data_flag",
"delayed_wastewater_data_flag",
"insufficient_ww_data_flag",
"most_below_lod",
"wastewater_values_too_low",
"most_flat"
),
value = c(
low_case_count_diagnostic,
wastewater_diagnostic$no_wastewaster_data_flag,
wastewater_diagnostic$delayed_wastewater_data_flag,
wastewater_diagnostic$insufficient_ww_data_flag,
wastewater_diagnostic$most_below_lod,
wastewater_diagnostic$wastewater_values_too_low,
wastewater_diagnostic$most_flat
),
"location" = location,
"forecast_date" = forecast_date,
"model_type" = model_type
)
diagnostics <- stan_fit_object$diagnostic_summary(quiet = TRUE)
n_chains <- stan_fit_object$num_chains()
iter_sampling <- stan_fit_object$metadata()$iter_sampling
# Summary is a large dataframe with diagnostics for each parameters
summary <- stan_fit_object$summary()
max_rhat <- summary |>
select(rhat) |>
max(na.rm = TRUE)
param_max_rhat <- summary |>
dplyr::filter(rhat == max_rhat) |>
pull(variable) |>
paste(collapse = ",")
run_time_min <- stan_fit_object$time()$total / 60
chain_df <- data.frame(stan_fit_object$time())
chain_times_min <- as.character((chain_df$chains.total / 60))
min_ess_bulk <- summary |>
select(ess_bulk) |>
min(na.rm = TRUE)
param_min_ess_bulk <- summary |>
dplyr::filter(ess_bulk == min_ess_bulk) |>
pull(variable) |>
paste(collapse = ",")
min_ess_tail <- summary |>
select(ess_tail) |>
min(na.rm = TRUE)
param_min_ess_tail <- summary |>
dplyr::filter(ess_tail == min_ess_tail) |>
pull(variable) |>
paste(collapse = ",")
flag_low_embfi <- mean(diagnostics$ebfmi) <= ebmfi_tolerance
max_n_divergences <- n_chains * iter_sampling * divergences_tolerance
flag_too_many_divergences <- any(diagnostics$num_divergent >= max_n_divergences)
p_high_rhat <- as.numeric(mean(stan_fit_object$summary()[, "rhat"]$rhat > 1.05, na.rm = TRUE))
flag_high_rhat <- p_high_rhat >= p_high_rhat_tolerance
max_n_max_treedepth <- n_chains * iter_sampling * max_tree_depth_tol
flag_high_max_treedepth <- any(diagnostics$num_max_tree_depth >= max_n_max_treedepth)
diagnostic_df <- tibble(
diagnostic = c(
"n_divergent",
"n_max_treedepth",
"mean_ebfmi",
"p_high_rhat",
"max_rhat",
"param_max_rhat",
"min_ess_bulk",
"param_min_ess_bulk",
"min_ess_tail",
"param_min_ess_tail",
"run_time_minutes",
"chain_times_minutes",
"flag_low_embfi",
"flag_too_many_divergences",
"flag_high_rhat",
"flag_high_max_treedepth"
),
value = c(
toString(diagnostics$num_divergent),
toString(diagnostics$num_max_treedepth),
mean(diagnostics$ebfmi),
p_high_rhat,
max_rhat,
param_max_rhat,
min_ess_bulk,
param_min_ess_bulk,
min_ess_tail,
param_min_ess_tail,
run_time_min,
toString(chain_times_min),
flag_low_embfi,
flag_too_many_divergences,
flag_high_rhat,
flag_high_max_treedepth
),
"location" = location,
"forecast_date" = forecast_date,
"model_type" = model_type
)
return(rbind(data_df, diagnostic_df))
}
#' Load in and combine all the diagnostic tables
#'
#' @param df_of_filepaths dataframe containing filepath indicating where
#' model outputs are saved
#'
#' @return a combined list of all the diagnostics across locations and model
#' runs
#' @export
#'
#' @examples
read_diagnostics_df <- function(df_of_filepaths) {
for (i in seq_len(nrow(df_of_filepaths))) {
diagnostics_i <- read_csv(
file.path(df_of_filepaths$diagnostics_file_path[i])
)
if (i == 1) {
diagnostics_df <- diagnostics_i
} else {
diagnostics_df <- rbind(diagnostics_df, diagnostics_i)
}
}
return(diagnostics_df)
}
#' @title Get sumamry stats of diagnostics
#'
#' @description
#' Takes the long dataframes of diagnostics by location and outputs summaries
#'
#'
#' @param df
#'
#' @return
#' @export
#'
#' @examples
get_summary_stats <- function(df) {
states_w_no_ww_data <- df %>%
dplyr::filter(diagnostic == "no_wastewater_data_flag", as.logical(value)) %>%
dplyr::pull(location)
states_w_insufficient_ww_data <- df %>%
filter(diagnostic == "insufficient_ww_data_flag", as.logical(value)) %>%
pull(location)
states_w_delayed_ww_data <- df %>%
filter(diagnostic == "delayed_wastewater_data_flag", as.logical(value)) %>%
pull(location)
# states with any data below LOD, or flat
states_below_lod_or_flat <- df %>%
filter(
diagnostic %in% c("most_below_lod", "most_flat"),
as.logical(value)
) %>%
pull(location)
# states with any wastewater values too low
states_low_ww <- df %>%
filter(
diagnostic %in% c("wastewater_values_too_low"),
as.logical(value)
) %>%
pull(location)
states_to_flag_for_hub <- unique(c(
states_w_insufficient_ww_data,
states_w_delayed_ww_data
))
states_w_low_hosp_admissions <- df %>%
filter(diagnostic == "low_case_count_flag", value == 1) %>%
pull(location)
states_w_low_ebmfi <- df %>%
filter(diagnostic == "flag_low_embfi", as.logical(value)) %>%
pull(location)
states_w_too_many_divergences <- df %>%
filter(
diagnostic == "flag_too_many_divergences", as.logical(value)
) %>%
pull(location)
states_w_high_rhat <- df %>%
filter(diagnostic == "flag_high_rhat", as.logical(value)) %>%
pull(location)
# states with high number of draws at maximum tree depth
states_high_tree_depth <- df %>%
filter(
diagnostic == "flag_high_max_treedepth", as.logical(value)
) %>%
pull(location)
stats <- list(
states_w_no_ww_data = states_w_no_ww_data,
states_w_insufficient_ww_data = states_w_insufficient_ww_data,
states_w_delayed_ww_data = states_w_delayed_ww_data,
states_below_lod_or_flat = states_below_lod_or_flat,
states_low_ww = states_low_ww,
states_to_flag_for_hub = states_to_flag_for_hub,
states_w_low_hosp_admissions = states_w_low_hosp_admissions,
states_w_low_ebmfi = states_w_low_ebmfi,
states_w_too_many_divergences = states_w_too_many_divergences,
states_w_high_rhat = states_w_high_rhat,
states_high_tree_depth = states_high_tree_depth
)
return(stats)
}
## Extract and format the generated quantites-----------------------------------
#' @title Get generated quantities draws site level model
#' @description
#' This function takes the raw stan output from the site leve model and
#' arranges them in a tidy data format, with time and site_index as indexing
#' variables.
#'
#'
#' @param all_draws
#' @param train_data
#'
#' @return A long dataframe with model draws from pred_hosp, pred_ww, R(t) and
#' p_hosp(t), where all but pred_ww have one value per time point and draw. Bc
#' we need all the column names to be the same, site_index is left empty for those.
#' The resulting dataframe has the following columns:
#' name, site_index, t, value, draw
#'
#' @export
#'
#' @examples
get_gen_quants_draws <- function(all_draws,
model_type) {
hosp_draws <- all_draws %>%
spread_draws(pred_hosp[t]) %>%
# sample_draws(ndraws = n_draws) %>%
rename(value = pred_hosp) %>%
mutate(
draw = `.draw`,
name = "pred_hosp",
lab_site_index = NA
) %>%
select(name, lab_site_index, t, value, draw)
ww_draws <- all_draws %>%
spread_draws(pred_ww[lab_site_index, t]) %>%
# sample_draws(ndraws = n_draws) %>%
rename(value = pred_ww) %>%
mutate(
draw = `.draw`,
name = "pred_ww",
value = exp(value)
) %>%
select(name, lab_site_index, t, value, draw)
exp_state_ww_draws <- all_draws %>%
spread_draws(exp_state_ww_conc[t]) %>%
# sample_draws(ndraws = n_draws) %>%
rename(value = exp_state_ww_conc) %>%
mutate(
draw = `.draw`,
name = "exp_state_ww_conc",
lab_site_index = NA
) %>%
select(name, lab_site_index, t, value, draw)
rt_draws <- all_draws %>%
spread_draws(rt[t]) %>%
# sample_draws(ndraws = n_draws) %>%
rename(value = rt) %>%
mutate(
draw = `.draw`,
name = "R(t)",
lab_site_index = NA
) %>%
select(name, lab_site_index, t, value, draw)
p_hosp_draws <- all_draws %>%
spread_draws(p_hosp[t]) %>%
# sample_draws(ndraws = n_draws) %>%
rename(value = p_hosp) %>%
mutate(
draw = `.draw`,
name = "p_hosp",
lab_site_index = NA
) %>%
select(name, lab_site_index, t, value, draw)
model_draws <- rbind(
hosp_draws, ww_draws,
exp_state_ww_draws, rt_draws,
p_hosp_draws
)
model_draws <- model_draws %>%
mutate(subpop_index = NA)
if (model_type == "site-level infection dynamics") {
site_level_rt <- all_draws %>%
spread_draws(r_site_t[subpop_index, t]) %>%
rename(value = r_site_t) %>%
mutate(
draw = `.draw`,
name = "R_site_t",
lab_site_index = NA
) %>%
select(colnames(model_draws))
model_draws <- rbind(model_draws, site_level_rt)
}
return(model_draws)
}
#' @title Get generated quantities draws
#' @description
#' This function takes the raw stan output from the aggregated model and
#' arranges them in a tidy data format, with time as an indexing variable.
#' @param all_draws
#' @param train_data
#'
#' @return A long dataframe with model draws from pred_hosp, pred_ww, R(t) and
#' p_hosp(t), where all have one value per time point and draw.
#' The resulting dataframe has the following columns:
#' name, t, value, draw
#' @export
#'
#' @examples
get_generated_quantities_draws <- function(all_draws,
model_type,
n_draws = 100) {
# Dataframes with ndraws (long format)
hosp_draws <- all_draws %>%
spread_draws(pred_hosp[t]) %>%
# sample_draws(ndraws = n_draws) %>%
rename(value = pred_hosp) %>%
mutate(
draw = `.draw`,
name = "pred_hosp"
) %>%
select(name, t, value, draw)
ww_draws <- all_draws %>%
spread_draws(pred_conc[t]) %>%
# sample_draws(ndraws = n_draws) %>%
rename(value = pred_conc) %>%
mutate(
draw = `.draw`,
name = "pred_ww",
value = exp(value)
) %>%
select(name, t, value, draw)
exp_state_ww_draws <- all_draws %>%
spread_draws(exp_state_ww_conc[t]) %>%
# sample_draws(ndraws = n_draws) %>%
rename(value = exp_state_ww_conc) %>%
mutate(
draw = `.draw`,
name = "exp_state_ww_conc",
) %>%
select(name, t, value, draw)
rt_draws <- all_draws %>%
spread_draws(rt[t]) %>%
# sample_draws(ndraws = n_draws) %>%
rename(value = rt) %>%
mutate(
draw = `.draw`,
name = "R(t)"
) %>%
select(name, t, value, draw)
if (model_type != "hospital admissions only") {
p_hosp_draws <- all_draws %>%
spread_draws(p_hosp[t]) %>%
# sample_draws(ndraws = n_draws) %>%
rename(value = p_hosp) %>%
mutate(
draw = `.draw`,
name = "p_hosp"
) %>%
select(name, t, value, draw)
model_draws <- rbind(
hosp_draws, ww_draws, rt_draws,
exp_state_ww_draws, p_hosp_draws
)
} else {
model_draws <- rbind(
hosp_draws, ww_draws, rt_draws,
exp_state_ww_draws
)
}
return(model_draws)
}
## Extract draws from posterior of static parameters----------------------------
#' @title Get parameters
#' @description
#' Returns a list of the static parameter in this model. Can be edited as needed
#'
#' @return
#' @export
#'
#' @examples
get_pars <- function() {
pars <- c(
"phi_h", "sigma_ww", "G", "eta_sd", "p_hosp_sd", "i0", "initial_growth",
"viral_peak", "t_peak", "dur_shed", "autoreg_rt"
)
return(pars)
}
#' @title Get raw parameter draws
#' @description
#' This concatenates all the tidy draws dataframes of each of the parameters
#'
#' @param stan_output_draws
#' @param model_type
#' @param n_draws
#' @param ...
#'
#' @return a long tidy dataframe with columns names:
#' name, t, value, draw corresponding to the value of the draw of the posterior
#' of that parameter
#' @export
#'
#' @examples
get_raw_param_draws <- function(stan_output_draws, model_type,
n_draws = 500, ...) {
# Single parmeter posterior draws with sumamry stats
phi_h <- stan_output_draws %>%
spread_draws(phi_h) %>%
sample_draws(ndraws = n_draws) %>%
mutate(draw = `.draw`) %>%
mutate(
name = "phi_h",
t = NA
) %>%
rename(value = phi_h) %>%
select(name, t, value, draw)
eta_sd <- stan_output_draws %>%
spread_draws(eta_sd) %>%
sample_draws(ndraws = n_draws) %>%
mutate(draw = `.draw`) %>%
mutate(
name = "eta_sd",
t = NA
) %>%
rename(value = eta_sd) %>%
select(name, t, value, draw)
log10_g <- stan_output_draws %>%
spread_draws(log10_g) %>%
sample_draws(ndraws = n_draws) %>%
mutate(draw = `.draw`) %>%
mutate(
name = "log10_g",
t = NA
) %>%
rename(value = log10_g) %>%
select(name, t, value, draw)
i0 <- stan_output_draws %>%
spread_draws(i0) %>%
sample_draws(ndraws = n_draws) %>%
mutate(draw = `.draw`) %>%
mutate(
name = "i0",
t = NA
) %>%
rename(value = i0) %>%
select(name, t, value, draw)
initial_growth <- stan_output_draws %>%
spread_draws(initial_growth) %>%
sample_draws(ndraws = n_draws) %>%
mutate(draw = `.draw`) %>%
mutate(
name = "initial_growth",
t = NA
) %>%
rename(value = initial_growth) %>%
select(name, t, value, draw)
infection_feedback <- stan_output_draws %>%
spread_draws(infection_feedback) %>%
sample_draws(ndraws = n_draws) %>%