-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathtopomap.py
4131 lines (3698 loc) · 128 KB
/
topomap.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 M/EEG data e.g. topographies."""
# Authors: The MNE-Python contributors.
# License: BSD-3-Clause
# Copyright the MNE-Python contributors.
import copy
import itertools
import warnings
from functools import partial
from numbers import Integral
import numpy as np
from scipy.interpolate import (
CloughTocher2DInterpolator,
LinearNDInterpolator,
NearestNDInterpolator,
)
from scipy.sparse import csr_array
from scipy.spatial import Delaunay, Voronoi
from scipy.spatial.distance import pdist, squareform
from .._fiff.meas_info import Info, _simplify_info
from .._fiff.pick import (
_MEG_CH_TYPES_SPLIT,
_pick_data_channels,
_picks_by_type,
_picks_to_idx,
pick_channels,
pick_info,
pick_types,
)
from ..baseline import rescale
from ..defaults import (
_BORDER_DEFAULT,
_EXTRAPOLATE_DEFAULT,
_INTERPOLATION_DEFAULT,
_handle_default,
)
from ..transforms import apply_trans, invert_transform
from ..utils import (
_check_option,
_check_sphere,
_clean_names,
_is_numeric,
_time_mask,
_validate_type,
check_version,
fill_doc,
legacy,
logger,
verbose,
warn,
)
from ..utils.spectrum import _split_psd_kwargs
from .ui_events import TimeChange, publish, subscribe
from .utils import (
DraggableColorbar,
_check_delayed_ssp,
_check_time_unit,
_check_type_projs,
_draw_proj_checkbox,
_format_units_psd,
_get_cmap,
_get_plot_ch_type,
_prepare_sensor_names,
_prepare_trellis,
_process_times,
_set_3d_axes_equal,
_setup_cmap,
_setup_vmin_vmax,
_validate_if_list_of_axes,
figure_nobar,
plot_sensors,
plt_show,
)
_fnirs_types = ("hbo", "hbr", "fnirs_cw_amplitude", "fnirs_od")
# 3.8+ uses a single Collection artist rather than .collections
# https://github.com/matplotlib/matplotlib/pull/25247
def _cont_collections(cont):
return (cont,) if check_version("matplotlib", "3.8") else tuple(cont.collections)
def _adjust_meg_sphere(sphere, info, ch_type):
sphere = _check_sphere(sphere, info)
assert ch_type is not None
if ch_type in ("mag", "grad", "planar1", "planar2"):
# move sphere X/Y (head coords) to device X/Y space
if info["dev_head_t"] is not None:
head_dev_t = invert_transform(info["dev_head_t"])
sphere[:3] = apply_trans(head_dev_t, sphere[:3])
# Set the sphere Z=0 because all this really affects is flattening.
# We could make the head size change as a function of depth in
# the helmet like:
#
# sphere[2] /= -5
#
# but let's just assume some orthographic rather than parallel
# projection for explicitness / simplicity.
sphere[2] = 0.0
clip_origin = (0.0, 0.0)
else:
clip_origin = sphere[:2].copy()
return sphere, clip_origin
def _prepare_topomap_plot(inst, ch_type, sphere=None):
"""Prepare topo plot."""
from ..channels.layout import _find_topomap_coords, _pair_grad_sensors, find_layout
info = copy.deepcopy(inst if isinstance(inst, Info) else inst.info)
sphere, clip_origin = _adjust_meg_sphere(sphere, info, ch_type)
clean_ch_names = _clean_names(info["ch_names"])
for ii, this_ch in enumerate(info["chs"]):
this_ch["ch_name"] = clean_ch_names[ii]
for comp in info["comps"]:
comp["data"]["col_names"] = _clean_names(comp["data"]["col_names"])
info._update_redundant()
info["bads"] = _clean_names(info["bads"])
info._check_consistency()
# special case for merging grad channels
layout = find_layout(info)
if (
ch_type == "grad"
and layout is not None
and (
layout.kind.startswith("Vectorview")
or layout.kind.startswith("Neuromag_122")
)
):
picks, _ = _pair_grad_sensors(info, layout)
pos = _find_topomap_coords(info, picks[::2], sphere=sphere)
merge_channels = True
elif ch_type in _fnirs_types:
# fNIRS data commonly has overlapping channels, so deal with separately
picks, pos, merge_channels, overlapping_channels = _average_fnirs_overlaps(
info, ch_type, sphere
)
else:
merge_channels = False
if ch_type == "eeg":
picks = pick_types(info, meg=False, eeg=True, ref_meg=False, exclude="bads")
elif ch_type == "csd":
picks = pick_types(info, meg=False, csd=True, ref_meg=False, exclude="bads")
elif ch_type == "dbs":
picks = pick_types(info, meg=False, dbs=True, ref_meg=False, exclude="bads")
elif ch_type == "seeg":
picks = pick_types(
info, meg=False, seeg=True, ref_meg=False, exclude="bads"
)
else:
picks = pick_types(info, meg=ch_type, ref_meg=False, exclude="bads")
if len(picks) == 0:
raise ValueError(f"No channels of type {ch_type!r}")
pos = _find_topomap_coords(info, picks, sphere=sphere)
ch_names = [info["ch_names"][k] for k in picks]
if ch_type in _fnirs_types:
# Remove the chroma label type for cleaner labeling.
ch_names = [k[:-4] for k in ch_names]
if merge_channels:
if ch_type == "grad":
# change names so that vectorview combined grads appear as MEG014x
# instead of MEG0142 or MEG0143 which are the 2 planar grads.
ch_names = [ch_names[k][:-1] + "x" for k in range(0, len(ch_names), 2)]
else:
assert ch_type in _fnirs_types
# Modify the nirs channel names to indicate they are to be merged
# New names will have the form S1_D1xS2_D2
# More than two channels can overlap and be merged
for set_ in overlapping_channels:
idx = ch_names.index(set_[0][:-4])
new_name = "x".join(s[:-4] for s in set_)
ch_names[idx] = new_name
pos = np.array(pos)[:, :2] # 2D plot, otherwise interpolation bugs
return picks, pos, merge_channels, ch_names, ch_type, sphere, clip_origin
def _average_fnirs_overlaps(info, ch_type, sphere):
from ..channels.layout import _find_topomap_coords
picks = pick_types(info, meg=False, ref_meg=False, fnirs=ch_type, exclude="bads")
chs = [info["chs"][i] for i in picks]
locs3d = np.array([ch["loc"][:3] for ch in chs])
dist = pdist(locs3d)
# Store the sets of channels to be merged
overlapping_channels = list()
# Channels to be excluded from picks, as will be removed after merging
channels_to_exclude = list()
if len(locs3d) > 1 and np.min(dist) < 1e-10:
overlapping_mask = np.triu(squareform(dist < 1e-10))
for chan_idx in range(overlapping_mask.shape[0]):
already_overlapped = list(
itertools.chain.from_iterable(overlapping_channels)
)
if overlapping_mask[chan_idx].any() and (
chs[chan_idx]["ch_name"] not in already_overlapped
):
# Determine the set of channels to be combined. Ensure the
# first listed channel is the one to be replaced with merge
overlapping_set = [
chs[i]["ch_name"] for i in np.where(overlapping_mask[chan_idx])[0]
]
overlapping_set = np.insert(
overlapping_set, 0, (chs[chan_idx]["ch_name"])
)
overlapping_channels.append(overlapping_set)
channels_to_exclude.append(overlapping_set[1:])
exclude = list(itertools.chain.from_iterable(channels_to_exclude))
[exclude.append(bad) for bad in info["bads"]]
picks = pick_types(
info, meg=False, ref_meg=False, fnirs=ch_type, exclude=exclude
)
pos = _find_topomap_coords(info, picks, sphere=sphere)
picks = pick_types(info, meg=False, ref_meg=False, fnirs=ch_type)
# Overload the merge_channels variable as this is returned to calling
# function and indicates that merging of data is required
merge_channels = overlapping_channels
else:
picks = pick_types(
info, meg=False, ref_meg=False, fnirs=ch_type, exclude="bads"
)
merge_channels = False
pos = _find_topomap_coords(info, picks, sphere=sphere)
return picks, pos, merge_channels, overlapping_channels
def _plot_update_evoked_topomap(params, bools):
"""Update topomaps."""
from ..channels.layout import _merge_ch_data
projs = [
proj for ii, proj in enumerate(params["projs"]) if ii in np.where(bools)[0]
]
params["proj_bools"] = bools
new_evoked = params["evoked"].copy()
with new_evoked.info._unlock():
new_evoked.info["projs"] = []
new_evoked.add_proj(projs)
new_evoked.apply_proj()
data = new_evoked.data[:, params["time_idx"]] * params["scale"]
if params["merge_channels"]:
data, _ = _merge_ch_data(data, "grad", [])
interp = params["interp"]
new_contours = list()
use_contours = params["contours_"]
if not len(use_contours):
use_contours = [None] * len(params["axes"])
assert len(use_contours) == len(params["images"])
assert len(params["axes"]) == len(params["images"])
assert len(data.T) == len(params["images"])
for cont, ax, im, d in zip(use_contours, params["axes"], params["images"], data.T):
Zi = interp.set_values(d)()
im.set_data(Zi)
if cont is None:
continue
# must be removed and re-added
cont_collections = _cont_collections(cont)
for col in cont_collections:
col.remove()
col = cont_collections[0]
lw = col.get_linewidth()
visible = col.get_visible()
patch_ = col.get_clip_path()
color = col.get_edgecolors()
cont = ax.contour(
interp.Xi, interp.Yi, Zi, params["contours"], colors=color, linewidths=lw
)
cont_collections = _cont_collections(cont)
for col in cont_collections:
col.set_visible(visible)
col.set_clip_path(patch_)
new_contours.append(cont)
params["contours_"] = new_contours
params["fig"].canvas.draw()
def _add_colorbar(
ax,
im,
cmap,
*,
title=None,
format_=None,
kind=None,
ch_type=None,
):
"""Add a colorbar to an axis."""
cbar = ax.figure.colorbar(im, format=format_, shrink=0.6)
if cmap is not None and cmap[1]:
ax.CB = DraggableColorbar(cbar, im, kind, ch_type)
cax = cbar.ax
if title is not None:
cax.set_title(title, y=1.05, fontsize=10)
return cbar, cax
def _eliminate_zeros(proj):
"""Remove grad or mag data if only contains 0s (gh 5641)."""
GRAD_ENDING = ("2", "3")
MAG_ENDING = "1"
proj = copy.deepcopy(proj)
proj["data"]["data"] = np.atleast_2d(proj["data"]["data"])
for ending in (GRAD_ENDING, MAG_ENDING):
names = proj["data"]["col_names"]
idx = [i for i, name in enumerate(names) if name.endswith(ending)]
# if all 0, remove the 0s an their labels
if not proj["data"]["data"][0][idx].any():
new_col_names = np.delete(np.array(names), idx).tolist()
new_data = np.delete(np.array(proj["data"]["data"][0]), idx)
proj["data"]["col_names"] = new_col_names
proj["data"]["data"] = np.array([new_data])
proj["data"]["ncol"] = len(proj["data"]["col_names"])
return proj
@fill_doc
def plot_projs_topomap(
projs,
info,
*,
sensors=True,
show_names=False,
contours=6,
outlines="head",
sphere=None,
image_interp=_INTERPOLATION_DEFAULT,
extrapolate=_EXTRAPOLATE_DEFAULT,
border=_BORDER_DEFAULT,
res=64,
size=1,
cmap=None,
vlim=(None, None),
cnorm=None,
colorbar=False,
cbar_fmt="%3.1f",
units=None,
axes=None,
show=True,
):
"""Plot topographic maps of SSP projections.
Parameters
----------
projs : list of Projection
The projections.
%(info_not_none)s Must be associated with the channels in the projectors.
.. versionchanged:: 0.20
The positional argument ``layout`` was replaced by ``info``.
%(sensors_topomap)s
%(show_names_topomap)s
.. versionadded:: 1.2
%(contours_topomap)s
%(outlines_topomap)s
%(sphere_topomap_auto)s
%(image_interp_topomap)s
%(extrapolate_topomap)s
.. versionadded:: 0.20
.. versionchanged:: 0.21
- The default was changed to ``'local'`` for MEG sensors.
- ``'local'`` was changed to use a convex hull mask
- ``'head'`` was changed to extrapolate out to the clipping circle.
%(border_topomap)s
.. versionadded:: 0.20
%(res_topomap)s
%(size_topomap)s
%(cmap_topomap)s
%(vlim_plot_topomap_proj)s
%(cnorm)s
.. versionadded:: 1.2
%(colorbar_topomap)s
%(cbar_fmt_topomap)s
.. versionadded:: 1.2
%(units_topomap)s
.. versionadded:: 1.2
%(axes_plot_projs_topomap)s
%(show)s
Returns
-------
fig : instance of matplotlib.figure.Figure
Figure with a topomap subplot for each projector.
Notes
-----
.. versionadded:: 0.9.0
"""
fig = _plot_projs_topomap(
projs,
info,
sensors=sensors,
show_names=show_names,
contours=contours,
outlines=outlines,
sphere=sphere,
image_interp=image_interp,
extrapolate=extrapolate,
border=border,
res=res,
size=size,
cmap=cmap,
vlim=vlim,
cnorm=cnorm,
colorbar=colorbar,
cbar_fmt=cbar_fmt,
units=units,
axes=axes,
)
with warnings.catch_warnings(record=True):
warnings.simplefilter("ignore")
plt_show(show)
return fig
def _plot_projs_topomap(
projs,
info,
sensors=True,
show_names=False,
contours=6,
outlines="head",
sphere=None,
image_interp=_INTERPOLATION_DEFAULT,
extrapolate=_EXTRAPOLATE_DEFAULT,
border=_BORDER_DEFAULT,
res=64,
size=1,
cmap=None,
vlim=(None, None),
cnorm=None,
colorbar=False,
cbar_fmt="%3.1f",
units=None,
axes=None,
):
import matplotlib.pyplot as plt
from ..channels.layout import _merge_ch_data
sphere = _check_sphere(sphere, info)
projs = _check_type_projs(projs)
_validate_type(info, "info", "info")
# Preprocess projs to deal with joint MEG projectors. If we duplicate these and
# split into mag and grad, they should work as expected
info_names = _clean_names(info["ch_names"], remove_whitespace=True)
use_projs = list()
for proj in projs:
proj = _eliminate_zeros(proj) # gh 5641, makes a copy
proj["data"]["col_names"] = _clean_names(
proj["data"]["col_names"],
remove_whitespace=True,
)
picks = pick_channels(info_names, proj["data"]["col_names"], ordered=True)
proj_types = info.get_channel_types(picks)
unique_types = sorted(set(proj_types))
for type_ in unique_types:
proj_picks = np.where([proj_type == type_ for proj_type in proj_types])[0]
use_projs.append(copy.deepcopy(proj))
use_projs[-1]["data"]["data"] = proj["data"]["data"][:, proj_picks]
use_projs[-1]["data"]["col_names"] = [
proj["data"]["col_names"][pick] for pick in proj_picks
]
projs = use_projs
datas, poss, spheres, outliness, ch_typess = [], [], [], [], []
for proj in projs:
# get ch_names, ch_types, data
data = proj["data"]["data"].ravel()
picks = pick_channels(info_names, proj["data"]["col_names"], ordered=True)
use_info = pick_info(info, picks)
these_ch_types = use_info.get_channel_types(unique=True)
assert len(these_ch_types) == 1 # should be guaranteed above
ch_type = these_ch_types[0]
(
data_picks,
pos,
merge_channels,
names,
_,
this_sphere,
clip_origin,
) = _prepare_topomap_plot(use_info, ch_type, sphere=sphere)
these_outlines = _make_head_outlines(sphere, pos, outlines, clip_origin)
data = data[data_picks]
if merge_channels:
data, _ = _merge_ch_data(data, "grad", [])
data = data.ravel()
# populate containers
datas.append(data)
poss.append(pos)
spheres.append(this_sphere)
outliness.append(these_outlines)
ch_typess.append(ch_type)
del data, pos, this_sphere, these_outlines, ch_type
del sphere
# setup axes
n_projs = len(projs)
if axes is None:
fig, axes, ncols, nrows = _prepare_trellis(
n_projs, ncols="auto", nrows="auto", size=size, sharex=True, sharey=True
)
elif isinstance(axes, plt.Axes):
axes = [axes]
_validate_if_list_of_axes(axes, n_projs)
# handle vmin/vmax
vlims = [None for _ in range(len(datas))]
if vlim == "joint":
for _ch_type in set(ch_typess):
idx = np.where(np.isin(ch_typess, _ch_type))[0]
these_data = np.concatenate(np.array(datas, dtype=object)[idx])
norm = all(these_data >= 0)
_vl = _setup_vmin_vmax(these_data, vmin=None, vmax=None, norm=norm)
for _idx in idx:
vlims[_idx] = _vl
# make sure we got a vlim for all projs
assert all([vl is not None for vl in vlims])
else:
vlims = [vlim] * len(datas)
# plot
for proj, ax, _data, _pos, _vlim, _sphere, _outlines, _ch_type in zip(
projs, axes, datas, poss, vlims, spheres, outliness, ch_typess
):
# ch_names
names = [info["ch_names"][k] for k in _picks_to_idx(info, _ch_type)]
names = _prepare_sensor_names(names, show_names)
# title
title = proj["desc"]
title = "\n".join(title[ii : ii + 22] for ii in range(0, len(title), 22))
ax.set_title(title, fontsize=10)
# plot
im, _ = plot_topomap(
_data,
_pos[:, :2],
vlim=_vlim,
cmap=cmap,
sensors=sensors,
names=names,
res=res,
axes=ax,
outlines=_outlines,
contours=contours,
cnorm=cnorm,
image_interp=image_interp,
show=False,
extrapolate=extrapolate,
sphere=_sphere,
border=border,
ch_type=_ch_type,
)
if colorbar:
_add_colorbar(
ax,
im,
cmap,
title=units,
format_=cbar_fmt,
kind="projs_topomap",
ch_type=_ch_type,
)
return ax.get_figure()
def _make_head_outlines(sphere, pos, outlines, clip_origin):
"""Check or create outlines for topoplot."""
assert isinstance(sphere, np.ndarray)
x, y, _, radius = sphere
del sphere
if outlines in ("head", None):
ll = np.linspace(0, 2 * np.pi, 101)
head_x = np.cos(ll) * radius + x
head_y = np.sin(ll) * radius + y
dx = np.exp(np.arccos(np.deg2rad(12)) * 1j)
dx, dy = dx.real, dx.imag
nose_x = np.array([-dx, 0, dx]) * radius + x
nose_y = np.array([dy, 1.15, dy]) * radius + y
ear_x = np.array(
[0.497, 0.510, 0.518, 0.5299, 0.5419, 0.54, 0.547, 0.532, 0.510, 0.489]
) * (radius * 2)
ear_y = (
np.array(
[
0.0555,
0.0775,
0.0783,
0.0746,
0.0555,
-0.0055,
-0.0932,
-0.1313,
-0.1384,
-0.1199,
]
)
* (radius * 2)
+ y
)
if outlines is not None:
# Define the outline of the head, ears and nose
outlines_dict = dict(
head=(head_x, head_y),
nose=(nose_x, nose_y),
ear_left=(-ear_x + x, ear_y),
ear_right=(ear_x + x, ear_y),
)
else:
outlines_dict = dict()
# Make the figure encompass slightly more than all points
# We probably want to ensure it always contains our most
# extremely positioned channels, so we do:
mask_scale = max(1.0, np.linalg.norm(pos, axis=1).max() * 1.01 / radius)
outlines_dict["mask_pos"] = (mask_scale * head_x, mask_scale * head_y)
clip_radius = radius * mask_scale
outlines_dict["clip_radius"] = (clip_radius,) * 2
outlines_dict["clip_origin"] = clip_origin
outlines = outlines_dict
elif isinstance(outlines, dict):
if "mask_pos" not in outlines:
raise ValueError("You must specify the coordinates of the image mask.")
else:
raise ValueError("Invalid value for `outlines`.")
return outlines
def _draw_outlines(ax, outlines):
"""Draw the outlines for a topomap."""
from matplotlib import rcParams
outlines_ = {k: v for k, v in outlines.items() if k not in ["patch"]}
for key, (x_coord, y_coord) in outlines_.items():
if "mask" in key or key in ("clip_radius", "clip_origin"):
continue
ax.plot(
x_coord,
y_coord,
color=rcParams["axes.edgecolor"],
linewidth=1,
clip_on=False,
)
return outlines_
def _get_extra_points(pos, extrapolate, origin, radii):
"""Get coordinates of additional interpolation points."""
radii = np.array(radii, float)
assert radii.shape == (2,)
x, y = origin
# auto should be gone by now
_check_option("extrapolate", extrapolate, ("head", "box", "local"))
# the old method of placement - large box
mask_pos = None
if extrapolate == "box":
extremes = np.array([pos.min(axis=0), pos.max(axis=0)])
diffs = extremes[1] - extremes[0]
extremes[0] -= diffs
extremes[1] += diffs
eidx = np.array(
list(itertools.product(*([[0] * (pos.shape[1] - 1) + [1]] * pos.shape[1])))
)
pidx = np.tile(np.arange(pos.shape[1])[np.newaxis], (len(eidx), 1))
outer_pts = extremes[eidx, pidx]
return outer_pts, mask_pos, Delaunay(np.concatenate((pos, outer_pts)))
# check if positions are colinear:
diffs = np.diff(pos, axis=0)
with np.errstate(divide="ignore"):
slopes = diffs[:, 1] / diffs[:, 0]
colinear = (slopes == slopes[0]).all() or np.isinf(slopes).all()
# compute median inter-electrode distance
if colinear or pos.shape[0] < 4:
dim = 1 if diffs[:, 1].sum() > diffs[:, 0].sum() else 0
sorting = np.argsort(pos[:, dim])
pos_sorted = pos[sorting, :]
diffs = np.diff(pos_sorted, axis=0)
distances = np.linalg.norm(diffs, axis=1)
distance = np.median(distances)
else:
tri = Delaunay(pos, incremental=True)
idx1, idx2, idx3 = tri.simplices.T
distances = np.concatenate(
[
np.linalg.norm(pos[i1, :] - pos[i2, :], axis=1)
for i1, i2 in zip([idx1, idx2], [idx2, idx3])
]
)
distance = np.median(distances)
if extrapolate == "local":
if colinear or pos.shape[0] < 4:
# special case for colinear points and when there is too
# little points for Delaunay (needs at least 3)
edge_points = sorting[[0, -1]]
line_len = np.diff(pos[edge_points, :], axis=0)
unit_vec = line_len / np.linalg.norm(line_len) * distance
unit_vec_par = unit_vec[:, ::-1] * [[-1, 1]]
edge_pos = pos[edge_points, :] + np.concatenate(
[-unit_vec, unit_vec], axis=0
)
new_pos = np.concatenate(
[pos + unit_vec_par, pos - unit_vec_par, edge_pos], axis=0
)
if pos.shape[0] == 3:
# there may be some new_pos points that are too close
# to the original points
new_pos_diff = pos[..., np.newaxis] - new_pos.T[np.newaxis, :]
new_pos_diff = np.linalg.norm(new_pos_diff, axis=1)
good_extra = (new_pos_diff > 0.5 * distance).all(axis=0)
new_pos = new_pos[good_extra]
tri = Delaunay(np.concatenate([pos, new_pos], axis=0))
return new_pos, new_pos, tri
# get the convex hull of data points from triangulation
hull_pos = pos[tri.convex_hull]
# extend the convex hull limits outwards a bit
channels_center = pos.mean(axis=0)
radial_dir = hull_pos - channels_center
unit_radial_dir = radial_dir / np.linalg.norm(
radial_dir, axis=-1, keepdims=True
)
hull_extended = hull_pos + unit_radial_dir * distance
mask_pos = hull_pos + unit_radial_dir * distance * 0.5
hull_diff = np.diff(hull_pos, axis=1)[:, 0]
hull_distances = np.linalg.norm(hull_diff, axis=-1)
del channels_center
# Construct a mask
mask_pos = np.unique(mask_pos.reshape(-1, 2), axis=0)
mask_center = np.mean(mask_pos, axis=0)
mask_pos -= mask_center
mask_pos = mask_pos[np.argsort(np.arctan2(mask_pos[:, 1], mask_pos[:, 0]))]
mask_pos += mask_center
# add points along hull edges so that the distance between points
# is around that of average distance between channels
add_points = list()
eps = np.finfo("float").eps
n_times_dist = np.round(0.25 * hull_distances / distance).astype("int")
for n in range(2, n_times_dist.max() + 1):
mask = n_times_dist == n
mult = np.arange(1 / n, 1 - eps, 1 / n)[:, np.newaxis, np.newaxis]
steps = hull_diff[mask][np.newaxis, ...] * mult
add_points.append(
(hull_extended[mask, 0][np.newaxis, ...] + steps).reshape((-1, 2))
)
# remove duplicates from hull_extended
hull_extended = np.unique(hull_extended.reshape((-1, 2)), axis=0)
new_pos = np.concatenate([hull_extended] + add_points)
else:
assert extrapolate == "head"
# return points on the head circle
angle = np.arcsin(min(distance / np.mean(radii), 1))
n_pnts = max(12, int(np.round(2 * np.pi / angle)))
points_l = np.linspace(0, 2 * np.pi, n_pnts, endpoint=False)
use_radii = radii * 1.1 + distance
points_x = np.cos(points_l) * use_radii[0] + x
points_y = np.sin(points_l) * use_radii[1] + y
new_pos = np.stack([points_x, points_y], axis=1)
if colinear or pos.shape[0] == 3:
tri = Delaunay(np.concatenate([pos, new_pos], axis=0))
return new_pos, mask_pos, tri
tri.add_points(new_pos)
return new_pos, mask_pos, tri
class _GridData:
"""Unstructured (x,y) data interpolator.
This class allows optimized interpolation by computing parameters
for a fixed set of true points, and allowing the values at those points
to be set independently.
"""
def __init__(self, pos, image_interp, extrapolate, origin, radii, border):
# in principle this works in N dimensions, not just 2
assert pos.ndim == 2 and pos.shape[1] == 2, pos.shape
_validate_type(border, ("numeric", str), "border")
# check that border, if string, is correct
if isinstance(border, str):
_check_option("border", border, ("mean",), extra="when a string")
# Adding points outside the extremes helps the interpolators
outer_pts, mask_pts, tri = _get_extra_points(pos, extrapolate, origin, radii)
self.n_extra = outer_pts.shape[0]
self.mask_pts = mask_pts
self.border = border
self.tri = tri
self.interp = {
"cubic": CloughTocher2DInterpolator,
"nearest": NearestNDInterpolator, # used only for anim
"linear": LinearNDInterpolator,
}[image_interp]
def set_values(self, v):
"""Set the values at interpolation points."""
# Rbf with thin-plate is what we used to use, but it's slower and
# looks about the same:
#
# zi = Rbf(x, y, v, function='multiquadric', smooth=0)(xi, yi)
#
# Eventually we could also do set_values with this class if we want,
# see scipy/interpolate/rbf.py, especially the self.nodes one-liner.
if isinstance(self.border, str):
# we've already checked that border = 'mean'
n_points = v.shape[0]
v_extra = np.zeros(self.n_extra)
indices, indptr = self.tri.vertex_neighbor_vertices
rng = range(n_points, n_points + self.n_extra)
used = np.zeros(len(rng), bool)
for idx, extra_idx in enumerate(rng):
ngb = indptr[indices[extra_idx] : indices[extra_idx + 1]]
ngb = ngb[ngb < n_points]
if len(ngb) > 0:
used[idx] = True
v_extra[idx] = v[ngb].mean()
if not used.all() and used.any():
# Eventually we might want to use the value of the nearest
# point or something, but this case should hopefully be
# rare so for now just use the average value of all extras
v_extra[~used] = np.mean(v_extra[used])
else:
v_extra = np.full(self.n_extra, self.border, dtype=float)
v = np.concatenate((v, v_extra))
self.interpolator = self.interp(self.tri, v)
return self
def set_locations(self, Xi, Yi):
"""Set locations for easier (delayed) calling."""
self.Xi = Xi
self.Yi = Yi
return self
def __call__(self, *args):
"""Evaluate the interpolator."""
if len(args) == 0:
args = [self.Xi, self.Yi]
return self.interpolator(*args)
def _topomap_plot_sensors(pos_x, pos_y, sensors, ax):
"""Plot sensors."""
if sensors is True:
ax.scatter(
pos_x,
pos_y,
s=0.25,
marker="o",
edgecolor=["k"] * len(pos_x),
facecolor="none",
)
else:
ax.plot(pos_x, pos_y, sensors)
def _get_pos_outlines(info, picks, sphere, to_sphere=True):
from ..channels.layout import _find_topomap_coords
picks = _picks_to_idx(info, picks, "all", exclude=(), allow_empty=False)
ch_type = _get_plot_ch_type(pick_info(_simplify_info(info), picks), None)
orig_sphere = sphere
sphere, clip_origin = _adjust_meg_sphere(sphere, info, ch_type)
logger.debug(
f"Generating pos outlines with sphere {sphere} from {orig_sphere} for {ch_type}"
)
pos = _find_topomap_coords(
info, picks, ignore_overlap=True, to_sphere=to_sphere, sphere=sphere
)
outlines = _make_head_outlines(sphere, pos, "head", clip_origin)
return pos, outlines
@fill_doc
def plot_topomap(
data,
pos,
*,
ch_type="eeg",
sensors=True,
names=None,
mask=None,
mask_params=None,
contours=6,
outlines="head",
sphere=None,
image_interp=_INTERPOLATION_DEFAULT,
extrapolate=_EXTRAPOLATE_DEFAULT,
border=_BORDER_DEFAULT,
res=64,
size=1,
cmap=None,
vlim=(None, None),
cnorm=None,
axes=None,
show=True,
onselect=None,
):
"""Plot a topographic map as image.
Parameters
----------
data : array, shape (n_chan,)
The data values to plot.
%(pos_topomap)s
If an :class:`~mne.Info` object it must contain only one channel type
and exactly ``len(data)`` channels; the x/y coordinates will
be inferred from the montage in the :class:`~mne.Info` object.
%(ch_type_topomap)s
.. versionadded:: 0.21
%(sensors_topomap)s
%(names_topomap)s
%(mask_topomap)s
%(mask_params_topomap)s
%(contours_topomap)s
%(outlines_topomap)s
%(sphere_topomap_auto)s
%(image_interp_topomap)s
%(extrapolate_topomap)s
.. versionadded:: 0.18
.. versionchanged:: 0.21
- The default was changed to ``'local'`` for MEG sensors.
- ``'local'`` was changed to use a convex hull mask
- ``'head'`` was changed to extrapolate out to the clipping circle.
%(border_topomap)s
.. versionadded:: 0.20
%(res_topomap)s
%(size_topomap)s
%(cmap_topomap)s
%(vlim_plot_topomap)s
.. versionadded:: 1.2
%(cnorm)s
.. versionadded:: 0.24
%(axes_plot_topomap)s
.. versionchanged:: 1.2
If ``axes=None``, a new :class:`~matplotlib.figure.Figure` is
created instead of plotting into the current axes.
%(show)s
onselect : callable | None
A function to be called when the user selects a set of channels by
click-dragging (uses a matplotlib
:class:`~matplotlib.widgets.RectangleSelector`). If ``None``
interactive channel selection is disabled. Defaults to ``None``.