fit_4pl: Fit the joint Bayesian 4PL to standardised TDT data

View source: R/fit_4pl.R

fit_4plR Documentation

Fit the joint Bayesian 4PL to standardised TDT data

Description

Wraps make_4pl_formula() + make_4pl_priors() + brms::brm(). Returns a workflow object containing the fit, data, formula, prior, and metadata that downstream helpers (e.g. tls()) read from.

Usage

fit_4pl(
  data,
  random_effects = NULL,
  temp_effects = c("low", "up", "k", "mid"),
  lower = 0,
  upper = 1,
  family = NULL,
  prior = NULL,
  chains = 4,
  iter = 4000,
  warmup = floor(iter/2),
  cores = chains,
  seed = 123,
  backend = "cmdstanr",
  control = list(adapt_delta = 0.95, max_treedepth = 12),
  init = 0,
  file = NULL,
  file_refit = "on_change",
  fit = TRUE,
  bounds = NULL,
  ctmax = NULL,
  z = NULL,
  up = NULL,
  low = NULL,
  k = NULL,
  mid = NULL,
  by = NULL,
  threshold = c("relative", "absolute"),
  p = 0.5,
  t_ref = 60,
  data2 = NULL,
  fix_asymptotes = NULL,
  ...
)

Arguments

data

Output of standardize_data().

random_effects

Optional character vector of grouping variables for random intercepts on mid.

temp_effects

Which 4PL sub-parameters carry a temp_c slope; a subset of c("low", "up", "k", "mid") (default all four). "mid" is always required. The all-four default needs roughly >= 15 cells per fixed effect to be stable; for sparse designs (few temperatures x durations, small n) prefer temp_effects = "mid" (constant-shape), which estimates only the midpoint's temperature slope (= -1/z) and shares the asymptotes and steepness across temperature. Passed to the formula builder (make_4pl_formula() for fit_4pl(), make_tdt_formula() for the other models).

lower, upper

Response-scale bounds for the asymptotes. Default ⁠0, 1⁠; pass ⁠lower = 0.85, upper = 1⁠ for sublethal data bounded above zero.

family

brms family. NULL (default) picks the family from the data's response_type metadata: beta_binomial(link = "identity") for count data and brms::Beta(link = "identity") for a continuous proportion response. Pass an explicit family to override (e.g. binomial(link = "identity") for the no-overdispersion count case).

prior

Optional brmsprior object. If NULL (default), the model's default priors are built from data, lower, upper, and random_effects (make_4pl_priors() for fit_4pl(), make_tdt_priors() for the other models).

chains, iter, warmup, cores, seed

Sampling arguments passed to brms::brm().

backend

Either "cmdstanr" (default) or "rstan".

control

List of HMC control parameters.

init

Initial values for the sampler. Default 0 initialises every unconstrained parameter at zero.

file

Optional path (without extension) to cache the fit.

file_refit

Passed to brms::brm(). Default "on_change".

fit

Logical. If FALSE, returns the workflow spec without fitting — useful for inspecting the formula and priors.

bounds

Length-2 c(lower, upper) asymptote interval; supersedes lower/upper when supplied.

ctmax, z, up, low, k

One-sided formulas selecting the direct CTmax/z parameterisation (see make_tdt_formula()). Supplying ctmax and/or z fits CTmax and z directly; up/low/k are inherited from them when omitted. up/low/k also take explicit formulas in the midpoint parameterisation.

mid, by

Midpoint parameterisation only (see make_tdt_formula()). mid is an explicit one-sided formula for the midpoint (must carry temp_c); by is a moderator column-name shortcut applying the moderator to all four sub-parameters (low/up/k/mid) at once, so a per-group CTmax/z fit needs only by = "<moderator>". Either records the moderator in meta$group_vars, so tls() auto-derives per-group quantities with ⁠by = ⁠. Both error in direct mode.

threshold

"relative" (default) or "absolute"; the threshold the fitted CTmax/z refer to (direct mode only).

p

Survival fraction for the "absolute" threshold (direct mode). Default 0.5 (LT50). The disjoint-bounds reparam splits the asymptotes at the bounds' midpoint, so an absolute p is only achievable near that midpoint (with the default bounds ⁠[0, 1]⁠ the achievable range is roughly ⁠(0.499, 0.501)⁠); fit_4pl() errors otherwise. For any other LTx (LT60, LT90, ...) or a sub-unit-bounded response, fit with threshold = "relative" and derive it afterwards via tls() with ⁠target_surv = ⁠.

t_ref

Reference exposure for CTmax, in minutes (default 60, i.e. one hour). Converted to the model's log10-time scale via the data's duration_unit.

data2

Named list of objects referenced by the model formulas but not part of data – currently the covariance/correlation matrices used by ⁠gr(<group>, cov = <name>)⁠ random-effect terms, e.g. a phylogenetic correlation matrix from ape::vcv(phy, corr = TRUE). Matrices are validated (symmetry, dimnames covering the grouping levels, unit diagonal) and passed to brms::brm().

fix_asymptotes

Pin one or both asymptotes instead of estimating them. Default NULL: low and up are estimated. TRUE fixes both at the response bounds (0 and 1 for proportions); c("up") or c("low") fixes only that one at its bound and leaves the other estimated; 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 cannot carry a formula (its formula becomes ~ 1 and it is dropped from temp_effects); it is pinned through a brms constant() prior, so every downstream function reads it like an estimated one. 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()). The effective values are stored in meta$fix_asymptotes.

...

Further arguments passed to brms::brm().

Details

By default all four 4PL sub-parameters get a temp_c slope, and random intercepts attach to mid only. Use temp_effects = "mid" for the classical constant-shape TDT model (recommended for sparse designs — see temp_effects). To fit separate categories (life stages, species, populations), filter data per category and call this function once per subset.

Censored readings: if standardize_data() was given a detection_limit (a continuous-proportion response whose instrument cannot resolve values beyond a limit), the fit adds brms's cens() term to the response so those readings contribute the probability of lying beyond the limit. Only the response side of the formula changes (survival | cens(censored)); the 4PL, the priors and every downstream reader of the curve are the same. Because censored readings then score as probabilities in log_lik(), loo() and waic(), compare such a fit only with fits to the same data and the same detection_limit.

Value

A list of class "bayes_tls" with elements fit, data, formula, prior, meta. See print.bayes_tls(), summary.bayes_tls(), and plot.bayes_tls() for the available methods.

Examples

## Not run: 
d  <- standardize_data(raw, ...)
wf <- fit_4pl(d, fit = FALSE)         # inspect spec only
wf <- fit_4pl(d, file = "output/models/my_fit")
wf <- fit_4pl(d, lower = 0.85)        # sublethal data

# Phylogenetic model: species-level CTmax/z with a phylogenetic
# correlation matrix (issue #12).
A  <- ape::vcv(phy, corr = TRUE)      # unit-diagonal correlation matrix
wf <- fit_4pl(d,
              ctmax = ~ 1 + (1 | gr(species, cov = A)),
              z     = ~ 1 + (1 | gr(species, cov = A)),
              t_ref = 60, data2 = list(A = A))
tls(wf, by = "species")               # per-species z / CTmax (shrunk via A)

## End(Not run)

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