Skip to content

Rank estimated from data saved to disk is incorrect if interpolated channels are present  #11523

Closed

Description

@ezemikulan

Description of the problem

Hi, I've noticed that If some channels have been interpolated and the data is saved to disk and then reloaded the estimated rank is not correct. Maybe it has to do with numerical precision when saving the data as in #7727?

Here are the plots from the code pasted below:

Original
cov_original

Reloaded
cov_reloaded

Steps to reproduce

import mne
data_path = mne.datasets.sample.data_path()
raw_fname = data_path / 'MEG' / 'sample' / 'sample_audvis_raw.fif'
raw = mne.io.read_raw_fif(raw_fname)
events = mne.find_events(raw)
epo = mne.Epochs(raw, events)
epo.load_data()
epo.pick_types(eeg=True)

epo.info['bads'] = ['EEG 056', 'EEG 057', 'EEG 058', 'EEG 059', 'EEG 060']
epo.interpolate_bads()

epo.set_eeg_reference('average', projection=True)
epo.apply_proj()

cov = mne.compute_covariance(epo, method='shrunk', tmin=-0.2,
                             tmax=-0.05)

fname_save = 'test-epo.fif'
epo.save(fname_save, overwrite=True)

epo_reload = mne.read_epochs(fname_save)
cov_reload = mne.compute_covariance(epo_reload, method='shrunk', tmin=-0.2,
                                    tmax=-0.05, )
cov.plot(epo.info)
cov_reload.plot(epo_reload.info)

Link to data

No response

Expected results

I would expect the same estimated rank in both cases.

Actual results

The estimated ranks differ.

Additional information

Platform: Linux-5.15.0-60-generic-x86_64-with-glibc2.35
Python: 3.10.6 | packaged by conda-forge | (main, Aug 22 2022, 20:35:26) [GCC 10.4.0]
Executable: /home/eze/soft/anaconda3/envs/mnepy/bin/python
CPU: x86_64: 8 cores
Memory: 31.3 GB
mne: 1.3.0
numpy: 1.23.3 {MKL 2021.4-Product with 4 threads}
scipy: 1.9.3
matplotlib: 3.5.3 {backend=Qt5Agg}
sklearn: 1.1.3
numba: 0.56.3
nibabel: 4.0.2
nilearn: 0.9.2
dipy: 1.5.0
openmeeg: Not found
cupy: Not found
pandas: 1.4.4
pyvista: 0.37.0 {OpenGL 4.5.0 NVIDIA 515.86.01 via NVIDIA GeForce GTX 1070/PCIe/SSE2}
pyvistaqt: 0.9.0
ipyvtklink: 0.2.2
vtk: 9.2.2
qtpy: 2.2.0 {PyQt5=5.15.6}
ipympl: Not found
pyqtgraph: 0.12.3
pooch: v1.6.0
mne_bids: 0.12
mne_nirs: Not found
mne_features: Not found
mne_qt_browser: 0.4.0
mne_connectivity: Not found
mne_icalabel: Not found

Activity

  1. larsoner commented on Mar 2, 2023

    @larsoner
    Member

    Maybe it has to do with numerical precision when saving the data as in #7727?

    Yes I think so. I'm not sure there is much we can do about it unfortunately. My solution/workaround would be to use mne.compute_rank on the Epochs (or raw) directly, then pass this rank to compute_covariance in both cases

  2. drammock commented on Mar 3, 2023

    @drammock
    Member

    @larsoner any thoughts on where in the docs we could add guidance about this?

  3. larsoner commented on Mar 3, 2023

    @larsoner
    Member

    compute_rank would be a natural place but it's not very discoverable. compute_covariance Notes is where it comes up a lot. It also occurs with EEG+ICA preprocessing, though -- and maybe more often there? -- so an ICA tutorial would be another good place.

    It also might make sense to have a dedicated tutorial to rank issues, since it happens in multiple places, including maxwell filtering (esp. with head movement compensation and lots of head movement).

  4. ezemikulan commented on Mar 6, 2023

    @ezemikulan
    ContributorAuthor

    I'm seeing that it has a considerable impact on source modelling results so I think that making it evident in the docs is important.

    Here are the results from the code pasted below:

    original:
    examp_stc_original

    reloaded:
    examp_stc_reload

    Non sure if it might make sense or be viable, but maybe keeping track of the channels that have been interpolated in info and then re-interpolating them on the fly inside compute_rank or compute_covariance to get a better estimate would be a solution.

    Code:

    import mne
    import os.path as op
    from mne.datasets import sample
    from mne.minimum_norm import make_inverse_operator, apply_inverse
    
    data_path = sample.data_path()
    raw_fname = data_path / 'MEG' / 'sample' / 'sample_audvis_filt-0-40_raw.fif'
    
    raw = mne.io.read_raw_fif(raw_fname)  # already has an average reference
    events = mne.find_events(raw, stim_channel='STI 014')
    
    event_id = dict(aud_l=1)  # event trigger and conditions
    tmin = -0.2  # start of each epoch (200ms before the trigger)
    tmax = 0.5  # end of each epoch (500ms after the trigger)
    raw.info['bads'] = ['MEG 2443', 'EEG 053']
    baseline = (None, 0)  # means from the first instant to t = 0
    reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6)
    
    epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,
                        baseline=baseline, reject=reject)
    epochs.load_data()
    epochs.pick_types(eeg=True)
    
    epochs.info['bads'] = ['EEG 057', 'EEG 058', 'EEG 059', 'EEG 060']
    epochs.interpolate_bads()
    
    fname_save = 'test_sm-epo.fif'
    epochs.save(fname_save, overwrite=True)
    
    epochs_reload = mne.read_epochs(fname_save)
    
    fname_fwd = data_path / 'MEG' / 'sample' / 'sample_audvis-eeg-oct-6-fwd.fif'
    fwd = mne.read_forward_solution(fname_fwd)
    
    method = "dSPM"
    snr = 3.
    lambda2 = 1. / snr ** 2
    
    
    stcs = {'original': [], 'reload': []}
    
    for epo, kind in zip([epochs, epochs_reload], ['original', 'reload']):
        noise_cov = mne.compute_covariance(epo, tmax=0., method='shrunk', verbose=True)
    
        fig_cov, fig_spectra = mne.viz.plot_cov(noise_cov, raw.info)
    
        evoked = epo.average()
        inverse_operator = make_inverse_operator(evoked.info, fwd, noise_cov, loose=0.2, depth=0.8)
    
        stc, residual = apply_inverse(evoked, inverse_operator, lambda2,
                                      method=method, pick_ori=None,
                                      return_residual=True, verbose=True)
    
        stc.plot(subjects_dir=op.join(data_path, 'subjects'), initial_time=0.1)
        stcs[kind] = stc
  5. agramfort commented on Mar 7, 2023

    @agramfort
    SponsorMember

    @ezemikulan use

    epo.save(fname_save, fmt="double", overwrite=True)

    it is twice bigger on disk but it fixes your problem.

  6. ezemikulan commented on Mar 7, 2023

    @ezemikulan
    ContributorAuthor

    Great, thanks

  7. drammock commented on Mar 7, 2023

    @drammock
    Member

    compute_rank would be a natural place but it's not very discoverable. compute_covariance Notes is where it comes up a lot. It also occurs with EEG+ICA preprocessing, though -- and maybe more often there? -- so an ICA tutorial would be another good place.

    @larsoner are all these cases ones where the issue only happens on save-load round-trips? If so, I can add a reusable note to the docdict and include it in the notes section of Epochs.save and ICA.save (does it also make sense for Raw.save and Evoked.save? folks can interpolate those too)

    It also might make sense to have a dedicated tutorial to rank issues, since it happens in multiple places, including maxwell filtering (esp. with head movement compensation and lots of head movement).

    This might still be a good idea, I'll make a new issue about that.

  8. larsoner commented on Mar 7, 2023

    @larsoner
    Member

    @larsoner are all these cases ones where the issue only happens on save-load round-trips? If so, I can add a reusable note to the docdict and include it in the notes section of Epochs.save and ICA.save (does it also make sense for Raw.save and Evoked.save? folks can interpolate those too)

    I think usually -- Maxwell filtering is an exception but we have #4676 to track that more or less. Raw and Evoked would also be good places.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions