# Phylogenetic generalised least squares
# https://tidyecology.com/posts/phylogenetic-generalised-least-squares/
#
# 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(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")
    )
}

## ---- type1-sim ----
set.seed(2024)
tree <- rcoal(40)
tree$tip.label <- sprintf("t%02d", 1:40)

nsim <- 1000
p_ols <- p_pgls <- numeric(nsim)
b_ols <- b_pgls <- se_ols <- se_pgls <- numeric(nsim)   # slopes and reported SEs
set.seed(2024)
for (i in seq_len(nsim)) {
  xi <- rTraitCont(tree, "BM", sigma = 1)
  yi <- rTraitCont(tree, "BM", sigma = 1)   # evolved independently of xi
  di <- data.frame(sp = tree$tip.label, x = xi[tree$tip.label], y = yi[tree$tip.label])
  tab_ols   <- summary(lm(y ~ x, data = di))$coef
  p_ols[i]  <- tab_ols[2, 4]
  fit_pgls  <- gls(y ~ x, data = di, correlation = corBrownian(1, tree, form = ~sp))
  tab_pgls  <- summary(fit_pgls)$tTable
  p_pgls[i] <- tab_pgls[2, 4]
  b_ols[i]  <- tab_ols[2, 1];  se_ols[i]  <- tab_ols[2, 2]
  b_pgls[i] <- tab_pgls[2, 1]; se_pgls[i] <- tab_pgls[2, 2]
}

c(ols_false_positive  = mean(p_ols  < 0.05),
  pgls_false_positive = mean(p_pgls < 0.05))

## ---- fig-pvalue-null ----
dfp <- rbind(data.frame(method = "ordinary least squares", p = p_ols),
             data.frame(method = "PGLS (Brownian)",        p = p_pgls))
dfp$method <- factor(dfp$method, levels = c("ordinary least squares", "PGLS (Brownian)"))
ggplot(dfp, aes(p)) +
  geom_histogram(breaks = seq(0, 1, 0.05), fill = te_sage, colour = te_paper, linewidth = 0.2) +
  geom_vline(xintercept = 0.05, colour = te_rust, linewidth = 0.8, linetype = "22") +
  facet_wrap(~method) +
  labs(x = "p-value for the slope (true slope is zero)", y = "count of datasets",
       title = "A valid test spreads p-values evenly") +
  theme_te(12)

## ---- fit-data ----
sim_pagel <- function(phy, lambda, sigma2 = 1) {
  V <- vcv(phy); Vl <- V * lambda; diag(Vl) <- diag(V)
  MASS::mvrnorm(1, rep(0, nrow(V)), sigma2 * Vl)
}
set.seed(101); tr <- rcoal(60); tr$tip.label <- sprintf("s%02d", 1:60)
set.seed(102); x <- sim_pagel(tr, 0.9)
set.seed(103); y <- 0.6 * x + sim_pagel(tr, 0.5, sigma2 = 1)
d <- data.frame(sp = tr$tip.label, x = x[tr$tip.label], y = y[tr$tip.label])

m_ols   <- gls(y ~ x, data = d, method = "ML")
m_bm    <- gls(y ~ x, data = d, correlation = corBrownian(1, tr, form = ~sp), method = "ML")
m_pagel <- gls(y ~ x, data = d, correlation = corPagel(0.5, tr, form = ~sp), method = "ML")
lambda_hat <- as.numeric(coef(m_pagel$modelStruct$corStruct, unconstrained = FALSE))

rbind(
  ols   = c(slope = coef(m_ols)[2],   AIC = AIC(m_ols)),
  brown = c(slope = coef(m_bm)[2],    AIC = AIC(m_bm)),
  pagel = c(slope = coef(m_pagel)[2], AIC = AIC(m_pagel)))

## ---- fig-three-fits ----
rng <- range(d$x); mx <- mean(d$x); my <- mean(d$y)
line_at <- function(b) data.frame(x = rng, y = my + b * (rng - mx))
lines_df <- rbind(
  cbind(model = "true (0.6)",              line_at(0.6)),
  cbind(model = "ordinary least squares",  line_at(coef(m_ols)[2])),
  cbind(model = "Brownian (lambda = 1)",   line_at(coef(m_bm)[2])),
  cbind(model = sprintf("Pagel (lambda = %.2f)", lambda_hat), line_at(coef(m_pagel)[2])))
lev <- c("true (0.6)", "ordinary least squares", "Brownian (lambda = 1)",
         sprintf("Pagel (lambda = %.2f)", lambda_hat))
lines_df$model <- factor(lines_df$model, levels = lev)
ggplot(d, aes(x, y)) +
  geom_point(colour = te_faint, alpha = 0.6, size = 1.8) +
  geom_line(data = lines_df, aes(colour = model, linetype = model), linewidth = 0.9) +
  scale_colour_manual(values = c(te_ink, te_rust, te_gold, te_green)) +
  scale_linetype_manual(values = c("22", "solid", "solid", "solid")) +
  labs(x = "trait x", y = "trait y", colour = NULL, linetype = NULL,
       title = "Estimating lambda lets the data set the correction") +
  guides(colour = guide_legend(nrow = 2), linetype = guide_legend(nrow = 2)) +
  theme_te(12) + theme(legend.position = "bottom")
