# Mantel tests in R: correlating distance matrices
# https://tidyecology.com/posts/mantel-tests-distance-correlation/
#
# 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-07

## ---- data ----
library(vegan)
library(ggplot2)
te_canvas <- theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
                   panel.background = element_rect(fill = "#f5f4ee", colour = NA))

set.seed(33)

n_sites <- 50
x <- runif(n_sites)
y <- runif(n_sites)

# moisture: west-east gradient (spatial), mild north-south, plus noise
moisture <- 60 + 25 * x + 6 * y + rnorm(n_sites, 0, 6)

# a second driver, not spatially structured and not measured.
# some species track it, so moisture explains only part of the pattern.
z <- rnorm(n_sites, 0, 1)

n_sp   <- 18
opt    <- seq(52, 98, length.out = n_sp)   # moisture optima
width  <- 10
peak   <- 18
z_load <- c(rep(0, 9), runif(9, 0.5, 1.1)) # last nine species respond to z

log_lambda <- outer(moisture, opt,
                    function(m, o) log(peak) - ((m - o)^2) / (2 * width^2)) +
  outer(z, z_load)
comm <- matrix(rpois(n_sites * n_sp, exp(log_lambda)), nrow = n_sites)
colnames(comm) <- paste0("sp", seq_len(n_sp))

## ---- fig-map ----
map_df <- data.frame(x = x, y = y, moisture = moisture)

ggplot(map_df, aes(x, y, fill = moisture)) +
  geom_point(shape = 21, size = 5, colour = "#2c3a31", stroke = 0.5) +
  scale_fill_gradient(low = "#c9b458", high = "#1d5b4e", name = "Soil\nmoisture") +
  coord_equal() +
  labs(x = "Easting (unit square)", y = "Northing (unit square)") +
  theme_minimal(base_size = 13) + te_canvas +
  theme(panel.grid.minor = element_blank(),
        text = element_text(colour = "#2c3a31"))

## ---- distances ----
comm_d <- vegdist(comm, method = "bray")   # community dissimilarity
env_d  <- dist(scale(moisture))            # environmental distance
geo_d  <- dist(cbind(x, y))                # geographic distance

## ---- simple-mantel ----
set.seed(33)
mantel(comm_d, env_d, method = "pearson", permutations = 999)

## ---- mantel-geo ----
set.seed(33)
mantel(comm_d, geo_d, method = "pearson", permutations = 999)

## ---- mantel-env-geo ----
set.seed(33)
mantel(env_d, geo_d, method = "pearson", permutations = 999)

## ---- fig-scatter ----
set.seed(33)
r_env <- mantel(comm_d, env_d, permutations = 999)$statistic
set.seed(33)
r_geo <- mantel(comm_d, geo_d, permutations = 999)$statistic

dd_long <- data.frame(
  comm = rep(as.vector(comm_d), 2),
  dist = c(as.vector(env_d), as.vector(geo_d)),
  type = rep(c(
    sprintf("community vs environment   (Mantel r = %.2f)", r_env),
    sprintf("community vs geography   (Mantel r = %.2f)", r_geo)
  ), each = length(comm_d))
)

ggplot(dd_long, aes(dist, comm)) +
  geom_point(alpha = 0.22, colour = "#275139", size = 1.2) +
  geom_smooth(method = "lm", formula = y ~ x, se = FALSE, colour = "#b5534e", linewidth = 1) +
  facet_wrap(~ type, scales = "free_x") +
  labs(x = "Pairwise distance between sites",
       y = "Community dissimilarity (Bray-Curtis)") +
  theme_minimal(base_size = 12) + te_canvas +
  theme(panel.grid.minor = element_blank(),
        strip.text = element_text(face = "bold", size = 10),
        text = element_text(colour = "#2c3a31"))

## ---- partial-env ----
set.seed(33)
pm_env <- mantel.partial(comm_d, env_d, geo_d, method = "pearson", permutations = 999)
pm_env

## ---- partial-geo ----
set.seed(33)
mantel.partial(comm_d, geo_d, env_d, method = "pearson", permutations = 999)

