# Degree days and thermal time in R
# https://tidyecology.com/posts/degree-days-and-thermal-time/
#
# 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-06

## ---- setup ----
library(ggplot2)

te_pal <- list(forest = "#275139", green = "#2f8f63", sage = "#93a87f",
               clay = "#b5534e", gold = "#cda23f", line = "#dad9ca",
               ink = "#16241d", paper = "#f5f4ee")

theme_te <- function() {
  theme_minimal(base_size = 12) +
    theme(panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "#e7e6dc"),
          plot.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          plot.title = element_text(face = "bold", colour = te_pal$ink),
          axis.title = element_text(colour = "#2c3a31"))
}

## ---- climate ----
set.seed(20260719)

doy_start <- 32       # 1 February
n_day     <- 250      # season length in days
n_step    <- 96       # sub-daily steps
t_low     <- 5        # hour of the daily minimum
t_high    <- 15       # hour of the daily maximum
night_k   <- 2.4      # curvature of the overnight decay
phi_ano   <- 0.72     # day to day autocorrelation of the weather anomaly
sd_ano    <- 2.8      # standard deviation of the weather anomaly
tbase_true <- 8       # true base temperature
K_true    <- 700      # true requirement, degree days
biofix    <- 60       # 1 March: the day accumulation truly starts
n_pool    <- 300      # independent simulated years

season_doy <- doy_start + seq_len(n_day) - 1
win_idx    <- which(season_doy >= biofix)[1]

gen_year <- function() {
  nn <- n_day + 2
  dd <- doy_start - 2 + seq_len(nn)
  mu <- 11 + 11 * cos(2 * pi * (dd - 201) / 365)
  e <- numeric(nn)
  e[1] <- rnorm(1, 0, sd_ano)
  for (i in 2:nn) e[i] <- phi_ano * e[i - 1] + sqrt(1 - phi_ano^2) * rnorm(1, 0, sd_ano)
  hh <- pmax(1.5, 4.5 + 1.2 * cos(2 * pi * (dd - 201) / 365) + rnorm(nn, 0, 0.8))
  list(L = mu + e - hh, H = mu + e + hh)
}

night_frac <- function(s) (exp(-night_k * s) - exp(-night_k)) / (1 - exp(-night_k))

fine_temp <- function(yr, nstep = n_step) {
  idx <- 2:(n_day + 1)
  tt <- (seq_len(nstep) - 0.5) * 24 / nstep
  nl <- 24 - (t_high - t_low)
  out <- matrix(0, nrow = n_day, ncol = nstep)
  pre <- tt < t_low; rise <- tt >= t_low & tt <= t_high; post <- tt > t_high
  L <- yr$L; H <- yr$H
  flat <- function(k) rep(1, k)
  out[, pre] <- outer(L[idx], flat(sum(pre))) +
    outer(H[idx - 1] - L[idx], night_frac((tt[pre] + 24 - t_high) / nl))
  out[, rise] <- outer(L[idx], flat(sum(rise))) +
    outer(H[idx] - L[idx], sin(pi / 2 * (tt[rise] - t_low) / (t_high - t_low)))
  out[, post] <- outer(L[idx + 1], flat(sum(post))) +
    outer(H[idx] - L[idx + 1], night_frac((tt[post] - t_high) / nl))
  out
}

row_min <- function(m) m[cbind(seq_len(nrow(m)), max.col(-m, ties.method = "first"))]
row_max <- function(m) m[cbind(seq_len(nrow(m)), max.col(m, ties.method = "first"))]

pool_L <- matrix(0, n_pool, n_day + 2); pool_H <- pool_L
tmin_m <- matrix(0, n_pool, n_day); tmax_m <- tmin_m; true_dd <- tmin_m; tmean_m <- tmin_m
for (i in seq_len(n_pool)) {
  yy <- gen_year(); ff <- fine_temp(yy)
  pool_L[i, ] <- yy$L; pool_H[i, ] <- yy$H
  tmin_m[i, ] <- row_min(ff); tmax_m[i, ] <- row_max(ff)
  tmean_m[i, ] <- rowMeans(ff)
  true_dd[i, ] <- rowSums(pmax(ff - tbase_true, 0)) / n_step
}
true_dd[, seq_len(win_idx - 1)] <- 0

