# Wavelet significance and the red noise null
# https://tidyecology.com/posts/wavelet-significance-and-red-noise/
#
# 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-15

## ---- 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)
}
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))
}

## ---- sim ----
set.seed(285)
n <- 256
y <- as.numeric(arima.sim(list(ar = 0.7), n = n))
acf1 <- as.numeric(acf(y, lag.max = 1, plot = FALSE)$acf[2])
o <- cwt(y)
P <- Mod(o$W)^2
usable <- outer(o$period, o$coi, "<=")
c(true_phi = 0.7, sample_lag1_acf = round(acf1, 3),
  map_cells = length(P), usable_cells = sum(usable))

## ---- nulls ----
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

lev_white <- sig95(o, y, 0)
lev_red <- sig95(o, y, acf1)
frac_white <- mean((P > lev_white)[usable])
frac_red <- mean((P > lev_red)[usable])
c(flagged_under_white_null = round(frac_white, 3),
  flagged_under_red_null = round(frac_red, 3))

## ---- fig-trap ----
mk <- function(lev, ttl, sub) {
  df <- expand.grid(time = 1:n, period = o$period)
  df$power <- as.vector(t(P))
  df$sig <- as.vector(t((P > lev) & usable))
  ggplot(df, 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 = 1:n, 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, 128), expand = c(0, 0)) +
    scale_x_continuous(expand = c(0, 0)) +
    coord_cartesian(ylim = c(2, 128)) +
    labs(x = NULL, y = "period", title = ttl, subtitle = sub) + theme_te()
}
g1 <- mk(lev_white, "White noise null",
         sprintf("%.0f%% of the usable map flagged, and there is no cycle here", 100 * frac_white))
g2 <- mk(lev_red, "Red noise null",
         sprintf("%.1f%% flagged, which is what 95%% is meant to mean", 100 * frac_red)) +
  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))

## ---- mc ----
mc <- function(B, n, phi, seed) {
  set.seed(seed)
  out <- matrix(NA_real_, B, 2)
  for (b in 1:B) {
    z <- as.numeric(arima.sim(list(ar = phi), n = n))
    oz <- cwt(z); Pz <- Mod(oz$W)^2
    ok <- outer(oz$period, oz$coi, "<=")
    a <- as.numeric(acf(z, lag.max = 1, plot = FALSE)$acf[2])
    out[b, ] <- c(mean((Pz > sig95(oz, z, 0))[ok]), mean((Pz > sig95(oz, z, a))[ok]))
  }
  colnames(out) <- c("white", "red")
  out
}
m <- mc(200, n, 0.7, 1285)
rate_white <- mean(m[, "white"])
rate_red <- mean(m[, "red"])
c(white_null_rejection_rate = round(rate_white, 3),
  red_null_rejection_rate = round(rate_red, 3),
  red_sd_across_series = round(sd(m[, "red"]), 3))

## ---- levels ----
i4 <- which.min(abs(o$period - 4)); i32 <- which.min(abs(o$period - 32))
c(red_level_at_period_4 = round(lev_red[i4], 2),
  red_level_at_period_32 = round(lev_red[i32], 2),
  level_ratio = round(lev_red[i32] / lev_red[i4], 1))

## ---- fig-levels ----
dfL <- rbind(
  data.frame(period = o$period, v = lev_white, what = "95% level, white null"),
  data.frame(period = o$period, v = lev_red, what = "95% level, red null"),
  data.frame(period = o$period, v = rowMeans(P), what = "observed mean power"))
ggplot(dfL, aes(period, v, colour = what, linetype = what)) +
  geom_line(linewidth = 0.5) +
  scale_x_continuous(transform = "log2", breaks = c(2, 4, 8, 16, 32, 64, 128)) +
  scale_y_continuous(transform = "log10") +
  coord_cartesian(xlim = c(2, 128)) +
  scale_colour_manual(values = c("95% level, white null" = "#c9b458",
                                 "95% level, red null" = "#b5534e",
                                 "observed mean power" = "#275139"), name = NULL) +
  scale_linetype_manual(values = c("95% level, white null" = "22",
                                   "95% level, red null" = "22",
                                   "observed mean power" = "solid"), name = NULL) +
  labs(x = "period (years)", y = "power (log scale)",
       title = "Why the white null flags the long periods") +
  theme_te() + theme(legend.position = "bottom")