## ---- correlog-sim ----
# a community with a known spatial range: base R, own seed
sph_cor  <- function(h, a) ifelse(h < a, 1 - 1.5 * h / a + 0.5 * (h / a)^3, 0)
range_cg <- 0.3                               # field correlation is zero beyond this
n_cg     <- 100
opt_cg   <- seq(-2.2, 2.2, length.out = 20)   # species optima along the field

sim_patchy <- function() {
  xy <- cbind(runif(n_cg), runif(n_cg))
  h  <- as.matrix(dist(xy))
  field  <- drop(crossprod(chol(sph_cor(h, range_cg) + diag(1e-8, n_cg)), rnorm(n_cg)))
  lambda <- exp(log(15) - outer(field, opt_cg, "-")^2 / (2 * 0.7^2))
  list(xy = xy, h = h, comm = matrix(rpois(length(lambda), lambda), n_cg))
}

set.seed(1986)
patchy   <- sim_patchy()
patchy_d <- vegdist(patchy$comm, method = "bray")

set.seed(1986)
cg_vegan <- mantel.correlog(patchy_d, XY = patchy$xy, nperm = 999)
round(cg_vegan$mantel.res[1:9, ], 3)

## ---- correlog-base ----
low_cg <- lower.tri(diag(n_cg))
pair_i <- row(diag(n_cg))[low_cg]
pair_j <- col(diag(n_cg))[low_cg]

# one column of pairwise dissimilarities per permutation of the site labels
perm_dissim <- function(dmat, nperm) {
  perms <- replicate(nperm, sample.int(n_cg))
  matrix(dmat[(perms[pair_j, ] - 1) * n_cg + perms[pair_i, ]], ncol = nperm)
}

mantel_correlog_base <- function(dv, hv, dperm, n_class) {
  brk  <- seq(min(hv), max(hv), length.out = n_class + 1)
  cls  <- factor(pmax(findInterval(hv, brk, left.open = TRUE), 1), levels = seq_len(n_class))
  n_in <- tabulate(cls, n_class)
  n_pr <- length(dv)
  # Pearson r between dissimilarity and the 0/1 class matrix, sign flipped as in vegan
  r_cls  <- -(tapply(dv, cls, mean) - mean(dv)) *
    sqrt(n_in * n_pr / (n_pr - n_in)) / (sd(dv) * sqrt(n_pr - 1))
  s_obs  <- rowsum(dv, cls, reorder = TRUE)[, 1]
  s_perm <- rowsum(dperm, cls, reorder = TRUE)
  covers <- sapply(seq_len(n_class), function(k)
    length(unique(c(pair_i[cls == k], pair_j[cls == k]))) == n_cg)
  tested <- n_in > 0 & (seq_len(n_class) <= n_class %/% 2 | covers)
  p_raw  <- ifelse(r_cls > 0, rowSums(s_perm <= s_obs), rowSums(s_perm >= s_obs))
  p_raw  <- (p_raw + 1) / (ncol(dperm) + 1)
  p_raw[!tested] <- NA
  p_prog <- sapply(seq_len(n_class), function(k)
    if (tested[k]) p.adjust(p_raw[1:k], "holm")[k] else NA)
  data.frame(lo = head(brk, -1), hi = brk[-1], mid = (head(brk, -1) + brk[-1]) / 2,
             r = unname(r_cls), p_raw = unname(p_raw), p_prog = p_prog)
}

patchy_m <- as.matrix(patchy_d)
set.seed(2012)
cg_base <- mantel_correlog_base(patchy_m[low_cg], patchy$h[low_cg],
                                perm_dissim(patchy_m, 999), n_class = 14)
stopifnot(max(abs(cg_base$r - cg_vegan$mantel.res[, "Mantel.cor"]), na.rm = TRUE) < 1e-12)
cg_sig <- !is.na(cg_base$p_prog) & cg_base$p_prog <= 0.05

## ---- fig-mantel-correlog ----
cg_plot <- cg_base[!is.na(cg_base$p_prog), ]      # the classes vegan tests
cg_plot$verdict <- factor(ifelse(cg_plot$p_prog > 0.05, "not significant",
                          ifelse(cg_plot$r > 0, "more alike, p <= 0.05", "less alike, p <= 0.05")),
                          levels = c("more alike, p <= 0.05", "less alike, p <= 0.05", "not significant"))

