# Moran eigenvector spatial filtering
# https://tidyecology.com/posts/moran-eigenvector-spatial-filtering/
#
# 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)
library(grid)
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE,
                      dev = "png", dev.args = list(bg = "#f5f4ee"),
                      dpi = 150, fig.width = 8, fig.height = 3.5)
theme_te <- function() {
  theme_minimal(base_size = 11) +
    theme(plot.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.grid = element_blank(),
          plot.title = element_text(face = "bold", size = 11),
          plot.subtitle = element_text(size = 9, colour = "grey30"),
          axis.text = element_blank(), axis.ticks = element_blank(),
          legend.key.width = unit(0.35, "cm"))
}
memmap <- function(coords, value, title, subtitle = NULL) {
  df <- data.frame(col = coords$col, row = coords$row, v = value)
  ggplot(df, aes(col, row, fill = v)) + geom_tile() + coord_equal() +
    scale_fill_gradient2(low = "#3b4cc0", mid = "white", high = "#b40426",
                         midpoint = 0) +
    labs(title = title, subtitle = subtitle, x = NULL, y = NULL, fill = NULL) +
    theme_te()
}
two_panel <- function(g1, g2) {
  grid.newpage(); pushViewport(viewport(layout = grid.layout(1, 2)))
  print(g1, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
  print(g2, vp = viewport(layout.pos.row = 1, layout.pos.col = 2))
}
moran_test <- function(z, W) {
  n <- length(z); z <- z - mean(z)
  S0 <- sum(W); S1 <- 0.5 * sum((W + t(W))^2)
  S2 <- sum((rowSums(W) + colSums(W))^2)
  I  <- (n / S0) * as.numeric(t(z) %*% W %*% z) / sum(z^2)
  EI <- -1 / (n - 1); b2 <- n * sum(z^4) / (sum(z^2)^2)
  VI <- (n * ((n^2 - 3 * n + 3) * S1 - n * S2 + 3 * S0^2)
         - b2 * ((n^2 - n) * S1 - 2 * n * S2 + 6 * S0^2)) /
        ((n - 1) * (n - 2) * (n - 3) * S0^2) - EI^2
  list(I = I, p = pnorm((I - EI) / sqrt(VI), lower.tail = FALSE))
}

## ---- sci-tex-helper ----
sci_tex <- function(x, digits = 2) {
  s <- formatC(x, format = "e", digits = digits)
  paste0("$", sub("e.*", "", s), " \\times 10^{", as.integer(sub(".*e", "", s)), "}$")
}

## ---- mem ----
side <- 20; n <- side * side
coords <- expand.grid(col = 1:side, row = 1:side)
A <- matrix(0, n, n)
idx <- function(r, c) (c - 1) * side + r
for (r in 1:side) for (c in 1:side) {
  i <- idx(r, c)
  if (r > 1)    A[i, idx(r - 1, c)] <- 1
  if (r < side) A[i, idx(r + 1, c)] <- 1
  if (c > 1)    A[i, idx(r, c - 1)] <- 1
  if (c < side) A[i, idx(r, c + 1)] <- 1
}
one <- rep(1, n); Cn <- diag(n) - outer(one, one) / n
eg  <- eigen(Cn %*% A %*% Cn, symmetric = TRUE)
keep <- abs(eg$values) > 1e-8
E <- eg$vectors[, keep]                       # the eigenvector maps
moranE <- (n / sum(A)) * eg$values[keep]      # Moran's I of each map
grp <- cumsum(c(TRUE, abs(diff(moranE)) > 1e-8))  # maps with tied eigenvalues share a group
broad <- which(moranE > 0)[order(-moranE[moranE > 0])]  # broad patterns first
mem_npos <- length(broad)

## ---- mem-check ----
k <- broad[1]
c(from_eigenvalue = moranE[k], from_moran_test = moran_test(E[, k], A)$I)

## ---- fig1-maps ----
kb <- broad[1]; kf <- broad[55]
two_panel(
  memmap(coords, E[, kb], "A broad-scale map",
         paste0("Moran's I = ", round(moranE[kb], 2))),
  memmap(coords, E[, kf], "A fine-scale map",
         paste0("Moran's I = ", round(moranE[kf], 2)))
)

## ---- simulate ----
set.seed(4233)
x   <- as.numeric(scale(1.1 * sin(pi * coords$col / 11) -
                        0.9 * cos(pi * coords$row / 12) + rnorm(n, 0, 0.5)))
fsp <- as.numeric(scale(1.2 * sin(pi * coords$col / 8 + 0.6) +
                        1.0 * cos(pi * coords$row / 7 - 0.4)))  # unmeasured field
b0 <- 1.4; b1_true <- 0
set.seed(20)
y <- rpois(n, exp(b0 + b1_true * x + 0.85 * fsp))
c(mean = mean(y), zeros = sum(y == 0), max = max(y))

## ---- base-glm ----
g0 <- glm(y ~ x, family = poisson)
s0 <- summary(g0)$coefficients
mem_base_b1    <- s0["x", "Estimate"]
mem_base_se    <- s0["x", "Std. Error"]
mem_base_z     <- s0["x", "z value"]
mem_base_p     <- s0["x", "Pr(>|z|)"]
mem_base_moran <- moran_test(residuals(g0, type = "pearson"), A)$I
round(c(b1 = mem_base_b1, se = mem_base_se, z = mem_base_z,
        p = mem_base_p, resid_moran = mem_base_moran), 4)

## ---- filter ----
cand <- broad[1:80]; sel <- integer(0); r <- resid(lm(y ~ x))
for (s in 1:25) {
  if (moran_test(r, A)$p > 0.05) break
  left <- setdiff(grp[cand], grp[sel])            # tied sets not yet in the model
  sc <- sapply(left, function(g) sum(crossprod(E[, grp == g, drop = FALSE], r)^2))
  sel <- c(sel, which(grp == left[which.max(sc)])) # add the whole tied set
  r <- resid(lm(y ~ x + E[, sel]))
}
gm <- glm(y ~ x + E[, sel], family = poisson)
sm <- summary(gm)$coefficients
mem_nsel      <- length(sel)
mem_filt_b1   <- sm["x", "Estimate"]
mem_filt_se   <- sm["x", "Std. Error"]
mem_filt_z    <- sm["x", "z value"]
mem_filt_p    <- sm["x", "Pr(>|z|)"]
mem_filt_moran <- moran_test(residuals(gm, type = "pearson"), A)$I
round(c(n_maps = mem_nsel, b1 = mem_filt_b1, se = mem_filt_se,
        z = mem_filt_z, p = mem_filt_p, resid_moran = mem_filt_moran), 4)

## ---- fig2-results ----
sel2 <- integer(0); rr <- resid(lm(y ~ x))
tr_moran <- moran_test(rr, A)$I
tr_p <- summary(glm(y ~ x, family = poisson))$coefficients["x", "Pr(>|z|)"]
for (g in unique(grp[sel])) {
  sel2 <- c(sel2, which(grp == g)); rr <- resid(lm(y ~ x + E[, sel2]))
  tr_moran <- c(tr_moran, moran_test(rr, A)$I)
  tr_p <- c(tr_p, summary(glm(y ~ x + E[, sel2], family = poisson))$coefficients["x", "Pr(>|z|)"])
}
steps <- c(0, cumsum(rle(grp[sel])$lengths))
g1 <- ggplot(data.frame(step = steps, moran = tr_moran), aes(step, moran)) +
  geom_hline(yintercept = 0, colour = "grey70", linetype = 2) +
  geom_line(colour = "#275139", linewidth = 0.9) +
  geom_point(colour = "#275139", size = 1.5) +
  labs(title = "Residuals whiten as maps are added",
       subtitle = "forward selection path", x = "eigenvector maps added",
       y = "residual Moran's I") +
  theme_te() + theme(axis.text = element_text(size = 8),
                     panel.grid.major.y = element_line(colour = "grey92"))
g2 <- ggplot(data.frame(step = steps, p = tr_p), aes(step, p)) +
  geom_hline(yintercept = 0.05, colour = "grey40", linetype = 2) +
  geom_line(colour = "#c98a1a", linewidth = 0.9) +
  geom_point(colour = "#c98a1a", size = 1.5) +
  annotate("text", x = max(steps) * 0.6, y = 0.09, label = "0.05",
           size = 3, colour = "grey40") +
  labs(title = "The spurious effect dies", subtitle = "covariate has no true effect",
       x = "eigenvector maps added", y = "covariate p-value") +
  theme_te() + theme(axis.text = element_text(size = 8),
                     panel.grid.major.y = element_line(colour = "grey92"))
two_panel(g1, g2)

## ---- mc ----
select_mem <- function(y, x, cand, maxK = 25) {
  sel <- integer(0); r <- resid(lm(y ~ x))
  for (s in 1:maxK) {
    if (moran_test(r, A)$p > 0.05) break
    left <- setdiff(grp[cand], grp[sel])
    sc <- sapply(left, function(g) sum(crossprod(E[, grp == g, drop = FALSE], r)^2))
    sel <- c(sel, which(grp == left[which.max(sc)])); r <- resid(lm(y ~ x + E[, sel]))
  }
  sel
}
mkx <- function(seed) { set.seed(seed)
  as.numeric(scale(1.1 * sin(pi * coords$col / 11) -
                   0.9 * cos(pi * coords$row / 12) + rnorm(n, 0, 0.5))) }
fb <- fsp                       # one unmeasured field, held fixed across replicates
B <- 300; naive <- adapt <- logical(B); nsel <- integer(B)
for (b in 1:B) {
  xb <- mkx(10000 + b); set.seed(20000 + b)
  yb <- rpois(n, exp(b0 + 0 * xb + 0.85 * fb))
  naive[b] <- summary(glm(yb ~ xb, family = poisson))$coefficients["xb", "Pr(>|z|)"] < 0.05
  se <- select_mem(yb, xb, broad[1:80]); nsel[b] <- length(se)
  adapt[b] <- summary(glm(yb ~ xb + E[, se], family = poisson))$coefficients["xb", "Pr(>|z|)"] < 0.05
}
mem_mc_naive <- mean(naive); mem_mc_adapt <- mean(adapt); mem_mc_medk <- median(nsel)
round(c(naive = mem_mc_naive, filtered = mem_mc_adapt, median_maps = mem_mc_medk), 3)
