# Angle-count sampling for basal area
# https://tidyecology.com/posts/angle-count-sampling-basal-area/
#
# 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-26

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

## ---- units ----
baf_set <- 4                                    # square metres per hectare
lim_dist <- function(dbh_cm, baf) dbh_cm / (2 * sqrt(baf))   # metres
dbh_chk <- 40
r_chk <- lim_dist(dbh_chk, baf_set)
g_chk <- pi * (dbh_chk / 200)^2                 # basal area of the tree, m2
zone_ha <- pi * r_chk^2 / 1e4                   # inclusion zone, hectares
per_ha_chk <- g_chk / zone_ha                   # should equal the BAF
angle_deg <- 2 * asin((dbh_chk / 200) / r_chk) * 180 / pi
baf_from_angle <- 1e4 * sin(angle_deg / 2 * pi / 180)^2

## ---- design ----
side_m <- 200; area_ha <- side_m^2 / 1e4
n_ha <- 750; parents_ha <- 10; clump_sd_main <- 6
n_pts <- 2000
rev_j <- function(n) 7 + rexp(n, 1 / 11)
make_stand <- function(n_per_ha, clump_sd, dbh_fun) {
  n_tree <- rpois(1, n_per_ha * area_ha)
  if (is.na(clump_sd)) {
    xs <- runif(n_tree, 0, side_m); ys <- runif(n_tree, 0, side_m)
  } else {
    n_par <- rpois(1, parents_ha * area_ha)
    px <- runif(n_par, 0, side_m); py <- runif(n_par, 0, side_m)
    who <- sample.int(n_par, n_tree, replace = TRUE)
    xs <- (px[who] + rnorm(n_tree, 0, clump_sd)) %% side_m
    ys <- (py[who] + rnorm(n_tree, 0, clump_sd)) %% side_m
  }
  dbh <- dbh_fun(n_tree)
  data.frame(x = xs, y = ys, dbh = dbh, g = pi * (dbh / 200)^2)
}
stand_truth <- function(st) c(ba = sum(st$g) / area_ha, n = nrow(st) / area_ha)

# distances from a block of points to every tree, on the torus or the plane
dist_block <- function(px, py, st, torus) {
  dx <- abs(outer(px, st$x, "-")); dy <- abs(outer(py, st$y, "-"))
  if (torus) { dx <- pmin(dx, side_m - dx); dy <- pmin(dy, side_m - dy) }
  sqrt(dx^2 + dy^2)
}
# per point estimates of basal area and stems per hectare from both designs
tally <- function(st, pts, baf, r_fix, torus = TRUE, block = 200) {
  r_lim <- lim_dist(st$dbh, baf); a_fix <- pi * r_fix^2 / 1e4
  est <- matrix(0, nrow(pts), 4,
                dimnames = list(NULL, c("ba_angle", "n_angle", "ba_fixed", "n_fixed")))
  for (s in seq(1, nrow(pts), by = block)) {
    ii <- s:min(nrow(pts), s + block - 1)
    dd <- dist_block(pts$x[ii], pts$y[ii], st, torus)
    in_a <- sweep(dd, 2, r_lim, "<"); in_f <- dd < r_fix
    est[ii, 1] <- baf * rowSums(in_a)
    est[ii, 2] <- as.vector(in_a %*% (baf / st$g))
    est[ii, 3] <- as.vector(in_f %*% st$g) / a_fix
    est[ii, 4] <- rowSums(in_f) / a_fix
  }
  est
}
cv_of <- function(v) sd(v) / mean(v)
# fixed radius giving the same expected number of trees per point as the gauge
equal_radius <- function(truth, baf) sqrt((truth[["ba"]] / baf) * 1e4 / (pi * truth[["n"]]))

## ---- mainstand ----
set.seed(2608)
st_main <- make_stand(n_ha, clump_sd_main, rev_j)
tr_main <- stand_truth(st_main)
m_main <- tr_main[["ba"]] / baf_set
r_fix_main <- equal_radius(tr_main, baf_set)
pts_main <- data.frame(x = runif(n_pts, 0, side_m), y = runif(n_pts, 0, side_m))
est_main <- tally(st_main, pts_main, baf_set, r_fix_main)
max_r_main <- max(lim_dist(st_main$dbh, baf_set))
n_count_pt <- as.vector(est_main[, "ba_angle"] / baf_set)
i_show <- which(n_count_pt == round(m_main) & pts_main$x > 40 & pts_main$x < 160 &
                pts_main$y > 40 & pts_main$y < 160)[1]

