# Daylength as a predictor in ecology
# https://tidyecology.com/posts/daylength-as-a-predictor/
#
# 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-16

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

te_paper  <- "#f5f4ee"
te_ink    <- "#16241d"
te_body   <- "#2c3a31"
te_forest <- "#275139"
te_rust   <- "#b5534e"
te_gold   <- "#c9b458"
te_line   <- "#dad9ca"

theme_datasheet <- function() {
  theme_minimal(base_size = 12) +
    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(),
          text             = element_text(colour = te_body),
          plot.title       = element_text(colour = te_ink, face = "bold"),
          axis.text        = element_text(colour = te_body))
}

## ---- daylength ----
sun_arg <- function(doy, lat, p = 0.8333) {
  theta <- 0.2163108 + 2 * atan(0.9671396 * tan(0.00860 * (doy - 186)))
  phi   <- asin(0.39795 * cos(theta))
  (sin(p * pi / 180) + sin(lat * pi / 180) * sin(phi)) /
    (cos(lat * pi / 180) * cos(phi))
}

daylength <- function(doy, lat, p = 0.8333) {
  arg <- sun_arg(doy, lat, p)
  arg[abs(arg) > 1] <- NA      # above 1 the sun never sinks to p below the
  24 - (24 / pi) * acos(arg)   # horizon; below -1 it never climbs to it
}

all_days <- 1:365
cross12  <- function(lat, p, window)
  uniroot(function(d) daylength(d, lat, p) - 12, window)$root
eq_geom  <- range(daylength(all_days, 0, p = 0)); march_eq <- cross12(47, 0, c(60, 100))
up12     <- sapply(c(47, 65), cross12, p = 0.8333, window = c(60, 100))
down12   <- sapply(c(47, 65), cross12, p = 0.8333, window = c(240, 300))
round(c(equator_geometric_min = eq_geom[1], equator_geometric_max = eq_geom[2],
        equator_standard = daylength(1, 0), geometric_equinox = march_eq,
        day_80_at_47N = daylength(80, 47, p = 0), up12_47N = up12[1],
        up12_65N = up12[2], down12_47N = down12[1], down12_65N = down12[2]), 3)

## ---- fig-curves ----
curve_df <- expand.grid(doy = all_days, lat = c(0, 47, 65))
curve_df$hours <- daylength(curve_df$doy, curve_df$lat)
curve_df$site  <- paste(curve_df$lat, "degrees north")

ggplot(curve_df, aes(doy, hours, colour = site)) +
  geom_hline(yintercept = 12, linetype = "dashed", colour = te_body) +
  geom_line(linewidth = 1) +
  scale_colour_manual(values = c(te_gold, te_forest, te_rust)) +
  labs(x = "day of year", y = "daylength (hours)", colour = NULL,
       title = "The covariate the model actually sees") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- within-site ----
harmonics <- function(d, k) do.call(cbind, lapply(1:k, function(j)
  cbind(sin(2 * pi * j * d / 365), cos(2 * pi * j * d / 365))))

lat_site <- 47
doy <- seq(32, 335, by = 3)
dl <- daylength(doy, lat_site); H2 <- harmonics(doy, 2)

r2_alias <- summary(lm(dl ~ H2))$r.squared
r2_three <- summary(lm(dl ~ harmonics(doy, 3)))$r.squared
round(c(n_days = length(doy), r2_on_two_harmonics = r2_alias,
        variance_inflation = 1 / (1 - r2_alias),
        r2_on_three_harmonics = r2_three), 6)

## ---- mirror ----
dl_grid <- daylength(all_days, lat_site)
day_max <- which.max(dl_grid); day_min <- which.min(dl_grid)
fall_days <- day_max:day_min                     # daylength decreasing
rise_days <- day_min:(365 + day_max)             # daylength increasing
rise_dl   <- daylength(((rise_days - 1) %% 365) + 1, lat_site)

mirror_day <- function(d) {
  target <- daylength(d, lat_site)
  m <- ifelse(d > day_max & d < day_min,
              approx(rise_dl, rise_days, xout = target)$y,
              approx(dl_grid[fall_days], fall_days, xout = target)$y)
  ((m - 1) %% 365) + 1
}

example <- c(116, 347)
round(cbind(day = example, mirror = mirror_day(example),
            hours = daylength(example, lat_site),
            hours_at_mirror = daylength(mirror_day(example), lat_site)), 3)

