# Harmonics or cyclic splines for a narrow seasonal peak
# https://tidyecology.com/posts/cyclic-splines-for-seasonal-data/
#
# 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-08-26

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

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"),
          plot.subtitle    = element_text(colour = te_body),
          axis.text        = element_text(colour = te_body))
}

## ---- sci-tex-helper ----
sci_tex <- function(x, digits = 2) {
  s <- formatC(x, format = "e", digits = digits)
  paste0("$", sub("e.*", "", s), " \\times 10^{", as.integer(sub(".*e", "", s)), "}$")
}

## ---- design ----
year_len  <- 365
visit_day <- seq(3, 365, by = 7)
n_visit   <- length(visit_day)
peak_day  <- 350
rise_sd   <- 6
fall_sd   <- 12
base_rate <- 0.5
k_max     <- 8
k_cc      <- 30
day_fine  <- seq(0.5, 365.5, by = 0.25)

circ_gap <- function(d) ((d + year_len / 2) %% year_len) - year_len / 2

pulse_mean <- function(d, peak, s_rise, s_fall, base, height) {
  bump <- 0
  for (m in -2:2) {
    z <- d - peak + year_len * m
    bump <- bump + exp(-z^2 / (2 * ifelse(z < 0, s_rise, s_fall)^2))
  }
  base + height * bump
}

harm_design <- function(d, n_harm) {
  w <- 2 * pi * d / year_len
  X <- matrix(1, length(d), 1 + 2 * n_harm)
  for (k in seq_len(n_harm)) {
    X[, 2 * k] <- cos(k * w)
    X[, 2 * k + 1] <- sin(k * w)
  }
  X
}

half_max <- function(f) {
  f_base <- min(f)
  i_top  <- which.max(f)
  above  <- rep(f > f_base + (max(f) - f_base) / 2, 3)
  n_f <- length(f)
  lo <- i_top + n_f
  hi <- lo
  while (lo > 1 && above[lo - 1]) lo <- lo - 1
  while (hi < 3 * n_f && above[hi + 1]) hi <- hi + 1
  c(peak = day_fine[i_top], width = min(hi - lo + 1, n_f) * 0.25)
}

truth_narrow <- half_max(pulse_mean(day_fine, peak_day, rise_sd, fall_sd,
                                    base_rate, 10))
truth_narrow

## ---- noiseless ----
exact_mu <- pulse_mean(visit_day, peak_day, rise_sd, fall_sd, base_rate, 10)
exact_h8 <- suppressWarnings(glm.fit(harm_design(visit_day, k_max), exact_mu,
                                     family = poisson()))$coefficients
exact_h8_fit <- half_max(exp(drop(harm_design(day_fine, k_max) %*% exact_h8)))
exact_cc <- suppressWarnings(gam(exact_mu ~ s(visit_day, bs = "cc", k = 45),
                                 family = quasipoisson, sp = 1e-6,
                                 knots = list(visit_day = c(0.5, 365.5))))
exact_cc_fit <- half_max(predict(exact_cc, data.frame(visit_day = day_fine),
                                 type = "response"))
rbind(truth = truth_narrow, harmonics_8 = exact_h8_fit, cyclic_unpenalised = exact_cc_fit)

## ---- fitters ----
fit_harmonics <- function(day, y) {
  n_obs <- length(y)
  fits <- lapply(seq_len(k_max), function(K) {
    X <- harm_design(day, K)
    gf <- suppressWarnings(glm.fit(X, y, family = poisson()))
    list(cf = gf$coefficients, npar = ncol(X),
         loglik = sum(dpois(y, gf$fitted.values, log = TRUE)))
  })
  loglik <- sapply(fits, `[[`, "loglik")
  npar   <- sapply(fits, `[[`, "npar")
  k_aic <- which.min(-2 * loglik + 2 * npar)
  k_bic <- which.min(-2 * loglik + log(n_obs) * npar)
  list(k_aic = k_aic, k_bic = k_bic,
       aic = exp(drop(harm_design(day_fine, k_aic) %*% fits[[k_aic]]$cf)),
       bic = exp(drop(harm_design(day_fine, k_bic) %*% fits[[k_bic]]$cf)))
}

fit_cyclic <- function(day, y, k_basis = k_cc, crit = "REML") {
  gam(y ~ s(day, bs = "cc", k = k_basis), family = poisson,
      method = crit, knots = list(day = c(0.5, 365.5)))
}

