R/wrappers_prior.R

Defines functions prior_rhs prior_ssp prior_jzs prior_weak prior_uniform prior_normal prior_flat .wrapper_y_range_scale .check_unused_dots .validate_prior_type .merge_prior

Documented in prior_flat prior_jzs prior_normal prior_rhs prior_ssp prior_uniform prior_weak

# Internal helper to merge priors without removing NULL values
.merge_prior <- function(default, user) {
  if (is.null(user)) return(default)
  res <- user
  for (name in names(default)) {
    if (!(name %in% names(user))) {
      res[[name]] <- default[[name]]
    }
  }
  return(res)
}

.validate_prior_type <- function(prior, allowed, context = "This wrapper") {
  if (is.null(prior)) prior <- prior_flat()
  if (!inherits(prior, "rtmb_prior")) {
    stop(
      "prior must be an object of class 'rtmb_prior'. ",
      "Use one of: ", paste(paste0("prior_", allowed, "()"), collapse = ", "), ".",
      call. = FALSE
    )
  }
  prior_type <- prior$type
  if (!is.character(prior_type) || length(prior_type) != 1L ||
      is.na(prior_type) || !(prior_type %in% allowed)) {
    got <- if (is.null(prior_type)) "unknown" else as.character(prior_type)[1L]
    stop(
      context, " supports only: ",
      paste(paste0("prior_", allowed, "()"), collapse = ", "),
      ". Received prior type '", got, "'.",
      call. = FALSE
    )
  }
  prior
}

.check_unused_dots <- function(..., .fn = "This function") {
  dots <- list(...)
  if (length(dots) == 0L) return(invisible(NULL))
  dot_names <- names(dots)
  if (is.null(dot_names)) dot_names <- rep("", length(dots))
  labels <- ifelse(nzchar(dot_names), dot_names, paste0("..", seq_along(dots)))
  stop(
    .fn, " got unused argument(s): ",
    paste(labels, collapse = ", "),
    call. = FALSE
  )
}

.wrapper_y_range_scale <- function(y_range, n_response, sd_ratio = 0.5,
                                   response_names = NULL, context = "This wrapper") {
  if (is.list(y_range) && !is.data.frame(y_range)) {
    if (!is.null(response_names) &&
        !is.null(names(y_range)) &&
        all(response_names %in% names(y_range))) {
      y_range <- y_range[response_names]
    }
    range_mat <- do.call(rbind, lapply(y_range, as.numeric))
  } else if (is.atomic(y_range) && is.null(dim(y_range)) && length(y_range) == 2L) {
    range_mat <- matrix(rep(as.numeric(y_range), n_response), nrow = n_response, byrow = TRUE)
  } else {
    range_mat <- as.matrix(y_range)
    if (nrow(range_mat) == 2L && ncol(range_mat) == n_response && ncol(range_mat) != 2L) {
      range_mat <- t(range_mat)
    }
  }

  if (!is.numeric(range_mat) ||
      !identical(dim(range_mat), c(as.integer(n_response), 2L)) ||
      any(!is.finite(range_mat)) ||
      any(range_mat[, 1L] >= range_mat[, 2L])) {
    stop(
      context,
      " requires 'y_range' to be a finite increasing range. ",
      "Use c(min, max) for all responses, or a P x 2 matrix/list for response-specific ranges.",
      call. = FALSE
    )
  }
  if (!is.numeric(sd_ratio) || length(sd_ratio) != 1L ||
      !is.finite(sd_ratio) || sd_ratio <= 0) {
    stop("'sd_ratio' must be a positive finite scalar.", call. = FALSE)
  }

  half_range <- (range_mat[, 2L] - range_mat[, 1L]) / 2
  base_scale <- half_range * sd_ratio
  list(
    center = rowMeans(range_mat),
    half_range = half_range,
    base_scale = base_scale,
    rate = 1 / base_scale
  )
}


#' Specify a flat prior
#'
#' @description
#' `prior_flat()` specifies that no additional prior density is added by the
#' wrapper. This is the only prior type allowed for `classic()`.
#'
#' @return A list with class `"rtmb_prior"` and `type = "flat"`.
#' @export
prior_flat <- function() {
  res <- list(type = "flat")
  class(res) <- "rtmb_prior"
  res
}


