tests/testthat/test-v051-std.R

# ==============================================================================
# test-v051-std.R — Axis-standardised statistic of null model B, trait shifts
# and mSD as the default number of axes (ascent 0.5.1)
# ==============================================================================

null_B   <- utils::getFromNamespace(".null_B", "ascent")
null_Bg  <- utils::getFromNamespace(".null_B_global", "ascent")
layers   <- utils::getFromNamespace(".layers", "ascent")
layers_g <- utils::getFromNamespace(".layers_global", "ascent")
lay_tab  <- utils::getFromNamespace(".layer_table", "ascent")
strata_f <- utils::getFromNamespace(".abundance_strata", "ascent")
trait_m  <- utils::getFromNamespace(".trait_matrix", "ascent")

# Two independent traits; the comparison state favours species with high B
trs <- withr::with_seed(11, data.frame(A = stats::rnorm(20), B = stats::rnorm(20),
                                       G = factor(rep(c("x", "y"), 10))))
rownames(trs) <- paste0("Sp", 1:20)
p_ref <- rep(1 / 20, 20)
p_cmp <- exp(1.5 * as.numeric(scale(trs$B))); p_cmp <- p_cmp / sum(p_cmp)
ab_s <- rbind(R = round(2000 * p_ref), C = round(2000 * p_cmp))
colnames(ab_s) <- rownames(trs)

# B as programmed in 0.5.0 (norm of the shift), for comparison
old_B <- function(p_r, p_c, F_mat, n_perm, stratum_size) {
  idx <- which(p_r > 0 | p_c > 0)
  strata <- strata_f((p_r / sum(p_r) + p_c / sum(p_c)) / 2, idx, stratum_size)
  nul <- matrix(NA_real_, n_perm, 3, dimnames = list(NULL, c("pos", "fdis", "fric")))
  for (i in seq_len(n_perm)) {
    Fp <- F_mat
    for (gr in strata) if (length(gr) > 1) Fp[gr, ] <- F_mat[gr[sample.int(length(gr))], , drop = FALSE]
    nul[i, ] <- layers(p_r, p_c, Fp)
  }
  lay_tab(layers(p_r, p_c, F_mat), nul, "B_stratified")
}

test_that("B keeps the permutations of 0.5.0: same norm result, same dispersion and volume", {
  F_mat <- asc_paired(trs, ab_s, sites = c("S", "S"), time = c("R", "C"), ref_time = "R")$F_space
  new <- withr::with_seed(7, null_B(p_ref, p_cmp, F_mat, 49, 5))
  old <- withr::with_seed(7, old_B(p_ref, p_cmp, F_mat, 49, 5))
  pn <- attr(new, "position_norm")
  expect_equal(unname(unlist(pn)), unname(unlist(old[1, names(pn)])))
  expect_equal(new[2:3, ], old[2:3, ], ignore_attr = TRUE)
})

test_that("B for position is the axis-standardised statistic", {
  F_mat <- asc_paired(trs, ab_s, sites = c("S", "S"), time = c("R", "C"), ref_time = "R")$F_space
  new <- withr::with_seed(7, null_B(p_ref, p_cmp, F_mat, 49, 5))
  # by hand, with the same draws
  V <- withr::with_seed(7, {
    idx <- which(p_ref > 0 | p_cmp > 0)
    st <- strata_f((p_ref + p_cmp) / 2, idx, 5)
    t(vapply(seq_len(49), function(i) {
      perm <- seq_len(nrow(F_mat))
      for (gr in st) if (length(gr) > 1) perm[gr] <- gr[sample.int(length(gr))]
      as.numeric((p_cmp - p_ref) %*% F_mat[perm, , drop = FALSE])
    }, numeric(ncol(F_mat))))
  })
  s_v <- apply(V, 2, stats::sd)
  v0 <- as.numeric((p_cmp - p_ref) %*% F_mat)
  nul <- rowSums(sweep(V, 2, s_v, "/")^2)
  expect_equal(new$Observed[1], sum((v0 / s_v)^2))
  expect_equal(new$P_upper[1], (1 + sum(nul >= sum((v0 / s_v)^2))) / 50)
})

test_that("asc_null returns b_position_norm and trait_shifts", {
  r <- asc_null(asc_paired(trs, ab_s, sites = c("S", "S"), time = c("R", "C"), ref_time = "R"),
                n_perm = 99, seed = 2)
  expect_equal(r$null_settings$b_position, "axis_standardised")
  expect_equal(nrow(r$b_position_norm), 1L)
  expect_true(all(c("Contrast", "Observed", "P_upper") %in% names(r$b_position_norm)))
  expect_setequal(r$trait_shifts$Trait, c("A", "B", "G = y"))  # a factor with two levels: one indicator
  expect_equal(r$trait_shifts$Trait[1], "B")                    # the trait that was changed
  expect_equal(r$trait_shifts$Type[r$trait_shifts$Trait == "G = y"], "level")
  expect_true(r$trait_shifts$Delta[1] > 0)
  out <- utils::capture.output(summary(r))
  expect_true(any(grepl("largest standardised shift", out)))
  expect_true(any(grepl("S: B", out, fixed = TRUE)))
  expect_true(any(grepl("axis-standardised|units of its null", out)))
})

test_that("categorical traits are used by level and constant traits are dropped", {
  tr_f <- data.frame(G = factor(rep(c("x", "y", "z", "w"), 5)), H = factor(rep(c("a", "b"), 10)),
                     K = rep(1, 20), L = factor(rep("u", 20)))
  rownames(tr_f) <- rownames(trs)
  z <- trait_m(tr_f, rownames(tr_f))
  expect_equal(colnames(z), c("G = w", "G = x", "G = y", "G = z", "H = b"))
  expect_equal(attr(z, "trait_type"), rep("level", 5))
  expect_null(trait_m(tr_f[, c("K", "L")], rownames(tr_f)))
  z2 <- trait_m(trs, rownames(trs))
  expect_equal(colnames(z2), c("A", "B", "G = y"))
  expect_equal(unname(colMeans(z2)), c(0, 0, 0), tolerance = 1e-12)
  # Delta of a level is the change in its share of abundance
  dz <- as.numeric((p_cmp - p_ref) %*% z2)
  share <- function(p) sum(p[trs$G == "y"])
  expect_equal(unname(dz[3] * attr(z2, "trait_sd")[3]), share(p_cmp) - share(p_ref), tolerance = 1e-12)
})

test_that("birds_sim: the factor traits that changed are named", {
  res <- asc_paired(birds_sim$traits, birds_sim$counts, sites = birds_sim$samples$site,
                    time = birds_sim$samples$time, ref_time = "Before")
  r <- asc_null(res, n_perm = 49, seed = 1)
  top <- r$trait_shifts$Trait[r$trait_shifts$Contrast == "Logged"][1]
  expect_true(grepl("^(Diet|Forest_Dep) = ", top))
})

test_that("the global test uses the axis-standardised statistic for B position", {
  X <- rbind(c1 = round(1000 * p_ref), c2 = round(1000 * (p_ref + p_cmp) / 2), c3 = round(1000 * p_cmp))
  colnames(X) <- rownames(trs)
  pw <- asc_pairwise(trs, X)
  F_mat <- pw$F_space
  Z <- trait_m(trs, rownames(F_mat))
  new <- withr::with_seed(5, null_Bg(X, F_mat, 49, 5, Z))
  P <- X / rowSums(X)
  vk <- function(C) colMeans(sweep(C, 2, colMeans(C))^2)
  V <- withr::with_seed(5, {
    st <- strata_f(colMeans(P), which(colSums(X) > 0), 5)
    t(vapply(seq_len(49), function(i) {
      perm <- seq_len(nrow(F_mat))
      for (gr in st) if (length(gr) > 1) perm[gr] <- gr[sample.int(length(gr))]
      vk(P %*% F_mat[perm, , drop = FALSE])
    }, numeric(ncol(F_mat))))
  })
  expect_equal(new$Observed[1], sum(vk(P %*% F_mat) / colMeans(V)))
  expect_equal(attr(new, "position_norm")$Observed, layers_g(X, F_mat)[["pos"]])
  expect_equal(attr(new, "trait_shift")$Trait[1], "B")
  r <- asc_null(pw, n_perm = 49, seed = 1)
  expect_equal(r$b_position_norm$Contrast, "Global")
  expect_equal(unique(r$trait_shifts$Contrast), "Global")
  expect_output(summary(r), "largest standardised shift")
})

test_that("mSD is the default number of axes and is reported", {
  r <- asc_paired(trs, ab_s, sites = c("S", "S"), time = c("R", "C"), ref_time = "R")
  q <- assess_functional_space(trs)
  expect_equal(r$dim_retention, "msd")
  expect_equal(r$k_retained, q$k_retained)
  expect_output(print(r), "rule: mSD")
  rv <- asc_paired(trs, ab_s, sites = c("S", "S"), time = c("R", "C"), ref_time = "R",
                   dim_retention = "variance")
  expect_output(print(rv), "rule: 80% variance")
  expect_equal(asc_pairwise(trs, ab_s)$dim_retention, "msd")
  expect_equal(asc_baseline(trs, ab_s)$dim_retention, "msd")
  old <- r; old$dim_retention <- NULL                         # object saved with 0.5.0
  expect_output(print(old), "rule: 80% variance")
})

test_that("the lower tail of B is not read as compensation in the global test", {
  X <- rbind(c1 = round(1000 * p_ref), c2 = round(1000 * p_cmp), c3 = round(1000 * p_ref))
  colnames(X) <- rownames(trs)
  r <- asc_null(asc_pairwise(trs, X), n_perm = 49, seed = 3)
  out <- utils::capture.output(summary(r))
  expect_false(any(grepl("compensation", out)))
  expect_true(any(grepl("lower tail of B is shown for description only", out)))
})

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.