forked from mne-tools/mne-python
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathepochs.py
1984 lines (1810 loc) · 81.3 KB
/
epochs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Functions to plot epochs data."""
# Authors: Alexandre Gramfort <[email protected]>
# Denis Engemann <[email protected]>
# Martin Luessi <[email protected]>
# Eric Larson <[email protected]>
# Jaakko Leppakangas <[email protected]>
# Jona Sassenhagen <[email protected]>
#
# License: Simplified BSD
from collections import Counter
from functools import partial
import copy
import numpy as np
from ..utils import verbose, get_config, set_config, logger, warn
from ..io.pick import pick_types, channel_type
from ..io.proj import setup_proj
from ..time_frequency import psd_multitaper
from .utils import (tight_layout, figure_nobar, _toggle_proj, _toggle_options,
_layout_figure, _setup_vmin_vmax, _channels_changed,
_plot_raw_onscroll, _onclick_help, plt_show,
_compute_scalings, DraggableColorbar, _setup_cmap,
_grad_pair_pick_and_name, _handle_decim)
from .misc import _handle_event_colors
from ..defaults import _handle_default
from ..externals.six import string_types
def plot_epochs_image(epochs, picks=None, sigma=0., vmin=None,
vmax=None, colorbar=True, order=None, show=True,
units=None, scalings=None, cmap=None, fig=None,
axes=None, overlay_times=None, combine=None,
group_by=None, evoked=True, ts_args=dict(), title=None):
"""Plot Event Related Potential / Fields image.
Parameters
----------
epochs : instance of Epochs
The epochs.
picks : int | array-like of int | None
The indices of the channels to consider. If None and ``combine`` is
also None, the first five good channels are plotted.
sigma : float
The standard deviation of the Gaussian smoothing to apply along
the epoch axis to apply in the image. If 0., no smoothing is applied.
Defaults to 0.
vmin : None | float | callable
The min value in the image (and the ER[P/F]). The unit is uV for
EEG channels, fT for magnetometers and fT/cm for gradiometers.
If vmin is None and multiple plots are returned, the limit is
equalized within channel types.
Hint: to specify the lower limit of the data, use
``vmin=lambda data: data.min()``.
vmax : None | float | callable
The max value in the image (and the ER[P/F]). The unit is uV for
EEG channels, fT for magnetometers and fT/cm for gradiometers.
If vmin is None and multiple plots are returned, the limit is
equalized within channel types.
colorbar : bool
Display or not a colorbar.
order : None | array of int | callable
If not None, order is used to reorder the epochs on the y-axis
of the image. If it's an array of int it should be of length
the number of good epochs. If it's a callable the arguments
passed are the times vector and the data as 2d array
(data.shape[1] == len(times).
show : bool
Show figure if True.
units : dict | None
The units of the channel types used for axes lables. If None,
defaults to `units=dict(eeg='uV', grad='fT/cm', mag='fT')`.
scalings : dict | None
The scalings of the channel types to be applied for plotting.
If None, defaults to `scalings=dict(eeg=1e6, grad=1e13, mag=1e15,
eog=1e6)`.
cmap : None | matplotlib colormap | (colormap, bool) | 'interactive'
Colormap. If tuple, the first value indicates the colormap to use and
the second value is a boolean defining interactivity. In interactive
mode the colors are adjustable by clicking and dragging the colorbar
with left and right mouse button. Left mouse button moves the scale up
and down and right mouse button adjusts the range. Hitting space bar
resets the scale. Up and down arrows can be used to change the
colormap. If 'interactive', translates to ('RdBu_r', True).
If None, "RdBu_r" is used, unless the data is all positive, in which
case "Reds" is used.
fig : matplotlib figure | None
Figure instance to draw the image to. Figure must contain two axes for
drawing the single trials and evoked responses. If None a new figure is
created. Defaults to None.
axes : list of matplotlib axes | dict of lists of matplotlib Axes | None
List of axes instances to draw the image, erp and colorbar to.
Must be of length three if colorbar is True (with the last list element
being the colorbar axes) or two if colorbar is False. If both fig and
axes are passed, an error is raised.
If ``group_by`` is a dict, this cannot be a list, but it can be a dict
of lists of axes, with the keys matching those of ``group_by``. In that
case, the provided axes will be used for the corresponding groups.
Defaults to `None`.
overlay_times : array-like, shape (n_epochs,) | None
If not None the parameter is interpreted as time instants in seconds
and is added to the image. It is typically useful to display reaction
times. Note that it is defined with respect to the order
of epochs such that overlay_times[0] corresponds to epochs[0].
combine : None | str | callable
If None, return one figure per pick. If not None, aggregate over
channels via the indicated method. If str, must be one of "mean",
"median", "std" or "gfp", in which case the mean, the median, the
standard deviation or the GFP over channels are plotted.
array (n_epochs, n_times).
If callable, it must accept one positional input, the data
in the format `(n_epochs, n_channels, n_times)`. It must return an
array `(n_epochs, n_times)`. For example::
combine = lambda data: np.median(data, axis=1)
Defaults to `None` if picks are provided, otherwise 'gfp'.
group_by : None | str | dict
If not None, combining happens over channel groups defined by this
parameter.
If str, must be "type", in which case one figure per channel type is
returned (combining within channel types).
If a dict, the values must be picks and one figure will be returned
for each entry, aggregating over the corresponding pick groups; keys
will become plot titles. This is useful for e.g. ROIs. Each entry must
contain only one channel type. For example::
group_by=dict(Left_ROI=[1, 2, 3, 4], Right_ROI=[5, 6, 7, 8])
If not None, combine must not be None. Defaults to `None` if picks are
provided, otherwise 'type'.
evoked : Bool
Draw the ER[P/F] below the image or not.
ts_args : dict
Arguments passed to a call to `mne.viz.plot_compare_evoked` to style
the evoked plot below the image. Defaults to an empty dictionary,
meaning `plot_compare_evokeds` will be called with default parameters
(yaxis truncation will be turned off).
title : None | str
If str, will be plotted as figure title. Else, the channels will be
indicated.
Returns
-------
figs : lists of matplotlib figures
One figure per channel displayed.
"""
units = _handle_default('units', units)
scalings = _handle_default('scalings', scalings)
# setting defaults
if group_by is not None and combine is None:
combine = 'gfp'
if all(param is None for param in (group_by, picks, combine)):
group_by = "type"
combine = "gfp"
if picks is None:
picks = pick_types(epochs.info, meg=True, eeg=True, ref_meg=False,
exclude='bads')
if group_by is None:
picks = picks[:5] # take 5 picks to prevent spawning many figs
else:
picks = np.atleast_1d(picks)
manual_ylims = "ylim" in ts_args
vlines = ts_args.get(
"vlines", [0] if (epochs.times[0] < 0 < epochs.times[-1]) else [])
# input checks
if (combine is None and (fig is not None or axes is not None) and
len(picks) > 1):
raise ValueError('Only single pick can be drawn to a figure/axis; '
'provide only one pick, or use `combine`.')
if set(units.keys()) != set(scalings.keys()):
raise ValueError('Scalings and units must have the same keys.')
ch_types = [channel_type(epochs.info, idx) for idx in picks]
if len(set(ch_types)) > 1 and group_by is None and combine is not None:
warn("Combining over multiple channel types. "
"Please use ``group_by``.")
for ch_type in ch_types:
if ch_type not in scalings:
# We know it's not in either scalings or units since keys match
raise KeyError('%s type not in scalings and units' % ch_type)
if isinstance(axes, dict):
show = False
if not isinstance(group_by, dict):
raise ValueError("If axes is a dict, group_by must be a dict, "
"got " + str(type(group_by)))
else:
if axes is not None and isinstance(group_by, dict):
raise ValueError("If ``group_by`` is a dict, axes must be a dict "
"or None, got " + str(type(group_by)))
if isinstance(group_by, dict) and combine is None:
raise ValueError("If ``group_by`` is a dict, ``combine`` must not be "
"None.")
# call helpers to prepare the plot
# First, we collect groupings of picks and types in two lists
# (all_picks, all_ch_types, names) -> group_by.
# Then, we construct a list of the corresponding data, names and evokeds
# (groups) -> combine.
# Then, we loop over this list and plot using _plot_epochs_image.
# group_by
all_picks, all_ch_types, names = _get_picks_and_types(
picks, ch_types, group_by, combine)
# all_picks is a list of lists of ints (picks); those lists will
# be length 1 if combine is None, else of length > 1.
# combine/construct list for plotting
groups = _pick_and_combine(
epochs, combine, all_picks, all_ch_types, scalings, names)
# each entry of groups is: (data, ch_type, evoked, name)
# prepare the image - required for uniform vlims
vmins, vmaxs = dict(), dict()
for group in groups:
epochs, ch_type = group[:2]
group.extend(_prepare_epochs_image_im_data(
epochs, ch_type, overlay_times, order, sigma, vmin, vmax,
scalings[ch_type], ts_args))
if vmin is None or vmax is None: # equalize across groups
this_vmin, this_vmax, this_ylim = group[-3:]
if vmin is None and (this_vmin < vmins.get(ch_type, 1)):
vmins[ch_type] = this_vmin
if vmax is None and (this_vmax > vmaxs.get(ch_type, -1)):
vmaxs[ch_type] = this_vmax
# plot
figs, axes_list = list(), list()
ylims = dict((ch_type, (1., -1.)) for ch_type in all_ch_types)
for (epochs_, ch_type, ax_name, name, data, overlay_times, vmin, vmax,
ts_args) in groups:
vmin, vmax = vmins.get(ch_type, vmin), vmaxs.get(ch_type, vmax)
these_axes = axes[ax_name] if isinstance(axes, dict) else axes
axes_dict = _prepare_epochs_image_axes(these_axes, fig, colorbar,
evoked)
axes_list.append(axes_dict)
title_ = ((ax_name if isinstance(axes, dict) else name)
if title is None else title)
this_fig = _plot_epochs_image(
epochs_, data, vmin=vmin, vmax=vmax, colorbar=colorbar, show=False,
unit=units[ch_type], ch_type=ch_type, cmap=cmap,
axes_dict=axes_dict, title=title_, overlay_times=overlay_times,
evoked=evoked, ts_args=ts_args)
figs.append(this_fig)
# the rest of the code is for aligning ylims for multiple plots
if evoked is True and not manual_ylims:
evoked_ax = axes_dict["evoked"]
this_min, this_max = evoked_ax.get_ylim()
curr_min, curr_max = ylims[ch_type]
ylims[ch_type] = min(curr_min, this_min), max(curr_max, this_max),
if evoked is True: # adjust ylims
for group, axes_dict in zip(groups, axes_list):
ch_type = group[1]
ax = axes_dict["evoked"]
if not manual_ylims:
ax.set_ylim(ylims[ch_type])
if len(vlines) > 0:
upper_v, lower_v = ylims[ch_type]
if overlay_times is not None:
overlay = {overlay_times.mean(), np.median(overlay_times)}
else:
overlay = {}
for line in vlines:
ax.vlines(line, upper_v, lower_v, colors='k',
linestyles='-' if line in overlay else "--",
linewidth=2. if line in overlay else 1.)
plt_show(show)
return figs
def _get_picks_and_types(picks, ch_types, group_by, combine):
"""Pack picks and types into a list. Helper for plot_epochs_image."""
if group_by is None:
if combine is not None:
picks = [picks]
return picks, ch_types, ch_types
elif group_by == "type":
all_picks, all_ch_types = list(), list()
for this_type in set(ch_types):
these_picks = picks[np.array(ch_types) == this_type]
all_picks.append(these_picks)
all_ch_types.append(this_type)
names = all_ch_types # only differs for dict group_by
elif isinstance(group_by, dict):
names = list(group_by.keys())
all_picks = [group_by[name] for name in names]
for name, picks_ in group_by.items():
n_picks = len(picks_)
if n_picks < 2:
raise ValueError(" ".join(
(name, "has only ", str(n_picks), "sensors.")))
all_ch_types = list()
for picks_, name in zip(all_picks, names):
this_ch_type = list(set((ch_types[pick] for pick in picks_)))
n_types = len(this_ch_type)
if n_types > 1: # we can only scale properly with 1 type
raise ValueError(
"Roi {} contains {} sensor types!".format(
name, n_types))
all_ch_types.append(this_ch_type[0])
names.append(name)
else:
raise ValueError("If ``group_by`` is not None, it must be a dict "
"or 'type', got " + str(type(group_by)))
return all_picks, all_ch_types, names # all_picks is a list of lists
def _pick_and_combine(epochs, combine, all_picks, all_ch_types, scalings,
names):
"""Pick and combine epochs image. Helper for plot_epochs_image."""
to_plot_list = list()
tmin = epochs.times[0]
if combine is None:
if epochs.preload is False:
epochs = epochs.copy().load_data() # FIXME: avoid copy
for pick, ch_type in zip(all_picks, all_ch_types):
name = epochs.ch_names[pick]
these_epochs = epochs.copy().pick_channels([name])
to_plot_list.append([these_epochs, ch_type, name, name])
return to_plot_list
# if combine is not None ...
from .. import EpochsArray, pick_info
data = epochs.get_data()
type2name = {"eeg": "EEG", "grad": "Gradiometers",
"mag": "Magnetometers"}
combine_title = (" (" + combine + ")"
if isinstance(combine, string_types) else "")
if combine == "gfp":
def combine(data):
return np.sqrt((data * data).mean(axis=1))
elif combine == "mean":
def combine(data):
return np.mean(data, axis=1)
elif combine == "std":
def combine(data):
return np.std(data, axis=1)
elif combine == "median":
def combine(data):
return np.median(data, axis=1)
elif not callable(combine):
raise ValueError(
"``combine`` must be None, a callable or one out of 'mean' "
"or 'gfp'. Got " + str(type(combine)))
for ch_type, picks_, name in zip(all_ch_types, all_picks, names):
if len(np.atleast_1d(picks_)) < 2:
raise ValueError("Cannot combine over only one sensor. "
"Consider using different values for "
"``picks`` and/or ``group_by``.")
if ch_type == "grad":
def pair_and_combine(data):
data = data ** 2
data = (data[:, ::2, :] + data[:, 1::2, :]) / 2
return combine(np.sqrt(data))
picks_ = _grad_pair_pick_and_name(epochs.info, picks_)[0]
this_data = pair_and_combine(
data[:, picks_, :])[:, np.newaxis, :]
else:
this_data = combine(
data[:, picks_, :])[:, np.newaxis, :]
info = pick_info(epochs.info, [picks_[0]], copy=True)
these_epochs = EpochsArray(this_data.copy(), info, tmin=tmin)
d = these_epochs.get_data() # Why is this necessary?
d[:] = this_data # Without this, the data is all-zeros!
to_plot_list.append([these_epochs, ch_type, name,
type2name.get(name, name) + combine_title])
return to_plot_list # epochs, ch_type, name, axtitle
def _prepare_epochs_image_im_data(epochs, ch_type, overlay_times, order,
sigma, vmin, vmax, scaling, ts_args):
"""Preprocess epochs image (sort, filter). Helper for plot_epochs_image."""
from scipy import ndimage
# data transforms - sorting, scaling, smoothing
data = epochs.get_data()[:, 0, :]
n_epochs = len(data)
if overlay_times is not None and len(overlay_times) != n_epochs:
raise ValueError('size of overlay_times parameter (%s) do not '
'match the number of epochs (%s).'
% (len(overlay_times), n_epochs))
if overlay_times is not None:
overlay_times = np.array(overlay_times)
times_min = np.min(overlay_times)
times_max = np.max(overlay_times)
if ((times_min < epochs.times[0]) or (times_max > epochs.times[-1])):
warn('Some values in overlay_times fall outside of the epochs '
'time interval (between %s s and %s s)'
% (epochs.times[0], epochs.times[-1]))
if callable(order):
order = order(epochs.times, data)
if order is not None and (len(order) != n_epochs):
raise ValueError(("`order` must be None, callable or an array as long "
"as the data. Got " + str(type(order))))
if order is not None:
order = np.asarray(order)
data = data[order]
if overlay_times is not None:
overlay_times = overlay_times[order]
if sigma > 0.:
data = ndimage.gaussian_filter1d(data, sigma=sigma, axis=0)
# setup lims and cmap
scale_vmin = True if (vmin is None or callable(vmin)) else False
scale_vmax = True if (vmax is None or callable(vmax)) else False
vmin, vmax = _setup_vmin_vmax(
data, vmin, vmax, norm=(data.min() >= 0) and (vmin is None))
if not scale_vmin:
vmin /= scaling
if not scale_vmax:
vmax /= scaling
ylim = dict()
ts_args_ = dict(colors={"cond": "black"}, ylim=ylim, picks=[0], title='',
truncate_yaxis=False, truncate_xaxis=False, show=False)
ts_args_.update(**ts_args)
ts_args_["vlines"] = []
return [data * scaling, overlay_times, vmin * scaling, vmax * scaling,
ts_args_]
def _prepare_epochs_image_axes(axes, fig, colorbar, evoked):
"""Prepare axes for image plotting. Helper for plot_epochs_image."""
import matplotlib.pyplot as plt
# prepare fig and axes
axes_dict = dict()
if axes is None:
if fig is None:
fig = plt.figure()
plt.figure(fig.number)
axes_dict["image"] = plt.subplot2grid(
(3, 10), (0, 0), colspan=9 if colorbar else 10,
rowspan=2 if evoked else 3)
if evoked:
axes_dict["evoked"] = plt.subplot2grid(
(3, 10), (2, 0), colspan=9 if colorbar else 10, rowspan=1)
if colorbar:
axes_dict["colorbar"] = plt.subplot2grid((3, 10), (0, 9),
colspan=1, rowspan=3)
else:
if fig is not None:
raise ValueError('Both figure and axes were passed, please'
'only pass one of these.')
from .utils import _validate_if_list_of_axes
oblig_len = 3 - ((not colorbar) + (not evoked))
_validate_if_list_of_axes(axes, obligatory_len=oblig_len)
axes_dict["image"] = axes[0]
if evoked:
axes_dict["evoked"] = axes[1]
# if axes were passed - we ignore fig param and get figure from axes
fig = axes_dict["image"].get_figure()
if colorbar:
axes_dict["colorbar"] = axes[-1]
return axes_dict
def _plot_epochs_image(epochs, data, ch_type, vmin=None, vmax=None,
colorbar=False, show=False, unit=None, cmap=None,
axes_dict=None, overlay_times=None, title=None,
evoked=False, ts_args=None):
"""Plot epochs image. Helper function for plot_epochs_image."""
if cmap is None:
cmap = "Reds" if data.min() >= 0 else 'RdBu_r'
# Plot
# draw the image
ax = axes_dict["image"]
fig = ax.get_figure()
cmap = _setup_cmap(cmap)
n_epochs = len(data)
extent = [1e3 * epochs.times[0], 1e3 * epochs.times[-1], 0, n_epochs]
im = ax.imshow(data, vmin=vmin, vmax=vmax, cmap=cmap[0], aspect='auto',
origin='lower', interpolation='nearest', extent=extent)
if overlay_times is not None:
ax.plot(1e3 * overlay_times, 0.5 + np.arange(n_epochs), 'k',
linewidth=2)
ax.set_title(title)
ax.set_ylabel('Epochs')
ax.axis('auto')
ax.axis('tight')
if overlay_times is not None:
ax.set_xlim(1e3 * epochs.times[0], 1e3 * epochs.times[-1])
ax.axvline(0, color='k', linewidth=1, linestyle='--')
# draw the evoked
if evoked:
from mne.viz import plot_compare_evokeds
plot_compare_evokeds(
{"cond": list(epochs.iter_evoked())}, axes=axes_dict["evoked"],
**ts_args)
axes_dict["evoked"].set_xlim(epochs.times[[0, -1]])
ax.set_xticks(())
# draw the colorbar
if colorbar:
import matplotlib.pyplot as plt
cbar = plt.colorbar(im, cax=axes_dict['colorbar'])
cbar.ax.set_ylabel(unit + "\n\n", rotation=270)
if cmap[1]:
ax.CB = DraggableColorbar(cbar, im)
tight_layout(fig=fig)
fig._axes_dict = axes_dict # storing this here for easy access later
# finish
plt_show(show)
return fig
def plot_drop_log(drop_log, threshold=0, n_max_plot=20, subject='Unknown',
color=(0.9, 0.9, 0.9), width=0.8, ignore=('IGNORED',),
show=True):
"""Show the channel stats based on a drop_log from Epochs.
Parameters
----------
drop_log : list of lists
Epoch drop log from Epochs.drop_log.
threshold : float
The percentage threshold to use to decide whether or not to
plot. Default is zero (always plot).
n_max_plot : int
Maximum number of channels to show stats for.
subject : str
The subject name to use in the title of the plot.
color : tuple | str
Color to use for the bars.
width : float
Width of the bars.
ignore : list
The drop reasons to ignore.
show : bool
Show figure if True.
Returns
-------
fig : Instance of matplotlib.figure.Figure
The figure.
"""
import matplotlib.pyplot as plt
from ..epochs import _drop_log_stats
perc = _drop_log_stats(drop_log, ignore)
scores = Counter([ch for d in drop_log for ch in d if ch not in ignore])
ch_names = np.array(list(scores.keys()))
fig = plt.figure()
if perc < threshold or len(ch_names) == 0:
plt.text(0, 0, 'No drops')
return fig
n_used = 0
for d in drop_log: # "d" is the list of drop reasons for each epoch
if len(d) == 0 or any(ch not in ignore for ch in d):
n_used += 1 # number of epochs not ignored
counts = 100 * np.array(list(scores.values()), dtype=float) / n_used
n_plot = min(n_max_plot, len(ch_names))
order = np.flipud(np.argsort(counts))
plt.title('%s: %0.1f%%' % (subject, perc))
x = np.arange(n_plot)
plt.bar(x, counts[order[:n_plot]], color=color, width=width)
plt.xticks(x + width / 2.0, ch_names[order[:n_plot]], rotation=45,
horizontalalignment='right')
plt.tick_params(axis='x', which='major', labelsize=10)
plt.ylabel('% of epochs rejected')
plt.xlim((-width / 2.0, (n_plot - 1) + width * 3 / 2))
plt.grid(True, axis='y')
tight_layout(pad=1, fig=fig)
plt_show(show)
return fig
def _draw_epochs_axes(epoch_idx, good_ch_idx, bad_ch_idx, data, times, axes,
title_str, axes_handler):
"""Handle drawing epochs axes."""
this = axes_handler[0]
for ii, data_, ax in zip(epoch_idx, data, axes):
for l, d in zip(ax.lines, data_[good_ch_idx]):
l.set_data(times, d)
if bad_ch_idx is not None:
bad_lines = [ax.lines[k] for k in bad_ch_idx]
for l, d in zip(bad_lines, data_[bad_ch_idx]):
l.set_data(times, d)
if title_str is not None:
ax.set_title(title_str % ii, fontsize=12)
ax.set_ylim(data.min(), data.max())
ax.set_yticks(list())
ax.set_xticks(list())
if vars(ax)[this]['reject'] is True:
# memorizing reject
for l in ax.lines:
l.set_color((0.8, 0.8, 0.8))
ax.get_figure().canvas.draw()
else:
# forgetting previous reject
for k in axes_handler:
if k == this:
continue
if vars(ax).get(k, {}).get('reject', None) is True:
for l in ax.lines[:len(good_ch_idx)]:
l.set_color('k')
if bad_ch_idx is not None:
for l in ax.lines[-len(bad_ch_idx):]:
l.set_color('r')
ax.get_figure().canvas.draw()
break
def _epochs_navigation_onclick(event, params):
"""Handle epochs navigation click."""
import matplotlib.pyplot as plt
p = params
here = None
if event.inaxes == p['back'].ax:
here = 1
elif event.inaxes == p['next'].ax:
here = -1
elif event.inaxes == p['reject-quit'].ax:
if p['reject_idx']:
p['epochs'].drop(p['reject_idx'])
plt.close(p['fig'])
plt.close(event.inaxes.get_figure())
if here is not None:
p['idx_handler'].rotate(here)
p['axes_handler'].rotate(here)
this_idx = p['idx_handler'][0]
_draw_epochs_axes(this_idx, p['good_ch_idx'], p['bad_ch_idx'],
p['data'][this_idx],
p['times'], p['axes'], p['title_str'],
p['axes_handler'])
# XXX don't ask me why
p['axes'][0].get_figure().canvas.draw()
def _epochs_axes_onclick(event, params):
"""Handle epochs axes click."""
reject_color = (0.8, 0.8, 0.8)
ax = event.inaxes
if event.inaxes is None:
return
p = params
here = vars(ax)[p['axes_handler'][0]]
if here.get('reject', None) is False:
idx = here['idx']
if idx not in p['reject_idx']:
p['reject_idx'].append(idx)
for l in ax.lines:
l.set_color(reject_color)
here['reject'] = True
elif here.get('reject', None) is True:
idx = here['idx']
if idx in p['reject_idx']:
p['reject_idx'].pop(p['reject_idx'].index(idx))
good_lines = [ax.lines[k] for k in p['good_ch_idx']]
for l in good_lines:
l.set_color('k')
if p['bad_ch_idx'] is not None:
bad_lines = ax.lines[-len(p['bad_ch_idx']):]
for l in bad_lines:
l.set_color('r')
here['reject'] = False
ax.get_figure().canvas.draw()
def plot_epochs(epochs, picks=None, scalings=None, n_epochs=20, n_channels=20,
title=None, events=None, event_colors=None, show=True,
block=False, decim='auto'):
"""Visualize epochs.
Bad epochs can be marked with a left click on top of the epoch. Bad
channels can be selected by clicking the channel name on the left side of
the main axes. Calling this function drops all the selected bad epochs as
well as bad epochs marked beforehand with rejection parameters.
Parameters
----------
epochs : instance of Epochs
The epochs object
picks : array-like of int | None
Channels to be included. If None only good data channels are used.
Defaults to None
scalings : dict | 'auto' | None
Scaling factors for the traces. If any fields in scalings are 'auto',
the scaling factor is set to match the 99.5th percentile of a subset of
the corresponding data. If scalings == 'auto', all scalings fields are
set to 'auto'. If any fields are 'auto' and data is not preloaded,
a subset of epochs up to 100mb will be loaded. If None, defaults to::
dict(mag=1e-12, grad=4e-11, eeg=20e-6, eog=150e-6, ecg=5e-4,
emg=1e-3, ref_meg=1e-12, misc=1e-3, stim=1, resp=1, chpi=1e-4)
n_epochs : int
The number of epochs per view. Defaults to 20.
n_channels : int
The number of channels per view. Defaults to 20.
title : str | None
The title of the window. If None, epochs name will be displayed.
Defaults to None.
events : None, array, shape (n_events, 3)
Events to show with vertical bars. If events are provided, the epoch
numbers are not shown to prevent overlap. You can toggle epoch
numbering through options (press 'o' key). You can use
:func:`mne.viz.plot_events` as a legend for the colors. By default, the
coloring scheme is the same.
.. warning:: If the epochs have been resampled, the events no longer
align with the data.
.. versionadded:: 0.14.0
event_colors : None, dict
Dictionary of event_id value and its associated color. If None,
colors are automatically drawn from a default list (cycled through if
number of events longer than list of default colors). Uses the same
coloring scheme as :func:`mne.viz.plot_events`.
.. versionadded:: 0.14.0
show : bool
Show figure if True. Defaults to True
block : bool
Whether to halt program execution until the figure is closed.
Useful for rejecting bad trials on the fly by clicking on an epoch.
Defaults to False.
decim : int | 'auto'
Amount to decimate the data during display for speed purposes.
You should only decimate if the data are sufficiently low-passed,
otherwise aliasing can occur. The 'auto' mode (default) uses
the decimation that results in a sampling rate at least three times
larger than ``info['lowpass']`` (e.g., a 40 Hz lowpass will result in
at least a 120 Hz displayed sample rate).
.. versionadded:: 0.15
Returns
-------
fig : Instance of matplotlib.figure.Figure
The figure.
Notes
-----
The arrow keys (up/down/left/right) can be used to navigate between
channels and epochs and the scaling can be adjusted with - and + (or =)
keys, but this depends on the backend matplotlib is configured to use
(e.g., mpl.use(``TkAgg``) should work). Full screen mode can be toggled
with f11 key. The amount of epochs and channels per view can be adjusted
with home/end and page down/page up keys. These can also be set through
options dialog by pressing ``o`` key. ``h`` key plots a histogram of
peak-to-peak values along with the used rejection thresholds. Butterfly
plot can be toggled with ``b`` key. Right mouse click adds a vertical line
to the plot. Click 'help' button at bottom left corner of the plotter to
view all the options.
.. versionadded:: 0.10.0
"""
epochs.drop_bad()
scalings = _compute_scalings(scalings, epochs)
scalings = _handle_default('scalings_plot_raw', scalings)
decim, data_picks = _handle_decim(epochs.info.copy(), decim, None)
projs = epochs.info['projs']
params = {'epochs': epochs,
'info': copy.deepcopy(epochs.info),
'bad_color': (0.8, 0.8, 0.8),
't_start': 0,
'histogram': None,
'decim': decim,
'data_picks': data_picks}
params['label_click_fun'] = partial(_pick_bad_channels, params=params)
_prepare_mne_browse_epochs(params, projs, n_channels, n_epochs, scalings,
title, picks, events=events,
event_colors=event_colors)
_prepare_projectors(params)
_layout_figure(params)
callback_close = partial(_close_event, params=params)
params['fig'].canvas.mpl_connect('close_event', callback_close)
try:
plt_show(show, block=block)
except TypeError: # not all versions have this
plt_show(show)
return params['fig']
@verbose
def plot_epochs_psd(epochs, fmin=0, fmax=np.inf, tmin=None, tmax=None,
proj=False, bandwidth=None, adaptive=False, low_bias=True,
normalization='length', picks=None, ax=None, color='black',
area_mode='std', area_alpha=0.33, dB=True, n_jobs=1,
show=True, verbose=None):
"""Plot the power spectral density across epochs.
Parameters
----------
epochs : instance of Epochs
The epochs object
fmin : float
Start frequency to consider.
fmax : float
End frequency to consider.
tmin : float | None
Start time to consider.
tmax : float | None
End time to consider.
proj : bool
Apply projection.
bandwidth : float
The bandwidth of the multi taper windowing function in Hz. The default
value is a window half-bandwidth of 4.
adaptive : bool
Use adaptive weights to combine the tapered spectra into PSD
(slow, use n_jobs >> 1 to speed up computation).
low_bias : bool
Only use tapers with more than 90% spectral concentration within
bandwidth.
normalization : str
Either "full" or "length" (default). If "full", the PSD will
be normalized by the sampling rate as well as the length of
the signal (as in nitime).
picks : array-like of int | None
List of channels to use.
ax : instance of matplotlib Axes | None
Axes to plot into. If None, axes will be created.
color : str | tuple
A matplotlib-compatible color to use.
area_mode : str | None
Mode for plotting area. If 'std', the mean +/- 1 STD (across channels)
will be plotted. If 'range', the min and max (across channels) will be
plotted. Bad channels will be excluded from these calculations.
If None, no area will be plotted.
area_alpha : float
Alpha for the area.
dB : bool
If True, transform data to decibels.
n_jobs : int
Number of jobs to run in parallel.
show : bool
Show figure if True.
verbose : bool, str, int, or None
If not None, override default verbose level (see :func:`mne.verbose`
and :ref:`Logging documentation <tut_logging>` for more).
Returns
-------
fig : instance of matplotlib figure
Figure distributing one image per channel across sensor topography.
"""
from .raw import _set_psd_plot_params, _convert_psds
fig, picks_list, titles_list, units_list, scalings_list, ax_list, \
make_label = _set_psd_plot_params(
epochs.info, proj, picks, ax, area_mode)
for ii, (picks, title, ax) in enumerate(zip(picks_list, titles_list,
ax_list)):
psds, freqs = psd_multitaper(epochs, picks=picks, fmin=fmin,
fmax=fmax, tmin=tmin, tmax=tmax,
bandwidth=bandwidth, adaptive=adaptive,
low_bias=low_bias,
normalization=normalization, proj=proj,
n_jobs=n_jobs)
ylabel = _convert_psds(psds, dB, 'auto', scalings_list[ii],
units_list[ii],
[epochs.ch_names[pi] for pi in picks])
# mean across epochs and channels
psd_mean = np.mean(psds, axis=0).mean(axis=0)
if area_mode == 'std':
# std across channels
psd_std = np.std(np.mean(psds, axis=0), axis=0)
hyp_limits = (psd_mean - psd_std, psd_mean + psd_std)
elif area_mode == 'range':
hyp_limits = (np.min(np.mean(psds, axis=0), axis=0),
np.max(np.mean(psds, axis=0), axis=0))
else: # area_mode is None
hyp_limits = None
ax.plot(freqs, psd_mean, color=color)
if hyp_limits is not None:
ax.fill_between(freqs, hyp_limits[0], y2=hyp_limits[1],
color=color, alpha=area_alpha)
if make_label:
if ii == len(picks_list) - 1:
ax.set_xlabel('Freq (Hz)')
ax.set_ylabel(ylabel)
ax.set_title(title)
ax.set_xlim(freqs[0], freqs[-1])
if make_label:
tight_layout(pad=0.1, h_pad=0.1, w_pad=0.1, fig=fig)
plt_show(show)
return fig
def _prepare_mne_browse_epochs(params, projs, n_channels, n_epochs, scalings,
title, picks, events=None, event_colors=None,
order=None):
"""Set up the mne_browse_epochs window."""
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.collections import LineCollection
from matplotlib.colors import colorConverter
epochs = params['epochs']
if picks is None:
picks = _handle_picks(epochs)
if len(picks) < 1:
raise RuntimeError('No appropriate channels found. Please'
' check your picks')
picks = sorted(picks)
# Reorganize channels
inds = list()
types = list()
for t in ['grad', 'mag']:
idxs = pick_types(params['info'], meg=t, ref_meg=False, exclude=[])
if len(idxs) < 1:
continue
mask = np.in1d(idxs, picks, assume_unique=True)
inds.append(idxs[mask])
types += [t] * len(inds[-1])
for t in ['hbo', 'hbr']:
idxs = pick_types(params['info'], meg=False, ref_meg=False, fnirs=t,
exclude=[])
if len(idxs) < 1:
continue
mask = np.in1d(idxs, picks, assume_unique=True)
inds.append(idxs[mask])
types += [t] * len(inds[-1])
pick_kwargs = dict(meg=False, ref_meg=False, exclude=[])
if order is None:
order = ['eeg', 'seeg', 'ecog', 'eog', 'ecg', 'emg', 'ref_meg', 'stim',
'resp', 'misc', 'chpi', 'syst', 'ias', 'exci']
for ch_type in order:
pick_kwargs[ch_type] = True
idxs = pick_types(params['info'], **pick_kwargs)
if len(idxs) < 1:
continue
mask = np.in1d(idxs, picks, assume_unique=True)
inds.append(idxs[mask])
types += [ch_type] * len(inds[-1])
pick_kwargs[ch_type] = False
inds = np.concatenate(inds).astype(int)
if not len(inds) == len(picks):
raise RuntimeError('Some channels not classified. Please'
' check your picks')
ch_names = [params['info']['ch_names'][x] for x in inds]
# set up plotting
size = get_config('MNE_BROWSE_RAW_SIZE')
n_epochs = min(n_epochs, len(epochs.events))
duration = len(epochs.times) * n_epochs
n_channels = min(n_channels, len(picks))
if size is not None:
size = size.split(',')
size = tuple(float(s) for s in size)
if title is None:
title = epochs._name
if title is None or len(title) == 0:
title = ''
fig = figure_nobar(facecolor='w', figsize=size, dpi=80)
fig.canvas.set_window_title('mne_browse_epochs')
ax = plt.subplot2grid((10, 15), (0, 1), colspan=13, rowspan=9)
ax.annotate(title, xy=(0.5, 1), xytext=(0, ax.get_ylim()[1] + 15),
ha='center', va='bottom', size=12, xycoords='axes fraction',
textcoords='offset points')
color = _handle_default('color', None)
ax.axis([0, duration, 0, 200])
ax2 = ax.twiny()
ax2.set_zorder(-1)
ax2.axis([0, duration, 0, 200])
ax_hscroll = plt.subplot2grid((10, 15), (9, 1), colspan=13)
ax_hscroll.get_yaxis().set_visible(False)
ax_hscroll.set_xlabel('Epochs')
ax_vscroll = plt.subplot2grid((10, 15), (0, 14), rowspan=9)
ax_vscroll.set_axis_off()
ax_vscroll.add_patch(mpl.patches.Rectangle((0, 0), 1, len(picks),
facecolor='w', zorder=3))
ax_help_button = plt.subplot2grid((10, 15), (9, 0), colspan=1)
help_button = mpl.widgets.Button(ax_help_button, 'Help')
help_button.on_clicked(partial(_onclick_help, params=params))