R/bayes.R

Defines functions pm_mcmc_ord pm_bayes_joint print.pm_bayesslopes pm_bayes_slopes pm_bayes_curve_diff pm_bayes_curves pm_bayes_curve_settings pm_bayes_trans_opt pm_bayes_cox_base pm_bayes_survmeans pm_bayes_surv_s pm_bayes_hr pm_bayes_dpar pm_bayes_trace pm_bayes_check pm_bayes_chains print.pm_bayes_r2 pm_bayes_r2 pm_bayes_varcomp pm_bayes_vc_draws pm_bayes_draws_plot as.data.frame.pm_bayescontrasts tidy.pm_bayescontrasts print.pm_bayescontrasts pm_bayes_contrasts plot.pm_bayesmeans autoplot.pm_bayesmeans as.data.frame.pm_bayesmeans tidy.pm_bayesmeans print.pm_bayesmeans pm_bayes_popmean pm_bayes_var pm_bayes_s2 pm_bayes_zvar pm_bayes_back pm_bayes_advice pm_bayes_settings pm_bayes_probs pm_bayes_ord_scale pm_bayes_cat_var pm_bayes_cat_popprob pm_bayes_softmax pm_bayes_cat_means pm_bayes_mix_means pm_bayes_mix_mean pm_bayes_cat_refuse pm_bayes_zi_part pm_bayes_overall_pairs pm_bayes_overall_tab pm_bayes_overall_fun pm_bayes_mean_type pm_bayes_means pm_bayes_letters pm_bayes_ratio pm_bayes_ratio_kind pm_bayes_compare pm_bayes_band pm_bayes_diag pm_draws.MCMCglmm pm_draws.stanreg pm_draws.brmsfit pm_draws.pm_bayesfit pm_data.pm_bayesfit pm_linkinv.pm_bayesfit pm_contrasts.pm_bayesfit pm_basis.pm_bayesfit pm_vcov.pm_bayesfit pm_coef.pm_bayesfit nobs.pm_bayesfit model.frame.pm_bayesfit family.pm_bayesfit formula.pm_bayesfit terms.pm_bayesfit pm_bayes_re pm_bayes_par pm_bayes_wrap pm_bayes_pd pm_bayes_summary pm_bayes_lin pm_bayes_refuse pm_inference_posterior pm_is_bayes pm_draws.pm_foreign pm_draws.default pm_draws

Documented in autoplot.pm_bayesmeans plot.pm_bayesmeans pm_draws pm_draws.brmsfit pm_draws.default pm_draws.MCMCglmm pm_draws.pm_bayesfit pm_draws.pm_foreign pm_draws.stanreg

## Bayesian fits (dev/review-bayes.md, steps D1-D5): means, pairs and contrasts from posterior draws.
##
## The reference grid and the K matrix do not change: a mean is K beta. The fit gives S draws of beta (an S x p
## matrix, pm_draws()); every quantity is computed per draw and summarised:
##   estimate     the posterior median (invariant under the back-transformation: the median of h(K beta) is
##                h of the median for monotone h; with an even number of draws the median averages the two middle
##                draws, so the two differ in the last digits)
##   posterior.sd the posterior SD (never called std.error: it is not a frequentist SE)
##   conf.low/.high  the equal-tailed credible interval at conf_level (quantiles of the draws, type 7, as
##                bayestestR::eti())
##   pd           the probability of direction, max(P(d > 0), P(d < 0)) (bayestestR::p_direction()); no p-value
## There are no df: the posterior carries the uncertainty of the variance parameters. pm_inference() returns the
## posterior mean and covariance of the draws (exact for the posterior mean and SD of any linear function), so the
## K matrix checks run as for any fit; the tables are made here, in one place (pm_bayes_summary()).
## The decisions of the maintainer's note (section 5): median + equal-tailed interval; pd, no p-value; letters only
## from simultaneous intervals (adj given); brms and rstanarm in Suggests.

#' Posterior draws of the coefficients of a Bayesian fit
#'
#' @description
#' The adapter generic for Bayesian model classes (see \code{\link{pm_coef}}): an S x p matrix of posterior draws of
#' the fixed-effect coefficients, columns named as \code{pm_coef()} names them, or \code{NULL} for a fit that has
#' none. A class whose \code{pm_draws()} gives draws is analysed by the draws in \code{\link{predictmeans}} and
#' \code{\link{contrastmeans}}: posterior medians, posterior SDs, equal-tailed credible intervals and the probability
#' of direction, with no df and no p-values.
#'
#' \code{brmsfit} (brms), \code{stanreg} (rstanarm) and \code{MCMCglmm} fits have their own methods: the draws of the
#' coefficients of the mean, named as the columns of its design. An MCMCglmm fit keeps no data: give them
#' (\code{predictmeans(fit, ..., data = d)}) or store them once (\code{fit$data <- d}); families gaussian, poisson and
#' categorical (two classes) and ordinal (the \code{units} variance fixed in the prior; latent means on the standard probit scale; class probabilities of an observation, on the latent sd sqrt(1 + units), and with \code{bias_adjust = TRUE} also over the random effects), random intercepts and \code{us()} / \code{idh()} structures; for poisson and categorical the means are at \code{units} (the additive overdispersion) = 0, a typical observation, and \code{bias_adjust = TRUE} averages over \code{units} and the random effects (the mean). For another Bayesian class write a \code{pm_draws()} method, with
#' \code{pm_coef()} (the posterior means), \code{pm_vcov()} and \code{pm_basis()}.
#'
#' @section What is done for Bayesian fits:
#' \itemize{
#'   \item \code{predictmeans()}, \code{contrastmeans()}, \code{covariatemeans()} (curves, and with \code{contr} the
#'   difference of two curves, with a simultaneous band over the covariate for \code{band = "simultaneous"}) and
#'   \code{pm_slopes()}: means, pairs, contrasts, curves and slopes from the draws; the inverse
#'   link (or \code{trans}) of each draw; \code{bias_adjust = TRUE}: the mean over the random effects of each draw;
#'   with \code{adj}, simultaneous bands (Besag et al. 1995) and letters; \code{equivalence}: the posterior
#'   probability within the margins (\code{p.rope}).
#'   \item \code{varcomp()}: the variance components; \code{R2_model()}: Nakagawa's R2 of each draw;
#'   \code{pm_check()}: Rhat, effective sample sizes, divergent transitions; \code{residplot()}: trace and density of
#'   each coefficient by chain; \code{autoplot()}: means, pairs and the posterior of each (\code{type = "draws"}).
#'   \item brms \code{weibull()}, \code{exponential()} and \code{lognormal()} with \code{cens()}: time ratios, hazard
#'   ratios exp(-k d) per draw (Weibull, exponential), and \code{\link{survmeans}()} curves and medians, of a typical
#'   cluster or averaged over the random effects (\code{marginal = TRUE}).
#'   \item brms \code{cox()}: hazard ratios per draw (means relative to the data's average linear predictor, as for
#'   \code{coxph()}), and survival curves from its spline baseline hazard (\code{\link{survmeans}()}; NA beyond the
#'   spline's range). Zero-inflated and hurdle families: the mean of the count (or non-zero) part, and with
#'   \code{mean_type = "overall"} the overall mean per draw ((1 - zi) mu; (1 - hu) E(y | y > 0); per trial for
#'   \code{zero_inflated_binomial}) at each cell, averaged over the cells on the response scale, and the pairs as
#'   ratios of overall means (pd, bands and letters on their log); a zi or hu modelled by predictors enters each cell
#'   (its variables not in the mean: over their levels, equally), and \code{bias_adjust = TRUE} integrates over the
#'   random effects of mu and of zi / hu (not when the two are correlated). \code{cumulative()}, \code{sratio()}, \code{cratio()} and \code{acat()}
#'   (logit): latent means x'b - mean(thresholds) (cumulative logit: odds ratios of a higher class), and with
#'   \code{mean_type = "prob"} or \code{"mean_class"} the class probabilities or the mean class per draw, each
#'   cell's probabilities averaged over the cells of the mean (as \code{posterior_epred()} averaged over the other
#'   factors, and as for \code{clm} fits).
#'   \item \code{pm_joint()} and \code{contrastmeans(joint = TRUE)}: the posterior region through 0 of several
#'   contrasts (\code{d2}, the Mahalanobis distance of 0 from the posterior, and \code{p.contour} = (b + 1) / (S + 1),
#'   b of the S draws at least as far from the posterior mean; Box and Tiao's contour probability), in place of the F
#'   test.
#'   \item Random intercepts and slopes in \code{bias_adjust}, \code{R2_model()} and \code{survmeans(marginal =
#'   TRUE)}: the variance at a row is z' Sigma z for each draw (z the row's values of the random-effect terms).
#' }
#' @section What is not done (it stops with a message):
#' \itemize{
#'   \item \code{df_term()}, \code{permmodels()},
#'   \code{permlmer()}, \code{bootmodels()}, \code{CookD()}, \code{se_ranef()}, \code{heritability()},
#'   \code{residvariogram()}, \code{semipred()}, the test of equal curves of \code{covariatemeans(contr = )},
#'   \code{varcomp(test = TRUE)},
#'   \code{permlist}.
#'   \item brms: families other than gaussian, student, skew_normal, binomial, bernoulli, beta_binomial, poisson,
#'   negbinomial, geometric, gamma, inverse.gaussian, beta, lognormal, weibull, exponential, cox, cumulative, the
#'   zero-inflated poisson, negbinomial, binomial and beta, the hurdle poisson, negbinomial, lognormal and gamma, and
#'   sratio, cratio, acat, categorical (class probabilities as for \code{nnet::multinom} fits: the class a factor of the means, \code{mean_type = "prob"}, \code{"prob_diff"} or \code{"link"}; random effects at zero, or with \code{bias_adjust = TRUE} averaged over them for up to 4 classes), and \code{mixture()} (the overall mean sum_k theta_k E_k by default; with \code{mean_type = "conditional"} the mean of each component, only for ordered components; fixed mixing proportions), so no zero-one-inflated models; ordinal models with a
#'   modelled disc or thresholds that are not flexible; multivariate and non-linear formulas; smooths,
#'   Gaussian processes, \code{mo()}, \code{me()}, \code{mi()}, category-specific and autocorrelation terms, offsets.
#'   A modelled \code{sigma} or \code{shape} leaves the means of \code{mu} as they are, but survival curves and hazard
#'   ratios need one shape or sigma for all rows.
#'   \item rstanarm: models other than \code{stan_glm()}, \code{stan_glmer()}, \code{stan_lmer()}, \code{stan_lm()},
#'   \code{stan_glm.nb()}, \code{stan_glmer.nb()} and \code{stan_aov()}. MCMCglmm: other families, several
#'   responses, other random structures than intercepts, us() and idh(); \code{R2_model()} of non-gaussian MCMCglmm fits.
#'   \item A random slope whose variable is not a column of the fixed-effect design (its value at the means is not
#'   known); \code{R2_model()} for families other than gaussian and binomial.
#'   \item Model checks of the data (posterior predictive checks): use \code{pp_check()} of brms or rstanarm.
#' }
#' @section Accuracy and checks:
#' The summaries are exact for the draws: medians and quantiles of the draws of each quantity (type 7, as
#' \code{bayestestR::eti()}); with an even number of draws the median averages two draws, so the median of a
#' back-transformed quantity and the back-transformation of the median differ in the last digits. Their Monte Carlo
#' error is that of the draws: the advice says when the draws have not converged (Rhat above 1.01, bulk or tail
#' effective sample size below 400) or are too few for the limits (fewer than 1,000). Checked against emmeans'
#' draws, bayestestR, brms' \code{VarCorr()} and \code{posterior_epred()} (overall means of zero-inflated and hurdle
#' models and class probabilities of ordinal ones, averaged over the other factors), \code{integrate()}
#' (\code{tests/testthat/test-bayes.R}).
#' Nakagawa's R2 of each draw equals \code{performance::r2_nakagawa()} of a glmmTMB fit held at the draw's parameter
#' values (gaussian with random slopes, Bernoulli); for an aggregated binomial response (\code{cbind()}) performance
#' uses another observation-level variance, where predictmeans uses the latent pi^2/3. The survival quantities of brms
#' fits are checked against their closed forms per draw, \code{integrate()} for the marginal curves, and
#' \code{survreg()} within 5\% with flat priors, and against SAS's own Bayesian fits of the same data (LIFEREG and
#' PHREG with a BAYES statement, PROC MCMC with a random institution effect; \code{dev/sas/survival-bayes.sas}): time
#' ratios within 0.5\%, hazard ratios within 1.1\%, survival probabilities and medians of the frailty model within
#' 4.5\% (different samplers and priors). On SAS's own draws (PROC MCMC, PHREG), predictmeans' survival formulas
#' reproduce SAS's time ratios, hazard ratios, S(t), marginal S(t) and medians to SAS's printed digits.
#' @references Besag, J., Green, P., Higdon, D. and Mengersen, K. (1995). Bayesian computation and stochastic
#'   systems. \emph{Statistical Science}, 10, 3-41.
#' @param model A fitted model.
#' @param ... Not used.
#' @return A numeric matrix (draws in rows, coefficients in columns), or \code{NULL}.
#' @examples
#' \donttest{
#' if (requireNamespace("rstanarm", quietly = TRUE) && requireNamespace("emmeans", quietly = TRUE)) {
#'   fit <- rstanarm::stan_glm(weight ~ group, data = PlantGrowth, chains = 1, iter = 1000,
#'                             refresh = 0, seed = 1)
#'   dim(pm_draws(fit))
#'   predictmeans(fit, "group", pairwise = TRUE)
#' }
#' }
#' @export
pm_draws <- function(model, ...) UseMethod("pm_draws")
#' @rdname pm_draws
#' @export
pm_draws.default <- function(model, ...) NULL
#' @rdname pm_draws
#' @export
pm_draws.pm_foreign <- function(model, ...) attr(model, "pm_foreign")$draws

## TRUE for a fit analysed by its posterior draws
pm_is_bayes <- function(model) !is.null(pm_draws(model))

## The posterior branch of pm_inference(): the posterior mean and covariance of the draws, no df. Options that
## belong to frequentist inference are refused or ignored here, once.
pm_inference_posterior <- function(model, draws, df_method = "auto", vcov = NULL, permlist = NULL) {
  if (!is.null(permlist)) {
    stop("Permutation tests do not apply to a Bayesian fit: its comparisons are summaries of the posterior draws.",
         call. = FALSE)
  }
  if (!is.null(vcov)) warning("'vcov' does not apply to a Bayesian fit (the draws are used); ignored.", call. = FALSE)
  if (!identical(df_method, "auto")) {
    warning("'df_method' does not apply to a Bayesian fit (no df: the draws are used); ignored.", call. = FALSE)
  }
  b <- colMeans(draws)
  mp <- structure(list(coef = b, vcov = stats::cov(draws), df = Inf, estimable = rep(TRUE, length(b))),
                  class = "mymodelparm")
  structure(list(mp = mp, df_type = "posterior", vcov_adj = NULL, vcov_adjust = FALSE, vcov_label = NULL,
                 per_row = FALSE, label = "none (posterior draws)",
                 df = function(L, terms = NULL) rep(Inf, nrow(rbind(L))),
                 ftest = function(...) stop("Joint F tests do not apply to a Bayesian fit; pm_joint() gives the posterior region through 0 instead; compare its means with ",
                                            "predictmeans() or contrastmeans().", call. = FALSE),
                 draws = draws),
            class = "pm_inference")
}

## A function that is not yet available for Bayesian fits stops here, with what to use instead
pm_bayes_refuse <- function(model, what) {
  if (inherits(model, pm_bayes_classes) || pm_is_bayes(model)) {
    stop(what, " is not available for Bayesian fits (", class(model)[1], "); predictmeans() and contrastmeans() ",
         "summarise their posterior draws.", call. = FALSE)
  }
  invisible(NULL)
}

## Draws of the linear functions in the rows of L (S x nrow(L)); rows that are not estimable: NA
pm_bayes_lin <- function(draws, L, estimable = rep(TRUE, nrow(L))) {
  L <- rbind(L)
  out <- draws[, colnames(L), drop = FALSE] %*% t(L)
  out[, !estimable] <- NA_real_
  colnames(out) <- rownames(L)
  out
}

## Posterior summaries of each column of X (S x k): median, SD, equal-tailed interval at 1 - level
pm_bayes_summary <- function(X, level) {
  q <- function(x, p) if (anyNA(x)) NA_real_ else stats::quantile(x, p, names = FALSE)
  data.frame(estimate = apply(X, 2, q, 0.5), posterior.sd = apply(X, 2, stats::sd),
             conf.low = apply(X, 2, q, level / 2), conf.high = apply(X, 2, q, 1 - level / 2), row.names = NULL)
}

## Probability of direction of each column (bayestestR::p_direction(): the share of draws on the side of the median)
pm_bayes_pd <- function(X) apply(X, 2, function(x) if (anyNA(x)) NA_real_ else max(mean(x > 0), mean(x < 0)))

## ---- brms and rstanarm fits -------------------------------------------------------------------------------------
## pm_means_model() turns a brmsfit or stanreg into a "pm_bayesfit": the fixed part of the mean (mu) as an ordinary
## formula, the data, the draws of its coefficients named as the columns of model.matrix() (brms names them
## "b_<name>", the intercept "Intercept"; rstanarm as lm), the link and the contrasts. Every predictmeans function
## that does not use the draws refuses it (pm_bayes_refuse()); stanreg inherits lm and lmerMod, so it must never
## reach their code.
pm_bayes_classes <- c("brmsfit", "stanreg", "MCMCglmm")
## brms families whose mu is the mean of the response on the link scale (or, log-normal, the mean of its log), and
## the survival families; any other is refused (zero-inflated, hurdle, shifted, asymmetric Laplace, cox, ...)
pm_bayes_brms_families <- c("gaussian", "student", "skew_normal", "binomial", "bernoulli", "beta_binomial", "poisson",
                            "negbinomial", "geometric", "gamma", "inverse.gaussian", "beta", "lognormal", "weibull",
                            "exponential", "cox", "cumulative", "sratio", "cratio", "acat",
                            "zero_inflated_poisson", "zero_inflated_negbinomial", "zero_inflated_binomial",
                            "zero_inflated_beta", "hurdle_poisson", "hurdle_negbinomial", "hurdle_lognormal",
                            "hurdle_gamma", "categorical")

