R/fit_4pl.R

Defines functions ranef.freq_tls summary.freq_tls confint.freq_tls nobs.freq_tls vcov.freq_tls logLik.freq_tls coef.freq_tls print.freq_tls fit_4pl make_4pl_formula

Documented in fit_4pl make_4pl_formula

# The bayesTLS-analogue fitting facade. fit_4pl() shares bayesTLS::fit_4pl()'s
# user-facing API (the direct CTmax/z formula interface, `by`, `threshold`,
# `t_ref`, asymptote bounds, and `family`) but fits by maximum likelihood through
# the freqTLS TMB engine (fit_tls) and returns a `freq_tls` workflow object that the quantity
# analogues (tls / extract_tdt / predict_*) read. The supported surface is similar to,
# but not a drop-in replacement for, bayesTLS.

#' Build a freqTLS 4PL formula from the direct CTmax/z interface
#'
#' Translates the bayesTLS-style direct-mode arguments (`ctmax`, `z`, `up`,
#' `low`, `k`, `by`) into the engine's [tls_bf()] `tls_formula` object. Supplying
#' a `ctmax` and/or `z` formula is the direct parameterisation; `by` is shorthand
#' for fixed cell means of CTmax and z by one moderator (`~ 0 + by`); it does
#' not add random effects or modify the shape formulas.
#'
#' Following the freqTLS constant-shape invariant, the asymptotes and steepness
#' (`up`, `low`, `k`) default to **shared** (`~ 1`) so the temperature effect runs
#' through the midpoint (CTmax / z) only; pass an explicit formula to let a shape
#' vary. `ctmax` and `z` must produce the same fixed-effect model-matrix columns.
#' Supported random intercepts go inside the `ctmax`/`z`/`low`/`k` formulas;
#' `up` random effects are not supported. For example,
#' `ctmax = ~ 1 + (1 | batch)` keeps the same intercept-only fixed design as the
#' default `z = ~ 1` while adding a `CTmax` random intercept.
#'
#' @param ctmax,z,up,low,k One-sided formulas (or `NULL`). `ctmax`/`z` set the
#'   CTmax / thermal-sensitivity structure and must have the same fixed-effect
#'   model-matrix columns; `up`/`low`/`k` set the 4PL shape. Random intercepts
#'   are supported on `ctmax`, `z`, `low`, and `k`, but not `up`.
#' @param by Optional single, non-missing moderator column name. It is shorthand
#'   for `ctmax = z = ~ 0 + by` when those are not given explicitly; it does not
#'   add random effects or modify `low`, `up`, or `k`.
#' @param family `"beta_binomial"`, `"binomial"`, or `"beta"` (selects the
#'   response idiom: `n_surv | trials(n_total)` for counts, bare `survival` for
#'   the continuous-proportion beta family).
#' @return A `tls_formula` object (as built by [tls_bf()]).
#' @seealso [fit_4pl()], [tls_bf()], [standardize_data()]
#' @examples
#' make_4pl_formula()
#' make_4pl_formula(by = "population", family = "binomial")
#' @export
make_4pl_formula <- function(ctmax = NULL, z = NULL, up = NULL, low = NULL,
                             k = NULL, by = NULL, family = "beta_binomial") {
  if (!is.null(by) && (!is.character(by) || length(by) != 1L || is.na(by) ||
                      !nzchar(by))) {
    cli::cli_abort(c(
      "{.arg by} must be one non-missing column name or {.code NULL}.",
      i = "For an interaction, create one moderator column in {.arg data} first."
    ))
  }
  fam_name <- if (is.character(family)) family[1L] else family$family
  rhs <- function(f, default = "1") {
    if (is.null(f)) return(default)
    if (!inherits(f, "formula"))
      cli::cli_abort(c("{.arg ctmax}/{.arg z}/{.arg up}/{.arg low}/{.arg k} must be one-sided formulas or {.code NULL}.",
                       x = "Got {.cls {class(f)}}."))
    paste(deparse(f[[length(f)]]), collapse = " ")
  }
  if (!is.null(by)) {
    by_rhs <- paste0("0 + ", paste(by, collapse = ":"))
    if (is.null(ctmax)) ctmax <- stats::reformulate(by_rhs)
    if (is.null(z))     z     <- stats::reformulate(by_rhs)
  }
  resp <- if (identical(fam_name, "beta"))
    "survival ~ time(duration) + temp(temp)"
  else
    "n_surv | trials(n_total) ~ time(duration) + temp(temp)"
  structure(
    list(
      response = stats::as.formula(resp),
      sub_formulas = list(
        low   = stats::as.formula(paste("low   ~", rhs(low))),
        up    = stats::as.formula(paste("up    ~", rhs(up))),
        log_k = stats::as.formula(paste("log_k ~", rhs(k))),
        CTmax = stats::as.formula(paste("CTmax ~", rhs(ctmax))),
        log_z = stats::as.formula(paste("log_z ~", rhs(z)))
      ),
      env = parent.frame()
    ),
    class = "tls_formula"
  )
}

