R/tdt-utils.R

Defines functions tdt_is_grouped tdt_resolve_time_multiplier tdt_unit_to_minutes tls_resolve_fix_asymptotes tls_validate_fixed_asymptote tls_validate_shape_bounds compute_4pl_bounds tdt_random_effect_variables tdt_format_random_effects tdt_check_columns clock_to_minutes `%||%` format_interval tdt_quantile

Documented in clock_to_minutes compute_4pl_bounds format_interval tdt_check_columns tdt_format_random_effects tdt_quantile tdt_random_effect_variables tdt_resolve_time_multiplier tdt_unit_to_minutes

# Small utilities used across the TDT function library.
# Internal helpers carry @keywords internal.

#' Quantile wrapper with TDT-friendly defaults
#'
#' @param x Numeric vector.
#' @param probs Numeric vector of quantile probabilities.
#' @return Numeric vector of length `length(probs)`.
#' @examples
#' tdt_quantile(rnorm(100))
#' @export
tdt_quantile <- function(x, probs = c(0.025, 0.5, 0.975)) {
  stats::quantile(x, probs = probs, na.rm = TRUE, names = FALSE)
}

#' Format a point estimate plus confidence interval as a single string
#'
#' @param median,lower,upper Numeric (scalar or vector). `median` is the central
#'   value (a point estimate or the median of bootstrap replicates), `lower` and
#'   `upper` the confidence-interval endpoints.
#' @param digits Integer rounding precision.
#' @return Character like `"5.12 [4.87, 5.4]"`. A non-finite `median` yields
#'   `NA_character_` (rather than `"NA [...]"`); a non-finite bound is shown as an
#'   en dash, so the strings stay table-ready.
#' @examples
#' format_interval(5.123, 4.872, 5.401)
#' format_interval(NA, 1, 2)   # -> NA
#' @export
format_interval <- function(median, lower, upper, digits = 2) {
  fmt <- function(x) ifelse(is.finite(x), as.character(round(x, digits)), "\u2013")
  out <- paste0(fmt(median), " [", fmt(lower), ", ", fmt(upper), "]")
  out[!is.finite(median)] <- NA_character_
  out
}

#' @noRd
`%||%` <- function(x, y) if (is.null(x)) y else x

#' Convert various clock formats to minutes
#'
#' Accepts POSIXt, hms / difftime, numeric fractions of a day (Excel time) or
#' bare numeric minutes, and character strings: `"HH:MM:SS"`, `"HH:MM"`, bare
#' numeric strings (minutes), and durations beyond 24 h (e.g. `"25:30:00"`).
#' Character strings are parsed element-wise; malformed entries become `NA`.
#'
#' @param x Time value(s).
#' @return Numeric vector of minutes.
#' @examples
#' clock_to_minutes("08:30:00")
#' clock_to_minutes("25:30")   # 25 h 30 min = 1530 min
#' clock_to_minutes(0.5)       # half a day = 720 min
#' @export
clock_to_minutes <- function(x) {
  if (inherits(x, "POSIXt")) {
    return(as.numeric(format(x, "%H")) * 60 +
             as.numeric(format(x, "%M")) +
             as.numeric(format(x, "%S")) / 60)
  }
  if (inherits(x, "hms") || inherits(x, "difftime")) {
    return(as.numeric(x, units = "mins"))
  }
  if (is.numeric(x)) {
    nona <- x[!is.na(x)]
    # Excel clock times arrive as fractions of a day in [0, 1]; everything else
    # is taken as already-minutes. A vector that mixes the two is ambiguous --
    # warn instead of silently reinterpreting it (the old all-or-nothing rule
    # turned c(0.5, 720) into 0.5 min, not 720 min).
    if (length(nona) && all(nona >= 0 & nona <= 1)) {
      message("clock_to_minutes(): all numeric values are in [0, 1]; ",
              "treating them as Excel day-fractions (x 1440 min). ",
              "If they are already minutes, pass them as values > 1 or ",
              "convert with as.numeric() first.")
      return(x * 24 * 60)
    }
    if (length(nona) && any(nona > 0 & nona < 1) && any(nona > 1))
      warning("clock_to_minutes(): numeric input mixes values < 1 and > 1; ",
              "treating ALL as minutes. If the < 1 values are Excel day-fractions ",
              "they will be wrong -- convert the column to one unit first.",
              call. = FALSE)
    return(x)
  }
  # Character: parse element-wise so HH:MM, HH:MM:SS, durations > 24 h, and bare
  # numeric strings all work (as.POSIXct("%H:%M:%S") returned NA for all three).
  vapply(as.character(x), function(s) {
    if (is.na(s)) return(NA_real_)
    s <- trimws(s)
    if (!nzchar(s)) return(NA_real_)
    if (grepl("^[0-9]*\\.?[0-9]+$", s)) return(as.numeric(s))      # bare -> minutes
    parts <- strsplit(s, ":", fixed = TRUE)[[1]]
    if (!length(parts) %in% c(2L, 3L) ||
        any(!grepl("^[0-9]*\\.?[0-9]+$", parts))) return(NA_real_)
    h <- as.numeric(parts[1]); m <- as.numeric(parts[2])
    sec <- if (length(parts) == 3L) as.numeric(parts[3]) else 0
    h * 60 + m + sec / 60                                          # supports h >= 24
  }, numeric(1), USE.NAMES = FALSE)
}

# --- internal helpers ---------------------------------------------------------

#' Error on missing columns
#'
#' @param data A data frame or data-frame-like object whose column names are
#'   checked.
#' @param cols Character vector of required column names. Missing values and
#'   empty strings are ignored.
#' @param arg_name Label used in the error message when columns are missing.
#' @return `TRUE`, invisibly, when every requested column is present; otherwise
#'   the function raises an error naming the missing columns.
#' @keywords internal
tdt_check_columns <- function(data, cols, arg_name = "columns") {
  cols <- cols[!is.na(cols) & nzchar(cols)]
  missing <- setdiff(cols, names(data))
  if (length(missing) > 0) {
    stop("Missing ", arg_name, ": ",
         paste(missing, collapse = ", "), call. = FALSE)
  }
  invisible(TRUE)
}

#' Format bare names as `(1 | name)` random-effect terms
#'
#' @param random_effects Optional character vector of grouping-variable names
#'   or already formatted random-intercept terms.
#' @return A character vector of random-intercept terms. Bare names are wrapped
#'   as `(1 | name)`; `NULL` or an empty input returns `character()`.
#' @keywords internal
tdt_format_random_effects <- function(random_effects = NULL) {
  if (is.null(random_effects) || length(random_effects) == 0) return(character())
  out <- vapply(random_effects, function(term) {
    term <- trimws(term)
    if (grepl("^\\(", term)) term else paste0("(1 | ", term, ")")
  }, character(1))
  unname(out)
}

#' Extract variable names from random-effect terms
#'
#' @param random_effects Optional character vector of grouping-variable names
#'   or random-intercept terms accepted by [tdt_format_random_effects()].
#' @return A character vector containing the unique grouping-variable names.
#' @keywords internal
tdt_random_effect_variables <- function(random_effects = NULL) {
  terms <- tdt_format_random_effects(random_effects)
  unique(unlist(lapply(terms, function(term) {
    vars <- all.vars(stats::as.formula(paste("~", term)))
    vars[vars != "1"]
  })))
}

