# Bayesian stable isotope mixing models
# https://tidyecology.com/posts/bayesian-isotope-mixing-models/
#
# 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)
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")
# Dirichlet density (log) and sampler; a small effective-sample-size helper.
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) }
ess <- function(x) {
  x <- x - mean(x); n <- length(x)
  r <- acf(x, lag.max = min(2000, n - 1), plot = FALSE)$acf[-1]
  k <- which(r < 0.05)[1]; if (is.na(k)) k <- length(r)
  rho <- r[1:max(1, k - 1)]; n / (1 + 2 * sum(rho))
}

## ---- sampler ----
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)                       # mixture mean per tracer
    v  <- as.numeric(t(Ssd^2) %*% (p^2)) + res^2         # source + residual variance
    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)         # propose from Dirichlet(kappa * p)
    aps <- pmax(kappa * ps, 1e-3)
    lls <- loglik(ps) + ldir(ps, alpha)
    # Hastings ratio: likelihood + prior + reverse/forward proposal densities
    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)
}

## ---- sources ----
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)                                       # residual SD per tracer

## ---- calibration ----
S3 <- Smu[c("C3", "C4", "Algae"), ]; Sd3 <- Ssd[c("C3", "C4", "Algae"), ]
p_true3 <- c(0.40, 0.30, 0.30)
mu3 <- as.numeric(t(S3) %*% p_true3)
sd3 <- sqrt(as.numeric(t(Sd3^2) %*% p_true3^2) + res^2)   # spread the model assumes
set.seed(101)
y3 <- cbind(rnorm(30, mu3[1], sd3[1]), rnorm(30, mu3[2], sd3[2]))
fit3 <- mix_mh(y3, S3, Sd3, res, alpha = rep(1, 3), iter = 40000, burn = 8000, seed = 202)
cal_acc <- round(fit3$acc, 3)
cal_ess <- round(min(apply(fit3$draws, 2, ess)))
cal_means <- round(colMeans(fit3$draws), 3)
c(acceptance = cal_acc, min_ESS = cal_ess)
rbind(posterior_mean = cal_means, truth = p_true3)

## ---- fig-calibration ----
cal_df <- data.frame(frac = c(fit3$draws),
                     src = factor(rep(rownames(S3), each = nrow(fit3$draws)),
                                  levels = rownames(S3)))
tr_df <- data.frame(src = factor(rownames(S3), levels = rownames(S3)), t = p_true3)
ggplot(cal_df, aes(frac, fill = src, colour = src)) +
  geom_density(alpha = 0.35, linewidth = 0.5) +
  geom_vline(data = tr_df, aes(xintercept = t, colour = src),
             linetype = "dashed", linewidth = 0.6, show.legend = FALSE) +
  scale_fill_manual(values = te_pal) + scale_colour_manual(values = te_pal) +
  labs(x = "diet fraction", y = "posterior density", fill = NULL, colour = NULL,
       title = "Determined problem: the posterior finds the truth") +
  theme_te() + theme(legend.position = "top")

## ---- underdetermined ----
p_true4 <- c(0.40, 0.10, 0.20, 0.30)
mu4 <- as.numeric(t(Smu) %*% p_true4)
sd4 <- sqrt(as.numeric(t(Ssd^2) %*% p_true4^2) + res^2)
set.seed(303)
y4 <- cbind(rnorm(20, mu4[1], sd4[1]), rnorm(20, mu4[2], sd4[2]))
fit4 <- mix_mh(y4, Smu, Ssd, res, iter = 60000, burn = 12000, seed = 404)
d <- fit4$draws
colnames(d) <- rownames(Smu)
u_acc <- round(fit4$acc, 3)
u_ess <- round(min(apply(d, 2, ess)))
post <- t(apply(d, 2, function(z) c(mean = mean(z), sd = sd(z),
                                    lo = quantile(z, 0.025), hi = quantile(z, 0.975))))
rownames(post) <- rownames(Smu)
sd_spom <- round(post["SPOM", "sd"], 3)
sd_c3 <- round(post["C3", "sd"], 3)
round(cbind(post, truth = p_true4), 3)

## ---- fig-underdetermined ----
u_df <- data.frame(frac = c(d),
                   src = factor(rep(rownames(Smu), each = nrow(d)), levels = rownames(Smu)))
