R/utils.R

Defines functions tls_name_map tls_re_blocks tls_has_re tls_cellmean_labels tls_is_constant_design tls_is_onehot tls_link tls_ci_df tls_logit_between tls_backtransform `%||%`

#' Default value for `NULL`
#'
#' Returns `x` unless it is `NULL`, in which case it returns `y`.
#'
#' @param x,y Values; `x` is returned unless `NULL`.
#' @return `x` if not `NULL`, otherwise `y`.
#' @keywords internal
#' @noRd
`%||%` <- function(x, y) {
  if (is.null(x)) y else x
}

# ---- link / back-transform helpers -----------------------------------------
# Internal parameters are unconstrained; these map to / from the natural scale.

#' Back-transform an internal coordinate to its natural scale
#'
#' @param x Numeric value(s) on the internal (unconstrained) scale.
#' @param link One of "log", "logit", or "identity".
#' @return Numeric value(s) on the natural scale.
#' @keywords internal
#' @noRd
tls_backtransform <- function(x, link) {
  switch(link,
    log = exp(x),
    logit = stats::plogis(x),
    identity = x,
    cli::cli_abort("Unknown link {.val {link}}.")
  )
}

# Compute qlogis((x - lower) / (upper - lower)) without first forming a
# proportion that can round to exactly zero or one for an interior x.
tls_logit_between <- function(x, lower, upper) {
  log(x - lower) - log(upper - x)
}

#' Residual degrees of freedom for t-based interval cutoffs
#'
#' Bates-Watts profile-t / Wald-t intervals compare the (signed-root) statistic
#' to a t distribution with `n - p` degrees of freedom: `n` data rows, `p`
#' estimated parameters. The t reference quantile tends to the normal quantile
#' as `df -> Inf`. The `n - p` choice is approximate for random-effects fits,
#' whose conditional modes are integrated out; coverage depends on the design.
#' @keywords internal
#' @noRd
tls_ci_df <- function(fit) {
  n_obs <- length(fit$diag_data$y)
  p <- length(fit$par)
  max(n_obs - p, 1L)
}

#' Transform a natural-scale value to its internal coordinate
#'
#' @param x Numeric value(s) on the natural scale.
#' @param link One of "log", "logit", or "identity".
#' @return Numeric value(s) on the internal (unconstrained) scale.
#' @keywords internal
#' @noRd
tls_link <- function(x, link) {
  switch(link,
    log = log(x),
    logit = stats::qlogis(x),
    identity = x,
    cli::cli_abort("Unknown link {.val {link}}.")
  )
}

#' Is a design matrix a one-hot factor indicator?
#'
#' Distinguishes a grouped (factor) shape design -- a clean 0/1 indicator with
#' exactly one 1 per row and no intercept, whose columns are group levels -- from
#' a general design (e.g. a continuous covariate, which carries an intercept so
#' the row sums are not all 1). A single-column (intercept-only) design is not a
#' one-hot grouping; callers handle that as the scalar shared case first.
#' @param X A design matrix.
#' @return `TRUE` for a multi-column one-hot indicator, else `FALSE`.
#' @keywords internal
#' @noRd
tls_is_onehot <- function(X) {
  ncol(X) > 1L && all(X %in% c(0, 1)) && all(abs(rowSums(X) - 1) < 1e-9)
}

tls_is_constant_design <- function(X) {
  # The compiled scalar shortcut represents an intercept coefficient. A
  # one-column numeric design such as `~ 0 + x` must retain X %*% beta even
  # when it happens to be constant in the observed sample.
  ncol(X) == 1L && all(abs(X[, 1L] - 1) < 1e-12)
}

