# Isotopic niche overlap between groups
# https://tidyecology.com/posts/isotopic-niche-overlap/
#
# 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-08

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

## ---- geometry ----
ell_area <- function(S, p) pi * qchisq(p, 2) * sqrt(det(S))

ell_yspan <- function(x, mu, S, p) {
  cc <- qchisq(p, 2)
  A <- solve(S)
  dA <- A[1, 1] * A[2, 2] - A[1, 2]^2
  u <- x - mu[1]
  disc <- A[2, 2] * cc - dA * u^2
  half <- sqrt(pmax(disc, 0)) / A[2, 2]
  half[disc <= 0] <- NA_real_
  ctr <- mu[2] - A[1, 2] * u / A[2, 2]
  cbind(lo = ctr - half, hi = ctr + half)
}

ell_xhalf <- function(S, p) {
  cc <- qchisq(p, 2)
  A <- solve(S)
  sqrt(A[2, 2] * cc / (A[1, 1] * A[2, 2] - A[1, 2]^2))
}

ell_overlap <- function(mu1, S1, mu2, S2, p, nx = 4000) {
  h1 <- ell_xhalf(S1, p); h2 <- ell_xhalf(S2, p)
  lo <- max(mu1[1] - h1, mu2[1] - h2)
  hi <- min(mu1[1] + h1, mu2[1] + h2)
  if (hi <= lo) return(0)
  dx <- (hi - lo) / nx
  x <- lo + (seq_len(nx) - 0.5) * dx
  s1 <- ell_yspan(x, mu1, S1, p)
  s2 <- ell_yspan(x, mu2, S2, p)
  len <- pmin(s1[, "hi"], s2[, "hi"]) - pmax(s1[, "lo"], s2[, "lo"])
  len[!is.finite(len)] <- 0
  sum(pmax(len, 0)) * dx
}

## ---- validate ----
n_slab <- 20000
p_ref <- 0.95
mu_g <- c(-24.0, 9.4);   S_g <- matrix(c(2.20, 0.55, 0.55, 1.35), 2)

same <- ell_overlap(mu_g, S_g, mu_g, S_g, p_ref, n_slab)
apart <- ell_overlap(mu_g, S_g, mu_g + c(50, 50), S_g, p_ref, n_slab)

lens_area <- function(r1, r2, d) {
  r1^2 * acos((d^2 + r1^2 - r2^2) / (2 * d * r1)) +
    r2^2 * acos((d^2 + r2^2 - r1^2) / (2 * d * r2)) -
    0.5 * sqrt((-d + r1 + r2) * (d + r1 - r2) * (d - r1 + r2) * (d + r1 + r2))
}
s1 <- 0.8; s2 <- 1.3; dd <- 1.9
rr <- sqrt(qchisq(p_ref, 2))
lens_true <- lens_area(s1 * rr, s2 * rr, dd)
lens_num <- ell_overlap(c(0, 0), diag(c(s1^2, s1^2)),
                        c(dd, 0), diag(c(s2^2, s2^2)), p_ref, n_slab)

c(strips = n_slab)
round(c(closed_form_area = ell_area(S_g, p_ref), calculator_area = same,
        lens_closed_form = lens_true, lens_calculator = lens_num), 6)
signif(c(identical_relative_error = same / ell_area(S_g, p_ref) - 1,
         far_apart_absolute_area = apart,
         lens_relative_error = lens_num / lens_true - 1), 3)

## ---- groups ----
mu_s <- c(-23.20, 9.90);  S_s <- matrix(c(0.34, 0.09, 0.09, 0.26), 2)
mu_b <- c(-25.50, 8.60);  S_b <- matrix(c(0.90, 0.25, 0.25, 0.70), 2)
mu_p <- c(-23.75, 9.95);  S_p <- S_b

p_std <- 0.40
areas <- c(generalist = ell_area(S_g, p_std), specialist = ell_area(S_s, p_std),
           benthic = ell_area(S_b, p_std), pelagic = ell_area(S_p, p_std))
round(c(containment = p_std, chisq_quantile = qchisq(p_std, 2)), 4)
round(areas, 4)

ov_gs <- ell_overlap(mu_g, S_g, mu_s, S_s, p_std, n_slab)
round(c(shared_area = ov_gs,
        divided_by_generalist = ov_gs / areas[["generalist"]],
        divided_by_specialist = ov_gs / areas[["specialist"]],
        ratio_of_the_two_answers = areas[["generalist"]] / areas[["specialist"]]), 4)

