Nothing
#' Null Models for Multi-Layer Functional Shifts
#'
#' @description
#' Tests each ASC-CFD layer (position, dispersion, volume) against two
#' complementary null models, and dispatches on the class of \code{x}:
#' \itemize{
#' \item objects from \code{\link{asc_paired}} (class \code{ascent_paired})
#' get one set of tests per contrast (reference vs comparison);
#' \item objects from \code{\link{asc_pairwise}} (class
#' \code{ascent_pairwise}) get a single
#' \strong{global test} over all communities at once (no p-value per pair).
#' }
#' The letters differ from version 0.1.x: A is now the sampling null model and
#' B the stratified trait null model. The 0.1.x models (Curveball, SAD
#' reshuffle and trait shuffle), written A0, B0 and C0 since 0.5.0, were removed.
#'
#' @section Null model A (sampling):
#' H0: the communities are samples of the same community. Individuals are
#' pooled and reassigned at random keeping sample sizes. When both states of
#' a contrast have replicates, whole replicates are permuted instead (A by
#' samples), which accounts for variation among replicates (individuals that
#' are captured in groups inflate A by individuals). If the samples of both
#' states were taken in matched units (\code{blocks} in \code{\link{asc_paired}}),
#' samples are exchanged only within each block. A needs \strong{counts of
#' individuals}; with relative abundances it is skipped with a warning.
#'
#' @section Choosing the permutation for A:
#' The permutation is chosen from the design described in
#' \code{\link{asc_paired}}; \code{summary()} reports which one was used.
#' \itemize{
#' \item \strong{One sample per state}: A by individuals. It tests
#' multinomial sampling error only; ordinary variation between samples
#' (e.g. between two months of the same community) can look like a change.
#' Use replicates whenever possible.
#' \item \strong{Replicates taken in matched units} (both states sampled in
#' the same months, plots or survey rounds): give that unit as
#' \code{blocks} in \code{asc_paired()}. Samples are exchanged between
#' states only within each block, so effects shared by the samples of a
#' block (weather of a month, a survey round) are removed from the test.
#' Blocks do not correct temporal autocorrelation within the series of
#' each state: in the validation, with month-to-month persistence like
#' that of the butterfly data (rho = 0.28), A within blocks still gave
#' 6-16\% false positives. Matching removes shared effects, not
#' pseudoreplication.
#' \item \strong{Independent replicates} (spaced in time or space, not
#' matched): free permutation of whole samples (no \code{blocks}).
#' \item \strong{Consecutive replicates} (e.g. consecutive months of each
#' state, matched or not): they are not independent (pseudoreplicates). No
#' permutation removes this dependence; A, like PERMANOVA and other tests
#' that permute samples, becomes liberal (9.7-17\% false positives in the
#' validation). Space the samples in time or treat the p-values as
#' indicative.
#' }
#' When the number of possible allocations of samples is at most
#' \code{n_perm}, all of them are enumerated (exact test). With
#' \code{blocks}, there are \eqn{\prod_j \binom{n_j}{r_j}} allocations
#' (\eqn{n_j} samples in block \eqn{j}, \eqn{r_j} of them in the reference
#' state); with one sample of each state per block, \eqn{2^{B}} for
#' \eqn{B} blocks. Ask for \code{n_perm} at least that large to enumerate them.
#' Few blocks give few allocations: with four matched pairs there are 16, and
#' the smallest attainable p-value for position is 0.125, so the test cannot
#' reject at alpha = 0.05 (a warning is given).
#'
#' @section Null model B (traits, stratified):
#' H0: the shift does not depend on which traits the species have. Abundances
#' are kept and species coordinates are permuted only among species of similar
#' abundance (groups of \code{stratum_size} species ranked by mean abundance).
#' Stratification calibrates the test in empirical trait spaces; it does not
#' add power. \code{stratum_size = Inf} gives the unstratified permutation
#' among the species present, which was biased in empirical trait spaces and
#' is not recommended; values near 5 (e.g. 3 to 10) can be used to check that
#' conclusions do not depend on the stratum size.
#'
#' B is read from its upper tail: the shift is larger than expected if traits
#' were unrelated to the change in abundances, i.e. the change is directed by
#' traits. Read B where A detects a change. The lower tail (a shift smaller
#' than expected from the traits) is reported for description only: it had
#' little power to detect compensation in the validation.
#'
#' For position, the statistic of B is axis-standardised: the shift of the
#' centroid along each axis is divided by its standard deviation under the
#' null and the squares are summed over axes (\eqn{\sum_k (v_k / s_k)^2},
#' about the number of axes when there is no change). Each axis counts in
#' units of its own chance variation, so a change along a minor axis (a trait
#' unrelated to the first axis) is detected as well as one along the first
#' axis. With the length of the shift, \eqn{||\Delta C||} (the statistic up
#' to 0.5.0), the first axis dominated and changes in minor traits were rarely
#' detected; the price of the new statistic is somewhat less power when the
#' change lies along the first axis. B with \eqn{||\Delta C||}, from the same
#' permutations, is kept in \code{b_position_norm}; with the same seed the
#' permutations are those of 0.5.0.
#'
#' In the validation, B was slightly liberal for dispersion (6.5\% false
#' positives at alpha = 0.05), when individuals are captured in groups
#' (7.2\%) and, for position, when only the evenness of the community
#' changes (about 7-8\%, with either statistic); interpret p-values close to
#' 0.05 with caution.
#'
#' @section Which trait changed:
#' The same permutations of B give, for each trait, the change of its
#' abundance-weighted mean, returned in \code{trait_shifts}; \code{summary()}
#' names the trait with the largest standardised shift. Numeric traits are
#' used as they are (\code{Delta} in the units of the trait). Each level of a
#' categorical trait (factor, character or logical) is used as a 0/1
#' indicator, named "trait = level" (only the second level when there are two),
#' so its \code{Delta} is the change in the share of abundance of species with
#' that level. \code{Std_shift} is the shift in null standard deviations:
#' values of about 1 or less are within chance variation. This describes which
#' trait moved most; it is not a test (no p-value is given: in the validation,
#' with numeric traits, its maximum was liberal under changes not related to
#' traits, and it has not been evaluated with categorical traits). Traits that
#' are correlated move together, so it points to a group of related traits,
#' not necessarily to the trait that caused the change. Missing values are set
#' to the mean of the trait.
#'
#' @section Entities:
#' With \code{entities} (from \code{\link{asc_entities}} or a named vector
#' assigning each species to an entity), A is repeated on counts summed by
#' entity. This is exploratory. "A significant for species but not for
#' entities", together with a large fraction of the shift occurring within
#' entities (\code{\link{asc_transitions}}), is consistent with replacement
#' among functionally similar species. Only replacement within an entity is
#' seen: similar species placed in different entities look like a change
#' between entities, so a negative result does not rule out redundancy. In
#' the validation the signal was weak except for strong compensation, and it
#' depends on the number of entities; check neighbouring values of \code{k}.
#'
#' @section Global test (pairwise objects):
#' With many communities, one test per pair would multiply false alarms, so
#' \code{asc_null()} runs one global test per layer over all communities.
#' Statistics: the mean distance of the community centroids to their common
#' centroid (position), and the standard deviation among communities of FDis
#' (dispersion) and FRic (volume). A global reassigns individuals among
#' communities; B global applies one stratified trait permutation to all
#' communities. All layers are read from the upper tail. A: the communities
#' differ more than samples of one community would. B: the variation among
#' communities is organised by traits. The lower tail of B is reported for
#' description only. For position, B global uses the axis-standardised
#' statistic: the variance of the community centroids along each axis divided
#' by its mean under the null, summed over axes (with two communities it is
#' equivalent to the paired statistic); B with the mean distance (as in 0.5.0)
#' is kept in \code{b_position_norm}. The distance of each community to the
#' common centroid is returned as a descriptive contribution
#' (\code{site_contribution}).
#'
#' @section Multiple testing:
#' Each test (A, B, A by entities, and each global test) evaluates three
#' layers, so \code{P_adj} adjusts, within each contrast and test, the three
#' p-values used for interpretation: the upper tail for position (and for all
#' layers of the global test) and the two-tailed value for dispersion and
#' volume. The method is chosen with \code{p_adjust} (any method of
#' \code{\link[stats]{p.adjust}}; default Benjamini-Hochberg). Contrasts are
#' not adjusted against each other; to do so, apply
#' \code{\link[stats]{p.adjust}} to the column of p-values of interest in
#' \code{null_models}. The lower tail is not adjusted.
#'
#' @section Two-tailed p-values:
#' Dispersion and volume can change in either direction, so they are read with
#' a two-tailed p-value, \code{P_two}. Two conventions are available
#' (argument \code{two_sided}):
#' \itemize{
#' \item \code{"centred"} (default, as in 0.5.0): the proportion of null
#' values at least as far from the null mean as the observed value.
#' \item \code{"doubled"}: twice the smaller tail,
#' \code{pmin(1, 2 * pmin(P_upper, P_lower))}, which judges each
#' direction against its own tail.
#' }
#' Both are valid; they coincide when the null distribution is symmetric and
#' can differ when it is asymmetric, as is common for the volume (FRic). Both
#' tails are always reported, so either convention can be computed from the
#' table. Choose the convention before looking at the results.
#'
#' @param x An object of class \code{ascent_paired} (from \code{asc_paired})
#' or \code{ascent_pairwise} (from \code{asc_pairwise}). Objects created
#' with ascent 0.5.0 (classes \code{ascfcd} and \code{ascfcd_pw}) are
#' accepted.
#' @param n_perm Integer. Number of permutations. Default is 999. When the
#' number of possible allocations of samples is at most \code{n_perm}, all
#' of them are used instead (exact test).
#' @param seed Integer or \code{NULL}. If given, results are reproducible and
#' the user's random number stream is left unchanged.
#' @param stratum_size Integer. Number of species per abundance stratum in
#' null model B. Default 5 (the validated value). Strata group species of
#' similar abundance; larger values approach the unstratified permutation.
#' @param entities Optional. An object from \code{\link{asc_entities}} or a
#' named vector (names = species) giving each species' entity.
#' @param two_sided Character. Convention for the two-tailed p-value of
#' dispersion and volume (see Two-tailed p-values): \code{"centred"}
#' (default) or \code{"doubled"}.
#' @param p_adjust Character. Method used to adjust the p-values of the three
#' layers within each contrast and test (see Multiple testing). One of
#' \code{stats::p.adjust.methods}; default \code{"BH"} (Benjamini and
#' Hochberg, 1995). \code{"none"} keeps them unadjusted.
#'
#' @return The input object with \code{null_models} appended: a data frame
#' with one row per contrast, test and layer, and columns \code{Contrast},
#' \code{Test}, \code{Layer}, \code{Observed}, \code{Null_mean},
#' \code{Null_sd}, \code{SES}, \code{P_upper}, \code{P_lower} and
#' \code{P_two} (two-tailed, with the convention set by \code{two_sided}),
#' and \code{P_adj}
#' (the p-value used for interpretation, adjusted with \code{p_adjust}).
#' P-values are \eqn{(b + 1)/(n + 1)} and are not rounded. For B, the row
#' of position refers to the axis-standardised statistic (\code{Observed},
#' \code{Null_mean}, \code{Null_sd}, \code{SES} and the p-values).
#' \code{b_position_norm} gives B for position with the statistic of 0.5.0
#' (\eqn{||\Delta C||}, or the mean distance to the common centroid in the
#' global test), one row per contrast. \code{trait_shifts} (see Which trait
#' changed) gives, per contrast, \code{Trait}, \code{Type} (\code{"numeric"}
#' or \code{"level"}), \code{Delta} and \code{Std_shift}, ordered by
#' \code{|Std_shift|}; in the
#' global test \code{Delta} is the standard deviation among communities of
#' the weighted mean of the trait and \code{Std_shift} its variance relative
#' to the null mean. For pairwise
#' objects, \code{site_contribution} is also appended. \code{null_settings}
#' records the options used and, in \code{permutation}, how samples were
#' permuted for A in each contrast (design, number of blocks, number of
#' possible allocations, exact enumeration or not, and the smallest
#' attainable p-value for position). Use \code{summary()} for a reading of
#' each test.
#'
#' @references
#' Benjamini, Y., & Hochberg, Y. (1995). Controlling the false discovery rate:
#' a practical and powerful approach to multiple testing. Journal of the Royal
#' Statistical Society B, 57, 289-300.
#'
#' Gower, J. C. (1971). A general coefficient of similarity and some of its
#' properties. Biometrics, 27, 857-871.
#'
#' @examples
#' \donttest{
#' # Paired contrasts (see ?birds_sim): five surveys per state at each site
#' res <- asc_paired(birds_sim$traits, birds_sim$counts,
#' sites = birds_sim$samples$site,
#' time = birds_sim$samples$time, ref_time = "Before")
#' res <- asc_null(res, n_perm = 199, seed = 1)
#'
#' # The Reading column interprets each test. At "Logged", A (sampling) and
#' # B (traits) detect the shift in position: the change is real and directed
#' # by the species' traits. At "Control" there is no evidence of change.
#' summary(res)
#'
#' # The full table (one row per contrast, test and layer)
#' res$null_models[res$null_models$Layer == "Position", ]
#'
#' # Which trait moved most at each site (descriptive)
#' res$trait_shifts
#'
#' # Matched samples: if the k-th survey of both states had been made in the
#' # same survey round, the rounds would be given as blocks. With only five
#' # matched pairs the smallest attainable p-value for position is 2/32, so
#' # asc_null() warns that A cannot reject at 0.05 (six pairs are the minimum)
#' round <- ave(seq_along(birds_sim$samples$site),
#' birds_sim$samples$site, birds_sim$samples$time, FUN = seq_along)
#' rb <- asc_paired(birds_sim$traits, birds_sim$counts,
#' sites = birds_sim$samples$site,
#' time = birds_sim$samples$time, ref_time = "Before",
#' blocks = round)
#' rb <- asc_null(rb, n_perm = 99, seed = 1)
#' rb$null_settings$permutation
#'
#' # Many communities: one global test per layer instead of one p per pair
#' pw <- asc_pairwise(birds_sim$traits, birds_sim$landscape)
#' pw <- asc_null(pw, n_perm = 99, seed = 1)
#' summary(pw)
#' }
#'
#' @export
asc_null <- function(x, n_perm = 999, seed = NULL, stratum_size = 5, entities = NULL,
two_sided = c("centred", "doubled"), p_adjust = "BH") {
two_sided <- match.arg(two_sided)
if (!.is_paired(x) && !.is_pairwise(x)) {
stop("Input object must come from asc_paired() or asc_pairwise().")
}
if (!is.character(p_adjust) || length(p_adjust) != 1L || !p_adjust %in% stats::p.adjust.methods) {
stop("'p_adjust' must be one of: ", paste(stats::p.adjust.methods, collapse = ", "), ".")
}
n_perm <- as.integer(n_perm)
if (length(n_perm) != 1L || is.na(n_perm) || n_perm < 9L) stop("'n_perm' must be an integer >= 9.")
if (!is.numeric(stratum_size) || length(stratum_size) != 1L || stratum_size < 2) {
stop("'stratum_size' must be a number >= 2 (or Inf).")
}
if (!is.null(seed)) {
return(withr::with_seed(seed, .asc_null_run(x, n_perm, stratum_size, entities, seed,
p_adjust, two_sided)))
}
.asc_null_run(x, n_perm, stratum_size, entities, seed, p_adjust, two_sided)
}
# ------------------------------------------------------------------------------
# Dispatcher (internal)
# ------------------------------------------------------------------------------
.asc_null_run <- function(x, n_perm, stratum_size, entities, seed, p_adjust,
two_sided = "centred") {
F_mat <- x$F_space
counts <- x$counts
ent <- .entity_vector(entities, rownames(F_mat))
if (is.null(counts)) {
warning("The object has no counts of individuals (abundances are not whole numbers): ",
"null model A is skipped and only B is evaluated.")
}
perm_info <- NULL
Z <- .trait_matrix(x$original_traits, rownames(F_mat))
if (.is_pairwise(x)) {
if (!is.null(ent)) message("Entities are not used in the global test; they are ignored.")
X_use <- if (!is.null(counts)) counts else x$original_abund
tests <- list()
if (!is.null(counts)) tests$A <- .null_A_global(counts, F_mat, n_perm)
tests$B <- .null_B_global(X_use, F_mat, n_perm, stratum_size, Z)
b_norm <- attr(tests$B, "position_norm"); b_traits <- attr(tests$B, "trait_shift")
out <- do.call(rbind, tests)
out <- cbind(Contrast = "Global", out, stringsAsFactors = FALSE)
rownames(out) <- NULL
x$null_models <- .add_p_adjust(.set_two_sided(out, two_sided), p_adjust, global = TRUE)
x$site_contribution <- .site_contribution(X_use, F_mat)
x$b_position_norm <- cbind(Contrast = "Global", b_norm, stringsAsFactors = FALSE)
x$trait_shifts <- if (!is.null(b_traits)) cbind(Contrast = "Global", b_traits, stringsAsFactors = FALSE)
} else {
blocks <- x$blocks # NULL without blocks (and for objects from ascent 0.5.0)
res <- lapply(unique(x$sites), function(s) {
i_r <- which(x$sites == s & x$time == x$ref_time)
i_c <- which(x$sites == s & x$time != x$ref_time)
if (!length(i_r) || !length(i_c) || is.null(x$p_ref[[s]])) return(NULL)
replicates <- length(i_r) > 1 && length(i_c) > 1
b <- if (!is.null(blocks) && replicates) blocks[c(i_r, i_c)] else NULL
if (!is.null(blocks) && !replicates && !is.null(counts)) {
message(sprintf("Contrast '%s': one sample per state, so 'blocks' is not used (A by individuals).", s))
}
if (!is.null(b) && !is.null(counts)) .check_blocks(b, length(i_r), n_perm, s)
parts <- list()
if (!is.null(counts)) {
R_mat <- counts[i_r, , drop = FALSE]; C_mat <- counts[i_c, , drop = FALSE]
parts$A <- if (replicates) .null_A_samples(R_mat, C_mat, F_mat, n_perm, blocks = b)
else .null_A_individuals(colSums(R_mat), colSums(C_mat), F_mat, n_perm)
}
p_r <- as.numeric(x$p_ref[[s]]); p_c <- as.numeric(x$p_comp[[s]])
parts$B <- .null_B(p_r, p_c, F_mat, n_perm, stratum_size, Z = Z)
b_norm <- cbind(Contrast = s, attr(parts$B, "position_norm"), stringsAsFactors = FALSE)
b_traits <- attr(parts$B, "trait_shift")
if (!is.null(b_traits)) b_traits <- cbind(Contrast = s, b_traits, stringsAsFactors = FALSE)
if (!is.null(ent) && !is.null(counts)) {
parts$E <- if (replicates) .null_A_samples_entities(R_mat, C_mat, F_mat, ent, n_perm, blocks = b)
else .null_A_entities(colSums(R_mat), colSums(C_mat), F_mat, ent, n_perm)
}
perm <- do.call(rbind, lapply(parts, attr, "permutation"))
if (!is.null(perm)) perm <- cbind(Contrast = s, perm, stringsAsFactors = FALSE)
list(tab = cbind(Contrast = s, do.call(rbind, parts), stringsAsFactors = FALSE), perm = perm,
b_norm = b_norm, b_traits = b_traits)
})
res <- res[!vapply(res, is.null, logical(1))]
out <- do.call(rbind, lapply(res, `[[`, "tab"))
rownames(out) <- NULL
x$null_models <- .add_p_adjust(.set_two_sided(out, two_sided), p_adjust, global = FALSE)
x$b_position_norm <- do.call(rbind, lapply(res, `[[`, "b_norm"))
rownames(x$b_position_norm) <- NULL
tr <- do.call(rbind, lapply(res, `[[`, "b_traits"))
if (!is.null(tr)) rownames(tr) <- NULL
x$trait_shifts <- tr
perm_info <- do.call(rbind, lapply(res, `[[`, "perm"))
if (!is.null(perm_info)) rownames(perm_info) <- NULL
}
x$null_settings <- list(n_perm = n_perm, stratum_size = stratum_size, seed = seed,
n_entities = if (is.null(ent)) NULL else length(unique(ent)),
two_sided = two_sided, p_adjust = p_adjust, blocks = !is.null(x$blocks),
b_position = "axis_standardised",
permutation = perm_info)
x
}
# Two-tailed convention (internal): "centred" keeps the value computed by
# .eval_null(); "doubled" replaces it by twice the smaller tail
.set_two_sided <- function(tab, two_sided) {
if (two_sided == "doubled") tab$P_two <- pmin(1, 2 * pmin(tab$P_upper, tab$P_lower))
tab
}
# ------------------------------------------------------------------------------
# Multiple testing (internal): adjusts, within each contrast and test, the
# p-values used for interpretation (upper tail for position and for the global
# test; two-tailed for dispersion and volume)
# ------------------------------------------------------------------------------
.p_used <- function(tab, global = FALSE) {
if (global) tab$P_upper else ifelse(tab$Layer == "Position", tab$P_upper, tab$P_two)
}
.add_p_adjust <- function(tab, method, global = FALSE) {
p <- .p_used(tab, global)
grp <- paste(tab$Contrast, tab$Test, sep = "\r")
tab$P_adj <- NA_real_
for (g in unique(grp)) {
i <- which(grp == g)
tab$P_adj[i] <- stats::p.adjust(p[i], method = method)
}
tab
}
# ------------------------------------------------------------------------------
# Layers and evaluation (internal)
# ------------------------------------------------------------------------------
.layers <- function(p_r, p_c, F_mat) {
p_r <- p_r / sum(p_r); p_c <- p_c / sum(p_c)
v <- as.numeric((p_c - p_r) %*% F_mat)
tr <- .calc_core_topology(p_r, F_mat)
tc <- .calc_core_topology(p_c, F_mat)
c(pos = sqrt(sum(v^2)), fdis = tc$FDis - tr$FDis, fric = tc$FRic - tr$FRic)
}
.eval_null <- function(obs, null_dist) {
null_dist <- null_dist[is.finite(null_dist)]
n <- length(null_dist)
empty <- c(Observed = obs, Null_mean = NA, Null_sd = NA, SES = NA,
P_upper = NA, P_lower = NA, P_two = NA)
if (!is.finite(obs) || n < 2) return(empty)
m <- mean(null_dist); s <- stats::sd(null_dist)
if (s < 1e-12) { empty[c("Null_mean", "Null_sd", "SES")] <- c(m, s, NaN); return(empty) }
c(Observed = obs, Null_mean = m, Null_sd = s, SES = (obs - m) / s,
P_upper = (sum(null_dist >= obs) + 1) / (n + 1),
P_lower = (sum(null_dist <= obs) + 1) / (n + 1),
P_two = (sum(abs(null_dist - m) >= abs(obs - m)) + 1) / (n + 1))
}
.LAYER_NAMES <- c(pos = "Position", fdis = "Dispersion", fric = "Volume")
.layer_table <- function(obs, null_mat, test) {
do.call(rbind, lapply(c("pos", "fdis", "fric"), function(k) {
e <- .eval_null(obs[[k]], null_mat[, k])
data.frame(Test = test, Layer = .LAYER_NAMES[[k]], t(e), row.names = NULL,
stringsAsFactors = FALSE)
}))
}
# ------------------------------------------------------------------------------
# Null model A (internal)
# ------------------------------------------------------------------------------
.null_A_individuals <- function(x_r, x_c, F_mat, n_perm, test = "A_individuals") {
.null_A_individuals_info(.null_A_individuals_core(x_r, x_c, F_mat, n_perm, test), n_perm)
}
.null_A_individuals_core <- function(x_r, x_c, F_mat, n_perm, test) {
S <- length(x_r); tot <- x_r + x_c
lab <- rep.int(seq_len(S), tot); N <- length(lab); n_r <- sum(x_r)
nul <- matrix(NA_real_, n_perm, 3, dimnames = list(NULL, c("pos", "fdis", "fric")))
for (i in seq_len(n_perm)) {
xr <- tabulate(lab[sample.int(N, n_r)], S)
nul[i, ] <- .layers(xr, tot - xr, F_mat)
}
.layer_table(.layers(x_r, x_c, F_mat), nul, test)
}
.null_A_individuals_info <- function(tab, n_perm) {
attr(tab, "permutation") <- .perm_row(tab$Test[1], "individuals", NA_integer_, NA_real_,
FALSE, n_perm, FALSE)
tab
}
# Free permutation of whole samples (blocks = NULL; unchanged from 0.5.0, so
# results with a given seed are the same) or permutation within blocks
.null_A_samples <- function(R_mat, C_mat, F_mat, n_perm, test = "A_samples", blocks = NULL) {
rel <- function(M) M / rowSums(M)
A <- rbind(rel(R_mat), rel(C_mat)); k_r <- nrow(R_mat); K <- nrow(A)
avg <- function(idx) colMeans(A[idx, , drop = FALSE])
obs <- .layers(avg(seq_len(k_r)), avg((k_r + 1):K), F_mat)
if (is.null(blocks)) {
n_comb <- choose(K, k_r)
exact <- n_comb <= n_perm
if (exact) {
combs <- utils::combn(K, k_r, simplify = FALSE)
combs <- combs[!vapply(combs, function(cc) identical(cc, seq_len(k_r)), logical(1))]
} else {
combs <- replicate(n_perm, sort(sample.int(K, k_r)), simplify = FALSE)
}
perm <- .perm_row(test, "free", NA_integer_, n_comb, exact, n_perm, 2 * k_r == K)
} else {
bp <- .block_plan(blocks, k_r)
exact <- bp$n_alloc <= n_perm
combs <- if (exact) .block_enumerate(bp, k_r)
else replicate(n_perm, .block_sample(bp), simplify = FALSE)
perm <- .perm_row(test, "blocks", sum(bp$informative), bp$n_alloc, exact, n_perm, bp$mirror)
}
nul <- t(vapply(combs, function(cc) .layers(avg(cc), avg(setdiff(seq_len(K), cc)), F_mat),
numeric(3)))
colnames(nul) <- c("pos", "fdis", "fric")
tab <- .layer_table(obs, nul, test)
attr(tab, "permutation") <- perm
tab
}
# ------------------------------------------------------------------------------
# Permutation within blocks (internal). Rows 1..k_r are the reference state.
# In each block, the number of reference samples is kept and the samples that
# play the reference role are chosen at random (or all choices are enumerated).
# ------------------------------------------------------------------------------
.block_plan <- function(blocks, k_r) {
K <- length(blocks)
is_ref <- seq_len(K) <= k_r
b <- as.character(blocks)
groups <- split(seq_len(K), factor(b, levels = unique(b)))
n_ref <- vapply(groups, function(g) sum(is_ref[g]), numeric(1))
n_tot <- lengths(groups)
list(groups = groups, n_ref = n_ref, n_tot = n_tot,
informative = n_ref > 0 & n_ref < n_tot,
n_alloc = prod(choose(n_tot, n_ref)),
# swapping the states in every block gives the same allocation mirrored,
# with the same position statistic (only if every block is balanced)
mirror = all(2 * n_ref == n_tot))
}
.block_choices <- function(g, r) {
if (r == 0) return(list(integer(0)))
if (r == length(g)) return(list(g))
utils::combn(g, r, simplify = FALSE) # length(g) >= 2 here
}
.block_enumerate <- function(bp, k_r) {
opts <- Map(.block_choices, bp$groups, bp$n_ref)
grid <- as.matrix(expand.grid(lapply(opts, seq_along), KEEP.OUT.ATTRS = FALSE))
combs <- lapply(seq_len(nrow(grid)), function(i) {
sort(unlist(Map(function(o, j) o[[j]], opts, grid[i, ]), use.names = FALSE))
})
combs[!vapply(combs, function(cc) identical(as.integer(cc), seq_len(k_r)), logical(1))]
}
.block_sample <- function(bp) {
sort(unlist(Map(function(g, r) {
if (r == 0) integer(0) else if (r == length(g)) g else g[sample.int(length(g), r)]
}, bp$groups, bp$n_ref), use.names = FALSE))
}
# One row describing the permutation used for A (internal)
.perm_row <- function(test, design, n_blocks, n_alloc, exact, n_perm, mirror) {
min_p <- if (design == "individuals") 1 / (n_perm + 1)
else if (exact) (1 + mirror) / n_alloc
else max(1 / (n_perm + 1), (1 + mirror) / n_alloc)
data.frame(Test = test, Design = design, Blocks = n_blocks, Allocations = n_alloc,
Exact = exact, Min_P_position = min_p, stringsAsFactors = FALSE)
}
# Checks of the blocks of one contrast (internal)
.check_blocks <- function(b, k_r, n_perm, contrast) {
bp <- .block_plan(b, k_r)
if (bp$n_alloc <= 1) {
stop(sprintf("Contrast '%s': no block contains samples of both states, so there is nothing to permute. Check 'blocks'.",
contrast), call. = FALSE)
}
if (any(!bp$informative)) {
message(sprintf("Contrast '%s': %d block(s) contain samples of only one state and are kept fixed: %s.",
contrast, sum(!bp$informative),
paste(utils::head(names(bp$groups)[!bp$informative], 10), collapse = ", ")))
}
pr <- .perm_row("A", "blocks", sum(bp$informative), bp$n_alloc, bp$n_alloc <= n_perm, n_perm, bp$mirror)
if (pr$Min_P_position > 0.05) {
warning(sprintf(paste0("Contrast '%s': the blocks allow only %g allocations of samples; the smallest ",
"attainable p-value for position is %.3f, so A cannot reject at alpha = 0.05."),
contrast, bp$n_alloc, pr$Min_P_position), call. = FALSE)
}
invisible(bp)
}
# ------------------------------------------------------------------------------
# Null model B, stratified (internal)
# ------------------------------------------------------------------------------
.abundance_strata <- function(p_mean, idx, stratum_size) {
ord <- idx[order(p_mean[idx], decreasing = TRUE)]
g <- ceiling(seq_along(ord) / stratum_size)
# a last stratum with a single species is merged with the previous one
if (length(g) > 1 && sum(g == max(g)) == 1) g[g == max(g)] <- max(g) - 1
split(ord, g)
}
.null_B <- function(p_r, p_c, F_mat, n_perm, stratum_size, test = "B_stratified", Z = NULL) {
idx <- which(p_r > 0 | p_c > 0)
strata <- .abundance_strata((p_r / sum(p_r) + p_c / sum(p_c)) / 2, idx, stratum_size)
dp <- p_c / sum(p_c) - p_r / sum(p_r)
nul <- matrix(NA_real_, n_perm, 3, dimnames = list(NULL, c("pos", "fdis", "fric")))
V <- matrix(NA_real_, n_perm, ncol(F_mat))
TT <- if (!is.null(Z)) matrix(NA_real_, n_perm, ncol(Z))
for (i in seq_len(n_perm)) {
# the same random draws as in 0.5.0 (one sample.int() per stratum)
perm <- seq_len(nrow(F_mat))
for (gr in strata) if (length(gr) > 1) perm[gr] <- gr[sample.int(length(gr))]
Fp <- F_mat[perm, , drop = FALSE]
nul[i, ] <- .layers(p_r, p_c, Fp)
V[i, ] <- as.numeric(dp %*% Fp)
if (!is.null(Z)) TT[i, ] <- as.numeric(dp %*% Z[perm, , drop = FALSE])
}
obs <- .layers(p_r, p_c, F_mat)
tab <- .layer_table(obs, nul, test)
# position: axis-standardised statistic, sum_k (v_k / s_k)^2 (s_k = null sd of
# the shift along axis k); the norm ||Delta C|| is kept as "position_norm"
s_v <- apply(V, 2, stats::sd); s_v[!is.finite(s_v) | s_v < 1e-12] <- Inf
v0 <- as.numeric(dp %*% F_mat)
std <- .eval_null(sum((v0 / s_v)^2), rowSums(sweep(V, 2, s_v, "/")^2))
pos_norm <- tab[1, setdiff(names(tab), c("Test", "Layer")), drop = FALSE]
rownames(pos_norm) <- NULL
tab[1, names(std)] <- std
attr(tab, "position_norm") <- pos_norm
if (!is.null(Z)) {
t0 <- as.numeric(dp %*% Z)
s_t <- apply(TT, 2, stats::sd); s_t[!is.finite(s_t) | s_t < 1e-12] <- Inf
attr(tab, "trait_shift") <- .trait_table(t0, t0 / s_t, Z)
}
tab
}
# Traits as columns standardised across species (mean 0, sd 1; missing values
# set to the mean), in the order of the functional space (internal). Numeric
# traits give one column each; categorical traits (factor, character, logical)
# give one 0/1 column per level, named "trait = level" (only the second level
# for traits with two levels, since both carry the same information). Columns
# that do not vary are dropped. NULL if no column is left.
.trait_matrix <- function(traits, species) {
if (is.null(traits)) return(NULL)
tr <- as.data.frame(traits, stringsAsFactors = FALSE)
if (!is.null(rownames(tr)) && all(species %in% rownames(tr))) tr <- tr[species, , drop = FALSE]
cols <- list(); type <- character(0)
for (nm in names(tr)) {
v <- tr[[nm]]
if (is.numeric(v) && !is.factor(v)) {
cols[[nm]] <- as.numeric(v); type[nm] <- "numeric"
} else if (is.factor(v) || is.character(v) || is.logical(v)) {
f <- if (is.factor(v)) droplevels(v) else factor(v)
lev <- levels(f)
if (length(lev) < 2) next
if (length(lev) == 2) lev <- lev[2]
for (l in lev) {
key <- paste0(nm, " = ", l)
cols[[key]] <- ifelse(is.na(f), NA_real_, as.numeric(f == l)); type[key] <- "level"
}
}
}
if (!length(cols)) return(NULL)
M <- do.call(cbind, cols); colnames(M) <- names(cols)
sds <- apply(M, 2, stats::sd, na.rm = TRUE)
keep <- is.finite(sds) & sds > 0
if (!any(keep)) return(NULL)
M <- M[, keep, drop = FALSE]
Z <- scale(M); Z[is.na(Z)] <- 0
attr(Z, "trait_sd") <- sds[keep]
attr(Z, "trait_type") <- unname(type[colnames(M)])
Z
}
# Shift of the abundance-weighted mean of each trait (internal). Delta is in
# the units of the trait (for a level of a categorical trait, the change in
# the share of abundance of species with that level); Std_shift is the shift
# in null standard deviations
.trait_table <- function(delta_z, std_shift, Z) {
out <- data.frame(Trait = colnames(Z), Type = attr(Z, "trait_type"),
Delta = delta_z * attr(Z, "trait_sd"),
Std_shift = std_shift, row.names = NULL, stringsAsFactors = FALSE)
out[order(-abs(out$Std_shift)), , drop = FALSE]
}
# ------------------------------------------------------------------------------
# Entities (internal)
# ------------------------------------------------------------------------------
.entity_vector <- function(entities, species) {
if (is.null(entities)) return(NULL)
if (inherits(entities, c("ascent_entities", "ascfcd_entities"))) entities <- entities$membership
if (is.null(names(entities)) || !all(species %in% names(entities))) {
stop("'entities' must assign an entity to every species (a named vector or an asc_entities() object).")
}
entities[species]
}
.aggregate_entities <- function(x, F_mat, group) {
x_e <- tapply(x, group, sum)
G <- rowsum(F_mat, group) / as.vector(table(group))
list(x = as.numeric(x_e[rownames(G)]), G = G)
}
.null_A_entities <- function(x_r, x_c, F_mat, group, n_perm) {
ar <- .aggregate_entities(x_r, F_mat, group); ac <- .aggregate_entities(x_c, F_mat, group)
.null_A_individuals(ar$x, ac$x, ar$G, n_perm, test = "A_entities")
}
.null_A_samples_entities <- function(R_mat, C_mat, F_mat, group, n_perm, blocks = NULL) {
agg <- function(M) t(rowsum(t(M), group))
G <- rowsum(F_mat, group) / as.vector(table(group))
Ra <- agg(R_mat)[, rownames(G), drop = FALSE]; Ca <- agg(C_mat)[, rownames(G), drop = FALSE]
.null_A_samples(Ra, Ca, G, n_perm, test = "A_entities_samples", blocks = blocks)
}
# ------------------------------------------------------------------------------
# Global test for pairwise objects (internal)
# ------------------------------------------------------------------------------
.layers_global <- function(X, F_mat) {
P <- X / rowSums(X)
C <- P %*% F_mat
Cbar <- colMeans(C)
topo <- lapply(seq_len(nrow(P)), function(k) .calc_core_topology(P[k, ], F_mat))
fdis <- vapply(topo, `[[`, numeric(1), "FDis"); fric <- vapply(topo, `[[`, numeric(1), "FRic")
c(pos = mean(sqrt(rowSums(sweep(C, 2, Cbar)^2))),
fdis = stats::sd(fdis),
fric = if (sum(is.finite(fric)) >= 2) stats::sd(fric, na.rm = TRUE) else NA_real_)
}
.site_contribution <- function(X, F_mat) {
P <- X / rowSums(X); C <- P %*% F_mat; Cbar <- colMeans(C)
d <- sqrt(rowSums(sweep(C, 2, Cbar)^2))
data.frame(Community = rownames(X), Distance_to_common_centroid = d,
Fraction = d / sum(d), row.names = NULL, stringsAsFactors = FALSE)
}
.null_A_global <- function(X, F_mat, n_perm) {
S <- ncol(X); n_k <- rowSums(X); K <- nrow(X)
lab <- rep.int(seq_len(S), colSums(X)); site <- rep.int(seq_len(K), n_k)
nul <- matrix(NA_real_, n_perm, 3, dimnames = list(NULL, c("pos", "fdis", "fric")))
for (i in seq_len(n_perm)) {
Xp <- matrix(tabulate((site - 1L) * S + sample(lab), K * S), K, S, byrow = TRUE)
nul[i, ] <- .layers_global(Xp, F_mat)
}
.layer_table(.layers_global(X, F_mat), nul, "A_global")
}
.null_B_global <- function(X, F_mat, n_perm, stratum_size, Z = NULL) {
present <- which(colSums(X) > 0)
P <- X / rowSums(X)
strata <- .abundance_strata(colMeans(P), present, stratum_size)
vk <- function(C) colMeans(sweep(C, 2, colMeans(C))^2)
nul <- matrix(NA_real_, n_perm, 3, dimnames = list(NULL, c("pos", "fdis", "fric")))
V <- matrix(NA_real_, n_perm, ncol(F_mat))
W <- if (!is.null(Z)) matrix(NA_real_, n_perm, ncol(Z))
for (i in seq_len(n_perm)) {
perm <- seq_len(nrow(F_mat))
for (gr in strata) if (length(gr) > 1) perm[gr] <- gr[sample.int(length(gr))]
Fp <- F_mat[perm, , drop = FALSE]
nul[i, ] <- .layers_global(X, Fp)
V[i, ] <- vk(P %*% Fp)
if (!is.null(Z)) W[i, ] <- vk(P %*% Z[perm, , drop = FALSE])
}
tab <- .layer_table(.layers_global(X, F_mat), nul, "B_global_stratified")
# position: sum over axes of V_k / E0[V_k], V_k = variance of the community
# centroids along axis k (equivalent to the paired statistic for two
# communities); the mean distance to the common centroid is kept as
# "position_norm"
eV <- colMeans(V); eV[!is.finite(eV) | eV < 1e-15] <- Inf
std <- .eval_null(sum(vk(P %*% F_mat) / eV), rowSums(sweep(V, 2, eV, "/")))
pos_norm <- tab[1, setdiff(names(tab), c("Test", "Layer")), drop = FALSE]
rownames(pos_norm) <- NULL
tab[1, names(std)] <- std
attr(tab, "position_norm") <- pos_norm
if (!is.null(Z)) {
eW <- colMeans(W); eW[!is.finite(eW) | eW < 1e-15] <- Inf
w0 <- vk(P %*% Z)
# Delta: standard deviation among communities of the weighted mean, in trait units
attr(tab, "trait_shift") <- .trait_table(sqrt(w0), w0 / eW, Z)
}
tab
}
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.