tests/testthat/test-tls.R

# tls() — the bayesTLS-twin quantity extractor (z, CTmax with CIs).

std_sim <- function(seed = 1, ...) {
  standardize_data(simulate_tls(family = "binomial", seed = seed, ...),
                   temp = "temp", duration = "duration",
                   n_total = "total", n_surv = "survived", duration_unit = "minutes")
}

test_that("tls() returns z and CTmax with confidence intervals (ungrouped)", {
  f <- fit_4pl(std_sim(seed = 1, CTmax = 36, z = 4), t_ref = 1,
               family = "binomial", quiet = TRUE)
  r <- tls(f, method = "wald")
  expect_identical(class(r), c("freq_tls_summary", "tls", "list"))
  expect_setequal(r$summary$quantity, c("z", "CTmax"))
  expect_true(all(c("quantity", "median", "lower", "upper") %in% names(r$summary)))
  expect_true(all(r$summary$lower <= r$summary$median &
                  r$summary$median <= r$summary$upper))
  ct <- r$summary[r$summary$quantity == "CTmax", ]
  expect_equal(ct$median, 36, tolerance = 0.3)
  expect_identical(r$meta$mode, "relative")
  expect_match(paste(capture.output(print(r)), collapse = " "), "<tls>")
})

test_that("check_tls and tls surface a non-positive-definite Hessian", {
  fit <- std_sim(seed = 71)
  fitted <- fit_4pl(fit, family = "binomial", t_ref = 60, quiet = TRUE)
  fitted$fit$convergence$code <- 0L
  fitted$fit$convergence$pdHess <- FALSE

  expect_warning(codes <- check_tls(fitted), "Hessian is not positive definite")
  expect_true("non_pd_hessian" %in% codes)
  expect_warning(summary <- tls(fitted, method = "wald"),
                 "Hessian is not positive definite")
  expect_false(summary$meta$pdHess)
  expect_match(paste(capture.output(print(summary)), collapse = " "),
               "pdHess = FALSE")
  profiled <- suppressWarnings(tls(fitted, method = "profile",
                                   nboot = 20, seed = 1))
  expect_identical(profiled$meta$method, "bootstrap")
  expect_false(profiled$meta$pdHess)
  expect_true(all(unname(profiled$meta$methods) == "bootstrap"))
  expect_error(get_tls_est(profiled, what = "draws"), "has no bootstrap draws")
})

test_that("check_tls uses fitted CTmax values for one-column numeric designs", {
  fit_at <- function(CTmax) {
    d <- simulate_tls(family = "binomial", CTmax = CTmax, z = 4, seed = 81)
    d$x <- 2
    s <- standardize_data(d, temp = "temp", duration = "duration",
      n_total = "total", n_surv = "survived", duration_unit = "minutes")
    suppressWarnings(fit_4pl(s, ctmax = ~ 0 + x, z = ~ 0 + x,
      family = "binomial", t_ref = 1, quiet = TRUE))
  }

  in_range <- fit_at(36)
  expect_false("ctmax_extrapolated" %in% suppressWarnings(check_tls(in_range)))

  outside <- fit_at(45)
  warning_text <- character()
  codes <- withCallingHandlers(check_tls(outside), warning = function(w) {
    warning_text <<- c(warning_text, conditionMessage(w))
    invokeRestart("muffleWarning")
  })
  expect_true("ctmax_extrapolated" %in% codes)
  range_warning <- warning_text[grepl("fitted CTmax prediction", warning_text)]
  expect_length(range_warning, 1L)
  expect_lt(nchar(range_warning), 300L)
  expect_match(range_warning, "outside range:")
})

test_that("tls() groups by the moderator with clean factor-level labels", {
  d <- simulate_tls(family = "binomial", group = c("A", "B"),
                    CTmax = c(34, 38), z = c(3, 5), seed = 3)
  s <- standardize_data(d, temp = "temp", duration = "duration",
                        n_total = "total", n_surv = "survived", duration_unit = "minutes")
  f <- suppressWarnings(fit_4pl(s, ctmax = ~ 0 + group, z = ~ 0 + group,
                                t_ref = 1, family = "binomial", quiet = TRUE))
  r <- tls(f, method = "wald")
  expect_true("group" %in% names(r$summary))
  expect_setequal(unique(r$summary$group), c("A", "B"))   # not "groupA"/"groupB"
  expect_equal(nrow(r$summary), 4L)                       # 2 groups x {z, CTmax}
  # CTmax recovers the per-group truth
  ctA <- r$summary$median[r$summary$group == "A" & r$summary$quantity == "CTmax"]
  expect_equal(ctA, 34, tolerance = 0.5)
})