ff1 <- fine_temp(list(L = pool_L[1, ], H = pool_H[1, ]))
ff1_fine <- fine_temp(list(L = pool_L[1, ], H = pool_H[1, ]), nstep = 960)
tot_96  <- sum((rowSums(pmax(ff1 - tbase_true, 0)) / n_step)[win_idx:n_day])
tot_960 <- sum((rowSums(pmax(ff1_fine - tbase_true, 0)) / 960)[win_idx:n_day])

round(c(years = n_pool, season_days = n_day, steps_per_day = n_step,
        minutes_per_step = 24 * 60 / n_step, hour_of_minimum = t_low,
        hour_of_maximum = t_high, night_decay_k = night_k,
        weather_sd = sd_ano, weather_autocorrelation = phi_ano,
        true_base = tbase_true, true_requirement = K_true,
        first_doy = doy_start, biofix_doy = biofix), 2)
round(c(mean_tmin = mean(tmin_m[, win_idx:n_day]), mean_tmax = mean(tmax_m[, win_idx:n_day]),
        mean_daily_range = mean((tmax_m - tmin_m)[, win_idx:n_day]),
        midpoint_minus_true_mean = mean(((tmin_m + tmax_m) / 2 - tmean_m)[, win_idx:n_day])), 3)
round(c(integral_96_steps = tot_96, integral_960_steps = tot_960,
        percent_gap = 100 * (tot_96 / tot_960 - 1)), 4)

## ---- event-truth ----
cross_from <- function(cs, dd, s, K) {
  offs <- if (s > 1) cs[s - 1] else 0
  tgt <- K + offs
  if (cs[length(cs)] < tgt) return(NA_real_)
  i <- which(cs >= tgt)[1]
  prev <- if (i == 1) 0 else cs[i - 1]
  (i - 1) + (tgt - prev) / dd[i]
}
cross_day <- function(dd, K, s = win_idx) cross_from(cumsum(dd), dd, s, K)
to_doy <- function(idx) idx + doy_start - 1

ev_true <- apply(true_dd, 1, cross_day, K = K_true)
round(c(mean_event_doy = mean(to_doy(ev_true)), sd_event_days = sd(ev_true),
        earliest_doy = min(to_doy(ev_true)), latest_doy = max(to_doy(ev_true))), 2)

## ---- fig-series ----
sel <- which(season_doy >= 88 & season_doy <= 108)
hour_mid <- (seq_len(n_step) - 0.5) * 24 / n_step
ser <- data.frame(
  day = rep(season_doy[sel], each = n_step) + rep(hour_mid / 24, length(sel)),
  temp = as.vector(t(ff1[sel, ])))
ser$top <- pmax(ser$temp, tbase_true)

ggplot(ser, aes(day, temp)) +
  geom_ribbon(aes(ymin = tbase_true, ymax = top), fill = te_pal$sage, alpha = 0.55) +
  geom_line(colour = te_pal$forest, linewidth = 0.35) +
  geom_hline(yintercept = tbase_true, colour = te_pal$clay, linewidth = 0.7) +
  scale_x_continuous(breaks = seq(90, 105, by = 5),
                     expand = expansion(mult = c(0.02, 0.02))) +
  labs(x = "Day of year", y = "Temperature (degrees C)",
       title = "The shaded area above the base line is the thermal time") +
  theme_te() +
  theme(plot.margin = margin(5.5, 12, 5.5, 5.5))

## ---- methods ----
dd_average <- function(tn, tx, tb) pmax((tn + tx) / 2 - tb, 0)

dd_triangle <- function(tn, tx, tb) {
  out <- pmax((tn + tx) / 2 - tb, 0)
  st <- tn < tb & tx > tb
  out[st] <- ((tx - tb)^2 / (2 * (tx - tn)))[st]
  out
}

dd_sine <- function(tn, tx, tb) {
  amp <- (tx - tn) / 2; avg <- (tx + tn) / 2
  out <- pmax(avg - tb, 0)
  st <- tn < tb & tx > tb
  th <- asin(pmin(1, pmax(-1, (tb - avg) / amp)))
  out[st] <- ((1 / pi) * ((avg - tb) * (pi / 2 - th) + amp * cos(th)))[st]
  out
}

