Skip to content

DTime series · ts.scattering

Wavelet scattering (shift-stable signal features)

What fixed, shift-stable features describe each signal — and do they tell known classes apart?

Computes the wavelet scattering transform of one or many signals: Morlet wavelet filters, a modulus and an average over the whole signal give first-order coefficients (energy per frequency band, on a log-frequency scale) and second-order coefficients (how each band's amplitude is modulated). The features don't move when a signal is shifted in time and need no training, so they suit sensors, vibration, audio-like and other signal data with few examples. With a class column, a leave-one-out nearest-neighbor probe shows how much class information the first- and second-order features carry.

Verified in Python and R Python and R agree to 10 decimals Also called scattering transform, wavelet scattering, scattering network…

A real result

Example “Signals probe”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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.
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.

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.

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Signals probeseq_signals · label: class · series: series · time: step · value: x
  • Signals periodic order1seq_signals · series: series · time: step · value: x
  • Signals unnormalizedseq_signals · label: class · series: series · value: x
  • Nile one seriesml_nile · time: year · value: flow
  • Degenerate constantseq_signals · series: series · time: step · value: x
  • Degenerate n3seq_signals · series: series · time: step · value: x
  • Degenerate infseq_signals · series: series · time: step · value: x
  • Degenerate huge cardinalityseq_signals · series: series · time: step · value: x

In the guides

Where it sits in the decision guides

  • Sequences, curves and signals (hidden Markov models, functional PCA, scattering) · DS & ML Decision Guide · Discover — find structure without labels

What you need

Signalnumeric · 1 column
The measured values, one per step.
Series (optional)categorical · 0–1 column
Which signal each row belongs to, when there are several (one per recording, machine or trial).
Time (optional)temporal / numeric · 0–1 column
Orders the steps within each signal; omit to use the row order. Steps are taken as evenly spaced.
Class (optional)categorical · 0–1 column
A known class per signal (constant within each series); turns on the nearest-neighbor probe.

Choices you make

model

Octavesdefault 0

How many halvings of frequency the wavelets cover; 0 picks log₂(length) − 2 (at most log₂(length) − 1).

Wavelets per octave (first order)default 4

More wavelets per octave resolve frequency more finely (and give more features); second order always uses one.

Highest orderdefault 2

1 gives band energies only; 2 adds how each band's amplitude is modulated.

Second order relative to firstdefault on

Order 2 only: divide each second-order coefficient by its first-order parent, so it measures modulation regardless of the band's energy.

options

Signal endsdefault reflect

How the filters treat the start and end of each signal.

  • Mirror the signal(default) — Extends each signal by its mirror image: fewer edge effects for signals that don't repeat.
  • Wrap around — Treats each signal as periodic: coefficients are exactly unchanged by circular shifts.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Features suit the taskNot checked from data: state why it holds

    Averaging over the whole signal discards when things happen; the features fit tasks where what happens matters more than where.

What it reports

n_series
Fixed wavelet filters, a modulus and an average: features that don't move when a signal shifts and need no training.
min_length
Fixed wavelet filters, a modulus and an average: features that don't move when a signal shifts and need no training.
max_length
Fixed wavelet filters, a modulus and an average: features that don't move when a signal shifts and need no training.
octaves
A wave inside a Gaussian envelope: in frequency, a bump at its center frequency corrected to have zero mean.
q
A wave inside a Gaussian envelope: in frequency, a bump at its center frequency corrected to have zero mean.
order
Order 0 is the mean, order 1 the average wavelet modulus per band, order 2 how each band's amplitude is modulated.
n_paths1
Order 0 is the mean, order 1 the average wavelet modulus per band, order 2 how each band's amplitude is modulated.
n_paths2
Order 0 is the mean, order 1 the average wavelet modulus per band, order 2 how each band's amplitude is modulated.
n_features
Fixed wavelet filters, a modulus and an average: features that don't move when a signal shifts and need no training.
s0
One averaged value along one path of wavelets; S0 is the signal's mean.
feature_check
A weighted sum of all coefficients, used to confirm two runs produced the same features in the same order.

Per group, level or term: s1[<lambda>], s2_check, probe_acc_order1, probe_acc_all, probe_chance

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • Both engines run the same twins (codesplash.stats.scattering ↔ codesplashr R/stats_scattering.R): the same Morlet filters on the discrete frequency grid and circular FFT convolutions (numpy's pocketfft and R's fft agree to rounding).
  • Coefficients follow this filter bank (centers 0.35·2^(−λ/Q), half-power crossings, global averaging), not kymatio's padding and subsampling conventions, so they are not interchangeable with kymatio's numbers; tests/crosscheck/w5seq_scattering.py checks them against direct time-domain circular convolution.
Python

The exact script CodeSplash ran for example “Signals probe” · 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,
})
R

The exact script CodeSplash ran for example “Signals probe” · 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
))

Sources

  • Mallat, S. (2012). Group invariant scattering. Communications on Pure and Applied Mathematics, 65, 1331–1398.
  • Andén, J., & Mallat, S. (2014). Deep scattering spectrum. IEEE Transactions on Signal Processing, 62, 4114–4128.
  • Andreux, M., et al. (2020). Kymatio: Scattering transforms in Python. Journal of Machine Learning Research, 21(60), 1–6.

From the CodeSplash method registry · ts.scattering v1.0.0.