# Thermal performance curves in R
# https://tidyecology.com/posts/thermal-performance-curves/
#
# 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-06-29

## ---- setup ----
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE,
                      dev = "png", dpi = 120, fig.path = "figures/",
                      fig.width = 7, fig.height = 4.4)
library(ggplot2)
theme_te <- theme_minimal(base_size = 12) +
  theme(panel.background = element_rect(fill = "#f5f4ee", colour = NA),
        plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
        panel.grid.minor = element_blank(),
        plot.title = element_text(face = "bold", size = 12))
theme_set(theme_te)
col_dat <- "#555555"; col_bri <- "#3a6b52"; col_gau <- "#b5651d"; col_ref <- "#8a8a8a"

briere <- function(T, a, T0, Tm) { p <- a*T*(T-T0)*sqrt(pmax(Tm-T, 0)); p[T < T0 | T > Tm] <- 0; p }

## true curve
a0 <- 8e-4; T0 <- 8; Tm <- 42
Tg <- seq(0, 45, 0.01); Pg <- briere(Tg, a0, T0, Tm)
Topt_true <- Tg[which.max(Pg)]; Pmax_true <- max(Pg)
b80 <- range(Tg[Pg >= 0.8 * Pmax_true]); breadth <- diff(b80)
asym <- 100 * (Topt_true - T0) / (Tm - T0)

## simulate data
set.seed(391)
Td <- rep(seq(10, 40, 2.5), each = 4)
y  <- pmax(briere(Td, a0, T0, Tm) + rnorm(length(Td), 0, 0.03 * Pmax_true), 0)

## fits
fitB <- nls(y ~ aa*Td*(Td-t0)*sqrt(pmax(tm-Td, 0)),
            start = list(aa = 6e-4, t0 = 6, tm = 44), control = nls.control(warnOnly = TRUE))
cb <- coef(fitB)
TgB <- seq(cb["t0"], cb["tm"], 0.01); PgB <- cb["aa"]*TgB*(TgB-cb["t0"])*sqrt(pmax(cb["tm"]-TgB, 0))
Topt_B <- TgB[which.max(PgB)]; CTmax_B <- cb["tm"]
bf <- range(TgB[PgB >= 0.8 * max(PgB)]); breadth_fit <- diff(bf)

fitG <- nls(y ~ A*exp(-((Td-mo)^2)/(2*s^2)),
            start = list(A = Pmax_true, mo = Topt_true, s = 8), control = nls.control(warnOnly = TRUE))
cg <- coef(fitG); Topt_G <- cg["mo"]; CTmax_G <- cg["mo"] + 2 * cg["s"]
overest <- CTmax_G - Tm

## ---- briere ----
briere <- function(T, a, T0, Tm) {
  p <- a * T * (T - T0) * sqrt(pmax(Tm - T, 0))
  p[T < T0 | T > Tm] <- 0
  p
}

## ---- fit ----
set.seed(391)
Td <- rep(seq(10, 40, 2.5), each = 4)
y  <- pmax(briere(Td, 8e-4, 8, 42) + rnorm(length(Td), 0, 0.06), 0)
fitB <- nls(y ~ aa * Td * (Td - t0) * sqrt(pmax(tm - Td, 0)),
            start = list(aa = 6e-4, t0 = 6, tm = 44))
round(coef(fitB), 4)

## ---- fig-tpc ----
dd  <- data.frame(Td = Td, y = y)
cur <- data.frame(T = TgB, P = PgB)
ggplot(dd, aes(Td, y)) +
  annotate("rect", xmin = bf[1], xmax = bf[2], ymin = -Inf, ymax = Inf, fill = col_bri, alpha = 0.10) +
  geom_line(data = cur, aes(T, P), colour = col_bri, linewidth = 1) +
  geom_point(colour = col_dat, size = 2, alpha = 0.7) +
  geom_vline(xintercept = Topt_B, colour = col_bri, linetype = "dashed") +
  annotate("text", x = Topt_B - 0.5, y = 0.2, label = "optimum", angle = 90, hjust = 0, colour = col_bri, size = 3.4) +
  labs(x = "Temperature (C)", y = "Performance", title = "An asymmetric thermal performance curve")

## ---- gaussian ----
fitG <- nls(y ~ A * exp(-((Td - mo)^2) / (2 * s^2)),
            start = list(A = 2, mo = 34, s = 8))
round(coef(fitG), 3)

## ---- fig-compare ----
TgG <- seq(10, 58, 0.1); PgG <- cg["A"] * exp(-((TgG - cg["mo"])^2) / (2 * cg["s"]^2))
ggplot(dd, aes(Td, y)) +
  geom_point(colour = col_dat, size = 2, alpha = 0.7) +
  geom_line(data = cur, aes(T, P), colour = col_bri, linewidth = 1) +
  geom_line(data = data.frame(T = TgG, P = PgG), aes(T, P), colour = col_gau, linewidth = 1, linetype = "22") +
  geom_vline(xintercept = Tm, colour = col_ref, linetype = "dotted") +
  annotate("text", x = Tm + 0.4, y = 1.6, label = "true CTmax", hjust = 0, colour = col_ref, size = 3.4) +
  labs(x = "Temperature (C)", y = "Performance", title = "Symmetric curves overshoot the thermal limit")
