/
_3d.py
2678 lines (2404 loc) · 110 KB
/
_3d.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""Functions to make 3D plots with M/EEG data."""
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>
# Mainak Jas <mainak@neuro.hut.fi>
# Mark Wronkiewicz <wronk.mark@gmail.com>
#
# License: Simplified BSD
import base64
from distutils.version import LooseVersion
from itertools import cycle
import os.path as op
import warnings
from functools import partial
import numpy as np
from scipy import linalg
from ..defaults import DEFAULTS
from ..externals.six import BytesIO, string_types, advance_iterator
from ..io import _loc_to_coil_trans, Info
from ..io.pick import pick_types
from ..io.constants import FIFF
from ..io.meas_info import read_fiducials
from ..source_space import SourceSpaces, _create_surf_spacing, _check_spacing
from ..surface import (_get_head_surface, get_meg_helmet_surf, read_surface,
transform_surface_to, _project_onto_surface,
complete_surface_info, mesh_edges,
_complete_sphere_surf)
from ..transforms import (read_trans, _find_trans, apply_trans,
combine_transforms, _get_trans, _ensure_trans,
invert_transform, Transform)
from ..utils import (get_subjects_dir, logger, _check_subject, verbose, warn,
_import_mlab, SilenceStdout, has_nibabel, check_version,
_ensure_int, deprecated)
from .utils import (mne_analyze_colormap, _prepare_trellis, COLORS, plt_show,
tight_layout, figure_nobar)
from ..bem import ConductorModel, _bem_find_surface, _surf_dict, _surf_name
FIDUCIAL_ORDER = (FIFF.FIFFV_POINT_LPA, FIFF.FIFFV_POINT_NASION,
FIFF.FIFFV_POINT_RPA)
def _fiducial_coords(points, coord_frame=None):
"""Generate 3x3 array of fiducial coordinates."""
if coord_frame is not None:
points = [p for p in points if p['coord_frame'] == coord_frame]
points_ = dict((p['ident'], p) for p in points if
p['kind'] == FIFF.FIFFV_POINT_CARDINAL)
if points_:
return np.array([points_[i]['r'] for i in FIDUCIAL_ORDER])
else:
# XXX eventually this should probably live in montage.py
if coord_frame is None or coord_frame == FIFF.FIFFV_COORD_HEAD:
# Try converting CTF HPI coils to fiducials
out = np.empty((3, 3))
out.fill(np.nan)
for p in points:
if p['kind'] == FIFF.FIFFV_POINT_HPI:
if np.isclose(p['r'][1:], 0, atol=1e-6).all():
out[0 if p['r'][0] < 0 else 2] = p['r']
elif np.isclose(p['r'][::2], 0, atol=1e-6).all():
out[1] = p['r']
if np.isfinite(out).all():
return out
return np.array([])
def plot_head_positions(pos, mode='traces', cmap='viridis', direction='z',
show=True):
"""Plot head positions.
Parameters
----------
pos : ndarray, shape (n_pos, 10)
The head position data.
mode : str
Can be 'traces' (default) to show position and quaternion traces,
or 'field' to show the position as a vector field over time.
The 'field' mode requires matplotlib 1.4+.
cmap : matplotlib Colormap
Colormap to use for the trace plot, default is "viridis".
direction : str
Can be any combination of "x", "y", or "z" (default: "z") to show
directional axes in "field" mode.
show : bool
Show figure if True. Defaults to True.
Returns
-------
fig : Instance of matplotlib.figure.Figure
The figure.
"""
from ..chpi import head_pos_to_trans_rot_t
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
from mpl_toolkits.mplot3d.art3d import Line3DCollection
from mpl_toolkits.mplot3d import axes3d # noqa: F401, analysis:ignore
if not isinstance(mode, string_types) or mode not in ('traces', 'field'):
raise ValueError('mode must be "traces" or "field", got %s' % (mode,))
trans, rot, t = head_pos_to_trans_rot_t(pos) # also ensures pos is okay
# trans, rot, and t are for dev_head_t, but what we really want
# is head_dev_t (i.e., where the head origin is in device coords)
use_trans = np.einsum('ijk,ik->ij', rot[:, :3, :3].transpose([0, 2, 1]),
-trans) * 1000
use_rot = rot.transpose([0, 2, 1])
use_quats = -pos[:, 1:4] # inverse (like doing rot.T)
if cmap == 'viridis' and not check_version('matplotlib', '1.5'):
warn('viridis is unavailable on matplotlib < 1.4, using "YlGnBu_r"')
cmap = 'YlGnBu_r'
if mode == 'traces':
fig, axes = plt.subplots(3, 2, sharex=True)
labels = ['xyz', ('$q_1$', '$q_2$', '$q_3$')]
for ii, (quat, coord) in enumerate(zip(use_quats.T, use_trans.T)):
axes[ii, 0].plot(t, coord, 'k')
axes[ii, 0].set(ylabel=labels[0][ii], xlim=t[[0, -1]])
axes[ii, 1].plot(t, quat, 'k')
axes[ii, 1].set(ylabel=labels[1][ii], xlim=t[[0, -1]])
for ii, title in enumerate(('Position (mm)', 'Rotation (quat)')):
axes[0, ii].set(title=title)
axes[-1, ii].set(xlabel='Time (s)')
else: # mode == 'field':
if not check_version('matplotlib', '1.4'):
raise RuntimeError('The "field" mode requires matplotlib version '
'1.4+')
fig, ax = plt.subplots(1, subplot_kw=dict(projection='3d'))
# First plot the trajectory as a colormap:
# http://matplotlib.org/examples/pylab_examples/multicolored_line.html
pts = use_trans[:, np.newaxis]
segments = np.concatenate([pts[:-1], pts[1:]], axis=1)
norm = Normalize(t[0], t[-2])
lc = Line3DCollection(segments, cmap=cmap, norm=norm)
lc.set_array(t[:-1])
ax.add_collection(lc)
# now plot the head directions as a quiver
dir_idx = dict(x=0, y=1, z=2)
kwargs = _pivot_kwargs()
for d, length in zip(direction, [1., 0.5, 0.25]):
use_dir = use_rot[:, :, dir_idx[d]]
# draws stems, then heads
array = np.concatenate((t, np.repeat(t, 2)))
ax.quiver(use_trans[:, 0], use_trans[:, 1], use_trans[:, 2],
use_dir[:, 0], use_dir[:, 1], use_dir[:, 2], norm=norm,
cmap=cmap, array=array, length=length, **kwargs)
mins = use_trans.min(0)
maxs = use_trans.max(0)
scale = (maxs - mins).max() / 2.
xlim, ylim, zlim = (maxs + mins)[:, np.newaxis] / 2. + [-scale, scale]
ax.set(xlabel='x', ylabel='y', zlabel='z',
xlim=xlim, ylim=ylim, zlim=zlim, aspect='equal')
ax.view_init(30, 45)
tight_layout(fig=fig)
plt_show(show)
return fig
def _pivot_kwargs():
"""Get kwargs for quiver."""
kwargs = dict()
if check_version('matplotlib', '1.5'):
kwargs['pivot'] = 'tail'
else:
import matplotlib
warn('pivot cannot be set in matplotlib %s (need version 1.5+), '
'locations are approximate' % (matplotlib.__version__,))
return kwargs
def plot_evoked_field(evoked, surf_maps, time=None, time_label='t = %0.0f ms',
n_jobs=1):
"""Plot MEG/EEG fields on head surface and helmet in 3D.
Parameters
----------
evoked : instance of mne.Evoked
The evoked object.
surf_maps : list
The surface mapping information obtained with make_field_map.
time : float | None
The time point at which the field map shall be displayed. If None,
the average peak latency (across sensor types) is used.
time_label : str
How to print info about the time instant visualized.
n_jobs : int
Number of jobs to run in parallel.
Returns
-------
fig : instance of mlab.Figure
The mayavi figure.
"""
types = [t for t in ['eeg', 'grad', 'mag'] if t in evoked]
time_idx = None
if time is None:
time = np.mean([evoked.get_peak(ch_type=t)[1] for t in types])
if not evoked.times[0] <= time <= evoked.times[-1]:
raise ValueError('`time` (%0.3f) must be inside `evoked.times`' % time)
time_idx = np.argmin(np.abs(evoked.times - time))
types = [sm['kind'] for sm in surf_maps]
# Plot them
mlab = _import_mlab()
alphas = [1.0, 0.5]
colors = [(0.6, 0.6, 0.6), (1.0, 1.0, 1.0)]
colormap = mne_analyze_colormap(format='mayavi')
colormap_lines = np.concatenate([np.tile([0., 0., 255., 255.], (127, 1)),
np.tile([0., 0., 0., 255.], (2, 1)),
np.tile([255., 0., 0., 255.], (127, 1))])
fig = mlab.figure(bgcolor=(0.0, 0.0, 0.0), size=(600, 600))
_toggle_mlab_render(fig, False)
for ii, this_map in enumerate(surf_maps):
surf = this_map['surf']
map_data = this_map['data']
map_type = this_map['kind']
map_ch_names = this_map['ch_names']
if map_type == 'eeg':
pick = pick_types(evoked.info, meg=False, eeg=True)
else:
pick = pick_types(evoked.info, meg=True, eeg=False, ref_meg=False)
ch_names = [evoked.ch_names[k] for k in pick]
set_ch_names = set(ch_names)
set_map_ch_names = set(map_ch_names)
if set_ch_names != set_map_ch_names:
message = ['Channels in map and data do not match.']
diff = set_map_ch_names - set_ch_names
if len(diff):
message += ['%s not in data file. ' % list(diff)]
diff = set_ch_names - set_map_ch_names
if len(diff):
message += ['%s not in map file.' % list(diff)]
raise RuntimeError(' '.join(message))
data = np.dot(map_data, evoked.data[pick, time_idx])
# Make a solid surface
vlim = np.max(np.abs(data))
alpha = alphas[ii]
mesh = _create_mesh_surf(surf, fig)
with warnings.catch_warnings(record=True): # traits
surface = mlab.pipeline.surface(mesh, color=colors[ii],
opacity=alpha, figure=fig)
surface.actor.property.backface_culling = True
# Now show our field pattern
mesh = _create_mesh_surf(surf, fig, scalars=data)
with warnings.catch_warnings(record=True): # traits
fsurf = mlab.pipeline.surface(mesh, vmin=-vlim, vmax=vlim,
figure=fig)
fsurf.module_manager.scalar_lut_manager.lut.table = colormap
fsurf.actor.property.backface_culling = True
# And the field lines on top
mesh = _create_mesh_surf(surf, fig, scalars=data)
with warnings.catch_warnings(record=True): # traits
cont = mlab.pipeline.contour_surface(
mesh, contours=21, line_width=1.0, vmin=-vlim, vmax=vlim,
opacity=alpha, figure=fig)
cont.module_manager.scalar_lut_manager.lut.table = colormap_lines
if '%' in time_label:
time_label %= (1e3 * evoked.times[time_idx])
with warnings.catch_warnings(record=True): # traits
mlab.text(0.01, 0.01, time_label, width=0.4, figure=fig)
with SilenceStdout(): # setting roll
mlab.view(10, 60, figure=fig)
_toggle_mlab_render(fig, True)
return fig
def _create_mesh_surf(surf, fig=None, scalars=None):
"""Create Mayavi mesh from MNE surf."""
mlab = _import_mlab()
nn = surf['nn'].copy()
# make absolutely sure these are normalized for Mayavi
norm = np.sum(nn * nn, axis=1)
mask = norm > 0
nn[mask] /= norm[mask][:, np.newaxis]
x, y, z = surf['rr'].T
with warnings.catch_warnings(record=True): # traits
mesh = mlab.pipeline.triangular_mesh_source(
x, y, z, surf['tris'], scalars=scalars, figure=fig)
mesh.data.point_data.normals = nn
mesh.data.cell_data.normals = None
mesh.update()
return mesh
def _plot_mri_contours(mri_fname, surf_fnames, orientation='coronal',
slices=None, show=True, img_output=False):
"""Plot BEM contours on anatomical slices.
Parameters
----------
mri_fname : str
The name of the file containing anatomical data.
surf_fnames : list of str
The filenames for the BEM surfaces in the format
['inner_skull.surf', 'outer_skull.surf', 'outer_skin.surf'].
orientation : str
'coronal' or 'transverse' or 'sagittal'
slices : list of int
Slice indices.
show : bool
Call pyplot.show() at the end.
img_output : None | tuple
If tuple (width and height), images will be produced instead of a
single figure with many axes. This mode is designed to reduce the
(substantial) overhead associated with making tens to hundreds
of matplotlib axes, instead opting to re-use a single Axes instance.
Returns
-------
fig : Instance of matplotlib.figure.Figure | list
The figure. Will instead be a list of png images if
img_output is a tuple.
"""
import matplotlib.pyplot as plt
import nibabel as nib
if orientation not in ['coronal', 'axial', 'sagittal']:
raise ValueError("Orientation must be 'coronal', 'axial' or "
"'sagittal'. Got %s." % orientation)
# Load the T1 data
nim = nib.load(mri_fname)
data = nim.get_data()
try:
affine = nim.affine
except AttributeError: # old nibabel
affine = nim.get_affine()
n_sag, n_axi, n_cor = data.shape
orientation_name2axis = dict(sagittal=0, axial=1, coronal=2)
orientation_axis = orientation_name2axis[orientation]
if slices is None:
n_slices = data.shape[orientation_axis]
slices = np.linspace(0, n_slices, 12, endpoint=False).astype(np.int)
# create of list of surfaces
surfs = list()
trans = linalg.inv(affine)
# XXX : next line is a hack don't ask why
trans[:3, -1] = [n_sag // 2, n_axi // 2, n_cor // 2]
for surf_fname in surf_fnames:
surf = read_surface(surf_fname, return_dict=True)[-1]
# move back surface to MRI coordinate system
surf['rr'] = nib.affines.apply_affine(trans, surf['rr'])
surfs.append(surf)
if img_output is None:
fig, axs = _prepare_trellis(len(slices), 4)
else:
fig, ax = plt.subplots(1, 1, figsize=(7.0, 7.0))
axs = [ax] * len(slices)
fig_size = fig.get_size_inches()
w, h = img_output[0], img_output[1]
w2 = fig_size[0]
fig.set_size_inches([(w2 / float(w)) * w, (w2 / float(w)) * h])
plt.close(fig)
inds = dict(coronal=[0, 1, 2], axial=[2, 0, 1],
sagittal=[2, 1, 0])[orientation]
outs = []
for ax, sl in zip(axs, slices):
# adjust the orientations for good view
if orientation == 'coronal':
dat = data[:, :, sl].transpose()
elif orientation == 'axial':
dat = data[:, sl, :]
elif orientation == 'sagittal':
dat = data[sl, :, :]
# First plot the anatomical data
if img_output is not None:
ax.clear()
ax.imshow(dat, cmap=plt.cm.gray)
ax.axis('off')
# and then plot the contours on top
for surf in surfs:
ax.tricontour(surf['rr'][:, inds[0]], surf['rr'][:, inds[1]],
surf['tris'], surf['rr'][:, inds[2]],
levels=[sl], colors='yellow', linewidths=2.0)
if img_output is not None:
ax.set_xticks([])
ax.set_yticks([])
ax.set_xlim(0, img_output[1])
ax.set_ylim(img_output[0], 0)
output = BytesIO()
fig.savefig(output, bbox_inches='tight',
pad_inches=0, format='png')
outs.append(base64.b64encode(output.getvalue()).decode('ascii'))
if show:
plt.subplots_adjust(left=0., bottom=0., right=1., top=1., wspace=0.,
hspace=0.)
plt_show(show)
return fig if img_output is None else outs
@deprecated('this function will be removed in version 0.16. '
'Use plot_alignment instead')
@verbose
def plot_trans(info, trans='auto', subject=None, subjects_dir=None,
source=('bem', 'head', 'outer_skin'),
coord_frame='head', meg_sensors=('helmet', 'sensors'),
eeg_sensors='original', dig=False, ref_meg=False,
ecog_sensors=True, head=None, brain=None, skull=False,
src=None, mri_fiducials=False, verbose=None):
"""Plot head, sensor, and source space alignment in 3D.
Parameters
----------
info : dict
The measurement info.
trans : str | 'auto' | dict | None
The full path to the head<->MRI transform ``*-trans.fif`` file
produced during coregistration. If trans is None, an identity matrix
is assumed.
subject : str | None
The subject name corresponding to FreeSurfer environment
variable SUBJECT. Can be omitted if ``src`` is provided.
subjects_dir : str
The path to the freesurfer subjects reconstructions.
It corresponds to Freesurfer environment variable SUBJECTS_DIR.
source : str | list
Type to load. Common choices would be `'bem'`, `'head'` or
`'outer_skin'`. If list, the sources are looked up in the given order
and first found surface is used. We first try loading
`'$SUBJECTS_DIR/$SUBJECT/bem/$SUBJECT-$SOURCE.fif'`, and then look for
`'$SUBJECT*$SOURCE.fif'` in the same directory. For `'outer_skin'`,
the subjects bem and bem/flash folders are searched. Defaults to 'bem'.
Note. For single layer bems it is recommended to use 'head'.
coord_frame : str
Coordinate frame to use, 'head', 'meg', or 'mri'.
meg_sensors : bool | str | list
Can be "helmet" (equivalent to False) or "sensors" to show the MEG
helmet or sensors, respectively, or a combination of the two like
``['helmet', 'sensors']`` (equivalent to True, default) or ``[]``.
eeg_sensors : bool | str | list
Can be "original" (default; equivalent to True) or "projected" to
show EEG sensors in their digitized locations or projected onto the
scalp, or a list of these options including ``[]`` (equivalent of
False).
dig : bool | 'fiducials'
If True, plot the digitization points; 'fiducials' to plot fiducial
points only.
ref_meg : bool
If True (default False), include reference MEG sensors.
ecog_sensors : bool
If True (default), show ECoG sensors.
head : bool | None
If True, show head surface. Can also be None, which will show the
head surface for MEG and EEG, but hide it if ECoG sensors are
present.
brain : bool | str | None
If True, show the brain surfaces. Can also be a str for
surface type (e.g., 'pial', same as True), or None (True for ECoG,
False otherwise).
skull : bool | str | list of str | list of dict
Whether to plot skull surface. If string, common choices would be
'inner_skull', or 'outer_skull'. Can also be a list to plot
multiple skull surfaces. If a list of dicts, each dict must
contain the complete surface info (such as you get from
:func:`mne.make_bem_model`). True is an alias of 'outer_skull'.
The subjects bem and bem/flash folders are searched for the 'surf'
files. Defaults to False.
src : instance of SourceSpaces | None
If not None, also plot the source space points.
.. versionadded:: 0.14
mri_fiducials : bool | str
Plot MRI fiducials (default False). If ``True``, look for a file with
the canonical name (``bem/{subject}-fiducials.fif``). If ``str`` it
should provide the full path to the fiducials file.
.. versionadded:: 0.14
verbose : bool, str, int, or None
If not None, override default verbose level (see :func:`mne.verbose`
and :ref:`Logging documentation <tut_logging>` for more).
Returns
-------
fig : instance of mlab.Figure
The mayavi figure.
"""
from ..forward import _create_meg_coils
mlab = _import_mlab()
if meg_sensors is False: # old behavior
meg_sensors = 'helmet'
elif meg_sensors is True:
meg_sensors = ['helmet', 'sensors']
if eeg_sensors is False:
eeg_sensors = []
elif eeg_sensors is True:
eeg_sensors = 'original'
if isinstance(eeg_sensors, string_types):
eeg_sensors = [eeg_sensors]
if isinstance(meg_sensors, string_types):
meg_sensors = [meg_sensors]
for kind, var in zip(('eeg', 'meg'), (eeg_sensors, meg_sensors)):
if not isinstance(var, (list, tuple)) or \
not all(isinstance(x, string_types) for x in var):
raise TypeError('%s_sensors must be list or tuple of str, got %s'
% (type(var),))
if not all(x in ('helmet', 'sensors') for x in meg_sensors):
raise ValueError('meg_sensors must only contain "helmet" and "points",'
' got %s' % (meg_sensors,))
if not all(x in ('original', 'projected') for x in eeg_sensors):
raise ValueError('eeg_sensors must only contain "original" and '
'"projected", got %s' % (eeg_sensors,))
if not isinstance(info, Info):
raise TypeError('info must be an instance of Info, got %s'
% type(info))
valid_coords = ['head', 'meg', 'mri']
if coord_frame not in valid_coords:
raise ValueError('coord_frame must be one of %s' % (valid_coords,))
if src is not None:
if not isinstance(src, SourceSpaces):
raise TypeError('src must be None or SourceSpaces, got %s'
% (type(src),))
src_subject = src[0].get('subject_his_id', None)
subject = src_subject if subject is None else subject
if src_subject is not None and subject != src_subject:
raise ValueError('subject ("%s") did not match the subject name '
' in src ("%s")' % (subject, src_subject))
src_rr = np.concatenate([s['rr'][s['inuse'].astype(bool)]
for s in src])
src_nn = np.concatenate([s['nn'][s['inuse'].astype(bool)]
for s in src])
else:
src_rr = src_nn = np.empty((0, 3))
meg_picks = pick_types(info, meg=True, ref_meg=ref_meg)
eeg_picks = pick_types(info, meg=False, eeg=True, ref_meg=False)
ecog_picks = pick_types(info, meg=False, ecog=True, ref_meg=False)
if head is None:
head = (len(ecog_picks) == 0 and subject is not None)
if head and subject is None:
raise ValueError('If head is True, subject must be provided')
if isinstance(trans, string_types):
if trans == 'auto':
# let's try to do this in MRI coordinates so they're easy to plot
subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)
trans = _find_trans(subject, subjects_dir)
trans = read_trans(trans, return_all=True)
exp = None
for trans in trans: # we got at least 1
try:
trans = _ensure_trans(trans, 'head', 'mri')
except Exception as exp:
pass
else:
break
else:
raise exp
elif trans is None:
trans = Transform('head', 'mri')
elif not isinstance(trans, dict):
raise TypeError('trans must be str, dict, or None')
head_mri_t = _ensure_trans(trans, 'head', 'mri')
dev_head_t = info['dev_head_t']
del trans
# Figure out our transformations
if coord_frame == 'meg':
head_trans = invert_transform(dev_head_t)
meg_trans = Transform('meg', 'meg')
mri_trans = invert_transform(combine_transforms(
dev_head_t, head_mri_t, 'meg', 'mri'))
elif coord_frame == 'mri':
head_trans = head_mri_t
meg_trans = combine_transforms(dev_head_t, head_mri_t, 'meg', 'mri')
mri_trans = Transform('mri', 'mri')
else: # coord_frame == 'head'
head_trans = Transform('head', 'head')
meg_trans = info['dev_head_t']
mri_trans = invert_transform(head_mri_t)
# both the head and helmet will be in MRI coordinates after this
surfs = dict()
if head:
subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)
head_surf = _get_head_surface(subject, source=source,
subjects_dir=subjects_dir,
raise_error=False)
if head_surf is None:
if isinstance(source, string_types):
source = [source]
for this_surf in source:
if not this_surf.endswith('outer_skin'):
continue
surf_fname = op.join(subjects_dir, subject, 'bem', 'flash',
'%s.surf' % this_surf)
if not op.exists(surf_fname):
surf_fname = op.join(subjects_dir, subject, 'bem',
'%s.surf' % this_surf)
if not op.exists(surf_fname):
continue
logger.info('Using %s for head surface.' % this_surf)
rr, tris = read_surface(surf_fname)
head_surf = dict(rr=rr / 1000., tris=tris, ntri=len(tris),
np=len(rr), coord_frame=FIFF.FIFFV_COORD_MRI)
complete_surface_info(head_surf, copy=False, verbose=False)
break
if head_surf is None:
raise IOError('No head surface found for subject %s.' % subject)
surfs['head'] = head_surf
if mri_fiducials:
if mri_fiducials is True:
subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)
if subject is None:
raise ValueError("Subject needs to be specified to "
"automatically find the fiducials file.")
mri_fiducials = op.join(subjects_dir, subject, 'bem',
subject + '-fiducials.fif')
if isinstance(mri_fiducials, string_types):
mri_fiducials, cf = read_fiducials(mri_fiducials)
if cf != FIFF.FIFFV_COORD_MRI:
raise ValueError("Fiducials are not in MRI space")
fid_loc = _fiducial_coords(mri_fiducials, FIFF.FIFFV_COORD_MRI)
fid_loc = apply_trans(mri_trans, fid_loc)
else:
fid_loc = []
if 'helmet' in meg_sensors and len(meg_picks) > 0:
surfs['helmet'] = get_meg_helmet_surf(info, head_mri_t)
if brain is None:
if len(ecog_picks) > 0 and subject is not None:
brain = 'pial'
else:
brain = False
if brain:
subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)
brain = 'pial' if brain is True else brain
for hemi in ['lh', 'rh']:
fname = op.join(subjects_dir, subject, 'surf',
'%s.%s' % (hemi, brain))
rr, tris = read_surface(fname)
rr *= 1e-3
surfs[hemi] = dict(rr=rr, tris=tris, ntri=len(tris), np=len(rr),
coord_frame=FIFF.FIFFV_COORD_MRI)
complete_surface_info(surfs[hemi], copy=False, verbose=False)
if skull is True:
skull = 'outer_skull'
if isinstance(skull, string_types):
skull = [skull]
elif not skull:
skull = []
if len(skull) > 0 and not isinstance(skull[0], dict):
skull = sorted(skull)
skull_alpha = dict()
skull_colors = dict()
hemi_val = 0.5
if src is None or (brain and any(s['type'] == 'surf' for s in src)):
hemi_val = 1.
alphas = (4 - np.arange(len(skull) + 1)) * (0.5 / 4.)
for idx, this_skull in enumerate(skull):
if isinstance(this_skull, dict):
from ..bem import _surf_name
skull_surf = this_skull
this_skull = _surf_name[skull_surf['id']]
else:
skull_fname = op.join(subjects_dir, subject, 'bem', 'flash',
'%s.surf' % this_skull)
if not op.exists(skull_fname):
skull_fname = op.join(subjects_dir, subject, 'bem',
'%s.surf' % this_skull)
if not op.exists(skull_fname):
raise IOError('No skull surface %s found for subject %s.'
% (this_skull, subject))
logger.info('Using %s for head surface.' % skull_fname)
rr, tris = read_surface(skull_fname)
skull_surf = dict(rr=rr / 1000., tris=tris, ntri=len(tris),
np=len(rr), coord_frame=FIFF.FIFFV_COORD_MRI)
complete_surface_info(skull_surf, copy=False, verbose=False)
skull_alpha[this_skull] = alphas[idx + 1]
skull_colors[this_skull] = (0.95 - idx * 0.2, 0.85, 0.95 - idx * 0.2)
surfs[this_skull] = skull_surf
if src is None and brain is False and len(skull) == 0:
head_alpha = 1.0
else:
head_alpha = alphas[0]
for key in surfs.keys():
surfs[key] = transform_surface_to(surfs[key], coord_frame, mri_trans)
src_rr = apply_trans(mri_trans, src_rr)
src_nn = apply_trans(mri_trans, src_nn, move=False)
# determine points
meg_rrs, meg_tris = list(), list()
ecog_loc = list()
hpi_loc = list()
ext_loc = list()
car_loc = list()
eeg_loc = list()
eegp_loc = list()
if len(eeg_sensors) > 0:
eeg_loc = np.array([info['chs'][k]['loc'][:3] for k in eeg_picks])
if len(eeg_loc) > 0:
eeg_loc = apply_trans(head_trans, eeg_loc)
# XXX do projections here if necessary
if 'projected' in eeg_sensors:
eegp_loc, eegp_nn = _project_onto_surface(
eeg_loc, surfs['head'], project_rrs=True,
return_nn=True)[2:4]
if 'original' not in eeg_sensors:
eeg_loc = list()
del eeg_sensors
if 'sensors' in meg_sensors:
coil_transs = [_loc_to_coil_trans(info['chs'][pick]['loc'])
for pick in meg_picks]
coils = _create_meg_coils([info['chs'][pick] for pick in meg_picks],
acc='normal')
offset = 0
for coil, coil_trans in zip(coils, coil_transs):
rrs, tris = _sensor_shape(coil)
rrs = apply_trans(coil_trans, rrs)
meg_rrs.append(rrs)
meg_tris.append(tris + offset)
offset += len(meg_rrs[-1])
if len(meg_rrs) == 0:
warn('MEG electrodes not found. Cannot plot MEG locations.')
else:
meg_rrs = apply_trans(meg_trans, np.concatenate(meg_rrs, axis=0))
meg_tris = np.concatenate(meg_tris, axis=0)
del meg_sensors
if dig:
if dig == 'fiducials':
hpi_loc = ext_loc = []
elif dig is not True:
raise ValueError("dig needs to be True, False or 'fiducials', "
"not %s" % repr(dig))
else:
hpi_loc = np.array([d['r'] for d in info['dig']
if d['kind'] == FIFF.FIFFV_POINT_HPI])
ext_loc = np.array([d['r'] for d in info['dig']
if d['kind'] == FIFF.FIFFV_POINT_EXTRA])
car_loc = _fiducial_coords(info['dig'])
# Transform from head coords if necessary
if coord_frame == 'meg':
for loc in (hpi_loc, ext_loc, car_loc):
loc[:] = apply_trans(invert_transform(info['dev_head_t']), loc)
elif coord_frame == 'mri':
for loc in (hpi_loc, ext_loc, car_loc):
loc[:] = apply_trans(head_mri_t, loc)
if len(car_loc) == len(ext_loc) == len(hpi_loc) == 0:
warn('Digitization points not found. Cannot plot digitization.')
del dig
if len(ecog_picks) > 0 and ecog_sensors:
ecog_loc = np.array([info['chs'][pick]['loc'][:3]
for pick in ecog_picks])
# initialize figure
fig = mlab.figure(bgcolor=(0.0, 0.0, 0.0), size=(600, 600))
_toggle_mlab_render(fig, False)
# plot surfaces
alphas = dict(head=head_alpha, helmet=0.5, lh=hemi_val, rh=hemi_val)
alphas.update(skull_alpha)
colors = dict(head=(0.6,) * 3, helmet=(0.0, 0.0, 0.6), lh=(0.5,) * 3,
rh=(0.5,) * 3)
colors.update(skull_colors)
for key, surf in surfs.items():
# Make a solid surface
mesh = _create_mesh_surf(surf, fig)
with warnings.catch_warnings(record=True): # traits
surface = mlab.pipeline.surface(mesh, color=colors[key],
opacity=alphas[key], figure=fig)
if key != 'helmet':
surface.actor.property.backface_culling = True
# plot points
defaults = DEFAULTS['coreg']
datas = [eeg_loc,
hpi_loc,
ext_loc, ecog_loc]
colors = [defaults['eeg_color'],
defaults['hpi_color'],
defaults['extra_color'], defaults['ecog_color']]
alphas = [0.8,
0.5,
0.25, 0.8]
scales = [defaults['eeg_scale'],
defaults['hpi_scale'],
defaults['extra_scale'], defaults['ecog_scale']]
for kind, loc in (('dig', car_loc), ('mri', fid_loc)):
if len(loc) > 0:
datas.extend(loc[:, np.newaxis])
colors.extend((defaults['lpa_color'],
defaults['nasion_color'],
defaults['rpa_color']))
alphas.extend(3 * (defaults[kind + '_fid_opacity'],))
scales.extend(3 * (defaults[kind + '_fid_scale'],))
for data, color, alpha, scale in zip(datas, colors, alphas, scales):
if len(data) > 0:
with warnings.catch_warnings(record=True): # traits
points = mlab.points3d(data[:, 0], data[:, 1], data[:, 2],
color=color, scale_factor=scale,
opacity=alpha, figure=fig)
points.actor.property.backface_culling = True
if len(eegp_loc) > 0:
with warnings.catch_warnings(record=True): # traits
quiv = mlab.quiver3d(
eegp_loc[:, 0], eegp_loc[:, 1], eegp_loc[:, 2],
eegp_nn[:, 0], eegp_nn[:, 1], eegp_nn[:, 2],
color=defaults['eegp_color'], mode='cylinder',
scale_factor=defaults['eegp_scale'], opacity=0.6, figure=fig)
quiv.glyph.glyph_source.glyph_source.height = defaults['eegp_height']
quiv.glyph.glyph_source.glyph_source.center = \
(0., -defaults['eegp_height'], 0)
quiv.glyph.glyph_source.glyph_source.resolution = 20
quiv.actor.property.backface_culling = True
if len(meg_rrs) > 0:
color, alpha = (0., 0.25, 0.5), 0.25
surf = dict(rr=meg_rrs, tris=meg_tris)
complete_surface_info(surf, copy=False, verbose=False)
mesh = _create_mesh_surf(surf, fig)
with warnings.catch_warnings(record=True): # traits
surface = mlab.pipeline.surface(mesh, color=color,
opacity=alpha, figure=fig)
# Don't cull these backfaces
if len(src_rr) > 0:
with warnings.catch_warnings(record=True): # traits
quiv = mlab.quiver3d(
src_rr[:, 0], src_rr[:, 1], src_rr[:, 2],
src_nn[:, 0], src_nn[:, 1], src_nn[:, 2], color=(1., 1., 0.),
mode='cylinder', scale_factor=3e-3, opacity=0.75, figure=fig)
quiv.glyph.glyph_source.glyph_source.height = 0.25
quiv.glyph.glyph_source.glyph_source.center = (0., 0., 0.)
quiv.glyph.glyph_source.glyph_source.resolution = 20
quiv.actor.property.backface_culling = True
with SilenceStdout():
mlab.view(90, 90, figure=fig)
_toggle_mlab_render(fig, True)
return fig
@verbose
def plot_alignment(info, trans=None, subject=None, subjects_dir=None,
surfaces=('head',), coord_frame='head',
meg=('helmet', 'sensors'), eeg='original',
dig=False, ecog=True, src=None, mri_fiducials=False,
bem=None, verbose=None):
"""Plot head, sensor, and source space alignment in 3D.
Parameters
----------
info : dict
The measurement info.
trans : str | 'auto' | dict | None
The full path to the head<->MRI transform ``*-trans.fif`` file
produced during coregistration. If trans is None, an identity matrix
is assumed.
subject : str | None
The subject name corresponding to FreeSurfer environment
variable SUBJECT. Can be omitted if ``src`` is provided.
subjects_dir : str | None
The path to the freesurfer subjects reconstructions.
It corresponds to Freesurfer environment variable SUBJECTS_DIR.
surfaces : str | list
Surfaces to plot. Supported values: 'head', 'outer_skin',
'outer_skull', 'inner_skull', 'brain', 'pial', 'white', 'inflated'.
Defaults to ('head',).
.. note:: For single layer BEMs it is recommended to use 'brain'.
coord_frame : str
Coordinate frame to use, 'head', 'meg', or 'mri'.
meg : str | list | bool
Can be "helmet", "sensors" or "ref" to show the MEG helmet, sensors or
reference sensors respectively, or a combination like
``['helmet', 'sensors']``. True translates to
``('helmet', 'sensors', 'ref')``.
eeg : bool | str | list
Can be "original" (default; equivalent to True) or "projected" to
show EEG sensors in their digitized locations or projected onto the
scalp, or a list of these options including ``[]`` (equivalent of
False).
dig : bool | 'fiducials'
If True, plot the digitization points; 'fiducials' to plot fiducial
points only.
ecog : bool
If True (default), show ECoG sensors.
src : instance of SourceSpaces | None
If not None, also plot the source space points.
mri_fiducials : bool | str
Plot MRI fiducials (default False). If ``True``, look for a file with
the canonical name (``bem/{subject}-fiducials.fif``). If ``str`` it
should provide the full path to the fiducials file.
bem : list of dict | Instance of ConductorModel | None
Can be either the BEM surfaces (list of dict), a BEM solution or a
sphere model. If None, we first try loading
`'$SUBJECTS_DIR/$SUBJECT/bem/$SUBJECT-$SOURCE.fif'`, and then look for
`'$SUBJECT*$SOURCE.fif'` in the same directory. For `'outer_skin'`,
the subjects bem and bem/flash folders are searched. Defaults to None.
verbose : bool, str, int, or None
If not None, override default verbose level (see :func:`mne.verbose`
and :ref:`Logging documentation <tut_logging>` for more).
Returns
-------
fig : instance of mlab.Figure
The mayavi figure.
See Also
--------
mne.viz.plot_bem
Notes
-----
This function serves the purpose of checking the validity of the many
different steps of source reconstruction:
- Transform matrix (keywords ``trans``, ``meg`` and ``mri_fiducials``),
- BEM surfaces (keywords ``bem`` and ``surfaces``),
- sphere conductor model (keywords ``bem`` and ``surfaces``) and
- source space (keywords ``surfaces`` and ``src``).
.. versionadded:: 0.15
"""
from ..forward import _create_meg_coils
mlab = _import_mlab()
if eeg is False:
eeg = list()
elif eeg is True:
eeg = 'original'
if meg is True:
meg = ('helmet', 'sensors', 'ref')
elif meg is False:
meg = list()
elif isinstance(meg, string_types):
meg = [meg]
if isinstance(eeg, string_types):
eeg = [eeg]
for kind, var in zip(('eeg', 'meg'), (eeg, meg)):
if not isinstance(var, (list, tuple)) or \
not all(isinstance(x, string_types) for x in var):
raise TypeError('%s must be list or tuple of str, got %s'
% (kind, type(var)))
if not all(x in ('helmet', 'sensors', 'ref') for x in meg):
raise ValueError('meg must only contain "helmet", "sensors" or "ref", '
'got %s' % (meg,))
if not all(x in ('original', 'projected') for x in eeg):
raise ValueError('eeg must only contain "original" and '
'"projected", got %s' % (eeg,))
if not isinstance(info, Info):
raise TypeError('info must be an instance of Info, got %s'
% type(info))
is_sphere = False
if isinstance(bem, ConductorModel) and bem['is_sphere']:
if len(bem['layers']) != 4 and len(surfaces) > 1:
raise ValueError('The sphere conductor model must have three '
'layers for plotting skull and head.')
is_sphere = True
# Skull:
skull = list()
if 'outer_skull' in surfaces:
if isinstance(bem, ConductorModel) and not bem['is_sphere']:
skull.append(_bem_find_surface(bem, FIFF.FIFFV_BEM_SURF_ID_SKULL))
else:
skull.append('outer_skull')
if 'inner_skull' in surfaces:
if isinstance(bem, ConductorModel) and not bem['is_sphere']:
skull.append(_bem_find_surface(bem, FIFF.FIFFV_BEM_SURF_ID_BRAIN))
else:
skull.append('inner_skull')
surf_dict = _surf_dict.copy()
surf_dict['outer_skin'] = FIFF.FIFFV_BEM_SURF_ID_HEAD