R/priors.R

Defines functions re_groups cell_means_has_extra_terms cell_means_coefs make_tdt_priors make_4pl_priors

Documented in make_4pl_priors make_tdt_priors

#' Default weakly informative priors for the joint Bayesian 4PL
#'
#' Priors are weakly informative and do not adapt to the data (which would
#' understate uncertainty). They are constructed to match
#' [make_4pl_formula()]'s disjoint-bounds reparameterisation
#' `low = low_min + inv_logit(lowraw) * low_w` and
#' `up = up_min + inv_logit(upraw) * up_w` for the asymptote intervals derived
#' from `lower` and `upper` by [compute_4pl_bounds()].
#'
#' Each of the four 4PL sub-parameters (`lowraw`, `upraw`, `logk`, `mid`) gets
#' an Intercept-specific prior plus a general `class = "b"` prior covering the
#' `temp_c` slope. Random-effect SDs on `mid` get one `prior_random_sd` row per
#' grouping variable.
#'
#' @param data            Output of [standardize_data()]. Only `logd` is used,
#'                        to centre the midpoint Intercept prior.
#' @param lower,upper     Response-scale bounds for the asymptotes. Default
#'                        `0, 1` for proportion data. For sublethal data
#'                        bounded above `0` (e.g. photosystem-II between 0.85
#'                        and 1), set `lower` accordingly.
#' @param random_effects  Optional character vector of grouping variables for
#'                        random intercepts on `mid`. Adds one
#'                        `prior_random_sd` row per group.
#' @param prior_random_sd Stan prior string for random-effect SDs. Default
#'                        `"exponential(2)"`.
#' @param prior_phi       Stan prior string for the beta-binomial precision
#'                        parameter `phi`. Default `"gamma(2, 0.1)"`. Pass
#'                        `NULL` to omit the `phi` prior — needed when fitting
#'                        with `family = binomial()` (no overdispersion).
#' @param bounds          Length-2 `c(lower, upper)` asymptote interval;
#'                        supersedes `lower`/`upper` when supplied.
#' @param ctmax,z,up,low,k One-sided formulas selecting the **direct** CTmax/z
#'                        priors (matching [make_4pl_formula()]). Supplying
#'                        `ctmax`/`z` switches to direct-mode priors: the same
#'                        centred asymptote priors (per factor level for
#'                        cell-means terms), coding-aware weakly-informative
#'                        `CTmaxdev`/`logz` priors (the level prior lands on the
#'                        Intercept or each factor level, while between-group
#'                        contrasts and temperature slopes are centred on zero, so
#'                        the per-group z/CTmax prior **mean** is invariant to
#'                        cell-means vs treatment coding — this removes the
#'                        log(3) shrinkage bias). The prior **variance** is not
#'                        fully coding-invariant: under treatment coding a
#'                        non-reference group's implied prior convolves the
#'                        Intercept and contrast SDs (e.g. logz SD
#'                        `sqrt(0.7^2 + 0.7^2) ~ 0.99` vs `0.70` under
#'                        cell-means), and `normalize_cellmeans()` only rewrites
#'                        single-factor formulas. Prefer cell-means (`0 + G`) for
#'                        multi-factor models to keep groups symmetric. Plus
#'                        random-effect SD priors on
#'                        `CTmaxdev`/`logz` only (never on the shape
#'                        sub-parameters). `up`/`low`/`k`
#'                        follow the same inheritance resolution as the formula.
#' @param fix_asymptotes  Pin one or both asymptotes instead of estimating
#'                        them (default `NULL`: both estimated). `TRUE` fixes
#'                        `low` and `up` at the response bounds (`lower`,
#'                        `upper`; `0` and `1` for proportions);
#'                        `c("up")` fixes only the named asymptote at its bound;
#'                        a named numeric vector such as `c(low = 0.02)` or
#'                        `c(low = 0, up = 1)` fixes the named ones at those
#'                        values. A fixed asymptote gets a brms `constant()`
#'                        prior on its Intercept and no slope prior (its formula
#'                        is `~ 1`). Values at the response bounds are pinned at
#'                        the edge of the padded window (`0.001` / `0.999` with
#'                        the defaults, see [compute_4pl_bounds()]) because the
#'                        identity-link likelihood needs probabilities strictly
#'                        inside `(lower, upper)`.
#' @return A `brmsprior` object ready to pass to [fit_4pl()].
#' @examples
#' raw <- data.frame(
#'   temperature_C = rep(c(30, 32, 34), each = 4),
#'   exposure_h    = rep(c(1, 2, 4, 8), times = 3),
#'   n             = 30L,
#'   alive         = c(29, 28, 25, 5, 30, 27, 18, 2, 28, 22, 10, 1)
#' )
#' d <- standardize_data(raw, temp = "temperature_C", duration = "exposure_h",
#'                       n_total = "n", n_surv = "alive")
#' make_4pl_priors(d)
#' @export
make_4pl_priors <- function(data,
                            lower           = 0,
                            upper           = 1,
                            random_effects  = NULL,
                            prior_random_sd = "exponential(2)",
                            prior_phi       = "gamma(2, 0.1)",
                            bounds          = NULL,
                            ctmax           = NULL,
                            z               = NULL,
                            up              = NULL,
                            low             = NULL,
                            k               = NULL,
                            fix_asymptotes  = NULL) {
  make_tdt_priors(model = "log-logistic",
                  data            = data,
                  lower           = lower,
                  upper           = upper,
                  random_effects  = random_effects,
                  prior_random_sd = prior_random_sd,
                  prior_phi       = prior_phi,
                  bounds          = bounds,
                  ctmax           = ctmax,
                  z               = z,
                  up              = up,
                  low             = low,
                  k               = k,
                  fix_asymptotes  = fix_asymptotes)
}

