forked from paul-buerkner/brms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbrmsfit-methods.R
3206 lines (3128 loc) · 113 KB
/
brmsfit-methods.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
#' @export
parnames.brmsfit <- function(x, ...) {
out <- dimnames(x$fit)
if (is.list(out)) {
out <- out$parameters
}
out
}
#' Extract Population-Level Estimates
#'
#' Extract the population-level ('fixed') effects
#' from a \code{brmsfit} object.
#'
#' @aliases fixef
#'
#' @param object An object of class \code{brmsfit}.
#' @param ... Currently ignored.
#' @inheritParams predict.brmsfit
#'
#' @return If \code{summary} is \code{TRUE}, a matrix with one row per
#' population-level effect and one column per calculated estimate.
#' If \code{summary} is \code{FALSE}, a matrix with one row per
#' posterior sample and one column per population-level effect.
#'
#' @author Paul-Christian Buerkner \email{[email protected]}
#'
#' @examples
#' \dontrun{
#' fit <- brm(time | cens(censored) ~ age + sex + disease,
#' data = kidney, family = "exponential")
#' fixef(fit)
#' }
#'
#' @method fixef brmsfit
#' @export
#' @export fixef
#' @importFrom nlme fixef
fixef.brmsfit <- function(object, summary = TRUE, robust = FALSE,
probs = c(0.025, 0.975), ...) {
contains_samples(object)
pars <- parnames(object)
fpars <- pars[grepl(fixef_pars(), pars)]
if (!length(fpars)) {
stop2("The model does not contain population-level effects.")
}
out <- as.matrix(object, pars = fpars, exact_match = TRUE)
colnames(out) <- gsub(fixef_pars(), "", fpars)
if (summary) {
out <- posterior_summary(out, probs, robust)
}
out
}
#' Covariance and Correlation Matrix of Population-Level Effects
#'
#' Get a point estimate of the covariance or
#' correlation matrix of population-level parameters
#'
#' @param object An object of class \code{brmsfit}
#' @param correlation logical; if \code{FALSE} (the default),
#' compute the covariance matrix,
#' if \code{TRUE}, compute the correlation matrix
#' @param ... Currently ignored
#'
#' @return covariance or correlation matrix of population-level parameters
#'
#' @details Estimates are obtained by calculating the maximum likelihood
#' covariances (correlations) of the posterior samples.
#'
#' @examples
#' \dontrun{
#' fit <- brm(count ~ log_Age_c + log_Base4_c * Trt_c + (1+Trt_c|visit),
#' data = epilepsy, family = gaussian(), chains = 2)
#' vcov(fit)
#' }
#'
#' @export
vcov.brmsfit <- function(object, correlation = FALSE, ...) {
contains_samples(object)
pars <- parnames(object)
fpars <- pars[grepl(fixef_pars(), pars)]
if (!length(fpars)) {
stop2("The model does not contain population-level effects.")
}
samples <- posterior_samples(object, pars = fpars, exact_match = TRUE)
names(samples) <- sub(fixef_pars(), "", names(samples))
if (correlation) {
out <- cor(samples)
} else {
out <- cov(samples)
}
out
}
#' Extract Group-Level Estimates
#'
#' Extract the group-level ('random') effects of each level
#' from a \code{brmsfit} object.
#'
#' @aliases ranef
#'
#' @param object An object of class \code{brmsfit}.
#' @inheritParams fixef.brmsfit
#' @param ... Currently ignored.
#'
#' @return If \code{old} is \code{FALSE}: A list of arrays
#' (one per grouping factor). If \code{summary} is \code{TRUE},
#' names of the first dimension are the factor levels and names
#' of the third dimension are the group-level effects.
#' If \code{summary} is \code{FALSE}, names of the second dimension
#' are the factor levels and names of the third dimension are the
#' group-level effects.
#'
#' @author Paul-Christian Buerkner \email{[email protected]}
#'
#' @examples
#' \dontrun{
#' fit <- brm(count ~ log_Age_c + log_Base4_c * Trt_c + (1+Trt_c|visit),
#' data = epilepsy, family = gaussian(), chains = 2)
#' ranef(fit)
#' }
#'
#' @method ranef brmsfit
#' @export
#' @export ranef
#' @importFrom nlme ranef
ranef.brmsfit <- function(object, summary = TRUE, robust = FALSE,
probs = c(0.025, 0.975), ...) {
contains_samples(object)
object <- restructure(object)
if (!nrow(object$ranef)) {
stop2("The model does not contain group-level effects.")
}
pars <- parnames(object)
ranef <- object$ranef
groups <- unique(ranef$group)
out <- named_list(groups)
for (g in groups) {
r <- subset2(ranef, group = g)
coefs <- paste0(usc(combine_prefix(r), "suffix"), r$coef)
levels <- attr(ranef, "levels")[[g]]
rpars <- pars[grepl(paste0("^r_", g, "(__.+\\[|\\[)"), pars)]
out[[g]] <- as.matrix(object, rpars, exact_match = TRUE)
dim(out[[g]]) <- c(nrow(out[[g]]), length(levels), length(coefs))
dimnames(out[[g]])[2:3] <- list(levels, coefs)
if (summary) {
out[[g]] <- posterior_summary(out[[g]], probs, robust)
}
}
out
}
#' Extract Model Coefficients
#'
#' Extract model coefficients, which are the sum of population-level
#' effects and corresponding group-level effects
#'
#' @param object An object of class \code{brmsfit}
#' @inheritParams ranef.brmsfit
#'
#' @return If \code{old} is \code{FALSE}: A list of arrays
#' (one per grouping factor). If \code{summary} is \code{TRUE},
#' names of the first dimension are the factor levels and names
#' of the third dimension are the group-level effects.
#' If \code{summary} is \code{FALSE}, names of the second dimension
#' are the factor levels and names of the third dimension are the
#' group-level effects.
#'
#' @author Paul-Christian Buerkner \email{[email protected]}
#'
#' @examples
#' \dontrun{
#' fit <- brm(count ~ log_Age_c + log_Base4_c * Trt_c + (1+Trt_c|visit),
#' data = epilepsy, family = gaussian(), chains = 2)
#' ## extract population and group-level coefficients separately
#' fixef(fit)
#' ranef(fit)
#' ## extract combined coefficients
#' coef(fit)
#' }
#'
#' @export
coef.brmsfit <- function(object, summary = TRUE, robust = FALSE,
probs = c(0.025, 0.975), ...) {
contains_samples(object)
object <- restructure(object)
if (!nrow(object$ranef)) {
stop2("No group-level effects detected. Call method ",
"'fixef' to access population-level effects.")
}
fixef <- fixef(object, summary = FALSE, ...)
coef <- ranef(object, summary = FALSE, ...)
# add missing coefficients to fixef
all_ranef_names <- unique(ulapply(coef, function(x) dimnames(x)[[3]]))
fixef_names <- colnames(fixef)
fixef_no_digits <- get_matches("^[^\\[]+", fixef_names)
miss_fixef <- setdiff(all_ranef_names, fixef_names)
miss_fixef_no_digits <- get_matches("^[^\\[]+", miss_fixef)
new_fixef <- named_list(miss_fixef)
for (k in seq_along(miss_fixef)) {
# digits occur in ordinal models with category specific effects
match_fixef <- match(miss_fixef_no_digits[k], fixef_names)
if (!is.na(match_fixef)) {
new_fixef[[k]] <- fixef[, match_fixef]
} else if (!miss_fixef[k] %in% fixef_no_digits) {
new_fixef[[k]] <- 0
}
}
rm_fixef <- fixef_names %in% miss_fixef_no_digits
fixef <- fixef[, !rm_fixef, drop = FALSE]
fixef <- do.call(cbind, c(list(fixef), rmNULL(new_fixef)))
for (g in names(coef)) {
# add missing coefficients to ranef
ranef_names <- dimnames(coef[[g]])[[3]]
ranef_no_digits <- get_matches("^[^\\[]+", ranef_names)
miss_ranef <- setdiff(fixef_names, ranef_names)
miss_ranef_no_digits <- get_matches("^[^\\[]+", miss_ranef)
new_ranef <- named_list(miss_ranef)
for (k in seq_along(miss_ranef)) {
# digits occur in ordinal models with category specific effects
match_ranef <- match(miss_ranef_no_digits[k], ranef_names)
if (!is.na(match_ranef)) {
new_ranef[[k]] <- coef[[g]][, , match_ranef]
} else if (!miss_ranef[k] %in% ranef_no_digits) {
new_ranef[[k]] <- array(0, dim = dim(coef[[g]])[1:2])
}
}
rm_ranef <- ranef_names %in% miss_ranef_no_digits
coef[[g]] <- coef[[g]][, , !rm_ranef, drop = FALSE]
coef[[g]] <- do.call(abind, c(list(coef[[g]]), rmNULL(new_ranef)))
for (nm in dimnames(coef[[g]])[[3]]) {
is_ord_intercept <- grepl("(^|_)Intercept\\[[[:digit:]]+\\]$", nm)
if (is_ord_intercept) {
# correct the sign of thresholds in ordinal models
resp <- if (is_mv(object)) get_matches("^[^_]+", nm)
family <- family(object, resp = resp)$family
if (family %in% c("cumulative", "sratio")) {
# threshold - mu
coef[[g]][, , nm] <- fixef[, nm] - coef[[g]][, , nm]
} else {
# mu - threshold
coef[[g]][, , nm] <- coef[[g]][, , nm] - fixef[, nm]
}
} else {
coef[[g]][, , nm] <- fixef[, nm] + coef[[g]][, , nm]
}
}
if (summary) {
coef[[g]] <- posterior_summary(coef[[g]], probs, robust)
}
}
coef
}
#' Extract Variance and Correlation Components
#'
#' This function calculates the estimated standard deviations,
#' correlations and covariances of the group-level terms
#' in a multilevel model of class \code{brmsfit}.
#' For linear models, the residual standard deviations,
#' correlations and covariances are also returned.
#'
#' @aliases VarCorr
#'
#' @param x An object of class \code{brmsfit}.
#' @inheritParams fixef.brmsfit
#' @param sigma Ignored (included for compatibility with
#' \code{\link[nlme:VarCorr]{VarCorr}}).
#' @param ... Currently ignored.
#'
#' @return A list of lists (one per grouping factor), each with
#' three elements: a matrix containing the standard deviations,
#' an array containing the correlation matrix, and an array
#' containing the covariance matrix with variances on the diagonal.
#'
#' @author Paul-Christian Buerkner \email{[email protected]}
#'
#' @examples
#' \dontrun{
#' fit <- brm(count ~ log_Age_c + log_Base4_c * Trt_c + (1+Trt_c|visit),
#' data = epilepsy, family = gaussian(), chains = 2)
#' VarCorr(fit)
#' }
#'
#' @method VarCorr brmsfit
#' @import abind abind
#' @importFrom nlme VarCorr
#' @export VarCorr
#' @export
VarCorr.brmsfit <- function(x, sigma = 1, summary = TRUE, robust = FALSE,
probs = c(0.025, 0.975), ...) {
contains_samples(x)
x <- restructure(x)
if (!(nrow(x$ranef) || any(grepl("^sigma($|_)", parnames(x))))) {
stop2("The model does not contain covariance matrices.")
}
.VarCorr <- function(y) {
# extract samples for sd, cor and cov
out <- list(sd = as.matrix(x, pars = y$sd_pars, exact_match = TRUE))
colnames(out$sd) <- y$rnames
# compute correlation and covariance matrices
found_cor_pars <- intersect(y$cor_pars, parnames(x))
if (length(found_cor_pars)) {
cor <- as.matrix(x, pars = found_cor_pars, exact_match = TRUE)
if (length(found_cor_pars) < length(y$cor_pars)) {
# some correlations are missing and will be replaced by 0
cor_all <- matrix(0, nrow = nrow(cor), ncol = length(y$cor_pars))
names(cor_all) <- y$cor_pars
for (i in seq_len(ncol(cor_all))) {
found <- match(names(cor_all)[i], colnames(cor))
if (!is.na(found)) {
cor_all[, i] <- cor[, found]
}
}
cor <- cor_all
}
out$cor <- get_cor_matrix(cor = cor)
out$cov <- get_cov_matrix(sd = out$sd, cor = cor)
dimnames(out$cor)[2:3] <- list(y$rnames, y$rnames)
dimnames(out$cov)[2:3] <- list(y$rnames, y$rnames)
if (summary) {
out$cor <- posterior_summary(out$cor, probs, robust)
out$cov <- posterior_summary(out$cov, probs, robust)
}
}
if (summary) {
out$sd <- posterior_summary(out$sd, probs, robust)
}
return(out)
}
if (nrow(x$ranef)) {
get_names <- function(group) {
# get names of group-level parameters
r <- subset2(x$ranef, group = group)
rnames <- as.vector(get_rnames(r))
cor_type <- paste0("cor_", group)
sd_pars <- paste0("sd_", group, "__", rnames)
cor_pars <- get_cornames(rnames, cor_type, brackets = FALSE)
nlist(rnames, sd_pars, cor_pars)
}
group <- unique(x$ranef$group)
tmp <- lapply(group, get_names)
names(tmp) <- group
} else {
tmp <- list()
}
# include residual variances in the output as well
bterms <- parse_bf(x$formula)
if (is.brmsterms(bterms)) {
if (simple_sigma(bterms) && !is.mixfamily(x$family)) {
tmp_resid <- list(rnames = bterms$resp, sd_pars = "sigma")
tmp <- c(tmp, residual__ = list(tmp_resid))
}
} else if (is.mvbrmsterms(bterms)) {
simple_sigma <- ulapply(bterms$terms, simple_sigma)
pred_sigma <- ulapply(bterms$terms, pred_sigma)
is_mix <- ulapply(x$family, is.mixfamily)
if (any(simple_sigma) && !any(pred_sigma) && !any(is_mix)) {
resps <- bterms$responses[simple_sigma]
sd_pars <- paste0("sigma_", resps)
if (bterms$rescor) {
cor_pars <- get_cornames(resps, type = "rescor", brackets = FALSE)
} else {
cor_pars <- character(0)
}
tmp_resid <- nlist(rnames = resps, sd_pars, cor_pars)
tmp <- c(tmp, residual__ = list(tmp_resid))
}
}
lapply(tmp, .VarCorr)
}
#' @export
model.frame.brmsfit <- function(formula, ...) {
formula$data
}
#' @rdname posterior_samples
#' @export
posterior_samples.brmsfit <- function(x, pars = NA, exact_match = FALSE,
add_chain = FALSE, subset = NULL,
as.matrix = FALSE, as.array = FALSE,
...) {
if (as.matrix && as.array) {
stop2("Cannot use 'as.matrix' and 'as.array' at the same time.")
}
if (add_chain && as.array) {
stop2("Cannot use 'add_chain' and 'as.array' at the same time.")
}
contains_samples(x)
pars <- extract_pars(pars, parnames(x), exact_match = exact_match, ...)
# get basic information on the samples
iter <- x$fit@sim$iter
warmup <- x$fit@sim$warmup
thin <- x$fit@sim$thin
chains <- x$fit@sim$chains
final_iter <- ceiling((iter - warmup) / thin)
samples_taken <- seq(warmup + 1, iter, thin)
if (length(pars)) {
if (as.matrix) {
samples <- as.matrix(x$fit, pars = pars)
} else if (as.array) {
samples <- as.array(x$fit, pars = pars)
} else {
samples <- as.data.frame(x$fit, pars = pars)
}
if (add_chain) {
# name the column 'chain' not 'chains' (#32)
samples <- cbind(samples,
chain = factor(rep(1:chains, each = final_iter)),
iter = rep(samples_taken, chains)
)
}
if (!is.null(subset)) {
if (as.array) {
samples <- samples[subset, , , drop = FALSE]
} else {
samples <- samples[subset, , drop = FALSE]
}
}
} else {
samples <- NULL
}
samples
}
#' @rdname posterior_samples
#' @export
as.data.frame.brmsfit <- function(x, row.names = NULL, optional = FALSE, ...) {
out <- posterior_samples(x, ..., as.matrix = FALSE)
data.frame(out, row.names = row.names, check.names = !optional)
}
#' @rdname posterior_samples
#' @export
as.matrix.brmsfit <- function(x, ...) {
posterior_samples(x, ..., as.matrix = TRUE)
}
#' @rdname posterior_samples
#' @export
as.array.brmsfit <- function(x, ...) {
posterior_samples(x, ..., as.array = TRUE)
}
#' Compute posterior uncertainty intervals
#'
#' Compute posterior uncertainty intervals for \code{brmsfit} objects.
#'
#' @inheritParams summary.brmsfit
#' @param pars Names of parameters for which posterior samples should be
#' returned, as given by a character vector or regular expressions.
#' By default, all posterior samples of all parameters are extracted.
#' @param ... More arguments passed to
#' \code{\link[brms:as.matrix.brmsfit]{as.matrix.brmsfit}}.
#'
#' @return A \code{matrix} with lower and upper interval bounds
#' as columns and as many rows as selected parameters.
#'
#' @examples
#' \dontrun{
#' fit <- brm(count ~ log_Age_c + log_Base4_c * Trt_c,
#' data = epilepsy, family = negbinomial())
#' posterior_interval(fit)
#' }
#'
#' @aliases posterior_interval
#' @method posterior_interval brmsfit
#' @export
#' @export posterior_interval
#' @importFrom rstantools posterior_interval
posterior_interval.brmsfit <- function(
object, pars = NA, prob = 0.95, ...
) {
ps <- as.matrix(object, pars = pars, ...)
rstantools::posterior_interval(ps, prob = prob)
}
#' @rdname posterior_summary
#' @export
posterior_summary.brmsfit <- function(x, pars = NA,
probs = c(0.025, 0.975),
robust = FALSE, ...) {
out <- as.matrix(x, pars = pars, ...)
posterior_summary(out, probs = probs, robust = robust, ...)
}
#' Extract posterior samples for use with the \pkg{coda} package
#'
#' @aliases as.mcmc
#'
#' @inheritParams posterior_samples
#' @param ... currently unused
#' @param combine_chains Indicates whether chains should be combined.
#' @param inc_warmup Indicates if the warmup samples should be included.
#' Default is \code{FALSE}. Warmup samples are used to tune the
#' parameters of the sampling algorithm and should not be analyzed.
#'
#' @return If \code{combine_chains = TRUE} an \code{mcmc} object is returned.
#' If \code{combine_chains = FALSE} an \code{mcmc.list} object is returned.
#'
#' @method as.mcmc brmsfit
#' @export
#' @export as.mcmc
#' @importFrom coda as.mcmc
as.mcmc.brmsfit <- function(x, pars = NA, exact_match = FALSE,
combine_chains = FALSE, inc_warmup = FALSE,
...) {
contains_samples(x)
pars <- extract_pars(
pars, all_pars = parnames(x),
exact_match = exact_match, ...
)
if (combine_chains) {
if (inc_warmup) {
stop2("Cannot include warmup samples when 'combine_chains' is TRUE.")
}
out <- as.matrix(x$fit, pars)
mcpar <- c(
x$fit@sim$warmup * x$fit@sim$chain + 1,
x$fit@sim$iter * x$fit@sim$chain, x$fit@sim$thin
)
attr(out, "mcpar") <- mcpar
class(out) <- "mcmc"
} else {
ps <- extract(x$fit, pars, permuted = FALSE, inc_warmup = inc_warmup)
mcpar <- c(
if (inc_warmup) 1 else x$fit@sim$warmup + 1,
x$fit@sim$iter, x$fit@sim$thin
)
out <- vector("list", length = dim(ps)[2])
for (i in seq_along(out)) {
out[[i]] <- ps[, i, ]
attr(out[[i]], "mcpar") <- mcpar
class(out[[i]]) <- "mcmc"
}
class(out) <- "mcmc.list"
}
out
}
#' Extract Priors of a Bayesian Model Fitted with \pkg{brms}
#'
#' @aliases prior_summary
#'
#' @param object A \code{brmsfit} object
#' @param all Logical; Show all parameters in the model which may have
#' priors (\code{TRUE}) or only those with proper priors (\code{FALSE})?
#' @param ... Further arguments passed to or from other methods.
#'
#' @return For \code{brmsfit} objects, an object of class \code{brmsprior}.
#'
#' @examples
#' \dontrun{
#' fit <- brm(count ~ log_Age_c + log_Base4_c * Trt_c
#' + (1|patient) + (1|obs),
#' data = epilepsy, family = poisson(),
#' prior = c(prior(student_t(5,0,10), class = b),
#' prior(cauchy(0,2), class = sd)))
#'
#' prior_summary(fit)
#' prior_summary(fit, all = FALSE)
#' print(prior_summary(fit, all = FALSE), show_df = FALSE)
#' }
#'
#' @method prior_summary brmsfit
#' @export
#' @export prior_summary
#' @importFrom rstantools prior_summary
prior_summary.brmsfit <- function(object, all = TRUE, ...) {
object <- restructure(object)
prior <- object$prior
if (!all) {
prior <- prior[nzchar(prior$prior), ]
}
prior
}
#' @rdname prior_samples
#' @export
prior_samples.brmsfit <- function(x, pars = NA, ...) {
if (!anyNA(pars) && !is.character(pars)) {
stop2("Argument 'pars' must be a character vector.")
}
par_names <- parnames(x)
prior_names <- unique(par_names[grepl("^prior_", par_names)])
if (length(prior_names)) {
samples <- posterior_samples(x, prior_names, exact_match = TRUE)
names(samples) <- sub("^prior_", "", prior_names)
if (!anyNA(pars)) {
.prior_samples <- function(par) {
# get prior samples for parameter par
matches <- lapply(paste0("^", names(samples)), regexpr, text = par)
matches <- ulapply(matches, attr, which = "match.length")
if (max(matches) == -1) {
out <- NULL
} else {
take <- match(max(matches), matches)
# order samples randomly to avoid artifical dependencies
# between parameters using the same prior samples
samples <- list(samples[sample(nsamples(x)), take])
out <- structure(samples, names = par)
}
return(out)
}
samples <- data.frame(
rmNULL(lapply(pars, .prior_samples)), check.names = FALSE
)
}
} else {
samples <- NULL
}
samples
}
#' Print a summary for a fitted model represented by a \code{brmsfit} object
#'
#' @aliases print.brmssummary
#'
#' @param x An object of class \code{brmsfit}
#' @param digits The number of significant digits for printing out the summary;
#' defaults to 2. The effective sample size is always rounded to integers.
#' @param ... Additional arguments that would be passed
#' to method \code{summary} of \code{brmsfit}.
#'
#' @author Paul-Christian Buerkner \email{[email protected]}
#'
#' @export
print.brmsfit <- function(x, digits = 2, ...) {
print(summary(x, ...), digits = digits, ...)
}
#' Create a summary of a fitted model represented by a \code{brmsfit} object
#'
#' @param object An object of class \code{brmsfit}
#' @param priors Logical; Indicating if priors should be included
#' in the summary. Default is \code{FALSE}.
#' @param prob A value between 0 and 1 indicating the desired probability
#' to be covered by the uncertainty intervals. The default is 0.95.
#' @param mc_se Logical; Indicating if the uncertainty caused by the
#' MCMC sampling should be shown in the summary. Defaults to \code{FALSE}.
#' @param use_cache Logical; Indicating if summary results should
#' be cached for future use by \pkg{rstan}. Defaults to \code{TRUE}.
#' For models fitted with earlier versions of \pkg{brms},
#' it may be necessary to set \code{use_cache} to
#' \code{FALSE} in order to get the \code{summary}
#' method working correctly.
#' @param ... Other potential arguments
#'
#' @author Paul-Christian Buerkner \email{[email protected]}
#'
#' @method summary brmsfit
#' @export
summary.brmsfit <- function(object, priors = FALSE, prob = 0.95,
mc_se = FALSE, use_cache = TRUE, ...) {
object <- restructure(object, rstr_summary = use_cache)
bterms <- parse_bf(object$formula)
out <- list(
formula = object$formula,
data.name = object$data.name,
group = unique(object$ranef$group),
nobs = nobs(object),
ngrps = ngrps(object),
autocor = object$autocor,
prior = empty_brmsprior(),
algorithm = algorithm(object),
waic = NA, loo = NA, R2 = NA
)
class(out) <- "brmssummary"
if (!length(object$fit@sim)) {
# the model does not contain posterior samples
return(out)
}
out$chains <- object$fit@sim$chains
out$iter <- object$fit@sim$iter
out$warmup <- object$fit@sim$warmup
out$thin <- object$fit@sim$thin
stan_args <- object$fit@stan_args[[1]]
out$sampler <- paste0(stan_args$method, "(", stan_args$algorithm, ")")
if (length(prob) != 1L || prob < 0 || prob > 1) {
stop2("'prob' must be a single numeric value in [0, 1].")
}
if (priors) {
out$prior <- prior_summary(object, all = FALSE)
}
pars <- parnames(object)
meta_pars <- object$fit@sim$pars_oi
meta_pars <- meta_pars[!grepl("^(r|s|zgp|Xme|prior|lp)_", meta_pars)]
probs <- c((1 - prob) / 2, 1 - (1 - prob) / 2)
fit_summary <- summary(
object$fit, pars = meta_pars,
probs = probs, use_cache = use_cache
)
fit_summary <- fit_summary$summary
if (!mc_se) {
fit_summary <- fit_summary[, -2, drop = FALSE]
}
CIs <- paste0(c("l-", "u-"), prob * 100, "% CI")
colnames(fit_summary) <- c(
"Estimate", if (mc_se) "MC.Error",
"Est.Error", CIs, "Eff.Sample", "Rhat"
)
if (algorithm(object) == "sampling") {
Rhats <- fit_summary[, "Rhat"]
if (any(Rhats > 1.1, na.rm = TRUE)) {
warning2(
"The model has not converged (some Rhats are > 1.1). ",
"Do not analyse the results! \nWe recommend running ",
"more iterations and/or setting stronger priors."
)
}
# nuts_params may not work for some models fitted with brms < 1.0.0
div_trans <- try(
sum(nuts_params(object, pars = "divergent__")$Value), silent = TRUE
)
if (is(div_trans, "try-error")) {
warning2("Could not extract information about divergent transitions.")
} else {
adapt_delta <- control_params(object)$adapt_delta
if (div_trans > 0) {
warning2(
"There were ", div_trans, " divergent transitions after warmup. ",
"Increasing adapt_delta above ", adapt_delta, " may help.\nSee ",
"http://mc-stan.org/misc/warnings.html#divergent-transitions-after-warmup"
)
}
}
}
# summary of population-level effects
fe_pars <- pars[grepl(fixef_pars(), pars)]
out$fixed <- fit_summary[fe_pars, , drop = FALSE]
rownames(out$fixed) <- gsub(fixef_pars(), "", fe_pars)
# summary of family specific parameters
spec_pars <- c(dpars(), "delta", "theta", "rescor")
spec_pars <- paste0(spec_pars, collapse = "|")
spec_pars <- paste0("^(", spec_pars, ")($|_|[[:digit:]])")
spec_pars <- pars[grepl(spec_pars, pars)]
out$spec_pars <- fit_summary[spec_pars, , drop = FALSE]
is_rescor <- grepl("^rescor_", spec_pars)
if (any(is_rescor)) {
rescor_pars <- spec_pars[is_rescor]
rescor_names <- sub("__", ",", sub("__", "(", rescor_pars))
spec_pars[is_rescor] <- paste0(rescor_names, ")")
}
rownames(out$spec_pars) <- spec_pars
# summary of autocorrelation effects
cor_pars <- pars[grepl(regex_cor_pars(), pars)]
out$cor_pars <- fit_summary[cor_pars, , drop = FALSE]
rownames(out$cor_pars) <- cor_pars
# summary of group-level effects
for (g in out$group) {
gregex <- escape_dot(g)
sd_prefix <- paste0("^sd_", gregex, "__")
sd_pars <- pars[grepl(sd_prefix, pars)]
cor_prefix <- paste0("^cor_", gregex, "__")
cor_pars <- pars[grepl(cor_prefix, pars)]
df_prefix <- paste0("^df_", gregex, "$")
df_pars <- pars[grepl(df_prefix, pars)]
gpars <- c(df_pars, sd_pars, cor_pars)
out$random[[g]] <- fit_summary[gpars, , drop = FALSE]
if (has_rows(out$random[[g]])) {
sd_names <- sub(sd_prefix, "sd(", sd_pars)
cor_names <- sub(cor_prefix, "cor(", cor_pars)
cor_names <- sub("__", ",", cor_names)
df_names <- sub(df_prefix, "df", df_pars)
gnames <- c(df_names, paste0(c(sd_names, cor_names), ")"))
rownames(out$random[[g]]) <- gnames
}
}
# summary of smooths
sm_pars <- pars[grepl("^sds_", pars)]
if (length(sm_pars)) {
out$splines <- fit_summary[sm_pars, , drop = FALSE]
rownames(out$splines) <- paste0(gsub("^sds_", "sds(", sm_pars), ")")
}
# summary of monotonic parameters
mo_pars <- pars[grepl("^simo_", pars)]
if (length(mo_pars)) {
out$mo <- fit_summary[mo_pars, , drop = FALSE]
rownames(out$mo) <- gsub("^simo_", "", mo_pars)
}
# summary of gaussian processes
gp_pars <- pars[grepl("^(sdgp|lscale)_", pars)]
if (length(gp_pars)) {
out$gp <- fit_summary[gp_pars, , drop = FALSE]
rownames(out$gp) <- gsub("^sdgp_", "sdgp(", rownames(out$gp))
rownames(out$gp) <- gsub("^lscale_", "lscale(", rownames(out$gp))
rownames(out$gp) <- paste0(rownames(out$gp), ")")
}
out
}
#' @rdname nsamples
#' @export
nsamples.brmsfit <- function(x, subset = NULL,
incl_warmup = FALSE, ...) {
if (!is(x$fit, "stanfit") || !length(x$fit@sim)) {
out <- 0
} else {
ntsamples <- x$fit@sim$n_save[1]
if (!incl_warmup) {
ntsamples <- ntsamples - x$fit@sim$warmup2[1]
}
ntsamples <- ntsamples * x$fit@sim$chains
if (length(subset)) {
out <- length(subset)
if (out > ntsamples || max(subset) > ntsamples) {
stop2("Argument 'subset' is invalid.")
}
} else {
out <- ntsamples
}
}
out
}
#' @export
nobs.brmsfit <- function(object, ...) {
nrow(model.frame(object))
}
#' @rdname ngrps
#' @export
ngrps.brmsfit <- function(object, ...) {
object <- restructure(object)
if (nrow(object$ranef)) {
out <- lapply(attr(object$ranef, "levels"), length)
} else {
out <- NULL
}
out
}
#' @export
formula.brmsfit <- function(x, ...) {
x$formula
}
#' @export
getCall.brmsfit <- function(x, ...) {
x$formula
}
#' @export
family.brmsfit <- function(object, resp = NULL, ...) {
if (!is.null(resp)) {
stopifnot(is_mv(object))
resp <- as_one_character(resp)
resp <- validate_resp(resp, object$formula$responses)
family <- object$formula$forms[[resp]]$family
} else {
family <- get_element(object$formula, "family")
if (is.null(family)) {
family <- object$family
}
}
family
}
#' @export
autocor.brmsfit <- function(object, resp = NULL, ...) {
if (!is.null(resp)) {
stopifnot(is_mv(object))
resp <- as_one_character(resp)
resp <- validate_resp(resp, object$formula$responses)
autocor <- object$formula$forms[[resp]]$autocor
} else {
autocor <- get_element(object$formula, "autocor")
if (is.null(autocor)) {
autocor <- object$autocor
}
}
autocor
}
#' @rdname stancode
#' @export
stancode.brmsfit <- function(object, version = TRUE, ...) {
out <- object$model
if (!version) {
out <- sub("^[^\n]+[[:digit:]]\\.[^\n]+\n", "", out)
}
out
}
#' @rdname standata
#' @export
standata.brmsfit <- function(object, newdata = NULL, re_formula = NULL,
incl_autocor = TRUE, new_objects = list(),
internal = FALSE, control = list(), ...) {
dots <- list(...)
object <- restructure(object)
if (!incl_autocor) {
object <- remove_autocor(object)
}
if (internal) {
control[c("not4stan", "save_order")] <- TRUE
}
new_formula <- update_re_terms(object$formula, re_formula)
is_original_data <- isTRUE(attr(newdata, "original"))
if (is.null(newdata)) {
newdata <- object$data
} else if (!is_original_data) {
if (!isTRUE(attr(newdata, "valid"))) {
newdata <- validate_newdata(
newdata, object, re_formula = re_formula, ...
)
}
object <- add_new_objects(object, newdata, new_objects)
control$new <- TRUE
# ensure correct handling of functions like poly or scale
bterms <- parse_bf(new_formula)
old_terms <- attr(object$data, "terms")
terms_attr <- c("variables", "predvars")
control$terms_attr <- attributes(old_terms)[terms_attr]
control$old_sdata <- extract_old_standata(bterms, object$data)
control$old_levels <- get_levels(
tidy_ranef(bterms, object$data),
tidy_meef(bterms, object$data)
)
}
sample_prior <- attr(object$prior, "sample_prior")
sample_prior <- ifelse(is.null(sample_prior), "no", sample_prior)
args <- list(
formula = new_formula, data = newdata,
prior = object$prior, cov_ranef = object$cov_ranef,
sample_prior = sample_prior, stanvars = object$stanvars,
knots = attr(object$data, "knots"), control = control
)
do.call(make_standata, c(args, dots))
}
#' Interface to \pkg{shinystan}
#'
#' Provide an interface to \pkg{shinystan} for models fitted with \pkg{brms}
#'
#' @aliases launch_shinystan
#'
#' @param object A fitted model object typically of class \code{brmsfit}.
#' @param rstudio Only relevant for RStudio users.
#' The default (\code{rstudio=FALSE}) is to launch the app
#' in the default web browser rather than RStudio's pop-up Viewer.
#' Users can change the default to \code{TRUE}
#' by setting the global option \cr \code{options(shinystan.rstudio = TRUE)}.
#' @param ... Optional arguments to pass to \code{\link[shiny:runApp]{runApp}}
#'
#' @return An S4 shinystan object
#'
#' @examples
#' \dontrun{
#' fit <- brm(rating ~ treat + period + carry + (1|subject),
#' data = inhaler, family = "gaussian")
#' launch_shinystan(fit)
#' }
#'
#' @seealso \code{\link[shinystan:launch_shinystan]{launch_shinystan}}
#'
#' @method launch_shinystan brmsfit
#' @importFrom shinystan launch_shinystan
#' @export launch_shinystan
#' @export
launch_shinystan.brmsfit <- function(
object, rstudio = getOption("shinystan.rstudio"), ...
) {
contains_samples(object)
if (object$algorithm != "sampling") {
return(shinystan::launch_shinystan(object$fit, rstudio = rstudio, ...))
}
draws <- as.array(object)
sampler_params <- rstan::get_sampler_params(object$fit, inc_warmup = FALSE)
control <- object$fit@stan_args[[1]]$control
if (is.null(control)) {
max_td <- 11
} else {
max_td <- control$max_treedepth
if (is.null(max_td)) {
max_td <- 11
}
}
sso <- shinystan::as.shinystan(
X = draws,
model_name = object$fit@model_name,
warmup = 0,
sampler_params = sampler_params,
max_treedepth = max_td,
algorithm = "NUTS"
)
shinystan::launch_shinystan(sso, rstudio = rstudio, ...)
}