Skip to content

Shape, not place: wavelet scattering, GraphWave and struc2vec

Some representations ignore where something is and describe what it looks like. Wavelet scattering does that for signals; GraphWave and struc2vec do it for nodes, so a hub in one corner of a network matches a hub in another.

Advanced ~14 min9 steps

What runs in CodeSplash

You will be able to

  • Describe the scattering cascade of wavelets, moduli and averaging, and why it is stable to shifts
  • Explain the difference between proximity-based node vectors and structural-role vectors
  • Describe how GraphWave and struc2vec build role signatures, and their main pitfalls

Read first

01

Where versus what

Read

A heartbeat shifted by a tenth of a second is the same heartbeat. A hub on the left of a network plays the same part as a hub on the right. Some questions care about where something is, others about what it looks like from where it stands.

Proximity-based representations (PCA scores of raw samples, DeepWalk) mix the two. This lesson's three methods are built to keep what and forget where.

02

The scattering cascade

Read

The wavelet scattering transformWavelet scattering transformFixed wavelet filters, a modulus and an average: features that don't move when a signal shifts and need no training. feeds a signal through fixed filters, never trained:

  • order 0: x∗ϕx * \phi, a local average;
  • order 1: ∣x∗ψλ1∣∗ϕ\lvert x * \psi_{\lambda_1}\rvert * \phi, how much energy sits at scale λ1\lambda_1;
  • order 2: ∣∣x∗ψλ1∣∗ψλ2∣∗ϕ\big\lvert \lvert x * \psi_{\lambda_1}\rvert * \psi_{\lambda_2}\big\rvert * \phi, how that energy itself fluctuates.

The modulus throws away phase, and the final average throws away exact position, so small shifts and gentle stretches barely change the output. Second-order paths keep rhythm information that a single averaged spectrum loses. In the reference's tiny example, one first-order path gives 0.943, 1.179, …: never negative, as moduli and averages must be.

03

Scattering in a run

Read
Wavelet scatteringRecorded · Python and R agreeRecorded 2026-11-21 · 35 values compared · largest relative difference 1.1e-15
R

Scattering transform of 24 series of x (128 values): 20 first-order and 40 second-order coefficients per series over 5 octaves (4 wavelets per octave). A leave-one-out nearest-neighbor probe on class is 88% accurate with order 0–1 and 92% with order 0–2 (always guessing the most common class: 50%).

Coefficients per series
61
Probe accuracy (order 0–1)
0.8750

Assumptions

  • Features suit the task — Assumed, not checked from the data: averaging over the whole series removes timing; use it when where something happens matters less than what happens.

Wavelets

OrderWaveletCenter frequency (cycles per step)Period (steps)Bandwidth σ
110.35002.8570.0334
120.29433.3980.0281
130.24754.0410.0236
140.20814.8050.0199
150.17505.7140.0167
160.14726.7950.0141
170.12378.0810.0118
180.10419.6100.0099
190.087511.4290.0084
1100.073613.5910.0070
1110.061916.1620.0059
1120.052019.2200.0050
1130.043722.8570.0042
1140.036827.1820.0035
1150.030932.3250.0030
1160.026038.4410.0025
1170.021945.7140.0021
1180.018454.3640.0018
1190.015564.6500.0015
1200.013076.8820.0012
210.35002.8570.1051
220.17505.7140.0525
230.087511.4290.0263
240.043722.8570.0131
250.021945.7140.0066

Scattering coefficients

seriesOrderPathCoefficient
s010mean0.0135
s011period 2.860.0177
s011period 3.40.0189
s011period 4.040.0216
s011period 4.810.0242
s011period 5.710.0457
s011period 6.80.1892
s011period 8.080.2908
s011period 9.610.3396
s011period 11.40.1052
s011period 13.60.1583
s011period 16.20.0582
s011period 19.20.0476
s011period 22.90.0476
s011period 27.20.0400
s011period 32.30.0253
s011period 38.40.0406
s011period 45.70.0176
s011period 54.40.0266
s011period 64.60.0051
s011period 76.90.0152
s012period 2.86 → 5.710.0163
s012period 2.86 → 11.40.0773
s012period 2.86 → 22.90.1905
s012period 2.86 → 45.70.1491
s012period 3.4 → 5.710.0179
s012period 3.4 → 11.40.0783
s012period 3.4 → 22.90.1493
s012period 3.4 → 45.70.2774
s012period 4.04 → 5.710.0115
s012period 4.04 → 11.40.0564
s012period 4.04 → 22.90.1719
s012period 4.04 → 45.70.1487
s012period 4.81 → 5.710.0054
s012period 4.81 → 11.40.0256
s012period 4.81 → 22.90.1192
s012period 4.81 → 45.70.2561
s012period 5.71 → 11.40.0454
s012period 5.71 → 22.90.1422
s012period 5.71 → 45.70.2505

First 40 of 50 rows.

Leave-one-out 1-nearest-neighbor probe

