# Circuit theory and effective resistance
# https://tidyecology.com/posts/circuit-theory-and-effective-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-10-07

## ---- 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 ----
build_laplacian <- function(res) {
  n <- nrow(res)
  m <- ncol(res)
  idx <- matrix(seq_len(n * m), n, m)
  ii <- c(as.vector(idx[-n, ]), as.vector(idx[, -m]))
  jj <- c(as.vector(idx[-1, ]), as.vector(idx[, -1]))
  cond <- 2 / (res[ii] + res[jj])
  lap <- matrix(0, n * m, n * m)
  for (k in seq_along(ii)) {
    lap[ii[k], jj[k]] <- lap[ii[k], jj[k]] - cond[k]
    lap[jj[k], ii[k]] <- lap[jj[k], ii[k]] - cond[k]
    lap[ii[k], ii[k]] <- lap[ii[k], ii[k]] + cond[k]
    lap[jj[k], jj[k]] <- lap[jj[k], jj[k]] + cond[k]
  }
  list(lap = lap, ii = ii, jj = jj, cond = cond)
}

effective_resistance <- function(res, s, t_node) {
  g <- build_laplacian(res)
  n_all <- nrow(g$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(g$lap[keep, keep], cur[keep])
  edge_cur <- g$cond * abs(v[g$ii] - v[g$jj])
  dens <- numeric(n_all)
  for (k in seq_along(edge_cur)) {
    dens[g$ii[k]] <- dens[g$ii[k]] + edge_cur[k] / 2
    dens[g$jj[k]] <- dens[g$jj[k]] + edge_cur[k] / 2
  }
  list(r_eff = v[s] - v[t_node], density = dens)
}

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

cost_distance <- function(res, src, max_iter = 4000) {
  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
}

## ---- corridors ----
n <- 41
one <- matrix(200, n, n)
one[, 11:13] <- 1
one[1:3, ] <- 1
one[(n - 2):n, ] <- 1
two <- one
two[, 29:31] <- 1

s_node <- 2 + (2 - 1) * n
t_node <- (n - 1) + (n - 1 - 1) * n

report <- function(res, nm) {
  src <- matrix(FALSE, n, n)
  src[((s_node - 1) %% n) + 1, ((s_node - 1) %/% n) + 1] <- TRUE
  d <- cost_distance(res, src)
  e <- effective_resistance(res, s_node, t_node)
  data.frame(landscape = nm,
             least_cost = round(d[((t_node - 1) %% n) + 1,
                                  ((t_node - 1) %/% n) + 1], 2),
             effective_resistance = round(e$r_eff, 4))
}

tab_a <- rbind(report(one, "one corridor"), report(two, "two corridors"))
print(tab_a, row.names = FALSE)
cat("ratio of effective resistances:",
    round(tab_a$effective_resistance[1] / tab_a$effective_resistance[2], 4),
    " ratio of least-cost distances:",
    round(tab_a$least_cost[1] / tab_a$least_cost[2], 4), "\n")

## ---- fig-corridors ----
dens_df <- do.call(rbind, lapply(list(list(one, "one corridor"),
                                      list(two, "two corridors")),
                                 function(z) {
  e <- effective_resistance(z[[1]], s_node, t_node)
  data.frame(x = rep(seq_len(n), each = n), y = rep(seq_len(n), times = n),
             current = e$density, panel = z[[2]])
}))

ggplot(dens_df, aes(x, y, fill = pmin(current, quantile(current, 0.995)))) +
  geom_raster() +
  facet_wrap(~panel) +
  coord_equal() +
  scale_fill_gradient(low = te_pal$paper, high = te_pal$forest,
                      name = "current") +
  labs(title = "A second corridor splits the current",
       subtitle = "same endpoints, same least-cost distance of 76",
       x = NULL, y = NULL) +
  theme_te() +
  theme(axis.text = element_blank(), panel.grid = element_blank())

## ---- surface ----
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))
}

nn <- 41
qual <- smooth_field(nn, 6, seed = 474)
res_b <- 1 + 99 * (1 - qual)
s2 <- 4 + (4 - 1) * nn
t2 <- (nn - 3) + (nn - 3 - 1) * nn
e2 <- effective_resistance(res_b, s2, t2)

src2 <- matrix(FALSE, nn, nn)
src2[4, 4] <- TRUE
snk2 <- matrix(FALSE, nn, nn)
snk2[nn - 3, nn - 3] <- TRUE
corr <- cost_distance(res_b, src2) + cost_distance(res_b, snk2)
dens <- matrix(e2$density, nn, nn)
ord <- order(dens, decreasing = TRUE)

cat("effective resistance:", round(e2$r_eff, 4), "\n")
cat("share of current in the top 5 per cent of cells:",
    round(sum(dens[ord[seq_len(round(0.05 * nn * nn))]]) / sum(dens), 4),
    " in the top 20 per cent:",
    round(sum(dens[ord[seq_len(round(0.2 * nn * nn))]]) / sum(dens), 4), "\n")
cat("least-cost corridor within five per cent of the minimum covers:",
    round(mean(corr <= 1.05 * min(corr)), 4), "of the map\n")
cat("Spearman correlation, current density against negative corridor cost:",
    round(cor(as.vector(dens), -as.vector(corr), method = "spearman"), 4), "\n")

## ---- fig-surface ----
surf_df <- data.frame(x = rep(seq_len(nn), each = nn),
                      y = rep(seq_len(nn), times = nn),
                      current = as.vector(dens),
                      corridor = as.vector(corr <= 1.05 * min(corr)))

ggplot(surf_df, aes(x, y)) +
  geom_raster(aes(fill = pmin(current, quantile(current, 0.99)))) +
  geom_contour(aes(z = as.numeric(corridor)), breaks = 0.5,
               colour = te_pal$clay, linetype = "dashed", linewidth = 0.6) +
  coord_equal() +
  scale_fill_gradient(low = te_pal$paper, high = te_pal$forest,
                      name = "current") +
  labs(title = "Current spreads where alternatives exist",
       subtitle = "dashed: least-cost corridor within five per cent of the cheapest total cost",
       x = NULL, y = NULL) +
  theme_te() +
  theme(axis.text = element_blank(), panel.grid = element_blank())
