# Isolation by distance and by resistance
# https://tidyecology.com/posts/isolation-by-resistance/
#
# 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-14

## ---- setup ----
library(ggplot2)

te_pal <- list(forest = "#275139", green = "#2f8f63", sage = "#93a87f",
               clay = "#b5534e", gold = "#cda23f", line = "#dad9ca",
               ink = "#16241d", paper = "#f5f4ee")

theme_te <- function() {
  theme_minimal(base_size = 12) +
    theme(panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "#e7e6dc"),
          plot.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          plot.title = element_text(face = "bold", colour = te_pal$ink),
          axis.title = element_text(colour = "#2c3a31"))
}

## ---- engine ----
smooth_field <- function(n, passes, seed) {
  set.seed(seed)
  z <- matrix(runif(n * n), n, n)
  for (p in seq_len(passes)) {
    pad <- rbind(z[1, ], z, z[n, ])
    pad <- cbind(pad[, 1], pad, pad[, n])
    z <- (pad[1:n, 2:(n + 1)] + pad[3:(n + 2), 2:(n + 1)] +
            pad[2:(n + 1), 1:n] + pad[2:(n + 1), 3:(n + 2)] +
            4 * pad[2:(n + 1), 2:(n + 1)]) / 8
  }
  (z - min(z)) / (max(z) - min(z))
}

shift_mat <- function(m, dy, dx) {
  n <- nrow(m)
  nc <- ncol(m)
  out <- matrix(Inf, n, nc)
  yi <- max(1, 1 - dy):min(n, n - dy)
  xi <- max(1, 1 - dx):min(nc, nc - dx)
  out[yi, xi] <- m[yi + dy, xi + dx]
  out
}

cost_distance <- function(res, src, max_iter = 2000) {
  d <- matrix(Inf, nrow(res), ncol(res))
  d[src] <- 0
  moves <- list(c(-1, 0), c(1, 0), c(0, -1), c(0, 1))
  for (it in seq_len(max_iter)) {
    old <- d
    for (mv in moves) {
      d <- pmin(d, shift_mat(d, mv[1], mv[2]) +
                  (res + shift_mat(res, mv[1], mv[2])) / 2)
    }
    if (all(old == d)) break
  }
  d
}

build_laplacian <- function(res) {
  n <- nrow(res)
  nc <- ncol(res)
  ids <- matrix(seq_len(n * nc), n, nc)
  ii <- c(as.vector(ids[-n, ]), as.vector(ids[, -nc]))
  jj <- c(as.vector(ids[-1, ]), as.vector(ids[, -1]))
  cond <- 2 / (res[ii] + res[jj])
  lap <- matrix(0, n * nc, n * nc)
  lap[cbind(ii, jj)] <- -cond
  lap[cbind(jj, ii)] <- -cond
  diag(lap) <- -rowSums(lap)
  lap
}

resistance_all <- function(lap) {
  n_all <- nrow(lap)
  jm <- matrix(1 / n_all, n_all, n_all)
  lp <- solve(lap + jm) - jm
  dg <- diag(lp)
  outer(dg, dg, "+") - 2 * lp
}

effective_resistance <- function(lap, s, t_node) {
  n_all <- nrow(lap)
  cur <- numeric(n_all)
  cur[s] <- 1
  cur[t_node] <- -1
  keep <- setdiff(seq_len(n_all), t_node)
  v <- numeric(n_all)
  v[keep] <- solve(lap[keep, keep], cur[keep])
  v[s] - v[t_node]
}

## ---- landscape ----
n_side <- 20
quality <- smooth_field(n_side, 5, seed = 4821)
res_land <- 1 + 59 * (1 - quality)
gap_row <- 18
r_barrier <- 1000
for (rr in seq_len(n_side)) {
  band <- if (rr <= 10) c(10, 11) else c(11, 12)
  if (rr != gap_row) res_land[rr, band] <- r_barrier
}

cat("lattice:", n_side, "by", n_side, "=", n_side * n_side, "demes\n")
cat("habitat resistance range:",
    round(range(res_land[res_land < r_barrier]), 2),
    " barrier resistance:", r_barrier,
    " barrier cells:", sum(res_land == r_barrier),
    " open row in the barrier:", gap_row, "\n")

## ---- migration ----
n_node <- n_side * n_side
ids <- matrix(seq_len(n_node), n_side, n_side)

neighbour_set <- function(dy, dx) {
  yy <- row(ids) + dy
  xx <- col(ids) + dx
  inside <- (yy >= 1) & (yy <= n_side) & (xx >= 1) & (xx <= n_side)
  list(id = as.vector(ids[cbind(as.vector(pmin(pmax(yy, 1), n_side)),
                                as.vector(pmin(pmax(xx, 1), n_side)))]),
       inside = as.vector(inside))
}

nbr <- lapply(list(c(-1, 0), c(1, 0), c(0, -1), c(0, 1)),
              function(v) neighbour_set(v[1], v[2]))
res_vec <- as.vector(res_land)
cond_dir <- lapply(nbr, function(b)
  ifelse(b$inside, 2 / (res_vec + res_vec[b$id]), 0))
cond_tot <- Reduce(`+`, cond_dir)
m_scale <- 0.5 / max(cond_tot)
mig_dir <- lapply(cond_dir, function(x) x * m_scale)
mig_stay <- 1 - cond_tot * m_scale
n_dip <- 50

cat("total emigration rate per deme: max", round(max(1 - mig_stay), 4),
    " mean", round(mean(1 - mig_stay), 4),
    " min", round(min(1 - mig_stay), 6), "\n")
cat("migrants per generation Nm: lattice mean",
    round(n_dip * mean(1 - mig_stay), 3),
    " most isolated deme", round(n_dip * min(1 - mig_stay), 4), "\n")

## ---- simulate ----
n_loci <- 60
gens <- 2500
cat("diploids per deme:", n_dip, " loci:", n_loci, " generations:", gens,
    " diploids on the lattice:", n_dip * n_node, "\n")
set.seed(4822)
p_frq <- matrix(0.5, n_node, n_loci)
for (g in seq_len(gens)) {
  p_mig <- mig_stay * p_frq
  for (k in seq_along(nbr)) p_mig <- p_mig + mig_dir[[k]] * p_frq[nbr[[k]]$id, ]
  p_frq <- matrix(rbinom(length(p_mig), 2 * n_dip,
                         pmin(pmax(as.vector(p_mig), 0), 1)),
                  n_node, n_loci) / (2 * n_dip)
}

fixed_locus <- apply(p_frq, 2, function(x) max(x) < 1e-12 || min(x) > 1 - 1e-12)
p_keep <- p_frq[, !fixed_locus, drop = FALSE]
cat("loci monomorphic across the whole lattice:", sum(fixed_locus),
    " loci kept:", ncol(p_keep), "\n")
cat("lattice-wide allele frequency, range over kept loci:",
    round(range(colMeans(p_keep)), 4), "\n")

## ---- sites-fst ----
sites <- data.frame(
  x = c(3, 7, 2, 6, 3, 8, 5, 15, 19, 14, 18, 15, 19, 16),
  y = c(2, 5, 9, 12, 16, 19, 8, 3, 6, 10, 13, 17, 20, 7))
sites$side <- ifelse(sites$x <= 10, "west", "east")
sites$node <- (sites$x - 1) * n_side + sites$y
prs <- t(combn(nrow(sites), 2))

pair_fst <- function(pa, pb) {
  p_bar <- (pa + pb) / 2
  hs <- (2 * pa * (1 - pa) + 2 * pb * (1 - pb)) / 2
  ht <- 2 * p_bar * (1 - p_bar)
  sum(ht - hs) / sum(ht)
}

gen <- data.frame(a = prs[, 1], b = prs[, 2])
gen$fst <- apply(prs, 1, function(k)
  pair_fst(p_keep[sites$node[k[1]], ], p_keep[sites$node[k[2]], ]))
gen$lin <- gen$fst / (1 - gen$fst)
gen$crosses <- sites$side[gen$a] != sites$side[gen$b]

cat("sampled demes:", nrow(sites), " west", sum(sites$side == "west"),
    " east", sum(sites$side == "east"), " pairs", nrow(gen),
    " crossing the barrier", sum(gen$crosses),
    " pairs containing any one deme:", nrow(sites) - 1, "\n")
cat("pairwise Fst: min", round(min(gen$fst), 4),
    " median", round(median(gen$fst), 4),
    " max", round(max(gen$fst), 4), "\n")

## ---- distances ----
gen$euclid <- sqrt((sites$x[gen$a] - sites$x[gen$b])^2 +
                     (sites$y[gen$a] - sites$y[gen$b])^2)

lcp_cols <- sapply(seq_len(nrow(sites)), function(k) {
  src <- matrix(FALSE, n_side, n_side)
  src[sites$y[k], sites$x[k]] <- TRUE
  cost_distance(res_land, src)[cbind(sites$y, sites$x)]
})
gen$leastcost <- lcp_cols[cbind(gen$a, gen$b)]

lap <- build_laplacian(res_land)
r_all <- resistance_all(lap)
gen$resist <- r_all[cbind(sites$node[gen$a], sites$node[gen$b])]

chk <- effective_resistance(lap, sites$node[1], sites$node[14])
r_absdiff <- signif(abs(r_all[sites$node[1], sites$node[14]] - chk), 3)
cat("resistance between sites 1 and 14: pseudo-inverse",
    round(r_all[sites$node[1], sites$node[14]], 6),
    " single-pair solve:", round(chk, 6),
    " absolute difference:",
    r_absdiff, "\n")
cat("Euclidean range:", round(range(gen$euclid), 2),
    " least-cost range:", round(range(gen$leastcost), 1),
    " resistance range:", round(range(gen$resist), 2), "\n")

## ---- fig-landscape ----
land_df <- data.frame(x = rep(seq_len(n_side), each = n_side),
                      y = rep(seq_len(n_side), times = n_side),
                      resistance = as.vector(res_land))

ggplot(land_df, aes(x, y)) +
  geom_raster(aes(fill = pmin(resistance, 60))) +
  geom_tile(data = subset(land_df, resistance > 60), fill = te_pal$ink) +
  geom_point(data = sites, aes(x, y), colour = "white", size = 4.2) +
  geom_point(data = sites, aes(x, y, colour = side), size = 2.6) +
  coord_equal() +
  scale_fill_gradient(low = te_pal$paper, high = te_pal$green,
                      name = "resistance") +
  scale_colour_manual(values = c(west = te_pal$gold, east = te_pal$clay),
                      name = "side") +
  labs(title = "One barrier with one gap",
       subtitle = "habitat resistance 1 to 60, barrier cells in black, row 18 open",
       x = NULL, y = NULL) +
  theme_te() +
  theme(panel.grid = element_blank())

## ---- compare ----
metrics <- c("euclid", "leastcost", "resist")
fit_tab <- data.frame(
  distance = c("Euclidean", "least-cost", "resistance"),
  correlation = round(as.numeric(sapply(metrics, function(v)
    cor(gen[[v]], gen$lin))), 4),
  r_squared = round(as.numeric(sapply(metrics, function(v)
    summary(lm(gen$lin ~ gen[[v]]))$r.squared)), 4))
print(fit_tab, row.names = FALSE)

cat("correlations among the distances themselves: Euclidean and least-cost",
    round(cor(gen$euclid, gen$leastcost), 4),
    " Euclidean and resistance", round(cor(gen$euclid, gen$resist), 4),
    " least-cost and resistance", round(cor(gen$leastcost, gen$resist), 4),
    "\n")

## ---- fig-fits ----
long_names <- c(euclid = "Euclidean distance",
                leastcost = "Least-cost distance",
                resist = "Resistance distance")
fit_df <- do.call(rbind, lapply(metrics, function(v) {
  mod <- lm(gen$lin ~ gen[[v]])
  xs <- seq(min(gen[[v]]), max(gen[[v]]), length.out = 50)
  data.frame(distance = xs,
             lin = coef(mod)[[1]] + coef(mod)[[2]] * xs,
             panel = long_names[[v]])
}))
pts_df <- do.call(rbind, lapply(metrics, function(v)
  data.frame(distance = gen[[v]], lin = gen$lin,
             pair = ifelse(gen$crosses, "crosses the barrier", "same side"),
             panel = long_names[[v]])))

