R/tls.R

Defines functions tdt_parameter_table diagnose_tdt_fit print.freq_tls_summary get_tls_est tls_flatten_tdt_draws tls_flatten_tdt tls_tcrit tls_ctmax tls_z tls

Documented in diagnose_tdt_fit get_tls_est tdt_parameter_table tls tls_ctmax tls_tcrit tls_z

# The bayesTLS-analogue quantity extractor. tls() reshapes the freqTLS engine's
# CTmax / z estimates + confidence intervals into bayesTLS's tls() output
# contract (a `$summary` with quantity / median / lower / upper, one row per
# group x quantity, plus `$meta`). Shared names express a common scientific
# step, not drop-in object or uncertainty compatibility.

#' Thermal-load-sensitivity quantities (z, CTmax) with confidence intervals
#'
#' The frequentist analogue of `bayesTLS::tls()`. Reads a [fit_4pl()] (`freq_tls`)
#' fit and returns the headline thermal-load-sensitivity quantities — thermal
#' sensitivity `z` and `CTmax` — as point estimates with confidence intervals,
#' one row per group when the fit is grouped. `CTmax` is the critical thermal
#' maximum at reference time `tref`; `z` is thermal sensitivity in degrees per
#' decade of duration. The default target is `relative`, the curve midpoint;
#' `absolute` requests a specified survival proportion. Relative requests use
#' profile-likelihood intervals by default (or Wald / bootstrap via `method`),
#' while absolute requests use bootstrap refits.
#'
#' @param object A `freq_tls` fit from [fit_4pl()] (or a bare `profile_tls` fit
#'   from [fit_tls()]).
#' @param by Optional name or names of the grouping columns in `$summary`; defaults
#'   to the fit's moderator (e.g. the `ctmax`/`z`/`by` factor).
#' @param params `"all"` (z and CTmax, the default, plus T_crit when
#'   `lethal = TRUE`), or any combination of `"z"`, `"ctmax"`, and `"tcrit"`.
#'   An explicit quantity vector determines exactly which quantities are
#'   returned. Selecting `"tcrit"` requests the bootstrap-derived T_crit
#'   quantity, but requires `lethal = TRUE` because T_crit assumes a lethal
#'   endpoint. This selects the returned headline quantities; use
#'   [tdt_parameter_table()] or [get_shape()] for `low`, `up`, and `k`.
#' @param target_surv Survival threshold for CTmax: `"relative"` (the curve
#'   midpoint, the default), `"absolute"` (50% survival), or a number in `(0, 1)`
#'   for an LTx. An absolute target must lie strictly between the fitted
#'   asymptotes for every reported group. Absolute targets and a requested
#'   `T_crit` are derived per bootstrap replicate via [extract_tdt()].
#' @param lethal A single non-missing logical value. If `TRUE`, declare a
#'   lethal endpoint so `T_crit` can be
#'   requested; `params = "all"` then includes `T_crit`. When `params` is an
#'   explicit quantity vector, only those quantities are returned. `T_crit`
#'   uses the bootstrap path. Setting `lethal = TRUE` alone does not request
#'   draws; select `T_crit`, request an absolute target, or set
#'   `method = "bootstrap"`.
#' @param method Interval method for relative requests: `"profile"` (default,
#'   from the fit's stored default), `"wald"`, or `"bootstrap"`. Absolute
#'   targets and requested `T_crit` use bootstrap; a relative request for other
#'   quantities follows `method`.
#' @param level Confidence level (default 0.95).
#' @param nboot,seed Number of bootstrap replicates and optional random seed.
#'   Used for draw-level extraction and bootstrap interval calculations.
#'   Percentile limits are reported only with at least 20 usable refits. The
#'   explicit bootstrap extraction path returns its converged draws and
#'   requested/converged/failed counts; automatic fallback from a relative
#'   profile request returns interval limits, method, and status only.
#' @param TC_rate_range Passed to [extract_tdt()] for `T_crit`.
#' @param mode,p Legacy bayesTLS aliases. mode = "relative" maps to the relative
#'   target and cannot be combined with p; mode = "absolute" maps to p or 0.5.
#'   If mode is omitted, p alone supplies the absolute target. Do not combine
#'   these aliases with target_surv.
#' @param ... Recognized Bayesian-only arguments are rejected with guidance
#'   when freqTLS cannot honor them. Unknown names also raise an explicit error.
#' @return A `tls` object with `$summary` (`[<group>,] quantity, median, lower,
#'   upper`) and `$meta`. The threshold in `$meta$mode` applies to CTmax and
#'   `T_crit`. `$meta$z_definition` describes `z` as relative-midpoint thermal
#'   sensitivity. The explicit bootstrap extraction path also returns `$draws`.
#'   When [confint.profile_tls()] supplies intervals, `$meta$methods` and
#'   `$meta$conf.status` record each parameter's method and status. Printed
#'   summaries show those details when methods are mixed or a status is not
#'   successful. Bootstrap summaries also report requested, converged, and
#'   failed refits and identify quantities whose percentile limits were withheld.
#' @seealso [fit_4pl()], [tls_z()], [tls_ctmax()], [confint.profile_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
#' )
#' tls(fit)
#' tls_z(fit)
#' tls_ctmax(fit)
#' @export
tls <- function(object, by = NULL, params = "all",
                target_surv = "relative", lethal = FALSE, method = NULL,
                level = 0.95, nboot = 1000L, TC_rate_range = c(0.1, 1),
                seed = NULL, mode = NULL, p = NULL, ...) {
  if (!is.logical(lethal) || length(lethal) != 1L || is.na(lethal)) {
    cli::cli_abort("{.arg lethal} must be a single non-missing logical value.")
  }
  target_surv_missing <- missing(target_surv)
  dots <- list(...)
  if (length(dots)) {
    dot_names <- names(dots)
    if (is.null(dot_names)) dot_names <- rep("", length(dots))
    recognised <- c("t_ref", "time_multiplier", "temp", "temp_mean",
                    "temp_grid", "re_formula", "lower", "upper", "nlpars",
                    "ndraws", "newdata", "probs")
    supplied_recognised <- unique(dot_names[nzchar(dot_names) &
                                               dot_names %in% recognised])
    if (length(supplied_recognised)) {
      cli::cli_abort(c(
        "Recognized bayesTLS arguments are not used by freqTLS: {.val {supplied_recognised}}.",
        i = "freqTLS summarizes an already-fitted maximum-likelihood model. Set model structure when calling fit_4pl() or fit_tls(), and use level, nboot, and seed for confidence intervals."
      ))
    }
    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(mode) || !is.null(p)) && !target_surv_missing) {
    cli::cli_abort("Supply target_surv or its legacy mode/p aliases, not both.")
  }
  if (!is.null(mode)) {
    mode <- match.arg(mode, c("absolute", "relative"))
    if (mode == "relative" && !is.null(p)) {
      cli::cli_abort("p has no effect with mode = \"relative\"; omit p or use mode = \"absolute\".")
    }
    target_surv <- if (mode == "relative") "relative" else (p %||% 0.5)
  } else if (!is.null(p)) {
    target_surv <- p
  }
  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} fit from {.fn fit_4pl} (or a {.cls profile_tls} fit).")
  }
  if (!is.character(params) || !length(params) || anyNA(params) ||
      any(!nzchar(params))) {
    cli::cli_abort("{.arg params} must be a non-empty character vector.")
  }
  params_lower <- tolower(params)
  all_quantities_requested <- length(params_lower) == 1L &&
    "all" %in% params_lower
  if ("all" %in% params_lower) {
    if (length(params_lower) != 1L) {
      cli::cli_abort("{.arg params} = {.val all} cannot be combined with individual quantities.")
    }
    qsel <- c("z", "CTmax")
  } else {
    unsupported <- setdiff(params_lower, c("z", "ctmax", "tcrit"))
    if (length(unsupported)) {
      cli::cli_abort("Unsupported {.arg params}: {.val {unsupported}}. Choose z, CTmax, Tcrit, or all.")
    }
    qsel <- c(if ("z" %in% params_lower) "z",
              if ("ctmax" %in% params_lower) "CTmax")
    if ("tcrit" %in% params_lower && !isTRUE(lethal)) {
      cli::cli_abort(c(
        "Selecting {.val tcrit} requires {.arg lethal = TRUE}.",
        i = "{.code T_crit} assumes a lethal endpoint; see {.fn derive_tcrit}."
      ))
    }
  }
  include_tcrit <- if (all_quantities_requested) isTRUE(lethal) else
    "tcrit" %in% params_lower
  method <- method %||% meta$method %||% "profile"
  method <- tryCatch(
    match.arg(method, c("profile", "wald", "bootstrap")),
    error = function(e) {
      cli::cli_abort("{.arg method} must be one of {.val profile}, {.val wald}, or {.val bootstrap}.")
    }
  )
  pd_hessian <- isTRUE(fit$convergence$pdHess)
  if (!pd_hessian) {
    cli::cli_warn(c(
      "The fitted Hessian is not positive definite; Wald confidence intervals may be unreliable.",
      i = "Inspect profile intervals and the fit diagnostics before interpreting the summary."
    ))
  }

  X_CT <- fit$tmb_inputs$data$X_CT
  X_logz <- fit$tmb_inputs$data$X_logz
  by_name <- by %||% meta$moderators %||% "group"
  source_data <- if (inherits(object, "freq_tls")) object$data else NULL
  cellmeans <- 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)
  cell_labels <- if (cellmeans) tls_cellmean_labels(X_CT, source_data, by_name) else NULL
  fallback_by <- meta$moderators %||% "group"
  if (cellmeans && is.null(source_data) && is.null(cell_labels) &&
      identical(by_name, fallback_by) && length(by_name) == 1L &&
      length(fit$group_levels) == ncol(X_CT)) {
    cell_labels <- data.frame(.cell = colnames(X_CT),
                              stringsAsFactors = FALSE)
    cell_labels[[by_name]] <- as.character(fit$group_levels)
  }
  has_group_coefficients <- any(grepl("^(CTmax|z):", fit$estimates$parameter))
  if (has_group_coefficients && (!cellmeans || is.null(cell_labels))) {
    cli::cli_abort(c(
      "Grouped {.fn tls} summaries require matching represented cell-mean designs for {.code CTmax} and {.code log_z}.",
      i = "The two designs must assign the same rows to each cell, and the requested source columns must identify each fitted cell uniquely.",
      i = "Use matching formulas such as {.code CTmax ~ 0 + group} and {.code log_z ~ 0 + group}."
    ))
  }

  # Absolute / LTx thresholds, T_crit, and explicitly requested bootstrap
  # intervals use the draw-level extractor. Profile requests go through
  # confint() even for a non-positive-definite Hessian so invalid_center status
  # cannot be hidden by a direct draw-level extraction.
  use_bootstrap <- !identical(target_surv, "relative") || include_tcrit ||
    identical(method, "bootstrap")
  if (use_bootstrap) {
    et <- extract_tdt(object, target_surv = target_surv, lethal = include_tcrit,
                      TC_rate_range = TC_rate_range, nboot = nboot,
                      level = level, seed = seed, by = by)
    summ <- tls_flatten_tdt(et, qsel, include_tcrit)
    draws <- tls_flatten_tdt_draws(et, qsel, include_tcrit)
    requested_interval_quantities <- c(
      qsel, if (include_tcrit) "T_crit"
    )
    interval_counts <- et$meta$interval_counts
    if (!is.null(interval_counts)) {
      interval_counts <- interval_counts[
        interval_counts$quantity %in% requested_interval_quantities,
        , drop = FALSE
      ]
    }
    requested_inversion_quantities <- c(
      if ("CTmax" %in% qsel) "CTmax",
      if (include_tcrit) "T_crit"
    )
    inversion_counts <- et$meta$inversion_counts
    if (!is.null(inversion_counts)) {
      inversion_counts <- inversion_counts[
        inversion_counts$quantity %in% requested_inversion_quantities,
        , drop = FALSE
      ]
    }
    out <- list(
      summary = summ,
      draws = draws,
      meta = list(params = c(qsel, if (include_tcrit) "Tcrit"),
                  mode = et$meta$target_surv, method = "bootstrap", level = level,
                  z_definition = et$meta$z_definition,
                  by = et$meta$by, tref = fit$tref,
                  pdHess = pd_hessian,
                  nboot_requested = et$meta$nboot_requested,
                  n_converged = et$meta$n_converged,
                  n_failed = et$meta$n_failed,
                  min_usable_bootstrap = et$meta$min_usable_bootstrap,
                  interval_counts = interval_counts,
                  inversion_counts = inversion_counts,
                  t_ref = meta$t_ref %||% fit$tref,
                  duration_unit = et$meta$duration_unit %||% meta$duration_unit,
                  temp_mean = meta$temp_mean)
    )
    class(out) <- c("freq_tls_summary", "tls", "list")
    return(out)
  }

  est <- fit$estimates
  pat <- paste0("^(", paste(qsel, collapse = "|"), ")(:|$)")
  rows <- est[grepl(pat, est$parameter), , drop = FALSE]
  has_labeled_coefficients <- any(grepl(":", rows$parameter, fixed = TRUE))
  if (has_labeled_coefficients && !cellmeans) {
    cli::cli_abort(c(
      "Grouped {.fn tls} summaries require represented cell-mean designs for both {.code CTmax} and {.code log_z}.",
      i = "Use matching no-intercept formulas such as {.code CTmax ~ 0 + group} and {.code log_z ~ 0 + group}; contrast-coded interactions do not identify the requested group means."
    ))
  }
  ci <- confint(fit, parm = rows$parameter, level = level, method = method,
                nboot = nboot, boot_seed = seed)
  idx <- match(rows$parameter, ci$parameter)

  quantity <- sub(":.*$", "", rows$parameter)
  # A fit is grouped iff its quantity coefficients are level-tagged ("CTmax:lvl").
  # An ungrouped fit's single "all"/intercept level is NOT surfaced as a column.
  grouped <- cellmeans && ncol(X_CT) > 1L
  if (grouped) {
    grp <- as.character(rows$group)
    map_idx <- match(grp, cell_labels$.cell)
    if (anyNA(map_idx)) cli::cli_abort("Could not map fitted cell labels to moderator rows.")
    df <- cell_labels[map_idx, by_name, drop = FALSE]
    df$quantity <- quantity
    df$median <- rows$estimate
    df$lower <- ci$conf.low[idx]
    df$upper <- ci$conf.high[idx]
    summ <- tibble::as_tibble(df)
  } else {
    summ <- tibble::tibble(quantity = quantity, median = rows$estimate,
                           lower = ci$conf.low[idx], upper = ci$conf.high[idx])
  }

  methods <- stats::setNames(as.character(ci$method[idx]), rows$parameter)
  methods_used <- unique(methods)
  method_used <- if (length(methods_used) == 1L) methods_used else "mixed"
  out <- list(
    summary = summ,
    draws = NULL,
    meta = list(params = qsel, mode = target_surv, method = method_used,
                z_definition = "relative-midpoint thermal sensitivity",
                methods = methods,
                conf.status = stats::setNames(ci$conf.status[idx], rows$parameter),
                level = level, by = if (grouped) by_name else NULL,
                pdHess = pd_hessian,
                tref = fit$tref, t_ref = meta$t_ref %||% fit$tref,
                duration_unit = meta$duration_unit %||% NULL,
                temp_mean = meta$temp_mean)
  )
  class(out) <- c("freq_tls_summary", "tls", "list")
  out
}

