Skip to content

MRG epochs.plot_image combine and groupby - #4289

Merged
agramfort merged 80 commits into
mne-tools:masterfrom
jona-sassenhagen:ep_plt_im_gfp_new
Sep 4, 2017
Merged

agramfort merged 80 commits into
mne-tools:masterfrom
jona-sassenhagen:ep_plt_im_gfp_new

Conversation

@jona-sassenhagen

@jona-sassenhagen jona-sassenhagen commented May 31, 2017 •

Copy link
Copy Markdown
Contributor

Continuation of #4227

Implement combine and groupby for epochs.plot_image cause I'm bad at Git.

unknown-316

@mmagnuski

Copy link
Copy Markdown
Member

No, the colorbar is blue at zero! 😢
😉

@jona-sassenhagen

Copy link
Copy Markdown
Contributor Author

Ah, the most recent version should choose "Reds" for all-positive data.

@jona-sassenhagen

Copy link
Copy Markdown
Contributor Author

Uh ... I'm having an issue with interactivity.

======================================================================
ERROR: Test epoch plotting.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/travis/miniconda/envs/test/lib/python2.7/site-packages/nose/case.py", line 197, in runTest
    self.test(*self.arg)
  File "/home/travis/build/mne-tools/mne-python/mne/viz/tests/test_epochs.py", line 115, in test_plot_epochs
    _fake_click(fig, data_ax, [-0.1, 0.9], button=3)
  File "/home/travis/build/mne-tools/mne-python/mne/viz/utils.py", line 1163, in _fake_click
    func()
  File "/home/travis/miniconda/envs/test/lib/python2.7/site-packages/matplotlib/backend_bases.py", line 1903, in button_press_event
    self.callbacks.process(s, mouseevent)
  File "/home/travis/miniconda/envs/test/lib/python2.7/site-packages/matplotlib/cbook.py", line 563, in process
    proxy(*args, **kwargs)
  File "/home/travis/miniconda/envs/test/lib/python2.7/site-packages/matplotlib/cbook.py", line 430, in __call__
    return mtd(*args, **kwargs)
  File "/home/travis/build/mne-tools/mne-python/mne/viz/epochs.py", line 1237, in _mouse_click
    fig=params['image_plot'])[0]
  File "/home/travis/build/mne-tools/mne-python/mne/viz/epochs.py", line 183, in plot_epochs_image
    overlay_times=overlay_times, title=name)
  File "/home/travis/build/mne-tools/mne-python/mne/viz/epochs.py", line 266, in _plot_epochs_image
    vmin=this_vmin, vmax=this_vmax, cmap=cmap[0])
  File "/home/travis/miniconda/envs/test/lib/python2.7/site-packages/matplotlib/__init__.py", line 1812, in inner
    return func(ax, *args, **kwargs)
  File "/home/travis/miniconda/envs/test/lib/python2.7/site-packages/matplotlib/axes/_axes.py", line 4947, in imshow
    im.set_data(X)
  File "/home/travis/miniconda/envs/test/lib/python2.7/site-packages/matplotlib/image.py", line 453, in set_data
    raise TypeError("Invalid dimensions for image data")
TypeError: Invalid dimensions for image data

I think this is the part where an epochs image is plotted in interactive mode from an epochs plot.
@jaeilepp maybe you can take a quick look?..

Comment thread mne/viz/epochs.py Outdated
msg = "If `groupby` is a dict, `combine` must not be None"
raise ValueError(msg)
all_ch_types = list(groupby.keys())
all_picks = [groupby[ch_type] for ch_type in all_ch_types]

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.

please create a private subfunction eg _setup_groupby that returns all_picks

Comment thread mne/viz/epochs.py Outdated
ev = epochs.average(picks=picks_)
ev.data = this_data.mean(0)
to_plot_list.append((this_data, ch_type, ev,
name_dict.get(ch_type, ch_type)))

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.

please create a subfunction that is called _combine_data and that returns to_plot_list

Comment thread mne/viz/epochs.py Outdated
ax1.axis('auto')
ax1.axis('tight')
ax1.axvline(0, color='m', linewidth=3, linestyle='--')
evoked_data = scaling * evoked.data.squeeze()

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.