pm_bayes_wrap <- function(model) {
  cls <- class(model)[1]
  dpars <- character(0)
  mord <- NULL
  cens <- FALSE
  if (inherits(model, "brmsfit")) {
    pm_need("brms", "brmsfit models")
    fam <- stats::family(model)
    mixf <- NULL
    if (inherits(fam, "mixfamily")) {
      # mixture (F5, dev/review-bayes-2.md): components mu1, mu2, ... each with its family and link, mixing
      # proportions theta (fixed per draw, not modelled); the overall mean sum_k theta_k E_k per draw
      comp <- vapply(fam$mix, function(x) x$family, "")
      okf <- c("gaussian", "student", "poisson", "negbinomial", "binomial", "bernoulli", "gamma", "beta", "lognormal",
               "exponential", "weibull")
      if (!all(comp %in% okf)) {
        stop("predictmeans handles brms mixture() components of families ", paste(okf, collapse = ", "), "; this one ",
             "has ", paste(setdiff(comp, okf), collapse = ", "), ".", call. = FALSE)
      }
      bt0 <- brms::brmsterms(model$formula)
      pn <- paste0("mu", seq_along(comp))
      fes <- lapply(bt0$dpars[pn], function(p) if (inherits(p, "btl")) stats::formula(p$fe))
      if (any(vapply(fes, is.null, NA)) || length(unique(vapply(fes, function(f) paste(deparse(f), collapse = ""), ""))) > 1) {
        stop("predictmeans handles brms mixture() models whose components all have the same formula.", call. = FALSE)
      }
      if (any(grepl("^theta", names(bt0$dpars)))) {
        stop("predictmeans handles brms mixture() models with fixed mixing proportions (theta not modelled).",
             call. = FALSE)
      }
      # only lognormal's mean needs its sigma; a modelled sigma<k> of a lognormal component stops
      if (any(comp == "lognormal" & paste0("sigma", seq_along(comp)) %in% names(bt0$dpars))) {
        stop("predictmeans needs one sigma for the lognormal components of a brms mixture() (here it is modelled by ",
             "predictors).", call. = FALSE)
      }
      if (any(comp == "binomial") && !is.null(bt0$adforms$trials)) {
        stop("predictmeans handles binomial components of a brms mixture() as proportions (no trials(); the ",
             "overall mean of counts needs the number of trials of each cell).", call. = FALSE)
      }
      mixf <- list(dpars = pn, families = comp, links = vapply(fam$mix, function(x) x$link, ""),
                   ordered = !identical(fam$order, "none") && !isFALSE(fam$order),
                   theta = as.matrix(model, variable = paste0("theta", seq_along(comp))),
                   aux = lapply(seq_along(comp), function(k) {
                     if (comp[k] == "lognormal") as.numeric(as.matrix(model, variable = paste0("sigma", k)))
                   }))
      fam <- fam$mix[[1]]
    }
    if (is.null(mixf) && !fam$family %in% pm_bayes_brms_families) {
      stop("predictmeans handles the brms families ", paste(pm_bayes_brms_families, collapse = ", "), "; '",
           fam$family, "' is not one of them: use emmeans for it.", call. = FALSE)
    }
    bt <- brms::brmsterms(model$formula)
    catf <- NULL
    if (!is.null(mixf)) {
      catf <- list(dpars = mixf$dpars, mixture = mixf)
      bt$dpars$mu <- bt$dpars[[mixf$dpars[1]]]
    }
    if (identical(fam$family, "categorical")) {
      # categorical (F1, dev/review-bayes-2.md): one linear predictor mu<class> per class except the reference, all
      # with the same formula; the draws of each, named as the design columns below; the means are class
      # probabilities (softmax), so 'mu' is the first predictor's formula
      pn <- fam$dpars
      fes <- lapply(bt$dpars[pn], function(p) if (inherits(p, "btl")) stats::formula(p$fe))
      if (any(vapply(fes, is.null, NA)) || length(unique(vapply(fes, function(f) paste(deparse(f), collapse = ""), ""))) > 1 ||
          length(setdiff(names(bt$dpars), pn))) {
        stop("predictmeans handles brms categorical() models whose class predictors all have the same formula and ",
             "no other modelled parameters.", call. = FALSE)
      }
      catf <- list(dpars = pn, levels = fam$cats, reference = fam$refcat, response = all.vars(bt$respform)[1])
      bt$dpars$mu <- bt$dpars[[pn[1]]]
    }
    mu <- bt$dpars$mu
    if (!inherits(mu, "btl") || length(bt$responses) > 1 || !is.null(bt$terms)) {
      stop("predictmeans handles brms models with one response and one linear predictor of the mean; this one ",
           "is multivariate or non-linear: use emmeans for it.", call. = FALSE)
    }
    extra <- intersect(names(mu), c("sp", "cs", "sm", "gp", "ac", "offset"))
    if (length(extra)) {
      stop("predictmeans handles brms models whose mean has fixed and random effects only; this one has ",
           paste(c(sp = "special terms (mo(), me(), mi())", cs = "category-specific effects", sm = "smooths",
                   gp = "Gaussian processes", ac = "autocorrelation terms", offset = "an offset")[extra],
                 collapse = ", "), ".", call. = FALSE)
    }
    rhs <- stats::formula(mu$fe)
    if ("Intercept" %in% all.vars(rhs)) {
      stop("Write the intercept of the brms formula in the usual way (1 + ...), not as brms' 'Intercept' term.",
           call. = FALSE)
    }
    fe <- stats::as.formula(paste(paste(deparse(bt$respform[[2]]), collapse = ""), "~",
                                  paste(deparse(rhs[[length(rhs)]]), collapse = "")), env = environment(rhs))
    data <- model$data                                   # (brms keeps the rows it used)
    dpars <- setdiff(names(bt$dpars), c("mu", catf$dpars))   # modelled distributional parameters (sigma ~ x, ...)
    if ("disc" %in% dpars) stop("predictmeans needs brms ordinal models with disc = 1 (not modelled).", call. = FALSE)
    bnames <- rownames(brms::fixef(model))
    if (length(dpars)) bnames <- bnames[!grepl(paste0("^(", paste(dpars, collapse = "|"), ")_"), bnames)]
    if (!is.null(catf)) {
      # the coefficients of each class predictor (b_muMedium_x), the first class's as 'draws'
      bn <- lapply(pn, function(p) sub(paste0("^", p, "_"), "", bnames[startsWith(bnames, paste0(p, "_"))]))
      catf$draws <- lapply(seq_along(pn), function(i) {
        as.matrix(model, variable = paste0("b_", pn[i], "_", bn[[i]]))
      })
      bnames <- bn[[1]]
    }
    # cumulative: the thresholds Intercept[k] are not in the mean (the latent scale has no intercept); cox(): the
    # intercept goes with the baseline hazard
    thr <- NULL
    if (fam$family %in% c("cumulative", "sratio", "cratio", "acat")) {
      if (fam$family == "acat" && fam$link != "logit") {
        stop("predictmeans handles brms acat() models with the logit link.", call. = FALSE)
      }
      ti <- grepl("^Intercept\\[", bnames)
      if (any(grepl(",", bnames[ti], fixed = TRUE))) {
        stop("predictmeans needs brms ordinal models with one set of thresholds (not thres(gr = )).", call. = FALSE)
      }
      thr <- as.matrix(model, variable = paste0("b_", bnames[ti]))
      bnames <- bnames[!ti]
    }
    if (fam$family == "cox") bnames <- setdiff(bnames, "Intercept")
    vars <- paste0("b_", bnames)
    draws <- if (!is.null(catf)) catf$draws[[1]] else as.matrix(model, variable = vars)
    cens <- !is.null(bt$adforms$cens)
  } else if (inherits(model, "MCMCglmm")) {
    # MCMCglmm: the fixed-effect draws are the first nfl columns of Sol; the data are found through the call;
    # families gaussian (identity), poisson (log) and a binary categorical / ordinal-free logit ("categorical" with
    # two classes). Poisson and categorical have an additive residual ("units"): the means are those of a typical
    # observation (units at zero), and bias_adjust averages over units and the random effects.
    # (MCMCglmm stores family = "categorical" as "multinomial")
    fam_name <- sub("^multinomial$", "categorical", unique(model$family))
    if (length(fam_name) != 1 || !fam_name %in% c("gaussian", "poisson", "categorical", "ordinal")) {
      stop("predictmeans handles MCMCglmm models with one response of family gaussian, poisson, categorical (two ",
           "classes) or ordinal; this one is ", paste(fam_name, collapse = ", "), ".", call. = FALSE)
    }
    fe <- model$Fixed$formula
    data <- if (is.data.frame(model$data)) model$data else attr(model, "pm_data")
    if (!is.data.frame(data)) {
      stop("An MCMCglmm fit keeps no data: give them (predictmeans(fit, ..., data = d)), or store them in the fit ",
           "once (fit$data <- d).", call. = FALSE)
    }
    if (fam_name == "categorical" && length(unique(stats::na.omit(data[[all.vars(fe)[1]]]))) != 2) {
      stop("predictmeans handles MCMCglmm categorical models with two classes (one latent trait); this response ",
           "has more.", call. = FALSE)
    }
    draws <- as.matrix(model$Sol)[, seq_len(model$Fixed$nfl), drop = FALSE]
    bnames <- colnames(draws)
    vars <- bnames
    fam <- switch(fam_name, gaussian = stats::gaussian(), poisson = stats::poisson(), categorical = stats::binomial(),
                  ordinal = stats::binomial("probit"))
    mord <- if (fam_name == "ordinal") pm_mcmc_ord(model, data, fe)
  } else {
    pm_need("rstanarm", "stanreg models")
    if (!is.null(model$stan_function) && !model$stan_function %in% c("stan_glm", "stan_glmer", "stan_lmer", "stan_lm",
                                                                       "stan_glm.nb", "stan_glmer.nb", "stan_aov")) {
      stop("predictmeans does not handle rstanarm '", model$stan_function, "' models: use emmeans for them.",
           call. = FALSE)
    }
    fe <- pm_nobars(stats::formula(model))
    # the rows rstanarm used (not those with a missing value or left out by 'subset')
    used <- rownames(stats::model.frame(model))
    data <- if (all(used %in% rownames(model$data))) model$data[used, , drop = FALSE] else model$data
    bnames <- names(if (inherits(model, "lmerMod")) lme4::fixef(model) else stats::coef(model))
    draws <- as.matrix(model, pars = bnames)
    vars <- bnames
    fam <- stats::family(model)
  }
  environment(fe) <- list2env(list(data = data), parent = environment(fe))
  # predvars (scale(), poly(), ns()) as the fit made them: rstanarm, as lm(), evaluates them on all the rows of its
  # data before dropping incomplete ones (unless 'subset' was given); brms on the rows it used
  base <- if (inherits(model, "stanreg") && is.null(stats::getCall(model)$subset)) model$data else data
  tt <- attr(stats::model.frame(fe, base, na.action = stats::na.omit), "terms")
  mf <- stats::model.frame(tt, data, na.action = stats::na.omit)
  X <- stats::model.matrix(tt, mf)
  no_int <- inherits(model, "brmsfit") && fam$family %in% c("cumulative", "sratio", "cratio", "acat", "cox")
  if (no_int) X <- X[, colnames(X) != "(Intercept)", drop = FALSE]
  if (ncol(X) != ncol(draws)) {
    stop("The design of the mean of this ", cls, " fit has ", ncol(X), " columns and the fit ", ncol(draws),
         " coefficients: predictmeans cannot match them; use emmeans for it.", call. = FALSE)
  }
  same <- function(a, b) gsub("[^[:alnum:]]", "", a) == gsub("[^[:alnum:]]", "", b)
  if (!all(same(sub("^\\(Intercept\\)$", "Intercept", colnames(X)), sub("^\\(Intercept\\)$", "Intercept", bnames)))) {
    stop("The coefficients of this ", cls, " fit (", paste(utils::head(bnames, 4), collapse = ", "), ") do not match ",
         "the columns of its design (", paste(utils::head(colnames(X), 4), collapse = ", "), ").", call. = FALSE)
  }
  colnames(draws) <- colnames(X)
  if (inherits(model, "brmsfit") && !is.null(catf)) {
    catf$draws <- lapply(catf$draws, function(d) { d <- unclass(d)[, , drop = FALSE]; colnames(d) <- colnames(X); d })
  } else catf <- NULL
  linkinv <- if (is.function(fam$linkinv)) fam$linkinv else tryCatch(stats::make.link(fam$link)$linkinv,
                                                                     error = function(e) NULL)
  rhs <- all.vars(stats::delete.response(tt))
  xlev <- lapply(mf[vapply(names(mf), function(v) v %in% rhs && (is.factor(mf[[v]]) || is.character(mf[[v]])), NA)],
                 function(z) if (is.factor(z)) levels(z) else sort(unique(z)))
  # log-normal (brms): mu is the mean of log y, exp gives the median; survival: Weibull and exponential (log link
  # of the mean time), and log-normal with censoring
  lognormal <- inherits(model, "brmsfit") && identical(fam$family, "lognormal")
  if (lognormal) linkinv <- exp
  surv <- if (inherits(model, "brmsfit") && (fam$family %in% c("weibull", "exponential") || (lognormal && cens))) fam$family
  # zero-inflated and hurdle families: mu is the mean of the count (or continuous) part; zi / hu the probability of
  # an extra zero / of a zero, with their draws (NULL when modelled by predictors: no overall mean then)
  zih <- NULL
  if (inherits(model, "brmsfit") && grepl("^(zero_inflated|hurdle)_", fam$family)) {
    pz <- if (startsWith(fam$family, "hurdle")) "hu" else "zi"
    aux <- intersect(c("shape", "sigma"), brms::brmsterms(model$formula)$family$dpars)
    zih <- list(type = pz, dist = sub("^(zero_inflated|hurdle)_", "", fam$family),
                p = if (!pz %in% dpars) as.numeric(as.matrix(model, variable = pz)),
                aux = if (length(aux) && !aux[1] %in% dpars) as.numeric(as.matrix(model, variable = aux[1])))
    if (pz %in% dpars) {
      # zi / hu modelled by predictors: its own fixed formula, coefficient draws and link (random effects of that
      # part at zero)
      zfe <- stats::formula(bt$dpars[[pz]]$fe)
      zn <- grep(paste0("^b_", pz, "_"), posterior::variables(model), value = TRUE)
      zl <- fam[[paste0("link_", pz)]]
      zih$part <- list(formula = zfe, draws = as.matrix(model, variable = zn),
                       names = sub("^Intercept$", "(Intercept)", sub(paste0("^b_", pz, "_"), "", zn)),
                       linkinv = stats::make.link(if (is.null(zl)) "logit" else zl)$linkinv)
    }
  }
  ord <- if (!is.null(mord)) mord else
    if (inherits(model, "brmsfit") && fam$family %in% c("cumulative", "sratio", "cratio", "acat")) {
    # the classes: the levels of a factor response (unused ones kept, as brms counts them), 1, ..., K of an integer
    # one (brms: K = the largest value)
    yr <- stats::model.response(stats::model.frame(stats::update(fe, . ~ 1), data))
    lev <- if (is.factor(yr)) levels(yr) else as.character(seq_len(ncol(thr) + 1))
    if (ncol(thr) != length(lev) - 1) {
      stop("predictmeans needs brms ordinal models with one threshold per cut point between the ", length(lev),
           " classes (threshold = \"flexible\"); this fit has ", ncol(thr), " thresholds.", call. = FALSE)
    }
    list(thr = unclass(thr)[, , drop = FALSE], link = fam$link, family = fam$family, levels = lev)
  }
  structure(list(fit = model, formula = fe, terms = tt, data = data, draws = unclass(draws)[, , drop = FALSE],
                 vars = vars, family = fam, link = fam$link, no_int = no_int, zih = zih, ord = ord,
                 cox = inherits(model, "brmsfit") && fam$family == "cox",
                 centre = if (inherits(model, "brmsfit") && fam$family == "cox") colMeans(X),
                 cat = catf,
                 linkinv = if (!is.null(ord) || !is.null(catf)) NULL else if (!identical(fam$link, "identity") || lognormal) linkinv,
                 surv = surv,
                 lognormal = lognormal, dpars = dpars,
                 contrasts = attr(X, "contrasts"), xlev = xlev, class0 = cls,
                 random = if (inherits(model, "brmsfit")) length(brms::ngrps(model)) > 0 else
                   if (inherits(model, "MCMCglmm")) length(setdiff(colnames(model$VCV), "units")) > 0 else
                     inherits(model, "lmerMod"),
                 call = call("pm_bayesfit", formula = fe, data = data)),
            class = "pm_bayesfit")
}

## Draws of named parameters of the fit (brms: variable names; rstanarm: pars), NULL when there are none
pm_bayes_par <- function(model, names = NULL, regex = NULL) {
  fit <- model$fit
  if (inherits(fit, "MCMCglmm")) {                    # (MCMCglmm: Sol and VCV)
    A <- cbind(as.matrix(fit$Sol), as.matrix(fit$VCV))
    cols <- if (is.null(regex)) intersect(names, colnames(A)) else grep(regex, colnames(A), value = TRUE)
    return(if (length(cols)) A[, cols, drop = FALSE])
  }
  tryCatch(if (inherits(fit, "brmsfit")) {
    if (is.null(regex)) as.matrix(fit, variable = names) else as.matrix(fit, variable = regex, regex = TRUE)
  } else {
    if (is.null(regex)) as.matrix(fit, pars = names) else as.matrix(fit, regex_pars = regex)
  }, error = function(e) NULL)
}