#' Derive 4PL asymptote intervals from a user-supplied response range
#'
#' Given the lower and upper bounds of where the asymptotes can sit, returns
#' the disjoint intervals used by [make_4pl_formula()]'s `inv_logit` reparam.
#' `low` is mapped to `(lower + pad, midpoint - gap/2)`, `up` to
#' `(midpoint + gap/2, upper - pad)`. The gap kills label-switching by ensuring
#' `up > low` always; the pad keeps the asymptotes off the exact boundaries.
#'
#' @param lower,upper Numeric scalars. The response-scale range that the
#'                    asymptotes can occupy (`0` and `1` for proportion data;
#'                    `0.85` and `1` for PSII-like sublethal data, etc.).
#' @param pad Absolute padding from `lower` and `upper`. Default `0.001`.
#' @param gap Absolute gap between the low and up intervals. Default `0.002`.
#' @return Named list with `low_min`, `low_max`, `low_w`, `up_min`, `up_max`,
#'         `up_w`, `midpoint`.
#' @keywords internal
compute_4pl_bounds <- function(lower = 0, upper = 1,
                               pad = 0.001, gap = 0.002) {
  if (upper <= lower)
    stop("upper must be strictly greater than lower.", call. = FALSE)
  if (2 * pad + gap >= (upper - lower))
    stop("pad and gap leave no room for asymptote intervals; ",
         "reduce pad/gap or widen lower/upper.", call. = FALSE)

  midpoint <- (lower + upper) / 2
  low_min  <- lower + pad
  low_max  <- midpoint - gap / 2
  up_min   <- midpoint + gap / 2
  up_max   <- upper - pad

  list(low_min  = low_min,
       low_max  = low_max,
       low_w    = low_max - low_min,
       up_min   = up_min,
       up_max   = up_max,
       up_w     = up_max - up_min,
       midpoint = midpoint)
}

tls_validate_shape_bounds <- function(bounds) {
  if (!is.numeric(bounds) || length(bounds) != 2L || any(!is.finite(bounds)) ||
      bounds[1L] < 0 || bounds[2L] > 1 || bounds[1L] >= bounds[2L]) {
    cli::cli_abort("{.arg bounds} must be two finite values with 0 <= lower < upper <= 1.")
  }
  compute_4pl_bounds(bounds[1L], bounds[2L])
}

tls_validate_fixed_asymptote <- function(value, arg, bounds) {
  if (is.null(value)) return(NULL)
  if (!is.numeric(value) || length(value) != 1L || !is.finite(value) ||
      value < bounds[1L] || value > bounds[2L]) {
    cli::cli_abort("{.arg {arg}} must be one finite value inside bounds.")
  }
  as.numeric(value)
}

tls_resolve_fix_asymptotes <- function(x, bounds) {
  b4 <- tls_validate_shape_bounds(bounds)
  if (is.null(x) || (is.logical(x) && length(x) == 1L && identical(x, FALSE))) {
    return(list(low = NULL, up = NULL))
  }
  if (is.logical(x) && length(x) == 1L && !is.na(x) && isTRUE(x)) {
    return(list(low = b4$low_min, up = b4$up_min + b4$up_w))
  }
  if (is.character(x)) {
    if (!length(x) || anyNA(x) || anyDuplicated(x) ||
        any(!x %in% c("low", "up"))) {
      cli::cli_abort("Only {.val low} and {.val up} can be fixed with {.arg fix_asymptotes}.")
    }
    return(list(
      low = if ("low" %in% x) b4$low_min else NULL,
      up = if ("up" %in% x) b4$up_min + b4$up_w else NULL
    ))
  }
  if (!is.numeric(x) || !length(x) || is.null(names(x)) ||
      anyNA(names(x)) || any(!nzchar(names(x))) ||
      anyDuplicated(names(x)) || any(!names(x) %in% c("low", "up")) ||
      any(!is.finite(x))) {
    cli::cli_abort(c(
      "{.arg fix_asymptotes} must be TRUE, a subset of {.val low} / {.val up}, or a named numeric vector.",
      i = "Named numeric values must be finite and use only the names {.val low} and {.val up}."
    ))
  }
  values <- as.list(x)
  if (!is.null(values$low) &&
      isTRUE(all.equal(as.numeric(values$low), as.numeric(bounds[1L])))) {
    values$low <- b4$low_min
  }
  if (!is.null(values$up) &&
      isTRUE(all.equal(as.numeric(values$up), as.numeric(bounds[2L])))) {
    values$up <- b4$up_min + b4$up_w
  }
  if (!is.null(values$low) &&
      (values$low < b4$low_min || values$low > b4$low_min + b4$low_w)) {
    cli::cli_abort("A fixed {.arg low} must lie in the lower disjoint band inside {.arg bounds}.")
  }
  if (!is.null(values$up) &&
      (values$up < b4$up_min || values$up > b4$up_min + b4$up_w)) {
    cli::cli_abort("A fixed {.arg up} must lie in the upper disjoint band inside {.arg bounds}.")
  }
  list(low = values$low, up = values$up)
}

