Example #1
0
 def plot_3D( self ):
     x = self.compute3D_plot[0]
     y = self.compute3D_plot[1]
     z = self.compute3D_plot[2]
     # print x_axis, y_axis, z_axis
     if self.autowarp_bool:
         x = x / x[-1]
         y = y / y[-1]
         z = z / z[-1] * self.z_scale
     mlab.surf( x, y , z, representation = 'wireframe' )
     engine = Engine()
     engine.start()
     if len( engine.scenes ) == 75.5:
         engine.new_scene()
         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.
         scene.scene.isometric_view()
         mlab.xlabel( self.x_name3D )
         mlab.ylabel( self.y_name3D )
     mlab.outline()
     mlab.show()
Example #2
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()
Example #3
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
Example #4
0
def sigma_m( m ):
    dataname = "sigmaOPT20_with_m{}.npy".format( m )
    res = np.load( dataname )
    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. , 0.2] )
    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.surf( x_axis2, y_axis2, res2 )
    #mlab.xlabel( "rand tau" )
    #mlab.ylabel( "rand r" )
    #mlab.zlabel( "z" )
    mlab.show()
Example #5
0
def sigma_m( m ):
    dataname = "sigmaOPT25_with_m{}.npy".format( m )
    res = np.load( dataname )
    print 'max', np.max( res ), 'min', np.min( res )
    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 = 0.
    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. , 0.8] )
    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()
 
    # mlab.surf( x_axis2, y_axis2, res2 )
    
    mlab.xlabel( "rand tau" )
    mlab.ylabel( "rand r" )
    mlab.zlabel( "z" )

    mlab.show()
Example #6
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)
Example #7
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()
Example #8
0
Co3O4_lat5 = rsp.lattice.lattice_from_cif('/home/finn/Documents/eclipse_workspace/2017_MA3074/preparation/structure_simulation/Co3O4.cif', HKL_normal = [1,0,0], HKL_para_x=[0,0,1])

PbBrF_lat = rsp.lattice.lattice_from_cif('/home/finn/Documents/eclipse_workspace/2017_MA3074/preparation/structure_simulation/PbBrF.cif', HKL_normal = [0,0,1], HKL_para_x=[0,1,0], energy_keV=25)


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)


Au_lat = rsp.lattice(
                 a          = 4.0782, 
                 b          = 4.0782, 
                 c          = 4.0782,
                 alpha      = 90,     
                  beta       = 90,     
                  gamma      = 90,     
                  basis      = [['Au', 0,0,0],['Au', 0.5,0.5,0],['Au', 0,0.5,0.5],['Au', 0.5,0,0.5]], 
                  HKL_normal = [0,0,1],
                  HKL_para_x = [0,1,0]
Example #9
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()
Example #10
0
# coding: utf-8

# In[1]:

import numpy as np
from mayavi.api import Engine
from mayavi.sources.vtk_file_reader import VTKFileReader

# In[2]:

e = Engine()
e.start()

# In[3]:

s = e.new_scene()

# In[4]:

r = VTKFileReader()

# In[5]:

r.initialize('heart.vtk')
e.add_source(r)

# In[6]:

from mayavi.modules import api

# In[7]:
Example #11
0
# Recorded script from Mayavi2
from numpy import array
try:
    engine = mayavi.engine
except NameError:
    from mayavi.api import Engine
    engine = Engine()
    engine.start()
if len(engine.scenes) == 0:
    engine.new_scene()
# -------------------------------------------
from mayavi.filters.threshold import Threshold
threshold = Threshold()
mayavi.add_filter(threshold, ug_waterlevel)
surface_waterlevel = Surface()
mayavi.add_filter(surface2, threshold)
threshold.auto_reset_lower = False
threshold.auto_reset_upper = False

module_manager2 = threshold.children[0]
module_manager2.vector_lut_manager.data_range = array([ 0.,  1.])
Example #12
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)
Example #13
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()
Example #14
0
"""
displayVmrl.py

Display a VMR file of a cube

Created   JRM 2015-11-24

Do "%gui qt" first

@author: John Minter
"""

import os
from mayavi.sources.vrml_importer import VRMLImporter
from mayavi.api import Engine


gitDir = os.environ["GIT_HOME"]
relImg = "/OSImageAnalysis/images/vrml/"
fName = "Lines"

filePath = gitDir + relImg + fName + ".wrl"
print(filePath)

e = Engine()
e.start()
s = e.new_scene()
src = VRMLImporter()
src.initialize(filePath)
e.add_source(src)
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'
Example #16
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()
Example #17
0
# Recorded script from Mayavi2
from numpy import array
try:
    engine = mayavi.engine
except NameError:
    from mayavi.api import Engine
    engine = Engine()
    engine.start()
if len(engine.scenes) == 0:
    engine.new_scene()
# -------------------------------------------

from mayavi.modules.iso_surface import IsoSurface

#vtk_file_reader2 = engine.open(u'/home/m/spammsand/spammsand/water_to_duals/z_15.vtk')
vtk_file_reader2 = engine.open(
    u'/home/matcha/Desktop/RESEARCH/spammsand_may_21_2015/spammsand/water_to_duals/z_14.vtk'
)

iso_surface2 = IsoSurface()
engine.add_module(iso_surface2, obj=None)
iso_surface2.actor.mapper.scalar_mode = 'use_field_data'

#iso_surface2.actor.property.specular_color = (0.5019607843137255, 0.5019607843137255, 0.5019607843137255)
#iso_surface2.actor.property.diffuse_color = (0.5019607843137255, 0.5019607843137255, 0.5019607843137255)
#iso_surface2.actor.property.ambient_color = (0.5019607843137255, 0.5019607843137255, 0.5019607843137255)
#iso_surface2.actor.property.color = (0.5019607843137255, 0.5019607843137255, 0.5019607843137255)

