R/brms.R

Defines functions brms_stream check_brms_likelihood IJ_se ijse

Documented in ijse IJ_se

#' Infinitesimal jackknife inference for brms models
#'
#' Extract matched draws and likelihood contributions from a \code{brmsfit}
#' object and compute IJ inference with \code{\link{ijse_draws}}.
#'
#' @param fit A fitted \code{brmsfit} object containing posterior draws.
#' @param cluster_var Optional cluster IDs in the order of the likelihood columns
#'   returned by \code{brms::log_lik(fit)}. IDs must refer to the observations
#'   actually used in fitting, after any omissions or subsetting. IDs are not inferred
#'   from the formula. Save them separately: brms can drop unused data columns,
#'   so an absent \code{fit$data$group} is not a safe source of IDs.
#' @param variables Optional exact parameter names. Defaults to parameters starting
#'   with \code{b_}, preserving \code{IJ_se()} behavior.
#' @param transform Optional function applied to the selected draws; see
#'   \code{\link{ijse_draws}}. Select every required input with \code{variables}.
#' @param draw_ids Optional strictly increasing indices of post-warmup draws,
#'   ordered by iteration within chain, then chain. The same indices are passed
#'   to likelihood extraction. Each retained chain requires at least two draws
#'   when \code{diagnostics = "all"}.
#' @param block_size \code{NULL} (default) for ordinary likelihood extraction, or
#'   a positive integer for pointwise streaming. Streaming currently supports
#'   univariate models and requires brms pointwise-likelihood support. Unsupported
#'   models fail explicitly; use \code{NULL} for ordinary extraction.
#' @param save_influence Whether to retain empirical influence values.
#' @param diagnostics One of \code{"all"}, \code{"posterior"}, or \code{"none"};
#'   see \code{\link{ijse_draws}}. The legacy \code{IJ_se()} wrapper uses
#'   \code{"none"} to avoid computing discarded diagnostics.
#'
#' @details MCMC chain diagnostics are retained for the selected or transformed
#'   quantities. The likelihood uses the brms default of conditioning on fitted
#'   group effects. This extraction choice does not establish IJ validity for
#'   arbitrary hierarchical models. For clustered working-independence models,
#'   supply cluster IDs explicitly; they are never inferred from a model formula.
#'
#'   Streaming respects observation permutations in brms prediction metadata.
#'   The tested brms release does not support pointwise evaluation for regression
#'   ARMA models; use ordinary extraction for those models. Covariance ARMA models
#'   are rejected because brms returns conditional LOO densities instead of joint
#'   likelihood factors. Supply one joint likelihood per independent series to
#'   \code{ijse_draws()}. Discrete truncated models also require explicit matrix
#'   input because the backend lower-bound normalization is not validated.
#'   Multivariate streaming is rejected
#'   because response-specific orderings may differ; the default dense path uses
#'   brms's combined likelihood.
#'
#'   Measurement-error predictors require saved latent draws, for example
#'   \code{brms::save_pars(latent = TRUE)} when fitting. Otherwise brms may
#'   resample prediction latents, which do not match the fitted posterior draws.
#'   Even with saved latents, the native likelihood conditions on them; it is not
#'   an observed-data likelihood integrating measurement error. Missing-response
#'   models may return non-finite likelihoods, which are rejected. Use explicitly
#'   derived observed-data likelihoods with \code{ijse_draws()} when appropriate.
#' @return \code{ijse()} returns the structured \code{ijse} object documented
#'   under \code{\link{ijse_draws}}. \code{IJ_se()} returns
#'   the named numeric vector of standard errors, as in previous releases.
#' @seealso \code{\link{ijse_draws}}, \code{\link{summary.ijse}}
#' @section Choosing an interface:
#'   Use \code{ijse()} to retain estimates, both covariance types, intervals,
#'   diagnostics and optional influence. \code{IJ_se()} returns only IJ SEs with
#'   the same pooled formula. Ordinary extraction is the default. A positive
#'   \code{block_size} requests brms pointwise likelihood evaluation; backend
#'   prediction/preparation objects may still be large. This differs from
#'   \code{ijse_draws()}, whose positive block size controls a supplied callback.
#'
#'   Parameter extraction and likelihood extraction share \code{draw_ids}.
#'   Do not manually reorder parameter rows or pass cluster IDs for the original
#'   unfiltered dataset. Keep fitting-row keys with the actual model data and
#'   check \code{clustered}, \code{n_obs}, \code{n_units}, and \code{unit_ids}.
#'   Correct lengths alone cannot identify mismatched scientific units.
#'
#' @examples
#' # Uses an installed synthetic fit: no Stan compilation or new fitting.
#' if (requireNamespace("brms", quietly = TRUE)) {
#'   examples <- readRDS(system.file("extdata", "tutorial",
#'     "median-examples.rds", package = "IJSE"))
#'   fit <- examples$clustered$fit
#'   ids <- examples$clustered$cluster
#'   result <- ijse(fit, cluster_var = ids, save_influence = TRUE)
#'   stopifnot(result$clustered, result$n_units == 30L)
#'   summary(result)
#'   vcov(result)
#'   vcov(result, type = "posterior")
#'   confint(result, parm = "b_x", level = 0.90)
#'   head(result$unit_ids)
#'   stopifnot(isTRUE(all.equal(IJ_se(fit, ids), result$se)))
#'   streamed <- ijse(fit, cluster_var = ids, block_size = 40,
#'                    diagnostics = "none")
#'   stopifnot(isTRUE(all.equal(vcov(streamed), vcov(result))))
#'   prediction <- ijse(fit, cluster_var = ids,
#'     variables = c("b_Intercept", "b_x"),
#'     transform = function(d) {
#'       cbind(median_at_x1 = d[, "b_Intercept"] + d[, "b_x"])
#'     }, diagnostics = "posterior")
#'   coef(prediction)
#' }
#' # For fitting instructions, run vignette("ijse-brms", package = "IJSE").
#' @export
ijse <- function(fit, cluster_var = NULL, variables = NULL, transform = NULL,
                 draw_ids = NULL, block_size = NULL, save_influence = FALSE,
                 diagnostics = c("all", "posterior", "none")) {
  call <- match.call()
  diagnostics <- match.arg(diagnostics)
  if (!inherits(fit, "brmsfit")) {
    stop("The 'fit' argument must be a brmsfit object.", call. = FALSE)
  }
  if (!requireNamespace("brms", quietly = TRUE)) {
    stop("Package 'brms' is required for ijse(fit); use ijse_draws() for matrix inputs.", call. = FALSE)
  }
  check_flag(save_influence, "save_influence")
  if (!is.null(block_size)) block_size <- check_count(block_size, "block_size")
  available <- posterior::variables(fit)
  check_brms_likelihood(fit, available)
  if (is.null(variables)) {
    variables <- available[grepl("^b_", available)]
    if (!length(variables)) {
      stop("No fixed effects parameters ('b_') found in the model.", call. = FALSE)
    }
  }
  variables <- select_names(variables, available, "variables")
  # brms subsets before converting: do not materialize all latent-effect draws.
  array <- posterior::as_draws_array(fit, variable = variables, regex = FALSE)
  chain_id <- rep(seq_len(posterior::nchains(array)),
                   each = posterior::niterations(array))
  draws <- posterior::as_draws_matrix(array)
  if (!is.null(draw_ids)) {
    if (!is.numeric(draw_ids) || is.complex(draw_ids) || !length(draw_ids) ||
        anyNA(draw_ids) || any(!is.finite(draw_ids)) ||
        any(draw_ids != floor(draw_ids)) || any(draw_ids < 1L) ||
        any(draw_ids > nrow(draws)) || is.unsorted(draw_ids, strictly = TRUE)) {
      stop("'draw_ids' must be strictly increasing, unique post-warmup draw indices.", call. = FALSE)
    }
    draws <- draws[draw_ids, , drop = FALSE]
    chain_id <- chain_id[draw_ids]
  }
  # brms likelihood matrices do not carry draw labels. The exact indices and
  # ordering above, rather than invented matrix names, establish correspondence.
  rownames(draws) <- NULL
  ll <- tryCatch(brms::log_lik(fit, draw_ids = draw_ids,
                              pointwise = !is.null(block_size)),
                 error = function(e) {
                   stop("Error extracting log-likelihood from brms: ",
                        conditionMessage(e), call. = FALSE)
                 })
  n_obs <- NULL
  if (!is.null(block_size)) {
    stream <- brms_stream(ll)
    ll <- stream$read
    n_obs <- stream$n_obs
  }
  out <- ijse_draws(draws, ll, cluster_var = cluster_var, variables = variables,
                    transform = transform, n_obs = n_obs,
                    block_size = if (is.null(block_size)) 1000L else block_size,
                    save_influence = save_influence, chain_id = chain_id,
                    diagnostics = diagnostics)
  out$call <- call
  out
}

