# Checking a joint species distribution model
# https://tidyecology.com/posts/checking-a-jsdm/
#
# 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-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))
}

set.seed(386)

null_max <- function(S, n, B) {
  off <- lower.tri(diag(S))
  replicate(B, {
    Z <- matrix(rnorm(n * S), n, S)
    x <- runif(n, -2, 2)
    R <- cor(residuals(lm(Z ~ x)))
    max(abs(R[off]))
  })
}

n_plots <- 100L
S_grid <- c(5L, 10L, 20L, 40L)
null_tab <- t(sapply(S_grid, function(S) {
  m <- null_max(S, n_plots, 600L)
  c(pairs = S * (S - 1) / 2, med = median(m), hi = unname(quantile(m, 0.95)))
}))

## ---- fig-null ----
dfn <- data.frame(S = S_grid, med = null_tab[, "med"], hi = null_tab[, "hi"])
ggplot(dfn, aes(S)) +
  geom_ribbon(aes(ymin = med, ymax = hi), fill = "#93a87f", alpha = 0.35) +
  geom_line(aes(y = hi), colour = "#c9b458", linewidth = 0.9) +
  geom_line(aes(y = med), colour = "#275139", linewidth = 0.9) +
  geom_point(aes(y = hi), colour = "#c9b458", size = 2.5) +
  geom_point(aes(y = med), colour = "#275139", size = 2.5) +
  scale_x_continuous(breaks = S_grid) +
  labs(x = "number of species", y = "largest absolute residual correlation",
       title = "The strongest association under a true null",
       subtitle = "100 plots, no associations in the simulation. Green: median. Gold: 95th percentile") +
  theme_te()

## ---- tetra ----
bvn <- function(h, k, rho) {
  s <- sqrt(1 - rho^2)
  integrate(function(z) pnorm((k - rho * z) / s) * dnorm(z),
            lower = -8, upper = h, rel.tol = 1e-8)$value
}

tetrachoric <- function(y1, y2) {
  h <- qnorm(mean(y1 == 0)); k <- qnorm(mean(y2 == 0))
  if (!is.finite(h) || !is.finite(k)) return(NA_real_)
  cnt <- c(sum(y1 == 0 & y2 == 0), sum(y1 == 0 & y2 == 1),
           sum(y1 == 1 & y2 == 0), sum(y1 == 1 & y2 == 1))
  nll <- function(rho) {
    p00 <- bvn(h, k, rho)
    p <- pmax(c(p00, pnorm(h) - p00, pnorm(k) - p00,
                1 - pnorm(h) - pnorm(k) + p00), 1e-12)
    -sum(cnt * log(p))
  }
  optimize(nll, c(-0.95, 0.95), tol = 1e-4)$minimum
}

rho_true <- 0.6
compare <- function(nn, prevalence, B) {
  cutoff <- qnorm(1 - prevalence)
  Ch <- chol(matrix(c(1, rho_true, rho_true, 1), 2, 2))
  g <- numeric(B); b <- numeric(B)
  for (i in seq_len(B)) {
    Z <- matrix(rnorm(2 * nn), nn, 2) %*% Ch
    g[i] <- cor(Z[, 1], Z[, 2])
    b[i] <- tetrachoric(as.integer(Z[, 1] > cutoff), as.integer(Z[, 2] > cutoff))
  }
  c(sd_abund = sd(g), sd_pa = sd(b, na.rm = TRUE),
    bias_pa = mean(b, na.rm = TRUE) - rho_true)
}

set.seed(3861)
prev_grid <- c(0.50, 0.25, 0.10)
pa_tab <- t(sapply(prev_grid, function(p) compare(100L, p, 300L)))
ratio_pa <- pa_tab[, "sd_pa"] / pa_tab[, "sd_abund"]

## ---- effort ----
set.seed(3862)
n2 <- 250L
Sp <- 10L
effort <- runif(n2, 0.5, 2)
env <- runif(n2, -2, 2)
slopes <- rnorm(Sp, 0, 0.8)
inter <- rnorm(Sp, 2, 0.4)

Yc <- outer(rep(1, n2), inter) + outer(env, slopes) +
      outer(log(effort), rep(1, Sp)) +
      matrix(rnorm(n2 * Sp, 0, 0.6), n2, Sp)

lower <- lower.tri(diag(Sp))
R_naive <- cor(residuals(lm(Yc ~ env)))
R_eff   <- cor(residuals(lm(Yc ~ env + log(effort))))
np <- sum(lower)
neg_naive <- sum(R_naive[lower] < 0)
neg_eff   <- sum(R_eff[lower] < 0)

## ---- fig-effort ----
dfe <- data.frame(
  r = c(R_naive[lower], R_eff[lower]),
  model = rep(c("effort omitted", "effort in the model"), each = np))
dfe$model <- factor(dfe$model, levels = c("effort in the model", "effort omitted"))

ggplot(dfe, aes(r, model, colour = model)) +
  geom_vline(xintercept = 0, colour = "#5d6b61", linetype = "dashed") +
  geom_jitter(height = 0.16, width = 0, size = 2.2, alpha = 0.75) +
  scale_colour_manual(values = c("effort omitted" = "#b5534e",
                                 "effort in the model" = "#275139"), guide = "none") +
  labs(x = "pairwise residual correlation", y = NULL,
       title = "An unrecorded effort gradient makes every species a friend",
       subtitle = "Ten species, 250 plots, effort varying from 0.5 to 2.0") +
  theme_te()
