# Species synchrony and community stability
# https://tidyecology.com/posts/synchrony-and-community-stability/
#
# 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-07

## ---- setup ----
library(ggplot2)
library(patchwork)

te_paper  <- "#f5f4ee"
te_ink    <- "#16241d"
te_body   <- "#2c3a31"
te_forest <- "#275139"
te_rust   <- "#b5534e"
te_gold   <- "#c9b458"
te_line   <- "#dad9ca"

theme_datasheet <- function() {
  theme_minimal(base_size = 12) +
    theme(plot.background  = element_rect(fill = te_paper, colour = NA),
          panel.background = element_rect(fill = te_paper, colour = NA),
          panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
          panel.grid.minor = element_blank(),
          text             = element_text(colour = te_body),
          plot.title       = element_text(colour = te_ink, face = "bold"),
          plot.subtitle    = element_text(colour = te_body),
          axis.text        = element_text(colour = te_body))
}

## ---- design ----
mu_tot  <- 100      # expected community total, held fixed throughout
c_tay   <- 0.4      # coefficient of the mean-variance law
z_main  <- 1.5      # exponent used unless stated otherwise
n_year  <- 30       # length of each series
n_rep   <- 400      # simulated communities per design point
n_batch <- 10       # batches for Monte Carlo standard errors
S_grid  <- c(2, 3, 4, 6, 8, 12, 16, 24, 32, 40)

sync_phi <- function(abund) {
  var(rowSums(abund)) / sum(apply(abund, 2, sd))^2
}
cv_total <- function(abund) sd(rowSums(abund)) / mean(rowSums(abund))

# n_year by S matrix of abundances with equal pairwise correlation rho
sim_comm <- function(mu_sp, rho, z, n_year, chol_r = NULL) {
  n_sp <- length(mu_sp)
  if (is.null(chol_r)) {
    cor_mat <- matrix(rho, n_sp, n_sp); diag(cor_mat) <- 1
    chol_r  <- chol(cor_mat)
  }
  sd_sp <- c_tay * mu_sp^(z / 2)
  noise <- matrix(rnorm(n_year * n_sp), n_year) %*% chol_r
  sweep(sweep(noise, 2, sd_sp, "*"), 2, mu_sp, "+")
}

# expected community CV for S equal species with correlation rho
cv_theory <- function(S, rho, z) {
  phi_true <- rho + (1 - rho) / S
  sqrt(phi_true) * S * c_tay * (mu_tot / S)^(z / 2) / mu_tot
}

## ---- identity ----
set.seed(2008)
n_check <- 200
check <- t(replicate(n_check, {
  n_sp  <- sample.int(39, 1) + 1
  share <- diff(c(0, sort(runif(n_sp - 1)), 1))
  rho   <- runif(1, 0, 0.9)
  abund <- sim_comm(mu_tot * share, rho, z_main, n_year)
  sd_sp <- apply(abund, 2, sd)
  cv_sp <- sd_sp / colMeans(abund)
  wts   <- colMeans(abund) / sum(colMeans(abund))
  phi_h <- sync_phi(abund)
  c(cv_direct = cv_total(abund),
    cv_split  = sqrt(phi_h) * sum(sd_sp) / mean(rowSums(abund)),
    cv_weight = sqrt(phi_h) * sum(wts * cv_sp),
    phi = phi_h,
    neg = sum(abund < 0), cells = length(abund))
}))
gap_split  <- max(abs(check[, "cv_direct"] - check[, "cv_split"]))
gap_weight <- max(abs(check[, "cv_direct"] - check[, "cv_weight"]))
phi_span   <- range(check[, "phi"])
neg_check  <- sum(check[, "neg"]) / sum(check[, "cells"])

## ---- fp-guard-1 ----
stopifnot(gap_split < 1e-10, gap_weight < 1e-10)

## ---- phi-by-S ----
rho_pair <- c(0, 0.3)
phi_sim <- do.call(rbind, lapply(rho_pair, function(rho) {
  do.call(rbind, lapply(S_grid, function(S) {
    cor_mat <- matrix(rho, S, S); diag(cor_mat) <- 1
    ch <- chol(cor_mat)
    phi_draw <- replicate(n_rep, sync_phi(sim_comm(rep(mu_tot / S, S), rho,
                                                   z_main, n_year, ch)))
    data.frame(S = S, rho = rho, phi_mean = mean(phi_draw),
               phi_se = sd(phi_draw) / sqrt(n_rep),
               phi_true = rho + (1 - rho) / S)
  }))
}))
phi_sim$gap_se <- (phi_sim$phi_mean - phi_sim$phi_true) / phi_sim$phi_se
ind40 <- phi_sim[phi_sim$rho == 0 & phi_sim$S == 40, ]
cor40 <- phi_sim[phi_sim$rho == 0.3 & phi_sim$S == 40, ]
above_ind <- sum(phi_sim$gap_se[phi_sim$rho == 0] > 0)
above_cor <- sum(phi_sim$gap_se[phi_sim$rho == 0.3] > 0)
rel_ind   <- mean(with(phi_sim[phi_sim$rho == 0, ], phi_mean / phi_true))

## ---- fig-phi ----
p_phi <- ggplot(phi_sim, aes(S, phi_mean, colour = factor(rho))) +
  geom_line(aes(y = phi_true), linewidth = 0.7) +
  geom_point(size = 2) +
  scale_x_log10(breaks = c(2, 4, 8, 16, 40)) +
  scale_y_log10(breaks = c(0.025, 0.05, 0.1, 0.2, 0.4, 0.65),
                labels = function(b) sprintf("%g", b)) +
  scale_colour_manual(values = c(te_forest, te_rust),
                      labels = c("independent", "rho = 0.3"),
                      name = NULL) +
  labs(x = "number of species", y = "synchrony index phi",
       title = "Synchrony has a floor",
       subtitle = "lines: theory; points: simulated") +
  theme_datasheet() +
  theme(legend.position = "bottom")

p_id <- ggplot(as.data.frame(check), aes(cv_split, cv_direct)) +
  geom_abline(slope = 1, intercept = 0, colour = te_line, linewidth = 0.9) +
  geom_point(colour = te_gold, size = 1.6, alpha = 0.8) +
  labs(x = "sqrt(phi) x sum(sd) / total mean",
       y = "community CV, direct",
       title = "The split is exact",
       subtitle = "200 unequal communities") +
  theme_datasheet()

p_phi + p_id + plot_annotation(theme = theme_datasheet())

## ---- fixed-phi ----
phi_fix <- 0.25
z_set   <- c(1, 1.5, 2)
batch_id <- rep(seq_len(n_batch), length.out = n_rep)
set.seed(1998)
fix_runs <- lapply(z_set, function(z) {
  cv_mat <- sapply(S_grid, function(S) {
    rho <- (phi_fix * S - 1) / (S - 1)
    cor_mat <- matrix(rho, S, S); diag(cor_mat) <- 1
    ch <- chol(cor_mat)
    replicate(n_rep, cv_total(sim_comm(rep(mu_tot / S, S), rho, z, n_year, ch)))
  })
  slope_all <- coef(lm(log(colMeans(cv_mat)) ~ log(S_grid)))[2]
  slope_bat <- sapply(seq_len(n_batch), function(b) {
    coef(lm(log(colMeans(cv_mat[batch_id == b, ])) ~ log(S_grid)))[2]
  })
  list(z = z, cv_mean = colMeans(cv_mat), slope = unname(slope_all),
       slope_se = sd(slope_bat) / sqrt(n_batch), theory = 1 - z / 2)
})
fix_tab <- data.frame(z = z_set,
                      slope = sapply(fix_runs, `[[`, "slope"),
                      slope_se = sapply(fix_runs, `[[`, "slope_se"),
                      theory = sapply(fix_runs, `[[`, "theory"))
