# Isotopic niche width: hulls and ellipses
# https://tidyecology.com/posts/isotopic-niche-width/
#
# 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-11-15

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

te_pal <- list(forest = "#275139", green = "#2f8f63", sage = "#93a87f",
               clay = "#b5534e", gold = "#cda23f", line = "#dad9ca",
               ink = "#16241d", paper = "#f5f4ee")

theme_te <- function() {
  theme_minimal(base_size = 12) +
    theme(panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "#e7e6dc"),
          plot.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          plot.title = element_text(face = "bold", colour = te_pal$ink),
          axis.title = element_text(colour = "#2c3a31"))
}

## ---- truth ----
set.seed(20260718)

rbvn <- function(n, mu, S) {
  L <- chol(S)
  matrix(rnorm(2 * n), ncol = 2) %*% L + matrix(mu, n, 2, byrow = TRUE)
}

sea_hat  <- function(x) pi * sqrt(det(cov(x)))
seac_hat <- function(x) sea_hat(x) * (nrow(x) - 1) / (nrow(x) - 2)

hull_area <- function(x) {
  h <- chull(x)
  p <- x[h, , drop = FALSE]
  m <- nrow(p)
  k <- c(2:m, 1)
  abs(sum(p[, 1] * p[k, 2] - p[k, 1] * p[, 2])) / 2
}

sd_c <- 1.2; sd_n <- 0.8; rho <- 0.15
Sig <- matrix(c(sd_c^2, rho * sd_c * sd_n, rho * sd_c * sd_n, sd_n^2), 2)
mu_a <- c(-24.5, 9.2)
sea_true <- pi * sqrt(det(Sig))

n_huge <- 2e6
x_huge <- rbvn(n_huge, mu_a, Sig)
cen_huge <- matrix(colMeans(x_huge), n_huge, 2, byrow = TRUE)
maha <- rowSums(((x_huge - cen_huge) %*% solve(Sig)) * (x_huge - cen_huge))

round(c(sd_carbon = sd_c, sd_nitrogen = sd_n, correlation = rho,
        det_Sigma = det(Sig), SEA_true = sea_true), 5)
round(c(huge_sample = n_huge, SEA_huge = sea_hat(x_huge),
        percent_of_truth = 100 * sea_hat(x_huge) / sea_true,
        inside_ellipse_percent = 100 * mean(maha <= 1),
        expected_inside_percent = 100 * (1 - exp(-0.5))), 4)

## ---- one-sample ----
n_one <- 40
set.seed(707)
x_one <- rbvn(n_one, mu_a, Sig)

round(c(n = n_one, TA = hull_area(x_one), SEA = sea_hat(x_one),
        SEAc = seac_hat(x_one), SEA_true = sea_true,
        SEAc_percent_of_truth = 100 * seac_hat(x_one) / sea_true), 4)

## ---- fig-biplot ----
ellipse_path <- function(ce, S, npt = 200) {
  th <- seq(0, 2 * pi, length.out = npt)
  ee <- eigen(S)
  p <- cbind(cos(th), sin(th)) %*% t(ee$vectors %*% diag(sqrt(ee$values)))
  data.frame(x = p[, 1] + ce[1], y = p[, 2] + ce[2])
}

pts_one <- data.frame(carbon = x_one[, 1], nitrogen = x_one[, 2])
hull_one <- pts_one[c(chull(x_one), chull(x_one)[1]), ]
fit_one <- ellipse_path(colMeans(x_one), cov(x_one))
true_one <- ellipse_path(colMeans(x_one), Sig)

ggplot(pts_one, aes(carbon, nitrogen)) +
  geom_polygon(data = hull_one, fill = te_pal$sage, alpha = 0.25,
               colour = te_pal$forest, linewidth = 0.7) +
  geom_path(data = true_one, aes(x, y), inherit.aes = FALSE,
            colour = te_pal$ink, linetype = "22", linewidth = 0.7) +
  geom_path(data = fit_one, aes(x, y), inherit.aes = FALSE,
            colour = te_pal$clay, linewidth = 1) +
  geom_point(colour = te_pal$forest, size = 2, alpha = 0.9) +
  labs(x = "delta 13C (per mille)", y = "delta 15N (per mille)",
       title = "The hull holds everything, the ellipse holds two fifths") +
  theme_te()

## ---- sweep ----
set.seed(11)
n_seq <- c(10, 20, 40, 80, 160, 320)
n_rep <- 4000

sw <- do.call(rbind, lapply(n_seq, function(nn) {
  ta <- numeric(n_rep); se <- numeric(n_rep)
  for (i in seq_len(n_rep)) {
    x <- rbvn(nn, mu_a, Sig)
    ta[i] <- hull_area(x)
    se[i] <- sea_hat(x)
  }
  data.frame(n = nn, TA = mean(ta), SEA = mean(se),
             SEAc = mean(se) * (nn - 1) / (nn - 2))
}))
sw$TA_over_SEAtrue <- sw$TA / sea_true
sw$SEA_pct <- 100 * sw$SEA / sea_true
sw$SEAc_pct <- 100 * sw$SEAc / sea_true

print(round(sw, 4))
round(c(replicates = n_rep,
        TA_ratio_320_over_10 = sw$TA[6] / sw$TA[1],
        TA_monotone = as.numeric(all(diff(sw$TA) > 0)),
        TA_last_step_percent = 100 * (sw$TA[6] / sw$TA[5] - 1),
        SEA_pct_at_10 = sw$SEA_pct[1],
        SEAc_pct_at_10 = sw$SEAc_pct[1],
        theory_pct_at_10 = 100 * 8 / 9), 3)

## ---- fig-sweep ----
sweep_long <- rbind(
  data.frame(n = sw$n, value = sw$TA / sea_true, metric = "Convex hull area (TA)"),
  data.frame(n = sw$n, value = sw$SEA / sea_true, metric = "Standard ellipse area (SEA)"),
  data.frame(n = sw$n, value = sw$SEAc / sea_true, metric = "Corrected ellipse area (SEAc)"))
sweep_long$metric <- factor(sweep_long$metric, levels = c(
  "Convex hull area (TA)", "Standard ellipse area (SEA)",
  "Corrected ellipse area (SEAc)"))

ggplot(sweep_long, aes(n, value, colour = metric)) +
  geom_hline(yintercept = 1, colour = "#a9a795", linewidth = 3.4) +
  geom_line(linewidth = 0.9) +
  geom_point(size = 2.4) +
  annotate("text", x = 10, y = 0.66, hjust = 0, size = 3.2, colour = "#5f5e4f",
           label = "The thick pale band is the truth, where a metric equals the true ellipse area") +
  scale_x_log10(breaks = n_seq) +
  scale_y_log10(breaks = c(0.7, 0.9, 1, 2, 4, 8)) +
  scale_colour_manual(values = c(te_pal$clay, te_pal$gold, te_pal$forest), name = NULL) +
  labs(x = "Individuals sampled per group",
       y = "Metric divided by the true ellipse area",
       title = "Only one of these three measures the population") +
  theme_te() +
  theme(legend.position = "top")

## ---- two-groups ----
set.seed(555)
n_small <- 15; n_big <- 60; n_pair <- 4000
mu_b <- mu_a + c(1.5, 0.6)

pair <- matrix(0, n_pair, 6)
for (i in seq_len(n_pair)) {
  a <- rbvn(n_small, mu_a, Sig)
  b <- rbvn(n_big, mu_b, Sig)
  pair[i, ] <- c(hull_area(a), hull_area(b), sea_hat(a), sea_hat(b),
                 seac_hat(a), seac_hat(b))
}
colnames(pair) <- c("TA_s", "TA_b", "SEA_s", "SEA_b", "SEAc_s", "SEAc_b")
pair <- as.data.frame(pair)

round(c(n_small = n_small, n_big = n_big, replicates = n_pair,
        TA_calls_big_wider_pct = 100 * mean(pair$TA_b > pair$TA_s),
        SEA_calls_big_wider_pct = 100 * mean(pair$SEA_b > pair$SEA_s),
        SEAc_calls_big_wider_pct = 100 * mean(pair$SEAc_b > pair$SEAc_s)), 3)
