Skip to content

MRG: Add whitening to plots - #4799

Merged
agramfort merged 11 commits into
mne-tools:masterfrom
larsoner:whitening
Feb 28, 2018
Merged

agramfort merged 11 commits into
mne-tools:masterfrom
larsoner:whitening

Conversation

@larsoner

@larsoner larsoner commented Nov 30, 2017 •

Copy link
Copy Markdown
Member

Need to:

  • fill out docstrings
  • add tests
  • update whats_new.rst

Will post CircleCI result once it comes up.

Closes #3926.

@larsoner

Copy link
Copy Markdown
Member Author

@larsoner

Copy link
Copy Markdown
Member Author

cc @olafhauk feel free to try this out to see if it addresses your use case from #3926

@codecov

codecov Bot commented Dec 1, 2017 •

Copy link
Copy Markdown

Codecov Report

Merging #4799 into master will increase coverage by 4.02%.
The diff coverage is 96.09%.

@@            Coverage Diff             @@
##           master    #4799      +/-   ##
==========================================
+ Coverage   83.66%   87.68%   +4.02%     
==========================================
  Files         348      348              
  Lines       62410    62321      -89     
  Branches    10736    10729       -7     
==========================================
+ Hits        52215    54647    +2432     
+ Misses       7443     4927    -2516     
+ Partials     2752     2747       -5

@larsoner larsoner changed the title WIP: Add whitening to plots MRG: Add whitening to plots Dec 1, 2017
@larsoner

larsoner commented Dec 1, 2017

Copy link
Copy Markdown
Member Author

This is now ready for review/merge from my end

@agramfort

Copy link
Copy Markdown
Member

if you pass a noise cov that does not contain a certain channel you should remove it as presently when I click on a bad channel I get errors such as:

  File "/Users/alex/work/src/mne-python/mne/cov.py", line 1639, in compute_whitener
    % missing)
RuntimeError: Not all channels present in noise covariance:
['MEG 2443']

@larsoner

Copy link
Copy Markdown
Member Author

@agramfort

Copy link
Copy Markdown
Member

@larsoner you need to rebase this one

Comment thread mne/viz/epochs.py
noise_cov : instance of Covariance | str | None
Noise covariance used to whiten the data while plotting.
Whitened data channels are scaled by ``scalings['whitened']``,
and their channel names are shown in italic.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why the str option?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

now I see that it is to be able to read from file from disk.
Please document it.

@@ -78,181 +78,184 @@ def test_plot_evoked():
import matplotlib.pyplot as plt
rng = np.random.RandomState(0)
evoked = _get_epochs().average()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you explain me the big diff in this file?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is no reason to have the with warnings.catch_warnings in there -- it could be masking useful warnings (and might have been, don't remember)

@agramfort

Copy link
Copy Markdown
Member

if I toggle off the bad eeg channel in the epochs.plot I get:

Traceback (most recent call last):
  File "/Users/alex/anaconda/envs/mne/lib/python3.6/site-packages/matplotlib/cbook/__init__.py", line 389, in process
    proxy(*args, **kwargs)
  File "/Users/alex/anaconda/envs/mne/lib/python3.6/site-packages/matplotlib/cbook/__init__.py", line 227, in __call__
    return mtd(*args, **kwargs)
  File "/Users/alex/work/src/mne-python/mne/viz/epochs.py", line 1490, in _mouse_click
    params['label_click_fun'](pos)
  File "/Users/alex/work/src/mne-python/mne/viz/epochs.py", line 1462, in _pick_bad_channels
    params['plot_update_proj_callback'](params)
  File "/Users/alex/work/src/mne-python/mne/viz/epochs.py", line 1342, in _plot_update_epochs_proj
    params['info'], params['noise_cov'], True, params['use_noise_cov'])
  File "/Users/alex/work/src/mne-python/mne/viz/utils.py", line 2269, in _setup_plot_projector
    noise_cov, use_info, verbose=False)
  File "<string>", line 2, in compute_whitener
  File "/Users/alex/work/src/mne-python/mne/utils.py", line 727, in verbose
    return function(*args, **kwargs)
  File "/Users/alex/work/src/mne-python/mne/cov.py", line 1640, in compute_whitener
    % missing)
RuntimeError: Not all channels present in noise covariance:
['EEG 053']

also when I do evoked.plot(noise_cov=noise_cov) and select a time interval the topos that are produced look weird.

@larsoner larsoner left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll fix the other things soon

Comment thread mne/viz/tests/test_evoked.py Outdated
# test GFP only
evoked.plot(gfp='only')
assert_raises(ValueError, evoked.plot, gfp='foo')
evoked.plot(noise_cov=cov_fname)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is the new line

