# Spectral analysis of population cycles
# https://tidyecology.com/posts/spectral-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-10-15

## ---- setup ----
library(ggplot2)
theme_te <- function(base_size = 12) {
  theme_minimal(base_size = base_size) + theme(
    text = element_text(colour = "#2c3a31"),
    plot.title = element_text(colour = "#16241d", face = "bold", size = rel(0.95)),
    plot.subtitle = element_text(colour = "#46604a", size = rel(0.80)),
    axis.title = element_text(colour = "#46604a", size = rel(0.88)),
    axis.text = element_text(colour = "#5d6b61", size = rel(0.78)),
    panel.grid.major = element_line(colour = "#dad9ca", linewidth = 0.3),
    panel.grid.minor = element_blank(),
    plot.background = element_rect(fill = "#f5f4ee", colour = NA),
    panel.background = element_rect(fill = "#f5f4ee", colour = NA),
    legend.position = "top")
}
FOREST <- "#275139"; GOLD <- "#c9b458"; RUST <- "#b5534e"; SAGE <- "#93a87f"; GREY <- "#8a988c"

## ---- cycle ----
set.seed(4242)
n <- 200; P_true <- 10; t <- 1:n
y <- 2 * cos(2 * pi * t / P_true) + as.numeric(arima.sim(list(ar = 0.3), n = n, sd = 1))

sp_raw <- spec.pgram(y, taper = 0, detrend = TRUE, log = "no", plot = FALSE)
sp_sm  <- spec.pgram(y, spans = 3, taper = 0.1, detrend = TRUE, log = "no", plot = FALSE)  # modified Daniell, spans = 3
peak_raw <- 1 / sp_raw$freq[which.max(sp_raw$spec)]
peak_sm  <- 1 / sp_sm$freq[which.max(sp_sm$spec)]
bg <- abs(sp_raw$freq - 1 / P_true) > 3.5 / n   # leave out the cycle ordinate and three neighbours either side
cv_raw <- sd(sp_raw$spec[bg]) / mean(sp_raw$spec[bg])
cv_sm  <- sd(sp_sm$spec[bg]) / mean(sp_sm$spec[bg])
ht_sm  <- max(sp_sm$spec) / max(sp_raw$spec)    # smoothed peak height relative to the raw one

## ---- aliasing ----
set.seed(303)
Nf <- 600; P_fast <- 3                         # a period-3 cycle in fine steps
xf <- 1.5 * cos(2 * pi * (1:Nf) / P_fast) + rnorm(Nf, 0, 0.4)
m <- 2                                         # keep every 2nd point (undersample)
xc <- xf[seq(1, Nf, by = m)]

spf <- spec.pgram(xf, taper = 0, detrend = TRUE, log = "no", plot = FALSE)
spc <- spec.pgram(xc, taper = 0, detrend = TRUE, log = "no", plot = FALSE)
peak_fine   <- 1 / spf$freq[which.max(spf$spec)]              # in fine steps
peak_coarse <- 1 / (spc$freq[which.max(spc$spec)] / m)        # back in original steps
nyq_coarse  <- 1 / (2 * m)

## ---- fig-alias ----
dfF <- data.frame(f = spf$freq, s = spf$spec / max(spf$spec))
dfC <- data.frame(f = spc$freq / m, s = spc$spec / max(spc$spec))
pC <- ggplot(dfF, aes(f, s)) +
  geom_line(colour = FOREST, linewidth = 0.6) +
  geom_vline(xintercept = 1/3, colour = RUST, linetype = "dashed", linewidth = 0.5) +
  annotate("text", x = 1/3 + 0.01, y = 0.9, label = "true freq 1/3\n(period 3)", colour = RUST, size = 3, hjust = 0) +
  labs(title = "Densely sampled: the true cycle",
       subtitle = "Every step; Nyquist = 0.5, so period 3 is resolved",
       x = "Frequency (cycles per step)", y = "Relative power") +
  coord_cartesian(xlim = c(0, 0.5)) + theme_te()
pD <- ggplot(dfC, aes(f, s)) +
  geom_line(colour = FOREST, linewidth = 0.6) +
  geom_vline(xintercept = nyq_coarse, colour = GREY, linetype = "dotted", linewidth = 0.5) +
  geom_vline(xintercept = 1/6, colour = RUST, linetype = "dashed", linewidth = 0.5) +
  annotate("text", x = 1/6 - 0.008, y = 0.9, label = "apparent freq 1/6\n(period 6, WRONG)", colour = RUST, size = 3, hjust = 1) +
  annotate("text", x = nyq_coarse + 0.006, y = 0.35, label = "Nyquist 0.25", colour = GREY, size = 2.8, hjust = 0) +
  labs(title = "Every 2nd point: aliased",
       subtitle = "Nyquist drops to 0.25; the true 1/3 folds down to 1/6",
       x = "Frequency (cycles per step)", y = "Relative power") +
  coord_cartesian(xlim = c(0, 0.5)) + theme_te()
