R/bootstrap.R

Defines functions tls_confint_bootstrap tls_boot_target tls_beta_shape_parameters tls_bootstrap_replicates tls_apply_beta_censoring tls_bootstrap_varying_shapes

## Parametric bootstrap confidence intervals for freqTLS fits.
##
## The profile likelihood is freqTLS's primary interval, but it can fail to
## close when a parameter is weakly identified, and the Wald/Hessian path is
## undefined when the fitted Hessian is not positive definite (`pdHess = FALSE`).
## A parametric bootstrap fills both gaps while staying prior-free: it regenerates
## count or Beta-proportion responses at the observed design from the fitted mean,
## refits,
## and reads the sampling distribution of each estimator. An unstable
## frequentist estimator can still leave a confidence interval unavailable.
##
## The refit reuses the same machinery as the profile path: the clean TMB inputs
## retained in `fit$tmb_inputs`, warm-started at the fitted MLE for speed and
## robustness. No Stan or model recompilation is needed. Each replicate replaces
## the response vector `y` with its simulated outcome. Percentiles are taken on each parameter's
## construction scale (z/phi on log, low on logit, CTmax/up on identity);
## general shape coefficients are already reported on their link scale. Natural-
## scale parameters are back-transformed, so the z interval equals exp() of the
## log_z interval.
## User-facing behaviour is documented in vignette("profile-likelihood").

# Fixed varying shapes are valid bootstrap refits. Downstream derived quantities
# decide separately whether their mathematical transform can handle them.
tls_bootstrap_varying_shapes <- function(fit) {
  shape_mats <- list(
    low = fit$tmb_inputs$data$X_low,
    up = fit$tmb_inputs$data$X_up,
    log_k = fit$tmb_inputs$data$X_logk
  )
  names(shape_mats)[vapply(shape_mats, function(X) {
    !tls_is_constant_design(X) && !tls_is_onehot(X)
  }, logical(1))]
}

# Apply the observation limit to latent Beta draws. Returns the observed
# placeholder response and a newly generated censor indicator; it never reuses
# the original fit's outcome flags.
tls_apply_beta_censoring <- function(latent, censor_limit) {
  latent <- as.numeric(latent)
  censor_limit <- as.numeric(censor_limit)
  if (length(latent) != length(censor_limit)) {
    cli::cli_abort("Bootstrap Beta draws and censor limits must have equal length.")
  }
  if (!any(censor_limit > 0)) {
    latent[latent <= 0] <- 1e-6
    latent[latent >= 1] <- 1 - 1e-6
    return(latent)
  }
  censored <- censor_limit > 0 & latent <= censor_limit
  observed <- latent
  observed[censored] <- censor_limit[censored]
  exact <- !censored
  # Preserve valid interior draws exactly. Only RNG-rounded boundary values
  # need a representation inside the Beta support. At the upper endpoint, a
  # high declared detection limit takes precedence over the generic clamp so
  # the exact draw cannot contradict its censoring metadata.
  lower_endpoint <- exact & observed <= 0
  upper_endpoint <- exact & observed >= 1
  observed[lower_endpoint] <- 1e-6
  observed[upper_endpoint] <- pmax(
    1 - 1e-6, censor_limit[upper_endpoint]
  )
  list(y = observed, left_censored = censored)
}