## The random-effect variance components of a brms or rstanarm fit, in one table: the varcomp() name (as the
## frequentist one: "<group>.<a>" for a variance, "<group>.<a>.<b>" for a covariance), the group, the two terms, and
## the draws (columns of 'draws'). rstanarm's groups are matched by name ("g2:g1" for nested ones), never split at
## the first colon.
pm_bayes_re <- function(model, part = NULL) {
  fit <- model$fit
  rows <- list()
  cross <- FALSE
  if (inherits(fit, "MCMCglmm")) {
    # random intercepts named by their grouping factor (random = ~ g); us(1 + x):g gives the full matrix as
    # "a:b.g" (both triangles), idh(1 + x):g the variances as "a.g" (F2, dev/review-bayes-2.md)
    V <- as.matrix(fit$VCV)
    g <- setdiff(colnames(V), "units")
    rf <- fit$Random$formula
    gv <- all.vars(rf)
    # the variance structures used: us() and idh() are read; corg(), corgh(), ante...(), cor() and others have names
    # like us()'s but other meanings (fixed correlations, antedependence parameters), so they stop here
    fn <- setdiff(all.names(rf), c(gv, "~", "+", ":", "(", "1", "-"))
    bad <- setdiff(fn, c("us", "idh"))
    if (length(bad)) {
      stop("predictmeans reads MCMCglmm random intercepts (random = ~ g) and us() / idh() structures; this fit uses ",
           paste0(bad, "()", collapse = ", "), ".", call. = FALSE)
    }
    rows <- list()
    for (k in g) {
      if (k %in% gv) {
        rows[[length(rows) + 1]] <- list(name = paste(k, "(Intercept)", sep = "."), group = k, a = "(Intercept)",
                                         b = "(Intercept)", draws = V[, k])
        next
      }
      m <- regmatches(k, regexec("^(.+)\\.([^.]+)$", k))[[1]]
      if (length(m) != 3 || !m[3] %in% gv) {
        stop("predictmeans reads MCMCglmm random intercepts (random = ~ g) and us() / idh() structures; this fit has ",
             "a term it cannot read (", k, ").", call. = FALSE)
      }
      ab <- strsplit(m[2], ":", fixed = TRUE)[[1]]
      if (length(ab) == 1) ab <- c(ab, ab)
      if (length(ab) != 2) stop("predictmeans cannot read the MCMCglmm random term '", k, "'.", call. = FALSE)
      if (ab[1] != ab[2] && any(vapply(rows, function(r) r$group == m[3] && r$a == ab[2] && r$b == ab[1], NA))) {
        next                                                    # (us(): the other triangle, already stored)
      }
      rows[[length(rows) + 1]] <- list(name = if (ab[1] == ab[2]) paste(m[3], ab[1], sep = ".") else
        paste(m[3], ab[1], ab[2], sep = "."), group = m[3], a = ab[1], b = ab[2], draws = V[, k])
    }
  } else if (inherits(fit, "brmsfit")) {
    A <- pm_bayes_par(model, regex = "^(sd|cor)_")
    if (is.null(A)) return(NULL)
    cf <- function(x) ifelse(x == "Intercept", "(Intercept)", x)
    # the part of each term: "mu", or a distributional parameter (sd_g__sigma_x, sd_g__zi_Intercept); part = NULL
    # keeps every term under its brms name (varcomp()), else the part's terms with the part's prefix removed
    dp <- c(model$dpars, model$cat$dpars)          # (categorical: the class predictors are parts, as muc2)
    part_of <- function(x) {
      hit <- dp[startsWith(x, paste0(dp, "_"))]
      if (length(hit)) hit[1] else "mu"
    }
    term <- function(x) cf(if (is.null(part) || part == "mu") x else sub(paste0("^", part, "_"), "", x))
    for (v in grep("^sd_", colnames(A), value = TRUE)) {
      p <- strsplit(sub("^sd_", "", v), "__", fixed = TRUE)[[1]]
      if (!is.null(part) && part_of(p[2]) != part) next
      rows[[length(rows) + 1]] <- list(name = paste(p[1], cf(p[2]), sep = "."), group = p[1], a = term(p[2]),
                                       b = term(p[2]), draws = A[, v]^2)
    }
    for (v in grep("^cor_", colnames(A), value = TRUE)) {
      p <- strsplit(sub("^cor_", "", v), "__", fixed = TRUE)[[1]]
      if (part_of(p[2]) != part_of(p[3])) cross <- TRUE           # (a correlation between two parts)
      if (!is.null(part) && (part_of(p[2]) != part || part_of(p[3]) != part)) next
      rows[[length(rows) + 1]] <- list(name = paste(p[1], cf(p[3]), cf(p[2]), sep = "."), group = p[1],
                                       a = term(p[3]), b = term(p[2]),
                                       draws = A[, v] * A[, paste0("sd_", p[1], "__", p[2])] *
                                         A[, paste0("sd_", p[1], "__", p[3])])
    }
  } else {
    A <- pm_bayes_par(model, regex = "^Sigma")
    if (is.null(A)) return(NULL)
    groups <- names(fit$glmod$reTrms$cnms)
    groups <- groups[order(-nchar(groups))]
    for (v in grep("^Sigma\\[", colnames(A), value = TRUE)) {
      inner <- sub("^Sigma\\[(.*)\\]$", "\\1", v)
      g <- groups[startsWith(inner, paste0(groups, ":"))][1]
      if (is.na(g)) next
      p <- strsplit(substring(inner, nchar(g) + 2), ",", fixed = TRUE)[[1]]
      rows[[length(rows) + 1]] <- list(name = if (p[1] == p[2]) paste(g, p[1], sep = ".") else paste(g, p[1], p[2], sep = "."),
                                       group = g, a = p[1], b = p[2], draws = A[, v])
    }
  }
  if (!length(rows)) return(if (cross) list(cross = TRUE))
  list(cross = cross, tab = data.frame(name = vapply(rows, `[[`, "", "name"), group = vapply(rows, `[[`, "", "group"),
                        a = vapply(rows, `[[`, "", "a"), b = vapply(rows, `[[`, "", "b"), stringsAsFactors = FALSE),
       draws = do.call(cbind, lapply(rows, `[[`, "draws")))
}

#' @exportS3Method stats::terms pm_bayesfit
terms.pm_bayesfit <- function(x, ...) x$terms
#' @exportS3Method stats::formula pm_bayesfit
formula.pm_bayesfit <- function(x, ...) x$formula
#' @exportS3Method stats::family pm_bayesfit
family.pm_bayesfit <- function(object, ...) object$family
#' @exportS3Method stats::model.frame pm_bayesfit
model.frame.pm_bayesfit <- function(formula, ...) stats::model.frame(formula$terms, formula$data, na.action = stats::na.omit)
#' @exportS3Method stats::nobs pm_bayesfit
nobs.pm_bayesfit <- function(object, ...) nrow(stats::model.frame(object))
#' @exportS3Method pm_coef pm_bayesfit
pm_coef.pm_bayesfit <- function(model, ...) colMeans(model$draws)
#' @exportS3Method pm_vcov pm_bayesfit
pm_vcov.pm_bayesfit <- function(model, ...) stats::cov(model$draws)
#' @exportS3Method pm_basis pm_bayesfit
pm_basis.pm_bayesfit <- function(model, newdata, xlev = NULL, ...) {
  tt <- stats::delete.response(model$terms)
  xl <- c(xlev, model$xlev[setdiff(names(model$xlev), names(xlev))])
  mf <- stats::model.frame(tt, newdata, xlev = xl, na.action = stats::na.pass)
  X <- stats::model.matrix(tt, mf, contrasts.arg = model$contrasts)
  if (isTRUE(model$no_int)) X <- X[, colnames(X) != "(Intercept)", drop = FALSE]
  # (cox(): relative to the data's average linear predictor, as coxph() means: R/adapter-survival.R)
  if (!is.null(model$centre)) X <- sweep(X, 2, model$centre[colnames(X)])
  X
}
#' @exportS3Method pm_contrasts pm_bayesfit
pm_contrasts.pm_bayesfit <- function(model, ...) model$contrasts
#' @exportS3Method pm_linkinv pm_bayesfit
pm_linkinv.pm_bayesfit <- function(model, ...) model$linkinv
#' @exportS3Method pm_data pm_bayesfit
pm_data.pm_bayesfit <- function(model, ...) model$data
#' @rdname pm_draws
#' @export
pm_draws.pm_bayesfit <- function(model, ...) model$draws
#' @rdname pm_draws
#' @export
pm_draws.brmsfit <- function(model, ...) {
  w <- pm_bayes_wrap(model)
  # (mixture: the draws of the first component's coefficients; predictmeans() reads every component itself)
  if (!is.null(w$cat$mixture)) attr(w$draws, "component") <- "mu1 (the first mixture component)"
  w$draws
}
#' @rdname pm_draws
#' @export
pm_draws.stanreg <- function(model, ...) pm_bayes_wrap(model)$draws
#' @rdname pm_draws
#' @export
pm_draws.MCMCglmm <- function(model, ...) as.matrix(model$Sol)[, seq_len(model$Fixed$nfl), drop = FALSE]

## Convergence of the draws of the coefficients: the largest Rhat and the smallest bulk ESS (posterior package), or
## NULL when they cannot be computed
pm_bayes_diag <- function(model) {
  if (!inherits(model, "pm_bayesfit") || !requireNamespace("posterior", quietly = TRUE)) return(NULL)
  tryCatch({
    a <- pm_bayes_chains(model)$array
    s <- posterior::summarise_draws(posterior::as_draws_array(a), "rhat", "ess_bulk", "ess_tail")
    list(rhat = max(s$rhat, na.rm = TRUE), ess = min(s$ess_bulk, s$ess_tail, na.rm = TRUE), chains = dim(a)[2])
  }, error = function(e) NULL)
}

## ---- Tables -------------------------------------------------------------------------------------------------------

## Simultaneous equal-tailed band over the columns of X (Besag et al. 1995): the order statistics k and S + 1 - k
## of every column, with k the largest for which at least 1 - level of the draws lie inside all the columns'
## intervals. Exact for the draws, invariant under monotone transformations, no normal approximation.
pm_bayes_band <- function(X, level) {
  ok <- colSums(is.na(X)) == 0
  out <- matrix(NA_real_, ncol(X), 2)
  if (!any(ok)) return(out)
  Y <- X[, ok, drop = FALSE]
  S <- nrow(Y)
  R <- apply(Y, 2, rank, ties.method = "first")
  srt <- apply(Y, 2, sort)
  # draw s is inside the band of k when k <= min rank and max rank <= S + 1 - k: k <= min(min rank, S + 1 - max rank)
  depth <- pmin(apply(R, 1, min), S + 1 - apply(R, 1, max))
  k <- max(1, sort(depth, decreasing = TRUE)[ceiling((1 - level) * S)])
  out[ok, ] <- cbind(srt[k, ], srt[S + 1 - k, ])
  out
}

## Summaries of draws of comparisons D (S x m): estimate, SD, interval, pd; with 'band' the simultaneous limits;
## with 'rope' (margins) the posterior probability inside them
pm_bayes_compare <- function(D, level, band = FALSE, rope = NULL, families = rep(1L, ncol(D))) {
  out <- cbind(pm_bayes_summary(D, level), pd = pm_bayes_pd(D))
  if (!is.null(rope)) {
    out$p.rope <- apply(D, 2, function(x) if (anyNA(x)) NA_real_ else mean(x > rope[1] & x < rope[2]))
  }
  if (band) {
    lim <- matrix(NA_real_, ncol(D), 2)
    for (f in unique(families)) {
      j <- which(families == f)
      lim[j, ] <- pm_bayes_band(D[, j, drop = FALSE], level)
    }
    out$adj.conf.low <- lim[, 1]
    out$adj.conf.high <- lim[, 2]
  }
  out
}

## Which ratios the pairs have: only when the means are back-transformed by exp (the link or trans = exp): time ratios
## (survival families), ratios of medians (log-normal), else as for any model (pm_ratio_kind(): log, logit)
pm_bayes_ratio_kind <- function(model, opt) {
  exp_scale <- isTRUE(opt$link_scale) || identical(opt$trans, exp)
  if (!inherits(model, "pm_bayesfit")) return(pm_ratio_kind(opt$trans, model, isTRUE(opt$link_scale)))
  if (isTRUE(model$cox)) return(if (exp_scale) "hazard")
  if (!is.null(model$ord)) return(if (identical(model$ord$link, "logit") && model$ord$family == "cumulative") "logit")
  if (!is.null(model$surv)) return(if (exp_scale) "time")
  if (isTRUE(model$lognormal)) return(if (exp_scale) "log")
  pm_ratio_kind(opt$trans, model, isTRUE(opt$link_scale))
}

## exp() of the summaries of a log-scale table: ratios (the median and the limits transform exactly)
pm_bayes_ratio <- function(tab, kind) {
  if (is.null(kind)) return(tab)
  pre <- switch(kind, log = "ratio", logit = "odds.ratio", hazard = "hazard.ratio", time = "time.ratio")
  tab[[pre]] <- exp(tab$estimate)
  tab[[paste0(pre, ".conf.low")]] <- exp(tab$conf.low)
  tab[[paste0(pre, ".conf.high")]] <- exp(tab$conf.high)
  tab
}

## Letters from the simultaneous intervals of the pairs: two means share a letter when the band of their
## difference holds 0 (only with 'adj': pointwise intervals would not make a set of letters that holds jointly)
pm_bayes_letters <- function(pairs, labels) {
  sig <- !is.na(pairs$adj.conf.low) & (pairs$adj.conf.low > 0 | pairs$adj.conf.high < 0)
  P <- matrix(1, length(labels), length(labels), dimnames = list(labels, labels))
  P[cbind(pairs$level1, pairs$level2)] <- P[cbind(pairs$level2, pairs$level1)] <- ifelse(sig, 0, 1)
  as.character(multcompLetters(P, Letters = LETTERS, threshold = 0.5)[labels])
}

## predictmeans() of a Bayesian fit: called after the K matrix is made (pm_estimate())
pm_bayes_means <- function(opt, est) {
  model <- opt$model
  if (!is.null(model$cat$mixture)) return(pm_bayes_mix_means(opt, est))   # (brms mixture())
  if (!is.null(model$cat)) return(pm_bayes_cat_means(opt, est))      # (brms categorical: class probabilities)
  draws <- pm_draws(model)
  level <- opt$slevel
  if (!is.null(opt$permlist)) stop("Permutation tests do not apply to a Bayesian fit.", call. = FALSE)
  if (isTRUE(opt$letter_ci)) warning("'letter_ci' does not apply to a Bayesian fit; ignored.", call. = FALSE)
  K <- est$K
  KK <- est$KK
  flag <- attr(KK, "estimable")
  ok <- if (is.null(flag)) rep(TRUE, nrow(K)) else unname(flag[rownames(K)])
  M <- pm_bayes_lin(draws, K, ok)
  # ordinal: the latent mean x'b - mean(thresholds), as clm and emmeans' latent mode (R/ordinal.R); differences are
  # those of x'b (the class probabilities: pm_bayes_probs(), from the cells)
  thr0 <- if (!is.null(model$ord)) rowMeans(model$ord$thr) else 0
  M <- M - thr0
  # MCMCglmm ordinal: on the standard probit scale (latent sd 1), as clm(link = "probit") and brms: divided by
  # sqrt(1 + units) per draw (MCMCglmm's latent residual sd)
  if (!is.null(model$ord$scale)) M <- M / model$ord$scale
  means <- est$label
  rownames(means) <- NULL
  for (v in names(means)) if (is.matrix(means[[v]])) means[[v]] <- as.vector(means[[v]])
  means <- cbind(means, pm_bayes_summary(M, level))
  mt <- pm_bayes_mean_type(model, opt$mean_type)
  # the overall mean of a zero-inflated or hurdle model replaces the back-transformed mean of its count part
  back <- if (mt == "overall") {
    if (!isFALSE(opt$bias_adjust) && !isTRUE(opt$bias_adjust)) {
      stop("For a Bayesian fit 'bias_adjust' is TRUE or FALSE.", call. = FALSE)
    }
    pm_bayes_overall_tab(model, draws, est$ctr.matrix$refgrid, match(rownames(K), rownames(KK)), ok, level,
                         isTRUE(opt$bias_adjust))
  } else if (mt %in% c("prob", "mean_class")) {
    list(tab = NULL, label = NULL)                   # (the class probabilities below are the response scale)
  } else pm_bayes_back(opt, model, M, level, K)
  if (!is.null(back$tab)) means <- cbind(means, back$tab)
  if (is.data.frame(est$ndf)) {
    key <- function(df) do.call(paste, c(lapply(df[opt$vars], as.character), sep = "\r"))
    means$n <- est$ndf$Freq[match(key(means), key(est$ndf))]
  }
  means$estimable <- ok
  # pairs: within each level of 'atvar' when given (the families), all pairs otherwise
  pairs <- NULL
  n <- nrow(K)
  band <- !identical(opt$adj, "none")
  rope <- pm_equiv_margins(opt$equivalence)
  if (n > 1 && isTRUE(opt$compare)) {
    pp <- pm_pair_index(n)
    by <- if (!is.null(opt$atvar)) do.call(paste, c(lapply(means[opt$atvar], as.character), sep = " : "))
    keep <- if (is.null(by)) rep(TRUE, length(pp$i)) else by[pp$i] == by[pp$j]
    C <- pm_pair_matrix(n)[keep, , drop = FALSE]
    colnames(C) <- rownames(K)
    cr <- pm_common_rows(est$ctr.matrix$empty_cells, C, C %*% K, colnames(K))     # (R/empty-cells.R)
    # (overall means: the log of the ratio of the two overall means, so pd, the band and the letters are theirs)
    D <- if (mt == "overall") pm_bayes_overall_pairs(back, back$draws, pp$j[keep], pp$i[keep], cr) else
      pm_bayes_lin(draws, structure(cr$L, dimnames = list(NULL, colnames(K))), !cr$na)
    if (!is.null(model$ord$scale) && mt != "overall") D <- D / model$ord$scale    # (MCMCglmm ordinal, as the means)
    fam <- if (is.null(by)) rep(1L, ncol(D)) else match(by[pp$j[keep]], unique(by))
    pairs <- data.frame(level1 = rownames(K)[pp$j[keep]], level2 = rownames(K)[pp$i[keep]], stringsAsFactors = FALSE)
    if (!is.null(by)) pairs$by <- by[pp$j[keep]]
    if (any(cr$sub)) pairs$over <- cr$over
    pairs <- cbind(pairs, pm_bayes_compare(D, level, band = band, rope = rope, families = fam))
    pairs <- pm_bayes_ratio(pairs, if (mt == "overall") "log" else pm_bayes_ratio_kind(model, opt))
    if (identical(pm_bayes_ratio_kind(model, opt), "time") && model$surv != "lognormal") {
      pairs <- cbind(pairs, pm_bayes_hr(model, D, level))
    }
    if (band) {
      grp <- rep(NA_character_, n)
      for (f in unique(fam)) {
        idx <- sort(unique(c(pp$j[keep][fam == f], pp$i[keep][fam == f])))
        grp[idx] <- pm_bayes_letters(pairs[fam == f, , drop = FALSE], rownames(K)[idx])
      }
      means$group <- grp
    }
  }
  settings <- pm_bayes_settings(model, opt$modelterm, level, if (band) "simultaneous (Besag et al. 1995)" else "none",
                                opt$atvar, back$label, rope, nrow(draws))
  # the draws, for autoplot(type = "draws") and further use (columns: the rows of means and pairs)
  settings$mean_type <- mt
  settings$bias_adjust <- isTRUE(opt$bias_adjust)
  if (mt == "overall") {
    settings$pairs_scale <- "estimate: log of the ratio of the overall means; ratio: their ratio"
  }
  if (!is.null(model$ord)) settings$scale <- pm_bayes_ord_scale(model)
  out <- structure(list(means = means, pairs = pairs, settings = settings), class = "pm_bayesmeans",
                   draws = list(means = M, pairs = if (!is.null(pairs)) D, response = back$draws))
  # class probabilities or the mean class of a cumulative model, for each mean
  if (mt %in% c("prob", "mean_class")) {
    out$probs <- pm_bayes_probs(model, draws, est$ctr.matrix$refgrid, match(rownames(K), rownames(KK)), ok,
                                means[opt$vars], level, isTRUE(opt$bias_adjust), mt)
  }
  do.call(pm_add_advice, c(list(out), pm_bayes_advice(model, nrow(draws))))
}

