Exemplo n.º 1
0
class TestEngineManager(unittest.TestCase):
    @patch_backend("test")
    def test_get_engine_backend_test(self):
        self.assertIsInstance(get_engine(), NullEngine)

    @patch_backend("envisage")
    @patch_registry_engines({"EnvisageEngine1": EnvisageEngine()})
    def test_get_engine_backend_envisage(self):
        self.assertIs(type(get_engine()), EnvisageEngine)

    @patch_backend("simple")
    @patch_registry_engines({"Engine1": NullEngine()})
    def test_get_engine_backend_simple_with_existing_engine(self):
        self.assertIs(type(get_engine()), Engine)

    @patch_backend("auto")
    @patch_registry_engines({"Engine1": EnvisageEngine()})
    def test_get_engine_backend_auto_with_existing_engine(self):
        self.assertIs(type(get_engine()), EnvisageEngine)

    @patch_backend("envisage")
    @patch_registry_engines({"EnvisageEngine1": EnvisageEngine()})
    @patch_offscreen(True)
    def test_get_engine_offscreen_backend_envisage(self):
        self.assertIs(type(get_engine()), EnvisageEngine)

    @patch_backend("test")
    @patch_offscreen(True)
    def test_get_engine_offscreen_backend_test(self):
        self.assertIs(type(get_engine()), NullEngine)

    @patch_backend("auto")
    @patch_offscreen(True)
    @patch_registry_engines({"Engine1": Engine()})
    def test_get_engine_offscreen_backend_auto_with_existing_engine(self):
        self.assertIs(type(get_engine()), OffScreenEngine)

    @patch_backend("auto")
    @patch_offscreen(True)
    @patch_registry_engines({"Engine1": Engine()})
    def test_get_engine_offscreen_backend_auto_switched_twice(self):
        self.assertIs(type(get_engine()), OffScreenEngine)
        # Now OffScreenEngine is the last used engine
        # if offscreen is switched back to False
        # get_engine should not return an OffScreenEngine
        from mayavi.tools.engine_manager import options
        options.offscreen = False
        self.assertIs(type(get_engine()), Engine)

    @patch_backend("simple")
    @patch_offscreen(True)
    @patch_registry_engines({"Engine1": Engine()})
    def test_get_engine_offscreen_backend_simple_with_started_engine(self):
        self.assertIs(type(get_engine()), OffScreenEngine)
Exemplo n.º 2
0
    def startMayavi(self):
        ''' initialise the Mayavi figure for plotting '''

        # start the engine
        from mayavi.api import Engine
        self.engine = Engine()
        self.engine.start()

        # create a Mayavi figure
        self.mfig = mlab.figure(bgcolor=(
            1.,
            1.,
            1.,
        ),
                                fgcolor=(0., 0., 0.),
                                engine=self.engine,
                                size=(1500, 1500))

        # holders for plot objects
        self.brainNodePlots = {}
        self.brainEdgePlots = {}
        self.skullPlots = {}
        self.isosurfacePlots = {}

        # autolabel for plots
        self.labelNo = 0
Exemplo n.º 3
0
    def startMayavi(self,bg):
        ''' initialise the Mayavi figure for plotting '''        
        
        # start the engine
        from mayavi.api import Engine
        self.engine = Engine()
        self.engine.start()
        
        if not bg:
            bg=(1., 1., 1.)
        
        # create a Mayavi figure
        self.mfig = mlab.figure(bgcolor = bg,
                                fgcolor = (0, 0, 0),
                                engine = self.engine,
                                size=(1500, 1500))
        
        # holders for plot objects
        self.brainNodePlots = {}
        self.brainEdgePlots = {}
        self.skullPlots = {}
        self.isosurfacePlots = {}
        
        # record order of plots
        self.plotKeys = []

        # autolabel for plots
        self.labelNo = 0         
Exemplo n.º 4
0
    def show_gaussians(self, scale=1.0, r=1.0, show=True):
        """Show clusters as ellipsoids.
        
        :param float scale: Number of standard deviations to show
        :param float r: Thickness of the tubes used to represent
            the unit cell
        :param bool show: If True mlab.show() is executed
        """
        from mayavi.api import Engine
        from mayavi import mlab
        engine = Engine()
        engine.start()
        scene = engine.new_scene()
        scene.scene.disable_render = True  # for speed
        surfs = []
        self._draw_cell(r=r)
        for gauss in self.gaussians:
            surf = self._show_one_gaussian(gauss, engine, scale=scale)
            surfs.append(surf)

        scene.scene.disable_render = False
        for i, surf in enumerate(surfs):
            vtk_srcs = mlab.pipeline.get_vtk_src(surf)
            vtk_src = vtk_srcs[0]
            npoints = len(vtk_src.point_data.scalars)
            vtk_src.point_data.scalars = np.tile(i, npoints)

        if show:
            mlab.show()
Exemplo n.º 5
0
 def __init__(self, polymer_coordinates, color_scheme='dark'):
     self.engine = Engine()
     self.engine.start()
     self.engine.new_scene()
     self.scene = self.engine.current_scene
     assert color_scheme in ('dark', 'light')  # we right now only have two color schemes
     self.color_scheme = color_scheme
     self.polymer_coordinates = polymer_coordinates
     self.L = self.get_polymer_length()
     self.set_colors()
     self.make_new_fig()
