/
distributions.R
2575 lines (2446 loc) · 77.8 KB
/
distributions.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
#' The Student-t Distribution
#'
#' Density, distribution function, quantile function and random generation
#' for the Student-t distribution with location \code{mu}, scale \code{sigma},
#' and degrees of freedom \code{df}.
#'
#' @name StudentT
#'
#' @param x Vector of quantiles.
#' @param q Vector of quantiles.
#' @param p Vector of probabilities.
#' @param n Number of draws to sample from the distribution.
#' @param mu Vector of location values.
#' @param sigma Vector of scale values.
#' @param df Vector of degrees of freedom.
#' @param log Logical; If \code{TRUE}, values are returned on the log scale.
#' @param log.p Logical; If \code{TRUE}, values are returned on the log scale.
#' @param lower.tail Logical; If \code{TRUE} (default), return P(X <= x).
#' Else, return P(X > x) .
#'
#' @details See \code{vignette("brms_families")} for details
#' on the parameterization.
#'
#' @seealso \code{\link[stats:TDist]{TDist}}
#'
#' @export
dstudent_t <- function(x, df, mu = 0, sigma = 1, log = FALSE) {
if (isTRUE(any(sigma < 0))) {
stop2("sigma must be non-negative.")
}
if (log) {
dt((x - mu) / sigma, df = df, log = TRUE) - log(sigma)
} else {
dt((x - mu) / sigma, df = df) / sigma
}
}
#' @rdname StudentT
#' @export
pstudent_t <- function(q, df, mu = 0, sigma = 1,
lower.tail = TRUE, log.p = FALSE) {
if (isTRUE(any(sigma < 0))) {
stop2("sigma must be non-negative.")
}
pt((q - mu) / sigma, df = df, lower.tail = lower.tail, log.p = log.p)
}
#' @rdname StudentT
#' @export
qstudent_t <- function(p, df, mu = 0, sigma = 1,
lower.tail = TRUE, log.p = FALSE) {
if (isTRUE(any(sigma < 0))) {
stop2("sigma must be non-negative.")
}
mu + sigma * qt(p, df = df, lower.tail = lower.tail, log.p = log.p)
}
#' @rdname StudentT
#' @export
rstudent_t <- function(n, df, mu = 0, sigma = 1) {
if (isTRUE(any(sigma < 0))) {
stop2("sigma must be non-negative.")
}
mu + sigma * rt(n, df = df)
}
#' The Multivariate Normal Distribution
#'
#' Density function and random generation for the multivariate normal
#' distribution with mean vector \code{mu} and covariance matrix \code{Sigma}.
#'
#' @name MultiNormal
#'
#' @inheritParams StudentT
#' @param x Vector or matrix of quantiles. If \code{x} is a matrix,
#' each row is taken to be a quantile.
#' @param mu Mean vector with length equal to the number of dimensions.
#' @param Sigma Covariance matrix.
#' @param check Logical; Indicates whether several input checks
#' should be performed. Defaults to \code{FALSE} to improve
#' efficiency.
#'
#' @details See the Stan user's manual \url{https://mc-stan.org/documentation/}
#' for details on the parameterization
#'
#' @export
dmulti_normal <- function(x, mu, Sigma, log = FALSE, check = FALSE) {
if (is.vector(x) || length(dim(x)) == 1L) {
x <- matrix(x, ncol = length(x))
}
p <- ncol(x)
if (check) {
if (length(mu) != p) {
stop2("Dimension of mu is incorrect.")
}
if (!all(dim(Sigma) == c(p, p))) {
stop2("Dimension of Sigma is incorrect.")
}
if (!is_symmetric(Sigma)) {
stop2("Sigma must be a symmetric matrix.")
}
}
chol_Sigma <- chol(Sigma)
rooti <- backsolve(chol_Sigma, t(x) - mu, transpose = TRUE)
quads <- colSums(rooti^2)
out <- -(p / 2) * log(2 * pi) - sum(log(diag(chol_Sigma))) - .5 * quads
if (!log) {
out <- exp(out)
}
out
}
#' @rdname MultiNormal
#' @export
rmulti_normal <- function(n, mu, Sigma, check = FALSE) {
p <- length(mu)
if (check) {
if (!(is_wholenumber(n) && n > 0)) {
stop2("n must be a positive integer.")
}
if (!all(dim(Sigma) == c(p, p))) {
stop2("Dimension of Sigma is incorrect.")
}
if (!is_symmetric(Sigma)) {
stop2("Sigma must be a symmetric matrix.")
}
}
draws <- matrix(rnorm(n * p), nrow = n, ncol = p)
sweep(draws %*% chol(Sigma), 2, mu, "+")
}
#' The Multivariate Student-t Distribution
#'
#' Density function and random generation for the multivariate Student-t
#' distribution with location vector \code{mu}, covariance matrix \code{Sigma},
#' and degrees of freedom \code{df}.
#'
#' @name MultiStudentT
#'
#' @inheritParams StudentT
#' @param x Vector or matrix of quantiles. If \code{x} is a matrix,
#' each row is taken to be a quantile.
#' @param mu Location vector with length equal to the number of dimensions.
#' @param Sigma Covariance matrix.
#' @param check Logical; Indicates whether several input checks
#' should be performed. Defaults to \code{FALSE} to improve
#' efficiency.
#'
#' @details See the Stan user's manual \url{https://mc-stan.org/documentation/}
#' for details on the parameterization
#'
#' @export
dmulti_student_t <- function(x, df, mu, Sigma, log = FALSE, check = FALSE) {
if (is.vector(x) || length(dim(x)) == 1L) {
x <- matrix(x, ncol = length(x))
}
p <- ncol(x)
if (check) {
if (isTRUE(any(df <= 0))) {
stop2("df must be greater than 0.")
}
if (length(mu) != p) {
stop2("Dimension of mu is incorrect.")
}
if (!all(dim(Sigma) == c(p, p))) {
stop2("Dimension of Sigma is incorrect.")
}
if (!is_symmetric(Sigma)) {
stop2("Sigma must be a symmetric matrix.")
}
}
chol_Sigma <- chol(Sigma)
rooti <- backsolve(chol_Sigma, t(x) - mu, transpose = TRUE)
quads <- colSums(rooti^2)
out <- lgamma((p + df)/2) - (lgamma(df / 2) + sum(log(diag(chol_Sigma))) +
p / 2 * log(pi * df)) - 0.5 * (df + p) * log1p(quads / df)
if (!log) {
out <- exp(out)
}
out
}
#' @rdname MultiStudentT
#' @export
rmulti_student_t <- function(n, df, mu, Sigma, check = FALSE) {
p <- length(mu)
if (isTRUE(any(df <= 0))) {
stop2("df must be greater than 0.")
}
draws <- rmulti_normal(n, mu = rep(0, p), Sigma = Sigma, check = check)
draws <- draws / sqrt(rchisq(n, df = df) / df)
sweep(draws, 2, mu, "+")
}
#' The (Multivariate) Logistic Normal Distribution
#'
#' Density function and random generation for the (multivariate) logistic normal
#' distribution with latent mean vector \code{mu} and covariance matrix \code{Sigma}.
#'
#' @name LogisticNormal
#'
#' @inheritParams StudentT
#' @param x Vector or matrix of quantiles. If \code{x} is a matrix,
#' each row is taken to be a quantile.
#' @param mu Mean vector with length equal to the number of dimensions.
#' @param Sigma Covariance matrix.
#' @param refcat A single integer indicating the reference category.
#' Defaults to \code{1}.
#' @param check Logical; Indicates whether several input checks
#' should be performed. Defaults to \code{FALSE} to improve
#' efficiency.
#'
#' @export
dlogistic_normal <- function(x, mu, Sigma, refcat = 1, log = FALSE,
check = FALSE) {
if (is.vector(x) || length(dim(x)) == 1L) {
x <- matrix(x, ncol = length(x))
}
lx <- link_categorical(x, refcat)
out <- dmulti_normal(lx, mu, Sigma, log = TRUE) - rowSums(log(x))
if (!log) {
out <- exp(out)
}
out
}
#' @rdname LogisticNormal
#' @export
rlogistic_normal <- function(n, mu, Sigma, refcat = 1, check = FALSE) {
out <- rmulti_normal(n, mu, Sigma, check = check)
inv_link_categorical(out, refcat = refcat)
}
#' The Skew-Normal Distribution
#'
#' Density, distribution function, and random generation for the
#' skew-normal distribution with mean \code{mu},
#' standard deviation \code{sigma}, and skewness \code{alpha}.
#'
#' @name SkewNormal
#'
#' @inheritParams StudentT
#' @param x,q Vector of quantiles.
#' @param mu Vector of mean values.
#' @param sigma Vector of standard deviation values.
#' @param alpha Vector of skewness values.
#' @param xi Optional vector of location values.
#' If \code{NULL} (the default), will be computed internally.
#' @param omega Optional vector of scale values.
#' If \code{NULL} (the default), will be computed internally.
#' @param tol Tolerance of the approximation used in the
#' computation of quantiles.
#'
#' @details See \code{vignette("brms_families")} for details
#' on the parameterization.
#'
#' @export
dskew_normal <- function(x, mu = 0, sigma = 1, alpha = 0,
xi = NULL, omega = NULL, log = FALSE) {
if (isTRUE(any(sigma < 0))) {
stop2("sigma must be greater than 0.")
}
args <- cp2dp(mu, sigma, alpha, xi = xi, omega = omega, x = x)
out <- with(args, {
# do it like sn::dsn
z <- (x - xi) / omega
if (length(alpha) == 1L) {
alpha <- rep(alpha, length(z))
}
logN <- -log(sqrt(2 * pi)) - log(omega) - z^2 / 2
logS <- ifelse(
abs(alpha) < Inf,
pnorm(alpha * z, log.p = TRUE),
log(as.numeric(sign(alpha) * z > 0))
)
out <- logN + logS - pnorm(0, log.p = TRUE)
ifelse(abs(z) == Inf, -Inf, out)
})
if (!log) {
out <- exp(out)
}
out
}
#' @rdname SkewNormal
#' @export
pskew_normal <- function(q, mu = 0, sigma = 1, alpha = 0,
xi = NULL, omega = NULL,
lower.tail = TRUE, log.p = FALSE) {
require_package("mnormt")
if (isTRUE(any(sigma < 0))) {
stop2("sigma must be non-negative.")
}
args <- cp2dp(mu, sigma, alpha, xi = xi, omega = omega, q = q)
out <- with(args, {
# do it like sn::psn
z <- (q - xi) / omega
nz <- length(z)
is_alpha_inf <- abs(alpha) == Inf
delta[is_alpha_inf] <- sign(alpha[is_alpha_inf])
out <- numeric(nz)
for (k in seq_len(nz)) {
if (is.infinite(z[k])) {
if (z[k] > 0) {
out[k] <- 1
} else {
out[k] <- 0
}
} else if (is_alpha_inf[k]) {
if (alpha[k] > 0) {
out[k] <- 2 * (pnorm(pmax(z[k], 0)) - 0.5)
} else {
out[k] <- 1 - 2 * (0.5 - pnorm(pmin(z[k], 0)))
}
} else {
S <- matrix(c(1, -delta[k], -delta[k], 1), 2, 2)
out[k] <- 2 * mnormt::biv.nt.prob(
0, lower = rep(-Inf, 2), upper = c(z[k], 0),
mean = c(0, 0), S = S
)
}
}
pmin(1, pmax(0, out))
})
if (!lower.tail) {
out <- 1 - out
}
if (log.p) {
out <- log(out)
}
out
}
#' @rdname SkewNormal
#' @export
qskew_normal <- function(p, mu = 0, sigma = 1, alpha = 0,
xi = NULL, omega = NULL,
lower.tail = TRUE, log.p = FALSE,
tol = 1e-8) {
if (isTRUE(any(sigma < 0))) {
stop2("sigma must be non-negative.")
}
p <- validate_p_dist(p, lower.tail = lower.tail, log.p = log.p)
args <- cp2dp(mu, sigma, alpha, xi = xi, omega = omega, p = p)
out <- with(args, {
# do it like sn::qsn
na <- is.na(p) | (p < 0) | (p > 1)
zero <- (p == 0)
one <- (p == 1)
p <- replace(p, (na | zero | one), 0.5)
cum <- skew_normal_cumulants(0, 1, alpha, n = 4)
g1 <- cum[, 3] / cum[, 2]^(3 / 2)
g2 <- cum[, 4] / cum[, 2]^2
x <- qnorm(p)
x <- x + (x^2 - 1) * g1 / 6 +
x * (x^2 - 3) * g2 / 24 -
x * (2 * x^2 - 5) * g1^2 / 36
x <- cum[, 1] + sqrt(cum[, 2]) * x
px <- pskew_normal(x, xi = 0, omega = 1, alpha = alpha)
max_err <- 1
while (max_err > tol) {
x1 <- x - (px - p) /
dskew_normal(x, xi = 0, omega = 1, alpha = alpha)
x <- x1
px <- pskew_normal(x, xi = 0, omega = 1, alpha = alpha)
max_err <- max(abs(px - p))
if (is.na(max_err)) {
warning2("Approximation in 'qskew_normal' might have failed.")
}
}
x <- replace(x, na, NA)
x <- replace(x, zero, -Inf)
x <- replace(x, one, Inf)
as.numeric(xi + omega * x)
})
out
}
#' @rdname SkewNormal
#' @export
rskew_normal <- function(n, mu = 0, sigma = 1, alpha = 0,
xi = NULL, omega = NULL) {
if (isTRUE(any(sigma < 0))) {
stop2("sigma must be non-negative.")
}
args <- cp2dp(mu, sigma, alpha, xi = xi, omega = omega)
with(args, {
# do it like sn::rsn
z1 <- rnorm(n)
z2 <- rnorm(n)
id <- z2 > args$alpha * z1
z1[id] <- -z1[id]
xi + omega * z1
})
}
# convert skew-normal mixed-CP to DP parameterization
# @return a data.frame containing all relevant parameters
cp2dp <- function(mu = 0, sigma = 1, alpha = 0,
xi = NULL, omega = NULL, ...) {
delta <- alpha / sqrt(1 + alpha^2)
if (is.null(omega)) {
omega <- sigma / sqrt(1 - 2 / pi * delta^2)
}
if (is.null(xi)) {
xi <- mu - omega * delta * sqrt(2 / pi)
}
expand(dots = nlist(mu, sigma, alpha, xi, omega, delta, ...))
}
# helper function for qskew_normal
# code basis taken from sn::sn.cumulants
# uses xi and omega rather than mu and sigma
skew_normal_cumulants <- function(xi = 0, omega = 1, alpha = 0, n = 4) {
cumulants_half_norm <- function(n) {
n <- max(n, 2)
n <- as.integer(2 * ceiling(n/2))
half.n <- as.integer(n/2)
m <- 0:(half.n - 1)
a <- sqrt(2/pi)/(gamma(m + 1) * 2^m * (2 * m + 1))
signs <- rep(c(1, -1), half.n)[seq_len(half.n)]
a <- as.vector(rbind(signs * a, rep(0, half.n)))
coeff <- rep(a[1], n)
for (k in 2:n) {
ind <- seq_len(k - 1)
coeff[k] <- a[k] - sum(ind * coeff[ind] * a[rev(ind)]/k)
}
kappa <- coeff * gamma(seq_len(n) + 1)
kappa[2] <- 1 + kappa[2]
return(kappa)
}
args <- expand(dots = nlist(xi, omega, alpha))
with(args, {
# do it like sn::sn.cumulants
delta <- alpha / sqrt(1 + alpha^2)
kv <- cumulants_half_norm(n)
if (length(kv) > n) {
kv <- kv[-(n + 1)]
}
kv[2] <- kv[2] - 1
kappa <- outer(delta, 1:n, "^") *
matrix(rep(kv, length(xi)), ncol = n, byrow = TRUE)
kappa[, 2] <- kappa[, 2] + 1
kappa <- kappa * outer(omega, 1:n, "^")
kappa[, 1] <- kappa[, 1] + xi
kappa
})
}
# CDF of the inverse gamma function
pinvgamma <- function(q, shape, rate, lower.tail = TRUE, log.p = FALSE) {
pgamma(1/q, shape, rate = rate, lower.tail = !lower.tail, log.p = log.p)
}
#' The von Mises Distribution
#'
#' Density, distribution function, and random generation for the
#' von Mises distribution with location \code{mu}, and precision \code{kappa}.
#'
#' @name VonMises
#'
#' @inheritParams StudentT
#' @param x,q Vector of quantiles between \code{-pi} and \code{pi}.
#' @param kappa Vector of precision values.
#' @param acc Accuracy of numerical approximations.
#'
#' @details See \code{vignette("brms_families")} for details
#' on the parameterization.
#'
#' @export
dvon_mises <- function(x, mu, kappa, log = FALSE) {
if (isTRUE(any(kappa < 0))) {
stop2("kappa must be non-negative")
}
# expects x in [-pi, pi] rather than [0, 2*pi] as CircStats::dvm
be <- besselI(kappa, nu = 0, expon.scaled = TRUE)
out <- -log(2 * pi * be) + kappa * (cos(x - mu) - 1)
if (!log) {
out <- exp(out)
}
out
}
#' @rdname VonMises
#' @export
pvon_mises <- function(q, mu, kappa, lower.tail = TRUE,
log.p = FALSE, acc = 1e-20) {
if (isTRUE(any(kappa < 0))) {
stop2("kappa must be non-negative")
}
pi <- base::pi
pi2 <- 2 * pi
q <- (q + pi) %% pi2
mu <- (mu + pi) %% pi2
args <- expand(q = q, mu = mu, kappa = kappa)
q <- args$q
mu <- args$mu
kappa <- args$kappa
rm(args)
# code basis taken from CircStats::pvm but improved
# considerably with respect to speed and stability
rec_sum <- function(q, kappa, acc, sum = 0, i = 1) {
# compute the sum of of besselI functions recursively
term <- (besselI(kappa, nu = i) * sin(i * q)) / i
sum <- sum + term
rd <- abs(term) >= acc
if (sum(rd)) {
sum[rd] <- rec_sum(
q[rd], kappa[rd], acc, sum = sum[rd], i = i + 1
)
}
sum
}
.pvon_mises <- function(q, kappa, acc) {
sum <- rec_sum(q, kappa, acc)
q / pi2 + sum / (pi * besselI(kappa, nu = 0))
}
out <- rep(NA, length(mu))
zero_mu <- mu == 0
if (sum(zero_mu)) {
out[zero_mu] <- .pvon_mises(q[zero_mu], kappa[zero_mu], acc)
}
lq_mu <- q <= mu
if (sum(lq_mu)) {
upper <- (q[lq_mu] - mu[lq_mu]) %% pi2
upper[upper == 0] <- pi2
lower <- (-mu[lq_mu]) %% pi2
out[lq_mu] <-
.pvon_mises(upper, kappa[lq_mu], acc) -
.pvon_mises(lower, kappa[lq_mu], acc)
}
uq_mu <- q > mu
if (sum(uq_mu)) {
upper <- q[uq_mu] - mu[uq_mu]
lower <- mu[uq_mu] %% pi2
out[uq_mu] <-
.pvon_mises(upper, kappa[uq_mu], acc) +
.pvon_mises(lower, kappa[uq_mu], acc)
}
if (!lower.tail) {
out <- 1 - out
}
if (log.p) {
out <- log(out)
}
out
}
#' @rdname VonMises
#' @export
rvon_mises <- function(n, mu, kappa) {
if (isTRUE(any(kappa < 0))) {
stop2("kappa must be non-negative")
}
args <- expand(mu = mu, kappa = kappa, length = n)
mu <- args$mu
kappa <- args$kappa
rm(args)
pi <- base::pi
mu <- mu + pi
# code basis taken from CircStats::rvm but improved
# considerably with respect to speed and stability
rvon_mises_outer <- function(r, mu, kappa) {
n <- length(r)
U1 <- runif(n, 0, 1)
z <- cos(pi * U1)
f <- (1 + r * z) / (r + z)
c <- kappa * (r - f)
U2 <- runif(n, 0, 1)
outer <- is.na(f) | is.infinite(f) |
!(c * (2 - c) - U2 > 0 | log(c / U2) + 1 - c >= 0)
inner <- !outer
out <- rep(NA, n)
if (sum(inner)) {
out[inner] <- rvon_mises_inner(f[inner], mu[inner])
}
if (sum(outer)) {
# evaluate recursively until a valid sample is found
out[outer] <- rvon_mises_outer(r[outer], mu[outer], kappa[outer])
}
out
}
rvon_mises_inner <- function(f, mu) {
n <- length(f)
U3 <- runif(n, 0, 1)
(sign(U3 - 0.5) * acos(f) + mu) %% (2 * pi)
}
a <- 1 + (1 + 4 * (kappa^2))^0.5
b <- (a - (2 * a)^0.5) / (2 * kappa)
r <- (1 + b^2) / (2 * b)
# indicates underflow due to kappa being close to zero
is_uf <- is.na(r) | is.infinite(r)
not_uf <- !is_uf
out <- rep(NA, n)
if (sum(is_uf)) {
out[is_uf] <- runif(sum(is_uf), 0, 2 * pi)
}
if (sum(not_uf)) {
out[not_uf] <- rvon_mises_outer(r[not_uf], mu[not_uf], kappa[not_uf])
}
out - pi
}
#' The Exponentially Modified Gaussian Distribution
#'
#' Density, distribution function, and random generation
#' for the exponentially modified Gaussian distribution with
#' mean \code{mu} and standard deviation \code{sigma} of the gaussian
#' component, as well as scale \code{beta} of the exponential
#' component.
#'
#' @name ExGaussian
#'
#' @inheritParams StudentT
#' @param x,q Vector of quantiles.
#' @param mu Vector of means of the combined distribution.
#' @param sigma Vector of standard deviations of the gaussian component.
#' @param beta Vector of scales of the exponential component.
#'
#' @details See \code{vignette("brms_families")} for details
#' on the parameterization.
#'
#' @export
dexgaussian <- function(x, mu, sigma, beta, log = FALSE) {
if (isTRUE(any(sigma < 0))) {
stop2("sigma must be non-negative.")
}
if (isTRUE(any(beta < 0))) {
stop2("beta must be non-negative.")
}
args <- nlist(x, mu, sigma, beta)
args <- do_call(expand, args)
args$mu <- with(args, mu - beta)
args$z <- with(args, x - mu - sigma^2 / beta)
out <- with(args,
-log(beta) - (z + sigma^2 / (2 * beta)) / beta +
pnorm(z / sigma, log.p = TRUE)
)
if (!log) {
out <- exp(out)
}
out
}
#' @rdname ExGaussian
#' @export
pexgaussian <- function(q, mu, sigma, beta,
lower.tail = TRUE, log.p = FALSE) {
if (isTRUE(any(sigma < 0))) {
stop2("sigma must be non-negative.")
}
if (isTRUE(any(beta < 0))) {
stop2("beta must be non-negative.")
}
args <- nlist(q, mu, sigma, beta)
args <- do_call(expand, args)
args$mu <- with(args, mu - beta)
args$z <- with(args, q - mu - sigma^2 / beta)
out <- with(args,
pnorm((q - mu) / sigma) - pnorm(z / sigma) *
exp(((mu + sigma^2 / beta)^2 - mu^2 - 2 * q * sigma^2 / beta) /
(2 * sigma^2))
)
if (!lower.tail) {
out <- 1 - out
}
if (log.p) {
out <- log(out)
}
out
}
#' @rdname ExGaussian
#' @export
rexgaussian <- function(n, mu, sigma, beta) {
if (isTRUE(any(sigma < 0))) {
stop2("sigma must be non-negative.")
}
if (isTRUE(any(beta < 0))) {
stop2("beta must be non-negative.")
}
mu <- mu - beta
rnorm(n, mean = mu, sd = sigma) + rexp(n, rate = 1 / beta)
}
#' The Frechet Distribution
#'
#' Density, distribution function, quantile function and random generation
#' for the Frechet distribution with location \code{loc}, scale \code{scale},
#' and shape \code{shape}.
#'
#' @name Frechet
#'
#' @inheritParams StudentT
#' @param x,q Vector of quantiles.
#' @param loc Vector of locations.
#' @param scale Vector of scales.
#' @param shape Vector of shapes.
#'
#' @details See \code{vignette("brms_families")} for details
#' on the parameterization.
#'
#' @export
dfrechet <- function(x, loc = 0, scale = 1, shape = 1, log = FALSE) {
if (isTRUE(any(scale <= 0))) {
stop2("Argument 'scale' must be positive.")
}
if (isTRUE(any(shape <= 0))) {
stop2("Argument 'shape' must be positive.")
}
x <- (x - loc) / scale
args <- nlist(x, loc, scale, shape)
args <- do_call(expand, args)
out <- with(args,
log(shape / scale) - (1 + shape) * log(x) - x^(-shape)
)
if (!log) {
out <- exp(out)
}
out
}
#' @rdname Frechet
#' @export
pfrechet <- function(q, loc = 0, scale = 1, shape = 1,
lower.tail = TRUE, log.p = FALSE) {
if (isTRUE(any(scale <= 0))) {
stop2("Argument 'scale' must be positive.")
}
if (isTRUE(any(shape <= 0))) {
stop2("Argument 'shape' must be positive.")
}
q <- pmax((q - loc) / scale, 0)
out <- exp(-q^(-shape))
if (!lower.tail) {
out <- 1 - out
}
if (log.p) {
out <- log(out)
}
out
}
#' @rdname Frechet
#' @export
qfrechet <- function(p, loc = 0, scale = 1, shape = 1,
lower.tail = TRUE, log.p = FALSE) {
if (isTRUE(any(scale <= 0))) {
stop2("Argument 'scale' must be positive.")
}
if (isTRUE(any(shape <= 0))) {
stop2("Argument 'shape' must be positive.")
}
p <- validate_p_dist(p, lower.tail = lower.tail, log.p = log.p)
loc + scale * (-log(p))^(-1/shape)
}
#' @rdname Frechet
#' @export
rfrechet <- function(n, loc = 0, scale = 1, shape = 1) {
if (isTRUE(any(scale <= 0))) {
stop2("Argument 'scale' must be positive.")
}
if (isTRUE(any(shape <= 0))) {
stop2("Argument 'shape' must be positive.")
}
loc + scale * rexp(n)^(-1 / shape)
}
#' The Shifted Log Normal Distribution
#'
#' Density, distribution function, quantile function and random generation
#' for the shifted log normal distribution with mean \code{meanlog},
#' standard deviation \code{sdlog}, and shift parameter \code{shift}.
#'
#' @name Shifted_Lognormal
#'
#' @inheritParams StudentT
#' @param x,q Vector of quantiles.
#' @param meanlog Vector of means.
#' @param sdlog Vector of standard deviations.
#' @param shift Vector of shifts.
#'
#' @details See \code{vignette("brms_families")} for details
#' on the parameterization.
#'
#' @export
dshifted_lnorm <- function(x, meanlog = 0, sdlog = 1, shift = 0, log = FALSE) {
args <- nlist(dist = "lnorm", x, shift, meanlog, sdlog, log)
do_call(dshifted, args)
}
#' @rdname Shifted_Lognormal
#' @export
pshifted_lnorm <- function(q, meanlog = 0, sdlog = 1, shift = 0,
lower.tail = TRUE, log.p = FALSE) {
args <- nlist(dist = "lnorm", q, shift, meanlog, sdlog, lower.tail, log.p)
do_call(pshifted, args)
}
#' @rdname Shifted_Lognormal
#' @export
qshifted_lnorm <- function(p, meanlog = 0, sdlog = 1, shift = 0,
lower.tail = TRUE, log.p = FALSE) {
args <- nlist(dist = "lnorm", p, shift, meanlog, sdlog, lower.tail, log.p)
do_call(qshifted, args)
}
#' @rdname Shifted_Lognormal
#' @export
rshifted_lnorm <- function(n, meanlog = 0, sdlog = 1, shift = 0) {
args <- nlist(dist = "lnorm", n, shift, meanlog, sdlog)
do_call(rshifted, args)
}
#' The Inverse Gaussian Distribution
#'
#' Density, distribution function, and random generation
#' for the inverse Gaussian distribution with location \code{mu},
#' and shape \code{shape}.
#'
#' @name InvGaussian
#'
#' @inheritParams StudentT
#' @param x,q Vector of quantiles.
#' @param mu Vector of locations.
#' @param shape Vector of shapes.
#'
#' @details See \code{vignette("brms_families")} for details
#' on the parameterization.
#'
#' @export
dinv_gaussian <- function(x, mu = 1, shape = 1, log = FALSE) {
if (isTRUE(any(mu <= 0))) {
stop2("Argument 'mu' must be positive.")
}
if (isTRUE(any(shape <= 0))) {
stop2("Argument 'shape' must be positive.")
}
args <- nlist(x, mu, shape)
args <- do_call(expand, args)
out <- with(args,
0.5 * log(shape / (2 * pi)) -
1.5 * log(x) - 0.5 * shape * (x - mu)^2 / (x * mu^2)
)
if (!log) {
out <- exp(out)
}
out
}
#' @rdname InvGaussian
#' @export
pinv_gaussian <- function(q, mu = 1, shape = 1, lower.tail = TRUE,
log.p = FALSE) {
if (isTRUE(any(mu <= 0))) {
stop2("Argument 'mu' must be positive.")
}
if (isTRUE(any(shape <= 0))) {
stop2("Argument 'shape' must be positive.")
}
args <- nlist(q, mu, shape)
args <- do_call(expand, args)
out <- with(args,
pnorm(sqrt(shape / q) * (q / mu - 1)) +
exp(2 * shape / mu) * pnorm(-sqrt(shape / q) * (q / mu + 1))
)
if (!lower.tail) {
out <- 1 - out
}
if (log.p) {
out <- log(out)
}
out
}
#' @rdname InvGaussian
#' @export
rinv_gaussian <- function(n, mu = 1, shape = 1) {
# create random numbers for the inverse gaussian distribution
# Args:
# Args: see dinv_gaussian
if (isTRUE(any(mu <= 0))) {
stop2("Argument 'mu' must be positive.")
}
if (isTRUE(any(shape <= 0))) {
stop2("Argument 'shape' must be positive.")
}
args <- nlist(mu, shape, length = n)
args <- do_call(expand, args)
# algorithm from wikipedia
args$y <- rnorm(n)^2
args$x <- with(args,
mu + (mu^2 * y) / (2 * shape) - mu / (2 * shape) *
sqrt(4 * mu * shape * y + mu^2 * y^2)
)
args$z <- runif(n)
with(args, ifelse(z <= mu / (mu + x), x, mu^2 / x))
}
#' The Beta-binomial Distribution
#'
#' Cumulative density & mass functions, and random number generation for the
#' Beta-binomial distribution using the following re-parameterisation of the
#' \href{https://mc-stan.org/docs/2_29/functions-reference/beta-binomial-distribution.html}{Stan
#' Beta-binomial definition}:
#' \itemize{
#' \item{\code{mu = alpha * beta}} mean probability of trial success.
#' \item{\code{phi = (1 - mu) * beta}} precision or over-dispersion, component.
#' }
#'
#' @name BetaBinomial
#'
#' @inheritParams StudentT
#' @param x,q Vector of quantiles.
#' @param size Vector of number of trials (zero or more).
#' @param mu Vector of means.
#' @param phi Vector of precisions.
#'
#' @export
dbeta_binomial <- function(x, size, mu, phi, log = FALSE) {
require_package("extraDistr")
alpha <- mu * phi
beta <- (1 - mu) * phi
extraDistr::dbbinom(x, size, alpha = alpha, beta = beta, log = log)
}
#' @rdname BetaBinomial
#' @export
pbeta_binomial <- function(q, size, mu, phi, lower.tail = TRUE, log.p = FALSE) {
require_package("extraDistr")
alpha <- mu * phi
beta <- (1 - mu) * phi
extraDistr::pbbinom(q, size, alpha = alpha, beta = beta,
lower.tail = lower.tail, log.p = log.p)
}
#' @rdname BetaBinomial
#' @export
rbeta_binomial <- function(n, size, mu, phi) {
# beta location-scale probabilities
probs <- rbeta(n, mu * phi, (1 - mu) * phi)
# binomial draws
rbinom(n, size = size, prob = probs)
}
#' The Generalized Extreme Value Distribution
#'
#' Density, distribution function, and random generation
#' for the generalized extreme value distribution with
#' location \code{mu}, scale \code{sigma} and shape \code{xi}.
#'
#' @name GenExtremeValue
#'
#' @inheritParams StudentT
#' @param x,q Vector of quantiles.
#' @param mu Vector of locations.
#' @param sigma Vector of scales.
#' @param xi Vector of shapes.
#'
#' @details See \code{vignette("brms_families")} for details
#' on the parameterization.
#'
#' @export
dgen_extreme_value <- function(x, mu = 0, sigma = 1, xi = 0, log = FALSE) {
if (isTRUE(any(sigma <= 0))) {
stop2("sigma bust be positive.")
}
x <- (x - mu) / sigma
args <- nlist(x, mu, sigma, xi)
args <- do_call(expand, args)
args$t <- with(args, 1 + xi * x)
out <- with(args, ifelse(
xi == 0,
-log(sigma) - x - exp(-x),
-log(sigma) - (1 + 1 / xi) * log(t) - t^(-1 / xi)
))
if (!log) {
out <- exp(out)
}
out
}
#' @rdname GenExtremeValue
#' @export
pgen_extreme_value <- function(q, mu = 0, sigma = 1, xi = 0,
lower.tail = TRUE, log.p = FALSE) {
if (isTRUE(any(sigma <= 0))) {
stop2("sigma bust be positive.")
}
q <- (q - mu) / sigma