@@ -78,181 +78,184 @@ def test_plot_evoked():
import matplotlib.pyplot as plt
rng = np.random.RandomState(0)
evoked = _get_epochs().average()

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is no reason to have the with warnings.catch_warnings in there -- it could be masking useful warnings (and might have been, don't remember)

@larsoner

Copy link
Copy Markdown
Member Author

when I do evoked.plot(noise_cov=noise_cov) and select a time interval the topos that are produced look weird.

I think this likely isn't bad math, but rather just whitened topos looking weird.

@larsoner larsoner changed the title MRG: Add whitening to plots WIP: Add whitening to plots Dec 28, 2017
@larsoner larsoner changed the title WIP: Add whitening to plots MRG: Add whitening to plots Jan 8, 2018
@larsoner

larsoner commented Jan 8, 2018

Copy link
Copy Markdown
Member Author

if I toggle off the bad eeg channel in the epochs.plot I get [an error]

Actually I think this is reasonable behavior and error message. If you try to plot whitened data and your noise cov does not have all data channels, you should get an error, no?

Other comments addressed and rebased.

@agramfort

agramfort commented Jan 8, 2018 via email

Copy link
Copy Markdown
Member

@larsoner

larsoner commented Jan 9, 2018

Copy link
Copy Markdown
Member Author

Okay lines have been removed

@larsoner

Copy link
Copy Markdown
Member Author

CI failure is a sporadic unrelated Travis OSX problem

@dengemann

Copy link
Copy Markdown
Member

@larsoner @agramfort why would we need evoked.plot(noise_cov=noise_cov) if there is evoked.plot_white? How should a user understand when to use which one? I am not sure what is the answer.

@larsoner

larsoner commented Jan 16, 2018 via email

Copy link
Copy Markdown
Member Author

@larsoner

Copy link
Copy Markdown
Member Author

Any chance for review here? I'd like to move on to doing group_by support in epochs.plot but don't want to start until this is in to avoid conflicts.

@agramfort

agramfort commented Jan 20, 2018 via email

Copy link
Copy Markdown
Member

@larsoner

Copy link
Copy Markdown
Member Author

@agramfort done. (Also the image you tried to post did not post, but I think I understood what you meant: never show traces of bads from info or cov in whiten mode.)

@larsoner

larsoner commented Feb 6, 2018 •

Copy link
Copy Markdown
Member Author

Okay scaling fixed / should now match that of plot_white. Along the way I refactored/simplified of some of the rank calculations.

I also fixed a bug with plot_evoked_white:

import mne
fname = mne.datasets.testing.data_path() + '/SSS/test_move_anon_raw_spatiotemporal_4s_sss.fif'
raw = mne.io.read_raw_fif(fname)
raw.set_eeg_reference(projection=True)
events = mne.make_fixed_length_events(raw, 1)
epochs = mne.Epochs(raw, events)
cov = mne.compute_covariance(epochs, tmax=0.)
evoked = epochs.average()
evoked.plot_white(cov)

on master:

master

On this PR it gives better labeling (and more uniform line widths to match evoked.plot:

pr

The interesting thing is that our magnetometer scaling gets a bit far from the +/- 1.96 limits for SSS'ed data. Adding evoked.plot(noise_cov=cov) above we get:

scaling

I think is to be expected, though. It actually exists in plot_white, too, although it's harder to see because grad and mag are overlayed. I added a note in the docstrings that this is expected and that plot_white can be used for additional inspection.

@larsoner

larsoner commented Feb 6, 2018

Copy link
Copy Markdown
Member Author

Examples (some didn't change much): plot_whitened, plot_compute_covariance, plot_evoked_whitening, plot_covariance_whitening_dspm.

the assumption of Gaussian white noise from which we expect values around
0 with less than 2 standard deviations. Covariance estimation and diagnostic
plots are based on [1]_.
the assumption of Gaussian white noise during the baseline period.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we specify +/- 1.96 here as expectation?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe it's enough below.

Comment thread mne/viz/epochs.py
and their channel names are shown in italic.
Can be a string to load a covariance from disk.
See also :meth:`mne.Evoked.plot_white` for additional inspection
of noise covariance properties when whitening evoked data.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

, specifically, for inspection of expected values and model violations ... {or so}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm wary of adding more text to an already long description here. I'll add it to the text for plot_evoked_white

Comment thread mne/viz/evoked.py
Can be a string to load a covariance from disk.
See also :meth:`mne.Evoked.plot_white` for additional inspection
of noise covariance properties when whitening evoked data.
For data processed with SSS, the effective dependence between

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

whatever is changed above should also be changed here (model violations / expected values etc).

Comment thread mne/viz/evoked.py
whitened GFPs based on each estimator separately for each sensor type.
Instead of numbers of channels the GFP display shows the estimated rank.
Note. The rank estimation will be printed by the logger for each noise
covariance estimator that is passed.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why is this removed? There is a lot of specific information. I think this is not a good idea.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok. Below. Nevermind.

Comment thread mne/viz/evoked.py
rank_list.append(this_rank)
evoked.pick_types(meg=True, eeg=True, ref_meg=False, exclude='bads')
n_ch_used, rank_list, picks_list, has_sss = _triage_rank_sss(
evoked.info, noise_cov, rank, scalings)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@larsoner is this call replacing all the work of the helper functions and other lines you removed?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes it was copy-paste to refactor + bug fixes

Comment thread mne/viz/ica.py
n_times=raw.n_times, bad_color=bad_color, picks=picks,
first_time=first_time, data_picks=[], decim=1)
first_time=first_time, data_picks=[], decim=1,
noise_cov=None, whitened_ch_names=())

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@larsoner why are we doing this actually? Just because we can or because people will need this. How does our whitening interact with ICA?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to pass the params / API uniformity internally. They shouldn't use it with ICA which is why it's not exposed in the public facing APIs for ICA plotting.

Comment thread mne/viz/utils.py
# (but in gray), but here we don't need to because "projector"
# starts out as identity. So all that is left to do is take any
# *good* data channels that are not in the noise cov to be NaN
nan_names = data_names - (bad_names | cov_names)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe the case for using set methods for better readability.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think set operations are clearly described using their arithmetic equivalents ...?

@dengemann

Copy link
Copy Markdown
Member

@larsoner I am not sure it is the best example. Can we plot the whitening of the evoked to see what is going on? As we discussed, the magnetometers are expected to be much lower in amplitude after SSS. Together with gradiometers they make up n_sss_components dimensions, as is shown in the GFP plot of the whitening.
Also to be on the same page, can you describe what was that bug that you fixed? / point to the buggy code you replaced with correct code?

We're getting somewhere, don't give up :) I think we're moving in the right direction .