# Recover group values from the rows assigned to each one-hot design column.
# Parsing model-matrix labels is ambiguous when names share prefixes or levels
# contain punctuation, so use the fitted source rows as the mapping.
tls_cellmean_labels <- function(X, data, by) {
  if (!tls_is_onehot(X) || is.null(data) || nrow(X) != nrow(data) ||
      !all(by %in% names(data))) return(NULL)
  out <- data.frame(.cell = colnames(X), stringsAsFactors = FALSE)
  for (nm in by) {
    vals <- vapply(seq_len(ncol(X)), function(j) {
      assigned <- which(X[, j] == 1)
      u <- unique(as.character(data[[nm]][assigned]))
      if (length(u) != 1L || is.na(u)) NA_character_ else u
    }, character(1))
    if (anyNA(vals)) return(NULL)
    # Preserve fitted factor levels when a single cell is later rebuilt with
    # model.matrix(); dropping unused levels would make valid crossed-cell
    # predictions fail with a one-level contrasts error.
    out[[nm]] <- if (is.factor(data[[nm]])) {
      factor(vals, levels = levels(data[[nm]]), ordered = is.ordered(data[[nm]]))
    } else {
      vals
    }
  }
  # Each fitted cell must be identified by one unique requested label tuple.
  # Otherwise a request such as `by = "group"` on group-by-site coefficients
  # would repeat the same group label and report several cell estimates as one.
  if (anyDuplicated(out[by])) return(NULL)
  out
}

#' Does a fit carry any random-effects block?
#'
#' `TRUE` when the fit has a random intercept on `CTmax` (`fit$re`) and/or on
#' `log_z` (`fit$re_logz`). Routing code (confint / profile / bootstrap /
#' plotting) keys "is this a random-effects fit?" on this rather than on a single
#' sub-parameter, so a `log_z`-only RE fit is not silently treated as
#' fixed-effects-only.
#' @param fit A `profile_tls` fit.
#' @return Logical scalar.
#' @keywords internal
#' @noRd
tls_has_re <- function(fit) {
  !is.null(fit$re) || !is.null(fit$re_logz) ||
    !is.null(fit$re_low) || !is.null(fit$re_logk)
}

#' Describe the active random-effects blocks of a fit
#'
#' Returns one descriptor per active random-intercept block (`CTmax` first, then
#' `log_z`), the single source of truth for the per-block bookkeeping that ranef,
#' the `sigma_*` rows, the profile re-Laplace, and the bootstrap redraw all share.
#' Each descriptor names the engine vector (`b_name`), its log-SD parameter
#' (`sd_name`), the REPORTed SD (`sigma_report`), the human-facing SD label
#' (`sigma_label`), the BLUP term label (`term`), and the parsed `spec`
#' (`index` / `n` / `group_levels` / `group_var`).
#' @param fit A `profile_tls` fit.
#' @return A list of block descriptors (empty for a fixed-effects-only fit).
#' @keywords internal
#' @noRd
tls_re_blocks <- function(fit) {
  blocks <- list()
  ct_terms <- fit$re_ct_terms %||% tls_re_terms(fit$re)
  if (length(ct_terms)) {
    offset <- 0L
    for (j in seq_along(ct_terms)) {
      spec <- ct_terms[[j]]
      sigma_label <- if (length(ct_terms) == 1L) "sigma_CTmax" else
        paste0("sigma_CTmax:", spec$group_var)
      blocks[[length(blocks) + 1L]] <- list(
        param = "CTmax", b_name = "b_CT", sd_name = "log_sd_CT",
        sd_idx = j, b_idx = seq.int(offset + 1L, offset + spec$n),
        sigma_report = "sigma_CT", sigma_label = sigma_label,
        term = if (length(ct_terms) == 1L) "CTmax" else paste0("CTmax:", spec$group_var),
        spec = spec
      )
      offset <- offset + spec$n
    }
  }
  if (!is.null(fit$re_logz)) {
    blocks[[length(blocks) + 1L]] <- list(
      param = "log_z", b_name = "b_logz", sd_name = "log_sd_logz",
      sigma_report = "sigma_logz", sigma_label = "sigma_logz",
      term = "log_z", spec = fit$re_logz, b_idx = seq_len(fit$re_logz$n), sd_idx = 1L
    )
  }
  if (!is.null(fit$re_low)) {
    blocks[[length(blocks) + 1L]] <- list(
      param = "low", b_name = "b_low", sd_name = "log_sd_low",
      sigma_report = "sigma_low", sigma_label = "sigma_low",
      term = "low", spec = fit$re_low, b_idx = seq_len(fit$re_low$n), sd_idx = 1L
    )
  }
  if (!is.null(fit$re_logk)) {
    blocks[[length(blocks) + 1L]] <- list(
      param = "log_k", b_name = "b_logk", sd_name = "log_sd_logk",
      sigma_report = "sigma_logk", sigma_label = "sigma_logk",
      term = "log_k", spec = fit$re_logk, b_idx = seq_len(fit$re_logk$n), sd_idx = 1L
    )
  }
  blocks
}