Exemplo n.º 6
0
class Visualization(HasTraits):
    """mayavi application"""
    scene = Instance(MlabSceneModel, ())
    try:
        engine = mayavi.engine
    except:
        from mayavi.api import Engine
        engine = Engine()
        engine.start()

    def __init__(self, ycube):
        self.ycube = ycube
        self.initialize = True
        self.update_plot()

        self.plane1 = self.engine.scenes[0].children[0].children[0].children[0]
        self.plane2 = self.engine.scenes[0].children[0].children[0].children[1]
        self.iso_surface = self.engine.scenes[0].children[0].children[
            0].children[2]

    def show_iso(self, check_state):
        self.iso_surface.actor.actor.visibility = check_state

    def show_plane1(self, check_state):
        self.plane1.actor.actor.visibility = check_state
        self.plane1.implicit_plane.widget.enabled = check_state

    def show_plane2(self, check_state):
        self.plane2.actor.actor.visibility = check_state
        self.plane2.implicit_plane.widget.enabled = check_state

    @on_trait_change('scene.activated')
    def update_plot(self):
        data = self.ycube
        scalar_field_data = self.scene.mlab.pipeline.scalar_field(data)
        self.scene.mlab.pipeline.scalar_cut_plane(scalar_field_data,
                                                  plane_orientation='y_axes')

        self.scene.mlab.pipeline.scalar_cut_plane(scalar_field_data,
                                                  plane_orientation='z_axes')
        self.scene.mlab.pipeline.iso_surface(scalar_field_data)

        self.scene.mlab.outline()

    view = View(
        Item('scene',
             editor=SceneEditor(scene_class=MayaviScene),
             height=250,
             width=300,
             show_label=False),
        resizable=True  # We need this to resize with the parent widget
    )
Exemplo n.º 7
0
def mayavi_plot(xlmc, ylmc, zlmc, rho, angle, figname):
    engine = Engine()
    engine.start()
    fig = mlab.figure(bgcolor=(0.0, 0.0, 0.0))

    #mlab.plot3d(, x_sat[:111]-x_gal[:111]+2.5, z_sat[:111]-z_gal[:111]+2.5,
    #            np.ones(len(x_sat[:111])), color=(1,0,0), line_width=200,
    #            tube_radius=2, opacity=1)

    tt = mlab.contour3d(rho,
                        opacity=0.5,
                        extent=[-300, 300, 300, 300, -300, 300],
                        transparent=True,
                        colormap='Spectral',
                        vmin=-0.5,
                        vmax=0.6)
    #mlab.colorbar()

    scene = engine.scenes[0]
    iso_surface = scene.children[0].children[0].children[0]

    # the following line will print you everything that you can modify on that object
    iso_surface.contour.print_traits()

    # now let's modify the number of contours and the min/max
    # you can also do these steps manually in the mayavi pipeline editor
    iso_surface.compute_normals = False  # without this only 1 contour will be displayed
    iso_surface.contour.number_of_contours = 15
    iso_surface.contour.minimum_contour = 0.6
    iso_surface.contour.maximum_contour = -0.5

    lut = tt.module_manager.scalar_lut_manager.lut.table.to_array()
    ilut = lut[::-1]
    # putting LUT back in the surface object
    tt.module_manager.scalar_lut_manager.lut.table = ilut
    #tt.actor.actor.rotate_z(270)
    #mlab.roll(270)
    #limits

    mlab.view(azimuth=angle, distance=1200)

    #zz = mlab.plot3d(xlmc, ylmc, zlmc,
    #                 np.ones(len(xlmc))*200, line_width=200, tube_radius=2, color=(1,1,1), opacity=1)

    mlab.savefig(figname, size=(400, 400))
    mlab.close()
    engine.stop()
Exemplo n.º 8
0
def mayavi_init():
    try:
        engine = mayavi.engine
    except NameError:
        from mayavi.api import Engine
        engine = Engine()
        engine.start()
    if len(engine.scenes) == 0:
        engine.new_scene(size=(600, 800))
    scene = engine.scenes[0]
    fig = mlab.gcf(engine)
    mlab.figure(figure=fig,
                bgcolor=(1.0, 1.0, 1.0),
                fgcolor=(0.0, 0.0, 0.0),
                engine=engine)

    return engine
Exemplo n.º 9
0
def view3d(sgrid):
    from mayavi.sources.vtk_data_source import VTKDataSource
    from mayavi.modules.api import Outline, GridPlane
    from mayavi.api import Engine
    from mayavi.core.ui.engine_view import EngineView
    e=Engine()
    e.start()
    s = e.new_scene()
     # Do this if you need to see the MayaVi tree view UI.
    ev = EngineView(engine=e)
    ui = ev.edit_traits()

#    mayavi.new_scene()
    src = VTKDataSource(data=sgrid)
    e.add_source(src)
    e.add_module(Outline())
    g = GridPlane()
    g.grid_plane.axis = 'x'
    e.add_module(g)