iso_surface2.actor.property.specular_color = (1.0, 1.0, 1.0)
iso_surface2.actor.property.diffuse_color = (1.0, 1.0, 1.0)
iso_surface2.actor.property.ambient_color = (1.0, 1.0, 1.0)
class Visualisation(object):
    ''' Class to visualize vascularNetworks in 3D
        using vtk and mayavi to visualize the vascular network and
        the area over time. The simulation results data as pressure and Flow
        are mapped on the surface of the vessels'''
    
    def __init__(self, vascularNetwork = None):
        '''
        Constructor of the Visualisation
        '''
        #dictionarys to save the src and actors
        self.vizActors = {}
        self.vizSources = {}
        self.vizVTKGrids = {}
        
        self.velArrowGrid = {}
        self.velArrowSrc = {}
        self.glyph = {}
        
        self.vesselLengths = {}
        self.vesselN = {}
        
        # Solution data
        # is numpyarray within numpyarrays 
        # control as 
        # AreaSolution[ vesselID ] [ point in time ]
        # scalarSolution[ vesselID ] [ point in time ]
        self.areaSolution = None
        self.scalarSolution = None
        self.scalarNames = None
        self.scalarPosition = 0
        self.solutionName = None
        self.solutionPosition = 0
        
        # set min max for look uptable
        self.SourceMin = 0
        self.SourceMax = 0
        
        #dimensions | 2 radius (inner outer) | 24 points on circle 
        # | third dimension  N = gridpoints in z axis: not fixed, vessel property
        self.dims = [1, 24]
    
        # vascularNetwork
        self.vascularNetwork = vascularNetwork 
        
        # engine and scene for visualisation
        self.engine = Engine()
        self.scene = None
        
        # to increase the radius change
        # radius(t) = radius0 + deltaRadius * factor
        self.factor = 50
        
        # Movie 
        self.movieBool = False 
        self.movNumber = 0
        self.movPath = None
        
        # update control
        self.moveWall = True
        self.moveWallOff = False
        self.pauseBool = True
        self.calls = 0
        self.currentTime = 0
        self.endTime = None 
        self.updateTimeStep = 1
        
        # bool for velocity profile
        self.vecBool = False
        self.powerLawCoefficient = 2.0
        
        self.static = False
        
        # 2 d plot figures
        self.figspace = None
        self.figtime = None
        self.plotSpace = False
        self.picked = None
        
        #### init this stuff prob move to another function
        self.initialize()

    def __del__(self):  
        '''
        Class Destructor
        '''
        del(self.vascularNetwork)
        print " visualisation removed"
        
#-------------------## public methods##-------------------#

    
    def initialize(self):
        '''
        Initialize and create a 3D representation of the network
        '''
        if self.vascularNetwork != None:
            
            gc.enable()
            
            for key,vessel in self.vascularNetwork.vessels.iteritems():
                self.vesselLengths[key] = vessel.length
                self.vesselN[key] = vessel.N
            
            self.scene = self.engine.new_scene(name = self.vascularNetwork.name)
            
            self.engine.scenes[0].name = str(self.vascularNetwork.name+' - '+'paused')
            
            self.scene.scene.background = (0.0,0.0,0.0)
            
            # start the engine
            self.engine.start()
            # set cameraposition
            self.scene.scene.camera.azimuth(90)
            self.scene.scene.camera.roll(90)

            # create the initial network
            self.createVizData()
            
            # add the initial network
            self.scene.scene.disable_render = True
            for Id in self.vizSources.iterkeys():
                self.engine.add_source(self.vizSources[Id],self.scene)
                self.engine.add_module(self.vizActors[Id], obj=self.vizSources[Id])
                self.engine.add_source(self.velArrowSrc[Id], self.scene)
                self.glyph[Id].actor.actor.visibility = self.vecBool # set bool for visualize the arrows
                self.engine.add_module(self.glyph[Id], obj=self.velArrowSrc[Id])
            # refit the camera position
            self.scene.scene.reset_zoom()
            self.scene.scene.disable_render = False
            
            if self.static == False:
                # add interactor
                self.scene.scene.interactor.add_observer("KeyPressEvent",self.key_press_N)
                self.scene.scene.interactor.add_observer("KeyPressEvent",self.key_press_M)
                self.scene.scene.interactor.add_observer("KeyPressEvent",self.key_press_B)
                self.scene.scene.interactor.add_observer("KeyPressEvent",self.key_press_V)
                self.scene.scene.interactor.add_observer("KeyPressEvent",self.key_press_C)
                self.scene.scene.interactor.add_observer("KeyPressEvent",self.key_press_X)
                self.scene.scene.interactor.add_observer("KeyPressEvent",self.key_press_Y)
                self.scene.scene.interactor.add_observer("KeyPressEvent",self.key_press_J)
                self.scene.scene.interactor.add_observer("KeyPressEvent",self.key_press_H)
                self.scene.scene.interactor.add_observer("KeyPressEvent",self.key_press_U)
                self.scene.scene.interactor.add_observer("KeyPressEvent",self.key_press_G)
                self.scene.scene.interactor.add_observer("KeyPressEvent",self.key_press_komma)
                self.scene.scene.interactor.add_observer("KeyPressEvent",self.key_press_punkt)
                #self.scene.mayavi_scene.on_mouse_pick(self.picker_callback)
                self.engine.scenes[0].on_mouse_pick(self.picker_callback)

            print " ..3d visualisation initialized!"
           
    
    def setVascularNetwork(self,vascularNetwork):
        '''
        Set the vascular Network if not set in constructor
        and initialize the network
        '''
        self.vascularNetwork = vascularNetwork
        self.initialize() 
        
    def setSolutionData(self,solutionData):
        '''
        Process the solutionData, calculates the velocity and set all needed varibles.
        solutionData is a list with dictionarys containing the solution one or several simulation solutions.
           solutionData = [ {'Pressure': pressureData, 'Flow': flowData, 'Area': areaData, 'Name': 'solution1' }, ...]
        '''
        #initialize
        self.areaSolution = []
        self.scalarSolution = []
        self.scalarNames = []
        self.solutionName = []
        
        for solution in solutionData:
            
            # save the solution name
            currentSolutionName = solution.pop('Name')
            
            #save the scalars of the solution
            currentScalars = []
            currentScalarNames = []
            
            # transfer pressure to mmHg
            Psol = {}
            for vesselId,Ptemp in solution['Pressure'].iteritems():
            	Psol[vesselId] = Ptemp/133.32
            
            currentScalars.append(Psol)
            currentScalarNames.append('Pressure')
            currentScalars.append(solution.pop('Flow'))
            currentScalarNames.append('Flow')
            currentScalars.append(solution.pop('Area'))
            currentScalarNames.append('Area')
            
            # calculate velocities 
            velocity = []
            for i in range (0,len(currentScalars[1]),1):
                vel_t = array([currentScalars[1][i][0]/currentScalars[2][i][0]])
                                
                for t in range(1,len(currentScalars[1][i]),1):
                    v = currentScalars[1][i][t]/currentScalars[2][i][t]
                    vel_t = append(vel_t,[v],axis = 0)
                velocity.append(vel_t)
            
            # set the velocity    
            currentScalars.append(velocity)
            currentScalarNames.append('Velocity')
            
            # check if additional solution data was passed:
            for key,value in solution.iteritems():
                currentScalars.append(value)
                currentScalarNames.append(key)
            
            # save the data in class variables
            self.areaSolution.append(currentScalars[2])
            self.scalarSolution.append(currentScalars)
            self.scalarNames.append(currentScalarNames)
            self.solutionName.append(currentSolutionName)
        
        del(currentScalars)
        del(currentScalarNames)
        del(currentSolutionName)

        self.endTime = len(self.areaSolution[self.solutionPosition][0])
        self.engine.scenes[0].name = str(self.vascularNetwork.name +' - '+'paused'+' - '+self.solutionName[self.solutionPosition])
            
        print ' .. solution data initialized!'
        
        
    def visualize(self):
        '''
        Start the visualisation of the simulation result.
        Set up Upgrade method and starts the main loop.
        Use only if the simulation result was set!
        '''
        # update the lookuptables and set them
        minL = []
        maxL = []
       
        for array in self.scalarSolution[self.solutionPosition][self.scalarPosition].itervalues(): 
            minL.append(array.min())
            maxL.append(array.max())
        self.SourceMin = min(minL)
        self.SourceMax = max(maxL)

        for actor in self.vizActors.itervalues():
            actor.module_manager.scalar_lut_manager.data_range = [self.SourceMin, self.SourceMax]
        #self.vizActors[0].module_manager.scalar_lut_manager.data_name = self.scalarNames[self.solutionPosition][self.scalarPosition]
        #self.vizActors[0].module_manager.scalar_lut_manager.show_scalar_bar = True

        timer = Timer(0.03, self.update)
        gui = GUI()
        gui.busy = True
        gui.start_event_loop()

    def visualizeStatic(self):
        gui = GUI()
        self.engine.scenes[0].name = str(self.vascularNetwork.name +' - '+'static')
        gui.start_event_loop()        
    
            
    def picker_callback(self, picker):
        '''
        Mouse pick callback, opens a 2D time plot if a vessel is picked; If the plotSpace is activated key "g"
        the animated space plot of the vessel is loaded aswell
        '''
        printOut = ' .. world - picked'
        if len(picker.actors) > 0:
            picked = picker.actors[0]
            for key,value in self.vizActors.iteritems():
                if value.actor.actor._vtk_obj == picked._vtk_obj:
                    
                    self.picked = self.vascularNetwork.vessels[key].name
                    printOut = str(' .. '+self.vascularNetwork.name +' - '+ self.picked + ' - picked')
                    
                    string = ' '.join(['python',cur+'/class2dVisualisationSimple.py','-f',self.vascularNetwork.name, '-n 1','-i',str(key)])                
                    subprocess.call(string, shell=True)