## ---- fig-pairs ----
ell_path <- function(mu, S, p, k = 400) {
  th <- seq(0, 2 * pi, length.out = k)
  z <- t(chol(S)) %*% rbind(cos(th), sin(th)) * sqrt(qchisq(p, 2))
  data.frame(x = mu[1] + z[1, ], y = mu[2] + z[2, ])
}

overlap_path <- function(mu1, S1, mu2, S2, p, k = 800) {
  h1 <- ell_xhalf(S1, p); h2 <- ell_xhalf(S2, p)
  lo <- max(mu1[1] - h1, mu2[1] - h2)
  hi <- min(mu1[1] + h1, mu2[1] + h2)
  if (hi <= lo) return(NULL)
  x <- seq(lo, hi, length.out = k)
  s1 <- ell_yspan(x, mu1, S1, p)
  s2 <- ell_yspan(x, mu2, S2, p)
  ylo <- pmax(s1[, "lo"], s2[, "lo"])
  yhi <- pmin(s1[, "hi"], s2[, "hi"])
  ok <- is.finite(ylo) & is.finite(yhi) & yhi > ylo
  if (!any(ok)) return(NULL)
  data.frame(x = c(x[ok], rev(x[ok])), y = c(yhi[ok], rev(ylo[ok])))
}

pan <- c("Generalist and specialist at 0.4", "Benthic and pelagic at 0.4 and 0.95")
lines_df <- rbind(
  data.frame(ell_path(mu_g, S_g, p_std), grp = "generalist", lev = "0.4", panel = pan[1]),
  data.frame(ell_path(mu_s, S_s, p_std), grp = "specialist", lev = "0.4", panel = pan[1]),
  data.frame(ell_path(mu_b, S_b, p_std), grp = "benthic", lev = "0.4", panel = pan[2]),
  data.frame(ell_path(mu_p, S_p, p_std), grp = "pelagic", lev = "0.4", panel = pan[2]),
  data.frame(ell_path(mu_b, S_b, 0.95), grp = "benthic", lev = "0.95", panel = pan[2]),
  data.frame(ell_path(mu_p, S_p, 0.95), grp = "pelagic", lev = "0.95", panel = pan[2]))
lines_df$panel <- factor(lines_df$panel, levels = pan)
lines_df$key <- paste(lines_df$grp, lines_df$lev)

fill_df <- rbind(
  data.frame(overlap_path(mu_g, S_g, mu_s, S_s, p_std), panel = pan[1]),
  data.frame(overlap_path(mu_b, S_b, mu_p, S_p, 0.95), panel = pan[2]))
fill_df$panel <- factor(fill_df$panel, levels = pan)

ggplot(lines_df, aes(x, y, group = key, colour = grp, linetype = lev)) +
  geom_polygon(data = fill_df, aes(x, y), inherit.aes = FALSE,
               fill = te_pal$gold, alpha = 0.45) +
  geom_path(linewidth = 0.8) +
  facet_wrap(~panel, scales = "free") +
  scale_colour_manual(values = c(generalist = te_pal$forest, specialist = te_pal$clay,
                                 benthic = te_pal$green, pelagic = "#c9793f"),
                      name = NULL) +
  scale_linetype_manual(values = c("0.4" = "22", "0.95" = "solid"),
                        name = "Containment") +
  labs(x = expression(delta^13 * "C (per mil)"), y = expression(delta^15 * "N (per mil)"),
       title = "Where the shared area is, and what it gets divided by") +
  theme_te() +
  theme(legend.position = "top",
        strip.text = element_text(colour = te_pal$ink, face = "bold"))

## ---- sweep ----
p_levels <- c(0.40, 0.60, 0.75, 0.95)
sweep_pair <- function(m1, Sa, m2, Sb, pv) {
  ov <- sapply(pv, function(p) ell_overlap(m1, Sa, m2, Sb, p, n_slab))
  data.frame(p = pv, shared = ov,
             by_first = ov / sapply(pv, function(p) ell_area(Sa, p)),
             by_second = ov / sapply(pv, function(p) ell_area(Sb, p)))
}

gb <- sweep_pair(mu_g, S_g, mu_b, S_b, p_levels)
bp <- sweep_pair(mu_b, S_b, mu_p, S_p, p_levels)
print(round(gb, 4))
print(round(bp, 4))
round(c(gb_extreme_ratio = max(gb$by_second) / min(gb$by_second),
        bp_at_lowest_p = bp$by_second[1], bp_at_highest_p = bp$by_second[4],
        bp_first_positive_p = min(bp$p[bp$shared > 0])), 4)