#' Fit the 4PL thermal-load-sensitivity model by maximum likelihood (TMB)
#'
#' The frequentist analogue of `bayesTLS::fit_4pl()`. Consumes [standardize_data()]
#' output and fits the single-stage 4PL thermal-load-sensitivity model, parameterised
#' directly in CTmax and thermal sensitivity (z), via the freqTLS TMB engine.
#' Returns a `freq_tls` workflow object; uncertainty (Wald / profile / bootstrap)
#' is computed on demand by the quantity analogues ([tls()], `confint()`).
#'
#' @section Experimental software:
#' **Use freqTLS at your own risk.** Results and APIs may be incorrect or
#' change. Users are responsible for checking their data, design, model
#' specification, convergence, identifiability, diagnostics, and
#' interpretation. Important analyses should be independently refitted and
#' cross-checked with [bayesTLS](https://daniel1noble.github.io/bayesTLS/)
#' ([source repository](https://github.com/daniel1noble/bayesTLS)). Agreement
#' is a cross-check, not proof of correctness; shared data or model errors can
#' make both packages agree.
#'
#' @param data Output of [standardize_data()]. The current function records
#'   input units there; for data created by an older release with a non-minute
#'   standardized-unit marker, `fit_4pl()` converts durations to minutes and
#'   reports the conversion.
#' @param ctmax,z,up,low,k,by Direct-mode formula interface; see
#'   [make_4pl_formula()]. `by` gives fixed cell means for both `ctmax` and `z`.
#'   When `ctmax` and `z` are both supplied, their fixed-effect right-hand sides
#'   must produce the same model-matrix columns; their optional random-intercept
#'   terms may differ.
#' @param threshold `"relative"` (default; CTmax/z at the curve midpoint) or
#'   `"absolute"` (at the `p`-survival level). The fitting backbone currently
#'   accepts only `"relative"`; obtain absolute-threshold quantities post fit
#'   with [extract_tdt()] and `target_surv = "absolute"`.
#' @param p Survival level for the absolute threshold (default 0.5).
#' @param t_ref Positive reference exposure time at which CTmax is reported,
#'   in minutes. When `NULL` (the default), it is `60` minutes (one hour).
#'   [standardize_data()] converts the input duration to minutes; supply a
#'   numeric value such as `240` for a non-hour reference.
#' @param bounds Finite ordered range for estimated asymptotes, contained in
#'   `[0, 1]`. Defaults to `c(0, 1)`. The bayesTLS aliases `lower` and `upper`
#'   can set either endpoint separately; they cannot be combined with a custom
#'   `bounds` value.
#' @param fixed_low Optional exact value for the constant lower asymptote. It
#'   must lie in `bounds` and remain below the estimated upper band. This and
#'   the other asymptote controls are trailing named arguments, preserving the
#'   existing positional interface.
#' @param fixed_up Optional exact value for the constant upper asymptote. It
#'   must lie in `bounds` and remain above the estimated lower band. Fix both to
#'   fit a two-parameter logistic curve.
#' @param lower,upper Optional bayesTLS-compatible aliases for the lower and
#'   upper endpoints of `bounds`; omitted endpoints retain 0 and 1. These
#'   aliases cannot be combined with a non-default `bounds` value.
#' @param fix_asymptotes Bayesian-style asymptote pinning. `TRUE` fixes both
#'   to the padded edges of the disjoint bands; `"low"` or `"up"` fixes one,
#'   and a named numeric vector fixes selected values within their bands.
#' @param family `"beta_binomial"` (default for counts), `"binomial"`, or
#'   `"beta"`. `NULL` picks beta for a proportion response, else beta-binomial.
#' @param method Default interval method for downstream extraction
#'   (`"profile"`, `"wald"`, or `"bootstrap"`); stored in the object.
#' @param start Initial values passed to the engine [fit_tls()].
#' @param control A list containing optional `optimizer` controls for
#'   [stats::nlminb()] and an optional logical `trace` flag. Optimizer settings
#'   must be finite numeric values in their valid ranges; `scale` may be a
#'   positive numeric vector passed to `nlminb()`, while `scale.init` is a
#'   scalar. `abs.tol = 0` disables the absolute convergence check. Integer
#'   controls must fit R's integer range. Bayesian HMC controls such as
#'   `adapt_delta` and
#'   `max_treedepth` are rejected because freqTLS does not run a sampler.
#' @param trace Logical scalar; print optimiser progress. `NA` and non-logical
#'   values are rejected.
#' @param quiet Logical; suppress diagnostic messages and warnings from the
#'   underlying fit when `TRUE`.
#' @param ... Recognized bayesTLS-only fitting arguments are rejected with
#'   guidance because freqTLS does not run Bayesian sampling. Use formulas for
#'   random-intercept structure and `start`, `control`, and `quiet` for the
#'   maximum-likelihood optimizer.
#' @return A `freq_tls` object: a list with `$fit` (the engine fit), `$data`,
#'   `$formula`, and `$meta` (threshold, t_ref, bounds, temp_mean, response_type,
#'   family, grouped, moderators, method).
#' @section Before interpretation:
#' Run [check_tls()] before interpreting the fit. It gives a concrete recovery
#' action for each data-adequacy warning; `vignette("profile-likelihood")`
#' explains open profiles and the fit-specific bootstrap / Wald fallback.
#'
#' @seealso [standardize_data()], [make_4pl_formula()], [fit_tls()], [check_tls()]
#' @examples
#' raw <- simulate_tls(family = "binomial", times = c(30, 60, 120, 240, 480),
#'                     CTmax = 36, z = 4, tref = 60, seed = 1)
#' dat <- standardize_data(
#'   raw, temp = "temp", duration = "duration",
#'   n_total = "total", n_surv = "survived", duration_unit = "minutes"
#' )
#' fit <- fit_4pl(
#'   dat, family = "binomial", t_ref = 60, method = "wald", quiet = TRUE
#' )
#' coef(fit)
#' fit_2pl <- fit_4pl(
#'   dat, family = "binomial", t_ref = 60, fixed_low = 0, fixed_up = 1,
#'   quiet = TRUE
#' )
#' @export
fit_4pl <- function(data,
                    ctmax = NULL, z = NULL, up = NULL, low = NULL, k = NULL,
                    by = NULL,
                    threshold = c("relative", "absolute"),
                    p = 0.5, t_ref = NULL, bounds = c(0, 1),
                    family = NULL,
                    method = c("profile", "wald", "bootstrap"),
                    start = NULL, control = list(), trace = FALSE,
                    quiet = FALSE, ...,
                    fixed_low = NULL, fixed_up = NULL,
                    fix_asymptotes = NULL,
                    lower = NULL, upper = NULL) {
  dots <- list(...)
  control <- tdt_validate_optimizer_control(control)
  trace <- tdt_validate_trace(trace)
  if (length(dots)) {
    dot_names <- names(dots)
    if (is.null(dot_names)) dot_names <- rep("", length(dots))
    recognised <- c("random_effects", "temp_effects", "prior", "chains",
                    "iter", "warmup", "cores",
                    "seed", "backend", "init", "file", "file_refit",
                    "fit", "data2", "mid", "censored")
    supplied_recognised <- unique(dot_names[nzchar(dot_names) &
                                               dot_names %in% recognised])
    if (length(supplied_recognised)) {
      cli::cli_abort(c(
        "Recognized bayesTLS fitting arguments are not used by freqTLS: {.val {supplied_recognised}}.",
        i = "freqTLS fits by maximum likelihood. Put supported random intercepts inside the ctmax, z, low, or k formulas; use bounds and fixed_low/fixed_up for asymptotes; use start and control for optimization."
      ))
    }
    unknown <- unique(dot_names[!nzchar(dot_names) | !dot_names %in% recognised])
    if (length(unknown)) {
      unknown[!nzchar(unknown)] <- "<unnamed>"
      cli::cli_abort("Argument{?s} {.val {unknown}} not recognized by freqTLS.")
    }
  }
  if (!is.null(lower) || !is.null(upper)) {
    default_bounds <- is.numeric(bounds) && length(bounds) == 2L &&
      all(is.finite(bounds)) && identical(as.numeric(bounds), c(0, 1))
    if (!default_bounds) {
      cli::cli_abort(c(
        "{.arg lower}/{.arg upper} cannot be combined with {.arg bounds}.",
        i = "Supply one bound specification."
      ))
    }
    for (nm in c("lower", "upper")) {
      value <- if (nm == "lower") lower else upper
      if (!is.null(value) &&
          (!is.numeric(value) || length(value) != 1L || !is.finite(value) ||
           value < 0 || value > 1)) {
        cli::cli_abort("{.arg {nm}} must be one finite number in [0, 1].")
      }
    }
    bounds <- c(
      if (is.null(lower)) bounds[[1L]] else lower,
      if (is.null(upper)) bounds[[2L]] else upper
    )
    if (bounds[[1L]] >= bounds[[2L]]) {
      cli::cli_abort(paste0(
        "Mapped {.arg lower}/{.arg upper} values must define a ",
        "finite, strictly ordered range."
      ))
    }
  }
  threshold <- match.arg(threshold)
  method <- match.arg(method)
  if (!is.numeric(p) || length(p) != 1L || !is.finite(p) || p <= 0 || p >= 1) {
    cli::cli_abort("{.arg p} must be one finite survival probability strictly between 0 and 1.")
  }

  meta_in <- attr(data, "tdt_meta")
  if (is.null(meta_in))
    cli::cli_abort(c(
      "{.arg data} must be the output of {.fn standardize_data}.",
      i = "Call {.code fit_4pl(standardize_data(raw, ...), ...)}."
    ))

  duration_unit <- meta_in$duration_unit
  if (is.null(duration_unit)) {
    cli::cli_abort("Standardized data must record their duration unit. Recreate them with {.fn standardize_data}.")
  }
  if (!identical(duration_unit, "minutes")) {
    multiplier <- tls_minutes_multiplier(duration_unit)
    cli::cli_inform("Converting standardized {.val {duration_unit}} durations to minutes for {.fn fit_4pl}.")
    data$duration <- data$duration * multiplier
    data$logd <- log10(data$duration)
    meta_in$duration_unit <- "minutes"
    attr(data, "tdt_meta") <- meta_in
  }
  t_ref <- tls_resolve_tref(t_ref, meta_in)

  if (is.null(family))
    family <- if (identical(meta_in$response_type, "proportion"))
      "beta" else "beta_binomial"
  fam_name <- if (is.character(family)) family[1L] else family$family

  if (!identical(threshold, "relative"))
    cli::cli_abort(c(
      "{.code threshold = \"absolute\"} is not yet wired into the TMB backbone.",
      i = "Fit with {.code threshold = \"relative\"} (the default), then use {.fn extract_tdt} with {.code target_surv = \"absolute\"} for post-fit absolute-threshold quantities."
    ))

  fixed_from_compat <- tls_resolve_fix_asymptotes(fix_asymptotes, bounds)
  if ((!is.null(fixed_from_compat$low) || !is.null(fixed_from_compat$up)) &&
      (!is.null(fixed_low) || !is.null(fixed_up))) {
    cli::cli_abort("{.arg fix_asymptotes} cannot be combined with {.arg fixed_low} or {.arg fixed_up}.")
  }
  if (!is.null(fixed_from_compat$low)) fixed_low <- fixed_from_compat$low
  if (!is.null(fixed_from_compat$up)) fixed_up <- fixed_from_compat$up
  has_censor_flag <- "left_censored" %in% names(data)
  has_censor_limit <- "censor_limit" %in% names(data)
  censoring_requested <- meta_in$has_left_censoring
  if (is.null(censoring_requested)) {
    if (has_censor_flag || has_censor_limit) {
      cli::cli_abort(c(
        "Standardized data contain censoring-named columns but no censoring metadata.",
        i = "Recreate the data with the current {.fn standardize_data} and supply {.arg left_censored} and {.arg censor_limit} explicitly."
      ))
    }
    censoring_requested <- FALSE
  }
  if (!is.logical(censoring_requested) || length(censoring_requested) != 1L ||
      is.na(censoring_requested)) {
    cli::cli_abort("Standardized data have invalid {.field has_left_censoring} metadata; recreate them with {.fn standardize_data}.")
  }
  if (isTRUE(censoring_requested) &&
      (!has_censor_flag || !has_censor_limit)) {
    cli::cli_abort("Standardized data record left-censoring but are missing {.field left_censored} or {.field censor_limit}.")
  }
  left_censored_arg <- if (isTRUE(censoring_requested)) data$left_censored else NULL
  censor_limit_arg <- if (isTRUE(censoring_requested)) data$censor_limit else NULL

  ff <- make_4pl_formula(ctmax = ctmax, z = z, up = up, low = low, k = k,
                         by = by, family = fam_name)
  fit <- fit_tls(ff, data = data, family = fam_name, tref = t_ref,
                 start = start, control = control, trace = trace, quiet = quiet,
                 left_censored = left_censored_arg,
                 censor_limit = censor_limit_arg,
                 bounds = bounds, fixed_low = fixed_low,
                 fixed_up = fixed_up)

  moderators <- by
  if (is.null(moderators) && !is.null(ctmax)) {
    ctmax_fixed <- fit$fixed_terms$CTmax %||% NULL
    moderators <- if (is.null(ctmax_fixed)) character() else
      setdiff(all.vars(ctmax_fixed), c("temp_c", "temp"))
    if (!length(moderators)) moderators <- NULL
  }
  out <- list(
    fit = fit,
    data = data,
    formula = ff,
    meta = list(
      threshold     = threshold,
      p             = p,
      t_ref         = t_ref,
      bounds        = bounds,
      fixed_low     = fixed_low,
      fixed_up      = fixed_up,
      fix_asymptotes = c(
        if (!is.null(fixed_low)) c(low = fixed_low),
        if (!is.null(fixed_up)) c(up = fixed_up)
      ),
      temp_mean     = meta_in$temp_mean,
      duration_unit = meta_in$duration_unit,
      input_duration_unit = meta_in$input_duration_unit,
      response_type = meta_in$response_type,
      family        = fam_name,
      grouped       = isTRUE(fit$data_summary$grouped),
      moderators    = moderators,
      method        = method
    )
  )
  class(out) <- "freq_tls"
  out
}