ggplot(cg_plot, aes(mid, r)) +
  geom_hline(yintercept = 0, colour = "#dad9ca", linewidth = 0.7) +
  geom_vline(xintercept = range_cg, linetype = "22", colour = "#16241d") +
  annotate("text", x = range_cg + 0.015, y = max(cg_plot$r) * 0.98, hjust = 0,
           label = "true range of the field", colour = "#16241d", size = 3.6) +
  geom_line(colour = "#2c3a31", linewidth = 0.5) +
  geom_point(aes(fill = verdict), shape = 21, size = 3.4, colour = "#2c3a31", stroke = 0.5) +
  scale_fill_manual(values = c("more alike, p <= 0.05" = "#275139",
                               "less alike, p <= 0.05" = "#b5534e",
                               "not significant" = "#c9b458"), drop = FALSE, name = NULL) +
  scale_x_continuous(breaks = seq(0, 0.7, by = 0.1)) +
  labs(x = "Geographic distance (class midpoint)", y = "Mantel r") +
  theme_minimal(base_size = 12) + te_canvas +
  theme(panel.grid.minor = element_blank(), legend.position = "top",
        text = element_text(colour = "#2c3a31"))

## ---- correlog-zero ----
# the expected correlogram, no test involved: own seed, base R
set.seed(1926)
n_zmc <- 20000                                   # simulated pairs of sites
cg_z1 <- rnorm(n_zmc)
cg_z2 <- rnorm(n_zmc)
# counts at a site with field value f, from the same species model as sim_patchy()
cg_counts <- function(f)
  matrix(rpois(n_zmc * length(opt_cg), exp(log(15) - outer(f, opt_cg, "-")^2 / (2 * 0.7^2))), n_zmc)
cg_site1 <- cg_counts(cg_z1)

# mean Bray-Curtis dissimilarity of two sites whose field values have correlation rho
rho_grid <- seq(0, 1, by = 0.02)
bray_rho <- sapply(rho_grid, function(rho) {
  site2 <- cg_counts(rho * cg_z1 + sqrt(1 - rho^2) * cg_z2)
  mean(rowSums(abs(cg_site1 - site2)) / rowSums(cg_site1 + site2), na.rm = TRUE)
})

# the average pair: distances between random pairs of points in the unit square
h_mc   <- sqrt((runif(n_zmc * 25) - runif(n_zmc * 25))^2 + (runif(n_zmc * 25) - runif(n_zmc * 25))^2)
bray_h <- approx(rho_grid, bray_rho, sph_cor(h_mc, range_cg))$y

# first distance at which the expected dissimilarity reaches that of the average pair
h_grid <- seq(0, range_cg, by = 0.001)
h_zero <- h_grid[which.max(approx(rho_grid, bray_rho, sph_cor(h_grid, range_cg))$y >= mean(bray_h))]
round(c(unrelated_pair = bray_rho[1], average_pair = mean(bray_h),
        zero_crossing = h_zero, field_cor_there = sph_cor(h_zero, range_cg)), 3)

## ---- correlog-mc ----
where_it_stops <- function(cg) {
  sig    <- !is.na(cg$p_prog) & cg$p_prog <= 0.05
  run    <- sum(cumprod(sig & cg$r > 0))      # length of the first run of positive classes
  run_raw <- sum(cumprod(!is.na(cg$p_raw) & cg$p_raw <= 0.05 & cg$r > 0))   # same, uncorrected
  beyond <- cg$lo >= range_cg & !is.na(cg$p_prog)
  c(stop = if (run > 0) cg$hi[run] else 0, run = run,
    stop_raw = if (run_raw > 0) cg$hi[run_raw] else 0,
    neg_beyond = any(sig[beyond] & cg$r[beyond] < 0),
    pos_beyond = any(sig[beyond] & cg$r[beyond] > 0))
}

n_rep_cg <- 150
set.seed(2012)
mc_cg <- do.call(rbind, lapply(seq_len(n_rep_cg), function(i) {
  sim <- sim_patchy()
  dm  <- as.matrix(vegdist(sim$comm, method = "bray"))
  dp  <- perm_dissim(dm, 999)
  do.call(rbind, lapply(c(7, 14, 28), function(k)
    data.frame(n_class = k,
               t(where_it_stops(mantel_correlog_base(dm[low_cg], sim$h[low_cg], dp, k))))))
}))