Exemplo n.º 10
0
def tresdeizar(X, Y, anchox, anchoy, angulo):
    engine = Engine()
    engine.start()
    scene = engine.new_scene()
    scene.scene.disable_render = True  # for speed

    visual.set_viewer(scene)

    surfaces = []
    for k in range(0, len(X)):
        source = ParametricSurface()
        source.function = 'ellipsoid'
        engine.add_source(source)

        surface = Surface()
        source.add_module(surface)

        actor = surface.actor  # mayavi actor, actor.actor is tvtk actor

        actor.property.opacity = 0.7
        actor.property.color = (0, 0, 1)  # tuple(np.random.rand(3))
        actor.mapper.scalar_visibility = False  # don't colour ellipses by their scalar indices into colour map

        actor.actor.orientation = np.array([90, angulo[k], 0
                                            ])  #* 90 #(angulo[k]) # in degrees

        actor.actor.position = np.array([X[k], Y[k], 0])
        actor.actor.scale = np.array(
            [anchox[k] / 2, anchox[k] / 2, anchoy[k] / 2])

        surfaces.append(surface)

        source.scene.background = (1.0, 1.0, 1.0)

    CellScann.set_img_3deizada(mlab)
    return mlab.show()
Exemplo n.º 11
0
def getFrames(pathThresh, pathSkel, totalTime, fps=24, totalRotation=360):
    """
    Return 3 vertex clique removed graph
    Parameters
    ----------
    pathThresh : str
        path of the .npy thresholded 3D Volume

    pathSKel : str
        path of the .npy skeleton 3D Volume

    totalTime : integer
        in seconds, duration of the video

    fps : integer
        frames per second, number of input frames per second

    totalRotation : integer
        angle in degrees frames should be captured in, integer between 0 and 360

    Returns
    -------
    frames of png images in the same directory as pathThresh
        mayavi scenes are saved as png images at different
        angle of rotations as anim%i.png i is the ith frame

    Notes
    -----
    threshold and skeletonized volume are overlapped,
    they need not be of the same size, but assuming they are
    for the same volume it asserted that they are of same size
    thresholded volume's isosurface is transparent and
    in grey and the skeletonized volume can be seen through
    it and is in red
    totalRotation can be any angle but it will be adjusted between 0 and
    360 using the % (modulus) operator
    """
    # modulus of totalRotation
    totalRotation = totalRotation % 360
    # total frames
    totalFrameCount = fps * totalTime
    # degree of rotation after each frame
    degreePerFrame = totalRotation / totalFrameCount
    # load the threshold and skeleton paths
    threshold = np.load(pathThresh)
    skeleton = np.load(pathSkel)
    assertionStr = "threshold and skeleton  must be of same shape"
    assert threshold.shape == skeleton.shape, (assertionStr, threshold.shape, skeleton.shape)
    mayaviEngine = Engine()
    mayaviEngine.start()
    # Create a new mayavi scene.
    mayaviScene = mayaviEngine.new_scene()
    mayaviScene.scene.background = WHITEBACKGROUND
    # thresholded image in transparent grey
    thresholdScene = mlab.contour3d(np.uint8(threshold), colormap='gray', contours=THRESHOLDCONTOURLIST)
    thresholdScene.actor.property.opacity = THRESHOLDSCENEOPACITY
    # skeleton in red
    f = mlab.contour3d(np.uint8(skeleton), contours=SKELETONCONTOURLIST)
    f.actor.property.representation = 'points'
    f.actor.property.point_size = POINTSSIZE
    mlab.options.offscreen = True
    mlab.outline(f).actor.property.color = BOUNDINGBOXCOLOR
    # extract rootDir of pathThresh
    rootDir = os.path.split(pathThresh)[0] + os.sep
    # Make an animation:
    for i in range(totalFrameCount):
        # Rotate the camera by 10 degrees.
        mayaviScene.scene.camera.azimuth(degreePerFrame)
        mayaviScene.scene.camera.elevation(ELEVATIONANGLE)
        # Resets the camera clipping plane so everything fits and then
        # renders.
        mayaviScene.scene.reset_zoom()
        # Save the scene. magnification=4 gives saves as an image when seen in fullscreen
        mayaviScene.scene.magnification = 4
        mayaviScene.scene.save(rootDir + "anim%d.png" % i)
from math import *

# Import the useful routines
import read_off
import surface_pre_computations
import geodesic_surface_congested
import cut_off

# To plot graph
import matplotlib.pyplot as plt

# To plot triangulated surfaces
from mayavi import mlab
from mayavi.api import Engine

engine = Engine()
engine.start()

# -----------------------------------------------------------------------------------------------
# Parameters
# -----------------------------------------------------------------------------------------------

# Discretization of the starting [0,1] (for the centered grid)
nTime = 31

# Name of the file in which is stored the triangulated surface D
nameFileD = os.path.join("meshes", "face_vector_field_319.off")

