R/utils.R

Defines functions tdt_fit_censored tdt_observed_as_recorded tdt_fixed_asymptote_values tdt_fixed_asymptote_raw tdt_resolve_fix_asymptotes tdt_is_grouped tdt_format_hours tdt_resolve_t_ref tdt_resolve_time_multiplier tdt_unit_to_minutes compute_4pl_bounds tdt_auto_re_formula tdt_validate_data2 tdt_bar_cov_vars tdt_bar_group_vars tdt_split_bars 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_auto_re_formula tdt_bar_cov_vars tdt_bar_group_vars tdt_check_columns tdt_format_random_effects tdt_quantile tdt_random_effect_variables tdt_resolve_time_multiplier tdt_resolve_t_ref tdt_split_bars tdt_unit_to_minutes tdt_validate_data2

# 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 posterior median plus credible interval as a single string
#'
#' @param median,lower,upper Numeric (scalar or vector).
#' @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
}

#' Null-coalescing operator
#'
#' Returns `x` unless it is `NULL`, in which case `y` is returned.
#'
#' @param x,y Any R objects.
#' @return `x` if non-`NULL`, otherwise `y`.
#' @keywords internal
#' @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 (\u00d7 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
#'
#' @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
#'
#' @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
#'
#' @keywords internal
tdt_random_effect_variables <- function(random_effects = NULL) {
  terms <- tdt_format_random_effects(random_effects)
  unique(unlist(lapply(terms, function(term) {
    bars <- tdt_split_bars(term)$bars
    if (length(bars)) unlist(lapply(bars, tdt_bar_group_vars))
    else {
      vars <- all.vars(stats::as.formula(paste("~", term)))
      vars[vars != "1"]
    }
  })))
}

#' Split a formula right-hand side into fixed terms and `(x | g)` bar terms
#'
#' Walks the parsed expression instead of using text patterns, so grouping
#' calls with nested parentheses -- `(1 | gr(species, cov = A))` -- survive
#' intact (the regex predecessors stopped at the first `)` and aborted;
#' issue #12). Returns `list(fixed = <RHS string>, bars = <list of `lhs | rhs`
#' calls>)`; `fixed` is `"1"` when nothing but bar terms remain.
#'
#' @keywords internal
tdt_split_bars <- function(rhs) {
  expr <- str2lang(paste("~", rhs))[[2]]
  bars <- list()
  walk <- function(e) {
    if (is.call(e)) {
      if (identical(e[[1]], as.name("(")) && is.call(e[[2]]) &&
          identical(e[[2]][[1]], as.name("|"))) {
        bars[[length(bars) + 1]] <<- e[[2]]
        return(NULL)
      }
      if (identical(e[[1]], as.name("+"))) {
        l <- walk(e[[2]])
        r <- if (length(e) > 2) walk(e[[3]]) else NULL
        if (is.null(l)) return(r)
        if (is.null(r)) return(l)
        return(call("+", l, r))
      }
    }
    e
  }
  fixed <- walk(expr)
  list(fixed = if (is.null(fixed)) "1"
       else paste(deparse(fixed), collapse = " "),
       bars = bars)
}

#' Data-column variables named by one `(x | g)` bar term's grouping side
#'
#' `gr()` aware: every argument except `cov =` (a `data2` matrix) and
#' `dist =` (a string) names data columns, so `gr(species, cov = A)` yields
#' `"species"` -- never `"A"`. Plain groups (`g`, `a/b`) fall through to
#' `all.vars()`. `mm()` multi-membership is not supported and errors clearly.
#'
#' @keywords internal
tdt_bar_group_vars <- function(bar) {
  g <- bar[[3]]
  if (is.call(g) && identical(g[[1]], as.name("mm")))
    stop("mm() multi-membership grouping is not supported in bayesTLS ",
         "formulas.", call. = FALSE)
  if (is.call(g) && identical(g[[1]], as.name("gr"))) {
    keep <- setdiff(seq_along(g)[-1],
                    which(names(g) %in% c("cov", "dist")))
    return(unique(unlist(lapply(as.list(g)[keep], all.vars))))
  }
  all.vars(g)
}

#' `cov =` matrix names used by the `gr()` terms of one bar list
#'
#' Returns a named character vector: names are the grouping variables, values
#' the `data2` object names their `cov =` argument references.
#'
#' @keywords internal
tdt_bar_cov_vars <- function(bars) {
  out <- character()
  for (bar in bars) {
    g <- bar[[3]]
    if (is.call(g) && identical(g[[1]], as.name("gr")) &&
        "cov" %in% names(g)) {
      cv <- all.vars(g[["cov"]])
      gv <- tdt_bar_group_vars(bar)[1]
      out[gv] <- cv[1]
    }
  }
  out
}