#' Build the parameter name map for a fitted model
#'
#' Connects each internal parameter coordinate to a natural-scale name, its
#' link, and (for grouped coordinates) the group level it refers to. This is the
#' contract used by profiling and printing.
#'
#' @param group_levels Character vector of group levels (length >= 1).
#' @param family A `tls_family` object (controls whether `phi` is present).
#' @return A `data.frame` with one row per internal coordinate.
#' @keywords internal
#' @noRd
tls_name_map <- function(group_levels, family, X_low, X_up, X_logk) {
  ng <- length(group_levels)

  # Shape coordinates. Each shape design is classified by its own columns:
  #   constant 1 column       -> the scalar shared `low` / `k`;
  #   >1 column, one-hot factor -> per-group `low:<level>` / `k:<level>` (natural);
  #   other designs            -> per-coefficient `low:<col>` / `k:<col>` (link
  #                                scale, e.g. a continuous covariate slope).
  # `up` is reported via the ADREPORTed `up` SE (delta-method Wald), not a profile
  # coordinate, so it is surfaced separately from the shape coordinates.
  shape_block <- function(base, natural_base, link, X) {
    nc <- ncol(X)
    if (tls_is_constant_design(X)) {
      data.frame(internal = paste0(base, "[1]"), natural = natural_base,
                 link = link, group = NA_character_, stringsAsFactors = FALSE)
    } else {
      grp <- if (tls_is_onehot(X)) colnames(X) else NA_character_
      data.frame(internal = paste0(base, "[", seq_len(nc), "]"),
                 natural = paste0(natural_base, ":", colnames(X)),
                 link = link, group = grp, stringsAsFactors = FALSE)
    }
  }
  scalar <- rbind(
    shape_block("beta_low", "low", "logit", X_low),
    if (tls_is_constant_design(X_up)) {
      data.frame(internal = "beta_up[1]", natural = "up", link = "identity",
                 group = NA_character_, stringsAsFactors = FALSE)
    } else {
      data.frame(internal = paste0("beta_up[", seq_len(ncol(X_up)), "]"),
                 natural = paste0("up:", colnames(X_up)),
                 link = if (tls_is_onehot(X_up)) "identity" else "logit",
                 group = if (tls_is_onehot(X_up)) colnames(X_up) else NA_character_,
                 stringsAsFactors = FALSE)
    },
    shape_block("beta_logk", "k", "log", X_logk)
  )

  ct <- data.frame(
    internal = paste0("beta_CT[", seq_len(ng), "]"),
    natural = if (ng == 1L) "CTmax" else paste0("CTmax:", group_levels),
    link = "identity",
    group = group_levels,
    stringsAsFactors = FALSE
  )
  logz <- data.frame(
    internal = paste0("beta_logz[", seq_len(ng), "]"),
    natural = if (ng == 1L) "z" else paste0("z:", group_levels),
    link = "log",
    group = group_levels,
    stringsAsFactors = FALSE
  )

  out <- rbind(scalar, ct, logz)
  if (family$family_code >= 1L) {
    out <- rbind(
      out,
      data.frame(
        internal = "log_phi", natural = "phi", link = "log",
        group = NA_character_, stringsAsFactors = FALSE
      )
    )
  }
  out
}

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.