# Parameter epsilon to regularize the Laplace problem
eps = 0.0 * 10**(-8)
Exemplo n.º 13
0
    def plot(self):
        '''
        Plot a 3D visualisation of the Voronoi grid using mayavi.

        This method requires mayavi to be installed and also needs the vertices
        information to be available (see the class constructor).

        Note that in order for this method to work in an interactive IPython session,
        a series of environment variables and proper switches need to be used
        depending on your system configuration. For instance, on a Linux machine
        with PyQt4 and a recent IPython version, the following bash startup
        command for IPython can be used:
        ``ETS_TOOLKIT=qt4 QT_API=pyqt ipython --gui=qt4``
        This sets both the mayavi and the IPython GUI toolkit to qt4, and the ``QT_API``
        variable is used to specify that we want the ``pyqt`` API (as opposed to the
        ``pyside`` alternative API - PySide is an alternative implementation of PyQt).

        It should be possible to get this method working on different configurations,
        but the details will be highly system-dependent.
        '''

        if not self._with_vertices:
            raise ValueError(
                'the class must be constructed with \'with_vertices=True\' in order to support plotting'
            )

        import numpy as np
        try:
            from tvtk.api import tvtk
            from mayavi.api import Engine
            from mayavi import mlab
            from mayavi.sources.vtk_data_source import VTKDataSource
            from mayavi.modules.surface import Surface
            from mayavi.modules.scalar_cut_plane import ScalarCutPlane
        except ImportError:
            raise ImportError(
                'the plot method requires Mayavi, please make sure it is correctly installed'
            )

        # Shortcut.
        vertices = self._neighbours_table['vertices']

        # This is a list of all the vertices composing all voronoi cells.
        # points = [[x1,y1,z1],[x2,y2,z2],...]
        points = []
        # Array to describe each voronoi cell in terms of the points list above. E.g.,
        # cells = [4,0,1,2,3,5,4,5,6,7,8]
        # This describes two cells, the first with 4 vertices whose indices in the points array
        # are 0,1,2,3, the second with 5 vertices whose indices are 4,5,6,7,8.
        cells = []
        cur_cell_idx = 0
        # Indices in the cells array where each new cell starts. In the example above,
        # offset = [0,5]
        offset = []
        cur_offset = 0
        # Array of cell types. Cells will all be of the same type.
        cell_types = []

        # Build the above quantities.
        for v in vertices:
            # Drop the empty vertices coordinates, signalled by NaN.
            arr = v[~np.isnan(v)]
            assert (len(arr) % 3 == 0)
            tmp = np.split(arr, len(arr) / 3)
            # Append the vertices.
            points = points + tmp
            # Append the cell description.
            cells = cells + \
                [len(tmp)] + range(cur_cell_idx, cur_cell_idx + len(tmp))
            cur_cell_idx += len(tmp)
            # Append the offset info.
            offset.append(cur_offset)
            cur_offset += len(tmp) + 1
            # Append the cell type.
            cell_types.append(tvtk.ConvexPointSet().cell_type)

        # Cache the sites' positions.
        sites_arr = self._neighbours_table['coordinates']

        # Setup the Mayavi engine and figure.
        e = Engine()
        e.start()
        fig = mlab.figure(engine=e)

        # Plot the sites.
        mlab.points3d(sites_arr[:, 0],
                      sites_arr[:, 1],
                      sites_arr[:, 2],
                      figure=fig)

        # Plot the cells with coloured surfaces.
        # This is just an array of scalars to assign a "temperature" to each cell vertex, which will be
        # used for coloring purposes.
        temperature = np.arange(0, len(points) * 10, 10, 'd')
        # Initialise the array of cells.
        cell_array = tvtk.CellArray()
        cell_array.set_cells(len(vertices), np.array(cells))
        # Initialise the unstructured grid object.
        ug = tvtk.UnstructuredGrid(points=np.array(points))
        ug.set_cells(np.array(cell_types), np.array(offset), cell_array)
        ug.point_data.scalars = temperature
        ug.point_data.scalars.name = 'temperature'
        # Create a data source from the unstructured grid object.
        src = VTKDataSource(data=ug)
        # Add the source to the engine.
        e.add_source(src)
        # Create a surface object with opacity 0.5
        surf = Surface()
        surf.actor.property.opacity = 0.5
        # Add the surface object to the engine.
        e.add_module(surf)
        # Add a cut plane as well.
        e.add_module(ScalarCutPlane())

        # Create another representation of the grid, this time using only white wireframe
        # to highlight to shape of the cells.
        # Rebuild the ug.
        ug = tvtk.UnstructuredGrid(points=np.array(points))
        ug.set_cells(np.array(cell_types), np.array(offset), cell_array)
        src = VTKDataSource(data=ug)
        e.add_source(src)
        surf = Surface()
        surf.actor.property.representation = 'wireframe'
        e.add_module(surf)
        cp = ScalarCutPlane()
        e.add_module(cp)
Exemplo n.º 14
0
    def view(prefix, name):
        """
        construct a generic visualization of base mesh, refined mesh,
        and potential/field/pseudopotential data in mayavi2
        requires running within mayavi2 or ipython with threads or
        something like::

            from pyface.api import GUI
            GUI().start_event_loop()

        in your script to interact with it.

        this is from a simplified macro recorded in mayavi2
        """
        try:
            engine = mayavi.engine
        except NameError:
            from mayavi.api import Engine
            engine = Engine()
            engine.start()

        if len(engine.scenes) == 0:
            engine.new_scene()

        scene = engine.scenes[0]

        base_mesh_name = "%s_mesh.vtk" % prefix
        if os.access(base_mesh_name, os.R_OK):
            base_mesh = engine.open(base_mesh_name)
            surface = Surface()
            engine.add_filter(surface, base_mesh)
            surface.actor.property.representation = 'wireframe'
            surface.actor.property.line_width = 1

        mesh_name = "%s_%s_mesh.vtk" % (prefix, name)
        if os.access(mesh_name, os.R_OK):
            mesh = engine.open(mesh_name)
            mesh.cell_scalars_name = 'charge'
            surface = Surface()
            engine.add_filter(surface, mesh)
            module_manager = mesh.children[0]
            module_manager.scalar_lut_manager.lut_mode = 'RdBu'
            module_manager.scalar_lut_manager.use_default_range = False
            r = np.fabs(module_manager.scalar_lut_manager.data_range).max()
            module_manager.scalar_lut_manager.data_range = [-r, r]
            surface.actor.property.backface_culling = True

        data_name = "%s_%s.vtk" % (prefix, name)
        if os.access(data_name, os.R_OK):
            data = engine.open(data_name)
            if "pseudo_potential" in data._point_scalars_list:
                data.point_scalars_name = "pseudo_potential"
            else:
                data.point_scalars_name = "potential"
            iso_surface = IsoSurface()
            engine.add_filter(iso_surface, data)
            module_manager = data.children[0]
            module_manager.scalar_lut_manager.lut_mode = 'Greys'
            iso_surface.contour.auto_contours = True
            iso_surface.contour.number_of_contours = 5
            try:
                iso_surface.contour.maximum_contour = 1e-2
            except:
                pass

        scene.scene.isometric_view()
        scene.scene.render()