#' Validate `data2` against the `gr(cov = )` terms of the model formulas
#'
#' Checks that every covariance matrix a `gr()` term references is present in
#' `data2`, symmetric, and has dimnames covering the grouping factor's levels;
#' warns when the diagonal is not ~1 (a covariance rather than the expected
#' correlation matrix, `ape::vcv(phy, corr = TRUE)` convention). Also checks
#' the grouping columns exist in `data`.
#'
#' @keywords internal
tdt_validate_data2 <- function(formulas, data, data2 = NULL) {
  rhss <- unlist(lapply(formulas, function(f) {
    if (is.null(f)) return(NULL)
    if (inherits(f, "formula")) paste(deparse(f[[length(f)]]), collapse = " ")
    else as.character(f)
  }))
  bars <- unlist(lapply(rhss, function(r) tdt_split_bars(r)$bars),
                 recursive = FALSE)
  if (!length(bars)) return(invisible(TRUE))

  gvars <- unique(unlist(lapply(bars, tdt_bar_group_vars)))
  miss_cols <- setdiff(gvars, names(data))
  if (length(miss_cols))
    stop("Random-effect grouping variable(s) not found in the data: ",
         paste(miss_cols, collapse = ", "),
         ". Carry them through standardize_data() (e.g. via `random_effects`)",
         " so the column reaches the model frame.", call. = FALSE)

  covs <- tdt_bar_cov_vars(bars)
  if (!length(covs)) return(invisible(TRUE))
  if (is.null(data2))
    stop("The model uses gr(..., cov = ", paste(covs, collapse = ", "),
         ") but no `data2` was supplied. Pass data2 = list(",
         paste0(covs, " = <matrix>", collapse = ", "), ").", call. = FALSE)

  for (gv in names(covs)) {
    cv <- covs[[gv]]
    M  <- data2[[cv]]
    if (is.null(M))
      stop("Covariance matrix '", cv, "' (used by gr(", gv,
           ", cov = ", cv, ")) is not in `data2`.", call. = FALSE)
    if (!is.matrix(M) || !isSymmetric(unname(M), tol = 1e-8))
      stop("`data2$", cv, "` must be a symmetric matrix.", call. = FALSE)
    if (is.null(rownames(M)) || is.null(colnames(M)))
      stop("`data2$", cv, "` must carry dimnames (row and column names ",
           "matching the levels of '", gv, "').", call. = FALSE)
    lev <- unique(as.character(data[[gv]]))
    missing_lev <- setdiff(lev, rownames(M))
    if (length(missing_lev))
      stop("`data2$", cv, "` is missing level(s) of '", gv, "': ",
           paste(missing_lev, collapse = ", "), call. = FALSE)
    if (max(abs(diag(M)[lev] - 1)) > 1e-6)
      warning("`data2$", cv, "` does not have a unit diagonal; it looks like ",
              "a covariance rather than a correlation matrix. brms expects a ",
              "correlation matrix (e.g. ape::vcv(phy, corr = TRUE)).",
              call. = FALSE)
  }
  invisible(TRUE)
}

#' Auto-resolve `re_formula` when a `by` variable exists only as a random effect
#'
#' Given the sub-parameter formula right-hand sides, a `by` request, and the
#' fixed-effect moderator names, returns `NA` (the legacy behaviour: `by` is a
#' fixed-effect moderator, or matches nothing) or a one-sided formula holding
#' EXACTLY the bar terms whose grouping variables include `by`. Never returns
#' a blanket `NULL`: the prediction grid pads unrelated grouping columns with
#' arbitrary first values, which blanket inclusion would turn into phantom
#' effects.
#'
#' @keywords internal
tdt_auto_re_formula <- function(pforms, by, fixed_vars = character(0)) {
  if (is.null(by) || !length(by)) return(NA)
  if (any(by %in% fixed_vars)) return(NA)
  bars <- unlist(lapply(pforms, function(r) tdt_split_bars(r)$bars),
                 recursive = FALSE)
  hit <- Filter(function(b) any(by %in% tdt_bar_group_vars(b)), bars)
  if (!length(hit)) return(NA)
  txt <- unique(vapply(hit, function(b)
    paste0("(", paste(deparse(b), collapse = " "), ")"), character(1)))
  stats::as.formula(paste("~", paste(txt, collapse = " + ")))
}