mask <- function(m) { m[, seq_len(win_idx - 1)] <- 0; m }
dd_a <- mask(dd_average(tmin_m, tmax_m, tbase_true))
dd_t <- mask(dd_triangle(tmin_m, tmax_m, tbase_true))
dd_s <- mask(dd_sine(tmin_m, tmax_m, tbase_true))

tot <- function(m) rowSums(m)
season_tab <- rbind(
  total = c(truth = mean(tot(true_dd)), average = mean(tot(dd_a)),
            triangle = mean(tot(dd_t)), sine = mean(tot(dd_s))),
  pct_error = c(0, 100 * (mean(tot(dd_a)) / mean(tot(true_dd)) - 1),
                100 * (mean(tot(dd_t)) / mean(tot(true_dd)) - 1),
                100 * (mean(tot(dd_s)) / mean(tot(true_dd)) - 1)))
print(round(season_tab, 3))

ev_a <- apply(dd_a, 1, cross_day, K = K_true)
ev_t <- apply(dd_t, 1, cross_day, K = K_true)
ev_s <- apply(dd_s, 1, cross_day, K = K_true)
date_tab <- rbind(
  mean_doy = c(truth = mean(to_doy(ev_true)), average = mean(to_doy(ev_a)),
               triangle = mean(to_doy(ev_t)), sine = mean(to_doy(ev_s))),
  mean_days_from_truth = c(0, mean(ev_a - ev_true), mean(ev_t - ev_true),
                           mean(ev_s - ev_true)),
  worst_year_days = c(0, max(abs(ev_a - ev_true)), max(abs(ev_t - ev_true)),
                      max(abs(ev_s - ev_true))))
print(round(date_tab, 3))

## ---- fig-accum ----
yr <- 1
panel_lv <- c("Accumulated thermal time", "Difference from the truth")
meth_lv <- c("Continuous truth", "Simple average", "Single triangle", "Single sine")
cum_mat <- cbind(cumsum(true_dd[yr, ]), cumsum(dd_a[yr, ]),
                 cumsum(dd_t[yr, ]), cumsum(dd_s[yr, ]))
keep <- season_doy >= biofix
acc_df <- do.call(rbind, lapply(seq_along(meth_lv), function(j)
  data.frame(doy = season_doy[keep], value = cum_mat[keep, j], method = meth_lv[j],
             panel = panel_lv[1])))
dif_df <- do.call(rbind, lapply(seq_along(meth_lv), function(j)
  data.frame(doy = season_doy[keep], value = (cum_mat[, j] - cum_mat[, 1])[keep],
             method = meth_lv[j], panel = panel_lv[2])))
acc_long <- rbind(acc_df, dif_df)
acc_long$panel <- factor(acc_long$panel, levels = panel_lv)
acc_long$method <- factor(acc_long$method, levels = meth_lv)
cross_pts <- data.frame(
  doy = to_doy(c(ev_true[yr], ev_a[yr], ev_t[yr], ev_s[yr])),
  value = K_true, method = factor(meth_lv, levels = meth_lv),
  panel = factor(panel_lv[1], levels = panel_lv))
req_line <- data.frame(yv = K_true, panel = factor(panel_lv[1], levels = panel_lv))

ggplot(acc_long, aes(doy, value, colour = method)) +
  geom_hline(data = req_line, aes(yintercept = yv), colour = te_pal$ink,
             linetype = "22", linewidth = 0.6) +
  geom_line(linewidth = 0.8) +
  geom_point(data = cross_pts, size = 2.4) +
  facet_wrap(~panel, ncol = 1, scales = "free_y") +
  scale_colour_manual(values = c(te_pal$ink, te_pal$green, te_pal$gold, te_pal$clay),
                      name = NULL) +
  labs(x = "Day of year", y = "Degree days",
       title = "The methods separate on the days that straddle the base") +
  theme_te() +
  theme(legend.position = "top",
        strip.text = element_text(colour = te_pal$ink, face = "bold"))

## ---- straddle ----
strad <- tmin_m < tbase_true & tmax_m > tbase_true
strad[, seq_len(win_idx - 1)] <- FALSE
gap <- dd_s - dd_a
round(c(straddle_days_per_year = mean(rowSums(strad)),
        window_days = n_day - win_idx + 1,
        straddle_share_of_days = 100 * mean(rowSums(strad)) / (n_day - win_idx + 1),
        total_gap_per_year = mean(rowSums(gap)),
        share_of_gap_on_straddle_days = 100 * sum(gap[strad]) / sum(gap),
        mean_gap_straddle_days = mean(gap[strad]),
        mean_gap_other_days = mean(gap[!strad]),
        largest_single_day_gap = max(gap)), 4)