## ---- E2: more brms families (cumulative, cox, zero-inflated, hurdle) ----------------------------------------------

## The mean type of a Bayesian result, checked against the family: "overall" for zero-inflated and hurdle models,
## "prob" and "mean_class" for ordinal ones, else "conditional"
pm_bayes_mean_type <- function(model, mean_type) {
  mt <- if (is.null(mean_type)) "conditional" else mean_type
  if (mt == "overall" && is.null(model$zih)) {
    stop("mean_type = \"overall\" is for brms zero-inflated and hurdle models.", call. = FALSE)
  }
  if (mt == "overall" && model$zih$type == "hu" && model$zih$dist %in% c("negbinomial", "lognormal") &&
      is.null(model$zih$aux)) {
    stop("mean_type = \"overall\" of a hurdle_", model$zih$dist, " model needs one ",
         if (model$zih$dist == "negbinomial") "shape" else "sigma", " for all rows (the mean of the non-zero part ",
         "depends on it); here it is modelled by predictors.", call. = FALSE)
  }
  if (mt %in% c("prob", "mean_class") && is.null(model$ord)) {
    stop("mean_type = \"", mt, "\" is for ordinal models (cumulative, sratio, cratio, acat).", call. = FALSE)
  }
  if (!mt %in% c("conditional", "overall", "prob", "mean_class")) {
    stop("mean_type = \"", mt, "\" does not apply to a Bayesian fit.", call. = FALSE)
  }
  mt
}

## The overall mean of a zero-inflated or hurdle model at linear predictor x, for the draws of the cells idx (S x k
## matrix positions), mu = the inverse link of x: zero-inflated (1 - zi) mu; hurdle (1 - hu) E(y | y > 0), the mean
## of the zero-truncated count (Poisson mu / (1 - exp(-mu)); negative binomial mu / (1 - (k / (k + mu))^k)), and for
## the continuous parts lognormal exp(x + sigma^2 / 2), gamma mu. P: zi / hu of each draw and cell (S x k).
pm_bayes_overall_fun <- function(model, P) {
  z <- model$zih
  S <- nrow(P)
  inv <- if (is.null(model$linkinv)) identity else model$linkinv
  structure(function(x, idx) {
    p <- P[idx]
    a <- if (!is.null(z$aux)) z$aux[(idx - 1) %% S + 1]
    mu <- inv(x)
    if (z$type == "zi") return((1 - p) * mu)
    (1 - p) * switch(z$dist,
                     poisson = mu / (-expm1(-mu)),
                     negbinomial = mu / (1 - (a / (a + mu))^a),
                     lognormal = exp(x + a^2 / 2),
                     gamma = mu,
                     stop("hurdle family '", z$dist, "' is not handled.", call. = FALSE))
  }, cells = TRUE)
}

## The table of overall means, as pm_bayes_back()'s result: for each draw the overall mean at every cell of the
## reference grid, then averaged over the cells with the weights of the means (W, Kmatrix()$refgrid): the mean of the
## response over the cells, as glmmTMB's overall means (R/zero-inflation.R) and brms' posterior_epred() averaged over
## the other factors. bias_adjust = TRUE: each cell's mean over the random effects of the draw, those of mu and those
## of zi / hu (independent: the overall mean is (1 - E zi) E mu, and as a product for a hurdle). rows: the rows of W
## that are the means; ok: the estimable means. Also returns the cells' draws (Hc, S x cells) for the pairs.
pm_bayes_overall_tab <- function(model, draws, refgrid, rows, ok, level, bias) {
  if (is.null(refgrid)) stop("The reference grid of the means is needed for mean_type = \"overall\".", call. = FALSE)
  z <- model$zih
  W <- as.matrix(refgrid$W[rows, , drop = FALSE])
  cells <- which(colSums(W[ok, , drop = FALSE]) > 0)
  Xg <- as.matrix(refgrid$basis(refgrid$grid[cells, , drop = FALSE]))[, colnames(draws), drop = FALSE]
  S <- nrow(draws)
  Mg <- draws %*% t(Xg)
  zre <- !is.null(z$part) && !is.null(pm_bayes_re(model, z$type)$tab)       # (random effects in zi / hu)
  if (bias && isTRUE(pm_bayes_re(model)$cross)) {
    stop("bias_adjust = TRUE: the random effects of mu and ", z$type, " are correlated (the |ID| syntax), which ",
         "predictmeans does not integrate; use bias_adjust = FALSE.", call. = FALSE)
  }
  P <- pm_bayes_zi_part(model, refgrid, cells, S, bias)
  h <- pm_bayes_overall_fun(model, P)
  Hc <- if (bias) {
    zv <- pm_bayes_zvar(model, Xg)
    if (is.null(zv) && !zre) stop("bias_adjust = TRUE needs random effects to average over; this fit has none.",
                                  call. = FALSE)
    pm_bayes_popmean(h, Mg, if (is.null(zv)) matrix(0, S, length(cells)) else zv)
  } else matrix(h(as.vector(Mg), seq_along(Mg)), S)
  H <- Hc %*% t(W[, cells, drop = FALSE])
  H[, !ok] <- NA
  tab <- pm_bayes_summary(H, level)
  names(tab) <- c("response", "response.posterior.sd", "response.conf.low", "response.conf.high")
  list(tab = tab, draws = H, cells = cells, Hc = Hc,
       label = list(by = "the overall mean", average = "response",
                    estimate = paste0("posterior median of the overall mean ",
                                      if (z$type == "zi") "(1 - zi) mu" else "(1 - hu) E(y | y > 0)",
                                      if (z$dist == "binomial") " (per trial: a proportion)",
                                      " averaged over the cells of the mean",
                                      if (bias) paste0(" and the random effects of each draw (", if (zre) "mu and " else
                                        "", if (zre) z$type else "mu", ")") else
                                        if (isTRUE(model$random) || zre) " (random effects at zero: a typical cluster)")))
}

## The pairs of overall means, from the draws of each cell (pm_bayes_overall_tab()): the log of the ratio of the two
## overall means for each draw, over all the cells of each mean, or, when the pair is compared on the cells both
## means have (empty cells: cr$W, the comparison's weights over the grid rows), over those cells only. S x pairs.
pm_bayes_overall_pairs <- function(back, H, j, i, cr) {
  D <- log(H[, j, drop = FALSE]) - log(H[, i, drop = FALSE])
  if (any(cr$sub)) {
    Wp <- as.matrix(cr$W[, back$cells, drop = FALSE])
    for (r in which(cr$sub & !cr$na)) {
      D[, r] <- log(back$Hc %*% pmax(Wp[r, ], 0)) - log(back$Hc %*% pmax(-Wp[r, ], 0))
    }
  }
  D[, cr$na] <- NA
  D
}

## zi / hu of each draw at the cells 'cells' of the means' reference grid (S x length(cells)): one parameter, or,
## when modelled by predictors, the inverse link of its linear predictor (bias = TRUE: averaged over the random
## effects of that part, per draw; else at zero). Variables of the zi / hu part that the grid lacks (not in the
## mean's formula): each cell over all their levels (factors, equal weights, as predictmeans averages; zi / hu
## averaged as a probability) or at their mean (covariates)
pm_bayes_zi_part <- function(model, refgrid, cells, S, bias = FALSE) {
  pt <- model$zih$part
  if (is.null(pt)) return(matrix(model$zih$p, S, length(cells)))
  tt <- stats::delete.response(stats::terms(pt$formula))
  grid <- refgrid$grid[cells, , drop = FALSE]
  miss <- setdiff(all.vars(tt), names(grid))
  d <- model$data
  lv <- lapply(miss, function(v) if (is.numeric(d[[v]])) mean(d[[v]], na.rm = TRUE) else
    factor(levels(factor(d[[v]])), levels = levels(factor(d[[v]]))))
  names(lv) <- miss
  ex <- if (length(miss)) expand.grid(lv, KEEP.OUT.ATTRS = FALSE, stringsAsFactors = FALSE) else data.frame(row.names = 1)
  big <- grid[rep(seq_len(nrow(grid)), each = nrow(ex)), , drop = FALSE]
  if (length(miss)) big <- cbind(big, ex[rep(seq_len(nrow(ex)), nrow(grid)), , drop = FALSE])
  xl <- c(model$xlev, lapply(d[intersect(miss, names(d))], function(z) if (!is.numeric(z)) levels(factor(z))))
  xl <- Filter(Negate(is.null), xl[intersect(names(xl), all.vars(tt))])
  Xb <- stats::model.matrix(tt, stats::model.frame(tt, big, na.action = stats::na.pass, xlev = xl))
  if (!setequal(colnames(Xb), pt$names)) {
    stop("The coefficients of the ", model$zih$type, " part (", paste(pt$names, collapse = ", "), ") do not match its ",
         "design on the grid.", call. = FALSE)
  }
  Xb <- Xb[, pt$names, drop = FALSE]
  Zb <- pt$draws %*% t(Xb)
  zv <- if (bias) pm_bayes_zvar(model, Xb, part = model$zih$type)
  Pb <- if (is.null(zv)) pt$linkinv(Zb) else pm_bayes_popmean(pt$linkinv, Zb, zv)
  t(rowsum(t(Pb), rep(seq_len(nrow(grid)), each = nrow(ex)))) / nrow(ex)
}


## brms categorical(): a mean is one probability per class, so only predictmeans() handles it (the other front ends
## would use one class predictor's draws); one check for all of them
pm_bayes_cat_refuse <- function(model, what) {
  m <- if (inherits(model, "brmsfit")) tryCatch(pm_bayes_wrap(model), error = function(e) NULL) else model
  if (inherits(m, "pm_bayesfit") && !is.null(m$cat)) {
    if (!is.null(m$cat$mixture)) {
      stop(what, " is not available for brms mixture() fits (a mean is a mixture of components); use predictmeans().",
           call. = FALSE)
    }
    stop(what, " is not available for brms categorical() fits (a mean is one probability per class); use ",
         "predictmeans(), whose pairs compare each class.", call. = FALSE)
  }
  invisible(NULL)
}
## ---- F5: brms mixture() (dev/review-bayes-2.md) ----------------------------------------------------------------

## The mean of one mixture component at linear predictor x (S x cells), its family's mean on the response scale;
## aux: the draws of its sigma / shape / phi where the mean needs them
pm_bayes_mix_mean <- function(family, link, x, aux) {
  inv <- stats::make.link(link)$linkinv
  switch(family,
         lognormal = exp(x + aux^2 / 2),
         weibull = exp(x),                                  # (brms: mu is the mean)
         inv(x))
}

## predictmeans() of a brms mixture() fit. mean_type = "overall" (the default here): the overall mean
## sum_k theta_k E_k per draw at each cell of the reference grid, averaged over the cells of the mean (as
## posterior_epred()); it does not depend on the components' labels. mean_type = "conditional": the mean of each
## component (the component a factor of the means), only for ordered components (brms order = "mu", the default for one
## family), since labels can switch between chains otherwise. Random effects at zero (a typical cluster).
pm_bayes_mix_means <- function(opt, est) {
  model <- opt$model
  mf <- model$cat$mixture
  mt <- if (isTRUE(opt$mean_type_default) || is.null(opt$mean_type)) "overall" else opt$mean_type
  if (!mt %in% c("overall", "conditional")) {
    stop("mean_type = \"", mt, "\" does not apply to a brms mixture() fit; use \"overall\" (the default) or ",
         "\"conditional\" (the mean of each component).", call. = FALSE)
  }
  if (mt == "conditional" && !mf$ordered) {
    stop("The components of this mixture are not ordered (order = \"none\"), so their labels can switch between ",
         "chains and the mean of each component is not identified; use mean_type = \"overall\", or refit with ",
         "order = \"mu\".", call. = FALSE)
  }
  if (isTRUE(opt$bias_adjust)) {
    stop("'bias_adjust' is not available for brms mixture() fits (the means are those of a typical cluster).",
         call. = FALSE)
  }
  if (!is.null(opt$permlist)) stop("Permutation tests do not apply to a Bayesian fit.", call. = FALSE)
  level <- opt$slevel
  K <- est$K
  KK <- est$KK
  flag <- attr(KK, "estimable")
  ok <- if (is.null(flag)) rep(TRUE, nrow(K)) else unname(flag[rownames(K)])
  if (!all(ok)) stop("Means over empty or aliased cells cannot be estimated for brms mixture() fits.", call. = FALSE)
  n <- nrow(K)
  draws <- model$cat$draws
  S <- nrow(draws[[1]])
  rg <- est$ctr.matrix$refgrid
  W <- as.matrix(rg$W[match(rownames(K), rownames(KK)), , drop = FALSE])
  cells <- which(colSums(W != 0) > 0)
  Xg <- as.matrix(rg$basis(rg$grid[cells, , drop = FALSE]))[, colnames(draws[[1]]), drop = FALSE]
  Wc <- t(W[, cells, drop = FALSE])
  # the mean of each component at each cell (S x cells), then averaged over the cells of each mean
  Ec <- lapply(seq_along(draws), function(k) {
    pm_bayes_mix_mean(mf$families[k], mf$links[k], draws[[k]] %*% t(Xg), mf$aux[[k]])
  })
  lab0 <- est$label
  rownames(lab0) <- NULL
  for (v in names(lab0)) if (is.matrix(lab0[[v]])) lab0[[v]] <- as.vector(lab0[[v]])
  if (mt == "overall") {
    H <- Reduce(`+`, lapply(seq_along(Ec), function(k) mf$theta[, k] * Ec[[k]])) %*% Wc
    means <- cbind(lab0, pm_bayes_summary(H, level))
    keys <- seq_len(n)
    by0 <- if (!is.null(opt$atvar)) do.call(paste, c(lapply(lab0[opt$atvar], as.character), sep = " : "))
    var <- NULL
  } else {
    H <- do.call(cbind, lapply(Ec, function(e) e %*% Wc))
    var <- "component"
    means <- lab0[rep(seq_len(n), length(Ec)), , drop = FALSE]
    means[[var]] <- factor(rep(seq_along(Ec), each = n))
    means <- cbind(means, pm_bayes_summary(H, level))
    th <- pm_bayes_summary(mf$theta, level)
    means$theta <- rep(th$estimate, each = n)
    by0 <- NULL
  }
  if (is.data.frame(est$ndf)) {
    key <- function(df) do.call(paste, c(lapply(df[opt$vars], as.character), sep = "\r"))
    means$n <- est$ndf$Freq[match(key(means), key(est$ndf))]
  }
  rownames(means) <- NULL
  pairs <- NULL
  D <- NULL
  band <- !identical(opt$adj, "none")
  rope <- pm_equiv_margins(opt$equivalence)
  if (n > 1 && isTRUE(opt$compare)) {
    pp <- pm_pair_index(n)
    keep <- if (is.null(by0)) rep(TRUE, length(pp$i)) else by0[pp$i] == by0[pp$j]
    ii <- pp$i[keep]
    jj <- pp$j[keep]
    nb <- ncol(H) / n
    D <- do.call(cbind, lapply(seq_len(nb), function(c0) H[, (c0 - 1) * n + jj, drop = FALSE] -
                                 H[, (c0 - 1) * n + ii, drop = FALSE]))
    rn <- rownames(K)
    pairs <- data.frame(level1 = rep(rn[jj], nb), level2 = rep(rn[ii], nb), stringsAsFactors = FALSE)
    byp <- if (!is.null(var)) paste0(var, " = ", rep(seq_len(nb), each = length(ii))) else
      if (!is.null(by0)) by0[jj]
    if (!is.null(byp)) pairs$by <- byp
    fam <- if (is.null(byp)) rep(1L, ncol(D)) else match(byp, unique(byp))
    pairs <- cbind(pairs, pm_bayes_compare(D, level, band = band, rope = rope, families = fam))
  }
  settings <- pm_bayes_settings(model, opt$modelterm, level, if (band) "simultaneous (Besag et al. 1995)" else "none",
                                c(var, opt$atvar), NULL, rope, S)
  settings$mean_type <- mt
  settings$scale <- if (mt == "overall") {
    paste0("overall mean of the mixture sum_k theta_k E_k (components: ", paste(mf$families, collapse = ", "),
           "), per draw at each cell, averaged over the cells of the mean",
           if (isTRUE(model$random)) " (random effects at zero: a typical cluster)", "; pairs: differences")
  } else {
    paste0("mean of each mixture component (column 'component'; brms orders the components by their intercepts, ",
           "order = \"mu\", which fixes their labels; theta: its posterior median mixing proportion), averaged over ",
           "the cells of the mean; pairs within a component")
  }
  out <- structure(list(means = means, pairs = pairs, settings = settings), class = "pm_bayesmeans",
                   draws = list(means = H, pairs = D))
  do.call(pm_add_advice, c(list(out), pm_bayes_advice(model, S)))
}

## ---- F1: brms categorical() (dev/review-bayes-2.md) ---------------------------------------------------------------

