tests/testthat/test-v051.R

# ==============================================================================
# test-v051.R — Tests for the 0.5.1 features
# ==============================================================================
# Permutation within blocks for null model A, adjustment of p-values (P_adj),
# the summary table with both tails, and the new class names (with the
# methods for objects created with 0.5.0).
# ==============================================================================

tr51 <- data.frame(
  Mass = c(15, 20, 30, 45, 60, 90, 150, 250, 400, 600),
  Beak = c(10, 12, 15, 22, 28, 35,  45,  60,  85, 120),
  Diet = factor(c(0, 0, 1, 1, 1, 0,  1,  1,  1,  0))
)
rownames(tr51) <- paste0("Sp", 1:10)

# Six matched pairs of samples (e.g. the same six months in both states)
ab51 <- withr::with_seed(51, {
  lam_r <- c(2, 3, 10, 15, 20, 18, 10, 8, 4, 2)
  lam_i <- c(8, 9, 12, 12, 15, 12, 8, 6, 3, 2)
  m <- rbind(matrix(stats::rpois(60, rep(lam_r, each = 6)), 6),
             matrix(stats::rpois(60, rep(lam_i, each = 6)), 6))
  m[m == 0 & col(m) %in% 3:6] <- 1
  dimnames(m) <- list(c(paste0("R", 1:6), paste0("I", 1:6)), rownames(tr51))
  m
})
time51 <- rep(c("R", "I"), each = 6)
month51 <- rep(paste0("m", 1:6), 2)

pair51 <- function(blocks = NULL, ab = ab51, time = time51) {
  asc_paired(tr51, ab, sites = rep("S", nrow(ab)), time = time, ref_time = "R",
             blocks = blocks)
}
A_rows <- function(r) r$null_models[r$null_models$Test == "A_samples", ]


# ==============================================================================
# Blocks
# ==============================================================================
test_that("blocks must have one value per sample and no missing values", {
  expect_error(pair51(blocks = month51[-1]), "one value per row")
  expect_error(pair51(blocks = replace(month51, 2, NA)), "missing values")
})

test_that("matched pairs give 2^B allocations, enumerated when n_perm allows", {
  r <- asc_null(pair51(blocks = month51), n_perm = 99, seed = 1)
  pm <- r$null_settings$permutation
  pm <- pm[pm$Test == "A_samples", ]
  expect_equal(pm$Design, "blocks")
  expect_equal(pm$Blocks, 6L)
  expect_equal(pm$Allocations, 2^6)
  expect_true(pm$Exact)
  # the two states swapped in every pair give the same position statistic
  expect_equal(pm$Min_P_position, 2 / 2^6)
  p <- unlist(A_rows(r)[, c("P_upper", "P_lower", "P_two")])
  p <- p[!is.na(p)]   # volume is NA when the hull is undefined
  expect_true(all(abs(p * 64 - round(p * 64)) < 1e-9))
  expect_gte(min(A_rows(r)$P_upper[A_rows(r)$Layer == "Position"]), 2 / 64)

  r_rand <- asc_null(pair51(blocks = month51), n_perm = 19, seed = 1)
  pm2 <- r_rand$null_settings$permutation
  expect_false(pm2$Exact[pm2$Test == "A_samples"])
})

test_that("a single block is the free permutation (same exact p-values)", {
  free <- asc_null(pair51(), n_perm = 999, seed = 1)
  one <- asc_null(pair51(blocks = rep("all", 12)), n_perm = 999, seed = 1)
  expect_equal(A_rows(one)[, c("P_upper", "P_lower", "P_two")],
               A_rows(free)[, c("P_upper", "P_lower", "P_two")])
  expect_equal(free$null_settings$permutation$Design[1], "free")
  expect_equal(free$null_settings$permutation$Allocations[1], choose(12, 6))
})

test_that("blocks with samples of only one state are reported, and useless blocks stop", {
  b_partial <- c(paste0("m", 1:6), paste0("m", c(1:5, 7)))
  expect_message(asc_null(pair51(blocks = b_partial), n_perm = 19, seed = 1), "only one state")
  b_none <- rep(c("a", "b"), each = 6)
  expect_error(asc_null(pair51(blocks = b_none), n_perm = 19, seed = 1), "nothing to permute")
})

test_that("too few blocks give a warning about the smallest attainable p-value", {
  ab3 <- ab51[c(1:3, 7:9), ]
  r3 <- pair51(blocks = rep(paste0("m", 1:3), 2), ab = ab3, time = rep(c("R", "I"), each = 3))
  expect_warning(asc_null(r3, n_perm = 99, seed = 1), "smallest attainable")
})

test_that("blocks are not used without replicates", {
  ab1 <- ab51[c(1, 7), ]
  r1 <- pair51(blocks = c("m1", "m1"), ab = ab1, time = c("R", "I"))
  expect_message(r1 <- asc_null(r1, n_perm = 19, seed = 1), "not used")
  expect_true("A_individuals" %in% r1$null_models$Test)
  expect_equal(r1$null_settings$permutation$Design[1], "individuals")
})

test_that("blocks also restrict A by entities", {
  ent <- stats::setNames(rep(paste0("E", 1:5), each = 2), rownames(tr51))
  r <- asc_null(pair51(blocks = month51), n_perm = 99, seed = 1, entities = ent)
  pm <- r$null_settings$permutation
  expect_equal(pm$Design[pm$Test == "A_entities_samples"], "blocks")
  expect_equal(pm$Allocations[pm$Test == "A_entities_samples"], 2^6)
})


# ==============================================================================
# Adjusted p-values
# ==============================================================================
test_that("P_adj adjusts the p-value used, within each contrast and test", {
  r <- asc_null(pair51(), n_perm = 99, seed = 2)
  tab <- r$null_models
  used <- ifelse(tab$Layer == "Position", tab$P_upper, tab$P_two)
  for (t in unique(tab$Test)) {
    i <- tab$Test == t
    expect_equal(tab$P_adj[i], stats::p.adjust(used[i], method = "BH"))
  }
  expect_equal(r$null_settings$p_adjust, "BH")

  r0 <- asc_null(pair51(), n_perm = 99, seed = 2, p_adjust = "none")
  expect_equal(r0$null_models$P_adj, used)
  rh <- asc_null(pair51(), n_perm = 99, seed = 2, p_adjust = "holm")
  expect_true(all(rh$null_models$P_adj >= used - 1e-12, na.rm = TRUE))
  expect_error(asc_null(pair51(), n_perm = 19, p_adjust = "bonf"), "p_adjust")
})

test_that("the global test adjusts the upper tail of its three layers", {
  ab_pw <- ab51[c(1, 3, 5, 7, 9, 11), ]
  pw <- asc_null(asc_pairwise(tr51, ab_pw), n_perm = 19, seed = 3)
  tab <- pw$null_models
  for (t in unique(tab$Test)) {
    i <- tab$Test == t
    expect_equal(tab$P_adj[i], stats::p.adjust(tab$P_upper[i], method = "BH"))
  }
})


test_that("two_sided chooses the two-tailed convention; centred is the default", {
  rc <- asc_null(pair51(), n_perm = 99, seed = 4)
  rd <- asc_null(pair51(), n_perm = 99, seed = 4, two_sided = "doubled")
  expect_equal(rc$null_settings$two_sided, "centred")
  expect_equal(rd$null_settings$two_sided, "doubled")
  expect_equal(rd$null_models$P_two, pmin(1, 2 * pmin(rd$null_models$P_upper, rd$null_models$P_lower)))
  # same permutations: only P_two (and therefore P_adj) can change
  expect_equal(rd$null_models[, c("P_upper", "P_lower", "SES")], rc$null_models[, c("P_upper", "P_lower", "SES")])
  used <- ifelse(rd$null_models$Layer == "Position", rd$null_models$P_upper, rd$null_models$P_two)
  for (t in unique(rd$null_models$Test)) {
    i <- rd$null_models$Test == t
    expect_equal(rd$null_models$P_adj[i], stats::p.adjust(used[i], method = "BH"))
  }
  expect_error(asc_null(pair51(), n_perm = 19, two_sided = "median"))
  out <- capture.output(summary(rd))
  expect_true(any(grepl("twice the smaller tail", out)))
})


