# Taylor’s power law and how many quadrats
# https://tidyecology.com/posts/taylors-power-law-and-sample-size/
#
# 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_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))
}

## ---- generator ----
rcount <- function(nq, M, a, b) {
  vtarget <- a * M^b
  if (vtarget <= M * 1.000001) return(rpois(nq, M))
  rnbinom(nq, mu = M, size = M^2 / (vtarget - M))
}

fit_law <- function(counts) {
  m  <- colMeans(counts)
  v  <- apply(counts, 2, var)
  ok <- m > 0 & v > 0
  f  <- lm(log(v[ok]) ~ log(m[ok]))
  c(a = unname(exp(coef(f)[1])), b = unname(coef(f)[2]), sites = sum(ok))
}

M_site <- exp(seq(log(0.4), log(45), length.out = 40))
n_q    <- 25
a_true <- 2.4
b_true <- 1.55

set.seed(20260813)
counts_pois <- sapply(M_site, function(m) rpois(n_q, m))
set.seed(20260813)
counts_clus <- sapply(M_site, function(m) rcount(n_q, m, a_true, b_true))

law_pois <- fit_law(counts_pois)
law_clus <- fit_law(counts_clus)
round(rbind(Poisson = law_pois, clustered = law_clus), 3)

## ---- fig-law ----
law_df <- rbind(
  data.frame(mean_count = colMeans(counts_pois),
             variance   = apply(counts_pois, 2, var), counts = "independent"),
  data.frame(mean_count = colMeans(counts_clus),
             variance   = apply(counts_clus, 2, var), counts = "clustered"))
law_df$counts <- factor(law_df$counts, levels = c("clustered", "independent"))

ggplot(law_df, aes(mean_count, variance, colour = counts)) +
  geom_abline(slope = 1, intercept = 0, linetype = "dashed", colour = te_body) +
  geom_point(size = 2.2) +
  geom_abline(slope = law_clus["b"], intercept = log10(law_clus["a"]),
              colour = te_rust, linewidth = 0.9) +
  geom_abline(slope = law_pois["b"], intercept = log10(law_pois["a"]),
              colour = te_forest, linewidth = 0.9) +
  scale_x_log10() + scale_y_log10() +
  scale_colour_manual(values = c(te_rust, te_forest)) +
  labs(x = "mean count per quadrat", y = "variance across quadrats",
       colour = NULL, title = "One slope, and the null it is measured against") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- cost ----
n_quadrats <- function(M, a, b, rse) a * M^(b - 2) / rse^2

rse_target <- 0.20
M_check    <- c(0.5, 2, 10, 40)
n_rep      <- 4000
mc_se      <- rse_target / sqrt(2 * (n_rep - 1))

set.seed(4747)
cost_tab <- do.call(rbind, lapply(M_check, function(m) {
  nq     <- ceiling(n_quadrats(m, a_true, b_true, rse_target))
  survey <- replicate(n_rep, mean(rcount(nq, m, a_true, b_true)))
  data.frame(mean_count  = m,
             quadrats    = nq,
             formula_rse = sqrt(a_true * m^(b_true - 2) / nq),
             simulated_rse = sd(survey) / m)
}))
print(cost_tab, row.names = FALSE, digits = 3)

## ---- fig-cost ----
b_grid <- c(1, b_true, 2)
M_grid <- exp(seq(log(0.2), log(50), length.out = 200))
cost_df <- do.call(rbind, lapply(b_grid, function(bb)
  data.frame(mean_count = M_grid,
             quadrats   = n_quadrats(M_grid, a_true, bb, rse_target),
             exponent   = factor(sprintf("b = %.2f", bb),
                                 levels = sprintf("b = %.2f", b_grid)))))

p_cost <- ggplot(cost_df, aes(mean_count, quadrats, colour = exponent)) +
  geom_vline(xintercept = 1, linetype = "dashed", colour = te_body) +
  geom_line(linewidth = 1) +
  scale_x_log10() + scale_y_log10() +
  scale_colour_manual(values = c(te_forest, te_rust, te_gold)) +
  labs(x = "mean count per quadrat", y = "quadrats for a 20 per cent standard error",
       colour = NULL, title = "What the exponent costs at low density") +
  theme_datasheet() +
  theme(legend.position = "bottom")
p_cost

## ---- thumbnail ----
ggsave("thumbnail.png", p_cost, width = 9, height = 6.48, dpi = 1000 / 12)

## ---- cluster ----
plot_side <- 32
n_parent  <- 200

set.seed(5012)
parents <- cbind(runif(n_parent, 0, plot_side), runif(n_parent, 0, plot_side))

sim_cluster <- function(par_xy, mu_off, sigma, seed) {
  set.seed(seed)
  k <- rpois(nrow(par_xy), mu_off)
  x <- rep(par_xy[, 1], k) + rnorm(sum(k), 0, sigma)
  y <- rep(par_xy[, 2], k) + rnorm(sum(k), 0, sigma)
  cbind(x %% plot_side, y %% plot_side)
}

quad_counts <- function(pts, side) {
  g  <- round(plot_side / side)
  ix <- pmin(floor(pts[, 1] / side), g - 1)
  iy <- pmin(floor(pts[, 2] / side), g - 1)
  tabulate(ix * g + iy + 1, nbins = g * g)
}

