R/predict.R

Defines functions derive_tcrit derive_ctmax tls_fit_with_boot_draw tls_validate_derived_group tls_temperature_varying_shapes tls_validate_derived_cell tls_absolute_threshold_root tls_observed_temp_bounds tls_bounded_root derive_lt predict_survival_surface tls_predict_pars predict.freq_tls predict.profile_tls

Documented in derive_ctmax derive_lt derive_tcrit predict.freq_tls predict.profile_tls predict_survival_surface

#' Predict survival, link, or midpoint from a fitted freqTLS model
#'
#' `predict()` evaluates the fitted four-parameter thermal-load-sensitivity
#' model at new temperature-by-duration cells, using exactly the
#' same forward map as the TMB engine in `src/profile_tls.cpp`:
#'
#' Here `CTmax` is the critical thermal maximum at the reference duration
#' `tref`; `z` is thermal sensitivity in degrees per order-of-magnitude change
#' in duration;
#' `low` and `up` are the fitted lower and upper survival asymptotes; and `k`
#' controls the curve's steepness. The model fits `log_z = log(z)` internally,
#' then reports positive natural-scale `z` values.
#'
#' All supported curves use `mid = log10(tref) - (temp - CTmax) / z`. The
#' selected curve then maps `eta = k * (log10(duration) - mid)` to survival.
#' The default log-logistic fraction is `plogis(-eta)`; `curve` also accepts
#' the log-normal and two midpoint-centred Weibull forms.
#'
#' @details
#' Four response types are available:
#' * `"survival"` (default) returns the fitted survival probability in `(0, 1)`.
#' * `"link"` returns the logit of the survival probability,
#'   `qlogis(survival)`.
#' * `"midpoint"` returns the temperature-dependent curve midpoint `mid` on the
#'   `log10(duration)` axis (constant within a temperature, so the `duration`
#'   column is ignored for this type but a `temp` column is still required).
#' * `"parameters"` returns the row-specific natural-scale `CTmax`, `z`, `low`,
#'   `up`, and `k` values. This is useful for interacted formula designs; the
#'   `duration` column may be omitted.
#'
#' `newdata` must also contain every predictor used by the fitted fixed-effect
#' designs for `CTmax`, `log_z`, `low`, `up`, or `log_k`. For a grouped column-
#' interface fit, supply `group` with values from the fitted `group_levels`.
#' For a formula fit, a literal [tls_bf()] call preserves the fixed-design
#' formulas needed to rebuild transformed or interacted terms. If the model was
#' instead passed through a formula-object variable, `predict()` can rebuild
#' direct numeric design columns but asks the user to refit with a literal
#' [tls_bf()] call when a transformed or interacted design cannot be recovered
#' safely.
#'
#' @param object A `profile_tls` fit from [fit_tls()].
#' @param newdata A data frame with numeric columns `temp` and `duration`, plus
#'   every predictor used in the fitted `CTmax`, `log_z`, `low`, `up`, and
#'   `log_k` fixed designs. Include `group` for a grouped column-interface fit.
#'   For a formula fit whose `temp()` axis uses another source-column name,
#'   temperature-dependent shape predictions rebuild that source column from
#'   `newdata$temp`.
#'   Conditional random-effect predictions additionally require every fitted
#'   grouping column. `duration` must be strictly positive (it is
#'   `log10`-transformed). For `type = "midpoint"` or `"parameters"`, `duration`
#'   may be omitted.
#' @param type One of `"survival"` (default), `"link"`, `"midpoint"`, or
#'   `"parameters"`.
#' @param re.form How to handle fitted random intercepts. `"population"`
#'   (default) sets them to zero; `"conditional"` adds the fitted BLUP for each
#'   random-effect grouping column in `newdata`. When omitted for a random-
#'   effects fit, `predict()` warns that it is returning a population prediction.
#' @param ... Reserved; must be empty.
#'
#' @return For `type = "parameters"`, a data frame with one row per row of
#'   `newdata` and columns `CTmax`, `z`, `low`, `up`, and `k`. Otherwise a
#'   numeric vector with one element per row; survival values lie in `(0, 1)`.
#'
#' @examples
#' d <- simulate_tls(family = "binomial", times = c(30, 60, 120, 240, 480),
#'                   CTmax = 36, z = 4, tref = 60, seed = 1)
#' fit <- fit_tls(d, y = survived, n = total, time = duration, temp = temp,
#'                family = "binomial", tref = 60)
#' nd <- expand.grid(temp = c(34, 36, 38), duration = c(60, 120, 240))
#' predict(fit, nd, type = "survival")
#'
#' # A continuous predictor used by CTmax and log_z must also be in newdata.
#' d$x <- rep(c(-1, 1), length.out = nrow(d))
#' fit_x <- fit_tls(
#'   tls_bf(survived | trials(total) ~ time(duration) + temp(temp),
#'          CTmax ~ x, log_z ~ x),
#'   data = d, family = "binomial", tref = 60
#' )
#' predict(fit_x, data.frame(temp = 36, duration = 60, x = c(-1, 1)))
#'
#' \donttest{
#' # Choose population or fitted-group prediction explicitly for an RE fit.
#' dre <- simulate_tls(family = "binomial", CTmax = 36, z = 4,
#'                     times = c(30, 60, 120, 240, 480), tref = 60,
#'                     re_sd = 1, n_re_groups = 8, seed = 2)
#' fit_re <- fit_tls(
#'   tls_bf(survived | trials(total) ~ time(duration) + temp(temp),
#'          CTmax ~ 1 + (1 | colony)),
#'   data = dre, family = "binomial", tref = 60
#' )
#' colony <- as.character(ranef(fit_re)$group[1])
#' nd_re <- data.frame(temp = 36, duration = 60, colony = colony)
#' predict(fit_re, nd_re, re.form = "population")
#' predict(fit_re, nd_re, re.form = "conditional")
#' }
#'
#' @importFrom stats predict
#' @export
predict.profile_tls <- function(object, newdata,
                                type = c("survival", "link", "midpoint",
                                         "parameters"),
                                re.form = c("population", "conditional"),
                                ...) {
  dots <- list(...)
  if (length(dots) > 0L) {
    cli::cli_abort("{.arg ...} is reserved; pass only documented arguments.")
  }
  if (inherits(object, "freq_tls")) object <- object$fit
  if (!inherits(object, "profile_tls")) {
    cli::cli_abort("{.arg object} must be a {.cls profile_tls} fit from {.fn fit_tls}.")
  }
  type <- match.arg(type)
  re_form_missing <- missing(re.form)
  re.form <- match.arg(re.form)
  if (missing(newdata) || !is.data.frame(newdata)) {
    cli::cli_abort("{.arg newdata} must be a data frame with columns {.code temp} and {.code duration}.")
  }

  needs_duration <- !type %in% c("midpoint", "parameters")
  required <- if (needs_duration) c("temp", "duration") else "temp"
  missing_cols <- setdiff(required, names(newdata))
  if (length(missing_cols) > 0L) {
    cli::cli_abort(
      "{.arg newdata} is missing required column{?s}: {.code {missing_cols}}."
    )
  }

  temp <- newdata$temp
  if (!is.numeric(temp)) {
    cli::cli_abort("{.code newdata$temp} must be numeric.")
  }
  if (anyNA(temp)) {
    cli::cli_abort("{.code newdata$temp} must not contain missing values.")
  }

  # Resolve per-row CTmax and z from the (possibly grouped) fit.
  if (isTRUE(re_form_missing) && tls_has_re(object)) {
    cli::cli_warn(c(
      "Returning a population prediction with fitted random intercepts set to zero.",
      i = "Use {.code re.form = \"conditional\"} and include each fitted random-effect grouping column in {.arg newdata} to add its BLUP.",
      i = "Use {.code re.form = \"population\"} explicitly to silence this warning."
    ))
  }
  pars <- tls_predict_pars(object, newdata, re.form = re.form)

  if (identical(type, "parameters")) {
    return(data.frame(
      CTmax = pars$CTmax,
      z = pars$z,
      low = pars$low,
      up = pars$up,
      k = pars$k,
      row.names = NULL
    ))
  }

  log10_tref <- log10(object$tref)
  mid <- log10_tref - (temp - pars$CTmax) / pars$z

  if (identical(type, "midpoint")) {
    return(mid)
  }

  duration <- newdata$duration
  if (!is.numeric(duration)) {
    cli::cli_abort("{.code newdata$duration} must be numeric.")
  }
  if (anyNA(duration)) {
    cli::cli_abort("{.code newdata$duration} must not contain missing values.")
  }
  if (any(duration <= 0)) {
    cli::cli_abort("{.code newdata$duration} must be strictly positive (it is log10-transformed).")
  }

  # Per-row shape (constant for shared shapes; per-group for grouped shapes).
  eta <- pars$k * (log10(duration) - mid)
  surv <- tls_curve_mean(eta, pars$low, pars$up,
                         object$curve %||% "loglogistic")

  if (identical(type, "link")) {
    return(stats::qlogis(surv))
  }
  surv
}

