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()
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
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
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()
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)
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 load_3D_plot( self ): config = 0 os.chdir( 'DATA' ) # os.chdir( self.load_folder3D ) os.chdir( self.dropdownls3D ) x = np.load( 'x.npy' ) y = np.load( 'y.npy' ) z = np.load( 'z.npy' ) print 'min_x', np.min( x ) print 'max_x', np.max( x ) print 'min_y', np.min( y ) print 'max_y', np.max( y ) print 'min_z', np.min( z ) print 'max_z', np.max( z ) # print x_axis, y_axis, z_axis engine = Engine() engine.start() if len( engine.scenes ) == 0: engine.new_scene # print os.curdir # os.chdir( '.' )() if self.autowarp_bool: x = x / x[-1] y = y / y[0][-1] z = z / z[-1] * self.z_scale # print x, y, z mlab.surf( x, y , z, representation = 'wireframe', line_width = 10 ) # ,warp_scale = "auto" if 'config.py' in os.listdir( os.curdir ): execfile( 'config.py' ) os.chdir( os.pardir ) os.chdir( os.pardir ) else: os.chdir( os.pardir ) os.chdir( os.pardir ) 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.outline() outline = engine.scenes[0].children[0].children[0].children[0].children[0].children[1] outline.actor.property.specular_color = ( 0.0, 0.0, 0.0 ) outline.actor.property.diffuse_color = ( 0.0, 0.0, 0.0 ) outline.actor.property.ambient_color = ( 0.0, 0.0, 0.0 ) outline.actor.property.color = ( 0.0, 0.0, 0.0 ) mlab.show()
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()
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()
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 )
def __init__(self): self.vmin = None self.vmax = None self.current_figure = -1 self.figure_offset_scale = 1.0 self.use_figure_offset_scale = True try: self.engine = mayavi.engine except NameError: from mayavi.api import Engine self.engine = Engine() self.engine.start()
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
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()
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
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()
ccz = pickle.load(open(case.resultPath[time] + pickleName + '_ccz.p', 'rb'), encoding='latin1') eigVals3D = pickle.load(open( case.resultPath[time] + pickleName + '_' + fields + '_eigVals.p', 'rb'), encoding='latin1') eigVecs4D = pickle.load(open( case.resultPath[time] + pickleName + '_' + fields + '_eigVecs.p', 'rb'), encoding='latin1') """ Mayavi Quiver Visualization """ # Start engine, don't know why engine = Engine() engine.start() axes = Axes() mlab.figure(pickleName + '_quivers', engine=engine, size=(1000, 800), bgcolor=(1, 1, 1), fgcolor=(0.5, 0.5, 0.5)) quiver = mlab.quiver3d(ccx, ccy, ccz, eigVecs4D[:, :, 0, 0].ravel(), eigVecs4D[:, :, 0, 1].ravel(), eigVecs4D[:, :, 0, 2].ravel(), scalars=eigVals3D[:, :, 0].ravel(), mask_points=150,
class plotObj(): ''' classes that plot various aspects of a brain object ''' def __init__(self, bg=None): # initialise mayavi figure self.startMayavi(bg) 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 def coordsToList(self, brain, nodeList=None): ''' get coordinates from lists in the brain object, possibly using only the indices given by nodeList and edgeList ''' # select some rows if necessary if not nodeList: nodeList = brain.G.nodes() # get coordinates # make into array for easy output # coords = array([brain.G.node[x]['xyz'] for x in nodeList]) # # get nodes from networkx object # else: coords = [] for x in brain.G.nodes(): # put into list try: coords.append(brain.G.node[x]['xyz']) except KeyError: print('node ' + str(x) + ' not found in function coordsToList') coords = array(coords) # return x, y and z coordinates return coords[:, 0], coords[:, 1], coords[:, 2] def edgesToList(self, brain): ''' Turn the edges of a brain into coordinates ''' # intialise output x1 = [] x2 = [] y1 = [] y2 = [] z1 = [] z2 = [] s = [] for e in brain.G.edges(data = True): # get coord and vector from each edge p1 = brain.G.node[e[0]]['xyz'] p2 = brain.G.node[e[1]]['xyz'] x1.append(p1[0]) x2.append(p2[0]-p1[0]) y1.append(p1[1]) y2.append(p2[1]-p1[1]) z1.append(p1[2]) z2.append(p2[2]-p1[2]) # set scalar value as edge weight s.append(e[2]['weight']) return x1, y1, z1, x2, y2, z2, s def plotBrain(self, brain, opacity = 1.0, edgeOpacity = None, label = 'plot', plotHighlights = True): ''' plot all the coords, edges and highlights in a brain ''' # sort out the edge opacity if not(edgeOpacity): edgeOpacity = opacity # plot coords coords = self.coordsToList(brain) self.plotCoords(coords, opacity = opacity, label=label) # plot edges ex1, ey1, ez1, ux, uy, yz, s = self.edgesToList(brain) self.plotEdges(ex1, ey1, ez1, ux, uy, yz, s, col = (0.,0.,0.), opacity = opacity, label=label) # plot the highlights if plotHighlights: self.plotBrainHighlights(brain) def plotBrainCoords(self, brain, nodes=None, opacity = 1.0, label = 'coordplot', sizeList=None, col=(0.,0.,0.), sf=None, sfRange=None): ''' plot all coordinates in a brain ''' coords = self.coordsToList(brain, nodeList=nodes) self.plotCoords(coords, opacity = opacity, label=label, col=col, sizeList=sizeList, sf=sf, sfRange=sfRange) def plotBrainEdges(self, brain, opacity = 1.0, label = 'edgeplot', col=None, cm ='GnBu', lw=2., scalars=None): ''' plot all edges within a brain lw = line width #### Not working currently - plots in a different window #### --Really, seems OK to me! ''' ex1, ey1, ez1, ux, uy, yz, s = self.edgesToList(brain) if scalars: s=scalars self.plotEdges(ex1, ey1, ez1, ux, uy, yz, s, lw=lw, col = col, cm=cm, opacity = opacity, label=label) def plotBrainHighlights(self, brain, highlights = [], labelPre = ''): ''' plot all or some of the highlights in a brain labelPre allow for a standard prefix (this is used by the GUI) ''' if highlights == []: highlights = brain.highlights # plot highlights (subsets of edges or points) for h in highlights: label = labelPre + h try: ho = brain.highlights[h] except: print('highlight not found: ' + h) continue # get edge data ex1, ey1, ez1, ux, uy, yz, s = ho.getEdgeCoordsToPlot(brain) # get node data hp = ho.nodeIndices # # case where there are node and edges # if (len(ex1)<0 | len(ex1)<0): # print('highlight ' + h + ' has nodes and edges, label will change') # labelEdge = label + '_edge' # labelNode = label + '_node' # else: # labelEdge = label # labelNode = label # case where edge opacity is not separately defined if not(ho.edgeOpacity): ho.edgeOpacity = ho.opacity # plot the edges if not(len(ex1)==0): self.plotEdges(ex1, ey1, ez1, ux, uy, yz, s, col = ho.colour, opacity = ho.edgeOpacity, label=label) # plot the nodes if not(len(hp)==0): x, y, z = ho.getCoords(brain) self.plotCoords((x,y,z), col = ho.colour, opacity = ho.opacity, label=label) def plotCoords(self, coords, col = (1.,1.,1.), opacity = 1., label='plot', sizeList=None, sf=1., sfRange=None): ''' plot the coordinates of a brain object "absoluteScaling" is an option to use and absolute rather than a relative scaling, particularly useful for multiple plots ''' # remove old version, if any if label in self.brainNodePlots: self.brainNodePlots[label].remove() if sizeList==None: # note that scalar value is currently set to 1. ptdata = mlab.pipeline.scalar_scatter(coords[0], coords[1], coords[2], figure = self.mfig) sf = 1. else: try: float(sizeList) sizeList = repeat(sizeList, len(coords[0])) except: pass if not sf: sf = 5./power(max(sizeList), 1/3) print "sf calculated as: "+str(sf) ptdata = mlab.pipeline.scalar_scatter(coords[0], coords[1], coords[2], sizeList, figure = self.mfig) self.brainNodePlots[label] = mlab.pipeline.glyph(ptdata, color = col, opacity = opacity, scale_factor=sf, scale_mode="scalar") if sfRange: print "Adjusting glyph range" self.brainNodePlots[label].glyph.glyph.range = array(sfRange) # record label for order # self.plotKeys.append(label) # self.brainNodePlots[label] = p # print(label, p) def plotEdges(self, ex1, ey1, ez1, ux, uy, uz, s, lw=2., col = None, opacity = 1., cm = 'GnBu', label='plot'): ''' plot some edges ec has the order [x0, x1, y0, y1, z0, z1] s is the scalars - used to determine the node colour cm = 'GnBu' colormap for plotting scalars col is a triple of numbers in the interval (0,1), or None lw is the line width ''' if label in self.brainEdgePlots: self.brainEdgePlots[label].remove() plotmode = '2ddash' # could be modified later # add data to mayavi # edata = mlab.pipeline.vector_scatter(ex1, ey1, ez1, ux, uy, yz, scalars = s, figure = self.mfig) # plot self.brainEdgePlots[label] = mlab.quiver3d(ex1, ey1, ez1, ux, uy, uz, scalars = s, line_width=lw, opacity=opacity, mode = plotmode, color = col, scale_factor = 1., scale_mode = 'vector', colormap = cm) if not col: self.brainEdgePlots[label].glyph.color_mode = 'color_by_scalar' def getCoords(self, brain, edge): ''' get coordinates from nodes and return a coordinate and a vector ''' c1 = brain.G.node[edge[0]]["xyz"] c2 = brain.G.node[edge[1]]["xyz"] diff = [c2[0]-c1[0], c2[1]-c1[1], c2[2]-c1[2]] return c1, diff def plotSkull(self, brain, label = None, contourVals = [], opacity = 0.1, cmap='Spectral'): ''' plot the skull using Mayavi ''' if not(label): label = self.getAutoLabel() # remove old version if not(label in self.skullPlots): self.skullPlots[label].remove() if contourVals == []: self.skullPlots[label] = mlab.contour3d(brain.background, opacity = opacity, colormap=cmap) else: self.skullPlots[label] = mlab.contour3d(brain.background, opacity = opacity, contours = contourVals, colormap=cmap) # get the object for editing # self.skullPlots[label] = s def plotIsosurface(self, brain, label = None, contourVals = [], opacity = 0.1, cmap='autumn'): ''' plot an isosurface using Mayavi, almost the same as skull plotting ''' if not(label): label = self.getAutoLabel() if label in self.isosurfacePlots: self.isosurfacePlots[label].remove() if contourVals == []: self.isosurfacePlots[label] = mlab.contour3d(brain.iso, opacity = opacity, colormap=cmap) else: self.isosurfacePlots[label] = mlab.contour3d(brain.iso, opacity = opacity, contours = contourVals, colormap=cmap) # get the object for editing # self.isosurfacePlots[label] = s def plotParcels(self, brain, label = None, contourVals = [], opacity = 0.5, cmap='autumn'): ''' plot an isosurface using Mayavi, almost the same as skull plotting ''' if not(label): label = self.getAutoLabel() if contourVals == []: self.isosurfacePlots[label] = mlab.contour3d(brain.parcels, opacity = opacity, colormap=cmap) else: self.isosurfacePlots[label] = mlab.contour3d(brain.parcels, opacity = opacity, contours = contourVals, colormap=cmap) # get the object for editing # self.isosurfacePlots[label] = s def changePlotProperty(self, plotType, prop, plotLabel, value = 0.): ''' change a specified property prop of a plot of type plotType, index is used if multiple plots of the same type have been made. Value is used by some properties. Allowed plotTypes: skull, brainNode, brainEdge Allowed props: opacity, visibility, colour This is basically a shortcut to mayavi visualisation functions ''' try: # get plot if plotType == 'skull': plot = self.skullPlots[plotLabel] elif plotType == 'nodes': plot = self.brainNodePlots[plotLabel] elif plotType == 'edges': plot = self.brainEdgePlots[plotLabel] else: print('plotType not recognised: ' + plotType) return except: # quietly go back if the selected plot doesn't exist return # change plot opacity if prop == 'opacity': try: plot.actor.property.opacity = value except: print('opacity value not recognised, should be a float', value) # toggle plot visibility elif prop == 'visibility': if type(value)!=bool: if plot.actor.actor.visibility: plot.actor.actor.visibility = False else: plot.actor.actor.visibility = True else: plot.actor.actor.visibility = value # change plot colour elif prop == 'colour': try: plot.actor.property.color = value except: print('colour not recognised, should be a triple of values between 0 and 1', value) else: print('property not recognised') def getPlotProperty(self, plotType, prop, plotLabel): ''' return the value of a given property for a given plot ''' # get plot if plotType == 'skull': plot = self.skullPlots[plotLabel] elif plotType == 'nodes': plot = self.brainNodePlots[plotLabel] elif plotType == 'edges': plot = self.brainEdgePlots[plotLabel] else: print('plotType not recognised: ' + plotType ) return if prop == 'opacity': value = plot.actor.property.opacity elif prop == 'visibility': value = plot.actor.actor.visibility elif prop == 'colour': value = plot.actor.property.color else: print('property not recognised') return return value def getAutoLabel(self): ''' generate an automatic label for a plot object if none given ''' # get index of label num = str(self.labelNo) num = '0' * (4-len(num)) + num # make label and print label = 'plot ' + num print('automatically generated label: '+ label) # iterate label index self.labelNo = self.labelNo + 1 return label def clear(self): ''' clear current plot ''' mlab.clf() # need to clear other things here self.brainNodePlots = {} self.brainEdgePlots = {} self.skullPlots = {} self.isosurfacePlots = {} # autolabel for plots self.labelNo = 0
# Recorded script from Mayavi2 from numpy import array 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() # ------------------------------------------- scene = engine.scenes[0] vtk_file_reader = engine.open(u'out.vtk', scene) from mayavi.modules.surface import Surface surface = Surface() engine.add_filter(surface, vtk_file_reader) from mayavi.modules.iso_surface import IsoSurface iso_surface1 = IsoSurface() vtk_file_reader = engine.scenes[0].children[0] engine.add_filter(iso_surface1, vtk_file_reader) scene.scene.x_minus_view() hand=mlab.gcf(engine) mlab.figure(hand,bgcolor=(1,1,1)) surface.actor.property.opacity = 0.78 scene.scene.save(u'out.png')
""" 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)
# 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/tube_5_duals/z_10.vtk') ##vtk_file_reader2 = engine.open(u'/home/matcha/Desktop/RESEARCH/spammsand_may_10_2015/spammsand/350_6311gss/z_12.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) iso_surface2.actor.property.color = (1.0, 1.0, 1.0)
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()
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)
# 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_6311gss_duals/y_15.vtk') ##vtk_file_reader2 = engine.open(u'/home/matcha/Desktop/RESEARCH/spammsand_may_10_2015/spammsand/350_6311gss/y_12.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) iso_surface2.actor.property.color = (1.0, 1.0, 1.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() # ------------------------------------------- scene = engine.scenes[0] scene.scene.camera.position = [ 311.77701153000146, 311.77701153000146, 311.77701153000146 ] scene.scene.camera.focal_point = [64.5, 64.5, 64.5] scene.scene.camera.view_angle = 30.0 scene.scene.camera.view_up = [0.0, 0.0, 1.0] scene.scene.camera.clipping_range = [203.4193931866478, 712.40317819590632] scene.scene.camera.compute_view_plane_normal() scene.scene.render() image_plane_widget1 = engine.scenes[0].children[1].children[0].children[0] image_plane_widget1.ipw.origin = array([0.5, 1., 0.5]) image_plane_widget1.ipw.slice_index = 0 image_plane_widget1.ipw.slice_position = 1.0 image_plane_widget1.ipw.point1 = array([0.5, 1., 128.5]) image_plane_widget1.ipw.point2 = array([128.5, 1., 0.5]) image_plane_widget1.ipw.origin = array([0.5, 1., 0.5]) image_plane_widget1.ipw.point1 = array([0.5, 1., 128.5]) image_plane_widget1.ipw.point2 = array([128.5, 1., 0.5]) image_plane_widget2 = engine.scenes[0].children[2].children[0].children[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)
# 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_6311gss_duals/z_15.vtk') ##vtk_file_reader2 = engine.open(u'/home/matcha/Desktop/RESEARCH/spammsand_may_10_2015/spammsand/350_6311gss/z_12.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) iso_surface2.actor.property.color = (1.0, 1.0, 1.0)
#!/usr/bin/python import sys if len(sys.argv) < 2: sys.exit("Usage: %s file.vtk" % sys.argv[0]) from numpy import array from mayavi.modules.axes import Axes from mayavi.api import Engine from mayavi.modules.streamline import Streamline from mayavi.tools.show import show try: engine = mayavi.engine except NameError: engine = Engine() engine.start() if len(engine.scenes) == 0: engine.new_scene() scene = engine.scenes[0] vtk_file_reader = engine.open(sys.argv[1]) axes = Axes() engine.add_filter(axes, vtk_file_reader) streamline = Streamline() engine.add_filter(streamline, vtk_file_reader) streamline.seed.widget.center = array([0.0, 12.0, 12.0]) streamline.seed.widget.center = array([0.0, 12.0, 12.0]) streamline.seed.widget.handle_direction = array([1.0, 0.0, 0.0]) streamline.seed.widget.enabled = False
import numpy as np from mayavi.mlab import * from mayavi.modules.contour_grid_plane import ContourGridPlane def mytest_contour3d(trans): x, y, z = np.ogrid[-5:5:64j, -5:5:64j, -5:5:64j] scalars = x * x * 0.5 + y * y + z * z * 2.0 obj = contour3d(scalars, contours=4, transparent=trans, opacity=1) return obj from mayavi.api import Engine engine = Engine() engine.start() if len(engine.scenes) == 0: engine.new_scene() # -------------------------- engine.new_scene() a = mytest_contour3d(False) cgp = ContourGridPlane() engine.add_module(cgp) cgp.grid_plane.axis = 'y' show()
[np.sin(T_z), np.cos(T_z), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ]) @ np.array([ [1, 0, 0, 0], [0, np.cos(T_x), -np.sin(T_x), 0], [0, np.sin(T_x), np.cos(T_x), 0], [0, 0, 0, 1], ]) c.mesh.apply_transform(rotmat) from mayavi import mlab from mayavi.api import Engine e = Engine() e.start() f = mlab.figure(None, bgcolor=(1, 1, 1), fgcolor=(0.5, 0.5, 0.5), size=(750, 900)) surfaces = c.suh_basis.plot(Nfuncs=c.basis.shape[1], Ncols=2, dist=0.1, colormap="RdBu", figure=f, ncolors=256) f.scene.z_plus_view()
# 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() # ------------------------------------------- scene = engine.scenes[0] scene.scene.camera.position = [311.77701153000146, 311.77701153000146, 311.77701153000146] scene.scene.camera.focal_point = [64.5, 64.5, 64.5] scene.scene.camera.view_angle = 30.0 scene.scene.camera.view_up = [0.0, 0.0, 1.0] scene.scene.camera.clipping_range = [203.4193931866478, 712.40317819590632] scene.scene.camera.compute_view_plane_normal() scene.scene.render() image_plane_widget1 = engine.scenes[0].children[1].children[0].children[0] image_plane_widget1.ipw.origin = array([ 0.5, 1. , 0.5]) image_plane_widget1.ipw.slice_index = 0 image_plane_widget1.ipw.slice_position = 1.0 image_plane_widget1.ipw.point1 = array([ 0.5, 1. , 128.5]) image_plane_widget1.ipw.point2 = array([ 128.5, 1. , 0.5]) image_plane_widget1.ipw.origin = array([ 0.5, 1. , 0.5]) image_plane_widget1.ipw.point1 = array([ 0.5, 1. , 128.5]) image_plane_widget1.ipw.point2 = array([ 128.5, 1. , 0.5]) image_plane_widget2 = engine.scenes[0].children[2].children[0].children[0] image_plane_widget2.ipw.origin = array([ 0.5, 0.5, 1. ]) image_plane_widget2.ipw.slice_index = 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)
class Mapper: def __init__(self): self.vmin = None self.vmax = None self.current_figure = -1 self.figure_offset_scale = 1.0 self.use_figure_offset_scale = True try: self.engine = mayavi.engine except NameError: from mayavi.api import Engine self.engine = Engine() self.engine.start() def create_figure(self): mlab.figure(size=(400, 320)) def show(self): mlab.show() def parse_srtm_data(self, zip_path, hgt_path): self._data = np.fromstring(zipfile.ZipFile(zip_path).read(hgt_path), '>i2') data_sqrt_for_shaping = math.sqrt(self._data.shape[0]) self._data.shape = (data_sqrt_for_shaping, data_sqrt_for_shaping) self._data = self._data.astype(np.float32) self._data[self._data == -32768] = self._data[self._data > 0].min() def adjust_offsets(self, map_offset_x = 0.0, map_offset_y = 0.0, map_offset_z = 0.0): self.current_figure += 1 figure_array_source = self.engine.scenes[0].children[self.current_figure] if self.use_figure_offset_scale: figure_array_source.origin = np.array([self.figure_offset_scale * map_offset_x, self.figure_offset_scale * map_offset_y, self.figure_offset_scale * map_offset_z]) else: figure_array_source.origin = np.array([map_offset_x, map_offset_y, map_offset_z]) def create_surf_map(self, zip_path, hgt_path, map_offset_x = 0.0, map_offset_y = 0.0, map_offset_z = 0.0): self.parse_srtm_data(zip_path, hgt_path) mlab.surf(self._data, name=hgt_path, colormap='gist_earth', warp_scale=0.2, vmin=self.vmin, vmax=self.vmax) self.adjust_offsets(map_offset_x, map_offset_y, map_offset_z) del self._data def create_decimated_map(self, zip_path, hgt_path, number_of_triangles = 5000, compute_normals = True, map_offset_x = 0.0, map_offset_y = 0.0, map_offset_z = 0.0): self.parse_srtm_data(zip_path, hgt_path) _pipelined_data = mlab.pipeline.array2d_source(self._data) terrain = mlab.pipeline.greedy_terrain_decimation(_pipelined_data) terrain.filter.error_measure = 'number_of_triangles' terrain.filter.number_of_triangles = number_of_triangles terrain.filter.compute_normals = compute_normals surf = mlab.pipeline.surface(terrain, colormap='gist_earth', vmin=self.vmin, vmax=self.vmax) self.adjust_offsets(map_offset_x, map_offset_y, map_offset_z) del self._data def calculate_min_max(self, zip_path, hgt_path): self.parse_srtm_data(zip_path, hgt_path) min = np.amin(self._data) max = np.amax(self._data) del self._data return (min, max)
depthFile2 = base_dir+'device_2/'+'depth_100_11_15_59_13_395133.png' result: T = np.array([[0.857551855717905, 0.11935353392976167, 0.5003594195108932, -1053.586999301418], [0.1430128492517155, 0.8790419590510106, -0.45478847740098743, 1081.8626448851123], [-0.4941175363248235, 0.4615625289885183, 0.736754974282534, 1295.7083313896273], [0.0, 0.0, 0.0, 1.0]]) ''' ''' --------------------Main setup-------------------------------- ''' depthIm1 = imread(depthFile1) depthIm2 = imread(depthFile2) pts1 = depthIm2XYZ(depthIm1).astype(np.int) pts2 = depthIm2XYZ(depthIm2).astype(np.int) engine = Engine() engine.start() figure = mlab.figure(1, bgcolor=(0, 0, 0), fgcolor=(1, 1, 1)) mlab.clf() figure.scene.disable_render = True interval = 40 # Don't show all points (otherwise it's slow!) pts = np.array([x for x in pts1 if x[2] > -93500]) pts = np.vstack([[0, 0, 1], pts]) ptsViz1 = mlab.points3d(pts[::interval, 0], pts[::interval, 1], pts[::interval, 2], 2. - (np.minimum(pts[::interval, 2], 5000) / float( (-pts[:, 2]).max())) / 1000., scale_factor=30.,
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)
depthIm2 = imread(depthFile2) depthIm3 = imread(depthFile3) ''' Put all in the frame of 2 ''' pts1 = depthIm2XYZ(depthIm1).astype(np.int) pts2 = depthIm2XYZ(depthIm2).astype(np.int) pts3 = depthIm2XYZ(depthIm3).astype(np.int) p1 = depthIm2PosIm(depthIm1) p2 = depthIm2PosIm(depthIm2) p3 = depthIm2PosIm(depthIm3) '''3DViz''' engine = Engine() engine.start() figure = mlab.figure(1, bgcolor=(0,0,0), fgcolor=(1,1,1)) mlab.clf() figure.scene.disable_render = True interval = 15 '''2''' pts = np.array([x for x in pts2 if x[2] > -93500]) ptsViz1 = mlab.points3d(pts[::interval,0], pts[::interval,1], pts[::interval,2], 2.-(np.minimum(pts[::interval,2], 5000)/float((-pts[:,2]).max()))/1000., scale_factor=10., colormap='Blues') '''3''' pts = np.array([x for x in pts3 if x[2] > -93500]) ptsViz2 = mlab.points3d(pts[::interval,0], pts[::interval,1], pts[::interval,2], 2.-(np.minimum(pts[::interval,2], 5000)/float((-pts[:,2]).max()))/1000., scale_factor=10., colormap='PuOr')
import os from os.path import join # Enthought library imports from mayavi import mlab from mayavi.mlab import * import mayavi from mayavi.api import Engine import time temp_file = argv[1] # temp_file = '/home/ashj/DEM_results/FBRGB/fbIN128/thesis_plots/GT_0_10.ply' # Render the dragon ply file from mayavi.api import Engine engine = Engine() engine.start() if len(engine.scenes) == 0: engine.new_scene() mlab.pipeline.surface(mlab.pipeline.open(temp_file)) mlab.points3d([0], [0], [1973.9], color=(0, 1, 0), scale_factor=5) mlab.points3d([0], [398], [1829.6], color=(1, 0, 0), scale_factor=5) import numpy as np from mayavi import mlab # x, y = np.mgrid[0:3:1,0:3:1] s = mlab.pipeline.surface(mlab.pipeline.open(temp_file)) print(mlab.view()) @mlab.animate def anim():
# Recorded script from Mayavi2 from numpy import array 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() # ------------------------------------------- vtk_file_reader = engine.open('/home/dori/develop/pySAM/vtk/_55_1.11595_1.70081e-05.vtk') from mayavi.modules.surface import Surface surface = Surface() engine.add_filter(surface, vtk_file_reader) mlab.savefig('scene.png')
# 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.])
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()
# 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'x_19.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) iso_surface2.actor.property.color = (1.0, 1.0, 1.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) iso_surface2.actor.property.color = (1.0, 1.0, 1.0)
Co3O4_lat2 = rsp.lattice.lattice_from_cif('/home/finn/Documents/eclipse_workspace/2017_MA3074/preparation/structure_simulation/Co3O4.cif', HKL_normal = [1,1,1], HKL_para_x=[1,1,-2], offset_angle=90) Co3O4_lat3 = rsp.lattice.lattice_from_cif('/home/finn/Documents/eclipse_workspace/2017_MA3074/preparation/structure_simulation/Co3O4.cif', HKL_normal = [1,1,1], HKL_para_x=[1,1,-2], offset_angle=180) Co3O4_lat4 = rsp.lattice.lattice_from_cif('/home/finn/Documents/eclipse_workspace/2017_MA3074/preparation/structure_simulation/Co3O4.cif', HKL_normal = [1,1,1], HKL_para_x=[1,1,-2], offset_angle=270) 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,
#!/usr/bin/python import sys if len(sys.argv) < 2: sys.exit('Usage: %s file.vtk' % sys.argv[0]) from numpy import array from mayavi.modules.axes import Axes from mayavi.api import Engine from mayavi.modules.surface import Surface from mayavi.tools.show import show try: engine = mayavi.engine except NameError: engine = Engine() engine.start() if len(engine.scenes) == 0: engine.new_scene() scene = engine.scenes[0] vtk_file_reader = engine.open(sys.argv[1], scene) axes = Axes() axes.property.color = (0.0, 0.0, 0.0) engine.add_filter(axes, vtk_file_reader) surface = Surface() engine.add_filter(surface, vtk_file_reader) scene.scene.background = (1.0, 1.0, 1.0) scene.scene.foreground = (0.0, 0.0, 0.0) surface.contour.contours = [1.5] surface.actor.mapper.progress = 1.0 surface.actor.mapper.scalar_range = array([ 0., 3.])
# 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'x_19.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)
from math import pi, atan # cos, sqrt, sin, tan import numpy as np from mayavi import mlab from utilities.coordinate_utilities import spherical_to_cartesian, cartesian_to_spherical try: from mayavi import engine except ImportError: from mayavi.api import Engine engine = Engine() engine.start() if __name__ == '__main__': radius_sphere = 1.0 length_rod = 10.0 dist_gap = 0.5 dist_to_rod = radius_sphere + dist_gap k = (4 * pi * 8.85e-12)**-1 charge_density_Cpm = -1e-6 n_field_pts_radial = 8 n_field_pts_theta = 36 n_field_pts_phi = 36 n_source_pts_theta = 32 radial_max = 0.9 * dist_to_rod radial_min = 1.1 * radius_sphere
# 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)
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)
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)
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()
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)
# #src = mlab.pipeline.scalar_field(s) #mlab.pipeline.iso_surface(src, contours=[s.min()+0.1*s.ptp(), ], opacity=0.3) #mlab.pipeline.iso_surface(src, contours=[s.max()-0.1*s.ptp(), ],) def minc_reader(fname): #Reader for .mnc files. #Parameters: #fname -- Filename to be read. from tvtk.api import tvtk from mayavi.sources.vtk_data_source import VTKDataSource r = tvtk.MINCImageReader(file_name=fname) r.update() src = VTKDataSource(data=r.output) print src.data return src from mayavi.api import Engine e = Engine() e.start() s = e.new_scene() source = minc_reader('/home/sulantha/Downloads/new_temp.mnc') e.add_source(source) from mayavi.modules.api import Surface surf = Surface() e.add_module(surf, obj=source) mlab.show()