#' 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)
}

#' 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
#' [tls()] and [derive_tdt_curve()] 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
}

#' Resolve the CTmax reference exposure for the TDT extractors
#'
#' `t_ref` is the reference exposure that `CTmax` is reported at. Because
#' `CTmax` shifts with the reference time (by \eqn{z \cdot \log_{10}} of the
#' ratio), reading a fit at a different `t_ref` than it was fitted with silently
#' moves `CTmax` (while leaving `z`, which is reference-invariant, unchanged).
#' When the caller does not supply `t_ref`, inherit the fit's own reference
#' (`meta$t_ref`, in minutes) and announce it via a message; fall back to 60 min
#' for raw fits that record no reference.
#'
#' @param t_ref Caller-supplied reference exposure (minutes) or `NULL`.
#' @param meta A `bayes_tls` workflow's `meta` list (uses `t_ref`).
#' @return Numeric reference exposure in minutes.
#' @keywords internal
tdt_resolve_t_ref <- function(t_ref, meta) {
  if (!is.null(t_ref)) return(t_ref)
  fit_tref <- meta$t_ref
  if (!is.null(fit_tref) && is.finite(fit_tref)) {
    message("`t_ref` not provided; defaulting to the model fit's reference ",
            "exposure: ", format(fit_tref), " min (", tdt_format_hours(fit_tref),
            "). Pass `t_ref` explicitly to read CTmax at a different reference.")
    return(fit_tref)
  }
  message("`t_ref` not provided and the fit records no reference exposure; ",
          "defaulting to 60 min (1 hour).")
  60
}

# Pretty "<n> hour(s)" label for a duration given in minutes.
tdt_format_hours <- function(minutes) {
  h  <- minutes / 60
  hr <- if (isTRUE(all.equal(h, round(h)))) format(round(h)) else format(round(h, 2))
  paste0(hr, if (identical(hr, "1")) " hour" else " hours")
}

# --- grouped-fit detection ---------------------------------------------------
# A direct/midpoint fit is "grouped" when CTmax/z (or mid) vary by a fixed
# moderator. fit_4pl() records this coding-independently in meta$grouped, so
# `~ 0 + G` (cell-means) and `~ 1 + G` (treatment) are both detected. The
# coefficient-count fallback covers hand-wrapped brmsfits lacking that metadata.
# Used by tdt_resolve_by() as a safety net: a fit that looks grouped but has no
# recorded moderators must not be silently extracted at its reference level.
tdt_is_grouped <- function(workflow) {
  g <- workflow$meta$grouped
  if (!is.null(g)) return(isTRUE(g))
  if (!inherits(workflow, "bayes_tls") || is.null(workflow$fit)) return(FALSE)
  nms <- names(posterior::as_draws_df(workflow$fit))
  ndirect <- max(sum(grepl("^b_CTmaxdev_", nms)), sum(grepl("^b_logz_", nms)))
  if (ndirect > 0) return(ndirect > 1)
  any(grepl("^b_mid_", nms) & !grepl("_(Intercept|temp_c)$", nms))
}

# --- Fixed asymptotes -------------------------------------------------------
#
# `fix_asymptotes` pins `low` and/or `up` instead of estimating them. It is a
# PRIOR feature, not a formula change: the asymptote keeps its `lowraw`/`upraw`
# nlpar (so every downstream reader -- tls(), predict_*(), accessors -- is
# untouched) but its Intercept gets a brms `constant()` prior and its formula
# is forced to `~ 1`. Resolution and the raw-scale mapping live here so
# fit_4pl() and make_4pl_priors() agree exactly.

