Repository navigation
Make share_comps work on rank-reduced fits - #256
Merged
Merged
Conversation
The merge metric de-sphered mixing columns with inv(sphere), which raised on every rank-reduced (non-square sphere) or rank-deficient fit, and the constructor refused share_comps with pcakeep/pcadb up front. Invertibility was never required: the reference's own sensor-space back-map under reduction is the pseudo-inverse Spinv (amica15.f90:550-560). Use pinv(sphere) unconditionally, through a single cached _pinv_sphere() now shared with get_sensor_mixing_matrix, and drop the constructor rejection. Full-rank fits are unchanged (pinv == inv to ~1e-15; comp_list and LL bit-identical on the bundled sample). A non-finite sphere still fails loudly, now with a message naming the degenerate fit instead of a LAPACK SVD error.
Real sample EEG only. Two rank-reduced routes through the public AMICA path (explicit pcakeep, and the #221 MEG recipe of projecting onto a rank-20 subspace with automatic rank detection), both asserting finite parameters and a comp_list/comp_used/shared_components() that agree. Full-rank regression: the same fitted state merges identically under pinv(sphere) and the exact inv(sphere), and the two de-sphered mixing matrices agree to <1e-10. The singular-sphere test now pins the loud failure that remains, a non-finite sphere from a degenerate fit.
Guide section on the pinv back-map and the NumPy backend's different metric (sphered-space columns, no back-map), plus a changelog entry.
2 tasks
This was referenced Aug 22, 2026
neuromechanist
added a commit
that referenced
this pull request
Aug 23, 2026
* Port sensor-space sharing similarity to numpy (#258) identify_shared_components now takes de-sphered sensor-space maps (pinv(sphere) @ A), mirroring AMICATorchNG._identify_shared_comps and the Fortran identify_shared_comps/Spinv back-map (amica15.f90:1916, :568-578) exactly, instead of comparing raw sphered A columns. Adds a cached, guarded _pinv_sphere() (mirrors AMICATorchNG._pinv_sphere), invalidated wherever self.sphere is reassigned, also used to refactor get_sensor_mixing_matrix. The merge log moves to the call site since the function is now stateless. Updates the two direct callers of the old 4-arg signature and adds cross-backend and rank-reduced sharing tests. * Document numpy sensor-space sharing change (#258) The amica-differences guide's numpy-compares-in-sphered-space passage (added with #256) is resolved: both backends now compare sensor-space maps, so it is rewritten with the current state and a concrete cosine example. Changelog gets one Unreleased bullet. * Fix docstring test cross-reference
This was referenced Aug 23, 2026
Merged
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.
Closes #253. Unblocks the Maxwell-filtered MEG report in #221.
The problem
_identify_shared_compsde-sphered mixing columns withSpinv = torch.linalg.inv(self.sphere)before comparing them, soshare_comps=TrueraisedRuntimeError: Component sharing needs an invertible sphere...on exactly the data class #223 had just made fittable: under rank reduction the sphere is(n_kept, n_channels)and has no inverse, and a square sphere fitted on rank-deficient data is singular. The constructor also refusedshare_compstogether withpcakeep/pcadbup front.Why the inverse was never required
The back-map only has to put the two columns in a common sensor-space frame before the cosine comparison. The reference does exactly that with a pseudo-inverse whenever reduction is active:
Spinv(nx, numeigs)(amica15.f90:550-560). Sopinv(sphere)is the faithful generalization, not a relaxation.For the reduced PCA sphere
S = D^-1/2 V_r^Tthe pseudo-inverse ispinv(S) = V_r D^1/2, i.e. a de-whitening followed by the orthonormalU_r = V_rembedding the reporter proposed in #221; an orthonormal embedding leaves the cosine untouched, so the comparison is the one the full-rank path already makes, evaluated in the subspace the data actually occupy.What changed
pamica/torch_impl/core.py: the merge metric usespinv(sphere); both invertibilityRuntimeErrorpaths are gone, as is the constructor'sshare_comps+pcakeep/pcadbrejection._spinvfor sharing,_sphere_pinvforget_sensor_mixing_matrix) are now one, behind_pinv_sphere(), invalidated per fit in_preprocessand on_load_params. Two caches of the same quantity with different invalidation points was a drift waiting to happen._identify_shared_comps,_pinv_sphereandcomp_threshcarry the reasoning and cite amica15.f90:550-560.Full-rank behavior is unchanged, measured not assumed
pinv == invto ~1e-15 on a square full-rank sphere, orders of magnitude below thecomp_thresh(~0.99) decision boundary. Confirmed end to end: the three existing full-rank sharing configurations (seeds 3 and 7 at 40 iterations, and the wrapper save/load config at 25) were run before and after the swap, andcomp_listis identical with the final log-likelihood andA.sum()differing by exactly0.0.share_compsis off by default and untouched paths are byte-for-byte unchanged, so single-model parity is unaffected.Tests (real bundled sample EEG only, no synthetic data)
test_rank_reduced_share_fit_completes: publicAMICApath,n_models=2withpcakeep=16andshare_comps=True, non-square(16, 32)sphere, merges fire, all parameters finite,comp_list/comp_used/shared_components()mutually consistent, sensor maps(32, 16).test_low_rank_projected_data_share_fit_completes: the Support for Maxwell-filtered Elekta MEG data #221 route, sample EEG projected onto its rank-20 subspace (what Maxwell filtering does to MEG), fitted with automatic rank detection plus sharing.test_full_rank_merge_decisions_unchanged_by_pinv: from one real fitted full-rank state, the merge scan runs twice, once withpinv(sphere)and once with the exactinv(sphere)injected into the same cache, and must produce identicalcomp_list, with merges actually firing so the comparison is not vacuous.test_pinv_matches_inv_on_a_fitted_full_rank_sphere: numerical pin,max|pinv(sphere) @ A - inv(sphere) @ A| < 1e-10(measured 6.0e-14).test_pca_reduction_no_longer_rejected_at_constructionreplaces the two removedValueErrorcases;test_non_finite_sphere_still_fails_loudlyreplacestest_singular_sphere_raises_on_share, pinning the loud failure that remains.NumPy backend: no equivalent change needed
Investigated rather than assumed.
numpy_impl/utils.py:identify_shared_componentscompares the columns ofAdirectly in the sphered space; it never de-spheres and inverts nothing, so the failure mode does not exist there.AMICA_NumPyalso holds a reduced sphere fine (it shares thepamica/rank.pypolicy and sizes the model to the kept rank), and ashare_comps=Truefit on the same rank-20-projected sample data completes with a(20, 32)sphere, 20 used components and finite parameters. So there is nothing to port.That does leave a genuine cross-backend divergence: PyTorch compares in sensor space, NumPy in sphered space, so the two can identify different pairs on the same data. It is pre-existing and not introduced here; it is recorded in
docs/guides/amica-differences.md, and the NumPy sharing path is being reworked concurrently in #240/#242, so the port is tracked separately (pamica/numpy_impl/**is owned by that work and untouched in this PR). MLX has noshare_compsat all, so it is not involved.Gates
uv run ruff check .,uv run ruff format --check .,uv run ty check .all clean.uv run pytest -m "not slow" -n auto: 389 passed, 16 skipped, 1 xfailed. Full torch suite (slow included): 212 passed, 5 skipped.