R/extract_tdt.R

Defines functions get_tcrit_draws get_tcrit_summary get_ctmax_draws get_ctmax_summary get_z_draws get_z_summary stop_if_not_freq_tdt print.freq_tdt extract_tdt

Documented in extract_tdt get_ctmax_draws get_ctmax_summary get_tcrit_draws get_tcrit_summary get_z_draws get_z_summary

# The bayesTLS-analogue comprehensive extractor. extract_tdt() returns the nested
# $z / $CTmax / $T_crit structure (draws + summary) bayesTLS produces, but the
# per-"draw" rows are parametric-bootstrap replicates (the frequentist analogue
# of posterior draws) rather than MCMC draws. Point estimates (`*_median`) are the
# MLE; intervals are bootstrap percentiles. z is threshold-invariant under the
# constant-shape model; CTmax shifts with the survival threshold; T_crit is the
# damage-rate-floor critical temperature derived per replicate.

#' Extract z, CTmax and (optionally) T_crit with bootstrap confidence intervals
#'
#' The frequentist analogue of `bayesTLS::extract_tdt()`. Runs a parametric bootstrap
#' (via the freqTLS engine), derives the thermal-death-time quantities on each
#' replicate, and returns the same nested `$z` / `$CTmax` / `$T_crit` structure
#' (each a list of `draws` + `summary`). Each row of a per-replicate table is a
#' derived estimate from one parametric-bootstrap refit: it is a resampled
#' frequentist estimate, not a posterior draw. `*_median` is the
#' maximum-likelihood point estimate and `*_lower` / `*_upper` are bootstrap
#' percentiles.
#' Absolute-target bootstrap values are calculated or inverted for each refit.
#' A draw whose target lies outside its refit's asymptotes, or has no unique
#' crossing for a temperature-varying shape, is retained as `NA` with
#' `.valid = FALSE`; counts by quantity and fitted group are returned in
#' `meta$inversion_counts`. Absolute-target percentile limits are conditional on
#' converged refits whose asymptotes bracket the target. For temperature-varying
#' shapes, a usable draw must also have one detected crossing over the pooled
#' fitted temperature range. Limits are withheld when fewer than 20 usable
#' refits remain for a target and group. If no refit converges, extraction
#' errors because there are no draws to return.
#'
#' @param object A `freq_tls` fit from [fit_4pl()] (or a `profile_tls` fit).
#' @param target_surv `"relative"` (curve midpoint, default), `"absolute"`
#'   (50% survival), or a numeric survival level in `(0, 1)` for an LTx CTmax.
#'   An absolute target must lie strictly between the fitted `low` and `up`
#'   asymptotes. Temperature-varying shapes also require one crossing inside the
#'   observed temperature range for each fitted group. Constant or cell-mean
#'   shapes use the closed form; temperature-varying shapes use a bounded inverse. This target changes
#'   `CTmax` (and `T_crit` when requested); returned `z` remains the model's
#'   thermal-sensitivity coordinate at the relative curve midpoint.
#' @param lethal If `TRUE`, also derive `T_crit` (the damage-rate-floor critical
#'   temperature, using a one-hour anchor for constant shapes and a bounded
#'   inverse at the equivalent duration for temperature-varying shapes. `rate`
#'   is log-uniform over `TC_rate_range`.
#' @param TC_rate_range Two finite positive damage-rate floor endpoints (percent
#'   of lethal dose per hour) for `T_crit`, in non-decreasing order. Equal
#'   endpoints specify a fixed rate. Used only when `lethal = TRUE`; default
#'   `c(0.1, 1)`.
#' @param nboot Number of bootstrap replicates (default 1000; smaller is faster).
#'   Percentile limits require at least 20 usable refits per quantity and group.
#'   With fewer usable refits, limits are `NA`; converged draws and the
#'   requested/converged/failed counts remain available. The examples request
#'   50 refits to allow some failures while still demonstrating finite limits.
#' @param level Confidence level, one number strictly between zero and one
#'   (default 0.95).
#' @param seed Optional RNG seed for reproducible replicates / rate draws.
#' @param by Optional name or names of source-data grouping columns; defaults to
#'   the fit moderator. Crossed cell-means fits can report multiple columns.
#' @return A list with `$z`, `$CTmax`, (`$T_crit` when `lethal`), and `$meta`.
#'   Each quantity is `list(draws = <tibble>, summary = <tibble>)`. Column names
#'   follow bayesTLS: `z_median/z_lower/z_upper` for z; `temp_median/temp_lower/
#'   temp_upper` for CTmax and T_crit; per-draw value columns are `z` / `temp`.
#'   `$meta$tref` records the reference time; `$meta$duration_unit` is retained
#'   when the input is a [fit_4pl()] workflow. `$meta$z_definition` clarifies
#'   that `z` remains the relative-midpoint model coordinate even when an
#'   absolute target was used. `$meta$interval_counts` records usable refits and
#'   the status of each percentile interval.
#' @seealso [fit_4pl()], [tls()], [get_z_summary()], [get_ctmax_summary()]
#' @examples
#' \donttest{
#' 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, quiet = TRUE)
#' tdt <- extract_tdt(fit, nboot = 50, seed = 1)
#' tdt$CTmax$summary
#' }
#' @export
extract_tdt <- function(object, target_surv = "relative", lethal = FALSE,
                        TC_rate_range = c(0.1, 1), nboot = 1000L,
                        level = 0.95, seed = NULL, by = NULL) {
  if (inherits(object, "freq_tls")) {
    fit <- object$fit; meta <- object$meta
  } else if (inherits(object, "profile_tls")) {
    fit <- object; meta <- list()
  } else {
    cli::cli_abort("{.arg object} must be a {.cls freq_tls} or {.cls profile_tls} fit.")
  }

  tls_validate_level(level)
  if (isTRUE(lethal) &&
      (!is.numeric(TC_rate_range) || length(TC_rate_range) != 2L ||
       any(!is.finite(TC_rate_range)) || any(TC_rate_range <= 0) ||
       TC_rate_range[[1L]] > TC_rate_range[[2L]])) {
    cli::cli_abort(c(
      "When {.arg lethal = TRUE}, {.arg TC_rate_range} must contain two finite positive rates in non-decreasing order.",
      i = "Equal endpoints are allowed for a fixed damage-rate floor."
    ))
  }

  if (is.character(target_surv)) {
    target_surv <- match.arg(target_surv, c("relative", "absolute"))
    mode <- target_surv
    p <- if (identical(mode, "absolute")) 0.5 else NA_real_
  } else if (is.numeric(target_surv) && length(target_surv) == 1L &&
             is.finite(target_surv) && target_surv > 0 && target_surv < 1) {
    mode <- "absolute"; p <- as.numeric(target_surv)
  } else {
    cli::cli_abort('{.arg target_surv} must be "relative", "absolute", or a number in (0, 1).')
  }

  est <- fit$estimates
  by_names <- by %||% meta$moderators %||% "group"
  source_data <- if (inherits(object, "freq_tls")) object$data else NULL
  if (!is.character(by_names) || !length(by_names) || anyNA(by_names) ||
      any(!nzchar(by_names)) || anyDuplicated(by_names)) {
    cli::cli_abort("{.arg by} must name one or more distinct source-data columns.")
  }
  ct_rows <- est[grepl("^CTmax(:|$)", est$parameter), , drop = FALSE]
  z_rows  <- est[grepl("^z(:|$)",   est$parameter), , drop = FALSE]
  grouped <- any(grepl(":", ct_rows$parameter))
  if (grouped) {
    X_CT <- fit$tmb_inputs$data$X_CT
    X_logz <- fit$tmb_inputs$data$X_logz
    matching_cells <- tls_is_onehot(X_CT) && tls_is_onehot(X_logz) &&
      identical(colnames(X_CT), colnames(X_logz)) &&
      identical(unname(X_CT), unname(X_logz)) && all(colSums(abs(X_CT)) > 0)
    label_map <- if (matching_cells) {
      tls_cellmean_labels(X_CT, source_data, by_names)
    } else NULL
    fallback_by <- meta$moderators %||% "group"
    if (is.null(label_map) && is.null(source_data) &&
        identical(by_names, fallback_by) && matching_cells &&
        length(by_names) == 1L &&
        length(fit$group_levels) == ncol(X_CT)) {
      label_map <- data.frame(.cell = colnames(X_CT), stringsAsFactors = FALSE)
      label_map[[by_names]] <- as.character(fit$group_levels)
    }
    if (is.null(label_map)) {
      cli::cli_abort(c(
        "Grouped {.fn extract_tdt} requires matching represented cell-mean designs for {.code CTmax} and {.code log_z}.",
        i = "The requested source columns must identify each fitted cell uniquely; for crossed cells, supply all required grouping columns."
      ))
    }
  } else label_map <- NULL
  label_for <- function(g) {
    if (!grouped) return(NULL)
    i <- match(g, label_map$.cell)
    if (is.na(i)) cli::cli_abort("Could not map a fitted group label to its source rows.")
    as.list(label_map[i, by_names, drop = FALSE])
  }
  mk_draws <- function(gl, v, value_name, extra = NULL) {
    cols <- list()
    if (!is.null(gl)) cols <- c(cols, gl)
    cols$.draw <- seq_along(v)
    cols[[value_name]] <- v
    if (!is.null(extra)) cols <- c(cols, extra)
    as.data.frame(cols, stringsAsFactors = FALSE)
  }
  mk_summ <- function(gl, med, q2, nms) {
    cols <- list()
    if (!is.null(gl)) cols <- c(cols, gl)
    cols[[nms[1L]]] <- med; cols[[nms[2L]]] <- q2[[1L]]; cols[[nms[3L]]] <- q2[[2L]]
    as.data.frame(cols, stringsAsFactors = FALSE)
  }

  varying_shapes <- tls_bootstrap_varying_shapes(fit)
  temperature_shapes <- tls_temperature_varying_shapes(
    fit, allowed_vars = c("temp", "temp_c", "group", by_names)
  )
  if (identical(mode, "absolute") && length(varying_shapes)) {
    if (length(setdiff(varying_shapes, temperature_shapes))) {
      cli::cli_abort(c(
        "Absolute-threshold extraction cannot invert shape predictors other than temperature.",
        i = "Use shared/cell-mean shapes or formulas based only on {.code temp} / {.code temp_c}."
      ))
    }
  }

  if (identical(mode, "absolute")) {
    shape_designs <- list(
      low = fit$tmb_inputs$data$X_low,
      up = fit$tmb_inputs$data$X_up,
      log_k = fit$tmb_inputs$data$X_logk
    )
    same_rhs <- function(a, b) {
      if (is.null(a) || is.null(b)) return(is.null(a) && is.null(b))
      ta <- stats::terms(a); tb <- stats::terms(b)
      identical(attr(ta, "term.labels"), attr(tb, "term.labels")) &&
        identical(all.vars(tls_formula_rhs(a)), all.vars(tls_formula_rhs(b)))
    }
    fixed_rhs <- fit$fixed_terms$CTmax %||% NULL
    matched <- vapply(names(shape_designs), function(role) {
      X <- shape_designs[[role]]
      if (tls_is_constant_design(X) || role %in% temperature_shapes) return(TRUE)
      grouped && identical(unname(X), unname(fit$tmb_inputs$data$X_CT)) &&
        same_rhs(fit$shape_terms[[role]], fixed_rhs)
    }, logical(1))
    if (!all(matched)) {
      cli::cli_abort(c(
        "Absolute-threshold extraction requires shared shapes or shapes matched to the CTmax cells.",
        i = "An independent shape grouping does not define one absolute threshold per CTmax group."
      ))
    }
  }

  alpha <- (1 - level) / 2; qs <- c(alpha, 1 - alpha)
  min_usable_bootstrap <- 20L
  boot <- tls_bootstrap_replicates(fit, nboot = nboot, seed = seed)
  R <- boot$replicates[boot$converged, , drop = FALSE]
  if (!nrow(R))
    cli::cli_abort("No bootstrap refits converged; increase {.arg nboot} or inspect the fitted model.")

  # Grouped iff coefficients are level-tagged ("CTmax:lvl"); an ungrouped fit's
  # single "all"/intercept level is not surfaced as a group column.
  z_d <- z_s <- c_d <- c_s <- t_d <- t_s <- vector("list", nrow(ct_rows))
  inversion_counts <- list()
  interval_counts <- list()
  bootstrap_interval <- function(quantity, gl, values) {
    valid <- is.finite(values)
    n_usable <- sum(valid)
    group_label <- if (is.null(gl) || !length(gl)) NA_character_ else
      paste(paste(names(gl), unlist(gl, use.names = FALSE), sep = "="),
            collapse = ", ")
    interval_counts[[length(interval_counts) + 1L]] <<- data.frame(
      quantity = quantity, group = group_label,
      n_requested = boot$nboot, n_converged = nrow(R),
      n_failed = boot$nboot - nrow(R),
      n_usable = n_usable, n_unusable = nrow(R) - n_usable,
      conf.status = if (n_usable >= min_usable_bootstrap)
        "bootstrap" else "bootstrap_unstable",
      stringsAsFactors = FALSE
    )
    if (n_usable < min_usable_bootstrap) {
      cli::cli_warn(c(
        "Only {n_usable} of {boot$nboot} requested bootstrap refits are usable for {.val {quantity}}{if (!is.na(group_label)) paste0(' in ', group_label)}.",
        i = "The percentile limits are unavailable below {min_usable_bootstrap} usable refits; returning {.val NA} limits. Usable draws remain in the returned draw table."
      ))
      return(c(NA_real_, NA_real_))
    }
    stats::quantile(values[valid], qs, names = FALSE)
  }
  for (i in seq_len(nrow(ct_rows))) {
    g  <- ct_rows$group[i]; gl <- label_for(g)
    zi <- if (is.na(g)) 1L else match(g, z_rows$group)
    z_v <- R[, z_rows$parameter[zi]]; z_mle <- z_rows$estimate[zi]
    ctr_v <- R[, ct_rows$parameter[i]]; ctr_mle <- ct_rows$estimate[i]

    z_d[[i]] <- mk_draws(gl, z_v, "z")
    z_q <- bootstrap_interval("z", gl, z_v)
    z_s[[i]] <- mk_summ(gl, z_mle, z_q,
                        c("z_median", "z_lower", "z_upper"))

    if (identical(mode, "absolute")) {
      if (length(temperature_shapes)) {
        cell <- gl %||% list()
        ct_v <- vapply(seq_len(nrow(R)), function(j) {
          draw_fit <- tls_fit_with_boot_draw(fit, R[j, ])
          if (is.null(draw_fit)) return(NA_real_)
          tls_absolute_threshold_root(draw_fit, p, duration = fit$tref,
                                      group = g, bounds = tls_observed_temp_bounds(fit),
                                      cell = cell)
        }, numeric(1))
        ct_mle <- tls_absolute_threshold_root(
          fit, p, duration = fit$tref, group = g,
          bounds = tls_observed_temp_bounds(fit), cell = cell
        )
        if (!is.finite(ct_mle)) {
          cli::cli_abort(c(
            "The bounded scan did not find one fitted absolute-threshold crossing for group {.val {g}} inside the observed temperature range.",
            i = "Check the target and temperature-varying shape fit."
          ))
        }
        valid_ct <- is.finite(ct_v)
        inversion_counts[[length(inversion_counts) + 1L]] <- data.frame(
          quantity = "CTmax", group = as.character(g),
          n_requested = boot$nboot, n_converged = length(ct_v),
          n_usable = sum(valid_ct),
          n_unusable = sum(!valid_ct), stringsAsFactors = FALSE
        )
        if (any(!valid_ct)) {
          cli::cli_warn(c(
            "{sum(!valid_ct)} of {length(ct_v)} converged bootstrap refits had no single detected absolute-threshold crossing for group {.val {g}}.",
            i = "Those draws are retained as {.code NA} and counted in {.field meta$inversion_counts}."
          ))
        }
      } else {
        shape_col <- function(name) {
          if (name %in% colnames(R)) name else {
            cell_name <- paste0(name, ":", g)
            if (cell_name %in% colnames(R)) cell_name else
              cli::cli_abort(c(
                "Absolute-threshold extraction cannot match {.code {name}} to group {.val {g}}.",
                i = "Use shared shapes or cell-mean shape formulas on the same group labels."
              ))
          }
        }
        low_col <- shape_col("low"); up_col <- shape_col("up"); k_col <- shape_col("k")
        low_v <- R[, low_col]; up_v <- R[, up_col]; k_v <- R[, k_col]
        low_mle <- est$estimate[est$parameter == low_col]
        up_mle <- est$estimate[est$parameter == up_col]
        k_mle <- est$estimate[est$parameter == k_col]
        valid_target <- is.finite(low_v) & is.finite(up_v) &
          is.finite(ctr_v) & is.finite(z_v) & is.finite(k_v) & k_v != 0 &
          p > low_v & p < up_v
        if (!(p > low_mle && p < up_mle)) {
          cli::cli_abort(c(
            "The absolute {.arg target_surv} {.val {p}} is not attainable in the fitted curve for group {.val {gl}}.",
            i = "Choose a target farther from the fitted asymptotes, or use the relative midpoint threshold."
          ))
        }
        ct_v <- rep(NA_real_, length(low_v))
        if (any(valid_target)) {
          ct_v[valid_target] <- ctr_v[valid_target] +
            z_v[valid_target] * tls_curve_eta_between(
              p, low_v[valid_target], up_v[valid_target],
              fit$curve %||% "loglogistic"
            ) / k_v[valid_target]
        }
        ct_mle <- ctr_mle + z_mle * tls_curve_eta_between(
          p, low_mle, up_mle, fit$curve %||% "loglogistic"
        ) / k_mle
        valid_ct <- is.finite(ct_v)
        inversion_counts[[length(inversion_counts) + 1L]] <- data.frame(
          quantity = "CTmax", group = as.character(g),
          n_requested = boot$nboot, n_converged = nrow(R),
          n_usable = sum(valid_ct), n_unusable = sum(!valid_ct),
          stringsAsFactors = FALSE
        )
        if (any(!valid_ct)) {
          cli::cli_warn(c(
            "{sum(!valid_ct)} of {nrow(R)} converged bootstrap refits could not reach the absolute target for group {.val {gl}}.",
            i = "Those draws are retained as {.code NA} and counted in {.field meta$inversion_counts}."
          ))
        }
      }
    } else {
      ct_v <- ctr_v; ct_mle <- ctr_mle
    }
    ct_valid <- is.finite(ct_v)
    c_d[[i]] <- mk_draws(gl, ct_v, "temp",
                         extra = if (identical(mode, "absolute"))
                           list(.valid = ct_valid) else NULL)
    ct_q <- bootstrap_interval("CTmax", gl, ct_v)
    c_s[[i]] <- mk_summ(gl, ct_mle, ct_q,
                        c("temp_median", "temp_lower", "temp_upper"))

    if (isTRUE(lethal)) {
      draw_rate <- function() exp(stats::runif(length(z_v), log(TC_rate_range[1L]),
                                                log(TC_rate_range[2L])))
      if (is.null(seed)) {
        rate <- draw_rate()
      } else {
        had_seed <- exists(".Random.seed", envir = .GlobalEnv, inherits = FALSE)
        if (had_seed) old_seed <- get(".Random.seed", envir = .GlobalEnv)
        rate <- local({
          on.exit(if (had_seed) assign(".Random.seed", old_seed, envir = .GlobalEnv)
                  else if (exists(".Random.seed", envir = .GlobalEnv, inherits = FALSE))
                    rm(".Random.seed", envir = .GlobalEnv), add = TRUE)
          set.seed(seed)
          draw_rate()
        })
      }
      rate_mid <- sqrt(prod(TC_rate_range))
      if (identical(mode, "absolute") && length(temperature_shapes)) {
        cell <- gl %||% list()
        tc_v <- vapply(seq_len(nrow(R)), function(j) {
          draw_fit <- tls_fit_with_boot_draw(fit, R[j, ])
          if (is.null(draw_fit)) return(NA_real_)
          tls_absolute_threshold_root(draw_fit, p,
            duration = 60 * 100 / rate[j], group = g,
            bounds = tls_observed_temp_bounds(fit), cell = cell)
        }, numeric(1))
        tc_mle <- tls_absolute_threshold_root(
          fit, p, duration = 60 * 100 / rate_mid, group = g,
          bounds = tls_observed_temp_bounds(fit), cell = cell
        )
        if (!is.finite(tc_mle)) {
          cli::cli_abort(c(
            "The bounded scan did not find one fitted absolute T_crit crossing for group {.val {g}} inside the observed temperature range.",
            i = "Check the target, rate range, and temperature-varying shape fit."
          ))
        }
        valid_tc <- is.finite(tc_v)
        inversion_counts[[length(inversion_counts) + 1L]] <- data.frame(
          quantity = "T_crit", group = as.character(g),
          n_requested = boot$nboot, n_converged = length(tc_v),
          n_usable = sum(valid_tc),
          n_unusable = sum(!valid_tc), stringsAsFactors = FALSE
        )
        if (any(!valid_tc)) {
          cli::cli_warn(c(
            "{sum(!valid_tc)} of {length(tc_v)} converged bootstrap refits had no single detected absolute T_crit crossing for group {.val {g}}.",
            i = "Those draws are retained as {.code NA} and counted in {.field meta$inversion_counts}."
          ))
        }
      } else if (identical(mode, "absolute")) {
        ctmax_1h <- ct_v - z_v * log10(60 / fit$tref)
        ctmax_1h_mle <- ctr_mle - z_mle * log10(60 / fit$tref) +
          z_mle * tls_curve_eta_between(
            p, low_mle, up_mle, fit$curve %||% "loglogistic"
          ) / k_mle
      } else {
        ctmax_1h <- ctr_v - z_v * log10(60 / fit$tref)
        ctmax_1h_mle <- ctr_mle - z_mle * log10(60 / fit$tref)
      }
      if (!(identical(mode, "absolute") && length(temperature_shapes))) {
        tc_v <- ctmax_1h + z_v * log10(rate / 100)
        tc_mle <- ctmax_1h_mle + z_mle * log10(rate_mid / 100)
      }
      tc_valid <- is.finite(tc_v)
      if (identical(mode, "absolute") && !length(temperature_shapes)) {
        inversion_counts[[length(inversion_counts) + 1L]] <- data.frame(
          quantity = "T_crit", group = as.character(g),
          n_requested = boot$nboot, n_converged = nrow(R),
          n_usable = sum(tc_valid), n_unusable = sum(!tc_valid),
          stringsAsFactors = FALSE
        )
        if (any(!tc_valid)) {
          cli::cli_warn(c(
            "{sum(!tc_valid)} of {nrow(R)} converged bootstrap refits could not reach the absolute T_crit target for group {.val {gl}}.",
            i = "Those draws are retained as {.code NA} and counted in {.field meta$inversion_counts}."
          ))
        }
      }
      t_d[[i]] <- mk_draws(gl, tc_v, "temp", extra = c(
        list(log10_rate = log10(rate)),
        if (identical(mode, "absolute"))
          list(.valid = tc_valid) else list()
      ))
      tc_q <- bootstrap_interval("T_crit", gl, tc_v)
      t_s[[i]] <- mk_summ(gl, tc_mle, tc_q,
                          c("temp_median", "temp_lower", "temp_upper"))
    }
  }

  bind <- function(l) tibble::as_tibble(do.call(rbind, l))
  out <- list(
    z     = list(draws = bind(z_d), summary = bind(z_s)),
    CTmax = list(draws = bind(c_d), summary = bind(c_s)),
    T_crit = if (isTRUE(lethal)) list(draws = bind(t_d), summary = bind(t_s)) else NULL,
    meta = list(
      target_surv = if (identical(mode, "relative")) "relative" else sprintf("p=%.3f", p),
      z_definition = "relative-midpoint thermal sensitivity",
      mode = mode, p = p, lethal = lethal, TC_rate_range = TC_rate_range,
      by = if (grouped) by_names else NULL,
      nboot = nrow(R), nboot_requested = boot$nboot,
      n_converged = nrow(R), n_failed = boot$nboot - nrow(R),
      min_usable_bootstrap = min_usable_bootstrap,
      interval_counts = do.call(rbind, interval_counts),
      level = level, tref = fit$tref,
      duration_unit = meta$duration_unit %||% NULL,
      input_duration_unit = meta$input_duration_unit %||% NULL,
      inversion_counts = if (length(inversion_counts))
        do.call(rbind, inversion_counts) else NULL,
      n_unusable_inversions = if (length(inversion_counts))
        sum(vapply(inversion_counts, function(x) x$n_unusable, numeric(1))) else 0L
    )
  )
  class(out) <- c("freq_tdt", "list")
  out
}