#' @rdname predict.profile_tls
#' @export
predict.freq_tls <- function(object, newdata,
                             type = c("survival", "link", "midpoint",
                                      "parameters"),
                             re.form = c("population", "conditional"),
                             ...) {
  predict.profile_tls(
    object = object,
    newdata = newdata,
    type = type,
    re.form = re.form,
    ...
  )
}

#' Resolve per-row CTmax, z, low, up, and k for a prediction
#'
#' Maps each row of `newdata` to its group's parameter values (or the single
#' ungrouped / shared estimate). A shared parameter is recycled across rows; a
#' grouped one (`nm:<level>`) is indexed by the row's group. Validates that any
#' supplied group is a known level. With shared shapes (the default) `low` / `up`
#' / `k` are constant across rows; with grouped shapes they vary by group.
#'
#' @param fit A `profile_tls` fit.
#' @param newdata The prediction data frame.
#' @return A list with numeric vectors `CTmax`, `z`, `low`, `up`, `k`, one element
#'   per row of `newdata`.
#' @keywords internal
#' @noRd
tls_predict_pars <- function(fit, newdata, re.form = "population",
                             include_shapes = TRUE) {
  temp_variable <- fit$prediction_meta$temp_variable %||% NULL
  if (!is.null(temp_variable) && !identical(temp_variable, "temp") &&
      "temp" %in% names(newdata)) {
    # The response formula's `temp(<column>)` identifies the same physical
    # coordinate used by predict()'s `newdata$temp`. Rebuild the source column
    # from that coordinate so shape slopes cannot be evaluated at a stale value.
    newdata[[temp_variable]] <- newdata$temp
  }
  est <- fit$estimates
  levels_g <- fit$group_levels
  ng <- length(levels_g)
  n_row <- nrow(newdata)
  shape_vars <- unique(unlist(lapply(fit$shape_terms %||% list(), all.vars)))
  X_CT_fit <- fit$tmb_inputs$data$X_CT
  X_logz_fit <- fit$tmb_inputs$data$X_logz
  general_fixed <- ncol(X_CT_fit) > 1L && is.null(fit$diag_data$group)
  if (!general_fixed && "group" %in% shape_vars && "group" %in% names(newdata) &&
      length(fit$group_levels) > 1L) {
    group_value <- as.character(newdata$group)
    unknown <- setdiff(unique(group_value), fit$group_levels)
    if (length(unknown)) {
      cli::cli_abort(c(
        "Prediction {.code newdata$group} has levels absent from the fit: {.val {unknown}}.",
        i = "Use one of the fitted levels: {.val {fit$group_levels}}."
      ))
    }
    newdata$group <- factor(group_value, levels = fit$group_levels)
  }
  if ("temp_c" %in% shape_vars && !"temp_c" %in% names(newdata)) {
    center <- fit$prediction_meta$temp_center %||% NULL
    if (!"temp" %in% names(newdata) || is.null(center) || !is.finite(center)) {
      cli::cli_abort(c(
        "Prediction must rebuild the fitted {.code temp_c} shape covariate.",
        i = "Supply {.code temp_c} in {.arg newdata}, or fit standardized data whose {.code tdt_meta$temp_mean} is available."
      ))
    }
    newdata$temp_c <- as.numeric(newdata$temp) - center
  }
  # Per-row group index: 1 for an ungrouped fit, else resolved and validated
  # from newdata$group.
  if (ng == 1L || general_fixed) {
    gi <- rep(1L, n_row)
  } else {
    if (is.null(newdata$group)) {
      cli::cli_abort(c(
        "{.arg newdata} must include a {.code group} column for a grouped fit.",
        i = "Fitted group levels: {.val {levels_g}}."
      ))
    }
    g <- as.character(newdata$group)
    if (anyNA(g)) {
      cli::cli_abort("{.code newdata$group} must not contain missing values.")
    }
    unknown <- setdiff(unique(g), levels_g)
    if (length(unknown) > 0L) {
      cli::cli_abort(c(
        "{.code newdata$group} has level{?s} not in the fit: {.val {unknown}}.",
        i = "Fitted group levels: {.val {levels_g}}."
      ))
    }
    gi <- match(g, levels_g)
  }

  # A shared parameter (one `nm` row) is recycled; a grouped one (`nm:<level>`)
  # is indexed by the row's group.
  resolve <- function(nm) {
    scalar <- est$estimate[est$parameter == nm]
    if (length(scalar) >= 1L) return(rep(scalar[1L], n_row))
    keyed <- est$parameter[startsWith(est$parameter, paste0(nm, ":"))]
    vals <- stats::setNames(
      est$estimate[startsWith(est$parameter, paste0(nm, ":"))],
      sub(paste0("^", nm, ":"), "", keyed)
    )
    unname(vals[levels_g][gi])
  }

  # Shape sub-parameters honour their OWN design. A scalar (1 column) or one-hot
  # grouping is resolved by the group lookup above (byte-identical to before); a
  # general (continuous) design is rebuilt from newdata and its link-scale
  # coefficients applied through the same forward map the engine uses.
  beta_of <- function(nm) {
    p <- fit$par
    unname(p[names(p) == nm])
  }
  X_low_fit  <- fit$tmb_inputs$data$X_low
  X_up_fit  <- fit$tmb_inputs$data$X_up
  X_logk_fit <- fit$tmb_inputs$data$X_logk
  # Reuse the canonical group lookup only for the same single-factor predictor
  # used by CTmax, and only when newdata omits that original column. Equal
  # training matrices from differently named predictors are not interchangeable.
  same_cell_factor <- function(role, X_fit) {
    shape_rhs <- fit$shape_terms[[role]] %||% NULL
    fixed_rhs <- fit$fixed_terms$CTmax %||% NULL
    if (is.null(shape_rhs) || is.null(fixed_rhs) ||
        !tls_is_onehot(X_fit) || !tls_is_onehot(X_CT_fit)) return(FALSE)
    shape_terms <- stats::terms(shape_rhs)
    fixed_terms <- stats::terms(fixed_rhs)
    same_predictor <- identical(attr(shape_terms, "term.labels"),
                                attr(fixed_terms, "term.labels")) &&
      identical(all.vars(tls_formula_rhs(shape_rhs)),
                all.vars(tls_formula_rhs(fixed_rhs))) &&
      length(attr(shape_terms, "term.labels")) == 1L &&
      length(all.vars(tls_formula_rhs(shape_rhs))) == 1L
    same_predictor && identical(unname(X_fit), unname(X_CT_fit)) &&
      !all(all.vars(tls_formula_rhs(shape_rhs)) %in% names(newdata))
  }
  needs_rebuild <- function(role, X_fit) {
    !tls_is_constant_design(X_fit) && !same_cell_factor(role, X_fit)
  }
  rebuild_eta <- function(role, beta_name) {
    if (is.null(fit$shape_terms[[role]])) {
      cli::cli_abort("This fit has no stored design for {.code {role}}; predict needs the formula interface.")
    }
    X_fit <- switch(role, low = X_low_fit, up = X_up_fit,
                    log_k = X_logk_fit)
    Xn <- tls_design_from_rhs(
      fit$shape_terms[[role]], newdata, role,
      fitted_terms = fit$shape_model_terms[[role]],
      fitted_columns = colnames(X_fit)
    )$X
    if (!identical(colnames(Xn), colnames(X_fit))) {
      cli::cli_abort(c(
        "The {.code {role}} design in {.arg newdata} does not match the fitted design.",
        x = "Fitted columns: {.val {colnames(X_fit)}}.",
        x = "Prediction columns: {.val {colnames(Xn)}}."
      ))
    }
    beta <- beta_of(beta_name)
    if (any(is.infinite(beta)) && tls_is_onehot(Xn)) {
      # A rounded asymptote can map to an infinite logit. Select the active
      # cell directly so zero weights never multiply another cell's infinity.
      return(beta[max.col(Xn, ties.method = "first")])
    }
    as.numeric(Xn %*% beta)
  }

  # CTmax and log_z share a fixed design. The legacy grouped-factor path above
  # remains authoritative for cell means; a general design must instead be
  # rebuilt from newdata and multiplied by the fitted link-scale coefficients.
  # Literal tls_bf() calls retain the exact RHS. For fits made from a formula
  # object, direct numeric columns can still be reconstructed from the stored
  # design labels; transformed/interacted designs fail loudly rather than
  # silently returning an intercept-only prediction.
  fixed_rhs <- function(role) {
    stored <- fit$fixed_terms[[role]] %||% NULL
    if (!is.null(stored)) return(stored)
    x_call <- fit$call$x
    if (!is.call(x_call)) return(NULL)
    head <- x_call[[1L]]
    fun <- if (is.symbol(head)) as.character(head) else if (is.call(head)) {
      as.character(head[[length(head)]])
    } else ""
    if (!identical(fun, "tls_bf")) return(NULL)
    tf <- eval(x_call, envir = environment(predict.profile_tls))
    f <- tf$sub_formulas[[role]]
    if (is.null(f)) return(~1)
    rhs <- tls_formula_rhs(f)
    stats::as.formula(paste("~", deparse1(rhs)), env = tf$env)
  }
  rebuild_fixed_eta <- function(role, X_fit, beta_name) {
    rhs <- fixed_rhs(role)
    if (!is.null(rhs)) {
      Xn <- tls_design_from_rhs(
        rhs, newdata, role, fitted_terms = fit$fixed_model_terms[[role]],
        fitted_columns = colnames(X_fit)
      )$X
    } else {
      cols <- colnames(X_fit)
      direct <- setdiff(cols, "(Intercept)")
      missing_direct <- setdiff(direct, names(newdata))
      if (length(missing_direct) > 0L ||
          any(!vapply(newdata[direct], is.numeric, logical(1)))) {
        cli::cli_abort(c(
          "Cannot rebuild the fitted {.code {role}} design from {.arg newdata}.",
          i = "Refit with a literal {.fn tls_bf} call, or supply direct numeric design columns: {.val {direct}}."
        ))
      }
      Xn <- matrix(1, nrow = n_row, ncol = length(cols),
                   dimnames = list(NULL, cols))
      if (length(direct) > 0L) Xn[, direct] <- as.matrix(newdata[direct])
    }
    if (!identical(colnames(Xn), colnames(X_fit))) {
      cli::cli_abort(c(
        "The {.code {role}} design in {.arg newdata} does not match the fitted design.",
        x = "Fitted columns: {.val {colnames(X_fit)}}.",
        x = "Prediction columns: {.val {colnames(Xn)}}."
      ))
    }
    as.numeric(Xn %*% beta_of(beta_name))
  }

  CTmax <- if (general_fixed) {
    rebuild_fixed_eta("CTmax", X_CT_fit, "beta_CT")
  } else {
    resolve("CTmax")
  }
  log_z <- if (general_fixed) {
    rebuild_fixed_eta("log_z", X_logz_fit, "beta_logz")
  } else {
    log(resolve("z"))
  }

  if (!isTRUE(include_shapes)) {
    return(list(CTmax = CTmax, z = exp(log_z)))
  }

  bb <- fit$tmb_inputs$data
  low <- if (needs_rebuild("low", X_low_fit)) {
    bb$low_min + bb$low_w * stats::plogis(rebuild_eta("low", "beta_low"))
  } else {
    resolve("low")
  }
  k <- if (needs_rebuild("log_k", X_logk_fit)) {
    exp(rebuild_eta("log_k", "beta_logk"))
  } else {
    resolve("k")
  }
  up <- if (needs_rebuild("up", X_up_fit)) {
    bb$up_min + bb$up_w * stats::plogis(rebuild_eta("up", "beta_up"))
  } else {
    resolve("up")
  }

  # Conditional predictions add the fitted group-level modes on the same scale
  # used by the TMB objective. Population predictions leave all deviations at
  # zero. Unknown/new groups are not silently assigned a zero BLUP.
  if (identical(re.form, "conditional")) {
    sdr <- fit$sdreport
    if (is.null(sdr)) {
      cli::cli_abort("Conditional prediction needs an available {.code sdreport}; refit and check convergence.")
    }
    sm <- summary(sdr, select = "random")
    for (bk in tls_re_blocks(fit)) {
      gv <- bk$spec$group_var
      if (!gv %in% names(newdata)) {
        cli::cli_abort(c(
          "Conditional prediction needs grouping column {.code {gv}} in {.arg newdata}.",
          i = "Use {.code re.form = \"population\"} for a prediction with random intercepts set to zero."
        ))
      }
      g <- as.character(newdata[[gv]])
      if (anyNA(g)) {
        cli::cli_abort("{.code newdata${gv}} must not contain missing values for conditional prediction.")
      }
      unknown <- setdiff(unique(g), bk$spec$group_levels)
      if (length(unknown) > 0L) {
        cli::cli_abort(c(
          "Conditional prediction cannot use unseen {.code {gv}} level{?s}: {.val {unknown}}.",
          i = "Use {.code re.form = \"population\"} for new groups."
        ))
      }
      rows <- which(rownames(sm) == bk$b_name)
      b <- stats::setNames(unname(sm[rows, "Estimate"]), bk$spec$group_levels)
      bi <- unname(b[g])
      if (identical(bk$param, "CTmax")) CTmax <- CTmax + bi
      if (identical(bk$param, "log_z")) log_z <- log_z + bi
      if (identical(bk$param, "low")) {
        eta_low <- if (tls_is_constant_design(X_low_fit)) {
          rep(beta_of("beta_low")[1L], n_row)
        } else {
          rebuild_eta("low", "beta_low")
        }
        low <- bb$low_min + bb$low_w * stats::plogis(eta_low + bi)
      }
      if (identical(bk$param, "log_k")) {
        eta_logk <- if (tls_is_constant_design(X_logk_fit)) {
          rep(beta_of("beta_logk")[1L], n_row)
        } else {
          rebuild_eta("log_k", "beta_logk")
        }
        k <- exp(eta_logk + bi)
      }
    }
  }

  list(CTmax = CTmax, z = exp(log_z), low = low, up = up, k = k)
}

