# Join counts for presence-absence maps
# https://tidyecology.com/posts/join-counts-for-presence-maps/
#
# 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-08-16

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

te_paper  <- "#f5f4ee"
te_ink    <- "#16241d"
te_body   <- "#2c3a31"
te_forest <- "#275139"
te_rust   <- "#b5534e"
te_gold   <- "#c9b458"
te_line   <- "#dad9ca"

theme_datasheet <- function() {
  theme_minimal(base_size = 12) +
    theme(plot.background  = element_rect(fill = te_paper, colour = NA),
          panel.background = element_rect(fill = te_paper, colour = NA),
          panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
          panel.grid.minor = element_blank(),
          text             = element_text(colour = te_body),
          plot.title       = element_text(colour = te_ink, face = "bold"),
          plot.subtitle    = element_text(colour = te_body),
          axis.text        = element_text(colour = te_body))
}

## ---- grid ----
side   <- 20
n_cell <- side^2
cell_id <- function(r, cl) (cl - 1) * side + r

# horizontal neighbours within a row, then vertical neighbours within a column
join_from <- c(cell_id(rep(1:side, side - 1), rep(1:(side - 1), each = side)),
               cell_id(rep(1:(side - 1), side), rep(1:side, each = side - 1)))
join_to   <- c(cell_id(rep(1:side, side - 1), rep(2:side, each = side)),
               cell_id(rep(2:side, side), rep(1:side, each = side - 1)))
n_join  <- length(join_from)
deg     <- tabulate(c(join_from, join_to), n_cell)
k_pairs <- sum(deg * (deg - 1) / 2)     # pairs of joins that share a cell
deg_tab <- table(deg)

## ---- maps ----
bb_count <- function(xm) colSums(xm[join_from, , drop = FALSE] * xm[join_to, , drop = FALSE])
bw_count <- function(xm) colSums(xm[join_from, , drop = FALSE] != xm[join_to, , drop = FALSE])

smooth_rook <- function(fm, n_pass) {
  for (i in seq_len(n_pass)) {
    nb_sum <- rowsum(rbind(fm[join_to, , drop = FALSE], fm[join_from, , drop = FALSE]),
                     c(join_from, join_to), reorder = TRUE)
    fm <- (fm + nb_sum) / (1 + deg)
  }
  fm
}

make_maps <- function(n_map, n_occ, w_mix, n_pass = 2) {
  sm <- scale(smooth_rook(matrix(rnorm(n_cell * n_map), n_cell), n_pass))
  fm <- sqrt(w_mix) * sm + sqrt(1 - w_mix) * matrix(rnorm(n_cell * n_map), n_cell)
  apply(fm, 2, function(v) as.numeric(rank(-v, ties.method = "first") <= n_occ))
}

w_example <- 0.5
n_occ     <- 140
set.seed(3071)
map_a <- make_maps(1, n_occ, w_example)
bb_a  <- bb_count(map_a)
bw_a  <- bw_count(map_a)
ww_a  <- n_join - bb_a - bw_a

## ---- fig-map ----
cell_xy <- data.frame(cl = rep(1:side, each = side), rw = rep(1:side, side),
                      occ = factor(map_a[, 1], levels = c(0, 1), labels = c("empty", "occupied")))
bb_idx  <- which(map_a[join_from, 1] * map_a[join_to, 1] == 1)
seg_df  <- data.frame(x0 = cell_xy$cl[join_from[bb_idx]], y0 = cell_xy$rw[join_from[bb_idx]],
                      x1 = cell_xy$cl[join_to[bb_idx]],   y1 = cell_xy$rw[join_to[bb_idx]])

ggplot(cell_xy, aes(cl, rw)) +
  geom_tile(aes(fill = occ), colour = te_paper, linewidth = 0.4) +
  geom_segment(data = seg_df, aes(x = x0, y = y0, xend = x1, yend = y1),
               colour = te_rust, linewidth = 0.8) +
  scale_fill_manual(values = c(empty = te_line, occupied = te_forest), name = NULL) +
  coord_equal(expand = FALSE) +
  labs(x = "column", y = "row", title = "A patchy presence map",
       subtitle = "red segments: the BB joins between neighbouring occupied cells") +
  theme_datasheet() +
  theme(legend.position = "bottom", panel.grid.major = element_blank())