FeaturesNumberAccuracy
Order 0–12187.5%
Order 0–26191.7%
Always the most common class050.0%
  • Coefficients average over the whole series, so a circular shift of the series leaves them unchanged (exactly, with periodic padding); first-order coefficients are like a spectrum on a log-frequency scale, second-order ones capture modulations within each band.
  • Morlet wavelets centered at 0.35·2^(−λ/Q) cycles per step with neighbors crossing at half power; the series is extended by its mirror image before filtering (fewer edge effects).
  • Second-order coefficients are divided by their first-order parent, so they measure modulation independent of the band's energy.
  • The probe standardizes log coefficients using the other series only, then predicts each series' class from its nearest neighbor: a quick check of how much class information the features carry, not a tuned classifier.
The exact R script · R R version 4.5.1 (2025-06-13)
# Wavelet scattering (shift-stable signal features)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.scattering 1.0.0 · spec a2cffb0010cc7e6e
# Dataset: seq_signals (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/seq_signals.parquet", col_select = c("x", "series", "step", "class")))
n_input <- nrow(df)
df[["series"]] <- factor(df[["series"]], levels = c("s01", "s02", "s03", "s04", "s05", "s06", "s07", "s08", "s09", "s10", "s11", "s12", "s13", "s14", "s15", "s16", "s17", "s18", "s19", "s20", "s21", "s22", "s23", "s24"))  # stored level order
df[["class"]] <- factor(df[["class"]], levels = c("fast", "slow"))  # stored level order
df <- df[stats::complete.cases(df[c("x", "series", "step", "class")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("x", "series", "step", "class"))  # infinite values stop the run (registry/errors.yaml)

# %% Signals
# One-dimensional wavelet scattering (Mallat 2012; Andén & Mallat 2014): Morlet filter banks, modulus and a
# global average, giving shift-stable features per signal; an optional leave-one-out 1-nearest-neighbor probe.
VALUE <- "x"
SERIES <- "series"
TIME <- "step"
LABEL <- "class"
TEMPORAL <- FALSE
OCTAVES <- as.integer(0)
QPO <- as.integer(4)
ORDER <- as.integer(2)
NORMALIZE <- TRUE
PAD <- "reflect"
d <- df
if (!is.null(SERIES) && !is.null(TIME)) {
  d <- d[order(as.integer(d[[SERIES]]), d[[TIME]], method = "radix"), , drop = FALSE]
} else if (!is.null(SERIES)) {
  d <- d[order(as.integer(d[[SERIES]]), method = "radix"), , drop = FALSE]
} else if (!is.null(TIME)) {
  d <- d[order(d[[TIME]], method = "radix"), , drop = FALSE]
}
rownames(d) <- NULL
x_all <- as.numeric(d[[VALUE]])
cs_check_rows(nrow(d), 16, "A scattering transform")
cs_check_not_constant(x_all, VALUE)
names_ <- if (!is.null(SERIES)) as.character(levels(d[[SERIES]])) else VALUE
ids <- if (!is.null(SERIES)) as.integer(d[[SERIES]]) else rep(1L, nrow(d))
signals <- lapply(seq_along(names_), function(i) x_all[ids == i])
lengths_ <- vapply(signals, length, integer(1))
if (min(lengths_) < 16) {
  cs_error("CS_E_UNDEFINED", what = "The scattering transform",
           reason = sprintf("series %s has %d values (at least 16 are needed)", names_[which.min(lengths_)], min(lengths_)))
}
J_max <- floor(log2(min(lengths_))) - 1
J <- if (OCTAVES > 0) OCTAVES else max(1, min(J_max - 1, 10))
if (J > J_max) cs_error("CS_E_INVALID_OPTION", option = "Octaves", allowed = sprintf("at most %d for series of %d values", J_max, min(lengths_)), value = as.character(J))
labels_by_series <- NULL
if (!is.null(LABEL)) {
  bad <- 0
  labels_by_series <- character(length(names_))
  for (i in seq_along(names_)) {
    lv <- unique(as.character(d[[LABEL]][ids == i]))
    bad <- bad + as.integer(length(lv) > 1)
    labels_by_series[i] <- lv[1]
  }
  if (bad > 0) cs_error("CS_E_INVALID_VALUES", column = LABEL, requirement = "the same within each series", count = bad)
}
if (max(lengths_) > 2 * min(lengths_))
  warnings <- c(warnings, sprintf("Series lengths run from %d to %d values; averaged coefficients are comparable, but long series average out more.", min(lengths_), max(lengths_)))

# %% Transform
res <- lapply(signals, function(s) cs_scat_transform(s, J, QPO, ORDER, PAD))
b1 <- cs_scat_bank(J, QPO)
b2 <- cs_scat_bank(J, 1)
paths <- res[[1]]$paths
n1 <- length(b1)
n2 <- length(paths)
features <- function(r, with2) {
  s2 <- r$s2
  if (NORMALIZE && length(s2)) {
    par <- vapply(r$paths, function(p) r$s1[p[1]], numeric(1))
    s2 <- ifelse(par > 0, s2 / ifelse(par > 0, par, 1), 0)
  }
  c(r$s0, r$s1, if (with2) s2 else numeric(0))
}
F <- do.call(rbind, lapply(res, features, with2 = TRUE))
values <- list(n_series = length(signals), min_length = min(lengths_), max_length = max(lengths_), octaves = J, q = QPO, order = ORDER,
               n_paths1 = n1, n_paths2 = n2, n_features = ncol(F), s0 = res[[1]]$s0)
for (lam in seq_len(n1)) values[[sprintf("s1[%d]", lam)]] <- res[[1]]$s1[lam]
if (n2 > 0) values$s2_check <- sum(seq_len(n2) * F[1, (1 + n1 + 1):(1 + n1 + n2)])
values$feature_check <- sum(outer(seq_len(nrow(F)), seq_len(ncol(F))) * F)

# %% Probe
probe_rows <- list()
if (!is.null(labels_by_series)) {
  classes <- sort(unique(labels_by_series))
  if (length(signals) >= 4 && length(classes) >= 2) {
    eps <- 1e-12 * max(max(F[, 2:(1 + n1)]), 1e-300)
    logf <- function(M) {
      M[, -1] <- log(M[, -1, drop = FALSE] + eps)
      M
    }
    F1 <- logf(do.call(rbind, lapply(res, features, with2 = FALSE)))
    acc1 <- cs_scat_probe(F1, labels_by_series)
    chance <- max(vapply(classes, function(cl) sum(labels_by_series == cl), numeric(1))) / length(labels_by_series)
    values$probe_acc_order1 <- acc1
    values$probe_chance <- chance
    probe_rows[[1]] <- list(features = "Order 0–1", n = ncol(F1), accuracy = acc1)
    if (ORDER >= 2 && n2 > 0) {
      acc2 <- cs_scat_probe(logf(F), labels_by_series)
      values$probe_acc_all <- acc2
      probe_rows[[length(probe_rows) + 1]] <- list(features = "Order 0–2", n = ncol(F), accuracy = acc2)
    }
    probe_rows[[length(probe_rows) + 1]] <- list(features = "Always the most common class", n = 0, accuracy = chance)
  } else {
    warnings <- c(warnings, "The probe needs at least 4 series and 2 classes; it was skipped.")
  }
}

# %% Charts
period <- function(xi) sprintf("%.3g", 1 / xi)
charts <- list()
r0 <- res[[1]]
T0 <- r0$T
nb <- min(T0, 64)
binid <- (0:(T0 - 1) * nb) %/% T0
tl <- if (!is.null(TIME)) cs_ts_time_labels(d[[TIME]][ids == 1], TEMPORAL) else seq_len(T0)
bin_label <- vapply(0:(nb - 1), function(b) as.character(tl[which(binid == b)[1]]), "")
rows_ <- character(0)
cols_ <- character(0)
vals_ <- numeric(0)
for (lam in seq_len(n1)) {
  u <- r0$U1[[lam]][seq_len(T0)]
  for (b in 0:(nb - 1)) {
    rows_ <- c(rows_, paste("period", period(b1[[lam]]$xi)))
    cols_ <- c(cols_, bin_label[b + 1])
    vals_ <- c(vals_, mean(u[binid == b]))
  }
}
charts[[1]] <- cs_chart("scalogram", "matrix-heatmap", sprintf("Wavelet modulus over time: %s", names_[1]), list(
  row = cs_col("wavelet", rows_, kind = "categorical"), col = cs_col(if (is.null(TIME)) "step" else TIME, cols_, kind = "categorical"),
  value = cs_col("|x ⋆ ψ|", vals_)))
shown <- min(length(signals), 12)
xi1 <- vapply(b1, function(b) b$xi, numeric(1))
charts[[2]] <- cs_chart("spectrum", "series-line", "First-order coefficients by wavelet period", list(
  x = cs_col("period (steps)", rep(1 / xi1, shown)),
  y = cs_col("S1", unlist(lapply(seq_len(shown), function(i) res[[i]]$s1))),
  group = cs_col(if (is.null(SERIES)) "series" else SERIES, rep(names_[seq_len(shown)], each = n1), kind = "categorical")))
if (n2 > 0) {
  s2_0 <- F[1, (1 + n1 + 1):(1 + n1 + n2)]
  charts[[3]] <- cs_chart("second", "matrix-heatmap",
    sprintf("Second-order coefficients%s: %s", if (NORMALIZE) " (relative to first order)" else "", names_[1]), list(
      row = cs_col("first wavelet", vapply(paths, function(p) paste("period", period(b1[[p[1]]]$xi)), ""), kind = "categorical"),
      col = cs_col("second wavelet", vapply(paths, function(p) paste("period", period(b2[[p[2]]]$xi)), ""), kind = "categorical"),
      value = cs_col("S2", s2_0)))
}

# %% Tables
filter_rows <- lapply(seq_len(n1), function(lam) list(order = 1, wavelet = lam, xi = b1[[lam]]$xi, period = 1 / b1[[lam]]$xi, sigma = b1[[lam]]$sigma))
if (ORDER >= 2) filter_rows <- c(filter_rows, lapply(seq_along(b2), function(j) list(order = 2, wavelet = j, xi = b2[[j]]$xi, period = 1 / b2[[j]]$xi, sigma = b2[[j]]$sigma)))
coef_rows <- list()
for (i in seq_along(signals)) {
  coef_rows[[length(coef_rows) + 1]] <- list(series = names_[i], order = 0, path = "mean", value = F[i, 1])
  for (lam in seq_len(n1)) coef_rows[[length(coef_rows) + 1]] <- list(series = names_[i], order = 1, path = paste("period", period(b1[[lam]]$xi)), value = F[i, 1 + lam])
  for (p in seq_len(n2)) {
    ab <- paths[[p]]
    coef_rows[[length(coef_rows) + 1]] <- list(series = names_[i], order = 2, path = sprintf("period %s → %s", period(b1[[ab[1]]]$xi), period(b2[[ab[2]]]$xi)),
                                               value = F[i, 1 + n1 + p])
  }
}
CAP <- 5000
tables <- list(
  list(key = "filters", title = "Wavelets",
       columns = list(list(key = "order", label = "Order", type = "integer"), list(key = "wavelet", label = "Wavelet", type = "integer"),
                      list(key = "xi", label = "Center frequency (cycles per step)", type = "number"),
                      list(key = "period", label = "Period (steps)", type = "number"), list(key = "sigma", label = "Bandwidth σ", type = "number")),
       rows = filter_rows),
  list(key = "coefficients", title = paste0("Scattering coefficients", if (length(coef_rows) > CAP) sprintf(" (first %d of %d)", CAP, length(coef_rows)) else ""),
       columns = list(list(key = "series", label = if (is.null(SERIES)) "Series" else SERIES, type = "string"), list(key = "order", label = "Order", type = "integer"),
                      list(key = "path", label = "Path", type = "string"), list(key = "value", label = "Coefficient", type = "number")),
       rows = utils::head(coef_rows, CAP)))
if (length(probe_rows)) {
  tables[[3]] <- list(key = "probe", title = "Leave-one-out 1-nearest-neighbor probe",
                      columns = list(list(key = "features", label = "Features", type = "string"), list(key = "n", label = "Number", type = "integer"),
                                     list(key = "accuracy", label = "Accuracy", type = "percent")),
                      rows = probe_rows)
}

# %% Result
summary <- sprintf("Scattering transform of %d series of %s (%d%s values): %d first-order and %d second-order coefficients per series over %d octave%s (%d wavelets per octave).",
                   length(signals), VALUE, min(lengths_), if (max(lengths_) != min(lengths_)) sprintf("–%d", max(lengths_)) else "", n1, n2, J, if (J != 1) "s" else "", QPO)
if (!is.null(values$probe_acc_order1)) {
  summary <- paste0(summary, sprintf(" A leave-one-out nearest-neighbor probe on %s is %.0f%% accurate with order 0–1", LABEL, 100 * values$probe_acc_order1),
                    if (!is.null(values$probe_acc_all)) sprintf(" and %.0f%% with order 0–2", 100 * values$probe_acc_all) else "",
                    sprintf(" (always guessing the most common class: %.0f%%).", 100 * values$probe_chance))
}
notes <- c(paste0("Coefficients average over the whole series, so a circular shift of the series leaves them unchanged (exactly, with periodic padding); ",
                  "first-order coefficients are like a spectrum on a log-frequency scale, second-order ones capture modulations within each band."),
           paste0("Morlet wavelets centered at 0.35·2^(−λ/Q) cycles per step with neighbors crossing at half power; ",
                  if (PAD == "reflect") "the series is extended by its mirror image before filtering (fewer edge effects)." else "convolutions wrap around the ends (periodic)."))
if (NORMALIZE && ORDER >= 2) notes <- c(notes, "Second-order coefficients are divided by their first-order parent, so they measure modulation independent of the band's energy.")
if (length(probe_rows)) notes <- c(notes, paste0("The probe standardizes log coefficients using the other series only, then predicts each series' class from its nearest neighbor: ",
                                                 "a quick check of how much class information the features carry, not a tuned classifier."))
cs_publish(list(
  method = "ts.scattering",
  methodVersion = "1.0.0",
  title = "Wavelet scattering",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = nrow(d),
  summary = summary,
  statistics = c(list(list(key = "n_features", label = "Coefficients per series", value = ncol(F))),
                 if (!is.null(values$probe_acc_order1)) list(list(key = "probe_acc_order1", label = "Probe accuracy (order 0–1)", value = values$probe_acc_order1)) else list()),
  tables = tables,
  assumptions = list(list(key = "stationary_bands", label = "Features suit the task", status = "info",
                          detail = "Assumed, not checked from the data: averaging over the whole series removes timing; use it when where something happens matters less than what happens.")),
  warnings = warnings,
  notes = notes,
  charts = charts,
  values = values
))
Python

Scattering transform of 24 series of x (128 values): 20 first-order and 40 second-order coefficients per series over 5 octaves (4 wavelets per octave). A leave-one-out nearest-neighbor probe on class is 88% accurate with order 0–1 and 92% with order 0–2 (always guessing the most common class: 50%).

Coefficients per series
61
Probe accuracy (order 0–1)
0.8750

Assumptions

  • Features suit the task — Assumed, not checked from the data: averaging over the whole series removes timing; use it when where something happens matters less than what happens.

Wavelets

OrderWaveletCenter frequency (cycles per step)Period (steps)Bandwidth σ
110.35002.8570.0334
120.29433.3980.0281
130.24754.0410.0236
140.20814.8050.0199
150.17505.7140.0167
160.14726.7950.0141
170.12378.0810.0118
180.10419.6100.0099
190.087511.4290.0084
1100.073613.5910.0070
1110.061916.1620.0059
1120.052019.2200.0050
1130.043722.8570.0042
1140.036827.1820.0035
1150.030932.3250.0030
1160.026038.4410.0025
1170.021945.7140.0021
1180.018454.3640.0018
1190.015564.6500.0015
1200.013076.8820.0012
210.35002.8570.1051
220.17505.7140.0525
230.087511.4290.0263
240.043722.8570.0131
250.021945.7140.0066

Scattering coefficients

seriesOrderPathCoefficient
s010mean0.0135
s011period 2.860.0177
s011period 3.40.0189
s011period 4.040.0216
s011period 4.810.0242
s011period 5.710.0457
s011period 6.80.1892
s011period 8.080.2908
s011period 9.610.3396
s011period 11.40.1052
s011period 13.60.1583
s011period 16.20.0582
s011period 19.20.0476
s011period 22.90.0476
s011period 27.20.0400
s011period 32.30.0253
s011period 38.40.0406
s011period 45.70.0176
s011period 54.40.0266
s011period 64.60.0051
s011period 76.90.0152
s012period 2.86 → 5.710.0163
s012period 2.86 → 11.40.0773
s012period 2.86 → 22.90.1905
s012period 2.86 → 45.70.1491
s012period 3.4 → 5.710.0179
s012period 3.4 → 11.40.0783
s012period 3.4 → 22.90.1493
s012period 3.4 → 45.70.2774
s012period 4.04 → 5.710.0115
s012period 4.04 → 11.40.0564
s012period 4.04 → 22.90.1719
s012period 4.04 → 45.70.1487
s012period 4.81 → 5.710.0054
s012period 4.81 → 11.40.0256
s012period 4.81 → 22.90.1192
s012period 4.81 → 45.70.2561
s012period 5.71 → 11.40.0454
s012period 5.71 → 22.90.1422
s012period 5.71 → 45.70.2505

First 40 of 50 rows.

Leave-one-out 1-nearest-neighbor probe

FeaturesNumberAccuracy
Order 0–12187.5%
Order 0–26191.7%
Always the most common class050.0%
  • Coefficients average over the whole series, so a circular shift of the series leaves them unchanged (exactly, with periodic padding); first-order coefficients are like a spectrum on a log-frequency scale, second-order ones capture modulations within each band.
  • Morlet wavelets centered at 0.35·2^(−λ/Q) cycles per step with neighbors crossing at half power; the series is extended by its mirror image before filtering (fewer edge effects).
  • Second-order coefficients are divided by their first-order parent, so they measure modulation independent of the band's energy.
  • The probe standardizes log coefficients using the other series only, then predicts each series' class from its nearest neighbor: a quick check of how much class information the features carry, not a tuned classifier.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Wavelet scattering (shift-stable signal features)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.scattering 1.0.0 · spec a2cffb0010cc7e6e
# Dataset: seq_signals (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import math

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import scattering as sc, ts

# %% Data
df = pd.read_parquet("tests/parity/fixtures/seq_signals.parquet", columns=["x", "series", "step", "class"])
n_input = len(df)
df["series"] = pd.Categorical(df["series"], categories=["s01", "s02", "s03", "s04", "s05", "s06", "s07", "s08", "s09", "s10", "s11", "s12", "s13", "s14", "s15", "s16", "s17", "s18", "s19", "s20", "s21", "s22", "s23", "s24"])  # stored level order
df["class"] = pd.Categorical(df["class"], categories=["fast", "slow"])  # stored level order
df = df.dropna(subset=["x", "series", "step", "class"])  # listwise deletion over the analysis columns
df["series"] = df["series"].cat.remove_unused_categories()
df["class"] = df["class"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["x", "series", "step", "class"])  # infinite values stop the run (registry/errors.yaml)

# %% Signals
# One-dimensional wavelet scattering (Mallat 2012; Andén & Mallat 2014): Morlet filter banks, modulus and a
# global average, giving shift-stable features per signal; an optional leave-one-out 1-nearest-neighbor probe.
VALUE = "x"
SERIES = "series"
TIME = "step"
LABEL = "class"
TEMPORAL = False
OCTAVES = int(0)
QPO = int(4)
ORDER = int(2)
NORMALIZE = True
PAD = "reflect"
keys = ([SERIES] if SERIES else []) + ([TIME] if TIME else [])
d = df.sort_values(keys, kind="mergesort").reset_index(drop=True) if keys else df.reset_index(drop=True)
x_all = d[VALUE].to_numpy(dtype=float)
cs.check_rows(len(d), 16, "A scattering transform")
check_not_constant(x_all, VALUE)
names = [str(v) for v in d[SERIES].cat.categories] if SERIES else [VALUE]
ids = d[SERIES].cat.codes.to_numpy() if SERIES else np.zeros(len(d), dtype=np.int64)
signals = [x_all[ids == i] for i in range(len(names))]
lengths = [len(s) for s in signals]
if min(lengths) < 16:
    short = names[int(np.argmin(lengths))]
    cs.cs_error("CS_E_UNDEFINED", what="The scattering transform", reason=f"series {short} has {min(lengths)} values (at least 16 are needed)")
J_max = int(math.floor(math.log2(min(lengths)))) - 1
J = OCTAVES if OCTAVES > 0 else max(1, min(J_max - 1, 10))
if J > J_max:
    cs.cs_error("CS_E_INVALID_OPTION", option="Octaves", allowed=f"at most {J_max} for series of {min(lengths)} values", value=str(J))
labels_by_series = None
if LABEL:
    labels_by_series = []
    bad = 0
    for i in range(len(names)):
        lv = d[LABEL][ids == i].astype(str).unique()
        bad += int(len(lv) > 1)
        labels_by_series.append(str(lv[0]))
    if bad:
        cs.cs_error("CS_E_INVALID_VALUES", column=LABEL, requirement="the same within each series", count=bad)
if max(lengths) > 2 * min(lengths):
    warnings.append(f"Series lengths run from {min(lengths)} to {max(lengths)} values; averaged coefficients are comparable, but long series average out more.")

# %% Transform
res = [sc.transform(s, J, QPO, ORDER, PAD) for s in signals]
b1 = sc.bank(J, QPO)
b2 = sc.bank(J, 1)
paths = res[0]["paths"]
n1, n2 = len(b1), len(paths)


def features(r: dict, with2: bool) -> np.ndarray:
    s2 = r["s2"].copy()
    if NORMALIZE and len(s2):
        par = np.array([r["s1"][i] for i, _ in r["paths"]])
        s2 = np.where(par > 0, s2 / np.where(par > 0, par, 1.0), 0.0)
    return np.concatenate([[r["s0"]], r["s1"], s2 if with2 else []])


F = np.vstack([features(r, True) for r in res])
values = {"n_series": len(signals), "min_length": min(lengths), "max_length": max(lengths), "octaves": J, "q": QPO, "order": ORDER,
          "n_paths1": n1, "n_paths2": n2, "n_features": F.shape[1], "s0": res[0]["s0"]}
for lam in range(n1):
    values[f"s1[{lam + 1}]"] = float(res[0]["s1"][lam])
if n2:
    values["s2_check"] = float(np.sum(np.arange(1, n2 + 1) * F[0, 1 + n1:]))
values["feature_check"] = float(np.sum(np.arange(1, F.shape[0] + 1)[:, None] * np.arange(1, F.shape[1] + 1)[None, :] * F))

# %% Probe
probe_rows = []
if labels_by_series is not None:
    classes = sorted(set(labels_by_series))
    if len(signals) >= 4 and len(classes) >= 2:
        eps = 1e-12 * max(float(np.max(F[:, 1:1 + n1])), 1e-300)

        def logf(M: np.ndarray) -> np.ndarray:
            out = M.copy()
            out[:, 1:] = np.log(out[:, 1:] + eps)
            return out

        F1 = logf(np.vstack([features(r, False) for r in res]))
        acc1 = sc.probe(F1, labels_by_series)
        chance = max(labels_by_series.count(c) for c in classes) / len(labels_by_series)
        values.update({"probe_acc_order1": acc1, "probe_chance": chance})
        probe_rows.append({"features": "Order 0–1", "n": F1.shape[1], "accuracy": acc1})
        if ORDER >= 2 and n2:
            acc2 = sc.probe(logf(F), labels_by_series)
            values["probe_acc_all"] = acc2
            probe_rows.append({"features": "Order 0–2", "n": F.shape[1], "accuracy": acc2})
        probe_rows.append({"features": "Always the most common class", "n": 0, "accuracy": chance})
    else:
        warnings.append("The probe needs at least 4 series and 2 classes; it was skipped.")

# %% Charts
def period(xi: float) -> str:
    return "%.3g" % (1.0 / xi)


charts = []
r0 = res[0]
T0 = r0["T"]
nb = min(T0, 64)
binid = (np.arange(T0) * nb) // T0
tl = ts.time_labels(d[TIME].to_numpy()[ids == 0], TEMPORAL) if TIME else list(range(1, T0 + 1))
bin_label = [str(tl[int(np.argmax(binid == b))]) for b in range(nb)]
rows_, cols_, vals_ = [], [], []
for lam in range(n1):
    u = r0["U1"][lam][:T0]
    for b in range(nb):
        rows_.append(f"period {period(b1[lam]['xi'])}")
        cols_.append(bin_label[b])
        vals_.append(float(np.mean(u[binid == b])))
charts.append(cs.chart("scalogram", "matrix-heatmap", f"Wavelet modulus over time: {names[0]}", {
    "row": cs.col("wavelet", rows_, kind="categorical"), "col": cs.col(TIME or "step", cols_, kind="categorical"),
    "value": cs.col("|x ⋆ ψ|", np.array(vals_))}))
shown = min(len(signals), 12)
charts.append(cs.chart("spectrum", "series-line", "First-order coefficients by wavelet period", {
    "x": cs.col("period (steps)", [1.0 / b1[lam]["xi"] for _ in range(shown) for lam in range(n1)]),
    "y": cs.col("S1", np.concatenate([res[i]["s1"] for i in range(shown)])),
    "group": cs.col(SERIES or "series", [names[i] for i in range(shown) for _ in range(n1)], kind="categorical")}))
if n2:
    s2_0 = F[0, 1 + n1:]
    charts.append(cs.chart("second", "matrix-heatmap", f"Second-order coefficients{' (relative to first order)' if NORMALIZE else ''}: {names[0]}", {
        "row": cs.col("first wavelet", [f"period {period(b1[i]['xi'])}" for i, _ in paths], kind="categorical"),
        "col": cs.col("second wavelet", [f"period {period(b2[j]['xi'])}" for _, j in paths], kind="categorical"),
        "value": cs.col("S2", s2_0)}))

# %% Tables
filter_rows = [{"order": 1, "wavelet": lam + 1, "xi": b1[lam]["xi"], "period": 1.0 / b1[lam]["xi"], "sigma": b1[lam]["sigma"]} for lam in range(n1)]
if ORDER >= 2:
    filter_rows += [{"order": 2, "wavelet": j + 1, "xi": b2[j]["xi"], "period": 1.0 / b2[j]["xi"], "sigma": b2[j]["sigma"]} for j in range(len(b2))]
coef_rows = []
for i in range(len(signals)):
    coef_rows.append({"series": names[i], "order": 0, "path": "mean", "value": float(F[i, 0])})
    for lam in range(n1):
        coef_rows.append({"series": names[i], "order": 1, "path": f"period {period(b1[lam]['xi'])}", "value": float(F[i, 1 + lam])})
    for p, (a, b) in enumerate(paths):
        coef_rows.append({"series": names[i], "order": 2, "path": f"period {period(b1[a]['xi'])} → {period(b2[b]['xi'])}", "value": float(F[i, 1 + n1 + p])})
CAP = 5000
tables = [{"key": "filters", "title": "Wavelets",
           "columns": [{"key": "order", "label": "Order", "type": "integer"}, {"key": "wavelet", "label": "Wavelet", "type": "integer"},
                       {"key": "xi", "label": "Center frequency (cycles per step)", "type": "number"},
                       {"key": "period", "label": "Period (steps)", "type": "number"}, {"key": "sigma", "label": "Bandwidth σ", "type": "number"}],
           "rows": filter_rows},
          {"key": "coefficients", "title": "Scattering coefficients" + (f" (first {CAP} of {len(coef_rows)})" if len(coef_rows) > CAP else ""),
           "columns": [{"key": "series", "label": SERIES or "Series", "type": "string"}, {"key": "order", "label": "Order", "type": "integer"},
                       {"key": "path", "label": "Path", "type": "string"}, {"key": "value", "label": "Coefficient", "type": "number"}],
           "rows": coef_rows[:CAP]}]
if probe_rows:
    tables.append({"key": "probe", "title": "Leave-one-out 1-nearest-neighbor probe",
                   "columns": [{"key": "features", "label": "Features", "type": "string"}, {"key": "n", "label": "Number", "type": "integer"},
                               {"key": "accuracy", "label": "Accuracy", "type": "percent"}],
                   "rows": probe_rows})

# %% Result
summary = (f"Scattering transform of {len(signals)} series of {VALUE} ({min(lengths)}" + (f"–{max(lengths)}" if max(lengths) != min(lengths) else "")
           + f" values): {n1} first-order and {n2} second-order coefficients per series over {J} octave{'s' if J != 1 else ''} ({QPO} wavelets per octave).")
if "probe_acc_order1" in values:
    summary += (f" A leave-one-out nearest-neighbor probe on {LABEL} is {values['probe_acc_order1']:.0%} accurate with order 0–1"
                + (f" and {values['probe_acc_all']:.0%} with order 0–2" if "probe_acc_all" in values else "")
                + f" (always guessing the most common class: {values['probe_chance']:.0%}).")
notes = ["Coefficients average over the whole series, so a circular shift of the series leaves them unchanged (exactly, with periodic padding); "
         "first-order coefficients are like a spectrum on a log-frequency scale, second-order ones capture modulations within each band.",
         "Morlet wavelets centered at 0.35·2^(−λ/Q) cycles per step with neighbors crossing at half power; "
         + ("the series is extended by its mirror image before filtering (fewer edge effects)." if PAD == "reflect" else "convolutions wrap around the ends (periodic).")]
if NORMALIZE and ORDER >= 2:
    notes.append("Second-order coefficients are divided by their first-order parent, so they measure modulation independent of the band's energy.")
if probe_rows:
    notes.append("The probe standardizes log coefficients using the other series only, then predicts each series' class from its nearest neighbor: "
                 "a quick check of how much class information the features carry, not a tuned classifier.")
cs.publish({
    "method": "ts.scattering",
    "methodVersion": "1.0.0",
    "title": "Wavelet scattering",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": len(d),
    "summary": summary,
    "statistics": [{"key": "n_features", "label": "Coefficients per series", "value": F.shape[1]}]
                  + ([{"key": "probe_acc_order1", "label": "Probe accuracy (order 0–1)", "value": values["probe_acc_order1"]}] if "probe_acc_order1" in values else []),
    "tables": tables,
    "assumptions": [{"key": "stationary_bands", "label": "Features suit the task", "status": "info",
                     "detail": "Assumed, not checked from the data: averaging over the whole series removes timing; use it when where something happens matters less than what happens."}],
    "warnings": warnings,
    "notes": notes,
    "charts": charts,
    "values": values,
})

Shortened for the Academy: 3 chart(s) dropped to stay under 100 KB; a table cut from 1464 to 50 rows; 3 chart(s) dropped to stay under 100 KB; a table cut from 1464 to 50 rows.

Each of 24 signals became 61 coefficients. A nearest-neighbor probe that hides each signal's class guesses it with 88% accuracy from first-order paths and 92% with second-order paths added, against 50% for the most common class.

With 24 signals, a few correct guesses move these numbers a lot. Fixed filters are also less adaptive than learned features when data are plentiful.

04

Roles in a network

Read

DeepWalk and node2vec with q>1q > 1 put nodes close when they are near each other. A structural roleStructural roleA node's position in the network's pattern, such as hub, bridge or leaf, regardless of which part of the network it sits in. is different: two hubs, two bridges or two leaves should match wherever they are.

Role vectors answer questions like "which accounts behave like this known fraud ring's coordinator?", where the matches sit in other parts of the network.

05

GraphWave: how heat spreads

Read

GraphWaveGraphWaveA node's structural signature from how heat spreads out of it over the network, so nodes in the same role match even when far apart. places a unit of heat on node ii and lets it diffuse for time ss with the heat kernel Ψs=Ue−sΛU⊤\Psi_s = U e^{-s\Lambda} U^\top of the graph Laplacian. Column ii of Ψs\Psi_s says how the heat spread out over every node.

It then summarizes that spread as a distribution, ignoring which nodes got the heat, through its characteristic function φi(t)=1n∑je i t Ψs[j,i]\varphi_i(t) = \frac1n \sum_j e^{\,\mathrm{i}\, t\, \Psi_s[j, i]} sampled at a few tt. Nodes whose heat spreads the same way get the same signature, wherever they are. The scale ss decides how large a neighborhood counts.

06

struc2vec: compare degree sequences

Read

struc2vecstruc2vecNode vectors from walks on a graph of structural similarity, built by comparing degree sequences at growing distances from each node. compares nodes by the sorted degrees of their neighbors at distance 1, 2, 3, …, using dynamic time warping so sequences of different lengths can be matched. It builds a multi-layer graph in which structurally similar nodes are linked, walks on that graph, and trains skip-gram vectors, as DeepWalk does.

Matching degree sequences (1,2,3)(1, 2, 3) against (1,2,2,3)(1, 2, 2, 3) costs 0 in the reference's example: warping absorbs the repeated degree. Exact construction is expensive, and different structures can share the same degree profiles.

07

Readiness

Read
  • Wavelet scattering (REP058) runs in CodeSplash for one-dimensional signals: Wavelet scattering. Two-dimensional image scattering isn't built.
  • GraphWave (REP059) runs as a notebook (its reference program) and struc2vec (REP060) is explained here. CodeSplash now loads networks, and its node embeddings cover proximity, not roles; the badge shows each entry's current label.
Reference · REP059 · Runs as a notebookGraphWaveLearn structural-role embeddings from graph wavelet diffusion patterns, so nodes in similar structural positions can resemble one another even when far apart. Reference · REP060 · Explained herestruc2vecRepresent structural identity through a hierarchy of structural similarities, separating node roles from simple geographic proximity in a graph.
08

Check: roles and signals

Checkpoint

Check yourself

Why do scattering coefficients barely change when a signal shifts slightly in time?

Show the answer

Answer: a

Averaging over a window makes the output depend on what happened, not exactly when.

Check yourself

What do second-order scattering paths capture that first-order paths miss?

Show the answer

Answer: a

First order measures average energy per scale, like a spectrum. Second order measures the variation of that energy, which a spectrum averages away.

Check yourself

Two nodes sit in distant parts of a network, but both are the center of a star of five leaves. What does GraphWave give them?

Show the answer

Answer: a

GraphWave summarizes the distribution of heat, not which nodes receive it, so position in the network drops out.

Check yourself

What does GraphWave's diffusion time ss control?

Show the answer

Answer: a

Small ss compares immediate surroundings; large ss compares wider patterns. Different scales can conflate or separate roles.

Check yourself

Why does struc2vec compare degree sequences with dynamic time warping?

Show the answer

Answer: a

Warping aligns similar parts of two sorted sequences even when one has extra entries.

Check yourself

How do struc2vec's walks differ from DeepWalk's?

Show the answer

Answer: a

Building the walk graph from structural distances is what makes the final skip-gram vectors encode roles.

09

Recap

Recap
  • Scattering cascades fixed wavelets, moduli and averages: stable to shifts, with second order keeping rhythm.
  • Role vectors match nodes by what their surroundings look like, not where they are.
  • GraphWave summarizes heat diffusion; struc2vec walks a structural-similarity graph. Scattering runs; GraphWave runs as a notebook and struc2vec is explained here.

Concepts in this lesson