tri_gap <- dd_t - dd_a
round(c(share_of_triangle_gap_on_straddle_days = 100 * sum(tri_gap[strad]) / sum(tri_gap),
        mean_triangle_gap_straddle_days = mean(tri_gap[strad]),
        mean_doy_of_straddle_days = sum(strad * matrix(season_doy, n_pool, n_day,
          byrow = TRUE)) / sum(strad)), 4)
mid_bias <- mask((tmin_m + tmax_m) / 2 - tmean_m)
round(c(mean_midpoint_bias_per_day = mean(mid_bias[, win_idx:n_day]),
        bias_degree_days_to_event = mean(sapply(seq_len(n_pool), function(i) {
          k <- floor(ev_true[i]); sum(mid_bias[i, seq_len(k)]) })),
        as_percent_of_requirement = 100 * mean(sapply(seq_len(n_pool), function(i) {
          k <- floor(ev_true[i]); sum(mid_bias[i, seq_len(k)]) })) / K_true), 3)

## ---- base-sweep ----
bseq <- seq(4, 12, by = 0.5)
sweep_fixed <- sapply(bseq, function(b) {
  m <- mask(dd_sine(tmin_m, tmax_m, b))
  mean(to_doy(apply(m, 1, cross_day, K = K_true)))
})
cal_yr <- 1:20; test_yr <- 21:n_pool
sweep_recal <- t(sapply(bseq, function(b) {
  m <- mask(dd_sine(tmin_m, tmax_m, b))
  cs <- t(apply(m, 1, cumsum))
  acc <- sapply(seq_len(n_pool), function(i) {
    k <- floor(ev_true[i])
    cs[i, k] - cs[i, win_idx - 1] + (ev_true[i] - k) * m[i, k + 1]
  })
  req <- mean(acc[cal_yr])
  c(requirement = req,
    mean_doy = mean(to_doy(sapply(test_yr, function(i)
      cross_from(cs[i, ], m[i, ], win_idx, req)))))
}))
warm_shift <- 2
m8 <- mask(dd_sine(tmin_m, tmax_m, tbase_true))
m8w <- mask(dd_sine(tmin_m + warm_shift, tmax_m + warm_shift, tbase_true))
doy_base <- mean(to_doy(apply(m8, 1, cross_day, K = K_true)))
doy_warm <- mean(to_doy(apply(m8w, 1, cross_day, K = K_true)))

print(round(data.frame(base = bseq, published_requirement = sweep_fixed,
                       recalibrated = sweep_recal[, "mean_doy"],
                       requirement = sweep_recal[, "requirement"]), 2))
swing_full <- diff(range(sweep_fixed))
swing_mid <- diff(range(sweep_fixed[bseq >= 6 & bseq <= 10]))
round(c(warming_degrees = warm_shift, calibration_years = length(cal_yr),
        prediction_years = length(test_yr),
        swing_base_4_to_12 = swing_full,
        swing_base_6_to_10 = swing_mid,
        swing_when_recalibrated = diff(range(sweep_recal[, "mean_doy"])),
        baseline_doy = doy_base, warmed_doy = doy_warm,
        warming_shift_days = doy_base - doy_warm,
        ratio_full = swing_full / (doy_base - doy_warm),
        ratio_mid = swing_mid / (doy_base - doy_warm)), 3)

## ---- start-date ----
sseq <- seq(32, 92, by = 4)
start_tab <- sapply(c(4, 6, 8), function(b) {
  m <- dd_sine(tmin_m, tmax_m, b)
  cs <- t(apply(m, 1, cumsum))
  sapply(sseq, function(s) {
    si <- s - doy_start + 1
    mean(to_doy(sapply(seq_len(n_pool), function(i) cross_from(cs[i, ], m[i, ], si, K_true))))
  })
})
dimnames(start_tab) <- list(paste0("start_doy_", sseq), paste0("base_", c(4, 6, 8)))
print(round(start_tab, 2))
round(c(start_swing_base_8 = diff(range(start_tab[, "base_8"])),
        start_swing_base_6 = diff(range(start_tab[, "base_6"])),
        start_swing_base_4 = diff(range(start_tab[, "base_4"]))), 3)

