Skip to content

Import ICA results from EEGLAB #6917

Closed
mne-tools/mne-testing-data
#55

Description

@christian-oreilly

Describe the problem

EEG .set files can contain ICA results. Related data are populated in fields icaweights, icasphere, and icawinv as far as I know. Although users can build mne.preprocessing.ICA objects by hand from these fields, as proposed in here, this requires a good knowledge of the internals of MNE to deal correctly with pre-whitening and similar preprocessing steps such that the results obtained in EEGLAB are reproducible in MNE. It is also error-prone.

Describe your solution

To add an import function to MNE to import ICA components from EEGLAB .set files in a transparent manner.

Activity

  1. cbrnr commented on Oct 5, 2019

    @cbrnr
    Contributor

    I'll take a look.

  2. christian-oreilly commented on Oct 5, 2019

    @christian-oreilly
    ContributorAuthor

    Let me know how it goes. I will need this pretty soon for my analyses so I can code it if needed and share the piece of code I'll come up with. But if you already have some useful code lying around, let me know. It would save me a bit of head-scratching!

  3. christian-oreilly commented on Oct 7, 2019

    @christian-oreilly
    ContributorAuthor

    A small tentative snippet of code.

    from eegip.utils import loadmat
    from mne.preprocessing import ICA
    import numpy as np
    from mne.io import read_raw_eeglab
    
    file_name = '/project/def-emayada/eegip/london/derivatives/lossless/sub-s601/ses-m06/eeg/sub-s601_ses-m06_eeg_qcr.set'
    
    def read_eeglab_ica(file_name):
        mat_file = loadmat(file_name)
    
        ica_ind = mat_file["EEG"]["chaninfo"]["icachansind"]-1
        ch_names = np.array([chan["labels"] for chan in mat_file["EEG"]["chanlocs"]])[ica_ind]
    
    
        ica = ICA(method='imported_eeglab', n_components=len(ch_names))  
    
        mat_file = loadmat(file_name)
    
        ica.current_fit = "eeglab"
        ica.ch_names = ch_names.tolist()
        ica.n_pca_components = None 
        ica.max_pca_components = len(ica.ch_names)
        ica.n_components_ = len(ica.ch_names)
    
        ica.pre_whitener_ = np.ones((ica.n_components_, 1))
        ica.pca_mean_ = np.zeros(ica.n_components_)
        ica.pca_components_ = mat_file["EEG"]["icasphere"]
    
        ica.unmixing_matrix_ = mat_file["EEG"]["icaweights"]
        ica.mixing_matrix_ = mat_file["EEG"]["icawinv"]
        
        return ica
    
    raw_data = read_raw_eeglab(file_name, preload=True)
    ica.apply(raw_data)
    

    A few things. The loadmat function is just a version of scipy.io.loadmat that does a better job at reading mat files, in line of what is discussed here https://stackoverflow.com/a/29126361/1825043

    Not sure I got right the MNE-EEGLAB correspondence for ICA properties. However, I am not even sure that it is possible to have a perfect correspondence because EEGLAB does not export variables expected by MNE such as the pca_mean_ values and because of differences in preprocessing (e.g., sphering versus whitening and such... as discussed in here ). Anyway, this code runs but its output is not really tested yet. I'll work on coding tests to compare results in EEGLAB and MNE but I thought that I would post this preliminary snippet in case more knowledgeable people (e.g., @cbrnr, @agramfort, @larsoner ) have comments that could save me lot of time investigating obvious issues that I would take a long time to debug because of my limited knowledge about ICA algorithms and MNE internals.

  4. larsoner commented on Oct 7, 2019

    @larsoner
    Member

    One hint is that we use mne.externals.pymatreader.read_mat to unify over old-style and new-style .mat files. Regarding the other stuff I'm not sure offhand, hopefully your investigations plus our documentation can make things clear.

  5. christian-oreilly commented on Oct 7, 2019

    @christian-oreilly
    ContributorAuthor

    Thanks for the hint @larsoner . I replaced eegip.utils.loadmat by mne.externals.pymatreader.read_mat and it works without issues with the rest of the snippet. I'll be happy to drop eegip.utils.loadmat and not have to care for this code anymore.

  6. agramfort commented on Oct 7, 2019

    @agramfort
    SponsorMember
  7. christian-oreilly commented on Oct 7, 2019

    @christian-oreilly
    ContributorAuthor

    @agramfort I'll be happy to open a PR when I'll have something suffiently well tested if you think it can help.

  8. agramfort commented on Oct 8, 2019

    @agramfort
    SponsorMember
  9. christian-oreilly commented on Oct 9, 2019

    @christian-oreilly
    ContributorAuthor

    I got some code that I'll prepare for PR. It has been tested using

    from mne.io import read_epochs_eeglab
    from mne.preprocessing import read_eeglab_ica
    from mne.externals.pymatreader import read_mat
    import numpy as np
    import os
    
    mica_root = '/home/christian/Documents/mica_release/'
    file_name = os.path.join(mica_root, 'datasets', 'ap82.set')
    file_name_cleaned_matlab = os.path.join(mica_root, 'datasets', 'ap82.cleaned.set')
    
    epochs = read_epochs_eeglab(file_name)
    epochs_cleaned_matlab = read_epochs_eeglab(file_name_cleaned_matlab)
    
    mark_to_remove = ["manual"]
    mat_file = read_mat(file_name_cleaned_matlab)["EEG"]
    comp_info = mat_file["marks"]["comp_info"]
    
    if len(comp_info["flags"].shape) > 1:
        ind_comp_to_drop = np.unique(np.concatenate([np.where(flags)[0] for flags, label in zip(comp_info["flags"],
                                                                                                comp_info["label"])
                                                     if label in mark_to_remove]))
    else:
        ind_comp_to_drop = np.where(comp_info["flags"])[0]
    
    ica = read_eeglab_ica(file_name_cleaned_matlab)
    eeg_epochs_cleaned = ica.apply(epochs.copy(), exclude=ind_comp_to_drop)
    
    assert (np.all(np.isclose(epochs_cleaned_matlab.get_data(), eeg_epochs_cleaned.get_data())))
    

    The file used for testing has been downloaded here and processed in Matlab using

    file_name_in = '/home/christian/Documents/mica_release/datasets/ap82.set';
    EEG = pop_loadset(file_name_in);
    N_of_Components = 60;
    [EEG.icaweights, EEG.icasphere] = runica(reshape(EEG.data,EEG.nbchan,EEG.pnts*EEG.trials), 'pca', N_of_Components);
    EEG.icawinv    = [];
    EEG.icaact     = [];
    
    flags = zeros(N_of_Components, 1);
    flags(5) = 1;
    flags(32) = 1;
    flags(43) = 1;
    flags(56) = 1;
    s = struct('label', 'manual', ...
               'line_color', [0.7000 0.7000 0.7000],...
               'order', 1,...
               'flags', flags);
    
    EEG.marks.comp_info = [s];
    EEG = eeg_checkset(EEG);
    
    EEG = pop_marks_select_data(EEG,'component marks',[],'labels',{'manual'},'remove','on');
    pop_saveset(EEG, 'filename', [file_name_in(1:end-4) '.cleaned.set']);
    

    I wil prepare the PR but I wont include this test in it because of the dependance on the ap82.set and Matlab. A possibility would be to add both ap82.set and ap82.cleaned.set to the testing datasets of MNE but since it involves adding about 200 MB of data, I do not think it is a good idea. Something with a smaller file could probably be prepared. Alternatively, a test could depend only on ap82.set and a Matlab-python interface library like this one but I do not like the idea of adding an additionnal dependency and a dependency on Matlab.

  10. larsoner commented on Oct 9, 2019

    @larsoner
    Member

    We already have these test files

    https://github.com/mne-tools/mne-testing-data/tree/master/EEGLAB

    If you adapt your code to run on these, then we don't have to add any new data.

  11. larsoner commented on Oct 9, 2019

    @larsoner
    Member

    ... oh, except I guess the bits needed to reconstruct the ICA from what you compute in MATLAB

  12. christian-oreilly commented on Oct 9, 2019

    @christian-oreilly
    ContributorAuthor

    OK. Just seen your comments @larsoner after creating the PR. I can create a separate PR for the tests (or look at how to modify the current PR to include it).
    Yes... so I would need to add two files "test_epochs.cleaned.fdt" and "test_epochs.cleaned.set" based on the Matlab code. I think that this is MUCH better than creating some dependencies on Matlab to generate these files within MNE test suite. I'll look into it.

  13. larsoner commented on Oct 9, 2019

    @larsoner
    Member
  14. christian-oreilly commented on Oct 9, 2019

    @christian-oreilly
    ContributorAuthor

    @larsoner OK, I pushed the dataset. If I understand well your procedure ("Once your PR is merged, ask a maintainer to cut a new release of the testing data"), I need to wait for one of you to merge this PR request to run my tests. I check to hack the value returned by mne.datasets.testing.data_path(verbose=True) to point it to my git repository of mne-testing-data but this code seems a bit involved.

    On a side note, the instructions to run the test does not seems to work on my setup

    $ make test
    python setup.py build_ext -i
    running build_ext
    rm -f .coverage
    py.test -m 'not ultraslowtest' mne
    ERROR: usage: py.test [options] [file_or_dir] [file_or_dir] [...]
    py.test: error: unrecognized arguments: --cov-report=
      inifile: /home/christian/mne-python/setup.cfg
      rootdir: /home/christian/mne-python
    

    You have an idea how to get around this? I'd like to run the tests in their current state before adding my new test...

  15. larsoner commented on Oct 9, 2019

    @larsoner
    Member

    You have an idea how to get around this? I'd like to run the tests in their current state before adding my new test...

    You probably do not have pytest-cov installed

  16. larsoner commented on Oct 9, 2019

    @larsoner
    Member

    ... and to test your specific one you should really do something more like:

    pytest mne/preprocessing/tests/test_ica.py -k test_ica_from_matlab
    

    Doing make test will take forever.

    Then do make flake and make docstyle before pushing your commits to your PR branch. That way you ensure style compliance.

    FYI the md5sum I get for testing 0.75 is 51d2ca16c449bbb27a54f53590283f16

  17. changed the title [-]Import ICA results form EEGLAB[/-] [+]Import ICA results from EEGLAB[/+] on Oct 9, 2019
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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions