# Checking a spatial regression
# https://tidyecology.com/posts/checking-a-spatial-regression/
#
# 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-04

## ---- 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.ticks = element_blank(),
          legend.key.width = unit(0.35, "cm"))
}
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))
}

## ---- lattice ----
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
}
deg <- rowSums(A); D <- diag(deg); W <- A / deg
ev <- eigen(diag(1 / sqrt(deg)) %*% A %*% diag(1 / sqrt(deg)), symmetric = TRUE)$values
rho_lo <- 1 / min(ev); rho_hi <- 1 / max(ev)
set.seed(4234)
x  <- as.numeric(scale(0.8 * sin(pi * coords$col / 7) +
                       0.6 * scale(coords$row)[, 1] + rnorm(n, 0, 0.6)))
X  <- cbind(1, x); b0 <- 0.6; b1 <- 0.7; sig <- 0.5

## ---- lm-tests ----
M  <- diag(n) - X %*% solve(crossprod(X)) %*% t(X)          # OLS annihilator
Tw <- sum(diag(crossprod(W))) + sum(diag(W %*% W))          # a weights constant
lm_tests <- function(y) {
  o <- lm(y ~ x); e <- resid(o); s2 <- sum(e^2) / n
  Wy <- as.numeric(W %*% y); We <- as.numeric(W %*% e)
  fit <- as.numeric(X %*% coef(o)); WXb <- as.numeric(W %*% fit)
  LMerr <- (sum(e * We) / s2)^2 / Tw
  Draj  <- as.numeric(t(WXb) %*% M %*% WXb) / s2 + Tw
  LMlag <- (sum(e * Wy) / s2)^2 / Draj
  c(LMerr = LMerr, LMlag = LMlag)
}

## ---- lm-apply ----
set.seed(51); y_lag <- as.numeric(solve(diag(n) - 0.6 * W) %*% (X %*% c(b0, b1) + rnorm(n, 0, sig)))
set.seed(52); y_err <- as.numeric(X %*% c(b0, b1) + solve(diag(n) - 0.6 * W) %*% rnorm(n, 0, sig))
hl <- lm_tests(y_lag); he <- lm_tests(y_err)
chk_lmerr_lag <- hl["LMerr"]; chk_lmlag_lag <- hl["LMlag"]
chk_lmerr_err <- he["LMerr"]; chk_lmlag_err <- he["LMlag"]
rbind(`lag data` = round(hl, 1), `error data` = round(he, 1))

## ---- compare ----
y <- y_lag
ols <- lm(y ~ x); chk_aic_ols <- AIC(ols); chk_mi_ols <- moran_test(resid(ols), W)$I
# spatial lag
fl <- optim(c(coef(ols), 0.1, log(sd(resid(ols)))), function(p) {
  be <- p[1:2]; r <- p[3]; s2 <- exp(2 * p[4]); if (r <= rho_lo || r >= rho_hi) return(1e10)
  Ay <- y - r * (W %*% y); e <- Ay - X %*% be
  -(-n / 2 * log(2 * pi) - n / 2 * log(s2) + sum(log(1 - r * ev)) - sum(e^2) / (2 * s2))
}, method = "BFGS")
chk_aic_slm <- 2 * 4 + 2 * fl$value
chk_mi_slm  <- moran_test(as.numeric((diag(n) - fl$par[3] * W) %*% y - X %*% fl$par[1:2]), W)$I
# spatial error
fe <- optim(c(0.1, log(sd(resid(ols)))), function(p) {
  lam <- p[1]; s2 <- exp(2 * p[2]); if (lam <= rho_lo || lam >= rho_hi) return(1e10)
  B <- diag(n) - lam * W; BtB <- crossprod(B)
  be <- solve(t(X) %*% BtB %*% X, t(X) %*% BtB %*% y); e <- B %*% (y - X %*% be)
  -(-n / 2 * log(2 * pi) - n / 2 * log(s2) + sum(log(1 - lam * ev)) - sum(e^2) / (2 * s2))
}, method = "BFGS")
lam <- fe$par[1]; Bh <- diag(n) - lam * W; BtB <- crossprod(Bh)
be_e <- solve(t(X) %*% BtB %*% X, t(X) %*% BtB %*% y)
chk_aic_sem <- 2 * 4 + 2 * fe$value; chk_mi_sem <- moran_test(as.numeric(Bh %*% (y - X %*% be_e)), W)$I
# CAR
fc <- optimise(function(r) {
  if (r <= rho_lo || r >= rho_hi) return(1e10); P <- D - r * A
  be <- solve(t(X) %*% P %*% X, t(X) %*% P %*% y); e <- y - X %*% be
  t2 <- as.numeric(t(e) %*% P %*% e) / n
  -(-n / 2 * log(2 * pi) - n / 2 - n / 2 * log(t2) + 0.5 * (sum(log(deg)) + sum(log(1 - r * ev))))
}, c(rho_lo + 1e-4, rho_hi - 1e-4))
Pc <- D - fc$minimum * A; be_c <- solve(t(X) %*% Pc %*% X, t(X) %*% Pc %*% y)
chk_aic_car <- 2 * 4 + 2 * fc$objective
chk_mi_car  <- moran_test(as.numeric(chol(Pc) %*% (y - X %*% be_c)), W)$I
# MEM filter
one <- rep(1, n); Cn <- diag(n) - outer(one, one) / n
egm <- eigen(Cn %*% A %*% Cn, symmetric = TRUE); keep <- abs(egm$values) > 1e-8
E <- egm$vectors[, keep]; moE <- (n / sum(A)) * egm$values[keep]
broad <- which(moE > 0)[order(-moE[moE > 0])]
sel <- integer(0); rr <- resid(lm(y ~ x))
for (s in 1:25) { if (moran_test(rr, W)$p > 0.05) break
  cc <- abs(cor(E[, setdiff(broad[1:80], sel)], rr))
  sel <- c(sel, setdiff(broad[1:80], sel)[which.max(cc)]); rr <- resid(lm(y ~ x + E[, sel])) }
