# Discrimination and concentration in mixing models
# https://tidyecology.com/posts/discrimination-and-concentration-in-mixing/
#
# 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-14

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

## ---- tdf-setup ----
S3 <- rbind(C3 = c(-29, 4), C4 = c(-13, 6), Algae = c(-15, 12))
colnames(S3) <- c("d13C", "d15N")
p_true <- c(0.40, 0.30, 0.30)
TDF_true <- c(0.5, 3.4)                                  # true discrimination (d13C, d15N)
consumer <- as.numeric(t(S3) %*% p_true) + TDF_true      # consumer = diet mean + TDF
# solve for diet given an ASSUMED discrimination factor
solve_p <- function(TDF) {
  Sc <- sweep(S3, 2, TDF, "+")                           # correct sources by assumed TDF
  as.numeric(solve(rbind(t(Sc), 1), c(consumer, 1)))
}
round(solve_p(TDF_true), 3)                              # correct TDF -> true diet

## ---- tdf-sweep ----
grid <- c(2.4, 2.9, 3.4, 3.9, 4.4)                       # assumed TDF_N, true value is 3.4
est <- t(sapply(grid, function(tn) solve_p(c(0.5, tn))))
colnames(est) <- rownames(S3); rownames(est) <- paste0("TDF_N=", grid)
algae_lo <- round(est["TDF_N=2.4", "Algae"], 3)
algae_hi <- round(est["TDF_N=4.4", "Algae"], 3)
algae_shift <- round(algae_lo - algae_hi, 3)
c4_shift <- round(est["TDF_N=4.4", "C4"] - est["TDF_N=2.4", "C4"], 3)
round(est, 3)

## ---- fig-tdf ----
sw_df <- data.frame(
  TDF_N = rep(grid, 3),
  frac = c(est[, "C3"], est[, "C4"], est[, "Algae"]),
  src = factor(rep(rownames(S3), each = length(grid)), levels = rownames(S3)))
tr_df <- data.frame(src = factor(rownames(S3), levels = rownames(S3)), t = p_true)
ggplot(sw_df, aes(TDF_N, frac, colour = src)) +
  geom_hline(data = tr_df, aes(yintercept = t, colour = src),
             linetype = "dashed", linewidth = 0.5, alpha = 0.7, show.legend = FALSE) +
  geom_vline(xintercept = 3.4, colour = "grey55", linewidth = 0.5) +
  geom_line(linewidth = 1) + geom_point(size = 2) +
  scale_colour_manual(values = te_pal) +
  labs(x = expression("assumed"~delta^15 * N~"discrimination (permil)"),
       y = "estimated diet fraction", colour = NULL,
       title = "The assumed discrimination factor drives the estimate") +
  theme_te() + theme(legend.position = "top")

## ---- conc-setup ----
Sc <- rbind(Plant = c(-30, 2), Detritus = c(-20, 5), Invert = c(-24, 10))
colnames(Sc) <- c("d13C", "d15N")
conc <- rbind(Plant = c(C = 44, N = 2.5), Detritus = c(C = 42, N = 4), Invert = c(C = 45, N = 6.5))
p_bio <- c(0.55, 0.30, 0.15)                             # true diet by biomass
# concentration-weighted mixing: each element weighted by mass x concentration
w_c <- p_bio * conc[, "C"]; w_n <- p_bio * conc[, "N"]
consumer_c <- c(d13C = sum(w_c * Sc[, "d13C"]) / sum(w_c),
                d15N = sum(w_n * Sc[, "d15N"]) / sum(w_n))
round(consumer_c, 2)

## ---- conc-fit ----
# naive: plain linear mixing, concentrations assumed equal
p_naive <- as.numeric(solve(rbind(t(Sc), 1), c(consumer_c, 1)))
names(p_naive) <- rownames(Sc)
# concentration-weighted: recover the biomass diet by minimising the weighted mismatch
obj <- function(q) {
  p <- c(q, 1 - sum(q)); if (any(p < 0)) return(1e6)
  wc <- p * conc[, "C"]; wn <- p * conc[, "N"]
  (sum(wc * Sc[, "d13C"]) / sum(wc) - consumer_c["d13C"])^2 +
  (sum(wn * Sc[, "d15N"]) / sum(wn) - consumer_c["d15N"])^2
}
op <- optim(c(0.33, 0.33), obj, control = list(reltol = 1e-12))
p_weighted <- c(op$par, 1 - sum(op$par))
inv_naive <- round(p_naive["Invert"], 3)
inv_bias <- round(100 * (p_naive["Invert"] - p_bio[3]) / p_bio[3])
rbind(truth = p_bio, naive = round(p_naive, 3), weighted = round(p_weighted, 3))

## ---- fig-conc ----
cf_df <- data.frame(
  src = factor(rep(rownames(Sc), 3), levels = rownames(Sc)),
  frac = c(p_bio, p_naive, p_weighted),
  model = factor(rep(c("truth", "naive", "weighted"), each = 3),
                 levels = c("truth", "naive", "weighted")))
ggplot(cf_df, aes(src, frac, fill = model)) +
  geom_col(position = position_dodge(width = 0.75), width = 0.7) +
  scale_fill_manual(values = c(truth = "grey35", naive = "#7a1f1f", weighted = te_green)) +
  labs(x = NULL, y = "diet fraction", fill = NULL,
       title = "Here, ignoring concentration overcounts the rich source") +
  theme_te() + theme(legend.position = "top")