#' Predict a survival surface over a temperature-by-duration grid
#'
#' `predict_survival_surface()` evaluates the fitted survival probability on a
#' factorial grid of temperatures by durations, returning a long data frame
#' suitable for a heatmap or contour plot (see [plot_survival_surface()]).
#' For random-effects fits this helper returns population-level predictions
#' (random intercepts set to zero); use `predict(..., re.form = "conditional")`
#' for known-group conditional predictions. General continuous fixed designs
#' require `predict()` with their covariate columns supplied in `newdata`.
#'
#' @param object A `profile_tls` fit from [fit_tls()].
#' @param temps Numeric vector of temperatures. Defaults to a length-60
#'   sequence spanning the fit's observed temperature range.
#' @param times Numeric vector of durations (strictly positive). Defaults to a
#'   length-60 log-spaced sequence spanning the fit's observed duration range.
#' @param group Optional single group level (grouped fits only). When `NULL`
#'   (default) the surface is built for every group level and the result
#'   carries a `group` column.
#'
#' @return A long `data.frame` with columns `temp`, `duration`, `survival`
#'   (and `group` when the fit is grouped).
#'
#' @examples
#' d <- simulate_tls(family = "binomial", times = c(30, 60, 120, 240, 480),
#'                   CTmax = 36, z = 4, tref = 60, seed = 1)
#' fit <- fit_tls(d, y = survived, n = total, time = duration, temp = temp,
#'                family = "binomial", tref = 60)
#' head(predict_survival_surface(fit, temps = c(34, 36, 38), times = c(60, 120, 240)))
#'
#' @export
predict_survival_surface <- function(object, temps = NULL, times = NULL,
                                     group = NULL) {
  if (inherits(object, "freq_tls")) object <- object$fit
  if (!inherits(object, "profile_tls")) {
    cli::cli_abort("{.arg object} must be a {.cls profile_tls} fit from {.fn fit_tls}.")
  }
  ds <- object$data_summary
  if (is.null(temps)) {
    temps <- seq(ds$temp_range[1L], ds$temp_range[2L], length.out = 60L)
  }
  if (is.null(times)) {
    # Log-spaced over the observed duration range (durations are on a log axis).
    times <- 10^seq(log10(ds$time_range[1L]), log10(ds$time_range[2L]),
                    length.out = 60L)
  }
  if (!is.numeric(temps) || !is.numeric(times)) {
    cli::cli_abort("{.arg temps} and {.arg times} must be numeric.")
  }
  if (any(times <= 0)) {
    cli::cli_abort("{.arg times} must be strictly positive.")
  }

  levels_g <- object$group_levels
  grouped <- isTRUE(object$data_summary$grouped)

  if (!is.null(group)) {
    if (!grouped) {
      cli::cli_abort("{.arg group} is only meaningful for a grouped fit.")
    }
    group <- as.character(group)
    if (length(group) != 1L || !group %in% levels_g) {
      cli::cli_abort(c(
        "{.arg group} must be a single fitted group level.",
        i = "Fitted group levels: {.val {levels_g}}."
      ))
    }
    use_levels <- group
  } else {
    use_levels <- if (grouped) levels_g else NA_character_
  }

  build_one <- function(lev) {
    grid <- expand.grid(temp = temps, duration = times,
                        KEEP.OUT.ATTRS = FALSE, stringsAsFactors = FALSE)
    nd <- grid
    if (grouped) nd$group <- lev
    grid$survival <- predict(object, nd, type = "survival")
    if (grouped) grid$group <- lev
    grid
  }

  parts <- lapply(use_levels, build_one)
  out <- do.call(rbind, parts)
  rownames(out) <- NULL
  if (grouped) {
    out[, c("temp", "duration", "group", "survival")]
  } else {
    out[, c("temp", "duration", "survival")]
  }
}