avoid squeeze and be explicit about dims

Comment thread mne/viz/epochs.py Outdated
to_plot_list = list()
if combine is None:
for pick, ch_type in zip(picks, all_ch_types):
this_data = data[:, pick, :].squeeze() #* scalings[ch_type] # (n_epochs, n_channels, n_times)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The test fails because this_data is 1d in when using a single pick. I'm not sure you want to do this, though. It looks like you're averaging each channel separately.

@jona-sassenhagen

Copy link
Copy Markdown
Contributor Author

Thanks for the tip @jaeilepp !

@agramfort

Copy link
Copy Markdown
Member

@jona-sassenhagen can you please update the tutorial on epochs viz so I can see the usage. it makes my life easier to test and review. Thx

@jona-sassenhagen

Copy link
Copy Markdown
Contributor Author

Ok! Although this is still not ready for review :( I'm very slow right now.

@codecov-io

codecov-io commented Jun 8, 2017 •

Copy link
Copy Markdown

Codecov Report

Merging #4289 into master will increase coverage by <.01%.
The diff coverage is 82.55%.

@@            Coverage Diff             @@
##           master    #4289      +/-   ##
==========================================
+ Coverage   83.59%   83.59%   +<.01%     
==========================================
  Files         349      349              
  Lines       65244    65402     +158     
  Branches    10089    10143      +54     
==========================================
+ Hits        54539    54672     +133     
- Misses       7848     7855       +7     
- Partials     2857     2875      +18

@jona-sassenhagen

Copy link
Copy Markdown
Contributor Author

Almost ... I added to the epochs viz tutorial, and an example that you can already run. Still need to make the axes and combine options play together.

@jona-sassenhagen

Copy link
Copy Markdown
Contributor Author

I need to add more tests to cover a bunch of failure cases, but otherwise this is ready. @agramfort the example is examples/vizualisation/plot_roi_erpimage_by_rt.py, and there is a line in the epochs viz tutorial.

@jona-sassenhagen

jona-sassenhagen commented Jun 10, 2017 •

Copy link
Copy Markdown
Contributor Author

I must say, I'm not happy with the ylims/ylims so far (if you compare multiple images of the same type, you want to be able to enforce shared lims). But it would require at least one additional kwarg, perhaps 3, to solve that. I think this will have to wait.

Also I dislike the enforced ylim symmetry.

@mmagnuski

Copy link
Copy Markdown
Member

The example BTW:
https://4769-1301584-gh.circle-artifacts.com/0/home/ubuntu/mne-python/doc/_build/html/auto_examples/visualization/plot_roi_erpimage_by_rt.html

You need to create the axes and plot in the same cell - currently the axes are empty.
I'd move axes creation to the plot cell.

@mmagnuski mmagnuski left a comment

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.

Didn't finish yet, but I'll be back to it tomorrow or on monday so I think it's better if it is visible.

event_id = {"rt": 1, "square": 2} # must be specified for str events
eog = {"FPz", "EOG1", "EOG2"}
raw = io.eeglab.read_raw_eeglab(
fname, preload=True, eog=eog, montage=montage, event_id=event_id)

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.

would still be 2 lines when doing:

raw = io.eeglab.read_raw_eeglab(name, preload=True, eog=eog,
                                montage=montage, event_id=event_id)

but I think it would be clearer this way.

# 2. extract A. "square" events B. followed by a button press within 700 msec
tmax = .7
events, rts = define_target_events(
events, 2, 1, raw.info["sfreq"], 0., tmax, 2)

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.

to be very clear what these values mean I'd do:

sfreq = raw.info["sfreq"]
reference_id, target_id = 2, 1
events, rts = define_target_events(events, reference_id, target_id, sfreq,
                                   tmin=0., tmax=0.7, new_id=2)

but would also consider naming events new_events (are any square events dropped due to rt > 0.7?)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

think so, yes

roi = "Left" if last_char % 2 else "Right"
rois[roi] = rois.get(roi, list()) + [pick]

# set up corresponding axes to plot to

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.

move this part to next cell so that plot output is ok.



def combine(data): # we will take the median of each ROI
return median(data, 1)

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.

axis=1

# The actual plot
epochs["square"].plot_image(
groupby=rois, combine=combine, axes=axes,
overlay_times=overlay_times, order=order, colorbar=False)

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.

Could be 2 lines if overlay_times var was times:

epochs["square"].plot_image(groupby=rois, combine=combine, axes=axes,
                            overlay_times=times, order=order, colorbar=False)

but that's very nitpicky :)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

nope, i think overlay_times is better :)

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.

