# The scale of effect in landscape data
# https://tidyecology.com/posts/the-scale-of-effect-in-landscape-data/
#
# 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

## ---- setup ----
library(terra)
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"),
          axis.text        = element_text(colour = te_body))
}

# a binary habitat map: smoothed noise, cut at a quantile to fix the cover
make_landscape <- function(range_cells, cover = 0.4, n = 400, res_m = 50) {
  r <- rast(xmin = 0, xmax = n * res_m, ymin = 0, ymax = n * res_m,
            resolution = res_m, crs = "EPSG:32634")
  values(r) <- rnorm(ncell(r))
  sm <- focal(r, focalMat(r, range_cells * res_m, "Gauss"), fun = sum,
              na.policy = "all", fillvalue = 0)
  cut_at <- global(sm, function(v, ...) quantile(v, 1 - cover, na.rm = TRUE))[1, 1]
  out <- sm > cut_at
  names(out) <- "forest"
  out
}

# proportion of forest within a circle, computed once for the whole map.
# na.rm = FALSE matters: with na.rm = TRUE a cell near the edge would be given
# the sum of a truncated circle instead of NA, which is a downward bias, not a
# missing value, and nothing downstream would notice.
cover_at <- function(land, radius_m) {
  f <- focal(land, focalMat(land, radius_m, "circle"), fun = sum,
             na.rm = FALSE, fillvalue = NA)
  names(f) <- paste0("r", radius_m)
  f
}

set.seed(20260812)
radii <- c(200, 400, 600, 800, 1000, 1400, 2000, 3000)
land  <- make_landscape(range_cells = 6)
cover <- rast(lapply(radii, function(rr) cover_at(land, rr)))

# the survey frame is inset by the widest radius, so every point has a
# complete buffer at every candidate scale
frame <- crop(land, ext(3000, 17000, 3000, 17000))
set.seed(4)
pts <- spatSample(frame, 150, "regular", as.points = TRUE, na.rm = TRUE)
X   <- terra::extract(cover, pts, ID = FALSE)
Z   <- scale(as.matrix(X))
c(points = nrow(Z), all_buffers_complete = all(complete.cases(X)))

## ---- fig-landscape ----
land_df <- as.data.frame(land, xy = TRUE)
pt_df   <- as.data.frame(crds(pts))
names(pt_df) <- c("x", "y")
focus   <- pt_df[which.min((pt_df$x - 10000)^2 + (pt_df$y - 10000)^2), ]
ring    <- do.call(rbind, lapply(c(400, 2000), function(rr) {
  th <- seq(0, 2 * pi, length.out = 200)
  data.frame(x = focus$x + rr * cos(th), y = focus$y + rr * sin(th),
             radius = factor(rr))
}))

ggplot(land_df, aes(x = x, y = y)) +
  geom_raster(aes(fill = forest)) +
  geom_point(data = pt_df, shape = 21, fill = te_gold, colour = te_ink,
             size = 1.3, stroke = 0.3) +
  geom_path(data = ring, aes(group = radius, colour = radius), linewidth = 0.8) +
  scale_fill_manual(values = c(`FALSE` = "#e6e4d6", `TRUE` = te_forest)) +
  scale_colour_manual(values = c(`400` = te_gold, `2000` = te_rust)) +
  coord_equal(expand = FALSE) +
  labs(x = NULL, y = NULL, colour = "buffer radius (m)",
       title = "Forty per cent forest, eight buffers per point") +
  theme_datasheet() +
  theme(legend.position = "bottom", axis.text = element_blank(),
        panel.grid.major = element_blank()) +
  guides(fill = "none")

## ---- correlations ----
round(cor(Z)[, c("r200", "r800", "r3000")], 2)

## ---- one-search ----
true_j    <- which(radii == 800)
beta_true <- 0.2

set.seed(77)
y <- rpois(nrow(Z), exp(1.6 + beta_true * Z[, true_j]))

aic <- vapply(seq_along(radii),
              function(j) AIC(glm(y ~ Z[, j], family = poisson)), numeric(1))
data.frame(radius_m = radii, delta_aic = round(aic - min(aic), 2))

## ---- fig-profile ----
prof <- data.frame(radius = radii, delta = aic - min(aic))

ggplot(prof, aes(x = radius, y = delta)) +
  geom_vline(xintercept = 800, linetype = "dashed", colour = te_ink) +
  geom_line(colour = te_forest, linewidth = 0.9) +
  geom_point(colour = te_forest, size = 2.4) +
  scale_x_log10(breaks = radii) +
  labs(x = "buffer radius (metres)", y = "delta AIC",
       title = "Steep flanks, and a tie where it matters") +
  theme_datasheet()

