/
utils.py
3321 lines (2927 loc) · 127 KB
/
utils.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
# -*- coding: utf-8 -*-
"""Utility functions for plotting M/EEG data."""
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Denis Engemann <denis.engemann@gmail.com>
# Martin Luessi <mluessi@nmr.mgh.harvard.edu>
# Eric Larson <larson.eric.d@gmail.com>
# Mainak Jas <mainak@neuro.hut.fi>
# Stefan Appelhoff <stefan.appelhoff@mailbox.org>
# Clemens Brunner <clemens.brunner@gmail.com>
# Daniel McCloy <dan.mccloy@gmail.com>
#
# License: Simplified BSD
from contextlib import contextmanager
from functools import partial
import difflib
import webbrowser
import tempfile
import math
import numpy as np
import platform
from copy import deepcopy
from distutils.version import LooseVersion
from itertools import cycle
import warnings
from ..defaults import _handle_default
from ..fixes import _get_status
from ..io import show_fiff, Info
from ..io.constants import FIFF
from ..io.pick import (channel_type, channel_indices_by_type, pick_channels,
_pick_data_channels, _DATA_CH_TYPES_SPLIT,
_VALID_CHANNEL_TYPES, pick_types,
pick_info, _picks_by_type, pick_channels_cov,
_picks_to_idx, _contains_ch_type)
from ..io.meas_info import create_info
from ..rank import compute_rank
from ..io.proj import setup_proj
from ..utils import (verbose, get_config, set_config, warn, _check_ch_locs,
_check_option, logger, fill_doc, _pl, _check_sphere)
from ..selection import (read_selection, _SELECTIONS, _EEG_SELECTIONS,
_divide_to_regions)
from ..annotations import _sync_onset
from ..transforms import apply_trans
_channel_type_prettyprint = {'eeg': "EEG channel", 'grad': "Gradiometer",
'mag': "Magnetometer", 'seeg': "sEEG channel",
'eog': "EOG channel", 'ecg': "ECG sensor",
'emg': "EMG sensor", 'ecog': "ECoG channel",
'misc': "miscellaneous sensor"}
def _setup_vmin_vmax(data, vmin, vmax, norm=False):
"""Handle vmin and vmax parameters for visualizing topomaps.
For the normal use-case (when `vmin` and `vmax` are None), the parameter
`norm` drives the computation. When norm=False, data is supposed to come
from a mag and the output tuple (vmin, vmax) is symmetric range
(-x, x) where x is the max(abs(data)). When norm=True (a.k.a. data is the
L2 norm of a gradiometer pair) the output tuple corresponds to (0, x).
Otherwise, vmin and vmax are callables that drive the operation.
"""
should_warn = False
if vmax is None and vmin is None:
vmax = np.abs(data).max()
vmin = 0. if norm else -vmax
if vmin == 0 and np.min(data) < 0:
should_warn = True
else:
if callable(vmin):
vmin = vmin(data)
elif vmin is None:
vmin = 0. if norm else np.min(data)
if vmin == 0 and np.min(data) < 0:
should_warn = True
if callable(vmax):
vmax = vmax(data)
elif vmax is None:
vmax = np.max(data)
if should_warn:
warn_msg = ("_setup_vmin_vmax output a (min={vmin}, max={vmax})"
" range whereas the minimum of data is {data_min}")
warn_val = {'vmin': vmin, 'vmax': vmax, 'data_min': np.min(data)}
warn(warn_msg.format(**warn_val), UserWarning)
return vmin, vmax
def plt_show(show=True, fig=None, **kwargs):
"""Show a figure while suppressing warnings.
Parameters
----------
show : bool
Show the figure.
fig : instance of Figure | None
If non-None, use fig.show().
**kwargs : dict
Extra arguments for :func:`matplotlib.pyplot.show`.
"""
from matplotlib import get_backend
import matplotlib.pyplot as plt
if show and get_backend() != 'agg':
(fig or plt).show(**kwargs)
def tight_layout(pad=1.2, h_pad=None, w_pad=None, fig=None):
"""Adjust subplot parameters to give specified padding.
.. note:: For plotting please use this function instead of
``plt.tight_layout``.
Parameters
----------
pad : float
Padding between the figure edge and the edges of subplots, as a
fraction of the font-size.
h_pad : float
Padding height between edges of adjacent subplots.
Defaults to ``pad_inches``.
w_pad : float
Padding width between edges of adjacent subplots.
Defaults to ``pad_inches``.
fig : instance of Figure
Figure to apply changes to.
Notes
-----
This will not force constrained_layout=False if the figure was created
with that method.
"""
import matplotlib.pyplot as plt
fig = plt.gcf() if fig is None else fig
fig.canvas.draw()
try:
constrained = fig.get_constrained_layout()
except AttributeError: # old matplotlib presumably
constrained = False
if constrained:
return # no-op
try: # see https://github.com/matplotlib/matplotlib/issues/2654
with warnings.catch_warnings(record=True) as ws:
fig.tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad)
except Exception:
try:
with warnings.catch_warnings(record=True) as ws:
fig.set_tight_layout(dict(pad=pad, h_pad=h_pad, w_pad=w_pad))
except Exception:
warn('Matplotlib function "tight_layout" is not supported.'
' Skipping subplot adjustment.')
return
for w in ws:
w_msg = str(w.message) if hasattr(w, 'message') else w.get_message()
if not w_msg.startswith('This figure includes Axes'):
warn(w_msg, w.category, 'matplotlib')
def _check_delayed_ssp(container):
"""Handle interactive SSP selection."""
if container.proj is True or\
all(p['active'] for p in container.info['projs']):
raise RuntimeError('Projs are already applied. Please initialize'
' the data with proj set to False.')
elif len(container.info['projs']) < 1:
raise RuntimeError('No projs found in evoked.')
def _validate_if_list_of_axes(axes, obligatory_len=None):
"""Validate whether input is a list/array of axes."""
from matplotlib.axes import Axes
if obligatory_len is not None and not isinstance(obligatory_len, int):
raise ValueError('obligatory_len must be None or int, got %d',
'instead' % type(obligatory_len))
if not isinstance(axes, (list, np.ndarray)):
raise ValueError('axes must be a list or numpy array of matplotlib '
'axes objects, got %s instead.' % type(axes))
if isinstance(axes, np.ndarray) and axes.ndim > 1:
raise ValueError('if input is a numpy array, it must be '
'one-dimensional. The received numpy array has %d '
'dimensions however. Try using ravel or flatten '
'method of the array.' % axes.ndim)
is_correct_type = np.array([isinstance(x, Axes)
for x in axes])
if not np.all(is_correct_type):
first_bad = np.where(np.logical_not(is_correct_type))[0][0]
raise ValueError('axes must be a list or numpy array of matplotlib '
'axes objects while one of the list elements is '
'%s.' % type(axes[first_bad]))
if obligatory_len is not None and not len(axes) == obligatory_len:
raise ValueError('axes must be a list/array of length %d, while the'
' length is %d' % (obligatory_len, len(axes)))
def mne_analyze_colormap(limits=[5, 10, 15], format='mayavi'):
"""Return a colormap similar to that used by mne_analyze.
Parameters
----------
limits : list (or array) of length 3 or 6
Bounds for the colormap, which will be mirrored across zero if length
3, or completely specified (and potentially asymmetric) if length 6.
format : str
Type of colormap to return. If 'matplotlib', will return a
matplotlib.colors.LinearSegmentedColormap. If 'mayavi', will
return an RGBA array of shape (256, 4).
Returns
-------
cmap : instance of colormap | array
A teal->blue->gray->red->yellow colormap. See docstring of the 'format'
argument for further details.
Notes
-----
For this will return a colormap that will display correctly for data
that are scaled by the plotting function to span [-fmax, fmax].
""" # noqa: E501
# Ensure limits is an array
limits = np.asarray(limits, dtype='float')
if len(limits) != 3 and len(limits) != 6:
raise ValueError('limits must have 3 or 6 elements')
if len(limits) == 3 and any(limits < 0.):
raise ValueError('if 3 elements, limits must all be non-negative')
if any(np.diff(limits) <= 0):
raise ValueError('limits must be monotonically increasing')
if format == 'matplotlib':
from matplotlib import colors
if len(limits) == 3:
limits = (np.concatenate((-np.flipud(limits), limits)) +
limits[-1]) / (2 * limits[-1])
else:
limits = (limits - np.min(limits)) / np.max(limits -
np.min(limits))
cdict = {'red': ((limits[0], 0.0, 0.0),
(limits[1], 0.0, 0.0),
(limits[2], 0.5, 0.5),
(limits[3], 0.5, 0.5),
(limits[4], 1.0, 1.0),
(limits[5], 1.0, 1.0)),
'green': ((limits[0], 1.0, 1.0),
(limits[1], 0.0, 0.0),
(limits[2], 0.5, 0.5),
(limits[3], 0.5, 0.5),
(limits[4], 0.0, 0.0),
(limits[5], 1.0, 1.0)),
'blue': ((limits[0], 1.0, 1.0),
(limits[1], 1.0, 1.0),
(limits[2], 0.5, 0.5),
(limits[3], 0.5, 0.5),
(limits[4], 0.0, 0.0),
(limits[5], 0.0, 0.0)),
'alpha': ((limits[0], 1.0, 1.0),
(limits[1], 1.0, 1.0),
(limits[2], 0.0, 0.0),
(limits[3], 0.0, 0.0),
(limits[4], 1.0, 1.0),
(limits[5], 1.0, 1.0)),
}
return colors.LinearSegmentedColormap('mne_analyze', cdict)
elif format == 'mayavi':
if len(limits) == 3:
limits = np.concatenate((-np.flipud(limits), [0], limits)) /\
limits[-1]
else:
limits = np.concatenate((limits[:3], [0], limits[3:]))
limits /= np.max(np.abs(limits))
r = np.array([0, 0, 0, 0, 1, 1, 1])
g = np.array([1, 0, 0, 0, 0, 0, 1])
b = np.array([1, 1, 1, 0, 0, 0, 0])
a = np.array([1, 1, 0, 0, 0, 1, 1])
xp = (np.arange(256) - 128) / 128.0
colormap = np.r_[[np.interp(xp, limits, 255 * c)
for c in [r, g, b, a]]].T
return colormap
else:
raise ValueError('format must be either matplotlib or mayavi')
def _toggle_options(event, params):
"""Toggle options (projectors) dialog."""
import matplotlib.pyplot as plt
if len(params['projs']) > 0:
if params['fig_proj'] is None:
_draw_proj_checkbox(event, params, draw_current_state=False)
else:
# turn off options dialog
plt.close(params['fig_proj'])
del params['proj_checks']
params['fig_proj'] = None
@contextmanager
def _events_off(obj):
obj.eventson = False
try:
yield
finally:
obj.eventson = True
def _toggle_proj(event, params, all_=False):
"""Perform operations when proj boxes clicked."""
# read options if possible
if 'proj_checks' in params:
bools = _get_status(params['proj_checks'])
if all_:
new_bools = [not all(bools)] * len(bools)
with _events_off(params['proj_checks']):
for bi, (old, new) in enumerate(zip(bools, new_bools)):
if old != new:
params['proj_checks'].set_active(bi)
bools[bi] = new
for bi, (b, p) in enumerate(zip(bools, params['projs'])):
# see if they tried to deactivate an active one
if not b and p['active']:
bools[bi] = True
else:
proj = params.get('apply_proj', True)
bools = [proj] * len(params['projs'])
compute_proj = False
if 'proj_bools' not in params:
compute_proj = True
elif not np.array_equal(bools, params['proj_bools']):
compute_proj = True
# if projectors changed, update plots
if compute_proj is True:
params['plot_update_proj_callback'](params, bools)
def _get_help_text(params):
"""Customize help dialogs text."""
is_mac = platform.system() == 'Darwin'
text, text2 = list(), list()
text.append('(Shift +) ← : \n')
text.append('(Shift +) → : \n')
text.append('↓ : \n')
text.append('↑ : \n')
text.append('- : \n')
text.append('+ or = : \n')
if is_mac:
text.append('fn + ← : \n')
text.append('fn + → : \n')
if 'fig_selection' not in params:
text.append('fn + ↓ : \n')
text.append('fn + ↑ : \n')
else:
text.append('Home : \n')
text.append('End : \n')
if 'fig_selection' not in params:
text.append('Page down : \n')
text.append('Page up : \n')
text.append('z : \n')
text.append('F11 : \n')
text.append('? : \n')
text.append('Esc : \n\n')
text.append('Mouse controls\n')
text.append('click on data :\n')
text2.append('Navigate left\n')
text2.append('Navigate right\n')
text2.append('Scale down\n')
text2.append('Scale up\n')
text2.append('Toggle scrollbars\n')
text2.append('Toggle full screen mode\n')
text2.append('Open help box\n')
text2.append('Quit\n\n\n')
if 'raw' in params:
text2.insert(4, 'Reduce the time shown per view\n')
text2.insert(5, 'Increase the time shown per view\n')
text.append('click elsewhere in the plot :\n')
if 'ica' in params:
text.append('click component name :\n')
text2.insert(2, 'Navigate components down\n')
text2.insert(3, 'Navigate components up\n')
text2.insert(8, 'Reduce the number of components per view\n')
text2.insert(9, 'Increase the number of components per view\n')
text2.append('Mark bad channel\n')
text2.append('Vertical line at a time instant\n')
text2.append('Show topography for the component\n')
else:
text.append('click channel name :\n')
text2.insert(2, 'Navigate channels down\n')
text2.insert(3, 'Navigate channels up\n')
text.insert(6, 'a : \n')
text2.insert(6, 'Toggle annotation mode\n')
text.insert(7, 'p : \n')
text2.insert(7, 'Toggle snap to annotations on/off\n')
text.insert(8, 'b : \n')
text2.insert(8, 'Toggle butterfly plot on/off\n')
text.insert(9, 'd : \n')
text2.insert(9, 'Toggle remove DC on/off\n')
text.insert(10, 's : \n')
text2.insert(10, 'Toggle scale bars\n')
if 'fig_selection' not in params:
text2.insert(13, 'Reduce the number of channels per view\n')
text2.insert(14, 'Increase the number of channels per view\n')
text2.append('Mark bad channel\n')
text2.append('Vertical line at a time instant\n')
text2.append('Mark bad channel\n')
elif 'epochs' in params:
text.append('right click :\n')
text2.insert(4, 'Reduce the number of epochs per view\n')
text2.insert(5, 'Increase the number of epochs per view\n')
if 'ica' in params:
text.append('click component name :\n')
text2.insert(2, 'Navigate components down\n')
text2.insert(3, 'Navigate components up\n')
text2.insert(8, 'Reduce the number of components per view\n')
text2.insert(9, 'Increase the number of components per view\n')
text2.append('Mark component for exclusion\n')
text2.append('Vertical line at a time instant\n')
text2.append('Show topography for the component\n')
else:
text.append('click channel name :\n')
text.append('right click channel name :\n')
text2.insert(2, 'Navigate channels down\n')
text2.insert(3, 'Navigate channels up\n')
text2.insert(8, 'Reduce the number of channels per view\n')
text2.insert(9, 'Increase the number of channels per view\n')
text.insert(10, 'b : \n')
text2.insert(10, 'Toggle butterfly plot on/off\n')
text.insert(11, 'h : \n')
text2.insert(11, 'Show histogram of peak-to-peak values\n')
text2.append('Mark bad epoch\n')
text2.append('Vertical line at a time instant\n')
text2.append('Mark bad channel\n')
text2.append('Plot ERP/ERF image\n')
text.append('middle click :\n')
text2.append('Show channel name (butterfly plot)\n')
text.insert(11, 'o : \n')
text2.insert(11, 'View settings (orig. view only)\n')
return ''.join(text), ''.join(text2)
def _prepare_trellis(n_cells, ncols, nrows='auto', title=False, colorbar=False,
size=1.3):
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
if n_cells == 1:
nrows = ncols = 1
elif isinstance(ncols, int) and n_cells <= ncols:
nrows, ncols = 1, n_cells
else:
if ncols == 'auto' and nrows == 'auto':
nrows = math.floor(math.sqrt(n_cells))
ncols = math.ceil(n_cells / nrows)
elif ncols == 'auto':
ncols = math.ceil(n_cells / nrows)
elif nrows == 'auto':
nrows = math.ceil(n_cells / ncols)
else:
naxes = ncols * nrows
if naxes < n_cells:
raise ValueError("Cannot plot {} axes in a {} by {} "
"figure.".format(n_cells, nrows, ncols))
if colorbar:
ncols += 1
width = size * ncols
height = (size + max(0, 0.1 * (4 - size))) * nrows + bool(title) * 0.5
height_ratios = None
g_kwargs = {}
figure_nobar(figsize=(width * 1.5, height * 1.5))
gs = GridSpec(nrows, ncols, height_ratios=height_ratios, **g_kwargs)
axes = []
if colorbar:
# exclude last axis of each row except top row, which is for colorbar
exclude = set(range(2 * ncols - 1, nrows * ncols, ncols))
ax_idxs = sorted(set(range(nrows * ncols)) - exclude)[:n_cells + 1]
else:
ax_idxs = range(n_cells)
for ax_idx in ax_idxs:
axes.append(plt.subplot(gs[ax_idx]))
fig = axes[0].get_figure()
return fig, axes, ncols, nrows
def _draw_proj_checkbox(event, params, draw_current_state=True):
"""Toggle options (projectors) dialog."""
from matplotlib import widgets
projs = params['projs']
# turn on options dialog
labels = [p['desc'] for p in projs]
actives = ([p['active'] for p in projs] if draw_current_state else
params.get('proj_bools', [params['apply_proj']] * len(projs)))
width = max([4., max([len(p['desc']) for p in projs]) / 6.0 + 0.5])
height = (len(projs) + 1) / 6.0 + 1.5
fig_proj = figure_nobar(figsize=(width, height))
_set_window_title(fig_proj, 'SSP projection vectors')
offset = (1. / 6. / height)
params['fig_proj'] = fig_proj # necessary for proper toggling
ax_temp = fig_proj.add_axes((0, offset, 1, 0.8 - offset), frameon=False)
ax_temp.set_title('Projectors marked with "X" are active')
proj_checks = widgets.CheckButtons(ax_temp, labels=labels, actives=actives)
# make edges around checkbox areas
for rect in proj_checks.rectangles:
rect.set_edgecolor('0.5')
rect.set_linewidth(1.)
# change already-applied projectors to red
for ii, p in enumerate(projs):
if p['active']:
for x in proj_checks.lines[ii]:
x.set_color('#ff0000')
# make minimal size
# pass key presses from option dialog over
proj_checks.on_clicked(partial(_toggle_proj, params=params))
params['proj_checks'] = proj_checks
fig_proj.canvas.mpl_connect('key_press_event', _key_press)
# Toggle all
ax_temp = fig_proj.add_axes((0, 0, 1, offset), frameon=False)
proj_all = widgets.Button(ax_temp, 'Toggle all')
proj_all.on_clicked(partial(_toggle_proj, params=params, all_=True))
params['proj_all'] = proj_all
# this should work for non-test cases
try:
fig_proj.canvas.draw()
plt_show(fig=fig_proj, warn=False)
except Exception:
pass
def _simplify_float(label):
# Heuristic to turn floats to ints where possible (e.g. -500.0 to -500)
if isinstance(label, float) and np.isfinite(label) and \
float(str(label)) != round(label):
label = round(label, 2)
return label
def _get_figsize_from_config():
"""Get default / most recent figure size from config."""
figsize = get_config('MNE_BROWSE_RAW_SIZE')
if figsize is not None:
figsize = figsize.split(',')
figsize = tuple([float(s) for s in figsize])
return figsize
def _get_figsize_px(fig):
"""Get figure size in pixels."""
dpi_ratio = _get_dpi_ratio(fig)
size = fig.get_size_inches() * fig.dpi / dpi_ratio
return size
def _get_dpi_ratio(fig):
"""Get DPI ratio (to handle hi-DPI screens)."""
dpi_ratio = 1.
for key in ('_dpi_ratio', '_device_scale'):
dpi_ratio = getattr(fig.canvas, key, dpi_ratio)
return dpi_ratio
def _inch_to_rel_dist(fig, dim_inches, horiz=True):
"""Convert inches to figure-relative distances."""
fig_w_px, fig_h_px = _get_figsize_px(fig)
w_or_h = fig_w_px if horiz else fig_h_px
return dim_inches * fig.dpi / _get_dpi_ratio(fig) / w_or_h
def _update_borders(params, new_width, new_height):
"""Update figure borders to maintain fixed size in inches/pixels."""
old_width, old_height = params['fig_size_px']
new_borders = dict()
sides = ('left', 'right', 'bottom', 'top')
for side in sides:
horiz = side in ('left', 'right')
ratio = (old_width / new_width) if horiz else (old_height / new_height)
rel_dim = getattr(params['fig'].subplotpars, side)
if side in ('right', 'top'):
rel_dim = (1 - rel_dim)
rel_dim = rel_dim * ratio
if side in ('right', 'top'):
rel_dim = (1 - rel_dim)
new_borders[side] = rel_dim
# zen mode adjustment
params['zen_w_delta'] *= old_width / new_width
params['zen_h_delta'] *= old_height / new_height
# update
params['fig'].subplots_adjust(**new_borders)
def _toggle_scrollbars(params):
"""Show or hide scrollbars (A.K.A. zen mode) in mne_browse-style plots."""
if params.get('show_scrollbars', None) is not None:
# grow/shrink main axes to take up space from/make room for scrollbars
# can't use ax.set_position() because axes are locatable, so we have to
# fake it with subplots_adjust
should_show = not params['show_scrollbars']
sides = ('left', 'bottom', 'right', 'top')
borders = {side: getattr(params['fig'].subplotpars, side)
for side in sides}
# if should_show, bottom margin moves up; right margin moves left
borders['bottom'] += (1 if should_show else -1) * params['zen_h_delta']
borders['right'] += (-1 if should_show else 1) * params['zen_w_delta']
# squeeze a little more because we don't need space for "Time (s)" now
v_delta = _inch_to_rel_dist(params['fig'], 0.16, horiz=False)
borders['bottom'] += (1 if should_show else -1) * v_delta
params['fig'].subplots_adjust(**borders)
# show/hide
for element in ('ax_hscroll', 'ax_vscroll', 'ax_button', 'ax_help'):
if params.get('butterfly', False) and element == 'ax_vscroll':
continue
# sometimes we don't have a proj button (ax_button)
if params.get(element, None) is not None:
params[element].set_visible(should_show)
params['show_scrollbars'] = should_show
params['fig'].canvas.draw()
def _prepare_mne_browse(params, xlabel):
"""Set up axes for mne_browse_* style raw/epochs/ICA plots."""
import matplotlib as mpl
from mpl_toolkits.axes_grid1.axes_size import Fixed
from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable
fig = params['fig']
fig_w_px, fig_h_px = _get_figsize_px(fig)
params['fig_size_px'] = fig_w_px, fig_h_px # store for on_resize callback
# default sizes (inches)
scroll_width = 0.25
hscroll_dist = 0.25
vscroll_dist = 0.1
l_border = 1.
r_border = 0.1
b_border = 0.45
t_border = 0.25
help_width = scroll_width * 2
# default borders (figure-relative coordinates)
fig.subplots_adjust(
left=_inch_to_rel_dist(fig, l_border - vscroll_dist - help_width),
right=1 - _inch_to_rel_dist(fig, r_border),
bottom=_inch_to_rel_dist(fig, b_border, horiz=False),
top=1 - _inch_to_rel_dist(fig, t_border, horiz=False)
)
# Main axes must be a `subplot` for `subplots_adjust` to work (so user can
# adjust margins). That's why we don't use the Divider class directly.
ax = fig.add_subplot(1, 1, 1)
div = make_axes_locatable(ax)
ax_hscroll = div.append_axes(position='bottom', size=Fixed(scroll_width),
pad=Fixed(hscroll_dist))
ax_vscroll = div.append_axes(position='right', size=Fixed(scroll_width),
pad=Fixed(vscroll_dist))
# proj button (optionally) added later, but easiest to compute position now
proj_button_pos = [
1 - _inch_to_rel_dist(fig, r_border + scroll_width), # left
_inch_to_rel_dist(fig, b_border, horiz=False), # bottom
_inch_to_rel_dist(fig, scroll_width), # width
_inch_to_rel_dist(fig, scroll_width, horiz=False) # height
]
params['proj_button_pos'] = proj_button_pos
params['proj_button_locator'] = div.new_locator(nx=2, ny=0)
# initialize help button axes in the wrong spot...
ax_help = div.append_axes(position='left', size=Fixed(help_width),
pad=Fixed(vscroll_dist))
# ...then move it down by changing its locator, and make it a button.
loc = div.new_locator(nx=0, ny=0)
ax_help.set_axes_locator(loc)
help_button = mpl.widgets.Button(ax_help, 'Help')
help_button.on_clicked(partial(_onclick_help, params=params))
# style scrollbars
ax_hscroll.get_yaxis().set_visible(False)
ax_hscroll.set_xlabel(xlabel)
ax_vscroll.set_axis_off()
# store these so they can be modified elsewhere
params['ax'] = ax
params['ax_hscroll'] = ax_hscroll
params['ax_vscroll'] = ax_vscroll
params['ax_help'] = ax_help
params['help_button'] = help_button
# default key to close window
params['close_key'] = 'escape'
# add resize callback (it's the same for Raw/Epochs/ICA)
callback_resize = partial(_resize_event, params=params)
params['fig'].canvas.mpl_connect('resize_event', callback_resize)
# zen mode
fig.canvas.draw() # otherwise the get_position() calls are inaccurate
params['zen_w_delta'] = (ax_vscroll.get_position().xmax -
ax.get_position().xmax)
params['zen_h_delta'] = (ax.get_position().ymin -
ax_hscroll.get_position().ymin)
if not params.get('show_scrollbars', True):
# change to True so toggle func will do the right thing
params['show_scrollbars'] = True
_toggle_scrollbars(params)
@verbose
def compare_fiff(fname_1, fname_2, fname_out=None, show=True, indent=' ',
read_limit=np.inf, max_str=30, verbose=None):
"""Compare the contents of two fiff files using diff and show_fiff.
Parameters
----------
fname_1 : str
First file to compare.
fname_2 : str
Second file to compare.
fname_out : str | None
Filename to store the resulting diff. If None, a temporary
file will be created.
show : bool
If True, show the resulting diff in a new tab in a web browser.
indent : str
How to indent the lines.
read_limit : int
Max number of bytes of data to read from a tag. Can be np.inf
to always read all data (helps test read completion).
max_str : int
Max number of characters of string representation to print for
each tag's data.
%(verbose)s
Returns
-------
fname_out : str
The filename used for storing the diff. Could be useful for
when a temporary file is used.
"""
file_1 = show_fiff(fname_1, output=list, indent=indent,
read_limit=read_limit, max_str=max_str)
file_2 = show_fiff(fname_2, output=list, indent=indent,
read_limit=read_limit, max_str=max_str)
diff = difflib.HtmlDiff().make_file(file_1, file_2, fname_1, fname_2)
if fname_out is not None:
f = open(fname_out, 'wb')
else:
f = tempfile.NamedTemporaryFile('wb', delete=False, suffix='.html')
fname_out = f.name
with f as fid:
fid.write(diff.encode('utf-8'))
if show is True:
webbrowser.open_new_tab(fname_out)
return fname_out
def figure_nobar(*args, **kwargs):
"""Make matplotlib figure with no toolbar.
Parameters
----------
*args : list
Arguments to pass to :func:`matplotlib.pyplot.figure`.
**kwargs : dict
Keyword arguments to pass to :func:`matplotlib.pyplot.figure`.
Returns
-------
fig : instance of Figure
The figure.
"""
from matplotlib import rcParams, pyplot as plt
old_val = rcParams['toolbar']
try:
rcParams['toolbar'] = 'none'
fig = plt.figure(*args, **kwargs)
# remove button press catchers (for toolbar)
cbs = list(fig.canvas.callbacks.callbacks['key_press_event'].keys())
for key in cbs:
fig.canvas.callbacks.disconnect(key)
finally:
rcParams['toolbar'] = old_val
return fig
def _resize_event(event, params):
"""Handle resize event for mne_browse-style plots (Raw/Epochs/ICA)."""
size = ','.join([str(s) for s in params['fig'].get_size_inches()])
set_config('MNE_BROWSE_RAW_SIZE', size, set_env=False)
new_width, new_height = _get_figsize_px(params['fig'])
_update_borders(params, new_width, new_height)
params['fig_size_px'] = (new_width, new_height)
def _plot_raw_onscroll(event, params, len_channels=None):
"""Interpret scroll events."""
if 'fig_selection' in params:
if params['butterfly']:
return
_change_channel_group(event.step, params)
return
if len_channels is None:
len_channels = len(params['inds'])
orig_start = params['ch_start']
if event.step < 0:
params['ch_start'] = min(params['ch_start'] + params['n_channels'],
len_channels - params['n_channels'])
else: # event.key == 'up':
params['ch_start'] = max(params['ch_start'] - params['n_channels'], 0)
if orig_start != params['ch_start']:
_channels_changed(params, len_channels)
def _channels_changed(params, len_channels):
"""Deal with the vertical shift of the viewport."""
if params['ch_start'] + params['n_channels'] > len_channels:
params['ch_start'] = len_channels - params['n_channels']
if params['ch_start'] < 0:
params['ch_start'] = 0
params['plot_fun']()
def _plot_raw_time(value, params):
"""Deal with changed time value."""
info = params['info']
max_times = params['n_times'] / float(info['sfreq']) + \
params['first_time'] - params['duration']
if value > max_times:
value = params['n_times'] / float(info['sfreq']) + \
params['first_time'] - params['duration']
if value < params['first_time']:
value = params['first_time']
if params['t_start'] != value:
params['t_start'] = value
params['hsel_patch'].set_x(value)
def _radio_clicked(label, params):
"""Handle radio buttons in selection dialog."""
from .evoked import _rgb
# First the selection dialog.
labels = [label._text for label in params['fig_selection'].radio.labels]
idx = labels.index(label)
params['fig_selection'].radio._active_idx = idx
channels = params['selections'][label]
ax_topo = params['fig_selection'].get_axes()[1]
types = np.array([], dtype=int)
for this_type in _DATA_CH_TYPES_SPLIT:
if this_type in params['types']:
types = np.concatenate(
[types, np.where(np.array(params['types']) == this_type)[0]])
colors = np.zeros((len(types), 4)) # alpha = 0 by default
locs3d = np.array([ch['loc'][:3] for ch in params['info']['chs']])
x, y, z = locs3d.T
color_vals = _rgb(x, y, z)
for color_idx, pick in enumerate(types):
if pick in channels: # set color and alpha = 1
colors[color_idx] = np.append(color_vals[pick], 1.)
ax_topo.collections[0]._facecolors = colors
params['fig_selection'].canvas.draw()
if params['butterfly']:
return
# Then the plotting window.
params['ax_vscroll'].set_visible(True)
nchan = sum([len(params['selections'][label]) for label in labels[:idx]])
params['vsel_patch'].set_y(nchan)
n_channels = len(channels)
params['n_channels'] = n_channels
params['inds'] = channels
for line in params['lines'][n_channels:]: # To remove lines from view.
line.set_xdata([])
line.set_ydata([])
if n_channels > 0: # Can be 0 with lasso selector.
_setup_browser_offsets(params, n_channels)
params['plot_fun']()
def _get_active_radio_idx(radio):
"""Find out active radio button."""
labels = [label.get_text() for label in radio.labels]
return labels.index(radio.value_selected)
def _set_annotation_radio_button(idx, params):
"""Set active button."""
radio = params['fig_annotation'].radio
for circle in radio.circles:
circle.set_facecolor('white')
radio.circles[idx].set_facecolor('#cccccc')
_annotation_radio_clicked('', radio, params['ax'].selector)
def _set_radio_button(idx, params):
"""Set radio button."""
# XXX: New version of matplotlib has this implemented for radio buttons,
# This function is for compatibility with old versions of mpl.
radio = params['fig_selection'].radio
radio.circles[radio._active_idx].set_facecolor((1., 1., 1., 1.))
radio.circles[idx].set_facecolor((0., 0., 1., 1.))
_radio_clicked(radio.labels[idx]._text, params)
def _change_channel_group(step, params):
"""Deal with change of channel group."""
radio = params['fig_selection'].radio
idx = radio._active_idx
if step < 0:
if idx < len(radio.labels) - 1:
_set_radio_button(idx + 1, params)
elif idx > 0:
_set_radio_button(idx - 1, params)
def _handle_change_selection(event, params):
"""Handle clicks on vertical scrollbar using selections."""
radio = params['fig_selection'].radio
ydata = event.ydata
labels = [label._text for label in radio.labels]
offset = 0
for idx, label in enumerate(labels):
nchans = len(params['selections'][label])
offset += nchans
if ydata < offset:
_set_radio_button(idx, params)
return
def _plot_raw_onkey(event, params):
"""Interpret key presses."""
import matplotlib.pyplot as plt
if event.key == params['close_key']:
plt.close(params['fig'])
if params['fig_annotation'] is not None:
plt.close(params['fig_annotation'])
elif event.key == 'down':
if 'fig_selection' in params.keys():
_change_channel_group(-1, params)
return
elif params['butterfly']:
return
params['ch_start'] += params['n_channels']
_channels_changed(params, len(params['inds']))
elif event.key == 'up':
if 'fig_selection' in params.keys():
_change_channel_group(1, params)
return
elif params['butterfly']:
return
params['ch_start'] -= params['n_channels']
_channels_changed(params, len(params['inds']))
elif event.key == 'right':
value = params['t_start'] + params['duration'] / 4
_plot_raw_time(value, params)
params['update_fun']()
params['plot_fun']()
elif event.key == 'shift+right':
value = params['t_start'] + params['duration']
_plot_raw_time(value, params)
params['update_fun']()
params['plot_fun']()
elif event.key == 'left':
value = params['t_start'] - params['duration'] / 4
_plot_raw_time(value, params)
params['update_fun']()
params['plot_fun']()
elif event.key == 'shift+left':
value = params['t_start'] - params['duration']
_plot_raw_time(value, params)
params['update_fun']()
params['plot_fun']()
elif event.key in ['+', '=']:
params['scale_factor'] *= 1.1
params['plot_fun']()
elif event.key == '-':
params['scale_factor'] /= 1.1
params['plot_fun']()
elif event.key == 'pageup' and 'fig_selection' not in params:
n_channels = min(params['n_channels'] + 1, len(params['info']['chs']))
_setup_browser_offsets(params, n_channels)
_channels_changed(params, len(params['inds']))
elif event.key == 'pagedown' and 'fig_selection' not in params:
n_channels = params['n_channels'] - 1
if n_channels == 0:
return
_setup_browser_offsets(params, n_channels)
if len(params['lines']) > n_channels: # remove line from view
params['lines'][n_channels].set_xdata([])