# Stable isotope mixing models in R
# https://tidyecology.com/posts/isotope-mixing-models-in-r/
#
# 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-15

## ---- 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(),
          legend.position = "none")
}
te_green <- "#275139"
te_pal <- c("#275139", "#8c6d1f", "#7a1f1f", "#1f5c7a")

## ---- sources ----
# Four sources, already corrected to the consumer's trophic level.
# Columns are the two tracers (d13C, d15N).
src <- rbind(C3    = c(-29,  4),
             C4    = c(-13,  6),
             Algae = c(-15, 12),
             SPOM  = c(-28, 10))
colnames(src) <- c("d13C", "d15N")
consumer <- c(d13C = -20, d15N = 8)
src

## ---- fig-space ----
hull <- src[chull(src), ]
hull_df <- as.data.frame(rbind(hull, hull[1, ]))
sd_df <- data.frame(src, lab = rownames(src))
# push each label outside the polygon: C3 below, C4 to the right, the top two above
sd_df$hj <- c(C3 = 0.5, C4 = -0.4, Algae = 0.5, SPOM = 0.5)[sd_df$lab]
sd_df$vj <- c(C3 = 1.8, C4 = 0.5, Algae = -1, SPOM = -1)[sd_df$lab]
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, hjust = hj, vjust = vj), size = 3.6) +
  geom_point(aes(consumer["d13C"], consumer["d15N"]), shape = 4, size = 4,
             stroke = 1.2, colour = "#7a1f1f") +
  annotate("text", x = consumer["d13C"], y = consumer["d15N"] - 0.7,
           label = "consumer", size = 3.6, colour = "#7a1f1f") +
  labs(x = expression(delta^13 * C~"(permil)"), y = expression(delta^15 * N~"(permil)"),
       title = "The mixing space") +
  scale_x_continuous(expand = expansion(mult = c(0.05, 0.08))) +
  scale_y_continuous(breaks = seq(4, 12, 2), expand = expansion(mult = c(0.1, 0.05))) +
  theme_te()

## ---- determined ----
S3 <- src[c("C3", "C4", "Algae"), ]        # drop the fourth source
M3 <- rbind(t(S3), 1)                       # 3 x 3: two tracer rows, one sum-to-one row
y3 <- c(consumer, 1)
p3 <- solve(M3, y3)
p3_c3    <- round(p3[1], 3)
p3_c4    <- round(p3[2], 3)
p3_algae <- round(p3[3], 3)
round(p3, 3)

## ---- underdetermined ----
M4 <- rbind(t(src), 1)                       # 3 x 4
dof <- ncol(M4) - qr(M4)$rank
pp <- qr.solve(M4, c(consumer, 1))           # one particular solution
ns <- svd(M4, nu = 0, nv = 4)$v[, 4]         # direction along the solution line
# walk along the line: p(t) = pp + t * ns, keep only t with all fractions >= 0
t_lo <- -Inf; t_hi <- Inf
for (j in 1:4) {
  if (ns[j] >  1e-12) t_lo <- max(t_lo, (-pp[j]) / ns[j])
  if (ns[j] < -1e-12) t_hi <- min(t_hi, (-pp[j]) / ns[j])
}
feas <- rbind(end_A = pp + t_lo * ns, end_B = pp + t_hi * ns)
colnames(feas) <- rownames(src)
dof
round(feas, 3)

## ---- ranges ----
rng <- apply(feas, 2, range)
width <- rng[2, ] - rng[1, ]
spom_lo <- round(rng[1, "SPOM"], 2); spom_hi <- round(rng[2, "SPOM"], 2)
wid_spom <- round(width["SPOM"], 2)
wid_algae <- round(width["Algae"], 2)
round(rbind(low = rng[1, ], high = rng[2, ], width = width), 3)

## ---- fig-feasible ----
rdf <- data.frame(src = factor(rownames(src), levels = rev(rownames(src))),
                  lo = rng[1, ], hi = rng[2, ], mid = colMeans(feas))
ggplot(rdf, aes(y = src)) +
  geom_segment(aes(x = lo, xend = hi, yend = src), linewidth = 6,
               colour = te_green, alpha = 0.35, lineend = "round") +
  geom_point(aes(x = mid), colour = te_green, size = 2.5) +
  scale_x_continuous(limits = c(0, 0.6)) +
  labs(x = "feasible diet fraction", y = NULL,
       title = "Four sources, two tracers: a band of answers") +
  theme_te()

## ---- outside ----
inpoly <- function(pt, poly) {           # ray-casting point-in-polygon
  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 <- src[chull(src), ]
out_consumer <- c(d13C = -31, d15N = 8)     # more depleted than any source
c(inside = inpoly(consumer, poly), outside = inpoly(out_consumer, poly))