#                    if self.static == False:
#                        
#                        if self.figspace is not None and type(self.figspace) is not int: 
#                            self.figspace.clf()
#                        if self.figtime is not None:
#                            self.figtime.clf()
#        
#                        networkPlot = NetworkPlot([self.scalarSolution[self.solutionPosition][0][key]],
#                                                  [self.scalarSolution[self.solutionPosition][1][key]],
#                                                  [self.scalarSolution[self.solutionPosition][2][key]])
#                        
#                        #self.figspace,self.figtime =  thread.start_new_thread(networkPlot, ({name: self.vascularNetwork.getSimulationDictionary()[name]},
#                        #                               0,1,False,True,True,self.vascularNetwork.simulationContext['totalTime'],True))
#                        self.figspace,self.figtime = networkPlot(VesselNetwork = {self.picked: self.vascularNetwork.getSimulationDictionary()[key]},
#                                                        cutTime=0,CUT=1,plotVelocity=False,plotSpace=self.plotSpace,plotTime=True,
#                                                       totaltime = self.vascularNetwork.simulationContext['totalTime'], scaleplot=True)                 
        print printOut
            
    def key_press_G(self,obj,event):
        '''
        Key event G: enable / disable 2D space plot if vessel is picked
        '''
        key = obj.GetKeyCode()
        if key=='G':
            if self.plotSpace  == False: 
                self.plotSpace  = True
                print " .. 2D space plot enabled"
            else: 
                self.plotSpace = False
                print " .. 2D space plot disabled"
        elif key=='g':
            if self.figtime is not None:
                print " .. time plot for ",self.picked," saved"
                path = str(cur+'/../network_files/'+self.vascularNetwork.name+'/2dTimePlots/')
                if not os.path.exists(path):
                    os.makedirs(path) 
                self.figtime.savefig(str(path+self.vascularNetwork.name+'-'+self.solutionName[self.solutionPosition]+'-'+self.picked+'.png'))

    def key_press_N(self,obj,event):
        '''
        Key event n: next lookup table - change the lookup and scalar mapping
        '''
        key = obj.GetKeyCode()
        if key=='n' or key=='N':
            self.scalarPosition = self.scalarPosition + 1
            if self.scalarPosition == len(self.scalarNames[self.solutionPosition]):
                self.scalarPosition = 0
            minL = []
            maxL = []
            for array in self.scalarSolution[self.solutionPosition][self.scalarPosition].itervalues(): 
                minL.append(array.min())
                maxL.append(array.max())
            self.SourceMin = min(minL)
            self.SourceMax = max(maxL)
            
            
    def key_press_J(self,obj,event):
        '''
        Key event j: last lookup table - change the lookup and scalar mapping
        '''
        key = obj.GetKeyCode()
        if key=='j' or key=='J':
            self.scalarPosition = self.scalarPosition - 1
            if self.scalarPosition < 0:
                self.scalarPosition = len(self.scalarNames[self.solutionPosition]) - 1
            # recalculate the range of the lookuptable ## Note: change this in further version to save memory -> (list)
            minL = []
            maxL = []
            for array in self.scalarSolution[self.solutionPosition][self.scalarPosition].itervalues(): 
                minL.append(array.min())
                maxL.append(array.max())
            self.SourceMin = min(minL)
            self.SourceMax = max(maxL)
            
            
    def key_press_H(self,obj,event):
        '''
        Key event h: next solution data - show next soultion data set
        '''
        key = obj.GetKeyCode()
        if key=='h' or key=='H':
            self.solutionPosition = self.solutionPosition + 1
            if self.solutionPosition == len(self.solutionName):
                self.solutionPosition = 0
            # recalculate the range of the lookuptable ## 
            self.scalarPosition = 0
            minL = []
            maxL = []
            for array in self.scalarSolution[self.solutionPosition][self.scalarPosition].itervalues(): 
                minL.append(array.min())
                maxL.append(array.max())
            self.SourceMin = min(minL)
            self.SourceMax = max(maxL)
    
            self.endTime = len(self.areaSolution[self.solutionPosition][0])
            
            #set name of the solution
            if self.pauseBool == False: self.engine.scenes[0].name = str(self.vascularNetwork.name +' - '+'paused'+' - '+self.solutionName[self.solutionPosition])
            else: self.engine.scenes[0].name = str(self.vascularNetwork.name +' - '+'running'+' - '+'t = 0.000' +' - '+self.solutionName[self.solutionPosition])
    
            #restart simulation
            self.currentTime = 0
            
    def key_press_U(self,obj,event):
        '''
        Key event u: last solution data - show last soultion data set
        '''
        key = obj.GetKeyCode()
        if key=='u' or key=='U':
            self.solutionPosition = self.solutionPosition - 1
            if self.solutionPosition < 0:
                self.solutionPosition = len(self.solutionName) - 1
            # recalculate the range of the lookuptable ## 
            self.scalarPosition = 0
            minL = []
            maxL = []
            for array in self.scalarSolution[self.solutionPosition][self.scalarPosition].itervalues(): 
                minL.append(array.min())
                maxL.append(array.max())
            self.SourceMin = min(minL)
            self.SourceMax = max(maxL)
    
            #set time
            self.endTime = len(self.areaSolution[self.solutionPosition][0])
            
            #set name of the solution
            if self.pauseBool == False: self.engine.scenes[0].name = str(self.vascularNetwork.name +' - '+'paused'+' - '+self.solutionName[self.solutionPosition])
            else: self.engine.scenes[0].name = str(self.vascularNetwork.name +' - '+'running'+' - '+'t = 0.000' +' - '+self.solutionName[self.solutionPosition])
    
            #restart simulation
            self.currentTime = 0
    
            
    def key_press_M(self,obj,event):
        '''
        Key event m: start saving png for movie
        '''
        key = obj.GetKeyCode()
        if key=='m' or key=='M':
            # create movie directory
            if self.movPath == None:
                self.movPath = str(cur+'/../NetworkFiles/'+self.vascularNetwork.name+'/movieTemplateData/')
                if not os.path.exists(str(self.movPath)):
                    os.makedirs(str(self.movPath)) 
            
            if self.movieBool == False: 
                self.movieBool = True
                print " .. start creating movie files"
            else: 
                self.movieBool = False
                self.movNumber = 0
                print " .. stop creating movie files"
        
    def key_press_B(self,obj,event):
        '''
        Key event B: pause/break the simulation
        '''
        key = obj.GetKeyCode()
        if key=='b' or key=='B':
            if self.pauseBool == False: 
                self.pauseBool = True
                self.engine.scenes[0].name = str(self.vascularNetwork.name +' - '+'paused'+' - '+self.solutionName[self.solutionPosition])
            else: 
                self.pauseBool = False
                self.engine.scenes[0].name = str(self.vascularNetwork.name +' - '+'running'+' - '+'t = 0.000' +' - '+self.solutionName[self.solutionPosition])
    
    
    def key_press_V(self,obj,event):
        '''
        Key event V: open vessels and show vectorfields
        '''
        key = obj.GetKeyCode()
        if key=='v' or key=='V':
            if self.vecBool == False: 
                self.vecBool = True
                for glyph in self.glyph.itervalues(): glyph.actor.actor.visibility = self.vecBool
                self.scalarPosition = 3
                
                minL = []
                maxL = []
                for array in self.scalarSolution[self.solutionPosition][self.scalarPosition].itervalues(): 
                    minL.append(array.min())
                    maxL.append(array.max())
                    
                self.SourceMin = min(minL)
                self.SourceMax = max(maxL)
                
                self.vizActors[0].module_manager.scalar_lut_manager.show_scalar_bar = False
                self.glyph[0].module_manager.scalar_lut_manager.data_range = [0, self.SourceMax]
                self.glyph[0].module_manager.scalar_lut_manager.show_scalar_bar = True
                self.glyph[0].module_manager.scalar_lut_manager.data_name = self.scalarNames[self.solutionPosition][self.scalarPosition]
                
                print " .. velocity profile enabled"
            else: 
                self.vecBool = False
                for glyph in self.glyph.itervalues(): glyph.actor.actor.visibility = self.vecBool
                print " .. velocity profile disabled"
                self.scalarPosition = 3
                minL = []
                maxL = []
                for array in self.scalarSolution[self.solutionPosition][self.scalarPosition].itervalues(): 
                    minL.append(array.min())
                    maxL.append(array.max())
                self.SourceMin = min(minL)
                self.SourceMax = max(maxL)
                self.vizActors[0].module_manager.scalar_lut_manager.data_name = self.scalarNames[self.solutionPosition][3]
                self.vizActors[0].module_manager.scalar_lut_manager.show_scalar_bar = True
                
                
    def key_press_C(self,obj,event):
        '''
        Key event C: stop/start simulation of the wall movement
        '''
        key = obj.GetKeyCode()
        print key
        if key=='c' or key=='C':
            if self.moveWall  == False: 
                self.moveWall  = True
                print " .. wall movement enabled"
            else: 
                self.moveWallOff = True
                print " .. wall movement disabled"
                
    def key_press_X(self,obj,event):
        '''
        Key event X: increase the radius factor
        '''
        key = obj.GetKeyCode()
        if key=='x' or key=='X':
            self.factor = self.factor + 1
            print " .. radius factor increased to: ",self.factor
    
    def key_press_Y(self,obj,event):
        '''
        Key event Y: decrease the radius factor
        '''
        key = obj.GetKeyCode()
        if key=='y' or key=='Y' or key=='z' or key=='Z':
            if self.factor > 0:
                self.factor = self.factor - 1
            print " .. radius factor decreased to: ",self.factor
    
    def key_press_komma(self,obj,event):
        '''
        Key event ,: increase the timestep
        '''
        key = obj.GetKeyCode()
        if key==',' or key==',':
            self.updateTimeStep = self.updateTimeStep + 1
            print " .. update timestep increased to: ",self.updateTimeStep
    
    def key_press_punkt(self,obj,event):
        '''
        Key event ,: decrease the timestep
        '''
        key = obj.GetKeyCode()
        if key=='.' or key=='.':
            if self.updateTimeStep > 1:
                self.updateTimeStep = self.updateTimeStep - 1
            print " .. update timestep decreased to: ",self.updateTimeStep
            
    