## ---- search-fn ----
search_once <- function(y, Zm) {
  a <- vapply(seq_along(radii),
              function(j) AIC(glm(y ~ Zm[, j], family = poisson)), numeric(1))
  j <- which.min(a)
  m <- glm(y ~ Zm[, j], family = poisson)
  c(radius = radii[j], p = coef(summary(m))[2, 4],
    daic = sort(a)[2] - sort(a)[1])
}
sim <- function(beta, Zm, truth_j, nsim = 300) {
  as.data.frame(t(vapply(seq_len(nsim), function(i) {
    search_once(rpois(nrow(Zm), exp(1.6 + beta * Zm[, truth_j])), Zm)
  }, numeric(3))))
}

## ---- sweep-true ----
set.seed(101)
found <- sim(beta = 0.2, Zm = Z, truth_j = true_j)
table(found$radius)
round(c(exactly_right   = mean(found$radius == 800),
        within_one_step = mean(found$radius %in% c(600, 800, 1000)),
        median_daic     = median(found$daic)), 3)

## ---- null-effect ----
set.seed(202)
null_search <- sim(beta = 0, Zm = Z, truth_j = 1)
table(null_search$radius)
mean(null_search$p < 0.05)

## ---- null-fixed ----
set.seed(202)
p_fixed <- t(vapply(seq_len(300), function(i) {
  y <- rpois(nrow(Z), exp(1.6))
  vapply(seq_along(radii),
         function(j) coef(summary(glm(y ~ Z[, j], family = poisson)))[2, 4],
         numeric(1))
}, numeric(length(radii))))
fixed_rate <- setNames(colMeans(p_fixed < 0.05), radii)
round(fixed_rate, 3)

## ---- boundary ----
null_pick <- function(Zm, cols, nsim = 300) {
  set.seed(202)
  r <- radii[cols]
  picked <- vapply(seq_len(nsim), function(i) {
    y <- rpois(nrow(Zm), exp(1.6))
    a <- vapply(cols, function(j) AIC(glm(y ~ Zm[, j], family = poisson)),
                numeric(1))
    r[which.min(a)]
  }, numeric(1))
  round(table(factor(picked, levels = r)) / nsim, 3)
}

# prediction 1: move the boundary and the pile-up moves with it
pick_full <- null_pick(Z, 1:8)
pick_mid  <- null_pick(Z, 3:6)
pick_full
pick_mid

## ---- boundary-control ----
# prediction 2: take the correlation away and the pile-up should vanish
set.seed(606)
Z_indep <- scale(matrix(rnorm(nrow(Z) * length(radii)), ncol = length(radii)))
null_pick(Z_indep, 1:8)

## ---- coarse ----
set.seed(303)
land_coarse  <- make_landscape(range_cells = 16)
cover_coarse <- rast(lapply(radii, function(rr) cover_at(land_coarse, rr)))
Xc <- terra::extract(cover_coarse, pts, ID = FALSE)
Zc <- scale(as.matrix(Xc[complete.cases(Xc), ]))

adj <- function(M) sapply(1:7, function(k) cor(M[, k], M[, k + 1]))
round(rbind(fine = adj(Z), coarse = adj(Zc)), 3)

## ---- coarse-search ----
set.seed(404)
found_coarse <- sim(beta = 0.2, Zm = Zc, truth_j = true_j)
table(found_coarse$radius)
c(fine = mean(found$radius == 800), coarse = mean(found_coarse$radius == 800))

## ---- fig-selected ----
sel <- rbind(
  data.frame(radius = found$radius,        case = "real effect, fine landscape"),
  data.frame(radius = found_coarse$radius, case = "real effect, coarse landscape"),
  data.frame(radius = null_search$radius,  case = "no effect"))
sel$case   <- factor(sel$case, levels = unique(sel$case))
sel$radius <- factor(sel$radius, levels = radii)

ggplot(sel, aes(x = radius, fill = case)) +
  geom_bar(width = 0.75) +
  facet_wrap(~ case, ncol = 1) +
  scale_fill_manual(values = c(te_forest, te_gold, te_rust)) +
  labs(x = "buffer radius selected (metres)", y = "simulations",
       title = "What the winning radius is telling you") +
  theme_datasheet() +
  theme(legend.position = "none",
        strip.text = element_text(colour = te_ink, face = "bold"))