## ---- simulate ----
lag_days     <- 32
thermal_peak <- day_max + lag_days                        # late July
site_temp <- function(d, peak = thermal_peak) 9 + 11 * cos(2 * pi * (d - peak) / 365)
mu_true   <- function(d, peak = thermal_peak) 6 + 0.9 * site_temp(d, peak)

set.seed(20260813)
noise <- rnorm(length(doy), 0, 2.2); activity <- mu_true(doy) + noise
round(c(solstice = day_max, thermal_peak = thermal_peak,
        temp_min = min(site_temp(doy)), temp_max = max(site_temp(doy)),
        response_sd = sd(activity)), 2)

## ---- compare ----
fit_dl  <- lm(activity ~ poly(dl, 4))
fit_doy <- lm(activity ~ H2)
lags <- c(0, 12, lag_days, 47)
loss <- sapply(lags, function(L) {
  a <- mu_true(doy, peak = day_max + L) + noise
  summary(lm(a ~ H2))$r.squared - summary(lm(a ~ poly(dl, 4)))$r.squared })

round(c(r2_dl = summary(fit_dl)$r.squared, r2_doy = summary(fit_doy)$r.squared,
        sigma_dl = summary(fit_dl)$sigma, sigma_doy = summary(fit_doy)$sigma), 3)
round(setNames(loss, paste0("loss_at_lag_", lags)), 3)

## ---- fig-loop ----
loop_df <- data.frame(dl = dl, activity = activity,
  half = factor(ifelse(doy <= day_max, "before the solstice", "after the solstice"),
                levels = c("before the solstice", "after the solstice")))
fit_df <- data.frame(dl = dl, fitted = fitted(fit_dl))

p_loop <- ggplot(loop_df, aes(dl, activity)) +
  geom_point(aes(colour = half), size = 2.4, alpha = 0.85) +
  geom_line(data = fit_df, aes(dl, fitted), colour = te_ink, linewidth = 1) +
  scale_colour_manual(values = c(te_forest, te_rust)) +
  labs(x = "daylength (hours)", y = "activity index", colour = NULL,
       title = "One daylength, two answers") +
  theme_datasheet() +
  theme(legend.position = "bottom")
p_loop

## ---- ceiling ----
mu_year   <- mu_true(all_days)
reflected <- ((2 * day_max - all_days - 1) %% 365) + 1   # exact, and closed on 1:365
mu_refl   <- mu_true(reflected)
pair_mean <- (mu_year + mu_refl) / 2; gap <- max(abs(mu_year - mu_refl))
ceiling_r2 <- 1 - sum((mu_year - pair_mean)^2) / sum((mu_year - mean(mu_year))^2)
attained <- sapply(c(4, 20), function(k)
  summary(lm(mu_year ~ poly(dl_grid, k)))$r.squared)
round(c(r2_symmetric_ceiling = ceiling_r2, r2_poly4 = attained[1],
        r2_poly20 = attained[2], largest_reflected_gap = gap,
        sd_of_true_mean = sd(mu_year), gap_in_sd_units = gap / sd(mu_year)), 3)

## ---- fig-residuals ----
res_dl <- resid(fit_dl); res_doy <- resid(fit_doy)
spring <- doy <= day_max
res_df <- data.frame(doy = doy, resid = c(res_dl, res_doy),
  model = rep(c("response ~ poly(daylength, 4)",
                "response ~ two harmonics of day of year"), each = length(doy)))
seg_df <- do.call(rbind, lapply(split(res_df, list(res_df$model, res_df$doy <= day_max)),
  function(z) data.frame(model = z$model[1], x = min(z$doy),
                         xend = max(z$doy), y = mean(z$resid))))

ggplot(res_df, aes(doy, resid)) +
  geom_hline(yintercept = 0, colour = te_body) +
  geom_vline(xintercept = day_max, linetype = "dashed", colour = te_gold) +
  geom_point(colour = te_forest, size = 1.9, alpha = 0.8) +
  geom_segment(data = seg_df, aes(x = x, xend = xend, y = y, yend = y),
               colour = te_rust, linewidth = 1.4) +
  facet_wrap(~ model, ncol = 1) +
  labs(x = "day of year", y = "residual",
       title = "The daylength model is wrong in opposite directions") +
  theme_datasheet()

## ---- sites ----
lats    <- seq(38, 62, by = 4)
dgrid   <- seq(60, 300, by = 6); may_day <- 121
sites <- expand.grid(doy = dgrid, lat = lats)
sites$dl <- daylength(sites$doy, sites$lat); sites$site <- factor(sites$lat)
Hs <- harmonics(sites$doy, 2)