fix_tab$gap_se <- (fix_tab$slope - fix_tab$theory) / fix_tab$slope_se
fix_pts <- do.call(rbind, lapply(fix_runs, function(r) {
  data.frame(S = S_grid, z = r$z, cv = r$cv_mean,
             cv_line = sqrt(phi_fix) * c_tay * mu_tot^(r$z / 2 - 1) *
                       S_grid^(1 - r$z / 2))
}))

## ---- fig-fixed-phi ----
ggplot(fix_pts, aes(S, cv, colour = factor(z), linetype = factor(z),
                    shape = factor(z))) +
  geom_line(aes(y = cv_line), linewidth = 0.7) +
  geom_point(size = 2.2) +
  scale_x_log10(breaks = c(2, 4, 8, 16, 40)) +
  scale_y_log10(breaks = c(0.03, 0.05, 0.075, 0.1, 0.15, 0.2),
                labels = function(b) sprintf("%g", b)) +
  scale_colour_manual(values = c(te_gold, te_body, te_ink),
                      labels = c("z = 1", "z = 1.5", "z = 2"), name = NULL) +
  scale_linetype_manual(values = c("solid", "dashed", "dotted"),
                        labels = c("z = 1", "z = 1.5", "z = 2"), name = NULL) +
  scale_shape_manual(values = c(16, 17, 15),
                     labels = c("z = 1", "z = 1.5", "z = 2"), name = NULL) +
  labs(x = "number of species (log scale)", y = "community CV (log scale)",
       title = "At fixed synchrony, the slope is 1 - z/2",
       subtitle = "fixed total mean, equal species, phi = 0.25") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- phi-sweep ----
S_sweep   <- 16
phi_sweep <- seq(0.05, 0.95, by = 0.10)
set.seed(2013)
sweep_cv <- sapply(phi_sweep, function(ph) {
  rho <- (ph * S_sweep - 1) / (S_sweep - 1)
  cor_mat <- matrix(rho, S_sweep, S_sweep); diag(cor_mat) <- 1
  ch <- chol(cor_mat)
  replicate(n_rep, cv_total(sim_comm(rep(mu_tot / S_sweep, S_sweep), rho,
                                     z_main, n_year, ch)))
})
sweep_df <- data.frame(phi = phi_sweep, cv = colMeans(sweep_cv),
                       cv_se = apply(sweep_cv, 2, sd) / sqrt(n_rep))
sum_sd_ratio <- S_sweep * c_tay * (mu_tot / S_sweep)^(z_main / 2) / mu_tot
sweep_df$cv_line <- sqrt(sweep_df$phi) * sum_sd_ratio
sweep_slope <- coef(lm(log(cv) ~ log(phi), data = sweep_df))[2]
sweep_ratio <- sweep_df$cv[nrow(sweep_df)] / sweep_df$cv[1]
sweep_ratio_true <- sqrt(max(phi_sweep) / min(phi_sweep))
sweep_bias <- mean(sweep_df$cv / sweep_df$cv_line)

## ---- fig-sweep ----
sweep_cloud <- data.frame(phi = rep(phi_sweep, each = n_rep),
                          cv = as.vector(sweep_cv))
ggplot(sweep_df, aes(phi, cv)) +
  geom_jitter(data = sweep_cloud, width = 0.012, height = 0,
              colour = te_line, size = 0.6, alpha = 0.6) +
  geom_line(aes(y = cv_line), colour = te_ink, linewidth = 0.8) +
  geom_point(colour = te_gold, size = 2.4) +
  scale_x_continuous(breaks = phi_sweep) +
  labs(x = "synchrony index phi", y = "community CV",
       title = "At fixed richness, CV goes as the square root of phi",
       subtitle = "sixteen species, z = 1.5, thirty-year series") +
  theme_datasheet()