#' Derive the lethal / survival-threshold duration at a temperature
#'
#' `derive_lt()` solves the fitted four-parameter curve for the duration at which survival
#' crosses a target probability `p` at each requested temperature (an "LT" / lethal-
#' time-style quantity, e.g. `p = 0.5` gives the absolute 50% survival time).
#' To obtain the curve's relative midpoint, use `p = (low + up) / 2`; that
#' crossing has `log10(duration) = mid` exactly.
#'
#' @details
#' The selected curve maps the normalized fraction `(p - low) / (up - low)`
#' back to `eta = k * (log10(duration) - mid)`. The log-logistic, log-normal,
#' and both Weibull curves use their own inverse map; all return `log10(duration)`
#' relative to the common midpoint.
#' The target must lie strictly between `low` and `up` for a finite crossing;
#' otherwise the survival curve never reaches `p` and `derive_lt()` aborts with
#' an explanatory message (confidence-language, never silent).
#' A vector of `p` values may be supplied, one for each temperature. Temperature-
#' varying shape formulas and a [`freq_tls`][fit_4pl()] workflow fit are supported.
#' For a random-effects fit this is a population-level derived quantity; it does
#' not add a group BLUP (best linear unbiased predictor; see [ranef()]).
#'
#' @param object A `profile_tls` fit from [fit_tls()] or a [`freq_tls`][fit_4pl()]
#'   workflow fit.
#' @param p Absolute target survival probability in `(low, up)` (default `0.5`);
#'   either one value or one value per temperature.
#' @param temp Numeric temperature(s) at which to solve. If `p` is a vector,
#'   it must have the same length as `temp`.
#' @param group Optional single group level (grouped fits only). Required when
#'   the fit is grouped.
#'
#' @return A numeric vector of durations (same length as `temp`) in the fitted
#'   duration unit; `standardize_data()` fits use minutes.
#'
#' @examples
#' d <- simulate_tls(family = "binomial", times = c(30, 60, 120, 240, 480),
#'                   CTmax = 36, z = 4, tref = 60, seed = 1)
#' fit <- fit_tls(d, y = survived, n = total, time = duration, temp = temp,
#'                family = "binomial", tref = 60)
#' # Absolute 50% survival duration at 36 C:
#' derive_lt(fit, p = 0.5, temp = 36)
#'
#' @export
derive_lt <- function(object, p = 0.5, temp, group = NULL) {
  if (inherits(object, "freq_tls")) object <- object$fit
  if (!inherits(object, "profile_tls")) {
    cli::cli_abort("{.arg object} must be a {.cls profile_tls} fit from {.fn fit_tls}.")
  }
  if (missing(temp) || !is.numeric(temp) || length(temp) == 0L) {
    cli::cli_abort("{.arg temp} must be a non-empty numeric vector.")
  }
  if (!is.numeric(p) || length(p) == 0L || anyNA(p) || any(!is.finite(p)) ||
      any(p <= 0 | p >= 1) || !(length(p) %in% c(1L, length(temp)))) {
    cli::cli_abort("{.arg p} must be one probability or one per {.arg temp}, all in (0, 1).")
  }
  if (anyNA(temp)) {
    cli::cli_abort("{.arg temp} must not contain missing values.")
  }

  # Resolve per-row CTmax/z and the group's shape via the same resolver predict()
  # uses (for a grouped-shape fit low/up/k are the group's values).
  nd <- data.frame(temp = temp)
  if (!is.null(group)) {
    group <- as.character(group)
    if (length(group) != 1L) {
      cli::cli_abort("{.arg group} must be a single group level.")
    }
    nd$group <- group
  }
  pars <- tls_predict_pars(object, nd)
  low <- pars$low; up <- pars$up; k <- pars$k
  p <- rep(p, length.out = length(temp))
  valid <- p > low & p < up
  if (!all(valid)) {
    cli::cli_abort(c(
      "Target survival is not between the fitted asymptotes at every requested temperature.",
      i = "Choose a {.arg p} strictly inside the fitted range across {.arg temp}."
    ))
  }

  log10_tref <- log10(object$tref)
  mid <- log10_tref - (temp - pars$CTmax) / pars$z
  # Invert the selected normalized mean curve to recover log10 duration.
  log_dur <- mid + tls_curve_eta_between(
    p, low, up, object$curve %||% "loglogistic"
  ) / k
  10^log_dur
}

