R/core.R

Defines functions finish_state add_covariance add_block new_state validate_clusters validate_ids select_names check_flag check_count name_columns numeric_matrix check_row_order ijse_draws

Documented in ijse_draws

#' Infinitesimal jackknife inference from posterior draws
#'
#' Compute sampling covariance of posterior expectations from matched posterior
#' draws and pointwise log likelihoods, with optional cluster aggregation.
#'
#' @param draws A numeric matrix or data frame (draws by parameters), or a
#'   \pkg{posterior} draws object. Rows must correspond exactly to likelihood rows.
#' @param log_lik A finite numeric matrix (draws by observations), or a function
#'   accepting observation indices and returning such a matrix for those columns.
#'   A callback must preserve the requested column order and draw row order.
#' @param cluster_var Optional atomic vector of cluster IDs, in likelihood-column
#'   order. Missing IDs, including used explicit NA factor levels, are rejected.
#'   At least two clusters are required.
#' @param variables Optional character vector of exact parameter names to select
#'   before applying \code{transform}. By default all parameters are selected.
#' @param transform Optional function of the selected plain numeric draw matrix.
#'   Return a numeric
#'   vector, matrix, or data frame with one row per input draw. Named columns are
#'   recommended. Each returned column defines a posterior expectation of interest.
#'   Names on a returned vector are draw-row labels, not a quantity name; they
#'   are preserved and checked against available input labels. Use a one-column
#'   matrix or data frame to name a single transformed quantity.
#' @param n_obs Number of likelihood columns. Required for a likelihood callback.
#' @param block_size Maximum number of likelihood columns requested per callback
#'   block. Already materialized matrices use the compiled dense covariance path.
#' @param save_influence Whether to retain the empirical influence matrix
#'   (parameters by resampling units). Default \code{FALSE}.
#' @param chain_id Optional atomic vector identifying the chain of each draw.
#'   Within each chain, rows must be in iteration order. Inferred for posterior
#'   draws objects unless supplied explicitly. Each chain must have two draws
#'   when computing chain-specific IJ SEs.
#'   Missing chain IDs, including used explicit NA factor levels, are rejected.
#' @param diagnostics One of \code{"all"} (chain-specific IJ SEs and posterior
#'   diagnostics), \code{"posterior"} (R-hat and ESS only), or \code{"none"}.
#'   None of these options changes the pooled IJ estimate.
#'
#' @details Inputs have \eqn{S} posterior-draw rows, \eqn{P} selected or
#'   transformed quantities, and \eqn{N} observation-level likelihood columns.
#'   Supply log likelihoods excluding the prior, rather than a log posterior or
#'   a single joint-likelihood column. At least two draws and two sampling units
#'   are required. \code{variables} is applied before \code{transform}.
#'
#'   For quantity vector \eqn{g(\theta)}, write
#'   \eqn{C_i = \operatorname{Cov}_{\theta\mid y}(g(\theta),\ell_i(\theta))}.
#'   Its estimate uses sample covariance over draws with denominator \eqn{S-1}.
#'   For independent observations, \eqn{K=N} and each unit contribution is
#'   \eqn{C_u=C_i}. For clusters, \eqn{K=J} and
#'   \eqn{C_u=\sum_{i\in u}C_i}. The returned sampling covariance is
#'   \deqn{\widehat V_{\mathrm{IJ}}=
#'     \frac{K}{K-1}\sum_{u=1}^K
#'     (\widehat C_u-\overline C)(\widehat C_u-\overline C)^{\mathsf T}.}
#'   Here \eqn{\overline C} is the average unit contribution. This is the
#'   finite-sample convention used by Ji et al. (2026).
#'
#'   The target is \eqn{E\{g(\theta)\mid y\}}, which can differ from
#'   \eqn{g\{E(\theta\mid y)\}}. Transforms use jointly sampled quantities.
#'   Fixed-reference predictors are supported; extra sampling variation from
#'   estimating the reference distribution is not included. IJ covariance is
#'   sampling covariance of posterior expectations, not posterior draw covariance.
#'   It does not remove estimator bias. Validity depends on sampling units,
#'   likelihood factorization, and model regularity. Cluster aggregation alone
#'   does not validate arbitrary latent-effects models, few clusters, time series,
#'   informative cluster sampling, or multiway dependence.
#'
#' @section Alignment and labels:
#'   Explicit row labels are checked when available on both sides. Names of a
#'   vector returned by \code{transform} are treated as draw-row labels. Automatic
#'   data-frame row numbers are positional. With unlabeled or incorrectly
#'   relabeled inputs, equal dimensions cannot establish correct row alignment.
#'   Labeled callback blocks must also agree with one another, including when
#'   the original draws are unlabeled. The first labeled block establishes that
#'   cross-block reference; unlabeled rows still require the caller's care.
#'   A callback must preserve observation-column order; it cannot be inferred.
#'
#'   Cluster and chain IDs are matched in order of first appearance. Their display
#'   labels use \code{make.unique(as.character(ids))}; distinct numeric IDs can
#'   otherwise print alike. Exact original cluster IDs are in \code{unit_ids},
#'   named by those labels. Exact chain IDs are in \code{diagnostics$chain_ids}
#'   when diagnostics are enabled. Do not parse display labels to reconstruct IDs.
#'
#' @section Diagnostics and memory:
#'   \code{"all"} computes chain-specific IJ SEs when each chain has at least
#'   two draws. R-hat and bulk/tail ESS require equally long chains with at least
#'   four draws each. The metrics describe selected or transformed quantities,
#'   not the precision of all quantity-likelihood covariances. Missing calculations
#'   are \code{NULL}; computed metrics can be \code{NA}, for example for constants.
#'   The chain relative range is \code{(max(SE)-min(SE))/pooled_SE}; it is a
#'   stability check, not a calibrated IJ Monte Carlo SE or a universal pass rule.
#'   For actual MCMC fits, also inspect sampler and nuisance-parameter diagnostics.
#'
#'   \code{block_size} limits callback requests, not storage of a matrix already
#'   supplied. Dense matrices use \code{stats::cov()}. Saved influence uses
#'   \eqn{P\times K} storage; it is off by default. Clustered computations retain
#'   aggregated quantity-by-cluster contributions even when influence is not saved.
#'   Finite inputs can overflow covariance calculations; rescale when requested.
#'
#' @return An \code{ijse} list containing:
#' \describe{
#'   \item{\code{estimate}}{Named vector of \eqn{P} posterior draw means.}
#'   \item{\code{posterior_sd}, \code{posterior_vcov}}{Named posterior sample
#'     SDs and a \eqn{P\times P} posterior sample covariance matrix.}
#'   \item{\code{se}, \code{vcov}}{Named IJ SEs and a \eqn{P\times P} IJ sampling
#'     covariance matrix. Both covariance matrices have quantity dimnames.}
#'   \item{\code{n_draws}, \code{n_obs}, \code{n_units}}{Counts \eqn{S}, \eqn{N},
#'     and \eqn{K}. Without clustering, \code{n_units == n_obs}.}
#'   \item{\code{clustered}}{Whether cluster IDs were supplied. Unique per-row
#'     IDs still set this flag to \code{TRUE}, with observation-equivalent covariance.}
#'   \item{\code{unit_ids}}{Exact original cluster IDs, named by unique display
#'     labels, in first-appearance order; \code{NULL} for independent observations.}
#'   \item{\code{influence}}{\code{NULL} unless requested; otherwise a
#'     \eqn{P\times K} matrix equal to \eqn{K\widehat C_u}, with quantity rows
#'     and unit-label columns. See \code{\link{summary.ijse}} for interpretation.}
#'   \item{\code{diagnostics}}{List with \code{mode}, \code{chain_ids},
#'     \code{chain_se} (chains by quantities), \code{chain_relative_range},
#'     \code{rhat}, \code{ess_bulk}, and \code{ess_tail}. Uncomputed entries are
#'     \code{NULL}. Posterior metrics and relative ranges are named by quantity.}
#'   \item{\code{call}}{The matched function call.}
#' }
#' @references Ji, F., Lee, J., and Rabe-Hesketh, S. (2026).
#'   Valid Standard Errors for Bayesian Quantile Regression With Clustered and
#'   Independent Data. \emph{Journal of Educational and Behavioral Statistics},
#'   51(5). \doi{10.3102/10769986251379738}.
#'   Giordano, R. and Broderick, T. (2024). The Bayesian Infinitesimal Jackknife
#'   for Variance. \doi{10.48550/arXiv.2305.06466}.
#' @seealso \code{\link{ijse}}, \code{\link{summary.ijse}},
#'   \code{\link{IJSE-package}}. Run \code{vignette("ijse", package = "IJSE")}
#'   for a complete executable introduction.
#' @examples
#' set.seed(12)
#' y <- c(-1, 0, 0.5, 1, 2)
#' v <- 1 / (length(y) + 1 / 4)
#' mu <- rnorm(2000, v * sum(y), sqrt(v))
#' draws <- cbind(mu = mu)
#' ll <- vapply(y, function(yi) dnorm(yi, mu, log = TRUE),
#'              numeric(length(mu)))
#' result <- ijse_draws(draws, ll)
#' summary(result)
#' vcov(result)
#' confint(result)
#' ijse_draws(draws, ll,
#'   transform = function(x) cbind(mu_squared = x[, 1]^2))
#' # A callback avoids storing the whole likelihood matrix.
#' ijse_draws(draws, function(i) ll[, i, drop = FALSE],
#'            n_obs = length(y), block_size = 2)
#' @export
ijse_draws <- function(draws, log_lik, cluster_var = NULL, variables = NULL,
                       transform = NULL, n_obs = NULL, block_size = 1000L,
                       save_influence = FALSE, chain_id = NULL,
                       diagnostics = c("all", "posterior", "none")) {
  call <- match.call()
  diagnostic_mode <- match.arg(diagnostics)
  check_flag(save_influence, "save_influence")
  block_size <- check_count(block_size, "block_size")
  if (posterior::is_draws(draws)) {
    if (is.null(chain_id) && diagnostic_mode != "none") {
      # draws_df may contain unequal chain lengths. Read the actual metadata;
      # nchains * niterations is not necessarily the number of retained rows.
      draws <- posterior::as_draws_df(draws)
      chain_id <- draws[[".chain"]]
    }
    draws <- posterior::as_draws_matrix(draws)
  }
  draws <- numeric_matrix(draws, "draws", min_rows = 2L)
  draws <- name_columns(draws, "parameter")
  if (!is.null(variables)) {
    variables <- select_names(variables, colnames(draws), "variables")
    draws <- draws[, variables, drop = FALSE]
  }
  if (!is.null(transform)) {
    if (!is.function(transform)) stop("'transform' must be a function.", call. = FALSE)
    transformed <- tryCatch(transform(draws), error = function(e) {
      stop("Error applying 'transform': ", conditionMessage(e), call. = FALSE)
    })
    if (is.numeric(transformed) && is.null(dim(transformed))) {
      transformed <- matrix(transformed, ncol = 1L,
                            dimnames = list(names(transformed), "quantity"))
    }
    transformed <- numeric_matrix(transformed, "transform result", min_rows = 2L)
    if (nrow(transformed) != nrow(draws)) {
      stop("'transform' must return one row per posterior draw.", call. = FALSE)
    }
    if (!is.null(rownames(draws)) && !is.null(rownames(transformed)) &&
        !identical(rownames(draws), rownames(transformed))) {
      stop("'transform' must preserve posterior draw row order and row names.", call. = FALSE)
    }
    # Transforms preserve row order by contract, even if column operations drop names.
    if (!is.null(rownames(draws))) rownames(transformed) <- rownames(draws)
    draws <- name_columns(transformed, "quantity")
  }
  s <- nrow(draws)
  streaming <- is.function(log_lik)
  if (streaming) {
    n_obs <- check_count(n_obs, "n_obs", minimum = 2L)
    read_block <- log_lik
  } else {
    log_lik <- numeric_matrix(log_lik, "log_lik", min_rows = 2L)
    if (nrow(log_lik) != s) {
      stop("'draws' and 'log_lik' must have the same number of rows.", call. = FALSE)
    }
    if (!is.null(n_obs) && check_count(n_obs, "n_obs", minimum = 2L) != ncol(log_lik)) {
      stop("'n_obs' must equal the number of likelihood columns.", call. = FALSE)
    }
    n_obs <- check_count(ncol(log_lik), "n_obs", minimum = 2L)
    check_row_order(draws, log_lik)
  }
  groups <- validate_clusters(cluster_var, n_obs)
  states <- list(new_state(draws, groups, n_obs, save_influence))
  chain_rows <- list()
  if (!is.null(chain_id)) {
    validate_ids(chain_id, s, "chain_id")
    ids <- unique(chain_id)
    chain_rows <- lapply(ids, function(id) which(chain_id == id))
    if (diagnostic_mode == "all" && any(lengths(chain_rows) < 2L)) {
      stop("Each chain must contain at least two posterior draws.", call. = FALSE)
    }
    names(chain_rows) <- make.unique(as.character(ids))
  }
  state_rows <- if (diagnostic_mode == "all") chain_rows else list()
  for (rows in state_rows) {
      states[[length(states) + 1L]] <- new_state(
        draws[rows, , drop = FALSE], groups, n_obs, FALSE)
  }
  if (!streaming) {
    # cov() reads the existing matrix directly. Slicing an already dense matrix
    # into many blocks can retain avoidable garbage and inflate peak memory.
    ii <- seq_len(n_obs)
    states[[1L]] <- add_covariance(states[[1L]],
                                  stats::cov(states[[1L]]$draws, log_lik), ii, groups)
    for (j in seq_along(state_rows)) {
      states[[j + 1L]] <- add_block(states[[j + 1L]],
                                    log_lik[state_rows[[j]], , drop = FALSE], ii, groups)
    }
  } else {
    row_ids <- rownames(draws)
    for (start in seq.int(1L, n_obs, by = block_size)) {
      ii <- seq.int(start, min(n_obs, start + (as.double(block_size) - 1)))
      block <- tryCatch(read_block(ii), error = function(e) {
        stop("Error evaluating log-likelihood block starting at ", start, ": ",
             conditionMessage(e), call. = FALSE)
      })
      block <- numeric_matrix(block, "log_lik block", min_rows = 2L)
      if (nrow(block) != s || ncol(block) != length(ii)) {
        stop("Each 'log_lik' block must have one row per draw and one column per requested observation.",
             call. = FALSE)
      }
      row_ids <- check_row_order(draws, block, reference = row_ids)
      states[[1L]] <- add_block(states[[1L]], block, ii, groups)
      for (j in seq_along(state_rows)) {
        states[[j + 1L]] <- add_block(states[[j + 1L]],
                                    block[state_rows[[j]], , drop = FALSE], ii, groups)
      }
    }
  }
  answer <- finish_state(states[[1L]], groups, n_obs, save_influence)
  estimate <- colMeans(draws)
  posterior_vcov <- stats::cov(draws)
  posterior_sd <- sqrt(diag(posterior_vcov))
  if (any(!is.finite(posterior_sd))) {
    stop("Posterior standard deviations overflowed; rescale the quantities.", call. = FALSE)
  }
  names(posterior_sd) <- colnames(draws)
  chain_ids <- if (diagnostic_mode != "none" && length(chain_rows)) {
    stats::setNames(ids, names(chain_rows))
  } else NULL
  diagnostics <- list(mode = diagnostic_mode, chain_ids = chain_ids,
                      chain_se = NULL, chain_relative_range = NULL,
                      rhat = NULL, ess_bulk = NULL, ess_tail = NULL)
  if (length(state_rows)) {
    chain_se <- t(matrix(vapply(states[-1L], function(state) {
      sqrt(diag(finish_state(state, groups, n_obs, FALSE)$vcov))
    }, numeric(ncol(draws))), nrow = ncol(draws)))
    dimnames(chain_se) <- list(names(chain_rows), colnames(draws))
    diagnostics$chain_se <- chain_se
    if (length(chain_rows) > 1L) {
      spread <- apply(chain_se, 2L, function(x) diff(range(x)))
      ratio <- spread / answer$se
      ratio[spread == 0 & answer$se == 0] <- 0
      diagnostics$chain_relative_range <- ratio
    }
  }
  if (diagnostic_mode != "none" && length(chain_rows)) {
    if (length(unique(lengths(chain_rows))) == 1L && length(chain_rows[[1L]]) >= 4L) {
      for (metric in c("rhat", "ess_bulk", "ess_tail")) {
        fun <- getExportedValue("posterior", metric)
        diagnostics[[metric]] <- vapply(seq_len(ncol(draws)), function(j) {
          chain_matrix <- vapply(chain_rows, function(rows) draws[rows, j],
                                  numeric(length(chain_rows[[1L]])))
          fun(chain_matrix)
        }, numeric(1L))
        names(diagnostics[[metric]]) <- colnames(draws)
      }
    }
  }
  structure(c(list(estimate = estimate, posterior_sd = posterior_sd,
                   posterior_vcov = posterior_vcov), answer,
              list(n_obs = n_obs, n_units = if (is.null(groups)) n_obs else length(unique(groups)),
                   unit_ids = if (is.null(groups)) NULL else attr(groups, "ids"),
                   n_draws = s, clustered = !is.null(groups), diagnostics = diagnostics,
                   call = call)), class = "ijse")
}

