R/global_test.R

Defines functions print.global_test global_test

Documented in global_test print.global_test

# R/global_test.R
# The global permutation test on its own, and the print method of its result.

#' Permutation Test for Differences Between Populations of Brain Networks
#'
#' Tests for differences between two or more populations of brain networks,
#' using the L1-distance ANOVA statistic T of Fraiman and Fraiman (2018)
#' and a permutation null distribution. Valid inference requires exchangeable
#' group labels under the null; equal central graphs alone are not enough.
#' This is the global test
#' that \code{\link{identify_critical_links}} runs before it starts removing
#' edges; here it is available on its own, so that the population-level
#' question can be answered, and reported, before any edge is singled out.
#'
#' @param populations A named \code{list} with at least two elements. Each
#'   element is itself a list of square, binary, symmetric adjacency matrices
#'   (zero diagonal, no self-loops), with at least two graphs per population.
#'   All graphs must have at least one node and share the same number of nodes.
#' @param n_permutations Positive integer giving the number of permutation
#'   replicates used to approximate the null distribution of T. Default
#'   \code{1000}.
#' @param seed Optional integer seed for reproducibility of the permutation
#'   replicates. Default \code{NULL}.
#' @param criterion \code{"combined"} (default) evaluates T together with the
#'   local statistic U, the smallest marginal p-value of all edges, in one
#'   permutation test; \code{"original"} uses T alone. See
#'   \code{\link{identify_critical_links}}.
#' @param method Marginal edge test used for U when \code{criterion =
#'   "combined"}: \code{"fisher"} (default), \code{"chi.squared"} or
#'   \code{"prop"}, as in \code{\link{compute_edge_pvalues}}. The
#'   \code{"prop"} method requires exactly two populations. The method is
#'   validated for both criteria, including when the graphs have no edges.
#'
#' @return An object of class \code{"global_test"}: a \code{list} with the
#'   components
#'   \describe{
#'     \item{statistic}{the observed value of T, computed with normalisation
#'       constant \code{a = 1}.}
#'     \item{p_value}{the permutation \eqn{p} value of the chosen
#'       \code{criterion}, computed among the \eqn{B + 1} values that include
#'       the observed one; \code{NA} when the graphs have a single node and
#'       hence no edges.}
#'     \item{p_value_global, p_value_local}{the permutation \eqn{p} values of
#'       T and of U on their own (\code{p_value_local} is \code{NA} with
#'       \code{criterion = "original"}).}
#'     \item{local_statistic}{the observed value of U, the smallest marginal
#'       p-value (\code{NA} with \code{criterion = "original"}).}
#'     \item{criterion}{the criterion used.}
#'     \item{null_distribution}{numeric vector of length
#'       \code{n_permutations} holding the statistic of every replicate.}
#'     \item{n_permutations}{the number of replicates.}
#'     \item{group_sizes}{named integer vector with the number of graphs in
#'       each population.}
#'     \item{n_nodes}{the number of nodes.}
#'     \item{call}{the matched call.}
#'   }
#'   A \code{\link[=print.global_test]{print}} method is provided.
#'
#' @details The statistic T contrasts the mean distance of each graph to its
#'   own population's central graph with its mean distance to every
#'   population's central graph (see \code{\link{compute_test_statistic}}).
#'   The test uses the lower tail of T and does not use a normal approximation.
#'   Replicates are generated by
#'   permuting the group labels across the pooled sample while preserving the
#'   group sizes, T is recomputed for each, and
#'   \eqn{p = (1 + \#\{b : T_b \le T_{obs}\}) / (B + 1)}, which is never below
#'   \eqn{1 / (B + 1)}. Ties are counted by comparing the stored values
#'   directly. On sparse networks, floating-point roundoff can separate
#'   mathematically equal statistics and produce spuriously small p-values.
#'   See \code{\link{identify_critical_links}} for the combined criterion.
#'
#'   Group labels must be exchangeable under the null: shuffling whole graphs
#'   must preserve the joint distribution of the observations. Independent
#'   graphs drawn from the same graph distribution satisfy this condition.
#'   Matching edge means alone does not, because dependence between edges can
#'   differ. Unrestricted permutations do not support paired observations,
#'   repeated measures, blocks or adjustment for covariates.
#'
#'   The normalisation constant \code{a} of
#'   \code{\link{compute_test_statistic}} is fixed at 1. The \eqn{p} value
#'   does not depend on it: \code{a} rescales the observed statistic and every
#'   replicate by the same positive factor, which leaves their comparison
#'   unchanged.
#'
#'   Distances sum all matrix entries. For symmetric graphs with zero diagonal,
#'   this counts each undirected edge twice, so reported T is twice the value
#'   from an upper-triangle-only distance. This shared positive factor does
#'   not change the permutation p-value.
#'
#'   The computation uses the edge-wise decomposition of T described in
#'   \code{\link{identify_critical_links}}: the statistic of every replicate
#'   is obtained from permuted edge counts through matrix products,
#'   rather than by rebuilding graphs and recomputing distances. That
#'   decomposition holds for binary graphs, which is why the input must be
#'   binary. Calling \code{global_test()} and
#'   \code{\link{identify_critical_links}} with the same populations,
#'   \code{n_permutations} and \code{seed} evaluates the same permutations, so
#'   the \eqn{p} value returned here is the one that
#'   \code{identify_critical_links()} records in its \code{p_value} component.
#'
#' @references
#' Fraiman, D. and Fraiman, R. (2018) An ANOVA approach for statistical
#' comparisons of brain networks. \emph{Scientific Reports}, 8, 4746.
#' \doi{10.1038/s41598-018-23152-5}.
#'
#' Winkler, A. M. et al. (2014) Permutation inference for the general linear
#' model. \emph{NeuroImage}, 92, 381--397.
#' \doi{10.1016/j.neuroimage.2014.01.060}.
#'
#' @seealso \code{\link{compute_test_statistic}} for the statistic alone,
#'   \code{\link{identify_critical_links}} for the edges behind a rejection,
#'   \code{\link{print.global_test}}.
#'
#' @export
#' @examples
#' control <- generate_category_graphs(n_graphs = 20, n_nodes = 10,
#'   n_communities = 2, base_intra_prob = 0.6, base_inter_prob = 0.2, seed = 1)
#' patient <- generate_category_graphs(n_graphs = 20, n_nodes = 10,
#'   n_communities = 2, base_intra_prob = 0.6, base_inter_prob = 0.4, seed = 2)
#' populations <- list(Control = control, Patient = patient)
#'
#' gt <- global_test(populations, n_permutations = 500, seed = 42)
#' gt
#' gt$p_value
#'
#' # The observed statistic is the one compute_test_statistic() returns
#' all.equal(gt$statistic, compute_test_statistic(populations, a = 1))
#'
#' # The null distribution is kept, so it can be inspected
#' summary(gt$null_distribution)
global_test <- function(populations, n_permutations = 1000, seed = NULL,
                        criterion = c("combined", "original"),
                        method = "fisher") {
  cl <- match.call()
  if (!is.null(seed)) set.seed(seed)
  n_nodes        <- .check_inference_populations(populations)
  n_permutations <- .check_count(n_permutations, "n_permutations")
  criterion      <- match.arg(criterion)
  method         <- .check_edge_method(method, length(populations))

  group_sizes <- lengths(populations)

  ## compute_distance() sums both triangles of the symmetric adjacency
  ## matrices, so the value compute_test_statistic() reports is twice the sum
  ## of the upper-triangle contributions Delta_e. T is reported on that scale
  ## here, so that `statistic` agrees with compute_test_statistic(); the common
  ## factor leaves every comparison, and hence the p value, unchanged.
  both_triangles <- 2

  freq  <- compute_edge_frequencies(populations)
  obs   <- .observed_edge_deltas(freq$edge_counts, group_sizes, a = 1)
  T_obs <- both_triangles * sum(obs$deltas)

  if (nrow(obs$indices) == 0L) {
    ## A single node: no edges, every distance is zero and T is identically 0.
    T_perm  <- rep(0, n_permutations)
    p_value <- p_global <- p_local <- U_obs <- NA_real_
  } else {
    X       <- .graph_edge_matrix(populations, obs$indices)
    C_list  <- .permuted_edge_counts(X, group_sizes, n_permutations)
    T_perm  <- both_triangles *
               colSums(.permuted_edge_deltas(C_list, group_sizes, a = 1))
    p_global <- .plus_one_pvalue(c(T_obs, T_perm))
    p_local  <- U_obs <- NA_real_
    p_value  <- p_global
    if (criterion == "combined") {
      obs_counts <- do.call(cbind, lapply(seq_along(group_sizes), function(k)
        freq$edge_counts[, , k][obs$indices]))
      if (!is.matrix(obs_counts)) obs_counts <- matrix(obs_counts, nrow = 1L)
      pv      <- .marginal_pvalues(obs_counts, C_list, group_sizes, method)
      U_all   <- c(min(pv$obs), apply(pv$perm, 2, min))
      U_obs   <- U_all[1L]
      p_local <- .plus_one_pvalue(U_all)
      p_value <- .combined_pvalue(c(T_obs, T_perm), U_all)
    }
  }

  structure(
    list(statistic         = T_obs,
         p_value           = p_value,
         p_value_global    = p_global,
         p_value_local     = p_local,
         local_statistic   = U_obs,
         criterion         = criterion,
         null_distribution = T_perm,
         n_permutations    = n_permutations,
         group_sizes       = group_sizes,
         n_nodes           = as.integer(n_nodes),
         call              = cl),
    class = "global_test")
}

#' Print a Global Test Result
#'
#' Reports the populations compared, the observed statistic and the
#' permutation \eqn{p} value of a \code{\link{global_test}} analysis. An
#' estimate at the resolution limit \eqn{1/(B+1)} is marked as the minimum
#' for \eqn{B} permutation replicates.
#'
#' @param x An object of class \code{"global_test"}.
#' @param digits Number of significant digits used for the statistic.
#'   Default \code{getOption("digits")}.
#' @param ... Further arguments, currently ignored.
#'
#' @return \code{x}, invisibly.
#' @seealso \code{\link{global_test}}.
#' @export
#' @examples
#' control <- generate_category_graphs(n_graphs = 20, n_nodes = 10,
#'   n_communities = 2, base_intra_prob = 0.6, base_inter_prob = 0.2, seed = 1)
#' patient <- generate_category_graphs(n_graphs = 20, n_nodes = 10,
#'   n_communities = 2, base_intra_prob = 0.6, base_inter_prob = 0.4, seed = 2)
#' global_test(list(Control = control, Patient = patient),
#'   n_permutations = 500, seed = 42)
print.global_test <- function(x, digits = getOption("digits"), ...) {
  cat("\nGlobal test for populations of brain networks\n\n")

  groups <- names(x$group_sizes)
  if (is.null(groups)) groups <- paste("group", seq_along(x$group_sizes))
  cat(sprintf("Populations:  %d (%s), %s graphs\n",
              length(x$group_sizes), paste(groups, collapse = ", "),
              paste(x$group_sizes, collapse = " / ")))
  cat(sprintf("Nodes:        %d (%d possible edges)\n",
              x$n_nodes, (x$n_nodes * (x$n_nodes - 1L)) %/% 2L))
  cat(sprintf("Statistic:    T = %s\n", format(x$statistic, digits = digits)))

  if (is.na(x$p_value)) {
    cat("p value:      not evaluated (no edges)\n\n")
  } else {
    crit <- if (is.null(x$criterion)) "original" else x$criterion
    cat(sprintf("p value:      %s; %s criterion, %d permutations\n",
                .format_pvalue(x$p_value, x$n_permutations), crit,
                x$n_permutations))
    if (identical(crit, "combined"))
      cat(sprintf("              T alone: %s; smallest marginal p-value alone: %s\n",
                  .format_pvalue(x$p_value_global, x$n_permutations),
                  .format_pvalue(x$p_value_local, x$n_permutations)))
    cat("\n")
  }

  invisible(x)
}

Try the BrainNetTest package in your browser

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

BrainNetTest documentation built on Dec. 3, 2026, 5:08 p.m.