# Checking a stable isotope mixing model
# https://tidyecology.com/posts/checking-an-isotope-mixing-model/
#
# 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-05

## ---- setup ----
library(ggplot2)
theme_te <- function() {
  theme_minimal(base_size = 12) +
    theme(plot.title = element_text(face = "bold", size = 13),
          plot.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.grid.minor = element_blank())
}
te_green <- "#275139"
te_pal <- c("#275139", "#8c6d1f", "#7a1f1f", "#1f5c7a")
ldir <- function(x, a) lgamma(sum(a)) - sum(lgamma(a)) + sum((a - 1) * log(pmax(x, 1e-12)))
rdir <- function(a) { g <- pmax(rgamma(length(a), a, 1), 1e-300); g / sum(g) }
mix_mh <- function(y, Smu, Ssd, res, alpha = rep(1, nrow(Smu)),
                   kappa = 600, iter = 60000, burn = 12000, seed = 1) {
  n <- nrow(y); J <- nrow(Smu)
  loglik <- function(p) {
    mu <- as.numeric(t(Smu) %*% p); v <- as.numeric(t(Ssd^2) %*% (p^2)) + res^2
    sum(dnorm(y, rep(mu, each = n), rep(sqrt(v), each = n), log = TRUE))
  }
  set.seed(seed); p <- rep(1 / J, J); ll <- loglik(p) + ldir(p, alpha)
  keep <- matrix(NA_real_, iter, J); acc <- 0
  for (t in 1:iter) {
    ap <- pmax(kappa * p, 1e-3); ps <- rdir(ap); aps <- pmax(kappa * ps, 1e-3)
    lls <- loglik(ps) + ldir(ps, alpha)
    if (log(runif(1)) < (lls - ll) + ldir(p, aps) - ldir(ps, ap)) { p <- ps; ll <- lls; acc <- acc + 1 }
    keep[t, ] <- p
  }
  list(draws = keep[(burn + 1):iter, , drop = FALSE], acc = acc / iter)
}
Smu <- rbind(C3 = c(-29, 4), C4 = c(-13, 6), Algae = c(-15, 12), SPOM = c(-28, 10))
Ssd <- rbind(C3 = c(1.0, 0.8), C4 = c(1.2, 1.0), Algae = c(0.9, 1.1), SPOM = c(1.1, 0.9))
colnames(Smu) <- colnames(Ssd) <- c("d13C", "d15N"); res <- c(0.5, 0.4)

## ---- feasibility ----
inpoly <- function(pt, poly) {
  n <- nrow(poly); inside <- FALSE; j <- n
  for (i in 1:n) {
    xi <- poly[i, 1]; yi <- poly[i, 2]; xj <- poly[j, 1]; yj <- poly[j, 2]
    if (((yi > pt[2]) != (yj > pt[2])) &&
        (pt[1] < (xj - xi) * (pt[2] - yi) / (yj - yi) + xi)) inside <- !inside
    j <- i
  }
  inside
}
poly <- Smu[chull(Smu), ]
consumer_in  <- c(d13C = -24.3, d15N = 7.6)              # a plausible consumer
consumer_out <- c(d13C = -33,   d15N = 8)                # more depleted than any source
c(inside = inpoly(consumer_in, poly), outside = inpoly(consumer_out, poly))

## ---- outside-fit ----
set.seed(701)
y_out <- cbind(rnorm(20, consumer_out["d13C"], res[1]), rnorm(20, consumer_out["d15N"], res[2]))  # no mixture reaches this point, so only residual spread
fit_out <- mix_mh(y_out, Smu, Ssd, res, seed = 702)
do <- fit_out$draws; colnames(do) <- rownames(Smu)
spom_mean <- round(mean(do[, "SPOM"]), 3)
spom_sd <- round(sd(do[, "SPOM"]), 3)
round(rbind(mean = colMeans(do), sd = apply(do, 2, sd)), 3)

## ---- fig-feasibility ----
hull_df <- as.data.frame(rbind(poly, poly[1, ]))
sd_df <- data.frame(Smu, lab = rownames(Smu))
ggplot() +
  geom_polygon(data = hull_df, aes(d13C, d15N), fill = te_green, alpha = 0.10,
               colour = te_green, linewidth = 0.6) +
  geom_point(data = sd_df, aes(d13C, d15N), colour = te_green, size = 3) +
  geom_text(data = sd_df, aes(d13C, d15N, label = lab), vjust = -1, size = 3.4) +
  geom_point(aes(consumer_in["d13C"], consumer_in["d15N"]), shape = 4, size = 4, stroke = 1.2) +
  annotate("text", x = consumer_in["d13C"], y = consumer_in["d15N"] - 0.8,
           label = "inside", size = 3.4) +
  geom_point(aes(consumer_out["d13C"], consumer_out["d15N"]), shape = 4, size = 4,
             stroke = 1.2, colour = "#7a1f1f") +
  annotate("text", x = consumer_out["d13C"], y = consumer_out["d15N"] - 0.8,
           label = "outside", size = 3.4, colour = "#7a1f1f") +
  labs(x = expression(delta^13 * C~"(permil)"), y = expression(delta^15 * N~"(permil)"),
       title = "Is the consumer inside the polygon?") +
  theme_te()