stop_tab <- do.call(rbind, lapply(split(mc_cg, mc_cg$n_class), function(s)
  data.frame(n_class = s$n_class[1], below = mean(s$stop < range_cg),
             median_stop = median(s$stop), neg_beyond = mean(s$neg_beyond))))
stop_tab$se_below <- sqrt(stop_tab$below * (1 - stop_tab$below) / n_rep_cg)
stop_tab
stop_n <- function(k) sum(mc_cg$stop[mc_cg$n_class == k] < range_cg)
neg_n  <- function(k) sum(mc_cg$neg_beyond[mc_cg$n_class == k])
pos_n  <- function(k) sum(mc_cg$pos_beyond[mc_cg$n_class == k])
raw_n  <- function(k) sum(mc_cg$stop_raw[mc_cg$n_class == k] < range_cg)
stop_w <- split(mc_cg$stop, mc_cg$n_class)      # one value per community, same order in each class design
earlier <- sum(stop_w[["28"]] < stop_w[["14"]])
later   <- sum(stop_w[["28"]] > stop_w[["14"]])
brk7   <- seq(min(patchy$h[low_cg]), max(patchy$h[low_cg]), length.out = 8)
past7  <- with(mc_cg[mc_cg$n_class == 7, ], c(past = sum(stop >= range_cg), via_second = sum(stop >= range_cg & run == 2)))
past7

## ---- fig-correlog-stop ----
mc_cg$classes <- factor(paste(mc_cg$n_class, "classes"),
                        levels = paste(c(7, 14, 28), "classes"))
ggplot(mc_cg, aes(stop, colour = classes)) +
  geom_vline(xintercept = range_cg, linetype = "22", colour = "#16241d") +
  annotate("text", x = range_cg + 0.008, y = 0.08, hjust = 0,
           label = "true range of the field", colour = "#16241d", size = 3.6) +
  stat_ecdf(geom = "step", linewidth = 0.9) +
  scale_colour_manual(values = c("#c9b458", "#275139", "#b5534e"), name = NULL) +
  labs(x = "Distance where significant positive autocorrelation ends",
       y = "Share of simulated communities") +
  theme_minimal(base_size = 12) + te_canvas +
  theme(panel.grid.minor = element_blank(), legend.position = "top",
        text = element_text(colour = "#2c3a31"))

