-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathdist.R
1419 lines (1363 loc) · 43 KB
/
dist.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
#' Distribution Skeleton
#'
#' @description `r lifecycle::badge("questioning")`
#' This function acts as a skeleton for a truncated distribution defined by
#' model type, maximum value and model parameters. It is designed to be used
#' with the output from `get_dist`.
#'
#' @param n Numeric vector, number of samples to take (or days for the
#' probability density).
#'
#' @param dist Logical, defaults to `FALSE`. Should the probability density be
#' returned rather than a number of samples.
#'
#' @param cum Logical, defaults to `TRUE`. If `dist = TRUE` should the returned
#' distribution be cumulative.
#'
#' @param model Character string, defining the model to be used. Supported
#' options are exponential ("exp"), gamma ("gamma"), and log normal
#' ("lognormal")
#'
#' @param discrete Logical, defaults to `FALSE`. Should the probability
#' distribution be discretised. In this case each entry of the probability
#' mass function corresponds to the 1-length interval ending at the entry,
#' i.e. the probability mass function is a vector where the first entry
#' corresponds to the integral over the (0,1] interval of the continuous
#' distribution, the second entry corresponds to the (1,2] interval etc.
#'
#' @param params A list of parameters values (by name) required for each model.
#' For the exponential model this is a rate parameter and for the gamma model
#' this is alpha and beta.
#'
#' @param max_value Numeric, the maximum value to allow. Defaults to 120.
#' Samples outside of this range are resampled.
#'
#' @return A vector of samples or a probability distribution.
#' @export
#' @author Sam Abbott
#' @author Sebastian Funk
#' @examples
#'
#' ## Exponential model
#' # sample
#' dist_skel(10, model = "exp", params = list(rate = 1))
#'
#' # cumulative prob density
#' dist_skel(1:10, model = "exp", dist = TRUE, params = list(rate = 1))
#'
#' # probability density
#' dist_skel(1:10,
#' model = "exp", dist = TRUE,
#' cum = FALSE, params = list(rate = 1)
#' )
#'
#' ## Gamma model
#' # sample
#' dist_skel(10, model = "gamma", params = list(shape = 1, scale = 2))
#'
#' # cumulative prob density
#' dist_skel(0:10,
#' model = "gamma", dist = TRUE,
#' params = list(shape = 1, scale = 2)
#' )
#'
#' # probability density
#' dist_skel(0:10,
#' model = "gamma", dist = TRUE,
#' cum = FALSE, params = list(shape = 2, scale = 2)
#' )
#'
#' ## Log normal model
#' # sample
#' dist_skel(10, model = "lognormal", params = list(mean = log(5), sd = log(2)))
#'
#' # cumulative prob density
#' dist_skel(0:10,
#' model = "lognormal", dist = TRUE,
#' params = list(mean = log(5), sd = log(2))
#' )
#'
#' # probability density
#' dist_skel(0:10,
#' model = "lognormal", dist = TRUE, cum = FALSE,
#' params = list(mean = log(5), sd = log(2))
#' )
dist_skel <- function(n, dist = FALSE, cum = TRUE, model,
discrete = FALSE, params, max_value = 120) {
if (model %in% "exp") {
# define support functions for exponential dist
rdist <- function(n) {
rexp(n, params$rate)
}
pdist <- function(n) {
pexp(n, params$rate) / pexp(max_value, params$rate)
}
ddist <- function(n) {
(pexp(n + 1, params$rate) -
pexp(n, params$rate)) /
pexp(max_value + 1, params$rate)
}
} else if (model %in% "gamma") {
rdist <- function(n) {
rgamma(n, params$shape, params$scale)
}
pdist <- function(n) {
pgamma(n, params$shape, params$scale) /
pgamma(max_value + 1, params$shape, params$scale)
}
ddist <- function(n) {
(pgamma(n + 1, params$shape, params$scale) -
pgamma(n, params$shape, params$scale)) /
pgamma(max_value + 1, params$shape, params$scale)
}
} else if (model %in% "lognormal") {
rdist <- function(n) {
rlnorm(n, params$mean, params$sd)
}
pdist <- function(n) {
plnorm(n, params$mean, params$sd) /
plnorm(max_value + 1, params$mean, params$sd)
}
ddist <- function(n) {
(plnorm(n + 1, params$mean, params$sd) -
plnorm(n, params$mean, params$sd)) /
plnorm(max_value + 1, params$mean, params$sd)
}
}
if (discrete) {
cmf <- c(0, pdist(seq_len(max_value + 1)))
pmf <- diff(cmf)
rdist <- function(n) {
sample(x = seq_len(max_value + 1) - 1, size = n, prob = pmf)
}
pdist <- function(n) {
cmf[n + 1]
}
ddist <- function(n) {
pmf[n + 1]
}
}
# define internal sampling function
inner_skel <- function(n, dist = FALSE, cum = TRUE, max_value = NULL) {
if (!dist) {
rdist(n)
} else {
if (cum) {
ret <- pdist(n)
} else {
ret <- ddist(n)
}
ret[ret > 1] <- NA_real_
return(ret)
}
}
# define truncation wrapper
truncated_skel <- function(n, dist, cum, max_value) {
n <- inner_skel(n, dist, cum, max_value)
if (!dist) {
while (any(!is.na(n) & n >= max_value)) {
n <- ifelse(n >= max_value, inner_skel(n), n)
}
n <- as.integer(n)
}
return(n)
}
# call function
sample <- truncated_skel(n, dist = dist, cum = cum, max_value = max_value)
return(sample)
}
#' Fit an Integer Adjusted Exponential, Gamma or Lognormal distributions
#'
#' @description `r lifecycle::badge("stable")`
#' Fits an integer adjusted exponential, gamma or lognormal distribution using
#' `stan`.
#' @param values Numeric vector of values
#'
#' @param samples Numeric, number of samples to take. Must be >= 1000.
#' Defaults to 1000.
#'
#' @param dist Character string, which distribution to fit. Defaults to
#' exponential (`"exp"`) but gamma (`"gamma"`) and lognormal (`"lognormal"`) are
#' also supported.
#'
#' @param cores Numeric, defaults to 1. Number of CPU cores to use (no effect
#' if greater than the number of chains).
#'
#' @param chains Numeric, defaults to 2. Number of MCMC chains to use. More is
#' better with the minimum being two.
#'
#' @param verbose Logical, defaults to FALSE. Should verbose progress messages
#' be printed.
#'
#' @return A `stan` fit of an interval censored distribution
#' @author Sam Abbott
#' @export
#' @examples
#' \donttest{
#' # integer adjusted exponential model
#' dist_fit(rexp(1:100, 2),
#' samples = 1000, dist = "exp",
#' cores = ifelse(interactive(), 4, 1), verbose = TRUE
#' )
#'
#'
#' # integer adjusted gamma model
#' dist_fit(rgamma(1:100, 5, 5),
#' samples = 1000, dist = "gamma",
#' cores = ifelse(interactive(), 4, 1), verbose = TRUE
#' )
#'
#' # integer adjusted lognormal model
#' dist_fit(rlnorm(1:100, log(5), 0.2),
#' samples = 1000, dist = "lognormal",
#' cores = ifelse(interactive(), 4, 1), verbose = TRUE
#' )
#' }
dist_fit <- function(values = NULL, samples = 1000, cores = 1,
chains = 2, dist = "exp", verbose = FALSE) {
if (samples < 1000) {
samples <- 1000
warning(sprintf("%s %s", "`samples` must be at least 1000.",
"Now setting it to 1000 internally."
)
)
}
# model parameters
lows <- values - 1
lows <- ifelse(lows <= 0, 1e-6, lows)
ups <- values + 1
data <- list(
N = length(values),
low = lows,
up = ups,
lam_mean = numeric(0),
prior_mean = numeric(0),
prior_sd = numeric(0),
par_sigma = numeric(0)
)
model <- stanmodels$dist_fit
if (dist %in% "exp") {
data$dist <- 0
data$lam_mean <- array(mean(values))
} else if (dist %in% "lognormal") {
data$dist <- 1
data$prior_mean <- array(log(mean(values)))
data$prior_sd <- array(log(sd(values)))
} else if (dist %in% "gamma") {
data$dist <- 2
data$prior_mean <- array(mean(values))
data$prior_sd <- array(sd(values))
data$par_sigma <- array(1.0)
}
# set adapt delta based on the sample size
if (length(values) <= 30) {
adapt_delta <- 0.999
} else {
adapt_delta <- 0.9
}
# fit model
fit <- rstan::sampling(
model,
data = data,
iter = samples + 1000,
warmup = 1000,
control = list(adapt_delta = adapt_delta),
chains = chains,
cores = cores,
refresh = ifelse(verbose, 50, 0)
)
return(fit)
}
#' Generate a Gamma Distribution Definition Based on Parameter Estimates
#'
#' @description `r lifecycle::badge("soft-deprecated")`
#' Generates a distribution definition when only parameter estimates
#' are available for gamma distributed parameters. See `rgamma` for
#' distribution information.
#'
#' @param shape Numeric, shape parameter of the gamma distribution.
#'
#' @param shape_sd Numeric, standard deviation of the shape parameter.
#'
#' @param scale Numeric, scale parameter of the gamma distribution.
#'
#' @param scale_sd Numeric, standard deviation of the scale parameter.
#'
#' @param samples Numeric, number of sample distributions to generate.
#'
#' @importFrom truncnorm rtruncnorm
#' @return A data.table defining the distribution as used by `dist_skel`
#' @export
#' @inheritParams dist_skel
#' @inheritParams lognorm_dist_def
#' @author Sam Abbott
#' @examples
#' # using estimated shape and scale
#' def <- gamma_dist_def(
#' shape = 5.807, shape_sd = 0.2,
#' scale = 0.9, scale_sd = 0.05,
#' max_value = 20, samples = 10
#' )
#' print(def)
#' def$params[[1]]
#'
#' # using mean and sd
#' def <- gamma_dist_def(
#' mean = 3, mean_sd = 0.5,
#' sd = 3, sd_sd = 0.1,
#' max_value = 20, samples = 10
#' )
#' print(def)
#' def$params[[1]]
gamma_dist_def <- function(shape, shape_sd,
scale, scale_sd,
mean, mean_sd,
sd, sd_sd,
max_value, samples) {
if (missing(shape) && missing(scale) && !missing(mean) && !missing(sd)) {
if (!missing(mean_sd)) {
mean <- truncnorm::rtruncnorm(samples, a = 0, mean = mean, sd = mean_sd)
}
if (!missing(sd_sd)) {
sd <- truncnorm::rtruncnorm(samples, a = 0, mean = sd, sd = sd_sd)
}
scale <- sd^2 / mean
shape <- mean / scale
scale <- 1 / scale
} else {
if (!missing(shape_sd)) {
shape <- truncnorm::rtruncnorm(
samples,
a = 0, mean = shape, sd = shape_sd
)
}
if (!missing(scale_sd)) {
scale <- 1 / truncnorm::rtruncnorm(
samples,
a = 0, mean = scale, sd = scale_sd
)
}
}
dist <- data.table::data.table(
model = rep("gamma", samples),
params = purrr::transpose(
list(
shape = shape,
scale = scale
)
),
max_value = rep(max_value, samples)
)
return(dist)
}
#' Generate a Log Normal Distribution Definition Based on Parameter Estimates
#'
#' @description `r lifecycle::badge("soft-deprecated")`
#' Generates a distribution definition when only parameter estimates
#' are available for log normal distributed parameters. See `rlnorm` for
#' distribution information.
#'
#' @param mean Numeric, log mean parameter of the gamma distribution.
#'
#' @param mean_sd Numeric, standard deviation of the log mean parameter.
#'
#' @param sd Numeric, log sd parameter of the gamma distribution.
#'
#' @param sd_sd Numeric, standard deviation of the log sd parameter.
#'
#' @param samples Numeric, number of sample distributions to generate.
#'
#' @param to_log Logical, should parameters be logged before use.
#'
#' @return A data.table defining the distribution as used by `dist_skel`
#' @author Sam Abbott
#' @importFrom truncnorm rtruncnorm
#' @export
#' @inheritParams dist_skel
#' @examples
#' def <- lognorm_dist_def(
#' mean = 1.621, mean_sd = 0.0640,
#' sd = 0.418, sd_sd = 0.0691,
#' max_value = 20, samples = 10
#' )
#' print(def)
#' def$params[[1]]
#'
#' def <- lognorm_dist_def(
#' mean = 5, mean_sd = 1,
#' sd = 3, sd_sd = 1,
#' max_value = 20, samples = 10,
#' to_log = TRUE
#' )
#' print(def)
#' def$params[[1]]
lognorm_dist_def <- function(mean, mean_sd,
sd, sd_sd,
max_value, samples,
to_log = FALSE) {
transform_mean <- function(mu, sig) {
mean_location <- log(mu^2 / sqrt(sig^2 + mu^2))
mean_location
}
transform_sd <- function(mu, sig) {
mean_shape <- sqrt(log(1 + (sig^2 / mu^2)))
mean_shape
}
if (missing(mean_sd)) {
sampled_means <- mean
} else {
sampled_means <- truncnorm::rtruncnorm(
samples,
a = 0, mean = mean, sd = mean_sd
)
}
if (missing(sd_sd)) {
sampled_sds <- sd
} else {
sampled_sds <- truncnorm::rtruncnorm(samples, a = 0, mean = sd, sd = sd_sd)
}
means <- sampled_means
sds <- sampled_sds
if (to_log) {
means <- mapply(transform_mean, sampled_means, sampled_sds)
sds <- mapply(transform_sd, sampled_means, sampled_sds)
}
dist <- data.table::data.table(
model = rep("lognormal", samples),
params = purrr::transpose(
list(
mean = means,
sd = sds
)
),
max_value = rep(max_value, samples)
)
return(dist)
}
#' Fit a Subsampled Bootstrap to Integer Values and Summarise Distribution
#' Parameters
#'
#' @description `r lifecycle::badge("stable")`
#' Fits an integer adjusted distribution to a subsampled bootstrap of data and
#' then integrates the posterior samples into a single set of summary
#' statistics. Can be used to generate a robust reporting delay that accounts
#' for the fact the underlying delay likely varies over time or that the size
#' of the available reporting delay sample may not be representative of the
#' current case load.
#'
#' @param values Integer vector of values.
#'
#' @param dist Character string, which distribution to fit. Defaults to
#' lognormal (`"lognormal"`) but gamma (`"gamma"`) is also supported.
#'
#' @param verbose Logical, defaults to `FALSE`. Should progress messages be
#' printed.
#'
#' @param samples Numeric, number of samples to take overall from the
#' bootstrapped posteriors.
#'
#' @param bootstraps Numeric, defaults to 1. The number of bootstrap samples
#' (with replacement) of the delay distribution to take.
#'
#' @param bootstrap_samples Numeric, defaults to 100. The number of samples to
#' take in each bootstrap. When the sample size of the supplied delay
#' distribution is less than 100 this is used instead.
#'
#' @param max_value Numeric, defaults to the maximum value in the observed
#' data. Maximum delay to allow (added to output but does impact fitting).
#'
#' @return A `dist_spec` object summarising the bootstrapped distribution
#' @author Sam Abbott
#' @importFrom purrr transpose
#' @importFrom future.apply future_lapply
#' @importFrom rstan extract
#' @importFrom data.table data.table rbindlist
#' @export
#' @examples
#' \donttest{
#' # lognormal
#' delays <- rlnorm(500, log(5), 1)
#' out <- bootstrapped_dist_fit(delays,
#' samples = 1000, bootstraps = 10,
#' dist = "lognormal"
#' )
#' out
#' }
bootstrapped_dist_fit <- function(values, dist = "lognormal",
samples = 2000, bootstraps = 10,
bootstrap_samples = 250, max_value,
verbose = FALSE) {
if (!dist %in% c("gamma", "lognormal")) {
stop("Only lognormal and gamma distributions are supported")
}
if (samples < bootstraps) {
samples <- bootstraps
}
## Make values integer if not
values <- as.integer(values)
## Remove NA values
values <- values[!is.na(values)]
## Filter out negative values
values <- values[values >= 0]
get_single_dist <- function(values, samples = 1) {
set_dt_single_thread()
fit <- EpiNow2::dist_fit(values, samples = samples, dist = dist)
out <- list()
if (dist == "lognormal") {
out$mean_samples <- sample(rstan::extract(fit)$mu, samples)
out$sd_samples <- sample(rstan::extract(fit)$sigma, samples)
} else if (dist == "gamma") {
alpha_samples <- sample(rstan::extract(fit)$alpha, samples)
beta_samples <- sample(rstan::extract(fit)$beta, samples)
out$mean_samples <- alpha_samples / beta_samples
out$sd_samples <- sqrt(alpha_samples) / beta_samples
}
return(out)
}
if (bootstraps == 1) {
dist_samples <- get_single_dist(values, samples = samples)
} else {
## Fit each sub sample
dist_samples <- future.apply::future_lapply(1:bootstraps,
function(boot) {
get_single_dist(
sample(values,
min(length(values), bootstrap_samples),
replace = TRUE
),
samples = ceiling(samples / bootstraps)
)
},
future.scheduling = Inf,
future.globals = c(
"values", "bootstraps", "samples",
"bootstrap_samples", "get_single_dist"
),
future.packages = "data.table", future.seed = TRUE
)
dist_samples <- purrr::transpose(dist_samples)
dist_samples <- purrr::map(dist_samples, unlist)
}
out <- list()
out$mean <- mean(dist_samples$mean_samples)
out$mean_sd <- sd(dist_samples$mean_samples)
out$sd <- mean(dist_samples$sd_sample)
out$sd_sd <- sd(dist_samples$sd_samples)
if (!missing(max_value)) {
out$max <- max_value
} else {
out$max <- max(values)
}
return(do.call(dist_spec, out))
}
#' Estimate a Delay Distribution
#'
#' @description `r lifecycle::badge("maturing")`
#' Estimate a log normal delay distribution from a vector of integer delays.
#' Currently this function is a simple wrapper for `bootstrapped_dist_fit`.
#'
#' @param delays Integer vector of delays
#'
#' @param ... Arguments to pass to internal methods.
#'
#' @return A `dist_spec` summarising the bootstrapped distribution
#' @author Sam Abbott
#' @export
#' @seealso bootstrapped_dist_fit
#' @examples
#' \donttest{
#' delays <- rlnorm(500, log(5), 1)
#' estimate_delay(delays, samples = 1000, bootstraps = 10)
#' }
estimate_delay <- function(delays, ...) {
fit <- bootstrapped_dist_fit(
values = delays,
dist = "lognormal", ...
)
return(fit)
}
#' Approximate Sampling a Distribution using Counts
#'
#' @description `r lifecycle::badge("soft-deprecated")`
#' Convolves cases by a PMF function. This function will soon be removed or
#' replaced with a more robust `stan` implementation.
#'
#' @param cases A dataframe of cases (in date order) with the following
#' variables: `date` and `cases`.
#'
#' @param max_value Numeric, maximum value to allow. Defaults to 120 days
#'
#' @param direction Character string, defato "backwards". Direction in which to
#' map cases. Supports either "backwards" or "forwards".
#'
#' @param dist_fn Function that takes two arguments with the first being
#' numeric and the second being logical (and defined as `dist`). Should return
#' the probability density or a sample from the defined distribution. See
#' the examples for more.
#'
#' @param earliest_allowed_mapped A character string representing a date
#' ("2020-01-01"). Indicates the earliest allowed mapped value.
#'
#' @param type Character string indicating the method to use to transform
#' counts. Supports either "sample" which approximates sampling or "median"
#' would shift by the median of the distribution.
#'
#' @param truncate_future Logical, should cases be truncated if they occur
#' after the first date reported in the data. Defaults to `TRUE`.
#'
#' @return A `data.table` of cases by date of onset
#' @export
#' @importFrom purrr map_dfc
#' @importFrom data.table data.table setorder
#' @importFrom lubridate days
#' @examples
#' \donttest{
#' cases <- example_confirmed
#' cases <- cases[, cases := as.integer(confirm)]
#' print(cases)
#'
#' # total cases
#' sum(cases$cases)
#'
#' delay_fn <- function(n, dist, cum) {
#' if (dist) {
#' pgamma(n + 0.9999, 2, 1) - pgamma(n - 1e-5, 2, 1)
#' } else {
#' as.integer(rgamma(n, 2, 1))
#' }
#' }
#'
#' onsets <- sample_approx_dist(
#' cases = cases,
#' dist_fn = delay_fn
#' )
#'
#' # estimated onset distribution
#' print(onsets)
#'
#' # check that sum is equal to reported cases
#' total_onsets <- median(
#' purrr::map_dbl(
#' 1:10,
#' ~ sum(sample_approx_dist(
#' cases = cases,
#' dist_fn = delay_fn
#' )$cases)
#' )
#' )
#' total_onsets
#'
#'
#' # map from onset cases to reported
#' reports <- sample_approx_dist(
#' cases = cases,
#' dist_fn = delay_fn,
#' direction = "forwards"
#' )
#'
#'
#' # map from onset cases to reported using a mean shift
#' reports <- sample_approx_dist(
#' cases = cases,
#' dist_fn = delay_fn,
#' direction = "forwards",
#' type = "median"
#' )
#' }
sample_approx_dist <- function(cases = NULL,
dist_fn = NULL,
max_value = 120,
earliest_allowed_mapped = NULL,
direction = "backwards",
type = "sample",
truncate_future = TRUE) {
if (type %in% "sample") {
if (direction %in% "backwards") {
direction_fn <- rev
} else if (direction %in% "forwards") {
direction_fn <- function(x) {
x
}
}
# reverse cases so starts with current first
reversed_cases <- direction_fn(cases$cases)
reversed_cases[is.na(reversed_cases)] <- 0
# draw from the density fn of the dist
draw <- dist_fn(0:max_value, dist = TRUE, cum = FALSE)
# approximate cases
mapped_cases <- suppressMessages(purrr::map_dfc(
seq_along(reversed_cases),
~ c(
rep(0, . - 1),
stats::rbinom(
length(draw),
rep(reversed_cases[.], length(draw)),
draw
),
rep(0, length(reversed_cases) - .)
)
))
# set dates order based on direction mapping
if (direction %in% "backwards") {
dates <- seq(min(cases$date) - lubridate::days(length(draw) - 1),
max(cases$date),
by = "days"
)
} else if (direction %in% "forwards") {
dates <- seq(min(cases$date),
max(cases$date) + lubridate::days(length(draw) - 1),
by = "days"
)
}
# summarises movements and sample for placement of non-integer cases
case_sum <- direction_fn(rowSums(mapped_cases))
floor_case_sum <- floor(case_sum)
sample_cases <- floor_case_sum +
as.numeric((runif(seq_along(case_sum)) < (case_sum - floor_case_sum)))
# summarise imputed onsets and build output data.table
mapped_cases <- data.table::data.table(
date = dates,
cases = sample_cases
)
# filter out all zero cases until first recorded case
mapped_cases <- data.table::setorder(mapped_cases, date)
mapped_cases <- mapped_cases[
,
cum_cases := cumsum(cases)
][cum_cases != 0][, cum_cases := NULL]
} else if (type %in% "median") {
shift <- as.integer(
median(as.integer(dist_fn(1000, dist = FALSE)), na.rm = TRUE)
)
if (direction %in% "backwards") {
mapped_cases <- data.table::copy(cases)[
,
date := date - lubridate::days(shift)
]
} else if (direction %in% "forwards") {
mapped_cases <- data.table::copy(cases)[
,
date := date + lubridate::days(shift)
]
}
}
if (!is.null(earliest_allowed_mapped)) {
mapped_cases <- mapped_cases[date >= as.Date(earliest_allowed_mapped)]
}
# filter out future cases
if (direction %in% "forwards" && truncate_future) {
max_date <- max(cases$date)
mapped_cases <- mapped_cases[date <= max_date]
}
return(mapped_cases)
}
#' Tune an Inverse Gamma to Achieve the Target Truncation
#'
#' @description `r lifecycle::badge("deprecated")`
#' Allows an inverse gamma distribution to be. tuned so that less than 0.01 of
#' its probability mass function falls outside of the specified bounds. This is
#' required when using an inverse gamma prior, for example for a Gaussian
#' process. As no inverse gamma priors are currently in use and this function
#' has some stability issues it has been deprecated.
#'
#' @param lower Numeric, defaults to 2. Lower truncation bound.
#'
#' @param upper Numeric, defaults to 21. Upper truncation bound.
#'
#' @return A list of alpha and beta values that describe a inverse gamma
#' distribution that achieves the target truncation.
#' @export
#'
#' @keywords internal
#'
tune_inv_gamma <- function(lower = 2, upper = 21) {
lifecycle::deprecate_stop(
"1.3.6", "tune_inv_gamma()",
details = paste0(
"As no inverse gamma priors are currently in use and this function has ",
"some stability issues it has been deprecated. Please let the package ",
"authors know if deprecating this function has caused any issues. ",
"For the last active version of the function see the one contained ",
"in version 1.3.5 at ",
"https://github.com/epiforecasts/EpiNow2/blob/bad836ebd650ace73ad1ead887fd0eae98c52dd6/R/dist.R#L739" # nolint
)
)
}
#' Specify a distribution.
#'
#' @description `r lifecycle::badge("stable")`
#' Defines the parameters of a supported distribution for use in onward
#' modelling. Multiple distribution families are supported - see the
#' documentation for `family` for details. Alternatively, a nonparametric
#' distribution can be specified using the \code{pmf} argument.
#' This function provides distribution
#' functionality in [delay_opts()], [generation_time_opts()], and
#' [trunc_opts()].
#'
#' @param mean Numeric. If the only non-zero summary parameter
#' then this is the fixed interval of the distribution. If the `sd` is
#' non-zero then this is the mean of the distribution given by \code{dist}.
#' If this is not given a vector of empty vectors is returned.
#'
#' @param sd Numeric, defaults to 0. Sets the standard deviation of the
#' distribution.
#'
#' @param mean_sd Numeric, defaults to 0. Sets the standard deviation of the
#' uncertainty around the mean of the distribution assuming a normal
#' prior.
#'
#' @param sd_sd Numeric, defaults to 0. Sets the standard deviation of the
#' uncertainty around the sd of the distribution assuming a normal prior.
#'
#' @param distribution Character, defaults to "lognormal". The (discretised
#' distribution to be used. If sd == 0 then the distribution is fixed and a
#' delta function is used. If sd > 0 then the distribution is discretised and
#' truncated.
#'
#' The following distributions are currently supported:
#'
#' - "lognormal" - a lognormal distribution. For this distribution `mean`
#' is the mean of the natural logarithm of the delay (on the log scale) and
#' `sd` is the standard deviation of the natural logarithm of the delay.
#'
#' - "gamma" - a gamma distribution. For this distribution `mean` is the
#' mean of the delay and `sd` is the standard deviation of the delay. During
#' model fitting these are then transformed to the shape and scale of the gamma
#' distribution.
#'
#' When `distribution` is the default lognormal distribution the other function
#' arguments have the following definition:
#' - `mean` is the mean of the natural logarithm of the delay (on the
#' log scale).
#' - `sd` is the standard deviation of the natural logarithm of the delay.
#'
#' @param max Numeric, maximum value of the distribution. The distribution will
#' be truncated at this value.
#'
#' @param pmf Numeric, a vector of values that represent the (nonparametric)
#' probability mass function of the delay (starting with 0); defaults to an
#' empty vector corresponding to a parametric specification of the distribution
#' (using \code{mean}, \code{sd} and corresponding uncertainties)
#'
#' @param fixed Logical, defaults to `FALSE`. Should delays be treated
#' as coming from fixed (vs uncertain) distributions. Overrides any values
#' assigned to \code{mean_sd} and \code{sd_sd} by setting them to zero.
#' reduces compute requirement but may produce spuriously precise estimates.
#' @return A list of distribution options.
#'
#' @author Sebastian Funk
#' @author Sam Abbott
#' @importFrom rlang warn
#' @export
#' @examples
#' # A fixed lognormal distribution with mean 5 and sd 1.
#' dist_spec(mean = 5, sd = 1, max = 20, distribution = "lognormal")
#'
#' # An uncertain gamma distribution with mean 3 and sd 2
#' dist_spec(
#' mean = 3, sd = 2, mean_sd = 0.5, sd_sd = 0.5, max = 20,
#' distribution = "gamma"
#' )
dist_spec <- function(mean, sd = 0, mean_sd = 0, sd_sd = 0,
distribution = c("lognormal", "gamma"), max,
pmf = numeric(0), fixed = FALSE) {
## deprecate previous behaviour
warn(
message = paste(
"The meaning of the 'max' argument has changed compared to",
"previous versions. It now indicates the maximum of a distribution",
"rather than the length of the probability mass function (including 0)",
"that it represented previously. To replicate previous behaviour reduce",
"max by 1."
),
.frequency = "regularly",
.frequency_id = "dist_spec_max"
)
## check if parametric or nonparametric
if (length(pmf) > 0 &&
!all(
missing(mean), missing(sd), missing(mean_sd),
missing(sd_sd), missing(distribution), missing(max)
)) {
stop("Distributional parameters or a pmf can be specified, but not both.")
}
if (fixed) {
mean_sd <- 0
sd_sd <- 0
}
fixed <- mean_sd == 0 && mean_sd == 0
## check parametric parameters make sense
if (!missing(mean)) {
if (sd == 0 && sd_sd == 0) { ## integer fixed
if (mean %% 1 != 0) {
stop(
"When a distribution is set to a constant ",
"(sd == 0 and sd_sd == 0) then the mean parameter ",
"must be an integer."
)
}
max <- mean
if (mean_sd > 0) {
stop(
"When a distribution has sd == 0 and ",
"sd_sd == 0 then mean_sd must be 0, too."
)
}
} else {
if (missing(max)) {
stop("Maximum of parametric distributions must be specified.")
}
}
} else {
if (!all(
missing(sd), missing(mean_sd),
missing(sd_sd), missing(distribution), missing(max)
)) {
stop(
"If any distributional parameters are given then so must the mean."
)
}
}
distribution <- match.arg(distribution)
if (fixed) {
ret <- list(
mean_mean = numeric(0),
mean_sd = numeric(0),
sd_mean = numeric(0),
sd_sd = numeric(0),
dist = character(0),
max = integer(0)
)
if (length(pmf) == 0) {
if (missing(mean)) { ## empty
ret <- c(ret, list(
n = 0,
n_p = 0,
n_np = 0,
np_pmf = numeric(0),
fixed = integer(0)
))
} else { ## parametric fixed
if (sd == 0) { ## delta
pmf <- c(rep(0, mean), 1)
} else {
if (distribution == "lognormal") {
params <- lognorm_dist_def(
mean = mean, mean_sd = mean_sd,
sd = sd, sd_sd = sd_sd, max_value = max, samples = 1
)
} else if (distribution == "gamma") {
params <- gamma_dist_def(
mean = mean, mean_sd = mean_sd,
sd = sd, sd_sd = sd_sd, max_value = max, samples = 1