#' Default priors for a joint Bayesian four-parameter dose-response model
#'
#' Model-generic twin of [make_4pl_priors()]. The only prior that depends on
#' `model` is the Intercept prior mean of `logk`: it is shifted by
#' `log(0.25 / slope_factor)` so that the implied prior on the slope of the
#' curve at its midpoint, `-k (up - low) * slope_factor`, is the same for every
#' model (`slope_factor` = 0.25 log-logistic, 0.399 log-normal, 0.347 both
#' Weibull types). [make_4pl_priors()] is `make_tdt_priors(model =
#' "log-logistic")`.
#'
#' @inheritParams make_tdt_formula
#' @inheritParams make_4pl_priors
#' @inherit make_4pl_priors return
#' @examples
#' raw <- data.frame(
#'   temperature_C = rep(c(30, 32, 34), each = 4),
#'   exposure_h    = rep(c(1, 2, 4, 8), times = 3),
#'   n             = 30L,
#'   alive         = c(29, 28, 25, 5, 30, 27, 18, 2, 28, 22, 10, 1)
#' )
#' d <- standardize_data(raw, temp = "temperature_C", duration = "exposure_h",
#'                       n_total = "n", n_surv = "alive")
#' make_tdt_priors(d, model = "weibull1")
#' @export
make_tdt_priors <- function(data,
                            model           = "log-logistic",
                            lower           = 0,
                            upper           = 1,
                            random_effects  = NULL,
                            prior_random_sd = "exponential(2)",
                            prior_phi       = "gamma(2, 0.1)",
                            bounds          = NULL,
                            ctmax           = NULL,
                            z               = NULL,
                            up              = NULL,
                            low             = NULL,
                            k               = NULL,
                            fix_asymptotes  = NULL) {

  if (is.null(bounds)) bounds <- c(lower, upper)
  b <- compute_4pl_bounds(bounds[1], bounds[2])

  # Fixed asymptotes: a constant() Intercept prior replaces the centred prior
  # and the slope prior; the sub-parameter formula is `~ 1` by construction.
  fx <- tdt_resolve_fix_asymptotes(fix_asymptotes, bounds[1], bounds[2])
  if (!is.null(fx$low)) low <- ~ 1
  if (!is.null(fx$up))  up  <- ~ 1
  fixed_prior <- function(which, nlpar) {
    raw <- tdt_fixed_asymptote_raw(fx[[which]], which, b, bounds[1], bounds[2])$raw
    brms::set_prior(sprintf("constant(%.10f)", raw),
                    class = "b", nlpar = nlpar, coef = "Intercept")
  }

  # Centre the raw asymptotes so low ~ bounds[1] + 0.02 * range and
  # up ~ bounds[1] + 0.98 * range — the typical TDT asymptotes for any range.
  low_target  <- bounds[1] + 0.02 * (bounds[2] - bounds[1])
  up_target   <- bounds[1] + 0.98 * (bounds[2] - bounds[1])
  lowraw_mean <- stats::qlogis((low_target - b$low_min) / b$low_w)
  upraw_mean  <- stats::qlogis((up_target  - b$up_min)  / b$up_w)
  logk_mean   <- tdt_logk_prior_mean(model)   # log(2) for the log-logistic

  if (is.null(ctmax) && is.null(z)) {
    ## ---- midpoint priors (unchanged) ----
    mid_start <- stats::median(data$logd, na.rm = TRUE)
    low_priors <- if (!is.null(fx$low)) fixed_prior("low", "lowraw") else c(
      brms::set_prior(sprintf("normal(%.6f, 1)", lowraw_mean),
                      class = "b", nlpar = "lowraw", coef = "Intercept"),
      brms::set_prior("normal(0, 0.5)", class = "b", nlpar = "lowraw"))
    up_priors  <- if (!is.null(fx$up))  fixed_prior("up",  "upraw")  else c(
      brms::set_prior(sprintf("normal(%.6f, 1)", upraw_mean),
                      class = "b", nlpar = "upraw", coef = "Intercept"),
      brms::set_prior("normal(0, 0.5)", class = "b", nlpar = "upraw"))
    priors <- c(
      low_priors,
      up_priors,
      brms::set_prior(sprintf("normal(%.6f, 1)", logk_mean),
                      class = "b", nlpar = "logk", coef = "Intercept"),
      brms::set_prior("normal(0, 0.3)", class = "b", nlpar = "logk"),
      brms::set_prior(sprintf("normal(%.6f, 1.5)", mid_start),
                      class = "b", nlpar = "mid", coef = "Intercept"),
      brms::set_prior("normal(0, 0.6)", class = "b", nlpar = "mid")
    )
    if (!is.null(prior_phi))
      priors <- c(priors, brms::set_prior(prior_phi, class = "phi"))
    for (re_var in tdt_random_effect_variables(random_effects))
      priors <- c(priors, brms::set_prior(prior_random_sd,
                                          class = "sd", nlpar = "mid", group = re_var))
    return(priors)
  }

  ## ---- direct CTmax/z priors ----
  # Centred asymptote priors are load-bearing (a flat prior gave 191 divergences;
  # see notes/package_design/2026-06-21-prior-sensitivity-direct-ctmax-z.qmd). They match the
  # midpoint centres exactly. CTmax/z are well identified and take simple priors;
  # random effects attach to CTmaxdev/logz only (never inherited onto the shape).
  ctmax_rhs <- formula_rhs(ctmax, "1")
  z_rhs     <- formula_rhs(z,     "1")
  inherit   <- if (!is.null(ctmax)) ctmax_rhs else z_rhs
  shape_rhs <- list(lowraw = resolve_shape(low, inherit),
                    upraw  = resolve_shape(up,  inherit),
                    logk   = resolve_shape(k,   inherit))

  # One builder for every direct sub-parameter. The centred prior lands on the
  # Intercept (treatment coding) or on each factor level (cell-means coding); a
  # separate, MEAN-ZERO prior covers everything else — temperature slopes AND
  # between-group contrasts. Centring the *contrast* prior on zero (not on
  # `centre`) is what makes the CTmaxdev/logz prior MEAN coding-invariant: under
  # treatment coding the logz contrast must not be shrunk toward log(3), or the
  # between-group z ratio is biased toward 3x (the asymptotes already did this
  # via `asy`; CTmaxdev/logz previously used a single blanket prior and did not).
  # The prior VARIANCE is not fully coding-invariant: a treatment-coded
  # non-reference group convolves the level + contrast SDs, so prefer cell-means
  # (0 + G) for multi-factor models. The global mean-zero `b` prior is emitted
  # only when extra terms (slopes/contrasts) exist beyond the cell-means levels;
  # for a bare `0 + G` it would be redundant (no slope/contrast coefficient) and
  # brms would warn about an unused global prior (CI runs error-on=warning).
  direct_par <- function(rhs, nlpar, centre, level_sd, slope_sd) {
    cells <- cell_means_coefs(rhs, data)
    centred <- if (is.null(cells))
      list(brms::set_prior(sprintf("normal(%.6f, %s)", centre, level_sd),
                           class = "b", nlpar = nlpar, coef = "Intercept"))
    else lapply(cells, function(cf)
      brms::set_prior(sprintf("normal(%.6f, %s)", centre, level_sd),
                      class = "b", nlpar = nlpar, coef = cf))
    priors <- do.call(c, centred)
    if (is.null(cells) || cell_means_has_extra_terms(rhs))
      priors <- c(priors,
                  brms::set_prior(sprintf("normal(0, %s)", slope_sd),
                                  class = "b", nlpar = nlpar))
    priors
  }

  priors <- c(
    if (!is.null(fx$low)) fixed_prior("low", "lowraw") else
      direct_par(shape_rhs$lowraw, "lowraw", lowraw_mean, "1", "0.5"),
    if (!is.null(fx$up))  fixed_prior("up",  "upraw")  else
      direct_par(shape_rhs$upraw,  "upraw",  upraw_mean,  "1", "0.5"),
    direct_par(shape_rhs$logk,   "logk",     logk_mean,   "1",   "0.3"),
    direct_par(ctmax_rhs,        "CTmaxdev", 0,           "10",  "10"),
    direct_par(z_rhs,            "logz",     log(3),      "0.7", "0.7")
  )
  if (!is.null(prior_phi))
    priors <- c(priors, brms::set_prior(prior_phi, class = "phi"))
  for (g in re_groups(ctmax))
    priors <- c(priors, brms::set_prior(prior_random_sd,
                                        class = "sd", nlpar = "CTmaxdev", group = g))
  for (g in re_groups(z))
    priors <- c(priors, brms::set_prior(prior_random_sd,
                                        class = "sd", nlpar = "logz", group = g))
  priors
}