## ---- coi-power ----
s16 <- 20 + 4 * sin(2 * pi * (1:n) / 16)   # a cycle of constant amplitude throughout
o16 <- cwt(s16); P16 <- Mod(o16$W)^2
b16 <- which.min(abs(o16$period - 16))
c(power_at_year_128 = round(P16[b16, 128], 2),
  power_at_year_20 = round(P16[b16, 20], 2),
  power_at_year_5 = round(P16[b16, 5], 2),
  year_5_as_share_of_mid = round(P16[b16, 5] / P16[b16, 128], 3),
  cone_reaches_period_16_at_year = ceiling(16 / (fourier_factor(6) / sqrt(2))))

## ---- patches ----
lab_patches <- function(M) {
  lab <- matrix(0L, nrow(M), ncol(M)); cur <- 0L
  for (i in seq_len(nrow(M))) for (j in seq_len(ncol(M))) {
    if (!M[i, j] || lab[i, j]) next
    cur <- cur + 1L
    stack <- list(c(i, j)); lab[i, j] <- cur
    while (length(stack)) {
      p <- stack[[length(stack)]]; stack[[length(stack)]] <- NULL
      for (d in list(c(-1, 0), c(1, 0), c(0, -1), c(0, 1))) {
        a <- p[1] + d[1]; b <- p[2] + d[2]
        if (a >= 1 && a <= nrow(M) && b >= 1 && b <= ncol(M) && M[a, b] && !lab[a, b]) {
          lab[a, b] <- cur; stack[[length(stack) + 1]] <- c(a, b)
        }
      }
    }
  }
  lab
}
flagged <- (P > lev_red) & usable
lab <- lab_patches(flagged)
sizes <- sort(tabulate(lab[lab > 0]), decreasing = TRUE)
c(flagged_cells = sum(flagged), patches = length(sizes),
  largest_patch = sizes[1], second = sizes[2], third = sizes[3])

## ---- areawise ----
mc_patch <- function(B, n, phi, seed) {
  set.seed(seed); big <- integer(B)
  for (b in 1:B) {
    z <- as.numeric(arima.sim(list(ar = phi), n = n))
    oz <- cwt(z); Pz <- Mod(oz$W)^2
    ok <- outer(oz$period, oz$coi, "<=")
    a <- as.numeric(acf(z, lag.max = 1, plot = FALSE)$acf[2])
    L <- lab_patches((Pz > sig95(oz, z, a)) & ok)
    tb <- tabulate(L[L > 0])
    big[b] <- if (length(tb)) max(tb) else 0L
  }
  big
}
null_big <- mc_patch(200, n, 0.7, 2285)
c(null_largest_patch_median = median(null_big),
  null_largest_patch_95th = round(quantile(null_big, 0.95), 0),
  null_largest_patch_max = max(null_big))

## ---- real ----
set.seed(3285)
env <- ifelse((1:n) >= 80 & (1:n) <= 140, 1, 0)
amp <- 3.0
z <- as.numeric(arima.sim(list(ar = 0.7), n = n)) + amp * env * sin(2 * pi * (1:n) / 10)
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])
Lz <- lab_patches((Pz > sig95(oz, z, az)) & okz)
tz <- sort(tabulate(Lz[Lz > 0]), decreasing = TRUE)
p_area <- mean(null_big >= tz[1])
proc_sd <- sqrt(1 / (1 - 0.7^2))
c(cycle_amplitude = amp, noise_process_sd = round(proc_sd, 2),
  flagged_cells = sum(Lz > 0), largest_patch = tz[1],
  areawise_p = round(p_area, 3))

