# Independent contrasts: Felsenstein’s method
# https://tidyecology.com/posts/independent-contrasts-felsenstein/
#
# 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(ape)
library(nlme)
library(ggplot2)

te_paper <- "#f5f4ee"; te_ink   <- "#16241d"; te_body <- "#2c3a31"
te_faint <- "#5d6b61"; te_sage  <- "#93a87f"; te_rust <- "#b5534e"
te_line  <- "#dad9ca"; te_green <- "#2f8f63"; te_gold <- "#cda23f"

theme_te <- function(base_size = 12) {
  theme_minimal(base_size = base_size) +
    theme(
      plot.background  = element_rect(fill = te_paper, colour = NA),
      panel.background = element_rect(fill = te_paper, colour = NA),
      panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
      panel.grid.minor = element_blank(),
      axis.text  = element_text(colour = te_body),
      axis.title = element_text(colour = te_ink),
      plot.title = element_text(colour = te_ink, face = "bold"),
      strip.text = element_text(colour = te_ink, face = "bold")
    )
}

## ---- data ----
set.seed(1)
tree <- rcoal(50)
tree$tip.label <- sprintf("t%02d", 1:50)
x <- rTraitCont(tree, model = "BM", sigma = 1)
y <- 0.75 * x + rTraitCont(tree, model = "BM", sigma = 0.6)

## ---- contrasts ----
cx <- pic(x, tree)
cy <- pic(y, tree)
length(cx)

## ---- pic-fit ----
m_pic <- lm(cy ~ cx - 1)
c(slope = coef(m_pic)[[1]], se = summary(m_pic)$coef[1, 2],
  p = summary(m_pic)$coef[1, 4])

## ---- ols-fit ----
m_ols <- lm(y ~ x)
c(slope = coef(m_ols)[[2]], se = summary(m_ols)$coef[2, 2],
  p = summary(m_ols)$coef[2, 4])

## ---- fig-raw-vs-contrasts ----
rng_x <- range(x); rng_cx <- range(cx)
lev <- c("species values (ordinary regression)", "contrasts (through the origin)")
pts <- rbind(
  data.frame(panel = lev[1], xv = x,  yv = y),
  data.frame(panel = lev[2], xv = cx, yv = cy))
ln <- rbind(
  data.frame(panel = lev[1], xv = rng_x,  yv = coef(m_ols)[1] + coef(m_ols)[2] * rng_x),
  data.frame(panel = lev[2], xv = rng_cx, yv = coef(m_pic)[1] * rng_cx))
pts$panel <- factor(pts$panel, levels = lev)
ln$panel  <- factor(ln$panel,  levels = lev)
ggplot(pts, aes(xv, yv)) +
  geom_point(colour = te_green, alpha = 0.7, size = 1.8) +
  geom_line(data = ln, colour = te_rust, linewidth = 0.9) +
  facet_wrap(~panel, scales = "free") +
  labs(x = "trait x  (or its contrast)", y = "trait y  (or its contrast)",
       title = "From species values to independent contrasts") +
  theme_te(12)

## ---- diagnostic ----
pic_x <- pic(x, tree, var.contrasts = TRUE)
abs_c <- abs(pic_x[, "contrasts"])
sd_c  <- sqrt(pic_x[, "variance"])
ct    <- cor.test(abs_c, sd_c)
c(correlation = unname(ct$estimate), p = ct$p.value)

## ---- fig-diagnostic ----
ggplot(data.frame(sd_c, abs_c), aes(sd_c, abs_c)) +
  geom_point(colour = te_gold, size = 2, alpha = 0.8) +
  geom_smooth(method = "lm", formula = y ~ x,
              colour = te_ink, fill = te_sage, alpha = 0.25, linewidth = 0.7) +
  labs(x = "standard deviation of the contrast",
       y = "absolute standardised contrast",
       title = "No clear trend, consistent with adequate branch lengths") +
  theme_te(12)

## ---- pgls-equivalence ----
d <- data.frame(sp = tree$tip.label, x = x[tree$tip.label], y = y[tree$tip.label])
m_pgls <- gls(y ~ x, data = d, correlation = corBrownian(1, tree, form = ~sp))
c(pic_slope  = coef(m_pic)[[1]],
  pgls_slope = coef(m_pgls)[[2]],
  difference = abs(coef(m_pic)[[1]] - coef(m_pgls)[[2]]))