## ---- shared ----
rho_shared <- 0.8
S_full <- c(1, S_grid)
set.seed(1999)
shared_runs <- do.call(rbind, lapply(c(0, rho_shared), function(rho) {
  cv_mat <- sapply(S_full, function(S) {
    cor_mat <- matrix(rho, S, S); diag(cor_mat) <- 1
    ch <- chol(cor_mat)
    replicate(n_rep, cv_total(sim_comm(rep(mu_tot / S, S), rho, z_main,
                                       n_year, ch)))
  })
  slope_bat <- sapply(seq_len(n_batch), function(b) {
    coef(lm(log(colMeans(cv_mat[batch_id == b, ])) ~ log(S_full)))[2]
  })
  data.frame(S = S_full, rho = rho, cv = colMeans(cv_mat),
             cv_line = cv_theory(S_full, rho, z_main),
             slope = unname(coef(lm(log(colMeans(cv_mat)) ~ log(S_full)))[2]),
             slope_se = sd(slope_bat) / sqrt(n_batch))
}))
ind_run <- shared_runs[shared_runs$rho == 0, ]
shr_run <- shared_runs[shared_runs$rho == rho_shared, ]
ind_fold <- ind_run$cv[ind_run$S == 40] / ind_run$cv[ind_run$S == 1]
shr_fold <- shr_run$cv[shr_run$S == 40] / shr_run$cv[shr_run$S == 1]
shr_phi40 <- rho_shared + (1 - rho_shared) / 40
fold_z2 <- cv_theory(40, rho_shared, 2) / cv_theory(1, rho_shared, 2)

## ---- fig-shared ----
ggplot(shared_runs, aes(S, cv, colour = factor(rho))) +
  geom_line(aes(y = cv_line), linewidth = 0.7) +
  geom_point(size = 2.2) +
  scale_x_log10(breaks = c(1, 2, 4, 8, 16, 40)) +
  scale_y_log10(breaks = c(0.05, 0.075, 0.1, 0.15, 0.2, 0.3),
                labels = function(b) sprintf("%g", b)) +
  scale_colour_manual(values = c(te_forest, te_rust),
                      labels = c("independent", "shared response, rho = 0.8"),
                      name = NULL) +
  labs(x = "number of species (log scale)", y = "community CV (log scale)",
       title = "Same exponent, opposite diversity slope",
       subtitle = "z = 1.5, fixed total mean") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- short-series ----
n_short   <- c(10, 30)
n_rep_sh  <- 10000  # more replicates here: the bias is a few per cent
rho_short <- 0.3
c4 <- function(n) sqrt(2 / (n - 1)) * exp(lgamma(n / 2) - lgamma((n - 1) / 2))
sd_eq  <- c_tay * (mu_tot / S_sweep)^(z_main / 2)
set.seed(4766)
short_runs <- do.call(rbind, lapply(c(0, rho_short), function(rho) {
  cor_mat <- matrix(rho, S_sweep, S_sweep); diag(cor_mat) <- 1
  ch <- chol(cor_mat)
  phi_true <- rho + (1 - rho) / S_sweep
  varT_true <- S_sweep * sd_eq^2 * (1 + (S_sweep - 1) * rho)
  do.call(rbind, lapply(n_short, function(n_yr) {
    draws <- replicate(n_rep_sh, {
      abund <- sim_comm(rep(mu_tot / S_sweep, S_sweep), rho, z_main, n_yr, ch)
      c(sync_phi(abund), var(rowSums(abund)))
    })
    data.frame(rho = rho, n = n_yr, phi_true = phi_true,
               phi_mean = mean(draws[1, ]),
               factor = mean(draws[1, ]) / phi_true,
               factor_se = sd(draws[1, ]) / sqrt(n_rep_sh) / phi_true,
               varT_ratio = mean(draws[2, ]) / varT_true,
               c4_factor = 1 / c4(n_yr)^2)
  }))
}))
sh_i10 <- short_runs[short_runs$rho == 0 & short_runs$n == 10, ]
sh_i30 <- short_runs[short_runs$rho == 0 & short_runs$n == 30, ]
sh_c10 <- short_runs[short_runs$rho == rho_short & short_runs$n == 10, ]
neg_share <- mean(sim_comm(rep(mu_tot / 40, 40), 0, 2, 2000) < 0)
