Skip to content

CDiscover · discover.fpca

Functional PCA (main shapes of a set of curves)

What are the main ways a set of curves — growth curves, daily profiles, spectra — differ from the average curve?

Treats each curve (one id with values over time, in long form) as a single observation and finds its main modes of variation: a mean curve, eigenfunctions φ(t) that are orthonormal under the integral over time, their eigenvalues and each curve's scores. Curves share a common grid (interior gaps are filled by straight lines; curves that start late or end early are left out), integrals use the trapezoid rule so uneven time steps count by their length, and curves can be smoothed first with a roughness penalty chosen by generalized cross-validation. Scores and eigenfunctions can be saved as datasets.

Verified in Python and R Python and R agree to 10 decimals Also called functional PCA, FPCA, functional principal component analysis…

A real result

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

Functional PCA (main shapes of a set of curves)Recorded · Python and R agreeRecorded 2026-11-21 · 27 values compared · largest relative difference 2.3e-15
R

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

Plots

Share of the curves' variance by componentHow many components carry most of the variance?
View data
ComponentCumulative shareShare of variance
10.92990.9299
20.98660.0567
30.99470.0081
40.99660.0019
50.99760.0011
60.99840.0008
70.99900.0006
80.99930.0003
90.99970.0003
100.99990.0002
Component 1 (93% of the variance): the mean curve moved by ±2 SDHow does the series move over time, and where is an estimated break?
View data
curveTimeweight
Mean041.067
Mean249.578
Mean460.156
Mean674.867
Mean892.422
Mean10110.09
Mean12132.78
Mean14146.24
Mean16169.53
Mean18192.42
Mean20211.60
Mean21218.69
Mean + 2√λ·φ040.396
Mean + 2√λ·φ250.713
Mean + 2√λ·φ464.546
Mean + 2√λ·φ685.943
Mean + 2√λ·φ8116.99
Mean + 2√λ·φ10148.36
Mean + 2√λ·φ12191.12
Mean + 2√λ·φ14218.17
Mean + 2√λ·φ16263.32
Mean + 2√λ·φ18307.03
Mean + 2√λ·φ20340.46
Mean + 2√λ·φ21355.73
Mean − 2√λ·φ041.737
Mean − 2√λ·φ248.442
Mean − 2√λ·φ455.765
Mean − 2√λ·φ663.791
Mean − 2√λ·φ867.857
Mean − 2√λ·φ1071.822
Mean − 2√λ·φ1274.433
Mean − 2√λ·φ1474.319
Mean − 2√λ·φ1675.747
Mean − 2√λ·φ1877.819
Mean − 2√λ·φ2082.743
Mean − 2√λ·φ2181.648
Component 2 (6% of the variance): the mean curve moved by ±2 SDHow does the series move over time, and where is an estimated break?
View data
curveTimeweight
Mean041.067
Mean249.578
Mean460.156
Mean674.867
Mean892.422
Mean10110.09
Mean12132.78
Mean14146.24
Mean16169.53
Mean18192.42
Mean20211.60
Mean21218.69
Mean + 2√λ·φ041.257
Mean + 2√λ·φ251.237
Mean + 2√λ·φ463.476
Mean + 2√λ·φ683.028
Mean + 2√λ·φ8108.84
Mean + 2√λ·φ10132.32
Mean + 2√λ·φ12159.10
Mean + 2√λ·φ14166.78
Mean + 2√λ·φ16177.03
Mean + 2√λ·φ18182.67
Mean + 2√λ·φ20184.23
Mean + 2√λ·φ21180.33
Mean − 2√λ·φ040.876
Mean − 2√λ·φ247.919
Mean − 2√λ·φ456.835
Mean − 2√λ·φ666.705
Mean − 2√λ·φ876.006
Mean − 2√λ·φ1087.853
Mean − 2√λ·φ12106.46
Mean − 2√λ·φ14125.71
Mean − 2√λ·φ16162.03
Mean − 2√λ·φ18202.17
Mean − 2√λ·φ20238.97
Mean − 2√λ·φ21257.04
Component 3 (1% of the variance): the mean curve moved by ±2 SDHow does the series move over time, and where is an estimated break?
View data
curveTimeweight
Mean041.067
Mean249.578
Mean460.156
Mean674.867
Mean892.422
Mean10110.09
Mean12132.78
Mean14146.24
Mean16169.53
Mean18192.42
Mean20211.60
Mean21218.69
Mean + 2√λ·φ041.138
Mean + 2√λ·φ253.088
Mean + 2√λ·φ465.070
Mean + 2√λ·φ683.075
Mean + 2√λ·φ8101.34
Mean + 2√λ·φ10116.59
Mean + 2√λ·φ12133.66
Mean + 2√λ·φ14140.97
Mean + 2√λ·φ16159.27
Mean + 2√λ·φ18189.38
Mean + 2√λ·φ20218.93
Mean + 2√λ·φ21228.81
Mean − 2√λ·φ040.995
Mean − 2√λ·φ246.067
Mean − 2√λ·φ455.242
Mean − 2√λ·φ666.659
Mean − 2√λ·φ883.507
Mean − 2√λ·φ10103.59
Mean − 2√λ·φ12131.90
Mean − 2√λ·φ14151.52
Mean − 2√λ·φ16179.80
Mean − 2√λ·φ18195.46
Mean − 2√λ·φ20204.27
Mean − 2√λ·φ21208.57
Eigenfunctions φ(t)How does the series move over time, and where is an estimated break?
View data
componentTimeφ
φ10−0.0021
φ120.0036
φ140.0139
φ160.0351
φ180.0778
φ1100.1212
φ1120.1847
φ1140.2278
φ1160.2970
φ1180.3629
φ1200.4080
φ1210.4339
φ200.0024
φ220.0213
φ240.0426
φ260.1047
φ280.2105
φ2100.2852
φ2120.3376
φ2140.2634
φ2160.0962
φ218−0.1251
φ220−0.3510
φ221−0.4919
φ300.0024
φ320.1190
φ340.1666
φ360.2783
φ380.3023
φ3100.2206
φ3120.0298
φ314−0.1789
φ316−0.3482
φ318−0.1031
φ3200.2485
φ3210.3433
Curve scores on the first two componentsWhich levels of a categorical variable does the model treat as alike?
View data
ChickScore 1Score 2
1−65.479−36.830
10−225.76−5.329
1110.88698.296
12−42.756−26.979
13−313.34−19.182
14152.1420.561
17−188.004.022
19−205.15−45.334
2−21.830−17.836
20−246.98−21.191
21327.8460.620
22−124.42−2.437
23−80.31120.194
24−331.600.9428
25101.48−9.684
2633.167−19.512
27−79.248−9.996
2832.15210.117
2998.722−65.907
3−34.858−17.382
30−116.0915.346
3120.557−43.073
32181.21−17.030
33−92.73359.353
34248.27−39.530
35380.358.663
3666.40114.062
37−116.83−26.024
38101.73−56.682
3949.318−41.958
4−130.70−18.369
40179.10−33.718
413.42247.037
42128.22−0.6616
4365.677120.11
45−39.39119.316
4643.7785.036
475.06233.777
48183.79−39.135
4957.05027.115
533.7760.6040
50120.162.607
6−69.30563.691
7153.16−44.446
9−252.6126.759

Components

ComponentEigenvalueShare of varianceCumulative
124933.2693.0%93.0%
21519.995.7%98.7%
3217.400.8%99.5%
450.3690.2%99.7%
528.4070.1%99.8%
620.8700.1%99.8%
716.1240.1%99.9%
88.9030.0%99.9%
98.1120.0%100.0%
105.6050.0%100.0%

Mean curve and eigenfunctions

TimeMeanφ1φ2φ3
041.067−0.00210.00240.0024
249.5780.00360.02130.1190
460.1560.01390.04260.1666
674.8670.03510.10470.2783
892.4220.07780.21050.3023
10110.090.12120.28520.2206
12132.780.18470.33760.0298
14146.240.22780.2634−0.1789
16169.530.29700.0962−0.3482
18192.420.3629−0.1251−0.1031
20211.600.4080−0.35100.2485
21218.690.4339−0.49190.3433

Curve scores

ChickScore 1Score 2Score 3Integrated squared error
1−65.479−36.830−5.887118.19
10−225.76−5.329−5.353103.73
1110.88698.296−3.79318.797
12−42.756−26.979−29.337122.88
13−313.34−19.1822.54058.762
14152.1420.561−24.32979.058
17−188.004.0228.64151.345
19−205.15−45.334−1.87969.410
2−21.830−17.836−3.60519.740
20−246.98−21.191−13.88242.253
21327.8460.620−16.699100.41
22−124.42−2.43716.146179.86
23−80.31120.194−0.947682.436
24−331.600.94285.373255.23
25101.48−9.6847.12264.948
2633.167−19.51212.510175.20
27−79.248−9.9966.26354.532
2832.15210.117−14.381169.50
2998.722−65.90713.118201.58
3−34.858−17.382−18.971244.06
30−116.0915.346−9.68999.970
3120.557−43.0737.12163.574
32181.21−17.0306.47484.219
33−92.73359.353−4.708162.30
34248.27−39.53010.938245.45
35380.358.663−8.68088.855
3666.40114.062−21.559435.26
37−116.83−26.024−6.080110.31
38101.73−56.68213.432193.70
3949.318−41.95818.195104.41
4−130.70−18.369−13.926209.65
40179.10−33.7186.219193.07
413.42247.03710.078190.20
42128.22−0.661610.524103.96
4365.677120.1119.95368.472
45−39.39119.31620.707161.85
4643.7785.03616.40689.230
475.06233.77712.050169.67
48183.79−39.13511.046153.96
4957.05027.11517.99789.074