grid::grid.newpage(); grid::pushViewport(grid::viewport(layout = grid::grid.layout(1, 2)))
print(pC, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 1))
print(pD, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 2))

## ---- red-null ----
set.seed(202)
phi <- 0.75
r <- as.numeric(arima.sim(list(ar = phi), n = n, sd = 1))    # persistent, NO cycle
spa <- spec.pgram(r, taper = 0, detrend = TRUE, log = "no", plot = FALSE)
f <- spa$freq; Pgram <- spa$spec

fit1 <- arima(r, order = c(1, 0, 0)); ph <- coef(fit1)["ar1"]; s2 <- fit1$sigma2
ar_spec <- s2 / (1 - 2 * ph * cos(2 * pi * f) + ph^2)         # AR(1) spectral density
ar_spec <- ar_spec * (mean(Pgram) / mean(ar_spec))            # match average power
white_thr <- mean(Pgram) * qchisq(0.95, 2) / 2                # flat 95% threshold
red_thr   <- ar_spec * qchisq(0.95, 2) / 2                    # rising 95% threshold

imax <- which.max(Pgram)
lo <- f < 0.1
n_white_lo <- sum(Pgram[lo] > white_thr)
n_red_lo   <- sum(Pgram[lo] > red_thr[lo])

## ---- fig-spectral ----
dfRaw <- data.frame(f = sp_raw$freq, s = sp_raw$spec); dfSm <- data.frame(f = sp_sm$freq, s = sp_sm$spec)
pA <- ggplot() +
  geom_line(data = dfRaw, aes(f, s), colour = GREY, linewidth = 0.7) +
  geom_line(data = dfSm, aes(f, s), colour = FOREST, linewidth = 0.7, alpha = 0.85) +
  geom_vline(xintercept = 0.1, colour = RUST, linetype = "dashed", linewidth = 0.4) +
  annotate("text", x = 0.13, y = max(dfRaw$s) * 0.9, label = "peak at\nperiod 10", colour = RUST, size = 3, hjust = 0) +
  annotate("text", x = 0.30, y = max(dfRaw$s) * 0.62, label = "raw (grey): noisy", colour = GREY, size = 2.9, hjust = 0) +
  annotate("text", x = 0.30, y = max(dfRaw$s) * 0.48, label = "smoothed (green)", colour = FOREST, size = 2.9, hjust = 0) +
  labs(title = "Periodogram of a cycle (period 10) plus noise",
       subtitle = "The raw periodogram is noisy; smoothing lowers its variance",
       x = "Frequency (cycles per step)", y = "Spectral power") + theme_te()
dfP <- data.frame(f = f, P = Pgram); dfThr <- data.frame(f = f, white = white_thr, red = red_thr)
pB <- ggplot() +
  geom_segment(data = dfP, aes(f, xend = f, y = 0, yend = P), colour = FOREST, linewidth = 0.4) +
  geom_line(data = dfThr, aes(f, white), colour = GOLD, linetype = "dashed", linewidth = 0.8) +
  geom_line(data = dfThr, aes(f, red), colour = RUST, linewidth = 0.9) +
  annotate("text", x = 0.28, y = max(Pgram) * 0.97, label = "dominant peak clears the", colour = "#16241d", size = 2.9, hjust = 0) +
  annotate("text", x = 0.28, y = max(Pgram) * 0.90, label = sprintf("white line (x%.1f) but sits", Pgram[imax] / white_thr), colour = "#16241d", size = 2.9, hjust = 0) +
  annotate("text", x = 0.28, y = max(Pgram) * 0.83, label = sprintf("below the red line (x%.2f)", Pgram[imax] / red_thr[imax]), colour = "#16241d", size = 2.9, hjust = 0) +
  annotate("text", x = 0.28, y = max(Pgram) * 0.60, label = "white-noise 95%", colour = GOLD, size = 2.9, hjust = 0) +
  annotate("text", x = 0.05, y = max(Pgram) * 0.70, label = "red-noise 95%", colour = RUST, size = 2.9, hjust = 0) +
  labs(title = "AR(1) series with NO cycle: which null?",
       subtitle = "Persistence fakes low-frequency peaks against a white null",
       x = "Frequency (cycles per step)", y = "Spectral power") +
  coord_cartesian(ylim = c(0, max(Pgram) * 1.05)) + theme_te()
grid::grid.newpage(); grid::pushViewport(grid::viewport(layout = grid::grid.layout(1, 2)))
print(pA, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 1))
print(pB, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 2))
