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

## ---- engine ----
nb_moore <- list(c(-1,-1), c(-1,0), c(-1,1), c(0,-1), c(0,1), c(1,-1), c(1,0), c(1,1))
nb_vn    <- list(c(-1,0), c(0,-1), c(0,1), c(1,0))

neighbours <- function(n, nb, torus = TRUE) {
  rr <- rep(seq_len(n), times = n); cc <- rep(seq_len(n), each = n)
  out <- matrix(NA_integer_, n * n, length(nb))
  for (j in seq_along(nb)) {
    r <- rr + nb[[j]][1]; c <- cc + nb[[j]][2]
    if (torus) {
      out[, j] <- ((c - 1) %% n) * n + ((r - 1) %% n) + 1
    } else {
      ok <- r >= 1 & r <= n & c >= 1 & c <= n
      out[ok, j] <- (c[ok] - 1) * n + r[ok]
    }
  }
  out
}

pay_of <- function(z, nC, deg, A, self) {
  if (self) { nC <- nC + z; deg <- deg + 1 }
  ifelse(z == 1, A[1,1] * nC + A[1,2] * (deg - nC),
                 A[2,1] * nC + A[2,2] * (deg - nC))
}

run_game <- function(n = 50, A, p0 = 0.9, gens = 150, seed = 1, nb = nb_moore,
                     torus = TRUE, self = FALSE, async = FALSE) {
  set.seed(seed)
  NI  <- neighbours(n, nb, torus)
  N   <- n * n
  deg <- rowSums(!is.na(NI))
  S   <- rbinom(N, 1, p0)
  count <- function(S) vapply(seq_len(N), function(i) {
    j <- NI[i, ]; sum(S[j[!is.na(j)]]) }, numeric(1))
  nC  <- count(S)
  fc  <- numeric(gens + 1); fc[1] <- mean(S)
  for (g in seq_len(gens)) {
    if (!async) {
      P    <- pay_of(S, nC, deg, A, self)
      cand <- cbind(P, matrix(P[NI], N, ncol(NI)))
      cs   <- cbind(S, matrix(S[NI], N, ncol(NI)))
      cand[is.na(cand)] <- -Inf
      S  <- cs[cbind(seq_len(N), max.col(cand, ties.method = "first"))]
      nC <- count(S)
    } else {
      for (i in sample.int(N)) {
        j   <- NI[i, ]; j <- j[!is.na(j)]
        set <- c(i, j)
        new <- S[set][which.max(pay_of(S[set], nC[set], deg[set], A, self))]
        if (new != S[i]) { nC[j] <- nC[j] + (new - S[i]); S[i] <- new }
      }
    }
    fc[g + 1] <- mean(S)
  }
  list(S = matrix(S, n, n), fc = fc)
}

pd        <- function(b) matrix(c(1, b, 0, 0), 2, 2)
snowdrift <- function(b, cost) matrix(c(b - cost/2, b, b - cost, 0), 2, 2)
xstar     <- function(M) (M[2,2] - M[1,2]) / (M[1,1] - M[1,2] - M[2,1] + M[2,2])
tail_mean <- function(r, k = 50) mean(tail(r$fc, k))

baseline_50 <- tail_mean(run_game(A = pd(1.45)))
cat("baseline, 50 by 50, temptation 1.45:", round(baseline_50, 4), "\n")

## ---- async ----
for (b in c(1.15, 1.45, 1.65)) {
  s <- mean(sapply(1:3, function(sd) tail_mean(run_game(A = pd(b), seed = sd))))
  a <- mean(sapply(1:3, function(sd) tail_mean(run_game(A = pd(b), seed = sd, async = TRUE))))
  cat(sprintf("temptation %.2f   synchronous %.4f   asynchronous %.4f\n", b, s, a))
}

## ---- fig-variants ----
library(ggplot2)
te_canvas <- theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
                   panel.background = element_rect(fill = "#f5f4ee", colour = NA))
variants <- list(
  `Moore, torus`         = list(nb = nb_moore, torus = TRUE,  self = FALSE),
  `von Neumann, torus`   = list(nb = nb_vn,    torus = TRUE,  self = FALSE),
  `Moore, fixed edges`   = list(nb = nb_moore, torus = FALSE, self = FALSE),
  `Moore, self included` = list(nb = nb_moore, torus = TRUE,  self = TRUE))

grid <- do.call(rbind, lapply(names(variants), function(nm) {
  v <- variants[[nm]]
  do.call(rbind, lapply(c(1.15, 1.45, 1.65), function(b) {
    fc <- mean(sapply(1:3, function(sd) tail_mean(
      run_game(A = pd(b), seed = sd, nb = v$nb, torus = v$torus, self = v$self))))
    data.frame(variant = nm, b = b, fc = fc)
  }))
}))
wide <- reshape(grid, idvar = "variant", timevar = "b", direction = "wide")
wide[-1] <- round(wide[-1], 4)
print(wide, row.names = FALSE)

ggplot(grid, aes(factor(b), fc, fill = variant)) +
  geom_col(position = position_dodge(width = 0.8), width = 0.72) +
  scale_fill_manual(values = c(`Moore, torus` = "#275139",
                               `von Neumann, torus` = "#b5534e",
                               `Moore, fixed edges` = "#93a87f",
                               `Moore, self included` = "#2f4858")) +
  ylim(0, 1) +
  labs(x = "Temptation to defect (b)", y = "Fraction cooperating", fill = NULL) +
  theme_minimal(base_size = 12) + te_canvas +
  theme(legend.position = "top", legend.text = element_text(size = 8.5))

## ---- seeds ----
for (b in c(1.45, 1.65)) {
  v <- sapply(1:10, function(sd) tail_mean(run_game(A = pd(b), seed = sd)))
  cat(sprintf("temptation %.2f   mean %.4f   sd %.4f   range %.4f to %.4f\n",
              b, mean(v), sd(v), min(v), max(v)))
}

## ---- snow ----
for (cost in c(0.3, 0.5, 0.7, 0.9)) {
  A  <- snowdrift(1, cost)
  m8 <- mean(sapply(1:3, function(sd) tail_mean(run_game(A = A, seed = sd))))
  m4 <- mean(sapply(1:3, function(sd) tail_mean(run_game(A = A, seed = sd, nb = nb_vn))))
  cat(sprintf("cost %.1f   well-mixed %.4f   eight neighbours %.4f   four neighbours %.4f\n",
              cost, xstar(A), m8, m4))
}