t4_df <- data.frame(src = factor(rownames(Smu), levels = rownames(Smu)), t = p_true4)
ggplot(u_df, aes(frac, fill = src, colour = src)) +
  geom_density(alpha = 0.30, linewidth = 0.5) +
  geom_vline(data = t4_df, aes(xintercept = t, colour = src),
             linetype = "dashed", linewidth = 0.6, show.legend = FALSE) +
  scale_fill_manual(values = te_pal) + scale_colour_manual(values = te_pal) +
  labs(x = "diet fraction", y = "posterior density", fill = NULL, colour = NULL,
       title = "Four sources, two tracers: a wide posterior") +
  theme_te() + theme(legend.position = "top")

## ---- point-solve ----
M <- rbind(t(Smu), 1)
b <- c(colMeans(y4), 1)
p_point <- as.numeric(t(M) %*% solve(M %*% t(M), b))     # minimum-norm solution
names(p_point) <- rownames(Smu)
round(p_point, 3)

## ---- correlations ----
C <- cor(d); dimnames(C) <- list(rownames(Smu), rownames(Smu))
cor_sc <- round(C["SPOM", "C3"], 2)
round(C, 2)

## ---- fig-correlation ----
cc_df <- data.frame(C3 = d[, 1], SPOM = d[, 4])
ggplot(cc_df, aes(C3, SPOM)) +
  geom_point(alpha = 0.08, colour = te_green, size = 0.6) +
  labs(x = "C3 fraction", y = "SPOM fraction",
       title = "The depleted sources trade off against each other") +
  theme_te()

## ---- aggregate ----
g_depleted <- d[, "C3"] + d[, "SPOM"]                    # true sum: 0.70
g_enriched <- d[, "C4"] + d[, "Algae"]                   # true sum: 0.30
summ <- function(z) c(mean(z), sd(z), as.numeric(quantile(z, c(0.025, 0.975))))
agg <- rbind(summ(g_depleted), summ(g_enriched))
dimnames(agg) <- list(c("C3 + SPOM", "C4 + Algae"), c("mean", "sd", "lo", "hi"))
sd_ind <- round(mean(apply(d, 2, sd)), 3)
sd_agg <- round(mean(c(sd(g_depleted), sd(g_enriched))), 3)
gain <- round(sd_ind / sd_agg, 1)
round(agg, 3)
c(individual_sd = sd_ind, aggregate_sd = sd_agg, narrower_by = gain)

## ---- fig-aggregate ----
agg_df <- rbind(
  data.frame(frac = d[, "C3"],  grp = "C3 (alone)"),
  data.frame(frac = d[, "SPOM"], grp = "SPOM (alone)"),
  data.frame(frac = g_depleted, grp = "C3 + SPOM (sum)"))
agg_df$grp <- factor(agg_df$grp, levels = c("C3 (alone)", "SPOM (alone)", "C3 + SPOM (sum)"))
ggplot(agg_df, aes(frac, colour = grp, fill = grp)) +
  geom_density(alpha = 0.25, linewidth = 0.6) +
  geom_vline(xintercept = 0.70, linetype = "dashed", colour = "grey30") +
  scale_colour_manual(values = c("#7fa793", "#b3a06a", te_green)) +
  scale_fill_manual(values = c("#a7c4b5", "#cdbf9a", te_green)) +
  labs(x = "diet fraction", y = "posterior density", colour = NULL, fill = NULL,
       title = "The sum is resolvable even when the parts are not") +
  theme_te() + theme(legend.position = "top")

## ---- more-data ----
set.seed(505)
y4b <- cbind(rnorm(200, mu4[1], sd4[1]), rnorm(200, mu4[2], sd4[2]))
fit4b <- mix_mh(y4b, Smu, Ssd, res, iter = 60000, burn = 12000, seed = 606)
# one data set is one draw: repeat both sizes on fresh data, own seeds for each
n_rep <- 8
sd_fit <- function(draws) mean(apply(draws, 2, sd))
sd_rep <- function(nn, k) {
  set.seed(1000 + k)
  yy <- cbind(rnorm(nn, mu4[1], sd4[1]), rnorm(nn, mu4[2], sd4[2]))
  sd_fit(mix_mh(yy, Smu, Ssd, res, iter = 60000, burn = 12000, seed = 2000 + k)$draws)
}
sd20 <- c(sd_fit(d), sapply(1:(n_rep - 1), function(k) sd_rep(20, k)))
sd200 <- c(sd_fit(fit4b$draws), sapply(n_rep:(2 * n_rep - 2), function(k) sd_rep(200, k)))
sd_small <- round(mean(sd20), 3)
sd_large <- round(mean(sd200), 3)
ratio <- round(sd_large / sd_small, 2)
round(rbind(n20 = sd20, n200 = sd200), 3)
c(sd_n20 = sd_small, sd_n200 = sd_large, ratio = ratio)