#' Parametric bootstrap replicates matching the fitted parameter table
#'
#' Regenerates `y` at the observed design from the fitted survival probabilities
#' (`p_fitted` from the compiled model) under the fit's family, refits each
#' replicate via the retained TMB inputs (warm-started at the MLE), and collects
#' estimates on the same scale and with the same names as `fit$estimates`.
#' Non-converged replicates are recorded as `NA` and excluded downstream rather
#' than silently dropped.
#'
#' @param fit A `profile_tls` fit from [fit_tls()].
#' @param nboot Number of bootstrap replicates (default `1000`).
#' @param seed Optional integer seed; when supplied the RNG state is set locally
#'   and restored on exit, so the bootstrap is reproducible without disturbing
#'   the caller's random stream.
#' @param cores Number of CPU cores for the refits (default `1`). With
#'   `cores > 1` the replicates are refitted in parallel via process forking
#'   (`parallel::mclapply`). The responses are pre-drawn sequentially under
#'   `seed`, so results are identical for a given seed regardless of `cores`.
#'   At most two cores are used, as required by CRAN. Requests above two emit a
#'   warning and are capped. Forking is unavailable on Windows, where this
#'   falls back to sequential.
#' @param trace Logical; print inner-optimisation progress.
#' @return A list with `replicates` (an `nboot`-by-parameter numeric matrix whose
#'   columns match `fit$estimates$parameter`), a logical `converged` vector,
#'   `n_converged`, `nboot`, and `param_names`.
#' @keywords internal
#' @noRd
tls_bootstrap_replicates <- function(fit, nboot = 1000L, seed = NULL,
                                     cores = 1L, trace = FALSE) {
  if (!inherits(fit, "profile_tls")) {
    cli::cli_abort("{.arg fit} must be a {.cls profile_tls} fit from {.fn fit_tls}.")
  }
  if (is.null(fit$obj) || is.null(fit$tmb_inputs)) {
    cli::cli_abort(c(
      "The parametric bootstrap needs the live TMB object and inputs retained in the fit.",
      i = "Refit with the current version of {.fn fit_tls}."
    ))
  }
  if (!is.numeric(nboot) || length(nboot) != 1L || nboot < 1) {
    cli::cli_abort("{.arg nboot} must be a single positive integer.")
  }
  nboot <- as.integer(nboot)
  if (!is.numeric(cores) || length(cores) != 1L || !is.finite(cores) || cores < 1) {
    cli::cli_abort("{.arg cores} must be a single positive integer.")
  }
  cores <- as.integer(cores)
  if (cores > 2L) {
    cli::cli_warn(c(
      "!" = "Bootstrap parallelism is limited to 2 cores for CRAN safety.",
      "i" = "Using {.code cores = 2} instead of the requested {cores}."
    ))
    cores <- 2L
  }

  if (!is.null(seed)) {
    if (!is.numeric(seed) || length(seed) != 1L) {
      cli::cli_abort("{.arg seed} must be a single number or {.code NULL}.")
    }
    if (exists(".Random.seed", envir = .GlobalEnv, inherits = FALSE)) {
      old_seed <- get(".Random.seed", envir = .GlobalEnv, inherits = FALSE)
      on.exit(assign(".Random.seed", old_seed, envir = .GlobalEnv), add = TRUE)
    } else {
      on.exit(
        suppressWarnings(rm(".Random.seed", envir = .GlobalEnv)),
        add = TRUE
      )
    }
    set.seed(as.integer(seed))
  }

  inputs <- fit$tmb_inputs
  base_data <- inputs$data
  base_map <- inputs$map %||% list()
  base_par <- tls_mle_par_list(fit, inputs$parameters)

  # Fitted probabilities + dispersion straight from the compiled model at the
  # MLE: guaranteed consistent with the likelihood and the (possibly grouped)
  # design, for both the column and formula interfaces.
  # For an RE fit the optimiser par is fixed-only; report needs the full par
  # vector (fixed + conditional modes).
  rep0 <- fit$obj$report(
    if (tls_has_re(fit)) fit$obj$env$last.par.best else fit$par
  )
  p_hat <- as.numeric(rep0$p_fitted)
  n_trials <- as.numeric(base_data$n)
  nobs <- length(p_hat)
  fam_code <- fit$family$family_code
  phi_hat <- if (fam_code >= 1L) rep0$phi else NULL

  # Random-effects fits are bootstrapped by redrawing the group deviations
  # b_g ~ N(0, sigma_hat) for every active block (CTmax and/or log_z) through the
  # compiled model (a parametric bootstrap of the hierarchical model), then
  # refitting with the random block(s).
  re_blocks <- tls_re_blocks(fit)
  is_re <- length(re_blocks) > 0L
  if (is_re) {
    full_par <- fit$obj$env$last.par.best
    re_random <- unique(vapply(re_blocks, function(bk) bk$b_name, character(1)))
    # Per-block: the positions of its b vector in the full par, and its MLE SD.
    re_draw <- lapply(re_blocks, function(bk) {
      all_idx <- which(names(full_par) == bk$b_name)
      idx <- all_idx[bk$b_idx]
      sigma_values <- as.numeric(rep0[[bk$sigma_report]])
      sigma <- if (length(sigma_values) == 1L) sigma_values else sigma_values[bk$sd_idx]
      list(idx = idx, sigma = sigma)
    })
  } else {
    re_random <- NULL
  }

  est <- fit$estimates
  param_names <- est$parameter
  glevels <- fit$group_levels
  ng <- length(glevels)
  ct_names <- if (ng == 1L) "CTmax" else paste0("CTmax:", glevels)
  z_names <- if (ng == 1L) "z" else paste0("z:", glevels)
  # Each shape owns its design. The public estimate names are the bootstrap
  # column contract; a continuous design is retained on its link scale, while a
  # shared/one-hot design is retained on its natural scale, exactly as
  # tls_estimates() reports it.
  shape_names <- function(base) {
    param_names[param_names == base | startsWith(param_names, paste0(base, ":"))]
  }
  low_names <- shape_names("low")
  up_names <- shape_names("up")
  k_names <- shape_names("k")
  shape_values <- function(report_values, beta_name, X, opt) {
    if (tls_is_constant_design(X) || tls_is_onehot(X)) return(as.numeric(report_values))
    as.numeric(opt$par[names(opt$par) == beta_name])
  }

  out <- matrix(NA_real_, nrow = nboot, ncol = length(param_names),
                dimnames = list(NULL, param_names))
  converged <- logical(nboot)

  draw_from_p <- function(p) {
    if (identical(fam_code, 2L)) {
      # beta: redraw latent continuous proportions, then reapply the explicit
      # row-specific detection limits. Censor flags belong to the simulated
      # replicate, not to the original observed response. Match the shape floor
      # used by the compiled exact and censored Beta likelihood contributions.
      shapes <- tls_beta_shape_parameters(p, phi_hat)
      prop <- stats::rbeta(nobs, shapes$a, shapes$b)
      tls_apply_beta_censoring(prop, as.numeric(base_data$censor_limit))
    } else if (identical(fam_code, 1L)) {
      # Match the beta-binomial likelihood's floored shape parameters, including
      # at the optimizer's extreme-phi boundary.
      shapes <- tls_beta_shape_parameters(p, phi_hat)
      prob <- stats::rbeta(nobs, shapes$a, shapes$b)
      stats::rbinom(nobs, size = n_trials, prob = prob)
    } else {
      stats::rbinom(nobs, size = n_trials, prob = p)
    }
  }

  draw_y <- function() {
    if (is_re) {
      # Redraw each block's group deviations, recompute p through the compiled
      # model. Single-block draws keep the previous RNG stream exactly.
      fp <- full_par
      for (blk in re_draw) {
        fp[blk$idx] <- stats::rnorm(length(blk$idx), 0, blk$sigma)
      }
      draw_from_p(as.numeric(fit$obj$report(fp)$p_fitted))
    } else {
      draw_from_p(p_hat)
    }
  }

  refit_one <- function(y_star) {
    d <- base_data
    if (is.list(y_star)) {
      d$y <- as.numeric(y_star$y)
      d$left_censored <- as.integer(y_star$left_censored)
    } else {
      d$y <- as.numeric(y_star)
    }
    inner <- tryCatch(
      TMB::MakeADFun(data = d, parameters = base_par, map = base_map,
                     random = re_random, DLL = "freqTLS",
                     silent = !isTRUE(trace)),
      error = function(e) e
    )
    if (inherits(inner, "error")) return(NULL)
    # Optimisers can emit low-level NA/NaN trial-step warnings before recovering
    # or returning a non-zero convergence code. The code below classifies that
    # replicate explicitly, so do not leak those implementation warnings into a
    # user's bootstrap fallback.
    opt <- tryCatch(suppressWarnings(stats::nlminb(inner$par, inner$fn, inner$gr)),
                    error = function(e) e)
    ok <- !inherits(opt, "error") && !is.null(opt$convergence) &&
      identical(as.integer(opt$convergence), 0L)
    if (!ok) {
      # Mirror the engine's BFGS fallback so a single optimiser stall does not
      # discard an otherwise informative replicate.
      o <- tryCatch(suppressWarnings(
                      stats::optim(inner$par, inner$fn, inner$gr, method = "BFGS")
                    ),
                    error = function(e) e)
      if (inherits(o, "error") || !identical(as.integer(o$convergence), 0L)) {
        return(NULL)
      }
      opt <- list(par = o$par)
    }
    # Re-pin at the optimum before reading the report. For an RE refit this
    # re-solves the inner Laplace problem (as tls_estimates does); for a no-RE
    # fit report(opt$par) is equivalent.
    if (is_re) {
      inner$fn(opt$par)
      rp <- inner$report()
    } else {
      rp <- inner$report(opt$par)
    }
    vals <- stats::setNames(rep(NA_real_, length(param_names)), param_names)
    vals[low_names] <- shape_values(rp$low, "beta_low", base_data$X_low, opt)
    vals[up_names] <- shape_values(rp$up, "beta_up", base_data$X_up, opt)
    vals[k_names] <- shape_values(rp$k, "beta_logk", base_data$X_logk, opt)
    if (fam_code >= 1L && "phi" %in% param_names) vals["phi"] <- rp$phi
    vals[ct_names] <- as.numeric(rp$beta_CT)
    vals[z_names] <- as.numeric(rp$z_group)
    for (bk in Filter(function(bk) identical(bk$param, "CTmax"), re_blocks)) {
      if (bk$sigma_label %in% param_names) {
        vals[bk$sigma_label] <- as.numeric(rp$sigma_CT)[bk$sd_idx]
      }
    }
    if (is_re && "sigma_logz" %in% param_names) vals["sigma_logz"] <- rp$sigma_logz
    if (is_re && "sigma_low" %in% param_names) vals["sigma_low"] <- rp$sigma_low
    if (is_re && "sigma_logk" %in% param_names) vals["sigma_logk"] <- rp$sigma_logk
    vals
  }

  # Pre-draw every replicate's response vector sequentially under the seed, then
  # parallelise only the deterministic refits (refits consume no RNG). This makes
  # the result identical for a given seed regardless of `cores`, and identical to
  # the sequential path.
  ys <- lapply(seq_len(nboot), function(b) draw_y())

  results <- if (cores > 1L && .Platform$OS.type != "windows") {
    parallel::mclapply(ys, refit_one, mc.cores = cores)
  } else {
    if (cores > 1L) {
      cli::cli_inform(c(
        "i" = "Multicore bootstrap forks processes, which is unavailable on Windows; running sequentially."
      ))
    }
    lapply(ys, refit_one)
  }

  for (b in seq_len(nboot)) {
    v <- results[[b]]
    if (is.numeric(v) && length(v) == length(param_names) &&
        all(is.finite(v[c(ct_names, z_names)]))) {
      out[b, ] <- v
      converged[b] <- TRUE
    }
  }

  list(
    replicates = out,
    converged = converged,
    n_converged = sum(converged),
    nboot = nboot,
    param_names = param_names
  )
}

# Match the shape floor in `src/profile_tls.cpp` for Beta likelihood and
# parametric-bootstrap generation.
tls_beta_shape_parameters <- function(p, phi) {
  list(a = pmax(p * phi, 1e-8), b = pmax((1 - p) * phi, 1e-8))
}

#' Map a target name to its bootstrap replicates on the construction scale
#'
#' Returns the replicate values on the scale the percentile is taken on (so the
#' interval respects the parameter's bounds and is exactly equivariant), the
#' monotone `backtransform` to the natural scale, the natural-scale point
#' `estimate`, and a `scale` label. Handles direct parameters (`CTmax`, `z`,
#' `low`, `up`, `k`, `phi`, and grouped names), the `log_z` family, and group
#' contrasts (`dCTmax`, `dz`, `dlog_z`), using the same conventions as the
#' profile path so the two methods agree on what each target means.
#' @keywords internal
#' @noRd
tls_boot_target <- function(parm, fit, reps) {
  cn <- colnames(reps)
  est <- fit$estimates
  est_of <- function(nm) {
    v <- est$estimate[est$parameter == nm]
    if (length(v)) v[1L] else NA_real_
  }
  ident <- function(x) x

  # Group contrasts use their written direction: <a>-<b> means group a minus b.
  if (grepl("^d(CTmax|z|log_z):", parm)) {
    m <- regmatches(parm, regexec("^d(CTmax|z|log_z):(.+)-(.+)$", parm))[[1L]]
    if (length(m) == 4L) {
      base <- m[2L]; a <- m[3L]; b <- m[4L]
      if (identical(base, "CTmax")) {
        na <- paste0("CTmax:", a); nb <- paste0("CTmax:", b)
        if (!all(c(na, nb) %in% cn)) {
          cli::cli_abort("Contrast groups {.val {a}}/{.val {b}} must be levels of the fit.")
        }
        return(list(values = reps[, na] - reps[, nb], backtransform = ident,
                    estimate = est_of(na) - est_of(nb), scale = "identity"))
      }
      # z / log_z contrast: a difference of log z (so the z ratio is exp()).
      na <- paste0("z:", a); nb <- paste0("z:", b)
      if (!all(c(na, nb) %in% cn)) {
        cli::cli_abort("Contrast groups {.val {a}}/{.val {b}} must be levels of the fit.")
      }
      return(list(values = log(reps[, na]) - log(reps[, nb]), backtransform = ident,
                  estimate = log(est_of(na)) - log(est_of(nb)), scale = "log"))
    }
  }

  # log_z family: percentile on log(z) (identity back-transform).
  if (parm == "log_z" || grepl("^log_z:", parm)) {
    zname <- sub("^log_z", "z", parm)
    if (!(zname %in% cn)) {
      cli::cli_abort("Unknown bootstrap target {.val {parm}}.")
    }
    return(list(values = log(reps[, zname]), backtransform = ident,
                estimate = log(est_of(zname)), scale = "log"))
  }

  # Direct natural-scale parameter, taken on its construction scale.
  if (parm %in% cn) {
    base <- sub(":.*$", "", parm)
    if (startsWith(parm, "sigma_CTmax:")) base <- "sigma_CTmax"
    shape_design <- switch(base,
      low = fit$tmb_inputs$data$X_low,
      up = fit$tmb_inputs$data$X_up,
      k = fit$tmb_inputs$data$X_logk,
      NULL
    )
    # General shape coefficients are already stored on their link scale. A
    # further log()/qlogis() would corrupt slopes (and can turn valid negative
    # coefficients into NaN).
    general_shape_coefficient <- !is.null(shape_design) &&
      !tls_is_constant_design(shape_design) && !tls_is_onehot(shape_design)
    if (general_shape_coefficient) {
      link <- switch(base, low = "logit", up = "logit", k = "log")
      return(list(values = reps[, parm], backtransform = ident,
                  estimate = est_of(parm), scale = link))
    }
    spec <- switch(base,
      CTmax = list(fwd = ident, back = ident, scale = "identity"),
      up    = list(fwd = ident, back = ident, scale = "identity"),
      low   = list(fwd = stats::qlogis, back = stats::plogis, scale = "logit"),
      z     = list(fwd = log, back = exp, scale = "log"),
      k     = list(fwd = log, back = exp, scale = "log"),
      phi   = list(fwd = log, back = exp, scale = "log"),
      sigma_CTmax = list(fwd = log, back = exp, scale = "log"),
      sigma_logz  = list(fwd = log, back = exp, scale = "log"),
      sigma_low   = list(fwd = log, back = exp, scale = "log"),
      sigma_logk  = list(fwd = log, back = exp, scale = "log"),
      list(fwd = ident, back = ident, scale = "identity")
    )
    return(list(values = spec$fwd(reps[, parm]), backtransform = spec$back,
                estimate = est_of(parm), scale = spec$scale))
  }

  cli::cli_abort(c(
    "Unknown bootstrap target {.val {parm}}.",
    i = "Valid targets: {.val {cn}} (and {.val log_z} or contrasts such as {.val dCTmax:A-B})."
  ))
}