#' @rdname ijse
#' @export
IJ_se <- function(fit, cluster_var = NULL) {
  ijse(fit, cluster_var = cluster_var, diagnostics = "none")$se
}

# These backend outputs are not matched likelihood factors for the fitted
# posterior. Check formula metadata before extraction or stochastic prediction.
check_brms_likelihood <- function(fit, available = posterior::variables(fit)) {
  terms <- brms::brmsterms(fit$formula)
  responses <- if (inherits(terms, "mvbrmsterms")) terms$terms else list(terms)
  for (response in responses) {
    if (identical(response$family$type, "int") &&
        !is.null(response$adforms$trunc)) {
      stop("Discrete truncated models require explicit likelihoods via ijse_draws(): ",
           "brms lower-bound normalization is not validated for this interface.", call. = FALSE)
    }
    for (predictor in c(response$dpars, response$nlpars)) {
      ac <- predictor$ac
      if (inherits(ac, "formula")) {
        covariance_ar <- function(expr) {
          if (!is.call(expr)) return(FALSE)
          if (as.character(expr[[1L]])[1L] %in% c("ar", "ma", "arma")) {
            return(isTRUE(eval(expr, envir = environment(ac))$cov))
          }
          any(vapply(as.list(expr)[-1L], covariance_ar, logical(1)))
        }
        if (covariance_ar(ac[[2L]])) {
          stop("Covariance ARMA models return conditional LOO densities from brms, ",
               "not joint likelihood factors. Supply joint sampling-unit likelihoods ",
               "to ijse_draws().", call. = FALSE)
        }
      }
      special <- predictor$sp
      # Inspect retained draws, rather than save_pars flags: character-valued
      # selections and manual retention are legitimate brms saving options.
      # With any Xme draws present brms uses its saved-draw path; missing
      # individual terms then fail in backend parameter validation.
      if (length(attr(special, "uni_me")) &&
          !any(grepl("^Xme_", available))) {
        stop("Measurement-error latent draws were not saved. Refit with ",
             "save_pars = brms::save_pars(latent = TRUE), or supply an observed-data ",
             "likelihood to ijse_draws(); resampled prediction latents cannot be ",
             "matched to the posterior draws.", call. = FALSE)
      }
    }
  }
  invisible(NULL)
}