## ---- mahalanobis ----
dvec <- mu_p - mu_b
md <- sqrt(as.numeric(t(dvec) %*% solve(S_b) %*% dvec))
round(c(mahalanobis_separation = md,
        touching_separation_at_0.40 = 2 * sqrt(qchisq(0.40, 2)),
        touching_separation_at_0.95 = 2 * sqrt(qchisq(0.95, 2))), 4)

## ---- fig-sweep ----
pgrid <- seq(0.05, 0.99, by = 0.01)
curve_lab <- c("generalist and benthic, over the benthic area",
               "generalist and benthic, over the generalist area",
               "benthic and pelagic, either area")
ov_gb <- sapply(pgrid, function(p) ell_overlap(mu_g, S_g, mu_b, S_b, p, 3000))
ov_bp <- sapply(pgrid, function(p) ell_overlap(mu_b, S_b, mu_p, S_p, p, 3000))
a_g <- sapply(pgrid, function(p) ell_area(S_g, p))
a_b <- sapply(pgrid, function(p) ell_area(S_b, p))
curves <- rbind(
  data.frame(p = pgrid, value = ov_gb / a_b, series = curve_lab[1]),
  data.frame(p = pgrid, value = ov_gb / a_g, series = curve_lab[2]),
  data.frame(p = pgrid, value = ov_bp / a_b, series = curve_lab[3]))
curves$series <- factor(curves$series, levels = curve_lab)

ggplot(curves, aes(p, value, colour = series)) +
  geom_vline(xintercept = p_levels, colour = te_pal$line, linewidth = 0.7) +
  geom_line(linewidth = 0.9) +
  scale_colour_manual(values = c(te_pal$forest, te_pal$sage, te_pal$clay), name = NULL) +
  guides(colour = guide_legend(ncol = 1)) +
  labs(x = "Containment probability of the ellipse", y = "Overlap as a proportion of one area",
       title = "What the containment probability alone does to an overlap") +
  theme_te() +
  theme(legend.position = "top")

## ---- sampling ----
set.seed(20260718)
rmvn <- function(n, mu, S) t(mu + t(chol(S)) %*% matrix(rnorm(2 * n), nrow = 2))

n_ind <- 15
n_rep <- 3000
truth_prop <- ell_overlap(mu_g, S_g, mu_b, S_b, p_std, n_slab) / ell_area(S_b, p_std)
kc <- (n_ind - 1) / (n_ind - 2)

est <- numeric(n_rep); est_c <- numeric(n_rep)
for (i in seq_len(n_rep)) {
  xg <- rmvn(n_ind, mu_g, S_g); xb <- rmvn(n_ind, mu_b, S_b)
  mg <- colMeans(xg); mb <- colMeans(xb)
  Sg <- cov(xg); Sb_hat <- cov(xb)
  est[i] <- ell_overlap(mg, Sg, mb, Sb_hat, p_std, 1500) / ell_area(Sb_hat, p_std)
  est_c[i] <- ell_overlap(mg, kc * Sg, mb, kc * Sb_hat, p_std, 1500) /
    ell_area(kc * Sb_hat, p_std)
}

round(c(individuals_per_group = n_ind, replicates = n_rep,
        small_sample_factor = kc), 4)
round(c(truth = truth_prop, mean_estimate = mean(est), bias = mean(est) - truth_prop,
        median_estimate = median(est)), 4)
round(c(interval_coverage_percent = 95,
        lower_2.5 = as.numeric(quantile(est, 0.025)),
        upper_97.5 = as.numeric(quantile(est, 0.975)),
        interval_width = as.numeric(diff(quantile(est, c(0.025, 0.975)))),
        proportion_exactly_zero = mean(est == 0),
        proportion_above_0.9 = mean(est > 0.9)), 4)
round(c(corrected_mean = mean(est_c), corrected_bias = mean(est_c) - truth_prop), 4)

