Repository navigation
MRG epochs.plot_image combine and groupby - #4289
Conversation
|
No, the colorbar is blue at zero! 😢 |
|
Ah, the most recent version should choose "Reds" for all-positive data. |
|
Uh ... I'm having an issue with interactivity. I think this is the part where an epochs image is plotted in interactive mode from an epochs plot. |
| 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] |
There was a problem hiding this comment.
please create a private subfunction eg _setup_groupby that returns all_picks
| 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))) |
There was a problem hiding this comment.
please create a subfunction that is called _combine_data and that returns to_plot_list
| ax1.axis('auto') | ||
| ax1.axis('tight') | ||
| ax1.axvline(0, color='m', linewidth=3, linestyle='--') | ||
| evoked_data = scaling * evoked.data.squeeze() |
There was a problem hiding this comment.
avoid squeeze and be explicit about dims
| 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) |
There was a problem hiding this comment.
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.
|
Thanks for the tip @jaeilepp ! |
|
@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 |
|
Ok! Although this is still not ready for review :( I'm very slow right now. |
Codecov Report
@@ 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 |
|
Almost ... I added to the epochs viz tutorial, and an example that you can already run. Still need to make the |
|
I need to add more tests to cover a bunch of failure cases, but otherwise this is ready. @agramfort the example is |
|
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. |
|
You need to create the axes and plot in the same cell - currently the axes are empty. |
mmagnuski
left a comment
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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?)
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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) |
| # The actual plot | ||
| epochs["square"].plot_image( | ||
| groupby=rois, combine=combine, axes=axes, | ||
| overlay_times=overlay_times, order=order, colorbar=False) |
There was a problem hiding this comment.
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 :)
There was a problem hiding this comment.
nope, i think overlay_times is better :)
| picks = np.atleast_1d(picks) | ||
|
|
||
| if ((fig is not None or axes is not None) and len(picks) > 1 | ||
| and combine is None): |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
I don't think it is - the plot uses 3 axes per pick. Right? (image, cbar, evoked)
There was a problem hiding this comment.
Ah, yes, true - 2 or 3 axes have to be passed (depending on colorbar).
| # (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. |
There was a problem hiding this comment.
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.
| # 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 |
There was a problem hiding this comment.
not sure if its better to have comments below code
| 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 |
There was a problem hiding this comment.
btw - you can use validate_if_list_of_axes from viz.utils (if I remember the name correctly) :)
| 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] |
There was a problem hiding this comment.
the remaining code would work if you construct the array only once above this loop: ch_types = np.array(ch_types)
|
+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 |
There was a problem hiding this comment.
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] |
There was a problem hiding this comment.
@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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
|
@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) I'm not sure what would be best. |
|
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. |
| 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 ... |
There was a problem hiding this comment.
just a reminder to document this
| elif not callable(combine): | ||
| raise ValueError( | ||
| "`combine` must be None, a callable or one out of 'mean' " | ||
| "or 'gfp'. Got " + str(type(combine))) |
There was a problem hiding this comment.
can be two lines :P
raise ValueError("`combine` must be None, a callable or one out "
"of 'mean' or 'gfp'. Got " + str(type(combine)))| 'decide between the two.') | ||
| from .utils import _validate_if_list_of_axes | ||
| oblig_len = 3 if colorbar else 2 | ||
| oblig_len = 3 |
There was a problem hiding this comment.
you could also do oblig_len = 3 - ((not colorbar) + (not draw_evoked)) i you don't think it is too convoluted.
| data = ndimage.gaussian_filter1d(data, sigma=sigma, axis=0) | ||
|
|
||
| ### Plot ### | ||
| #### draw the image #### |
There was a problem hiding this comment.
I think you have some Travis style errors due to multiple # starting comments
| if sigma > 0.: | ||
| for k in range(len(picks)): | ||
| data[k, :] = ndimage.gaussian_filter1d( | ||
| data[k, :], sigma=sigma, axis=0) |
There was a problem hiding this comment.
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') | ||
|
|
||
| ############################################################################### |
There was a problem hiding this comment.
"overview of" and I'd remove "for example"
|
|
||
| ############################################################################### | ||
| # 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 |
There was a problem hiding this comment.
"in this way" -> "with gfp" ? (or just without "in this way"?)
| ############################################################################### | ||
| # 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` |
There was a problem hiding this comment.
"Setting groupby to 'type'"?
bed21e0 to
d991b8a
Compare
|
thx @jona-sassenhagen ! |
|
Thanks @jona-sassenhagen ! |
|
Thanks guys!
|
| if method == "boot": | ||
| return _bootstrap_ci(arr, ci, n_bootstraps=n_bootstraps) | ||
| else: | ||
| return _parametric_ci(arr, ci) |
There was a problem hiding this comment.
@jona-sassenhagen maybe worth a separate whatsnew entry advertising the joint work.
Continuation of #4227
Implement
combineandgroupbyforepochs.plot_imagecause I'm bad at Git.