check_row_order <- function(draws, ll, reference = rownames(draws)) {
  actual <- rownames(ll)
  if (!is.null(reference) && !is.null(actual) && !identical(reference, actual)) {
    stop("Row names of 'draws' and 'log_lik' must agree in order, including across likelihood blocks.",
         call. = FALSE)
  }
  if (is.null(reference)) actual else reference
}

numeric_matrix <- function(x, label, min_rows = 1L, finite = TRUE) {
  if (is.data.frame(x)) {
    if (!all(vapply(x, function(z) is.numeric(z) && !is.complex(z), logical(1L)))) {
      stop("'", label, "' must contain only numeric columns.", call. = FALSE)
    }
    x <- as.matrix(x)
  }
  if (!is.matrix(x) || !is.numeric(x) || is.complex(x) ||
      nrow(x) < min_rows || ncol(x) < 1L) {
    stop("'", label, "' must be a numeric matrix with at least ", min_rows,
         " rows and one column.", call. = FALSE)
  }
  # range() scans numeric storage without allocating a matrix-sized logical mask.
  if (finite && any(!is.finite(range(x)))) {
    stop("'", label, "' must contain only finite values.", call. = FALSE)
  }
  # Drop draws-specific attributes; matrix operations below use plain matrices.
  if (!identical(class(x), c("matrix", "array"))) class(x) <- c("matrix", "array")
  x
}