# --- internal: structure helpers for the direct CTmax/z priors -------------
# (Unexported. Placed after make_4pl_priors() so its roxygen @export attaches to
# the function, not to these helpers.)

# Cell-means coefficient names for a "0 + G ..." resolved RHS (e.g.
# "0 + life_stage + temp_c:life_stage" -> c("life_stageA", "life_stageB", ...));
# NULL when the term is not cell-means coded (then the prior uses "Intercept").
cell_means_coefs <- function(rhs, data) {
  if (!grepl("^0\\s*\\+", rhs)) return(NULL)
  core <- trimws(sub("^0\\s*\\+\\s*", "", rhs))
  fac  <- trimws(strsplit(core, "[:+*]")[[1]][1])
  if (is.null(data) || !fac %in% names(data)) return(NULL)
  paste0(fac, levels(factor(data[[fac]])))
}

# TRUE when a cell-means "0 + G" RHS carries terms beyond the single factor
# (slopes or interactions, e.g. "0 + G + temp_c:G"), so its coefficients are
# not fully covered by the per-level priors and a global mean-zero `b` prior is
# still needed. FALSE for a bare "0 + G" (per-level priors cover everything, so
# the global prior would be redundant and trigger a brms unused-prior warning).
cell_means_has_extra_terms <- function(rhs) {
  if (!grepl("^0\\s*\\+", rhs)) return(TRUE)
  core  <- trimws(sub("^0\\s*\\+\\s*", "", rhs))
  terms <- trimws(strsplit(core, "\\+")[[1]])
  terms <- terms[nzchar(terms)]
  length(terms) > 1L || grepl("[:*]", core)
}

# Grouping-factor names in a one-sided formula's (x | g) random-effect terms,
# as brms names them for `class = "sd"` priors. AST-based (tdt_split_bars):
# the old regex read up to the first ")", so gr(species, cov = A) yielded the
# invalid group "gr(species, cov = A". For gr() terms brms's group name is the
# grouping variable itself (first unnamed argument); plain and nested groups
# deparse unchanged (Date -> "Date", a/b -> "a/b", legacy-identical).
re_groups <- function(f) {
  if (is.null(f)) return(character(0))
  rhs <- formula_rhs(f, "")
  if (!nzchar(trimws(rhs))) return(character(0))
  bars <- tdt_split_bars(rhs)$bars
  vapply(bars, function(bar) {
    g <- bar[[3]]
    if (is.call(g) && identical(g[[1]], as.name("gr"))) {
      keep <- setdiff(seq_along(g)[-1],
                      which(names(g) %in% c("cov", "dist", "by")))
      return(paste(deparse(g[[keep[1]]]), collapse = ""))
    }
    paste(deparse(g), collapse = " ")
  }, character(1))
}

Try the bayesTLS package in your browser

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

bayesTLS documentation built on Nov. 29, 2026, 1:06 a.m.