Exemplo n.º 15
0
    def view(prefix, name):
        """
        construct a generic visualization of base mesh, refined mesh,
        and potential/field/pseudopotential data in mayavi2
        requires running within mayavi2 or ipython with threads or
        something like::

            from pyface.api import GUI
            GUI().start_event_loop()

        in your script to interact with it.

        this is from a simplified macro recorded in mayavi2
        """
        """
        wwc 11/23/2018
        In both python 2.7 and 3.5, this 3D visualization with mayavi 
        works in Linux, but it's not compatible with X11 remote forwarding. 
        Install mayavi through conda channel "menpo" in python 3.5 or just 
        see environment setup of "ele35" in README. However, I haven't 
        found a mayavi version for python 3.6.
        """

        import mayavi
        try:
            from mayavi.api import Engine
            engine = Engine()
            engine.start()
        except AttributeError: # NameError:
            engine = mayavi.engine

        if len(engine.scenes) == 0:
            engine.new_scene()

        scene = engine.scenes[0]

        base_mesh_name = "%s_mesh.vtk" % prefix
        if os.access(base_mesh_name, os.R_OK):
            base_mesh = engine.open(base_mesh_name)
            surface = Surface()
            engine.add_filter(surface, base_mesh)
            surface.actor.property.representation = 'wireframe'
            surface.actor.property.line_width = 1

        mesh_name = "%s_%s_mesh.vtk" % (prefix, name)
        if os.access(mesh_name, os.R_OK):
            mesh = engine.open(mesh_name)
            mesh.cell_scalars_name = 'charge'
            surface = Surface()
            engine.add_filter(surface, mesh)
            module_manager = mesh.children[0]
            module_manager.scalar_lut_manager.lut_mode = 'RdBu'
            module_manager.scalar_lut_manager.use_default_range = False
            r = np.fabs(module_manager.scalar_lut_manager.data_range).max()
            module_manager.scalar_lut_manager.data_range = [-r, r]
            surface.actor.property.backface_culling = True

        data_name = "%s_%s.vtk" % (prefix, name)
        if os.access(data_name, os.R_OK):
            data = engine.open(data_name)
            if "pseudo_potential" in data._point_scalars_list:
                data.point_scalars_name = "pseudo_potential"
            else:
                data.point_scalars_name = "potential"
            iso_surface = IsoSurface()
            engine.add_filter(iso_surface, data)
            module_manager = data.children[0]
            module_manager.scalar_lut_manager.lut_mode = 'Greys'
            iso_surface.contour.auto_contours = True
            iso_surface.contour.number_of_contours = 5
            try:
                iso_surface.contour.maximum_contour = 1e-2
            except:
                pass

        scene.scene.isometric_view()
        scene.scene.render()