#' Find a single threshold crossing inside explicit temperature bounds
#'
#' A varying shape can make the temperature response non-linear. Search a fixed
#' grid first; a missing or multiple detected crossing is reported as unusable.
#' Crossings closer than the grid spacing may not be distinguished.
#' @keywords internal
#' @noRd
tls_bounded_root <- function(fn, target = 0, bounds, grid_n = 201L) {
  if (!is.numeric(bounds) || length(bounds) != 2L || any(!is.finite(bounds)) ||
      bounds[1L] >= bounds[2L] || length(grid_n) != 1L || grid_n < 3L) {
    return(NA_real_)
  }
  grid <- seq(bounds[1L], bounds[2L], length.out = as.integer(grid_n))
  vals <- vapply(grid, function(x) fn(x) - target, numeric(1))
  if (any(!is.finite(vals))) return(NA_real_)
  exact <- which(vals == 0)
  crossings <- which(vals[-length(vals)] * vals[-1L] < 0)
  if (length(exact) + length(crossings) != 1L) return(NA_real_)
  if (length(exact)) return(grid[exact])
  i <- crossings[1L]
  tryCatch(
    stats::uniroot(function(x) fn(x) - target,
                   interval = grid[c(i, i + 1L)], tol = 1e-10)$root,
    error = function(e) NA_real_
  )
}

tls_observed_temp_bounds <- function(fit) {
  fit$data_summary$temp_range %||% fit$diag_data$temp_range %||% NULL
}

tls_absolute_threshold_root <- function(fit, target, duration, group = NULL,
                                         bounds = tls_observed_temp_bounds(fit),
                                         cell = list()) {
  cell <- tls_validate_derived_cell(cell, fit = fit)
  value <- function(temp) {
    nd <- as.data.frame(c(list(temp = temp), cell), stringsAsFactors = FALSE)
    if (!is.null(group) && is.null(cell$group)) {
      nd$group <- as.character(group)
    }
    pars <- tls_predict_pars(fit, nd)
    mid <- log10(fit$tref) - (temp - pars$CTmax) / pars$z
    tls_curve_mean(pars$k * (log10(duration) - mid), pars$low, pars$up,
                   fit$curve %||% "loglogistic")
  }
  tls_bounded_root(value, target = target, bounds = bounds)
}