name_columns <- function(x, prefix) {
  nm <- colnames(x)
  if (is.null(nm)) nm <- paste0(prefix, seq_len(ncol(x)))
  if (anyNA(nm) || any(!nzchar(nm)) || anyDuplicated(nm)) {
    stop("Parameter or quantity names must be nonempty and unique.", call. = FALSE)
  }
  colnames(x) <- nm
  x
}

check_count <- function(x, label, minimum = 1L) {
  if (!is.numeric(x) || is.complex(x) || length(x) != 1L || is.na(x) || !is.finite(x) ||
      x < minimum || x != floor(x) || x > .Machine$integer.max) {
    stop("'", label, "' must be a single integer >= ", minimum, ".", call. = FALSE)
  }
  as.integer(x)
}

check_flag <- function(x, label) {
  if (!is.logical(x) || length(x) != 1L || is.na(x)) {
    stop("'", label, "' must be TRUE or FALSE.", call. = FALSE)
  }
}

select_names <- function(x, choices, label) {
  if (!is.character(x) || !length(x) || anyNA(x) || anyDuplicated(x) ||
      any(!x %in% choices)) {
    stop("'", label, "' must contain unique, existing parameter names.", call. = FALSE)
  }
  x
}

validate_ids <- function(x, n, label) {
  if (!is.atomic(x) || !is.null(dim(x)) || length(x) != n || anyNA(x) ||
      (is.factor(x) && anyNA(as.character(x))) ||
      (is.numeric(x) && any(!is.finite(x)))) {
    stop("'", label, "' must be a non-missing atomic vector of length ", n, ".", call. = FALSE)
  }
}