#' @rdname tls
#' @export
tls_z <- function(object, ...) tls(object, params = "z", ...)

#' @rdname tls
#' @export
tls_ctmax <- function(object, ...) tls(object, params = "ctmax", ...)

#' @rdname tls
#' @export
tls_tcrit <- function(object, ...) {
  r <- tls(object, params = "tcrit", lethal = TRUE, ...)
  r$summary <- r$summary[r$summary$quantity == "Tcrit", , drop = FALSE]
  if (!is.null(r$draws)) {
    r$draws <- r$draws[r$draws$quantity == "Tcrit", , drop = FALSE]
  }
  r$meta$params <- "Tcrit"
  if (!is.null(r$meta$interval_counts)) {
    r$meta$interval_counts <- r$meta$interval_counts[
      r$meta$interval_counts$quantity == "T_crit", , drop = FALSE
    ]
  }
  if (!is.null(r$meta$inversion_counts)) {
    r$meta$inversion_counts <- r$meta$inversion_counts[
      r$meta$inversion_counts$quantity == "T_crit", , drop = FALSE
    ]
  }
  r
}

# Flatten an extract_tdt() result into the flat tls() $summary shape
# (quantity / [group] / median / lower / upper).
tls_flatten_tdt <- function(et, qsel, lethal) {
  byc <- et$meta$by
  one <- function(s, label, prefix) {
    cols <- if (!is.null(byc)) lapply(byc, function(nm) s[[nm]]) else list()
    if (!is.null(byc)) names(cols) <- byc
    cols$quantity <- label
    cols$median <- s[[paste0(prefix, "_median")]]
    cols$lower  <- s[[paste0(prefix, "_lower")]]
    cols$upper  <- s[[paste0(prefix, "_upper")]]
    as.data.frame(cols, stringsAsFactors = FALSE)
  }
  parts <- list()
  if ("z" %in% qsel)     parts <- c(parts, list(one(et$z$summary, "z", "z")))
  if ("CTmax" %in% qsel) parts <- c(parts, list(one(et$CTmax$summary, "CTmax", "temp")))
  if (isTRUE(lethal))    parts <- c(parts, list(one(et$T_crit$summary, "Tcrit", "temp")))
  tibble::as_tibble(do.call(rbind, parts))
}