#' @export
print.freq_tdt <- function(x, ...) {
  unit <- x$meta$duration_unit %||% "time units"
  cat(sprintf("<freq_tdt> %s threshold; %d of %d bootstrap refits converged; CTmax at tref = %g %s%s\n",
              x$meta$target_surv, x$meta$n_converged,
              x$meta$nboot_requested,
              x$meta$tref, unit,
              if (isTRUE(x$meta$lethal)) "; T_crit included" else ""))
  cat("  $z, $CTmax", if (!is.null(x$T_crit)) ", $T_crit" else "", " (each $draws + $summary)\n", sep = "")
  if (x$meta$n_unusable_inversions > 0L) {
    cat(sprintf("  %d bootstrap threshold inversions were unusable; see $meta$inversion_counts\n",
                x$meta$n_unusable_inversions))
  }
  unavailable <- x$meta$interval_counts
  if (!is.null(unavailable) && any(unavailable$conf.status == "bootstrap_unstable")) {
    cat(sprintf("  Percentile limits require %d usable refits; unavailable quantities and counts are in $meta$interval_counts\n",
                x$meta$min_usable_bootstrap))
  }
  invisible(x)
}

# ---- accessors (analogues of bayesTLS get_*_summary / get_*_draws) ------------

stop_if_not_freq_tdt <- function(et) {
  if (!is.list(et) || is.null(et$z) || is.null(et$CTmax))
    cli::cli_abort("{.arg et} must be an {.fn extract_tdt} result (with {.field $z} and {.field $CTmax}).")
}

