# Joint species distribution models in R
# https://tidyecology.com/posts/joint-species-distribution-models/
#
# 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"),
          strip.text = element_text(colour = "#16241d"),
          plot.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA))
}

set.seed(383)

n <- 200L
S <- 12L
moisture <- runif(n, -2, 2)
openness <- runif(n, -2, 2)
X <- cbind(1, moisture, openness)
p <- ncol(X)

B_true <- cbind(rnorm(S, 2.0, 0.6), rnorm(S, 0.0, 0.9), rnorm(S, 0.0, 0.7))

Lam <- cbind(c( 0.9,  0.8,  0.7,  0.6, -0.7, -0.8, -0.6,  0.1, 0.0, 0.2, -0.1,  0.3),
             c( 0.2, -0.1,  0.3,  0.5,  0.4, -0.2,  0.6, -0.8, -0.7, 0.7,  0.8, -0.6))
psi_true <- rep(0.35, S)
Sigma_true <- Lam %*% t(Lam) + diag(psi_true)
R_true <- cov2cor(Sigma_true)

Y <- X %*% t(B_true) + matrix(rnorm(n * S), n, S) %*% chol(Sigma_true)
colnames(Y) <- paste0("sp", sprintf("%02d", seq_len(S)))

## ---- r2env ----
r2_env <- sapply(seq_len(S), function(j) summary(lm(Y[, j] ~ moisture + openness))$r.squared)
r2_med <- median(r2_env)

## ---- stackvsjoint ----
B_stacked <- t(sapply(seq_len(S), function(j) coef(lm(Y[, j] ~ moisture + openness))))

Sinv <- solve(Sigma_true)
A <- kronecker(Sinv, crossprod(X))
b <- as.vector(crossprod(X, Y) %*% Sinv)
B_joint <- t(matrix(solve(A, b), p, S))

sur_gap <- max(abs(B_joint - B_stacked))

## ---- fp-guard-1 ----
stopifnot(sur_gap / max(abs(B_stacked)) < 1e-10)

## ---- residcor ----
Res <- Y - X %*% t(B_stacked)
R_hat <- cor(Res)
lower <- lower.tri(R_hat)

cor_recovery <- cor(R_hat[lower], R_true[lower])
max_gap <- max(abs(R_hat[lower] - R_true[lower]))
mean_abs <- mean(abs(R_hat[lower]))
strongest <- max(abs(R_hat[lower]))

## ---- fig-heat ----
ord <- order(Lam[, 1])
Rp <- R_hat[ord, ord]
lab <- colnames(Y)[ord]
dfh <- data.frame(
  a = factor(rep(lab, times = S), levels = lab),
  b = factor(rep(lab, each = S), levels = rev(lab)),
  r = as.vector(Rp))

ggplot(dfh, aes(a, b, fill = r)) +
  geom_tile(colour = "white", linewidth = 0.4) +
  scale_fill_gradient2(low = "#b5534e", mid = "#f5f4ee", high = "#2f8f63",
                       midpoint = 0, limits = c(-1, 1), name = "residual\ncorrelation") +
  coord_equal() +
  labs(x = NULL, y = NULL,
       title = "Residual correlation after the measured environment",
       subtitle = "Twelve fen species, 200 plots") +
  theme_te() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1),
        panel.grid.major = element_blank())

## ---- condpred ----
set.seed(3831)
holdout <- sample(n, 60)
train <- setdiff(seq_len(n), holdout)

B_tr <- t(sapply(seq_len(S), function(j)
  coef(lm(Y[train, j] ~ moisture[train] + openness[train]))))
Res_tr <- Y[train, ] - X[train, ] %*% t(B_tr)
S_tr <- cov(Res_tr)

Mu <- X[holdout, ] %*% t(B_tr)
pred_cond <- Mu
for (j in seq_len(S)) {
  w <- S_tr[j, -j, drop = FALSE] %*% solve(S_tr[-j, -j])
  pred_cond[, j] <- Mu[, j] + as.vector((Y[holdout, -j] - Mu[, -j]) %*% t(w))
}

rmse <- function(a, b) sqrt(mean((a - b)^2))
rmse_marg <- rmse(Mu, Y[holdout, ])
rmse_cond <- rmse(pred_cond, Y[holdout, ])
gain <- 1 - rmse_cond / rmse_marg

per_species <- sapply(seq_len(S), function(j)
  1 - rmse(pred_cond[, j], Y[holdout, j]) / rmse(Mu[, j], Y[holdout, j]))

## ---- fig-pred ----
dfp <- data.frame(
  sp = factor(colnames(Y), levels = rev(colnames(Y))),
  marg = sapply(seq_len(S), function(j) rmse(Mu[, j], Y[holdout, j])),
  cond = sapply(seq_len(S), function(j) rmse(pred_cond[, j], Y[holdout, j])))

ggplot(dfp, aes(y = sp)) +
  geom_segment(aes(x = cond, xend = marg, yend = sp), colour = "#93a87f", linewidth = 1.1) +
  geom_point(aes(x = marg), colour = "#c9b458", size = 2.6) +
  geom_point(aes(x = cond), colour = "#275139", size = 2.6) +
  labs(x = "root mean squared error on held-out plots", y = NULL,
       title = "Conditioning on the rest of the community",
       subtitle = "Gold: environment only. Green: environment plus the other eleven species") +
  theme_te()

## ---- missing ----
set.seed(3832)
n2 <- 200L
S2 <- 4L
Sig2 <- matrix(c(1.0, 0.8, 0.2, 0.0,
                 0.8, 1.0, 0.2, 0.0,
                 0.2, 0.2, 1.0, 0.1,
                 0.0, 0.0, 0.1, 1.0), S2, S2)
B2 <- rbind(c(2, 1.0), c(2, -0.5), c(2, 0.7), c(2, 0.3))

gls_missing <- function(Yc, Xm, Sig, obs) {
  q <- 2L
  A <- matrix(0, S2 * q, S2 * q)
  b <- numeric(S2 * q)
  for (i in seq_len(nrow(Xm))) {
    o <- which(obs[i, ])
    if (!length(o)) next
    V <- solve(Sig[o, o, drop = FALSE])
    Z <- matrix(0, length(o), S2 * q)
    for (k in seq_along(o)) Z[k, ((o[k] - 1) * q + 1):(o[k] * q)] <- Xm[i, ]
    A <- A + crossprod(Z, V) %*% Z
    b <- b + crossprod(Z, V) %*% Yc[i, o]
  }
  t(matrix(solve(A, b), q, S2))
}

run_gap <- function(target, reps) {
  keep <- matrix(NA_real_, reps, 2)
  for (r in seq_len(reps)) {
    xx <- runif(n2, -2, 2)
    Xm <- cbind(1, xx)
    Yf <- Xm %*% t(B2) + matrix(rnorm(n2 * S2), n2, S2) %*% chol(Sig2)
    obs <- matrix(TRUE, n2, S2)
    obs[sample(n2, 150), target] <- FALSE
    Yc <- Yf
    Yc[!obs] <- NA
    keep[r, ] <- c(coef(lm(Yc[, target] ~ xx))[2],
                   gls_missing(Yc, Xm, Sig2, obs)[target, 2])
  }
  keep
}

k_linked <- run_gap(1L, 400L)
k_alone  <- run_gap(3L, 200L)

sd_st <- sd(k_linked[, 1]); sd_jt <- sd(k_linked[, 2])
vr_linked <- var(k_linked[, 1]) / var(k_linked[, 2])
vr_alone  <- var(k_alone[, 1]) / var(k_alone[, 2])