## ---- fig-stand ----
p0 <- pts_main[i_show, ]
win <- 30
near <- st_main
near$dx <- (near$x - p0$x + side_m / 2) %% side_m - side_m / 2
near$dy <- (near$y - p0$y + side_m / 2) %% side_m - side_m / 2
near <- near[abs(near$dx) < win & abs(near$dy) < win, ]
near$dist <- sqrt(near$dx^2 + near$dy^2)
near$r_lim <- lim_dist(near$dbh, baf_set)
near$angle_in <- near$dist < near$r_lim
near$fixed_in <- near$dist < r_fix_main
near$status <- factor(ifelse(near$angle_in & near$fixed_in, "both",
                      ifelse(near$angle_in, "angle count only",
                      ifelse(near$fixed_in, "fixed plot only", "neither"))),
                      levels = c("angle count only", "fixed plot only", "both", "neither"))
circ <- function(cx, cy, r, id) {
  th <- seq(0, 2 * pi, length.out = 90)
  data.frame(x = cx + r * cos(th), y = cy + r * sin(th), id = id)
}
zones <- do.call(rbind, lapply(which(near$angle_in), function(i)
  circ(near$dx[i], near$dy[i], near$r_lim[i], i)))
plot_c <- circ(0, 0, r_fix_main, 0)
ggplot() +
  geom_path(data = zones, aes(x, y, group = id), colour = te_gold, linewidth = 0.4) +
  geom_path(data = plot_c, aes(x, y), colour = te_ink, linetype = "dashed", linewidth = 0.7) +
  geom_point(data = near, aes(dx, dy, size = dbh, colour = status), alpha = 0.9) +
  annotate("point", x = 0, y = 0, shape = 3, size = 4, stroke = 1.2, colour = te_ink) +
  scale_colour_manual(values = c("angle count only" = te_rust, "fixed plot only" = te_forest,
                                 "both" = te_ink, "neither" = "#9aa396"), name = NULL, drop = FALSE) +
  scale_size_continuous(range = c(0.6, 5), name = "DBH (cm)") +
  coord_equal(xlim = c(-win, win), ylim = c(-win, win)) +
  labs(x = "metres east of the point", y = "metres north of the point",
       title = "Who gets counted at one point",
       subtitle = "gold: inclusion zones of counted trees, dashed: fixed plot") +
  theme_datasheet()

## ---- unbiased ----
set.seed(2609)
st_csr <- make_stand(n_ha, NA, rev_j)
tr_csr <- stand_truth(st_csr)
r_fix_csr <- equal_radius(tr_csr, baf_set)
pts_csr <- data.frame(x = runif(n_pts, 0, side_m), y = runif(n_pts, 0, side_m))
est_csr <- tally(st_csr, pts_csr, baf_set, r_fix_csr)
truth_vec <- function(tr) c(tr[["ba"]], tr[["n"]], tr[["ba"]], tr[["n"]])
bias_tab <- function(est, tr) {
  rel <- sweep(est, 2, truth_vec(tr), "/")
  data.frame(design = colnames(est), ratio = colMeans(rel),
             mcse = apply(rel, 2, sd) / sqrt(nrow(rel)), cv = apply(est, 2, cv_of))
}
bt_csr <- bias_tab(est_csr, tr_csr); bt_main <- bias_tab(est_main, tr_main)
z_max <- max(abs(c((bt_csr$ratio - 1) / bt_csr$mcse, (bt_main$ratio - 1) / bt_main$mcse)))
# closed form variance ratios for a Poisson stand at equal expected count
theory_ba <- function(st) sqrt(mean(st$g^2) / mean(st$g)^2)       # CV fixed / CV angle
theory_n  <- function(st) sqrt(mean(st$g) * mean(1 / st$g))       # CV angle / CV fixed
th_ba_csr <- theory_ba(st_csr); th_n_csr <- theory_n(st_csr)
ratio_ba_csr <- bt_csr$cv[3] / bt_csr$cv[1]; ratio_n_csr <- bt_csr$cv[2] / bt_csr$cv[4]
ratio_ba_main <- bt_main$cv[3] / bt_main$cv[1]; ratio_n_main <- bt_main$cv[2] / bt_main$cv[4]

## ---- fig-estimates ----
long_est <- function(est, tr, stand_lab) {
  rel <- sweep(est, 2, truth_vec(tr), "/")
  data.frame(value = as.vector(rel),
             total = rep(c("basal area", "stems", "basal area", "stems"), each = nrow(rel)),
             design = rep(c("angle count", "angle count", "fixed plot", "fixed plot"), each = nrow(rel)),
             stand = stand_lab)
}
ld <- rbind(long_est(est_csr, tr_csr, "random stand"), long_est(est_main, tr_main, "clumped stand"))
ld$stand <- factor(ld$stand, levels = c("random stand", "clumped stand"))
ld$value_cap <- pmin(ld$value, 5)
ggplot(ld, aes(design, value_cap, fill = design)) +
  geom_violin(colour = NA, scale = "width", adjust = 1.2) +
  stat_summary(aes(y = value), fun = mean, geom = "point", shape = 23, size = 2.4, fill = te_paper, colour = te_ink) +
  geom_hline(yintercept = 1, linetype = "dashed", colour = te_ink, linewidth = 0.5) +
  facet_grid(stand ~ total) +
  scale_fill_manual(values = c("angle count" = te_rust, "fixed plot" = te_forest), guide = "none") +
  labs(x = NULL, y = "estimate / true value (capped at 5)",
       title = "Same mean, different spread",
       subtitle = "diamonds: mean over all points (before the cap), dashed line: truth") +
  theme_datasheet() +
  theme(strip.text = element_text(colour = te_ink, face = "bold"))

## ---- clumpsweep ----
sd_grid <- c(NA, 3, 6, 12, 24)
n_stands <- 8
set.seed(2610)
sweep_rows <- list()
for (cs in sd_grid) for (k in seq_len(n_stands)) {
  st <- make_stand(n_ha, cs, rev_j); tr <- stand_truth(st)
  pts <- data.frame(x = runif(n_pts, 0, side_m), y = runif(n_pts, 0, side_m))
  est <- tally(st, pts, baf_set, equal_radius(tr, baf_set))
  cvs <- apply(est, 2, cv_of)
  sweep_rows[[length(sweep_rows) + 1]] <- data.frame(
    clump = ifelse(is.na(cs), "random", sprintf("%g m", cs)),
    ba_ratio = cvs[["ba_fixed"]] / cvs[["ba_angle"]], n_ratio = cvs[["n_angle"]] / cvs[["n_fixed"]],
    th_ba = theory_ba(st), th_n = theory_n(st))
}
sw <- do.call(rbind, sweep_rows)
clump_lev <- c(sprintf("%g m", sd_grid[-1]), "random")
sw$clump <- factor(sw$clump, levels = clump_lev)
agg_fun <- function(v) c(mean = mean(v), se = sd(v) / sqrt(length(v)))
sw_sum <- do.call(rbind, lapply(clump_lev, function(cl) {
  s <- sw[sw$clump == cl, ]
  data.frame(clump = cl, total = c("basal area", "stems"),
             ratio = c(mean(s$ba_ratio), mean(s$n_ratio)),
             se = c(sd(s$ba_ratio), sd(s$n_ratio)) / sqrt(nrow(s)),
             theory = c(mean(s$th_ba), mean(s$th_n)))
}))
sw_sum$clump <- factor(sw_sum$clump, levels = clump_lev)
sr <- function(cl, tot) sw_sum$ratio[sw_sum$clump == cl & sw_sum$total == tot]
sse <- function(cl, tot) sw_sum$se[sw_sum$clump == cl & sw_sum$total == tot]
min_stand_n <- min(sw$n_ratio); min_stand_ba <- min(sw$ba_ratio)
th_ba_rand <- sw_sum$theory[sw_sum$clump == "random" & sw_sum$total == "basal area"]
th_n_rand <- sw_sum$theory[sw_sum$clump == "random" & sw_sum$total == "stems"]
rand <- sw[sw$clump == "random", ]
gap_ba <- rand$th_ba - rand$ba_ratio; gap_n <- rand$th_n - rand$n_ratio
gap_ba_m <- mean(gap_ba); gap_ba_se <- sd(gap_ba) / sqrt(nrow(rand))
gap_n_m <- mean(gap_n); gap_n_se <- sd(gap_n) / sqrt(nrow(rand))
# Welch t for the basal area dip at 6 m and the stem plateau at 3 and 6 m
welch <- function(a, b, v) t.test(sw[[v]][sw$clump == a], sw[[v]][sw$clump == b])$statistic[[1]]
d_ba_3_6 <- sr("3 m", "basal area") - sr("6 m", "basal area"); t_ba_3_6 <- welch("3 m", "6 m", "ba_ratio")
d_ba_12_6 <- sr("12 m", "basal area") - sr("6 m", "basal area"); t_ba_12_6 <- welch("12 m", "6 m", "ba_ratio")
d_n_3_6 <- sr("3 m", "stems") - sr("6 m", "stems"); t_n_3_6 <- welch("3 m", "6 m", "n_ratio")
s24 <- sw[sw$clump == "24 m", ]; i24 <- which.max(s24$ba_ratio)
max24_ba <- s24$ba_ratio[i24]; max24_th <- s24$th_ba[i24]; max_rand_ba <- max(rand$ba_ratio)