#' Specify normal/exponential priors for MAP and Bayesian inference
#'
#' @description
#' `prior_normal()` specifies normal priors for location parameters and
#' exponential priors for scale parameters. It is intended for MAP and Bayesian
#' inference, not for `classic()`.
#'
#' @param Intercept_sd Standard deviation for the intercept prior. If `NULL`, no intercept prior is added.
#' @param b_sd Standard deviation for coefficient priors. If `NULL`, no coefficient prior is added.
#' @param mu_sd Standard deviation for mean/intercept priors. If `NULL`, no mean prior is added.
#' @param sigma_rate Rate for residual standard deviation priors. The default
#'   `1 / 5` gives an exponential prior with mean 5. If `NULL`, no sigma prior
#'   is added.
#' @param tau_rate Rate for random-effect standard deviation priors. The default
#'   `1 / 5` gives an exponential prior with mean 5. If `NULL`, no tau prior is
#'   added.
#' @param ... Optional wrapper-specific hyperparameters.
#'
#' @return A list with class `"rtmb_prior"` and `type = "normal"`.
#' @export
prior_normal <- function(
  Intercept_sd = 10,
  mu_sd = 10,
  b_sd = 10,
  sigma_rate = 1 / 5,
  tau_rate = 1 / 5,
  ...
) {
  res <- list(
    type = "normal",
    Intercept_sd = Intercept_sd,
    mu_sd = mu_sd,
    b_sd = b_sd,
    sigma_rate = sigma_rate,
    tau_rate = tau_rate,
    ...
  )
  class(res) <- "rtmb_prior"
  res
}


#' Specify a flat prior
#'
#' @description
#' Deprecated alias of `prior_flat()`.
#'
#' @return A list with class `"rtmb_prior"` and `type = "flat"`.
#' @export
prior_uniform <- function() {
  prior_flat()
}

#' Specify a weakly informative prior
#'
#' @param sd_ratio Ratio of the prior standard deviation to the half-range of the response variable. Default is 0.5.
#' @param max_beta Maximum expected effect size. Default is 1.0.
#' @param ... Optional hyperparameters for other distributions.
#' @return A list with class "rtmb_prior"
#' @export
prior_weak <- function(sd_ratio = 0.5, max_beta = 1.0, ...) {
  res <- list(type = "weak", sd_ratio = sd_ratio, max_beta = max_beta, ...)
  class(res) <- "rtmb_prior"
  return(res)
}

#' Specify a JZS (Jeffrey-Zellner-Siow) prior for t-tests
#'
#' @param r Numeric; scale parameter for the Cauchy prior on effect size delta. Default is 0.707.
#' @return A list with class "rtmb_prior"
#' @export
prior_jzs <- function(r = 0.707) {
  res <- list(type = "jzs", r = r)
  class(res) <- "rtmb_prior"
  return(res)
}

#' Specify a Spike-and-Slab prior for variable selection
#'
#' @param ssp_ratio Prior probability of inclusion for each variable. Default is 0.25.
#' @param max_beta Maximum expected effect size. Default is 1.0.
#' @param ... Optional hyperparameters for other distributions.
#' @return A list with class "rtmb_prior"
#' @export
prior_ssp <- function(ssp_ratio = 0.25, max_beta = 1.0, ...) {
  res <- list(type = "ssp", ssp_ratio = ssp_ratio, max_beta = max_beta, ...)
  class(res) <- "rtmb_prior"
  return(res)
}

#' Specify a Regularized Horseshoe prior for continuous shrinkage
#'
#' @param expected_vars Expected number of non-zero variables. Default is 3.
#' @param slab_scale Scale parameter for the slab distribution. Default is 2.0.
#' @param slab_df Degrees of freedom for the slab distribution. Default is 4.0.
#' @param ... Optional hyperparameters for other distributions.
#' @return A list with class "rtmb_prior"
#' @export
prior_rhs <- function(expected_vars = 3, slab_scale = 2.0, slab_df = 4.0, ...) {
  res <- list(type = "rhs", expected_vars = expected_vars, slab_scale = slab_scale, slab_df = slab_df, ...)
  class(res) <- "rtmb_prior"
  return(res)
}

Try the BayesRTMB package in your browser

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

BayesRTMB documentation built on Nov. 24, 2026, 9:06 a.m.