Exemplo n.º 16
0
def plotIsosurfaces3D(x3D,
                      y3D,
                      z3D,
                      surface3Dlist,
                      contourList,
                      slice3Dlist=(None, ),
                      boundSurface=(None, ),
                      customColors=(None, ),
                      figDir='./',
                      name='UntitledIsosurface',
                      sliceOriantations=(None, ),
                      sliceOffsets=(None, ),
                      boundSlice=(None, ),
                      sliceValRange=(None, )):
    from mayavi import mlab
    from mayavi.modules.contour_grid_plane import ContourGridPlane
    from mayavi.modules.outline import Outline
    from mayavi.api import Engine
    import numpy as np
    from warnings import warn

    x3D, y3D, z3D = np.array(x3D), np.array(y3D), np.array(z3D)

    engine = Engine()
    engine.start()
    # if len(engine.scenes) == 0:
    #     engine.new_scene()

    if customColors[0] is not None:
        customColors = iter(customColors)
    else:
        customColors = iter(
            ('inferno', 'viridis', 'coolwarm', 'Reds', 'Blues') * 2)

    contourList = iter(contourList)
    if sliceOriantations[0] is not None:
        sliceOriantations = iter(sliceOriantations)
    else:
        sliceOriantations = iter(('z_axes', ) * len(slice3Dlist))

    if boundSurface[0] is None:
        boundSurface = (x3D.min(), x3D.max(), y3D.min(), y3D.max(), z3D.min(),
                        z3D.max())

    if boundSlice[0] is None:
        boundSlice = (x3D.min(), x3D.max(), y3D.min(), y3D.max(), z3D.min(),
                      z3D.max())

    if sliceOffsets[0] is None:
        sliceOffsets = iter((0, ) * len(slice3Dlist))
    else:
        sliceOffsets = iter(sliceOffsets)

    if sliceValRange[0] is None:
        sliceValRange = iter((None, None) * len(slice3Dlist))
    else:
        sliceValRange = iter(sliceValRange)

    mlab.figure(name,
                engine=engine,
                size=(1200, 900),
                bgcolor=(1, 1, 1),
                fgcolor=(0.5, 0.5, 0.5))

    for surface3D in surface3Dlist:
        color = next(customColors)
        # If a colormap given
        if isinstance(color, str):
            mlab.contour3d(x3D,
                           y3D,
                           z3D,
                           surface3D,
                           contours=next(contourList),
                           colormap=color,
                           extent=boundSurface)
        # If only one color of (0-1, 0-1, 0-1) given
        else:
            mlab.contour3d(x3D,
                           y3D,
                           z3D,
                           surface3D,
                           contours=next(contourList),
                           color=color,
                           extent=boundSurface)

        # cgp = ContourGridPlane()
        # engine.add_module(cgp)
        # cgp.grid_plane.axis = 'y'
        # cgp.grid_plane.position = x3D.shape[1] - 1
        # cgp.contour.number_of_contours = 20
        # # contour_grid_plane2.actor.mapper.scalar_range = array([298., 302.])
        # # contour_grid_plane2.actor.mapper.progress = 1.0
        # # contour_grid_plane2.actor.mapper.scalar_mode = 'use_cell_data'
        # cgp.contour.filled_contours = True
        # cgp.actor.property.lighting = False

    for slice3D in slice3Dlist:
        sliceOriantation = next(sliceOriantations)
        sliceOffset = next(sliceOffsets)
        if sliceOriantation == 'z_axes':
            origin = np.array([boundSlice[0], boundSlice[2], sliceOffset])
            point1 = np.array([boundSlice[1], boundSlice[2], sliceOffset])
            point2 = np.array([boundSlice[0], boundSlice[3], sliceOffset])
        elif sliceOriantation == 'x_axes':
            origin = np.array([sliceOffset, boundSlice[2], boundSlice[4]])
            point1 = np.array([sliceOffset, boundSlice[3], boundSlice[4]])
            point2 = np.array([sliceOffset, boundSlice[2], boundSlice[5]])
        else:
            origin = np.array([boundSlice[0], sliceOffset, boundSlice[4]])
            point1 = np.array([boundSlice[1], sliceOffset, boundSlice[4]])
            point2 = np.array([boundSlice[0], sliceOffset, boundSlice[5]])

        image_plane_widget = mlab.volume_slice(
            x3D,
            y3D,
            z3D,
            slice3D,
            plane_orientation=sliceOriantation,
            colormap=next(customColors),
            vmin=next(sliceValRange),
            vmax=next(sliceValRange))
        image_plane_widget.ipw.reslice_interpolate = 'cubic'
        image_plane_widget.ipw.origin = origin
        image_plane_widget.ipw.point1 = point1
        image_plane_widget.ipw.point2 = point2
        # image_plane_widget.ipw.slice_index = 2
        image_plane_widget.ipw.slice_position = sliceOffset

    # Contour grid plane at last y if the last slice is in xy plane
    if sliceOriantation == 'z_axes':
        cgp2 = ContourGridPlane()
        engine.add_module(cgp2)
        cgp2.grid_plane.axis = 'y'
        cgp2.grid_plane.position = x3D.shape[1] - 1
        cgp2.contour.number_of_contours = 20
        cgp2.contour.filled_contours = True
        cgp2.actor.property.lighting = False

    outline = Outline()
    engine.add_module(outline)
    outline.actor.property.color = (0.2, 0.2, 0.2)
    outline.bounds = np.array(boundSurface)
    outline.manual_bounds = True

    mlab.view(azimuth=270, elevation=45)
    mlab.move(-500, 0, 0)
    mlab.savefig(figDir + '/' + name + '.png', magnification=3)
    print('\nFigure ' + name + ' saved at ' + figDir)
    mlab.show()