## ---- fig-clump ----
ggplot(sw_sum, aes(clump, ratio, colour = total, group = total)) +
  geom_hline(yintercept = 1, colour = te_body, linewidth = 0.5) +
  geom_hline(data = data.frame(total = c("basal area", "stems"), th = c(th_ba_rand, th_n_rand)),
             aes(yintercept = th, colour = total), linetype = "dashed", linewidth = 0.6) +
  geom_jitter(data = data.frame(clump = rep(sw$clump, 2), total = rep(c("basal area", "stems"), each = nrow(sw)),
                                ratio = c(sw$ba_ratio, sw$n_ratio)),
              width = 0.12, height = 0, size = 1.1, alpha = 0.45) +
  geom_line(linewidth = 0.9) +
  geom_errorbar(aes(ymin = ratio - 2 * se, ymax = ratio + 2 * se), width = 0.15, linewidth = 0.5) +
  geom_point(size = 2.6) +
  scale_colour_manual(values = c("basal area" = te_rust, "stems" = te_forest), name = NULL,
                      labels = c("basal area: CV fixed / CV angle", "stems: CV angle / CV fixed")) +
  scale_x_discrete(labels = c("3 m", "6 m", "12 m", "24 m", "random\n(no clusters)")) +
  scale_y_continuous(limits = c(0.9, NA)) +
  labs(x = "cluster scatter", y = "ratio of coefficients of variation",
       title = "Clumping shrinks the difference between designs",
       subtitle = "dashed: closed form for a random stand, small dots: single stands") +
  theme_datasheet() + theme(legend.position = "bottom")

## ---- edges ----
buffer_m <- ceiling(max_r_main)
set.seed(2611)
pts_buf <- data.frame(x = runif(n_pts, buffer_m, side_m - buffer_m),
                      y = runif(n_pts, buffer_m, side_m - buffer_m))
est_buf <- tally(st_main, pts_buf, baf_set, r_fix_main, torus = FALSE)
est_buf_torus <- tally(st_main, pts_buf, baf_set, r_fix_main, torus = TRUE)
buf_gap <- max(abs(est_buf - est_buf_torus))
cv_buf <- apply(est_buf, 2, cv_of)
ratio_ba_buf <- cv_buf[["ba_fixed"]] / cv_buf[["ba_angle"]]
ratio_n_buf <- cv_buf[["n_angle"]] / cv_buf[["n_fixed"]]
inner <- st_main$x > buffer_m & st_main$x < side_m - buffer_m &
         st_main$y > buffer_m & st_main$y < side_m - buffer_m
inner_ha <- (side_m - 2 * buffer_m)^2 / 1e4
tr_inner <- c(ba = sum(st_main$g[inner]) / inner_ha, n = sum(inner) / inner_ha)
buf_to_inner <- colMeans(est_buf) / truth_vec(tr_inner)
# slopover: the same points, plane minus torus, so only the edge differs
est_naive <- tally(st_main, pts_main, baf_set, r_fix_main, torus = FALSE)
loss <- sweep(est_naive - est_main, 2, truth_vec(tr_main), "/")
loss_mean <- colMeans(loss); loss_se <- apply(loss, 2, sd) / sqrt(n_pts)

## ---- border ----
tol_grid <- c(0.05, 0.10, 0.20, 0.30)          # band half-width, metres
eps_share <- 0.01                              # error as a share of the limiting distance
mature <- function(n) 7 + rlnorm(n, log(26), 0.35)
set.seed(2612)
st_mat <- make_stand(260, NA, mature); tr_mat <- stand_truth(st_mat)
exact_bias <- function(st, tol, rule) {
  r2 <- lim_dist(st$dbh, baf_set)^2
  shift <- if (rule == "in") pmin(2 * tol * sqrt(r2) + tol^2, Inf) else
             -pmin(r2, 2 * tol * sqrt(r2) - tol^2)
  c(ba = sum(shift) / sum(r2), n = mean(shift / r2))
}
sim_bias <- function(st, tr, pts, tols) {
  r_lim <- lim_dist(st$dbh, baf_set); w_n <- baf_set / st$g
  acc <- array(0, c(nrow(pts), length(tols), 4))
  for (s in seq(1, nrow(pts), by = 200)) {
    ii <- s:min(nrow(pts), s + 199)
    dd <- dist_block(pts$x[ii], pts$y[ii], st, TRUE)
    base <- sweep(dd, 2, r_lim, "<")
    for (j in seq_along(tols)) {
      add <- sweep(dd, 2, r_lim + tols[j], "<") & !base
      drop <- base & !sweep(dd, 2, r_lim - tols[j], "<")
      acc[ii, j, 1] <- baf_set * rowSums(add);  acc[ii, j, 2] <- add %*% w_n
      acc[ii, j, 3] <- -baf_set * rowSums(drop); acc[ii, j, 4] <- -(drop %*% w_n)
    }
  }
  scale_by <- c(tr[["ba"]], tr[["n"]], tr[["ba"]], tr[["n"]])
  mean_rel <- sweep(apply(acc, c(2, 3), mean), 2, scale_by, "/")
  se_rel <- sweep(apply(acc, c(2, 3), sd) / sqrt(nrow(pts)), 2, scale_by, "/")
  list(mean = mean_rel, se = se_rel)
}
pts_b <- data.frame(x = runif(n_pts, 0, side_m), y = runif(n_pts, 0, side_m))
stands_b <- list("reverse-J stand" = list(st = st_csr, tr = tr_csr),
                 "mature stand" = list(st = st_mat, tr = tr_mat))
