# Model-based unconstrained ordination
# https://tidyecology.com/posts/model-based-unconstrained-ordination/
#
# 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(MASS)
library(ggplot2)

te_ink   <- "#16241d"; te_body <- "#2c3a31"; te_green <- "#275139"
te_label <- "#46604a"; te_sage <- "#93a87f"; te_paper <- "#f5f4ee"
te_line  <- "#dad9ca"; te_faint <- "#5d6b61"; te_warm <- "#b5534e"; te_gold <- "#c9b458"
theme_te <- function() {
  theme_minimal(base_size = 12) +
    theme(panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "#dad9ca", linewidth = 0.3),
          axis.title = element_text(colour = "#2c3a31"),
          axis.text  = element_text(colour = "#5d6b61"),
          plot.title = element_text(colour = "#16241d", face = "bold", size = 13),
          plot.subtitle = element_text(colour = "#46604a", size = 10),
          strip.text = element_text(colour = "#275139", face = "bold"),
          legend.title = element_text(colour = "#2c3a31"),
          legend.text  = element_text(colour = "#46604a"),
          plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA))
}

## ---- data ----
set.seed(4223)
n <- 60; S <- 25
z <- runif(n, -2, 2)                          # true latent gradient (unknown to the methods)
b0     <- sort(rnorm(S, mean = log(c(rep(16,6), rep(5,7), rep(1.6,7), rep(0.7,5))), sd = 0.2),
               decreasing = TRUE)
lambda <- c(rnorm(6, 0, 0.05), rnorm(7, 0, 0.5), rnorm(7, 0, 1.1), rnorm(5, 0, 1.3))
theta_true <- 1.5
samp <- rnorm(n, 0, 0.6)                       # sampling intensity, uncorrelated with z

eta <- outer(rep(1,n), b0) + outer(z, lambda) + outer(samp, rep(1,S))
Y   <- matrix(rnbinom(n * S, mu = as.vector(exp(eta)), size = theta_true), n, S)
colnames(Y) <- paste0("sp", 1:S)
c(total = sum(Y), min_rowsum = min(rowSums(Y)), max_rowsum = max(rowSums(Y)))

## ---- nmds ----
bray <- function(M) { n <- nrow(M); D <- matrix(0, n, n)
  for (i in 1:(n-1)) for (j in (i+1):n) {
    d <- sum(abs(M[i,] - M[j,])) / sum(M[i,] + M[j,]); D[i,j] <- D[j,i] <- d }; D }
Dbc <- bray(Y)

nmds <- function(D, k = 2, maxit = 300, seed = 1) {
  set.seed(seed); n <- nrow(D)
  X <- scale(cmdscale(D, k), scale = FALSE)
  low <- lower.tri(D); Dl <- D[low]; o <- order(Dl); Sprev <- Inf; Sval <- NA
  for (it in 1:maxit) {
    dx <- as.matrix(dist(X)); dl <- dx[low]
    iso <- isoreg(dl[o])$yf; dhat <- numeric(length(dl)); dhat[o] <- iso
    Sval <- sqrt(sum((dl - dhat)^2) / sum(dl^2))
    Dh <- matrix(0, n, n); Dh[low] <- dhat; Dh <- Dh + t(Dh)
    B <- matrix(0, n, n); nz <- dx > 1e-9; B[nz] <- -Dh[nz] / dx[nz]; diag(B) <- -rowSums(B)
    X <- scale((1/n) * B %*% X, scale = FALSE)
    if (abs(Sprev - Sval) < 1e-7) break; Sprev <- Sval
  }
  list(points = X, stress = Sval)
}
mds <- nmds(Dbc, k = 2, seed = 7)
db1 <- mds$points[,1]; db2 <- mds$points[,2]
mds_stress <- mds$stress
round(mds_stress, 3)

## ---- modelbased ----
long <- data.frame(count = as.vector(Y),
                   site  = factor(rep(1:n, times = S)),
                   sp    = factor(rep(1:S, each = n)))
fit    <- glm.nb(count ~ site + sp, data = long)   # site total + species mean, removed
mu_hat <- fitted(fit); th_hat <- fit$theta

ds_resid <- function(y, mu, theta, u) {
  a <- pnbinom(y - 1, mu = mu, size = theta)
  b <- pnbinom(y,     mu = mu, size = theta)
  qnorm(a + u * (b - a))
}
set.seed(99)
R  <- matrix(ds_resid(long$count, mu_hat, th_hat, runif(nrow(long))), n, S)
sv <- svd(scale(R, center = TRUE, scale = FALSE))
mb1 <- sv$u[,1] * sv$d[1]; mb2 <- sv$u[,2] * sv$d[2]
round(th_hat, 2)

## ---- recovery ----
cor_mb <- abs(cor(mb1, z)); cor_db <- abs(cor(db1, z))
lrs <- log(rowSums(Y))
cor_mb_tot <- abs(cor(mb1, lrs)); cor_db_tot <- abs(cor(db1, lrs))
c(mb_vs_z = round(cor_mb,3), nmds_vs_z = round(cor_db,3),
  mb_vs_total = round(cor_mb_tot,3), nmds_vs_total = round(cor_db_tot,3))

## ---- fig-recovery ----
mb1s <- if (cor(mb1, z) < 0) -mb1 else mb1
db1s <- if (cor(db1, z) < 0) -db1 else db1
df <- rbind(data.frame(z = z, axis = scale(mb1s)[,1], method = sprintf("model-based (|r| = %.2f)", cor_mb)),
            data.frame(z = z, axis = scale(db1s)[,1], method = sprintf("distance NMDS (|r| = %.2f)", cor_db)))
ggplot(df, aes(z, axis, colour = method)) +
  geom_point(size = 2) + geom_smooth(method = "lm", formula = y ~ x, se = FALSE, linewidth = 0.6) +
  scale_colour_manual(values = c(te_green, te_warm)) +
  labs(title = "Recovering a latent gradient",
       x = "true latent gradient z", y = "ordination axis 1 (standardised)") + theme_te() + theme(legend.title = element_blank())

## ---- fig-space ----
op <- rbind(data.frame(a1 = mb1s, a2 = scale(mb2, scale = FALSE)[,1], z = z, panel = "model-based"),
            data.frame(a1 = db1s, a2 = db2, z = z, panel = "distance NMDS"))
ggplot(op, aes(a1, a2, colour = z)) + geom_point(size = 2.4) +
  facet_wrap(~panel, scales = "free") +
  scale_colour_gradient(low = te_gold, high = te_green) +
  labs(title = "Sites in ordination space, coloured by the true gradient",
       x = "axis 1", y = "axis 2") + theme_te()