set.seed(3504)
one_mu <- pulse_mean(visit_day, peak_day, rise_sd, fall_sd, base_rate, 10)
one_y  <- rpois(n_visit, one_mu)
one_h  <- fit_harmonics(visit_day, one_y)
one_cc <- fit_cyclic(visit_day, one_y)
one_cc_curve <- predict(one_cc, data.frame(day = day_fine), type = "response")
one_tab <- rbind(truth = truth_narrow, aic = half_max(one_h$aic),
                 bic = half_max(one_h$bic), cyclic = half_max(one_cc_curve))
one_tab
c(k_aic = one_h$k_aic, k_bic = one_h$k_bic, edf = sum(one_cc$edf) - 1)
top_idx <- order(one_y, decreasing = TRUE)[1:2]
rbind(day = visit_day[top_idx], count = one_y[top_idx])

## ---- fig-one-year ----
shift_day <- function(d) (d - 182) %% year_len
month_at  <- shift_day(c(182, 244, 305, 1, 60, 121))
month_lab <- c("1 Jul", "1 Sep", "1 Nov", "1 Jan", "1 Mar", "1 May")
curve_df <- rbind(
  data.frame(day = day_fine, rate = pulse_mean(day_fine, peak_day, rise_sd,
             fall_sd, base_rate, 10), fit = "true mean"),
  data.frame(day = day_fine, rate = one_h$aic,
             fit = sprintf("harmonics, AIC (%d)", one_h$k_aic)),
  data.frame(day = day_fine, rate = one_h$bic,
             fit = sprintf("harmonics, BIC (%d)", one_h$k_bic)),
  data.frame(day = day_fine, rate = one_cc_curve, fit = "cyclic spline, REML"))
curve_df$pos <- shift_day(curve_df$day)
curve_df <- curve_df[order(curve_df$fit, curve_df$pos), ]
curve_df$fit <- factor(curve_df$fit, levels = c("true mean",
  sprintf("harmonics, AIC (%d)", one_h$k_aic),
  sprintf("harmonics, BIC (%d)", one_h$k_bic), "cyclic spline, REML"))
fit_cols <- setNames(c(te_line, te_gold, te_rust, te_forest), levels(curve_df$fit))
pts_df <- data.frame(pos = shift_day(visit_day), count = one_y)

ggplot() +
  geom_line(data = curve_df, aes(pos, rate, colour = fit,
                                 linewidth = fit == "true mean")) +
  geom_point(data = pts_df, aes(pos, count), colour = te_ink, size = 1.6) +
  scale_linewidth_manual(values = c(0.8, 2.2), guide = "none") +
  scale_colour_manual(values = fit_cols, name = NULL) +
  scale_x_continuous(breaks = month_at, labels = month_lab) +
  coord_cartesian(xlim = shift_day(c(305, 60))) +
  labs(x = NULL, y = "moths per trap night",
       title = "One season, three smoothers",
       subtitle = "weekly trap nights; the peak sits in mid December") +
  guides(colour = guide_legend(nrow = 2)) +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- replicate ----
one_season <- function(s_rise, s_fall, height) {
  y  <- rpois(n_visit, pulse_mean(visit_day, peak_day, s_rise, s_fall,
                                  base_rate, height))
  hf <- fit_harmonics(visit_day, y)
  warned <- c(reml = FALSE, ubre = FALSE)
  flag <- function(expr, which_fit) withCallingHandlers(expr, warning = function(w) {
    warned[[which_fit]] <<- TRUE
    invokeRestart("muffleWarning")
  })
  fit_re <- flag(fit_cyclic(visit_day, y), "reml")
  fit_ub <- flag(fit_cyclic(visit_day, y, crit = "GCV.Cp"), "ubre")
  cc <- predict(fit_re, data.frame(day = day_fine), type = "response")
  ub <- predict(fit_ub, data.frame(day = day_fine), type = "response")
  mu_true <- pulse_mean(day_fine, peak_day, s_rise, s_fall, base_rate, height)
  tr <- half_max(mu_true)
  est <- rbind(half_max(hf$aic), half_max(hf$bic), half_max(cc), half_max(ub))
  c(k_aic = hf$k_aic, k_bic = hf$k_bic,
    peak_err = circ_gap(est[, "peak"] - tr["peak"]),
    width_ratio = est[, "width"] / tr["width"],
    sq_err = sapply(list(hf$aic, hf$bic, cc, ub), function(f) mean((f - mu_true)^2)),
    top_ratio = sapply(list(hf$aic, hf$bic, cc, ub), max) / max(mu_true),
    edf_reml = sum(fit_re$edf) - 1, edf_ubre = sum(fit_ub$edf) - 1,
    warn_reml = warned[["reml"]], warn_ubre = warned[["ubre"]])
}