#' @export
print.freq_tls <- function(x, ...) {
  m <- x$meta
  cat("<freq_tls>\n")
  cat(sprintf("  Data:    %d rows; %d temperatures; %d durations\n",
              nrow(x$data), length(unique(x$data$temp)),
              length(unique(x$data$duration))))
  cat(sprintf("  T_bar:   %.2f\n", m$temp_mean))
  cat(sprintf("  Family:  %s (%s threshold, t_ref = %g %s)\n",
              m$family, m$threshold, m$t_ref, m$duration_unit %||% "units"))
  if (!is.null(m$moderators))
    cat(sprintf("  By:      %s\n", paste(m$moderators, collapse = ", ")))
  conv <- x$fit$convergence
  cat(sprintf("  Fit:     %s (pdHess = %s); default CI method = %s\n",
              if (isTRUE(conv$code == 0)) "converged" else "NOT converged",
              isTRUE(conv$pdHess), m$method))
  sf <- x$formula$sub_formulas
  formula_text <- function(handle) {
    if (is.null(sf[[handle]])) return("~ 1")
    paste("~", deparse1(sf[[handle]][[3L]]))
  }
  cat(sprintf("  Model:   low %s; up %s; k %s\n",
              formula_text("low"), formula_text("up"), formula_text("log_k")))
  for (detail in tls_fit_print_details(x$fit)) cat("  ", detail, "\n", sep = "")
  invisible(x)
}

