# Wavelet analysis of population cycles
# https://tidyecology.com/posts/wavelet-analysis-of-population-cycles/
#
# 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-04

## ---- sim ----
set.seed(284)
n <- 256
tt <- 1:n
half <- n / 2
sig <- c(sin(2 * pi * (1:half) / 10), sin(2 * pi * ((half + 1):n) / 5))
y <- 20 + 6 * sig + rnorm(n, 0, 1.6)

## ---- theme ----
library(ggplot2)
theme_te <- function(base_size = 11) {
  theme_minimal(base_size = base_size) +
    theme(panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "#dad9ca", linewidth = 0.3),
          axis.title = element_text(colour = "#2c3a31"),
          axis.text = element_text(colour = "#5d6b61"),
          plot.title = element_text(colour = "#16241d", face = "bold", size = rel(1)),
          plot.subtitle = element_text(colour = "#5d6b61", size = rel(0.9)),
          legend.text = element_text(colour = "#5d6b61"),
          legend.title = element_text(colour = "#2c3a31"),
          plot.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA))
}

## ---- pgram ----
pg <- spec.pgram(y, taper = 0, detrend = TRUE, fast = FALSE, plot = FALSE)
pgp <- 1 / pg$freq
w10 <- which(pgp > 7 & pgp < 14)
w5 <- which(pgp > 3.5 & pgp < 7)
p_peak10 <- pgp[w10][which.max(pg$spec[w10])]
p_peak5 <- pgp[w5][which.max(pg$spec[w5])]
c(peak_near_10 = round(p_peak10, 2), height = round(max(pg$spec[w10]), 1),
  peak_near_5 = round(p_peak5, 2), height = round(max(pg$spec[w5]), 1))

## ---- fig-series ----
pA <- ggplot(data.frame(t = tt, y = y), aes(t, y)) +
  geom_line(colour = "#275139", linewidth = 0.4) +
  geom_vline(xintercept = 128, colour = "#b5534e", linetype = "22", linewidth = 0.5) +
  labs(x = "year", y = "index", title = "The series",
       subtitle = "period 10 up to year 128, period 5 afterwards") +
  theme_te()
pB <- ggplot(data.frame(p = pgp, s = pg$spec), aes(p, s)) +
  geom_line(colour = "#275139", linewidth = 0.4) +
  scale_x_continuous(transform = "log2", breaks = c(2, 4, 8, 16, 32, 64)) +
  coord_cartesian(xlim = c(2, 64)) +
  labs(x = "period (years)", y = "spectral density", title = "The periodogram",
       subtitle = "two peaks, near equal, no hint that they are sequential") +
  theme_te()
grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(2, 1)))
print(pA, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 1))
print(pB, vp = grid::viewport(layout.pos.row = 2, layout.pos.col = 1))

## ---- engine ----
morlet_daughter <- function(k, scale, dt, w0 = 6) {
  expnt <- -(scale * k - w0)^2 / 2 * (k > 0)
  nrm <- sqrt(2 * pi * scale / dt) * pi^(-0.25)
  nrm * exp(expnt) * (k > 0)
}
fourier_factor <- function(w0 = 6) (4 * pi) / (w0 + sqrt(2 + w0^2))

cwt <- function(x, dt = 1, dj = 0.1, s0 = 2 * dt, J = NULL, w0 = 6) {
  n1 <- length(x)
  x <- x - mean(x)
  x <- c(x, rep(0, 2^(floor(log2(n1) + 0.4999) + 1) - n1))   # zero pad
  n <- length(x)
  if (is.null(J)) J <- floor(log2(n1 * dt / s0) / dj)
  kk <- seq_len(floor(n / 2)) * (2 * pi) / (n * dt)
  k <- c(0, kk, -rev(kk[seq_len(floor((n - 1) / 2))]))       # wavenumbers
  f <- fft(x)
  scale <- s0 * 2^((0:J) * dj)
  W <- matrix(0 + 0i, length(scale), n)
  for (a in seq_along(scale)) {
    W[a, ] <- fft(f * morlet_daughter(k, scale[a], dt, w0), inverse = TRUE) / n
  }
  ff <- fourier_factor(w0)
  coi <- ff / sqrt(2) * dt * c(1e-5, seq_len(floor((n1 + 1) / 2) - 1),
                               rev(seq_len(floor(n1 / 2) - 1)), 1e-5)
  list(W = W[, seq_len(n1), drop = FALSE], scale = scale, period = ff * scale,
       coi = coi[seq_len(n1)], dt = dt, dj = dj, w0 = w0, n = n1)
}

## ---- run ----
o <- cwt(y)
P <- Mod(o$W)^2
b10 <- which.min(abs(o$period - 10))
b5 <- which.min(abs(o$period - 5))
first <- 1:half
second <- (half + 1):n
r10 <- mean(P[b10, first]) / mean(P[b10, second])
r5 <- mean(P[b5, second]) / mean(P[b5, first])
c(band_10 = round(o$period[b10], 2), first_over_second = round(r10, 1),
  band_5 = round(o$period[b5], 2), second_over_first = round(r5, 1))