## ---- fig-base ----
kind_lv <- c("Requirement taken from the literature",
             "Requirement recalibrated at each base")
base_df <- data.frame(
  base = rep(bseq, 2),
  doy = c(sweep_fixed, sweep_recal[, "mean_doy"]),
  kind = factor(rep(kind_lv, each = length(bseq)), levels = kind_lv))
arrow_df <- data.frame(x = tbase_true, xend = tbase_true, y = doy_base, yend = doy_warm)

ggplot(base_df, aes(base, doy, colour = kind)) +
  geom_line(linewidth = 0.9) +
  geom_point(size = 1.7) +
  geom_segment(data = arrow_df, aes(x = x, xend = xend, y = y, yend = yend),
               inherit.aes = FALSE, colour = te_pal$ink, linewidth = 0.9,
               arrow = arrow(length = unit(0.16, "cm"), ends = "both")) +
  annotate("text", x = tbase_true + 0.25, y = (doy_base + doy_warm) / 2,
           label = "2 degrees of warming", hjust = 0, size = 3.4, colour = te_pal$ink) +
  scale_colour_manual(values = c(te_pal$clay, te_pal$forest), name = NULL) +
  labs(x = "Assumed base temperature (degrees C)", y = "Mean predicted event, day of year",
       title = "The base is only meaningful with its requirement attached") +
  theme_te() +
  theme(legend.position = "top")

## ---- cv-method ----
bgrid <- seq(2, 14, by = 0.1)
wmat <- t(sapply(seq_len(n_pool), function(i) {
  k <- floor(ev_true[i]); w <- numeric(n_day)
  w[win_idx:k] <- 1; w[k + 1] <- ev_true[i] - k; w
}))
A_clean <- sapply(bgrid, function(b) rowSums(dd_sine(tmin_m, tmax_m, b) * wmat))
pick_base <- function(AA, rows, gg) {
  sub <- AA[rows, , drop = FALSE]
  mu <- colMeans(sub)
  sdv <- sqrt(colSums((sub - rep(mu, each = length(rows)))^2) / (length(rows) - 1))
  gg[which.min(sdv / mu)]
}
n_rep <- 400
ygrid <- c(3, 4, 5, 6, 8, 10, 15, 20, 30, 40)
set.seed(4104)
clean_tab <- t(sapply(ygrid, function(Y) {
  est <- replicate(n_rep, pick_base(A_clean, sample.int(n_pool, Y), bgrid))
  c(years = Y, mean = mean(est), bias = mean(est) - tbase_true, sd = sd(est))
}))
print(round(clean_tab, 4))
hit <- which(clean_tab[, "sd"] < 0.5)[1]
round(c(replicates_per_row = n_rep, base_grid_low = min(bgrid), base_grid_high = max(bgrid),
        base_grid_step = 0.1,
        years_needed_for_sd_under_half = as.numeric(clean_tab[hit, "years"]),
        sd_there = as.numeric(clean_tab[hit, "sd"]),
        bias_there = as.numeric(clean_tab[hit, "bias"])), 3)

## ---- cv-source ----
bfine <- seq(6, 10, by = 0.25)
A_exact <- matrix(0, n_pool, length(bfine))
for (i in seq_len(n_pool)) {
  ff <- fine_temp(list(L = pool_L[i, ], H = pool_H[i, ]))
  for (j in seq_along(bfine)) {
    A_exact[i, j] <- sum((rowSums(pmax(ff - bfine[j], 0)) / n_step) * wmat[i, ])
  }
}
A_sine_f <- sapply(bfine, function(b) rowSums(dd_sine(tmin_m, tmax_m, b) * wmat))
set.seed(613)
src_tab <- t(sapply(c(15, 40), function(Y) {
  e1 <- replicate(200, pick_base(A_exact, sample.int(n_pool, Y), bfine))
  e2 <- replicate(200, pick_base(A_sine_f, sample.int(n_pool, Y), bfine))
  c(years = Y, exact_mean = mean(e1), exact_sd = sd(e1),
    sine_mean = mean(e2), sine_sd = sd(e2))
}))
print(round(src_tab, 4))