ggplot(pts_df, aes(distance, lin)) +
  geom_line(data = fit_df, colour = "grey45", linewidth = 0.8) +
  geom_point(aes(colour = pair), size = 1.9, alpha = 0.9) +
  facet_wrap(~panel, scales = "free_x") +
  scale_colour_manual(values = c(`crosses the barrier` = te_pal$clay,
                                 `same side` = te_pal$forest), name = NULL) +
  labs(title = "Same genetic data, three horizontal axes",
       subtitle = "91 pairs from 14 demes, grey line fitted to all pairs in the panel",
       x = "between-site distance", y = "Fst / (1 - Fst)") +
  theme_te() +
  theme(legend.position = "bottom")

## ---- barrier-split ----
win_lo <- 8
win_hi <- 16
win <- gen$euclid >= win_lo & gen$euclid <= win_hi
cat("Euclidean window used for the matched comparison:", win_lo, "to", win_hi,
    "cells\n")
split_tab <- data.frame(
  pairs = c("crossing the barrier", "same side"),
  n = c(sum(win & gen$crosses), sum(win & !gen$crosses)),
  mean_euclid = round(c(mean(gen$euclid[win & gen$crosses]),
                        mean(gen$euclid[win & !gen$crosses])), 2),
  mean_resist = round(c(mean(gen$resist[win & gen$crosses]),
                        mean(gen$resist[win & !gen$crosses])), 1),
  mean_lin_fst = round(c(mean(gen$lin[win & gen$crosses]),
                         mean(gen$lin[win & !gen$crosses])), 4))
print(split_tab, row.names = FALSE)

cat("Euclidean distance, overlap of the two groups: barrier pairs from",
    round(min(gen$euclid[gen$crosses]), 2), "and same-side pairs up to",
    round(max(gen$euclid[!gen$crosses]), 2), "\n")
cat("resistance distance, same comparison: barrier pairs from",
    round(min(gen$resist[gen$crosses]), 2), "and same-side pairs up to",
    round(max(gen$resist[!gen$crosses]), 2), "\n")

res_e <- residuals(lm(lin ~ euclid, data = gen))
res_r <- residuals(lm(lin ~ resist, data = gen))
cat("mean residual from the Euclidean fit: barrier pairs",
    round(mean(res_e[gen$crosses]), 4), " same side",
    round(mean(res_e[!gen$crosses]), 4), "\n")
cat("mean residual from the resistance fit: barrier pairs",
    round(mean(res_r[gen$crosses]), 4), " same side",
    round(mean(res_r[!gen$crosses]), 4), "\n")

## ---- fig-collinear ----
coll_df <- data.frame(euclid = gen$euclid, resist = gen$resist,
                      pair = ifelse(gen$crosses, "crosses the barrier",
                                    "same side"))

ggplot(coll_df, aes(euclid, resist, colour = pair)) +
  geom_point(size = 2.2, alpha = 0.9) +
  scale_colour_manual(values = c(`crosses the barrier` = te_pal$clay,
                                 `same side` = te_pal$forest), name = NULL) +
  labs(title = "The barrier is invisible on the horizontal axis",
       subtitle = "same 91 pairs, resistance distance against straight-line distance",
       x = "Euclidean distance in cells", y = "resistance distance") +
  theme_te() +
  theme(legend.position = "bottom")

## ---- locus-blocks ----
block_tab <- do.call(rbind, lapply(1:3, function(bk) {
  cols <- seq(bk, ncol(p_keep), by = 3)
  p_sub <- p_keep[, cols, drop = FALSE]
  fst_b <- apply(prs, 1, function(k)
    pair_fst(p_sub[sites$node[k[1]], ], p_sub[sites$node[k[2]], ]))
  lin_b <- fst_b / (1 - fst_b)
  data.frame(block = bk, loci = length(cols),
             euclidean = round(summary(lm(lin_b ~ gen$euclid))$r.squared, 4),
             least_cost = round(summary(lm(lin_b ~ gen$leastcost))$r.squared, 4),
             resistance = round(summary(lm(lin_b ~ gen$resist))$r.squared, 4))
}))
print(block_tab, row.names = FALSE)