@larsoner

larsoner commented Feb 7, 2018

Copy link
Copy Markdown
Member Author

@larsoner I am not sure it is the best example. Can we plot the whitening of the evoked to see what is going on?

Which example? The script I posted above? The three images in my previous post all come from the same script so it has plot_white as well as evoked.plot(noise_cov=cov) outputs. The traces are the same you just can't see the mags in the plot_white case because they are small relative to the grads. (I checked this by manually .set_visible(False)ing the gradiometer lines in the plot_white case.)

Comment thread mne/viz/utils.py
# we risk the rank estimates being incorrect (i.e., if the projectors
# do not match).
info_proj = info.copy()
info_proj['projs'] += cov['projs']

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is one bugfix -- the estimated rank needs to use the union of projectors to mirror what happens in computing the whitener

Comment thread mne/viz/utils.py
projector = setup_proj(this_info, add_eeg_ref=False)[0]
this_C = C[idx]
if projector is not None:
this_C = np.dot(np.dot(projector, this_C), projector.T)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

... and correspondingly this joint projector actually needs to be applied to the covariance matrix to ensure rank estimation works properly

Comment thread mne/viz/evoked.py
ax.axhline(hline, color='red', linestyle='--')
ax.axhline(hline, color='red', linestyle='--', lw=2)
ax.set(title='{0} ({1} channels)'.format(titles_[ch_type],
len(picks)))

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is a bug / consistency fix (the one I show with a script in a previous comment)

@larsoner

larsoner commented Feb 7, 2018

Copy link
Copy Markdown
Member Author

@dengemann comments addressed (I think)

@larsoner

Copy link
Copy Markdown
Member Author

ping @dengemann let me know if this is good to go for you

@dengemann

Copy link
Copy Markdown
Member

Looks good. We should move on. I let @agramfort take another look.

@larsoner

Copy link
Copy Markdown
Member Author

@agramfort okay for you too?

@agramfort

Copy link
Copy Markdown
Member

works now like a charm and both

evoked.plot_white(noise_cov)
evoked.plot(noise_cov=noise_cov)

give consistent scales.

thanks @larsoner

@agramfort
agramfort merged commit e84b316 into mne-tools:master Feb 28, 2018
@larsoner
larsoner deleted the whitening branch February 28, 2018 12:43
@larsoner larsoner mentioned this pull request Apr 16, 2018
2 of 5 tasks
britta-wstnr pushed a commit to britta-wstnr/mne-python that referenced this pull request Jul 5, 2018
* WIP: Add whitening to plots

* FIX: Add tests

* FIX: Fix for labels and butterfly

* DOC: Document option

* FIX: Remove lines

* FIX: Never show bads in whiten mode

* FIX: Fix bad behavior

* FIX: Add doc

* FIX: Fix scaling

* FIX: Unify cov handling and add warning about SSS

* DOC: Better description
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants