Skip to content

Restore the PCA residual in AMICAICA.apply - #325

Merged
neuromechanist merged 17 commits into
devfrom
feature/issue-322-phase2-pca-residual
Sep 22, 2026
Merged

neuromechanist merged 17 commits into
devfrom
feature/issue-322-phase2-pca-residual

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

Summary

A rank-reduced AMICAICA fit (explicit pcakeep/pcadb, or automatic rank detection on Maxwell-filtered, average-referenced or interpolated data) models only the retained PCA subspace.
to_mne_ica exported only those retained rows of the PCA basis, so apply silently dropped the discarded subspace: on the bundled 32-channel EEG with pcakeep=20, apply with nothing excluded returned the input with a relative error of 0.080.

pamica/mne_compat/core.py: AMICAICA.fit now computes the full orthonormal PCA basis once, after the backend fit and before publishing state, and stores it as pca_components_ (n_channels x n_channels) and pca_explained_variance_ (n_channels).
The retained rows are the export's existing computation, moved into a shared helper (_pca_basis) and not altered.
For a reduced sphere, the residual rows are the sphere's null space (full SVD), rotated to the eigenvectors of the pre-whitened fit data's population covariance restricted to that subspace, ordered by descending variance, with variances clipped at 0.
The covariance is accumulated in two passes over 8192-column blocks (_population_covariance), so no full-size copy of the data is made and only an n_channels x n_channels matrix persists; it is never computed for a full-rank fit.
to_mne_ica exports the full basis with n_pca_components left at None, so MNE's own ICA._pick_sources keeps the rows past n_components_ as residual PCA components during apply, exactly as MNE's own ICA does.
pca_mean_ stays per-model (the c fold lies in the retained row space, so it never reaches the residual rows).
to_mne_ica logs at INFO when it exports a residual, with its dimension and the opt-out.
No backend (torch/NumPy/MLX) changes; the basis is plain NumPy on the fitted sphere as a float64 array, so Phase 4 can route MLX through it.
One consequence of the float64 cast: for a dtype=torch.float32 fit the retained basis is now computed in float64 from the float32 sphere and exported as float64 (it differs from the old float32 computation by 2.9e-8, within float32 precision); float64 fits, the default, are bit-identical.

pamica/tests/mne_tests/test_pca_residual.py (new): pin tests for the full-rank export (committed first, passing against the pre-change code) and the pre-registered residual gates below.
Three existing tests that asserted the old (n_components, n_channels) basis shape now assert the full basis (still orthonormal, n_components_ still the retained rank).

Docs: ADR 0005 (.context/decisions/0005-restore-pca-residual-in-mne-export.md); a new section and row 11 in docs/guides/amica-differences.md (what the reference does, what pamica does, why, what does not change, how to restore the reference); docstrings (class Attributes and Notes, fit, to_mne_ica, apply); a "Rank-reduced fits and the PCA residual" subsection in docs/api/mne-compat.md (which also drops the stale claim that fit rejects pcakeep/pcadb); a changelog entry flagged as a behavior change.

Closes #322
Part of epic #324

Behavior change