mfit <- lm(y ~ x + E[, sel]); chk_aic_mem <- AIC(mfit); chk_mi_mem <- moran_test(resid(mfit), W)$I
chk_nmem <- length(sel)
data.frame(model = c("OLS", "SLM", "SEM", "CAR", "MEM"),
           AIC = round(c(chk_aic_ols, chk_aic_slm, chk_aic_sem, chk_aic_car, chk_aic_mem), 1),
           resid_moran = round(c(chk_mi_ols, chk_mi_slm, chk_mi_sem, chk_mi_car, chk_mi_mem), 3))

## ---- fig1-compare ----
mods <- factor(c("OLS", "SLM", "SEM", "CAR", "MEM"),
               levels = c("OLS", "SLM", "SEM", "CAR", "MEM"))
d1 <- data.frame(model = mods,
                 AIC = c(chk_aic_ols, chk_aic_slm, chk_aic_sem, chk_aic_car, chk_aic_mem))
g1 <- ggplot(d1, aes(model, AIC, fill = model == "SLM")) +
  geom_col(width = 0.65) +
  scale_fill_manual(values = c(`FALSE` = "grey70", `TRUE` = "#275139")) +
  labs(title = "Model comparison by AIC", subtitle = "lower is better; SLM wins",
       x = NULL, y = "AIC") +
  theme_te() + theme(legend.position = "none",
                     panel.grid.major.y = element_line(colour = "grey92"))
d2 <- data.frame(model = mods,
                 mi = abs(c(chk_mi_ols, chk_mi_slm, chk_mi_sem, chk_mi_car, chk_mi_mem)))
g2 <- ggplot(d2, aes(model, mi, fill = model == "OLS")) +
  geom_col(width = 0.65) +
  scale_fill_manual(values = c(`FALSE` = "#275139", `TRUE` = "#b40426")) +
  labs(title = "Residual autocorrelation", subtitle = "absolute Moran's I of innovations",
       x = NULL, y = "|Moran's I|") +
  theme_te() + theme(legend.position = "none",
                     panel.grid.major.y = element_line(colour = "grey92"))
two_panel(g1, g2)

## ---- confound ----
set.seed(4235)
xs  <- as.numeric(scale(sin(pi * coords$col / 13) * cos(pi * coords$row / 11) +
                        0.15 * rnorm(n)))            # a very smooth spatial covariate
b1c <- 0.6
ys  <- b0 + b1c * xs + as.numeric(solve(diag(n) - 0.6 * W) %*% rnorm(n, 0, 0.5))
Ks  <- c(0, 10, 30, 60, 100, 150); bx <- sx <- vif <- numeric(length(Ks))
for (i in seq_along(Ks)) {
  K <- Ks[i]
  if (K == 0) { m <- lm(ys ~ xs); vif[i] <- 1 } else {
    m <- lm(ys ~ xs + E[, broad[1:K]])
    vif[i] <- 1 / (1 - summary(lm(xs ~ E[, broad[1:K]]))$r.squared)
  }
  bx[i] <- coef(m)["xs"]; sx[i] <- summary(m)$coefficients["xs", "Std. Error"]
}
chk_bx <- bx; chk_sx <- sx; chk_vif <- vif
data.frame(maps = Ks, beta_x = round(bx, 3), se = round(sx, 3), VIF = round(vif, 1))
# the real spread of the slope: refit to fresh draws of the same autocorrelated errors
Binv <- solve(diag(n) - 0.6 * W); n_mc <- 300
set.seed(4236)
sd_mc <- apply(replicate(n_mc, {
  yy <- b0 + b1c * xs + as.numeric(Binv %*% rnorm(n, 0, 0.5))
  vapply(Ks, function(K) coef(if (K == 0) lm(yy ~ xs) else lm(yy ~ xs + E[, broad[1:K]]))[["xs"]], 0)
}), 1, sd)
data.frame(maps = Ks, reported_se = round(sx, 3), real_sd = round(sd_mc, 3))

## ---- fig2-confound ----
dc <- data.frame(K = Ks, bx = bx, lo = bx - 1.96 * sx, hi = bx + 1.96 * sx)
g1 <- ggplot(dc, aes(factor(K), bx)) +
  geom_hline(yintercept = b1c, linetype = 2, colour = "grey55") +
  geom_errorbar(aes(ymin = lo, ymax = hi), width = 0.25, colour = "#275139") +
  geom_point(size = 2, colour = "#275139") +
  labs(title = "The slope loses precision", subtitle = "true value dashed at 0.6",
       x = "eigenvector maps added", y = "slope estimate") +
  theme_te() + theme(axis.text = element_text(size = 8),
                     panel.grid.major.y = element_line(colour = "grey92"))
g2 <- ggplot(data.frame(K = Ks, vif = vif), aes(factor(K), vif)) +
  geom_col(width = 0.6, fill = "#b40426") +
  labs(title = "Covariate and space overlap", subtitle = "variance inflation factor",
       x = "eigenvector maps added", y = "VIF") +
  theme_te() + theme(axis.text = element_text(size = 8),
                     panel.grid.major.y = element_line(colour = "grey92"))
two_panel(g1, g2)
