# Checking a wavelet analysis
# https://tidyecology.com/posts/checking-a-wavelet-analysis/
#
# 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-14

## ---- engine ----
morlet_daughter <- function(k, scale, dt, w0 = 6) {
  nrm <- sqrt(2 * pi * scale / dt) * pi^(-0.25)
  nrm * exp(-(scale * k - w0)^2 / 2 * (k > 0)) * (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)); 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))]))
  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(ceiling((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)
}
P_theor <- function(period, dt, alpha) {
  fr <- dt / period
  (1 - alpha^2) / (1 + alpha^2 - 2 * alpha * cos(2 * pi * fr))
}
sig95 <- function(o, x, alpha) var(x) * P_theor(o$period, o$dt, alpha) * qchisq(0.95, 2) / 2
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))
}

## ---- bias ----
n <- 1024
t <- 1:n
x <- sin(2 * pi * t / 4) + sin(2 * pi * t / 32)     # identical amplitudes
o <- cwt(x)
P <- Mod(o$W)^2
gws <- rowMeans(P)
i4 <- which.min(abs(o$period - 4)); i32 <- which.min(abs(o$period - 32))
c(gws_at_period_4 = round(gws[i4], 1), gws_at_period_32 = round(gws[i32], 1),
  conventional_ratio = round(gws[i32] / gws[i4], 2), true_ratio = 1)

## ---- rectified ----
gws_rect <- rowMeans(P / o$scale)
c(rectified_at_period_4 = round(gws_rect[i4], 3),
  rectified_at_period_32 = round(gws_rect[i32], 3),
  rectified_ratio = round(gws_rect[i32] / gws_rect[i4], 2), true_ratio = 1)

## ---- fig-bias ----
dfB <- rbind(data.frame(period = o$period, v = gws / max(gws), what = "conventional"),
             data.frame(period = o$period, v = gws_rect / max(gws_rect), what = "rectified (power / scale)"))
ggplot(dfB, aes(period, v, colour = what)) +
  geom_line(linewidth = 0.5) +
  geom_vline(xintercept = c(4, 32), colour = "#dad9ca", linewidth = 0.3) +
  scale_x_continuous(transform = "log2", breaks = c(2, 4, 8, 16, 32, 64, 128, 256)) +
  coord_cartesian(xlim = c(2, 256)) +
  scale_colour_manual(values = c("conventional" = "#b5534e",
                                 "rectified (power / scale)" = "#275139"), name = NULL) +
  labs(x = "period", y = "power (each curve scaled to its own peak)",
       title = "Two equal cycles, two different answers",
       subtitle = "vertical guides at the true periods, 4 and 32") +
  theme_te() + theme(legend.position = "bottom")

## ---- spike ----
set.seed(287)
n2 <- 256; t2 <- 1:n2
z <- rnorm(n2)
z[128] <- z[128] + 12                                # one bad winter
oz <- cwt(z)
Pz <- Mod(oz$W)^2
okz <- outer(oz$period, oz$coi, "<=")
az <- as.numeric(acf(z, lag.max = 1, plot = FALSE)$acf[2])
flag <- (Pz > sig95(oz, z, az)) & okz
per_flagged <- range(oz$period[apply(flag, 1, any)])
c(share_of_map_flagged = round(mean(flag[okz]), 3),
  flagged_from_period = round(per_flagged[1], 2),
  flagged_to_period = round(per_flagged[2], 2))

## ---- smear ----
b8 <- which.min(abs(oz$period - 8))
yrs <- which(flag[b8, ])
col_periods <- oz$period[flag[, 128]]
c(at_period = round(oz$period[b8], 2),
  flagged_from_year = min(yrs), flagged_to_year = max(yrs),
  column_period_span = round(max(col_periods) / min(col_periods), 1))

## ---- real-vs-event ----
set.seed(3287)
env <- ifelse(t2 >= 100 & t2 <= 156, 1, 0)
r <- rnorm(n2) + 3 * env * sin(2 * pi * t2 / 8)      # a genuine period-8 transient
orr <- cwt(r)
Pr <- Mod(orr$W)^2
okr <- outer(orr$period, orr$coi, "<=")
ar <- as.numeric(acf(r, lag.max = 1, plot = FALSE)$acf[2])
flag_r <- (Pr > sig95(orr, r, ar)) & okr
col_r <- orr$period[flag_r[, 128]]
c(event_column_span = round(max(col_periods) / min(col_periods), 1),
  cycle_column_span = round(max(col_r) / min(col_r), 1))