## ---- bioenv-search ----
data("varespec", "varechem", package = "vegan")
stopifnot(dim(varespec) == c(24, 44), dim(varechem) == c(24, 14), abs(sum(varespec) - 2417.72) < 1e-6)
env6  <- with(varechem, data.frame(logN = log(N), P, K, Ca, pH, Al))   # the ?bioenv example
env14 <- cbind(env6, varechem[, c("Mg", "S", "Fe", "Mn", "Zn", "Mo", "Baresoil", "Humdepth")])
be_d  <- vegdist(wisconsin(varespec), method = "bray")
sol6  <- bioenv(wisconsin(varespec) ~ log(N) + P + K + Ca + pH + Al, varechem)
invisible(capture.output(sol14 <- bioenv(be_d, env14)))      # silences its progress line
n_be <- nrow(varespec); low_be <- lower.tri(diag(n_be))
be_i <- row(diag(n_be))[low_be]; be_j <- col(diag(n_be))[low_be]
unit_c <- function(m) { m <- sweep(as.matrix(m), 2, colMeans(as.matrix(m))); sweep(m, 2, sqrt(colSums(m^2)), "/") }
comm_mat <- matrix(0, n_be, n_be); comm_mat[low_be] <- rank(be_d); comm_mat <- comm_mat + t(comm_mat)
# relabelling the sites permutes the pairs; Pearson on centred ranks = Spearman
perm_comm <- function(nperm) unit_c(replicate(nperm, { s <- sample.int(n_be); comm_mat[cbind(s[be_i], s[be_j])] }))
best_subset_null <- function(env, n_null, n_inner = 999, batch = 100) {
  sc <- scale(env); d2 <- (sc[be_i, , drop = FALSE] - sc[be_j, , drop = FALSE])^2
  subs <- as.matrix(expand.grid(rep(list(0:1), ncol(env))))[-1, , drop = FALSE]
  rk <- unit_c(apply(sqrt(d2 %*% t(subs)), 2, rank))          # every subset, ranked distances
  r_obs <- drop(crossprod(unit_c(rank(be_d)), rk)); win <- which.max(r_obs)
  fixed <- drop(crossprod(perm_comm(n_inner), rk[, win]))     # naive Mantel of the real winner
  nul <- do.call(rbind, lapply(split(seq_len(n_null), ceiling(seq_len(n_null) / batch)), function(ix) {
    rr <- crossprod(perm_comm(length(ix)), rk)                 # null data: rerun the whole search
    pick <- max.col(rr, ties.method = "first"); mx <- apply(rr, 1, max); cols <- unique(pick)
    inner <- crossprod(perm_comm(n_inner), rk[, cols, drop = FALSE])   # naive Mantel, fresh permutations
    hits <- colSums(inner[, match(pick, cols), drop = FALSE] >= rep(mx, each = n_inner))
    cbind(batch = ix[1], max_rho = mx, reject = (1 + hits) / (n_inner + 1) <= 0.05) }))
  by_batch <- tapply(nul[, "reject"], nul[, "batch"], mean)   # batches give the Monte Carlo error
  list(n_sub = nrow(subs), vars = colnames(env)[subs[win, ] == 1], rho = r_obs[win], fixed_rho = fixed,
       n_close = sum(r_obs >= r_obs[win] - 0.02), naive_p = (1 + sum(fixed >= r_obs[win])) / (n_inner + 1),
       n_beat = sum(nul[, "max_rho"] >= r_obs[win]), global_p = (1 + sum(nul[, "max_rho"] >= r_obs[win])) / (n_null + 1),
       type1 = mean(nul[, "reject"]), type1_se = sd(by_batch) / sqrt(length(by_batch)), n_null = n_null,
       max_rho = nul[, "max_rho"])
}
set.seed(2748); bst6  <- best_subset_null(env6, 9999)
bst14 <- best_subset_null(env14, 2000)
be_ok <- function(b, s) with(s$models[[s$whichbest]], abs(b$rho - est) < 1e-12 && identical(b$vars, s$names[best]))
stopifnot(be_ok(bst6, sol6), be_ok(bst14, sol14))            # the hand-coded search is bioenv()
mc_se <- function(p, n) sqrt(p * (1 - p) / n)
round(t(sapply(list(six = bst6, fourteen = bst14), function(b) c(subsets = b$n_sub, rho = b$rho,
  naive_p = b$naive_p, global_p = b$global_p, null_sets = b$n_null, naive_type1 = b$type1, se_type1 = b$type1_se))), 4)

## ---- fig-bioenv-null ----
null_df <- do.call(rbind, Map(function(b, lab) data.frame(rho = c(b$fixed_rho, b$max_rho), set = lab, obs = b$rho,
  what = rep(c("winning subset, held fixed", "best subset of each null search"), c(length(b$fixed_rho), b$n_null))),
  list(bst6, bst14), c("6 candidates, 63 subsets", "14 candidates, 16383 subsets")))
null_df$set <- factor(null_df$set, levels = unique(null_df$set))
ggplot(null_df, aes(rho, fill = what)) +
  geom_histogram(aes(y = after_stat(density)), binwidth = 0.02, boundary = 0, position = "identity", alpha = 0.7) +
  geom_vline(data = unique(null_df[c("set", "obs")]), aes(xintercept = obs), colour = "#b5534e", linewidth = 0.9) +
  facet_wrap(~ set) + scale_x_continuous(breaks = seq(-0.2, 0.6, by = 0.2)) +
  scale_fill_manual(values = c("winning subset, held fixed" = "#c9b458",
                               "best subset of each null search" = "#275139"), name = NULL) +
  labs(x = "Spearman Mantel rho", y = "Density") +
  theme_minimal(base_size = 12) + te_canvas +
  theme(panel.grid.minor = element_blank(), legend.position = "top", panel.spacing = unit(1.5, "lines"),
        strip.text = element_text(face = "bold", size = 10), text = element_text(colour = "#2c3a31"))