## ---- fig-areawise ----
q95 <- as.numeric(quantile(null_big, 0.95))
ggplot(data.frame(x = null_big), aes(x)) +
  geom_histogram(bins = 28, fill = "#dad9ca", colour = "white", linewidth = 0.2) +
  geom_vline(xintercept = q95, colour = "#b5534e", linetype = "22", linewidth = 0.5) +
  annotate("point", x = tz[1], y = 2, colour = "#275139", size = 2.6) +
  annotate("point", x = sizes[1], y = 2, colour = "#c9b458", size = 2.6) +
  annotate("segment", x = tz[1], xend = tz[1], y = 2.6, yend = 5.8,
           colour = "#275139", linewidth = 0.3) +
  annotate("segment", x = sizes[1], xend = sizes[1], y = 2.6, yend = 5.8,
           colour = "#b08d1e", linewidth = 0.3) +
  annotate("label", x = tz[1], y = 7, label = "real transient cycle",
           colour = "#275139", size = 3, hjust = 0.9,
           fill = "#f5f4ee", linewidth = 0) +
  annotate("label", x = sizes[1], y = 7, label = "no cycle at all",
           colour = "#b08d1e", size = 3, hjust = -0.05,
           fill = "#f5f4ee", linewidth = 0) +
  annotate("text", x = q95, y = 20, label = "null 95th pct",
           colour = "#b5534e", size = 3, hjust = -0.1) +
  labs(x = "largest patch of pointwise-significant cells", y = "number of null series",
       title = "Test the patch, not the pixel",
       subtitle = "200 red noise series with no cycle in any of them") +
  theme_te()

## ---- sweep ----
sweep_one <- function(amp, seed = 3285) {
  set.seed(seed)
  zz <- as.numeric(arima.sim(list(ar = 0.7), n = n)) + amp * env * sin(2 * pi * (1:n) / 10)
  oo <- cwt(zz); PP <- Mod(oo$W)^2
  ok <- outer(oo$period, oo$coi, "<=")
  a <- as.numeric(acf(zz, lag.max = 1, plot = FALSE)$acf[2])
  LL <- lab_patches((PP > sig95(oo, zz, a)) & ok)
  tb <- tabulate(LL[LL > 0])
  bg <- if (length(tb)) max(tb) else 0L
  c(amplitude = amp, amp_over_noise_sd = round(amp / sqrt(2) / proc_sd, 2),
    largest_patch = bg, areawise_p = round(mean(null_big >= bg), 3))
}
t(sapply(c(0, 1.0, 1.6, 2.2, 3.0, 4.0), sweep_one))

## ---- pink ----
pink <- function(n, beta = 1) {
  m <- 2^ceiling(log2(n)) * 2
  z <- fft(rnorm(m))
  f <- c(1, seq_len(m / 2), rev(seq_len(m / 2 - 1)))
  x <- Re(fft(z / f^(beta / 2), inverse = TRUE))[seq_len(n)]
  as.numeric(scale(x))
}
long_cut <- 70
pk_long <- c(flagged = 0, usable = 0)
set.seed(4285)
pk_rate <- replicate(200, {
  z <- pink(n)
  oz <- cwt(z); Pz <- Mod(oz$W)^2
  ok <- outer(oz$period, oz$coi, "<=")
  hit <- Pz > sig95(oz, z, as.numeric(acf(z, lag.max = 1, plot = FALSE)$acf[2]))
  long <- ok & (oz$period >= long_cut)
  pk_long <<- pk_long + c(sum(hit[long]), sum(long))
  mean(hit[ok])
})
pk_long_rate <- pk_long[["flagged"]] / pk_long[["usable"]]
c(pink_noise_rejection_rate = round(mean(pk_rate), 3),
  rate_at_longest_periods = round(pk_long_rate, 3), nominal = 0.05)

## ---- thumb ----
dfT <- expand.grid(time = 1:n, period = o$period)
dfT$power <- as.vector(t(P))
dfT$sig <- as.vector(t((P > lev_white) & usable))
ggsave("thumbnail.png",
  ggplot(dfT, 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 = 1:n, 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 = "year", y = "period") + theme_te(13),
  width = 7.5, height = 5.4, dpi = 100, bg = "#f5f4ee")