test_that("tls() preserves crossed cell labels after rows are reordered", {
  d <- simulate_tls(family = "binomial",
                    group = c("A_north", "A_south", "B_north", "B_south"),
                    CTmax = c(34, 36, 38, 40), z = c(3, 4, 5, 6), seed = 32)
  cells <- as.character(d$group)
  d$group <- factor(sub("_.*$", "", cells), levels = c("A", "B"))
  d$site <- factor(sub("^.*_", "", cells), levels = c("north", "south"))
  std <- standardize_data(d, temp = "temp", duration = "duration",
                          n_total = "total", n_surv = "survived",
                          duration_unit = "minutes")
  fit <- suppressWarnings(fit_4pl(std, ctmax = ~ 0 + group:site,
                                  z = ~ 0 + group:site, t_ref = 1,
                                  family = "binomial", quiet = TRUE))
  summary <- tls(fit, by = c("group", "site"), method = "wald")
  expect_true(all(c("group", "site") %in% names(summary$summary)))
  expect_setequal(paste(summary$summary$group, summary$summary$site),
                  c("A north", "A south", "B north", "B south"))

  reordered <- std[rev(seq_len(nrow(std))), , drop = FALSE]
  fit_reordered <- suppressWarnings(fit_4pl(reordered,
    ctmax = ~ 0 + group:site, z = ~ 0 + group:site, t_ref = 1,
    family = "binomial", quiet = TRUE))
  summary_reordered <- tls(fit_reordered, by = c("group", "site"),
                           method = "wald")
  expect_equal(summary_reordered$summary, summary$summary, tolerance = 1e-6)

  lethal <- suppressWarnings(tls(fit, by = c("group", "site"), lethal = TRUE,
                                 nboot = 40, seed = 33))
  expect_true(all(c("group", "site", "quantity") %in%
                    names(lethal$summary)))
  expect_equal(anyDuplicated(lethal$summary[c("group", "site", "quantity")]), 0L)
  expect_setequal(unique(lethal$summary$quantity), c("z", "CTmax", "Tcrit"))
  expect_error(tls(fit, by = "group", method = "wald"),
               "map to the requested moderator|identify each fitted cell")
  expect_error(extract_tdt(fit, by = "group", nboot = 6, seed = 34),
               "identify each fitted cell|requested source columns")
})

test_that("grouped summaries reject a moderator that does not identify fitted cells", {
  d <- simulate_tls(family = "binomial", group = c("A", "B"),
                    CTmax = c(34, 38), z = c(3, 5), seed = 35)
  d$age <- factor(rep(c("young", "old"), length.out = nrow(d)))
  std <- standardize_data(d, temp = "temp", duration = "duration",
                          n_total = "total", n_surv = "survived",
                          duration_unit = "minutes")
  fit <- suppressWarnings(fit_4pl(std, ctmax = ~ 0 + group,
                                  z = ~ 0 + group, t_ref = 1,
                                  family = "binomial", quiet = TRUE))
  expect_identical(unique(std$group), c("A", "B"))
  expect_setequal(unique(std$age), c("old", "young"))
  expect_error(tls(fit, by = "age", method = "wald"),
               "map to the requested moderator|identify each fitted cell")
  expect_error(extract_tdt(fit, by = "age", nboot = 6, seed = 36),
               "map to the requested moderator|identify each fitted cell")
  expect_setequal(unique(tls(fit, method = "wald")$summary$group), c("A", "B"))
})

test_that("tls() rejects contrast-coded moderator designs as group summaries", {
  d <- simulate_tls(family = "binomial", group = c("A", "B"), seed = 33)
  d$site <- factor(rep(c("north", "south"), length.out = nrow(d)))
  std <- standardize_data(d, temp = "temp", duration = "duration",
                          n_total = "total", n_surv = "survived",
                          duration_unit = "minutes")
  fit <- suppressWarnings(fit_4pl(std, ctmax = ~ group * site,
                                  z = ~ group * site, t_ref = 1,
                                  family = "binomial", quiet = TRUE))
  expect_error(tls(fit, by = c("group", "site"), method = "wald"),
               "cell-mean designs|no-intercept")
})