## ---- prior-sensitivity ----
p_true <- c(0.40, 0.10, 0.20, 0.30); mu_in <- as.numeric(t(Smu) %*% p_true)
sd_in <- sqrt(as.numeric(t(Ssd^2) %*% (p_true^2)) + res^2)   # source spread mixed in, plus residual: what the model assumes
set.seed(303)
y_in <- cbind(rnorm(20, mu_in[1], sd_in[1]), rnorm(20, mu_in[2], sd_in[2]))
fit_in <- mix_mh(y_in, Smu, Ssd, res, seed = 404)
d <- fit_in$draws; colnames(d) <- rownames(Smu)
J <- 4
prior_sd_ind <- sqrt((J - 1) / (J^2 * (J + 1)))          # Beta(1, J-1): single source
prior_sd_agg <- sqrt(2 * (J - 2) / (J^2 * (J + 1)))      # Beta(2, J-2): sum of two sources
g <- d[, "C3"] + d[, "SPOM"]                             # the depleted group
shrink_ind <- round(prior_sd_ind / mean(apply(d, 2, sd)), 1)
shrink_agg <- round(prior_sd_agg / sd(g), 1)
c(prior_sd_individual = round(prior_sd_ind, 3), posterior_sd_individual = round(mean(apply(d, 2, sd)), 3),
  shrink_individual = shrink_ind)
c(prior_sd_aggregate = round(prior_sd_agg, 3), posterior_sd_aggregate = round(sd(g), 3),
  shrink_aggregate = shrink_agg)

## ---- fig-prior ----
xx <- seq(0, 1, length.out = 400)
prior_ind <- dbeta(xx, 1, J - 1); prior_agg <- dbeta(xx, 2, J - 2)
pf <- rbind(
  data.frame(x = xx, dens = prior_ind, kind = "prior", panel = "single source (C3)"),
  data.frame(x = density(d[, "C3"], from = 0, to = 1)$x,
             dens = density(d[, "C3"], from = 0, to = 1)$y, kind = "posterior", panel = "single source (C3)"),
  data.frame(x = xx, dens = prior_agg, kind = "prior", panel = "depleted group (C3 + SPOM)"),
  data.frame(x = density(g, from = 0, to = 1)$x,
             dens = density(g, from = 0, to = 1)$y, kind = "posterior", panel = "depleted group (C3 + SPOM)"))
pf$panel <- factor(pf$panel, levels = c("single source (C3)", "depleted group (C3 + SPOM)"))
ggplot(pf, aes(x, dens, colour = kind, linetype = kind)) +
  geom_line(linewidth = 0.8) +
  facet_wrap(~panel) +
  scale_colour_manual(values = c(prior = "grey55", posterior = te_green)) +
  scale_linetype_manual(values = c(prior = "dashed", posterior = "solid")) +
  labs(x = "diet fraction", y = "density", colour = NULL, linetype = NULL,
       title = "How far does the data move each quantity from its prior?") +
  theme_te() + theme(legend.position = "top")

## ---- aggregate-check ----
Smu3 <- rbind(Depleted = colMeans(Smu[c("C3", "SPOM"), ]), C4 = Smu["C4", ], Algae = Smu["Algae", ])
Ssd3 <- rbind(Depleted = sqrt(colMeans(Ssd[c("C3", "SPOM"), ]^2)), C4 = Ssd["C4", ], Algae = Ssd["Algae", ])
fit3 <- mix_mh(y_in, Smu3, Ssd3, res, alpha = rep(1, 3), seed = 808)
d3 <- fit3$draws; colnames(d3) <- rownames(Smu3)
post_hoc <- round(c(mean = mean(g), sd = sd(g)), 3)
a_priori <- round(c(mean = mean(d3[, "Depleted"]), sd = sd(d3[, "Depleted"])), 3)
rbind(a_posteriori = post_hoc, a_priori = a_priori, truth = c(mean = 0.70, sd = NA))