brms_stream <- function(fun) {
  data <- attr(fun, "data")
  prep <- attr(fun, "draws")
  if (!is.function(fun) || !is.data.frame(data) || !"i" %in% names(data) ||
      is.null(prep)) {
    stop("Unsupported brms pointwise metadata; use 'block_size = NULL'.", call. = FALSE)
  }
  if (inherits(prep, "mvbrmsprep")) {
    stop("Multivariate streaming is not supported; use 'block_size = NULL'.", call. = FALSE)
  }
  n <- nrow(data)
  order <- prep$old_order
  if (length(order) && length(order) != n) {
    # Some joint likelihoods return fewer contributions than raw observations.
    stop("Streaming cannot establish observation order for this likelihood; use 'block_size = NULL'.",
         call. = FALSE)
  }
  if (length(order) && (!is.numeric(order) || is.complex(order) ||
      anyNA(order) || any(!is.finite(order)) || any(order != floor(order)) ||
      !identical(sort(as.integer(order)), seq_len(n)))) {
    stop("Invalid brms observation permutation; use 'block_size = NULL'.", call. = FALSE)
  }
  if (!length(order)) order <- seq_len(n)
  read <- function(ii) {
    columns <- lapply(ii, function(i) {
      value <- tryCatch(fun(data_i = data[order[i], , drop = FALSE], draws = prep),
                        error = function(e) {
                          stop("brms pointwise evaluation failed: ", conditionMessage(e),
                               " Use 'block_size = NULL' for ordinary extraction.", call. = FALSE)
                        })
      # Some univariate families (notably categorical) retain an S-by-1
      # matrix for a single observation. Drop only that singleton column;
      # a multi-column response or transposed vector is not interchangeable.
      if (is.matrix(value) && ncol(value) == 1L) value <- value[, 1L]
      if (!is.numeric(value) || is.complex(value) || !is.null(dim(value))) {
        stop("The brms pointwise likelihood must return one numeric vector per observation.", call. = FALSE)
      }
      value
    })
    sizes <- lengths(columns)
    if (length(unique(sizes)) != 1L || sizes[1L] < 2L) {
      stop("Inconsistent brms pointwise likelihood draw counts.", call. = FALSE)
    }
    matrix(unlist(columns, use.names = FALSE), nrow = sizes[1L], ncol = length(ii))
  }
  list(read = read, n_obs = n)
}

Try the IJSE package in your browser

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

IJSE documentation built on Oct. 22, 2026, 5:18 p.m.