## ---- fig-event ----
mk2 <- function(o_, P_, fl_, ttl, sub) {
  d <- expand.grid(time = t2, period = o_$period)
  d$power <- as.vector(t(P_)); d$sig <- as.vector(t(fl_))
  ggplot(d, aes(time, period)) +
    geom_raster(aes(fill = power)) +
    geom_contour(aes(z = as.numeric(sig)), breaks = 0.5, colour = "#b5534e", linewidth = 0.45) +
    geom_ribbon(data = data.frame(time = t2, period = o_$coi),
                aes(x = time, ymin = period, ymax = max(o_$period)), inherit.aes = FALSE,
                fill = "white", alpha = 0.6) +
    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 = NULL, y = "period", title = ttl, subtitle = sub) + theme_te()
}
g1 <- mk2(oz, Pz, flag, "One spike, no cycle",
          sprintf("%.1f%% of the map significant, over a %.1f-fold span of periods",
                  100 * mean(flag[okz]), max(col_periods) / min(col_periods)))
g2 <- mk2(orr, Pr, flag_r, "A real period-8 transient",
          sprintf("the same column spans %.1f-fold", max(col_r) / min(col_r))) + labs(x = "year")
grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(2, 1)))
print(g1, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 1))
print(g2, vp = grid::viewport(layout.pos.row = 2, layout.pos.col = 1))

## ---- w0 ----
half <- n2 / 2
sig2 <- c(sin(2 * pi * (1:half) / 10), sin(2 * pi * ((half + 1):n2) / 5))
fwhm <- function(g, i) {                             # width of the peak at i, at half its height
  half_h <- g[i] / 2
  lo <- i; while (lo > 1 && g[lo - 1] >= half_h) lo <- lo - 1
  hi <- i; while (hi < length(g) && g[hi + 1] >= half_h) hi <- hi + 1
  c(lo, hi)
}
probe <- function(w0) {
  ow <- cwt(sig2, w0 = w0, dj = 0.01)               # fine scale grid, so the width is not quantised
  Pw <- Mod(ow$W)^2
  g <- rowMeans(Pw / ow$scale)                       # rectified, per check one
  b10 <- which.min(abs(ow$period - 10))
  w <- fwhm(g, b10)
  band <- Pw[b10, ] / max(Pw[b10, ])                 # how long to notice the cycle stopped?
  hi <- max(which(band[1:half] > 0.9))
  lo <- min(which(band[half:n2] < 0.1)) + half - 1
  c(w0 = w0,
    fourier_factor = round(fourier_factor(w0), 4),
    period_halfwidth = round(ow$period[w[2]] - ow$period[w[1]], 2),
    transition_years = lo - hi,
    coi_cost_at_period_10 = round(10 / (fourier_factor(w0) / sqrt(2)), 1))
}
tab <- t(sapply(c(4, 6, 12), probe))
tab

## ---- fig-w0 ----
dfW <- do.call(rbind, lapply(c(4, 6, 12), function(w) {
  ow <- cwt(sig2, w0 = w); Pw <- Mod(ow$W)^2
  b <- which.min(abs(ow$period - 10))
  data.frame(year = t2, v = Pw[b, ] / max(Pw[b, ]), w0 = factor(w))
}))
ggplot(dfW, aes(year, v, colour = w0)) +
  geom_vline(xintercept = half, colour = "#dad9ca", linewidth = 0.4) +
  geom_line(linewidth = 0.5) +
  scale_colour_manual(values = c("4" = "#c9b458", "6" = "#275139", "12" = "#b5534e"),
                      name = "w0") +
  labs(x = "year", y = "period-10 band power (scaled)",
       title = "When did the cycle stop?",
       subtitle = "the true answer is exactly at the guide line") +
  theme_te() + theme(legend.position = "bottom")

## ---- thumb ----
dT <- expand.grid(time = t2, period = oz$period)
dT$power <- as.vector(t(Pz)); dT$sig <- as.vector(t(flag))
ggsave("thumbnail.png",
  ggplot(dT, aes(time, period)) +
    geom_raster(aes(fill = power)) +
    geom_contour(aes(z = as.numeric(sig)), breaks = 0.5, colour = "#b5534e", linewidth = 0.6) +
    geom_ribbon(data = data.frame(time = t2, period = oz$coi),
                aes(x = time, ymin = period, ymax = max(oz$period)), inherit.aes = FALSE,
                fill = "white", alpha = 0.6) +
    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")
