# Co-occurrence is not interaction
# https://tidyecology.com/posts/co-occurrence-is-not-interaction/
#
# 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_te <- function(base_size = 11) {
  theme_minimal(base_size = base_size) +
    theme(panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "#dad9ca", linewidth = 0.3),
          axis.title = element_text(colour = "#46604a"),
          axis.text = element_text(colour = "#5d6b61"),
          plot.title = element_text(colour = "#16241d", face = "bold"),
          plot.subtitle = element_text(colour = "#5d6b61"),
          legend.title = element_text(colour = "#46604a"),
          legend.text = element_text(colour = "#5d6b61"),
          plot.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA))
}

lam_a <- 0.9; lam_b <- 0.7
sd_a  <- 0.6; sd_b  <- 0.5

Sigma_driver <- matrix(c(lam_a^2 + sd_a^2, lam_a * lam_b,
                         lam_a * lam_b,    lam_b^2 + sd_b^2), 2, 2)
r_driver <- cov2cor(Sigma_driver)[1, 2]

## ---- interaction ----
var_a <- lam_a^2 + sd_a^2
beta  <- lam_a * lam_b / var_a
var_b <- (lam_b^2 + sd_b^2) - beta^2 * var_a

Sigma_inter <- matrix(c(var_a, beta * var_a,
                        beta * var_a, beta^2 * var_a + var_b), 2, 2)

equiv_gap <- max(abs(Sigma_driver - Sigma_inter))
r_inter <- cov2cor(Sigma_inter)[1, 2]

## ---- fp-guard-1 ----
stopifnot(equiv_gap < 1e-10)

## ---- direction ----
beta_ab <- Sigma_driver[1, 2] / Sigma_driver[1, 1]
beta_ba <- Sigma_driver[1, 2] / Sigma_driver[2, 2]

rebuild <- function(b, v_from, v_noise) {
  matrix(c(v_from, b * v_from, b * v_from, b^2 * v_from + v_noise), 2, 2)
}
gap_ab <- max(abs(rebuild(beta_ab, Sigma_driver[1, 1],
                          Sigma_driver[2, 2] - beta_ab^2 * Sigma_driver[1, 1]) -
                  Sigma_driver))
gap_ba <- max(abs(rebuild(beta_ba, Sigma_driver[2, 2],
                          Sigma_driver[1, 1] - beta_ba^2 * Sigma_driver[2, 2])[2:1, 2:1] -
                  Sigma_driver))

## ---- fp-guard-2 ----
stopifnot(gap_ab < 1e-10, gap_ba < 1e-10)

## ---- cascade ----
S <- 6L
L6 <- cbind(c(0.9, 0.8, -0.7, 0.2, 0.1, -0.3),
            c(0.2, -0.4, 0.5, 0.8, -0.7, 0.6))
Sig6 <- L6 %*% t(L6) + diag(rep(0.4, S))

Ch1 <- t(chol(Sig6))
gap1 <- max(abs(Ch1 %*% t(Ch1) - Sig6))

ord <- c(4, 1, 6, 2, 5, 3)
Ch2 <- t(chol(Sig6[ord, ord]))
back <- matrix(0, S, S)
back[ord, ord] <- Ch2 %*% t(Ch2)
gap2 <- max(abs(back - Sig6))

## ---- fp-guard-3 ----
stopifnot(gap1 < 1e-10, gap2 < 1e-10)

## ---- missing ----
set.seed(385)
n <- 300L
Sp <- 10L
x1 <- runif(n, -2, 2)
x2 <- runif(n, -2, 2)
x3 <- runif(n, -2, 2)

b1 <- rnorm(Sp, 0, 0.8)
b2 <- rnorm(Sp, 0, 0.6)
b3 <- c(1.2, 1.1, 0.9, 0.8, 0.7, -0.9, -1.0, -1.1, 0.1, -0.2)
a0 <- rnorm(Sp, 2, 0.5)

Y <- outer(rep(1, n), a0) + outer(x1, b1) + outer(x2, b2) + outer(x3, b3) +
     matrix(rnorm(n * Sp, 0, 0.7), n, Sp)

lower <- lower.tri(diag(Sp))
R_short <- cor(residuals(lm(Y ~ x1 + x2)))
R_full  <- cor(residuals(lm(Y ~ x1 + x2 + x3)))

## k is the number of variables partialled out, so the z has sqrt(n - 3 - k)
z_test <- function(r, nn, k) 2 * pnorm(-abs(atanh(r) * sqrt(nn - 3 - k)))
flag_short <- sum(z_test(R_short[lower], n, 2) < 0.05)
flag_full  <- sum(z_test(R_full[lower], n, 3) < 0.05)
npairs <- sum(lower)

## ---- fig-shift ----
dfd <- data.frame(
  r = c(R_short[lower], R_full[lower]),
  model = rep(c("two gradients measured", "all three gradients measured"),
              each = npairs))
dfd$model <- factor(dfd$model,
                    levels = c("two gradients measured", "all three gradients measured"))

ggplot(dfd, aes(r, fill = model, colour = model)) +
  geom_density(alpha = 0.45, linewidth = 0.7, bw = 0.08) +
  geom_vline(xintercept = 0, colour = "#5d6b61", linetype = "dashed") +
  scale_fill_manual(values = c("#c9b458", "#275139"), name = NULL) +
  scale_colour_manual(values = c("#b5534e", "#1d5b4e"), name = NULL) +
  labs(x = "pairwise residual correlation", y = "density",
       title = "One missing gradient, thirty-nine spurious associations",
       subtitle = "Ten species, 300 plots, no biotic interaction in the simulation") +
  theme_te() +
  theme(legend.position = "bottom")

## ---- proxy ----
set.seed(3851)
rhos <- c(0, 0.3, 0.6, 0.9, 0.99)
z3 <- as.numeric(scale(x3))  # x3 is not unit-variance, so standardise it first
proxy_mean <- sapply(rhos, function(rho) {
  e <- residuals(lm(rnorm(n) ~ z3)); e <- e / sd(e)  # unit-variance noise uncorrelated with z3
  prox <- rho * z3 + sqrt(1 - rho^2) * e             # so cor(prox, x3) is exactly rho
  Rp <- cor(residuals(lm(Y ~ x1 + x2 + prox)))
  mean(abs(Rp[lower]))
})
base_mean <- mean(abs(R_short[lower]))
removed <- 1 - proxy_mean / base_mean

## ---- fig-proxy ----
dfx <- data.frame(rho = rhos, m = proxy_mean)
ggplot(dfx, aes(rho, m)) +
  geom_line(colour = "#275139", linewidth = 0.9) +
  geom_point(colour = "#275139", size = 2.8) +
  scale_x_continuous(breaks = rhos) +
  labs(x = "correlation between the proxy and the true gradient",
       y = "mean absolute residual correlation",
       title = "A good proxy is not good enough",
       subtitle = "Same ten species, same 300 plots") +
  theme_te()
