# Permutation tests for social networks
# https://tidyecology.com/posts/permutation-tests-social-networks/
#
# The R code of this Tidy Ecology tutorial, chunk by chunk, in the order of the post.
# Run it top to bottom in a fresh R session. Code the post shows but does not run
# is commented out. The prose, and the numbers it quotes, are in the post itself.
# Post last modified: 2026-09-30

## ---- setup ----
library(ggplot2)
theme_set(theme_minimal(base_size = 12) +
  theme(plot.background = element_rect(fill = "#f5f4ee", colour = NA),
        panel.background = element_rect(fill = "#f5f4ee", colour = NA),
        panel.grid.minor = element_blank()))
knitr::opts_chunk$set(dev.args = list(bg = "#f5f4ee"))

## ---- machinery ----
sri_from_gbi <- function(gbi) {
  co <- crossprod(gbi)
  n  <- diag(co)
  a  <- co / (outer(n, n, "+") - co)
  diag(a) <- 0
  a
}
node_degree <- function(a) rowSums(a > 0)

swap_data_stream <- function(gbi, n_swaps) {
  nr <- nrow(gbi); nc <- ncol(gbi); done <- 0L
  while (done < n_swaps) {
    batch <- (n_swaps - done) * 30L
    r1 <- sample.int(nr, batch, TRUE); r2 <- sample.int(nr, batch, TRUE)
    c1 <- sample.int(nc, batch, TRUE); c2 <- sample.int(nc, batch, TRUE)
    for (k in seq_len(batch)) {
      i1 <- r1[k]; i2 <- r2[k]; j1 <- c1[k]; j2 <- c2[k]
      if (i1 == i2 || j1 == j2) next
      if (gbi[i1,j1] && gbi[i2,j2] && !gbi[i1,j2] && !gbi[i2,j1]) {
        gbi[i1,j1] <- 0L; gbi[i2,j2] <- 0L; gbi[i1,j2] <- 1L; gbi[i2,j1] <- 1L
        done <- done + 1L
      } else if (gbi[i1,j2] && gbi[i2,j1] && !gbi[i1,j1] && !gbi[i2,j2]) {
        gbi[i1,j2] <- 0L; gbi[i2,j1] <- 0L; gbi[i1,j1] <- 1L; gbi[i2,j2] <- 1L
        done <- done + 1L
      }
      if (done == n_swaps) break
    }
  }
  gbi
}

## ---- cv-invariance ----
set.seed(1)
m <- matrix(runif(15 * 15), 15, 15); m <- (m + t(m)) / 2; diag(m) <- 0
cv <- function(a) { v <- a[upper.tri(a)]; sd(v) / mean(v) }
obs_cv <- cv(m)
relabel_cv <- replicate(2000, { p <- sample(15); cv(m[p, p]) })
c(observed = round(obs_cv, 4),
  null_min = round(min(relabel_cv), 4),
  null_max = round(max(relabel_cv), 4),
  null_sd  = signif(sd(relabel_cv), 3))

## ---- illustrative ----
set.seed(27)
n_ind <- 20; n_grp <- 24
detect <- runif(n_ind, 0.10, 0.35)
raw <- matrix(rbinom(n_grp * n_ind, 1, rep(detect, each = n_grp)), n_grp, n_ind)
raw <- raw[rowSums(raw) > 0, ]
raw <- raw[, colSums(raw) > 0]
gbi <- swap_data_stream(raw, 1500)               # a random-association network
trait <- colSums(gbi) + rnorm(ncol(gbi), 0, 1.2) # trait tracks sighting count only
net  <- sri_from_gbi(gbi)
deg  <- node_degree(net)
obs_r <- cor(trait, deg)

n_perm <- 1000
node_null <- replicate(n_perm, cor(sample(trait), deg))
p_node <- mean(abs(node_null) >= abs(obs_r))

ds_null <- numeric(n_perm); g <- gbi
for (b in seq_len(n_perm)) {
  g <- swap_data_stream(g, 50)
  ds_null[b] <- cor(trait, node_degree(sri_from_gbi(g)))
}
p_ds <- mean(abs(ds_null) >= abs(obs_r))

c(observed_cor = round(obs_r, 3),
  p_node = round(p_node, 3),
  p_data_stream = round(p_ds, 3),
  cor_trait_count  = round(cor(trait, colSums(gbi)), 3),
  cor_degree_count = round(cor(deg, colSums(gbi)), 3))

## ---- fig-nulls ----
nulls <- rbind(
  data.frame(r = node_null, null = "node permutation"),
  data.frame(r = ds_null,   null = "data-stream permutation"))
ggplot(nulls, aes(r, fill = null)) +
  geom_histogram(bins = 40, alpha = 0.75, position = "identity") +
  geom_vline(xintercept = obs_r, linetype = "dashed", linewidth = 0.7) +
  annotate("text", x = obs_r, y = Inf, label = "observed", vjust = 1.5, hjust = 1.1, size = 3.4) +
  scale_fill_manual(values = c("node permutation" = "#c46a1b",
                               "data-stream permutation" = "#2b5d34"), name = NULL) +
  labs(title = "Same data, two nulls, opposite verdicts",
       x = "correlation between trait and degree under the null", y = "count") +
  theme(legend.position = "top")

## ---- type-one ----
one_study <- function(n_ind = 20, n_grp = 24, n_perm = 120, n_sw = 50, burn = 1500) {
  d <- runif(n_ind, 0.10, 0.35)
  g0 <- matrix(rbinom(n_grp * n_ind, 1, rep(d, each = n_grp)), n_grp, n_ind)
  g0 <- g0[rowSums(g0) > 0, ]; g0 <- g0[, colSums(g0) > 0]
  gbi <- swap_data_stream(g0, burn)
  trait <- colSums(gbi) + rnorm(ncol(gbi), 0, 1.2)
  deg <- node_degree(sri_from_gbi(gbi))
  if (sd(deg) == 0) return(c(NA, NA))
  obs <- cor(trait, deg)
  nn <- replicate(n_perm, cor(sample(trait), deg))
  p_node <- mean(abs(nn) >= abs(obs))
  dd <- numeric(n_perm); g <- gbi
  for (b in seq_len(n_perm)) {
    g <- swap_data_stream(g, n_sw); dg <- node_degree(sri_from_gbi(g))
    dd[b] <- if (sd(dg) == 0) NA else cor(trait, dg)
  }
  c(p_node = p_node, p_ds = mean(abs(dd) >= abs(obs), na.rm = TRUE))
}

set.seed(2024)
res <- t(replicate(120, one_study()))
res <- res[!is.na(res[, 1]), ]
se <- function(p, n) sqrt(p * (1 - p) / n)
rate_node <- mean(res[, "p_node"] < 0.05)
rate_ds   <- mean(res[, "p_ds"]   < 0.05)
c(studies = nrow(res),
  node_type_I_pct = round(100 * rate_node, 1),
  node_SE = round(100 * se(rate_node, nrow(res)), 1),
  data_stream_type_I_pct = round(100 * rate_ds, 1),
  data_stream_SE = round(100 * se(rate_ds, nrow(res)), 1))