mu_levels <- exp(seq(log(8), log(90), length.out = 12))
fields    <- lapply(seq_along(mu_levels),
                    function(i) sim_cluster(parents, mu_levels[i], 1, 5000 + i))
sides     <- c(4, 2, 1, 0.5)

grain_mv <- do.call(rbind, lapply(sides, function(s) do.call(rbind,
  lapply(fields, function(p) {
    z <- quad_counts(p, s)
    data.frame(side = s, mean_count = mean(z), variance = var(z))
  }))))

grain <- do.call(rbind, lapply(sides, function(s) {
  d <- grain_mv[grain_mv$side == s, ]
  f <- lm(log(d$variance) ~ log(d$mean_count))
  data.frame(side = s, quadrats_in_plot = (plot_side / s)^2,
             a = unname(exp(coef(f)[1])), b = unname(coef(f)[2]))
}))
print(grain, row.names = FALSE, digits = 3)

## ---- fig-grain ----
grain_mv$quadrat <- factor(sprintf("%.1f m", grain_mv$side),
                           levels = sprintf("%.1f m", sides))
grain$quadrat <- factor(sprintf("%.1f m", grain$side),
                        levels = sprintf("%.1f m", sides))

ggplot(grain_mv, aes(mean_count, variance, colour = quadrat)) +
  geom_abline(data = grain, aes(slope = b, intercept = log10(a), colour = quadrat),
              linewidth = 0.8) +
  geom_point(size = 2.2) +
  scale_x_log10() + scale_y_log10() +
  scale_colour_manual(values = c(te_ink, te_rust, te_forest, te_gold)) +
  labs(x = "mean count per quadrat", y = "variance across quadrats",
       colour = "quadrat side", title = "Twelve fields, four grains, four laws") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- grain-repeat ----
grain_b <- function(seed) {
  set.seed(seed)
  pp <- cbind(runif(n_parent, 0, plot_side), runif(n_parent, 0, plot_side))
  fs <- lapply(seq_along(mu_levels),
               function(i) sim_cluster(pp, mu_levels[i], 1, seed * 100 + i))
  sapply(sides, function(s) {
    d <- do.call(rbind, lapply(fs, function(p) {
      z <- quad_counts(p, s)
      c(mean(z), var(z))
    }))
    unname(coef(lm(log(d[, 2]) ~ log(d[, 1])))[2])
  })
}

reps <- t(sapply(1:100, function(r) grain_b(70000 + r)))
colnames(reps) <- sprintf("%.1f m", sides)
mono <- mean(apply(reps, 1, function(x) all(diff(x) < 0)))
round(rbind(mean_b = colMeans(reps), sd_b = apply(reps, 2, sd)), 3)
round(c(monotone_fraction = mono), 3)

## ---- transfer ----
set.seed(424241)
new_parents <- cbind(runif(n_parent, 0, plot_side), runif(n_parent, 0, plot_side))
new_field   <- sim_cluster(new_parents, 20, 1, 424242)
dens_new    <- nrow(new_field) / plot_side^2

grain$mean_at_dens <- dens_new * grain$side^2
grain$n_own <- ceiling(n_quadrats(grain$mean_at_dens, grain$a, grain$b, rse_target))
grain$n_borrowed <- ceiling(n_quadrats(grain$mean_at_dens, grain$a[1], grain$b[1],
                                       rse_target))

achieved <- do.call(rbind, lapply(seq_len(nrow(grain)), function(i) {
  z    <- quad_counts(new_field, grain$side[i])
  pvar <- mean((z - mean(z))^2)
  rse  <- function(nq) sqrt(pvar / nq) / mean(z)
  data.frame(side = grain$side[i], mean_count = mean(z),
             var_ratio = var(z) / (grain$a[i] * mean(z)^grain$b[i]),
             n_own = grain$n_own[i], rse_own = rse(grain$n_own[i]),
             n_borrowed = grain$n_borrowed[i],
             rse_borrowed = rse(grain$n_borrowed[i]))
}))
print(achieved, row.names = FALSE, digits = 3)

## ---- pilot ----
pilot_fit <- function(nq, seed, nq_max = 50) {
  set.seed(seed)
  mv <- sapply(M_site, function(m) {
    z <- rcount(nq_max, m, a_true, b_true)[seq_len(nq)]
    c(mean(z), var(z))
  })
  ok <- mv[1, ] > 0 & mv[2, ] > 0
  f  <- lm(log(mv[2, ok]) ~ log(mv[1, ok]))
  c(a = unname(exp(coef(f)[1])), b = unname(coef(f)[2]))
}

pilot_small <- t(sapply(1:400, function(i) pilot_fit(5,  1000 + i)))
pilot_large <- t(sapply(1:400, function(i) pilot_fit(50, 1000 + i)))

pilot_n <- function(fits, M) fits[, "a"] * M^(fits[, "b"] - 2) / rse_target^2
truth_n <- n_quadrats(0.5, a_true, b_true, rse_target)
summarise_pilot <- function(fits) c(mean_a = mean(fits[, "a"]), mean_b = mean(fits[, "b"]),
                                    sd_a = sd(fits[, "a"]), sd_b = sd(fits[, "b"]),
                                    n_median = median(pilot_n(fits, 0.5)))
round(rbind(five  = summarise_pilot(pilot_small),
            fifty = summarise_pilot(pilot_large)), 3)
round(c(truth_a = a_true, truth_b = b_true, truth_n = truth_n), 2)
