# Wavelet coherence and phase
# https://tidyecology.com/posts/wavelet-coherence-and-phase/
#
# 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

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

## ---- identity ----
set.seed(286)
n <- 300
x1 <- as.numeric(arima.sim(list(ar = 0.8), n))
x2 <- as.numeric(arima.sim(list(ar = 0.8), n))   # completely independent
o1 <- cwt(x1); o2 <- cwt(x2)
Wxy <- o1$W * Conj(o2$W)
lhs <- Mod(Wxy)^2
rhs <- Mod(o1$W)^2 * Mod(o2$W)^2
max_rel_diff <- max(abs(lhs - rhs) / rhs)
c(max_relative_difference = signif(max_rel_diff, 3))

## ---- crosspow ----
usable <- outer(o1$period, o1$coi, "<=")
lhs_ok <- replace(lhs, !usable, -Inf)
i_max <- which(lhs_ok == max(lhs_ok), arr.ind = TRUE)[1, ]
c(largest_cross_power = round(max(lhs_ok), 1),
  at_period = round(o1$period[i_max[1]], 2), at_year = as.numeric(i_max[2]))

## ---- unsmoothed ----
R2_raw <- Mod(Wxy)^2 / (Mod(o1$W)^2 * Mod(o2$W)^2)
c(max_deviation_from_one = signif(max(abs(R2_raw - 1)), 3),
  min_coherence = min(R2_raw), max_coherence = max(R2_raw))

## ---- smoother ----
smooth_wt <- function(M, scale, dt, dj) {
  n <- ncol(M)
  npad <- 2^ceiling(log2(n))
  kk <- seq_len(floor(npad / 2)) * (2 * pi / npad)
  k2 <- c(0, kk, -rev(kk[seq_len(floor((npad - 1) / 2))]))^2
  S <- matrix(0 + 0i, nrow(M), n)
  for (a in seq_len(nrow(M))) {                       # gaussian in time, width proportional to scale
    z <- c(M[a, ], rep(0, npad - n))
    S[a, ] <- (fft(exp(-0.5 * (scale[a] / dt)^2 * k2) * fft(z), inverse = TRUE) / npad)[seq_len(n)]
  }
  m <- 0.6 / (dj * 2)                                 # boxcar of 0.6 decorrelation length (Morlet)
  k <- -ceiling(m):ceiling(m); w <- pmax(0, pmin(1, m + 0.5 - abs(k))); w <- w / sum(w)
  h <- (length(w) - 1) / 2
  out <- matrix(0 + 0i, nrow(M), n)
  for (a in seq_len(nrow(M))) {
    idx <- pmin(pmax(seq(a - h, a + h), 1), nrow(M))
    out[a, ] <- colSums(w * S[idx, , drop = FALSE])
  }
  out
}

wcoh <- function(o1, o2) {
  s <- o1$scale
  Sxy <- smooth_wt(o1$W * Conj(o2$W) / s, s, o1$dt, o1$dj)
  Sxx <- Re(smooth_wt((Mod(o1$W)^2 + 0i) / s, s, o1$dt, o1$dj))
  Syy <- Re(smooth_wt((Mod(o2$W)^2 + 0i) / s, s, o1$dt, o1$dj))
  list(R2 = Mod(Sxy)^2 / (Sxx * Syy), phase = Arg(Sxy))
}

## ---- indep-coh ----
cc <- wcoh(o1, o2)
c(mean_coherence_independent_pair = round(mean(cc$R2[usable]), 3),
  max_coherence = round(max(cc$R2[usable]), 3),
  in_range = all(cc$R2 >= 0 & cc$R2 <= 1 + 1e-9))

