Repository navigation
Description
Background
First of all, I think pAMICA is an excellent Python package. It provides a very comprehensive implementation of AMICA, and I really appreciate the amount of work and thought that has gone into developing it.
However, as far as I understand, pAMICA currently does not explicitly support MEG data, particularly Maxwell-filtered Elekta/MEGIN MEG data. I am currently trying to apply AMICA to my MEG data, and I encountered two issues that seem particularly relevant for MEG. A common preprocessing step for Elekta/MEGIN MEG data is Maxwell filtering. After Maxwell filtering, the resulting MEG data are generally not full-rank. For example, my original Elekta MEG data contain 306 MEG channels (102 magnetometers + 204 gradiometers), but after Maxwell filtering the numerical rank of the MEG data is only around 70. Therefore, the rank deficiency is expected as a consequence of Maxwell filtering and does not necessarily indicate a problem with the data.
1. Support for non-full-rank Maxwell-filtered MEG data
When I try to use pAMICA directly on Maxwell-filtered MEG data, the fit can become degenerate or the resulting decomposition cannot be directly mapped back to the original sensor space. This makes it difficult to use pAMICA directly with Maxwell-filtered MEG.
Would it be possible to support non-full-rank MEG data explicitly in pAMICA?
For example, one possible approach could be:
- Estimate the numerical rank of the input MEG data.
- Perform SVD/PCA reduction to the numerical rank.
- Represent the data in this reduced-rank space.
- Run AMICA in the reduced-rank space.
- Transform the AMICA decomposition back to the original MEG sensor space.
Conceptually, if the original data are
X ∈ R^(306 × T)
and the numerical rank is approximately 70, I would construct a rank-70 representation
X ≈ U_70 Z
where
U_70 ∈ R^(306 × 70)
Z ∈ R^(70 × T).
AMICA would then operate on Z rather than directly on the 306-channel rank-deficient data. Afterwards, the decomposition could potentially be mapped back to the 306-channel sensor space through U_70.
Would this be a mathematically valid way of applying AMICA to Maxwell-filtered MEG data?
2. Different scales of Elekta MEG channel types
There is another issue when applying ICA/AMICA to Elekta MEG. The magnetometer and gradiometer channels have very different physical units and numerical scales. For example, the magnetometers and gradiometers are not naturally on the same numerical scale, so directly feeding the raw sensor values into an ICA algorithm may cause one channel type to dominate the numerical optimization. MNE addresses this during ICA preprocessing by applying channel-type-specific scaling/whitening before PCA/ICA.
Would it be possible for pAMICA to provide a similar channel-type-aware scaling option for MEG? For example, something conceptually similar to:
magnetometers → normalize using their channel-type scale
gradiometers → normalize using their channel-type scale
followed by PCA/whitening and AMICA. I think this would be particularly important for Elekta/MEGIN MEG because magnetometers and gradiometers have substantially different units/scales.
Overall question
I would be very interested to know whether pAMICA is intended to support MEG data in the future, and, if so, whether the above approach would be a reasonable way to handle Maxwell-filtered Elekta MEG data. In particular, I would greatly appreciate your advice on whether performing the PCA/SVD rank reduction before AMICA and then transforming the resulting decomposition back to the original sensor space is mathematically valid.
Any response or advice would be greatly appreciated, as I am currently working on applying AMICA to my MEG data.
Activity
neuromechanist commentedon Aug 15, 2026
Thanks for the detailed report — and yes, MEG is meant to be supported. Both issues are real, and they turn out to be coupled in a way worth spelling out.
Short answer: your proposed approach is mathematically valid. I verified the whole path (type-scaling → rank reduction → AMICA → back-projection) on real data made rank-deficient the same way, and it round-trips to ~1e-15. But the back-projection has one non-obvious step, and the scaling question matters because of the rank reduction rather than independently.
1. Non-full-rank data
Reproduced. Taking real 32-channel EEG, projecting it onto its top-20 subspace (the same thing SSS does to MEG) and feeding it in directly:
The cause is sphering. pamica uses Fortran's symmetric ZCA sphere
V diag(1/sqrt(λ)) Vᵀ; in the null directionsλ ≈ 0, so1/sqrt(λ)blows up and the first log-likelihood is already NaN. (Thenan_llstop is the #50 contract: the fit is marked unusable rather than handing back NaN sources.)Your recipe is correct. The one thing to watch is that
get_mixing_matrix()returns A in the sphered space, not sensor space, so you must de-sphere before projecting back throughU_r:That reconstructs the original sensor data to 1.7e-15 relative error.
On the built-in options:
pcakeep/pcadbdo exist and perform PCA reduction inside_preprocess, but neither solves your case today.pcakeep=70on its own keeps the symmetric ZCA form, so the sphere stays 306×306 with rank 70 and AMICA still estimates 306 components from rank-70 data. It avoids the NaN, but it is not the decomposition you want.pcakeep=70, do_approx_sphere=Falseis the genuinely dimension-reducing path, and it currently crashes:RuntimeError: The size of tensor a (70) must match the size of tensor b (306).n_channelsis taken from the input row count and never resized to the kept rank.So external reduction is the reliable route from the Python backends for now.
Worth knowing: the reference Fortran already handles this automatically, and pamica ships it.
amica15.f90does three things we did not port:It detects the numerical rank from the covariance spectrum, sizes the model to it, and keeps a pseudo-inverse to map components back to the original
nxchannels — exactly the procedure you sketched, done for you. That is why AMICA-through-EEGLAB copes with rank-deficient data (average reference, interpolated channels) without the user doing anything.pamica bundles that binary as a runnable engine, so you can use it today:
One catch that bites specifically on MEG:
mineigis an absolute threshold on covariance eigenvalues. EEG in microvolts gives eigenvalues of order 1-100 and the default is fine. MEG in Tesla gives ~1e-26, so every eigenvalue falls below1e-15andnumeigscollapses to 0. Scale your data before handing it to either backend — which is the same conclusion as section 2 below, from a different direction.I have filed the missing rank handling as #223.
2. Magnetometer/gradiometer scaling
The answer is more specific than "yes, add scaling". Tested on the same real data with every other channel rescaled by 1e4:
Σ log(scale) / n_channels— the log-Jacobian of the rescaling. That is the same fit reported on a different data scale, not a different solution; the sphering absorbs the rest.So for Elekta the scaling is essential — not because AMICA needs it, but because it determines which 70 directions survive your SVD. Scale first, then reduce.
Full pipeline
Verified end to end on real rank-deficient data with a 1e4 type-scale mismatch: 1.7e-15 max relative reconstruction error.
What we will add
Both of these should be first-class rather than something you assemble yourself:
mineigdetection, size the model tonumeigs, and carrySpinvsoget_mixing_matrix()returns sensor-space maps directly. This also fixes thedo_approx_sphere=False+pcakeepcrash. Since the reference already does all of this, we treat it as a parity gap rather than a new feature.pamica.mne_compatcurrently sets a unit pre-whitener (ica.pre_whitener_ = np.ones((n_ch, 1))), which is fine for EEG and wrong for mixed mag/grad. Given themineigunit-sensitivity above, this matters for MEG on both backends, not just cosmetically.Thanks for the clear write-up — the rank/scaling interaction in particular was worth measuring, and it turned up a parity gap we would not otherwise have looked for.
sunyuhongwr commentedon Aug 17, 2026
shared_comps error in rank-deficient data
Hi, thank you very much for the recent updates! I reviewed pamica new code and tested the new version with my Maxwell-filtered Elekta MEG data, and it looks like the two issues I previously mentioned have been addressed. This is exactly what I needed for applying pAMICA to Maxwell-filtered Elekta MEG data. Thank you for implementing these changes!
However, I encountered one remaining issue when I enable:
share_comps=True
I get:
RuntimeError:
Component sharing needs an invertible sphere, but it is singular(common with average-referenced or rank-deficient data). Disable share_comps or use full-rank data.
I looked through _identify_shared_comps() and noticed that component sharing currently computes
Spinv = torch.linalg.inv(self.sphere)
A_tilde = Spinv @ self.A
and then calculates the correlation between the de-sphered mixing columns.
I understand why this is problematic for Maxwell-filtered MEG: even though the rank-deficient data are now handled correctly by reducing the effective dimensionality, the original sensor-space sphere remains singular, so it cannot be directly inverted.
My question
Is the invertibility of the original sphere mathematically required for component sharing, or is this mainly a consequence of the current implementation? My understanding is that the purpose of Spinv @ A is to recover the mixing columns in the original sensor/data space and then compare their spatial similarity. If the AMICA solution has already been fitted in the effective rank-r subspace, could we instead map the mixing columns back to the original 306-channel MEG sensor space and calculate the component similarity there?
For example, for Maxwell-filtered MEG:
X∈R (306channel×Timepoint),rank(X)=r≈70
we have an effective subspace representation
X≈UrZ,
where Ur∈R(306channel×Timepoint)
After fitting AMICA in the rank-r space, the mixing columns could potentially be mapped back to the 306-channel sensor space using Ur. Then the correlation between these reconstructed sensor-space mixing maps could be calculated directly, without requiring an inverse of the singular 306-dimensional sphere.
So conceptually, I am wondering whether
rank-reduced AMICA
↓
mixing matrix in effective space
↓
map back to 306-channel sensor space
↓
compare mixing/topographic maps
↓
identify shared components
would be equivalent, or at least theoretically valid, for share_comps.
I am asking because Maxwell-filtered Elekta MEG is intrinsically rank-deficient, so requiring an invertible sensor-space sphere would prevent share_comps from being used even though the main AMICA fitting itself now works correctly. Also, i think share_comps is very useful during analysis.
If the current Spinv @ A formulation is mathematically essential, could you explain why the inverse of the full-rank sphere is required for identifying shared components? Otherwise, would it be possible to adapt share_comps to operate in the effective rank-reduced space or directly on the reconstructed sensor-space mixing maps?
I would be happy to test a modified implementation on my Maxwell-filtered Elekta MEG data.
Thanks again for the excellent updates to pAMICA — the new rank-deficient MEG handling and mag/grad scaling are already very helpful!
@neuromechanist
neuromechanist commentedon Aug 22, 2026
@sunyuhongwr Good question, and your analysis is correct: the invertibility requirement is an implementation artifact, not mathematics.
Spinv @ Aexists only to put the mixing columns back in sensor space before the cosine comparison, and the reference itself never inverts the sphere in the reduced case -- under PCA reduction Fortran'sSpinvis a pseudo-inverse-style back-map of shape(nx, numeigs)(amica15.f90:550-560). So the faithful generalization ispinv(sphere) @ A: identical toinv(sphere) @ Ato machine precision when the sphere is square and full-rank (thecomp_thresh|cos| test cannot flip on a ~1e-15 perturbation), and for a rank-r fit it maps the columns into the retained sensor-space subspace -- which is exactly yourU_rconstruction. Cosine similarity is invariant under a common orthonormal embedding, so comparing the reconstructed 306-channel maps or the rank-70 coordinates gives the same statistic; your proposed pipeline and the pinv formulation are the same operation.This is now tracked as #253 with a fix in progress that removes the RuntimeError entirely rather than gating it. I will ping you when the PR is up -- testing it on your Maxwell-filtered Elekta data would be very welcome, since the repo's sample set has no MEG recordings. Your annotation-rejection PR (#252) is also reviewed and close to merge; see the comment there for what changed.
Make share_comps work on rank-reduced fits (#256)
neuromechanist commentedon Aug 22, 2026
@sunyuhongwr The share_comps fix landed on
dev(#256, closing #253):_identify_shared_compsnow de-spheres with the pseudo-inverse, so component sharing works on rank-reduced fits -- no invertible sphere required, and the constructor no longer rejectsshare_compstogether withpcakeep/pcadb. Full-rank merge decisions are pinned unchanged by tests, and the rank-reduced path is covered on real data projected the way SSS projects MEG. If you can testshare_comps=Trueon your Maxwell-filtered Elekta recordings from currentdev, that would be the best real-world validation we can get -- please report anything odd back on this issue. The annotation-rejection support (#252) is ondevtoo, so both should now work together.Add MLX sharing edge-case tests
Phase 2: port share_comps to the MLX backend (#268)
neuromechanist commentedon Aug 23, 2026
@sunyuhongwr Following up on the earlier ping: everything from that round plus a second wave has now landed on dev via epic #260, and several pieces are directly relevant to your Maxwell-filtered Elekta data.
The share_comps similarity metric is now unified across all backends on de-sphered sensor-space maps (pinv(sphere) @ A, the Fortran Spinv semantics), so component sharing works consistently on rank-deficient data in the torch, numpy, and MLX backends (#258, #263). A numpy bug that crashed ANY multi-model Newton fit (not just the share-collapse case, a dgm broadcast-axis error) is fixed with 1/2/3-model regression tests (#267). The MLX backend now has full feature parity for fitting: component sharing, Newton acceleration (float32, validated against the float64 torch reference to ~1e-5 in the converged LL with zero posdef fallbacks on our sample data), and all five source-density families including the extended-Infomax switcher (#264, #265) — relevant if you want Apple-Silicon speed on your rank ~70 data, where MLX has been the fastest backend in our benchmarks.
If you get a chance to re-run your MEG configuration (share_comps with multi-model, and the bad_* annotation handling from #251/#252) against current dev, we would value the validation — yours is the only real-MEG channel this project has. Happy to dig into anything that looks off.
Add Newton coverage: 3-model, rank-reduced, three-way (#284)
sunyuhongwr commentedon Aug 24, 2026
Thanks for the detailed explanation and for carefully working through the implementation and validating the behavior against the Fortran reference. I really appreciate the thorough investigation. Thanks also for tracking this as #253 #256 and for working on a proper fix.
TEST IN REAL MEG DATA WITH BAD ANNOTATION #252 #251
I tested the change at dev version(https://github.com/sccn/pAMICA.git (d392ba0)) from the
sccn/pAMICArepository with the following two configurations:Test 1 —
pcakeep=Nonepicks: meg
max_iter: 1000
n_models: 5
num_mix_comps: 3
lrate: 0.01
do_reject: False
share_comp: True
pcakeep: None
do_approx_sphere: True
reject_by_annotation: True
device: cuda
verbose: True
Test 2 — pcakeep=20
picks: meg
max_iter: 1000
n_models: 5
num_mix_comps: 3
lrate: 0.01
do_reject: False
share_comp: True
pcakeep: 20
do_approx_sphere: True
reject_by_annotation: True
device: cuda
verbose: True
The test with pcakeep=None passed successfully. get_model_probability() also worked as expected: the probabilities were correctly returned with the same number of samples as the original data, and the samples corresponding to the bad annotation periods were returned as NaN.
I also tested pcakeep=20, but the results appeared to be the same as those obtained with pcakeep=None. In other words, under this particular configuration, pcakeep=20 does not appear to result in an effective PCA reduction.Unfortunately, I haven't had enough time yet to thoroughly inspect the updated implementation, so I cannot currently identify exactly where the issue might be or whether this behavior is expected under these settings. I will investigate it further when I have more time.
Thank you again for your time, effort, and contribution to improving the package. I really appreciate your work on this.
@neuromechanist
neuromechanist commentedon Aug 24, 2026
@sunyuhongwr Thank you for the real-data validation — Test 1 passing (share_comps + reject_by_annotation on 5-model, 306-channel Maxwell-filtered data, with the NaN-timeline scoring behaving as designed) is exactly the confirmation this project could not produce internally, and we are recording it as the field validation for #251/#252/#253/#256.
On Test 2: I investigated pcakeep=20 immediately, and the forwarding path is verified working — AMICAICA.fit(raw, pcakeep=20) reduces to n_components_ == 20 on our bundled data, and the regression suite pins pcakeep and automatic rank detection combined with annotation rejection through the wrapper (pamica/tests/mne_tests/test_annotation_rank_reduction.py, added after your earlier report). Two observations that may explain what you saw. First, get_model_probability() returns shape (n_models, n_times) regardless of the retained rank, so its output genuinely cannot distinguish a reduced fit from a full-rank one — if that (or the annotation NaN pattern) was the artifact you compared, both runs will look identical even when the reduction applied correctly. The direct checks are ica.n_components_ (should be 20), to_mne_ica().pca_components_.shape, or the fit log line 'Data covariance has numerical rank R of N; fitting R sources'. Second, a misspelled fit keyword raises TypeError rather than being dropped silently (we verified: share_comp without the s raises immediately), so if your run completed, every kwarg either reached the backend or was filtered by your own configuration layer before the call — worth checking if your harness prunes kwargs against an allowlist, since that is the one place pcakeep could vanish without an error from us.
Also relevant to your exact configuration: yesterday we fixed mir() to recognize automatically detected rank reduction (it previously raised an opaque LinAlgError on Maxwell-filtered-class data with no explicit pcakeep; now a clear ValueError, #283, on dev), and the numpy backend's multi-model Newton crash you would have hit via share_comps collapse is fixed with 1/2/3-model regression tests (#267). If the n_components_ check still shows no reduction on your data with pcakeep passed directly to fit(), that would be a genuine bug specific to your data path and we would want the fit log output — happy to dig in.
sunyuhongwr commentedon Aug 24, 2026
Thank you for the detailed explanation and for pointing me toward the direct checks.
I re-reviewed my code and added the following checks for n_components_, the AMICA sphere shape, and the input channel count. I then tested the updated code on a cropped 30-second dataset. The results now confirm that pcakeep=20 is working as expected, and the reported n_components_ is correctly reduced to 20.
After reviewing my previous code more carefully, I found that the issue was actually a small typo on my side: I had accidentally written pcakeep as packeep in one part of my testing code. I apologize for the confusion, and I’m sorry that this led to an unnecessary investigation on your side.
The get_model_probability() behavior and the good_sample_mask reconstruction also work as expected. In particular, the model probability retains the original time-axis length, with rejected samples represented by NaN, while n_components_ correctly reflects the PCA-reduced dimensionality.
I will continue with the full test on the complete MEG dataset. I need a little more time to finish the complete validation, especially on the long real-world recording, but I will report back once the testing is finished.
Thank you again for your careful investigation, detailed explanation, and all the work you have put into improving the robustness of the package. I really appreciate it.
code(after AMICAICA.fit) :
``print("========================================")
print("AMICA PCA / rank information")
print("========================================")
print("Input channels:", len(ica.ch_names_))
print("AMICA n_components_:", ica.n_components_)
if ica.amica_.model_ is not None:
print("AMICA sphere shape:", ica.amica_.model_.sphere.shape)
print("========================================")
@neuromechanist
neuromechanist commentedon Aug 24, 2026
@sunyuhongwr No apology needed — the investigation was genuinely useful on our side: it produced the wrapper-level regression tests for pcakeep and auto-rank combined with annotation rejection, and while walking your configuration we found and fixed a real bug on that exact path (mir() raising an opaque error under automatically detected rank reduction, #283). Your checks output looks exactly right: n_components_ 20, sphere (20, 306), full-length probability timeline with NaN at the annotated spans.
Take whatever time the full-length recording needs — that long-run validation on real data is the last mile we cannot cover ourselves, and we will hold #221 open for it. Thank you for the careful, reproducible reports; they have directly shaped this package's test suite.
sunyuhongwr commentedon Aug 24, 2026
Thank you for the kind words and for explaining how the investigation contributed to the regression tests. I’m glad that the testing was useful on your side as well.
I have now completed the test on the full-length MEG recording using the same configuration as before:
picks: meg
max_iter: 1000
n_models: 5
num_mix_comps: 3
lrate: 0.01
do_reject: False
share_comp: True
pcakeep: 20
do_approx_sphere: True
device: cuda
The full-length recording ran successfully with pcakeep=20, and the PCA reduction was correctly applied. The model probability output also behaved as expected, including reconstruction to the original time axis with NaN values at the rejected annotation periods.


I also tested the PMI calculation on the fitted models, and it completed successfully. For example, below is the PMI heatmap for one of the five AMICA models:
also plot the model probability:
(note:plot fig bin size is 5s, sample rate 250hz, so some bad segement seems to discontinuous.)
So at this point, the full-length real MEG dataset appears to pass the complete workflow successfully, including PCA reduction, shared components, annotation rejection, model probability reconstruction, and PMI calculation.
Thanks again for your careful work on this and for keeping the issue open for real-data validation. I’m happy to confirm that the full-length test is now working as expected.
@neuromechanist
neuromechanist commentedon Aug 24, 2026
@sunyuhongwr This completes the loop, and it is a significant milestone for the project: your full-length run is the first end-to-end production validation of pamica on real Maxwell-filtered MEG — the data class that motivated this issue and that our CI cannot cover. Closing #221 with the record of what your reports drove: the pinv(sphere) sensor-space sharing metric unified across all backends (#253/#256/#258), rank-deficiency support through the numerical-rank machinery (#223), bad_* annotation rejection with timeline-faithful scoring (#251/#252, your own PR), the multi-model Newton broadcast fix (#267), the mir() auto-rank guard (#283), and the wrapper-level regression suite that now pins your exact configuration (annotations x pcakeep x sharing) on every CI run.
If anything surfaces on future recordings — or when you want the MLX backend for Apple-hardware runs (transform/save-load are the next epic) — please open a fresh issue; reports of your quality are the best QA this project gets. Thank you.
neuromechanist commentedon Sep 1, 2026
@sunyuhongwr pamica v0.3.3 is now on PyPI (pip install -U pamica), carrying everything you field-validated here from dev: rank-deficiency support, share_comps on rank-reduced fits with the unified sensor-space metric, your bad_* annotation rejection with timeline-faithful scoring, the multi-model Newton fix, and the mir() auto-rank guard, plus the MLX fitting-parity work. Your Maxwell-filtered runs are the reason this release exists in its current shape -- thank you again. Release notes: https://github.com/sccn/pAMICA/releases/tag/v0.3.3