# S3 generics delegate from the freq_tls workflow to its engine fit, so
# coef()/logLik()/vcov()/nobs()/confint()/summary() work on the object
# fit_4pl() returns.

#' @importFrom stats coef
#' @export
coef.freq_tls <- function(object, ...) stats::coef(object$fit, ...)

#' @importFrom stats logLik
#' @export
logLik.freq_tls <- function(object, ...) stats::logLik(object$fit, ...)

#' @importFrom stats vcov
#' @export
vcov.freq_tls <- function(object, ...) stats::vcov(object$fit, ...)

#' @importFrom stats nobs
#' @export
nobs.freq_tls <- function(object, ...) stats::nobs(object$fit, ...)

#' @importFrom stats confint
#' @export
confint.freq_tls <- function(object, ...) stats::confint(object$fit, ...)

#' @export
summary.freq_tls <- function(object, ...) {
  out <- summary(object$fit, ...)
  sf <- object$formula$sub_formulas
  formula_text <- function(handle) {
    if (is.null(sf[[handle]])) return("~ 1")
    paste("~", deparse1(sf[[handle]][[3L]]))
  }
  out$model_formulas <- c(
    low = formula_text("low"), up = formula_text("up"),
    k = formula_text("log_k")
  )
  out
}

#' @export
ranef.freq_tls <- function(object, ...) ranef(object$fit, ...)

Try the freqTLS package in your browser

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

freqTLS documentation built on Dec. 4, 2026, 5:11 p.m.