First 40 of 45 rows.

Curves left out

ChickWhy
15ends before the last time
16ends before the last time
18ends before the last time
44ends before the last time
8ends 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.
Python

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

ComponentEigenvalueShare of varianceCumulative
124933.2693.0%93.0%
21519.995.7%98.7%
3217.400.8%99.5%
450.3690.2%99.7%
528.4070.1%99.8%
620.8700.1%99.8%
716.1240.1%99.9%
88.9030.0%99.9%
98.1120.0%100.0%
105.6050.0%100.0%

Mean curve and eigenfunctions

TimeMeanφ1φ2φ3
041.067−0.00210.00240.0024
249.5780.00360.02130.1190
460.1560.01390.04260.1666
674.8670.03510.10470.2783
892.4220.07780.21050.3023
10110.090.12120.28520.2206
12132.780.18470.33760.0298
14146.240.22780.2634−0.1789
16169.530.29700.0962−0.3482
18192.420.3629−0.1251−0.1031
20211.600.4080−0.35100.2485
21218.690.4339−0.49190.3433

Curve scores

ChickScore 1Score 2Score 3Integrated squared error
1−65.479−36.830−5.887118.19
10−225.76−5.329−5.353103.73
1110.88698.296−3.79318.797
12−42.756−26.979−29.337122.88
13−313.34−19.1822.54058.762
14152.1420.561−24.32979.058
17−188.004.0228.64151.345
19−205.15−45.334−1.87969.410
2−21.830−17.836−3.60519.740
20−246.98−21.191−13.88242.253
21327.8460.620−16.699100.41
22−124.42−2.43716.146179.86
23−80.31120.194−0.947682.436
24−331.600.94285.373255.23
25101.48−9.6847.12264.948
2633.167−19.51212.510175.20
27−79.248−9.9966.26354.532
2832.15210.117−14.381169.50
2998.722−65.90713.118201.58
3−34.858−17.382−18.971244.06
30−116.0915.346−9.68999.970
3120.557−43.0737.12163.574
32181.21−17.0306.47484.219
33−92.73359.353−4.708162.30
34248.27−39.53010.938245.45
35380.358.663−8.68088.855
3666.40114.062−21.559435.26
37−116.83−26.024−6.080110.31
38101.73−56.68213.432193.70
3949.318−41.95818.195104.41
4−130.70−18.369−13.926209.65
40179.10−33.7186.219193.07
413.42247.03710.078190.20
42128.22−0.661610.524103.96
4365.677120.1119.95368.472
45−39.39119.31620.707161.85
4643.7785.03616.40689.230
475.06233.77712.050169.67
48183.79−39.13511.046153.96
4957.05027.11517.99789.074

First 40 of 45 rows.

