-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
topomap.py
2132 lines (1898 loc) · 88.6 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."""
from __future__ import print_function
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Denis Engemann <denis.engemann@gmail.com>
# Martin Luessi <mluessi@nmr.mgh.harvard.edu>
# Eric Larson <larson.eric.d@gmail.com>
#
# License: Simplified BSD
import math
import copy
from functools import partial
from numbers import Integral
import numpy as np
from scipy import linalg
from ..baseline import rescale
from ..io.constants import FIFF
from ..io.pick import (pick_types, _picks_by_type, channel_type, pick_info,
_pick_data_channels)
from ..utils import _clean_names, _time_mask, verbose, logger, warn
from .utils import (tight_layout, _setup_vmin_vmax, _prepare_trellis,
_check_delayed_ssp, _draw_proj_checkbox, figure_nobar,
plt_show, _process_times, DraggableColorbar,
_validate_if_list_of_axes, _setup_cmap)
from ..time_frequency import psd_multitaper
from ..defaults import _handle_default
from ..channels.layout import _find_topomap_coords
from ..io.meas_info import Info
from ..externals.six import string_types
def _prepare_topo_plot(inst, ch_type, layout):
"""Prepare topo plot."""
info = copy.deepcopy(inst if isinstance(inst, Info) else inst.info)
if layout is None and ch_type is not 'eeg':
from ..channels import find_layout
layout = find_layout(info)
elif layout == 'auto':
layout = None
clean_ch_names = _clean_names(info['ch_names'])
for ii, this_ch in enumerate(info['chs']):
this_ch['ch_name'] = clean_ch_names[ii]
info._update_redundant()
info._check_consistency()
# special case for merging grad channels
if (ch_type == 'grad' and FIFF.FIFFV_COIL_VV_PLANAR_T1 in
np.unique([ch['coil_type'] for ch in info['chs']])):
from ..channels.layout import _pair_grad_sensors
picks, pos = _pair_grad_sensors(info, layout)
merge_grads = True
else:
merge_grads = False
if ch_type == 'eeg':
picks = pick_types(info, meg=False, eeg=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("No channels of type %r" % ch_type)
if layout is None:
pos = _find_topomap_coords(info, picks)
else:
names = [n.upper() for n in layout.names]
pos = list()
for pick in picks:
this_name = info['ch_names'][pick].upper()
if this_name in names:
pos.append(layout.pos[names.index(this_name)])
else:
warn('Failed to locate %s channel positions from layout. '
'Inferring channel positions from data.' % ch_type)
pos = _find_topomap_coords(info, picks)
break
ch_names = [info['ch_names'][k] for k in picks]
if merge_grads:
# 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)]
pos = np.array(pos)[:, :2] # 2D plot, otherwise interpolation bugs
return picks, pos, merge_grads, ch_names, ch_type
def _plot_update_evoked_topomap(params, bools):
"""Update topomaps."""
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()
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_grads']:
from ..channels.layout import _merge_grad_data
data = _merge_grad_data(data)
image_mask = params['image_mask']
pos_x, pos_y = np.asarray(params['pos'])[:, :2].T
xi = np.linspace(pos_x.min(), pos_x.max(), params['res'])
yi = np.linspace(pos_y.min(), pos_y.max(), params['res'])
Xi, Yi = np.meshgrid(xi, yi)
for ii, im in enumerate(params['images']):
Zi = _griddata(pos_x, pos_y, data[:, ii], Xi, Yi)
Zi[~image_mask] = np.nan
im.set_data(Zi)
for cont in params['contours']:
cont.set_array(np.c_[Xi, Yi, Zi])
params['fig'].canvas.draw()
def plot_projs_topomap(projs, layout=None, cmap=None, sensors=True,
colorbar=False, res=64, size=1, show=True,
outlines='head', contours=6, image_interp='bilinear',
axes=None):
"""Plot topographic maps of SSP projections.
Parameters
----------
projs : list of Projection
The projections
layout : None | Layout | list of Layout
Layout instance specifying sensor positions (does not need to be
specified for Neuromag data). Or a list of Layout if projections
are from different sensor types.
cmap : matplotlib colormap | (colormap, bool) | 'interactive' | None
Colormap to use. If tuple, the first value indicates the colormap to
use and the second value is a boolean defining interactivity. In
interactive mode (only works if ``colorbar=True``) the colors are
adjustable by clicking and dragging the colorbar with left and right
mouse button. Left mouse button moves the scale up and down and right
mouse button adjusts the range. Hitting space bar resets the range. Up
and down arrows can be used to change the colormap. If None (default),
'Reds' is used for all positive data, otherwise defaults to 'RdBu_r'.
If 'interactive', translates to (None, True).
sensors : bool | str
Add markers for sensor locations to the plot. Accepts matplotlib plot
format string (e.g., 'r+' for red plusses). If True, a circle will be
used (via .add_artist). Defaults to True.
colorbar : bool
Plot a colorbar.
res : int
The resolution of the topomap image (n pixels along each side).
size : scalar
Side length of the topomaps in inches (only applies when plotting
multiple topomaps at a time).
show : bool
Show figure if True.
outlines : 'head' | 'skirt' | dict | None
The outlines to be drawn. If 'head', the default head scheme will be
drawn. If 'skirt' the head scheme will be drawn, but sensors are
allowed to be plotted outside of the head circle. If dict, each key
refers to a tuple of x and y positions, the values in 'mask_pos' will
serve as image mask, and the 'autoshrink' (bool) field will trigger
automated shrinking of the positions due to points outside the outline.
Alternatively, a matplotlib patch object can be passed for advanced
masking options, either directly or as a function that returns patches
(required for multi-axis plots). If None, nothing will be drawn.
Defaults to 'head'.
contours : int | False | None
The number of contour lines to draw. If 0, no contours will be drawn.
image_interp : str
The image interpolation to be used. All matplotlib options are
accepted.
axes : instance of Axes | list | None
The axes to plot to. If list, the list must be a list of Axes of
the same length as the number of projectors. If instance of Axes,
there must be only one projector. Defaults to None.
Returns
-------
fig : instance of matplotlib figure
Figure distributing one image per channel across sensor topography.
Notes
-----
.. versionadded:: 0.9.0
"""
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
if layout is None:
from ..channels import read_layout
layout = read_layout('Vectorview-all')
if not isinstance(layout, list):
layout = [layout]
n_projs = len(projs)
nrows = math.floor(math.sqrt(n_projs))
ncols = math.ceil(n_projs / nrows)
cmap = _setup_cmap(cmap)
if axes is None:
plt.figure()
axes = list()
for idx in range(len(projs)):
ax = plt.subplot(nrows, ncols, idx + 1)
axes.append(ax)
elif isinstance(axes, plt.Axes):
axes = [axes]
if len(axes) != len(projs):
raise RuntimeError('There must be an axes for each picked projector.')
for proj_idx, proj in enumerate(projs):
axes[proj_idx].set_title(proj['desc'][:10] + '...')
ch_names = _clean_names(proj['data']['col_names'],
remove_whitespace=True)
data = proj['data']['data'].ravel()
idx = []
for l in layout:
is_vv = l.kind.startswith('Vectorview')
if is_vv:
from ..channels.layout import _pair_grad_sensors_from_ch_names
grad_pairs = _pair_grad_sensors_from_ch_names(ch_names)
if grad_pairs:
ch_names = [ch_names[i] for i in grad_pairs]
l_names = _clean_names(l.names, remove_whitespace=True)
idx = [l_names.index(c) for c in ch_names if c in l_names]
if len(idx) == 0:
continue
pos = l.pos[idx]
if is_vv and grad_pairs:
from ..channels.layout import _merge_grad_data
shape = (len(idx) // 2, 2, -1)
pos = pos.reshape(shape).mean(axis=1)
data = _merge_grad_data(data[grad_pairs]).ravel()
break
if len(idx):
im = plot_topomap(data, pos[:, :2], vmax=None, cmap=cmap[0],
sensors=sensors, res=res, axes=axes[proj_idx],
outlines=outlines, contours=contours,
image_interp=image_interp, show=False)[0]
if colorbar:
divider = make_axes_locatable(axes[proj_idx])
cax = divider.append_axes("right", size="5%", pad=0.05)
cbar = plt.colorbar(im, cax=cax, cmap=cmap)
if cmap[1]:
axes[proj_idx].CB = DraggableColorbar(cbar, im)
else:
raise RuntimeError('Cannot find a proper layout for projection %s'
% proj['desc'])
tight_layout(fig=axes[0].get_figure())
plt_show(show)
return axes[0].get_figure()
def _check_outlines(pos, outlines, head_pos=None):
"""Check or create outlines for topoplot."""
pos = np.array(pos, float)[:, :2] # ensure we have a copy
head_pos = dict() if head_pos is None else head_pos
if not isinstance(head_pos, dict):
raise TypeError('head_pos must be dict or None')
head_pos = copy.deepcopy(head_pos)
for key in head_pos.keys():
if key not in ('center', 'scale'):
raise KeyError('head_pos must only contain "center" and '
'"scale"')
head_pos[key] = np.array(head_pos[key], float)
if head_pos[key].shape != (2,):
raise ValueError('head_pos["%s"] must have shape (2,), not '
'%s' % (key, head_pos[key].shape))
if isinstance(outlines, np.ndarray) or outlines in ('head', 'skirt', None):
radius = 0.5
l = np.linspace(0, 2 * np.pi, 101)
head_x = np.cos(l) * radius
head_y = np.sin(l) * radius
nose_x = np.array([0.18, 0, -0.18]) * radius
nose_y = np.array([radius - .004, radius * 1.15, radius - .004])
ear_x = np.array([.497, .510, .518, .5299, .5419, .54, .547,
.532, .510, .489])
ear_y = np.array([.0555, .0775, .0783, .0746, .0555, -.0055, -.0932,
-.1313, -.1384, -.1199])
# shift and scale the electrode positions
if 'center' not in head_pos:
head_pos['center'] = 0.5 * (pos.max(axis=0) + pos.min(axis=0))
pos -= head_pos['center']
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, ear_y),
ear_right=(-ear_x, ear_y))
else:
outlines_dict = dict()
if isinstance(outlines, string_types) and outlines == 'skirt':
if 'scale' not in head_pos:
# By default, fit electrodes inside the head circle
head_pos['scale'] = 1.0 / (pos.max(axis=0) - pos.min(axis=0))
pos *= head_pos['scale']
# Make the figure encompass slightly more than all points
mask_scale = 1.25 * (pos.max(axis=0) - pos.min(axis=0))
outlines_dict['autoshrink'] = False
outlines_dict['mask_pos'] = (mask_scale[0] * head_x,
mask_scale[1] * head_y)
outlines_dict['clip_radius'] = (mask_scale / 2.)
else:
if 'scale' not in head_pos:
# The default is to make the points occupy a slightly smaller
# proportion (0.85) of the total width and height
# this number was empirically determined (seems to work well)
head_pos['scale'] = 0.85 / (pos.max(axis=0) - pos.min(axis=0))
pos *= head_pos['scale']
outlines_dict['mask_pos'] = head_x, head_y
if isinstance(outlines, np.ndarray):
outlines_dict['autoshrink'] = False
outlines_dict['clip_radius'] = outlines
x_scale = np.max(outlines_dict['head'][0]) / outlines[0]
y_scale = np.max(outlines_dict['head'][1]) / outlines[1]
for key in ['head', 'nose', 'ear_left', 'ear_right']:
value = outlines_dict[key]
value = (value[0] / x_scale, value[1] / y_scale)
outlines_dict[key] = value
else:
outlines_dict['autoshrink'] = True
outlines_dict['clip_radius'] = (0.5, 0.5)
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 pos, outlines
def _draw_outlines(ax, outlines):
"""Draw the outlines for a topomap."""
outlines_ = dict([(k, v) for k, v in outlines.items() if k not in
['patch', 'autoshrink']])
for key, (x_coord, y_coord) in outlines_.items():
if 'mask' in key:
continue
ax.plot(x_coord, y_coord, color='k', linewidth=1, clip_on=False)
return outlines_
def _griddata(x, y, v, xi, yi):
"""Make griddata."""
xy = x.ravel() + y.ravel() * -1j
d = xy[None, :] * np.ones((len(xy), 1))
d = np.abs(d - d.T)
n = d.shape[0]
d.flat[::n + 1] = 1.
g = (d * d) * (np.log(d) - 1.)
g.flat[::n + 1] = 0.
weights = linalg.solve(g, v.ravel())
m, n = xi.shape
zi = np.zeros_like(xi)
xy = xy.T
g = np.empty(xy.shape)
for i in range(m):
for j in range(n):
d = np.abs(xi[i, j] + -1j * yi[i, j] - xy)
mask = np.where(d == 0)[0]
if len(mask):
d[mask] = 1.
np.log(d, out=g)
g -= 1.
g *= d * d
if len(mask):
g[mask] = 0.
zi[i, j] = g.dot(weights)
return zi
def _plot_sensors(pos_x, pos_y, sensors, ax):
"""Plot sensors."""
from matplotlib.patches import Circle
if sensors is True:
for x, y in zip(pos_x, pos_y):
ax.add_artist(Circle(xy=(x, y), radius=0.003, color='k'))
else:
ax.plot(pos_x, pos_y, sensors)
def plot_topomap(data, pos, vmin=None, vmax=None, cmap=None, sensors=True,
res=64, axes=None, names=None, show_names=False, mask=None,
mask_params=None, outlines='head', image_mask=None,
contours=6, image_interp='bilinear', show=True,
head_pos=None, onselect=None):
"""Plot a topographic map as image.
Parameters
----------
data : array, shape (n_chan,)
The data values to plot.
pos : array, shape (n_chan, 2) | instance of Info
Location information for the data points(/channels).
If an array, for each data point, the x and y coordinates.
If an Info object, it must contain only one data type and
exactly `len(data)` data channels, and the x/y coordinates will
be inferred from this Info object.
vmin : float | callable | None
The value specifying the lower bound of the color range.
If None, and vmax is None, -vmax is used. Else np.min(data).
If callable, the output equals vmin(data). Defaults to None.
vmax : float | callable | None
The value specifying the upper bound of the color range.
If None, the maximum absolute value is used. If callable, the output
equals vmax(data). Defaults to None.
cmap : matplotlib colormap | None
Colormap to use. If None, 'Reds' is used for all positive data,
otherwise defaults to 'RdBu_r'.
sensors : bool | str
Add markers for sensor locations to the plot. Accepts matplotlib plot
format string (e.g., 'r+' for red plusses). If True, a circle will be
used (via .add_artist). Defaults to True.
res : int
The resolution of the topomap image (n pixels along each side).
axes : instance of Axes | None
The axes to plot to. If None, the current axes will be used.
names : list | None
List of channel names. If None, channel names are not plotted.
show_names : bool | callable
If True, show channel names on top of the map. If a callable is
passed, channel names will be formatted using the callable; e.g., to
delete the prefix 'MEG ' from all channel names, pass the function
lambda x: x.replace('MEG ', ''). If `mask` is not None, only
significant sensors will be shown.
If `True`, a list of names must be provided (see `names` keyword).
mask : ndarray of bool, shape (n_channels, n_times) | None
The channels to be marked as significant at a given time point.
Indices set to `True` will be considered. Defaults to None.
mask_params : dict | None
Additional plotting parameters for plotting significant sensors.
Default (None) equals::
dict(marker='o', markerfacecolor='w', markeredgecolor='k',
linewidth=0, markersize=4)
outlines : 'head' | 'skirt' | dict | None
The outlines to be drawn. If 'head', the default head scheme will be
drawn. If 'skirt' the head scheme will be drawn, but sensors are
allowed to be plotted outside of the head circle. If dict, each key
refers to a tuple of x and y positions, the values in 'mask_pos' will
serve as image mask, and the 'autoshrink' (bool) field will trigger
automated shrinking of the positions due to points outside the outline.
Alternatively, a matplotlib patch object can be passed for advanced
masking options, either directly or as a function that returns patches
(required for multi-axes plots). If None, nothing will be drawn.
Defaults to 'head'.
image_mask : ndarray of bool, shape (res, res) | None
The image mask to cover the interpolated surface. If None, it will be
computed from the outline.
contours : int | False | array of float | None
The number of contour lines to draw. If 0, no contours will be drawn.
If an array, the values represent the levels for the contours. The
values are in uV for EEG, fT for magnetometers and fT/m for
gradiometers.
image_interp : str
The image interpolation to be used. All matplotlib options are
accepted.
show : bool
Show figure if True.
head_pos : dict | None
If None (default), the sensors are positioned such that they span
the head circle. If dict, can have entries 'center' (tuple) and
'scale' (tuple) for what the center and scale of the head should be
relative to the electrode locations.
onselect : callable | None
Handle for a function that is called when the user selects a set of
channels by rectangle selection (matplotlib ``RectangleSelector``). If
None interactive selection is disabled. Defaults to None.
Returns
-------
im : matplotlib.image.AxesImage
The interpolated data.
cn : matplotlib.contour.ContourSet
The fieldlines.
"""
import matplotlib.pyplot as plt
from matplotlib.widgets import RectangleSelector
data = np.asarray(data)
logger.debug('Plotting topomap for data shape %s' % (data.shape,))
if isinstance(pos, Info): # infer pos from Info object
picks = _pick_data_channels(pos) # pick only data channels
pos = pick_info(pos, picks)
# check if there is only 1 channel type, and n_chans matches the data
ch_type = set(channel_type(pos, idx)
for idx, _ in enumerate(pos["chs"]))
info_help = ("Pick Info with e.g. mne.pick_info and "
"mne.channels.channel_indices_by_type.")
if len(ch_type) > 1:
raise ValueError("Multiple channel types in Info structure. " +
info_help)
elif len(pos["chs"]) != data.shape[0]:
raise ValueError("Number of channels in the Info object and "
"the data array does not match. " + info_help)
else:
ch_type = ch_type.pop()
if any(type_ in ch_type for type_ in ('planar', 'grad')):
# deal with grad pairs
from ..channels.layout import (_merge_grad_data, find_layout,
_pair_grad_sensors)
picks, pos = _pair_grad_sensors(pos, find_layout(pos))
data = _merge_grad_data(data[picks]).reshape(-1)
else:
picks = list(range(data.shape[0]))
pos = _find_topomap_coords(pos, picks=picks)
if data.ndim > 1:
raise ValueError("Data needs to be array of shape (n_sensors,); got "
"shape %s." % str(data.shape))
# Give a helpful error message for common mistakes regarding the position
# matrix.
pos_help = ("Electrode positions should be specified as a 2D array with "
"shape (n_channels, 2). Each row in this matrix contains the "
"(x, y) position of an electrode.")
if pos.ndim != 2:
error = ("{ndim}D array supplied as electrode positions, where a 2D "
"array was expected").format(ndim=pos.ndim)
raise ValueError(error + " " + pos_help)
elif pos.shape[1] == 3:
error = ("The supplied electrode positions matrix contains 3 columns. "
"Are you trying to specify XYZ coordinates? Perhaps the "
"mne.channels.create_eeg_layout function is useful for you.")
raise ValueError(error + " " + pos_help)
# No error is raised in case of pos.shape[1] == 4. In this case, it is
# assumed the position matrix contains both (x, y) and (width, height)
# values, such as Layout.pos.
elif pos.shape[1] == 1 or pos.shape[1] > 4:
raise ValueError(pos_help)
if len(data) != len(pos):
raise ValueError("Data and pos need to be of same length. Got data of "
"length %s, pos of length %s" % (len(data), len(pos)))
norm = min(data) >= 0
vmin, vmax = _setup_vmin_vmax(data, vmin, vmax, norm)
if cmap is None:
cmap = 'Reds' if norm else 'RdBu_r'
pos, outlines = _check_outlines(pos, outlines, head_pos)
ax = axes if axes else plt.gca()
pos_x, pos_y = _prepare_topomap(pos, ax)
if outlines is None:
xmin, xmax = pos_x.min(), pos_x.max()
ymin, ymax = pos_y.min(), pos_y.max()
else:
xlim = np.inf, -np.inf,
ylim = np.inf, -np.inf,
mask_ = np.c_[outlines['mask_pos']]
xmin, xmax = (np.min(np.r_[xlim[0], mask_[:, 0]]),
np.max(np.r_[xlim[1], mask_[:, 0]]))
ymin, ymax = (np.min(np.r_[ylim[0], mask_[:, 1]]),
np.max(np.r_[ylim[1], mask_[:, 1]]))
# interpolate data
xi = np.linspace(xmin, xmax, res)
yi = np.linspace(ymin, ymax, res)
Xi, Yi = np.meshgrid(xi, yi)
Zi = _griddata(pos_x, pos_y, data, Xi, Yi)
if outlines is None:
_is_default_outlines = False
elif isinstance(outlines, dict):
_is_default_outlines = any(k.startswith('head') for k in outlines)
if _is_default_outlines and image_mask is None:
# prepare masking
image_mask, pos = _make_image_mask(outlines, pos, res)
mask_params = _handle_default('mask_params', mask_params)
# plot outline
linewidth = mask_params['markeredgewidth']
patch = None
if 'patch' in outlines:
patch = outlines['patch']
patch_ = patch() if callable(patch) else patch
patch_.set_clip_on(False)
ax.add_patch(patch_)
ax.set_transform(ax.transAxes)
ax.set_clip_path(patch_)
# plot map and countour
im = ax.imshow(Zi, cmap=cmap, vmin=vmin, vmax=vmax, origin='lower',
aspect='equal', extent=(xmin, xmax, ymin, ymax),
interpolation=image_interp)
# This tackles an incomprehensible matplotlib bug if no contours are
# drawn. To avoid rescalings, we will always draw contours.
# But if no contours are desired we only draw one and make it invisible .
no_contours = False
if isinstance(contours, (np.ndarray, list)):
pass # contours precomputed
elif contours in (False, None):
contours, no_contours = 1, True
cont = ax.contour(Xi, Yi, Zi, contours, colors='k',
linewidths=linewidth)
if no_contours is True:
for col in cont.collections:
col.set_visible(False)
if _is_default_outlines:
from matplotlib import patches
patch_ = patches.Ellipse((0, 0),
2 * outlines['clip_radius'][0],
2 * outlines['clip_radius'][1],
clip_on=True,
transform=ax.transData)
if _is_default_outlines or patch is not None:
im.set_clip_path(patch_)
if cont is not None:
for col in cont.collections:
col.set_clip_path(patch_)
if sensors is not False and mask is None:
_plot_sensors(pos_x, pos_y, sensors=sensors, ax=ax)
elif sensors and mask is not None:
idx = np.where(mask)[0]
ax.plot(pos_x[idx], pos_y[idx], **mask_params)
idx = np.where(~mask)[0]
_plot_sensors(pos_x[idx], pos_y[idx], sensors=sensors, ax=ax)
elif not sensors and mask is not None:
idx = np.where(mask)[0]
ax.plot(pos_x[idx], pos_y[idx], **mask_params)
if isinstance(outlines, dict):
_draw_outlines(ax, outlines)
if show_names:
if names is None:
raise ValueError("To show names, a list of names must be provided"
" (see `names` keyword).")
if show_names is True:
def _show_names(x):
return x
else:
_show_names = show_names
show_idx = np.arange(len(names)) if mask is None else np.where(mask)[0]
for ii, (p, ch_id) in enumerate(zip(pos, names)):
if ii not in show_idx:
continue
ch_id = _show_names(ch_id)
ax.text(p[0], p[1], ch_id, horizontalalignment='center',
verticalalignment='center', size='x-small')
plt.subplots_adjust(top=.95)
if onselect is not None:
ax.RS = RectangleSelector(ax, onselect=onselect)
plt_show(show)
return im, cont
def _make_image_mask(outlines, pos, res):
"""Make an image mask."""
mask_ = np.c_[outlines['mask_pos']]
xmin, xmax = (np.min(np.r_[np.inf, mask_[:, 0]]),
np.max(np.r_[-np.inf, mask_[:, 0]]))
ymin, ymax = (np.min(np.r_[np.inf, mask_[:, 1]]),
np.max(np.r_[-np.inf, mask_[:, 1]]))
if outlines.get('autoshrink', False) is not False:
inside = _inside_contour(pos, mask_)
outside = np.invert(inside)
outlier_points = pos[outside]
while np.any(outlier_points): # auto shrink
pos *= 0.99
inside = _inside_contour(pos, mask_)
outside = np.invert(inside)
outlier_points = pos[outside]
image_mask = np.zeros((res, res), dtype=bool)
xi_mask = np.linspace(xmin, xmax, res)
yi_mask = np.linspace(ymin, ymax, res)
Xi_mask, Yi_mask = np.meshgrid(xi_mask, yi_mask)
pos_ = np.c_[Xi_mask.flatten(), Yi_mask.flatten()]
inds = _inside_contour(pos_, mask_)
image_mask[inds.reshape(image_mask.shape)] = True
return image_mask, pos
def _inside_contour(pos, contour):
"""Check if points are inside a contour."""
npos = len(pos)
x, y = pos[:, :2].T
check_mask = np.ones((npos), dtype=bool)
check_mask[((x < np.min(x)) | (y < np.min(y)) |
(x > np.max(x)) | (y > np.max(y)))] = False
critval = 0.1
sel = np.where(check_mask)[0]
for this_sel in sel:
contourx = contour[:, 0] - pos[this_sel, 0]
contoury = contour[:, 1] - pos[this_sel, 1]
angle = np.arctan2(contoury, contourx)
angle = np.unwrap(angle)
total = np.sum(np.diff(angle))
check_mask[this_sel] = np.abs(total) > critval
return check_mask
def _plot_ica_topomap(ica, idx=0, ch_type=None, res=64, layout=None,
vmin=None, vmax=None, cmap='RdBu_r', colorbar=False,
title=None, show=True, outlines='head', contours=6,
image_interp='bilinear', head_pos=None, axes=None):
"""Plot single ica map to axes."""
import matplotlib as mpl
from ..channels import _get_ch_type
if ica.info is None:
raise RuntimeError('The ICA\'s measurement info is missing. Please '
'fit the ICA or add the corresponding info object.')
if not isinstance(axes, mpl.axes.Axes):
raise ValueError('axis has to be an instance of matplotlib Axes, '
'got %s instead.' % type(axes))
ch_type = _get_ch_type(ica, ch_type)
data = ica.get_components()[:, idx]
data_picks, pos, merge_grads, names, _ = _prepare_topo_plot(
ica, ch_type, layout)
pos, outlines = _check_outlines(pos, outlines, head_pos)
if outlines not in (None, 'head'):
image_mask, pos = _make_image_mask(outlines, pos, res)
else:
image_mask = None
data = data[data_picks]
if merge_grads:
from ..channels.layout import _merge_grad_data
data = _merge_grad_data(data)
axes.set_title('IC #%03d' % idx, fontsize=12)
vmin_, vmax_ = _setup_vmin_vmax(data, vmin, vmax)
im = plot_topomap(data.ravel(), pos, vmin=vmin_, vmax=vmax_,
res=res, axes=axes, cmap=cmap, outlines=outlines,
image_mask=image_mask, contours=contours,
image_interp=image_interp, show=show)[0]
if colorbar:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid import make_axes_locatable
divider = make_axes_locatable(axes)
cax = divider.append_axes("right", size="5%", pad=0.05)
cbar = plt.colorbar(im, cax=cax, format='%3.2f', cmap=cmap)
cbar.ax.tick_params(labelsize=12)
cbar.set_ticks((vmin_, vmax_))
cbar.ax.set_title('AU', fontsize=10)
_hide_frame(axes)
def plot_ica_components(ica, picks=None, ch_type=None, res=64,
layout=None, vmin=None, vmax=None, cmap='RdBu_r',
sensors=True, colorbar=False, title=None,
show=True, outlines='head', contours=6,
image_interp='bilinear', head_pos=None,
inst=None):
"""Project unmixing matrix on interpolated sensor topogrpahy.
Parameters
----------
ica : instance of mne.preprocessing.ICA
The ICA solution.
picks : int | array-like | None
The indices of the sources to be plotted.
If None all are plotted in batches of 20.
ch_type : 'mag' | 'grad' | 'planar1' | 'planar2' | 'eeg' | None
The channel type to plot. For 'grad', the gradiometers are
collected in pairs and the RMS for each pair is plotted.
If None, then channels are chosen in the order given above.
res : int
The resolution of the topomap image (n pixels along each side).
layout : None | Layout
Layout instance specifying sensor positions (does not need to
be specified for Neuromag data). If possible, the correct layout is
inferred from the data.
vmin : float | callable | None
The value specifying the lower bound of the color range.
If None, and vmax is None, -vmax is used. Else np.min(data).
If callable, the output equals vmin(data). Defaults to None.
vmax : float | callable | None
The value specifying the upper bound of the color range.
If None, the maximum absolute value is used. If callable, the output
equals vmax(data). Defaults to None.
cmap : matplotlib colormap | (colormap, bool) | 'interactive' | None
Colormap to use. If tuple, the first value indicates the colormap to
use and the second value is a boolean defining interactivity. In
interactive mode the colors are adjustable by clicking and dragging the
colorbar with left and right mouse button. Left mouse button moves the
scale up and down and right mouse button adjusts the range. Hitting
space bar resets the range. Up and down arrows can be used to change
the colormap. If None, 'Reds' is used for all positive data,
otherwise defaults to 'RdBu_r'. If 'interactive', translates to
(None, True). Defaults to 'RdBu_r'.
.. warning:: Interactive mode works smoothly only for a small amount
of topomaps.
sensors : bool | str
Add markers for sensor locations to the plot. Accepts matplotlib
plot format string (e.g., 'r+' for red plusses). If True, a circle
will be used (via .add_artist). Defaults to True.
colorbar : bool
Plot a colorbar.
title : str | None
Title to use.
show : bool
Show figure if True.
outlines : 'head' | 'skirt' | dict | None
The outlines to be drawn. If 'head', the default head scheme will be
drawn. If 'skirt' the head scheme will be drawn, but sensors are
allowed to be plotted outside of the head circle. If dict, each key
refers to a tuple of x and y positions, the values in 'mask_pos' will
serve as image mask, and the 'autoshrink' (bool) field will trigger
automated shrinking of the positions due to points outside the outline.
Alternatively, a matplotlib patch object can be passed for advanced
masking options, either directly or as a function that returns patches
(required for multi-axis plots). If None, nothing will be drawn.
Defaults to 'head'.
contours : int | False | None
The number of contour lines to draw. If 0, no contours will be drawn.
image_interp : str
The image interpolation to be used. All matplotlib options are
accepted.
head_pos : dict | None
If None (default), the sensors are positioned such that they span
the head circle. If dict, can have entries 'center' (tuple) and
'scale' (tuple) for what the center and scale of the head should be
relative to the electrode locations.
inst : Raw | Epochs | None
To be able to see component properties after clicking on component
topomap you need to pass relevant data - instances of Raw or Epochs
(for example the data that ICA was trained on). This takes effect
only when running matplotlib in interactive mode.
Returns
-------
fig : instance of matplotlib.pyplot.Figure or list
The figure object(s).
"""
from ..io import BaseRaw
from ..epochs import BaseEpochs
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid import make_axes_locatable
from ..channels import _get_ch_type
if picks is None: # plot components by sets of 20
ch_type = _get_ch_type(ica, ch_type)
n_components = ica.mixing_matrix_.shape[1]
p = 20
figs = []
for k in range(0, n_components, p):
picks = range(k, min(k + p, n_components))
fig = plot_ica_components(ica, picks=picks, ch_type=ch_type,
res=res, layout=layout, vmax=vmax,
cmap=cmap, sensors=sensors,
colorbar=colorbar, title=title,
show=show, outlines=outlines,
contours=contours,
image_interp=image_interp,
head_pos=head_pos, inst=inst)
figs.append(fig)
return figs
elif np.isscalar(picks):
picks = [picks]
ch_type = _get_ch_type(ica, ch_type)
cmap = _setup_cmap(cmap, n_axes=len(picks))
data = np.dot(ica.mixing_matrix_[:, picks].T,
ica.pca_components_[:ica.n_components_])
if ica.info is None:
raise RuntimeError('The ICA\'s measurement info is missing. Please '
'fit the ICA or add the corresponding info object.')
data_picks, pos, merge_grads, names, _ = _prepare_topo_plot(ica, ch_type,
layout)
pos, outlines = _check_outlines(pos, outlines, head_pos)
if outlines not in (None, 'head'):
image_mask, pos = _make_image_mask(outlines, pos, res)
else:
image_mask = None
data = np.atleast_2d(data)
data = data[:, data_picks]
# prepare data for iteration
fig, axes = _prepare_trellis(len(data), max_col=5)
if title is None:
title = 'ICA components'
fig.suptitle(title)
if merge_grads:
from ..channels.layout import _merge_grad_data
for ii, data_, ax in zip(picks, data, axes):
ax.set_title('IC #%03d' % ii, fontsize=12)
data_ = _merge_grad_data(data_) if merge_grads else data_
vmin_, vmax_ = _setup_vmin_vmax(data_, vmin, vmax)
im = plot_topomap(data_.flatten(), pos, vmin=vmin_, vmax=vmax_,
res=res, axes=ax, cmap=cmap[0], outlines=outlines,
image_mask=image_mask, contours=contours,
image_interp=image_interp, show=False)[0]
im.axes.set_label('IC #%03d' % ii)
if colorbar:
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
cbar = plt.colorbar(im, cax=cax, format='%3.2f', cmap=cmap)
cbar.ax.tick_params(labelsize=12)
cbar.set_ticks((vmin_, vmax_))
cbar.ax.set_title('AU', fontsize=10)
if cmap[1]:
ax.CB = DraggableColorbar(cbar, im)
_hide_frame(ax)
tight_layout(fig=fig)
fig.subplots_adjust(top=0.95)
fig.canvas.draw()
if isinstance(inst, (BaseRaw, BaseEpochs)):
def onclick(event, ica=ica, inst=inst):
# check which component to plot
label = event.inaxes.get_label()
if 'IC #' in label:
ic = int(label[4:])
ica.plot_properties(inst, picks=ic, show=True)
fig.canvas.mpl_connect('button_press_event', onclick)
plt_show(show)
return fig
def plot_tfr_topomap(tfr, tmin=None, tmax=None, fmin=None, fmax=None,
ch_type=None, baseline=None, mode='mean', layout=None,
vmin=None, vmax=None, cmap=None, sensors=True,
colorbar=True, unit=None, res=64, size=2,
cbar_fmt='%1.1e', show_names=False, title=None,
axes=None, show=True, outlines='head', head_pos=None):
"""Plot topographic maps of specific time-frequency intervals of TFR data.
Parameters
----------
tfr : AvereageTFR
The AvereageTFR object.
tmin : None | float
The first time instant to display. If None the first time point
available is used.
tmax : None | float
The last time instant to display. If None the last time point
available is used.
fmin : None | float
The first frequency to display. If None the first frequency
available is used.
fmax : None | float
The last frequency to display. If None the last frequency
available is used.
ch_type : 'mag' | 'grad' | 'planar1' | 'planar2' | 'eeg' | None
The channel type to plot. For 'grad', the gradiometers are
collected in pairs and the RMS for each pair is plotted.
If None, then channels are chosen in the order given above.
baseline : tuple or list of length 2
The time interval to apply rescaling / baseline correction.
If None do not apply it. If baseline is (a, b)
the interval is between "a (s)" and "b (s)".
If a is None the beginning of the data is used
and if b is None then b is set to the end of the interval.
If baseline is equal to (None, None) all the time
interval is used.
mode : 'logratio' | 'ratio' | 'zscore' | 'mean' | 'percent'
Do baseline correction with ratio (power is divided by mean
power during baseline) or z-score (power is divided by standard
deviation of power during baseline after subtracting the mean,
power = [power - mean(power_baseline)] / std(power_baseline))