-
Notifications
You must be signed in to change notification settings - Fork 100
/
Copy pathviz.py
3684 lines (3285 loc) · 145 KB
/
viz.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
from copy import deepcopy
import logging
from math import floor
import os
from os.path import join as pjoin
import warnings
from warnings import warn
import numpy as np
import nibabel as nib
from mayavi import mlab
from mayavi.tools.mlab_scene_model import MlabSceneModel
from mayavi.core import lut_manager
from mayavi.core.scene import Scene
from mayavi.core.ui.api import SceneEditor
from mayavi.core.ui.mayavi_scene import MayaviScene
from traits.api import (HasTraits, Range, Int, Float,
Bool, Enum, on_trait_change, Instance)
from tvtk.api import tvtk
from pyface.api import GUI
from traitsui.api import View, Item, Group, VGroup, HGroup, VSplit, HSplit
from . import utils, io
from .utils import (Surface, verbose, create_color_lut, _get_subjects_dir,
string_types, threshold_filter, _check_units)
logger = logging.getLogger('surfer')
lh_viewdict = {'lateral': {'v': (180., 90.), 'r': 90.},
'medial': {'v': (0., 90.), 'r': -90.},
'rostral': {'v': (90., 90.), 'r': -180.},
'caudal': {'v': (270., 90.), 'r': 0.},
'dorsal': {'v': (180., 0.), 'r': 90.},
'ventral': {'v': (180., 180.), 'r': 90.},
'frontal': {'v': (120., 80.), 'r': 106.739},
'parietal': {'v': (-120., 60.), 'r': 49.106}}
rh_viewdict = {'lateral': {'v': (180., -90.), 'r': -90.},
'medial': {'v': (0., -90.), 'r': 90.},
'rostral': {'v': (-90., -90.), 'r': 180.},
'caudal': {'v': (90., -90.), 'r': 0.},
'dorsal': {'v': (180., 0.), 'r': 90.},
'ventral': {'v': (180., 180.), 'r': 90.},
'frontal': {'v': (60., 80.), 'r': -106.739},
'parietal': {'v': (-60., 60.), 'r': -49.106}}
viewdicts = dict(lh=lh_viewdict, rh=rh_viewdict)
def make_montage(filename, fnames, orientation='h', colorbar=None,
border_size=15):
"""Save montage of current figure
Parameters
----------
filename : str
The name of the file, e.g, 'montage.png'. If None, the image
will not be saved.
fnames : list of str | list of array
The images to make the montage of. Can be a list of filenames
or a list of image data arrays.
orientation : 'h' | 'v' | list
The orientation of the montage: horizontal, vertical, or a nested
list of int (indexes into fnames).
colorbar : None | list of int
If None remove colorbars, else keep the ones whose index
is present.
border_size : int
The size of the border to keep.
Returns
-------
out : array
The montage image data array.
"""
try:
import Image
except (ValueError, ImportError):
from PIL import Image
from scipy import ndimage
# This line is only necessary to overcome a PIL bug, see:
# http://stackoverflow.com/questions/10854903/what-is-causing-
# dimension-dependent-attributeerror-in-pil-fromarray-function
fnames = [f if isinstance(f, string_types) else f.copy() for f in fnames]
if isinstance(fnames[0], string_types):
images = list(map(Image.open, fnames))
else:
images = list(map(Image.fromarray, fnames))
# get bounding box for cropping
boxes = []
for ix, im in enumerate(images):
# sum the RGB dimension so we do not miss G or B-only pieces
gray = np.sum(np.array(im), axis=-1)
gray[gray == gray[0, 0]] = 0 # hack for find_objects that wants 0
if np.all(gray == 0):
raise ValueError("Empty image (all pixels have the same color).")
labels, n_labels = ndimage.label(gray.astype(np.float))
slices = ndimage.find_objects(labels, n_labels) # slice roi
if colorbar is not None and ix in colorbar:
# we need all pieces so let's compose them into single min/max
slices_a = np.array([[[xy.start, xy.stop] for xy in s]
for s in slices])
# TODO: ideally gaps could be deduced and cut out with
# consideration of border_size
# so we need mins on 0th and maxs on 1th of 1-nd dimension
mins = np.min(slices_a[:, :, 0], axis=0)
maxs = np.max(slices_a[:, :, 1], axis=0)
s = (slice(mins[0], maxs[0]), slice(mins[1], maxs[1]))
else:
# we need just the first piece
s = slices[0]
# box = (left, top, width, height)
boxes.append([s[1].start - border_size, s[0].start - border_size,
s[1].stop + border_size, s[0].stop + border_size])
# convert orientation to nested list of int
if orientation == 'h':
orientation = [range(len(images))]
elif orientation == 'v':
orientation = [[i] for i in range(len(images))]
# find bounding box
n_rows = len(orientation)
n_cols = max(len(row) for row in orientation)
if n_rows > 1:
min_left = min(box[0] for box in boxes)
max_width = max(box[2] for box in boxes)
for box in boxes:
box[0] = min_left
box[2] = max_width
if n_cols > 1:
min_top = min(box[1] for box in boxes)
max_height = max(box[3] for box in boxes)
for box in boxes:
box[1] = min_top
box[3] = max_height
# crop images
cropped_images = []
for im, box in zip(images, boxes):
cropped_images.append(im.crop(box))
images = cropped_images
# Get full image size
row_w = [sum(images[i].size[0] for i in row) for row in orientation]
row_h = [max(images[i].size[1] for i in row) for row in orientation]
out_w = max(row_w)
out_h = sum(row_h)
# compose image
new = Image.new("RGBA", (out_w, out_h))
y = 0
for row, h in zip(orientation, row_h):
x = 0
for i in row:
im = images[i]
pos = (x, y)
new.paste(im, pos)
x += im.size[0]
y += h
if filename is not None:
new.save(filename)
return np.array(new)
def _prepare_data(data):
"""Ensure data is float64 and has proper endianness.
Note: this is largely aimed at working around a Mayavi bug.
"""
data = data.copy()
data = data.astype(np.float64)
if data.dtype.byteorder == '>':
data.byteswap(True)
return data
def _force_render(figures):
"""Ensure plots are updated before properties are used"""
if not isinstance(figures, list):
figures = [[figures]]
_gui = GUI()
orig_val = _gui.busy
_gui.set_busy(busy=True)
_gui.process_events()
for ff in figures:
for f in ff:
f.render()
mlab.draw(figure=f)
_gui.set_busy(busy=orig_val)
_gui.process_events()
def _make_viewer(figure, n_row, n_col, title, scene_size, offscreen,
interaction='trackball', antialias=True):
"""Triage viewer creation
If n_row == n_col == 1, then we can use a Mayavi figure, which
generally guarantees that things will be drawn before control
is returned to the command line. With the multi-view, TraitsUI
unfortunately has no such support, so we only use it if needed.
"""
if figure is None:
# spawn scenes
h, w = scene_size
if offscreen == 'auto':
offscreen = mlab.options.offscreen
if offscreen:
orig_val = mlab.options.offscreen
try:
mlab.options.offscreen = True
with warnings.catch_warnings(record=True): # traits
figures = [[mlab.figure(size=(w / n_col, h / n_row))
for _ in range(n_col)] for __ in range(n_row)]
finally:
mlab.options.offscreen = orig_val
_v = None
else:
# Triage: don't make TraitsUI if we don't have to
if n_row == 1 and n_col == 1:
with warnings.catch_warnings(record=True): # traits
figure = mlab.figure(size=(w, h))
figure.name = title # should set the figure title
figures = [[figure]]
_v = None
else:
window = _MlabGenerator(n_row, n_col, w, h, title)
figures, _v = window._get_figs_view()
if interaction == 'terrain': # "trackball" is default
for figure in figures:
for f in figure:
f.scene.interactor.interactor_style = \
tvtk.InteractorStyleTerrain()
if antialias:
for figure in figures:
for f in figure:
# on a non-testing backend, and using modern VTK/Mayavi
if hasattr(getattr(f.scene, 'renderer', None),
'use_fxaa'):
f.scene.renderer.use_fxaa = True
else:
if isinstance(figure, int): # use figure with specified id
figure = [mlab.figure(figure, size=scene_size)]
elif isinstance(figure, tuple):
figure = list(figure)
elif not isinstance(figure, list):
figure = [figure]
if not all(isinstance(f, Scene) for f in figure):
raise TypeError('figure must be a mayavi scene or list of scenes')
if not len(figure) == n_row * n_col:
raise ValueError('For the requested view, figure must be a '
'list or tuple with exactly %i elements, '
'not %i' % (n_row * n_col, len(figure)))
_v = None
figures = [figure[slice(ri * n_col, (ri + 1) * n_col)]
for ri in range(n_row)]
return figures, _v
class _MlabGenerator(HasTraits):
"""TraitsUI mlab figure generator"""
view = Instance(View)
def __init__(self, n_row, n_col, width, height, title, **traits):
HasTraits.__init__(self, **traits)
self.mlab_names = []
self.n_row = n_row
self.n_col = n_col
self.width = width
self.height = height
for fi in range(n_row * n_col):
name = 'mlab_view%03g' % fi
self.mlab_names.append(name)
self.add_trait(name, Instance(MlabSceneModel, ()))
self.view = self._get_gen_view()
self._v = self.edit_traits(view=self.view)
self._v.title = title
def _get_figs_view(self):
figures = []
ind = 0
for ri in range(self.n_row):
rfigs = []
for ci in range(self.n_col):
x = getattr(self, self.mlab_names[ind])
rfigs.append(x.mayavi_scene)
ind += 1
figures.append(rfigs)
return figures, self._v
def _get_gen_view(self):
ind = 0
va = []
for ri in range(self.n_row):
ha = []
for ci in range(self.n_col):
ha += [Item(name=self.mlab_names[ind], style='custom',
resizable=True, show_label=False,
editor=SceneEditor(scene_class=MayaviScene))]
ind += 1
va += [HGroup(*ha)]
view = View(VGroup(*va), resizable=True,
height=self.height, width=self.width)
return view
class Brain(object):
"""Class for visualizing a brain using multiple views in mlab
Parameters
----------
subject_id : str
subject name in Freesurfer subjects dir
hemi : str
hemisphere id (ie 'lh', 'rh', 'both', or 'split'). In the case
of 'both', both hemispheres are shown in the same window.
In the case of 'split' hemispheres are displayed side-by-side
in different viewing panes.
surf : str
freesurfer surface mesh name (ie 'white', 'inflated', etc.)
title : str
title for the window
cortex : str, tuple, dict, or None
Specifies how the cortical surface is rendered. Options:
1. The name of one of the preset cortex styles:
``'classic'`` (default), ``'high_contrast'``,
``'low_contrast'``, or ``'bone'``.
2. A color-like argument to render the cortex as a single
color, e.g. ``'red'`` or ``(0.1, 0.4, 1.)``. Setting
this to ``None`` is equivalent to ``(0.5, 0.5, 0.5)``.
3. The name of a colormap used to render binarized
curvature values, e.g., ``Grays``.
4. A list of colors used to render binarized curvature
values. Only the first and last colors are used. E.g.,
['red', 'blue'] or [(1, 0, 0), (0, 0, 1)].
5. A container with four entries for colormap (string
specifiying the name of a colormap), vmin (float
specifying the minimum value for the colormap), vmax
(float specifying the maximum value for the colormap),
and reverse (bool specifying whether the colormap
should be reversed. E.g., ``('Greys', -1, 2, False)``.
6. A dict of keyword arguments that is passed on to the
call to surface.
alpha : float in [0, 1]
Alpha level to control opacity of the cortical surface.
size : float or pair of floats
the size of the window, in pixels. can be one number to specify
a square window, or the (width, height) of a rectangular window.
background : matplotlib color
Color of the background.
foreground : matplotlib color
Color of the foreground (will be used for colorbars and text).
None (default) will use black or white depending on the value
of ``background``.
figure : list of mayavi.core.scene.Scene | None | int
If None (default), a new window will be created with the appropriate
views. For single view plots, the figure can be specified as int to
retrieve the corresponding Mayavi window.
subjects_dir : str | None
If not None, this directory will be used as the subjects directory
instead of the value set using the SUBJECTS_DIR environment
variable.
views : list | str
views to use
offset : bool
If True, aligs origin with medial wall. Useful for viewing inflated
surface where hemispheres typically overlap (Default: True)
show_toolbar : bool
If True, toolbars will be shown for each view.
offscreen : bool | str
If True, rendering will be done offscreen (not shown). Useful
mostly for generating images or screenshots, but can be buggy.
Use at your own risk. Can be "auto" (default) to use
``mlab.options.offscreen``.
interaction : str
Can be "trackball" (default) or "terrain", i.e. a turntable-style
camera.
units : str
Can be 'm' or 'mm' (default).
antialias : bool
If True (default), turn on antialiasing. Can be problematic for
some renderers (e.g., software rendering with MESA).
Attributes
----------
annot : list
List of annotations.
brains : list
List of the underlying brain instances.
contour : list
List of the contours.
foci : foci
The foci.
labels : dict
The labels.
overlays : dict
The overlays.
texts : dict
The text objects.
"""
def __init__(self, subject_id, hemi, surf, title=None,
cortex="classic", alpha=1.0, size=800, background="black",
foreground=None, figure=None, subjects_dir=None,
views=['lat'], offset=True, show_toolbar=False,
offscreen='auto', interaction='trackball', units='mm',
antialias=True):
if not isinstance(interaction, string_types) or \
interaction not in ('trackball', 'terrain'):
raise ValueError('interaction must be "trackball" or "terrain", '
'got "%s"' % (interaction,))
self._units = _check_units(units)
col_dict = dict(lh=1, rh=1, both=1, split=2)
n_col = col_dict[hemi]
if hemi not in col_dict.keys():
raise ValueError('hemi must be one of [%s], not %s'
% (', '.join(col_dict.keys()), hemi))
# Get the subjects directory from parameter or env. var
subjects_dir = _get_subjects_dir(subjects_dir=subjects_dir)
self._hemi = hemi
if title is None:
title = subject_id
self.subject_id = subject_id
if not isinstance(views, (list, tuple)):
views = [views]
n_row = len(views)
# load geometry for one or both hemispheres as necessary
offset = None if (not offset or hemi != 'both') else 0.0
self.geo = dict()
if hemi in ['split', 'both']:
geo_hemis = ['lh', 'rh']
elif hemi == 'lh':
geo_hemis = ['lh']
elif hemi == 'rh':
geo_hemis = ['rh']
else:
raise ValueError('bad hemi value')
geo_kwargs, geo_reverse, geo_curv = self._get_geo_params(cortex, alpha)
for h in geo_hemis:
# Initialize a Surface object as the geometry
geo = Surface(subject_id, h, surf, subjects_dir, offset,
units=self._units)
# Load in the geometry and (maybe) curvature
geo.load_geometry()
if geo_curv:
geo.load_curvature()
self.geo[h] = geo
# deal with making figures
self._set_window_properties(size, background, foreground)
del background, foreground
figures, _v = _make_viewer(figure, n_row, n_col, title,
self._scene_size, offscreen,
interaction, antialias)
self._figures = figures
self._v = _v
self._window_backend = 'Mayavi' if self._v is None else 'TraitsUI'
for ff in self._figures:
for f in ff:
if f.scene is not None:
f.scene.background = self._bg_color
f.scene.foreground = self._fg_color
# force rendering so scene.lights exists
_force_render(self._figures)
self.toggle_toolbars(show_toolbar)
_force_render(self._figures)
self._toggle_render(False)
# fill figures with brains
kwargs = dict(geo_curv=geo_curv, geo_kwargs=geo_kwargs,
geo_reverse=geo_reverse, subjects_dir=subjects_dir,
bg_color=self._bg_color, fg_color=self._fg_color)
brains = []
brain_matrix = []
for ri, view in enumerate(views):
brain_row = []
for hi, h in enumerate(['lh', 'rh']):
if not (hemi in ['lh', 'rh'] and h != hemi):
ci = hi if hemi == 'split' else 0
kwargs['hemi'] = h
kwargs['geo'] = self.geo[h]
kwargs['figure'] = figures[ri][ci]
kwargs['backend'] = self._window_backend
brain = _Hemisphere(subject_id, **kwargs)
brain.show_view(view)
brains += [dict(row=ri, col=ci, brain=brain, hemi=h)]
brain_row += [brain]
brain_matrix += [brain_row]
self._toggle_render(True)
self._original_views = views
self._brain_list = brains
for brain in self._brain_list:
brain['brain']._orient_lights()
self.brains = [b['brain'] for b in brains]
self.brain_matrix = np.array(brain_matrix)
self.subjects_dir = subjects_dir
self.surf = surf
# Initialize the overlay and label dictionaries
self.foci_dict = dict()
self._label_dicts = dict()
self.overlays_dict = dict()
self.contour_list = []
self.morphometry_list = []
self.annot_list = []
self._data_dicts = dict(lh=[], rh=[])
# note that texts gets treated differently
self.texts_dict = dict()
self._times = None
self.n_times = None
@property
def data_dict(self):
"""For backwards compatibility"""
lh_list = self._data_dicts['lh']
rh_list = self._data_dicts['rh']
return dict(lh=lh_list[-1] if lh_list else None,
rh=rh_list[-1] if rh_list else None)
@property
def labels_dict(self):
"""For backwards compatibility"""
return {key: data['surfaces'] for key, data in
self._label_dicts.items()}
###########################################################################
# HELPERS
def _toggle_render(self, state, views=None):
"""Turn rendering on (True) or off (False)"""
figs = [fig for fig_row in self._figures for fig in fig_row]
if views is None:
views = [None] * len(figs)
for vi, (_f, view) in enumerate(zip(figs, views)):
# Testing backend doesn't have these options
if mlab.options.backend == 'test':
continue
if state is False and view is None:
views[vi] = (mlab.view(figure=_f), mlab.roll(figure=_f),
_f.scene.camera.parallel_scale
if _f.scene is not None else False)
if _f.scene is not None:
_f.scene.disable_render = not state
if state is True and view is not None and _f.scene is not None:
mlab.draw(figure=_f)
with warnings.catch_warnings(record=True): # traits focalpoint
mlab.view(*view[0], figure=_f)
mlab.roll(view[1], figure=_f)
# let's do the ugly force draw
if state is True:
_force_render(self._figures)
return views
def _set_window_properties(self, size, background, foreground):
"""Set window properties that are used elsewhere."""
# old option "size" sets both width and height
from matplotlib.colors import colorConverter
try:
width, height = size
except (TypeError, ValueError):
width, height = size, size
self._scene_size = height, width
self._bg_color = colorConverter.to_rgb(background)
if foreground is None:
foreground = 'w' if sum(self._bg_color) < 2 else 'k'
self._fg_color = colorConverter.to_rgb(foreground)
def _get_geo_params(self, cortex, alpha=1.0):
"""Return keyword arguments and other parameters for surface
rendering.
Parameters
----------
cortex : {str, tuple, dict, None}
Can be set to: (1) the name of one of the preset cortex
styles ('classic', 'high_contrast', 'low_contrast', or
'bone'), (2) the name of a colormap, (3) a tuple with
four entries for (colormap, vmin, vmax, reverse)
indicating the name of the colormap, the min and max
values respectively and whether or not the colormap should
be reversed, (4) a valid color specification (such as a
3-tuple with RGB values or a valid color name), or (5) a
dictionary of keyword arguments that is passed on to the
call to surface. If set to None, color is set to (0.5,
0.5, 0.5).
alpha : float in [0, 1]
Alpha level to control opacity of the cortical surface.
Returns
-------
kwargs : dict
Dictionary with keyword arguments to be used for surface
rendering. For colormaps, keys are ['colormap', 'vmin',
'vmax', 'alpha'] to specify the name, minimum, maximum,
and alpha transparency of the colormap respectively. For
colors, keys are ['color', 'alpha'] to specify the name
and alpha transparency of the color respectively.
reverse : boolean
Boolean indicating whether a colormap should be
reversed. Set to False if a color (rather than a colormap)
is specified.
curv : boolean
Boolean indicating whether curv file is loaded and binary
curvature is displayed.
"""
from matplotlib.colors import colorConverter
colormap_map = dict(classic=(dict(colormap="Greys",
vmin=-1, vmax=2,
opacity=alpha), False, True),
high_contrast=(dict(colormap="Greys",
vmin=-.1, vmax=1.3,
opacity=alpha), False, True),
low_contrast=(dict(colormap="Greys",
vmin=-5, vmax=5,
opacity=alpha), False, True),
bone=(dict(colormap="bone",
vmin=-.2, vmax=2,
opacity=alpha), True, True))
if isinstance(cortex, dict):
if 'opacity' not in cortex:
cortex['opacity'] = alpha
if 'colormap' in cortex:
if 'vmin' not in cortex:
cortex['vmin'] = -1
if 'vmax' not in cortex:
cortex['vmax'] = 2
geo_params = cortex, False, True
elif isinstance(cortex, string_types):
if cortex in colormap_map:
geo_params = colormap_map[cortex]
elif cortex in lut_manager.lut_mode_list():
geo_params = dict(colormap=cortex, vmin=-1, vmax=2,
opacity=alpha), False, True
else:
try:
color = colorConverter.to_rgb(cortex)
geo_params = dict(color=color, opacity=alpha), False, False
except ValueError:
geo_params = cortex, False, True
# check for None before checking len:
elif cortex is None:
geo_params = dict(color=(0.5, 0.5, 0.5),
opacity=alpha), False, False
# Test for 4-tuple specifying colormap parameters. Need to
# avoid 4 letter strings and 4-tuples not specifying a
# colormap name in the first position (color can be specified
# as RGBA tuple, but the A value will be dropped by to_rgb()):
elif (len(cortex) == 4) and (isinstance(cortex[0], string_types)):
geo_params = dict(colormap=cortex[0], vmin=cortex[1],
vmax=cortex[2], opacity=alpha), cortex[3], True
else:
try: # check if it's a non-string color specification
color = colorConverter.to_rgb(cortex)
geo_params = dict(color=color, opacity=alpha), False, False
except (ValueError, TypeError):
try:
lut = create_color_lut(cortex)
geo_params = dict(colormap="Greys", opacity=alpha,
lut=lut), False, True
except ValueError:
geo_params = cortex, False, True
return geo_params
def get_data_properties(self):
""" Get properties of the data shown
Returns
-------
props : dict
Dictionary with data properties
props["fmin"] : minimum colormap
props["fmid"] : midpoint colormap
props["fmax"] : maximum colormap
props["transparent"] : lower part of colormap transparent?
props["time"] : time points
props["time_idx"] : current time index
props["smoothing_steps"] : number of smoothing steps
"""
props = dict()
keys = ['fmin', 'fmid', 'fmax', 'transparent', 'time', 'time_idx',
'smoothing_steps', 'center']
try:
if self.data_dict['lh'] is not None:
hemi = 'lh'
else:
hemi = 'rh'
for key in keys:
props[key] = self.data_dict[hemi][key]
except KeyError:
# The user has not added any data
for key in keys:
props[key] = 0
return props
def toggle_toolbars(self, show=None):
"""Toggle toolbar display
Parameters
----------
show : bool | None
If None, the state is toggled. If True, the toolbar will
be shown, if False, hidden.
"""
# don't do anything if testing is on
if self._figures[0][0].scene is not None:
# this may not work if QT is not the backend (?), or in testing
if hasattr(self._figures[0][0].scene, 'scene_editor'):
# Within TraitsUI
bars = [f.scene.scene_editor._tool_bar
for ff in self._figures for f in ff]
else:
# Mayavi figure
bars = [f.scene._tool_bar for ff in self._figures for f in ff]
if show is None:
if hasattr(bars[0], 'isVisible'):
# QT4
show = not bars[0].isVisible()
elif hasattr(bars[0], 'Shown'):
# WX
show = not bars[0].Shown()
for bar in bars:
if hasattr(bar, 'setVisible'):
bar.setVisible(show)
elif hasattr(bar, 'Show'):
bar.Show(show)
def _get_one_brain(self, d, name):
"""Helper for various properties"""
if len(self.brains) > 1:
raise ValueError('Cannot access brain.%s when more than '
'one view is plotted. Use brain.brain_matrix '
'or brain.brains.' % name)
if isinstance(d, dict):
out = dict()
for key, value in d.items():
out[key] = value[0]
else:
out = d[0]
return out
@property
def overlays(self):
return self._get_one_brain(self.overlays_dict, 'overlays')
@property
def foci(self):
return self._get_one_brain(self.foci_dict, 'foci')
@property
def labels(self):
return self._get_one_brain(self.labels_dict, 'labels')
@property
def contour(self):
return self._get_one_brain(self.contour_list, 'contour')
@property
def annot(self):
return self._get_one_brain(self.annot_list, 'annot')
@property
def texts(self):
self._get_one_brain([[]], 'texts')
out = dict()
for key, val in self.texts_dict.iteritems():
out[key] = val['text']
return out
@property
def data(self):
self._get_one_brain([[]], 'data')
if self.data_dict['lh'] is not None:
data = self.data_dict['lh'].copy()
else:
data = self.data_dict['rh'].copy()
if 'colorbars' in data:
data['colorbar'] = data['colorbars'][0]
return data
def _check_hemi(self, hemi):
"""Check for safe single-hemi input, returns str"""
if hemi is None:
if self._hemi not in ['lh', 'rh']:
raise ValueError('hemi must not be None when both '
'hemispheres are displayed')
else:
hemi = self._hemi
elif hemi not in ['lh', 'rh']:
extra = ' or None' if self._hemi in ['lh', 'rh'] else ''
raise ValueError('hemi must be either "lh" or "rh"' + extra)
return hemi
def _check_hemis(self, hemi):
"""Check for safe dual or single-hemi input, returns list"""
if hemi is None:
if self._hemi not in ['lh', 'rh']:
hemi = ['lh', 'rh']
else:
hemi = [self._hemi]
elif hemi not in ['lh', 'rh']:
extra = ' or None' if self._hemi in ['lh', 'rh'] else ''
raise ValueError('hemi must be either "lh" or "rh"' + extra)
else:
hemi = [hemi]
return hemi
def _read_scalar_data(self, source, hemi, name=None, cast=True):
"""Load in scalar data from an image stored in a file or an array
Parameters
----------
source : str or numpy array
path to scalar data file or a numpy array
name : str or None, optional
name for the overlay in the internal dictionary
cast : bool, optional
either to cast float data into 64bit datatype as a
workaround. cast=True can fix a rendering problem with
certain versions of Mayavi
Returns
-------
scalar_data : numpy array
flat numpy array of scalar data
name : str
if no name was provided, deduces the name if filename was given
as a source
"""
# If source is a string, try to load a file
if isinstance(source, string_types):
if name is None:
basename = os.path.basename(source)
if basename.endswith(".gz"):
basename = basename[:-3]
if basename.startswith("%s." % hemi):
basename = basename[3:]
name = os.path.splitext(basename)[0]
scalar_data = io.read_scalar_data(source)
else:
# Can't think of a good way to check that this will work nicely
scalar_data = source
if cast:
if (scalar_data.dtype.char == 'f' and
scalar_data.dtype.itemsize < 8):
scalar_data = scalar_data.astype(np.float)
return scalar_data, name
def _get_display_range(self, scalar_data, min, max, sign):
if scalar_data.min() >= 0:
sign = "pos"
elif scalar_data.max() <= 0:
sign = "neg"
# Get data with a range that will make sense for automatic thresholding
if sign == "neg":
range_data = np.abs(scalar_data[np.where(scalar_data < 0)])
elif sign == "pos":
range_data = scalar_data[np.where(scalar_data > 0)]
else:
range_data = np.abs(scalar_data)
# Get a numeric value for the scalar minimum
if min is None:
min = "robust_min"
if min == "robust_min":
min = np.percentile(range_data, 2)
elif min == "actual_min":
min = range_data.min()
# Get a numeric value for the scalar maximum
if max is None:
max = "robust_max"
if max == "robust_max":
max = np.percentile(scalar_data, 98)
elif max == "actual_max":
max = range_data.max()
return min, max
def _iter_time(self, time_idx, interpolation):
"""Iterate through time points, then reset to current time
Parameters
----------
time_idx : array_like
Time point indexes through which to iterate.
interpolation : str
Interpolation method (``scipy.interpolate.interp1d`` parameter,
one of 'linear' | 'nearest' | 'zero' | 'slinear' | 'quadratic' |
'cubic'). Interpolation is only used for non-integer indexes.
Yields
------
idx : int | float
Current index.
Notes
-----
Used by movie and image sequence saving functions.
"""
current_time_idx = self.data_time_index
for idx in time_idx:
self.set_data_time_index(idx, interpolation)
yield idx
# Restore original time index
self.set_data_time_index(current_time_idx)
###########################################################################
# ADDING DATA PLOTS
def add_overlay(self, source, min=2, max="robust_max", sign="abs",
name=None, hemi=None, **kwargs):
"""Add an overlay to the overlay dict from a file or array.
Parameters
----------
source : str or numpy array
path to the overlay file or numpy array with data
min : float
threshold for overlay display
max : float
saturation point for overlay display
sign : {'abs' | 'pos' | 'neg'}
whether positive, negative, or both values should be displayed
name : str
name for the overlay in the internal dictionary
hemi : str | None
If None, it is assumed to belong to the hemipshere being
shown. If two hemispheres are being shown, an error will
be thrown.
**kwargs : additional keyword arguments
These are passed to the underlying
``mayavi.mlab.pipeline.surface`` call.
"""
hemi = self._check_hemi(hemi)
# load data here
scalar_data, name = self._read_scalar_data(source, hemi, name=name)
min, max = self._get_display_range(scalar_data, min, max, sign)
if sign not in ["abs", "pos", "neg"]:
raise ValueError("Overlay sign must be 'abs', 'pos', or 'neg'")
old = OverlayData(scalar_data, min, max, sign)
ol = []
views = self._toggle_render(False)
for brain in self._brain_list:
if brain['hemi'] == hemi:
ol.append(brain['brain'].add_overlay(old, **kwargs))
if name in self.overlays_dict:
name = "%s%d" % (name, len(self.overlays_dict) + 1)
self.overlays_dict[name] = ol
self._toggle_render(True, views)
@verbose
def add_data(self, array, min=None, max=None, thresh=None,
colormap="auto", alpha=1,
vertices=None, smoothing_steps=20, time=None,
time_label="time index=%d", colorbar=True,
hemi=None, remove_existing=False, time_label_size=14,
initial_time=None, scale_factor=None, vector_alpha=None,
mid=None, center=None, transparent=False, verbose=None,
**kwargs):
"""Display data from a numpy array on the surface.
This provides a similar interface to
:meth:`surfer.Brain.add_overlay`, but it displays
it with a single colormap. It offers more flexibility over the
colormap, and provides a way to display four-dimensional data
(i.e., a timecourse) or five-dimensional data (i.e., a
vector-valued timecourse).
.. note:: ``min`` sets the low end of the colormap, and is separate
from thresh (this is a different convention from
:meth:`surfer.Brain.add_overlay`).
Parameters
----------
array : numpy array, shape (n_vertices[, 3][, n_times])
Data array. For the data to be understood as vector-valued
(3 values per vertex corresponding to X/Y/Z surface RAS),
then ``array`` must be have all 3 dimensions.
If vectors with no time dimension are desired, consider using a
singleton (e.g., ``np.newaxis``) to create a "time" dimension
and pass ``time_label=None``.
min : float
min value in colormap (uses real min if None)
mid : float
intermediate value in colormap (middle between min and max if None)
max : float
max value in colormap (uses real max if None)
thresh : None or float