## ---- coupled ----
set.seed(1286)
tt <- 1:n
per <- 10
true_lag <- 2.5                                       # a quarter of the period
prey <- sin(2 * pi * tt / per) + rnorm(n, 0, 0.4)
pred <- sin(2 * pi * (tt - true_lag) / per) + rnorm(n, 0, 0.4)
q1 <- cwt(prey); q2 <- cwt(pred)
cq <- wcoh(q1, q2)
band <- which.min(abs(q1$period - per))
sel <- q1$period[band] <= q1$coi
coh_band <- mean(cq$R2[band, sel])
ph <- mean(cq$phase[band, sel])
lag_hat <- ph / (2 * pi) * q1$period[band]
c(band_period = round(q1$period[band], 2), mean_coherence = round(coh_band, 3),
  mean_phase_rad = round(ph, 4), implied_lag = round(lag_hat, 3), true_lag = true_lag)

## ---- ccf ----
cf <- ccf(prey, pred, lag.max = 12, plot = FALSE)
c(ccf_peak_lag = cf$lag[which.max(cf$acf)], ccf_peak_value = round(max(cf$acf), 3))

## ---- fig-coh ----
pTop <- ggplot(rbind(data.frame(t = tt, v = prey, s = "prey"),
                     data.frame(t = tt, v = pred, s = "predator")), aes(t, v, colour = s)) +
  geom_line(linewidth = 0.35) +
  scale_colour_manual(values = c(prey = "#275139", predator = "#b5534e"), name = NULL) +
  coord_cartesian(xlim = c(1, 120)) +
  labs(x = NULL, y = "index", title = "Two coupled series (first 120 years shown)") +
  theme_te() + theme(legend.position = "bottom")
dfc <- expand.grid(time = tt, period = q1$period)
dfc$R2 <- as.vector(t(cq$R2))
ar <- expand.grid(time = seq(12, n - 12, by = 14), period = q1$period[seq(4, length(q1$period), by = 7)])
ar$ph <- mapply(function(ti, pe) cq$phase[which.min(abs(q1$period - pe)), ti], ar$time, ar$period)
ar$r2 <- mapply(function(ti, pe) cq$R2[which.min(abs(q1$period - pe)), ti], ar$time, ar$period)
ar <- ar[ar$r2 > 0.6 & ar$period <= q1$coi[ar$time], ]
ar$dx <- 9 * cos(ar$ph); ar$dy <- 0.16 * sin(ar$ph) * ar$period
pBot <- ggplot(dfc, aes(time, period)) +
  geom_raster(aes(fill = R2)) +
  geom_segment(data = ar, aes(x = time, y = period, xend = time + dx, yend = period + dy),
               inherit.aes = FALSE, colour = "#f5f4ee", linewidth = 0.35,
               arrow = grid::arrow(length = grid::unit(0.05, "cm"), type = "closed")) +
  geom_ribbon(data = data.frame(time = tt, period = q1$coi),
              aes(x = time, ymin = period, ymax = max(q1$period)), inherit.aes = FALSE,
              fill = "white", alpha = 0.6) +
  scale_fill_gradient(low = "#f5f4ee", high = "#275139", name = "coherence", limits = c(0, 1)) +
  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 coherence, with phase arrows") +
  theme_te()
grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(2, 1, heights = grid::unit(c(2, 3), "null"))))
print(pTop, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 1))
print(pBot, vp = grid::viewport(layout.pos.row = 2, layout.pos.col = 1))

## ---- null-coh ----
mc_coh <- function(B, n, phi, seed) {
  set.seed(seed)
  out <- numeric(0)
  for (b in 1:B) {
    z1 <- as.numeric(arima.sim(list(ar = phi), n))
    z2 <- as.numeric(arima.sim(list(ar = phi), n))
    p1 <- cwt(z1); p2 <- cwt(z2)
    r <- wcoh(p1, p2)$R2
    out <- c(out, r[outer(p1$period, p1$coi, "<=")])
  }
  out
}
nullR2 <- mc_coh(200, 200, 0.7, 2286)
c(null_mean = round(mean(nullR2), 3), null_median = round(median(nullR2), 3),
  null_95th = round(quantile(nullR2, 0.95), 3), null_99th = round(quantile(nullR2, 0.99), 3),
  share_of_null_above_0.5 = round(mean(nullR2 > 0.5), 3),
  share_of_null_below_0.7 = round(mean(nullR2 < 0.7), 3))