Exemplo n.º 17
0
    def __init__(self,
                 a,
                 b,
                 c,
                 alpha=90,
                 beta=90,
                 gamma=90,
                 basis=[0, 0, 0],
                 HKL_normal=[0, 0, 1],
                 HKL_para_x=[1, 0, 0],
                 offset_angle=0,
                 energy_keV=22.5):
        self.a = a
        self.b = b
        self.c = c
        self.alpha = np.deg2rad(alpha)
        self.beta = np.deg2rad(beta)
        self.gamma = np.deg2rad(gamma)
        self.energy_keV = energy_keV
        self.k0 = id03.get_K_0(energy_keV)
        self.basis = basis  # list of [Atomic_form_factor, x, y, z]
        for i in xrange(len(self.basis)):
            if (isinstance(self.basis[i][0], basestring)):
                f1, f2 = elements.symbol(
                    self.basis[i][0]).xray.scattering_factors(
                        energy=energy_keV)
                self.basis[i][0] = f1 + 1.j * f2
        self.HKL_normal = HKL_normal
        self.HKL_para_x = HKL_para_x

        # calculate real space unit cell vectors
        self.A1 = np.array([self.a, 0, 0])
        self.A2 = np.array(
            [self.b * np.cos(self.gamma), b * np.sin(self.gamma), 0])
        A31 = self.c * np.cos(self.alpha)
        A32 = self.c / np.sin(self.gamma) * (
            np.cos(self.beta) - np.cos(self.gamma) * np.cos(self.alpha))
        A33 = np.sqrt(self.c**2 - A31**2 - A32**2)
        self.A3 = np.array([A31, A32, A33])
        self.RealTM = np.array([[self.A1[0], self.A2[0], self.A3[0]],
                                [self.A1[1], self.A2[1], self.A3[1]],
                                [self.A1[2], self.A2[2], self.A3[2]]])

        #TODO: remove
        if (0):
            from mayavi import mlab
            try:
                engine = mayavi.engine
            except NameError:
                from mayavi.api import Engine
                engine = Engine()
                engine.start()
            if len(engine.scenes) == 0:
                engine.new_scene(size=(600, 800))
            scene = engine.scenes[0]
            fig = mlab.gcf(engine)
            mlab.figure(figure=fig,
                        bgcolor=(1.0, 1.0, 1.0),
                        fgcolor=(0.0, 0.0, 0.0),
                        engine=engine)

            hkls = [[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0], [0, 0, 1],
                    [1, 0, 1], [0, 1, 1], [1, 1, 1]]
            lines = [[0, 1], [0, 2], [0, 4], [5, 1], [5, 4], [5, 7], [3, 1],
                     [3, 2], [3, 7], [6, 4], [6, 2], [6, 7]]
            for line in lines:
                xyz1 = self.RealTM.dot(hkls[line[0]])
                xyz2 = self.RealTM.dot(hkls[line[1]])

                mlab.plot3d([xyz1[0], xyz2[0]], [xyz1[1], xyz2[1]],
                            [xyz1[2], xyz2[2]])

            mlab.show()

        # calculate reciprocal space unit cell vectors
        self._V_real = self.A1.dot(np.cross(self.A2, self.A3))
        self.B1 = 2 * np.pi * np.cross(self.A2, self.A3) / self._V_real
        self.B2 = 2 * np.pi * np.cross(self.A3, self.A1) / self._V_real
        self.B3 = 2 * np.pi * np.cross(self.A1, self.A2) / self._V_real
        self.RecTM = np.array([[self.B1[0], self.B2[0], self.B3[0]],
                               [self.B1[1], self.B2[1], self.B3[1]],
                               [self.B1[2], self.B2[2], self.B3[2]]])

        self._V_rec = self.B1.dot(np.cross(self.B2, self.B3))

        # align surface normal to z axis
        q_normal = self.q(HKL_normal)
        q_normal /= np.sqrt(q_normal.dot(q_normal))
        z = np.array([0, 0, 1])
        v = np.cross(q_normal, z)
        I = np.zeros((3, 3))
        I[0, 0] = 1
        I[1, 1] = 1
        I[2, 2] = 1
        R = np.zeros((3, 3))
        if (v[0] == 0 and v[1] == 0 and v[2] == 0):
            R = I  # unit matrix
        elif (q_normal[0] == 0 and q_normal[1] == 0 and q_normal[2] == -1):
            R = np.array([[1, 0, 0], [0, -1, 0],
                          [0, 0, -1]])  # rotation by 180deg around x
        else:
            vx = np.array([[0, -v[2], v[1]], [v[2], 0, -v[0]],
                           [-v[1], v[0], 0]])
            R = I + vx + vx.dot(vx) / (1. + q_normal.dot(z))

        self.RecTM = R.dot(self.RecTM)

        # align projection of HKL_para_x to x axis
        q = self.q(HKL_para_x)
        rot = -np.arctan2(q[1], q[0]) + np.deg2rad(offset_angle)
        R = np.array([[np.cos(rot), -np.sin(rot), 0],
                      [np.sin(rot), np.cos(rot), 0], [0, 0, 1]])
        self.RecTM = R.dot(self.RecTM)

        self.RecTMInv = inv(self.RecTM)