## ---- cv-noise ----
req_cv <- 0.05
set.seed(9110)
K_year <- K_true * exp(rnorm(n_pool, 0, req_cv))
ev_noisy <- sapply(seq_len(n_pool), function(i) cross_day(true_dd[i, ], K_year[i]))
w_noisy <- t(sapply(seq_len(n_pool), function(i) {
  k <- floor(ev_noisy[i]); w <- numeric(n_day)
  w[win_idx:k] <- 1; w[k + 1] <- ev_noisy[i] - k; w
}))
A_noisy <- sapply(bgrid, function(b) rowSums(dd_sine(tmin_m, tmax_m, b) * w_noisy))
set.seed(5150)
noisy_tab <- t(sapply(c(5, 15, 40), function(Y) {
  est <- replicate(n_rep, pick_base(A_noisy, sample.int(n_pool, Y), bgrid))
  c(years = Y, mean = mean(est), bias = mean(est) - tbase_true, sd = sd(est),
    at_floor = mean(est <= min(bgrid) + 1e-9))
}))
print(round(noisy_tab, 4))
cv_curve <- function(AA) apply(AA, 2, sd) / colMeans(AA)
cc_clean <- cv_curve(A_clean); cc_noisy <- cv_curve(A_noisy)
round(c(requirement_cv_percent = 100 * req_cv,
        cv_at_true_base_clean = cc_clean[bgrid == tbase_true],
        cv_minimum_clean = min(cc_clean), base_at_minimum_clean = bgrid[which.min(cc_clean)],
        cv_at_true_base_noisy = cc_noisy[bgrid == tbase_true],
        cv_at_lowest_base_noisy = cc_noisy[1],
        base_at_minimum_noisy = bgrid[which.min(cc_noisy)],
        event_sd_days_noisy = sd(ev_noisy)), 4)

## ---- nonlinear ----
T_low_dev <- 8; T_lethal <- 32; hot_shift <- 5; target_doy <- 225
n_dev <- 60
bri_shape <- function(tt) ifelse(tt > T_low_dev & tt < T_lethal,
                                 tt * (tt - T_low_dev) * sqrt(pmax(T_lethal - tt, 0)), 0)
tgrid <- seq(0, 36, by = 0.01)
t_opt <- tgrid[which.max(bri_shape(tgrid))]

S0 <- matrix(0, n_dev, n_day); S5 <- S0; D0 <- S0; D5 <- S0
hot_frac0 <- matrix(0, n_dev, n_day); hot_frac5 <- hot_frac0
for (i in seq_len(n_dev)) {
  ff <- fine_temp(list(L = pool_L[i, ], H = pool_H[i, ]))
  S0[i, ] <- rowSums(bri_shape(ff)) / n_step
  S5[i, ] <- rowSums(bri_shape(ff + hot_shift)) / n_step
  D0[i, ] <- rowSums(pmax(ff - tbase_true, 0)) / n_step
  D5[i, ] <- rowSums(pmax(ff + hot_shift - tbase_true, 0)) / n_step
  hot_frac0[i, ] <- rowMeans(ff > t_opt)
  hot_frac5[i, ] <- rowMeans((ff + hot_shift) > t_opt)
}
S0 <- mask(S0); S5 <- mask(S5); D0 <- mask(D0); D5 <- mask(D5)
acc_to <- function(dd, day) { k <- floor(day); sum(dd[seq_len(k)]) + (day - k) * dd[k + 1] }
target_idx <- target_doy - doy_start + 1
a_dev <- 1 / mean(apply(S0, 1, acc_to, day = target_idx))
t0 <- apply(S0 * a_dev, 1, cross_day, K = 1)
t5 <- apply(S5 * a_dev, 1, cross_day, K = 1)
acc0 <- sapply(seq_len(n_dev), function(i) acc_to(D0[i, ], t0[i]))
acc5 <- sapply(seq_len(n_dev), function(i) acc_to(D5[i, ], t5[i]))
K_dev <- mean(acc0[cal_yr])
p0 <- apply(D0, 1, cross_day, K = K_dev)
p5 <- apply(D5, 1, cross_day, K = K_dev)
dev_test <- 21:n_dev
err0 <- p0[dev_test] - t0[dev_test]
err5 <- p5[dev_test] - t5[dev_test]
hrs0 <- mean(sapply(dev_test, function(i) mean(hot_frac0[i, win_idx:floor(t0[i])])))
hrs5 <- mean(sapply(dev_test, function(i) mean(hot_frac5[i, win_idx:floor(t5[i])])))

