def _full_screen_fired(self): fs = self._fullscreen if isinstance(fs, PopupScene): fs.close() self._fullscreen = None elif fs is None: ver = tvtk.Version() popup = False if wx.Platform == '__WXMSW__': popup = True elif ver.vtk_major_version > 5: popup = True elif (ver.vtk_major_version == 5) and \ ((ver.vtk_minor_version >= 1) or \ (ver.vtk_build_version > 2)): popup = True if popup: # There is a bug with earlier versions of VTK that # breaks reparenting a window which is why we test for # the version above. f = PopupScene(self) self._fullscreen = f f.fullscreen() else: f = FullScreen(self) f.run() # This will block. self._fullscreen = None
def setUp(self): ver = tvtk.Version() self.less_than_vtk_5_6 = True if ver.vtk_major_version >= 5 and ver.vtk_minor_version >= 10: self.less_than_vtk_5_6 = False if self.less_than_vtk_5_6: super(TestMlabPipeline, self).setUp() else: e = Engine() e.start() mlab.set_engine(e)
def test_slice_unstructured_grid(self): v = tvtk.Version() if v.vtk_major_version < 6 and v.vtk_minor_version < 10: raise unittest.SkipTest('Broken on Travis with VTK-5.8?') # Given src = mlab.pipeline.open(get_example_data('uGridEx.vtk')) eg = mlab.pipeline.extract_unstructured_grid(src) eg.filter.set(cell_clipping=True, cell_maximum=2) # When sug = mlab.pipeline.slice_unstructured_grid(eg) # Then assert_allclose(sug.actor.actor.bounds, (1.0, 2.0, 0.0, 1.0, 0.0, 1.0))
file. This file can either be exec()ed or imported. See core/base.py:Base.trait_view() for what is currently used. Using exec() allows view changes without needing to restart Mayavi, but is slower than importing. """ # Authors: Prabhu Ramachandran <*****@*****.**> # Judah De Paula <*****@*****.**> # Copyright (c) 2005-2018, Enthought, Inc. # License: BSD Style. from traitsui.api import (View, Group, Item, InstanceEditor, DropEditor, Tabbed) from tvtk.api import tvtk from tvtk.common import vtk_major_version VTK_VER = tvtk.Version().vtk_version # The properties view group. _prop_base_group = Group(Item(name='representation'), Item(name='color'), Item(name='line_width'), Item(name='point_size'), Item(name='opacity')) _prop_group = Group(Item(name='property', style='custom', show_label=False, editor=InstanceEditor(view=View(_prop_base_group))), Item(name='property', show_label=False, editor=InstanceEditor(label='More options ...')), show_border=True, label='Property')
import numpy from traits.api import HasTraits, List, Instance, Any, Float, Bool, \ Str, Trait, Int from pyface.api import GUI from tvtk.api import tvtk from tvtk.tvtk_base import TVTKBase, vtk_color_trait from tvtk.common import configure_input_data from tvtk.tools import ivtk # Set this to False to not use LOD Actors. USE_LOD_ACTOR = True VTK_VER = StrictVersion(tvtk.Version().vtk_version) ###################################################################### # Utility functions. ###################################################################### def _make_actor(**kwargs): """Return a TVTK actor. If `mlab.USE_LOD_ACTOR` is `True` it returns an LODActor if not it returns a normal actor. """ if USE_LOD_ACTOR: r = tvtk.LODActor(number_of_cloud_points=1500) r.property.point_size = 2.0 r.trait_set(**kwargs) return r else:
def plot_map(map, affine, cut_coords=None, anat=None, anat_affine=None, slicer='ortho', figure=None, axes=None, title=None, threshold=None, annotate=True, draw_cross=True, do3d=False, threshold_3d=None, view_3d=(38.5, 70.5, 300, (-2.7, -12, 9.1)), black_bg=False, **kwargs): """ Plot three cuts of a given activation map (Frontal, Axial, and Lateral) Parameters ---------- map : 3D ndarray The activation map, as a 3D image. affine : 4x4 ndarray The affine matrix going from image voxel space to MNI space. cut_coords: None, or a tuple of floats The MNI coordinates of the point where the cut is performed, in MNI coordinates and order. If slicer is 'ortho', this should be a 3-tuple: (x, y, z) For slicer == 'x', 'y', or 'z', then these are the coordinates of each cut in the corresponding direction. If None is given, the cuts is calculated automaticaly. anat : 3D ndarray or False, optional The anatomical image to be used as a background. If None, the MNI152 T1 1mm template is used. If False, no anat is displayed. anat_affine : 4x4 ndarray, optional The affine matrix going from the anatomical image voxel space to MNI space. This parameter is not used when the default anatomical is used, but it is compulsory when using an explicite anatomical image. slicer: {'ortho', 'x', 'y', 'z'} Choose the direction of the cuts. With 'ortho' three cuts are performed in orthogonal directions figure : integer or matplotlib figure, optional Matplotlib figure used or its number. If None is given, a new figure is created. axes : matplotlib axes or 4 tuple of float: (xmin, xmax, ymin, ymin), optional The axes, or the coordinates, in matplotlib figure space, of the axes used to display the plot. If None, the complete figure is used. title : string, optional The title dispayed on the figure. threshold : a number, None, or 'auto' If None is given, the maps are not thresholded. If a number is given, it is used to threshold the maps: values below the threshold are plotted as transparent. If auto is given, the threshold is determined magically by analysis of the map. annotate: boolean, optional If annotate is True, positions and left/right annotation are added to the plot. draw_cross: boolean, optional If draw_cross is True, a cross is drawn on the plot to indicate the cut plosition. do3d: {True, False or 'interactive'}, optional If True, Mayavi is used to plot a 3D view of the map in addition to the slicing. If 'interactive', the 3D visualization is displayed in an additional interactive window. threshold_3d: The threshold to use for the 3D view (if any). Defaults to the same threshold as that used for the 2D view. view_3d: tuple, The view used to take the screenshot: azimuth, elevation, distance and focalpoint, see the docstring of mlab.view. black_bg: boolean, optional If True, the background of the image is set to be black. If you whish to save figures with a black background, you will need to pass "facecolor='k', edgecolor='k'" to pylab's savefig. kwargs: extra keyword arguments, optional Extra keyword arguments passed to pylab.imshow Notes ----- Arrays should be passed in numpy convention: (x, y, z) ordered. Use masked arrays to create transparency: import numpy as np map = np.ma.masked_less(map, 0.5) plot_map(map, affine) """ map, affine = _xyz_order(map, affine) nan_mask = np.isnan(np.asarray(map)) if np.any(nan_mask): map = map.copy() map[nan_mask] = 0 del nan_mask # Deal with automatic settings of plot parameters if threshold == 'auto': # Threshold epsilon above a percentile value, to be sure that some # voxels are indeed threshold threshold = _fast_abs_percentile(map) + 1e-5 if do3d: try: try: from mayavi import version except ImportError: from enthought.mayavi import version if not int(version.version[0]) > 2: raise ImportError except ImportError: warnings.warn('Mayavi > 3.x not installed, plotting only 2D') do3d = False slicer = SLICERS[slicer].init_with_figure(data=map, affine=affine, threshold=threshold, cut_coords=cut_coords, figure=figure, axes=axes, black_bg=black_bg, leave_space=do3d) # Use Mayavi for the 3D plotting if do3d: from .maps_3d import plot_map_3d, m2screenshot try: from tvtk.api import tvtk except ImportError: from enthought.tvtk.api import tvtk version = tvtk.Version() offscreen = True if (version.vtk_major_version, version.vtk_minor_version) < (5, 2): offscreen = False if do3d == 'interactive': offscreen = False cmap = kwargs.get('cmap', pl.cm.cmap_d[pl.rcParams['image.cmap']]) # Computing vmin and vmax is costly in time, and is needed # later, so we compute them now, and store them for future # use vmin = kwargs.get('vmin', map.min()) kwargs['vmin'] = vmin vmax = kwargs.get('vmax', map.max()) kwargs['vmax'] = vmax try: from mayavi import mlab except ImportError: from enthought.mayavi import mlab if threshold_3d is None: threshold_3d = threshold plot_map_3d(np.asarray(map), affine, cut_coords=cut_coords, anat=anat, anat_affine=anat_affine, offscreen=offscreen, cmap=cmap, threshold=threshold_3d, view=view_3d, vmin=vmin, vmax=vmax) ax = slicer.axes.values()[0].ax.figure.add_axes((0.001, 0, 0.29, 1)) ax.axis('off') m2screenshot(mpl_axes=ax) if offscreen: # Clean up, so that the offscreen engine doesn't become the # default mlab.clf() engine = mlab.get_engine() try: from mayavi.core.registry import registry except: from enthought.mayavi.core.registry import registry for key, value in registry.engines.iteritems(): if value is engine: registry.engines.pop(key) break if threshold: map = np.ma.masked_inside(map, -threshold, threshold, copy=False) _plot_anat(slicer, anat, anat_affine, title=title, annotate=annotate, draw_cross=draw_cross) slicer.plot_map(map, affine, **kwargs) return slicer
def plot_anat_3d(anat=None, anat_affine=None, scale=1, sulci_opacity=0.5, gyri_opacity=0.3, opacity=None, skull_percentile=78, wm_percentile=79, outline_color=None): """ 3D anatomical display Parameters ---------- skull_percentile : float, optional The percentile of the values in the image that delimit the skull from the outside of the brain. The smaller the fraction of you field of view is occupied by the brain, the larger this value should be. wm_percentile : float, optional The percentile of the values in the image that delimit the white matter from the grey matter. Typical this is skull_percentile + 1 """ # Late import to avoid triggering wx imports before needed. try: from mayavi import mlab except ImportError: # Try out old install of Mayavi, with namespace packages from enthought.mayavi import mlab fig = mlab.gcf() disable_render = fig.scene.disable_render fig.scene.disable_render = True if anat is None: anat, anat_affine, anat_max = _AnatCache.get_anat() anat_blurred = _AnatCache.get_blurred() skull_threshold = 4800 inner_threshold = 5000 upper_threshold = 7227.8 else: from scipy import ndimage # XXX: This should be in a separate function voxel_size = np.sqrt((anat_affine[:3, :3]**2).sum() / 3.) skull_threshold = stats.scoreatpercentile(anat.ravel(), skull_percentile) inner_threshold = stats.scoreatpercentile(anat.ravel(), wm_percentile) upper_threshold = anat.max() anat_blurred = ndimage.gaussian_filter( (ndimage.morphology.binary_fill_holes( ndimage.gaussian_filter((anat > skull_threshold).astype( np.float), 6. / voxel_size) > 0.5)).astype(np.float), 2. / voxel_size).T.ravel() if opacity is None: try: from tvtk.api import tvtk except ImportError: # Try out old install of Mayavi, with namespace packages from enthought.tvtk.api import tvtk version = tvtk.Version() if (version.vtk_major_version, version.vtk_minor_version) < (5, 2): opacity = .99 else: opacity = 1 ########################################################################### # Display the cortical surface (flattenned) anat_src = affine_img_src(anat, anat_affine, scale=scale, name='Anat') anat_src.image_data.point_data.add_array(anat_blurred) anat_src.image_data.point_data.get_array(1).name = 'blurred' anat_src.image_data.point_data.update() anat_blurred = mlab.pipeline.set_active_attribute(anat_src, point_scalars='blurred') anat_blurred.update_pipeline() # anat_blurred = anat_src cortex_surf = mlab.pipeline.set_active_attribute( mlab.pipeline.contour(anat_blurred), point_scalars='scalar') # XXX: the choice in vmin and vmax should be tuned to show the # sulci better cortex = mlab.pipeline.surface(cortex_surf, colormap='copper', opacity=opacity, vmin=skull_threshold, vmax=inner_threshold) cortex.enable_contours = True cortex.contour.filled_contours = True cortex.contour.auto_contours = False cortex.contour.contours = [0, inner_threshold, upper_threshold] #cortex.actor.property.backface_culling = True # XXX: Why do we do 'frontface_culling' to see the front. cortex.actor.property.frontface_culling = True cortex.actor.mapper.interpolate_scalars_before_mapping = True cortex.actor.property.interpolation = 'flat' # Add opacity variation to the colormap cmap = cortex.module_manager.scalar_lut_manager.lut.table.to_array() cmap[128:, -1] = gyri_opacity * 255 cmap[:128, -1] = sulci_opacity * 255 cortex.module_manager.scalar_lut_manager.lut.table = cmap if outline_color is not None: outline = mlab.pipeline.iso_surface(anat_blurred, contours=[0.4], color=outline_color, opacity=.9) outline.actor.property.backface_culling = True fig.scene.disable_render = disable_render return cortex
""" An object to register callbacks and dispatch event wiring mouse clicks on a scene to picking. """ # ETS imports from traits.api import HasTraits, Dict, Instance, \ Enum, Int, Callable, on_trait_change, List, Tuple, WeakRef from mayavi.core.scene import Scene from tvtk.api import tvtk VTK_VERSION = tvtk.Version().vtk_major_version \ + .1*tvtk.Version().vtk_minor_version ################################################################################ # class `MousePickDispatcher` ################################################################################ class MousePickDispatcher(HasTraits): """ An event dispatcher to send pick event on mouse clicks. This objects wires VTK observers so that picking callbacks can be bound to mouse click without movement. The object deals with adding and removing the VTK-level callbacks. """ # The scene events are wired to. scene = WeakRef(Scene)
# Author: Prabhu Ramachandran <*****@*****.**> # Copyright (c) 2005, Enthought, Inc. # License: BSD Style. # Enthought library imports. from traits.api import Instance, Range, Str, Bool, Property, \ Float from traitsui.api import View, Group, Item, InstanceEditor from tvtk.api import tvtk from apptools.persistence import state_pickler # Local imports from mayavi.core.module import Module from mayavi.core.pipeline_info import PipelineInfo VTK_VER = float(tvtk.Version().vtk_version[:3]) ###################################################################### # `Text` class. ###################################################################### class Text(Module): # The version of this class. Used for persistence. __version__ = 0 # The tvtk TextActor. actor = Instance(tvtk.TextActor, allow_none=False, record=True) # The property of the axes (color etc.). property = Property(record=True)