scen_tab <- data.frame(
  scenario = c("narrow, peak 20", "narrow, peak 10", "narrow, peak 4",
               "broad, peak 10"),
  s_rise = c(rise_sd, rise_sd, rise_sd, 30),
  s_fall = c(fall_sd, fall_sd, fall_sd, 50),
  height = c(20, 10, 4, 10))
n_rep <- 300

set.seed(8126)
rep_out <- lapply(seq_len(nrow(scen_tab)), function(i)
  t(replicate(n_rep, one_season(scen_tab$s_rise[i], scen_tab$s_fall[i],
                                scen_tab$height[i]))))
colnames(rep_out[[1]])

method_lab <- c("harmonics, AIC", "harmonics, BIC", "cyclic spline, REML",
                "cyclic spline, UBRE")
summ <- do.call(rbind, lapply(seq_len(nrow(scen_tab)), function(i) {
  r_mat <- rep_out[[i]]
  w_mat <- r_mat[, paste0("width_ratio", 1:4)]
  p_mat <- r_mat[, paste0("peak_err", 1:4)]
  data.frame(scenario = scen_tab$scenario[i], method = method_lab,
             width_med = apply(w_mat, 2, median),
             width_lo = apply(w_mat, 2, quantile, 0.25),
             width_hi = apply(w_mat, 2, quantile, 0.75),
             wide_share = colMeans(w_mat > 1.5),
             wide_se = sqrt(colMeans(w_mat > 1.5) * (1 - colMeans(w_mat > 1.5)) / n_rep),
             peak_bias = colMeans(p_mat),
             peak_se = apply(p_mat, 2, sd) / sqrt(n_rep),
             peak_mae = colMeans(abs(p_mat)),
             peak_far = colMeans(abs(p_mat) > 30),
             sq_err_med = apply(r_mat[, paste0("sq_err", 1:4)], 2, median),
             runaway = colMeans(r_mat[, paste0("top_ratio", 1:4)] > 2))
}))
rownames(summ) <- NULL
print(summ, digits = 3)

paired <- t(sapply(rep_out, function(r_mat) {
  d_log <- log(r_mat[, "width_ratio3"]) - log(r_mat[, "width_ratio1"])
  d_ub <- log(r_mat[, "width_ratio4"]) - log(r_mat[, "width_ratio1"])
  c(mean = mean(d_log), se = sd(d_log) / sqrt(n_rep),
    cc_narrower = mean(r_mat[, "width_ratio3"] < r_mat[, "width_ratio1"]),
    ub_mean = mean(d_ub), ub_se = sd(d_ub) / sqrt(n_rep),
    ub_narrower = mean(r_mat[, "width_ratio4"] < r_mat[, "width_ratio1"]),
    edf_reml = median(r_mat[, "edf_reml"]), edf_ubre = median(r_mat[, "edf_ubre"]),
    warn_reml = mean(r_mat[, "warn_reml"]), warn_ubre = mean(r_mat[, "warn_ubre"]))
}))
paired
pick <- function(s, m, col) summ[summ$scenario == s & summ$method == m, col]
sel_stats <- t(sapply(rep_out, function(r_mat)
  c(aic_mode = which.max(tabulate(r_mat[, "k_aic"], k_max)),
    bic_mode = which.max(tabulate(r_mat[, "k_bic"], k_max)),
    aic_mean = mean(r_mat[, "k_aic"]), bic_mean = mean(r_mat[, "k_bic"]),
    aic_ceiling = mean(r_mat[, "k_aic"] == k_max),
    bic_le3 = mean(r_mat[, "k_bic"] <= 3),
    bic_one = mean(r_mat[, "k_bic"] == 1))))
sel_stats