border_rows <- list(); sim_rows <- list()
for (nm in names(stands_b)) {
  sb <- stands_b[[nm]]
  tol_fine <- seq(0, 0.3, by = 0.01)
  for (rule in c("in", "out")) {
    ex <- t(vapply(tol_fine, function(tl) exact_bias(sb$st, tl, rule), numeric(2)))
    border_rows[[length(border_rows) + 1]] <- data.frame(
      stand = nm, rule = sprintf("all counted %s", rule), tol = rep(tol_fine, 2),
      total = rep(c("basal area", "stems"), each = length(tol_fine)), bias = c(ex[, 1], ex[, 2]))
  }
  sb_sim <- sim_bias(sb$st, sb$tr, pts_b, tol_grid)
  sim_rows[[nm]] <- data.frame(
    stand = nm, tol = rep(tol_grid, 4),
    rule = rep(c("all counted in", "all counted in", "all counted out", "all counted out"), each = length(tol_grid)),
    total = rep(c("basal area", "stems", "basal area", "stems"), each = length(tol_grid)),
    bias = as.vector(sb_sim$mean), se = as.vector(sb_sim$se))
}
bord <- do.call(rbind, border_rows); bsim <- do.call(rbind, sim_rows)
bsim$exact <- mapply(function(nm, tl, rl, tot) {
  e <- exact_bias(stands_b[[nm]]$st, tl, ifelse(rl == "all counted in", "in", "out"))
  e[[ifelse(tot == "basal area", "ba", "n")]]
}, bsim$stand, bsim$tol, bsim$rule, bsim$total)
z_border <- max(abs(bsim$bias - bsim$exact) / bsim$se)
eb <- function(nm, tl, rule, tot) exact_bias(stands_b[[nm]]$st, tl, rule)[[tot]]
half_ba <- (eb("reverse-J stand", 0.1, "in", "ba") + eb("reverse-J stand", 0.1, "out", "ba")) / 2
eps_bias <- 2 * eps_share + eps_share^2
dbh_mean_rj <- mean(st_csr$dbh); dbh_mean_mat <- mean(st_mat$dbh)

## ---- fig-border ----
bord$stand <- factor(bord$stand, levels = names(stands_b))
bsim$stand <- factor(bsim$stand, levels = names(stands_b))
ggplot(bord, aes(100 * tol, 100 * bias, colour = stand, linetype = rule)) +
  geom_hline(yintercept = 0, colour = te_body, linewidth = 0.4) +
  geom_line(linewidth = 0.9) +
  geom_errorbar(data = bsim, aes(ymin = 100 * (bias - 2 * se), ymax = 100 * (bias + 2 * se)),
                width = 0.8, linewidth = 0.4, linetype = "solid") +
  geom_point(data = bsim, size = 1.9) +
  facet_wrap(~ total) +
  scale_colour_manual(values = c("reverse-J stand" = te_rust, "mature stand" = te_forest), name = NULL) +
  scale_linetype_manual(values = c("all counted in" = "solid", "all counted out" = "dashed"), name = NULL) +
  labs(x = "half-width of the borderline band (cm)", y = "relative bias (per cent)",
       title = "Borderline bias depends on the diameters",
       subtitle = "same band, two stands, two totals") +
  guides(colour = guide_legend(nrow = 1), linetype = guide_legend(nrow = 1)) +
  theme_datasheet() +
  theme(legend.position = "bottom", legend.box = "vertical",
        strip.text = element_text(colour = te_ink, face = "bold"))
