Skip to content

Handle rank-deficient input across all backends - #224

Merged
neuromechanist merged 4 commits into
mainfrom
223-rank-deficient-numeigs
Aug 15, 2026
Merged

neuromechanist merged 4 commits into
mainfrom
223-rank-deficient-numeigs

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Closes #223.

Ports the Fortran reference's numerical-rank handling, which pamica had dropped. Rank-deficient input (Maxwell-filtered MEG, average-referenced or interpolated EEG) previously died with nan_ll on iteration 0, or silently fitted a full-rank model to rank-deficient data. Reported in #221 by a user applying pamica to 306-channel Elekta MEG at numerical rank ~70.

What Fortran does, and now we do

Fortran Reference pamica before pamica now
numeigs = min(pcakeep, count(eigs > mineig)) amica15.f90:395 absent mineig, default 1e-15
nw = numeigs amica15.f90:545 n_channels fixed from X.shape[0] model sized to kept rank
Spinv (nx, numeigs) amica15.f90:550-560 absent get_sensor_mixing_matrix()

The reduced sphere follows Fortran's construction exactly, including the do_approx_sphere branch that symmetrizes the reduced whitening by the orthogonal polar factor of the leading numeigs block of V^T (amica15.f90:483-490).

Parity

Full-rank data keep every eigenvalue, so the reduction path never fires and the existing code paths are untouched. Verified bit-identical before/after on the bundled sample EEG across single-model, Newton-enabled, and two-model fits (log-likelihood, sphere sum, mixing-matrix sum, and the first five LL-history entries all compare equal by repr).

Improving on the reference

mineig is an absolute eigenvalue floor, so it is unit-dependent. Two consequences, both handled:

  1. MEG in Tesla has covariance eigenvalues ~1e-26, all below 1e-15. Fortran would compute numeigs = 0 and proceed; pamica raises a ValueError naming the cause and the fix rather than fitting an empty model.

  2. The absolute floor is a poor rank detector, because numerical-zero eigenvalues straddle it. On real EEG projected to rank 20:

    threshold rank found reconstruction error
    mineig=1e-15 (Fortran default) 24 1.98e-09
    mineig_rel=1e-9 20 (exact) 7.52e-15

mineig_rel is opt-in and replaces the absolute floor when set, so the default stays Fortran-exact while the better detector is one argument away.

Also fixed

pcakeep=N, do_approx_sphere=False — the genuinely dimension-reducing path — raised RuntimeError: The size of tensor a (N) must match the size of tensor b (n_channels). _preprocess returned (N, T) while every parameter was still sized to the input channel count. Covered by a regression test.

Tests

pamica/tests/torch_tests/test_ng_rank_deficient.py, 7 tests, real sample EEG only. Rank deficiency is produced by projecting the real recording onto its own leading subspace — the same rank-reducing linear operator SSS applies to MEG — so no synthetic data is involved.

Follow-ups (not in this PR)

  • numpy_impl and mlx_impl still lack rank handling.
  • mne_compat sets a unit pre-whitener (ica.pre_whitener_ = np.ones((n_ch, 1))), so mixed magnetometer/gradiometer data are not channel-type scaled. Since the scaling determines which directions survive rank truncation, this matters for MEG; tracked in Support for Maxwell-filtered Elekta MEG data #221.

@neuromechanist neuromechanist changed the title Handle rank-deficient input via mineig rank detection Handle rank-deficient input across all backends Aug 15, 2026
@neuromechanist

Copy link
Copy Markdown
Member Author

Update: folded backend parity and documentation in

Per review direction, this is no longer a PyTorch-only change.

All backends, one shared policy

Rank detection now lives in pamica/rank.py and is called by the PyTorch, NumPy, and MLX backends. Only the decision is shared -- each backend still builds its sphering matrix in its own array library, so the bit-exact PyTorch path is not routed through a different eigensolver.

pamica/tests/test_rank_policy.py asserts all three size their models identically; PyTorch and NumPy run unconditionally, MLX via importorskip. That test is the anti-drift guard.

Default changed to a relative floor

mineig_rel=1e-12 is now the default; mineig_rel=None restores Fortran's absolute floor exactly.

The absolute floor is unit-dependent, and it is not only MEG that suffers. Average-referenced EEG -- an everyday step -- sits at lambda_min/lambda_max = 8.5e-17 on the bundled sample, within a factor of ~10 of the 1e-15 floor, so the reference detects that rank deficiency essentially by luck. The relative floor detects it every time, and is scale-invariant across 1e-13 to 1e6.

Well-conditioned data is unaffected: real EEG sits at 5e-4, eight orders above the floor. Re-verified bit-identical against main after the refactor.

Documentation

  • ADR 0004 -- the decision, the measurements, and the alternatives (including max(mineig, rel), which was implemented first and is wrong: for Tesla-scale data the absolute term dominates and reproduces the bug).
  • .rules/backend_parity.md -- new standing rule: no one-off backends, shared decisions go in shared modules, cross-backend tests mandatory, deliberate divergences must be recorded. Referenced from AGENTS.md Core Principles.
  • docs/guides/amica-differences.md -- every deliberate pamica-vs-AMICA difference in one table, with why and how to restore reference behavior, plus a backend feature matrix. Added to the mkdocs nav.

The differences table is the answer to "which ones are different and why, in one look", and it is now the documented home for any future divergence.

@neuromechanist
neuromechanist merged commit fabd370 into main Aug 15, 2026
7 checks passed
@neuromechanist
neuromechanist deleted the 223-rank-deficient-numeigs branch August 15, 2026 20:52
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.

Rank-deficient input: no mineig detection, model dimension not reduced to numeigs

1 participant