round(c(median_TA_ratio = median(pair$TA_b / pair$TA_s),
        TA_ratio_5th_pct = as.numeric(quantile(pair$TA_b / pair$TA_s, 0.05)),
        median_SEAc_ratio = median(pair$SEAc_b / pair$SEAc_s),
        SEAc_ratio_5th_pct = as.numeric(quantile(pair$SEAc_b / pair$SEAc_s, 0.05)),
        SEAc_ratio_95th_pct = as.numeric(quantile(pair$SEAc_b / pair$SEAc_s, 0.95))), 3)

## ---- fig-verdict ----
verdict <- rbind(
  data.frame(ratio = pair$TA_b / pair$TA_s, metric = "Convex hull area (TA)"),
  data.frame(ratio = pair$SEAc_b / pair$SEAc_s, metric = "Corrected ellipse area (SEAc)"))
verdict$metric <- factor(verdict$metric, levels = c(
  "Convex hull area (TA)", "Corrected ellipse area (SEAc)"))
verdict$side <- ifelse(verdict$ratio > 1, "larger sample called wider",
                       "smaller sample called wider")

ggplot(verdict, aes(ratio, fill = side)) +
  geom_histogram(bins = 55, colour = NA) +
  geom_vline(xintercept = 1, colour = te_pal$ink, linetype = "22", linewidth = 0.7) +
  facet_wrap(~metric) +
  scale_x_log10(breaks = c(0.5, 1, 2, 4, 8)) +
  scale_fill_manual(values = c(te_pal$clay, te_pal$green), name = NULL) +
  labs(x = "Measured width of the group of 60 divided by that of the group of 15",
       y = "Replicate pairs",
       title = "The same niche, measured twice, judged twice") +
  theme_te() +
  theme(legend.position = "top",
        strip.text = element_text(colour = te_pal$ink, face = "bold"))

## ---- layman ----
set.seed(99)
n_lay <- 400

lay <- do.call(rbind, lapply(n_seq, function(nn) {
  m <- t(replicate(n_lay, {
    x <- rbvn(nn, mu_a, Sig)
    ce <- colMeans(x)
    cd <- mean(sqrt((x[, 1] - ce[1])^2 + (x[, 2] - ce[2])^2))
    dd <- as.matrix(dist(x))
    diag(dd) <- Inf
    nnv <- apply(dd, 1, min)
    c(CD = cd, NND = mean(nnv), SDNND = sd(nnv))
  }))
  data.frame(n = nn, t(round(colMeans(m), 4)))
}))

cd_true <- mean(sqrt(rowSums((x_huge - cen_huge)^2)))
print(lay)
round(c(replicates = n_lay, CD_true = cd_true,
        CD_ratio_320_over_10 = lay$CD[6] / lay$CD[1],
        NND_ratio_320_over_10 = lay$NND[6] / lay$NND[1],
        SDNND_ratio_320_over_10 = lay$SDNND[6] / lay$SDNND[1]), 4)

## ---- bimodal ----
d_sep <- 1.16
Sw <- Sig - d_sep^2 * matrix(c(1, 0, 0, 0), 2)

sim_bimodal <- function(n) {
  s <- sample(c(-1, 1), n, TRUE)
  rbvn(n, c(0, 0), Sw) + cbind(mu_a[1] + d_sep * s, mu_a[2])
}

ell_fill <- function(ce, S, m) {
  ee <- eigen(S)
  ang <- runif(m, 0, 2 * pi)
  rr <- sqrt(runif(m))
  cbind(rr * cos(ang), rr * sin(ang)) %*% t(ee$vectors %*% diag(sqrt(ee$values))) +
    matrix(ce, m, 2, byrow = TRUE)
}

uncovered <- function(x, pts, rad) {
  d2 <- outer(pts[, 1], x[, 1], "-")^2 + outer(pts[, 2], x[, 2], "-")^2
  apply(d2, 1, min) > rad^2
}

empty_share <- function(x, rad, m) {
  mean(uncovered(x, ell_fill(colMeans(x), cov(x), m), rad))
}

set.seed(4242)
n_bi <- 120; rad <- 0.3; n_bi_rep <- 120; m_grid <- 6000
emp_uni <- replicate(n_bi_rep, empty_share(rbvn(n_bi, mu_a, Sig), rad, m_grid))
emp_bi  <- replicate(n_bi_rep, empty_share(sim_bimodal(n_bi), rad, m_grid))
sea_uni <- replicate(n_bi_rep, seac_hat(rbvn(n_bi, mu_a, Sig)))
sea_bi  <- replicate(n_bi_rep, seac_hat(sim_bimodal(n_bi)))

round(c(group_n = n_bi, radius = rad, replicates = n_bi_rep, grid_points = m_grid,
        mode_offset = d_sep, modes_apart_permille = 2 * d_sep,
        within_mode_sd_carbon = sqrt(Sw[1, 1]),
        modes_apart_in_within_sd = 2 * d_sep / sqrt(Sw[1, 1])), 4)
round(c(empty_unimodal_pct = 100 * mean(emp_uni),
        empty_bimodal_pct = 100 * mean(emp_bi),
        ratio = mean(emp_bi) / mean(emp_uni),
        SEAc_unimodal = mean(sea_uni), SEAc_bimodal = mean(sea_bi),
        SEA_true = sea_true), 4)

## ---- fig-bimodal ----
set.seed(88)
show_uni <- rbvn(n_bi, mu_a, Sig)
show_bi <- sim_bimodal(n_bi)
panel_lab <- c("One feeding mode", "Two feeding modes")

show_frame <- function(x, lab) {
  g <- ell_fill(colMeans(x), cov(x), 4000)
  gap <- uncovered(x, g, rad)
  list(pts = data.frame(carbon = x[, 1], nitrogen = x[, 2], panel = lab),
       hole = data.frame(carbon = g[gap, 1], nitrogen = g[gap, 2], panel = lab),
       ell = data.frame(ellipse_path(colMeans(x), cov(x)), panel = lab))
}
set.seed(90)
fu <- show_frame(show_uni, panel_lab[1])
fb <- show_frame(show_bi, panel_lab[2])
bi_pts <- rbind(fu$pts, fb$pts)
bi_hole <- rbind(fu$hole, fb$hole)
bi_ell <- rbind(fu$ell, fb$ell)
for (dd in c("bi_pts", "bi_hole", "bi_ell")) {
  tmp <- get(dd); tmp$panel <- factor(tmp$panel, levels = panel_lab); assign(dd, tmp)
}

bi_hole_thin <- do.call(rbind, lapply(split(bi_hole, bi_hole$panel), function(d)
  d[seq(1, nrow(d), by = 2), , drop = FALSE]))

key_hole <- "Ellipse interior with no individual within 0.3 per mille"
key_ind <- "Sampled individual"

ggplot(bi_pts, aes(carbon, nitrogen)) +
  geom_point(data = bi_hole_thin, aes(colour = key_hole), size = 0.55, alpha = 0.35) +
  geom_path(data = bi_ell, aes(x, y), inherit.aes = FALSE,
            colour = te_pal$clay, linewidth = 1) +
  geom_point(aes(colour = key_ind), size = 1.6, alpha = 0.9) +
  facet_wrap(~panel) +
  scale_colour_manual(values = setNames(c(te_pal$gold, te_pal$forest),
                                        c(key_hole, key_ind)),
                      breaks = c(key_ind, key_hole), name = NULL) +
  guides(colour = guide_legend(override.aes = list(size = 2.6, alpha = 1))) +
  labs(x = "delta 13C (per mille)", y = "delta 15N (per mille)",
       title = "One ellipse, two very different populations",
       subtitle = "The red outline is the fitted standard ellipse in both panels") +
  theme_te() +
  theme(legend.position = "top",
        plot.subtitle = element_text(colour = "#2c3a31"),
        strip.text = element_text(colour = te_pal$ink, face = "bold"))