#' Convert a time-unit label to minutes
#'
#' Maps a free-text duration/time unit (e.g. `"hours"`, `"min"`, `"s"`) to its
#' length in minutes. Used to derive the model-to-output `time_multiplier` in
#' [extract_tdt()] from a workflow's `duration_unit`.
#'
#' @param unit Character scalar time-unit label.
#' @return Numeric scalar: the unit's length in minutes.
#' @keywords internal
tdt_unit_to_minutes <- function(unit) {
  if (is.null(unit) || length(unit) != 1L || is.na(unit))
    stop("time unit is NULL/NA", call. = FALSE)
  u <- tolower(trimws(as.character(unit)))
  switch(u,
         "s" = , "sec" = , "secs" = , "second" = , "seconds" = 1 / 60,
         "m" = , "min" = , "mins" = , "minute" = , "minutes" = 1,
         "h" = , "hr" = , "hrs" = , "hour" = , "hours"   = 60,
         "d" = , "day" = , "days" = 1440,
         stop("Unrecognised time unit: '", unit, "'. Use seconds/minutes/",
              "hours/days (or pass time_multiplier explicitly).", call. = FALSE))
}

#' Resolve the model-to-output time multiplier for TDT helpers
#'
#' If `time_multiplier` is supplied it is returned unchanged (explicit override).
#' Otherwise it is derived from the workflow's `meta$duration_unit` (the unit of
#' the model's `duration` column) and the requested `output_time_unit`, so that
#' `model_time * time_multiplier` is in `output_time_unit`. Falls back to `1`
#' (with a message) when the units cannot be resolved.
#'
#' @param time_multiplier Numeric scalar or `NULL`.
#' @param meta A `bayes_tls` workflow's `meta` list (uses `duration_unit`).
#' @param output_time_unit Target output time unit (e.g. `"min"`).
#' @return Numeric scalar multiplier.
#' @keywords internal
tdt_resolve_time_multiplier <- function(time_multiplier, meta,
                                        output_time_unit) {
  if (!is.null(time_multiplier)) return(time_multiplier)

  du <- meta$duration_unit
  mins_model  <- tryCatch(tdt_unit_to_minutes(du),
                          error = function(e) NA_real_)
  mins_output <- tryCatch(tdt_unit_to_minutes(output_time_unit),
                          error = function(e) NA_real_)

  if (is.na(mins_model) || is.na(mins_output)) {
    message("Could not derive time_multiplier from duration_unit ('",
            du %||% "NULL", "') and output_time_unit ('", output_time_unit,
            "'); assuming model time unit == output unit (time_multiplier = 1). ",
            "Pass time_multiplier explicitly to override.")
    return(1)
  }
  mins_model / mins_output
}

# --- grouped-fit detection ---------------------------------------------------
# A direct/midpoint fit is "grouped" when CTmax/z (or mid) vary by a fixed
# moderator. The freq_tls fit records this coding-independently in meta$grouped.
# (The Bayesian draw-name fallback used by bayesTLS is dropped here; freqTLS reads
# meta$grouped directly. Re-introduced in the P4 quantity-twin layer.)
tdt_is_grouped <- function(workflow) {
  isTRUE(workflow$meta$grouped)
}

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.