## ---- fig-scalo ----
ridge <- sapply(seq_len(n), function(i) {
  ok <- o$period <= o$coi[i]
  if (!any(ok)) return(NA_real_)      # the first and last few years have nothing usable
  o$period[which.max(replace(P[, i], !ok, -Inf))]
})
ridge_df <- na.omit(data.frame(time = tt, period = ridge))
dfP <- expand.grid(time = tt, period = o$period)
dfP$power <- as.vector(t(P))
ggplot(dfP, aes(time, period, fill = power)) +
  geom_raster() +
  geom_line(data = data.frame(time = tt, period = o$coi),
            aes(time, period), inherit.aes = FALSE,
            colour = "#f5f4ee", linewidth = 0.7) +
  geom_ribbon(data = data.frame(time = tt, period = o$coi),
              aes(x = time, ymin = period, ymax = max(o$period)), inherit.aes = FALSE,
              fill = "white", alpha = 0.55) +
  geom_line(data = ridge_df, aes(time, period), inherit.aes = FALSE,
            colour = "#c9b458", linetype = "22", linewidth = 0.6) +
  scale_fill_gradient(low = "#f5f4ee", high = "#275139", name = "power") +
  scale_y_continuous(transform = "log2", breaks = c(2, 4, 8, 16, 32, 64, 128),
                     expand = c(0, 0)) +
  scale_x_continuous(expand = c(0, 0)) +
  coord_cartesian(ylim = c(2, 128)) +
  labs(x = "year", y = "period (years)", title = "Wavelet power",
       subtitle = "the two cycles are sequential, not simultaneous") +
  theme_te()

## ---- ridge-num ----
c(median_period_years_30_to_100 = round(median(ridge[30:100], na.rm = TRUE), 2),
  median_period_years_160_to_230 = round(median(ridge[160:230], na.rm = TRUE), 2))

## ---- bias-tease ----
c(power_at_period_10 = round(mean(P[b10, first]), 1),
  power_at_period_5 = round(mean(P[b5, second]), 1),
  power_ratio = round(mean(P[b10, first]) / mean(P[b5, second]), 2),
  period_ratio = round(o$period[b10] / o$period[b5], 2))

## ---- gws ----
gws <- rowMeans(P)
g10 <- which(o$period > 7 & o$period < 14)
g5 <- which(o$period > 3.5 & o$period < 7)
gws_10 <- o$period[g10][which.max(gws[g10])]
gws_5 <- o$period[g5][which.max(gws[g5])]
c(gws_peak_near_10 = round(gws_10, 2), periodogram_said = round(p_peak10, 2),
  gws_peak_near_5 = round(gws_5, 2), periodogram_said = round(p_peak5, 2))

## ---- fig-gws ----
dfG <- rbind(
  data.frame(period = o$period, v = gws / max(gws), what = "global wavelet spectrum"),
  data.frame(period = pgp, v = pg$spec / max(pg$spec), what = "periodogram"))
ggplot(dfG, aes(period, v, colour = what)) +
  geom_line(linewidth = 0.45) +
  scale_x_continuous(transform = "log2", breaks = c(2, 4, 8, 16, 32, 64)) +
  coord_cartesian(xlim = c(2, 64)) +
  scale_colour_manual(values = c("global wavelet spectrum" = "#275139",
                                 "periodogram" = "#c9b458"), name = NULL) +
  labs(x = "period (years)", y = "power (own maximum = 1)",
       title = "Same peaks, different smoothness") +
  theme_te() + theme(legend.position = "bottom")

## ---- invert ----
cwt_invert <- function(o, Cdelta = 0.776) {
  (o$dj * sqrt(o$dt)) / (Cdelta * pi^(-0.25)) * colSums(Re(o$W) / sqrt(o$scale))
}
yr <- cwt_invert(o)
rel_noisy <- sqrt(mean((yr - (y - mean(y)))^2)) / sd(y)
clean <- 20 + 6 * sig
oc <- cwt(clean)
rel_clean <- sqrt(mean((cwt_invert(oc) - (clean - mean(clean)))^2)) / sd(clean)
c(rel_rmse_noisy = round(rel_noisy, 4), rel_rmse_noiseless = round(rel_clean, 4))

## ---- coi ----
usable <- mean(outer(o$period, o$coi, "<="))
c(cone_slope = round(fourier_factor(6) / sqrt(2), 4),
  longest_usable_period_at_year_10 = round(o$coi[10], 2),
  longest_at_year_50 = round(o$coi[50], 2),
  share_of_map_usable = round(usable, 3))

## ---- thumb ----
ggsave("thumbnail.png",
  ggplot(dfP, aes(time, period, fill = power)) +
    geom_raster() +
    geom_ribbon(data = data.frame(time = tt, period = o$coi),
                aes(x = time, ymin = period, ymax = max(o$period)), inherit.aes = FALSE,
                fill = "white", alpha = 0.55) +
    geom_line(data = ridge_df, aes(time, period),
              inherit.aes = FALSE, colour = "#c9b458", linetype = "22", linewidth = 0.7) +
    scale_fill_gradient(low = "#f5f4ee", high = "#275139", guide = "none") +
    scale_y_continuous(transform = "log2", breaks = c(2, 4, 8, 16, 32, 64), expand = c(0, 0)) +
    scale_x_continuous(expand = c(0, 0)) +
    coord_cartesian(ylim = c(2, 64)) +
    labs(x = "year", y = "period") + theme_te(13),
  width = 7.5, height = 5.4, dpi = 100, bg = "#f5f4ee")