focal      <- sites[sites$lat == 46, ]
r2_focal   <- summary(lm(focal$dl ~ harmonics(focal$doy, 2)))$r.squared
r2_pool    <- summary(lm(sites$dl ~ Hs + sites$site))$r.squared
spread_may <- diff(range(daylength(may_day, lats)))
round(c(n_total = nrow(sites), spread_on_1_may = spread_may,
        r2_at_46N = r2_focal, vif_at_46N = 1 / (1 - r2_focal),
        r2_pooled = r2_pool, vif_pooled = 1 / (1 - r2_pool)), 4)

## ---- fig-fan ----
ggplot(sites, aes(doy, dl, colour = lat, group = lat)) +
  geom_vline(xintercept = may_day, linetype = "dashed", colour = te_body) +
  geom_line(linewidth = 0.9) +
  scale_colour_gradient(low = te_gold, high = te_ink,
                        name = "latitude (degrees north)") +
  labs(x = "day of year", y = "daylength (hours)",
       title = "Latitude is what makes the coefficient estimable") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- identify ----
beta_dl  <- 1.5
seasonal <- function(d) 8 * sin(2 * pi * (d - 100) / 365) +
                        3 * cos(2 * pi * 2 * (d - 40) / 365)
sites$mu <- 10 + beta_dl * sites$dl + seasonal(sites$doy)

set.seed(4711)
sites$y <- sites$mu + rnorm(nrow(sites), 0, 2.5)

fit_pool <- lm(y ~ dl + Hs + site, data = sites)
one_site <- sites[sites$lat == 46, ]; H_one <- harmonics(one_site$doy, 2)
fit_one  <- lm(y ~ dl + H_one, data = one_site)
ci_one   <- confint(fit_one)["dl", ]; ci_pool <- confint(fit_pool)["dl", ]
round(rbind(
  one_site    = c(coef(fit_one)["dl"], ci_one, sigma = summary(fit_one)$sigma),
  seven_sites = c(coef(fit_pool)["dl"], ci_pool, sigma = summary(fit_pool)$sigma)), 3)

## ---- confounded ----
amp <- 1.64 + 0.22 * sites$lat
sites$temp <- (26 - 0.38 * sites$lat) +
              amp * cos(2 * pi * (sites$doy - thermal_peak) / 365)
sites$mu_no_photo <- 4 + 0.9 * sites$temp

set.seed(99001)
sites$y_no_photo <- sites$mu_no_photo + rnorm(nrow(sites), 0, 2.5)

coef_conf   <- summary(lm(y_no_photo ~ dl + Hs + site, data = sites))$coefficients["dl", ]
b_noiseless <- coef(lm(mu_no_photo ~ dl + Hs + site, data = sites))["dl"]
std_spurious <- b_noiseless * sd(sites$dl) / sd(sites$mu_no_photo)
std_genuine  <- beta_dl * sd(sites$dl) / sd(sites$mu)
round(c(amplitude_south = min(amp), amplitude_north = max(amp),
        estimate = coef_conf[1], std_error = coef_conf[2], p_value = coef_conf[4],
        noiseless_estimate = b_noiseless, standardised_spurious = std_spurious,
        standardised_genuine = std_genuine), 4)

## ---- twilight ----
civil_gap <- mean(daylength(all_days, lat_site, p = 6) - dl_grid)
disc_gap  <- mean(dl_grid - daylength(all_days, lat_site, p = 0))
undefined <- function(lat, p) {
  a <- sun_arg(all_days, lat, p)
  c(never_ends = sum(a > 1), never_starts = sum(a < -1))
}
polar <- sapply(c(62, 66.5, 68), function(L)
  c(standard = undefined(L, 0.8333), civil = undefined(L, 6)))
colnames(polar) <- paste0("lat_", c(62, 66.5, 68))
round(c(mean_civil_minus_standard = civil_gap,
        mean_standard_minus_disc = disc_gap,
        as_fraction_of_latitude_spread = civil_gap / spread_may), 3)
polar

## ---- thumbnail ----
p_thumb <- p_loop +
  labs(subtitle = "the same photoperiod arrives in spring and again in autumn") +
  theme(plot.subtitle = element_text(colour = te_body))
ggsave("thumbnail.png", p_thumb, width = 9, height = 6.48, dpi = 1000 / 12)