Curves left out

ChickWhy
15ends before the last time
16ends before the last time
18ends before the last time
44ends before the last time
8ends 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.

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

Worked examples in the app

  • Chickweight growthml_chickweight · curve: Chick · time: Time · value: weight
  • Chickweight gcv smoothingml_chickweight · curve: Chick · time: Time · value: weight
  • Curves uneven gridseq_curves · curve: curve · time: t · value: value
  • Curves dates manual smoothingseq_curves · curve: curve · time: date · value: value
  • Degenerate constantseq_curves · curve: curve · time: t · value: value
  • Degenerate n3seq_curves · curve: curve · time: t · value: value
  • Degenerate one curveseq_curves · curve: curve · time: t · value: value
  • Degenerate infseq_curves · curve: curve · time: t · value: value

In the guides

Where it sits in the decision guides

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

What you need

Curvecategorical · 1 column · 3–20000 levels
Which curve each row belongs to — a child, a day, a sample.
Timenumeric / temporal · 1 column
Where along the curve the value was measured (age, hour, wavelength, date).
Valuenumeric · 1 column
The measured value; repeated measurements of the same curve and time are averaged.

Choices you make

model

Componentsdefault 3

How many eigenfunctions to keep; the components table lists up to 10 so you can see how much each adds.

preprocess

Smooth the curves firstdefault none

Noisy curves give wiggly eigenfunctions; a roughness penalty smooths each curve before the decomposition.

  • No (use the measured values)(default) — Best for smooth curves or few time points.
  • Yes, amount chosen by cross-validation — One penalty for all curves, chosen by generalized cross-validation over 41 values.
  • Yes, amount set below — Use the penalty you set; larger values smooth more.
Smoothing amount (log₁₀ scale)default -2

Penalty on curvature, log₁₀ relative to the grid; −8 barely smooths, 2 is nearly a straight line.

What it reports

n_curves
The time points shared by the curves that cover the whole time range; interior gaps are filled by straight lines.
n_dropped_curves
The time points shared by the curves that cover the whole time range; interior gaps are filled by straight lines.
n_grid
The time points shared by the curves that cover the whole time range; interior gaps are filled by straight lines.
n_interpolated
The time points shared by the curves that cover the whole time range; interior gaps are filled by straight lines.
smoothing
Fits a smooth curve by trading closeness to the values against a penalty on curvature; λ sets the trade-off.
log_lambda
Fits a smooth curve by trading closeness to the values against a penalty on curvature; λ sets the trade-off.
edf
Fits a smooth curve by trading closeness to the values against a penalty on curvature; λ sets the trade-off.
gcv
Estimates prediction error from the residuals and the smoother's effective degrees of freedom, without refitting.
components
PCA where each observation is a whole curve: a mean curve plus a few eigenfunctions, each curve a score on each.
total_variance
Variance of the curves' scores on a component; with the time axis doubled it doubles, because it is an integral.
explained
Variance of the curves' scores on a component; with the time axis doubled it doubles, because it is an integral.
recon_error
∫(curve − its reconstruction from the kept components)² dt, averaged over curves; smaller means the components describe the curves well.

Per group, level or term: eigen[<k>], share[<k>], cumulative[<k>], phi_check[<k>], score_check[<k>]

Python and R

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

Default traps between the two languages

  • Both engines run the same twins (codesplash.ml.fpca ↔ codesplashr R/ml_fpca.R): the same grid and interpolation rule, trapezoid weights, Whittaker smoother and SVD of (Y − μ)·√w, with each eigenfunction signed so ∫φ dt ≥ 0.
Python

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

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

Sources

  • Ramsay, J. O., & Silverman, B. W. (2005). Functional Data Analysis (2nd ed.), chapter 8. Springer.
  • Silverman, B. W. (1996). Smoothed functional principal components analysis by choice of norm. Annals of Statistics, 24, 1–24.
  • Eilers, P. H. C. (2003). A perfect smoother. Analytical Chemistry, 75, 3631–3636.
  • Craven, P., & Wahba, G. (1979). Smoothing noisy data with spline functions. Numerische Mathematik, 31, 377–403.

From the CodeSplash method registry · discover.fpca v1.0.0.