## ---- fig-sampling ----
qs <- as.numeric(quantile(est, c(0.025, 0.975)))
# the numerical integration can overshoot 1 by a hair; cap at 1 for display
ggplot(data.frame(est = pmin(est, 1)), aes(est)) +
  geom_histogram(binwidth = 0.025, boundary = 0, fill = te_pal$sage,
                 colour = te_pal$forest, linewidth = 0.25) +
  geom_vline(xintercept = truth_prop, colour = te_pal$ink, linewidth = 0.9) +
  geom_vline(xintercept = qs, colour = te_pal$clay, linewidth = 0.7, linetype = "22") +
  annotate("text", x = qs[2] - 0.012, y = 432, hjust = 1, size = 3.1,
           colour = te_pal$clay,
           label = "Upper bound of the central 95 per cent of estimates") +
  annotate("text", x = qs[1] + 0.03, y = 250, hjust = 0, size = 3.1,
           colour = te_pal$clay,
           label = "Lower bound, sitting at zero") +
  annotate("text", x = truth_prop + 0.018, y = 348, hjust = 0, size = 3.1,
           colour = te_pal$ink, fontface = "bold",
           label = "The truth") +
  labs(x = "Estimated overlap, proportion of the benthic ellipse", y = "Replicates",
       title = "One truth, and the answers fifteen individuals give") +
  theme_te()

## ---- wishart ----
rinvwish2 <- function(m, S, df) {
  L <- t(chol(solve(S)))
  a11 <- sqrt(rchisq(m, df))
  a22 <- sqrt(rchisq(m, df - 1))
  a21 <- rnorm(m)
  m11 <- L[1, 1] * a11
  m21 <- L[2, 1] * a11 + L[2, 2] * a21
  m22 <- L[2, 2] * a22
  w11 <- m11^2; w12 <- m11 * m21; w22 <- m21^2 + m22^2
  dw <- w11 * w22 - w12^2
  cbind(s11 = w22 / dw, s12 = -w12 / dw, s22 = w11 / dw, det = 1 / dw)
}

set.seed(4407)
S_check <- matrix(c(9.0, 2.5, 2.5, 6.0), 2)
df_check <- 14L
n_check <- 200000L
chk <- rinvwish2(n_check, S_check, df_check)
target <- c(S_check[1, 1], S_check[1, 2], S_check[2, 2]) / (df_check - 3)
print(round(rbind(sampler = colMeans(chk[, 1:3]), analytic = target), 4))
c(check_df = df_check, check_draws = n_check)
signif(c(max_relative_error = max(abs(colMeans(chk[, 1:3]) / target - 1))), 2)

## ---- ordering ----
set.seed(881)
S_narrow <- 0.6 * S_b
n_draw <- 4000

post_narrower <- function(xa, xb, m) {
  da <- rinvwish2(m, (nrow(xa) - 1) * cov(xa), nrow(xa) - 1)[, "det"]
  db <- rinvwish2(m, (nrow(xb) - 1) * cov(xb), nrow(xb) - 1)[, "det"]
  mean(da < db)
}

x_narrow <- rmvn(n_ind, mu_b, S_narrow); x_wide <- rmvn(n_ind, mu_p, S_b)
y_one <- rmvn(n_ind, mu_b, S_b); y_two <- rmvn(n_ind, mu_p, S_b)

round(c(true_area_ratio = sqrt(det(S_narrow) / det(S_b)),
        posterior_draws = n_draw,
        P_narrower_when_true = post_narrower(x_narrow, x_wide, n_draw),
        P_narrower_when_equal = post_narrower(y_one, y_two, n_draw)), 4)

## ---- false-confidence ----
set.seed(5150)
n_study <- 1200
pr_eq <- numeric(n_study); pr_tr <- numeric(n_study)
for (i in seq_len(n_study)) {
  pr_eq[i] <- post_narrower(rmvn(n_ind, mu_b, S_b), rmvn(n_ind, mu_p, S_b), n_draw)
  pr_tr[i] <- post_narrower(rmvn(n_ind, mu_b, S_narrow), rmvn(n_ind, mu_p, S_b), n_draw)
}
round(c(studies = n_study,
        equal_median_P = median(pr_eq),
        equal_P_above_0.95 = mean(pr_eq > 0.95),
        equal_P_below_0.05 = mean(pr_eq < 0.05),
        false_confidence_rate = mean(pr_eq > 0.95 | pr_eq < 0.05)), 4)
round(c(true_median_P = median(pr_tr),
        true_P_above_0.95 = mean(pr_tr > 0.95),
        true_wrong_side_of_half = mean(pr_tr < 0.5)), 4)

## ---- disjoint ----
set.seed(303)
prey_low <- c(-27.0, 6.0)
prey_high <- c(-21.5, 8.5)
tdf <- c(0.4, 3.4)
sig_ind <- matrix(c(0.16, 0.02, 0.02, 0.13), 2)
n_cons <- 60