validate_clusters <- function(cluster, n) {
  if (is.null(cluster)) return(NULL)
  validate_ids(cluster, n, "cluster_var")
  ids <- unique(cluster)
  if (length(ids) < 2L) stop("At least two clusters are required.", call. = FALSE)
  groups <- match(cluster, ids)
  labels <- make.unique(as.character(ids))
  attr(groups, "labels") <- labels
  attr(groups, "ids") <- stats::setNames(ids, labels)
  groups
}

new_state <- function(draws, groups, n, save) {
  p <- ncol(draws)
  k <- if (is.null(groups)) n else length(unique(groups))
  list(draws = draws,
       mean = numeric(p), scatter = matrix(0, p, p), count = 0L,
       # Cluster aggregation takes place after posterior covariance, avoiding S x J storage.
       unit_cov = if (!is.null(groups) || save) matrix(0, p, k) else NULL,
       names = colnames(draws))
}

add_block <- function(state, ll, ii, groups) {
  # stats::cov centers in C without sweep()'s full-size broadcast temporaries.
  add_covariance(state, stats::cov(state$draws, ll), ii, groups)
}

add_covariance <- function(state, c_bl, ii, groups) {
  if (any(!is.finite(c_bl))) {
    stop("Posterior covariance overflowed; rescale the quantities or likelihood contributions.", call. = FALSE)
  }
  if (!is.null(groups)) {
    ids <- groups[ii]
    sums <- rowsum(t(c_bl), ids, reorder = FALSE)
    selected <- unique(ids)
    state$unit_cov[, selected] <- state$unit_cov[, selected, drop = FALSE] + t(sums)
  } else {
    if (!is.null(state$unit_cov)) state$unit_cov[, ii] <- c_bl
    # Merge block-centered scatter matrices (Chan's identity); do not subtract
    # two potentially large, nearly equal raw second moments.
    b <- ncol(c_bl)
    mean_b <- rowMeans(c_bl)
    delta <- mean_b - state$mean
    total <- state$count + b
    state$scatter <- state$scatter + tcrossprod(sweep(c_bl, 1L, mean_b, "-"))
    # There is no between-block correction for the first block. Squaring its
    # potentially large mean and multiplying by zero can create 0 * Inf = NaN.
    if (state$count > 0L) {
      state$scatter <- state$scatter + tcrossprod(delta) * (state$count / total) * b
    }
    state$mean <- state$mean + delta * (b / total)
    state$count <- total
  }
  state
}

finish_state <- function(state, groups, n, save) {
  k <- if (is.null(groups)) n else length(unique(groups))
  scatter <- if (is.null(groups)) state$scatter else {
    tcrossprod(sweep(state$unit_cov, 1L, rowMeans(state$unit_cov), "-"))
  }
  v <- (k / (k - 1L)) * scatter
  if (any(!is.finite(v))) stop("IJ covariance is non-finite; rescale the inputs.", call. = FALSE)
  dimnames(v) <- list(state$names, state$names)
  influence <- NULL
  if (save) {
    influence <- k * state$unit_cov
    dimnames(influence) <- list(state$names, if (is.null(groups)) {
      as.character(seq_len(n))
    } else attr(groups, "labels"))
  }
  list(se = sqrt(diag(v)), vcov = v, influence = influence)
}

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.