# ==============================================================================
# summary(): both tails and adjusted p-values
# ==============================================================================
test_that("summary shows both tails, the two-tailed and the adjusted p-value", {
  r <- asc_null(pair51(blocks = month51), n_perm = 99, seed = 1)
  out <- capture.output(summary(r))
  expect_true(any(grepl("P_upper", out)))
  expect_true(any(grepl("P_lower", out)))
  expect_true(any(grepl("P_two", out)))
  expect_true(any(grepl("P_BH", out)))
  expect_true(any(grepl("2 x min\\(P_upper, P_lower\\)", out)))
  expect_true(any(grepl("Reading: based on the adjusted p-value \\(P_BH\\)", out)))
  expect_true(any(grepl("within 6 blocks", out)))
  # in paired contrasts the lower tail of B is not read as compensation
  expect_false(any(grepl("compensation\\)", out[grepl("^ *S ", out)])))
})


# ==============================================================================
# Class names
# ==============================================================================
test_that("objects carry the new class and the class of 0.5.0", {
  r <- pair51()
  expect_s3_class(r, "ascent_paired")
  expect_s3_class(r, "ascfcd")
  expect_s3_class(asc_transitions(r), "ascent_transitions")
})

test_that("objects saved with 0.5.0 (old class only) still work", {
  old <- asc_null(pair51(), n_perm = 19, seed = 1)
  class(old) <- "ascfcd"
  old$null_models$P_adj <- NULL       # 0.5.0 had no P_adj
  old$null_settings$permutation <- NULL
  expect_output(print(old), "Paired")
  expect_output(summary(old), "Null Models")
  expect_s3_class(asc_null(old, n_perm = 19, seed = 1), "ascfcd")
  tr_old <- asc_transitions(old)
  class(tr_old) <- "ascfcd_transitions"
  expect_output(summary(tr_old), "Transitions")
})


# ==============================================================================
# Number of axes by mSD, orthogonal part of the leverage, rarefied Delta FRic
# ==============================================================================
test_that("dim_retention = 'msd' keeps the k (>= 2) with minimum mSD", {
  q <- assess_functional_space(tr51, dim_retention = "msd")
  expect_named(q$msd, c("k", "mSD", "r"))
  expect_equal(q$k_retained, which.min(replace(q$msd$mSD, 1, Inf)))
  r <- asc_paired(tr51, ab51, sites = rep("S", 12), time = time51, ref_time = "R",
                  dim_retention = "msd")
  expect_equal(r$k_retained, q$k_retained)
  expect_output(summary(q), "Maire")
})

test_that("leverage and orthogonal part rebuild the size of each contribution", {
  tr <- asc_transitions(pair51())$S$species_leverage
  expect_true("Orthogonal" %in% names(tr))
  expect_true(all(tr$Orthogonal >= 0))
  r <- pair51()
  p_r <- as.numeric(r$p_ref$S); p_c <- as.numeric(r$p_comp$S)
  mid <- (as.numeric(p_r %*% r$F_space) + as.numeric(p_c %*% r$F_space)) / 2
  size <- abs(p_c - p_r) * sqrt(rowSums(sweep(r$F_space, 2, mid)^2))
  names(size) <- rownames(r$F_space)
  expect_equal(sqrt(tr$Leverage^2 + tr$Orthogonal^2), unname(size[tr$Species]), tolerance = 1e-10)
})

test_that("Delta_FRic_rarefied uses the same number of samples in both states", {
  eq <- pair51()
  expect_equal(eq$site_results$S$Delta_FRic_rarefied, eq$site_results$S$Delta_FRic)
  ab <- ab51[c(1:6, 7:10), ]
  un <- asc_paired(tr51, ab, sites = rep("S", 10), time = rep(c("R", "I"), c(6, 4)), ref_time = "R")
  expect_equal(unname(un$site_results$S$n_samples), c(6, 4))
  rel <- ab / rowSums(ab)
  topo <- utils::getFromNamespace(".calc_core_topology", "ascent")
  f_r <- mean(vapply(utils::combn(6, 4, simplify = FALSE), function(i)
    topo(colMeans(rel[i, , drop = FALSE]), un$F_space)$FRic, numeric(1)), na.rm = TRUE)
  f_c <- topo(colMeans(rel[7:10, ]), un$F_space)$FRic
  expect_equal(un$site_results$S$Delta_FRic_rarefied, f_c - f_r)
})

Try the ascent package in your browser

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

ascent documentation built on Nov. 30, 2026, 1:07 a.m.