## ---- moments ----
join_moments <- function(n_occ, free) {
  n_emp <- n_cell - n_occ
  if (free) {
    p <- n_occ / n_cell; q <- 1 - p
    p_k  <- p^(1:4)
    p_bw <- c(2 * p * q, p * q, 4 * p^2 * q^2)
  } else {
    p_k  <- sapply(1:4, function(k) prod((n_occ - 0:(k - 1)) / (n_cell - 0:(k - 1))))
    p_bw <- c(2 * n_occ * n_emp / (n_cell * (n_cell - 1)),
              (n_occ * n_emp * (n_emp - 1) + n_emp * n_occ * (n_occ - 1)) /
                (n_cell * (n_cell - 1) * (n_cell - 2)),
              4 * n_occ * (n_occ - 1) * n_emp * (n_emp - 1) / prod(n_cell - 0:3))
  }
  n_other <- n_join^2 - n_join - 2 * k_pairs
  e_bb <- n_join * p_k[2]
  v_bb <- n_join * p_k[2] + 2 * k_pairs * p_k[3] + n_other * p_k[4] - e_bb^2
  e_bw <- n_join * p_bw[1]
  v_bw <- n_join * p_bw[1] + 2 * k_pairs * p_bw[2] + n_other * p_bw[3] - e_bw^2
  c(e_bb = e_bb, sd_bb = sqrt(v_bb), e_bw = e_bw, sd_bw = sqrt(v_bw))
}

mom_free <- join_moments(n_occ, free = TRUE)
mom_nonf <- join_moments(n_occ, free = FALSE)
z_bb_free <- (bb_a - mom_free[["e_bb"]]) / mom_free[["sd_bb"]]
z_bb_nonf <- (bb_a - mom_nonf[["e_bb"]]) / mom_nonf[["sd_bb"]]
z_bw_free <- (bw_a - mom_free[["e_bw"]]) / mom_free[["sd_bw"]]
z_bw_nonf <- (bw_a - mom_nonf[["e_bw"]]) / mom_nonf[["sd_bw"]]
sd_ratio  <- mom_free[["sd_bb"]] / mom_nonf[["sd_bb"]]

## ---- permnull ----
s0 <- 2 * n_join; s1 <- 4 * n_join; s2 <- sum((2 * deg)^2)
e_moran <- -1 / (n_cell - 1)

moran_i <- function(xm) {
  zm <- sweep(xm, 2, colMeans(xm))
  2 * colSums(zm[join_from, , drop = FALSE] * zm[join_to, , drop = FALSE]) *
    (n_cell / s0) / colSums(zm^2)
}
sd_moran_norm <- sqrt((n_cell^2 * s1 - n_cell * s2 + 3 * s0^2) /
                        ((n_cell^2 - 1) * s0^2) - e_moran^2)
sd_moran_rand <- function(n_occ) {
  x0 <- c(rep(1, n_occ), rep(0, n_cell - n_occ)) - n_occ / n_cell
  b2 <- n_cell * sum(x0^4) / sum(x0^2)^2
  nn <- n_cell
  sqrt((nn * ((nn^2 - 3 * nn + 3) * s1 - nn * s2 + 3 * s0^2) -
          b2 * ((nn^2 - nn) * s1 - 2 * nn * s2 + 6 * s0^2)) /
         ((nn - 1) * (nn - 2) * (nn - 3) * s0^2) - e_moran^2)
}

perm_null <- function(n_occ, n_perm, chunk = 5000) {
  bb_out <- numeric(0); i_out <- numeric(0)
  while (length(bb_out) < n_perm) {
    m_now <- min(chunk, n_perm - length(bb_out))
    xm  <- matrix(0, n_cell, m_now)
    pos <- replicate(m_now, sample.int(n_cell, n_occ))
    xm[cbind(as.vector(pos), rep(seq_len(m_now), each = n_occ))] <- 1
    bb_out <- c(bb_out, bb_count(xm)); i_out <- c(i_out, moran_i(xm))
  }
  list(bb = bb_out, moran = i_out)
}
perm_p <- function(obs, null_vals) (1 + sum(null_vals >= obs)) / (1 + length(null_vals))

n_perm <- 40000
set.seed(3072)
null_a <- perm_null(n_occ, n_perm)
perm_mean_bb <- mean(null_a$bb); perm_sd_bb <- sd(null_a$bb)
perm_sd_i    <- sd(null_a$moran)

i_a      <- moran_i(map_a)
z_i_norm <- (i_a - e_moran) / sd_moran_norm
z_i_rand <- (i_a - e_moran) / sd_moran_rand(n_occ)
cor_bb_i <- cor(null_a$bb, null_a$moran)
p_perm_bb_a <- perm_p(bb_a, null_a$bb)
n_above_a   <- sum(null_a$bb >= bb_a)

## ---- fig-nulls ----
null_df  <- data.frame(bb = null_a$bb)
bb_grid  <- seq(40, 150, by = 0.5)
curve_df <- rbind(
  data.frame(bb = bb_grid, dens = dnorm(bb_grid, mom_nonf[["e_bb"]], mom_nonf[["sd_bb"]]),
             model = "non free sampling"),
  data.frame(bb = bb_grid, dens = dnorm(bb_grid, mom_free[["e_bb"]], mom_free[["sd_bb"]]),
             model = "free sampling"))

ggplot(null_df, aes(bb)) +
  geom_histogram(aes(y = after_stat(density)), binwidth = 1,
                 fill = te_line, colour = NA) +
  geom_line(data = curve_df, aes(bb, dens, colour = model), linewidth = 0.9) +
  geom_vline(xintercept = bb_a, colour = te_rust, linetype = "dashed", linewidth = 0.8) +
  annotate("text", x = bb_a - 2, y = 0.055, label = "example map", hjust = 1,
           colour = te_rust, size = 3.8) +
  scale_colour_manual(values = c("non free sampling" = te_forest,
                                 "free sampling" = te_gold), name = NULL) +
  labs(x = "BB joins", y = "density",
       title = "The permutation null is the non free one",
       subtitle = "grey: 40000 random arrangements of the same 140 occupied cells") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- bernoulli ----
n_bern <- 20000
p_true <- 0.35
z_crit <- qnorm(0.95)
set.seed(3073)
bern_maps <- matrix(rbinom(n_cell * n_bern, 1, p_true), n_cell)
bern_bb   <- bb_count(bern_maps)
bern_occ  <- colSums(bern_maps)

mom_true <- join_moments(n_cell * p_true, free = TRUE)   # uses p_true directly
z_true   <- (bern_bb - mom_true[["e_bb"]]) / mom_true[["sd_bb"]]
mom_hat_free <- t(vapply(bern_occ, join_moments, numeric(4), free = TRUE))
mom_hat_nonf <- t(vapply(bern_occ, join_moments, numeric(4), free = FALSE))
z_hat_free <- (bern_bb - mom_hat_free[, "e_bb"]) / mom_hat_free[, "sd_bb"]
z_hat_nonf <- (bern_bb - mom_hat_nonf[, "e_bb"]) / mom_hat_nonf[, "sd_bb"]

rej_true <- mean(z_true >= z_crit)
rej_free <- mean(z_hat_free >= z_crit)
rej_nonf <- mean(z_hat_nonf >= z_crit)
se_rate  <- function(r, n) sqrt(r * (1 - r) / n)
sd_z_free <- sd(z_hat_free); sd_z_nonf <- sd(z_hat_nonf)

## ---- sizesweep ----
occ_grid <- c(4, 8, 12, 16, 20, 24, 30, 40, 60, 80, 100, 140, 200)
n_perm_sweep <- 40000
set.seed(3074)
size_tab <- do.call(rbind, lapply(occ_grid, function(k_occ) {
  nl <- perm_null(k_occ, n_perm_sweep)
  mn <- join_moments(k_occ, free = FALSE)
  mf <- join_moments(k_occ, free = TRUE)
  tail_prob <- sapply(0:max(nl$bb), function(v) mean(nl$bb >= v))
  cut_perm  <- which(tail_prob <= 0.05)[1] - 1
  data.frame(n_occ = k_occ,
             bb_nonfree = mean((nl$bb - mn[["e_bb"]]) / mn[["sd_bb"]] >= z_crit),
             bb_free    = mean((nl$bb - mf[["e_bb"]]) / mf[["sd_bb"]] >= z_crit),
             moran_rand = mean((nl$moran - e_moran) / sd_moran_rand(k_occ) >= z_crit),
             moran_norm = mean((nl$moran - e_moran) / sd_moran_norm >= z_crit),
             perm_level = mean(nl$bb >= cut_perm))
}))
se_size <- se_rate(0.05, n_perm_sweep)
row20   <- size_tab[size_tab$n_occ == 20, ]
row8    <- size_tab[size_tab$n_occ == 8, ]
row4    <- size_tab[size_tab$n_occ == 4, ]
row12   <- size_tab[size_tab$n_occ == 12, ]
mom8    <- join_moments(8, free = FALSE)
cut8    <- mom8[["e_bb"]] + z_crit * mom8[["sd_bb"]]
big_occ <- size_tab[size_tab$n_occ >= 60, ]