draw_consumer <- function(n) {
  w <- rbeta(n, 2.5, 2.5)
  base <- cbind(w * prey_low[1] + (1 - w) * prey_high[1],
                w * prey_low[2] + (1 - w) * prey_high[2])
  base + t(t(chol(sig_ind)) %*% matrix(rnorm(2 * n), nrow = 2)) +
    matrix(tdf, nrow = n, ncol = 2, byrow = TRUE)
}

diet_a <- c(0.5, 0.0, 0.5, 0.0)
diet_b <- c(0.0, 0.5, 0.0, 0.5)

xa <- draw_consumer(n_cons); xb <- draw_consumer(n_cons)
Sa <- cov(xa); Sb2 <- cov(xb)
ov_ab <- ell_overlap(colMeans(xa), Sa, colMeans(xb), Sb2, p_std, n_slab)

round(c(consumers_per_group = n_cons, prey_species = length(diet_a),
        shared_prey_species = sum(diet_a > 0 & diet_b > 0),
        true_dietary_overlap = sum(pmin(diet_a, diet_b)),
        true_isotopic_overlap = 1), 4)
round(c(measured_over_a = ov_ab / ell_area(Sa, p_std),
        measured_over_b = ov_ab / ell_area(Sb2, p_std),
        centroid_distance = sqrt(sum((colMeans(xa) - colMeans(xb))^2))), 4)

## ---- disjoint-reps ----
set.seed(717)
n_rep2 <- 300
rep_ov <- sapply(seq_len(n_rep2), function(i) {
  a <- draw_consumer(n_cons); b <- draw_consumer(n_cons)
  Aa <- cov(a); Bb <- cov(b)
  ell_overlap(colMeans(a), Aa, colMeans(b), Bb, p_std, 1500) / ell_area(Aa, p_std)
})
round(c(replicates = n_rep2, percentile_low = 5, percentile_high = 95,
        median_measured_overlap = median(rep_ov),
        lower_5 = as.numeric(quantile(rep_ov, 0.05)),
        upper_95 = as.numeric(quantile(rep_ov, 0.95))), 4)

## ---- fig-disjoint ----
pts <- rbind(data.frame(x = xa[, 1], y = xa[, 2], grp = "consumer A: prey 1 and 3"),
             data.frame(x = xb[, 1], y = xb[, 2], grp = "consumer B: prey 2 and 4"))
ells <- rbind(
  data.frame(ell_path(colMeans(xa), Sa, p_std), grp = "consumer A: prey 1 and 3"),
  data.frame(ell_path(colMeans(xb), Sb2, p_std), grp = "consumer B: prey 2 and 4"))
shade <- overlap_path(colMeans(xa), Sa, colMeans(xb), Sb2, p_std)
mixline <- data.frame(x = c(prey_low[1], prey_high[1]) + tdf[1],
                      y = c(prey_low[2], prey_high[2]) + tdf[2])
preys <- mixline

ggplot(pts, aes(x, y, colour = grp)) +
  geom_polygon(data = shade, aes(x, y), inherit.aes = FALSE,
               fill = te_pal$gold, alpha = 0.4) +
  geom_line(data = mixline, aes(x, y), inherit.aes = FALSE,
            colour = te_pal$ink, linetype = "22", linewidth = 0.5) +
  geom_point(size = 1.6, alpha = 0.85) +
  geom_path(data = ells, aes(x, y, colour = grp), linewidth = 0.9) +
  geom_point(data = preys, aes(x, y), inherit.aes = FALSE, shape = 22,
             size = 3.4, stroke = 1.1, colour = te_pal$ink, fill = te_pal$paper) +
  annotate("text", x = min(mixline$x) - 0.15, y = max(mixline$y) + 0.34, hjust = 0,
           size = 3.0, colour = "#3d4a41",
           label = "Open squares: the two prey signatures after discrimination") +
  annotate("text", x = max(mixline$x) + 0.15, y = min(mixline$y) - 0.16, hjust = 1,
           size = 3.0, colour = "#3d4a41",
           label = "Dotted line: mixtures of those two") +
  scale_colour_manual(values = c(te_pal$forest, te_pal$clay), name = NULL) +
  labs(x = expression(delta^13 * "C (per mil)"), y = expression(delta^15 * "N (per mil)"),
       title = "Disjoint diets, one isotopic niche") +
  theme_te() +
  theme(legend.position = "top")