#' Accessors for an extract_tdt() result
#'
#' Analogues of the bayesTLS `get_*_summary` / `get_*_draws` accessors. `*_summary`
#' returns the maximum-likelihood point estimate (in the compatibility-named
#' `*_median` column) and its bootstrap-percentile interval. `*_draws` returns
#' one derived estimate from each parametric-bootstrap refit; these are resampled
#' frequentist estimates, not posterior draws.
#'
#' @param et An [extract_tdt()] result.
#' @return A tibble (see [extract_tdt()] for the column contract).
#' @examples
#' \donttest{
#' 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, quiet = TRUE)
#' tdt <- extract_tdt(fit, nboot = 50, seed = 1)
#' get_z_summary(tdt)
#' get_ctmax_draws(tdt)
#' }
#' @name tdt-accessors
NULL

#' @rdname tdt-accessors
#' @export
get_z_summary <- function(et) { stop_if_not_freq_tdt(et); et$z$summary }

#' @rdname tdt-accessors
#' @export
get_z_draws <- function(et) { stop_if_not_freq_tdt(et); et$z$draws }

#' @rdname tdt-accessors
#' @export
get_ctmax_summary <- function(et) { stop_if_not_freq_tdt(et); et$CTmax$summary }

#' @rdname tdt-accessors
#' @export
get_ctmax_draws <- function(et) {
  stop_if_not_freq_tdt(et)
  d <- et$CTmax$draws
  names(d)[names(d) == "temp"] <- "CTmax"
  d
}

#' @rdname tdt-accessors
#' @export
get_tcrit_summary <- function(et) {
  stop_if_not_freq_tdt(et)
  if (is.null(et$T_crit))
    cli::cli_abort("This {.fn extract_tdt} result has no T_crit; call with {.code lethal = TRUE}.")
  et$T_crit$summary
}

#' @rdname tdt-accessors
#' @export
get_tcrit_draws <- function(et) {
  stop_if_not_freq_tdt(et)
  if (is.null(et$T_crit))
    cli::cli_abort("This {.fn extract_tdt} result has no T_crit; call with {.code lethal = TRUE}.")
  d <- et$T_crit$draws
  names(d)[names(d) == "temp"] <- "T_crit"
  d
}

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.