## ---- fig-size ----
size_long <- rbind(
  data.frame(n_occ = size_tab$n_occ, rate = size_tab$bb_nonfree, test = "BB, non free normal"),
  data.frame(n_occ = size_tab$n_occ, rate = size_tab$moran_rand, test = "Moran I, randomisation"),
  data.frame(n_occ = size_tab$n_occ, rate = size_tab$bb_free,    test = "BB, free normal, p estimated"),
  data.frame(n_occ = size_tab$n_occ, rate = size_tab$perm_level, test = "permutation, achieved level"))
size_long$test <- factor(size_long$test, levels = unique(size_long$test))
size_long$lw <- c(2.2, 1.4, 0.9, 0.5)[as.integer(size_long$test)]   # wider lines drawn first

ggplot(size_long, aes(n_occ, rate, colour = test)) +
  geom_hline(yintercept = 0.05, linetype = "dashed", colour = te_ink, linewidth = 0.5) +
  geom_line(aes(linewidth = lw)) +
  geom_point(size = 2) +
  scale_linewidth_identity() +
  scale_colour_manual(values = c(te_forest, te_gold, te_rust, "grey45"), name = NULL) +
  scale_x_log10(breaks = occ_grid) +
  guides(colour = guide_legend(nrow = 2)) +
  labs(x = "occupied cells (log scale)", y = "rejection rate under the null",
       title = "Sparse maps break the normal approximation",
       subtitle = "dashed: nominal five per cent; coinciding tests show as nested lines") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- lowprev ----
n_low <- 20
set.seed(3075)
null_low <- perm_null(n_low, n_perm)
mom_low  <- join_moments(n_low, free = FALSE)
pmf_low  <- as.data.frame(table(factor(null_low$bb, levels = 0:max(null_low$bb))) / n_perm)
names(pmf_low) <- c("bb", "prob")
pmf_low$bb <- as.numeric(as.character(pmf_low$bb))
cut_norm  <- mom_low[["e_bb"]] + z_crit * mom_low[["sd_bb"]]
p_zero    <- mean(null_low$bb == 0)
skew_low  <- mean((null_low$bb - mean(null_low$bb))^3) / sd(null_low$bb)^3
tail_norm <- mean(null_low$bb >= ceiling(cut_norm))

set.seed(3076)
map_low <- make_maps(1, n_low, w_example)
bb_low  <- bb_count(map_low)
z_low   <- (bb_low - mom_low[["e_bb"]]) / mom_low[["sd_bb"]]
p_norm_low <- pnorm(z_low, lower.tail = FALSE)
p_perm_low <- perm_p(bb_low, null_low$bb)

## ---- fig-lowprev ----
dens_low <- data.frame(bb = seq(-2, 9, by = 0.05))
dens_low$dens <- dnorm(dens_low$bb, mom_low[["e_bb"]], mom_low[["sd_bb"]])

ggplot(pmf_low[pmf_low$bb <= 9, ], aes(bb, prob)) +
  geom_col(fill = te_line, colour = NA, width = 0.8) +
  geom_line(data = dens_low, aes(bb, dens), colour = te_forest, linewidth = 0.9) +
  geom_vline(xintercept = cut_norm, colour = te_rust, linetype = "dashed", linewidth = 0.8) +
  scale_x_continuous(breaks = 0:9) +
  labs(x = "BB joins", y = "probability",
       title = "Twenty occupied cells: a skewed count",
       subtitle = "grey: permutation null; green: normal curve; dashed red: normal cut off") +
  theme_datasheet()