Yes, I have to agree :)

Comment thread mne/viz/epochs.py Outdated
picks = np.atleast_1d(picks)

if ((fig is not None or axes is not None) and len(picks) > 1
and combine is None):

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.

if axes is a list of axes, len(picks) > 1 and combine is None this would give an error. Is a situation with 3 picks and 3 axes not valid?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I don't think it is - the plot uses 3 axes per pick. Right? (image, cbar, evoked)

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.

Ah, yes, true - 2 or 3 axes have to be passed (depending on colorbar).

Comment thread mne/viz/epochs.py
# (all_picks, all_ch_types, names) -> groupby.
# Then, we construct a list of the corresponding data, names and evokeds
# (to_plot_list) -> combine.
# Then, we loop over this list and plot using _plot_epochs_image.

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.

The description above is a bit redundant with the code and comments below. I think it would be clearer if the comments were above the code that does what description says.

Comment thread mne/viz/epochs.py
# groupby
all_picks, all_ch_types, names = _get_picks_and_types(
picks, ch_types, groupby, combine)
# all_picks is a list of lists of ints (picks); those lists will

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.

not sure if its better to have comments below code

Comment thread mne/viz/epochs.py
drawing the single trials and evoked responses. If None a new figure is
created. Defaults to None.
axes : list of matplotlib axes | None
axes : list of matplotlib axes | dict of lists of matplotlib Axes | None

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.

btw - you can use validate_if_list_of_axes from viz.utils (if I remember the name correctly) :)

Comment thread mne/viz/epochs.py Outdated
if groupby == "type":
all_picks, all_ch_types = list(), list()
for this_type in set(ch_types):
these_picks = picks[np.array(ch_types) == this_type]

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.

the remaining code would work if you construct the array only once above this loop: ch_types = np.array(ch_types)

@agramfort

Copy link
Copy Markdown
Member

+1 to share the same ylims when channel type is the same. ylims should however not be shared between eeg and meg images.

#
# License: BSD (3-clause)

from numpy import median

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.

from numpy as np
np.median

the reason is that then np.median is explicit of where it's coming from

else:
last_char = int(last_char)
roi = "Left" if last_char % 2 else "Right"
rois[roi] = rois.get(roi, list()) + [pick]

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.

@jona-sassenhagen please keep things simple. I know that you want to show how powerful it can be but it's a lot of lines just to avoid 3 different figures. We've always tried to keep example short to avoid scaring the less geeky ones.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The roi dict has to be created anyways ... Also this can be used for every 10/20 layout, which are very common in EEG world.

The code is redundant, we can save 2 lines easily:

rois = dict()
for pick, channel in enumerate(epochs.ch_names):
    last_char = channel[-1]
    if last_char == "z":
        roi = "Midline"
    else:
        roi = "Left" if int(last_char) % 2 else "Right"
    rois[roi] = rois.get(roi, list()) + [pick]

And you can do it in essentially 2 lines of code:

roi_per_chan = ["midline" if ch_name.endswith("z")
    else ("Left" if int(ch_name[-1]) % 2 else "Right")
    for ch_name in epochs.ch_names]
rois = {roi:[ii for ii, this_roi in enumerate(roi_per_chan) if this_roi == roi]
    for roi in set(roi_per_chan)]}

