Curves and signals as data: functional PCA and wavelet scattering
When each observation is a whole curve or signal, functional PCA finds its main shapes and the scattering transform turns it into stable features for comparing and classifying.
What runs in CodeSplash
- Functional PCA (main shapes of a set of curves) Verified in Python and R
- Wavelet scattering (shift-stable signal features) Verified in Python and R
You will be able to
- Read a functional PCA component as the mean curve moved along its eigenfunction
- Explain why integrals over time make FPCA respect uneven time steps
- Describe first- and second-order scattering coefficients and why they don't move when a signal shifts
- Use a nearest-neighbor probe to judge how much class information features carry
Read first
A curve is one observation
ReadWeights of chicks measured every few days, a daily load profile, a spectrum: each curve is one observation, not many unrelated numbers. Ordinary PCA on the columns would ignore that the columns are ordered in time and unevenly spaced.
Functional PCAFunctional PCAPCA where each observation is a whole curve: a mean curve plus a few eigenfunctions, each curve a score on each. works with whole curves:
- A mean curve.
- A few eigenfunctionsEigenfunctionA curve φ(t) with ∫φ² dt = 1 along which the curves vary most; successive ones are orthogonal under the integral. φ(t), the directions in which curves differ most. Each has ∫φ² dt = 1.
- A score per curve on each eigenfunction: ∫(curve − mean)·φ dt.
Integrals use the trapezoid ruleTrapezoid ruleApproximates an integral by straight lines between grid points, so each point counts by the length of time around it., so a gap of 6 days counts three times as much as a gap of 2.
Chick growth curves
ReadFunctional PCA of 45 curves of weight on 12 time points: the first 3 components explain 99.5% of the variance between curves (component 1 alone 93.0%).
- Variance explained by 3 components
- 0.9947
- Mean integrated squared error
- 138.98
Plots
View data
| Component | Cumulative share | Share of variance |
|---|---|---|
| 1 | 0.9299 | 0.9299 |
| 2 | 0.9866 | 0.0567 |
| 3 | 0.9947 | 0.0081 |
| 4 | 0.9966 | 0.0019 |
| 5 | 0.9976 | 0.0011 |
| 6 | 0.9984 | 0.0008 |
| 7 | 0.9990 | 0.0006 |
| 8 | 0.9993 | 0.0003 |
| 9 | 0.9997 | 0.0003 |
| 10 | 0.9999 | 0.0002 |
View data
| curve | Time | weight |
|---|---|---|
| Mean | 0 | 41.067 |
| Mean | 2 | 49.578 |
| Mean | 4 | 60.156 |
| Mean | 6 | 74.867 |
| Mean | 8 | 92.422 |
| Mean | 10 | 110.09 |
| Mean | 12 | 132.78 |
| Mean | 14 | 146.24 |
| Mean | 16 | 169.53 |
| Mean | 18 | 192.42 |
| Mean | 20 | 211.60 |
| Mean | 21 | 218.69 |
| Mean + 2√λ·φ | 0 | 40.396 |
| Mean + 2√λ·φ | 2 | 50.713 |
| Mean + 2√λ·φ | 4 | 64.546 |
| Mean + 2√λ·φ | 6 | 85.943 |
| Mean + 2√λ·φ | 8 | 116.99 |
| Mean + 2√λ·φ | 10 | 148.36 |
| Mean + 2√λ·φ | 12 | 191.12 |
| Mean + 2√λ·φ | 14 | 218.17 |
| Mean + 2√λ·φ | 16 | 263.32 |
| Mean + 2√λ·φ | 18 | 307.03 |
| Mean + 2√λ·φ | 20 | 340.46 |
| Mean + 2√λ·φ | 21 | 355.73 |
| Mean − 2√λ·φ | 0 | 41.737 |
| Mean − 2√λ·φ | 2 | 48.442 |
| Mean − 2√λ·φ | 4 | 55.765 |
| Mean − 2√λ·φ | 6 | 63.791 |
| Mean − 2√λ·φ | 8 | 67.857 |
| Mean − 2√λ·φ | 10 | 71.822 |
| Mean − 2√λ·φ | 12 | 74.433 |
| Mean − 2√λ·φ | 14 | 74.319 |
| Mean − 2√λ·φ | 16 | 75.747 |
| Mean − 2√λ·φ | 18 | 77.819 |
| Mean − 2√λ·φ | 20 | 82.743 |
| Mean − 2√λ·φ | 21 | 81.648 |
View data
| curve | Time | weight |
|---|---|---|
| Mean | 0 | 41.067 |
| Mean | 2 | 49.578 |
| Mean | 4 | 60.156 |
| Mean | 6 | 74.867 |
| Mean | 8 | 92.422 |
| Mean | 10 | 110.09 |
| Mean | 12 | 132.78 |
| Mean | 14 | 146.24 |
| Mean | 16 | 169.53 |
| Mean | 18 | 192.42 |
| Mean | 20 | 211.60 |
| Mean | 21 | 218.69 |
| Mean + 2√λ·φ | 0 | 41.257 |
| Mean + 2√λ·φ | 2 | 51.237 |
| Mean + 2√λ·φ | 4 | 63.476 |
| Mean + 2√λ·φ | 6 | 83.028 |
| Mean + 2√λ·φ | 8 | 108.84 |
| Mean + 2√λ·φ | 10 | 132.32 |
| Mean + 2√λ·φ | 12 | 159.10 |
| Mean + 2√λ·φ | 14 | 166.78 |
| Mean + 2√λ·φ | 16 | 177.03 |
| Mean + 2√λ·φ | 18 | 182.67 |
| Mean + 2√λ·φ | 20 | 184.23 |
| Mean + 2√λ·φ | 21 | 180.33 |
| Mean − 2√λ·φ | 0 | 40.876 |
| Mean − 2√λ·φ | 2 | 47.919 |
| Mean − 2√λ·φ | 4 | 56.835 |
| Mean − 2√λ·φ | 6 | 66.705 |
| Mean − 2√λ·φ | 8 | 76.006 |
| Mean − 2√λ·φ | 10 | 87.853 |
| Mean − 2√λ·φ | 12 | 106.46 |
| Mean − 2√λ·φ | 14 | 125.71 |
| Mean − 2√λ·φ | 16 | 162.03 |
| Mean − 2√λ·φ | 18 | 202.17 |
| Mean − 2√λ·φ | 20 | 238.97 |
| Mean − 2√λ·φ | 21 | 257.04 |
View data
| curve | Time | weight |
|---|---|---|
| Mean | 0 | 41.067 |
| Mean | 2 | 49.578 |
| Mean | 4 | 60.156 |
| Mean | 6 | 74.867 |
| Mean | 8 | 92.422 |
| Mean | 10 | 110.09 |
| Mean | 12 | 132.78 |
| Mean | 14 | 146.24 |
| Mean | 16 | 169.53 |
| Mean | 18 | 192.42 |
| Mean | 20 | 211.60 |
| Mean | 21 | 218.69 |
| Mean + 2√λ·φ | 0 | 41.138 |
| Mean + 2√λ·φ | 2 | 53.088 |
| Mean + 2√λ·φ | 4 | 65.070 |
| Mean + 2√λ·φ | 6 | 83.075 |
| Mean + 2√λ·φ | 8 | 101.34 |
| Mean + 2√λ·φ | 10 | 116.59 |
| Mean + 2√λ·φ | 12 | 133.66 |
| Mean + 2√λ·φ | 14 | 140.97 |
| Mean + 2√λ·φ | 16 | 159.27 |
| Mean + 2√λ·φ | 18 | 189.38 |
| Mean + 2√λ·φ | 20 | 218.93 |
| Mean + 2√λ·φ | 21 | 228.81 |
| Mean − 2√λ·φ | 0 | 40.995 |
| Mean − 2√λ·φ | 2 | 46.067 |
| Mean − 2√λ·φ | 4 | 55.242 |
| Mean − 2√λ·φ | 6 | 66.659 |
| Mean − 2√λ·φ | 8 | 83.507 |
| Mean − 2√λ·φ | 10 | 103.59 |
| Mean − 2√λ·φ | 12 | 131.90 |
| Mean − 2√λ·φ | 14 | 151.52 |
| Mean − 2√λ·φ | 16 | 179.80 |
| Mean − 2√λ·φ | 18 | 195.46 |
| Mean − 2√λ·φ | 20 | 204.27 |
| Mean − 2√λ·φ | 21 | 208.57 |
View data
| component | Time | φ |
|---|---|---|
| φ1 | 0 | −0.0021 |
| φ1 | 2 | 0.0036 |
| φ1 | 4 | 0.0139 |
| φ1 | 6 | 0.0351 |
| φ1 | 8 | 0.0778 |
| φ1 | 10 | 0.1212 |
| φ1 | 12 | 0.1847 |
| φ1 | 14 | 0.2278 |
| φ1 | 16 | 0.2970 |
| φ1 | 18 | 0.3629 |
| φ1 | 20 | 0.4080 |
| φ1 | 21 | 0.4339 |
| φ2 | 0 | 0.0024 |
| φ2 | 2 | 0.0213 |
| φ2 | 4 | 0.0426 |
| φ2 | 6 | 0.1047 |
| φ2 | 8 | 0.2105 |
| φ2 | 10 | 0.2852 |
| φ2 | 12 | 0.3376 |
| φ2 | 14 | 0.2634 |
| φ2 | 16 | 0.0962 |
| φ2 | 18 | −0.1251 |
| φ2 | 20 | −0.3510 |
| φ2 | 21 | −0.4919 |
| φ3 | 0 | 0.0024 |
| φ3 | 2 | 0.1190 |
| φ3 | 4 | 0.1666 |
| φ3 | 6 | 0.2783 |
| φ3 | 8 | 0.3023 |
| φ3 | 10 | 0.2206 |
| φ3 | 12 | 0.0298 |
| φ3 | 14 | −0.1789 |
| φ3 | 16 | −0.3482 |
| φ3 | 18 | −0.1031 |
| φ3 | 20 | 0.2485 |
| φ3 | 21 | 0.3433 |
View data
| Chick | Score 1 | Score 2 |
|---|---|---|
| 1 | −65.479 | −36.830 |
| 10 | −225.76 | −5.329 |
| 11 | 10.886 | 98.296 |
| 12 | −42.756 | −26.979 |
| 13 | −313.34 | −19.182 |
| 14 | 152.14 | 20.561 |
| 17 | −188.00 | 4.022 |
| 19 | −205.15 | −45.334 |
| 2 | −21.830 | −17.836 |
| 20 | −246.98 | −21.191 |
| 21 | 327.84 | 60.620 |
| 22 | −124.42 | −2.437 |
| 23 | −80.311 | 20.194 |
| 24 | −331.60 | 0.9428 |
| 25 | 101.48 | −9.684 |
| 26 | 33.167 | −19.512 |
| 27 | −79.248 | −9.996 |
| 28 | 32.152 | 10.117 |
| 29 | 98.722 | −65.907 |
| 3 | −34.858 | −17.382 |
| 30 | −116.09 | 15.346 |
| 31 | 20.557 | −43.073 |
| 32 | 181.21 | −17.030 |
| 33 | −92.733 | 59.353 |
| 34 | 248.27 | −39.530 |
| 35 | 380.35 | 8.663 |
| 36 | 66.401 | 14.062 |
| 37 | −116.83 | −26.024 |
| 38 | 101.73 | −56.682 |
| 39 | 49.318 | −41.958 |
| 4 | −130.70 | −18.369 |
| 40 | 179.10 | −33.718 |
| 41 | 3.422 | 47.037 |
| 42 | 128.22 | −0.6616 |
| 43 | 65.677 | 120.11 |
| 45 | −39.391 | 19.316 |
| 46 | 43.778 | 5.036 |
| 47 | 5.062 | 33.777 |
| 48 | 183.79 | −39.135 |
| 49 | 57.050 | 27.115 |
| 5 | 33.776 | 0.6040 |
| 50 | 120.16 | 2.607 |
| 6 | −69.305 | 63.691 |
| 7 | 153.16 | −44.446 |
| 9 | −252.61 | 26.759 |
Components
| Component | Eigenvalue | Share of variance | Cumulative |
|---|---|---|---|
| 1 | 24933.26 | 93.0% | 93.0% |
| 2 | 1519.99 | 5.7% | 98.7% |
| 3 | 217.40 | 0.8% | 99.5% |
| 4 | 50.369 | 0.2% | 99.7% |
| 5 | 28.407 | 0.1% | 99.8% |
| 6 | 20.870 | 0.1% | 99.8% |
| 7 | 16.124 | 0.1% | 99.9% |
| 8 | 8.903 | 0.0% | 99.9% |
| 9 | 8.112 | 0.0% | 100.0% |
| 10 | 5.605 | 0.0% | 100.0% |
Mean curve and eigenfunctions
| Time | Mean | φ1 | φ2 | φ3 |
|---|---|---|---|---|
| 0 | 41.067 | −0.0021 | 0.0024 | 0.0024 |
| 2 | 49.578 | 0.0036 | 0.0213 | 0.1190 |
| 4 | 60.156 | 0.0139 | 0.0426 | 0.1666 |
| 6 | 74.867 | 0.0351 | 0.1047 | 0.2783 |
| 8 | 92.422 | 0.0778 | 0.2105 | 0.3023 |
| 10 | 110.09 | 0.1212 | 0.2852 | 0.2206 |
| 12 | 132.78 | 0.1847 | 0.3376 | 0.0298 |
| 14 | 146.24 | 0.2278 | 0.2634 | −0.1789 |
| 16 | 169.53 | 0.2970 | 0.0962 | −0.3482 |
| 18 | 192.42 | 0.3629 | −0.1251 | −0.1031 |
| 20 | 211.60 | 0.4080 | −0.3510 | 0.2485 |
| 21 | 218.69 | 0.4339 | −0.4919 | 0.3433 |
Curve scores
| Chick | Score 1 | Score 2 | Score 3 | Integrated squared error |
|---|---|---|---|---|
| 1 | −65.479 | −36.830 | −5.887 | 118.19 |
| 10 | −225.76 | −5.329 | −5.353 | 103.73 |
| 11 | 10.886 | 98.296 | −3.793 | 18.797 |
| 12 | −42.756 | −26.979 | −29.337 | 122.88 |
| 13 | −313.34 | −19.182 | 2.540 | 58.762 |
| 14 | 152.14 | 20.561 | −24.329 | 79.058 |
| 17 | −188.00 | 4.022 | 8.641 | 51.345 |
| 19 | −205.15 | −45.334 | −1.879 | 69.410 |
| 2 | −21.830 | −17.836 | −3.605 | 19.740 |
| 20 | −246.98 | −21.191 | −13.882 | 42.253 |
| 21 | 327.84 | 60.620 | −16.699 | 100.41 |
| 22 | −124.42 | −2.437 | 16.146 | 179.86 |
| 23 | −80.311 | 20.194 | −0.9476 | 82.436 |
| 24 | −331.60 | 0.9428 | 5.373 | 255.23 |
| 25 | 101.48 | −9.684 | 7.122 | 64.948 |
| 26 | 33.167 | −19.512 | 12.510 | 175.20 |
| 27 | −79.248 | −9.996 | 6.263 | 54.532 |
| 28 | 32.152 | 10.117 | −14.381 | 169.50 |
| 29 | 98.722 | −65.907 | 13.118 | 201.58 |
| 3 | −34.858 | −17.382 | −18.971 | 244.06 |
| 30 | −116.09 | 15.346 | −9.689 | 99.970 |
| 31 | 20.557 | −43.073 | 7.121 | 63.574 |
| 32 | 181.21 | −17.030 | 6.474 | 84.219 |
| 33 | −92.733 | 59.353 | −4.708 | 162.30 |
| 34 | 248.27 | −39.530 | 10.938 | 245.45 |
| 35 | 380.35 | 8.663 | −8.680 | 88.855 |
| 36 | 66.401 | 14.062 | −21.559 | 435.26 |
| 37 | −116.83 | −26.024 | −6.080 | 110.31 |
| 38 | 101.73 | −56.682 | 13.432 | 193.70 |
| 39 | 49.318 | −41.958 | 18.195 | 104.41 |
| 4 | −130.70 | −18.369 | −13.926 | 209.65 |
| 40 | 179.10 | −33.718 | 6.219 | 193.07 |
| 41 | 3.422 | 47.037 | 10.078 | 190.20 |
| 42 | 128.22 | −0.6616 | 10.524 | 103.96 |
| 43 | 65.677 | 120.11 | 19.953 | 68.472 |
| 45 | −39.391 | 19.316 | 20.707 | 161.85 |
| 46 | 43.778 | 5.036 | 16.406 | 89.230 |
| 47 | 5.062 | 33.777 | 12.050 | 169.67 |
| 48 | 183.79 | −39.135 | 11.046 | 153.96 |
| 49 | 57.050 | 27.115 | 17.997 | 89.074 |
First 40 of 45 rows.
Curves left out
| Chick | Why |
|---|---|
| 15 | ends before the last time |
| 16 | ends before the last time |
| 18 | ends before the last time |
| 44 | ends before the last time |
| 8 | ends before the last time |
- 5 curve(s) don't cover the whole time range and were left out (FPCA doesn't extrapolate): 15, 16, 18, 44, 8.
- Integrals use the trapezoid rule on the common grid, so uneven time steps count by their length; eigenvalues are the variance of each component's scores (divisor n − 1) and each eigenfunction has ∫φ² dt = 1, signed so ∫φ dt ≥ 0.
- Read a component by its mean ± 2 SD chart: it shows how curves with a high or low score differ from the average curve.
- Phase variation (the same shape shifted in time) shows up as extra components; align the curves first when timing differences aren't of interest.
The exact R script · R R version 4.5.1 (2025-06-13)
# Functional PCA (main shapes of a set of curves)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.fpca 1.0.0 · spec 43928583d1219167
# Dataset: ml_chickweight (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/ml_chickweight.parquet", col_select = c("Chick", "Time", "weight")))
n_input <- nrow(df)
df[["Chick"]] <- factor(df[["Chick"]], levels = c("1", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "2", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "3", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "4", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "5", "50", "6", "7", "8", "9")) # stored level order
df <- df[stats::complete.cases(df[c("Chick", "Time", "weight")]), , 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("Chick", "Time", "weight")) # infinite values stop the run (registry/errors.yaml)
# %% Curves
# Functional PCA (Ramsay & Silverman 2005): curves in long form (curve, time, value) on a common grid,
# trapezoid quadrature, optional Whittaker pre-smoothing, eigenfunctions orthonormal under the integral.
CURVE <- "Chick"
TIME <- "Time"
VALUE <- "weight"
TEMPORAL <- FALSE
Q <- as.integer(3)
SMOOTHING <- "none" # none | gcv | manual
LOG_LAMBDA <- as.numeric(-2)
cs_check_rows(nrow(df), 9, "Functional PCA")
cs_check_groups(as.character(df[[CURVE]]), CURVE, minimum = 3)
cs_check_not_constant(as.numeric(df[[VALUE]]), VALUE)
traw <- df[[TIME]]
tnum <- if (TEMPORAL) {
if (inherits(traw, "POSIXt")) as.numeric(traw) / 86400 else as.numeric(as.Date(traw))
} else as.numeric(traw)
cs_check_not_constant(tnum, TIME)
curve_levels <- as.character(levels(df[[CURVE]]))
g <- cs_fpca_grid(as.integer(df[[CURVE]]), length(curve_levels), tnum, as.numeric(df[[VALUE]]))
grid <- g$grid
Y <- g$Y
kept <- curve_levels[g$kept]
if (length(kept) < 3)
cs_error("CS_E_UNDEFINED", what = "Functional PCA", reason = sprintf("only %d curve(s) cover the whole time range (at least 3 are needed)", length(kept)))
if (length(grid) < 3)
cs_error("CS_E_UNDEFINED", what = "Functional PCA", reason = sprintf("the curves share only %d time point(s) (at least 3 are needed)", length(grid)))
if (length(grid) > 500)
cs_error("CS_E_UNDEFINED", what = "Functional PCA", reason = sprintf("the common grid has %d time points (at most 500; aggregate the times first)", length(grid)))
if (g$n_dup > 0) warnings <- c(warnings, sprintf("%d row(s) repeated a curve's time; each such point uses the mean of its values.", g$n_dup))
if (length(g$dropped)) {
dn <- vapply(g$dropped, function(dd) curve_levels[dd$code], "")
warnings <- c(warnings, paste0(sprintf("%d curve(s) don't cover the whole time range and were left out (FPCA doesn't extrapolate): ", length(dn)),
paste(head(dn, 10), collapse = ", "), if (length(dn) > 10) " …" else "", "."))
}
share_interp <- g$n_interp / (length(kept) * length(grid))
if (share_interp > 0.5)
cs_error("CS_E_UNDEFINED", what = "Functional PCA", reason = sprintf("%.0f%% of the grid values would be interpolated (curves measured at different times need sparse-data methods)", 100 * share_interp))
if (g$n_interp > 0)
warnings <- c(warnings, sprintf("%d grid value(s) (%.1f%%) were filled by straight lines between a curve's neighboring measurements.", g$n_interp, 100 * share_interp))
w <- cs_fpca_weights(grid)
values <- list(n_curves = length(kept), n_dropped_curves = length(g$dropped), n_grid = length(grid), n_interpolated = g$n_interp,
smoothing = SMOOTHING, log_lambda = NaN, edf = NaN, gcv = NaN)
Ys <- Y
if (SMOOTHING != "none") {
sm <- cs_fpca_smooth(Y, grid, w, if (SMOOTHING == "gcv") NULL else LOG_LAMBDA)
Ys <- sm$Y
values$log_lambda <- sm$log_lambda
values$edf <- sm$edf
values$gcv <- sm$gcv
}
# %% Decompose
fit <- cs_fpca_fit(Ys, w, Q)
q <- fit$q
if (q < Q) warnings <- c(warnings, sprintf("Only %d component(s) are available (the curves span %d dimension(s)); %d were requested.", q, fit$rank, Q))
ev <- fit$eigenvalues
values$components <- q
values$total_variance <- fit$total
values$explained <- sum(ev[seq_len(q)]) / fit$total
values$recon_error <- mean(fit$ise)
cum <- 0
comp_rows <- list()
for (k in seq_along(ev)) {
share <- ev[k] / fit$total
cum <- cum + share
if (k <= max(q, min(length(ev), 10))) comp_rows[[length(comp_rows) + 1]] <- list(component = k, eigenvalue = ev[k], share = share, cumulative = cum)
if (k <= q) {
values[[sprintf("eigen[%d]", k)]] <- ev[k]
values[[sprintf("share[%d]", k)]] <- share
values[[sprintf("cumulative[%d]", k)]] <- cum
values[[sprintf("phi_check[%d]", k)]] <- sum(seq_along(grid) * w * fit$phi[, k])
values[[sprintf("score_check[%d]", k)]] <- sum(seq_along(kept) * fit$scores[, k])
}
}
grid_labels <- if (TEMPORAL) format(as.Date(grid, origin = "1970-01-01"), "%Y-%m-%d") else sprintf("%.10g", grid)
# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-82309/discover.fpca/chickweight-growth/out-r")
artifacts <- list()
modes <- list(list(name = CURVE, levels = kept, F = fit$scores), list(name = TIME, levels = grid_labels, F = fit$phi))
for (md in modes) {
fdf <- data.frame(level = md$levels, stringsAsFactors = FALSE)
for (k in seq_len(q)) fdf[[sprintf("factor_%d", k)]] <- md$F[, k]
path <- file.path(out, sprintf("factors_%s.parquet", md$name))
nanoparquet::write_parquet(fdf, path)
artifacts[[length(artifacts) + 1]] <- list(key = sprintf("factors_%s", md$name), path = path, format = "parquet")
}
# %% Charts
xkind <- if (TEMPORAL) "temporal" else "numeric"
xvals <- if (TEMPORAL) grid_labels else grid
charts <- list(cs_chart("scree", "scree-plot", "Share of the curves' variance by component", list(
component = cs_col("Component", as.numeric(vapply(comp_rows, function(r) r$component, numeric(1)))),
variance = cs_col("Share of variance", vapply(comp_rows, function(r) r$share, numeric(1))),
cumulative = cs_col("Cumulative share", vapply(comp_rows, function(r) r$cumulative, numeric(1))))))
for (k in seq_len(min(q, 3))) {
amp <- 2 * sqrt(ev[k])
ys <- c(fit$mean, fit$mean + amp * fit$phi[, k], fit$mean - amp * fit$phi[, k])
labs <- rep(c("Mean", "Mean + 2√λ·φ", "Mean − 2√λ·φ"), each = length(grid))
charts[[length(charts) + 1]] <- cs_chart(sprintf("mode%d", k), "series-line",
sprintf("Component %d (%.0f%% of the variance): the mean curve moved by ±2 SD", k, 100 * ev[k] / fit$total), list(
x = cs_col(TIME, rep(xvals, 3), kind = xkind), y = cs_col(VALUE, ys), group = cs_col("curve", labs, kind = "categorical")))
}
if (q >= 1) {
charts[[length(charts) + 1]] <- cs_chart("eigenfunctions", "series-line", "Eigenfunctions φ(t)", list(
x = cs_col(TIME, rep(xvals, q), kind = xkind), y = cs_col("φ", as.vector(fit$phi)),
group = cs_col("component", rep(sprintf("φ%d", seq_len(q)), each = length(grid)), kind = "categorical")))
}
if (q >= 2) {
charts[[length(charts) + 1]] <- cs_chart("scores", "embedding-map", "Curve scores on the first two components", list(
x = cs_col("Score 1", fit$scores[, 1]), y = cs_col("Score 2", fit$scores[, 2]), label = cs_col(CURVE, kept, kind = "categorical")))
}
# %% Tables
tables <- list(
list(key = "components", title = "Components",
columns = list(list(key = "component", label = "Component", type = "integer"), list(key = "eigenvalue", label = "Eigenvalue", type = "number"),
list(key = "share", label = "Share of variance", type = "percent"), list(key = "cumulative", label = "Cumulative", type = "percent")),
rows = comp_rows),
list(key = "functions", title = "Mean curve and eigenfunctions",
columns = c(list(list(key = "time", label = TIME, type = "string"), list(key = "mean", label = "Mean", type = "number")),
lapply(seq_len(q), function(k) list(key = sprintf("phi%d", k), label = sprintf("φ%d", k), type = "number"))),
rows = lapply(seq_along(grid), function(j) c(list(time = grid_labels[j], mean = fit$mean[j]),
stats::setNames(as.list(fit$phi[j, seq_len(q)]), sprintf("phi%d", seq_len(q)))))),
list(key = "scores", title = "Curve scores",
columns = c(list(list(key = "curve", label = CURVE, type = "string")),
lapply(seq_len(q), function(k) list(key = sprintf("s%d", k), label = sprintf("Score %d", k), type = "number")),
list(list(key = "ise", label = "Integrated squared error", type = "number"))),
rows = lapply(seq_along(kept), function(i) c(list(curve = kept[i]), stats::setNames(as.list(fit$scores[i, seq_len(q)]), sprintf("s%d", seq_len(q))),
list(ise = fit$ise[i])))))
if (length(g$dropped)) {
tables[[length(tables) + 1]] <- list(key = "dropped", title = "Curves left out",
columns = list(list(key = "curve", label = CURVE, type = "string"), list(key = "reason", label = "Why", type = "string")),
rows = lapply(g$dropped, function(dd) list(curve = curve_levels[dd$code], reason = dd$reason)))
}
# %% Result
summary <- paste0(sprintf("Functional PCA of %d curves of %s on %d time points: the first %d component%s explain %.1f%% of the variance between curves",
length(kept), VALUE, length(grid), q, if (q != 1) "s" else "", 100 * values$explained),
if (q > 1) sprintf(" (component 1 alone %.1f%%)", 100 * ev[1] / fit$total) else "", ".")
notes <- c(paste0("Integrals use the trapezoid rule on the common grid, so uneven time steps count by their length; eigenvalues are the variance of each ",
"component's scores (divisor n − 1) and each eigenfunction has ∫φ² dt = 1, signed so ∫φ dt ≥ 0."),
"Read a component by its mean ± 2 SD chart: it shows how curves with a high or low score differ from the average curve.")
if (SMOOTHING != "none") {
notes <- c(notes, paste0(sprintf("Curves were smoothed first with a second-difference penalty (λ = 10^%.2f relative to the grid, %.2f effective degrees of freedom of %d",
values$log_lambda, values$edf, length(grid)),
if (SMOOTHING == "gcv") "; chosen by generalized cross-validation" else "", ")."))
}
notes <- c(notes, "Phase variation (the same shape shifted in time) shows up as extra components; align the curves first when timing differences aren't of interest.")
cs_publish(list(
title = "Functional PCA (main shapes of a set of curves)",
engine = cs_engine_info("nanoparquet"),
n = length(kept),
summary = summary,
statistics = list(list(key = "explained", label = sprintf("Variance explained by %d components", q), value = values$explained),
list(key = "recon_error", label = "Mean integrated squared error", value = values$recon_error)),
tables = tables,
charts = charts,
values = values,
warnings = warnings,
notes = notes,
artifacts = artifacts
))
Functional PCA of 45 curves of weight on 12 time points: the first 3 components explain 99.5% of the variance between curves (component 1 alone 93.0%).
- Variance explained by 3 components
- 0.9947
- Mean integrated squared error
- 138.98
To keep this page light, the plots are shown once, under the R tab.
Components
| Component | Eigenvalue | Share of variance | Cumulative |
|---|---|---|---|
| 1 | 24933.26 | 93.0% | 93.0% |
| 2 | 1519.99 | 5.7% | 98.7% |
| 3 | 217.40 | 0.8% | 99.5% |
| 4 | 50.369 | 0.2% | 99.7% |
| 5 | 28.407 | 0.1% | 99.8% |
| 6 | 20.870 | 0.1% | 99.8% |
| 7 | 16.124 | 0.1% | 99.9% |
| 8 | 8.903 | 0.0% | 99.9% |
| 9 | 8.112 | 0.0% | 100.0% |
| 10 | 5.605 | 0.0% | 100.0% |
Mean curve and eigenfunctions
| Time | Mean | φ1 | φ2 | φ3 |
|---|---|---|---|---|
| 0 | 41.067 | −0.0021 | 0.0024 | 0.0024 |
| 2 | 49.578 | 0.0036 | 0.0213 | 0.1190 |
| 4 | 60.156 | 0.0139 | 0.0426 | 0.1666 |
| 6 | 74.867 | 0.0351 | 0.1047 | 0.2783 |
| 8 | 92.422 | 0.0778 | 0.2105 | 0.3023 |
| 10 | 110.09 | 0.1212 | 0.2852 | 0.2206 |
| 12 | 132.78 | 0.1847 | 0.3376 | 0.0298 |
| 14 | 146.24 | 0.2278 | 0.2634 | −0.1789 |
| 16 | 169.53 | 0.2970 | 0.0962 | −0.3482 |
| 18 | 192.42 | 0.3629 | −0.1251 | −0.1031 |
| 20 | 211.60 | 0.4080 | −0.3510 | 0.2485 |
| 21 | 218.69 | 0.4339 | −0.4919 | 0.3433 |
Curve scores
| Chick | Score 1 | Score 2 | Score 3 | Integrated squared error |
|---|---|---|---|---|
| 1 | −65.479 | −36.830 | −5.887 | 118.19 |
| 10 | −225.76 | −5.329 | −5.353 | 103.73 |
| 11 | 10.886 | 98.296 | −3.793 | 18.797 |
| 12 | −42.756 | −26.979 | −29.337 | 122.88 |
| 13 | −313.34 | −19.182 | 2.540 | 58.762 |
| 14 | 152.14 | 20.561 | −24.329 | 79.058 |
| 17 | −188.00 | 4.022 | 8.641 | 51.345 |
| 19 | −205.15 | −45.334 | −1.879 | 69.410 |
| 2 | −21.830 | −17.836 | −3.605 | 19.740 |
| 20 | −246.98 | −21.191 | −13.882 | 42.253 |
| 21 | 327.84 | 60.620 | −16.699 | 100.41 |
| 22 | −124.42 | −2.437 | 16.146 | 179.86 |
| 23 | −80.311 | 20.194 | −0.9476 | 82.436 |
| 24 | −331.60 | 0.9428 | 5.373 | 255.23 |
| 25 | 101.48 | −9.684 | 7.122 | 64.948 |
| 26 | 33.167 | −19.512 | 12.510 | 175.20 |
| 27 | −79.248 | −9.996 | 6.263 | 54.532 |
| 28 | 32.152 | 10.117 | −14.381 | 169.50 |
| 29 | 98.722 | −65.907 | 13.118 | 201.58 |
| 3 | −34.858 | −17.382 | −18.971 | 244.06 |
| 30 | −116.09 | 15.346 | −9.689 | 99.970 |
| 31 | 20.557 | −43.073 | 7.121 | 63.574 |
| 32 | 181.21 | −17.030 | 6.474 | 84.219 |
| 33 | −92.733 | 59.353 | −4.708 | 162.30 |
| 34 | 248.27 | −39.530 | 10.938 | 245.45 |
| 35 | 380.35 | 8.663 | −8.680 | 88.855 |
| 36 | 66.401 | 14.062 | −21.559 | 435.26 |
| 37 | −116.83 | −26.024 | −6.080 | 110.31 |
| 38 | 101.73 | −56.682 | 13.432 | 193.70 |
| 39 | 49.318 | −41.958 | 18.195 | 104.41 |
| 4 | −130.70 | −18.369 | −13.926 | 209.65 |
| 40 | 179.10 | −33.718 | 6.219 | 193.07 |
| 41 | 3.422 | 47.037 | 10.078 | 190.20 |
| 42 | 128.22 | −0.6616 | 10.524 | 103.96 |
| 43 | 65.677 | 120.11 | 19.953 | 68.472 |
| 45 | −39.391 | 19.316 | 20.707 | 161.85 |
| 46 | 43.778 | 5.036 | 16.406 | 89.230 |
| 47 | 5.062 | 33.777 | 12.050 | 169.67 |
| 48 | 183.79 | −39.135 | 11.046 | 153.96 |
| 49 | 57.050 | 27.115 | 17.997 | 89.074 |
First 40 of 45 rows.
Curves left out
| Chick | Why |
|---|---|
| 15 | ends before the last time |
| 16 | ends before the last time |
| 18 | ends before the last time |
| 44 | ends before the last time |
| 8 | ends before the last time |
- 5 curve(s) don't cover the whole time range and were left out (FPCA doesn't extrapolate): 15, 16, 18, 44, 8.
- Integrals use the trapezoid rule on the common grid, so uneven time steps count by their length; eigenvalues are the variance of each component's scores (divisor n − 1) and each eigenfunction has ∫φ² dt = 1, signed so ∫φ dt ≥ 0.
- Read a component by its mean ± 2 SD chart: it shows how curves with a high or low score differ from the average curve.
- Phase variation (the same shape shifted in time) shows up as extra components; align the curves first when timing differences aren't of interest.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Functional PCA (main shapes of a set of curves)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.fpca 1.0.0 · spec 43928583d1219167
# Dataset: ml_chickweight (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.errors import check_groups, check_not_constant
from codesplash import ml as csml
from codesplash.ml import fpca
from codesplash.stats import ts
# %% Data
df = pd.read_parquet("tests/parity/fixtures/ml_chickweight.parquet", columns=["Chick", "Time", "weight"])
n_input = len(df)
df["Chick"] = pd.Categorical(df["Chick"], categories=["1", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "2", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "3", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "4", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "5", "50", "6", "7", "8", "9"]) # stored level order
df = df.dropna(subset=["Chick", "Time", "weight"]) # listwise deletion over the analysis columns
df["Chick"] = df["Chick"].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, ["Chick", "Time", "weight"]) # infinite values stop the run (registry/errors.yaml)
# %% Curves
# Functional PCA (Ramsay & Silverman 2005): curves in long form (curve, time, value) on a common grid,
# trapezoid quadrature, optional Whittaker pre-smoothing, eigenfunctions orthonormal under ∫φ_j φ_k dt.
CURVE = "Chick"
TIME = "Time"
VALUE = "weight"
TEMPORAL = False
Q = int(3)
SMOOTHING = "none" # none | gcv | manual
LOG_LAMBDA = float(-2)
cs.check_rows(len(df), 9, "Functional PCA")
check_groups(df[CURVE].astype(str), CURVE, minimum=3)
check_not_constant(df[VALUE].to_numpy(dtype=float), VALUE)
if TEMPORAL:
tnum = ((pd.to_datetime(df[TIME]) - pd.Timestamp("1970-01-01")) / pd.Timedelta(days=1)).to_numpy(dtype=float)
else:
tnum = df[TIME].to_numpy(dtype=float)
check_not_constant(tnum, TIME)
curve_levels = [str(v) for v in df[CURVE].cat.categories]
g = fpca.to_grid(df[CURVE].cat.codes.to_numpy(), len(curve_levels), tnum, df[VALUE].to_numpy(dtype=float))
grid, Y = g["grid"], g["Y"]
kept = [curve_levels[c] for c in g["kept"]]
if len(kept) < 3:
cs.cs_error("CS_E_UNDEFINED", what="Functional PCA", reason=f"only {len(kept)} curve(s) cover the whole time range (at least 3 are needed)")
if len(grid) < 3:
cs.cs_error("CS_E_UNDEFINED", what="Functional PCA", reason=f"the curves share only {len(grid)} time point(s) (at least 3 are needed)")
if len(grid) > 500:
cs.cs_error("CS_E_UNDEFINED", what="Functional PCA", reason=f"the common grid has {len(grid)} time points (at most 500; aggregate the times first)")
if g["n_dup"]:
warnings.append(f"{g['n_dup']} row(s) repeated a curve's time; each such point uses the mean of its values.")
if g["dropped"]:
warnings.append(f"{len(g['dropped'])} curve(s) don't cover the whole time range and were left out (FPCA doesn't extrapolate): "
+ ", ".join(curve_levels[c] for c, _ in g["dropped"][:10]) + (" …" if len(g["dropped"]) > 10 else "") + ".")
share_interp = g["n_interp"] / (len(kept) * len(grid))
if share_interp > 0.5:
cs.cs_error("CS_E_UNDEFINED", what="Functional PCA", reason=f"{share_interp:.0%} of the grid values would be interpolated (curves measured at different times need sparse-data methods)")
if g["n_interp"]:
warnings.append(f"{g['n_interp']} grid value(s) ({share_interp:.1%}) were filled by straight lines between a curve's neighboring measurements.")
w = fpca.trapezoid_weights(grid)
values = {"n_curves": len(kept), "n_dropped_curves": len(g["dropped"]), "n_grid": len(grid), "n_interpolated": g["n_interp"],
"smoothing": SMOOTHING, "log_lambda": float("nan"), "edf": float("nan"), "gcv": float("nan")}
Ys = Y
if SMOOTHING != "none":
sm = fpca.smooth(Y, grid, w, None if SMOOTHING == "gcv" else LOG_LAMBDA)
Ys = sm["Y"]
values.update({"log_lambda": sm["log_lambda"], "edf": sm["edf"], "gcv": sm["gcv"]})
# %% Decompose
fit = fpca.fit(Ys, w, Q)
q = fit["q"]
if q < Q:
warnings.append(f"Only {q} component(s) are available (the curves span {fit['rank']} dimension(s)); {Q} were requested.")
ev = fit["eigenvalues"]
values.update({"components": q, "total_variance": fit["total"], "explained": float(np.sum(ev[:q]) / fit["total"]),
"recon_error": float(np.mean(fit["ise"]))})
cum = 0.0
comp_rows = []
for k in range(len(ev)):
share = float(ev[k] / fit["total"])
cum += share
if k < max(q, min(len(ev), 10)):
comp_rows.append({"component": k + 1, "eigenvalue": float(ev[k]), "share": share, "cumulative": cum})
if k < q:
values[f"eigen[{k + 1}]"] = float(ev[k])
values[f"share[{k + 1}]"] = share
values[f"cumulative[{k + 1}]"] = cum
values[f"phi_check[{k + 1}]"] = float(np.sum(np.arange(1, len(grid) + 1) * w * fit["phi"][:, k]))
values[f"score_check[{k + 1}]"] = float(np.sum(np.arange(1, len(kept) + 1) * fit["scores"][:, k]))
grid_labels = ts.time_labels(pd.to_datetime(grid, unit="D").to_numpy(), True) if TEMPORAL else ["%.10g" % v for v in grid]
# %% Artifacts
out = csml.out_dir("target/academy-parity/run-82309/discover.fpca/chickweight-growth/out-python")
artifacts = []
for name, levels_, F in ((CURVE, kept, fit["scores"]), (TIME, grid_labels, fit["phi"])):
fdf = pd.DataFrame({"level": levels_})
for k in range(q):
fdf[f"factor_{k + 1}"] = F[:, k]
path = os.path.join(out, f"factors_{name}.parquet")
fdf.to_parquet(path, index=False)
artifacts.append({"key": f"factors_{name}", "path": path, "format": "parquet"})
# %% Charts
xkind = "temporal" if TEMPORAL else "numeric"
xvals = grid_labels if TEMPORAL else grid.tolist()
charts = [cs.chart("scree", "scree-plot", "Share of the curves' variance by component", {
"component": cs.col("Component", np.array([r["component"] for r in comp_rows], dtype=float)),
"variance": cs.col("Share of variance", np.array([r["share"] for r in comp_rows])),
"cumulative": cs.col("Cumulative share", np.array([r["cumulative"] for r in comp_rows]))})]
for k in range(min(q, 3)):
amp = 2.0 * np.sqrt(ev[k])
lines = [("Mean", fit["mean"]), ("Mean + 2√λ·φ", fit["mean"] + amp * fit["phi"][:, k]), ("Mean − 2√λ·φ", fit["mean"] - amp * fit["phi"][:, k])]
charts.append(cs.chart(f"mode{k + 1}", "series-line", f"Component {k + 1} ({ev[k] / fit['total']:.0%} of the variance): the mean curve moved by ±2 SD", {
"x": cs.col(TIME, [v for _ in lines for v in xvals], kind=xkind),
"y": cs.col(VALUE, np.concatenate([y for _, y in lines])),
"group": cs.col("curve", [lab for lab, _ in lines for _ in xvals], kind="categorical")}))
if q >= 1:
charts.append(cs.chart("eigenfunctions", "series-line", "Eigenfunctions φ(t)", {
"x": cs.col(TIME, [v for _ in range(q) for v in xvals], kind=xkind),
"y": cs.col("φ", fit["phi"].T.reshape(-1)),
"group": cs.col("component", [f"φ{k + 1}" for k in range(q) for _ in xvals], kind="categorical")}))
if q >= 2:
charts.append(cs.chart("scores", "embedding-map", "Curve scores on the first two components", {
"x": cs.col("Score 1", fit["scores"][:, 0]), "y": cs.col("Score 2", fit["scores"][:, 1]),
"label": cs.col(CURVE, kept, kind="categorical")}))
# %% Tables
tables = [{"key": "components", "title": "Components",
"columns": [{"key": "component", "label": "Component", "type": "integer"}, {"key": "eigenvalue", "label": "Eigenvalue", "type": "number"},
{"key": "share", "label": "Share of variance", "type": "percent"}, {"key": "cumulative", "label": "Cumulative", "type": "percent"}],
"rows": comp_rows},
{"key": "functions", "title": "Mean curve and eigenfunctions",
"columns": [{"key": "time", "label": TIME, "type": "string"}, {"key": "mean", "label": "Mean", "type": "number"}]
+ [{"key": f"phi{k + 1}", "label": f"φ{k + 1}", "type": "number"} for k in range(q)],
"rows": [{"time": grid_labels[j], "mean": float(fit["mean"][j]), **{f"phi{k + 1}": float(fit["phi"][j, k]) for k in range(q)}} for j in range(len(grid))]},
{"key": "scores", "title": "Curve scores",
"columns": [{"key": "curve", "label": CURVE, "type": "string"}] + [{"key": f"s{k + 1}", "label": f"Score {k + 1}", "type": "number"} for k in range(q)]
+ [{"key": "ise", "label": "Integrated squared error", "type": "number"}],
"rows": [{"curve": kept[i], **{f"s{k + 1}": float(fit["scores"][i, k]) for k in range(q)}, "ise": float(fit["ise"][i])} for i in range(len(kept))]}]
if g["dropped"]:
tables.append({"key": "dropped", "title": "Curves left out",
"columns": [{"key": "curve", "label": CURVE, "type": "string"}, {"key": "reason", "label": "Why", "type": "string"}],
"rows": [{"curve": curve_levels[c], "reason": why} for c, why in g["dropped"]]})
# %% Result
summary = (f"Functional PCA of {len(kept)} curves of {VALUE} on {len(grid)} time points: the first {q} component{'s' if q != 1 else ''} "
f"explain {values['explained']:.1%} of the variance between curves"
+ (f" (component 1 alone {ev[0] / fit['total']:.1%})" if q > 1 else "") + ".")
notes = ["Integrals use the trapezoid rule on the common grid, so uneven time steps count by their length; eigenvalues are the variance of each "
"component's scores (divisor n − 1) and each eigenfunction has ∫φ² dt = 1, signed so ∫φ dt ≥ 0.",
"Read a component by its mean ± 2 SD chart: it shows how curves with a high or low score differ from the average curve."]
if SMOOTHING != "none":
notes.append(f"Curves were smoothed first with a second-difference penalty (λ = 10^{values['log_lambda']:.2f} relative to the grid, "
f"{values['edf']:.2f} effective degrees of freedom of {len(grid)}" + ("; chosen by generalized cross-validation" if SMOOTHING == "gcv" else "") + ").")
notes.append("Phase variation (the same shape shifted in time) shows up as extra components; align the curves first when timing differences aren't of interest.")
cs.publish({
"title": "Functional PCA (main shapes of a set of curves)",
"engine": cs.engine_info("numpy", "pandas"),
"n": len(kept),
"summary": summary,
"statistics": [{"key": "explained", "label": f"Variance explained by {q} components", "value": values["explained"]},
{"key": "recon_error", "label": "Mean integrated squared error", "value": values["recon_error"]}],
"tables": tables,
"charts": charts,
"values": values,
"warnings": warnings,
"notes": notes,
"artifacts": artifacts,
})
45 chicks were measured at every time point. 5 stopped early and were left out: FPCA doesn't extrapolate a curve beyond its last measurement.
The first component alone carries 0.930 of the variance. Its chart (mean ± 2 SD) shows the main difference between chicks: some grow fast and pull away, others stay small. Growth differences widen with age, so the eigenfunction rises over time.
Reading a component
ReadNever read an eigenfunction on its own. Look at the mean curve moved by ±2 standard deviations along it:
- Component 1 usually describes overall size or level.
- Later components describe shape, such as early versus late growth or a peak that comes sooner.
The scores chart places each curve on the first two components; curves far out on component 1 are the unusually large or small ones. Scores and eigenfunctions can be saved as datasets for a model or a chart.
Uneven grids and gaps
ReadFunctional PCA of 29 curves of value on 9 time points: the first 3 components explain 98.2% of the variance between curves (component 1 alone 85.6%).
- Variance explained by 3 components
- 0.9815
- Mean integrated squared error
- 0.7796
Plots
View data
| Component | Cumulative share | Share of variance |
|---|---|---|
| 1 | 0.8559 | 0.8559 |
| 2 | 0.9696 | 0.1137 |
| 3 | 0.9815 | 0.0120 |
| 4 | 0.9872 | 0.0056 |
| 5 | 0.9922 | 0.0050 |
| 6 | 0.9956 | 0.0034 |
| 7 | 0.9980 | 0.0023 |
| 8 | 0.9996 | 0.0016 |
| 9 | 1 | 0.0004 |
View data
| curve | t | value |
|---|---|---|
| Mean | 0 | 9.826 |
| Mean | 1 | 13.744 |
| Mean | 2 | 15.447 |
| Mean | 3 | 16.693 |
| Mean | 5 | 18.601 |
| Mean | 7 | 20.240 |
| Mean | 10 | 22.252 |
| Mean | 14 | 24.475 |
| Mean | 20 | 27.347 |
| Mean + 2√λ·φ | 0 | 12.862 |
| Mean + 2√λ·φ | 1 | 16.605 |
| Mean + 2√λ·φ | 2 | 18.392 |
| Mean + 2√λ·φ | 3 | 19.589 |
| Mean + 2√λ·φ | 5 | 21.482 |
| Mean + 2√λ·φ | 7 | 22.972 |
| Mean + 2√λ·φ | 10 | 25.060 |
| Mean + 2√λ·φ | 14 | 27.051 |
| Mean + 2√λ·φ | 20 | 29.910 |
| Mean − 2√λ·φ | 0 | 6.789 |
| Mean − 2√λ·φ | 1 | 10.883 |
| Mean − 2√λ·φ | 2 | 12.501 |
| Mean − 2√λ·φ | 3 | 13.797 |
| Mean − 2√λ·φ | 5 | 15.720 |
| Mean − 2√λ·φ | 7 | 17.507 |
| Mean − 2√λ·φ | 10 | 19.445 |
| Mean − 2√λ·φ | 14 | 21.899 |
| Mean − 2√λ·φ | 20 | 24.784 |
View data
| curve | t | value |
|---|---|---|
| Mean | 0 | 9.826 |
| Mean | 1 | 13.744 |
| Mean | 2 | 15.447 |
| Mean | 3 | 16.693 |
| Mean | 5 | 18.601 |
| Mean | 7 | 20.240 |
| Mean | 10 | 22.252 |
| Mean | 14 | 24.475 |
| Mean | 20 | 27.347 |
| Mean + 2√λ·φ | 0 | 8.323 |
| Mean + 2√λ·φ | 1 | 12.301 |
| Mean + 2√λ·φ | 2 | 14.218 |
| Mean + 2√λ·φ | 3 | 15.519 |
| Mean + 2√λ·φ | 5 | 17.625 |
| Mean + 2√λ·φ | 7 | 19.878 |
| Mean + 2√λ·φ | 10 | 22.370 |
| Mean + 2√λ·φ | 14 | 25.203 |
| Mean + 2√λ·φ | 20 | 28.998 |
| Mean − 2√λ·φ | 0 | 11.329 |
| Mean − 2√λ·φ | 1 | 15.187 |
| Mean − 2√λ·φ | 2 | 16.675 |
| Mean − 2√λ·φ | 3 | 17.867 |
| Mean − 2√λ·φ | 5 | 19.577 |
| Mean − 2√λ·φ | 7 | 20.602 |
| Mean − 2√λ·φ | 10 | 22.135 |
| Mean − 2√λ·φ | 14 | 23.747 |
| Mean − 2√λ·φ | 20 | 25.696 |
View data
| curve | t | value |
|---|---|---|
| Mean | 0 | 9.826 |
| Mean | 1 | 13.744 |
| Mean | 2 | 15.447 |
| Mean | 3 | 16.693 |
| Mean | 5 | 18.601 |
| Mean | 7 | 20.240 |
| Mean | 10 | 22.252 |
| Mean | 14 | 24.475 |
| Mean | 20 | 27.347 |
| Mean + 2√λ·φ | 0 | 9.969 |
| Mean + 2√λ·φ | 1 | 13.600 |
| Mean + 2√λ·φ | 2 | 15.253 |
| Mean + 2√λ·φ | 3 | 16.658 |
| Mean + 2√λ·φ | 5 | 18.541 |
| Mean + 2√λ·φ | 7 | 20.267 |
| Mean + 2√λ·φ | 10 | 22.057 |
| Mean + 2√λ·φ | 14 | 24.978 |
| Mean + 2√λ·φ | 20 | 26.894 |
| Mean − 2√λ·φ | 0 | 9.682 |
| Mean − 2√λ·φ | 1 | 13.888 |
| Mean − 2√λ·φ | 2 | 15.640 |
| Mean − 2√λ·φ | 3 | 16.728 |
| Mean − 2√λ·φ | 5 | 18.661 |
| Mean − 2√λ·φ | 7 | 20.212 |
| Mean − 2√λ·φ | 10 | 22.448 |
| Mean − 2√λ·φ | 14 | 23.972 |
| Mean − 2√λ·φ | 20 | 27.800 |
View data
| component | t | φ |
|---|---|---|
| φ1 | 0 | 0.2481 |
| φ1 | 1 | 0.2338 |
| φ1 | 2 | 0.2407 |
| φ1 | 3 | 0.2366 |
| φ1 | 5 | 0.2354 |
| φ1 | 7 | 0.2233 |
| φ1 | 10 | 0.2294 |
| φ1 | 14 | 0.2105 |
| φ1 | 20 | 0.2094 |
| φ2 | 0 | −0.3370 |
| φ2 | 1 | −0.3235 |
| φ2 | 2 | −0.2754 |
| φ2 | 3 | −0.2632 |
| φ2 | 5 | −0.2187 |
| φ2 | 7 | −0.0811 |
| φ2 | 10 | 0.0263 |
| φ2 | 14 | 0.1633 |
| φ2 | 20 | 0.3701 |
| φ3 | 0 | 0.0991 |
| φ3 | 1 | −0.0993 |
| φ3 | 2 | −0.1336 |
| φ3 | 3 | −0.0244 |
| φ3 | 5 | −0.0417 |
| φ3 | 7 | 0.0190 |
| φ3 | 10 | −0.1350 |
| φ3 | 14 | 0.3476 |
| φ3 | 20 | −0.3131 |
View data
| curve | Score 1 | Score 2 |
|---|---|---|
| c01 | −0.1186 | −2.409 |
| c02 | 5.877 | −3.001 |
| c03 | −6.530 | −0.2745 |
| c04 | 1.661 | 2.186 |
| c05 | 7.066 | −2.306 |
| c06 | −1.881 | 0.0835 |
| c07 | 1.058 | −0.3665 |
| c08 | 1.760 | 0.0840 |
| c09 | 3.171 | −4.345 |
| c10 | −0.6238 | −0.8961 |
| c11 | −4.113 | −0.3905 |
| c12 | −7.182 | 4.360 |
| c13 | 3.790 | −1.613 |
| c14 | 7.190 | 3.731 |
| c15 | 16.114 | 0.6794 |
| c16 | −2.335 | 0.1618 |
| c17 | 1.299 | −2.319 |
| c18 | −7.180 | 2.562 |
| c19 | −2.645 | −1.556 |
| c20 | −11.421 | 0.8916 |
| c21 | 2.651 | −0.9579 |
| c22 | −6.864 | −1.268 |
| c23 | 3.866 | 1.902 |
| c24 | −1.971 | −2.028 |
| c25 | −2.630 | 1.921 |
| c26 | −0.9221 | 0.0971 |
| c27 | −8.140 | 1.383 |
| c28 | −3.286 | −1.351 |
| c29 | 12.338 | 5.040 |
Components
| Component | Eigenvalue | Share of variance | Cumulative |
|---|---|---|---|
| 1 | 37.445 | 85.6% | 85.6% |
| 2 | 4.973 | 11.4% | 97.0% |
| 3 | 0.5241 | 1.2% | 98.2% |
| 4 | 0.2457 | 0.6% | 98.7% |
| 5 | 0.2202 | 0.5% | 99.2% |
| 6 | 0.1492 | 0.3% | 99.6% |
| 7 | 0.1027 | 0.2% | 99.8% |
| 8 | 0.0715 | 0.2% | 100.0% |
| 9 | 0.0182 | 0.0% | 100.0% |
Mean curve and eigenfunctions
| t | Mean | φ1 | φ2 | φ3 |
|---|---|---|---|---|
| 0 | 9.826 | 0.2481 | −0.3370 | 0.0991 |
| 1 | 13.744 | 0.2338 | −0.3235 | −0.0993 |
| 2 | 15.447 | 0.2407 | −0.2754 | −0.1336 |
| 3 | 16.693 | 0.2366 | −0.2632 | −0.0244 |
| 5 | 18.601 | 0.2354 | −0.2187 | −0.0417 |
| 7 | 20.240 | 0.2233 | −0.0811 | 0.0190 |
| 10 | 22.252 | 0.2294 | 0.0263 | −0.1350 |
| 14 | 24.475 | 0.2105 | 0.1633 | 0.3476 |
| 20 | 27.347 | 0.2094 | 0.3701 | −0.3131 |
Curve scores
| curve | Score 1 | Score 2 | Score 3 | Integrated squared error |
|---|---|---|---|---|
| c01 | −0.1186 | −2.409 | 0.2672 | 0.3526 |
| c02 | 5.877 | −3.001 | −0.7571 | 0.2028 |
| c03 | −6.530 | −0.2745 | −0.6255 | 0.7704 |
| c04 | 1.661 | 2.186 | −0.6921 | 1.647 |
| c05 | 7.066 | −2.306 | −0.0049 | 0.5874 |
| c06 | −1.881 | 0.0835 | −0.7798 | 0.7017 |
| c07 | 1.058 | −0.3665 | −0.3264 | 1.234 |
| c08 | 1.760 | 0.0840 | 0.4077 | 1.221 |
| c09 | 3.171 | −4.345 | −0.1991 | 0.7535 |
| c10 | −0.6238 | −0.8961 | 0.3449 | 0.6789 |
| c11 | −4.113 | −0.3905 | 0.4598 | 0.8418 |
| c12 | −7.182 | 4.360 | 0.3477 | 0.4819 |
| c13 | 3.790 | −1.613 | 0.0349 | 1.564 |
| c14 | 7.190 | 3.731 | −1.051 | 0.5183 |
| c15 | 16.114 | 0.6794 | 0.0908 | 0.3603 |
| c16 | −2.335 | 0.1618 | −1.655 | 0.7345 |
| c17 | 1.299 | −2.319 | −0.8653 | 2.206 |
| c18 | −7.180 | 2.562 | 0.1581 | 1.062 |
| c19 | −2.645 | −1.556 | 1.074 | 0.9992 |
| c20 | −11.421 | 0.8916 | −0.0843 | 0.6565 |
| c21 | 2.651 | −0.9579 | 1.488 | 0.5108 |
| c22 | −6.864 | −1.268 | 1.277 | 1.029 |
| c23 | 3.866 | 1.902 | −0.0748 | 0.3351 |
| c24 | −1.971 | −2.028 | 0.3708 | 1.159 |
| c25 | −2.630 | 1.921 | 0.4930 | 0.6117 |
| c26 | −0.9221 | 0.0971 | 0.4625 | 0.1246 |
| c27 | −8.140 | 1.383 | −0.7408 | 0.6366 |
| c28 | −3.286 | −1.351 | −0.3586 | 0.4239 |
| c29 | 12.338 | 5.040 | 0.9374 | 0.2027 |
Curves left out
| curve | Why |
|---|---|
| c30 | ends before the last time |
- 1 curve(s) don't cover the whole time range and were left out (FPCA doesn't extrapolate): c30.
- 2 grid value(s) (0.8%) were filled by straight lines between a curve's neighboring measurements.
- Integrals use the trapezoid rule on the common grid, so uneven time steps count by their length; eigenvalues are the variance of each component's scores (divisor n − 1) and each eigenfunction has ∫φ² dt = 1, signed so ∫φ dt ≥ 0.
- Read a component by its mean ± 2 SD chart: it shows how curves with a high or low score differ from the average curve.
- Phase variation (the same shape shifted in time) shows up as extra components; align the curves first when timing differences aren't of interest.
The exact R script · R R version 4.5.1 (2025-06-13)
# Functional PCA (main shapes of a set of curves)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.fpca 1.0.0 · spec d519321c0b6f6ce4
# Dataset: seq_curves (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_curves.parquet", col_select = c("curve", "t", "value")))
n_input <- nrow(df)
df[["curve"]] <- factor(df[["curve"]], levels = c("c01", "c02", "c03", "c04", "c05", "c06", "c07", "c08", "c09", "c10", "c11", "c12", "c13", "c14", "c15", "c16", "c17", "c18", "c19", "c20", "c21", "c22", "c23", "c24", "c25", "c26", "c27", "c28", "c29", "c30")) # stored level order
df <- df[stats::complete.cases(df[c("curve", "t", "value")]), , 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("curve", "t", "value")) # infinite values stop the run (registry/errors.yaml)
# %% Curves
# Functional PCA (Ramsay & Silverman 2005): curves in long form (curve, time, value) on a common grid,
# trapezoid quadrature, optional Whittaker pre-smoothing, eigenfunctions orthonormal under the integral.
CURVE <- "curve"
TIME <- "t"
VALUE <- "value"
TEMPORAL <- FALSE
Q <- as.integer(3)
SMOOTHING <- "none" # none | gcv | manual
LOG_LAMBDA <- as.numeric(-2)
cs_check_rows(nrow(df), 9, "Functional PCA")
cs_check_groups(as.character(df[[CURVE]]), CURVE, minimum = 3)
cs_check_not_constant(as.numeric(df[[VALUE]]), VALUE)
traw <- df[[TIME]]
tnum <- if (TEMPORAL) {
if (inherits(traw, "POSIXt")) as.numeric(traw) / 86400 else as.numeric(as.Date(traw))
} else as.numeric(traw)
cs_check_not_constant(tnum, TIME)
curve_levels <- as.character(levels(df[[CURVE]]))
g <- cs_fpca_grid(as.integer(df[[CURVE]]), length(curve_levels), tnum, as.numeric(df[[VALUE]]))
grid <- g$grid
Y <- g$Y
kept <- curve_levels[g$kept]
if (length(kept) < 3)
cs_error("CS_E_UNDEFINED", what = "Functional PCA", reason = sprintf("only %d curve(s) cover the whole time range (at least 3 are needed)", length(kept)))
if (length(grid) < 3)
cs_error("CS_E_UNDEFINED", what = "Functional PCA", reason = sprintf("the curves share only %d time point(s) (at least 3 are needed)", length(grid)))
if (length(grid) > 500)
cs_error("CS_E_UNDEFINED", what = "Functional PCA", reason = sprintf("the common grid has %d time points (at most 500; aggregate the times first)", length(grid)))
if (g$n_dup > 0) warnings <- c(warnings, sprintf("%d row(s) repeated a curve's time; each such point uses the mean of its values.", g$n_dup))
if (length(g$dropped)) {
dn <- vapply(g$dropped, function(dd) curve_levels[dd$code], "")
warnings <- c(warnings, paste0(sprintf("%d curve(s) don't cover the whole time range and were left out (FPCA doesn't extrapolate): ", length(dn)),
paste(head(dn, 10), collapse = ", "), if (length(dn) > 10) " …" else "", "."))
}
share_interp <- g$n_interp / (length(kept) * length(grid))
if (share_interp > 0.5)
cs_error("CS_E_UNDEFINED", what = "Functional PCA", reason = sprintf("%.0f%% of the grid values would be interpolated (curves measured at different times need sparse-data methods)", 100 * share_interp))
if (g$n_interp > 0)
warnings <- c(warnings, sprintf("%d grid value(s) (%.1f%%) were filled by straight lines between a curve's neighboring measurements.", g$n_interp, 100 * share_interp))
w <- cs_fpca_weights(grid)
values <- list(n_curves = length(kept), n_dropped_curves = length(g$dropped), n_grid = length(grid), n_interpolated = g$n_interp,
smoothing = SMOOTHING, log_lambda = NaN, edf = NaN, gcv = NaN)
Ys <- Y
if (SMOOTHING != "none") {
sm <- cs_fpca_smooth(Y, grid, w, if (SMOOTHING == "gcv") NULL else LOG_LAMBDA)
Ys <- sm$Y
values$log_lambda <- sm$log_lambda
values$edf <- sm$edf
values$gcv <- sm$gcv
}
# %% Decompose
fit <- cs_fpca_fit(Ys, w, Q)
q <- fit$q
if (q < Q) warnings <- c(warnings, sprintf("Only %d component(s) are available (the curves span %d dimension(s)); %d were requested.", q, fit$rank, Q))
ev <- fit$eigenvalues
values$components <- q
values$total_variance <- fit$total
values$explained <- sum(ev[seq_len(q)]) / fit$total
values$recon_error <- mean(fit$ise)
cum <- 0
comp_rows <- list()
for (k in seq_along(ev)) {
share <- ev[k] / fit$total
cum <- cum + share
if (k <= max(q, min(length(ev), 10))) comp_rows[[length(comp_rows) + 1]] <- list(component = k, eigenvalue = ev[k], share = share, cumulative = cum)
if (k <= q) {
values[[sprintf("eigen[%d]", k)]] <- ev[k]
values[[sprintf("share[%d]", k)]] <- share
values[[sprintf("cumulative[%d]", k)]] <- cum
values[[sprintf("phi_check[%d]", k)]] <- sum(seq_along(grid) * w * fit$phi[, k])
values[[sprintf("score_check[%d]", k)]] <- sum(seq_along(kept) * fit$scores[, k])
}
}
grid_labels <- if (TEMPORAL) format(as.Date(grid, origin = "1970-01-01"), "%Y-%m-%d") else sprintf("%.10g", grid)
# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-82309/discover.fpca/curves-uneven-grid/out-r")
artifacts <- list()
modes <- list(list(name = CURVE, levels = kept, F = fit$scores), list(name = TIME, levels = grid_labels, F = fit$phi))
for (md in modes) {
fdf <- data.frame(level = md$levels, stringsAsFactors = FALSE)
for (k in seq_len(q)) fdf[[sprintf("factor_%d", k)]] <- md$F[, k]
path <- file.path(out, sprintf("factors_%s.parquet", md$name))
nanoparquet::write_parquet(fdf, path)
artifacts[[length(artifacts) + 1]] <- list(key = sprintf("factors_%s", md$name), path = path, format = "parquet")
}
# %% Charts
xkind <- if (TEMPORAL) "temporal" else "numeric"
xvals <- if (TEMPORAL) grid_labels else grid
charts <- list(cs_chart("scree", "scree-plot", "Share of the curves' variance by component", list(
component = cs_col("Component", as.numeric(vapply(comp_rows, function(r) r$component, numeric(1)))),
variance = cs_col("Share of variance", vapply(comp_rows, function(r) r$share, numeric(1))),
cumulative = cs_col("Cumulative share", vapply(comp_rows, function(r) r$cumulative, numeric(1))))))
for (k in seq_len(min(q, 3))) {
amp <- 2 * sqrt(ev[k])
ys <- c(fit$mean, fit$mean + amp * fit$phi[, k], fit$mean - amp * fit$phi[, k])
labs <- rep(c("Mean", "Mean + 2√λ·φ", "Mean − 2√λ·φ"), each = length(grid))
charts[[length(charts) + 1]] <- cs_chart(sprintf("mode%d", k), "series-line",
sprintf("Component %d (%.0f%% of the variance): the mean curve moved by ±2 SD", k, 100 * ev[k] / fit$total), list(
x = cs_col(TIME, rep(xvals, 3), kind = xkind), y = cs_col(VALUE, ys), group = cs_col("curve", labs, kind = "categorical")))
}
if (q >= 1) {
charts[[length(charts) + 1]] <- cs_chart("eigenfunctions", "series-line", "Eigenfunctions φ(t)", list(
x = cs_col(TIME, rep(xvals, q), kind = xkind), y = cs_col("φ", as.vector(fit$phi)),
group = cs_col("component", rep(sprintf("φ%d", seq_len(q)), each = length(grid)), kind = "categorical")))
}
if (q >= 2) {
charts[[length(charts) + 1]] <- cs_chart("scores", "embedding-map", "Curve scores on the first two components", list(
x = cs_col("Score 1", fit$scores[, 1]), y = cs_col("Score 2", fit$scores[, 2]), label = cs_col(CURVE, kept, kind = "categorical")))
}
# %% Tables
tables <- list(
list(key = "components", title = "Components",
columns = list(list(key = "component", label = "Component", type = "integer"), list(key = "eigenvalue", label = "Eigenvalue", type = "number"),
list(key = "share", label = "Share of variance", type = "percent"), list(key = "cumulative", label = "Cumulative", type = "percent")),
rows = comp_rows),
list(key = "functions", title = "Mean curve and eigenfunctions",
columns = c(list(list(key = "time", label = TIME, type = "string"), list(key = "mean", label = "Mean", type = "number")),
lapply(seq_len(q), function(k) list(key = sprintf("phi%d", k), label = sprintf("φ%d", k), type = "number"))),
rows = lapply(seq_along(grid), function(j) c(list(time = grid_labels[j], mean = fit$mean[j]),
stats::setNames(as.list(fit$phi[j, seq_len(q)]), sprintf("phi%d", seq_len(q)))))),
list(key = "scores", title = "Curve scores",
columns = c(list(list(key = "curve", label = CURVE, type = "string")),
lapply(seq_len(q), function(k) list(key = sprintf("s%d", k), label = sprintf("Score %d", k), type = "number")),
list(list(key = "ise", label = "Integrated squared error", type = "number"))),
rows = lapply(seq_along(kept), function(i) c(list(curve = kept[i]), stats::setNames(as.list(fit$scores[i, seq_len(q)]), sprintf("s%d", seq_len(q))),
list(ise = fit$ise[i])))))
if (length(g$dropped)) {
tables[[length(tables) + 1]] <- list(key = "dropped", title = "Curves left out",
columns = list(list(key = "curve", label = CURVE, type = "string"), list(key = "reason", label = "Why", type = "string")),
rows = lapply(g$dropped, function(dd) list(curve = curve_levels[dd$code], reason = dd$reason)))
}
# %% Result
summary <- paste0(sprintf("Functional PCA of %d curves of %s on %d time points: the first %d component%s explain %.1f%% of the variance between curves",
length(kept), VALUE, length(grid), q, if (q != 1) "s" else "", 100 * values$explained),
if (q > 1) sprintf(" (component 1 alone %.1f%%)", 100 * ev[1] / fit$total) else "", ".")
notes <- c(paste0("Integrals use the trapezoid rule on the common grid, so uneven time steps count by their length; eigenvalues are the variance of each ",
"component's scores (divisor n − 1) and each eigenfunction has ∫φ² dt = 1, signed so ∫φ dt ≥ 0."),
"Read a component by its mean ± 2 SD chart: it shows how curves with a high or low score differ from the average curve.")
if (SMOOTHING != "none") {
notes <- c(notes, paste0(sprintf("Curves were smoothed first with a second-difference penalty (λ = 10^%.2f relative to the grid, %.2f effective degrees of freedom of %d",
values$log_lambda, values$edf, length(grid)),
if (SMOOTHING == "gcv") "; chosen by generalized cross-validation" else "", ")."))
}
notes <- c(notes, "Phase variation (the same shape shifted in time) shows up as extra components; align the curves first when timing differences aren't of interest.")
cs_publish(list(
title = "Functional PCA (main shapes of a set of curves)",
engine = cs_engine_info("nanoparquet"),
n = length(kept),
summary = summary,
statistics = list(list(key = "explained", label = sprintf("Variance explained by %d components", q), value = values$explained),
list(key = "recon_error", label = "Mean integrated squared error", value = values$recon_error)),
tables = tables,
charts = charts,
values = values,
warnings = warnings,
notes = notes,
artifacts = artifacts
))
Functional PCA of 29 curves of value on 9 time points: the first 3 components explain 98.2% of the variance between curves (component 1 alone 85.6%).
- Variance explained by 3 components
- 0.9815
- Mean integrated squared error
- 0.7796
To keep this page light, the plots are shown once, under the R tab.
Components
| Component | Eigenvalue | Share of variance | Cumulative |
|---|---|---|---|
| 1 | 37.445 | 85.6% | 85.6% |
| 2 | 4.973 | 11.4% | 97.0% |
| 3 | 0.5241 | 1.2% | 98.2% |
| 4 | 0.2457 | 0.6% | 98.7% |
| 5 | 0.2202 | 0.5% | 99.2% |
| 6 | 0.1492 | 0.3% | 99.6% |
| 7 | 0.1027 | 0.2% | 99.8% |
| 8 | 0.0715 | 0.2% | 100.0% |
| 9 | 0.0182 | 0.0% | 100.0% |
Mean curve and eigenfunctions
| t | Mean | φ1 | φ2 | φ3 |
|---|---|---|---|---|
| 0 | 9.826 | 0.2481 | −0.3370 | 0.0991 |
| 1 | 13.744 | 0.2338 | −0.3235 | −0.0993 |
| 2 | 15.447 | 0.2407 | −0.2754 | −0.1336 |
| 3 | 16.693 | 0.2366 | −0.2632 | −0.0244 |
| 5 | 18.601 | 0.2354 | −0.2187 | −0.0417 |
| 7 | 20.240 | 0.2233 | −0.0811 | 0.0190 |
| 10 | 22.252 | 0.2294 | 0.0263 | −0.1350 |
| 14 | 24.475 | 0.2105 | 0.1633 | 0.3476 |
| 20 | 27.347 | 0.2094 | 0.3701 | −0.3131 |
Curve scores
| curve | Score 1 | Score 2 | Score 3 | Integrated squared error |
|---|---|---|---|---|
| c01 | −0.1186 | −2.409 | 0.2672 | 0.3526 |
| c02 | 5.877 | −3.001 | −0.7571 | 0.2028 |
| c03 | −6.530 | −0.2745 | −0.6255 | 0.7704 |
| c04 | 1.661 | 2.186 | −0.6921 | 1.647 |
| c05 | 7.066 | −2.306 | −0.0049 | 0.5874 |
| c06 | −1.881 | 0.0835 | −0.7798 | 0.7017 |
| c07 | 1.058 | −0.3665 | −0.3264 | 1.234 |
| c08 | 1.760 | 0.0840 | 0.4077 | 1.221 |
| c09 | 3.171 | −4.345 | −0.1991 | 0.7535 |
| c10 | −0.6238 | −0.8961 | 0.3449 | 0.6789 |
| c11 | −4.113 | −0.3905 | 0.4598 | 0.8418 |
| c12 | −7.182 | 4.360 | 0.3477 | 0.4819 |
| c13 | 3.790 | −1.613 | 0.0349 | 1.564 |
| c14 | 7.190 | 3.731 | −1.051 | 0.5183 |
| c15 | 16.114 | 0.6794 | 0.0908 | 0.3603 |
| c16 | −2.335 | 0.1618 | −1.655 | 0.7345 |
| c17 | 1.299 | −2.319 | −0.8653 | 2.206 |
| c18 | −7.180 | 2.562 | 0.1581 | 1.062 |
| c19 | −2.645 | −1.556 | 1.074 | 0.9992 |
| c20 | −11.421 | 0.8916 | −0.0843 | 0.6565 |
| c21 | 2.651 | −0.9579 | 1.488 | 0.5108 |
| c22 | −6.864 | −1.268 | 1.277 | 1.029 |
| c23 | 3.866 | 1.902 | −0.0748 | 0.3351 |
| c24 | −1.971 | −2.028 | 0.3708 | 1.159 |
| c25 | −2.630 | 1.921 | 0.4930 | 0.6117 |
| c26 | −0.9221 | 0.0971 | 0.4625 | 0.1246 |
| c27 | −8.140 | 1.383 | −0.7408 | 0.6366 |
| c28 | −3.286 | −1.351 | −0.3586 | 0.4239 |
| c29 | 12.338 | 5.040 | 0.9374 | 0.2027 |
Curves left out
| curve | Why |
|---|---|
| c30 | ends before the last time |
- 1 curve(s) don't cover the whole time range and were left out (FPCA doesn't extrapolate): c30.
- 2 grid value(s) (0.8%) were filled by straight lines between a curve's neighboring measurements.
- Integrals use the trapezoid rule on the common grid, so uneven time steps count by their length; eigenvalues are the variance of each component's scores (divisor n − 1) and each eigenfunction has ∫φ² dt = 1, signed so ∫φ dt ≥ 0.
- Read a component by its mean ± 2 SD chart: it shows how curves with a high or low score differ from the average curve.
- Phase variation (the same shape shifted in time) shows up as extra components; align the curves first when timing differences aren't of interest.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Functional PCA (main shapes of a set of curves)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.fpca 1.0.0 · spec d519321c0b6f6ce4
# Dataset: seq_curves (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.errors import check_groups, check_not_constant
from codesplash import ml as csml
from codesplash.ml import fpca
from codesplash.stats import ts
# %% Data
df = pd.read_parquet("tests/parity/fixtures/seq_curves.parquet", columns=["curve", "t", "value"])
n_input = len(df)
df["curve"] = pd.Categorical(df["curve"], categories=["c01", "c02", "c03", "c04", "c05", "c06", "c07", "c08", "c09", "c10", "c11", "c12", "c13", "c14", "c15", "c16", "c17", "c18", "c19", "c20", "c21", "c22", "c23", "c24", "c25", "c26", "c27", "c28", "c29", "c30"]) # stored level order
df = df.dropna(subset=["curve", "t", "value"]) # listwise deletion over the analysis columns
df["curve"] = df["curve"].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, ["curve", "t", "value"]) # infinite values stop the run (registry/errors.yaml)
# %% Curves
# Functional PCA (Ramsay & Silverman 2005): curves in long form (curve, time, value) on a common grid,
# trapezoid quadrature, optional Whittaker pre-smoothing, eigenfunctions orthonormal under ∫φ_j φ_k dt.
CURVE = "curve"
TIME = "t"
VALUE = "value"
TEMPORAL = False
Q = int(3)
SMOOTHING = "none" # none | gcv | manual
LOG_LAMBDA = float(-2)
cs.check_rows(len(df), 9, "Functional PCA")
check_groups(df[CURVE].astype(str), CURVE, minimum=3)
check_not_constant(df[VALUE].to_numpy(dtype=float), VALUE)
if TEMPORAL:
tnum = ((pd.to_datetime(df[TIME]) - pd.Timestamp("1970-01-01")) / pd.Timedelta(days=1)).to_numpy(dtype=float)
else:
tnum = df[TIME].to_numpy(dtype=float)
check_not_constant(tnum, TIME)
curve_levels = [str(v) for v in df[CURVE].cat.categories]
g = fpca.to_grid(df[CURVE].cat.codes.to_numpy(), len(curve_levels), tnum, df[VALUE].to_numpy(dtype=float))
grid, Y = g["grid"], g["Y"]
kept = [curve_levels[c] for c in g["kept"]]
if len(kept) < 3:
cs.cs_error("CS_E_UNDEFINED", what="Functional PCA", reason=f"only {len(kept)} curve(s) cover the whole time range (at least 3 are needed)")
if len(grid) < 3:
cs.cs_error("CS_E_UNDEFINED", what="Functional PCA", reason=f"the curves share only {len(grid)} time point(s) (at least 3 are needed)")
if len(grid) > 500:
cs.cs_error("CS_E_UNDEFINED", what="Functional PCA", reason=f"the common grid has {len(grid)} time points (at most 500; aggregate the times first)")
if g["n_dup"]:
warnings.append(f"{g['n_dup']} row(s) repeated a curve's time; each such point uses the mean of its values.")
if g["dropped"]:
warnings.append(f"{len(g['dropped'])} curve(s) don't cover the whole time range and were left out (FPCA doesn't extrapolate): "
+ ", ".join(curve_levels[c] for c, _ in g["dropped"][:10]) + (" …" if len(g["dropped"]) > 10 else "") + ".")
share_interp = g["n_interp"] / (len(kept) * len(grid))
if share_interp > 0.5:
cs.cs_error("CS_E_UNDEFINED", what="Functional PCA", reason=f"{share_interp:.0%} of the grid values would be interpolated (curves measured at different times need sparse-data methods)")
if g["n_interp"]:
warnings.append(f"{g['n_interp']} grid value(s) ({share_interp:.1%}) were filled by straight lines between a curve's neighboring measurements.")
w = fpca.trapezoid_weights(grid)
values = {"n_curves": len(kept), "n_dropped_curves": len(g["dropped"]), "n_grid": len(grid), "n_interpolated": g["n_interp"],
"smoothing": SMOOTHING, "log_lambda": float("nan"), "edf": float("nan"), "gcv": float("nan")}
Ys = Y
if SMOOTHING != "none":
sm = fpca.smooth(Y, grid, w, None if SMOOTHING == "gcv" else LOG_LAMBDA)
Ys = sm["Y"]
values.update({"log_lambda": sm["log_lambda"], "edf": sm["edf"], "gcv": sm["gcv"]})
# %% Decompose
fit = fpca.fit(Ys, w, Q)
q = fit["q"]
if q < Q:
warnings.append(f"Only {q} component(s) are available (the curves span {fit['rank']} dimension(s)); {Q} were requested.")
ev = fit["eigenvalues"]
values.update({"components": q, "total_variance": fit["total"], "explained": float(np.sum(ev[:q]) / fit["total"]),
"recon_error": float(np.mean(fit["ise"]))})
cum = 0.0
comp_rows = []
for k in range(len(ev)):
share = float(ev[k] / fit["total"])
cum += share
if k < max(q, min(len(ev), 10)):
comp_rows.append({"component": k + 1, "eigenvalue": float(ev[k]), "share": share, "cumulative": cum})
if k < q:
values[f"eigen[{k + 1}]"] = float(ev[k])
values[f"share[{k + 1}]"] = share
values[f"cumulative[{k + 1}]"] = cum
values[f"phi_check[{k + 1}]"] = float(np.sum(np.arange(1, len(grid) + 1) * w * fit["phi"][:, k]))
values[f"score_check[{k + 1}]"] = float(np.sum(np.arange(1, len(kept) + 1) * fit["scores"][:, k]))
grid_labels = ts.time_labels(pd.to_datetime(grid, unit="D").to_numpy(), True) if TEMPORAL else ["%.10g" % v for v in grid]
# %% Artifacts
out = csml.out_dir("target/academy-parity/run-82309/discover.fpca/curves-uneven-grid/out-python")
artifacts = []
for name, levels_, F in ((CURVE, kept, fit["scores"]), (TIME, grid_labels, fit["phi"])):
fdf = pd.DataFrame({"level": levels_})
for k in range(q):
fdf[f"factor_{k + 1}"] = F[:, k]
path = os.path.join(out, f"factors_{name}.parquet")
fdf.to_parquet(path, index=False)
artifacts.append({"key": f"factors_{name}", "path": path, "format": "parquet"})
# %% Charts
xkind = "temporal" if TEMPORAL else "numeric"
xvals = grid_labels if TEMPORAL else grid.tolist()
charts = [cs.chart("scree", "scree-plot", "Share of the curves' variance by component", {
"component": cs.col("Component", np.array([r["component"] for r in comp_rows], dtype=float)),
"variance": cs.col("Share of variance", np.array([r["share"] for r in comp_rows])),
"cumulative": cs.col("Cumulative share", np.array([r["cumulative"] for r in comp_rows]))})]
for k in range(min(q, 3)):
amp = 2.0 * np.sqrt(ev[k])
lines = [("Mean", fit["mean"]), ("Mean + 2√λ·φ", fit["mean"] + amp * fit["phi"][:, k]), ("Mean − 2√λ·φ", fit["mean"] - amp * fit["phi"][:, k])]
charts.append(cs.chart(f"mode{k + 1}", "series-line", f"Component {k + 1} ({ev[k] / fit['total']:.0%} of the variance): the mean curve moved by ±2 SD", {
"x": cs.col(TIME, [v for _ in lines for v in xvals], kind=xkind),
"y": cs.col(VALUE, np.concatenate([y for _, y in lines])),
"group": cs.col("curve", [lab for lab, _ in lines for _ in xvals], kind="categorical")}))
if q >= 1:
charts.append(cs.chart("eigenfunctions", "series-line", "Eigenfunctions φ(t)", {
"x": cs.col(TIME, [v for _ in range(q) for v in xvals], kind=xkind),
"y": cs.col("φ", fit["phi"].T.reshape(-1)),
"group": cs.col("component", [f"φ{k + 1}" for k in range(q) for _ in xvals], kind="categorical")}))
if q >= 2:
charts.append(cs.chart("scores", "embedding-map", "Curve scores on the first two components", {
"x": cs.col("Score 1", fit["scores"][:, 0]), "y": cs.col("Score 2", fit["scores"][:, 1]),
"label": cs.col(CURVE, kept, kind="categorical")}))
# %% Tables
tables = [{"key": "components", "title": "Components",
"columns": [{"key": "component", "label": "Component", "type": "integer"}, {"key": "eigenvalue", "label": "Eigenvalue", "type": "number"},
{"key": "share", "label": "Share of variance", "type": "percent"}, {"key": "cumulative", "label": "Cumulative", "type": "percent"}],
"rows": comp_rows},
{"key": "functions", "title": "Mean curve and eigenfunctions",
"columns": [{"key": "time", "label": TIME, "type": "string"}, {"key": "mean", "label": "Mean", "type": "number"}]
+ [{"key": f"phi{k + 1}", "label": f"φ{k + 1}", "type": "number"} for k in range(q)],
"rows": [{"time": grid_labels[j], "mean": float(fit["mean"][j]), **{f"phi{k + 1}": float(fit["phi"][j, k]) for k in range(q)}} for j in range(len(grid))]},
{"key": "scores", "title": "Curve scores",
"columns": [{"key": "curve", "label": CURVE, "type": "string"}] + [{"key": f"s{k + 1}", "label": f"Score {k + 1}", "type": "number"} for k in range(q)]
+ [{"key": "ise", "label": "Integrated squared error", "type": "number"}],
"rows": [{"curve": kept[i], **{f"s{k + 1}": float(fit["scores"][i, k]) for k in range(q)}, "ise": float(fit["ise"][i])} for i in range(len(kept))]}]
if g["dropped"]:
tables.append({"key": "dropped", "title": "Curves left out",
"columns": [{"key": "curve", "label": CURVE, "type": "string"}, {"key": "reason", "label": "Why", "type": "string"}],
"rows": [{"curve": curve_levels[c], "reason": why} for c, why in g["dropped"]]})
# %% Result
summary = (f"Functional PCA of {len(kept)} curves of {VALUE} on {len(grid)} time points: the first {q} component{'s' if q != 1 else ''} "
f"explain {values['explained']:.1%} of the variance between curves"
+ (f" (component 1 alone {ev[0] / fit['total']:.1%})" if q > 1 else "") + ".")
notes = ["Integrals use the trapezoid rule on the common grid, so uneven time steps count by their length; eigenvalues are the variance of each "
"component's scores (divisor n − 1) and each eigenfunction has ∫φ² dt = 1, signed so ∫φ dt ≥ 0.",
"Read a component by its mean ± 2 SD chart: it shows how curves with a high or low score differ from the average curve."]
if SMOOTHING != "none":
notes.append(f"Curves were smoothed first with a second-difference penalty (λ = 10^{values['log_lambda']:.2f} relative to the grid, "
f"{values['edf']:.2f} effective degrees of freedom of {len(grid)}" + ("; chosen by generalized cross-validation" if SMOOTHING == "gcv" else "") + ").")
notes.append("Phase variation (the same shape shifted in time) shows up as extra components; align the curves first when timing differences aren't of interest.")
cs.publish({
"title": "Functional PCA (main shapes of a set of curves)",
"engine": cs.engine_info("numpy", "pandas"),
"n": len(kept),
"summary": summary,
"statistics": [{"key": "explained", "label": f"Variance explained by {q} components", "value": values["explained"]},
{"key": "recon_error", "label": "Mean integrated squared error", "value": values["recon_error"]}],
"tables": tables,
"charts": charts,
"values": values,
"warnings": warnings,
"notes": notes,
"artifacts": artifacts,
})
These curves were measured at 0, 1, 2, 3, 5, 7, 10, 14 and 20. 2 interior values were missing and filled by straight lines between neighboring measurements, and one curve that ended early was left out. If most values had to be filled (curves measured at different times), sparse-data methods would be needed instead.
Predict: stretching time
PredictPredict first
You redo the analysis with time measured in half-days instead of days, so every time value doubles. What happens to the eigenvalues?
Reveal
They double. Each eigenvalue is a variance of ∫(curve − mean)·φ dt, and the integral is over a time axis twice as long.
Signals: features that don't move
ReadVibration, sensor and audio-like signals are long and wiggly, and the same event can happen at any moment. 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. builds fixed features with no training:
- Order 0: the mean.
- Order 1: filter with Morlet waveletsMorlet waveletA wave inside a Gaussian envelope: in frequency, a bump at its center frequency corrected to have zero mean. at several frequencies, take the modulus and average it over the whole signal. That is the energy per frequency band, like a spectrum on a log-frequency scale.
- Order 2: filter each order-1 modulus again with coarser wavelets and average. That measures how each band's amplitude is modulated, which order 1 averages away.
Because everything is averaged over the whole signal, shifting a signal in time leaves the coefficients unchanged.
Two kinds of modulation
ReadEach of these 24 signals has its own carrier frequency, so their band energies overlap. In class "slow" the amplitude swells and fades slowly, in class "fast" twice as often.
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
| Order | Wavelet | Center frequency (cycles per step) | Period (steps) | Bandwidth σ |
|---|---|---|---|---|
| 1 | 1 | 0.3500 | 2.857 | 0.0334 |
| 1 | 2 | 0.2943 | 3.398 | 0.0281 |
| 1 | 3 | 0.2475 | 4.041 | 0.0236 |
| 1 | 4 | 0.2081 | 4.805 | 0.0199 |
| 1 | 5 | 0.1750 | 5.714 | 0.0167 |
| 1 | 6 | 0.1472 | 6.795 | 0.0141 |
| 1 | 7 | 0.1237 | 8.081 | 0.0118 |
| 1 | 8 | 0.1041 | 9.610 | 0.0099 |
| 1 | 9 | 0.0875 | 11.429 | 0.0084 |
| 1 | 10 | 0.0736 | 13.591 | 0.0070 |
| 1 | 11 | 0.0619 | 16.162 | 0.0059 |
| 1 | 12 | 0.0520 | 19.220 | 0.0050 |
| 1 | 13 | 0.0437 | 22.857 | 0.0042 |
| 1 | 14 | 0.0368 | 27.182 | 0.0035 |
| 1 | 15 | 0.0309 | 32.325 | 0.0030 |
| 1 | 16 | 0.0260 | 38.441 | 0.0025 |
| 1 | 17 | 0.0219 | 45.714 | 0.0021 |
| 1 | 18 | 0.0184 | 54.364 | 0.0018 |
| 1 | 19 | 0.0155 | 64.650 | 0.0015 |
| 1 | 20 | 0.0130 | 76.882 | 0.0012 |
| 2 | 1 | 0.3500 | 2.857 | 0.1051 |
| 2 | 2 | 0.1750 | 5.714 | 0.0525 |
| 2 | 3 | 0.0875 | 11.429 | 0.0263 |
| 2 | 4 | 0.0437 | 22.857 | 0.0131 |
| 2 | 5 | 0.0219 | 45.714 | 0.0066 |
Scattering coefficients
| series | Order | Path | Coefficient |
|---|---|---|---|
| s01 | 0 | mean | 0.0135 |
| s01 | 1 | period 2.86 | 0.0177 |
| s01 | 1 | period 3.4 | 0.0189 |
| s01 | 1 | period 4.04 | 0.0216 |
| s01 | 1 | period 4.81 | 0.0242 |
| s01 | 1 | period 5.71 | 0.0457 |
| s01 | 1 | period 6.8 | 0.1892 |
| s01 | 1 | period 8.08 | 0.2908 |
| s01 | 1 | period 9.61 | 0.3396 |
| s01 | 1 | period 11.4 | 0.1052 |
| s01 | 1 | period 13.6 | 0.1583 |
| s01 | 1 | period 16.2 | 0.0582 |
| s01 | 1 | period 19.2 | 0.0476 |
| s01 | 1 | period 22.9 | 0.0476 |
| s01 | 1 | period 27.2 | 0.0400 |
| s01 | 1 | period 32.3 | 0.0253 |
| s01 | 1 | period 38.4 | 0.0406 |
| s01 | 1 | period 45.7 | 0.0176 |
| s01 | 1 | period 54.4 | 0.0266 |
| s01 | 1 | period 64.6 | 0.0051 |
| s01 | 1 | period 76.9 | 0.0152 |
| s01 | 2 | period 2.86 → 5.71 | 0.0163 |
| s01 | 2 | period 2.86 → 11.4 | 0.0773 |
| s01 | 2 | period 2.86 → 22.9 | 0.1905 |
| s01 | 2 | period 2.86 → 45.7 | 0.1491 |
| s01 | 2 | period 3.4 → 5.71 | 0.0179 |
| s01 | 2 | period 3.4 → 11.4 | 0.0783 |
| s01 | 2 | period 3.4 → 22.9 | 0.1493 |
| s01 | 2 | period 3.4 → 45.7 | 0.2774 |
| s01 | 2 | period 4.04 → 5.71 | 0.0115 |
| s01 | 2 | period 4.04 → 11.4 | 0.0564 |
| s01 | 2 | period 4.04 → 22.9 | 0.1719 |
| s01 | 2 | period 4.04 → 45.7 | 0.1487 |
| s01 | 2 | period 4.81 → 5.71 | 0.0054 |
| s01 | 2 | period 4.81 → 11.4 | 0.0256 |
| s01 | 2 | period 4.81 → 22.9 | 0.1192 |
| s01 | 2 | period 4.81 → 45.7 | 0.2561 |
| s01 | 2 | period 5.71 → 11.4 | 0.0454 |
| s01 | 2 | period 5.71 → 22.9 | 0.1422 |
| s01 | 2 | period 5.71 → 45.7 | 0.2505 |
First 40 of 50 rows.
Leave-one-out 1-nearest-neighbor probe
| Features | Number | Accuracy |
|---|---|---|
| Order 0–1 | 21 | 87.5% |
| Order 0–2 | 61 | 91.7% |
| Always the most common class | 0 | 50.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
))
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
| Order | Wavelet | Center frequency (cycles per step) | Period (steps) | Bandwidth σ |
|---|---|---|---|---|
| 1 | 1 | 0.3500 | 2.857 | 0.0334 |
| 1 | 2 | 0.2943 | 3.398 | 0.0281 |
| 1 | 3 | 0.2475 | 4.041 | 0.0236 |
| 1 | 4 | 0.2081 | 4.805 | 0.0199 |
| 1 | 5 | 0.1750 | 5.714 | 0.0167 |
| 1 | 6 | 0.1472 | 6.795 | 0.0141 |
| 1 | 7 | 0.1237 | 8.081 | 0.0118 |
| 1 | 8 | 0.1041 | 9.610 | 0.0099 |
| 1 | 9 | 0.0875 | 11.429 | 0.0084 |
| 1 | 10 | 0.0736 | 13.591 | 0.0070 |
| 1 | 11 | 0.0619 | 16.162 | 0.0059 |
| 1 | 12 | 0.0520 | 19.220 | 0.0050 |
| 1 | 13 | 0.0437 | 22.857 | 0.0042 |
| 1 | 14 | 0.0368 | 27.182 | 0.0035 |
| 1 | 15 | 0.0309 | 32.325 | 0.0030 |
| 1 | 16 | 0.0260 | 38.441 | 0.0025 |
| 1 | 17 | 0.0219 | 45.714 | 0.0021 |
| 1 | 18 | 0.0184 | 54.364 | 0.0018 |
| 1 | 19 | 0.0155 | 64.650 | 0.0015 |
| 1 | 20 | 0.0130 | 76.882 | 0.0012 |
| 2 | 1 | 0.3500 | 2.857 | 0.1051 |
| 2 | 2 | 0.1750 | 5.714 | 0.0525 |
| 2 | 3 | 0.0875 | 11.429 | 0.0263 |
| 2 | 4 | 0.0437 | 22.857 | 0.0131 |
| 2 | 5 | 0.0219 | 45.714 | 0.0066 |
Scattering coefficients
| series | Order | Path | Coefficient |
|---|---|---|---|
| s01 | 0 | mean | 0.0135 |
| s01 | 1 | period 2.86 | 0.0177 |
| s01 | 1 | period 3.4 | 0.0189 |
| s01 | 1 | period 4.04 | 0.0216 |
| s01 | 1 | period 4.81 | 0.0242 |
| s01 | 1 | period 5.71 | 0.0457 |
| s01 | 1 | period 6.8 | 0.1892 |
| s01 | 1 | period 8.08 | 0.2908 |
| s01 | 1 | period 9.61 | 0.3396 |
| s01 | 1 | period 11.4 | 0.1052 |
| s01 | 1 | period 13.6 | 0.1583 |
| s01 | 1 | period 16.2 | 0.0582 |
| s01 | 1 | period 19.2 | 0.0476 |
| s01 | 1 | period 22.9 | 0.0476 |
| s01 | 1 | period 27.2 | 0.0400 |
| s01 | 1 | period 32.3 | 0.0253 |
| s01 | 1 | period 38.4 | 0.0406 |
| s01 | 1 | period 45.7 | 0.0176 |
| s01 | 1 | period 54.4 | 0.0266 |
| s01 | 1 | period 64.6 | 0.0051 |
| s01 | 1 | period 76.9 | 0.0152 |
| s01 | 2 | period 2.86 → 5.71 | 0.0163 |
| s01 | 2 | period 2.86 → 11.4 | 0.0773 |
| s01 | 2 | period 2.86 → 22.9 | 0.1905 |
| s01 | 2 | period 2.86 → 45.7 | 0.1491 |
| s01 | 2 | period 3.4 → 5.71 | 0.0179 |
| s01 | 2 | period 3.4 → 11.4 | 0.0783 |
| s01 | 2 | period 3.4 → 22.9 | 0.1493 |
| s01 | 2 | period 3.4 → 45.7 | 0.2774 |
| s01 | 2 | period 4.04 → 5.71 | 0.0115 |
| s01 | 2 | period 4.04 → 11.4 | 0.0564 |
| s01 | 2 | period 4.04 → 22.9 | 0.1719 |
| s01 | 2 | period 4.04 → 45.7 | 0.1487 |
| s01 | 2 | period 4.81 → 5.71 | 0.0054 |
| s01 | 2 | period 4.81 → 11.4 | 0.0256 |
| s01 | 2 | period 4.81 → 22.9 | 0.1192 |
| s01 | 2 | period 4.81 → 45.7 | 0.2561 |
| s01 | 2 | period 5.71 → 11.4 | 0.0454 |
| s01 | 2 | period 5.71 → 22.9 | 0.1422 |
| s01 | 2 | period 5.71 → 45.7 | 0.2505 |
First 40 of 50 rows.
Leave-one-out 1-nearest-neighbor probe
| Features | Number | Accuracy |
|---|---|---|
| Order 0–1 | 21 | 87.5% |
| Order 0–2 | 61 | 91.7% |
| Always the most common class | 0 | 50.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.
A nearest-neighbor probeNearest-neighbor probePredicts each series' class from its nearest other series in feature space: how much class information the features carry. predicts each series' class from its closest other series. Order 0–1 features get 0.88 right; adding order 2 gives 0.92. Chance is 0.50. The classes differ in their modulation, which is exactly what order 2 measures.
Wrapping around
ReadScattering transform of 24 series of x (128 values): 40 first-order and 0 second-order coefficients per series over 5 octaves (8 wavelets per octave).
- Coefficients per series
- 41
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
| Order | Wavelet | Center frequency (cycles per step) | Period (steps) | Bandwidth σ |
|---|---|---|---|---|
| 1 | 1 | 0.3500 | 2.857 | 0.0174 |
| 1 | 2 | 0.3210 | 3.116 | 0.0160 |
| 1 | 3 | 0.2943 | 3.398 | 0.0147 |
| 1 | 4 | 0.2699 | 3.705 | 0.0135 |
| 1 | 5 | 0.2475 | 4.041 | 0.0123 |
| 1 | 6 | 0.2269 | 4.406 | 0.0113 |
| 1 | 7 | 0.2081 | 4.805 | 0.0104 |
| 1 | 8 | 0.1908 | 5.240 | 0.0095 |
| 1 | 9 | 0.1750 | 5.714 | 0.0087 |
| 1 | 10 | 0.1605 | 6.231 | 0.0080 |
| 1 | 11 | 0.1472 | 6.795 | 0.0073 |
| 1 | 12 | 0.1349 | 7.411 | 0.0067 |
| 1 | 13 | 0.1237 | 8.081 | 0.0062 |
| 1 | 14 | 0.1135 | 8.813 | 0.0057 |
| 1 | 15 | 0.1041 | 9.610 | 0.0052 |
| 1 | 16 | 0.0954 | 10.480 | 0.0048 |
| 1 | 17 | 0.0875 | 11.429 | 0.0044 |
| 1 | 18 | 0.0802 | 12.463 | 0.0040 |
| 1 | 19 | 0.0736 | 13.591 | 0.0037 |
| 1 | 20 | 0.0675 | 14.821 | 0.0034 |
| 1 | 21 | 0.0619 | 16.162 | 0.0031 |
| 1 | 22 | 0.0567 | 17.625 | 0.0028 |
| 1 | 23 | 0.0520 | 19.220 | 0.0026 |
| 1 | 24 | 0.0477 | 20.960 | 0.0024 |
| 1 | 25 | 0.0437 | 22.857 | 0.0022 |
| 1 | 26 | 0.0401 | 24.926 | 0.0020 |
| 1 | 27 | 0.0368 | 27.182 | 0.0018 |
| 1 | 28 | 0.0337 | 29.642 | 0.0017 |
| 1 | 29 | 0.0309 | 32.325 | 0.0015 |
| 1 | 30 | 0.0284 | 35.251 | 0.0014 |
| 1 | 31 | 0.0260 | 38.441 | 0.0013 |
| 1 | 32 | 0.0239 | 41.920 | 0.0012 |
| 1 | 33 | 0.0219 | 45.714 | 0.0011 |
| 1 | 34 | 0.0201 | 49.852 | 0.0010 |
| 1 | 35 | 0.0184 | 54.364 | 0.0009 |
| 1 | 36 | 0.0169 | 59.284 | 0.0008 |
| 1 | 37 | 0.0155 | 64.650 | 0.0008 |
| 1 | 38 | 0.0142 | 70.501 | 0.0007 |
| 1 | 39 | 0.0130 | 76.882 | 0.0006 |
| 1 | 40 | 0.0119 | 83.840 | 0.0006 |
Scattering coefficients
| series | Order | Path | Coefficient |
|---|---|---|---|
| s01 | 0 | mean | 0.0135 |
| s01 | 1 | period 2.86 | 0.0142 |
| s01 | 1 | period 3.12 | 0.0131 |
| s01 | 1 | period 3.4 | 0.0160 |
| s01 | 1 | period 3.71 | 0.0186 |
| s01 | 1 | period 4.04 | 0.0140 |
| s01 | 1 | period 4.41 | 0.0168 |
| s01 | 1 | period 4.81 | 0.0187 |
| s01 | 1 | period 5.24 | 0.0168 |
| s01 | 1 | period 5.71 | 0.0151 |
| s01 | 1 | period 6.23 | 0.0306 |
| s01 | 1 | period 6.8 | 0.1267 |
| s01 | 1 | period 7.41 | 0.1281 |
| s01 | 1 | period 8.08 | 0.0708 |
| s01 | 1 | period 8.81 | 0.3732 |
| s01 | 1 | period 9.61 | 0.2865 |
| s01 | 1 | period 10.5 | 0.0274 |
| s01 | 1 | period 11.4 | 0.0309 |
| s01 | 1 | period 12.5 | 0.1821 |
| s01 | 1 | period 13.6 | 0.0977 |
| s01 | 1 | period 14.8 | 0.0172 |
| s01 | 1 | period 16.2 | 0.0216 |
| s01 | 1 | period 17.6 | 0.0105 |
| s01 | 1 | period 19.2 | 0.0081 |
| s01 | 1 | period 21 | 0.0137 |
| s01 | 1 | period 22.9 | 0.0052 |
| s01 | 1 | period 24.9 | 0.0089 |
| s01 | 1 | period 27.2 | 0.0048 |
| s01 | 1 | period 29.6 | 0.0021 |
| s01 | 1 | period 32.3 | 0.0063 |
| s01 | 1 | period 35.3 | 0.0008 |
| s01 | 1 | period 38.4 | 0.0011 |
| s01 | 1 | period 41.9 | 0.0074 |
| s01 | 1 | period 45.7 | 0.0028 |
| s01 | 1 | period 49.9 | 2.615e-5 |
| s01 | 1 | period 54.4 | 6.068e-5 |
| s01 | 1 | period 59.3 | 0.0019 |
| s01 | 1 | period 64.6 | 0.0057 |
| s01 | 1 | period 70.5 | 0.0007 |
| s01 | 1 | period 76.9 | 1.673e-6 |
First 40 of 50 rows.
- 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; convolutions wrap around the ends (periodic).
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 375139667bcf17f0
# 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")))
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 <- df[stats::complete.cases(df[c("x", "series", "step")]), , 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")) # 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 <- NULL
TEMPORAL <- FALSE
OCTAVES <- as.integer(0)
QPO <- as.integer(8)
ORDER <- as.integer(1)
NORMALIZE <- TRUE
PAD <- "periodic"
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
))
Scattering transform of 24 series of x (128 values): 40 first-order and 0 second-order coefficients per series over 5 octaves (8 wavelets per octave).
- Coefficients per series
- 41
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
| Order | Wavelet | Center frequency (cycles per step) | Period (steps) | Bandwidth σ |
|---|---|---|---|---|
| 1 | 1 | 0.3500 | 2.857 | 0.0174 |
| 1 | 2 | 0.3210 | 3.116 | 0.0160 |
| 1 | 3 | 0.2943 | 3.398 | 0.0147 |
| 1 | 4 | 0.2699 | 3.705 | 0.0135 |
| 1 | 5 | 0.2475 | 4.041 | 0.0123 |
| 1 | 6 | 0.2269 | 4.406 | 0.0113 |
| 1 | 7 | 0.2081 | 4.805 | 0.0104 |
| 1 | 8 | 0.1908 | 5.240 | 0.0095 |
| 1 | 9 | 0.1750 | 5.714 | 0.0087 |
| 1 | 10 | 0.1605 | 6.231 | 0.0080 |
| 1 | 11 | 0.1472 | 6.795 | 0.0073 |
| 1 | 12 | 0.1349 | 7.411 | 0.0067 |
| 1 | 13 | 0.1237 | 8.081 | 0.0062 |
| 1 | 14 | 0.1135 | 8.813 | 0.0057 |
| 1 | 15 | 0.1041 | 9.610 | 0.0052 |
| 1 | 16 | 0.0954 | 10.480 | 0.0048 |
| 1 | 17 | 0.0875 | 11.429 | 0.0044 |
| 1 | 18 | 0.0802 | 12.463 | 0.0040 |
| 1 | 19 | 0.0736 | 13.591 | 0.0037 |
| 1 | 20 | 0.0675 | 14.821 | 0.0034 |
| 1 | 21 | 0.0619 | 16.162 | 0.0031 |
| 1 | 22 | 0.0567 | 17.625 | 0.0028 |
| 1 | 23 | 0.0520 | 19.220 | 0.0026 |
| 1 | 24 | 0.0477 | 20.960 | 0.0024 |
| 1 | 25 | 0.0437 | 22.857 | 0.0022 |
| 1 | 26 | 0.0401 | 24.926 | 0.0020 |
| 1 | 27 | 0.0368 | 27.182 | 0.0018 |
| 1 | 28 | 0.0337 | 29.642 | 0.0017 |
| 1 | 29 | 0.0309 | 32.325 | 0.0015 |
| 1 | 30 | 0.0284 | 35.251 | 0.0014 |
| 1 | 31 | 0.0260 | 38.441 | 0.0013 |
| 1 | 32 | 0.0239 | 41.920 | 0.0012 |
| 1 | 33 | 0.0219 | 45.714 | 0.0011 |
| 1 | 34 | 0.0201 | 49.852 | 0.0010 |
| 1 | 35 | 0.0184 | 54.364 | 0.0009 |
| 1 | 36 | 0.0169 | 59.284 | 0.0008 |
| 1 | 37 | 0.0155 | 64.650 | 0.0008 |
| 1 | 38 | 0.0142 | 70.501 | 0.0007 |
| 1 | 39 | 0.0130 | 76.882 | 0.0006 |
| 1 | 40 | 0.0119 | 83.840 | 0.0006 |
Scattering coefficients
| series | Order | Path | Coefficient |
|---|---|---|---|
| s01 | 0 | mean | 0.0135 |
| s01 | 1 | period 2.86 | 0.0142 |
| s01 | 1 | period 3.12 | 0.0131 |
| s01 | 1 | period 3.4 | 0.0160 |
| s01 | 1 | period 3.71 | 0.0186 |
| s01 | 1 | period 4.04 | 0.0140 |
| s01 | 1 | period 4.41 | 0.0168 |
| s01 | 1 | period 4.81 | 0.0187 |
| s01 | 1 | period 5.24 | 0.0168 |
| s01 | 1 | period 5.71 | 0.0151 |
| s01 | 1 | period 6.23 | 0.0306 |
| s01 | 1 | period 6.8 | 0.1267 |
| s01 | 1 | period 7.41 | 0.1281 |
| s01 | 1 | period 8.08 | 0.0708 |
| s01 | 1 | period 8.81 | 0.3732 |
| s01 | 1 | period 9.61 | 0.2865 |
| s01 | 1 | period 10.5 | 0.0274 |
| s01 | 1 | period 11.4 | 0.0309 |
| s01 | 1 | period 12.5 | 0.1821 |
| s01 | 1 | period 13.6 | 0.0977 |
| s01 | 1 | period 14.8 | 0.0172 |
| s01 | 1 | period 16.2 | 0.0216 |
| s01 | 1 | period 17.6 | 0.0105 |
| s01 | 1 | period 19.2 | 0.0081 |
| s01 | 1 | period 21 | 0.0137 |
| s01 | 1 | period 22.9 | 0.0052 |
| s01 | 1 | period 24.9 | 0.0089 |
| s01 | 1 | period 27.2 | 0.0048 |
| s01 | 1 | period 29.6 | 0.0021 |
| s01 | 1 | period 32.3 | 0.0063 |
| s01 | 1 | period 35.3 | 0.0008 |
| s01 | 1 | period 38.4 | 0.0011 |
| s01 | 1 | period 41.9 | 0.0074 |
| s01 | 1 | period 45.7 | 0.0028 |
| s01 | 1 | period 49.9 | 2.615e-5 |
| s01 | 1 | period 54.4 | 6.068e-5 |
| s01 | 1 | period 59.3 | 0.0019 |
| s01 | 1 | period 64.6 | 0.0057 |
| s01 | 1 | period 70.5 | 0.0007 |
| s01 | 1 | period 76.9 | 1.673e-6 |
First 40 of 50 rows.
- 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; convolutions wrap around the ends (periodic).
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 375139667bcf17f0
# 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"])
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 = df.dropna(subset=["x", "series", "step"]) # listwise deletion over the analysis columns
df["series"] = df["series"].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"]) # 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 = None
TEMPORAL = False
OCTAVES = int(0)
QPO = int(8)
ORDER = int(1)
NORMALIZE = True
PAD = "periodic"
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: 2 chart(s) dropped to stay under 100 KB; a table cut from 984 to 50 rows; 2 chart(s) dropped to stay under 100 KB; a table cut from 984 to 50 rows.
With wrap-around padding a circular shift leaves every coefficient exactly unchanged. Mirror padding (the default) has fewer edge effects for signals that don't repeat, and coefficients are then nearly unchanged by a shift.
Check: curves and signals
CheckpointCheck yourself
What is the best way to read a functional PCA component?
Show the answer
Answer: a
The ±2 SD chart shows how curves with high and low scores differ from the average curve.
Check yourself
Why does CodeSplash leave out a curve that stops before the last time point?
Show the answer
Answer: a
Interior gaps are filled by straight lines between measurements, but nothing is invented past a curve's ends.
Check yourself
The grid is 0, 2, 8. With the trapezoid rule, the middle point's weight is half of each gap next to it. What is that weight?
Show the answer
Answer: 4
(2 − 0)/2 + (8 − 2)/2 = 1 + 3 = 4: the long gap on its right makes the middle point count more.
Check yourself
Two classes of signals have the same frequencies but differ in how fast their amplitude swells and fades. Which coefficients tell them apart?
Show the answer
Answer: a
Order 1 averages the modulus over the whole signal; order 2 filters it again and so captures its modulation.
Check yourself
With wrap-around padding, a signal is shifted 13 steps circularly. What happens to its scattering coefficients?
Show the answer
Answer: a
Every coefficient is a global average of a modulus of circular convolutions, so a circular shift cannot change it.
Concepts in this lesson