## ---- power ----
w_grid <- c(0, 0.05, 0.1, 0.15, 0.2, 0.3, 0.4, 0.5)
n_map  <- 1000
null_140 <- null_a$bb
set.seed(3077)
pow_tab <- do.call(rbind, lapply(c(n_occ, n_low), function(k_occ) {
  null_k <- if (k_occ == n_occ) null_140 else null_low$bb
  srt <- sort(null_k)
  mn <- join_moments(k_occ, free = FALSE); mf <- join_moments(k_occ, free = TRUE)
  sdr <- sd_moran_rand(k_occ)
  do.call(rbind, lapply(w_grid, function(w_now) {
    xm <- make_maps(n_map, k_occ, w_now)
    bb <- bb_count(xm); mi <- moran_i(xm)
    p_perm <- (1 + length(srt) - findInterval(bb, srt, left.open = TRUE)) / (1 + length(srt))
    data.frame(n_occ = k_occ, w_mix = w_now,
               bb_nonfree = mean((bb - mn[["e_bb"]]) / mn[["sd_bb"]] >= z_crit),
               bb_free    = mean((bb - mf[["e_bb"]]) / mf[["sd_bb"]] >= z_crit),
               moran_rand = mean((mi - e_moran) / sdr >= z_crit),
               permutation = mean(p_perm <= 0.05),
               diff_moran_bb = mean((mi - e_moran) / sdr >= z_crit) -
                 mean((bb - mn[["e_bb"]]) / mn[["sd_bb"]] >= z_crit),
               se_diff = sd(((mi - e_moran) / sdr >= z_crit) -
                 ((bb - mn[["e_bb"]]) / mn[["sd_bb"]] >= z_crit)) / sqrt(n_map))
  }))
}))
pw_hi  <- pow_tab[pow_tab$n_occ == n_occ & pow_tab$w_mix == 0.2, ]
pw_lo  <- pow_tab[pow_tab$n_occ == n_low & pow_tab$w_mix == 0.2, ]
pw_lo0 <- pow_tab[pow_tab$n_occ == n_low & pow_tab$w_mix == 0, ]
pw_hi5 <- pow_tab[pow_tab$n_occ == n_occ & pow_tab$w_mix == 0.5, ]
se_pow <- se_rate(0.5, n_map)
mf_low   <- join_moments(n_low, free = TRUE)
cut_free_low <- mf_low[["e_bb"]] + z_crit * mf_low[["sd_bb"]]
cut_perm_low <- which(sapply(0:max(null_low$bb), function(v) mean(null_low$bb >= v)) <= 0.05)[1] - 1

## ---- levelmatch ----
n_match <- 4000
set.seed(3078)
xm_match <- make_maps(n_match, n_occ, 0.2)
bb_match <- bb_count(xm_match); mi_match <- moran_i(xm_match)
sdr_140  <- sd_moran_rand(n_occ)
lev_bb_140 <- mean((null_a$bb - mom_nonf[["e_bb"]]) / mom_nonf[["sd_bb"]] >= z_crit)
lev_mi_140 <- mean((null_a$moran - e_moran) / sdr_140 >= z_crit)
srt_i   <- sort(null_a$moran)
tail_i  <- 1 - findInterval(srt_i, srt_i, left.open = TRUE) / length(srt_i)
cut_i   <- srt_i[which(tail_i <= lev_bb_140)[1]]
lev_mi_matched <- mean(null_a$moran >= cut_i)
rej_bb_m  <- (bb_match - mom_nonf[["e_bb"]]) / mom_nonf[["sd_bb"]] >= z_crit
rej_mi_z  <- (mi_match - e_moran) / sdr_140 >= z_crit
rej_mi_lm <- mi_match >= cut_i
gap_raw <- mean(rej_mi_z - rej_bb_m);  se_gap_raw <- sd(rej_mi_z - rej_bb_m) / sqrt(n_match)
gap_lm  <- mean(rej_mi_lm - rej_bb_m); se_gap_lm  <- sd(rej_mi_lm - rej_bb_m) / sqrt(n_match)

## ---- fig-power ----
pow_long <- do.call(rbind, lapply(c("bb_nonfree", "moran_rand", "bb_free", "permutation"),
  function(col) data.frame(n_occ = pow_tab$n_occ, w_mix = pow_tab$w_mix,
                           rate = pow_tab[[col]], test = col)))
pow_long$test <- factor(pow_long$test,
  levels = c("bb_nonfree", "moran_rand", "bb_free", "permutation"),
  labels = c("BB, non free normal", "Moran I, randomisation",
             "BB, free normal, p estimated", "BB permutation"))
pow_long$panel <- factor(ifelse(pow_long$n_occ == n_occ, "140 occupied cells", "20 occupied cells"),
                         levels = c("140 occupied cells", "20 occupied cells"))

ggplot(pow_long, aes(w_mix, rate, colour = test, linetype = test)) +
  geom_hline(yintercept = 0.05, linetype = "dashed", colour = te_ink, linewidth = 0.4) +
  geom_line(linewidth = 0.9) +
  geom_point(size = 1.8) +
  facet_wrap(~ panel) +
  scale_colour_manual(values = c(te_forest, te_gold, te_rust, "grey35"), name = NULL) +
  scale_linetype_manual(values = c("solid", "solid", "solid", "22"), name = NULL) +
  guides(colour = guide_legend(nrow = 2), linetype = guide_legend(nrow = 2)) +
  labs(x = "weight of the smoothed surface in the latent field", y = "rejection rate",
       title = "Power follows the variance, level follows the tail",
       subtitle = "1000 maps per point; dashed line: five per cent") +
  theme_datasheet() +
  theme(legend.position = "bottom",
        strip.text = element_text(colour = te_ink, face = "bold"))