Do you think doing it e.g. manually (rois = {"left": [1, 2, 3, 4, 5], "right": [6, 7, 8, 9, 10] ... is better? To me that's less transparent. But if you think it's enough python in an MNE example, I will do it manually.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Or is it the axes dict you dislike? (Not the groupby dict by itself)
E.g., would plotting individual figures for left, midline right (which would still require a roid dict) be ok?

@jona-sassenhagen

Copy link
Copy Markdown
Contributor Author

@agramfort do you think v/ylim sharing should be done automatically for all plots with the same channel type? (e.g., change current behavior from diff. lims -> per default share lims)
Or should there be a kwarg?

I'm not sure what would be best.
Keep in mind shared lims can be enforced by manually providing vlims, but not different lims.

@mmagnuski

Copy link
Copy Markdown
Member

A simplifying rule could be to keep limits separate if groupby is 'type' and have them the same in all other cases. You can always call the function multiple times with different channel groups to have separate limits.

@jona-sassenhagen

Copy link
Copy Markdown
Contributor Author

A simplifying rule could be to keep limits separate if groupby is 'type' and have them the same in all other cases. You can always call the function multiple times with different channel groups to have separate limits.

That is convincing to me.

Comment thread mne/viz/epochs.py Outdated
combine = lambda data: np.sqrt((data * data).mean(axis=1))
elif combine == "mean":
combine = lambda data: np.mean(data, axis=1)
elif combine == "std": # undocumented ...

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.

just a reminder to document this

Comment thread mne/viz/epochs.py Outdated
elif not callable(combine):
raise ValueError(
"`combine` must be None, a callable or one out of 'mean' "
"or 'gfp'. Got " + str(type(combine)))

@mmagnuski mmagnuski Jun 11, 2017 •

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 be two lines :P

            raise ValueError("`combine` must be None, a callable or one out "
                              "of 'mean' or 'gfp'. Got " + str(type(combine)))

Comment thread mne/viz/epochs.py Outdated
'decide between the two.')
from .utils import _validate_if_list_of_axes
oblig_len = 3 if colorbar else 2
oblig_len = 3

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.

you could also do oblig_len = 3 - ((not colorbar) + (not draw_evoked)) i you don't think it is too convoluted.

Comment thread mne/viz/epochs.py Outdated
data = ndimage.gaussian_filter1d(data, sigma=sigma, axis=0)

### Plot ###
#### draw the image ####

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.

I think you have some Travis style errors due to multiple # starting comments

Comment thread mne/viz/epochs.py
if sigma > 0.:
for k in range(len(picks)):
data[k, :] = ndimage.gaussian_filter1d(
data[k, :], sigma=sigma, axis=0)

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.

The smoothing was previously done here so that vmin and vmax are with respect to smoothed data (otherwise the images were often pale).

# button. Hitting space bar resets the scale.
epochs.plot_image(278, cmap='interactive')

###############################################################################

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.

"overview of" and I'd remove "for example"

Comment thread tutorials/plot_visualize_epochs.py Outdated

###############################################################################
# We can also give an overview over all channels, for example by calculating
# the global field power. However, combining multiple channel types (e.g., MEG

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.

"in this way" -> "with gfp" ? (or just without "in this way"?)

Comment thread tutorials/plot_visualize_epochs.py Outdated
###############################################################################
# We can also give an overview over all channels, for example by calculating
# the global field power. However, combining multiple channel types (e.g., MEG
# and EEG) in this way is not sensible. For this, we can use the `groupby`

@mmagnuski mmagnuski Jun 11, 2017 •

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.

"Setting groupby to 'type'"?

@agramfort
agramfort merged commit 525dab5 into mne-tools:master Sep 4, 2017
@agramfort

Copy link
Copy Markdown
Member

thx @jona-sassenhagen !

@mmagnuski

Copy link
Copy Markdown
Member

Thanks @jona-sassenhagen !

@jona-sassenhagen

jona-sassenhagen commented Sep 4, 2017 via email

Copy link
Copy Markdown
Contributor Author

Comment thread mne/viz/evoked.py Outdated
if method == "boot":
return _bootstrap_ci(arr, ci, n_bootstraps=n_bootstraps)
else:
return _parametric_ci(arr, ci)

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.

@jona-sassenhagen maybe worth a separate whatsnew entry advertising the joint work.

@jona-sassenhagen
jona-sassenhagen deleted the ep_plt_im_gfp_new branch March 10, 2018 10:41
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.

7 participants