# Ancestral state reconstruction in R
# https://tidyecology.com/posts/ancestral-state-reconstruction/
#
# 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-11-15

## ---- setup ----
library(ape)
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"
te_forest <- "#275139"

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

## ---- cont-fit ----
set.seed(7)
tr_c <- rcoal(40)
tr_c$tip.label <- sprintf("t%02d", 1:40)
set.seed(20)
xc <- rTraitCont(tr_c, model = "BM", sigma = 1, root.value = 0)  # true root = 0

fit_c <- ace(xc[tr_c$tip.label], tr_c, type = "continuous", method = "REML")
root_est <- fit_c$ace[1]        # first internal node is the root
root_ci  <- fit_c$CI95[1, ]
c(root_estimate = root_est, lower = root_ci[1], upper = root_ci[2])

## ---- fig-continuous-ci ----
Ntip <- length(tr_c$tip.label)
nn   <- (Ntip + 1):(Ntip + tr_c$Nnode)
bt   <- branching.times(tr_c)
dfc  <- data.frame(node = nn, age = as.numeric(bt[as.character(nn)]),
                   est = fit_c$ace, lo = fit_c$CI95[, 1], hi = fit_c$CI95[, 2])
dfc$root <- dfc$node == (Ntip + 1)
ggplot(dfc, aes(age, est)) +
  geom_hline(yintercept = 0, colour = te_faint, linetype = "22") +
  geom_linerange(aes(ymin = lo, ymax = hi, colour = root), linewidth = 0.6, alpha = 0.8) +
  geom_point(aes(colour = root), size = 1.8) +
  scale_colour_manual(values = c(`FALSE` = te_sage, `TRUE` = te_rust), guide = "none") +
  scale_x_continuous(transform = scales::compose_trans(scales::sqrt_trans(),
                                                       scales::reverse_trans()),
                     breaks = c(0, 0.05, 0.2, 0.5, 1)) +
  annotate("text", x = max(dfc$age), y = dfc$est[dfc$root] + 0.18, label = "root",
           colour = te_rust, hjust = 0, size = 3.5, fontface = "bold") +
  labs(x = "node age (time before present)", y = "reconstructed trait value",
       title = "Uncertainty grows toward the root") +
  theme_te(12)

## ---- disc-fit ----
set.seed(58)
tr_d <- rcoal(36)
tr_d$tip.label <- sprintf("s%02d", 1:36)
set.seed(58)
xd <- suppressWarnings(rTraitDisc(tr_d, model = "ER", k = 2, rate = 0.6,
                                  states = c("open", "forest"), root.value = 1))
tb <- table(factor(xd, levels = c("open", "forest")))

fit_d <- ace(xd[tr_d$tip.label], tr_d, type = "discrete", model = "ER")
rootp <- fit_d$lik.anc[1, ]           # state probabilities at the root
c(rate = unname(fit_d$rates), rootp)

## ---- fig-discrete-tree ----
co <- c(open = te_gold, forest = te_forest)
par(bg = te_paper, mar = c(0, 0, 2, 0))
plot(tr_d, show.tip.label = FALSE, edge.color = te_faint, edge.width = 1.3)
title(main = "Tip states and node probabilities on the tree", col.main = te_ink,
      cex.main = 1.0, font.main = 2)
tiplabels(pch = 21, bg = co[as.character(xd[tr_d$tip.label])], col = te_paper, cex = 1.2)
nodelabels(pie = fit_d$lik.anc, piecol = c(te_gold, te_forest), cex = 0.45)
legend("bottomleft", legend = c("open", "forest"), pt.bg = c(te_gold, te_forest),
       pch = 21, col = te_paper, bty = "n", text.col = te_body, cex = 0.9)