## predictmeans() of a brms categorical fit: the probability of each class at each mean, per draw: the softmax of the
## class predictors (reference class 0) at each cell of the means' reference grid, averaged over the cells of the mean
## with its weights (as posterior_epred() averaged over the other factors; the rule of the class means of multinom
## fits, R/categorical.R). The class is a factor of the means (column named after the response) and the pairs are
## within each class, as for multinom fits. mean_type = "prob" (default): pairs as log odds ratios of the class
## (logit of each probability); "prob_diff": differences of probabilities; "link": the class predictors at the means
## (log(P[class] / P[reference])).
pm_bayes_cat_means <- function(opt, est) {
  model <- opt$model
  cf <- model$cat
  mt <- if (isTRUE(opt$mean_type_default) || is.null(opt$mean_type) || identical(opt$mean_type, "conditional")) "prob" else
    opt$mean_type
  if (!mt %in% c("prob", "prob_diff", "link")) {
    stop("mean_type = \"", mt, "\" does not apply to a brms categorical() fit (a mean is one probability per class); ",
         "use \"prob\" (the default), \"prob_diff\" or \"link\".", call. = FALSE)
  }
  ba <- isTRUE(opt$bias_adjust)
  if (!isFALSE(opt$bias_adjust) && !is.null(opt$bias_adjust) && !ba) {
    stop("For a Bayesian fit 'bias_adjust' is TRUE or FALSE.", call. = FALSE)
  }
  if (ba && mt == "link") {
    stop("'bias_adjust' applies to the class probabilities (mean_type = \"prob\" or \"prob_diff\"), not to the ",
         "class predictors.", call. = FALSE)
  }
  if (!is.null(opt$permlist)) stop("Permutation tests do not apply to a Bayesian fit.", call. = FALSE)
  level <- opt$slevel
  K <- est$K
  KK <- est$KK
  flag <- attr(KK, "estimable")
  ok <- if (is.null(flag)) rep(TRUE, nrow(K)) else unname(flag[rownames(K)])
  if (!all(ok)) {
    stop("Means over empty or aliased cells cannot be estimated for brms categorical() fits; leave out the ",
         "interaction or the empty cells.", call. = FALSE)
  }
  n <- nrow(K)
  S <- nrow(cf$draws[[1]])
  lev <- cf$levels
  others <- setdiff(lev, cf$reference)
  # draws of each class predictor at the means (link) or of each class probability averaged over the cells (prob)
  if (mt == "link") {
    Q <- lapply(cf$draws, function(d) pm_bayes_lin(d, K))
    names(Q) <- paste0("log(P[", others, "]/P[", cf$reference, "])")
  } else {
    rg <- est$ctr.matrix$refgrid
    W <- as.matrix(rg$W[match(rownames(K), rownames(KK)), , drop = FALSE])
    cells <- which(colSums(W != 0) > 0)
    Xg <- as.matrix(rg$basis(rg$grid[cells, , drop = FALSE]))[, colnames(cf$draws[[1]]), drop = FALSE]
    eta <- lapply(cf$draws, function(d) d %*% t(Xg))                       # each S x cells
    Wc <- t(W[, cells, drop = FALSE])
    Pc <- if (ba) pm_bayes_cat_popprob(model, eta, Xg) else pm_bayes_softmax(eta)   # (classes: S x cells each)
    Q <- lapply(Pc, function(p) p %*% Wc)
    names(Q) <- lev
  }
  cls <- names(Q)
  M <- do.call(cbind, Q)                                                   # S x (n * classes), class by class
  # the labels: the means' factors, then the class
  lab0 <- est$label
  rownames(lab0) <- NULL
  for (v in names(lab0)) if (is.matrix(lab0[[v]])) lab0[[v]] <- as.vector(lab0[[v]])
  var <- pm_bayes_cat_var(model, opt$vars, mt)
  means <- lab0[rep(seq_len(n), length(cls)), , drop = FALSE]
  means[[var]] <- factor(rep(cls, each = n), levels = cls)
  if (mt == "prob") {
    Lg <- stats::qlogis(M)                                                 # (logit scale: pairs as log odds ratios)
    means <- cbind(means, pm_bayes_summary(Lg, level))
    resp <- pm_bayes_summary(M, level)
    names(resp) <- c("response", "response.posterior.sd", "response.conf.low", "response.conf.high")
    means <- cbind(means, resp)
    D0 <- Lg
  } else {
    means <- cbind(means, pm_bayes_summary(M, level))
    D0 <- M
  }
  if (is.data.frame(est$ndf)) {
    key <- function(df) do.call(paste, c(lapply(df[opt$vars], as.character), sep = "\r"))
    means$n <- est$ndf$Freq[match(key(means), key(est$ndf))]
  }
  rownames(means) <- NULL
  # pairs within each class (and each level of the user's atvar)
  pairs <- NULL
  band <- !identical(opt$adj, "none")
  rope <- pm_equiv_margins(opt$equivalence)
  if (n > 1 && isTRUE(opt$compare)) {
    by0 <- if (!is.null(opt$atvar)) do.call(paste, c(lapply(lab0[opt$atvar], as.character), sep = " : "))
    pp <- pm_pair_index(n)
    keep <- if (is.null(by0)) rep(TRUE, length(pp$i)) else by0[pp$i] == by0[pp$j]
    ii <- pp$i[keep]
    jj <- pp$j[keep]
    rn <- rownames(K)
    D <- do.call(cbind, lapply(seq_along(cls), function(c0) D0[, (c0 - 1) * n + jj, drop = FALSE] -
                                 D0[, (c0 - 1) * n + ii, drop = FALSE]))
    byp <- paste0(var, " = ", rep(cls, each = length(ii)))
    if (!is.null(by0)) byp <- paste(byp, by0[rep(jj, length(cls))], sep = " : ")
    pairs <- data.frame(level1 = rep(rn[jj], length(cls)), level2 = rep(rn[ii], length(cls)), by = byp,
                        stringsAsFactors = FALSE)
    fam <- match(byp, unique(byp))
    pairs <- cbind(pairs, pm_bayes_compare(D, level, band = band, rope = rope, families = fam))
    if (mt == "prob") pairs <- pm_bayes_ratio(pairs, "logit")
  }
  settings <- pm_bayes_settings(model, opt$modelterm, level, if (band) "simultaneous (Besag et al. 1995)" else "none",
                                c(var, opt$atvar), NULL, rope, S)
  settings$mean_type <- mt
  settings$bias_adjust <- ba
  settings$scale <- switch(mt,
    prob = paste0("logit of the probability of each class of ", cf$response, " (column '", var, "'), back-",
                  "transformed in 'response': the probabilities of each cell averaged over the cells of the mean",
                  if (ba) " and over the random effects of each draw (the population of clusters)" else
                    if (isTRUE(model$random)) " (random effects at zero: a typical cluster; bias_adjust = TRUE averages over them)",
                  "; pairs within a class: log odds ratios of that class"),
    prob_diff = paste0("probability of each class (column '", var, "'), averaged over the cells of the mean",
                       if (ba) " and the random effects of each draw" else if (isTRUE(model$random)) " (random effects at zero)",
                       "; pairs ",
                       "within a class: differences of probabilities"),
    link = paste0("the class predictors log(P[class] / P[", cf$reference, "]) (column '", var, "'); pairs within a ",
                  "predictor"))
  out <- structure(list(means = means, pairs = pairs, settings = settings), class = "pm_bayesmeans",
                   draws = list(means = D0, pairs = if (!is.null(pairs)) D))
  do.call(pm_add_advice, c(list(out), pm_bayes_advice(model, S)))
}

## Softmax of the class predictors (a list, one S x cells matrix per class other than the reference): the class
## probabilities, reference class first, as a list of S x cells matrices
pm_bayes_softmax <- function(eta) {
  E <- c(list(matrix(0, nrow(eta[[1]]), ncol(eta[[1]]))), eta)
  mx <- Reduce(pmax, E)
  E <- lapply(E, function(e) exp(e - mx))
  tot <- Reduce(`+`, E)
  lapply(E, function(e) e / tot)
}

## bias_adjust = TRUE of a brms categorical fit: each cell's class probabilities averaged over the random effects of
## the draw, the population of clusters. The class predictors' random effects at a cell form a normal vector with
## covariance Sigma (z' Sigma z per pair of predictors, so correlated terms (1 | p | g) are included); the mean of the
## softmax over it by a product Gauss-Hermite rule on its Cholesky factor (21 and 31 points per predictor must agree
## to 1e-6, else an error; closed-form Cholesky over all draws at once for up to 3 classes, a loop over draws beyond;
## the grid has 31^(classes - 1) points, so more than 4 classes stop).
pm_bayes_cat_popprob <- function(model, eta, Xg, rows = NULL) {
  cf <- model$cat
  re <- pm_bayes_re(model)
  if (is.null(re$tab)) stop("bias_adjust = TRUE needs random effects to average over; this fit has none.", call. = FALSE)
  M <- length(eta)
  if (M > 3) {
    stop("bias_adjust = TRUE of a brms categorical() fit is available for up to 4 classes (the average over the ",
         "random effects is a ", M, "-dimensional integral here); use bias_adjust = FALSE.", call. = FALSE)
  }
  S <- nrow(eta[[1]])
  nc <- ncol(eta[[1]])
  # covariance of the M class predictors' random effects at each cell, per draw: S x nc x M x M
  part <- function(x) {
    hit <- cf$dpars[startsWith(x, paste0(cf$dpars, "_"))]
    if (length(hit)) match(hit[1], cf$dpars) else NA_integer_
  }
  zval <- function(term) {
    t0 <- sub("^[^_]+_", "", term)
    if (t0 == "Intercept") return(rep(1, nc))
    if (t0 %in% colnames(Xg)) return(Xg[, t0])
    stop("The random-effect term '", t0, "' is not a column of the fixed-effect design (bias_adjust of a categorical ",
         "fit).", call. = FALSE)
  }
  Sig <- array(0, c(S, nc, M, M))
  for (i in seq_len(nrow(re$tab))) {
    a <- re$tab$a[i]
    b <- re$tab$b[i]
    pa <- part(a)
    pb <- part(b)
    if (is.na(pa) || is.na(pb)) next
    v <- outer(if (is.null(rows)) re$draws[, i] else re$draws[rows, i], zval(a) * zval(b))
    Sig[, , pa, pb] <- Sig[, , pa, pb] + v
    if (pa != pb || a != b) Sig[, , pb, pa] <- Sig[, , pb, pa] + v
  }
  rule <- function(n) {
    g <- pm_gauss_hermite(n)
    Z <- as.matrix(expand.grid(rep(list(g$z), M)))
    w <- apply(as.matrix(expand.grid(rep(list(g$w), M))), 1, prod)
    out <- lapply(seq_len(M + 1), function(k) matrix(0, S, nc))
    for (j in seq_len(nc)) {
      # each draw's Cholesky factor (lower triangle), vectorised over the draws: M = 1 or 2 in closed form
      if (M == 1) {
        L11 <- sqrt(pmax(Sig[, j, 1, 1], 0))
        U <- TRUE
      } else if (M == 2) {
        a11 <- pmax(Sig[, j, 1, 1], 0)
        L11 <- sqrt(a11)
        L21 <- ifelse(L11 > 0, Sig[, j, 2, 1] / L11, 0)
        L22 <- sqrt(pmax(Sig[, j, 2, 2] - L21^2, 0))
        U <- TRUE
      } else {
        U <- NULL
      }
      if (!is.null(U)) {
        # all nodes at once: each class predictor as an S x nodes matrix (eta + the node's random effects)
        e0 <- matrix(vapply(eta, function(e) e[, j], numeric(S)), S)     # S x M
        R <- nrow(Z)
        Ek <- lapply(seq_len(M), function(m) {
          b <- if (M == 1) outer(L11, Z[, 1]) else if (m == 1) outer(L11, Z[, 1]) else
            outer(L21, Z[, 1]) + outer(L22, Z[, 2])
          e0[, m] + b
        })
        mx <- Reduce(pmax, c(list(matrix(0, S, R)), Ek))
        Ex <- c(list(exp(-mx)), lapply(Ek, function(e) exp(e - mx)))
        tot <- Reduce(`+`, Ex)
        for (k in seq_len(M + 1)) out[[k]][, j] <- drop((Ex[[k]] / tot) %*% w)
        next
      }
      for (s in seq_len(S)) {
        C <- matrix(Sig[s, j, , ], M, M)
        L <- tryCatch(t(chol(C)), error = function(e) {
          ev <- eigen(C, symmetric = TRUE)
          ev$vectors %*% diag(sqrt(pmax(ev$values, 0)), M)
        })
        U <- Z %*% t(L)                                   # nodes of the random effects (points x M)
        E <- cbind(0, sweep(U, 2, vapply(eta, function(e) e[s, j], 0), "+"))
        E <- exp(E - apply(E, 1, max))
        p <- colSums(E / rowSums(E) * w)
        for (k in seq_len(M + 1)) out[[k]][s, j] <- p[k]
      }
    }
    out
  }
  # (the mean of a softmax over normal random effects: Gauss-Hermite with 21 and 31 points per class predictor agree
  # to 1e-10 for random-effect SDs near 1 and to 1e-7 at 2.5)
  a <- rule(21)
  b <- rule(31)
  if (max(abs(unlist(a) - unlist(b))) > 1e-6) {
    stop("bias_adjust: the average over the random effects did not converge (random-effect variances too large for ",
         "the quadrature); use bias_adjust = FALSE.", call. = FALSE)
  }
  b
}

## The name of the class column: the response's name (if it is not taken), as pm_cat_carrier()
pm_bayes_cat_var <- function(model, vars, mt) {
  if (mt == "link") return("predictor")
  y <- model$cat$response
  if (is.null(y) || !identical(make.names(y), y)) y <- "class"
  if (y %in% c(vars, "y", "estimate", "response", "n", "by", "level1", "level2")) y <- paste0(y, "_class")
  y
}

## The latent scale of a cumulative model (settings$scale)
pm_bayes_ord_scale <- function(model) {
  paste0("latent mean x'b - mean(thresholds) (", model$ord$family, ", ", model$ord$link,
         if (isTRUE(model$ord$units)) paste0("; MCMCglmm: thresholds with tau_1 = 0, on the standard probit scale ",
                                             "(divided by sqrt(1 + units) per draw); class probabilities of an observation"),
         "); a positive difference: higher classes more likely",
         if (identical(model$ord$link, "logit") && model$ord$family == "cumulative")
           "; exp(difference): the odds ratio of a higher class")
}

## Class probabilities (or the mean class) of an ordinal model at each mean, for each draw: at each cell of the
## means' reference grid (cumulative: P(Y = k) = F(tau_k - eta) - F(tau_(k-1) - eta), tau the draw's thresholds),
## averaged over the cells of the mean with its weights; bias_adjust = TRUE averages each cell over the random effects
## of the draw (the population of clusters), else a typical cluster. rows: the rows of W that are the means
pm_bayes_probs <- function(model, draws, refgrid, rows, ok, lab, level, bias, what) {
  o <- model$ord
  F <- stats::make.link(o$link)$linkinv
  if (is.null(refgrid)) stop("The reference grid of the means is needed for class probabilities.", call. = FALSE)
  # the cells of the means' reference grid: x'b of each draw and cell (the probabilities use x'b itself)
  W <- as.matrix(refgrid$W[rows, , drop = FALSE])
  cells <- which(colSums(W[ok, , drop = FALSE] != 0) > 0)
  Xg <- as.matrix(refgrid$basis(refgrid$grid[cells, , drop = FALSE]))[, colnames(draws), drop = FALSE]
  M <- draws %*% t(Xg)
  S <- nrow(M)
  nk <- ncol(o$thr) + 1
  zv <- if (bias) pm_bayes_zvar(model, Xg, "bias_adjust = TRUE")
  # P(Y = k) at linear predictor x for the draws of cells idx, as brms defines each family: cumulative
  # P(Y <= k) = F(tau_k - eta); sratio P(Y = k | Y >= k) = F(tau_k - eta); cratio P(Y > k | Y >= k) = F(eta - tau_k);
  # acat (logit) log(P(Y = k + 1) / P(Y = k)) = eta - tau_k
  pk <- function(k, x, idx) {
    th <- o$thr[(idx - 1) %% S + 1, , drop = FALSE]
    if (!is.null(o$scale)) {                           # (MCMCglmm ordinal: on the scale sqrt(1 + units))
      sc <- o$scale[(idx - 1) %% S + 1]
      th <- th / sc
      x <- x / sc
    }
    switch(o$family,
           cumulative = (if (k < nk) F(th[, k] - x) else 1) - (if (k > 1) F(th[, k - 1] - x) else 0),
           sratio = (if (k < nk) F(th[, k] - x) else 1) *
             (if (k > 1) Reduce(`*`, lapply(seq_len(k - 1), function(j) 1 - F(th[, j] - x))) else 1),
           cratio = (if (k < nk) 1 - F(x - th[, k]) else 1) *
             (if (k > 1) Reduce(`*`, lapply(seq_len(k - 1), function(j) F(x - th[, j]))) else 1),
           acat = {
             Dm <- x - th                                       # (eta - tau_j, one column per cut point)
             cs <- cbind(0, Dm)
             for (j in seq_len(ncol(cs))[-1]) cs[, j] <- cs[, j - 1] + Dm[, j - 1]
             e <- exp(cs - apply(cs, 1, max))
             e[, k] / rowSums(e)
           })
  }
  # each cell's probabilities, then averaged over the cells of each mean with its weights (as posterior_epred()
  # averaged over the other factors)
  Wc <- t(W[, cells, drop = FALSE])
  P <- lapply(seq_len(nk), function(k) {
    h <- structure(function(x, idx) pk(k, x, idx), cells = TRUE)
    Pc <- if (bias) pm_bayes_popmean(h, M, zv) else matrix(h(as.vector(M), seq_along(M)), S)
    out <- Pc %*% Wc
    out[, !ok] <- NA
    out
  })
  if (what == "mean_class") {
    E <- Reduce(`+`, lapply(seq_len(nk), function(k) k * P[[k]]))
    out <- cbind(lab, pm_bayes_summary(E, level))
  } else {
    out <- do.call(rbind, lapply(seq_len(nk), function(k) {
      cbind(lab, class = o$levels[k], pm_bayes_summary(P[[k]], level))
    }))
    out <- out[order(rep(seq_len(nrow(lab)), nk)), , drop = FALSE]
  }
  rownames(out) <- NULL
  structure(out, what = what, population_average = bias, random = isTRUE(model$random))
}

## The settings of a Bayesian result
pm_bayes_settings <- function(model, modelterm, level, adjust, atvar, back_label, rope, S) {
  list(modelterm = modelterm, level = level, adjust = adjust, atvar = atvar, inference = "Bayesian",
       estimate = "posterior median", interval = "equal-tailed", draws = S, df_method = "none (posterior draws)",
       equivalence = rope, back_transform = back_label, source = "model",
       model_class = if (inherits(model, "pm_bayesfit")) model$class0 else class(model)[1],
       version = as.character(utils::packageVersion("predictmeans")))
}

## Advice of a Bayesian fit (R/advice.R): draws that have not converged, or too few for the limits
pm_bayes_advice <- function(model, S) {
  rows <- list()
  dg <- pm_bayes_diag(model)
  if (!is.null(dg) && (dg$rhat > 1.01 || dg$ess < 400)) {
    rows$conv <- pm_advice("posterior_not_converged", paste0(
      "The draws of the coefficients may not have converged (largest Rhat ", format(round(dg$rhat, 3)),
      ", smallest bulk or tail ESS ", format(round(dg$ess)), "; aim for Rhat <= 1.01 and ESS >= 400): run longer or more ",
      "chains before using these summaries."), "caution")
  }
  if (S < 1000) {
    rows$few <- pm_advice("posterior_few_draws", paste0(
      "Only ", S, " posterior draws: the interval limits (tail quantiles) have a large Monte Carlo error; use at ",
      "least 1,000 (e.g. 4 chains of 500 kept draws)."), "note")
  }
  rows
}

## Back-transformed summaries: the inverse link (or the user's 'trans') of each draw, then summarised. The median
## and the limits are those of the link scale transformed (monotone h); the SD is of the transformed draws.
pm_bayes_back <- function(opt, model, M, level, K) {
  trans <- opt$trans
  ba <- opt$bias_adjust
  if (!is.function(trans) || identical(trans, I)) {
    if (!isFALSE(ba)) warning("'bias_adjust' applies to back-transformed means; ignored.", call. = FALSE)
    return(list(tab = NULL, label = NULL))
  }
  link <- isTRUE(opt$link_scale)
  random <- inherits(model, "pm_bayesfit") && isTRUE(model$random)
  units <- inherits(model, "pm_bayesfit") && !is.null(pm_bayes_var(model)$units)   # (MCMCglmm non-gaussian)
  surv <- if (inherits(model, "pm_bayesfit")) model$surv
  lognormal <- inherits(model, "pm_bayesfit") && isTRUE(model$lognormal)
  from_formula <- grepl("model formula", paste(opt$trans_by, collapse = ""))
  if (!is.null(opt$sigma)) warning("'sigma' does not apply to a Bayesian fit (its draws are used); ignored.", call. = FALSE)
  if (isTRUE(ba)) {
    s2 <- pm_bayes_s2(model, link, K)
    H <- pm_bayes_popmean(trans, M, s2)
    what <- if (!is.null(surv)) {
      paste0("the mean survival time: exp of each draw averaged over the ",
             if (lognormal) "residual variance and the random effects" else "random effects")
    } else if (lognormal) {
      "the mean: exp of each draw averaged over the residual variance and the random effects"
    } else if (link) {
      "the population mean: the inverse link averaged over the random effects of each draw"
    } else {
      "the mean: the back-transformation of each draw averaged over the random effects and the residual variance"
    }
  } else {
    if (!isFALSE(ba)) stop("For a Bayesian fit 'bias_adjust' is TRUE or FALSE (the mean over the random effects is ",
                           "computed for each draw).", call. = FALSE)
    H <- matrix(as.numeric(trans(as.vector(M))), nrow(M))
    what <- paste0(if (!is.null(surv) && link) paste0("the ", if (lognormal) "median" else "mean",
                                                       " survival time, exp of each draw") else
      if (lognormal && link) "the median of the response, exp of each draw" else
      if (link) "the inverse link of each draw" else if (from_formula)
        "the inverse of the response transformation of each draw: the median of the original scale" else
      "'trans' of each draw",
                   if (random) " (random effects at zero: a typical cluster)",
                   if (units) " (the additive overdispersion 'units' at zero: not the mean)",
                   if (random || units || lognormal || from_formula) "; bias_adjust = TRUE gives the mean")
  }
  # (families whose mu is a part of the model: say which)
  if (isFALSE(ba) && link && isTRUE(model$cox)) {
    what <- "the hazard relative to the data's average linear predictor (exp of each draw)"
  } else if (link && !is.null(model$zih)) {
    what <- paste0("the mean of the ", if (model$zih$type == "zi") "count part, without the extra zeros" else
      "untruncated distribution of the non-zero part", " (mu, inverse link of each draw",
      if (isTRUE(ba)) " averaged over the random effects of the draw" else if (random) "; random effects at zero",
      "); mean_type = \"overall\" gives the overall mean")
  }
  tab <- pm_bayes_summary(H, level)
  names(tab) <- c("response", "response.posterior.sd", "response.conf.low", "response.conf.high")
  label <- list(by = if (link) "the inverse link" else "trans", estimate = paste0("posterior median of ", what),
                average = "link")
  list(tab = tab, label = label, draws = H)
}

## The variance of the random effects at each row of K, for each draw: z' Sigma_g z summed over the grouping factors g,
## z the row's values of the terms of g ("(Intercept)": 1, a slope: the design column of the same name; for a mean
## averaged over the cells of a factor, the averaged row: the variance at the link-scale mean). S x nrow(K), or NULL
## without random effects (need: the option that needs them, for the message). (Random intercepts only: the sum of
## their variances in every column.)
pm_bayes_zvar <- function(model, K, need = NULL, part = "mu") {
  re <- pm_bayes_re(model, part)
  if (is.null(re$tab) && !is.null(need)) stop(need, " needs random effects to average over; this fit has none.",
                                               call. = FALSE)
  if (is.null(re$tab)) return(NULL)
  K <- rbind(K)
  # (cox(): K is centred at the data's means, the random slopes act on the variable itself)
  ctr <- if (!is.null(model$centre)) model$centre else numeric(0)
  zval <- function(term) {
    if (term == "(Intercept)") return(rep(1, nrow(K)))
    if (term %in% colnames(K)) return(K[, term] + if (term %in% names(ctr)) ctr[[term]] else 0)
    stop("The random-effect term '", term, "' is not a column of the fixed-effect design, so its value at the means ",
         "is not known: put the same term in the fixed part of the model with the same coding (a factor in ",
         "MCMCglmm us(f):g or idh(f):g is coded without an intercept, unlike the fixed part).", call. = FALSE)
  }
  out <- matrix(0, nrow(re$draws), nrow(K))
  for (i in seq_len(nrow(re$tab))) {
    za <- zval(re$tab$a[i])
    zb <- zval(re$tab$b[i])
    out <- out + outer(re$draws[, i], if (re$tab$a[i] == re$tab$b[i]) za * za else 2 * za * zb)
  }
  out
}

## The variance averaged over by bias_adjust, for each draw and row of K (S x nrow(K)): the variance of the random
## effects at the row (pm_bayes_zvar(): intercepts and slopes), plus the residual variance for a transformed normal or
## a log-normal response
pm_bayes_s2 <- function(model, link, K) {
  v <- pm_bayes_var(model)
  zv <- pm_bayes_zvar(model, K)
  re <- if (is.null(zv)) 0 else zv
  if (link && isTRUE(model$lognormal)) {                 # (log-normal: the mean of y is exp(mu + sigma^2/2))
    if (is.null(v$sigma2)) stop("bias_adjust of a log-normal model needs one sigma for all rows.", call. = FALSE)
    return(v$sigma2 + re)
  }
  if (link) {
    if (!is.null(v$units)) return(v$units + re)        # (MCMCglmm: the additive residual is on the link scale too)
    if (is.null(zv)) stop("bias_adjust: a model without random effects on a link scale needs no adjustment (the ",
                          "inverse link of each draw is already the mean); use bias_adjust = FALSE.", call. = FALSE)
    return(zv)
  }
  if (is.null(v$sigma2)) stop("bias_adjust with 'trans' needs a normal response with a residual SD ('sigma').",
                              call. = FALSE)
  v$sigma2 + re
}

## Draws of the residual variance parameters used by bias_adjust, R2 and survmeans(marginal = TRUE) (the random
## effects: pm_bayes_zvar()): sigma2 (the residual variance of a normal response, or of log y for a log-normal one),
## units (MCMCglmm's additive overdispersion of a non-normal response)
pm_bayes_var <- function(model) {
  out <- list()
  if (inherits(model$fit, "MCMCglmm")) {
    u <- as.numeric(as.matrix(model$fit$VCV)[, "units"])
    if (model$family$family == "gaussian") out$sigma2 <- u else out$units <- u   # (additive overdispersion)
  } else if (model$family$family %in% c("gaussian", "lognormal") && !"sigma" %in% model$dpars) {
    sg <- pm_bayes_par(model, "sigma")
    if (!is.null(sg)) out$sigma2 <- as.numeric(sg)^2
  }
  out
}

## E h(m + s Z), Z standard normal, for every draw (rows of M) with its own s^2, vectorised over the cells:
## Gauss-Hermite with 31 and 61 nodes; where they disagree (a wide s: h has poles near the real line, e.g. plogis,
## and Gauss-Hermite converges slowly), the trapezoid rule in z on [-12, 12] with steps 0.02 and 0.01, which converges
## exponentially for such integrands; the few cells left go to pm_normal_mean() (R/back-transform.R: poles,
## adaptive integration)
## h(x) of a vector, or h(x, idx) when it depends on the cell (idx: positions in M, e.g. a draw's own shape).
pm_bayes_popmean <- function(h, M, s2) {
  s <- matrix(sqrt(s2), nrow(M), ncol(M))           # (s2: one per draw, or one per draw and cell)
  hh <- if (length(formals(h)) >= 2 && !is.null(attr(h, "cells"))) h else function(x, idx) h(x)
  rule <- function(z, w, idx) {
    out <- 0
    for (k in seq_along(z)) out <- out + w[k] * as.numeric(hh(M[idx] + s[idx] * z[k], idx))
    out
  }
  gh <- function(n) { g <- pm_gauss_hermite(n); function(idx) rule(g$z, g$w, idx) }
  tz <- function(step) {
    z <- seq(-12, 12, by = step)
    function(idx) rule(z, step * stats::dnorm(z), idx)
  }
  idx <- which(!is.na(M))
  v <- matrix(NA_real_, nrow(M), ncol(M))
  for (pair in list(list(gh(31), gh(61)), list(tz(0.02), tz(0.01)))) {
    if (!length(idx)) break
    a <- pair[[1]](idx)
    b <- pair[[2]](idx)
    ok <- is.finite(a) & is.finite(b) & abs(a - b) <= 1e-8 * pmax(1, abs(b))
    v[idx[ok]] <- b[ok]
    idx <- idx[!ok]
  }
  for (k in idx) {
    v[k] <- tryCatch(pm_normal_mean(function(x) hh(x, rep(k, length(x))), s[k], "mean")(M[k]), error = function(e) {
      stop("bias_adjust: the mean over the random effects does not exist for some draws (the back-transformation ",
           "has a pole or overflows where the random effects have mass); use bias_adjust = FALSE.", call. = FALSE)
    })
  }
  v
}

#' @exportS3Method print pm_bayesmeans
print.pm_bayesmeans <- function(x, digits = 4, ...) {
  s <- x$settings
  cat("Posterior summaries of the means of '", s$modelterm, "' (", s$model_class, " model, ", s$draws, " draws)\n",
      "Estimate: posterior median; limits: ", (1 - s$level) * 100, "% equal-tailed credible interval; no df\n",
      sep = "")
  if (!is.null(s$scale)) cat("Scale: ", s$scale, "\n", sep = "")
  if (!is.null(s$back_transform)) cat("Response scale: ", s$back_transform$estimate, "\n", sep = "")
  if (!is.null(s$pairs_scale)) cat("Pairs: ", s$pairs_scale, "\n", sep = "")
  cat("\n")
  num <- function(d) { d[] <- lapply(d, function(z) if (is.numeric(z)) signif(z, digits) else z); d }
  print(num(x$means[setdiff(names(x$means), "estimable")]), row.names = FALSE)
  if (!is.null(x$pairs)) {
    cat("\nPairwise differences", if (!is.null(s$atvar)) paste0(" within each level of ", paste(s$atvar, collapse = " and ")),
        " (pd: probability of direction", if (!is.null(s$equivalence)) paste0("; p.rope: posterior probability within (",
        paste(format(s$equivalence), collapse = ", "), ")"), if (s$adjust != "none") "; adj.conf: simultaneous band",
        "):\n", sep = "")
    print(num(x$pairs), row.names = FALSE)
    if ("group" %in% names(x$means)) cat("Means sharing a letter: the simultaneous band of their difference holds 0.\n")
  }
  if (!is.null(x$probs)) {
    cat("\n", if (identical(attr(x$probs, "what"), "mean_class")) "Mean class" else "Class probabilities",
        if (isTRUE(attr(x$probs, "population_average"))) " averaged over the random effects" else
          if (isTRUE(attr(x$probs, "random"))) " (random effects at zero)",
        " at each mean (averaged over the cells of the mean):\n", sep = "")
    print(num(x$probs), row.names = FALSE)
  }
  pm_print_advice(x)
  invisible(x)
}

#' @exportS3Method generics::tidy pm_bayesmeans
tidy.pm_bayesmeans <- function(x, what = c("means", "pairs", "probs"), ...) x[[match.arg(what)]]
#' @exportS3Method as.data.frame pm_bayesmeans
as.data.frame.pm_bayesmeans <- function(x, row.names = NULL, optional = FALSE, what = c("means", "pairs", "probs"),
                                        ...) {
  x[[match.arg(what)]]
}

#' @rdname autoplot.predictmeans
#' @param what For a Bayesian result with \code{type = "draws"}: the posterior distributions of the \code{"means"}
#'   or of the \code{"pairs"}.
#' @exportS3Method ggplot2::autoplot pm_bayesmeans
autoplot.pm_bayesmeans <- function(object, type = c("means", "pairs", "draws"), scale = c("auto", "model", "response"),
                                   what = c("means", "pairs"), ...) {
  type <- match.arg(type)
  scale <- match.arg(scale)
  s <- object$settings
  if (type == "draws") return(pm_bayes_draws_plot(object, match.arg(what), scale))
  if (type == "pairs") {
    p <- object$pairs
    if (is.null(p)) stop("There are no pairwise comparisons to plot (pairwise = TRUE).", call. = FALSE)
    rcol <- intersect(c("time.ratio", "odds.ratio", "ratio"), names(p))[1]      # (columns that are exp(estimate))
    ratio <- !is.na(rcol) && scale != "model"
    band <- !is.null(p$adj.conf.low)
    f <- if (ratio) exp else identity
    d <- data.frame(est = f(p$estimate), lo = f(if (band) p$adj.conf.low else p$conf.low),
                    hi = f(if (band) p$adj.conf.high else p$conf.high),
                    row = factor(paste(p$level1, if (ratio) "/" else "-", p$level2)))
    d$row <- factor(d$row, levels = rev(unique(d$row)))
    if (!is.null(p$by)) d$by <- p$by
    return(ggplot2::ggplot(d, ggplot2::aes(x = .data$est, y = .data$row)) +
      ggplot2::geom_vline(xintercept = if (ratio) 1 else 0, linetype = pm_style_defaults$ref_linetype,
                        colour = pm_style_defaults$ref, linewidth = pm_style_defaults$ref_linewidth) +
      ggplot2::geom_errorbar(ggplot2::aes(xmin = .data$lo, xmax = .data$hi), width = 0.2, orientation = "y",
                             colour = pm_style_defaults$line, linewidth = 0.8, na.rm = TRUE) +
      ggplot2::geom_point(colour = pm_style_defaults$line, size = 2) +
      (if (ratio) ggplot2::scale_x_log10()) +
      (if (!is.null(d$by)) ggplot2::facet_wrap(~ by, scales = "free_y")) +
      ggplot2::labs(x = if (ratio) paste0(sub("\\.", " ", sub("\\.?ratio$", " ratio", rcol)), " (log axis)") else "difference",
                    y = NULL, title = pm_wrap_title(paste0("Posterior medians of the pairwise ", if (ratio) "ratios" else "differences",
                                                           " for '", s$modelterm, "' with ", (1 - s$level) * 100, "% ",
                                                           if (band) "simultaneous bands" else "credible intervals"), 14)) +
      pm_theme())
  }
  m <- object$means
  resp <- scale != "model" && !is.null(m$response)
  vars <- unlist(strsplit(s$modelterm, ":"))
  m$row <- factor(do.call(paste, c(lapply(m[vars], as.character), sep = ":")), levels = unique(do.call(paste, c(lapply(m[vars], as.character), sep = ":"))))
  m$y <- if (resp) m$response else m$estimate
  m$lo <- if (resp) m$response.conf.low else m$conf.low
  m$hi <- if (resp) m$response.conf.high else m$conf.high
  ggplot2::ggplot(m, ggplot2::aes(x = .data$row, y = .data$y)) +
    ggplot2::geom_errorbar(ggplot2::aes(ymin = .data$lo, ymax = .data$hi), width = 0.15, colour = pm_style_defaults$line, na.rm = TRUE) +
    ggplot2::geom_point(colour = pm_style_defaults$line, size = 2) +
    ggplot2::labs(x = s$modelterm, y = if (resp) "Posterior median (response scale)" else "Posterior median",
                  title = pm_wrap_title(paste0("Posterior medians for '", s$modelterm, "' with ", (1 - s$level) * 100,
                                               "% credible intervals"), 14)) +
    pm_theme()
}

#' @rdname autoplot.predictmeans
#' @exportS3Method plot pm_bayesmeans
plot.pm_bayesmeans <- function(x, ...) pm_plot_via_autoplot(x, ...)

## contrastmeans() of a Bayesian fit: each row of rK (contrasts in coefficient space) from the draws
pm_bayes_contrasts <- function(model, rK, ctrmatrix, cr, modelterm, adj, level, equivalence, joint = FALSE) {
  draws <- pm_draws(model)
  rope <- pm_equiv_margins(equivalence)
  band <- !identical(adj, "none") && nrow(rK) > 1
  D <- pm_bayes_lin(draws, structure(rK, dimnames = list(NULL, colnames(rK))), !cr$na)
  cn <- if (is.null(rownames(ctrmatrix))) paste("contrast", seq_len(nrow(ctrmatrix))) else rownames(ctrmatrix)
  tab <- cbind(data.frame(contrast = cn, stringsAsFactors = FALSE),
               pm_bayes_compare(D, level, band = band, rope = rope))
  if (any(cr$sub)) tab$over <- cr$over
  settings <- pm_bayes_settings(model, modelterm, level, if (band) "simultaneous (Besag et al. 1995)" else "none",
                                NULL, NULL, rope, nrow(draws))
  out <- structure(list(contrasts = tab, settings = settings), class = "pm_bayescontrasts")
  if (joint) {                                   # (the posterior region through 0 of all the contrasts)
    if (any(cr$na)) stop("A contrast has no cells in common: no joint region.", call. = FALSE)
    j <- pm_bayes_joint(draws, structure(rK, dimnames = list(NULL, colnames(rK))))
    out$joint <- data.frame(df1 = j[1], d2 = j[2], p.contour = j[3])
  }
  do.call(pm_add_advice, c(list(out), pm_bayes_advice(model, nrow(draws))))
}

#' @exportS3Method print pm_bayescontrasts
print.pm_bayescontrasts <- function(x, digits = 4, ...) {
  s <- x$settings
  cat("Posterior summaries of contrasts of '", s$modelterm, "' (", s$model_class, " model, ", s$draws, " draws)\n",
      "Estimate: posterior median; limits: ", (1 - s$level) * 100, "% equal-tailed credible interval",
      if (s$adjust != "none") "; adj.conf: simultaneous band", "; pd: probability of direction\n\n", sep = "")
  d <- x$contrasts
  d[] <- lapply(d, function(z) if (is.numeric(z)) signif(z, digits) else z)
  print(d, row.names = FALSE)
  if (!is.null(x$joint)) {
    cat("\nJoint: the posterior region through 0 (p.contour: (b + 1) / (S + 1), b of the S draws at least as far ",
        "from the posterior mean as 0; smallest possible ", signif(1 / (s$draws + 1), 2), ")\n", sep = "")
    print(signif(x$joint, digits), row.names = FALSE)
  }
  pm_print_advice(x)
  invisible(x)
}
#' @exportS3Method generics::tidy pm_bayescontrasts
tidy.pm_bayescontrasts <- function(x, what = c("contrasts", "joint"), ...) x[[match.arg(what)]]
#' @exportS3Method as.data.frame pm_bayescontrasts
as.data.frame.pm_bayescontrasts <- function(x, row.names = NULL, optional = FALSE, what = c("contrasts", "joint"),
                                            ...) {
  x[[match.arg(what)]]
}

## Posterior densities of the means or pairs (autoplot(type = "draws")): one half-eye per row, the density of its
## draws above a line for the credible interval (thick: the central 66%) and a point at the median. Ratios of a
## log-scale pair on a log axis.
pm_bayes_draws_plot <- function(object, what, scale) {
  s <- object$settings
  dr <- attr(object, "draws")
  tab <- object[[what]]
  if (is.null(tab) || is.null(dr[[what]])) stop("There are no ", what, " to plot (pairwise = TRUE for pairs).", call. = FALSE)
  resp <- what == "means" && scale == "response" || (what == "means" && scale == "auto" && !is.null(dr$response))
  X <- if (resp) dr$response else dr[[what]]
  rcol <- intersect(c("time.ratio", "odds.ratio", "ratio"), names(tab))[1]    # (columns that are exp(estimate))
  ratio <- what == "pairs" && scale != "model" && !is.na(rcol)
  if (ratio) X <- exp(X)
  vars <- unlist(strsplit(s$modelterm, ":"))
  lab <- if (what == "means") do.call(paste, c(lapply(tab[vars], as.character), sep = ":")) else
    paste(tab$level1, if (ratio) "/" else "-", tab$level2)
  ok <- colSums(is.na(X)) == 0
  tf <- if (ratio) log else identity
  itf <- if (ratio) exp else identity
  dens <- do.call(rbind, lapply(which(ok), function(j) {
    d <- stats::density(tf(X[, j]), n = 256)
    data.frame(row = j, x = itf(d$x), h = d$y / max(d$y) * 0.85)
  }))
  q <- function(p) apply(X[, ok, drop = FALSE], 2, stats::quantile, p, names = FALSE)
  iv <- data.frame(row = which(ok), med = q(0.5), lo = q(s$level / 2), hi = q(1 - s$level / 2), lo66 = q(0.17),
                   hi66 = q(0.83))
  p <- ggplot2::ggplot() +
    ggplot2::geom_ribbon(ggplot2::aes(x = .data$x, ymin = .data$row, ymax = .data$row + .data$h, group = .data$row),
                         data = dens, fill = pm_style_defaults$band, alpha = pm_style_defaults$alpha, colour = NA) +
    ggplot2::geom_segment(ggplot2::aes(x = .data$lo, xend = .data$hi, y = .data$row, yend = .data$row), data = iv,
                          colour = pm_style_defaults$line, linewidth = 0.6) +
    ggplot2::geom_segment(ggplot2::aes(x = .data$lo66, xend = .data$hi66, y = .data$row, yend = .data$row), data = iv,
                          colour = pm_style_defaults$line, linewidth = 1.6) +
    ggplot2::geom_point(ggplot2::aes(x = .data$med, y = .data$row), data = iv, colour = pm_style_defaults$line, size = 2) +
    (if (what == "pairs") ggplot2::geom_vline(xintercept = if (ratio) 1 else 0, linetype = pm_style_defaults$ref_linetype,
                        colour = pm_style_defaults$ref, linewidth = pm_style_defaults$ref_linewidth)) +
    (if (ratio) ggplot2::scale_x_log10()) +
    ggplot2::scale_y_continuous(breaks = seq_along(lab), labels = lab, expand = ggplot2::expansion(add = c(0.3, 0.9))) +
    ggplot2::labs(x = if (what == "pairs") (if (ratio) paste0(sub(".", " ", rcol, fixed = TRUE), " (log axis)") else "difference") else
                    if (resp) "response scale" else "model scale",
                  y = NULL,
                  title = pm_wrap_title(paste0("Posterior distributions of the ", if (what == "pairs") "pairwise ",
                                               if (what == "pairs") (if (ratio) "ratios" else "differences") else "means",
                                               " for '", s$modelterm, "'"), 14),
                  caption = paste0("Point: median; lines: 66% and ", (1 - s$level) * 100, "% equal-tailed intervals")) +
    pm_theme()
  p
}

## ---- D4: variance components and R2 from the draws ------------------------------------------------------------

## Draws of the variance components, named as varcomp() names them, with the residual variance of a normal response
pm_bayes_vc_draws <- function(model) {
  re <- pm_bayes_re(model)
  V <- if (!is.null(re)) structure(re$draws, dimnames = list(NULL, re$tab$name))
  v <- pm_bayes_var(model)
  if (!is.null(v$sigma2) && identical(model$family$family, "gaussian")) V <- cbind(V, residual = v$sigma2)
  V
}

## varcomp() of a Bayesian fit: posterior median, posterior SD and equal-tailed interval of each variance component
pm_bayes_varcomp <- function(model, ci = TRUE, conf_level = 0.95) {
  V <- pm_bayes_vc_draws(model)
  if (is.null(V)) stop("The ", model$class0, " fit has no variance parameters to summarise.", call. = FALSE)
  level <- 1 - conf_level
  s <- pm_bayes_summary(V, level)
  tab <- data.frame(vcov = s$estimate, posterior.sd = s$posterior.sd, row.names = colnames(V))
  if (ci) {
    tab[[paste(format(100 * level / 2), "%")]] <- s$conf.low
    tab[[paste(format(100 * (1 - level / 2)), "%")]] <- s$conf.high
  }
  attr(tab, "draws") <- V
  attr(tab, "note") <- paste0("Posterior medians of ", nrow(V), " draws (", model$class0, "); limits: ", conf_level * 100,
                              "% equal-tailed credible intervals.")
  do.call(pm_add_advice, c(list(tab), pm_bayes_advice(model, nrow(V))))
}

## R2_model() of a Bayesian fit: Nakagawa & Schielzeth's marginal and conditional R2 for each draw (random
## intercepts; gaussian and binomial models, as R2_model(method = "nakagawa")), summarised
pm_bayes_r2 <- function(model, conf_level = 0.95) {
  v <- pm_bayes_var(model)
  fam <- model$family
  if (inherits(model$fit, "MCMCglmm") && fam$family != "gaussian") {
    stop("R2_model() of an MCMCglmm fit is available for gaussian models (the latent-scale R2 of the others would ",
         "need the additive 'units' variance as well).", call. = FALSE)
  }
  var_obs <- if (identical(fam$family, "gaussian")) v$sigma2 else if (identical(fam$family, "binomial") &&
                                                                       !is.null(pm_r2_latent_var(fam$link))) {
    rep(pm_r2_latent_var(fam$link), nrow(model$draws))
  } else {
    stop("R2_model() of a Bayesian fit is available for gaussian and binomial models.", call. = FALSE)
  }
  X <- pm_fb_quiet_contrasts(pm_basis(model, model$data))          # (the rows of the fit, raw variables)
  X <- X[stats::complete.cases(X), , drop = FALSE]
  eta <- model$draws[, colnames(X), drop = FALSE] %*% t(X)          # S x n: the fixed part for each draw
  var_fixed <- apply(eta, 1, stats::var)
  # random slopes as Johnson (2014): the mean over the data rows of z' Sigma z (as R2_model() of lmer)
  zv <- pm_bayes_zvar(model, X)
  var_random <- if (is.null(zv)) 0 else rowMeans(zv)
  tot <- var_fixed + var_random + var_obs
  R <- cbind(Marginal = var_fixed / tot, Conditional = (var_fixed + var_random) / tot)
  tab <- cbind(data.frame(R2 = colnames(R)), pm_bayes_summary(R, 1 - conf_level))
  out <- structure(tab, class = c("pm_bayes_r2", "data.frame"), draws = R, method = "nakagawa", conf_level = conf_level)
  do.call(pm_add_advice, c(list(out), pm_bayes_advice(model, nrow(R))))
}

#' @exportS3Method print pm_bayes_r2
print.pm_bayes_r2 <- function(x, digits = 3, ...) {
  cat("Nakagawa R2 of each posterior draw (", nrow(attr(x, "draws")), " draws): median, posterior SD and ",
      attr(x, "conf_level") * 100, "% equal-tailed interval\n", sep = "")
  y <- as.data.frame(unclass(x))
  y[-1] <- lapply(y[-1], function(z) signif(z, digits))
  print(y, row.names = FALSE)
  pm_print_advice(x)
  invisible(x)
}

## ---- D5: checks and plots of the draws ----------------------------------------------------------------------------

## The draws of the coefficients by chain (iterations x chains x coefficients, named as the design columns), and the
## sampler's divergent transitions
pm_bayes_chains <- function(model) {
  a <- if (inherits(model$fit, "MCMCglmm")) {
    S0 <- as.matrix(model$fit$Sol)[, model$vars, drop = FALSE]
    array(S0, c(nrow(S0), 1, ncol(S0)), dimnames = list(NULL, NULL, model$vars))
  } else if (inherits(model$fit, "brmsfit")) as.array(model$fit, variable = model$vars) else
    as.array(model$fit, pars = model$vars)
  a <- a[, , model$vars, drop = FALSE]
  dimnames(a)[[3]] <- colnames(model$draws)
  sf <- if (inherits(model$fit, "brmsfit")) model$fit$fit else model$fit$stanfit
  div <- if (inherits(model$fit, "MCMCglmm")) NA_integer_ else
    tryCatch(sum(rstan::get_divergent_iterations(sf)), error = function(e) NA_integer_)
  list(array = a, divergent = div)
}

## pm_check() of a Bayesian fit: is the posterior sample good enough to summarise (Rhat, bulk and tail ESS of the
## coefficients, divergent transitions)? The model checks of a frequentist fit (residual patterns) are posterior
## predictive checks here (brms::pp_check(), rstanarm::pp_check()), not done by predictmeans.
pm_bayes_check <- function(model, plot = FALSE) {
  pm_need("posterior", "the checks of Bayesian fits")
  ch <- pm_bayes_chains(model)
  s <- posterior::summarise_draws(posterior::as_draws_array(ch$array), "rhat", "ess_bulk", "ess_tail")
  S <- prod(dim(ch$array)[1:2])
  out <- list()
  add <- function(...) out[[length(out) + 1]] <<- pm_check_row(...)
  i <- which.max(s$rhat)
  add("Fit", "Convergence (Rhat)", paste0("largest ", format(round(s$rhat[i], 3)), " (", s$variable[i], "), ",
                                          dim(ch$array)[2], " chains"),
      note = if (s$rhat[i] > 1.01) "Rhat above 1.01: the chains have not mixed; run longer chains." else "",
      look = s$rhat[i] > 1.01)
  eb <- min(s$ess_bulk)
  et <- min(s$ess_tail)
  add("Fit", "Effective sample size", paste0("smallest bulk ", round(eb), ", tail ", round(et), " of ", S, " draws"),
      note = if (min(eb, et) < 400) "Below 400: medians and limits have a large Monte Carlo error; draw more." else "",
      look = min(eb, et) < 400)
  if (!is.na(ch$divergent)) {
    add("Fit", "Divergent transitions", paste0(ch$divergent, " of ", S),
        note = if (ch$divergent > 0) "The sampler did not explore the whole posterior: raise adapt_delta or reparametrise." else "",
        look = ch$divergent > 0)
  }
  add("Fit", "Model checks", if (inherits(model$fit, "MCMCglmm")) "posterior predictive checks: simulate() of the fit" else
    "posterior predictive checks: pp_check() of brms or rstanarm", info = TRUE)
  res <- pm_check_finish(out, model$fit, stats::nobs(model))
  if (plot) print(pm_bayes_trace(model))
  res
}

## residplot() of a Bayesian fit: the trace of each coefficient by chain, and its density by chain (chains that
## agree overlap)
pm_bayes_trace <- function(model, plot = FALSE) {
  a <- pm_bayes_chains(model)$array
  d <- do.call(rbind, lapply(dimnames(a)[[3]], function(p) {
    data.frame(parameter = p, iteration = rep(seq_len(dim(a)[1]), dim(a)[2]),
               chain = factor(rep(seq_len(dim(a)[2]), each = dim(a)[1])), value = as.vector(a[, , p]))
  }))
  d$parameter <- factor(d$parameter, levels = dimnames(a)[[3]])
  p1 <- ggplot2::ggplot(d, ggplot2::aes(x = .data$iteration, y = .data$value, colour = .data$chain)) +
    ggplot2::geom_line(linewidth = 0.25, alpha = 0.7) +
    ggplot2::facet_wrap(~ parameter, scales = "free_y") +
    ggplot2::guides(colour = "none") + pm_group_scales(pm_style_defaults, nlevels(factor(d$chain)))[[1]] +
    ggplot2::labs(x = "Iteration (after warm-up)", y = NULL, title = "Trace of the coefficients",
                  caption = "One colour per chain: well-mixed chains overlap with no trend") +
    pm_theme()
  p2 <- ggplot2::ggplot(d, ggplot2::aes(x = .data$value, colour = .data$chain)) +
    ggplot2::geom_density(linewidth = 0.5) +
    ggplot2::facet_wrap(~ parameter, scales = "free") +
    ggplot2::guides(colour = "none") + pm_group_scales(pm_style_defaults, nlevels(factor(d$chain)))[[1]] +
    ggplot2::labs(x = NULL, y = "Density", title = "Posterior density of the coefficients by chain",
                  caption = "Chains that agree give the same curve") +
    pm_theme()
  plots <- list(p1, p2)
  if (plot) pm_print_grid(plots)
  invisible(structure(plots, class = c("pm_residplot", "list")))
}

## ---- D6: survival families (brms weibull, lognormal, exponential) ----------------------------------------------

## The draws of the shape (Weibull) or sigma (log-normal) of a brms survival fit; a stop when it is modelled
pm_bayes_dpar <- function(model) {
  if (identical(model$surv, "exponential")) return(rep(1, nrow(model$draws)))
  nm <- if (identical(model$surv, "weibull")) "shape" else "sigma"
  A <- if (!nm %in% model$dpars) pm_bayes_par(model, nm)
  if (is.null(A)) {
    stop("The ", nm, " of this ", model$surv, " model is modelled by predictors: survival quantities need one ", nm,
         " for all rows.", call. = FALSE)
  }
  as.numeric(A)
}

## Hazard ratios of the pairs of a Weibull (or exponential) fit: with a common shape k, the hazard ratio of a
## difference d of log mean times is exp(-k d), per draw (so the uncertainty of k is carried); summarised
pm_bayes_hr <- function(model, D, level) {
  k <- pm_bayes_dpar(model)
  H <- exp(-k * D)
  s <- pm_bayes_summary(H, level)
  data.frame(hazard.ratio = s$estimate, hazard.ratio.conf.low = s$conf.low, hazard.ratio.conf.high = s$conf.high)
}

## S(t) of each draw at log time lt (rows of E: S x k linear predictors, columns: rows of the pattern); par: the shape
## or sigma of each draw. brms: Weibull mu = exp(eta) is the mean, scale lambda = mu / gamma(1 + 1/k); exponential mu
## the mean; log-normal eta the mean of log time.
pm_bayes_surv_s <- function(surv, lt, E, par) {
  switch(surv,
         weibull = exp(-(exp(lt) * gamma(1 + 1 / par) / exp(E))^par),
         exponential = exp(-exp(lt) / exp(E)),
         lognormal = stats::pnorm((lt - E) / par, lower.tail = FALSE))
}