test_that("tls_z / tls_ctmax select a single quantity", {
  f <- fit_4pl(std_sim(seed = 5), t_ref = 1, family = "binomial", quiet = TRUE)
  expect_setequal(tls_z(f, method = "wald")$summary$quantity, "z")
  expect_setequal(tls_ctmax(f, method = "wald")$summary$quantity, "CTmax")
})

test_that("tls() accepts a bare profile_tls fit; absolute delegates to the bootstrap path", {
  f4 <- fit_4pl(std_sim(seed = 6), t_ref = 1, family = "binomial", quiet = TRUE)
  expect_s3_class(tls(f4$fit, method = "wald"), "tls")     # bare engine fit
  ra <- suppressWarnings(tls(f4, target_surv = "absolute", nboot = 40, seed = 1))
  expect_s3_class(ra, "tls")
  expect_match(ra$meta$mode, "p=0.500")
  expect_identical(ra$meta$method, "bootstrap")
})

test_that("tls keeps exact source group labels and rejects swapped cell assignments", {
  d <- simulate_tls(family = "binomial", group = c("groupA", "groupB"), seed = 71)
  std <- standardize_data(d, temp = "temp", duration = "duration",
                          n_total = "total", n_surv = "survived",
                          duration_unit = "minutes")
  f <- suppressWarnings(fit_4pl(std, by = "group", family = "binomial",
                                 t_ref = 1, quiet = TRUE))
  expect_setequal(tls(f, method = "wald")$summary$group, c("groupA", "groupB"))

  std$group2 <- factor(ifelse(std$group == "groupA", "groupB", "groupA"),
                       levels = c("groupA", "groupB"))
  swapped <- suppressWarnings(fit_4pl(std, ctmax = ~ 0 + group,
                                      z = ~ 0 + group2, family = "binomial",
                                      t_ref = 1, quiet = TRUE))
  expect_error(tls(swapped, method = "wald"), "matching represented cell-mean")
  expect_error(tls(swapped, target_surv = "absolute", nboot = 10, seed = 1),
               "matching represented cell-mean")
})

test_that("diagnose_tdt_fit reports a one-row convergence summary", {
  f <- fit_4pl(std_sim(seed = 7), t_ref = 1, family = "binomial", quiet = TRUE)
  d <- diagnose_tdt_fit(f)
  expect_equal(nrow(d), 1L)
  expect_true(all(c("converged", "pd_hessian", "max_abs_gradient",
                    "gradient_pass", "all_pass") %in% names(d)))
  expect_true(d$converged)
  expect_true(d$pd_hessian)
  expect_true(d$all_pass)
})

test_that("tdt_parameter_table returns the bayesTLS parameter/median/lower/upper shape", {
  f <- fit_4pl(std_sim(seed = 8), t_ref = 1, family = "binomial", quiet = TRUE)
  pt <- tdt_parameter_table(f, method = "wald")
  expect_setequal(names(pt), c("parameter", "group", "median", "lower", "upper"))
  expect_true(all(c("low", "up", "k", "CTmax", "z") %in% pt$parameter))
})

test_that("tls() delegates absolute / lethal to the bootstrap path", {
  d <- simulate_tls(family = "binomial", group = c("A", "B"),
                    CTmax = c(34, 38), z = c(3, 5), seed = 3)
  s <- standardize_data(d, temp = "temp", duration = "duration",
                        n_total = "total", n_surv = "survived", duration_unit = "minutes")
  f <- suppressWarnings(fit_4pl(s, ctmax = ~ 0 + group, z = ~ 0 + group,
                                t_ref = 1, family = "binomial", quiet = TRUE))
  r <- suppressWarnings(tls(f, lethal = TRUE, nboot = 49, seed = 1))
  expect_true(all(c("z", "CTmax", "Tcrit") %in% r$summary$quantity))
  expect_identical(r$meta$method, "bootstrap")
  expect_true("group" %in% names(r$summary))
  rt <- suppressWarnings(tls_tcrit(f, nboot = 49, seed = 1))
  expect_setequal(rt$summary$quantity, "Tcrit")
})

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.