You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
So a colleague of mine was handed a set of files that had been pre-processed in EEGLAB. The data was read via mne.read_epochs_eeglab(). When computing the noise covariance via mne.compute_covariance() and visualizing the results via Covariance.plot(), we noticed that the data looked a bit odd. Turns out that during preprocessing, artifact rejection via ICA had been carried out, and some ICs had been removed. So the data was now rank-deficient. However, MNE didn't "pick this up" – in fact, mne.compute_rank() assumed the rank was full even with rank=None to force an actual estimation. And according to raw.info, obviously, the rank was full as well.
So I'm wondering how to best deal with this now. We could certainly pass rank=dict(eeg=true_rank) to all functions that require a rank input. But this seems cumbersome and error-prone, and I'm not sure if there are other places where this situation could lead to errors? I would prefer just being able to do something like, raw.rank = true_rank; or, even better, the EEGLAB import should do something of that sort. A way to detect rank deficiency after ICA is simply by checking if the number of sensors is equal to the number of ICs in the EEG structure:
data=scipy.io.loadmat('myfile.set')
n_comps, n_sensors=data['EEG']['icaweights'][0, 0].shapeifn_comps==n_sensors:
print('Data has full rank')
else:
print(f'Data has rank {n_comps}')
(Of course this only works if no (avg) reference has been set)
Also just looking at what MNE's ICA.apply() does, it also appears to me that a potential change of data rank is not "documented" anywhere. Is this not bound to lead to issues?
one intuition is that the EEGLAB data were stored to disk in single precision and our rank detection code does not use thresholds for this
So you think that, under normal circumstances, rank calculation should work? Because I also remember that in the mne-study-template, we had to switch to using rank='info', because the default didn't work with some MEG datasets…
Can you really determine the rank of the channel data based on the number of ICs? Especially in the case where some ICs are zeroed out and the remaining ICs are back-projected to channel space, I'm not sure if determining the rank is that easy. How does MNE compute the rank of the data matrix? SVD?
Can you really determine the rank of the channel data based on the number of ICs? Especially in the case where some ICs are zeroed out and the remaining ICs are back-projected to channel space, I'm not sure if determining the rank is that easy.
I'll be totally honest with you and say that I have no idea. All I can say is that when we used this approach, we got much more sensible-looking results with our data:
EEGLAB data noise cov estimated with rank=None
EEGLAB data noise cov estimated with rank=n_comps_from_EEGLAB_icaweights
I agree that in this special case it might make sense to infer the rank from the retained components (although strictly speaking, this is probably not the rank from a mathematical perspective). Can you quickly explain the plots to me? What is the noise covariance and what do these plots show?
I agree that in this special case it might make sense to infer the rank from the retained components (although strictly speaking, this is probably not the rank from a mathematical perspective). Can you quickly explain the plots to me? What is the noise covariance and what do these plots show?
Based on epoched data, the covariance of the pre-stimulus periods was estimated via mne.compute_covariance, with the rank parameter set to either None or the number of retained ICs. The figures I posted are the SVD spectra plots based on these covariance estimates (generated via Covariance.plot()).
My layman's way of reading this plot is that the ordinate shows how much variance is explained by the data, and the abscissa corresponds to the sensors, ordered descending by explained variance. So as you move along the abscissa from left to right, once you reach the number of channels that is equal to the data rank, you will see a steep decline in explained variance.
In the first figure, there is an unusual step in this plot at around sensor ~50; investigation of the data showed that only 48 ICs had been retained, so we then set rank=48 in our call to compute_covariance, which produced the second figure. And this one looks much more like what I would expect.
@agramfort@dengemann
Bummer. So. How to proceed from here, then? @agramfort suggested this might have to do with floating point precision in the EEGLAB data set… how could we handle that?
I had a quick look at the preprocessing pipeline, which was based on PREP, and I couldn't find any hints that PCA was used.
I've shared the data with @agramfort, but if anyone else would like to take a look too, let me know.
This is a MWE used to derive my observations.
(Plots look a little different because this is a different participant now, but the pattern is the same as what can be seen in the figures I posted above)
importmneimportmatplotlibfromscipy.ioimportloadmatmatplotlib.use('Qt5agg')
fname='eeglab_epochs.set'epochs=mne.read_epochs_eeglab(fname)
# Estimating covariance with rank=Nonecov=mne.compute_covariance(epochs=epochs, tmax=0, method='auto', rank=None)
cov.plot(epochs.info)
# Estimating covariance with rank derived from number of retaind ICseeglab_data=loadmat(fname)['EEG']
n_components, n_sensors=eeglab_data['icaweights'][0, 0].shaperank=dict(eeg=n_components)
cov=mne.compute_covariance(epochs=epochs, tmax=0, method='auto', rank=rank)
cov.plot(epochs.info)
Please ignore my ignorance here, but: which SVD spectra do you suggest to overlay?
Multiple subjects, such that you get a feeling for what is normal and where to suspect the real common rank.
Ok, could be nice I guess :)
But in my specific use case, this wouldn't have helped, as apparently the rank deficiency I observed was introduced by interpolation of bad channels, followed by a PCA step before doing ICA. Since the number of interpolated channels can vary between participants, I don't think a "common" rank would make sense here.
providing a useful hint when they import potentially rank-deficient data.
Sure, why not as long as we have a clear criterion for detecting that.
I think the code snippet I provided above should be a reliable indicator for this specific use case. But I'd be more comfortable if some EEGLAB experts were to confirm this :)
Also I'm still concerned about the fact that a user would have to manually keep track of rank-changing operations from that point onward.
Things can get more complicated and cannot be easily predicted once head movements and other non-stationarities come into play, especially in MEG.
If you want to really be sure what's going on you must do it by hand and document things using plots.
Can we not offer something like (...) keep track of the new rank somewhere, and be good?
I am not sure I understand where you want to go. Why would you offer a function to reduce the rank (who needs to do this anyways knows how to do this)?
It's not so much about reducing rank per-se, but to inform MNE that the rank of the data has changed. You see, in the mne-study-template, for example, I'm explicitly passing rank='info'when estimating covariance and when creating the inverse operator. We did this after discovering that rank=None, i.e. rank estimation based on the data alone, didn't yield very usable results with the data we had tested the pipeline on – switching to rank='info' fixed these issues. Now I haven't looked into the code to figure what exactlyrank='info' does, but my undersatanding is that it takes into account projectors, reference channels etc. It would be good if a rank-reducing operating like PCA could be considered and treated accordingly within this existing framework.
don't think a "common" rank would make sense here.
In some contexts a common rank would be the minimum rank, deliberately inducing more rank reduction for some of the datasets.
Anyways, whether comparing subjects or not, cov plots are really amazingly useful.
Is there an MNE tutorial about rank estimation and when rank is important? It sounds like this might be an interesting topic relevant to MNE users.
@cbrnr I think some info can be found here and there. A tutorial on debugging rank issues could be really nice and save some user support time in the future ...
I didn't understand how that PR could fix it until I looked back at...
EEGLAB data noise cov estimated with rank=None
... I realized that I probably misunderstood this plot. Did you have some form of regularization on (e.g., shrunk) during estimation? If so it would explain why the first shelf is only 1e-2 or so below the real data (regularization inflated the eigenvalues). Can you do the same plot of the noise covariance estimated with empirical? You will probably see a much larger shelf at 48 (at least 1e-6 below the largest eigenvalue), and hence using a rtol vs atol like in #7736 could indeed help.
Okay, so I asked my colleagues to provide me with more data. And as is sometimes the case, things were a little messy – I couldn't exactly recreate the figure I posted initially, and it was unclear which dataset and version of MNE were used to generate it. Also turned out I got mixed up between data rank and noise covariance matrix rank rank at some point.
The SVD plots are identical between master and larsoner:rank, as far as I can tell.
Empirical
SHRUNK
Consistency of results
I've tested this on 24 datasets, and the pattern of results is always the same as shown above in all but one dataset: cov. rank (SHRUNK-regularized) is reported as full; while the empirical cov. rank is equal to the 1st dimension of the icaweights matrix and to the rtol-based rank. In one dataset, the computed rank deviates by 1 from the first icaweights matrix dimension (50 vs 51).
Additional information
I was also provided with a list of interpolated channels, and the number of interpolated channels is typically much smaller than the difference between the number of total channels and the first dimension of the icaweights matrix. Since, like I said, the PREP pipeline performs interpolation and rank reduction via PCA before ICA (based on the number of interpolated channels), I am inclined to believe that the icaweights matrix contains the ICs that are to be kept after PCA and (manual) IC rejection.
This is expected because the rank internally is calculated still using atol not rtol, so this result should not change. Basically if you want rtol behavior or custom tol you should use rank = compute_rank(...) manually, then pass the rank to compute_covariance.
Automatic rank estimation will always have this sort of problem where you might miss the shelf. If we try to make it smarter we will almost certainly break some other things that currently work. So I think we just need to document that people need to examine the SVD spectrum of their empirical noise cov first, then ensure that the rank is preserved if they are using an automatic regularizer, because if the rank is not computed properly that automatic regularizer will inflate the "zero" eigenvalues.
In the empirical case, it doesn't matter what you pass as rank in compute_covariance(..., rank=...) because it's not used, and the resulting matrix is unregularized. And then when you compute the rank of that matrix using rtol, you get 48.
In the shrunk case, when you do rank=None when computing the covariance, internally we estimate the rank of the covariance matrix using atol, which will mis-estimate the rank to be 63. The covariance is regularized in this dim-63 space, so then the eigenvalues that probably should get zero get inflated by the regularization. At that point it doesn't matter if you compute the rank of the resulting regularized matrix with atol or rtol because the regularization process has (errantly) moved those "should-be-zero" eigenvalues up to just ~1e-2 below "should-be-nonzero" eigenvalue levels -- you'll get 63 either way.
On the other hand, if you used the rtol method before regularizing the matrix by calling rank = compute_rank(..., rank_tol_kind='relative'), you will get back correctlry that rank = dict(eeg=48), and then when you pass this to compute_covariance(..., rank=rank, method='shrunk') it will correctly use the subspace of dimension 48 when regularizing, and then if you compute the rank of that matrix using rtol or atol (shouldn't matter at that point) they should both be 48.
Activity
hoechenberger commentedon May 5, 2020
Also just looking at what MNE's
ICA.apply()does, it also appears to me that a potential change of data rank is not "documented" anywhere. Is this not bound to lead to issues?agramfort commentedon May 5, 2020
hoechenberger commentedon May 5, 2020
So you think that, under normal circumstances, rank calculation should work? Because I also remember that in the
mne-study-template, we had to switch to usingrank='info', because the default didn't work with some MEG datasets…cbrnr commentedon May 5, 2020
Can you really determine the rank of the channel data based on the number of ICs? Especially in the case where some ICs are zeroed out and the remaining ICs are back-projected to channel space, I'm not sure if determining the rank is that easy. How does MNE compute the rank of the data matrix? SVD?
agramfort commentedon May 5, 2020
hoechenberger commentedon May 5, 2020
@cbrnr
I'll be totally honest with you and say that I have no idea. All I can say is that when we used this approach, we got much more sensible-looking results with our data:
EEGLAB data noise cov estimated with
rank=NoneEEGLAB data noise cov estimated with
rank=n_comps_from_EEGLAB_icaweightscbrnr commentedon May 5, 2020
I agree that in this special case it might make sense to infer the rank from the retained components (although strictly speaking, this is probably not the rank from a mathematical perspective). Can you quickly explain the plots to me? What is the noise covariance and what do these plots show?
dengemann commentedon May 5, 2020
Im my experience the # of ica components does not give a strong clue on the rank, it can coincide with it but often it does not.
agramfort commentedon May 5, 2020
hoechenberger commentedon May 5, 2020
@cbrnr
Based on epoched data, the covariance of the pre-stimulus periods was estimated via
mne.compute_covariance, with therankparameter set to eitherNoneor the number of retained ICs. The figures I posted are the SVD spectra plots based on these covariance estimates (generated viaCovariance.plot()).My layman's way of reading this plot is that the ordinate shows how much variance is explained by the data, and the abscissa corresponds to the sensors, ordered descending by explained variance. So as you move along the abscissa from left to right, once you reach the number of channels that is equal to the data rank, you will see a steep decline in explained variance.
In the first figure, there is an unusual step in this plot at around sensor ~50; investigation of the data showed that only 48 ICs had been retained, so we then set
rank=48in our call tocompute_covariance, which produced the second figure. And this one looks much more like what I would expect.agramfort commentedon May 5, 2020
hoechenberger commentedon May 5, 2020
@agramfort @dengemann
Bummer. So. How to proceed from here, then? @agramfort suggested this might have to do with floating point precision in the EEGLAB data set… how could we handle that?
hoechenberger commentedon May 5, 2020
I don't think PCA dimensionality reduction was used, but I would need to check
agramfort commentedon May 5, 2020
hoechenberger commentedon May 5, 2020
I had a quick look at the preprocessing pipeline, which was based on PREP, and I couldn't find any hints that PCA was used.
I've shared the data with @agramfort, but if anyone else would like to take a look too, let me know.
This is a MWE used to derive my observations.
(Plots look a little different because this is a different participant now, but the pattern is the same as what can be seen in the figures I posted above)
15 remaining items
dengemann commentedon May 6, 2020
@hoechenberger btw. I could not find that URL ... nice idea though.
cbrnr commentedon May 6, 2020
@dengemann I agree! So this leaves the info message for imported EEGLAB data for this issue.
Is there an MNE tutorial about rank estimation and when rank is important? It sounds like this might be an interesting topic relevant to MNE users.
hoechenberger commentedon May 6, 2020
@dengemann
Ok, could be nice I guess :)
But in my specific use case, this wouldn't have helped, as apparently the rank deficiency I observed was introduced by interpolation of bad channels, followed by a PCA step before doing ICA. Since the number of interpolated channels can vary between participants, I don't think a "common" rank would make sense here.
I think the code snippet I provided above should be a reliable indicator for this specific use case. But I'd be more comfortable if some EEGLAB experts were to confirm this :)
It's not so much about reducing rank per-se, but to inform MNE that the rank of the data has changed. You see, in the
mne-study-template, for example, I'm explicitly passingrank='info'when estimating covariance and when creating the inverse operator. We did this after discovering thatrank=None, i.e. rank estimation based on the data alone, didn't yield very usable results with the data we had tested the pipeline on – switching torank='info'fixed these issues. Now I haven't looked into the code to figure what exactlyrank='info'does, but my undersatanding is that it takes into account projectors, reference channels etc. It would be good if a rank-reducing operating like PCA could be considered and treated accordingly within this existing framework.@cbrnr
@dengemann
Haha, not sure the others would be too happy about it… 😂 But if there are no objections, I'd be the first to sign up!
dengemann commentedon May 6, 2020
In some contexts a common rank would be the minimum rank, deliberately inducing more rank reduction for some of the datasets.
Anyways, whether comparing subjects or not, cov plots are really amazingly useful.
@cbrnr I think some info can be found here and there. A tutorial on debugging rank issues could be really nice and save some user support time in the future ...
hoechenberger commentedon May 6, 2020
Just for the record, I just pulled @larsoner's #7736, and this is what I get with the problematic EEGLAB data:
… which is good!
So… merely a precision issue, like @agramfort suggested??
larsoner commentedon May 6, 2020
I didn't understand how that PR could fix it until I looked back at...
... I realized that I probably misunderstood this plot. Did you have some form of regularization on (e.g.,
shrunk) during estimation? If so it would explain why the first shelf is only 1e-2 or so below the real data (regularization inflated the eigenvalues). Can you do the same plot of the noise covariance estimated withempirical? You will probably see a much larger shelf at 48 (at least 1e-6 below the largest eigenvalue), and hence using artolvsatollike in #7736 could indeed help.hoechenberger commentedon May 6, 2020
@larsoner Will get back to you tomorrow!
hoechenberger commentedon May 11, 2020
Okay, so I asked my colleagues to provide me with more data. And as is sometimes the case, things were a little messy – I couldn't exactly recreate the figure I posted initially, and it was unclear which dataset and version of MNE were used to generate it. Also turned out I got mixed up between data rank and noise covariance matrix rank rank at some point.
So I just started from scratch.
MWE
This is the MWE I came up with. Please find the example dataset here:
https://drive.google.com/open?id=13aiakuwp1HmJt-BYsRISCk6XcdO2INuf
Output on
masterOutput on
larsoner:rank(#7736)SVD Plots
The SVD plots are identical between
masterandlarsoner:rank, as far as I can tell.Empirical
SHRUNK
Consistency of results
I've tested this on 24 datasets, and the pattern of results is always the same as shown above in all but one dataset: cov. rank (SHRUNK-regularized) is reported as full; while the empirical cov. rank is equal to the 1st dimension of the
icaweightsmatrix and to thertol-based rank. In one dataset, the computed rank deviates by 1 from the firsticaweightsmatrix dimension (50 vs 51).Additional information
I was also provided with a list of interpolated channels, and the number of interpolated channels is typically much smaller than the difference between the number of total channels and the first dimension of the
icaweightsmatrix. Since, like I said, the PREP pipeline performs interpolation and rank reduction via PCA before ICA (based on the number of interpolated channels), I am inclined to believe that theicaweightsmatrix contains the ICs that are to be kept after PCA and (manual) IC rejection.larsoner commentedon May 11, 2020
This is expected because the rank internally is calculated still using
atolnotrtol, so this result should not change. Basically if you wantrtolbehavior or customtolyou should userank = compute_rank(...)manually, then pass theranktocompute_covariance.Automatic rank estimation will always have this sort of problem where you might miss the shelf. If we try to make it smarter we will almost certainly break some other things that currently work. So I think we just need to document that people need to examine the SVD spectrum of their
empiricalnoise cov first, then ensure that the rank is preserved if they are using an automatic regularizer, because if the rank is not computed properly that automatic regularizer will inflate the "zero" eigenvalues.hoechenberger commentedon May 11, 2020
But this still doesn't explain why I (correctly) get
no? Or is the regularization in
compute_covarianceperformed before callingcompute_rank?Edit Never mind, I guess this question didn't make too much sense ;) I'm still slightly confused, though!
larsoner commentedon May 11, 2020
In the empirical case, it doesn't matter what you pass as
rankincompute_covariance(..., rank=...)because it's not used, and the resulting matrix is unregularized. And then when you compute the rank of that matrix usingrtol, you get 48.In the
shrunkcase, when you dorank=Nonewhen computing the covariance, internally we estimate the rank of the covariance matrix usingatol, which will mis-estimate the rank to be 63. The covariance is regularized in this dim-63 space, so then the eigenvalues that probably should get zero get inflated by the regularization. At that point it doesn't matter if you compute the rank of the resulting regularized matrix withatolorrtolbecause the regularization process has (errantly) moved those "should-be-zero" eigenvalues up to just ~1e-2 below "should-be-nonzero" eigenvalue levels -- you'll get 63 either way.On the other hand, if you used the
rtolmethod before regularizing the matrix by callingrank = compute_rank(..., rank_tol_kind='relative'), you will get back correctlry thatrank = dict(eeg=48), and then when you pass this tocompute_covariance(..., rank=rank, method='shrunk')it will correctly use the subspace of dimension 48 when regularizing, and then if you compute the rank of that matrix usingrtoloratol(shouldn't matter at that point) they should both be 48.hoechenberger commentedon May 12, 2020
Thanks for the explanation, @larsoner!
So I guess what this boils down to, in the end, is improving the docs?
larsoner commentedon May 12, 2020
Yeah I think so