def draw(vtk_files,
         coords_file,
         conn_list=None,
         brain_rgba=(0.5, 0.5, 0.5, 0.2),
         node_rgba=(0.30, 0.69, 1.0, 1.0),
         node_rad=2.5,
         conn_thr=[0.75, 1.0],
         conn_cmap='YlOrRd'):

    ### Setup the engine and scene
    my_engine = Engine()
    my_engine.start()

    # Create a new scene
    my_scene = my_engine.new_scene()

    # Set background
    my_scene.scene.background = (1.0, 1.0, 1.0)

    # Initialize the rendering
    my_scene.scene.disable_render = True

    # Import VTK file to pipeline
    for vtk_file in vtk_files:
        vtk_source = my_engine.open(vtk_file)

        # Render surface
        vtk_surface = Surface()
        my_engine.add_module(vtk_surface, obj=vtk_source)
        vtk_surface.actor.property.specular_color = brain_rgba[:3]
        vtk_surface.actor.property.diffuse_color = brain_rgba[:3]
        vtk_surface.actor.property.ambient_color = brain_rgba[:3]
        vtk_surface.actor.property.color = brain_rgba[:3]
        vtk_surface.actor.property.opacity = brain_rgba[3]

    # Reset camera
    my_scene.scene.disable_render = False
    my_scene.scene.reset_zoom()

    ### Sensor-Locations
    # Load Coordinates in MRI-space
    node_coords = np.loadtxt(coords_file, delimiter=',')
    n_node = node_coords.shape[0]
    n_conn = np.int(n_node * (n_node - 1) * 0.5)

    # Import coordinates into pipeline
    crd_source = mlab.pipeline.scalar_scatter(node_coords[:, 0],
                                              node_coords[:, 1],
                                              node_coords[:, 2])
    # Render Glyphs for node points
    crd_surface = mlab.pipeline.glyph(crd_source,
                                      scale_mode='none',
                                      scale_factor=node_rad,
                                      mode='sphere',
                                      colormap='cool',
                                      color=node_rgba[:3],
                                      opacity=node_rgba[3])

    ### Connection-Locations
    if conn_list is None:
        return
    assert len(conn_list) == n_conn

    # Generate all vectors
    e_start = np.zeros((n_conn, 3))
    e_vec = np.zeros((n_conn, 3))

    triu_ix, triu_iy = np.triu_indices(n_node, k=1)

    for ii, (ix, iy) in enumerate(zip(triu_ix, triu_iy)):
        e_start[ii, :] = node_coords[ix, :]
        e_vec[ii, :] = 1e-3 * (node_coords[iy, :] - node_coords[ix, :])

    # Import vectors (connections) into pipeline
    edg_source = mlab.pipeline.vector_scatter(e_start[:, 0], e_start[:, 1],
                                              e_start[:, 2], e_vec[:, 0],
                                              e_vec[:, 1], e_vec[:, 2])
    edg_source.mlab_source.dataset.point_data.scalars = conn_list

    edg_thresh = mlab.pipeline.threshold(
        edg_source,
        low=np.percentile(conn_list, 100 * conn_thr[0]),
        up=np.percentile(conn_list, 100 * conn_thr[1]))
    edg_thresh.auto_reset_lower = False
    edg_thresh.auto_reset_upper = False

    edg_surface = mlab.pipeline.vectors(edg_thresh,
                                        colormap=conn_cmap,
                                        line_width=3.0,
                                        scale_factor=1000,
                                        scale_mode='vector')

    edg_surface.glyph.glyph.clamping = False
    edg_surface.actor.property.opacity = 0.75
    edg_surface.module_manager.vector_lut_manager.reverse_lut = True

    edg_surface.glyph.glyph_source.glyph_source = (
        edg_surface.glyph.glyph_source.glyph_dict['glyph_source2d'])
    edg_surface.glyph.glyph_source.glyph_source.glyph_type = 'dash'
Exemplo n.º 19
0
def w_m(m):
    dataname = "wOPT20_with_m{}.npy".format(m)
    res = np.load(dataname)
    #res2 = np.load( "sigmaAN_with_m7.0.npy" )

    from mayavi.api import Engine
    engine = Engine()
    engine.start()
    if len(engine.scenes) == 0:
        engine.new_scene()
    mlab.surf(x_axis1, y_axis1, res, representation='wireframe')

    surface = engine.scenes[0].children[0].children[0].children[0].children[
        0].children[0]
    surface.actor.mapper.scalar_range = np.array([6.97602671, 8.8533387])
    surface.actor.mapper.scalar_visibility = False
    scene = engine.scenes[0]
    scene.scene.background = (1.0, 1.0, 1.0)
    surface.actor.property.specular_color = (0.0, 0.0, 0.0)
    surface.actor.property.diffuse_color = (0.0, 0.0, 0.0)
    surface.actor.property.ambient_color = (0.0, 0.0, 0.0)
    surface.actor.property.color = (0.0, 0.0, 0.0)
    surface.actor.property.line_width = 1.
    warp_scalar = engine.scenes[0].children[0].children[0]
    module_manager = engine.scenes[0].children[0].children[0].children[
        0].children[0]
    warp_scalar.filter.normal = np.array([0., 0., 15])
    module_manager.scalar_lut_manager.scalar_bar.global_warning_display = 1
    module_manager.scalar_lut_manager.scalar_bar.position2 = np.array(
        [0.8, 0.17])
    module_manager.scalar_lut_manager.scalar_bar.position = np.array(
        [0.1, 0.01])
    module_manager.scalar_lut_manager.data_range = np.array(
        [6.97602671, 8.8533387])
    module_manager.scalar_lut_manager.default_data_range = np.array(
        [6.97602671, 8.8533387])
    module_manager.vector_lut_manager.scalar_bar.global_warning_display = 1
    module_manager.vector_lut_manager.scalar_bar.position2 = np.array(
        [0.8, 0.17])
    module_manager.vector_lut_manager.scalar_bar.position = np.array(
        [0.1, 0.01])
    module_manager.vector_lut_manager.data_range = np.array([0., 1.])
    module_manager.vector_lut_manager.default_data_range = np.array([0., 1.])
    scene.scene.isometric_view()

    scene.scene.camera.position = [
        1.2836424071875543, 1.4371492101974028, 4.0390558511994534
    ]
    scene.scene.camera.focal_point = [
        0.17361105930834225, 0.21417386120592863, 3.4874067491767562
    ]
    scene.scene.camera.view_angle = 30.0
    scene.scene.camera.view_up = [
        -0.21371002618964222, -0.23386371429877953, 0.94849132196367569
    ]
    scene.scene.camera.clipping_range = [
        0.79163912587841923, 2.7365159886347699
    ]
    scene.scene.camera.compute_view_plane_normal()

    mlab.show()