## ---- fig-widths ----
summ$scenario <- factor(summ$scenario, levels = rev(scen_tab$scenario))
summ$method <- factor(summ$method, levels = method_lab)
ggplot(summ, aes(y = scenario, colour = method)) +
  geom_vline(xintercept = 1, linetype = "dashed", colour = te_ink, linewidth = 0.5) +
  geom_linerange(aes(xmin = width_lo, xmax = width_hi),
                 position = position_dodge(width = 0.6), linewidth = 1.1) +
  geom_point(aes(x = width_med), position = position_dodge(width = 0.6), size = 2.6) +
  scale_colour_manual(values = c(te_gold, te_rust, te_forest, "#86a98f"), name = NULL) +
  scale_x_log10(breaks = c(0.75, 1, 1.5, 2, 3, 4, 6),
                labels = c("0.75", "1", "1.5", "2", "3", "4", "6")) +
  labs(x = "fitted half-maximum width / true width (log scale)", y = NULL,
       title = "Which fit widens the pulse",
       subtitle = "median and interquartile range over 300 simulated seasons") +
  guides(colour = guide_legend(reverse = FALSE)) +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- fig-selected ----
sel_df <- do.call(rbind, lapply(seq_len(nrow(scen_tab)), function(i) {
  r_mat <- rep_out[[i]]
  rbind(data.frame(k = seq_len(k_max), share = tabulate(r_mat[, 1], k_max) / n_rep,
                   rule = "AIC", scenario = scen_tab$scenario[i]),
        data.frame(k = seq_len(k_max), share = tabulate(r_mat[, 2], k_max) / n_rep,
                   rule = "BIC", scenario = scen_tab$scenario[i]))
}))
sel_df$scenario <- factor(sel_df$scenario, levels = scen_tab$scenario)
ggplot(sel_df, aes(k, share, fill = rule)) +
  geom_col(position = position_dodge(width = 0.8), width = 0.75) +
  facet_wrap(~ scenario, nrow = 1) +
  scale_fill_manual(values = c(te_gold, te_rust), name = NULL) +
  scale_x_continuous(breaks = 1:8) +
  labs(x = "harmonics selected (1 to 8)", y = "share of seasons",
       title = "BIC stops earlier, and earlier still when counts are low") +
  theme_datasheet() +
  theme(legend.position = "bottom", strip.text = element_text(colour = te_ink))

## ---- basis-check ----
n_check <- 60
set.seed(5530)
k_check <- t(replicate(n_check, {
  y <- rpois(n_visit, pulse_mean(visit_day, peak_day, rise_sd, fall_sd,
                                 base_rate, 10))
  tr <- half_max(pulse_mean(day_fine, peak_day, rise_sd, fall_sd, base_rate, 10))
  w30 <- fit_cyclic(visit_day, y, 30)
  w45 <- fit_cyclic(visit_day, y, 45)
  c(r30 = half_max(predict(w30, data.frame(day = day_fine), type = "response"))[["width"]] / tr[["width"]],
    r45 = half_max(predict(w45, data.frame(day = day_fine), type = "response"))[["width"]] / tr[["width"]],
    edf30 = sum(w30$edf) - 1, edf45 = sum(w45$edf) - 1)
}))
k_summ <- colMeans(k_check)
k_summ

## ---- boundary-one ----
one_plain <- gam(y ~ s(day, k = k_cc), family = poisson, method = "REML",
                 data = data.frame(day = visit_day, y = one_y))
one_dflt  <- gam(y ~ s(day, bs = "cc", k = k_cc), family = poisson,
                 method = "REML", data = data.frame(day = visit_day, y = one_y))
end_link <- function(fit, lo, hi, h_step = 0.01) {
  p <- predict(fit, data.frame(day = c(lo, lo + h_step, hi - h_step, hi)))
  c(value_gap = p[[4]] - p[[1]],
    slope_gap = (p[[4]] - p[[3]]) / h_step - (p[[2]] - p[[1]]) / h_step)
}
wrap_cc    <- end_link(one_cc, 0.5, 365.5)
wrap_plain <- end_link(one_plain, 0.5, 365.5)
wrap_dflt  <- end_link(one_dflt, 3, 360)
wrap_cc_fine <- end_link(one_cc, 0.5, 365.5, h_step = 0.001)
rbind(cyclic_year_knots = wrap_cc, cyclic_year_knots_fine = wrap_cc_fine,
      plain = wrap_plain, cyclic_default = wrap_dflt)
one_dflt$smooth[[1]]$xp[c(1, length(one_dflt$smooth[[1]]$xp))]
true_lr <- log(pulse_mean(360, peak_day, rise_sd, fall_sd, base_rate, 10) /
               pulse_mean(3, peak_day, rise_sd, fall_sd, base_rate, 10))
true_lr

