# Jensen’s inequality and thermal variability
# https://tidyecology.com/posts/jensens-inequality-and-thermal-variability/
#
# 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 ----
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_curve <- "#3a6b52"; col_hi <- "#b5651d"; col_ref <- "#555555"

briere <- function(T, a = 8e-4, T0 = 8, Tm = 42) {
  p <- a*T*(T-T0)*sqrt(pmax(Tm-T, 0)); p[T < T0 | T > Tm] <- 0; p }
Tg <- seq(0, 45, 0.005); Pg <- briere(Tg); Topt <- Tg[which.max(Pg)]

## inflection on the rising limb (curvature sign change)
d2 <- diff(Pg, differences = 2)
infl_all <- Tg[which(diff(sign(d2)) != 0) + 1]
infl <- infl_all[infl_all > 12 & infl_all < Topt][1]

## expected performance over Normal(mu, sd)
EP <- function(mu, sd) { x <- seq(mu-4*sd, mu+4*sd, length = 4001); w <- dnorm(x, mu, sd); sum(briere(x)*w)/sum(w) }

g_lo <- EP(20, 6) - briere(20)      # below inflection: helps
g_opt <- EP(Topt, 6) - briere(Topt) # at optimum: hurts
loss_opt <- 100 * (1 - EP(Topt, 6) / briere(Topt))

## loss at optimum vs sd
sds <- c(2, 4, 6, 8)
loss_tab <- sapply(sds, function(s) 100 * (1 - EP(Topt, s) / briere(Topt)))

## optimal mean temperature vs sd
best_mu <- function(sd) { mus <- seq(20, 40, 0.05); mus[which.max(sapply(mus, EP, sd = sd))] }
bm <- sapply(c(3, 6, 9), best_mu); shift <- Topt - bm

## ---- ep ----
briere <- function(T, a = 8e-4, T0 = 8, Tm = 42) {
  p <- a*T*(T-T0)*sqrt(pmax(Tm-T, 0)); p[T < T0 | T > Tm] <- 0; p }
EP <- function(mu, sd) {                       # expected performance over Normal(mu, sd)
  x <- seq(mu-4*sd, mu+4*sd, length = 4001); w <- dnorm(x, mu, sd)
  sum(briere(x) * w) / sum(w)
}
c(at_mean_20  = briere(20),  expected_20  = EP(20, 6),
  at_mean_opt = briere(Topt), expected_opt = EP(Topt, 6))

## ---- fig-jensen ----
mk <- function(mu, sd = 6, lab) {
  xs <- seq(mu-3*sd, mu+3*sd, 0.1)
  data.frame(T = xs, dens = dnorm(xs, mu, sd), mu = mu, lab = lab,
             at = briere(mu), ex = EP(mu, sd))
}
band <- rbind(mk(20, lab = "mean 20 C (accelerating: variation helps)"),
              mk(Topt, lab = "mean at optimum (variation hurts)"))
cur  <- data.frame(T = Tg, P = Pg)
ggplot() +
  geom_line(data = cur, aes(T, P), colour = col_curve, linewidth = 1) +
  geom_area(data = band, aes(T, dens * 3), fill = col_hi, alpha = 0.25) +
  geom_point(data = unique(band[, c("mu","at","lab")]), aes(mu, at), colour = col_ref, size = 2.6) +
  geom_point(data = unique(band[, c("mu","ex","lab")]), aes(mu, ex), colour = col_hi, size = 2.6, shape = 17) +
  facet_wrap(~lab) +
  labs(x = "Temperature (C)", y = "Performance",
       title = "Mean performance is not performance at the mean") +
  theme(strip.text = element_text(size = 9))

## ---- best-mean ----
best_mu <- function(sd) { mus <- seq(20, 40, 0.05); mus[which.max(sapply(mus, EP, sd = sd))] }
sapply(c(3, 6, 9), best_mu)          # optimal mean temperature at three variability levels

## ---- fig-loss ----
dl <- data.frame(sd = seq(0, 9, 0.25))
dl$loss <- sapply(dl$sd, function(s) if (s == 0) 0 else 100 * (1 - EP(Topt, s) / briere(Topt)))
ggplot(dl, aes(sd, loss)) +
  geom_line(colour = col_hi, linewidth = 1) +
  labs(x = "Thermal standard deviation (C)", y = "Performance loss at the optimum (%)",
       title = "More variable, not warmer: variance alone costs performance")
