Skip to content

The computation of the mixing matrix for ICA imported from EEGLAB ICA is broken #7657

Closed

Description

@christian-oreilly

Describe the bug

Commit 23c6aa9 introduced a bug in the PR #6938 as described in the comment 23c6aa9#r413113709

Steps to reproduce

Using an ICA with a number of components smaller than the number of channels, I get the following components with the code as patched with this commit:

image

and using seaborn clustermap on the correlation matrix between these components, I get:

image

Expected results

Now, if I revert this change, I get something more reasonable:

image

image

I unfortunately don't have the "gold truth" to compare with for the components at this time, but it already seems much more reasonable to me...

Proposal

I spotted that the issue here is the change from

    ica.mixing_matrix_ = np.linalg.pinv(ica.pca_components_) @ eeg.icawinv

to

    ica._update_mixing_matrix()  # ==> self.mixing_matrix_ = linalg.pinv(self.unmixing_matrix_)

(Also, shouldn't "u * s" be "u @ s"? It does not seem to make any difference in my specific use case, but conceptually, it should be matrix multiplication, not a broadcasting.)

Apparently, the way EEGLAB defined its variable linalg.pinv(self.unmixing_matrix_) != np.linalg.pinv(ica.pca_components_) @ eeg.icawinv. I find it very hard to align the interfaces of MNE and EEGLAB because the approaches to ICA are a bit different, the naming is different, and so on, which makes it quite confusing. For example, how u @ s relates exactly to EEGLAB icawinv is unclear to me at this point.

This seems to work:

    if n_components < n_ch:
        u, s, v = _safe_svd(eeg.icaweights, full_matrices=False)
        ica.unmixing_matrix_ = u @ s
        ica.pca_components_ = v
    else:
        [...]
    ica.mixing_matrix_ = np.linalg.pinv(ica.pca_components_) @ eeg.icawinv

The down side is that calling ica._update_mixing_matrix() at a later point would introduce a bug. So, an additional (ugly) fix is to store somewhere the value of eeg.icawinv and make ica._update_mixing_matrix() of ica.method == "imported_eeglab" , which would looks like:

def _update_mixing_matrix(self):
    if self.method == "imported_eeglab":
        self.mixing_matrix_ = np.linalg.pinv(self.pca_components_) @ self._eeglab_icawinv         
    else:
        self.mixing_matrix_ = linalg.pinv(self.unmixing_matrix_)

def read_ica_eeglab(fname):
    [...]
    if n_components < n_ch:
        u, s, v = _safe_svd(eeg.icaweights, full_matrices=False)
        ica.unmixing_matrix_ = u @ s
        ica.pca_components_ = v
    else:
        [...]
    ica._eeglab_icawinv = eeg.icawinv  # Not great to add this attribute...
    ica._update_mixing_matrix()

FYI, simply doing

    if n_components < n_ch:
        u, s, v = _safe_svd(eeg.icaweights, full_matrices=False)
        # replace `ica.unmixing_matrix_ = u @ s` by
        ica.unmixing_matrix_ = np.linalg.pinv(np.linalg.pinv(ica.pca_components_) @ eeg.icawinv)
        ica.pca_components_ = v
    else:
        [...]
    ica._update_mixing_matrix() 

does not work. Don't ask me to explain why... Anyway, I can submit a PR with the proposed ugly changes and we can see if we can prettify it somehow... although, at this point, I am at a lost for a clean alignment of MNE and EEGLAB ICA interfaces, so I am not sure I can improve much on this. In any case, I would argue that a working ugly code is preferable to an elegant broken one...

Activity

  1. christian-oreilly commented on Apr 22, 2020

    @christian-oreilly
    ContributorAuthor

    ... and I can see if I can also propose in the PR a second test for this ICA import. I suspect that the current one test only the else part corresponding to the if n_components < n_ch: which might explain why it passes without issues.

  2. larsoner commented on Apr 22, 2020

    @larsoner
    Member

    (Also, shouldn't "u * s" be "u @ s"? It does not seem to make any difference in my specific use case, but conceptually, it should be matrix multiplication, not a broadcasting.)

    s is a vector here so a (properly) broadcasted multiply is the same as a dot with the matrix version of s (np.diag(s))

    So the code:

            u, s, v = _safe_svd(eeg.icaweights, full_matrices=False)
            ica.unmixing_matrix_ = u @ s
    

    Must be broken:

    >>> import numpy as np
    >>> x = np.random.RandomState(0).randn(3, 3)
    >>> u, s, v = np.linalg.svd(x, full_matrices=False)
    >>> s.shape
    (3,)
    >>> (u @ s).shape
    (3,)
    

    You either need to u @ np.diag(s) or use broadcasting to make it do the right thing:

    >>> np.allclose(u @ np.diag(s), u * s)
    True
    

    Can you see if making use of this allows you to make more progress on the unification?

    I am not sure I can improve much on this. In any case, I would argue that a working ugly code is preferable to an elegant broken one...

    Indeed we need to make it work. One issue will be how we store any new values during I/O round trip. But yes making something work in the first place would help.

    and I can see if I can also propose in the PR a second test for this ICA import. I suspect that the current one test only the else part corresponding to the if n_components < n_ch: which might explain why it passes without issues.

    I would actually do this in the opposite order. Write the test that fails in a first commit and push that (after adding any necessary mne-testing-data data, etc.). Then change the ICA code to make the new case and the old case work. That way others can take a look simultaneously -- I'd try to at least look to understand better for example. And we get the benefit of doing true TDD :)

  3. larsoner commented on Apr 22, 2020

    @larsoner
    Member

    Using an ICA with a number of components smaller than the number of channels, I get the following components with the code as patched with this commit:

    Just by eye looking at the maps thought of something -- have you tried tweaking the rtol in any pinv commands used in the code? To me it looks like a pseudoinversion gone wrong, blowing up a component. In particular we might store these matrices in float32 format in which case the default rtol=1e-15 could be wrong after I/O round trip. But even before that, it might be too high.

    If you set them all to something very conservative like rtol=1e-5 and your maps still look crazy, then this is not the problem. Though it could be some errantly set n_components-sort of thing somewhere, if those are used to choose the number of components during any inversion step.

  4. marcpabst commented on Sep 23, 2020

    @marcpabst

    Any progress on this? Just ran into this problem and can confirm that 379a1b9 seems to work fine.

  5. agramfort commented on Sep 23, 2020

    @agramfort
    SponsorMember

    @marcpabst can you share a file with some code that could be the basis of a test ?

  6. marcpabst commented on Sep 23, 2020

    @marcpabst

    Sure. ICA solutions should be fine from a privacy standpoint, I suppose. I might have to remove the actual data but that should not be needed for creating the ICA object anyway. Also, for me, the Info object is None. Btw I'm happy to work on this myself if no one else is atm.

  7. agramfort commented on Sep 23, 2020

    @agramfort
    SponsorMember
  8. christian-oreilly commented on Sep 23, 2020

    @christian-oreilly
    ContributorAuthor

    In case it can be of any help, here is the "diff" from the version I use:

    diff --git a/mne/preprocessing/ica.py b/mne/preprocessing/ica.py
    index ae9bf6c45..0f579df71 100644
    --- a/mne/preprocessing/ica.py
    +++ b/mne/preprocessing/ica.py
    @@ -709,7 +709,10 @@ class ICA(ContainsMixin):
             self.current_fit = fit_type
     
         def _update_mixing_matrix(self):
    -        self.mixing_matrix_ = linalg.pinv(self.unmixing_matrix_)
    +        if self.method == "imported_eeglab":
    +            self.mixing_matrix_ = np.linalg.pinv(self.pca_components_) @ self._eeglab_icawinv
    +        else:
    +            self.mixing_matrix_ = linalg.pinv(self.unmixing_matrix_)
     
         def _update_ica_names(self):
             """Update ICA names when n_components_ is set."""
    @@ -2545,11 +2548,13 @@ def read_ica_eeglab(fname):
             # sphere = eye(urchans), so let's use SVD to get our square
             # weights matrix (u * s) and our PCA vectors (v) back
             u, s, v = _safe_svd(eeg.icaweights, full_matrices=False)
    -        ica.unmixing_matrix_ = u * s
    +        ica.unmixing_matrix_ = u @ s
             ica.pca_components_ = v
         else:
             ica.unmixing_matrix_ = eeg.icaweights
             ica.pca_components_ = eeg.icasphere
    +    ica._eeglab_icawinv = eeg.icawinv
         ica._update_mixing_matrix()
    +
         ica._update_ica_names()
         return ica
    

    I guess I did not have time to make a proper PR for that. My immediate concerns more often leans toward having code that simply works (at the expense of aesthetics or generalizability) when I am working on a specific analysis... so this "works" but it may be less well integrated than what would be an acceptable solution for a proper python-mne PR.

  9. agramfort commented on Sep 25, 2020

    @agramfort
    SponsorMember
  10. marcpabst commented on Sep 25, 2020

    @marcpabst

    Here you go. I set all data to 0. but otherwise, this file should work.

    Oh, I forgot to rename the file to *.set, sorry.

    eeg.zip

  11. agramfort commented on Sep 25, 2020

    @agramfort
    SponsorMember
    >>> ica =  mne.preprocessing.ica.read_ica_eeglab('eeg.mat')
    >>> ica.plot_components()
    

    RuntimeError: The ICA's measurement info is missing. Please fit the ICA or add the corresponding info object.

    you don't get a proper info when reading from EEGLAB?

  12. marcpabst commented on Sep 25, 2020

    @marcpabst

    I do when using read_raw_eeglab(). Here's my working code. Note that I have to re-set the montage because coordinates directly imported from EEGLAB are not rendered correctly (eeg_with_montage.zip).

    import mne
    
    ica = mne.preprocessing.ica.read_ica_eeglab("eeg.set")
    raw = mne.io.read_raw_eeglab("eeg.set")
    
    ica.info = raw.info
    
    ica._update_ica_names()
    
    besa = mne.channels.read_custom_montage("standard-10-5-cap385.elp")
    ica.info.set_montage(besa)
    
    ica.plot_components()

    Looks like this to me:
    image

    EDIT: Here is the aforementioned problem with imported EEGLAB coordinates:
    image

  13. agramfort commented on Sep 25, 2020

    @agramfort
    SponsorMember
  14. marcpabst commented on Sep 25, 2020

    @marcpabst

    Really weird. I'm on 0.21.0 and the code I posted works fine. Although using ica.info.set_montage(besa, match_case=False) might help?

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