-
-
Notifications
You must be signed in to change notification settings - Fork 176
/
priors.R
2064 lines (2001 loc) · 76.5 KB
/
priors.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
#' Prior Definitions for \pkg{brms} Models
#'
#' Define priors for specific parameters or classes of parameters.
#'
#' @aliases brmsprior brmsprior-class
#'
#' @param prior A character string defining a distribution in \pkg{Stan} language
#' @param class The parameter class. Defaults to \code{"b"}
#' (i.e. population-level effects).
#' See 'Details' for other valid parameter classes.
#' @param coef Name of the coefficient within the parameter class.
#' @param group Grouping factor for group-level parameters.
#' @param resp Name of the response variable.
#' Only used in multivariate models.
#' @param dpar Name of a distributional parameter.
#' Only used in distributional models.
#' @param nlpar Name of a non-linear parameter.
#' Only used in non-linear models.
#' @param lb Lower bound for parameter restriction. Currently only allowed
#' for classes \code{"b"}. Defaults to \code{NULL}, that is no restriction.
#' @param ub Upper bound for parameter restriction. Currently only allowed
#' for classes \code{"b"}. Defaults to \code{NULL}, that is no restriction.
#' @param check Logical; Indicates whether priors
#' should be checked for validity (as far as possible).
#' Defaults to \code{TRUE}. If \code{FALSE}, \code{prior} is passed
#' to the Stan code as is, and all other arguments are ignored.
#' @param ... Arguments passed to \code{set_prior}.
#'
#' @return An object of class \code{brmsprior} to be used in the \code{prior}
#' argument of \code{\link{brm}}.
#'
#' @details
#' \code{set_prior} is used to define prior distributions for parameters
#' in \pkg{brms} models. The functions \code{prior}, \code{prior_}, and
#' \code{prior_string} are aliases of \code{set_prior} each allowing
#' for a different kind of argument specification.
#' \code{prior} allows specifying arguments as expression without
#' quotation marks using non-standard evaluation.
#' \code{prior_} allows specifying arguments as one-sided formulas
#' or wrapped in \code{quote}.
#' \code{prior_string} allows specifying arguments as strings just
#' as \code{set_prior} itself.
#'
#' Below, we explain its usage and list some common
#' prior distributions for parameters.
#' A complete overview on possible prior distributions is given
#' in the Stan Reference Manual available at \url{https://mc-stan.org/}.
#'
#' To combine multiple priors, use \code{c(...)} or the \code{+} operator
#' (see 'Examples'). \pkg{brms} does not check if the priors are written
#' in correct \pkg{Stan} language. Instead, \pkg{Stan} will check their
#' syntactical correctness when the model is parsed to \code{C++} and
#' returns an error if they are not.
#' This, however, does not imply that priors are always meaningful if they are
#' accepted by \pkg{Stan}. Although \pkg{brms} trys to find common problems
#' (e.g., setting bounded priors on unbounded parameters), there is no guarantee
#' that the defined priors are reasonable for the model.
#' Below, we list the types of parameters in \pkg{brms} models,
#' for which the user can specify prior distributions.
#'
#' 1. Population-level ('fixed') effects
#'
#' Every Population-level effect has its own regression parameter
# These parameters are internally named as \code{b_<coef>}, where \code{<coef>}
#' represents the name of the corresponding population-level effect.
#' Suppose, for instance, that \code{y} is predicted by \code{x1} and \code{x2}
#' (i.e., \code{y ~ x1 + x2} in formula syntax).
#' Then, \code{x1} and \code{x2} have regression parameters
#' \code{b_x1} and \code{b_x2} respectively.
#' The default prior for population-level effects (including monotonic and
#' category specific effects) is an improper flat prior over the reals.
#' Other common options are normal priors or student-t priors.
#' If we want to have a normal prior with mean 0 and
#' standard deviation 5 for \code{x1}, and a unit student-t prior with 10
#' degrees of freedom for \code{x2}, we can specify this via
#' \code{set_prior("normal(0,5)", class = "b", coef = "x1")} and \cr
#' \code{set_prior("student_t(10, 0, 1)", class = "b", coef = "x2")}.
#' To put the same prior on all population-level effects at once,
#' we may write as a shortcut \code{set_prior("<prior>", class = "b")}.
#' This also leads to faster sampling, because priors can be vectorized in this case.
#' Both ways of defining priors can be combined using for instance
#' \code{set_prior("normal(0, 2)", class = "b")} and \cr
#' \code{set_prior("normal(0, 10)", class = "b", coef = "x1")}
#' at the same time. This will set a \code{normal(0, 10)} prior on
#' the effect of \code{x1} and a \code{normal(0, 2)} prior
#' on all other population-level effects.
#' However, this will break vectorization and
#' may slow down the sampling procedure a bit.
#'
#' In case of the default intercept parameterization
#' (discussed in the 'Details' section of \code{\link{brmsformula}}),
#' general priors on class \code{"b"} will \emph{not} affect
#' the intercept. Instead, the intercept has its own parameter class
#' named \code{"Intercept"} and priors can thus be
#' specified via \code{set_prior("<prior>", class = "Intercept")}.
#' Setting a prior on the intercept will not break vectorization
#' of the other population-level effects.
#' Note that technically, this prior is set on an intercept that
#' results when internally centering all population-level predictors
#' around zero to improve sampling efficiency. On this centered
#' intercept, specifying a prior is actually much easier and
#' intuitive than on the original intercept, since the former
#' represents the expected response value when all predictors
#' are at their means. To treat the intercept as an ordinary
#' population-level effect and avoid the centering parameterization,
#' use \code{0 + Intercept} on the right-hand side of the model formula.
#'
#' A special shrinkage prior to be applied on population-level effects is the
#' (regularized) horseshoe prior and related priors. See
#' \code{\link{horseshoe}} for details. Another shrinkage prior is the
#' so-called lasso prior. See \code{\link{lasso}} for details.
#'
#' In non-linear models, population-level effects are defined separately
#' for each non-linear parameter. Accordingly, it is necessary to specify
#' the non-linear parameter in \code{set_prior} so that priors
#' we can be assigned correctly.
#' If, for instance, \code{alpha} is the parameter and \code{x} the predictor
#' for which we want to define the prior, we can write
#' \code{set_prior("<prior>", coef = "x", nlpar = "alpha")}.
#' As a shortcut we can use \code{set_prior("<prior>", nlpar = "alpha")}
#' to set the same prior on all population-level effects of \code{alpha} at once.
#'
#' If desired, population-level effects can be restricted to fall only
#' within a certain interval using the \code{lb} and \code{ub} arguments
#' of \code{set_prior}. This is often required when defining priors
#' that are not defined everywhere on the real line, such as uniform
#' or gamma priors. When defining a \code{uniform(2,4)} prior,
#' you should write \code{set_prior("uniform(2,4)", lb = 2, ub = 4)}.
#' When using a prior that is defined on the positive reals only
#' (such as a gamma prior) set \code{lb = 0}.
#' In most situations, it is not useful to restrict population-level
#' parameters through bounded priors
#' (non-linear models are an important exception),
#' but if you really want to this is the way to go.
#'
#' 2. Standard deviations of group-level ('random') effects
#'
#' Each group-level effect of each grouping factor has a standard deviation named
#' \code{sd_<group>_<coef>}. Consider, for instance, the formula
#' \code{y ~ x1 + x2 + (1 + x1 | g)}.
#' We see that the intercept as well as \code{x1} are group-level effects
#' nested in the grouping factor \code{g}.
#' The corresponding standard deviation parameters are named as
#' \code{sd_g_Intercept} and \code{sd_g_x1} respectively.
#' These parameters are restricted to be non-negative and, by default,
#' have a half student-t prior with 3 degrees of freedom and a
#' scale parameter that depends on the standard deviation of the response
#' after applying the link function. Minimally, the scale parameter is 2.5.
#' This prior is used (a) to be only weakly informative in order to influence
#' results as few as possible, while (b) providing at least some regularization
#' to considerably improve convergence and sampling efficiency.
#' To define a prior distribution only for standard deviations
#' of a specific grouping factor,
#' use \cr \code{set_prior("<prior>", class = "sd", group = "<group>")}.
#' To define a prior distribution only for a specific standard deviation
#' of a specific grouping factor, you may write \cr
#' \code{set_prior("<prior>", class = "sd", group = "<group>", coef = "<coef>")}.
#' Recommendations on useful prior distributions for
#' standard deviations are given in Gelman (2006), but note that he
#' is no longer recommending uniform priors, anymore. \cr
#'
#' When defining priors on group-level parameters in non-linear models,
#' please make sure to specify the corresponding non-linear parameter
#' through the \code{nlpar} argument in the same way as
#' for population-level effects.
#'
#' 3. Correlations of group-level ('random') effects
#'
#' If there is more than one group-level effect per grouping factor,
#' the correlations between those effects have to be estimated.
#' The prior \code{lkj_corr_cholesky(eta)} or in short
#' \code{lkj(eta)} with \code{eta > 0}
#' is essentially the only prior for (Cholesky factors) of correlation matrices.
#' If \code{eta = 1} (the default) all correlations matrices
#' are equally likely a priori. If \code{eta > 1}, extreme correlations
#' become less likely, whereas \code{0 < eta < 1} results in
#' higher probabilities for extreme correlations.
#' Correlation matrix parameters in \code{brms} models are named as
#' \code{cor_<group>}, (e.g., \code{cor_g} if \code{g} is the grouping factor).
#' To set the same prior on every correlation matrix,
#' use for instance \code{set_prior("lkj(2)", class = "cor")}.
#' Internally, the priors are transformed to be put on the Cholesky factors
#' of the correlation matrices to improve efficiency and numerical stability.
#' The corresponding parameter class of the Cholesky factors is \code{L},
#' but it is not recommended to specify priors for this parameter class directly.
#'
#' 4. Splines
#'
#' Splines are implemented in \pkg{brms} using the 'random effects'
#' formulation as explained in \code{\link[mgcv:gamm]{gamm}}).
#' Thus, each spline has its corresponding standard deviations
#' modeling the variability within this term. In \pkg{brms}, this
#' parameter class is called \code{sds} and priors can
#' be specified via \code{set_prior("<prior>", class = "sds",
#' coef = "<term label>")}. The default prior is the same as
#' for standard deviations of group-level effects.
#'
#' 5. Gaussian processes
#'
#' Gaussian processes as currently implemented in \pkg{brms} have
#' two parameters, the standard deviation parameter \code{sdgp},
#' and characteristic length-scale parameter \code{lscale}
#' (see \code{\link{gp}} for more details). The default prior
#' of \code{sdgp} is the same as for standard deviations of
#' group-level effects. The default prior of \code{lscale}
#' is an informative inverse-gamma prior specifically tuned
#' to the covariates of the Gaussian process (for more details see
#' \url{https://betanalpha.github.io/assets/case_studies/gp_part3/part3.html}).
#' This tuned prior may be overly informative in some cases, so please
#' consider other priors as well to make sure inference is
#' robust to the prior specification. If tuning fails, a half-normal prior
#' is used instead.
#'
#' 6. Autocorrelation parameters
#'
#' The autocorrelation parameters currently implemented are named
#' \code{ar} (autoregression), \code{ma} (moving average),
#' \code{arr} (autoregression of the response), \code{car}
#' (spatial conditional autoregression), as well as \code{lagsar}
#' and \code{errorsar} (Spatial simultaneous autoregression).
#'
#' Priors can be defined by \code{set_prior("<prior>", class = "ar")}
#' for \code{ar} and similar for other autocorrelation parameters.
#' By default, \code{ar} and \code{ma} are bounded between \code{-1}
#' and \code{1}, \code{car}, \code{lagsar}, and \code{errorsar} are
#' bounded between \code{0}, and \code{1}, and \code{arr} is unbounded
#' (you may change this by using the arguments \code{lb} and \code{ub}).
#' The default prior is flat over the definition area.
#'
#' 7. Distance parameters of monotonic effects
#'
#' As explained in the details section of \code{\link{brm}},
#' monotonic effects make use of a special parameter vector to
#' estimate the 'normalized distances' between consecutive predictor
#' categories. This is realized in \pkg{Stan} using the \code{simplex}
#' parameter type. This class is named \code{"simo"} (short for
#' simplex monotonic) in \pkg{brms}.
#' The only valid prior for simplex parameters is the
#' dirichlet prior, which accepts a vector of length \code{K - 1}
#' (K = number of predictor categories) as input defining the
#' 'concentration' of the distribution. Explaining the dirichlet prior
#' is beyond the scope of this documentation, but we want to describe
#' how to define this prior syntactically correct.
#' If a predictor \code{x} with \code{K} categories is modeled as monotonic,
#' we can define a prior on its corresponding simplex via \cr
#' \code{prior(dirichlet(<vector>), class = simo, coef = mox1)}.
#' The \code{1} in the end of \code{coef} indicates that this is the first
#' simplex in this term. If interactions between multiple monotonic
#' variables are modeled, multiple simplexes per term are required.
#' For \code{<vector>}, we can put in any \code{R} expression
#' defining a vector of length \code{K - 1}. The default is a uniform
#' prior (i.e. \code{<vector> = rep(1, K-1)}) over all simplexes
#' of the respective dimension.
#'
#' 8. Parameters for specific families
#'
#' Some families need additional parameters to be estimated.
#' Families \code{gaussian}, \code{student}, \code{skew_normal},
#' \code{lognormal}, and \code{gen_extreme_value} need the parameter
#' \code{sigma} to account for the residual standard deviation.
#' By default, \code{sigma} has a half student-t prior that scales
#' in the same way as the group-level standard deviations.
#' Further, family \code{student} needs the parameter
#' \code{nu} representing the degrees of freedom of students-t distribution.
#' By default, \code{nu} has prior \code{gamma(2, 0.1)}
#' and a fixed lower bound of \code{1}.
#' Families \code{gamma}, \code{weibull}, \code{inverse.gaussian}, and
#' \code{negbinomial} need a \code{shape} parameter that has a
#' \code{gamma(0.01, 0.01)} prior by default.
#' For families \code{cumulative}, \code{cratio}, \code{sratio},
#' and \code{acat}, and only if \code{threshold = "equidistant"},
#' the parameter \code{delta} is used to model the distance between
#' two adjacent thresholds.
#' By default, \code{delta} has an improper flat prior over the reals.
#' The \code{von_mises} family needs the parameter \code{kappa}, representing
#' the concentration parameter. By default, \code{kappa} has prior
#' \code{gamma(2, 0.01)}. \cr
#' Every family specific parameter has its own prior class, so that
#' \code{set_prior("<prior>", class = "<parameter>")} is the right way to go.
#' All of these priors are chosen to be weakly informative,
#' having only minimal influence on the estimations,
#' while improving convergence and sampling efficiency.
#'
#' Fixing parameters to constants is possible by using the \code{constant}
#' function, for example, \code{constant(1)} to fix a parameter to 1.
#' Broadcasting to vectors and matrices is done automatically.
#'
#' Often, it may not be immediately clear, which parameters are present in the
#' model. To get a full list of parameters and parameter classes for which
#' priors can be specified (depending on the model) use function
#' \code{\link{get_prior}}.
#'
#' @seealso \code{\link{get_prior}}
#'
#' @references
#' Gelman A. (2006). Prior distributions for variance parameters in hierarchical models.
#' Bayesian analysis, 1(3), 515 -- 534.
#'
#' @examples
#' ## use alias functions
#' (prior1 <- prior(cauchy(0, 1), class = sd))
#' (prior2 <- prior_(~cauchy(0, 1), class = ~sd))
#' (prior3 <- prior_string("cauchy(0, 1)", class = "sd"))
#' identical(prior1, prior2)
#' identical(prior1, prior3)
#'
#' # check which parameters can have priors
#' get_prior(rating ~ treat + period + carry + (1|subject),
#' data = inhaler, family = cumulative())
#'
#' # define some priors
#' bprior <- c(prior_string("normal(0,10)", class = "b"),
#' prior(normal(1,2), class = b, coef = treat),
#' prior_(~cauchy(0,2), class = ~sd,
#' group = ~subject, coef = ~Intercept))
#'
#' # verify that the priors indeed found their way into Stan's model code
#' make_stancode(rating ~ treat + period + carry + (1|subject),
#' data = inhaler, family = cumulative(),
#' prior = bprior)
#'
#' # use the horseshoe prior to model sparsity in regression coefficients
#' make_stancode(count ~ zAge + zBase * Trt,
#' data = epilepsy, family = poisson(),
#' prior = set_prior("horseshoe(3)"))
#'
#' # fix certain priors to constants
#' bprior <- prior(constant(1), class = "b") +
#' prior(constant(2), class = "b", coef = "zBase") +
#' prior(constant(0.5), class = "sd")
#' make_stancode(count ~ zAge + zBase + (1 | patient),
#' data = epilepsy, prior = bprior)
#'
#' # pass priors to Stan without checking
#' prior <- prior_string("target += normal_lpdf(b[1] | 0, 1)", check = FALSE)
#' make_stancode(count ~ Trt, data = epilepsy, prior = prior)
#'
#' @export
set_prior <- function(prior, class = "b", coef = "", group = "",
resp = "", dpar = "", nlpar = "",
lb = NA, ub = NA, check = TRUE) {
input <- nlist(prior, class, coef, group, resp, dpar, nlpar, lb, ub, check)
input <- try(as.data.frame(input), silent = TRUE)
if (is(input, "try-error")) {
stop2("Processing arguments of 'set_prior' has failed:\n", input)
}
out <- vector("list", nrow(input))
for (i in seq_along(out)) {
out[[i]] <- do_call(.set_prior, input[i, ])
}
Reduce("+", out)
}
# validate arguments passed to 'set_prior'
.set_prior <- function(prior, class, coef, group, resp,
dpar, nlpar, lb, ub, check) {
prior <- as_one_character(prior)
class <- as_one_character(class)
group <- as_one_character(group)
coef <- as_one_character(coef)
resp <- as_one_character(resp)
dpar <- as_one_character(dpar)
nlpar <- as_one_character(nlpar)
lb <- as_one_character(lb, allow_na = TRUE)
ub <- as_one_character(ub, allow_na = TRUE)
check <- as_one_logical(check)
# validate boundaries
bound <- ""
if (class %in% c("ar", "ma") && (!is.na(lb) || !is.na(ub))) {
# changed in version 2.9.5
lb <- ub <- NA
warning2(
"Changing the boundaries of autocorrelation parameters ",
"is deprecated and will be ignored."
)
}
if (!is.na(lb) || !is.na(ub)) {
# TODO: extend the boundary interface to more parameter classes
boundary_classes <- c("b")
if (!class %in% boundary_classes) {
stop2("Currently boundaries are only allowed for classe(s) ",
collapse_comma(boundary_classes), "."
)
}
if (nzchar(coef)) {
stop2("Argument 'coef' may not be specified when using boundaries.")
}
# don't put spaces in boundary declarations
lb <- if (!is.na(lb)) paste0("lower=", lb)
ub <- if (!is.na(ub)) paste0("upper=", ub)
if (!is.null(lb) || !is.null(ub)) {
bound <- paste0("<", paste(c(lb, ub), collapse = ","), ">")
}
}
if (!check) {
# prior will be added to the log-posterior as is
class <- coef <- group <- resp <- dpar <- nlpar <- bound <- ""
}
source <- "user"
out <- nlist(prior, source, class, coef, group, resp, dpar, nlpar, bound)
do_call(brmsprior, out)
}
#' @describeIn set_prior Alias of \code{set_prior} allowing to
#' specify arguments as expressions without quotation marks.
#' @export
prior <- function(prior, ...) {
call <- as.list(match.call()[-1])
seval <- rmNULL(call[prior_seval_args()])
call[prior_seval_args()] <- NULL
call <- lapply(call, deparse_no_string)
do_call(set_prior, c(call, seval))
}
#' @describeIn set_prior Alias of \code{set_prior} allowing to specify
#' arguments as as one-sided formulas or wrapped in \code{quote}.
#' @export
prior_ <- function(prior, ...) {
call <- nlist(prior, ...)
seval <- rmNULL(call[prior_seval_args()])
call[prior_seval_args()] <- NULL
as_string <- function(x) {
if (is.formula(x) && length(x) == 2) {
deparse_no_string(x[[2]])
} else if (is.call(x) || is.name(x) || is.atomic(x)) {
deparse_no_string(x)
} else {
stop2("Arguments must be one-sided formula, call, name, or constant.")
}
}
call <- lapply(call, as_string)
do_call(set_prior, c(call, seval))
}
# arguments for which to use standard evaluation
prior_seval_args <- function() {
c("check")
}
#' @describeIn set_prior Alias of \code{set_prior} allowing to
#' specify arguments as strings.
#' @export
prior_string <- function(prior, ...) {
set_prior(prior, ...)
}
#' Overview on Priors for \pkg{brms} Models
#'
#' Get information on all parameters (and parameter classes) for which priors
#' may be specified including default priors.
#'
#' @inheritParams brm
#' @param ... Other arguments for internal usage only.
#'
#' @return A data.frame with columns \code{prior}, \code{class}, \code{coef},
#' and \code{group} and several rows, each providing information on a
#' parameter (or parameter class) on which priors can be specified. The prior
#' column is empty except for internal default priors.
#'
#' @seealso \code{\link{set_prior}}
#'
#' @examples
#' ## get all parameters and parameters classes to define priors on
#' (prior <- get_prior(count ~ zAge + zBase * Trt + (1|patient) + (1|obs),
#' data = epilepsy, family = poisson()))
#'
#' ## define a prior on all population-level effects a once
#' prior$prior[1] <- "normal(0,10)"
#'
#' ## define a specific prior on the population-level effect of Trt
#' prior$prior[5] <- "student_t(10, 0, 5)"
#'
#' ## verify that the priors indeed found their way into Stan's model code
#' make_stancode(count ~ zAge + zBase * Trt + (1|patient) + (1|obs),
#' data = epilepsy, family = poisson(),
#' prior = prior)
#'
#' @export
get_prior <- function(formula, data, family = gaussian(), autocor = NULL,
data2 = NULL, knots = NULL, sparse = NULL, ...) {
if (is.brmsfit(formula)) {
stop2("Use 'prior_summary' to extract priors from 'brmsfit' objects.")
}
formula <- validate_formula(
formula, data = data, family = family,
autocor = autocor, sparse = sparse
)
bterms <- brmsterms(formula)
data2 <- validate_data2(
data2, bterms = bterms,
get_data2_autocor(formula)
)
data <- validate_data(
data, bterms = bterms,
data2 = data2, knots = knots
)
.get_prior(bterms, data, ...)
}
# internal work function of 'get_prior'
# @param internal return priors for internal use?
# @return a brmsprior object
.get_prior <- function(bterms, data, internal = FALSE, ...) {
ranef <- tidy_ranef(bterms, data)
meef <- tidy_meef(bterms, data)
# initialize output
prior <- empty_prior()
# priors for distributional parameters
prior <- prior + prior_predictor(
bterms, data = data, internal = internal
)
# priors of group-level parameters
def_scale_prior <- def_scale_prior(bterms, data)
prior <- prior + prior_re(
ranef, def_scale_prior = def_scale_prior,
internal = internal
)
# priors for noise-free variables
prior <- prior + prior_Xme(meef, internal = internal)
# explicitly label default priors as such
prior$source <- "default"
# apply 'unique' as the same prior may have been included multiple times
to_order <- with(prior, order(resp, dpar, nlpar, class, group, coef))
prior <- unique(prior[to_order, , drop = FALSE])
rownames(prior) <- NULL
class(prior) <- c("brmsprior", "data.frame")
prior
}
# generate priors for predictor terms
# @return a 'brmsprior' object
prior_predictor <- function(x, ...) {
UseMethod("prior_predictor")
}
#' @export
prior_predictor.default <- function(x, ...) {
empty_prior()
}
prior_predictor.mvbrmsterms <- function(x, internal = FALSE, ...) {
prior <- empty_prior()
for (i in seq_along(x$terms)) {
prior <- prior + prior_predictor(x$terms[[i]], ...)
}
for (cl in c("b", "Intercept")) {
# deprecated; see warning in 'validate_prior_special'
if (any(with(prior, class == cl & coef == ""))) {
prior <- prior + brmsprior(class = cl)
}
}
if (x$rescor) {
if (internal) {
prior <- prior +
brmsprior(class = "Lrescor", prior = "lkj_corr_cholesky(1)")
} else {
prior <- prior + brmsprior(class = "rescor", prior = "lkj(1)")
}
if (family_names(x)[1] %in% "student") {
prior <- prior + brmsprior(class = "nu", prior = "gamma(2, 0.1)")
}
}
prior
}
prior_predictor.brmsterms <- function(x, data, ...) {
data <- subset_data(data, x)
def_scale_prior <- def_scale_prior(x, data)
valid_dpars <- valid_dpars(x)
prior <- empty_prior()
# priors for mixture models
if (is.mixfamily(x$family)) {
if (has_joint_theta(x)) {
# individual theta parameters should not have a prior in this case
theta_dpars <- str_subset(valid_dpars, "^theta[[:digit:]]+")
valid_dpars <- setdiff(valid_dpars, theta_dpars)
prior <- prior +
brmsprior(prior = "dirichlet(1)", class = "theta", resp = x$resp)
}
if (fix_intercepts(x)) {
# fixing thresholds across mixture componenents
# requires a single set of priors at the top level
stopifnot(is_ordinal(x))
prior <- prior + prior_thres(x, def_scale_prior = def_scale_prior)
}
}
# priors for distributional parameters
for (dp in valid_dpars) {
def_dprior <- def_dprior(x, dp, data = data)
if (!is.null(x$dpars[[dp]])) {
# parameter is predicted
dp_prior <- prior_predictor(
x$dpars[[dp]], data = data,
def_scale_prior = def_scale_prior,
def_dprior = def_dprior
)
} else if (!is.null(x$fdpars[[dp]])) {
# parameter is fixed
dp_prior <- empty_prior()
} else {
# parameter is estimated
dp_prior <- brmsprior(def_dprior, class = dp, resp = x$resp)
}
prior <- prior + dp_prior
}
# priors for non-linear parameters
for (nlp in names(x$nlpars)) {
nlp_prior <- prior_predictor(
x$nlpars[[nlp]], data = data,
def_scale_prior = def_scale_prior,
def_dprior = def_dprior
)
prior <- prior + nlp_prior
}
if (conv_cats_dpars(x$family)) {
# deprecated; see warning in 'validate_prior_special'
for (cl in c("b", "Intercept")) {
if (any(find_rows(prior, class = cl, coef = "", resp = x$resp))) {
prior <- prior + brmsprior(class = cl, resp = x$resp)
}
}
}
# priors for noise-free response variables
sdy <- get_sdy(x, data)
if (!is.null(sdy)) {
prior <- prior +
brmsprior(class = "meanme", resp = x$resp) +
brmsprior(class = "sdme", resp = x$resp)
}
# priors for autocorrelation parameters
# prior <- prior + prior_autocor(x, def_scale_prior = def_scale_prior)
prior
}
# prior for linear predictor termss
#' @export
prior_predictor.btl <- function(x, ...) {
prior_fe(x, ...) +
prior_thres(x, ...) +
prior_sp(x, ...) +
prior_cs(x, ...) +
prior_sm(x, ...) +
prior_gp(x, ...) +
prior_ac(x, ...) +
prior_bhaz(x, ...)
}
# priors for non-linear predictor terms
#' @export
prior_predictor.btnl <- function(x, ...) {
# thresholds are required even in non-linear ordinal models
prior_thres(x, ...) +
prior_ac(x, ...)
}
# priors for population-level parameters
prior_fe <- function(bterms, data, def_dprior = "", ...) {
prior <- empty_prior()
fixef <- colnames(data_fe(bterms, data)$X)
px <- check_prefix(bterms)
center_X <- stan_center_X(bterms)
if (center_X && !is_ordinal(bterms)) {
# priors for ordinal thresholds are provided in 'prior_thres'
prior <- prior + brmsprior(def_dprior, class = "Intercept", ls = px)
fixef <- setdiff(fixef, "Intercept")
}
if (length(fixef)) {
prior <- prior + brmsprior(class = "b", coef = c("", fixef), ls = px)
}
prior
}
# priors for thresholds of ordinal models
prior_thres <- function(bterms, def_scale_prior = "", ...) {
prior <- empty_prior()
if (!is_ordinal(bterms)) {
# thresholds only exist in ordinal models
return(prior)
}
if (fix_intercepts(bterms) && !is.mixfamily(bterms$family)) {
# fixed thresholds cannot have separate priors
return(prior)
}
# create priors for threshold per group
.prior_thres <- function(thres, thres_prior = "", group = "") {
prior <- empty_prior()
if (has_equidistant_thres(bterms)) {
# prior for the delta parameter for equidistant thresholds
thres <- character(0)
bound <- str_if(has_ordered_thres(bterms), "<lower=0>")
prior <- prior + brmsprior(
class = "delta", group = group, bound = bound, ls = px
)
}
prior <- prior + brmsprior(
prior = c(thres_prior, rep("", length(thres))),
class = "Intercept", coef = c("", thres),
group = group, ls = px
)
}
px <- check_prefix(bterms)
groups <- get_thres_groups(bterms)
if (any(nzchar(groups))) {
# for models with multiple threshold vectors
prior <- prior + .prior_thres(character(0), def_scale_prior)
for (g in groups) {
prior <- prior + .prior_thres(get_thres(bterms, group = g), group = g)
}
} else {
# for models with a single threshold vector
prior <- prior + .prior_thres(get_thres(bterms), def_scale_prior)
}
prior
}
# priors for coefficients of baseline hazards in the Cox model
prior_bhaz <- function(bterms, ...) {
prior <- empty_prior()
if (!is_cox(bterms$family)) {
return(prior)
}
px <- check_prefix(bterms)
# the scale of sbhaz is not identified when an intercept is part of mu
# thus a sum-to-one constraint ensures identification
prior <- prior + brmsprior("dirichlet(1)", class = "sbhaz", ls = px)
prior
}
# priors for special effects parameters
prior_sp <- function(bterms, data, ...) {
prior <- empty_prior()
spef <- tidy_spef(bterms, data)
if (nrow(spef)) {
px <- check_prefix(bterms)
prior <- prior + brmsprior(
class = "b", coef = c("", spef$coef), ls = px
)
simo_coef <- get_simo_labels(spef, use_id = TRUE)
if (length(simo_coef)) {
prior <- prior + brmsprior(
prior = "dirichlet(1)", class = "simo",
coef = simo_coef, ls = px
)
}
}
prior
}
# priors for category spcific effects parameters
prior_cs <- function(bterms, data, ...) {
prior <- empty_prior()
csef <- colnames(get_model_matrix(bterms$cs, data = data))
if (length(csef)) {
px <- check_prefix(bterms)
prior <- prior +
brmsprior(class = "b", coef = c("", csef), ls = px)
}
prior
}
# default priors for hyper-parameters of noise-free variables
prior_Xme <- function(meef, internal = FALSE, ...) {
stopifnot(is.meef_frame(meef))
prior <- empty_prior()
if (nrow(meef)) {
prior <- prior +
brmsprior(class = "meanme", coef = c("", meef$coef)) +
brmsprior(class = "sdme", coef = c("", meef$coef))
# priors for correlation parameters
groups <- unique(meef$grname)
for (i in seq_along(groups)) {
g <- groups[i]
K <- which(meef$grname %in% g)
if (meef$cor[K[1]] && length(K) > 1L) {
if (internal) {
prior <- prior + brmsprior("lkj_corr_cholesky(1)", class = "Lme")
if (nzchar(g)) {
prior <- prior + brmsprior(class = "Lme", group = g)
}
} else {
prior <- prior + brmsprior("lkj(1)", class = "corme")
if (nzchar(g)) {
prior <- prior + brmsprior(class = "corme", group = g)
}
}
}
}
}
prior
}
# default priors of gaussian processes
# @param def_scale_prior: a character string defining
# the default prior SD parameters
prior_gp <- function(bterms, data, def_scale_prior, ...) {
prior <- empty_prior()
gpef <- tidy_gpef(bterms, data)
if (nrow(gpef)) {
px <- check_prefix(bterms)
lscale_prior <- def_lscale_prior(bterms, data)
prior <- prior +
brmsprior(class = "sdgp", prior = def_scale_prior, ls = px) +
brmsprior(class = "sdgp", coef = unlist(gpef$sfx1), ls = px) +
brmsprior(class = "lscale", ls = px) +
brmsprior(class = "lscale", prior = lscale_prior,
coef = names(lscale_prior), ls = px)
}
prior
}
# default priors for length-scale parameters of GPs
# see https://betanalpha.github.io/assets/case_studies/gp_part3/part3.html
# @param plb prior probability of being lower than minimum length-scale
# @param pub prior probability of being higher than maximum length-scale
def_lscale_prior <- function(bterms, data, plb = 0.01, pub = 0.01) {
.opt_fun <- function(x, lb, ub) {
# optimize parameters on the log-scale to make them positive only
x <- exp(x)
y1 <- pinvgamma(lb, x[1], x[2], log.p = TRUE)
y2 <- pinvgamma(ub, x[1], x[2], lower.tail = FALSE, log.p = TRUE)
c(y1 - log(plb), y2 - log(pub))
}
.def_lscale_prior <- function(X) {
dq <- diff_quad(X)
ub <- sqrt(max(dq))
lb <- sqrt(min(dq[dq > 0]))
# prevent extreme priors
lb <- max(lb, 0.01 * ub)
opt_res <- nleqslv::nleqslv(
c(0, 0), .opt_fun, lb = lb, ub = ub,
control = list(allowSingular = TRUE)
)
prior <- "normal(0, 0.5)"
if (opt_res$termcd %in% 1:2) {
# use the inverse-gamma prior only in case of convergence
pars <- exp(opt_res$x)
prior <- paste0("inv_gamma(", sargs(round(pars, 6)), ")")
}
return(prior)
}
p <- usc(combine_prefix(bterms))
gpef <- tidy_gpef(bterms, data)
data_gp <- data_gp(bterms, data, internal = TRUE)
out <- vector("list", NROW(gpef))
for (i in seq_along(out)) {
pi <- paste0(p, "_", i)
iso <- gpef$iso[i]
cons <- gpef$cons[[i]]
if (length(cons) > 0L) {
for (j in seq_along(cons)) {
Xgp <- data_gp[[paste0("Xgp_prior", pi, "_", j)]]
if (iso) {
c(out[[i]]) <- .def_lscale_prior(Xgp)
} else {
c(out[[i]]) <- apply(Xgp, 2, .def_lscale_prior)
}
}
} else {
Xgp <- data_gp[[paste0("Xgp_prior", pi)]]
if (iso) {
out[[i]] <- .def_lscale_prior(Xgp)
} else {
out[[i]] <- apply(Xgp, 2, .def_lscale_prior)
}
}
# transpose so that by-levels vary last
names(out[[i]]) <- as.vector(t(gpef$sfx2[[i]]))
}
unlist(out)
}
# priors for varying effects parameters
# @param ranef: a list returned by tidy_ranef
# @param def_scale_prior a character string defining
# the default prior for SD parameters
# @param internal: see 'get_prior'
prior_re <- function(ranef, def_scale_prior, internal = FALSE, ...) {
prior <- empty_prior()
if (!nrow(ranef)) {
return(prior)
}
# global sd class
px <- check_prefix(ranef)
upx <- unique(px)
if (length(def_scale_prior) > 1L) {
def_scale_prior <- def_scale_prior[px$resp]
}
global_sd_prior <- brmsprior(
class = "sd", prior = def_scale_prior, ls = px
)
prior <- prior + global_sd_prior
for (id in unique(ranef$id)) {
r <- subset2(ranef, id = id)
group <- r$group[1]
rpx <- check_prefix(r)
urpx <- unique(rpx)
# include group-level standard deviations
prior <- prior +
brmsprior(class = "sd", group = group, ls = urpx) +
brmsprior(class = "sd", coef = r$coef, group = group, ls = rpx)
# detect duplicated group-level effects
J <- with(prior, class == "sd" & nzchar(coef))
dupli <- duplicated(prior[J, ])
if (any(dupli)) {
stop2("Duplicated group-level effects detected for group ", group)
}
# include correlation parameters
if (isTRUE(r$cor[1]) && nrow(r) > 1L) {
if (internal) {
prior <- prior +
brmsprior(
class = "L", group = c("", group),
prior = c("lkj_corr_cholesky(1)", "")
)
} else {
prior <- prior +
brmsprior(
class = "cor", group = c("", group),
prior = c("lkj(1)", "")
)
}
}
}
tranef <- get_dist_groups(ranef, "student")
if (isTRUE(nrow(tranef) > 0L)) {
prior <- prior +
brmsprior("gamma(2, 0.1)", class = "df", group = tranef$group)
}
prior
}
# priors for smooth terms
prior_sm <- function(bterms, data, def_scale_prior, ...) {
prior <- empty_prior()
smef <- tidy_smef(bterms, data)
if (NROW(smef)) {
px <- check_prefix(bterms)
# prior for the FE coefficients
Xs_names <- attr(smef, "Xs_names")
if (length(Xs_names)) {
prior <- prior + brmsprior(
class = "b", coef = c("", Xs_names), ls = px
)
}
# prior for SD parameters of the RE coefficients
smterms <- unique(smef$term)
prior_strings <- c(def_scale_prior, rep("", length(smterms)))
prior <- prior + brmsprior(
class = "sds", coef = c("", smterms),
prior = prior_strings, ls = px
)
}
prior
}
# priors for autocor parameters
prior_ac <- function(bterms, def_scale_prior, ...) {
prior <- empty_prior()
acef <- tidy_acef(bterms)
if (!NROW(acef)) {
return(prior)
}
px <- check_prefix(bterms)
if (has_ac_class(acef, "arma")) {
acef_arma <- subset2(acef, class = "arma")
if (acef_arma$p > 0) {
prior <- prior + brmsprior(class = "ar", ls = px)
}
if (acef_arma$q > 0) {
prior <- prior + brmsprior(class = "ma", ls = px)
}
}
if (has_ac_class(acef, "cosy")) {
prior <- prior + brmsprior(class = "cosy", ls = px)
}
if (has_ac_latent_residuals(bterms)) {
prior <- prior +
brmsprior(def_scale_prior, class = "sderr", ls = px)
}
if (has_ac_class(acef, "sar")) {
acef_sar <- subset2(acef, class = "sar")
if (acef_sar$type == "lag") {
prior <- prior + brmsprior(class = "lagsar", ls = px)
}
if (acef_sar$type == "error") {
prior <- prior + brmsprior(class = "errorsar", ls = px)
}
}
if (has_ac_class(acef, "car")) {
acef_car <- subset2(acef, class = "car")
prior <- prior +
brmsprior(def_scale_prior, class = "sdcar", ls = px)
if (acef_car$type %in% "escar") {
prior <- prior + brmsprior(class = "car", ls = px)
} else if (acef_car$type %in% "bym2") {
prior <- prior +
brmsprior("beta(1, 1)", class = "rhocar", ls = px)
}