## survmeans() of a brms survival fit: S(t) and the median survival time of each draw at the covariate pattern,
## summarised (posterior median, equal-tailed pointwise limits). marginal = TRUE averages S(t) over the random
## effects of each draw (Gauss-Hermite, 61 nodes): the survival of the population, not of a typical cluster.
pm_bayes_survmeans <- function(model, modelterm, at, times, conf_level, marginal) {
  cox <- isTRUE(model$cox)
  if (is.null(model$surv) && !cox) {
    stop("survmeans() of a Bayesian fit needs a brms weibull(), lognormal(), exponential() or cox() family.",
         call. = FALSE)
  }
  if (!is.numeric(conf_level) || length(conf_level) != 1 || conf_level <= 0 || conf_level >= 1) {
    stop("'conf_level' must be a number between 0 and 1.", call. = FALSE)
  }
  level <- 1 - conf_level
  d <- model$data
  used <- all.vars(stats::delete.response(model$terms))
  pt <- pm_surv_pattern(d, modelterm, used, at)
  X <- pm_fb_quiet_contrasts(pm_basis(model, pt$nd))
  E <- model$draws[, colnames(X), drop = FALSE] %*% t(X)
  S <- nrow(E)
  # the survival function of a cell: closed forms (Weibull, exponential, log-normal) or, for cox(), the spline
  # baseline hazard (pm_bayes_cox_base()); lt: log time of each cell, idx: positions in the S x k matrix
  if (cox) {
    cb <- pm_bayes_cox_base(model)
    E <- E + drop(cb$int + model$draws %*% model$centre[colnames(model$draws)])    # (the full linear predictor)
    hcell <- function(x, idx, lt) {
      H0 <- rowSums(cb$I(exp(lt)) * cb$sb[(idx - 1) %% S + 1, , drop = FALSE])
      out <- exp(-H0 * exp(x))
      # (outside the spline's range: not estimated)
      out[exp(lt) > cb$upper * (1 + 1e-9) | exp(lt) < cb$lower * (1 - 1e-9)] <- NA_real_
      out
    }
  } else {
    par <- pm_bayes_dpar(model)
    hcell <- function(x, idx, lt) pm_bayes_surv_s(model$surv, lt, x, par[(idx - 1) %% S + 1])
  }
  zv <- NULL
  if (isTRUE(marginal)) {
    zv <- pm_bayes_zvar(model, X, "marginal = TRUE")    # (S x k: the random-effect variance at each pattern row)
  }
  # S(t) of each draw and pattern row at log time lt (a number or an S x k matrix): conditional, or averaged over the
  # random effects (the checked quadrature of pm_bayes_popmean())
  all_idx <- seq_along(E)
  Slog <- function(lt) {
    LT <- matrix(lt, S, ncol(E))
    if (is.null(zv)) return(matrix(hcell(as.vector(E), all_idx, as.vector(LT)), S))
    h <- structure(function(x, idx) hcell(x, idx, LT[idx]), cells = TRUE)
    pm_bayes_popmean(h, E, zv)
  }
  Sfun <- function(t) if (t <= 0) matrix(1, S, ncol(E)) else Slog(log(t))
  resp <- all.vars(brms::brmsterms(model$fit$formula)$respform)[1]
  if (is.null(times)) times <- seq(0, max(d[[resp]], na.rm = TRUE), length.out = 101)
  times <- sort(unique(times))
  Sl <- lapply(times, Sfun)                                         # each S x k
  qf <- function(x, p) if (anyNA(x)) NA_real_ else stats::quantile(x, p, names = FALSE)
  curves <- do.call(rbind, lapply(seq_len(ncol(E)), function(j) {
    Sj <- vapply(Sl, function(m) m[, j], numeric(S))               # S x times
    data.frame(pt$levs[rep(j, length(times)), , drop = FALSE], time = times,
               surv = apply(Sj, 2, function(x) if (anyNA(x)) NA_real_ else stats::median(x)),
               conf.low = apply(Sj, 2, qf, level / 2), conf.high = apply(Sj, 2, qf, 1 - level / 2), row.names = NULL)
  }))
  # median survival time of each draw: closed forms when conditional (parametric families); else the root of
  # S(t) = 1/2 on log t by bisection (cox(): within the spline's range, NA when S stays above 1/2 there)
  med <- if (is.null(zv) && !cox) {
    par <- pm_bayes_dpar(model)
    switch(model$surv,
           weibull = exp(E) / gamma(1 + 1 / par) * log(2)^(1 / par),
           exponential = exp(E) * log(2),
           lognormal = exp(E))
  } else {
    top <- if (cox) log(cb$upper) else max(E) + 20
    lo <- matrix(if (cox && cb$lower > 0) log(cb$lower) else min(log(1e-8), min(E) - 20), S, ncol(E))
    hi <- matrix(top, S, ncol(E))
    never <- Slog(top) > 0.5
    for (it in 1:80) {
      mid <- (lo + hi) / 2
      above <- Slog(mid) > 0.5
      lo[above] <- mid[above]
      hi[!above] <- mid[!above]
    }
    m <- exp((lo + hi) / 2)
    m[never] <- NA_real_
    m
  }
  # a draw whose median lies beyond the time range (NA) counts as larger than any time: the quantiles that fall
  # among those draws are NA ("beyond the follow-up"), the others are exact
  qb <- function(x, p) {
    v <- stats::quantile(ifelse(is.na(x), .Machine$double.xmax, x), p, names = FALSE, type = 7)
    if (v > max(x, na.rm = TRUE)) NA_real_ else v
  }
  medians <- data.frame(pt$levs, median = apply(med, 2, qb, 0.5), conf.low = apply(med, 2, qb, level / 2),
                        conf.high = apply(med, 2, qb, 1 - level / 2), row.names = NULL)
  if (anyNA(med)) medians$beyond <- colMeans(is.na(med))     # (the share of draws whose median is beyond the range)
  fam <- if (cox) "cox" else model$surv
  out <- list(curves = curves, medians = medians,
              settings = list(modelterm = modelterm, at = pt$pat, conf_level = conf_level,
                              method = paste0("posterior draws (brms ", fam,
                                              if (!is.null(zv)) "; averaged over the random effects" else
                                                if (isTRUE(model$random)) "; random effects at zero: a typical cluster",
                                              "); posterior medians"),
                              marginal = !is.null(zv), draws = S, model_class = "brmsfit",
                              version = as.character(utils::packageVersion("predictmeans"))))
  class(out) <- "pm_survmeans"
  do.call(pm_add_advice, c(list(out), pm_bayes_advice(model, S)))
}

## The baseline hazard of a brms cox() fit: brms models it with M-splines (splines2), so the cumulative baseline
## hazard is the I-spline basis at t (same knots, degree, boundary) times the draw's spline weights (sbhaz), and
## S(t | x) = exp(-H0(t) exp(eta)), eta with the intercept (checked: brms' log_lik() rebuilt from it). Returns the
## intercept draws, the weight draws, the I-spline basis function and the upper boundary knot.
pm_bayes_cox_base <- function(model) {
  pm_need("splines2", "survival curves of brms cox() fits")
  b <- model$fit$basis$dpars$mu$bhaz$basis_matrix
  if (is.null(b)) stop("The baseline hazard basis of this cox() fit was not found.", call. = FALSE)
  A <- pm_bayes_par(model, regex = "^sbhaz")
  int <- pm_bayes_par(model, "b_Intercept")
  if (is.null(A) || is.null(int)) stop("The baseline hazard draws of this cox() fit were not found.", call. = FALSE)
  a <- attributes(b)
  list(int = as.numeric(int), sb = A, lower = a$Boundary.knots[1], upper = a$Boundary.knots[2],
       I = function(t) unclass(splines2::iSpline(pmin(pmax(t, a$Boundary.knots[1]), a$Boundary.knots[2]), knots = a$knots,
                                                 Boundary.knots = a$Boundary.knots, degree = a$degree,
                                                 intercept = a$intercept))[, , drop = FALSE])
}

## ---- Curves and slopes from the draws (covariatemeans(), pm_slopes()) ----------------------------------------------

## The back-transformation of a curve function, as pm_setup() decides it for predictmeans(): the user's 'trans', else
## the inverse link, else the inverse of a response transformation in the formula (pm_bayes_back() options)
pm_bayes_trans_opt <- function(model, trans, bias_adjust, sigma) {
  link <- pm_link_trans(model)
  if (!is.null(trans)) {
    return(list(trans = trans, link_scale = FALSE, trans_by = "trans", bias_adjust = bias_adjust, sigma = sigma))
  }
  if (!is.null(link)) {
    return(list(trans = link, link_scale = TRUE, trans_by = "the inverse link", bias_adjust = bias_adjust, sigma = sigma))
  }
  rt <- pm_response_trans(model)
  if (!is.null(rt)) {
    message("The response is ", rt$label, ": the fitted lines are back-transformed to the original scale ",
            "(trans = I for the model scale).")
    return(list(trans = rt$fun, link_scale = FALSE, trans_by = "the inverse of the response (the model formula)",
                bias_adjust = bias_adjust, sigma = sigma))
  }
  list(trans = I, link_scale = FALSE, trans_by = NA_character_, bias_adjust = bias_adjust, sigma = sigma)
}

## The settings of a Bayesian curve result (covariatemeans())
pm_bayes_curve_settings <- function(model, modelterm, covariate, level, back, S, ...) {
  c(pm_curve_settings(model, modelterm, covariate, level, "none (posterior draws)", "conditional", back$label, ...),
    list(inference = "Bayesian", estimate = "posterior median", interval = "equal-tailed", draws = S,
         model_class = model$class0))
}

## covariatemeans() of a Bayesian fit: each point of each curve from the draws (KK: K rows in the coefficient
## columns, est: estimable rows); limits pointwise
pm_bayes_curves <- function(model, KK, pltdf, est, vars, covariate, modelterm, level, trans, bias_adjust, sigma,
                            mdf, plot_data, pargs, draw) {
  draws <- pm_draws(model)
  M <- pm_bayes_lin(draws, KK, est)
  opt <- pm_bayes_trans_opt(model, trans, bias_adjust, sigma)
  back <- pm_bayes_back(opt, model, M, level, KK)
  lab_cols <- c(setdiff(intersect(vars, names(pltdf)), covariate), intersect(covariate, names(pltdf)))
  means <- cbind(pltdf[, lab_cols, drop = FALSE], pm_bayes_summary(M, level))
  if (!is.null(back$tab)) means <- cbind(means, back$tab)
  rownames(means) <- NULL
  pred <- pltdf
  pred$Mean <- if (is.null(back$tab)) means$estimate else means$response
  pred$LL <- if (is.null(back$tab)) means$conf.low else means$response.conf.low
  pred$UL <- if (is.null(back$tab)) means$conf.high else means$response.conf.high
  pred$factors <- if (setequal(modelterm, covariate)) factor(1) else factor(do.call(paste, c(pltdf[, vars, drop = FALSE], sep = ":")))
  if (length(covariate) == 1) colnames(pred)[colnames(pred) == covariate] <- "xvar"
  # combinations of factor levels with no data have no curve (as for other fits)
  if (!setequal(modelterm, covariate) && !is.null(mdf) && all(vars %in% names(mdf))) {
    ndf <- data.frame(table(mdf[, vars, drop = FALSE]))
    empty <- do.call(paste, c(ndf[ndf$Freq == 0, vars, drop = FALSE], sep = ":"))
    keep <- !as.character(pred$factors) %in% empty
    pred <- pred[keep, , drop = FALSE]
    means <- means[keep, , drop = FALSE]
    M <- M[, keep, drop = FALSE]
    rownames(means) <- NULL
  }
  settings <- pm_bayes_curve_settings(model, modelterm, covariate, level, back, nrow(draws),
                                      response = pm_response_label_info(model, opt$trans, isTRUE(opt$link_scale),
                                                                        !is.null(back$tab)))
  out <- pm_curve_result(means = means, settings = settings, legacy = list(plt = FALSE, pred_df = pred))
  attr(out, "plot_data") <- plot_data
  attr(out, "draws") <- M
  out <- do.call(pm_add_advice, c(list(out), pm_bayes_advice(model, nrow(draws))))
  pm_curve_add_plot(out, pargs, draw)
}

## covariatemeans(contr = ) of a Bayesian fit: the difference of two curves at each covariate value, from the draws,
## on the model scale (or of the back-transformed curves, contr_scale = "response"); band = "simultaneous": the
## Besag band over the covariate values
pm_bayes_curve_diff <- function(contr, KK, pltdf, vars, covariate, modelterm, model, level, trans, contr_scale, band,
                                bias_adjust, sigma, plot_data, pargs, draw) {
  if (length(covariate) != 1 || setequal(modelterm, covariate)) {
    stop("'contr' compares two levels of 'modelterm' along one covariate.", call. = FALSE)
  }
  lab <- do.call(paste, c(lapply(pltdf[vars], as.character), sep = ":"))
  levs <- unique(lab)
  k <- if (is.numeric(contr)) contr else match(contr, levs)
  if (length(contr) != 2 || anyNA(k) || any(!k %in% seq_along(levs)) || k[1] == k[2]) {
    stop("'contr' must be two different levels of '", modelterm, "': ", paste(levs, collapse = ", "), ".", call. = FALSE)
  }
  x <- pltdf[[covariate]]
  a <- which(lab == levs[k[1]])
  b <- which(lab == levs[k[2]])
  b <- b[match(x[a], x[b])]
  draws <- pm_draws(model)
  opt <- pm_bayes_trans_opt(model, trans, bias_adjust, sigma)
  Ma <- pm_bayes_lin(draws, KK[a, , drop = FALSE])
  Mb <- pm_bayes_lin(draws, KK[b, , drop = FALSE])
  D <- Ma - Mb
  simult <- band == "simultaneous"
  pairs <- cbind(data.frame(level1 = levs[k[1]], level2 = levs[k[2]], stringsAsFactors = FALSE),
                 stats::setNames(data.frame(x[a]), covariate), pm_bayes_compare(D, level, band = simult))
  ba <- pm_bayes_back(opt, model, Ma, level, KK[a, , drop = FALSE])
  if (!is.null(ba$tab)) {
    Hd <- ba$draws - pm_bayes_back(opt, model, Mb, level, KK[b, , drop = FALSE])$draws
    r <- pm_bayes_compare(Hd, level, band = simult)
    names(r) <- paste0("response.", sub("^estimate$", "", names(r)))
    names(r)[names(r) == "response."] <- "response"
    pairs <- cbind(pairs, r[setdiff(names(r), "response.pd")])
    pairs <- pm_bayes_ratio(pairs, pm_bayes_ratio_kind(model, opt))
  }
  rownames(pairs) <- NULL
  settings <- pm_bayes_curve_settings(model, modelterm, covariate, level, ba, nrow(draws), contr = levs[k],
                                      band = if (simult) "simultaneous (Besag et al. 1995)" else "pointwise",
                                      contr_scale = contr_scale)
  out <- pm_curve_result(pairs = pairs, settings = settings, legacy = list(plt = FALSE))
  attr(out, "plot_data") <- plot_data
  attr(out, "draws") <- D
  out <- do.call(pm_add_advice, c(list(out), pm_bayes_advice(model, nrow(draws))))
  pm_curve_add_plot(out, pargs, draw)
}

## pm_slopes() of a Bayesian fit: the slope of each level (rows of L: derivatives of the K rows) and their pairs,
## from the draws; with 'adj', simultaneous bands of the pairs
pm_bayes_slopes <- function(model, L, lab, levs, est_ok, covariate, modelterm, at, level, adj) {
  draws <- pm_draws(model)
  G <- pm_bayes_lin(draws, structure(L, dimnames = list(levs, colnames(L))), est_ok)
  slopes <- cbind(lab, pm_bayes_summary(G, level), pd = pm_bayes_pd(G), estimable = est_ok)
  rownames(slopes) <- NULL
  pairs <- NULL
  n <- ncol(G)
  band <- !identical(adj, "none")
  if (n > 1) {
    pp <- pm_pair_index(n)
    D <- G[, pp$j, drop = FALSE] - G[, pp$i, drop = FALSE]
    if (any(abs(D) > 1e-10 * max(1, abs(G)), na.rm = TRUE)) {
      pairs <- cbind(data.frame(level1 = levs[pp$j], level2 = levs[pp$i], stringsAsFactors = FALSE),
                     pm_bayes_compare(D, level, band = band))
    }
  }
  settings <- c(pm_bayes_settings(model, modelterm, level, if (band) "simultaneous (Besag et al. 1995)" else "none",
                                  NULL, NULL, NULL, nrow(draws)), list(covariate = covariate, at = at))
  out <- structure(list(slopes = slopes, pairs = pairs, settings = settings), class = c("pm_bayesslopes", "pm_slopes"),
                   covariate = covariate, at = at, adjust = adj, draws = G)
  do.call(pm_add_advice, c(list(out), pm_bayes_advice(model, nrow(draws))))
}

#' @exportS3Method print pm_bayesslopes
print.pm_bayesslopes <- function(x, digits = 4, ...) {
  s <- x$settings
  cat("Posterior summaries of the slopes of '", s$covariate, "' by '", s$modelterm, "' (", s$model_class, " model, ",
      s$draws, " draws; at ", s$covariate, " = ", format(signif(s$at, 4)), ")\n",
      "Estimate: posterior median; limits: ", (1 - s$level) * 100, "% equal-tailed credible interval",
      if (s$adjust != "none") "; adj.conf: simultaneous band", "\n\n", sep = "")
  num <- function(d) { d[] <- lapply(d, function(z) if (is.numeric(z)) signif(z, digits) else z); d }
  print(num(x$slopes[setdiff(names(x$slopes), "estimable")]), row.names = FALSE)
  if (!is.null(x$pairs)) {
    cat("\nDifferences between slopes (pd: probability of direction):\n")
    print(num(x$pairs), row.names = FALSE)
  }
  pm_print_advice(x)
  invisible(x)
}

## ---- Joint tests of a Bayesian fit: the posterior region through 0 ------------------------------------------------

## The joint "test" of the rows of L (contrasts in coefficient space) from the draws: the posterior probability of the
## draws at least as far from the posterior mean as 0 is, in the Mahalanobis distance of the posterior covariance
## (Box and Tiao's contour probability for a normal posterior; the smallest highest-density-type region that
## contains 0 has probability 1 - p.contour). For a normal linear model with flat priors it is close to the F test's
## p-value (the posterior of L b is multivariate t), with much data to the Wald test's. Returns c(r, d2 of 0, p.contour); rows of L that are linear combinations of others are dropped.
pm_bayes_joint <- function(draws, L) {
  L <- rbind(L)
  ql <- qr(t(L))
  L <- L[ql$pivot[seq_len(ql$rank)], , drop = FALSE]
  D <- draws[, colnames(L), drop = FALSE] %*% t(L)
  m <- colMeans(D)
  V <- stats::cov(D)
  Dc <- sweep(D, 2, m)
  d2 <- rowSums((Dc %*% solve(V)) * Dc)
  d0 <- drop(m %*% solve(V, m))
  c(nrow(L), d0, (sum(d2 >= d0) + 1) / (length(d2) + 1))     # (0 counted as one more draw: never 0)
}

## ---- F3: MCMCglmm ordinal (dev/review-bayes-2.md) ------------------------------------------------------------------

## The classes and cut points of an MCMCglmm family = "ordinal" fit, as the 'ord' part of a pm_bayesfit (a cumulative
## probit model): P(Y <= k) = pnorm((tau_k - eta) / s), tau_1 = 0 fixed and the others in CP; s = sqrt(1 + units),
## the probit residual plus MCMCglmm's additive 'units' variance (folded in: the probabilities of an observation, the
## maintainer's decision of 2026-12-02; as predict.MCMCglmm). 'scale' holds s per draw.
pm_mcmc_ord <- function(model, data, fe) {
  yr <- stats::model.response(stats::model.frame(stats::update(fe, . ~ 1), data))
  lev <- if (is.factor(yr)) levels(droplevels(yr)) else as.character(sort(unique(yr)))
  cp <- if (is.null(model$CP)) NULL else as.matrix(model$CP)
  if (length(unique(sub("[.][0-9]+$", "", colnames(cp)))) > 1) {
    stop("predictmeans handles MCMCglmm ordinal models with one response.", call. = FALSE)
  }
  thr <- cbind(0, cp)
  if (ncol(thr) != length(lev) - 1) {
    stop("The MCMCglmm ordinal fit has ", ncol(thr), " cut points for ", length(lev), " classes.", call. = FALSE)
  }
  u <- as.numeric(as.matrix(model$VCV)[, "units"])
  # (the latent scale of an ordinal probit model is identified only with 'units' fixed: prior R = list(V = 1, fix = 1))
  if (stats::sd(u) > 1e-8 * max(1, abs(mean(u)))) {
    stop("The 'units' variance of this MCMCglmm ordinal fit is not fixed, so its latent scale is not identified: refit ",
         "with prior = list(R = list(V = 1, fix = 1), ...).", call. = FALSE)
  }
  list(thr = unname(thr), link = "probit", family = "cumulative", levels = lev, scale = sqrt(1 + u),
       units = TRUE)
}

Try the predictmeans package in your browser

Any scripts or data that you put into this service are public.

predictmeans documentation built on Dec. 3, 2026, 5:07 p.m.