## ---- fig-null ----
ggplot(data.frame(x = nullR2), aes(x)) +
  geom_histogram(bins = 50, fill = "#dad9ca", colour = NA) +
  geom_vline(xintercept = median(nullR2), colour = "#c9b458", linetype = "22", linewidth = 0.5) +
  geom_vline(xintercept = as.numeric(quantile(nullR2, 0.95)), colour = "#b5534e",
             linetype = "22", linewidth = 0.5) +
  geom_vline(xintercept = coh_band, colour = "#275139", linewidth = 0.6) +
  annotate("text", x = median(nullR2), y = Inf, label = " null median", colour = "#b08d1e",
           hjust = 0, vjust = 1.6, size = 3) +
  annotate("text", x = as.numeric(quantile(nullR2, 0.95)), y = Inf, label = " null 95th",
           colour = "#b5534e", hjust = 0, vjust = 3.2, size = 3) +
  annotate("text", x = coh_band, y = Inf, label = "the coupled pair ", colour = "#275139",
           hjust = 1, vjust = 1.6, size = 3) +
  labs(x = "coherence", y = "cells", title = "Coherence under the null",
       subtitle = "200 pairs of independent AR(1) series") +
  theme_te()

## ---- wrap ----
set.seed(2287)
big_lag <- 7
w1 <- sin(2 * pi * tt / per) + rnorm(n, 0, 0.4)
w2 <- sin(2 * pi * (tt - big_lag) / per) + rnorm(n, 0, 0.4)
v1 <- cwt(w1); v2 <- cwt(w2)
cw <- wcoh(v1, v2)
selw <- v1$period[band] <= v1$coi
phw <- mean(cw$phase[band, selw])
c(true_lag = big_lag, mean_phase_rad = round(phw, 3),
  apparent_lag = round(phw / (2 * pi) * v1$period[band], 3),
  coherence = round(mean(cw$R2[band, selw]), 3))

## ---- driver ----
set.seed(3286)
driver <- sin(2 * pi * tt / 12)
sp_a <- 1.2 * driver + rnorm(n, 0, 0.5)
sp_b <- 1.2 * driver + rnorm(n, 0, 0.5)   # sp_b never sees sp_a
d1 <- cwt(sp_a); d2 <- cwt(sp_b)
cd <- wcoh(d1, d2)
bd <- which.min(abs(d1$period - 12))
seld <- d1$period[bd] <= d1$coi
c(coherence_at_period_12 = round(mean(cd$R2[bd, seld]), 3),
  mean_phase_rad = round(mean(cd$phase[bd, seld]), 4))

## ---- edge ----
c(mean_coherence_usable = round(mean(cc$R2[usable]), 3),
  mean_coherence_in_the_cone = round(mean(cc$R2[!usable]), 3))

## ---- thumb ----
ggsave("thumbnail.png",
  ggplot(dfc, aes(time, period)) +
    geom_raster(aes(fill = R2)) +
    geom_segment(data = ar, aes(x = time, y = period, xend = time + dx, yend = period + dy),
                 inherit.aes = FALSE, colour = "#f5f4ee", linewidth = 0.4,
                 arrow = grid::arrow(length = grid::unit(0.06, "cm"), type = "closed")) +
    geom_ribbon(data = data.frame(time = tt, period = q1$coi),
                aes(x = time, ymin = period, ymax = max(q1$period)), inherit.aes = FALSE,
                fill = "white", alpha = 0.6) +
    scale_fill_gradient(low = "#f5f4ee", high = "#275139", guide = "none", limits = c(0, 1)) +
    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) +
    theme(plot.margin = ggplot2::margin(8, 14, 8, 8)),
  width = 7.5, height = 5.4, dpi = 100, bg = "#f5f4ee")