# Resolve the user-facing `fix_asymptotes` value into NULL (estimate both) or a
# named list with the requested response-scale values for "low" and/or "up".
#   TRUE                 -> both at the response bounds (lower, upper)
#   c("up")              -> the named asymptote(s) at the response bounds
#   c(low = 0.02, up = 1) -> the named asymptote(s) at the given values
tdt_resolve_fix_asymptotes <- function(fix_asymptotes, lower = 0, upper = 1) {
  usage <- paste0("`fix_asymptotes` must be NULL/FALSE (estimate both), TRUE ",
                  "(fix both at the response bounds), a character vector of ",
                  "\"low\"/\"up\" (fix those at the bounds) or a named numeric ",
                  "vector such as c(low = 0, up = 1).")
  if (is.null(fix_asymptotes) || isFALSE(fix_asymptotes)) return(NULL)
  if (isTRUE(fix_asymptotes)) return(list(low = lower, up = upper))
  if (is.character(fix_asymptotes)) {
    bad <- setdiff(fix_asymptotes, c("low", "up"))
    if (length(bad) || !length(fix_asymptotes) || anyDuplicated(fix_asymptotes))
      stop(usage, call. = FALSE)
    return(as.list(c(low = lower, up = upper)[fix_asymptotes]))
  }
  if (is.numeric(fix_asymptotes)) {
    nm <- names(fix_asymptotes)
    if (is.null(nm) || !length(nm) || !all(nm %in% c("low", "up")) ||
        anyDuplicated(nm))
      stop(usage, call. = FALSE)
    vals <- as.list(fix_asymptotes)
    for (n in names(vals)) {
      v <- vals[[n]]
      if (!is.finite(v) || v < lower || v > upper)
        stop(sprintf(paste0("fix_asymptotes: %s = %g is outside the response ",
                            "bounds [%g, %g]."), n, v, lower, upper),
             call. = FALSE)
    }
    return(vals)
  }
  stop(usage, call. = FALSE)
}

# Map a fixed response-scale asymptote value to the raw (logit-scale) constant
# used by the disjoint-bounds reparameterisation, and return the EFFECTIVE value
# the model carries. `which` is "low" or "up"; `b` is compute_4pl_bounds().
# A value AT the response bound (the usual request: low = 0, up = 1) cannot be
# represented exactly, because the window keeps `pad` away from the bound so
# the identity-link likelihood never sees a probability of exactly 0 or 1; it
# is pinned at the window edge (0.001 / 0.999 with the defaults). Any other
# value outside the window would cross the disjoint-bounds midpoint and is an
# error.
tdt_fixed_asymptote_raw <- function(value, which = c("low", "up"), b,
                                    lower = 0, upper = 1) {
  which <- match.arg(which)
  mn <- if (which == "low") b$low_min else b$up_min
  w  <- if (which == "low") b$low_w   else b$up_w
  mx <- mn + w
  if (which == "low" && isTRUE(all.equal(value, lower))) value <- mn
  if (which == "up"  && isTRUE(all.equal(value, upper))) value <- mx
  if (value < mn || value > mx)
    stop(sprintf(paste0("fix_asymptotes: %s = %g lies outside the interval ",
                        "(%.4g, %.4g) that `%s` may occupy under the ",
                        "disjoint-bounds reparameterisation (see ",
                        "compute_4pl_bounds()). Values at the response bounds ",
                        "(%g or %g) are pinned at the interval edge; choose a ",
                        "value inside the interval otherwise."),
                 which, value, mn, mx, which, lower, upper), call. = FALSE)
  q   <- min(max((value - mn) / w, 1e-9), 1 - 1e-9)
  raw <- stats::qlogis(q)
  list(raw = raw, value = mn + stats::plogis(raw) * w)
}

# Effective fixed values (named numeric, response scale) for `meta`, or NULL.
tdt_fixed_asymptote_values <- function(fx, b, lower = 0, upper = 1) {
  if (is.null(fx)) return(NULL)
  vapply(names(fx), function(n)
    tdt_fixed_asymptote_raw(fx[[n]], n, b, lower, upper)$value, numeric(1))
}


# Observed data as recorded: a censored reading (standardize_data(detection_limit
# = )) carries its limit in `survival` for the likelihood, but plots and
# observed summaries should show what was recorded (e.g. 0). Swaps only for
# censored data, i.e. when both the flag and the recorded column are present,
# so an unrelated raw column named `survival_recorded` is left alone.
tdt_observed_as_recorded <- function(observed) {
  if (is.null(observed) ||
      !all(c("censored", "survival_recorded") %in% names(observed)))
    return(observed)
  meta <- attr(observed, "tdt_meta")
  if (!is.null(meta) && !isTRUE(meta$censored)) return(observed)  # stale pair
  rec <- observed$survival_recorded
  observed$survival <- ifelse(is.na(rec), observed$survival, rec)
  observed
}

# Whether a brmsfit (or brmsformula) has a censoring term on its response.
tdt_fit_censored <- function(fit) {
  f <- if (inherits(fit, "brmsfit")) fit$formula else fit
  !is.null(f) && !is.null(brms::brmsterms(f)$adforms$cens)
}

Try the bayesTLS package in your browser

Any scripts or data that you put into this service are public.

bayesTLS documentation built on Nov. 29, 2026, 1:06 a.m.