# Complementarity and selection effects
# https://tidyecology.com/posts/complementarity-and-selection-effects/
#
# 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-11-04

## ---- setup ----
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE,
                      dev = "png", dpi = 120, fig.path = "figures/",
                      fig.width = 7, fig.height = 4.4)
library(ggplot2)
theme_te <- theme_minimal(base_size = 12) +
  theme(panel.background = element_rect(fill = "#f5f4ee", colour = NA),
        plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
        panel.grid.minor = element_blank(),
        plot.title = element_text(face = "bold", size = 12),
        strip.text = element_text(face = "bold"))
theme_set(theme_te)
col_a <- "#3a6b52"; col_b <- "#b5651d"; col_ref <- "#555555"

lh <- function(M, RYo, RYe) {
  dRY <- RYo - RYe; N <- length(M)
  c(dY = sum(dRY * M), comp = N * mean(dRY) * mean(M),
    sel = N * mean((dRY - mean(dRY)) * (M - mean(M))))
}

## two mechanisms, identical partition
set.seed(389)
M   <- round(runif(6, 80, 700)); RYe <- rep(1/6, 6); m <- 0.08
dRY_A <- rep(m, 6)
raw   <- c(-0.05, 0.22, 0.05, 0.14, -0.02, 0.10)
bcoef <- sum((raw - mean(raw)) * (M - mean(M))) / sum((M - mean(M))^2)
dRY_B <- m + (raw - mean(raw)) - bcoef * (M - mean(M))
pA <- lh(M, RYe + dRY_A, RYe); pB <- lh(M, RYe + dRY_B, RYe)
covB <- mean((dRY_B - mean(dRY_B)) * (M - mean(M)))

## monoculture-reference instability
Mbase <- rep(300, 6); Yobs <- c(120,110,130,125,115,140); RYe6 <- rep(1/6, 6)
frac  <- seq(1, 0.05, by = -0.05)
inst  <- data.frame()
for (f in frac) {
  M6 <- Mbase; M6[1] <- 300 * f
  p  <- lh(M6, Yobs / M6, RYe6)
  inst <- rbind(inst, data.frame(frac = f, comp = p["comp"], sel = p["sel"], net = p["dY"]))
}
net_full <- inst$net[inst$frac == 1]; comp_full <- inst$comp[inst$frac == 1]
i_lo <- which.min(inst$frac)
RYo1_lo <- Yobs[1] / (300 * min(frac))

## ---- two-mechanisms ----
m     <- 0.08
dRY_A <- rep(m, 6)                                   # uniform: "resource partitioning"
raw   <- c(-0.05, 0.22, 0.05, 0.14, -0.02, 0.10)     # uneven: "facilitation"
bcoef <- sum((raw - mean(raw)) * (M - mean(M))) / sum((M - mean(M))^2)
dRY_B <- m + (raw - mean(raw)) - bcoef * (M - mean(M))
rbind(A = round(lh(M, RYe + dRY_A, RYe), 4),
      B = round(lh(M, RYe + dRY_B, RYe), 4))

## ---- fp-guard-1 ----
stopifnot(abs(covB) < 1e-10 * sd(M) * sd(dRY_B))

## ---- fig-mechanisms ----
dm <- rbind(
  data.frame(mech = "A: uniform benefit", sp = 1:6, dRY = dRY_A),
  data.frame(mech = "B: uneven benefit",  sp = 1:6, dRY = dRY_B))
ggplot(dm, aes(factor(sp), dRY, fill = mech)) +
  geom_col(width = 0.7) +
  geom_hline(yintercept = m, colour = col_ref, linetype = "dashed") +
  facet_wrap(~mech) +
  scale_fill_manual(values = c("A: uniform benefit" = col_a, "B: uneven benefit" = col_b), guide = "none") +
  labs(x = "Species", y = "Change in relative yield",
       title = "Same complementarity, same selection, different biology")

## ---- instability ----
Mbase <- rep(300, 6); Yobs <- c(120,110,130,125,115,140)
shrink <- function(f) { M6 <- Mbase; M6[1] <- 300 * f; lh(M6, Yobs / M6, rep(1/6,6)) }
rbind(full = round(shrink(1.00), 1), nearly_zero = round(shrink(0.05), 1))

## ---- fig-instability ----
il <- rbind(data.frame(frac = inst$frac, effect = "complementarity", val = inst$comp),
            data.frame(frac = inst$frac, effect = "selection",       val = inst$sel),
            data.frame(frac = inst$frac, effect = "net",             val = inst$net))
ggplot(il, aes(frac, val, colour = effect)) +
  geom_line(linewidth = 1) +
  scale_x_reverse() +
  scale_colour_manual(values = c(complementarity = col_a, selection = col_b, net = col_ref)) +
  labs(x = "Monoculture yield of species 1 (fraction of the others)",
       y = expression(Effect~(g/m^2)), colour = NULL,
       title = "One small denominator breaks the split, not the total")