#' Parametric bootstrap confidence-interval tibble for named targets
#'
#' Returns the same tibble shape as the profile and Wald paths, with
#' `method = "bootstrap"` and `conf.status = "bootstrap"`. Percentile intervals
#' are taken over the converged, finite replicates on each target's construction
#' scale and back-transformed. A target with too few usable replicates returns
#' `NA` with `conf.status = "bootstrap_unstable"` and a warning rather than a
#' fabricated bound.
#'
#' @param fit A `profile_tls` fit.
#' @param parm Character vector of target names.
#' @param level Confidence level.
#' @param nboot Number of replicates (ignored when `replicates` is supplied).
#' @param seed Optional integer seed (ignored when `replicates` is supplied).
#' @param cores Number of CPU cores for the refits (ignored when `replicates` is
#'   supplied).
#' @param replicates Optional precomputed result of `tls_bootstrap_replicates()`
#'   (so a single set of refits serves many targets, e.g. the fallback path).
#' @keywords internal
#' @noRd
tls_confint_bootstrap <- function(fit, parm, level, nboot = 1000L, seed = NULL,
                                  cores = 1L, replicates = NULL) {
  boot <- replicates %||%
    tls_bootstrap_replicates(fit, nboot = nboot, seed = seed, cores = cores)
  reps <- boot$replicates
  alpha <- 1 - level
  floor_n <- 20L

  rows <- lapply(parm, function(p) {
    tg <- tls_boot_target(p, fit, reps)
    vals <- tg$values[boot$converged]
    vals <- vals[is.finite(vals)]
    n_use <- length(vals)
    if (n_use < floor_n) {
      cli::cli_warn(c(
        "The parametric bootstrap for {.val {p}} produced only {n_use} usable replicate{?s} of {boot$nboot}.",
        i = "Returning {.val NA}; the estimator is too unstable to summarise (consider {.pkg bayesTLS})."
      ))
      return(tibble::tibble(
        parameter = p, conf.low = NA_real_, conf.high = NA_real_,
        estimate = tg$estimate, level = level, method = "bootstrap",
        scale = tg$scale, conf.status = "bootstrap_unstable"
      ))
    }
    if (n_use < 0.5 * boot$nboot) {
      cli::cli_inform(c(
        "i" = "Only {n_use} of {boot$nboot} bootstrap replicates for {.val {p}} converged; the interval uses those."
      ))
    }
    q <- stats::quantile(vals, c(alpha / 2, 1 - alpha / 2), names = FALSE,
                         na.rm = TRUE)
    lo <- tg$backtransform(q[1L])
    hi <- tg$backtransform(q[2L])
    tibble::tibble(
      parameter = p, conf.low = lo, conf.high = hi,
      estimate = tg$estimate, level = level, method = "bootstrap",
      scale = tg$scale, conf.status = "bootstrap"
    )
  })
  do.call(rbind, rows)
}

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.