tls_validate_derived_cell <- function(cell, fit = NULL) {
  if (is.null(cell)) return(list())
  if (is.data.frame(cell)) {
    if (nrow(cell) != 1L) {
      cli::cli_abort("{.arg cell} must have exactly one row of fitted predictor values.")
    }
    cell <- as.list(cell[1L, , drop = FALSE])
  }
  if (is.list(cell) && !length(cell)) return(list())
  if (!is.list(cell) || is.null(names(cell)) ||
      anyNA(names(cell)) || any(!nzchar(names(cell))) || anyDuplicated(names(cell)) ||
      any(lengths(cell) != 1L) || any(vapply(cell, anyNA, logical(1)))) {
    cli::cli_abort(c(
      "{.arg cell} must be {.code NULL} or a named list of single predictor values.",
      i = "For a crossed CTmax design, supply every source column needed by the fitted CTmax and shape formulas, using factor values with their fitted levels when appropriate."
    ))
  }
  temperature_vars <- c("temp", "temp_c")
  if (!is.null(fit$prediction_meta$temp_variable)) {
    temperature_vars <- c(temperature_vars, fit$prediction_meta$temp_variable)
  }
  overridden_temperature <- intersect(names(cell), unique(temperature_vars))
  if (length(overridden_temperature)) {
    cli::cli_abort(c(
      "Temperature predictors cannot be supplied in {.arg cell} for an absolute threshold inversion.",
      i = "The inversion solves for temperature, so remove {.val {overridden_temperature}} from {.arg cell}."
    ))
  }
  cell
}

tls_temperature_varying_shapes <- function(
    fit, allowed_vars = NULL) {
  temperature_vars <- unique(c(
    "temp", "temp_c", fit$prediction_meta$temp_variable %||% NULL
  ))
  allowed_vars <- unique(c(
    allowed_vars %||% "group", temperature_vars
  ))
  varying <- tls_bootstrap_varying_shapes(fit)
  varying[vapply(varying, function(role) {
    rhs <- fit$shape_terms[[role]] %||% NULL
    if (is.null(rhs)) return(FALSE)
    vars <- all.vars(tls_formula_rhs(rhs))
    any(vars %in% temperature_vars) &&
      all(vars %in% allowed_vars)
  }, logical(1))]
}

tls_validate_derived_group <- function(fit, group) {
  if (is.null(group)) return(NULL)
  if (!isTRUE(fit$data_summary$grouped)) {
    cli::cli_abort("{.arg group} is only available for a grouped fit.")
  }
  group <- as.character(group)
  if (length(group) != 1L || is.na(group) || !nzchar(group)) {
    cli::cli_abort("{.arg group} must be one non-missing fitted group level.")
  }
  if (!group %in% fit$group_levels) {
    cli::cli_abort(c(
      "{.arg group} must be one fitted group level.",
      i = "Fitted levels: {.val {fit$group_levels}}."
    ))
  }
  group
}

tls_fit_with_boot_draw <- function(fit, draw) {
  out <- fit
  at <- match(out$estimates$parameter, names(draw))
  if (anyNA(at)) return(NULL)
  out$estimates$estimate <- as.numeric(draw[at])

  X_CT <- fit$tmb_inputs$data$X_CT
  X_logz <- fit$tmb_inputs$data$X_logz
  general_fixed <- ncol(X_CT) > 1L && is.null(fit$diag_data$group)
  if (general_fixed) {
    ct_labels <- paste0("CTmax:", colnames(X_CT))
    z_labels <- paste0("z:", colnames(X_logz))
    if (!all(c(ct_labels, z_labels) %in% names(draw))) return(NULL)
    ix_ct <- which(names(out$par) == "beta_CT")
    ix_logz <- which(names(out$par) == "beta_logz")
    ct_values <- unname(draw[ct_labels])
    z_values <- unname(draw[z_labels])
    if (length(ix_ct) != length(ct_values) ||
        length(ix_logz) != length(z_values) ||
        any(!is.finite(ct_values)) || any(!is.finite(z_values)) ||
        any(z_values <= 0)) return(NULL)
    out$par[ix_ct] <- ct_values
    out$par[ix_logz] <- log(z_values)
  }

  for (spec in list(
    list(role = "low", beta = "beta_low", natural = "low", X = fit$tmb_inputs$data$X_low),
    list(role = "up", beta = "beta_up", natural = "up", X = fit$tmb_inputs$data$X_up),
    list(role = "log_k", beta = "beta_logk", natural = "k", X = fit$tmb_inputs$data$X_logk)
  )) {
    if (tls_is_constant_design(spec$X)) next
    labels <- paste0(spec$natural, ":", colnames(spec$X))
    ix <- which(names(out$par) == spec$beta)
    vals <- draw[labels]
    if (length(ix) != length(vals) || any(!is.finite(vals))) return(NULL)
    if (tls_is_onehot(spec$X)) {
      if (identical(spec$role, "log_k")) {
        if (any(vals <= 0)) return(NULL)
        vals <- log(vals)
      } else {
        bounds <- fit$tmb_inputs$data
        lower <- bounds[[paste0(spec$role, "_min")]]
        width <- bounds[[paste0(spec$role, "_w")]]
        if (any(vals < lower | vals > lower + width)) return(NULL)
        vals <- stats::qlogis(pmin((vals - lower) / width, 1))
      }
    }
    out$par[ix] <- vals
  }
  out
}

