-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
utils.py
2929 lines (2559 loc) · 97.4 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
"""Utility functions for plotting M/EEG data."""
# Authors: Alexandre Gramfort <[email protected]>
# Denis Engemann <[email protected]>
# Martin Luessi <[email protected]>
# Eric Larson <[email protected]>
# Mainak Jas <[email protected]>
# Stefan Appelhoff <[email protected]>
# Clemens Brunner <[email protected]>
# Daniel McCloy <[email protected]>
#
# License: Simplified BSD
from collections import defaultdict
from contextlib import contextmanager
from datetime import datetime
from inspect import signature
import difflib
from functools import partial
import math
import os
import sys
import tempfile
import traceback
import warnings
import webbrowser
from decorator import decorator
import numpy as np
from ..defaults import _handle_default
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,
_DATA_CH_TYPES_ORDER_DEFAULT,
_VALID_CHANNEL_TYPES,
pick_info,
_picks_by_type,
pick_channels_cov,
_contains_ch_type,
)
from ..io.proj import setup_proj, Projection
from ..rank import compute_rank
from ..utils import (
verbose,
get_config,
_check_ch_locs,
_check_option,
logger,
fill_doc,
_pl,
_check_sphere,
_ensure_int,
_validate_type,
_to_rgb,
warn,
check_version,
)
from ..transforms import apply_trans
_channel_type_prettyprint = {
"eeg": "EEG channel",
"grad": "Gradiometer",
"mag": "Magnetometer",
"seeg": "sEEG channel",
"dbs": "DBS channel",
"eog": "EOG channel",
"ecg": "ECG sensor",
"emg": "EMG sensor",
"ecog": "ECoG channel",
"misc": "miscellaneous sensor",
}
@decorator
def safe_event(fun, *args, **kwargs):
"""Protect against Qt exiting on event-handling errors."""
try:
return fun(*args, **kwargs)
except Exception:
traceback.print_exc(file=sys.stderr)
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.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.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`.
"""
import matplotlib.pyplot as plt
from matplotlib import get_backend
if hasattr(fig, "mne") and hasattr(fig.mne, "backend"):
backend = fig.mne.backend
else:
backend = get_backend()
if show and backend != "agg":
(fig or plt).show(**kwargs)
def _show_browser(show=True, block=True, fig=None, **kwargs):
"""Show the browser considering different backends.
Parameters
----------
show : bool
Show the figure.
block : bool
If to block execution on showing.
fig : instance of Figure | None
Needs to be passed for Qt backend,
optional for matplotlib.
**kwargs : dict
Extra arguments for :func:`matplotlib.pyplot.show`.
"""
from ._figure import get_browser_backend
_validate_type(block, bool, "block")
backend = get_browser_backend()
if os.getenv("_MNE_BROWSER_NO_BLOCK", "false").lower() == "true":
block = False
if backend == "matplotlib":
plt_show(show, block=block, **kwargs)
else:
from qtpy.QtCore import Qt
from qtpy.QtWidgets import QApplication
from .backends._utils import _qt_app_exec
if fig is not None and os.getenv("_MNE_BROWSER_BACK", "").lower() == "true":
fig.setWindowFlags(fig.windowFlags() | Qt.WindowStaysOnBottomHint)
if show:
fig.show()
# If block=False, a Qt-Event-Loop has to be started
# somewhere else in the calling code.
if block:
_qt_app_exec(QApplication.instance())
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.
"""
_validate_type(pad, "numeric", "pad")
import matplotlib.pyplot as plt
fig = plt.gcf() if fig is None else fig
fig.canvas.draw()
constrained = fig.get_constrained_layout()
kwargs = dict(pad=pad, h_pad=h_pad, w_pad=w_pad)
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(**kwargs)
except Exception:
try:
with warnings.catch_warnings(record=True) as ws:
if hasattr(fig, "set_layout_engine"):
fig.set_layout_engine("tight", **kwargs)
else:
fig.set_tight_layout(kwargs)
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, name="axes"):
"""Validate whether input is a list/array of axes."""
from matplotlib.axes import Axes
_validate_type(axes, (list, tuple, np.ndarray), name)
if isinstance(axes, np.ndarray) and axes.ndim > 1:
raise ValueError(
f"if {name} is a numpy array, it must be one-dimensional, but "
f"the received numpy array has {axes.ndim} dimensions. Try using "
"ravel or flatten method of the array."
)
wrong_idx = np.where([not isinstance(x, Axes) for x in axes])[0]
if len(wrong_idx):
raise TypeError(
f"{name} must be an array-like of matplotlib axes objects, but "
f"{name}[{wrong_idx[0]}] is of type {type(axes[wrong_idx[0]])}"
)
if obligatory_len is not None:
obligatory_len = _ensure_int(
obligatory_len, "obligatory_len", extra="if not None"
)
if len(axes) != obligatory_len:
raise ValueError(
f"{name} must be an array-like of length {obligatory_len}, "
f"but the length is {len(axes)}"
)
def mne_analyze_colormap(limits=[5, 10, 15], format="vtk"):
"""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 'vtk', 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.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 in ("vtk", "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:
# Use this instead of check_option because we have a hidden option
raise ValueError(f"format must be either matplotlib or vtk, got {repr(format)}")
@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 = list(params["proj_checks"].get_status())
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_channel_plotting_order(order, ch_types, picks=None):
"""Determine channel plotting order for browse-style Raw/Epochs plots."""
if order is None:
# for backward compat, we swap the first two to keep grad before mag
ch_type_order = list(_DATA_CH_TYPES_ORDER_DEFAULT)
ch_type_order = tuple(["grad", "mag"] + ch_type_order[2:])
order = [
pick_idx
for order_type in ch_type_order
for pick_idx, pick_type in enumerate(ch_types)
if order_type == pick_type
]
elif not isinstance(order, (np.ndarray, list, tuple)):
raise ValueError(
"order should be array-like; got " f'"{order}" ({type(order)}).'
)
if picks is not None:
order = [ch for ch in order if ch in picks]
return np.asarray(order, int)
def _make_event_color_dict(event_color, events=None, event_id=None):
"""Make or validate a dict mapping event ids to colors."""
from .misc import _handle_event_colors
if isinstance(event_color, dict): # if event_color is a dict, validate it
event_id = dict() if event_id is None else event_id
event_color = {
_ensure_int(event_id.get(key, key), "event_color key"): value
for key, value in event_color.items()
}
default = event_color.pop(-1, None)
default_factory = None if default is None else lambda: default
new_dict = defaultdict(default_factory)
for key, value in event_color.items():
if key < 1:
raise KeyError(
"event_color keys must be strictly positive, "
f"or -1 (cannot use {key})"
)
new_dict[key] = value
return new_dict
elif event_color is None: # make a dict from color cycle
uniq_events = set() if events is False else np.unique(events[:, 2])
return _handle_event_colors(event_color, uniq_events, event_id)
else: # if event_color is a MPL color-like thing, use it for all events
return defaultdict(lambda: event_color)
def _prepare_trellis(
n_cells,
ncols,
nrows="auto",
title=False,
colorbar=False,
size=1.3,
sharex=False,
sharey=False,
):
from matplotlib.gridspec import GridSpec
from ._mpl_figure import _figure
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
fig = _figure(toolbar=False, figsize=(width * 1.5, 0.25 + height * 1.5))
gs = GridSpec(nrows, ncols, figure=fig, height_ratios=height_ratios)
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:
subplot_kw = dict()
if ax_idx > 0:
if sharex:
subplot_kw.update(sharex=axes[0])
if sharey:
subplot_kw.update(sharey=axes[0])
axes.append(fig.add_subplot(gs[ax_idx], **subplot_kw))
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.0, 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.0 / 6.0 / 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')
# make edges around checkbox areas and change already-applied projectors
# to red
from ._mpl_figure import _OLD_BUTTONS
check_kwargs = dict()
if not _OLD_BUTTONS:
checkcolor = ["#ff0000" if p["active"] else "k" for p in projs]
check_kwargs["check_props"] = dict(facecolor=checkcolor)
check_kwargs["frame_props"] = dict(edgecolor="0.5", linewidth=1)
proj_checks = widgets.CheckButtons(
ax_temp, labels=labels, actives=actives, **check_kwargs
)
if _OLD_BUTTONS:
for rect in proj_checks.rectangles:
rect.set_edgecolor("0.5")
rect.set_linewidth(1.0)
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
@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 : path-like
First file to compare.
fname_2 : path-like
Second file to compare.
fname_out : path-like | 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 _show_help_fig(col1, col2, fig_help, ax, show):
_set_window_title(fig_help, "Help")
celltext = [
[c1, c2] for c1, c2 in zip(col1.strip().split("\n"), col2.strip().split("\n"))
]
table = ax.table(cellText=celltext, loc="center", cellLoc="left")
table.auto_set_font_size(False)
table.set_fontsize(12)
ax.set_axis_off()
for (row, col), cell in table.get_celld().items():
cell.set_edgecolor(None) # remove cell borders
# right justify, following:
# https://stackoverflow.com/questions/48210749/matplotlib-table-assign-different-text-alignments-to-different-columns?rq=1 # noqa: E501
if col == 0:
cell._loc = "right"
fig_help.canvas.mpl_connect("key_press_event", _key_press)
if show:
# this should work for non-test cases
try:
fig_help.canvas.draw()
plt_show(fig=fig_help, warn=False)
except Exception:
pass
def _show_help(col1, col2, width, height):
fig_help = figure_nobar(figsize=(width, height), dpi=80)
ax = fig_help.add_subplot(111)
_show_help_fig(col1, col2, fig_help, ax, show=True)
def _key_press(event):
"""Handle key press in dialog."""
import matplotlib.pyplot as plt
if event.key == "escape":
plt.close(event.canvas.figure)
class ClickableImage:
"""Display an image so you can click on it and store x/y positions.
Takes as input an image array (can be any array that works with imshow,
but will work best with images. Displays the image and lets you
click on it. Stores the xy coordinates of each click, so now you can
superimpose something on top of it.
Upon clicking, the x/y coordinate of the cursor will be stored in
self.coords, which is a list of (x, y) tuples.
Parameters
----------
imdata : ndarray
The image that you wish to click on for 2-d points.
**kwargs : dict
Keyword arguments. Passed to ax.imshow.
Notes
-----
.. versionadded:: 0.9.0
"""
def __init__(self, imdata, **kwargs):
"""Display the image for clicking."""
import matplotlib.pyplot as plt
self.coords = []
self.imdata = imdata
self.fig = plt.figure()
self.ax = self.fig.add_subplot(111)
self.ymax = self.imdata.shape[0]
self.xmax = self.imdata.shape[1]
self.im = self.ax.imshow(
imdata, extent=(0, self.xmax, 0, self.ymax), picker=True, **kwargs
)
self.ax.axis("off")
self.fig.canvas.mpl_connect("pick_event", self.onclick)
plt_show(block=True)
def onclick(self, event):
"""Handle Mouse clicks.
Parameters
----------
event : matplotlib.backend_bases.Event
The matplotlib object that we use to get x/y position.
"""
mouseevent = event.mouseevent
self.coords.append((mouseevent.xdata, mouseevent.ydata))
def plot_clicks(self, **kwargs):
"""Plot the x/y positions stored in self.coords.
Parameters
----------
**kwargs : dict
Arguments are passed to imshow in displaying the bg image.
"""
import matplotlib.pyplot as plt
if len(self.coords) == 0:
raise ValueError(
"No coordinates found, make sure you click "
"on the image that is first shown."
)
f, ax = plt.subplots()
ax.imshow(self.imdata, extent=(0, self.xmax, 0, self.ymax), **kwargs)
xlim, ylim = [ax.get_xlim(), ax.get_ylim()]
xcoords, ycoords = zip(*self.coords)
ax.scatter(xcoords, ycoords, c="#ff0000")
ann_text = np.arange(len(self.coords)).astype(str)
for txt, coord in zip(ann_text, self.coords):
ax.annotate(txt, coord, fontsize=20, color="#ff0000")
ax.set_xlim(xlim)
ax.set_ylim(ylim)
plt_show()
def to_layout(self, **kwargs):
"""Turn coordinates into an MNE Layout object.
Normalizes by the image you used to generate clicks
Parameters
----------
**kwargs : dict
Arguments are passed to generate_2d_layout.
Returns
-------
layout : instance of Layout
The layout.
"""
from ..channels.layout import generate_2d_layout
coords = np.array(self.coords)
lt = generate_2d_layout(coords, bg_image=self.imdata, **kwargs)
return lt
def _old_mpl_events():
return not check_version("matplotlib", "3.6")
def _fake_click(fig, ax, point, xform="ax", button=1, kind="press", key=None):
"""Fake a click at a relative point within axes."""
from matplotlib import backend_bases
if xform == "ax":
x, y = ax.transAxes.transform_point(point)
elif xform == "data":
x, y = ax.transData.transform_point(point)
else:
assert xform == "pix"
x, y = point
# This works on 3.6+, but not on <= 3.5.1 (lasso events not propagated)
if _old_mpl_events():
if kind == "press":
fig.canvas.button_press_event(x=x, y=y, button=button)
elif kind == "release":
fig.canvas.button_release_event(x=x, y=y, button=button)
elif kind == "motion":
fig.canvas.motion_notify_event(x=x, y=y)
else:
if kind in ("press", "release"):
kind = f"button_{kind}_event"
else:
assert kind == "motion"
kind = "motion_notify_event"
button = None
logger.debug(f"Faking {kind} @ ({x}, {y}) with button={button} and key={key}")
fig.canvas.callbacks.process(
kind,
backend_bases.MouseEvent(
name=kind, canvas=fig.canvas, x=x, y=y, button=button, key=key
),
)
def _fake_keypress(fig, key):
if _old_mpl_events():
fig.canvas.key_press_event(key)
else:
from matplotlib import backend_bases
fig.canvas.callbacks.process(
"key_press_event",
backend_bases.KeyEvent(name="key_press_event", canvas=fig.canvas, key=key),
)
def _fake_scroll(fig, x, y, step):
from matplotlib import backend_bases
button = "up" if step >= 0 else "down"
fig.canvas.callbacks.process(
"scroll_event",
backend_bases.MouseEvent(
name="scroll_event", canvas=fig.canvas, x=x, y=y, step=step, button=button
),
)
def add_background_image(fig, im, set_ratios=None):
"""Add a background image to a plot.
Adds the image specified in ``im`` to the
figure ``fig``. This is generally meant to
be done with topo plots, though it could work
for any plot.
.. note:: This modifies the figure and/or axes in place.
Parameters
----------
fig : Figure
The figure you wish to add a bg image to.
im : array, shape (M, N, {3, 4})
A background image for the figure. This must be a valid input to
`matplotlib.pyplot.imshow`. Defaults to None.
set_ratios : None | str
Set the aspect ratio of any axes in fig
to the value in set_ratios. Defaults to None,
which does nothing to axes.
Returns
-------
ax_im : instance of Axes
Axes created corresponding to the image you added.
Notes
-----
.. versionadded:: 0.9.0
"""
if im is None:
# Don't do anything and return nothing
return None
if set_ratios is not None:
for ax in fig.axes:
ax.set_aspect(set_ratios)
ax_im = fig.add_axes([0, 0, 1, 1], label="background")
ax_im.imshow(im, aspect="auto")
ax_im.set_zorder(-1)
return ax_im
def _find_peaks(evoked, npeaks):
"""Find peaks from evoked data.
Returns ``npeaks`` biggest peaks as a list of time points.
"""
from scipy.signal import argrelmax
gfp = evoked.data.std(axis=0)
order = len(evoked.times) // 30
if order < 1:
order = 1
peaks = argrelmax(gfp, order=order, axis=0)[0]
if len(peaks) > npeaks:
max_indices = np.argsort(gfp[peaks])[-npeaks:]
peaks = np.sort(peaks[max_indices])
times = evoked.times[peaks]
if len(times) == 0:
times = [evoked.times[gfp.argmax()]]
return times
def _process_times(inst, use_times, n_peaks=None, few=False):
"""Return a list of times for topomaps."""
if isinstance(use_times, str):
if use_times == "interactive":
use_times, n_peaks = "peaks", 1
if use_times == "peaks":
if n_peaks is None:
n_peaks = min(3 if few else 7, len(inst.times))
use_times = _find_peaks(inst, n_peaks)
elif use_times == "auto":
if n_peaks is None:
n_peaks = min(5 if few else 10, len(use_times))
use_times = np.linspace(inst.times[0], inst.times[-1], n_peaks)
else:
raise ValueError(
"Got an unrecognized method for `times`. Only "
"'peaks', 'auto' and 'interactive' are supported "
"(or directly passing numbers)."
)
elif np.isscalar(use_times):
use_times = [use_times]
use_times = np.array(use_times, float)
if use_times.ndim != 1:
raise ValueError("times must be 1D, got %d dimensions" % use_times.ndim)