tls_flatten_tdt_draws <- function(et, qsel, lethal) {
  group_cols <- et$meta$by %||% character()
  has_valid <- any(vapply(
    Filter(Negate(is.null), list(et$CTmax$draws, et$T_crit$draws)),
    function(d) ".valid" %in% names(d), logical(1)
  ))
  one <- function(d, label, column) {
    cols <- lapply(group_cols, function(nm) d[[nm]])
    names(cols) <- group_cols
    cols$.draw <- d$.draw
    cols$value <- d[[column]]
    cols$quantity <- label
    if (has_valid) {
      cols$.valid <- if (".valid" %in% names(d)) d$.valid else rep(TRUE, nrow(d))
    }
    as.data.frame(cols, stringsAsFactors = FALSE)
  }
  parts <- list()
  if ("z" %in% qsel) parts <- c(parts, list(one(et$z$draws, "z", "z")))
  if ("CTmax" %in% qsel) {
    parts <- c(parts, list(one(et$CTmax$draws, "CTmax", "temp")))
  }
  if (isTRUE(lethal)) {
    parts <- c(parts, list(one(et$T_crit$draws, "Tcrit", "temp")))
  }
  tibble::as_tibble(do.call(rbind, parts))
}

#' Extract TLS summaries or bootstrap replicates
#'
#' Return the summary or long-format parametric-bootstrap replicates from a
#' `tls()` result. Draw-level values are available when `tls()` used
#' `method = "bootstrap"`, requested an absolute threshold, or selected
#' `T_crit`. Setting `lethal = TRUE` without selecting `T_crit` does not by
#' itself return draws. An automatic bootstrap fallback from a relative profile request returns
#' interval limits, method, and status, not draw-level values. Draws are
#' frequentist bootstrap refits, not posterior draws.
#'
#' @param x A `freq_tls_summary` result returned by `freqTLS::tls()`.
#' @param what "summary" (default) or "draws".
#' @param params Optional case-insensitive quantity names such as "z",
#'   "CTmax", or "Tcrit". Every requested name must be present in the result.
#' @return A tibble. Summary output contains quantity, median, lower, and
#'   upper, plus grouping columns. Draw output contains grouping columns,
#'   .draw, value, quantity, and `.valid` for absolute-threshold refits.
#' @examples
#' d <- simulate_tls(family = "binomial", times = c(30, 60, 120, 240, 480),
#'                   CTmax = 36, z = 4, tref = 60, seed = 1)
#' std <- standardize_data(d, temp = "temp", duration = "duration",
#'   n_total = "total", n_surv = "survived", duration_unit = "minutes")
#' fit <- fit_4pl(std, family = "binomial", method = "bootstrap", quiet = TRUE)
#' estimates <- tls(fit, nboot = 20, seed = 1)
#' get_tls_est(estimates, what = "draws", params = "CTmax")
#' @export
get_tls_est <- function(x, what = c("summary", "draws"), params = NULL) {
  if (!inherits(x, "freq_tls_summary")) {
    cli::cli_abort("{.arg x} must be a {.cls freq_tls_summary} result from {.fn tls}.")
  }
  what <- match.arg(what)
  out <- if (identical(what, "summary")) x$summary else x$draws
  if (is.null(out)) {
    cli::cli_abort(c(
      "This {.fn tls} result has no bootstrap draws.",
      i = "Call {.fn tls} with {.code method = \"bootstrap\"} to return draw-level estimates."
    ))
  }
  if (!is.null(params)) {
    if (!is.character(params) || anyNA(params) || !length(params) ||
        any(!nzchar(params))) {
      cli::cli_abort("{.arg params} must be a non-empty character vector or NULL.")
    }
    available <- unique(as.character(out$quantity))
    requested <- unique(tolower(params))
    available_lower <- tolower(available)
    unmatched <- params[!tolower(params) %in% available_lower]
    if (length(unmatched)) {
      cli::cli_abort("Unknown {.arg params}: {.val {unique(unmatched)}}. Available quantities: {.val {available}}.")
    }
    selected <- available[available_lower %in% requested]
    out <- out[out$quantity %in% selected, , drop = FALSE]
  }
  tibble::as_tibble(out)
}

#' @export
print.freq_tls_summary <- function(x, ...) {
  params <- x$meta$params
  threshold_params <- intersect(params, c("CTmax", "Tcrit"))
  labels <- c(
    if ("z" %in% params) {
      definition <- x$meta$z_definition %||% "relative-midpoint thermal sensitivity"
      sprintf("z (%s)", definition)
    },
    if (length(threshold_params)) {
      sprintf("%s at %s threshold", paste(threshold_params, collapse = ", "),
              x$meta$mode)
    }
  )
  cat(sprintf("<tls> %s (%s intervals, pdHess = %s)\n",
              paste(labels, collapse = ", "), x$meta$method,
              x$meta$pdHess %||% NA))
  print(x$summary)
  if (!is.null(x$meta$nboot_requested)) {
    cat(sprintf("Bootstrap refits: %d of %d converged; %d failed.\n",
                x$meta$n_converged, x$meta$nboot_requested, x$meta$n_failed))
    counts <- x$meta$interval_counts
    if (!is.null(counts) && any(counts$conf.status == "bootstrap_unstable")) {
      cat(sprintf("Percentile limits require %d usable refits; unavailable limits are marked bootstrap_unstable:\n",
                  x$meta$min_usable_bootstrap))
      print(counts[counts$conf.status == "bootstrap_unstable", , drop = FALSE],
            row.names = FALSE)
    }
  }
  methods <- x$meta$methods
  statuses <- x$meta$conf.status
  if (length(methods)) {
    parameter <- names(methods)
    status <- unname(statuses[parameter])
    details <- data.frame(
      parameter = parameter,
      method = unname(methods),
      status = status,
      stringsAsFactors = FALSE
    )
    mixed <- length(unique(details$method[!is.na(details$method)])) > 1L
    nonstandard_status <- any(
      !is.na(details$status) &
        !details$status %in% c("ok", "bootstrap", "fixed")
    )
    if (mixed || nonstandard_status) {
      cat("Interval method and status by parameter:\n")
      print(details, row.names = FALSE)
    }
  }
  invisible(x)
}

#' Diagnose a freqTLS fit (frequentist analogue of `diagnose_tdt_fit`)
#'
#' The maximum-likelihood analogue of `bayesTLS::diagnose_tdt_fit()`: where the
#' Bayesian version reports Rhat / ESS / divergences, the freqTLS version reports
#' optimiser convergence, a positive-definite Hessian, and the gradient norm at
#' the optimum, with a single `all_pass` flag.
#'
#' @param object A `freq_tls` fit from [fit_4pl()] (or a `profile_tls` fit).
#' @return A one-row tibble of convergence diagnostics.
#' @seealso [fit_4pl()], [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, quiet = TRUE)
#' diagnose_tdt_fit(fit)
#' @export
diagnose_tdt_fit <- function(object) {
  fit <- if (inherits(object, "freq_tls")) object$fit else object
  if (!inherits(fit, "profile_tls"))
    cli::cli_abort("{.arg object} must be a {.cls freq_tls} or {.cls profile_tls} fit.")
  conv <- fit$convergence
  g <- tryCatch(max(abs(fit$obj$gr(fit$opt$par))),
                error = function(e) NA_real_)
  converged    <- isTRUE(conv$code == 0L)
  pd_hessian   <- isTRUE(conv$pdHess)
  gradient_pass <- is.finite(g) && g < 1e-3
  tibble::tibble(
    converged        = converged,
    pd_hessian       = pd_hessian,
    max_abs_gradient = g,
    gradient_pass    = gradient_pass,
    optimizer        = conv$optimizer %||% NA_character_,
    logLik           = as.numeric(fit$logLik),
    n_params         = fit$df,
    AIC              = fit$AIC,
    all_pass         = converged && pd_hessian && gradient_pass
  )
}

#' 4PL parameter table (frequentist analogue of `tdt_parameter_table`)
#'
#' Returns the fitted 4PL parameters (`low`, `up`, `k`, `CTmax`, `z`, and `phi`
#' for over-dispersed families) as point estimates with confidence intervals, in
#' bayesTLS's `parameter / [group] / median / lower / upper` shape. `low` and
#' `up` are the fitted survival asymptotes, `k` is curve steepness, `CTmax` is
#' the critical thermal maximum at the reference time, `z` is thermal sensitivity
#' in degrees per order-of-magnitude change in duration, and `phi` is
#' beta/beta-binomial precision
#' or overdispersion. The `median` name is retained for table compatibility; for
#' frequentist Wald or profile output it contains the maximum-likelihood point
#' estimate, not a posterior median.
#'
#' @param object A `freq_tls` fit from [fit_4pl()] (or a `profile_tls` fit).
#' @param method Interval method: `"wald"` (default) or `"profile"`.
#' @param level Confidence level (default 0.95).
#' @return A tibble with `parameter`, `group`, `median`, `lower`, `upper`.
#' @seealso [tls()], [tidy_parameters()]
#' @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, quiet = TRUE)
#' tdt_parameter_table(fit, method = "wald")
#' @export
tdt_parameter_table <- function(object, method = NULL, level = 0.95) {
  fit <- if (inherits(object, "freq_tls")) object$fit else object
  meta <- if (inherits(object, "freq_tls")) object$meta else list()
  method <- method %||% meta$method %||% "wald"
  method <- if (identical(method, "profile")) "profile" else "wald"
  tp <- tidy_parameters(fit, conf.int = TRUE, conf.level = level, method = method)
  tibble::tibble(parameter = tp$parameter, group = tp$group,
                 median = tp$estimate, lower = tp$conf.low, upper = tp$conf.high)
}

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.