# Checking a social network analysis
# https://tidyecology.com/posts/checking-a-social-network-analysis/
#
# 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-10-14

## ---- 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)
node_strength <- function(a) rowSums(a)
eigen_cent    <- function(a) { e <- eigen(a, symmetric = TRUE); v <- abs(e$vectors[, 1]); v / max(v) }
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
}

## ---- check-a ----
set.seed(11)
n_ind <- 24; n_grp <- 60
community <- rep(1:3, each = 8)
effort <- runif(n_ind, 0.5, 3)
gbi <- matrix(0L, n_grp, n_ind)
for (k in 1:n_grp) {
  base <- ifelse(community == sample(1:3, 1), 0.55, 0.06) * (effort / mean(effort))
  gbi[k, ] <- rbinom(n_ind, 1, pmin(base, 0.95))
}
gbi <- gbi[rowSums(gbi) > 0, ]; count <- colSums(gbi)
net <- sri_from_gbi(gbi); str <- node_strength(net)

c(cor_degree_count   = round(cor(node_degree(net), count), 3),
  cor_strength_count = round(cor(str, count), 3),
  cor_eigen_count    = round(cor(eigen_cent(net), count), 3))

## ---- check-a-fix ----
res_str <- residuals(lm(str ~ count))
c(raw_top_individual = which.max(str),
  effort_controlled_top_individual = unname(which.max(res_str)))

## ---- fig-check-a ----
dfa <- data.frame(raw = str, controlled = res_str, count = count)
ggplot(dfa, aes(raw, controlled, size = count)) +
  geom_point(colour = "#2b5d34", alpha = 0.8) +
  scale_size_continuous(name = "sightings", range = c(2, 6)) +
  labs(title = "Removing effort reorders the centrality ranking",
       x = "raw strength", y = "effort-controlled strength (residual)")

## ---- check-b ----
cv_stat <- function(a) { v <- a[upper.tri(a)]; sd(v) / mean(v) }
sim_power <- function(n_grp, pref = 0.75, n_ind = 16, n_perm = 120, n_rep = 400) {
  community <- rep(1:2, length.out = n_ind); rej <- logical(n_rep)
  for (r in 1:n_rep) {
    gbi <- matrix(0L, n_grp, n_ind)
    for (k in 1:n_grp) {
      base <- ifelse(community == sample(1:2, 1), pref, 1 - pref) * 0.4
      gbi[k, ] <- rbinom(n_ind, 1, base)
    }
    gbi <- gbi[rowSums(gbi) > 0, ]; gbi <- gbi[, colSums(gbi) > 0]
    if (ncol(gbi) < 6 || nrow(gbi) < 6) { rej[r] <- NA; next }
    obs <- cv_stat(sri_from_gbi(gbi)); g <- gbi; nd <- numeric(n_perm)
    for (b in 1:n_perm) { g <- swap_data_stream(g, 40); nd[b] <- cv_stat(sri_from_gbi(g)) }
    rej[r] <- obs > quantile(nd, 0.95, na.rm = TRUE)
  }
  mean(rej, na.rm = TRUE)
}

set.seed(303)
power <- c(`20 groups` = sim_power(20),
           `45 groups` = sim_power(45),
           `90 groups` = sim_power(90))
round(power, 2)
fpr20 <- sim_power(20, pref = 0.5)   # same test, a society with no preferred associations
round(fpr20, 2)

## ---- fig-check-b ----
dfb <- data.frame(groups = c(20, 45, 90), power = as.numeric(power))
ggplot(dfb, aes(groups, power)) +
  geom_hline(yintercept = 0.8, linetype = "dashed", colour = "grey60") +
  geom_line(colour = "#c46a1b", linewidth = 0.9) +
  geom_point(colour = "#c46a1b", size = 3) +
  ylim(0, 1) +
  labs(title = "Power to detect fixed structure rises with effort",
       x = "number of observed groups", y = "power of the CV test")

## ---- check-c ----
set.seed(9)
n_ind <- 15; n_sight <- 240
times <- sort(runif(n_sight, 0, 100))
grp_of <- rep(1:2, length.out = n_ind); ids <- integer(n_sight)
for (s in 1:n_sight) {
  phase <- (sin(times[s] / 6) > 0) + 1L
  ids[s] <- sample(n_ind, 1, prob = ifelse(grp_of == phase, 3, 1))
}
build_gbi <- function(gap) {
  grp <- c(0, cumsum(diff(times) > gap)) + 1
  m <- matrix(0L, max(grp), n_ind); for (s in 1:n_sight) m[grp[s], ids[s]] <- 1L
  m[rowSums(m) > 0, , drop = FALSE]
}
summarise_gap <- function(gap) {
  a <- sri_from_gbi(build_gbi(gap))
  c(gap = gap, groups = nrow(build_gbi(gap)),
    mean_sri = mean(a[upper.tri(a)]),
    top = which.max(node_strength(a)))
}
t(sapply(c(0.4, 1.2), summarise_gap))

## ---- fig-check-c ----
gaps <- seq(0.3, 2.5, by = 0.1)
sweep <- data.frame(gap = gaps,
  mean_sri = sapply(gaps, function(gp) { a <- sri_from_gbi(build_gbi(gp)); mean(a[upper.tri(a)]) }))
ggplot(sweep, aes(gap, mean_sri)) +
  geom_line(colour = "#2b5d34", linewidth = 0.9) +
  geom_point(colour = "#2b5d34", size = 1.6) +
  labs(title = "The network depends on where you split groups",
       x = "time-gap threshold for one group", y = "mean association (SRI)")