#' Derive the temperature giving a target survival at a fixed exposure
#'
#' `derive_ctmax()` inverts the fitted thermal-survival curve for **temperature**: it returns the
#' assay temperature at which survival equals a target `surv` after exposure
#' `duration`. By default `surv` is the *relative* midpoint threshold
#' `(low + up) / 2` and `duration` is `tref`, so `derive_ctmax(fit)` reproduces
#' the fitted `CTmax`. Supplying an **absolute** `surv` gives the absolute-
#' threshold critical temperature (the analogue of the `bayesTLS`
#' `extract_tdt()` absolute mode), with the asymmetry correction
#' family-specific inverse curve built in, including the exact log-logistic
#' inverse for the default model.
#' For a supplied absolute `surv` target, a temperature-varying shape uses a
#' 201-point bounded scan and refines one crossing detected inside `temp_bounds`
#' (the observed range by default). The relative default uses the analytic
#' inverse. Crossings closer than the scan spacing may not be distinguished.
#'
#' @details
#' Let `eta_curve(q)` be the inverse of the selected normalized survival curve
#' at `q = (surv - low) / (up - low)`. Solving for temperature gives
#' `temp = CTmax - z * (log10(duration) - log10(tref) - eta_curve(q) / k)`.
#' The target `surv` must lie strictly between `low` and `up`.
#' For a supplied absolute `surv` target, a temperature-varying shape uses bounded
#' numerical inversion and requires one crossing detected by the fixed grid
#' inside the search interval. The relative default is evaluated analytically.
#' For a random-effects fit this is a population-level derived quantity; it does
#' not add a group BLUP (best linear unbiased predictor; see [ranef()]).
#'
#' @param object A `profile_tls` fit from [fit_tls()].
#' @param surv Target survival probability in `(low, up)`. `NULL` (default) uses
#'   the relative midpoint `(low + up) / 2`, reproducing `CTmax` at `tref`.
#' @param duration Exposure duration(s) (native time unit; strictly positive).
#'   Defaults to the fit's `tref`.
#' @param group Optional single group level (grouped fits only).
#' @param cell Optional named list of one-row predictor values for a general
#'   formula design. Use this when CTmax cells combine predictors and a shape
#'   formula uses one of the source columns, for example
#'   `cell = list(group = factor("A", levels = c("A", "B")),
#'   site = factor("north", levels = c("north", "south")))` for
#'   `CTmax ~ group:site`. For an absolute inversion, omit `temp`, `temp_c`,
#'   and the source column named in `temp()`; the inversion sets those from its
#'   candidate temperature.
#' @param temp_bounds Optional finite increasing temperature bounds for the
#'   numerical inverse used when a fitted shape depends on temperature. The
#'   default is the fitted data's observed temperature range.
#' @return A numeric vector of temperatures (degrees C), one per `duration`.
#' @examples
#' d <- simulate_tls(family = "binomial", times = c(30, 60, 120, 240, 480),
#'                   CTmax = 36, z = 4, tref = 60, seed = 1)
#' fit <- fit_tls(d, y = survived, n = total, time = duration, temp = temp,
#'                family = "binomial", tref = 60)
#' derive_ctmax(fit)                                  # ~ CTmax (relative, at tref)
#' derive_ctmax(fit, surv = 0.5, duration = c(60, 240)) # absolute 50% survival
#' @export
derive_ctmax <- function(object, surv = NULL, duration = NULL, group = NULL,
                         temp_bounds = NULL, cell = NULL) {
  if (inherits(object, "freq_tls")) object <- object$fit
  if (!inherits(object, "profile_tls")) {
    cli::cli_abort("{.arg object} must be a {.cls profile_tls} fit from {.fn fit_tls}.")
  }
  group <- tls_validate_derived_group(object, group)
  cell <- tls_validate_derived_cell(cell, fit = object)
  if (is.null(duration)) duration <- object$tref
  if (!is.numeric(duration) || length(duration) == 0L) {
    cli::cli_abort("{.arg duration} must be a non-empty numeric vector.")
  }
  if (anyNA(duration) || any(duration <= 0)) {
    cli::cli_abort("{.arg duration} must be strictly positive (it is log10-transformed).")
  }
  absolute_target <- !is.null(surv)
  varying_shapes <- tls_bootstrap_varying_shapes(object)
  temperature_shapes <- tls_temperature_varying_shapes(
    object, allowed_vars = unique(c("temp", "temp_c", "group", names(cell)))
  )
  if (absolute_target && length(varying_shapes)) {
    if (length(setdiff(varying_shapes, temperature_shapes))) {
      cli::cli_abort(c(
        "Absolute-threshold {.fn derive_ctmax} cannot invert non-temperature shape predictors without their values.",
        i = "Use a shape formula based on {.code temp} or {.code temp_c}, or supply a model with shared shapes."
      ))
    }
    bounds <- temp_bounds %||% tls_observed_temp_bounds(object)
    if (!is.numeric(bounds) || length(bounds) != 2L || any(!is.finite(bounds)) ||
        bounds[1L] >= bounds[2L]) {
      cli::cli_abort("For a temperature-varying shape, {.arg temp_bounds} must contain two finite increasing temperatures.")
    }
    if (!is.numeric(surv) || length(surv) != 1L || !is.finite(surv) ||
        surv <= 0 || surv >= 1) {
      cli::cli_abort("With a temperature-varying shape, {.arg surv} must be one finite probability in (0, 1).")
    }
    if (any(!is.finite(duration)) || any(duration <= 0)) {
      cli::cli_abort("{.arg duration} must contain finite, strictly positive values.")
    }
    return(vapply(duration, function(d) {
      root <- tls_absolute_threshold_root(object, surv, d, group = group,
                                          bounds = bounds, cell = cell)
      if (!is.finite(root)) {
        cli::cli_abort(c(
          "The bounded scan did not find one absolute survival crossing inside {.arg temp_bounds}.",
          i = "Use bounds that contain one detected crossing or fit a monotone temperature response."
        ))
      }
      root
    }, numeric(1)))
  }
  if (!absolute_target) {
    nd <- as.data.frame(c(list(temp = rep(NA_real_, length(duration))), cell),
                        stringsAsFactors = FALSE)
    if (!is.null(group)) {
      group <- as.character(group)
      if (length(group) != 1L) cli::cli_abort("{.arg group} must be a single group level.")
      nd$group <- group
    }
    pars <- tls_predict_pars(object, nd, include_shapes = FALSE)
    return(pars$CTmax - pars$z *
      (log10(duration) - log10(object$tref)))
  }

  # Resolve per-row CTmax/z and the group's shape via the same resolver
  # predict()/derive_lt() use.
  nd <- as.data.frame(c(list(temp = rep(NA_real_, length(duration))), cell),
                      stringsAsFactors = FALSE)
  if (!is.null(group)) {
    group <- as.character(group)
    if (length(group) != 1L) cli::cli_abort("{.arg group} must be a single group level.")
    nd$group <- group
  }
  pars <- tls_predict_pars(object, nd)
  low <- pars$low[1L]; up <- pars$up[1L]; k <- pars$k[1L]

  if (is.null(surv)) surv <- (low + up) / 2
  if (!is.numeric(surv) || length(surv) != 1L) {
    cli::cli_abort("{.arg surv} must be a single number (or {.code NULL}).")
  }
  if (!(surv > low && surv < up)) {
    cli::cli_abort(c(
      "Target survival {.val {surv}} is not between the fitted asymptotes.",
      i = "Survival ranges in ({round(low, 3)}, {round(up, 3)}); pick a {.arg surv} strictly inside that range."
    ))
  }

  log10_tref <- log10(object$tref)
  eta <- tls_curve_eta_between(surv, low, up,
                               object$curve %||% "loglogistic")
  pars$CTmax - pars$z * (log10(duration) - log10_tref - eta / k)
}