brk <- seq(-15, 45, by = 1)
bin_of <- function(x) tabulate(findInterval(x, brk), nbins = length(brk) - 1)
hist0 <- numeric(length(brk) - 1); hist5 <- hist0
for (i in dev_test) {
  ff <- fine_temp(list(L = pool_L[i, ], H = pool_H[i, ]))
  hist0 <- hist0 + bin_of(ff[win_idx:floor(t0[i]), ])
  hist5 <- hist5 + bin_of(ff[win_idx:floor(t5[i]), ] + hot_shift)
}

round(c(lower_threshold = T_low_dev, upper_threshold = T_lethal,
        optimum_temperature = t_opt, hot_year_offset = hot_shift,
        target_completion_doy = target_doy,
        years_simulated = n_dev, calibration_years = length(cal_yr),
        test_years = length(dev_test), fitted_requirement = K_dev), 3)
round(c(true_completion_normal_doy = mean(to_doy(t0[dev_test])),
        true_completion_hot_doy = mean(to_doy(t5[dev_test])),
        predicted_normal_doy = mean(to_doy(p0[dev_test])),
        predicted_hot_doy = mean(to_doy(p5[dev_test])),
        mean_error_normal_days = mean(err0), mean_error_hot_days = mean(err5),
        mean_abs_error_normal = mean(abs(err0)), mean_abs_error_hot = mean(abs(err5)),
        worst_year_hot = min(err5)), 3)
round(c(hours_above_optimum_normal = 100 * hrs0, hours_above_optimum_hot = 100 * hrs5,
        degree_days_used_normal = mean(acc0[dev_test]),
        degree_days_used_hot = mean(acc5[dev_test]),
        percent_more_in_hot_years = 100 * (mean(acc5[dev_test]) / mean(acc0[dev_test]) - 1),
        cv_of_requirement_normal = sd(acc0[dev_test]) / mean(acc0[dev_test]),
        cv_of_requirement_hot = sd(acc5[dev_test]) / mean(acc5[dev_test])), 3)

## ---- fig-rate ----
panel_r <- c("Development rate per day", "Share of development hours")
tp <- seq(0, 34, by = 0.05)
rate_df <- data.frame(
  temp = rep(tp, 2),
  value = c(a_dev * bri_shape(tp), pmax(tp - tbase_true, 0) / K_dev),
  series = factor(rep(c("True rate curve", "Linear degree day assumption"), each = length(tp)),
                  levels = c("True rate curve", "Linear degree day assumption")),
  panel = factor(panel_r[1], levels = panel_r))
mids <- brk[-length(brk)] + 0.5
keep_b <- mids >= -4 & mids <= 40
hist_df <- data.frame(
  temp = rep(mids[keep_b], 2),
  value = c((hist0 / sum(hist0))[keep_b], (hist5 / sum(hist5))[keep_b]),
  years = factor(rep(c("Normal years", "Hot years"), each = sum(keep_b)),
                 levels = c("Normal years", "Hot years")),
  panel = factor(panel_r[2], levels = panel_r))
opt_line <- data.frame(xv = t_opt, panel = factor(panel_r, levels = panel_r))

ggplot(mapping = aes(temp, value)) +
  geom_vline(data = opt_line, aes(xintercept = xv), colour = te_pal$ink,
             linetype = "22", linewidth = 0.6) +
  geom_col(data = hist_df, aes(fill = years), position = "identity",
           alpha = 0.6, width = 1) +
  geom_line(data = rate_df, aes(colour = series), linewidth = 0.9) +
  facet_wrap(~panel, ncol = 1, scales = "free_y") +
  scale_colour_manual(values = c(te_pal$forest, te_pal$clay), name = NULL) +
  scale_fill_manual(values = c(te_pal$sage, te_pal$gold), name = NULL) +
  coord_cartesian(xlim = c(0, 34)) +
  labs(x = "Temperature (degrees C)", y = NULL,
       title = "The linear model keeps rising where the organism slows down") +
  theme_te() +
  theme(legend.position = "top",
        strip.text = element_text(colour = te_pal$ink, face = "bold"))
