# Conditional autoregressive (CAR) models
# https://tidyecology.com/posts/conditional-autoregressive-car-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-07

## ---- 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"))
}
tilemap <- function(df, value, title, subtitle = NULL) {
  ggplot(df, aes(col, row, fill = value)) + geom_tile() + coord_equal() +
    scale_fill_viridis_c(option = "mako", direction = -1) +
    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))
}

## ---- 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)
# eigenvalues of the row-standardised operator fix the admissible rho range
ev <- eigen(diag(1 / sqrt(deg)) %*% A %*% diag(1 / sqrt(deg)), symmetric = TRUE)$values
rho_lo <- 1 / min(ev); rho_hi <- 1 / max(ev)
c(lower = rho_lo, upper = rho_hi)

## ---- simulate ----
set.seed(4231)
cc <- scale(coords$col)[, 1]
x  <- as.numeric(scale(0.8 * cos(pi * coords$row / 7) + 0.6 * cc + rnorm(n, 0, 0.6)))
X  <- cbind(1, x)
b0 <- 0.5; b1 <- 0.7; rho <- 0.9; tau <- 0.4
Q  <- (D - rho * A) / tau^2
set.seed(11)
y  <- as.numeric(X %*% c(b0, b1) + t(chol(solve(Q))) %*% rnorm(n))

## ---- car-fit ----
nll_car <- function(r) {
  if (r <= rho_lo || r >= rho_hi) return(1e10)
  P  <- D - r * A                               # precision up to 1/tau^2
  be <- solve(t(X) %*% P %*% X, t(X) %*% P %*% y)
  e  <- y - X %*% be; t2 <- as.numeric(t(e) %*% P %*% e) / n
  ldetP <- sum(log(deg)) + sum(log(1 - r * ev)) # log|D - rho A|
  -(-n / 2 * log(2 * pi) - n / 2 - n / 2 * log(t2) + 0.5 * ldetP)
}
opt <- optimise(nll_car, c(rho_lo + 1e-4, rho_hi - 1e-4))
car_rho <- opt$minimum
P  <- D - car_rho * A
be <- solve(t(X) %*% P %*% X, t(X) %*% P %*% y)
car_b0 <- be[1]; car_b1 <- be[2]
car_tau <- sqrt(as.numeric(t(y - X %*% be) %*% P %*% (y - X %*% be)) / n)
car_ll  <- -opt$objective
round(c(rho = car_rho, tau = car_tau, b0 = car_b0, b1 = car_b1), 4)

## ---- car-symmetric ----
evA <- eigen(A, symmetric = TRUE)$values
loA <- 1 / min(evA); hiA <- 1 / max(evA)
nll_sym <- function(lam) {
  if (lam <= loA || lam >= hiA) return(1e10)
  P  <- diag(n) - lam * A
  be <- solve(t(X) %*% P %*% X, t(X) %*% P %*% y); e <- y - X %*% be
  s2 <- as.numeric(t(e) %*% P %*% e) / n
  -(-n / 2 * log(2 * pi) - n / 2 - n / 2 * log(s2) + 0.5 * sum(log(1 - lam * evA)))
}
car_sym_lambda <- optimise(nll_sym, c(loA + 1e-6, hiA - 1e-6))$minimum
round(car_sym_lambda, 4)

## ---- reach ----
centre <- idx(10, 10)
gdist  <- rep(NA_integer_, n); gdist[centre] <- 0L; step <- 0L; front <- centre
repeat {
  nb <- setdiff(unique(unlist(lapply(front, function(i) which(A[i, ] > 0)))),
                which(!is.na(gdist)))
  if (!length(nb)) break
  step <- step + 1L; gdist[nb] <- step; front <- nb
}
Ccar <- cov2cor(solve(D - 0.9 * A))[centre, ]                       # CAR reach
Wrs  <- A / deg
Csar <- cov2cor(solve(crossprod(diag(n) - 0.6 * Wrs)))[centre, ]    # SAR reach
reach <- aggregate(data.frame(CAR = Ccar, SAR = Csar), list(dist = gdist), mean)
round(head(reach, 5), 3)

## ---- fig1-reach ----
long <- data.frame(dist = rep(reach$dist, 2),
                   corr = c(reach$CAR, reach$SAR),
                   model = rep(c("CAR", "SAR"), each = nrow(reach)))
long <- long[long$dist <= 8, ]
g1 <- ggplot(long, aes(dist, corr, colour = model)) +
  geom_line(linewidth = 0.9) + geom_point(size = 1.6) +
  scale_colour_manual(values = c(CAR = "#275139", SAR = "#c98a1a")) +
  labs(title = "Correlation with the centre cell",
       subtitle = "by number of steps through the lattice",
       x = "graph distance", y = "correlation", colour = NULL) +
  theme_te() + theme(axis.text = element_text(size = 8),
                     panel.grid.major.y = element_line(colour = "grey92"),
                     legend.position = "inside", legend.position.inside = c(0.8, 0.8))
g2 <- tilemap(coords, y, "Simulated response", "covariate plus proper-CAR error, rho = 0.9")
two_panel(g1, g2)

## ---- icar ----
set.seed(4232)
truef <- as.numeric(scale(1.4 * sin(pi * coords$col / 8) * cos(pi * coords$row / 9)))
yn    <- truef + rnorm(n, 0, 1.0)          # noisy observation per cell
R_icar <- D - A                            # intrinsic precision (graph Laplacian)
# GMRF smoother S = (I + kappa R)^{-1}; choose kappa by generalised cross-validation
gcv <- function(kappa) {
  S <- solve(diag(n) + kappa * R_icar); fit <- S %*% yn
  n * sum((yn - fit)^2) / (n - sum(diag(S)))^2
}
ks <- 10^seq(-2, 2, length = 40); k_opt <- ks[which.min(sapply(ks, gcv))]
Sopt   <- solve(diag(n) + k_opt * R_icar)
fit_ic <- as.numeric(Sopt %*% yn)
icar_kappa    <- k_opt
icar_edf      <- sum(diag(Sopt))
icar_rmse_raw <- sqrt(mean((yn - truef)^2))
icar_rmse_sm  <- sqrt(mean((fit_ic - truef)^2))
round(c(kappa = icar_kappa, edf = icar_edf,
        rmse_raw = icar_rmse_raw, rmse_smooth = icar_rmse_sm), 3)

## ---- fig2-smooth ----
lim <- range(c(yn, fit_ic))
p1 <- tilemap(coords, yn, "Noisy observations", "one draw per cell") +
      scale_fill_viridis_c(option = "mako", direction = -1, limits = lim)
p2 <- tilemap(coords, fit_ic, "ICAR smoother", paste0("edf = ", round(icar_edf, 0))) +
      scale_fill_viridis_c(option = "mako", direction = -1, limits = lim)
two_panel(p1, p2)