#-------------------## private methods##-------------------#

    def update(self):
        '''
        update function: updates the scene,actors every time it is called
        '''
        if self.endTime == None:
            self.endTime = len(self.areaSolution[self.solutionPosition][0])
            
        if self.pauseBool == False:
            
            
            Lstart = time.clock()
            
            ###start the update  
            # stop the rendering while updating grids and the piplines
            # without mayavi is rendering during the update 
            # --> updateTime is 10x higher
            # --> all vessels are updated at the same time
            self.scene.scene.disable_render = True
            
            # to accelerate fist calculat data then apply
            TempColor = {}
            TempPoints = {}
            TempVelPoints = {}
            TempVelColor = {}
            #create new data
            LstartD = time.clock()
            for Id in self.vesselLengths.iterkeys():
                
                if self.moveWall == True:
                    
                    radiusAr = sqrt(self.areaSolution[self.solutionPosition][Id][0]/pi)+(sqrt(self.areaSolution[self.solutionPosition][Id][self.currentTime]/pi)-sqrt(self.areaSolution[self.solutionPosition][Id][0]/pi))*self.factor # calculate the radius from the area    
                    if self.moveWallOff == True:
                        radiusAr = sqrt(self.areaSolution[self.solutionPosition][Id][0]/pi)
                    # create points for the vessels
                    TempPoints[Id] = self.generate_vertices(r_array = radiusAr, length = self.vesselLengths[Id], N = self.vesselN[Id])        
                    # create points for the velocity arrows
                    TempVelPoints[Id] = self.generate_velocity_points(length = self.vesselLengths[Id], N = self.vesselN[Id], r_array= radiusAr)
                    
                # set size and color of the velocity arrows 
                if self.vecBool == True:
                    ## here the 3 must refer to the velocity!! in scalarSolution 
                    self.scalarPosition = 3
                    TempVelColor[Id] = self.generate_velocity_colorScalars(velArray = self.scalarSolution[self.solutionPosition][self.scalarPosition][Id][self.currentTime], N = self.vesselN[Id])
                    
                    if Id == 1:
                        print self.scalarSolution[self.solutionPosition][self.scalarPosition][Id][self.currentTime][1]
                    #set the scalar color array to velocity
                    colorAr = self.scalarSolution[self.solutionPosition][self.scalarPosition][Id][0]  
                else: 
                    # set the scalar color array to the current choosen
                    colorAr = self.scalarSolution[self.solutionPosition][self.scalarPosition][Id][self.currentTime] 
                # create scalar color map
                TempColor[Id]= ravel(self.generate_colorScalars(colorAr, N = self.vesselN[Id]))  
            
            LendD = time.clock()
            #print ' time:', LendD - LstartD
            
            for Id,grid in self.vizVTKGrids.iteritems():
                # modify grid of the vizVTKGrid
                # create scalar color map
                grid.point_data.scalars = TempColor[Id]
                grid.point_data.scalars.name = 'scalars' 
                # create update data if wall movement is enabled
                if self.moveWall == True:
                    grid.points = TempPoints[Id]
                    
                # set lut range (necessary)
                self.vizActors[Id].module_manager.scalar_lut_manager.data_range = [self.SourceMin, self.SourceMax]
            # set lut (for 1 actor is enough
            
            
            
            # update velocity vectors
            if self.vecBool == True:
                for Id,grid in self.velArrowGrid.iteritems():
                    grid.point_data.scalars = TempVelColor[Id][1]
                    grid.point_data.scalars.name = 'scalars' 
                    grid.point_data.vectors = TempVelColor[Id][0]
                    grid.point_data.vectors.name = 'vectors'
                    
                    self.glyph[Id].glyph.scale_mode = 'scale_by_scalar'
                    self.glyph[Id].glyph.glyph.range = [0, self.SourceMax]     
                    self.glyph[Id].glyph.color_mode = 'color_by_scalar'       
                    self.glyph[Id].module_manager.scalar_lut_manager.data_range = [0, self.SourceMax]
                    self.glyph[Id].module_manager.scalar_lut_manager.use_default_range = False
                    self.glyph[0].module_manager.scalar_lut_manager.show_scalar_bar = True
                    self.glyph[0].module_manager.scalar_lut_manager.data_name = self.scalarNames[self.solutionPosition][self.scalarPosition]
                    
                    # update position if they change (wallmovement)
                    if self.moveWall == True:
                        grid.points = TempVelPoints[Id]
            #else:
                #self.vizActors[0].module_manager.scalar_lut_manager.data_name = self.scalarNames[self.solutionPosition][self.scalarPosition]
                #self.vizActors[0].module_manager.scalar_lut_manager.show_scalar_bar = True
            
            if self.moveWallOff == True:
                self.moveWall = False
                self.moveWallOff = False
            
            dt = (self.vascularNetwork.simulationContext['totalTime']/self.endTime)*self.currentTime
            self.engine.scenes[0].name = str(self.vascularNetwork.name +' - '+'running'+' - '+'t = %0.4f' %dt+' - '+self.solutionName[self.solutionPosition])
    
            # control the current timeStep
            self.currentTime = self.currentTime+self.updateTimeStep
            # restart simulation if end reached
            if self.currentTime >= self.endTime:
                self.currentTime = 0
                
            # if no movie:
            if self.movieBool == False:
                #start the rendering again
                self.scene.scene.disable_render = False
            #save pictures for the movies
            else: 
                #thread.start_new_thread(self.scene.scene.save_png,(('../data/temp/'+'movieTemplateData'+str(self.movNumber).zfill(4)+'.png'),  ))
                Lstart = time.clock()
                self.scene.scene.save_png(self.movPath+'movieTemplateData'+str(self.movNumber).zfill(4)+'.png')
                Lend = time.clock()
                print" needed %1.6f  sec to save the picture" %((Lend-Lstart)) 
                self.movNumber = self.movNumber + 1
            
            Lend = time.clock()
            #print" update time %1.6f -- framerate: %1.2f -- increase in framerate: %1.2f " %((Lend-Lstart), 1.0/(Lend-Lstart), (1.0/(Lend-Lstart-LendD+LstartD))-(1.0/(Lend-Lstart))) 
            
 
    def generate_vertices(self,length,N,r_array = None,r_init = None):
        '''
        Calculates vertices of an vessel
        either based on radius array with lenght N
        or radius init = [radius start, radius end]
        '''
        N = int(N)
        if r_array == None:
            r_initA = r_init[0]
            r_initB = r_init[1]
            r_array = linspace(r_initA, r_initB, N)
        
        # inner wall (not necesarry!)   
        #ri_array = r_array*array([0.9])
        #r = vstack((ri_array,r_array)).transpose()
        r = r_array.transpose()
        
        if self.vecBool == False : 
            thetaFactor = 2
        else: 
            thetaFactor = 1
        
        theta = linspace(pi/2.0, pi/2.0+thetaFactor*pi, self.dims[1])
        z = linspace(0, length, N)
        
        ## create Points
        aLength = self.dims[0]*self.dims[1]
        points = empty([aLength*N,3])
        
        start = 0
        for z_plane in range(0,len(z),1):
            end = start+aLength
            plane_points = points[start:end]
            plane_points[:,0] = (cos(theta)*r[z_plane]).ravel() # for inner wall add r[z_plane,:][:,None]
            plane_points[:,1] = (sin(theta)*r[z_plane]).ravel()
            plane_points[:,2] = z[z_plane]
            start = end
        return points

    def generate_colorScalars(self,colorArray, N):
        '''
        map the values of the colorArray to the points of the grid
        '''
        # for loop
        #colors = array([])
        #for z_plane in range(0,int(N),1):
        #    s_z = linspace(colorArray[z_plane] ,colorArray[z_plane], (self.dims[0]*self.dims[1]))
        #    colors = hstack((colors,s_z))
        
        # matrix calculation
        colors = column_stack(ones(((self.dims[0]*self.dims[1]),int(N)))*colorArray).ravel()
       
        return colors
    
    def generate_velocity_points(self, length, N , r_array = None,r_init = None, numberOfVec = 11):
        '''
        calculates the points for the velocity arrows of the velocity profil
        '''
        #numberOfVec should be odd
        
        if r_array == None:
            r_initA = r_init[0]
            r_initB = r_init[1]
            r_array = linspace(r_initA, r_initB, N)
        
        dz = length/N
        z = linspace(dz, length-dz, (N-2))
        
        ## create Points
        aLength = numberOfVec
        points = empty([aLength*(N-2),3])
        
        start = 0
        for z_plane in range(0,len(z),1):
            end = start+aLength
            y_plane = linspace(- r_array[z_plane]*0.9, r_array[z_plane]*0.9, numberOfVec)
            plane_points = points[start:end]
            plane_points[:,0] = 0
            plane_points[:,1] = y_plane
            plane_points[:,2] = z[z_plane]
            start = end
        return points
    
    def generate_velocity_colorScalars(self, N, velArray = None, numberOfVec=11):
        '''
        Map the values of the velocity calculated of the mean velocity to the points of the grid
        '''
        
        if velArray == None:
            velC = linspace(0.001,0.005,int((N-2)))
        else:
            velC = delete(velArray,[0,int(N-1)])
                  
        profileA = linspace(0.9,0.0,6)
        profileB = linspace(0,0.9,6)
        prof = append(profileA,profileB)
        profile = delete(prof, 6)
        
        #cast N
        colorVectors = empty([numberOfVec*(N-2),3])
        colorScalars = array([])
        count = 0
        for z in range(0,int(N-2),1):
            for i in range (0,numberOfVec,1):
                #velocity profile using powerlaw with n = self.powerLawCoefficient
                vel = velC[z]*((self.powerLawCoefficient+2.0)/self.powerLawCoefficient)*(1.0-profile[i]**self.powerLawCoefficient)
                
                # vectors are for direction of the arrows
                t = 1.0
                if vel != 0:
                    t = vel/abs(vel)
                # scalares determine size and color
                vec_i = array([0,0,t*abs(vel)])
                colorVectors[count] = vec_i
                colorScalars = hstack((colorScalars,[abs(vel)]))
                count = count + 1
            
                    
        
        return [colorVectors,colorScalars]
            
    
    def createVizData(self):
        '''
        Creates the actors and sources of the vascular network
        parsing through the network as binary tree
        using connection of mother and daughter vessels
        '''
        ### INIT
        viz = []
        vessels = self.vascularNetwork.vessels
        root = self.vascularNetwork.root[0]
        
        ### root vessel
        
        ## find data
        #find initial rotation
        rootRot = 0.0
        if vessels[root].angleToMother != None:
            rootRot = vessels[root].angleToMother 
        
        #find inital RadiusA
        dRadiusA = 0.05
        if vessels[root].radiusA != None:
            dRadiusA = vessels[root].radiusA
            
        #find inital RadiusB
        dRadiusB = dRadiusA
        if vessels[root].radiusB != None:
            dRadiusB = vessels[root].radiusB
        
        #find length of root
        rLength = 1.0
        if vessels[root].length != None:
            rLength = vessels[root].length
        
        ## create visualisation Data
        # create the data points 
        points =  self.generate_vertices(r_init=[dRadiusA,dRadiusB],length = rLength, N = self.vesselN[root])
        # create scalar color map
        col = linspace(0.0, 0.0, self.vesselN[root])
        color = self.generate_colorScalars(col, N = self.vesselN[root])
        # generate structured grid, data source
        self.vizVTKGrids[root] = tvtk.StructuredGrid(dimensions=(self.dims[1], self.dims[0], self.vesselN[root]))
        #set data points
        self.vizVTKGrids[root].points = points
        #set scalar color map
        self.vizVTKGrids[root].point_data.scalars = ravel(color)
        self.vizVTKGrids[root].point_data.scalars.name = 'scalars' #self.scalarNames[self.scalarPosition]
        
        # create datasource for mayavi
        self.vizSources[root] = VTKDataSource(data = self.vizVTKGrids[root])
  
        # create surface actor for the datas ource
        self.vizActors[root] = Surface()
        self.vizActors[root].actor.actor.position=0,0,0
        self.vizActors[root].actor.actor.rotate_x(rootRot)
    
        ### create the velocity vector field 
        # creat gird for the velocity arrows
        self.velArrowGrid[root] = tvtk.StructuredGrid(dimensions=(11, 1, self.vesselN[root]))
        #set data points
        self.velArrowGrid[root].points = self.generate_velocity_points(self.vesselLengths[root], self.vesselN[root], r_init=[dRadiusA,dRadiusB])
        #set scalar color map
        color = self.generate_velocity_colorScalars(self.vesselN[root])
        self.velArrowGrid[root].point_data.vectors = color[0].copy()
        self.velArrowGrid[root].point_data.vectors.name = 'vectors'
        self.velArrowGrid[root].point_data.scalars = color[1].copy()
        self.velArrowGrid[root].point_data.scalars.name = 'scalars'
        # create source
        self.velArrowSrc[root] = VTKDataSource(data = self.velArrowGrid[root])
        # create vectors data
        self.glyph[root] = Glyph()
        self.glyph[root].glyph.scale_mode = 'scale_by_scalar'
        self.glyph[root].glyph.color_mode = 'color_by_scalar'
        
        self.glyph[root].glyph.glyph_source.glyph_source = self.glyph[root].glyph.glyph_source.glyph_dict['arrow_source']
        self.glyph[root].glyph.glyph_source.glyph_position = 'tail'
        self.glyph[root].glyph.glyph.scale_factor = self.vesselLengths[root] / self.vesselN[root] * 4 / 7
        
        
        # set position
        self.glyph[root].actor.actor.position = 0,0,0
        self.glyph[root].actor.actor.rotate_x(rootRot)
    
        viz.append(root)
    
        ## set rest of the network
        while len(viz) != 0:
        # Current left Daughter
            currentVessel = viz.pop(0)
    
            #find values of the current mother
            moPos = self.vizActors[currentVessel].actor.actor.position
            moRot = self.vizActors[currentVessel].actor.actor.orientation[0]
            moRotY = self.vizActors[currentVessel].actor.actor.orientation[1]
            
            moLength = 1.0
            if vessels[currentVessel].length != None:
                moLength = vessels[currentVessel].length
            if vessels[currentVessel].radiusB != None:
                moRadiusB = vessels[currentVessel].radiusB
            elif vessels[currentVessel].radiusA != None:
                moRadiusB = vessels[currentVessel].radiusA
            else:
                moRadiusB = 0.05
            
            #find Daughters
            rightDaughter = None
            rightDaughter = vessels[currentVessel].rightDaughter 
            leftDaughter = None
            leftDaughter = vessels[currentVessel].leftDaughter 
            
            # create left Daughter vessel visualisation
            if leftDaughter is not None:
                        
                #find length of Daughter
                dLength = 1.0
                if vessels[leftDaughter].length != None:
                    dLength = vessels[leftDaughter].length
                
                #find inital RadiusA
                dRadiusA = moRadiusB
                if vessels[leftDaughter].radiusA != None:
                    dRadiusA = vessels[leftDaughter].radiusA
                
                #find inital RadiusB
                dRadiusB = dRadiusA
                if vessels[leftDaughter].radiusB != None:
                    dRadiusB = vessels[leftDaughter].radiusB
                
                #set rotation
                
                if rightDaughter is not None:
                    if vessels[leftDaughter].angleToMother is not None:
                        drot =  -moRotY+(1+2/180.0*moRotY)*((1+2/180.0*moRotY)*-vessels[leftDaughter].angleToMother + moRot) 
                    else:
                        drot = -moRotY+(1+2/180.0*moRotY)*((1+2/180.0*moRotY)*-30.0 + moRot)
                else:
                    drot = moRot
                
                #set z_position
                pos_z = moLength*cos(moRot*pi/180)*(1+2/180.0*moRotY)
                #set y_position
                if moRot != 0.0:
                    pos_y = -moLength*sin(moRot*pi/180)
                else:
                    pos_y = 0.0
                # apply position changes
                dpos = moPos[0],moPos[1]+pos_y,moPos[2]+pos_z
                
                ## create visualisation Data
                # create the data points 
                points =  self.generate_vertices(r_init=[dRadiusA,dRadiusB],length = dLength,N = self.vesselN[leftDaughter])
                # create scalar color map
                col = linspace(0.0, 0.0, self.vesselN[leftDaughter])
                color = self.generate_colorScalars(col, N = self.vesselN[leftDaughter])
                # generate structured grid, data source
                self.vizVTKGrids[leftDaughter] = tvtk.StructuredGrid(dimensions=(self.dims[1], self.dims[0], self.vesselN[leftDaughter]))
                #set data points
                self.vizVTKGrids[leftDaughter].points = points
                #set scalar color map
                self.vizVTKGrids[leftDaughter].point_data.scalars = ravel(color.copy())
                self.vizVTKGrids[leftDaughter].point_data.scalars.name = 'scalars' #self.scalarNames[self.scalarPosition]
                
                # create datasource for mayavi
                self.vizSources[leftDaughter] = VTKDataSource(data = self.vizVTKGrids[leftDaughter])
                
                # create surface actor for the datas ource
                self.vizActors[leftDaughter] = Surface()
                self.vizActors[leftDaughter].actor.actor.position = dpos
                self.vizActors[leftDaughter].actor.actor.rotate_x(drot)
                
                ## set arrows
                self.velArrowGrid[leftDaughter] = tvtk.StructuredGrid(dimensions=(11, 1, self.vesselN[leftDaughter]))
                #set data points
                self.velArrowGrid[leftDaughter].points = self.generate_velocity_points(self.vesselLengths[leftDaughter], self.vesselN[leftDaughter], r_init=[dRadiusA,dRadiusB])
                #set scalar color map
                color = self.generate_velocity_colorScalars(self.vesselN[leftDaughter])
                self.velArrowGrid[leftDaughter].point_data.vectors = color[0].copy()
                self.velArrowGrid[leftDaughter].point_data.vectors.name = 'vectors'
                self.velArrowGrid[leftDaughter].point_data.scalars = color[1].copy()
                self.velArrowGrid[leftDaughter].point_data.scalars.name = 'scalars'
                # create source
                self.velArrowSrc[leftDaughter] = VTKDataSource(data = self.velArrowGrid[leftDaughter])
                # create vectors data
                self.glyph[leftDaughter] = Glyph()
                self.glyph[leftDaughter].glyph.scale_mode = 'scale_by_scalar'
                self.glyph[leftDaughter].glyph.color_mode = 'color_by_scalar'
                self.glyph[leftDaughter].glyph.glyph_source.glyph_source = self.glyph[leftDaughter].glyph.glyph_source.glyph_dict['arrow_source']
                self.glyph[leftDaughter].glyph.glyph_source.glyph_position = 'tail'
                self.glyph[leftDaughter].glyph.glyph.scale_factor = self.vesselLengths[leftDaughter] / self.vesselN[leftDaughter] * 4 / 7
                
                # set position
                self.glyph[leftDaughter].actor.actor.position = dpos
                self.glyph[leftDaughter].actor.actor.rotate_x(drot)
                
                
                #check for children
                if vessels[leftDaughter].leftDaughter is not None:
                    viz.append(leftDaughter)
                
                # right Daughter (only if left Daughter)
                if rightDaughter is not None:
                    
                    #find length of Daughter
                    dLength = 1.0
                    if vessels[rightDaughter].length != None:
                        dLength = vessels[rightDaughter].length
                    
                    #find inital RadiusA
                    dRadiusA = moRadiusB
                    if vessels[rightDaughter].radiusA != None:
                        dRadiusA = vessels[rightDaughter].radiusA
 
                    #find inital RadiusB
                    dRadiusB = dRadiusA
                    if vessels[rightDaughter].radiusB != None:
                        dRadiusB = vessels[rightDaughter].radiusB
                    
                    # set values          
                    
                    if vessels[rightDaughter].angleToMother is not None:
                        drot = -moRotY+(1+2/180.0*moRotY)*( (1+2/180.0*moRotY)*vessels[rightDaughter].angleToMother + moRot)
                    else:
                        drot =  -moRotY+(1+2/180.0*moRotY)*((1+2/180.0*moRotY)*30.0 + moRot) 
                                   
                    # set z position
                    pos_z = moLength*cos(moRot*pi/180)*(1+2/180.0*moRotY) # truns with 180 degree
                    #set rotation
                    if moRot != 0:
                        pos_y = -moLength*sin(moRot*pi/180)   
                    else:
                        pos_y = 0.0
                    dpos = moPos[0],moPos[1]+pos_y,moPos[2]+pos_z
                    
                    ## create visualisation Data
                    # create the data points 
                    points =  self.generate_vertices(r_init=[dRadiusA,dRadiusB],length = dLength,N = self.vesselN[rightDaughter])
                    # create scalar color map
                    col = linspace(0.0, 0.0, self.vesselN[rightDaughter])
                    color  = self.generate_colorScalars(col, N = self.vesselN[rightDaughter])
                    # generate structured grid, data source
                    self.vizVTKGrids[rightDaughter] = tvtk.StructuredGrid(dimensions=(self.dims[1], self.dims[0], self.vesselN[rightDaughter]))
                    #set data points
                    self.vizVTKGrids[rightDaughter].points = points
                    #set scalar color map
                    self.vizVTKGrids[rightDaughter].point_data.scalars = ravel(color.copy())
                    self.vizVTKGrids[rightDaughter].point_data.scalars.name =  'scalars' #self.scalarNames[self.scalarPosition]
                    
                    # create datasource for mayavi
                    self.vizSources[rightDaughter] = VTKDataSource(data = self.vizVTKGrids[rightDaughter])
                    
                    # create surface actor for the datas ource
                    self.vizActors[rightDaughter] = Surface()
                    self.vizActors[rightDaughter].actor.actor.position = dpos
                    self.vizActors[rightDaughter].actor.actor.rotate_x(drot)
                    
                    
                    self.velArrowGrid[rightDaughter] = tvtk.StructuredGrid(dimensions=(11, 1, self.vesselN[rightDaughter]))
                    #set data points
                    self.velArrowGrid[rightDaughter].points = self.generate_velocity_points(self.vesselLengths[rightDaughter], self.vesselN[rightDaughter], r_init=[dRadiusA,dRadiusB])
                    #set scalar color map
                    color = self.generate_velocity_colorScalars(self.vesselN[rightDaughter])
                    self.velArrowGrid[rightDaughter].point_data.vectors = color[0].copy()
                    self.velArrowGrid[rightDaughter].point_data.vectors.name = 'vectors'
                    self.velArrowGrid[rightDaughter].point_data.scalars = color[1].copy()
                    self.velArrowGrid[rightDaughter].point_data.scalars.name = 'scalars'
                    # create source
                    self.velArrowSrc[rightDaughter] = VTKDataSource(data = self.velArrowGrid[rightDaughter])
                    # create vectors data
                    self.glyph[rightDaughter] = Glyph()
                    self.glyph[rightDaughter].glyph.scale_mode = 'scale_by_scalar'
                    self.glyph[rightDaughter].glyph.color_mode = 'color_by_scalar'
                    self.glyph[rightDaughter].glyph.glyph_source.glyph_source = self.glyph[rightDaughter].glyph.glyph_source.glyph_dict['arrow_source']
                    self.glyph[rightDaughter].glyph.glyph_source.glyph_position = 'tail'
                    self.glyph[rightDaughter].glyph.glyph.scale_factor = self.vesselLengths[rightDaughter] / self.vesselN[rightDaughter] * 4 / 7
                    # set position
                    self.glyph[rightDaughter].actor.actor.position = dpos
                    self.glyph[rightDaughter].actor.actor.rotate_x(drot)
                
                    
                    # check for children
                    if vessels[rightDaughter].leftDaughter is not None:
                        viz.append(rightDaughter)     