## ---- boundary-rep ----
n_bound <- 200
set.seed(6617)
bound_out <- t(replicate(n_bound, {
  dat <- data.frame(day = visit_day,
                    y = rpois(n_visit, pulse_mean(visit_day, peak_day, rise_sd,
                                                  fall_sd, base_rate, 10)))
  f_cc <- gam(y ~ s(day, bs = "cc", k = k_cc), family = poisson, method = "REML",
              data = dat, knots = list(day = c(0.5, 365.5)))
  f_pl <- gam(y ~ s(day, k = k_cc), family = poisson, method = "REML", data = dat)
  f_df <- gam(y ~ s(day, bs = "cc", k = k_cc), family = poisson, method = "REML",
              data = dat)
  p_cc <- predict(f_cc, data.frame(day = c(0.5, 365.5, 3, 360)))
  p_pl <- predict(f_pl, data.frame(day = c(0.5, 365.5, 3, 360)))
  p_df <- predict(f_df, data.frame(day = c(3, 360)))
  c(jump_cc = p_cc[[2]] - p_cc[[1]], jump_pl = p_pl[[2]] - p_pl[[1]],
    lr_cc = p_cc[[4]] - p_cc[[3]], lr_pl = p_pl[[4]] - p_pl[[3]],
    lr_df = p_df[[2]] - p_df[[1]])
}))
bound_mean <- colMeans(bound_out)
bound_se   <- apply(bound_out, 2, sd) / sqrt(n_bound)
rbind(mean = bound_mean, se = bound_se)

## ---- fp-guard-1 ----
stopifnot(max(abs(bound_out[, "lr_df"])) < 1e-10)

## ---- fig-boundary ----
edge_day <- c(seq(300.5, 365.5, by = 0.25), seq(0.5, 60.5, by = 0.25))
edge_pos <- ifelse(edge_day > 182, edge_day - 365.5, edge_day - 0.5)
edge_df <- rbind(
  data.frame(pos = edge_pos, rate = pulse_mean(edge_day, peak_day, rise_sd,
             fall_sd, base_rate, 10), fit = "true mean"),
  data.frame(pos = edge_pos, rate = predict(one_plain, data.frame(day = edge_day),
             type = "response"), fit = "s(day), plain"),
  data.frame(pos = edge_pos, rate = predict(one_cc, data.frame(day = edge_day),
             type = "response"), fit = "s(day, bs = \"cc\"), knots at 0.5 and 365.5"))
dflt_day <- c(seq(300, 360, by = 0.25), seq(3, 60, by = 0.25))
dflt_pos <- ifelse(dflt_day > 182, dflt_day - 365.5, dflt_day - 0.5)
edge_df <- rbind(edge_df, data.frame(pos = dflt_pos,
  rate = predict(one_dflt, data.frame(day = dflt_day), type = "response"),
  fit = "s(day, bs = \"cc\"), default knots"))
edge_df$side <- ifelse(c(edge_day, edge_day, edge_day, dflt_day) > 182, "Dec", "Jan")
edge_pts <- data.frame(pos = ifelse(visit_day > 182, visit_day - 365.5, visit_day - 0.5),
                       rate = one_y)
edge_pts <- edge_pts[abs(edge_pts$pos) <= 62, ]
edge_df$fit <- factor(edge_df$fit, levels = unique(edge_df$fit)[c(1, 2, 4, 3)])
ggplot(edge_df, aes(pos, rate, colour = fit, group = interaction(fit, side))) +
  geom_vline(xintercept = 0, colour = te_ink, linetype = "dotted") +
  geom_line(aes(linewidth = fit == "true mean")) +
  geom_point(data = edge_pts, aes(pos, rate), inherit.aes = FALSE,
             colour = te_ink, size = 1.6) +
  scale_linewidth_manual(values = c(0.8, 2.2), guide = "none") +
  scale_colour_manual(values = c(te_line, te_rust, te_gold, te_forest), name = NULL) +
  scale_x_continuous(breaks = c(-60.5, -30.5, 0.5, 31.5, 59.5),
                     labels = c("1 Nov", "1 Dec", "1 Jan", "1 Feb", "1 Mar")) +
  labs(x = NULL, y = "moths per trap night",
       title = "The same data either side of 31 December",
       subtitle = "dotted line: the year boundary") +
  guides(colour = guide_legend(nrow = 2)) +
  theme_datasheet() +
  theme(legend.position = "bottom")
