Repository navigation
Restore the PCA residual in AMICAICA.apply - #325
Merged
Merged
Conversation
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.
This was referenced Sep 22, 2026
neuromechanist
added a commit
that referenced
this pull request
Sep 22, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
A rank-reduced
AMICAICAfit (explicitpcakeep/pcadb, or automatic rank detection on Maxwell-filtered, average-referenced or interpolated data) models only the retained PCA subspace.to_mne_icaexported only those retained rows of the PCA basis, soapplysilently dropped the discarded subspace: on the bundled 32-channel EEG withpcakeep=20,applywith nothing excluded returned the input with a relative error of 0.080.pamica/mne_compat/core.py:AMICAICA.fitnow computes the full orthonormal PCA basis once, after the backend fit and before publishing state, and stores it aspca_components_(n_channels x n_channels) andpca_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 ann_channels x n_channelsmatrix persists; it is never computed for a full-rank fit.to_mne_icaexports the full basis withn_pca_componentsleft atNone, so MNE's ownICA._pick_sourceskeeps the rows pastn_components_as residual PCA components duringapply, exactly as MNE's ownICAdoes.pca_mean_stays per-model (thecfold lies in the retained row space, so it never reaches the residual rows).to_mne_icalogs 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.float32fit 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 indocs/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 indocs/api/mne-compat.md(which also drops the stale claim thatfitrejectspcakeep/pcadb); a changelog entry flagged as a behavior change.Closes #322
Part of epic #324
Behavior change
For rank-reduced fits only,
AMICAICA.apply(andapplyon the exportedmne.preprocessing.ICA, including one saved and reloaded withread_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 pastnumeigsare zero in the defaultdo_approx_spherepath, 501-508), so a back-projection through thenchan x nwinverse of that output (as EEGLAB'sicawinvis 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):
Test plan
All on the bundled real EEG (
eeglab_data.setthroughmne.io.read_raw_eeglab),max_iter=10, seed 42, independent oracles (the input, the backend's owntransform/sphere/unmixing,np.linalg.eigvalshof the fit covariance). Relative errors are Frobenius-norm.to_mne_icaattributes (pca_components_,pca_explained_variance_,unmixing_matrix_,pca_mean_) andapplyoutput (no exclusions andexclude=[0, 3]) bit-identical to the pre-change formulapcakeep=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'sapply, and equal to an independent retained-subspace projection; settingn_pca_componentson a copy of the export gives the samepcakeep=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-15pcakeep=20:get_sourcesequalsamica_.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 thecfold's residual component is 3.9e-16 / 4.0e-16 relativeEpochsfit and apply: input reproduced (1.3e-15), residual variances match (1.1e-12)ica.save()+read_ica:applyoutput bit-identical (no exclusions andexclude=[0]); a floatn_pca_componentsselects the same rows as MNE's cumulative-variance rule predicts, including after a save/read round trippre_whitener_, built as intest_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)pcakeep:apply()reproduces the input (2.1e-15); residual variance clipped to >= 0 (1.3e-15)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.float32fit withpcakeep=20: float64 basis orthonormal (2.7e-15),apply()reproduces the input (1.7e-15),get_sourcesvs the float32transform1.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)pca_components_/pca_explained_variance_unchangedcore.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: cleanuv run pytest pamica/tests/mne_tests -q: 101 passed (after review fixes; 98 before);pamica/tests/test_amica.py: 3 passeduv 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) andtyposon the changed files: clean