Example #19
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)
Example #20
0
class TubePlot:
    """
    Class to generate pretty 3d pictures of polymers, based on inputted polymer coordinates.
    """
    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()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        mlab.clf()
        mlab.close()

    @staticmethod
    def _hex_to_rgb_(val):
        return tuple(int(val.lstrip('#')[i:i + 2], 16) / 256 for i in (0, 2, 4))

    def set_colors(self):
        """
        Based on the private variable self.color_scheme this method sets various other private variables such as the polymer color etc.
        """
        if self.color_scheme == 'dark':
            self.color_polymer = (.8, .8, .8)
        else:
            self.color_polymer = (.5, .5, .5)

    def make_new_fig(self):
        """
        Constructs a figure object with the correct background color based on the color scheme.
        """
        
        mlab.figure(figure=self.scene).scene.background = (.1, .1, .1) if self.color_scheme == 'dark' else (1., 1., 1.)

    def get_polymer_length(self):
        """
        :return: Length of the polymer, of type integer. Based on the raw_attributes.
        """
        return len(self.polymer_coordinates)

    @staticmethod
    def make_coordinates_circular(coordinates):
        """
        Add a coordinate at the end that is equal to the first coordinate.
        :param coordinates: Nx3 numpy array of coordinates in space
        """
        return np.concatenate([coordinates, [coordinates[0, :]]])  # add the first coordinate for constructing a circular interpolation

    @staticmethod
    def translate_coordinates_by_center_of_mass(coordinates):
        """
        Returns coordinates displaced by their center of mass
        :param coordinates: Nx3 numpy array of integer coordinates
        :returns: Nx3 numpy array of displaced coordinates
        """
        return coordinates - np.mean(coordinates, axis=0, dtype=int)

    @staticmethod
    def compute_interpolation(coordinates, interpolation_factor=20):
        """
        Returns an interpolated version of the :param coordinates.
        :param coordinates: Nx3 numpy array of coordinates in space
        :param interpolation_factor: Number of coordinates to return per input coordinate (sets degree of smoothness for the interpolation)
        :returns: N*interpolation x 3 numpy array of coordinates, where now the last coordinate is equal to the first
        """
        # circular_coordinates = self.make_coordinates_circular(coordinates)
        n = len(coordinates)
        N = interpolation_factor * n
        t_old = np.arange(n)
        f = interpolate.interp1d(t_old, coordinates, axis=0, kind='cubic')
        t_new = np.linspace(0, n - 1, num=N, endpoint=True)
        return f(t_new)

    def draw_tube(self, coordinates, color=None, opacity=1., tube_radius=0.5):
        """
        Draws a Mayavi tubeplot on the canvas. Coordinates are retrieved using a different method in this same class.
        """
        mlab.plot3d(coordinates[:, 0], coordinates[:, 1], coordinates[:, 2], np.abs(2*np.arange(-len(coordinates)/2,+len(coordinates)/2))/len(coordinates), tube_radius=tube_radius, tube_sides=40, opacity=opacity, colormap='Spectral', figure=self.scene)

    def draw_all(self):
        """
        Draw polymer, proteins, origin, terminus etc.
        """
        coordinates = self.polymer_coordinates
        coordinates_circular = self.make_coordinates_circular(coordinates)
        coordinates_interpolated = self.compute_interpolation(coordinates_circular)
        self.draw_tube(coordinates_interpolated)

    def add_text(self, string):
        """
        Adds some interesting text to the current mayavi-canvas.
        :param string: String to put in the image
        """
        c = (1.,1.,1.) if self.color_scheme == 'dark' else (0.,0.,0.)
        mlab.text(0.025,0.025, string, color=c, width=0.3)