For rank-reduced fits only, AMICAICA.apply (and apply on the exported mne.preprocessing.ICA, including one saved and reloaded with read_ica) now restores the PCA residual by default: with nothing excluded it returns the input, and excluding a component removes that component's back-projection and nothing else.
This goes beyond the Fortran reference, whose output has no representation of the residual (numeigs, amica15.f90:413/466; nw = numeigs, 563; the written sphere's rows past numeigs are zero in the default do_approx_sphere path, 501-508), so a back-projection through the nchan x nw inverse of that output (as EEGLAB's icawinv is built) can only reconstruct the retained subspace (an inference from the output's shape; EEGLAB is not in this repository).
Sources, component maps, unmixing_matrix_, pca_mean_, n_components_ and the log-likelihood are unchanged; full-rank fits export bit-identically.

One-line opt-out (the reference's rank-reduced reconstruction):

ica.apply(raw, exclude=[0], n_pca_components=ica.n_components_)

Test plan

All on the bundled real EEG (eeglab_data.set through mne.io.read_raw_eeglab), max_iter=10, seed 42, independent oracles (the input, the backend's own transform/sphere/unmixing, np.linalg.eigvalsh of the fit covariance). Relative errors are Frobenius-norm.

  • Pin (first commit, passing before and after): full-rank single- and two-model to_mne_ica attributes (pca_components_, pca_explained_variance_, unmixing_matrix_, pca_mean_) and apply output (no exclusions and exclude=[0, 3]) bit-identical to the pre-change formula
  • pcakeep=20: apply() reproduces the input, rel 1.3e-15 (pre-change export: 8.0e-2)
  • pcakeep=20: apply(n_pca_components=ica.n_components_) bit-identical to the pre-change export's apply, and equal to an independent retained-subspace projection; setting n_pca_components on a copy of the export gives the same
  • pcakeep=20: exclude=[k] (k = 0 and 19) changes the data by exactly minus component k's backend back-projection, rel 7.7e-15 / 7.9e-15; residual-subspace part of the change 1.5e-15 / 2.0e-15
  • pcakeep=20: get_sources equals amica_.transform (rel 2.3e-15); residual variances equal the discarded eigenvalues (max rel 5.7e-13, gate rtol 1e-8); exported basis orthonormal (max err 1.7e-15)
  • n_models=2, pcakeep=20: both models reproduce the input (1.1e-15, 1.3e-15), share the same basis, and the c fold's residual component is 3.9e-16 / 4.0e-16 relative
  • Epochs fit and apply: input reproduced (1.3e-15), residual variances match (1.1e-12)
  • ica.save() + read_ica: apply output bit-identical (no exclusions and exclude=[0]); a float n_pca_components selects the same rows as MNE's cumulative-variance rule predicts, including after a save/read round trip
  • Mixed channel types (non-uniform pre_whitener_, built as in test_mne_meg.py): input reproduced per type (mag 1.3e-15, grad 1.2e-15), exclusion change matches the oracle in original units (8.4e-15)
  • Average-referenced sample, automatic rank 31, no pcakeep: apply() reproduces the input (2.1e-15); residual variance clipped to >= 0 (1.3e-15)
  • INFO log emitted for a reduced export, not for a full-rank one
  • pcadb=30 (keeps 26 of 32 on the sample): apply() reproduces the input (2.2e-15; rank-reduced 4.7e-2), residual variances match (5.6e-13), exclusion leaves the residual untouched (7.6e-16)
  • dtype=torch.float32 fit with pcakeep=20: float64 basis orthonormal (2.7e-15), apply() reproduces the input (1.7e-15), get_sources vs the float32 transform 1.9e-7 (bound 100 float32 eps), exclusion oracle 2.3e-7 with the residual part 1.0e-15, retained basis vs the float32 sphere's right singular vectors 2.3e-8 (bound 1e-6, about 8 eps), variances 1.0e-7 (bound 10 eps)
  • A failed refit leaves pca_components_/pca_explained_variance_ unchanged
  • 13 of the 19 new tests fail against the pre-change core.py (the other 6 are the pins and the unchanged-behavior checks)
  • uv run ruff check --fix . && uv run ruff format ., uv run ty check: clean
  • uv run pytest pamica/tests/mne_tests -q: 101 passed (after review fixes; 98 before); pamica/tests/test_amica.py: 3 passed
  • uv run pytest -q -n auto: 1048 passed, 14 skipped, 3 xfailed (before the review-fix commits, which add tests and docs only)
  • mkdocs build --strict (isolated docs env) and typos on the changed files: clean

Recomputes the pre-#322 to_mne_ica attributes and apply output by the
original formula and asserts bit-identity for a full-rank single- and
two-model fit. Passes against the current code (4 passed).
AMICAICA.fit now computes the full orthonormal PCA basis once from the
fitted sphere (retained rows exactly as before, then the sphere's null
space rotated by the fit covariance, accumulated blockwise), and
to_mne_ica exports all n_channels rows. MNE's ICA.apply keeps rows past
n_components_ as residual PCA components, so a rank-reduced fit now
reconstructs the discarded subspace by default; apply(...,
n_pca_components=ica.n_components_) gives the reference behavior.

Full-rank exports are unchanged (pin tests pass bit for bit). The three
tests asserting the old (n_components, n_channels) basis shape now assert
the full basis. mne_tests: 83 passed.
Real sample EEG, independent oracles (the input, the backend's
transform/sphere/unmixing, eigvalsh of the fit covariance): pcakeep=20
apply reproduces the input (rel 1.3e-15; the pre-#322 export loses
8.0%), n_pca_components=n_components_ is bit-identical to the old
export, exclude=[k] removes exactly component k and leaves the residual
untouched, residual variances equal the discarded eigenvalues. Also
two-model, Epochs, save/read_ica, float n_pca_components, mixed channel
types, average-reference auto rank, and the INFO log.

19 passed; 13 of them fail against the pre-change code (the other 6 are
the pins and the unchanged-behavior checks).
Setting n_pca_components=n_components_ on a copy of the exported ICA
reproduces the pre-#322 apply output bit for bit (1 passed).
ADR 0005 (context, decision, consequences with measured numbers,
alternatives, how to restore the reference) and a new section plus
row 11 in docs/guides/amica-differences.md: what the Fortran reference
does (amica15.f90:413/466/501-508/563), what pamica does, why, what does
not change, and the n_pca_components opt-out.
Class Attributes (pca_components_, pca_explained_variance_), the
rank-deficient Notes paragraph, fit's pcakeep/pcadb note, to_mne_ica and
apply now state that the residual is restored by default, that this goes
beyond the Fortran reference, and the n_pca_components opt-out.
docs/api/mne-compat.md gains a 'Rank-reduced fits and the PCA residual'
subsection with both behaviors, and drops the stale claim that fit
rejects pcakeep/pcadb. Changelog entry flagged as a behavior change.
mkdocs build --strict passes; typos clean.
The class Notes formula now slices pca_components_[:n_components_],
matching MNE's ICA._transform and docs/api/mne-compat.md; the full basis
has residual rows past n_components_ for a reduced fit.
test_failed_refit_leaves_prior_state_intact now also asserts that
pca_components_ and pca_explained_variance_ are unchanged after the
aborted refit (1 passed).
pcadb=30 keeps 26 of the sample's 32 dimensions; apply() reproduces the
input (rel 2.2e-15, rank-reduced 4.7e-2), residual variances equal the
discarded eigenvalues (5.6e-13), exclusion leaves the residual
untouched (7.6e-16). 20 passed.
A dtype=torch.float32 CPU fit with pcakeep=20: float64 basis
orthonormal (2.7e-15), apply() reproduces the input (1.7e-15),
get_sources vs the float32 transform 1.9e-7 (bound 100 float32 eps),
exclusion oracle 2.3e-7 with the residual part 1.0e-15, and the retained
basis matches the float32 sphere's right singular vectors to 2.3e-8
(bound 1e-6, about 8 eps). 22 passed.
ADR 0005 and amica-differences.md now state the EEGLAB point as an
inference from the reference output's shape (EEGLAB is not in this
repository) rather than as a fact about EEGLAB internals.
The covariance pass allocates block temporaries, so 'no copy' overclaimed;
now matches the _population_covariance docstring.
Principal component analysis (PCA) is spelled out at its first use in
ADR 0005, amica-differences.md (row 11, the page's first use) and
mne-compat.md (the fit paragraph, the page's first use); ADR 0005 also
defines MEG, EEG and ICA, and spells out singular value decomposition.
keep_best, Newton and residual restoration are also changed defaults,
so section 1 of amica-differences.md is now 'Relative rank threshold'.
No links pointed at the old anchor.
The ADR index listed only 0001; it now lists every ADR with its title
and status, in the existing entry format.
Behaviour, cancelling, neighbour and acknowledgement become behavior,
canceling, neighbor and acknowledgment; all four are prose, not
identifiers. Words only, no reflow.
@neuromechanist
neuromechanist merged commit 42a59c2 into dev Sep 22, 2026
8 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-322-phase2-pca-residual branch September 22, 2026 22:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Restore PCA residual when applying AMICA with pcakeep < n_rank (or n_channel)

1 participant