#' Derive the critical temperature at a damage-rate floor (T_crit)
#'
#' `derive_tcrit()` returns the rate-multiplier critical temperature `T_crit`: the
#' temperature at which the thermal-damage rate falls to a chosen low floor
#' `rate`. It is the maximum-likelihood analogue of the `bayesTLS`
#' `extract_tdt()` absolute-family `T_crit`. It first expresses the requested
#' survival threshold at one hour, then applies the rate floor:
#' `T_crit = CTmax - z * log10(60 / tref) +
#' z * eta_curve((target_surv - low) / (up - low)) / k +
#' z * log10(rate / 100)`.
#' The inverse uses the selected curve family, including the log-logistic default.
#' At `rate = 100`, the result is the one-hour temperature at `target_surv`.
#' Lower rates place `T_crit` below that one-hour threshold for constant shapes.
#' For temperature-varying shapes, freqTLS instead solves for a unique crossing
#' at the equivalent exposure `60 * 100 / rate` minutes inside the observed
#' temperature range.
#' It is the temperature cutoff that a heat-injury accumulation model treats as
#' negligible damage.
#'
#' @details
#' `rate` is a damage-rate floor expressed as a **percentage of the lethal dose
#' per hour**; `bayesTLS` brackets observed breakpoints with a default range of
#' `0.1`--`1` %/hour. Unlike the Bayesian path, which samples `rate` to fold an
#' operational choice into the posterior, freqTLS treats `rate` as a fixed
#' input and returns the deterministic transform of the fitted `CTmax` and `z`.
#' `target_surv` defaults to the fitted relative midpoint `(low + up) / 2`;
#' supply one probability strictly between the fitted asymptotes for an absolute
#' threshold.
#' For the default relative target, uncertainty depends on `CTmax` and `z`. For
#' an explicit absolute `target_surv`, it also depends on `low`, `up`, and `k`.
#' Apply the delta method to the joint covariance matrix of every parameter in
#' the selected expression; separate marginal confidence intervals do not
#' combine into a valid interval for `T_crit`.
#' Relative `T_crit` remains defined for temperature-varying shapes because the
#' midpoint correction is zero. An explicit absolute target uses a bounded root
#' search and errors when the observed range does not contain exactly one crossing.
#' For a random-effects fit this is a population-level derived quantity; it does
#' not add a group BLUP (best linear unbiased predictor; see [ranef()]).
#'
#' `T_crit` assumes a **lethal endpoint**: it is a damage-accumulation concept, so
#' for sublethal endpoints (knockdown, photosynthetic failure) the steeper `z`
#' drives it implausibly low. `derive_tcrit()` says so, once per call.
#'
#' @param object A `profile_tls` fit from [fit_tls()].
#' @param rate Damage-rate floor(s), a percentage of the lethal dose per hour
#'   (strictly positive). A scalar or a vector; default `1`.
#' @param group Optional single group level (grouped fits only; required when the
#'   fit is grouped).
#' @param target_surv One survival probability strictly between the fitted
#'   asymptotes. `NULL` (default) selects the relative midpoint.
#' @param cell Optional named list of one-row predictor values for a general
#'   formula design whose CTmax cells combine source columns. For an absolute
#'   inversion, omit `temp`, `temp_c`, and the source column named in `temp()`;
#'   the inversion sets those from its candidate temperature.
#' @return A numeric vector of critical temperatures (degrees C), one per `rate`.
#' @seealso [derive_ctmax()] for the absolute-threshold critical temperature.
#' @examples
#' d <- simulate_tls(family = "binomial", times = c(30, 60, 120, 240, 480),
#'                   CTmax = 36, z = 4, tref = 60, seed = 1)
#' fit <- fit_tls(d, y = survived, n = total, time = duration, temp = temp,
#'                family = "binomial", tref = 60)
#' derive_tcrit(fit, rate = c(0.1, 1)) # lower thermal thresholds
#' @export
derive_tcrit <- function(object, rate = 1, group = NULL, target_surv = NULL,
                         cell = NULL) {
  if (inherits(object, "freq_tls")) object <- object$fit
  if (!inherits(object, "profile_tls")) {
    cli::cli_abort("{.arg object} must be a {.cls profile_tls} fit from {.fn fit_tls}.")
  }
  group <- tls_validate_derived_group(object, group)
  cell <- tls_validate_derived_cell(cell, fit = object)
  varying_shapes <- tls_bootstrap_varying_shapes(object)
  temperature_shapes <- tls_temperature_varying_shapes(
    object, allowed_vars = unique(c("temp", "temp_c", "group", names(cell)))
  )
  absolute_target <- !is.null(target_surv)
  if (!is.numeric(rate) || length(rate) == 0L || anyNA(rate) ||
      any(!is.finite(rate)) || any(rate <= 0)) {
    cli::cli_abort(c(
      "{.arg rate} must be a non-empty vector of finite, strictly positive damage-rate floors.",
      i = "It is a percentage of the lethal dose per hour (the {.code bayesTLS} default range is 0.1-1)."
    ))
  }

  if (absolute_target && length(varying_shapes)) {
    if (length(setdiff(varying_shapes, temperature_shapes))) {
      cli::cli_abort(c(
        "Absolute {.code T_crit} cannot invert shape predictors other than temperature.",
        i = "Use constant/cell-mean shapes or temperature-only shape formulas."
      ))
    }
    if (!is.numeric(target_surv) || length(target_surv) != 1L ||
        !is.finite(target_surv) || target_surv <= 0 || target_surv >= 1) {
      cli::cli_abort("{.arg target_surv} must be one finite probability in (0, 1).")
    }
    cli::cli_inform(
      "{.code T_crit} assumes a lethal endpoint; for sublethal data its steeper {.code z} makes it implausibly low."
    )
    bounds <- tls_observed_temp_bounds(object)
    out <- vapply(rate, function(r) {
      tls_absolute_threshold_root(
        object, target_surv, duration = 60 * 100 / r, group = group,
        bounds = bounds, cell = cell
      )
    }, numeric(1))
    if (any(!is.finite(out))) {
      cli::cli_abort(c(
        "The bounded scan did not find one absolute {.code T_crit} crossing inside the observed temperature range for every {.arg rate}.",
        i = "Check the fitted shape and threshold, or use {.code target_surv = NULL} for the relative midpoint."
      ))
    }
    return(out)
  }

  # Resolve CTmax and z for the requested group via the same resolver predict()
  # and derive_ctmax() use; one row is enough since T_crit varies only with rate.
  nd <- as.data.frame(c(list(temp = NA_real_), cell), stringsAsFactors = FALSE)
  if (!is.null(group)) {
    group <- as.character(group)
    if (length(group) != 1L) cli::cli_abort("{.arg group} must be a single group level.")
    nd$group <- group
  }
  pars <- tls_predict_pars(object, nd, include_shapes = absolute_target)
  if (!absolute_target) {
    cli::cli_inform(
      "{.code T_crit} assumes a lethal endpoint; for sublethal data its steeper {.code z} makes it implausibly low."
    )
    return(pars$CTmax[1L] - pars$z[1L] * log10(60 / object$tref) +
             pars$z[1L] * log10(rate / 100))
  }
  low <- pars$low[1L]
  up <- pars$up[1L]
  k <- pars$k[1L]
  if (is.null(target_surv)) target_surv <- (low + up) / 2
  if (!is.numeric(target_surv) || length(target_surv) != 1L ||
      !is.finite(target_surv) || target_surv <= low || target_surv >= up) {
    cli::cli_abort("{.arg target_surv} must be one finite survival probability strictly between the fitted asymptotes.")
  }
  tref <- object$tref
  eta <- tls_curve_eta_between(target_surv, low, up,
                               object$curve %||% "loglogistic")
  ctmax_1h <- pars$CTmax - pars$z * log10(60 / tref) +
    pars$z * eta / k
  z <- pars$z[1L]

  cli::cli_inform(
    "{.code T_crit} assumes a lethal endpoint; for sublethal data its steeper {.code z} makes it implausibly low."
  )
  ctmax_1h + pars$z[1L] * log10(rate / 100)
}

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.