def _readVtkFile(self): """Function to read tensor from a file and store the info in a numpy array. """ from enthought.mayavi.sources.vtk_file_reader import VTKFileReader from enthought.tvtk.api import tvtk reader = VTKFileReader() reader.initialize(self.vtkInputFile) data = reader.outputs[0] # Get vertex and cell info. cellVtk = data.get_cells() numCells = cellVtk.number_of_cells cellArray = cellVtk.to_array() self.cells = tvtk.CellArray() self.cells.set_cells(numCells, cellArray) self.vertArray = data._get_points().to_array() self.cellType = data.get_cell_type(0) (numVerts, self.spaceDim) = self.vertArray.shape # Get cell fields and extract tensor. cellData = data._get_cell_data() numCellDataArrays = cellData._get_number_of_arrays() tensor = cellData.get_array(self.vtkTensorIndex).to_array() (self.numTensorPoints, numCols) = tensor.shape sxx = tensor[:, self.vtkTensorComponentsOrder[0]] syy = tensor[:, self.vtkTensorComponentsOrder[1]] szz = tensor[:, self.vtkTensorComponentsOrder[2]] sxy = tensor[:, self.vtkTensorComponentsOrder[3]] syz = tensor[:, self.vtkTensorComponentsOrder[4]] sxz = tensor[:, self.vtkTensorComponentsOrder[5]] self.tensorSorted = numpy.column_stack((sxx, syy, szz, sxy, syz, sxz)) return
def animateVTKFiles_2D(folder): if not os.path.isdir(folder): return vtkFiles = [] for f in sorted(os.listdir(folder)): if f.endswith(".vtk"): vtkFiles.append(os.path.join(folder, f)) if len(vtkFiles) == 0: return figure = mlab.figure(size=(800, 600)) figure.scene.disable_render = True vtkSource = VTKFileReader() vtk_file = vtkFiles[0] vtkSource.initialize(vtk_file) surface = mlab.pipeline.surface(vtkSource) axes = mlab.axes() colorbar = mlab.colorbar(object=surface, orientation='horizontal') mlab.view(0, 0) figure.scene.disable_render = False mlab.draw() a = animateVTKFiles(figure, vtkSource, vtkFiles)
def _readFaultInfo(self): """ Function to read fault information from VTK file. """ from enthought.mayavi.sources.vtk_file_reader import VTKFileReader from enthought.tvtk.api import tvtk reader = VTKFileReader() reader.initialize(self.faultInfoFile) data = reader.outputs[0] # Get cell and vertex info. cellVtk = data.get_cells() self.numFaultCells = cellVtk.number_of_cells self.faultCellArray = cellVtk.to_array() self.faultVertices = data._get_points().to_array() self.cellType = data.get_cell_type(0) (self.numFaultVertices, self.spaceDim) = self.faultVertices.shape # Get vertex fields and extract normal vectors. vertData = data._get_point_data() numVertDataArrays = vertData._get_number_of_arrays() for vertDataArray in range(numVertDataArrays): arrayName = vertData.get_array_name(vertDataArray) if (arrayName == "normal_dir"): self.normalDir = vertData.get_array(vertDataArray).to_array() elif (arrayName == "strike_dir"): self.strikeDir = vertData.get_array(vertDataArray).to_array() elif (arrayName == "dip_dir"): self.dipDir = vertData.get_array(vertDataArray).to_array() return
def showVTKFile_2D(filename): figure = mlab.figure(size=(800, 600)) vtkSource = VTKFileReader() vtkSource.initialize(filename) surface = mlab.pipeline.surface(vtkSource) axes = mlab.axes() colorbar = mlab.colorbar(object=surface, orientation='horizontal') mlab.view(0, 0) mlab.show()
def setup_data(fname): """Given a VTK file name `fname`, this creates a mayavi2 reader for it and adds it to the pipeline. It returns the reader created. """ # 'mayavi' is always defined on the interpreter. d = VTKFileReader() d.initialize(fname) mayavi.add_source(d) return d
def contour(): """The script itself. We needn't have defined a function but having a function makes this more reusable. """ # 'mayavi' is always defined on the interpreter. # Create a new scene. mayavi.new_scene() # Read a VTK (old style) data file. r = VTKFileReader() filename = join(mayavi2.get_data_dir(dirname(abspath(__file__))), 'heart.vtk') r.initialize(filename) mayavi.add_source(r) # Create an outline for the data. o = Outline() mayavi.add_module(o) # Create three simple grid plane modules. # First normal to 'x' axis. gp = GridPlane() mayavi.add_module(gp) # Second normal to 'y' axis. gp = GridPlane() mayavi.add_module(gp) gp.grid_plane.axis = 'y' # Third normal to 'z' axis. gp = GridPlane() mayavi.add_module(gp) gp.grid_plane.axis = 'z' # Create one ContourGridPlane normal to the 'x' axis. cgp = ContourGridPlane() mayavi.add_module(cgp) # Set the position to the middle of the data. cgp.grid_plane.position = 15 # Another with filled contours normal to 'y' axis. cgp = ContourGridPlane() mayavi.add_module(cgp) # Set the axis and position to the middle of the data. cgp.grid_plane.axis = 'y' cgp.grid_plane.position = 15 cgp.contour.filled_contours = True # An isosurface module. iso = IsoSurface(compute_normals=True) mayavi.add_module(iso) iso.contour.contours = [220.0] # An interactive scalar cut plane. cp = ScalarCutPlane() mayavi.add_module(cp) cp.implicit_plane.normal = 0,0,1
def contour(): """The script itself. We needn't have defined a function but having a function makes this more reusable. """ # 'mayavi' is always defined on the interpreter. # Create a new scene. mayavi.new_scene() # Read a VTK (old style) data file. r = VTKFileReader() filename = join(mayavi2.get_data_dir(dirname(abspath(__file__))), 'heart.vtk') r.initialize(filename) mayavi.add_source(r) # Create an outline for the data. o = Outline() mayavi.add_module(o) # Create three simple grid plane modules. # First normal to 'x' axis. gp = GridPlane() mayavi.add_module(gp) # Second normal to 'y' axis. gp = GridPlane() mayavi.add_module(gp) gp.grid_plane.axis = 'y' # Third normal to 'z' axis. gp = GridPlane() mayavi.add_module(gp) gp.grid_plane.axis = 'z' # Create one ContourGridPlane normal to the 'x' axis. cgp = ContourGridPlane() mayavi.add_module(cgp) # Set the position to the middle of the data. cgp.grid_plane.position = 15 # Another with filled contours normal to 'y' axis. cgp = ContourGridPlane() mayavi.add_module(cgp) # Set the axis and position to the middle of the data. cgp.grid_plane.axis = 'y' cgp.grid_plane.position = 15 cgp.contour.filled_contours = True # An isosurface module. iso = IsoSurface(compute_normals=True) mayavi.add_module(iso) iso.contour.contours = [220.0] # An interactive scalar cut plane. cp = ScalarCutPlane() mayavi.add_module(cp) cp.implicit_plane.normal = 0, 0, 1
def setup_data(fname): """Given a VTK file name `fname`, this creates a mayavi2 reader for it and adds it to the pipeline. It returns the reader created. """ # 'mayavi' is always defined on the interpreter. mayavi.new_scene() d = VTKFileReader() d.initialize(fname) mayavi.add_source(d) return d
def setup_source(self, fname): """Given a VTK file name `fname`, this creates a mayavi2 reader for it and adds it to the pipeline. It returns the reader created. """ if fname is None: return None source = VTKFileReader() source.initialize(fname) mlab.pipeline.add_dataset(source) return source
def run(self): win = self.script.engine.application.gui.GetTopWindow() win.CenterOnScreen() self.script.new_scene() for idx in range(len(self.filelists)): f = self.filelists[idx][0] d = VTKFileReader() d.initialize(f) self.data.append(d) self.filestatus.append(os.stat(f)[-2]) mayavi.add_source(d) self.addmodules(idx, idx == 0) self.modifymenu()
def _readStress(self, vtkFile): """ Function to read stresses from a file and store the info in a numpy array. """ from enthought.mayavi.sources.vtk_file_reader import VTKFileReader from enthought.tvtk.api import tvtk reader = VTKFileReader() reader.initialize(vtkFile) data = reader.outputs[0] # Get vertex and cell info if it hasn't already been done if not self.readMesh: cellVtk = data.get_cells() self.numVertsPerCell = cellVtk._get_max_cell_size() self.numCells = cellVtk.number_of_cells cellArray = cellVtk.to_array() self.cells = tvtk.CellArray() self.cells.set_cells(self.numCells, cellArray) self.vertArray = data._get_points().to_array() self.cellType = data.get_cell_type(0) (self.numVerts, self.spaceDim) = self.vertArray.shape self.readMesh = True # Get cell fields and extract stresses cellData = data._get_cell_data() numCellDataArrays = cellData._get_number_of_arrays() stress = cellData.get_array(self.stressIndex).to_array() (self.numStressPoints, numCols) = stress.shape sxx = stress[:,self.stressComponentsOrder[0]] syy = stress[:,self.stressComponentsOrder[1]] szz = stress[:,self.stressComponentsOrder[2]] sxy = stress[:,self.stressComponentsOrder[3]] syz = stress[:,self.stressComponentsOrder[4]] sxz = stress[:,self.stressComponentsOrder[5]] stressOrdered = numpy.column_stack((sxx, syy, szz, sxy, syz, sxz)) return stressOrdered
def _getVec(self, vtkFile, vecName): """ Function to read a vector from a file and store it in a numpy array. """ from enthought.mayavi.sources.vtk_file_reader import VTKFileReader from enthought.tvtk.api import tvtk reader = VTKFileReader() reader.initialize(vtkFile) data = reader.outputs[0] # Get vertex and cell info if it hasn't already been done if not self.readMesh: cellVtk = data.get_cells() self.numVertsPerCell = cellVtk._get_max_cell_size() self.numCells = cellVtk.number_of_cells cellArray = cellVtk.to_array() self.cells = tvtk.CellArray() self.cells.set_cells(self.numCells, cellArray) self.vertArray = data._get_points().to_array() self.cellType = data.get_cell_type(0) (self.numVerts, self.spaceDim) = self.vertArray.shape self.readMesh = True # Get vertex fields and extract the requested vector. vertData = data._get_point_data() numArrays = vertData._get_number_of_arrays() gotArray = False for vertDataArray in range(numArrays): arrayName = vertData.get_array_name(vertDataArray) if (arrayName == vecName): vector = vertData.get_array(vertDataArray).to_array() gotArray = True if gotArray: break else: raise IOError("Unable to find vector '%s'." % vecName) return vector
def _readVtkFile(self): """ Function to read tensor from a file and store the info in a numpy array. """ from enthought.mayavi.sources.vtk_file_reader import VTKFileReader from enthought.tvtk.api import tvtk reader = VTKFileReader() reader.initialize(self.vtkInputFile) data = reader.outputs[0] # Get vertex and cell info. cellVtk = data.get_cells() numCells = cellVtk.number_of_cells cellArray = cellVtk.to_array() self.cells = tvtk.CellArray() self.cells.set_cells(numCells, cellArray) self.vertArray = data._get_points().to_array() self.cellType = data.get_cell_type(0) (numVerts, self.spaceDim) = self.vertArray.shape # Get cell fields and extract tensor. cellData = data._get_cell_data() numCellDataArrays = cellData._get_number_of_arrays() tensor = cellData.get_array(self.tensorIndex).to_array() (self.numTensorPoints, numCols) = tensor.shape sxx = tensor[:,self.tensorComponentsOrder[0]] syy = tensor[:,self.tensorComponentsOrder[1]] szz = tensor[:,self.tensorComponentsOrder[2]] sxy = tensor[:,self.tensorComponentsOrder[3]] syz = tensor[:,self.tensorComponentsOrder[4]] sxz = tensor[:,self.tensorComponentsOrder[5]] self.tensorSorted = numpy.column_stack((sxx, syy, szz, sxy, syz, sxz)) return
def saveVTKFilesAsImages_2D(sourceFolder, destinationFolder): if not os.path.isdir(sourceFolder) or not os.path.isdir( destinationFolder): return vtkFiles = [] for f in sorted(os.listdir(sourceFolder)): if f.endswith(".vtk"): vtkFiles.append(f) if len(vtkFiles) == 0: return figure = mlab.figure(size=(800, 600)) figure.scene.disable_render = True vtkSource = VTKFileReader() vtk_file = os.path.join(sourceFolder, vtkFiles[0]) vtkSource.initialize(vtk_file) surface = mlab.pipeline.surface(vtkSource) axes = mlab.axes() colorbar = mlab.colorbar(object=surface, orientation='horizontal') mlab.view(0, 0) figure.scene.disable_render = False mlab.draw() png_file = os.path.join(destinationFolder, vtkFiles[0]).replace('.vtk', '.png') mlab.savefig(png_file) for f in vtkFiles[1:-1]: vtk_file = os.path.join(sourceFolder, f) vtkSource.initialize(vtk_file) png_file = os.path.join(destinationFolder, f).replace('.vtk', '.png') mlab.savefig(png_file) app = QtCore.QCoreApplication.instance() if app: app.processEvents()
def do(self): ############################################################ # Imports. script = self.script from enthought.mayavi.sources.vtk_file_reader import VTKFileReader from enthought.mayavi.modules.outline import Outline from enthought.mayavi.modules.grid_plane import GridPlane ############################################################ # Create a new scene and set up the visualization. s = self.new_scene() # Read a VTK (old style) data file. r = VTKFileReader() r.initialize(get_example_data('heart.vtk')) script.add_source(r) # Create an outline for the data. o = Outline() script.add_module(o) # Create three simple grid plane modules. # First normal to 'x' axis. gp1 = GridPlane() script.add_module(gp1) # Second normal to 'y' axis. gp2 = GridPlane() # We'll test how robust things are by setting attributes # *before* we add it to the scene. gp2.grid_plane.axis = 'y' gp2.grid_plane.position = 16 script.add_module(gp2) # Third normal to 'z' axis. gp3 = GridPlane() script.add_module(gp3) gp3.grid_plane.axis = 'z' gp3.grid_plane.position = 6 for gp in (gp1, gp2, gp3): gp.actor.property.set(ambient=1.0) # Set the scene to an isometric view. s.scene.isometric_view() self.check() ############################################################ # Test if saving a visualization and restoring it works. # Save visualization. f = StringIO() f.name = abspath('test.mv2') # We simulate a file. script.save_visualization(f) f.seek(0) # So we can read this saved data. # Remove existing scene. engine = script.engine engine.close_scene(s) # Load visualization script.load_visualization(f) s = engine.current_scene self.check() ############################################################ # Test if the MayaVi2 visualization can be deepcopied. # Pop the source object. source = s.children.pop() # Add it back to see if that works without error. s.children.append(source) self.check() # Now deepcopy the source and replace the existing one with # the copy. This basically simulates cutting/copying the # object from the UI via the right-click menu on the tree # view, and pasting the copy back. source1 = copy.deepcopy(source) s.children[0] = source1 self.check()
def run(self): """This is executed once the application GUI has started. *Make sure all other MayaVi specific imports are made here!* """ # Various imports to do different things. from enthought.mayavi.sources.vtk_file_reader import VTKFileReader from enthought.mayavi.modules.outline import Outline from enthought.mayavi.modules.axes import Axes from enthought.mayavi.modules.grid_plane import GridPlane from enthought.mayavi.modules.image_plane_widget import ImagePlaneWidget from enthought.mayavi.modules.text import Text from enthought.mayavi.modules.contour_grid_plane import ContourGridPlane from enthought.mayavi.modules.iso_surface import IsoSurface script = self.script # Create a new scene. script.new_scene() # Read a VTK (old style) data file. r = VTKFileReader() r.initialize(join(get_data_dir(abspath(__file__)), 'heart.vtk')) script.add_source(r) # Put up some text. t = Text(text='MayaVi rules!', x_position=0.2, y_position=0.9, width=0.8) t.property.color = 1, 1, 0 # Bright yellow, yeah! script.add_module(t) # Create an outline for the data. o = Outline() script.add_module(o) # Create an axes for the data. a = Axes() script.add_module(a) # Create three simple grid plane modules. # First normal to 'x' axis. gp = GridPlane() script.add_module(gp) # Second normal to 'y' axis. gp = GridPlane() gp.grid_plane.axis = 'y' script.add_module(gp) # Third normal to 'z' axis. gp = GridPlane() script.add_module(gp) gp.grid_plane.axis = 'z' # Create one ImagePlaneWidget. ipw = ImagePlaneWidget() script.add_module(ipw) # Set the position to the middle of the data. ipw.ipw.slice_position = 16 # Create one ContourGridPlane normal to the 'x' axis. cgp = ContourGridPlane() script.add_module(cgp) # Set the position to the middle of the data. cgp.grid_plane.axis = 'y' cgp.grid_plane.position = 15 # An isosurface module. iso = IsoSurface(compute_normals=True) script.add_module(iso) iso.contour.contours = [200.0] # Set the view. s = script.engine.current_scene cam = s.scene.camera cam.azimuth(45) cam.elevation(15) s.render()
def run(self): """This is executed once the application GUI has started. *Make sure all other MayaVi specific imports are made here!* """ # Various imports to do different things. from enthought.mayavi.sources.vtk_file_reader import VTKFileReader from enthought.mayavi.modules.outline import Outline from enthought.mayavi.modules.axes import Axes from enthought.mayavi.modules.grid_plane import GridPlane from enthought.mayavi.modules.image_plane_widget import ImagePlaneWidget from enthought.mayavi.modules.text import Text script = self.script # Create a new scene. script.new_scene() # Read a VTK (old style) data file. r = VTKFileReader() r.initialize( join(get_data_dir(dirname(abspath(__file__))), 'heart.vtk')) script.add_source(r) # Put up some text. t = Text(text='MayaVi rules!', x_position=0.2, y_position=0.9, width=0.8) t.property.color = 1, 1, 0 # Bright yellow, yeah! script.add_module(t) # Create an outline for the data. o = Outline() script.add_module(o) # Create an axes for the data. a = Axes() script.add_module(a) # Create an orientation axes for the scene. This only works with # VTK-4.5 and above which is why we have the try block. try: from enthought.mayavi.modules.orientation_axes import OrientationAxes except ImportError: pass else: a = OrientationAxes() a.marker.set_viewport(0.0, 0.8, 0.2, 1.0) script.add_module(a) # Create three simple grid plane modules. # First normal to 'x' axis. gp = GridPlane() script.add_module(gp) # Second normal to 'y' axis. gp = GridPlane() gp.grid_plane.axis = 'y' script.add_module(gp) # Third normal to 'z' axis. gp = GridPlane() script.add_module(gp) gp.grid_plane.axis = 'z' # Create one ImagePlaneWidget. ipw = ImagePlaneWidget() script.add_module(ipw) # Set the position to the middle of the data. ipw.ipw.slice_position = 16
from enthought.mayavi import mlab from enthought.mayavi.sources.vtk_file_reader import VTKFileReader casca = VTKFileReader() casca.initialize('casca.vtk') mlab.pipeline.surface(casca) mlab.show()
def do(self): ############################################################ # Imports. script = self.script from enthought.mayavi.sources.vtk_file_reader import VTKFileReader from enthought.mayavi.modules.outline import Outline from enthought.mayavi.modules.iso_surface import IsoSurface from enthought.mayavi.modules.contour_grid_plane \ import ContourGridPlane from enthought.mayavi.modules.scalar_cut_plane import ScalarCutPlane ############################################################ # Create a new scene and set up the visualization. s = self.new_scene() # Read a VTK (old style) data file. r = VTKFileReader() r.initialize(get_example_data('heart.vtk')) script.add_source(r) # Create an outline for the data. o = Outline() script.add_module(o) # Create one ContourGridPlane normal to the 'x' axis. cgp1 = ContourGridPlane() script.add_module(cgp1) # Set the position to the middle of the data. cgp1.grid_plane.position = 15 # Another with filled contours normal to 'y' axis. cgp2 = ContourGridPlane() cgp2.contour.filled_contours = True # Set the axis and position to the middle of the data. cgp2.grid_plane.axis = 'y' cgp2.grid_plane.position = 15 script.add_module(cgp2) # An isosurface module. iso = IsoSurface(compute_normals=True) script.add_module(iso) iso.contour.contours = [200.0] # An interactive scalar cut plane. cp = ScalarCutPlane() script.add_module(cp) ip = cp.implicit_plane ip.normal = 0, 0, 1 ip.origin = 0, 0, 5 ip.widget.enabled = False # Set the scene to an isometric view. s.scene.isometric_view() # Now test. self.check() ############################################################ # Test if the modules respond correctly when the components # are changed. ctr = cgp2.contour cgp2.contour = ctr.__class__() cgp2.contour = ctr cgp2.actor = cgp2.actor.__class__() iso.contour = iso.contour.__class__() iso.contour.contours = [200.0] iso.actor = iso.actor.__class__() iso.normals = iso.normals.__class__() ip = cp.implicit_plane cp.implicit_plane = cp.implicit_plane.__class__() cp.implicit_plane = ip ip.widget.enabled = False cp.contour = cp.contour.__class__() cp.cutter = cp.cutter.__class__() cp.actor = cp.actor.__class__() s.render() # Now check. self.check() ############################################################ # Test if saving a visualization and restoring it works. # Save visualization. f = StringIO() f.name = abspath('test.mv2') # We simulate a file. script.save_visualization(f) f.seek(0) # So we can read this saved data. # Remove existing scene. engine = script.engine engine.close_scene(s) # Load visualization script.load_visualization(f) s = engine.current_scene self.check() ############################################################ # Test if the MayaVi2 visualization can be deep-copied. # Pop the source object. source = s.children.pop() # Add it back to see if that works without error. s.children.append(source) # Now set the enabled status of the widget, this is impossible # to get correctly. cp = source.children[0].children[-1] cp.implicit_plane.widget.enabled = False self.check() # Now deepcopy the source and replace the existing one with # the copy. This basically simulates cutting/copying the # object from the UI via the right-click menu on the tree # view, and pasting the copy back. source1 = copy.deepcopy(source) s.children[0] = source1 cp = source1.children[0].children[-1] cp.implicit_plane.widget.enabled = False self.check()
def do(self): ############################################################ # Imports. script = self.script from enthought.mayavi.sources.vtk_file_reader import VTKFileReader from enthought.mayavi.filters.contour import Contour from enthought.mayavi.filters.optional import Optional from enthought.mayavi.filters.collection import Collection from enthought.mayavi.filters.api import PolyDataNormals from enthought.mayavi.modules.api import Surface ############################################################ # Create a new scene and set up the visualization. s = self.new_scene() # Read a VTK (old style) data file. r = VTKFileReader() r.initialize(get_example_data('heart.vtk')) script.add_source(r) c = Contour() # `name` is used for the notebook tabs. n = PolyDataNormals(name='Normals') o = Optional(filter=n, label_text='Compute normals') coll = Collection(filters=[c, o], name='IsoSurface') script.add_filter(coll) s = Surface() script.add_module(s) ######################################## # do the testing. def check(coll): """Check if test status is OK given the collection.""" c, o = coll.filters c = c.filter n = o.filter assert coll.outputs[0].point_data.scalars.range == (127.5, 127.5) # Adding a contour should create the appropriate output in # the collection. c.contours.append(200) assert coll.outputs[0].point_data.scalars.range == (127.5, 200.0) # the collection's output should be that of the normals. assert coll.outputs[0] is n.outputs[0] # disable the optional filter and check. o.enabled = False assert 'disabled' in o.name assert coll.outputs[0] is c.outputs[0] # Set back everything to original state. c.contours.pop() o.enabled = True assert coll.outputs[0].point_data.scalars.range == (127.5, 127.5) assert coll.outputs[0] is n.outputs[0] assert 'disabled' not in o.name check(coll) ############################################################ # Test if saving a visualization and restoring it works. # Save visualization. f = StringIO() f.name = abspath('test.mv2') # We simulate a file. script.save_visualization(f) f.seek(0) # So we can read this saved data. # Remove existing scene. engine = script.engine engine.close_scene(s) # Load visualization script.load_visualization(f) s = engine.current_scene # Now do the check. coll = s.children[0].children[0] check(coll) ############################################################ # Test if the Mayavi2 visualization can be deep-copied. # Pop the source object. source = s.children.pop() # Add it back to see if that works without error. s.children.append(source) # Now do the check. coll = s.children[0].children[0] check(coll) # Now deepcopy the source and replace the existing one with # the copy. This basically simulates cutting/copying the # object from the UI via the right-click menu on the tree # view, and pasting the copy back. source1 = copy.deepcopy(source) s.children[0] = source1 # Now do the check. coll = s.children[0].children[0] check(coll)
def run(self): from enthought.mayavi.sources.vtk_file_reader import VTKFileReader #import modules here from enthought.mayavi.modules import surface, glyph, axes, outline, orientation_axes, scalar_cut_plane from enthought.mayavi.sources.vtk_data_source import VTKDataSource from enthought.tvtk.api import tvtk #CitcomS filter from plugins.filter.CitcomSshowCaps import CitcomSshowCaps from plugins.filter.CitcomSreduce import CitcomSreduce import re script = self.script #DEFINES orange = (1.0, 0.5, 0) ################ #Read Meta information meta = "" try: vtk = open(self.filename, "r") vtk.readline() meta = vtk.readline() except IOError: print 'cannot open file' try: print "Reading meta-information" m = re.search('(?<=NX:)\d+', meta) nx = int(m.group(0)) print "NX: ", nx m = re.search('(?<=NY:)\d+', meta) ny = int(m.group(0)) print "NY: ", ny m = re.search('(?<=NZ:)\d+', meta) nz = int(m.group(0)) print "NZ: ", nz m = re.search('(?<=Radius_Inner:)(\d+|.)+', meta) print m.group(0) radius_inner = float(m.group(0)) print "Radius Inner: ", radius_inner except ValueError: print "Non-valid meta information in file..." vtk.close() ################ #Read Vtk file src_vtkf = VTKFileReader() src_vtkf.initialize(self.filename) ###########Display Data############ #Create new scene script.new_scene() script.add_source(src_vtkf) scap = CitcomSshowCaps() script.add_filter(scap) #Show ScalarCutPlane scp = scalar_cut_plane.ScalarCutPlane() script.add_module(scp) #Add filter for a reduce grid redu = CitcomSreduce() script.add_filter(redu) #Shows Glyph on reduce grid gly = glyph.Glyph() gly.glyph.glyph_source.scale = 0.082 gly.glyph.scale_mode = 'scale_by_scalar' gly.glyph.color_mode = 'color_by_scalar' script.add_module(gly) mm = gly.module_manager mm.scalar_lut_manager.use_default_range = False mm.scalar_lut_manager.data_range = 0.0, 1.0 ################### Create CORE ################################ #Load VTK Data Sets sphere = tvtk.SphereSource() sphere.radius = radius_inner sphere.theta_resolution = 24 sphere.phi_resolution = 24 # Create a mesh from the data created above. src = VTKDataSource() src.data = sphere.output script.add_source(src) #Show Surface surf_module = surface.Surface() surf_module.actor.property.color = orange script.add_module(surf_module)
# ====================================================================== # from enthought.mayavi.sources.vtk_file_reader import VTKFileReader import numpy import tables shape = "hex8" res = 1000 t = 0.0 filenameRoot = "../results/strikeslip_%s_%04dm" % (shape, res) filenameIn = "%s_t%07d.vtk" % (filenameRoot, int(t*1.0e+7)) print filenameIn filenameOut = "%s.h5" % filenameRoot reader = VTKFileReader() reader.initialize(filenameIn) data = reader.outputs[0] cellsVtk = data.get_cells().to_array() if shape == "hex8": ncorners = 8 elif shape == "tet4": ncorners = 4 (size,) = cellsVtk.shape ncells = size / (1+ncorners) assert((1+ncorners)*ncells == size) cellsVtk = numpy.reshape(cellsVtk, (ncells, 1+ncorners))[:,1:1+ncorners] verticesVtk = data._get_points().to_array() (nvertices, spaceDim) = verticesVtk.shape
def run(self): """This is executed once the application GUI has started. *Make sure all other MayaVi specific imports are made here!* """ # Various imports to do different things. from enthought.mayavi.sources.vtk_file_reader import VTKFileReader from enthought.mayavi.modules.outline import Outline from enthought.mayavi.modules.axes import Axes from enthought.mayavi.modules.grid_plane import GridPlane from enthought.mayavi.modules.image_plane_widget import ImagePlaneWidget from enthought.mayavi.modules.text import Text script = self.script # Create a new scene. script.new_scene() # Read a VTK (old style) data file. r = VTKFileReader() r.initialize(join(get_data_dir(dirname(abspath(__file__))), 'heart.vtk')) script.add_source(r) # Put up some text. t = Text(text='MayaVi rules!', x_position=0.2, y_position=0.9, width=0.8) t.property.color = 1, 1, 0 # Bright yellow, yeah! script.add_module(t) # Create an outline for the data. o = Outline() script.add_module(o) # Create an axes for the data. a = Axes() script.add_module(a) # Create an orientation axes for the scene. This only works with # VTK-4.5 and above which is why we have the try block. try: from enthought.mayavi.modules.orientation_axes import OrientationAxes except ImportError: pass else: a = OrientationAxes() a.marker.set_viewport(0.0, 0.8, 0.2, 1.0) script.add_module(a) # Create three simple grid plane modules. # First normal to 'x' axis. gp = GridPlane() script.add_module(gp) # Second normal to 'y' axis. gp = GridPlane() gp.grid_plane.axis = 'y' script.add_module(gp) # Third normal to 'z' axis. gp = GridPlane() script.add_module(gp) gp.grid_plane.axis = 'z' # Create one ImagePlaneWidget. ipw = ImagePlaneWidget() script.add_module(ipw) # Set the position to the middle of the data. ipw.ipw.slice_position = 16
def _diffFiles(self, vtkFile1, vtkFile2, vtkFileOut, dt): """ Function to compute field differences between two VTK files, divide the differences by dt, and output the results to a new VTK file. """ from enthought.mayavi.sources.vtk_file_reader import VTKFileReader from enthought.tvtk.api import tvtk # Set up input files reader1 = VTKFileReader() reader2 = VTKFileReader() reader1.initialize(vtkFile1) reader2.initialize(vtkFile2) data1 = reader1.outputs[0] data2 = reader2.outputs[0] # Get vertex and cell info if it hasn't already been done if not self.readMesh: cellVtk = data1.get_cells() self.numVertsPerCell = cellVtk._get_max_cell_size() self.numCells = cellVtk.number_of_cells cellArray = cellVtk.to_array() self.cells = tvtk.CellArray() self.cells.set_cells(self.numCells, cellArray) self.vertArray = data1._get_points().to_array() self.cellType = data1.get_cell_type(0) (self.numVerts, self.spaceDim) = self.vertArray.shape self.readMesh = True # Set up mesh info for VTK file mesh = tvtk.UnstructuredGrid(points=self.vertArray) mesh.set_cells(self.cellType, self.cells) # Get vertex fields and compute differences if the fields exist vertData1 = data1._get_point_data() numVertDataArrays = vertData1._get_number_of_arrays() if numVertDataArrays != 0: vertData2 = data2._get_point_data() # This is very kludgy because I haven't yet figured out how to include # multiple scalar or vector fields, and I also don't know how to put in # a name for a general array (represented as a field). numScalarsUsed = 0 numVectorsUsed = 0 for vertDataArray in range(numVertDataArrays): array1 = vertData1.get_array(vertDataArray).to_array() (numPoints, numCols) = array1.shape arrayName = vertData1.get_array_name(vertDataArray) + "/dt" array2 = vertData2.get_array(vertDataArray).to_array() arrayOut = (array2 - array1)/dt # This is wrong if we have a scalar field with 3 components if (numCols == 3 and numVectorsUsed == 0): mesh.point_data.vectors = arrayOut mesh.point_data.vectors.name = arrayName numVectorsUsed += 1 elif numScalarsUsed == 0: mesh.point_data.scalars = arrayOut mesh.point_data.scalars.name = arrayName numScalarsUsed += 1 # Kludge to add a general array else: mesh.point_data.add_array(arrayOut) # Get cell fields and compute differences if the fields exist cellData1 = data1._get_cell_data() numCellDataArrays = cellData1._get_number_of_arrays() if numCellDataArrays != 0: cellData2 = data2._get_cell_data() # This is very kludgy because I haven't yet figured out how to include # multiple scalar or vector fields, and I also don't know how to put in # a name for a general array (represented as a field). numScalarsUsed = 0 numVectorsUsed = 0 for cellDataArray in range(numCellDataArrays): array1 = cellData1.get_array(cellDataArray).to_array() (numPoints, numCols) = array1.shape arrayName = cellData1.get_array_name(cellDataArray) + "/dt" array2 = cellData2.get_array(cellDataArray).to_array() arrayOut = (array2 - array1)/dt # This is wrong if we have a scalar field with 3 components if (numCols == 3 and numVectorsUsed == 0): mesh.cell_data.vectors = arrayOut mesh.cell_data.vectors.name = arrayName numVectorsUsed += 1 elif numScalarsUsed == 0: mesh.cell_data.scalars = arrayOut mesh.cell_data.scalars.name = arrayName numScalarsUsed += 1 # Kludge to add a general array else: mesh.cell_data.add_array(arrayOut) # Write results to VTK file #w = tvtk.UnstructuredGridWriter(file_name=vtkFileOut, input=mesh) w = tvtk.XMLDataSetWriter(file_name=vtkFileOut, input=mesh) w.write() return
def _diffFiles(self, vtkFile1, vtkFile2, vtkFileOut, dt): """ Function to compute field differences between two VTK files, divide the differences by dt, and output the results to a new VTK file. """ from enthought.mayavi.sources.vtk_file_reader import VTKFileReader from enthought.tvtk.api import tvtk # Set up input files reader1 = VTKFileReader() reader2 = VTKFileReader() reader1.initialize(vtkFile1) reader2.initialize(vtkFile2) data1 = reader1.outputs[0] data2 = reader2.outputs[0] # Get vertex and cell info if it hasn't already been done if not self.readMesh: cellVtk = data1.get_cells() self.numVertsPerCell = cellVtk._get_max_cell_size() self.numCells = cellVtk.number_of_cells cellArray = cellVtk.to_array() self.cells = tvtk.CellArray() self.cells.set_cells(self.numCells, cellArray) self.vertArray = data1._get_points().to_array() self.cellType = data1.get_cell_type(0) (self.numVerts, self.spaceDim) = self.vertArray.shape self.readMesh = True # Set up mesh info for VTK file mesh = tvtk.UnstructuredGrid(points=self.vertArray) mesh.set_cells(self.cellType, self.cells) # Get vertex fields and compute differences if the fields exist vertData1 = data1._get_point_data() numVertDataArrays = vertData1._get_number_of_arrays() if numVertDataArrays != 0: vertData2 = data2._get_point_data() # This is very kludgy because I haven't yet figured out how to include # multiple scalar or vector fields, and I also don't know how to put in # a name for a general array (represented as a field). numScalarsUsed = 0 numVectorsUsed = 0 for vertDataArray in range(numVertDataArrays): array1 = vertData1.get_array(vertDataArray).to_array() (numPoints, numCols) = array1.shape arrayName = vertData1.get_array_name(vertDataArray) + "/dt" array2 = vertData2.get_array(vertDataArray).to_array() arrayOut = (array2 - array1) / dt # This is wrong if we have a scalar field with 3 components if (numCols == 3 and numVectorsUsed == 0): mesh.point_data.vectors = arrayOut mesh.point_data.vectors.name = arrayName numVectorsUsed += 1 elif numScalarsUsed == 0: mesh.point_data.scalars = arrayOut mesh.point_data.scalars.name = arrayName numScalarsUsed += 1 # Kludge to add a general array else: mesh.point_data.add_array(arrayOut) # Get cell fields and compute differences if the fields exist cellData1 = data1._get_cell_data() numCellDataArrays = cellData1._get_number_of_arrays() if numCellDataArrays != 0: cellData2 = data2._get_cell_data() # This is very kludgy because I haven't yet figured out how to include # multiple scalar or vector fields, and I also don't know how to put in # a name for a general array (represented as a field). numScalarsUsed = 0 numVectorsUsed = 0 for cellDataArray in range(numCellDataArrays): array1 = cellData1.get_array(cellDataArray).to_array() (numPoints, numCols) = array1.shape arrayName = cellData1.get_array_name(cellDataArray) + "/dt" array2 = cellData2.get_array(cellDataArray).to_array() arrayOut = (array2 - array1) / dt # This is wrong if we have a scalar field with 3 components if (numCols == 3 and numVectorsUsed == 0): mesh.cell_data.vectors = arrayOut mesh.cell_data.vectors.name = arrayName numVectorsUsed += 1 elif numScalarsUsed == 0: mesh.cell_data.scalars = arrayOut mesh.cell_data.scalars.name = arrayName numScalarsUsed += 1 # Kludge to add a general array else: mesh.cell_data.add_array(arrayOut) # Write results to VTK file #w = tvtk.UnstructuredGridWriter(file_name=vtkFileOut, input=mesh) w = tvtk.XMLDataSetWriter(file_name=vtkFileOut, input=mesh) w.write() return
def do(self): ############################################################ # Imports. script = self.script from enthought.mayavi.sources.vtk_file_reader import VTKFileReader from enthought.mayavi.modules.outline import Outline from enthought.mayavi.modules.iso_surface import IsoSurface from enthought.mayavi.modules.contour_grid_plane \ import ContourGridPlane from enthought.mayavi.modules.scalar_cut_plane import ScalarCutPlane ############################################################ # Create a new scene and set up the visualization. s = self.new_scene() # Read a VTK (old style) data file. r = VTKFileReader() r.initialize(get_example_data('heart.vtk')) script.add_source(r) # Create an outline for the data. o = Outline() script.add_module(o) # Create one ContourGridPlane normal to the 'x' axis. cgp1 = ContourGridPlane() script.add_module(cgp1) # Set the position to the middle of the data. cgp1.grid_plane.position = 15 # Another with filled contours normal to 'y' axis. cgp2 = ContourGridPlane() cgp2.contour.filled_contours = True # Set the axis and position to the middle of the data. cgp2.grid_plane.axis = 'y' cgp2.grid_plane.position = 15 script.add_module(cgp2) # An isosurface module. iso = IsoSurface(compute_normals=True) script.add_module(iso) iso.contour.contours = [200.0] # An interactive scalar cut plane. cp = ScalarCutPlane() script.add_module(cp) ip = cp.implicit_plane ip.normal = 0,0,1 ip.origin = 0,0,5 ip.widget.enabled = False # Set the scene to an isometric view. s.scene.isometric_view() # Now test. self.check() ############################################################ # Test if the modules respond correctly when the components # are changed. ctr = cgp2.contour cgp2.contour = ctr.__class__() cgp2.contour = ctr cgp2.actor = cgp2.actor.__class__() iso.contour = iso.contour.__class__() iso.contour.contours = [200.0] iso.actor = iso.actor.__class__() iso.normals = iso.normals.__class__() ip = cp.implicit_plane cp.implicit_plane = cp.implicit_plane.__class__() cp.implicit_plane = ip ip.widget.enabled = False cp.contour = cp.contour.__class__() cp.cutter = cp.cutter.__class__() cp.actor = cp.actor.__class__() s.render() # Now check. self.check() ############################################################ # Test if saving a visualization and restoring it works. # Save visualization. f = StringIO() f.name = abspath('test.mv2') # We simulate a file. script.save_visualization(f) f.seek(0) # So we can read this saved data. # Remove existing scene. engine = script.engine engine.close_scene(s) # Load visualization script.load_visualization(f) s = engine.current_scene self.check() ############################################################ # Test if the MayaVi2 visualization can be deep-copied. # Pop the source object. source = s.children.pop() # Add it back to see if that works without error. s.children.append(source) # Now set the enabled status of the widget, this is impossible # to get correctly. cp = source.children[0].children[-1] cp.implicit_plane.widget.enabled = False self.check() # Now deepcopy the source and replace the existing one with # the copy. This basically simulates cutting/copying the # object from the UI via the right-click menu on the tree # view, and pasting the copy back. source1 = copy.deepcopy(source) s.children[0] = source1 cp = source1.children[0].children[-1] cp.implicit_plane.widget.enabled = False self.check()
# src.vector_data = Hv # <markdowncell> # Loading data from file using FileReader methods # ----------------------------------------------- # # To load a VTK data file, say heart.vtk file in mayavi/examples/data/ # directory, simply type: # # <codecell> from enthought.mayavi.sources.vtk_file_reader import VTKFileReader src = VTKFileReader() src.initialize("heart.vtk") # <markdowncell> # Note: Files with .vtk extension are called "legacy VTK" files. !MayaVi2 # can read a lot of other files formats (XML, files from Ensight, Plot3D # and so on). For example, you can load an XML file (with extension .vti, # .vtp, .vtr, .vts, .vtu, etc) using VTKXML!FileReader method. # # Add the source to your MayaVi2 class # ------------------------------------ # # Then, once your data are loaded using one of the two methods above, add # the source with the add\_source() method in the body of the class # !MyClass (after script.new\_scene):
# ====================================================================== # from enthought.mayavi.sources.vtk_file_reader import VTKFileReader import numpy import tables shape = "hex8" res = 1000 t = 0.0 filenameRoot = "../results/strikeslip_%s_%04dm" % (shape, res) filenameIn = "%s_t%07d.vtk" % (filenameRoot, int(t * 1.0e+7)) print filenameIn filenameOut = "%s.h5" % filenameRoot reader = VTKFileReader() reader.initialize(filenameIn) data = reader.outputs[0] cellsVtk = data.get_cells().to_array() if shape == "hex8": ncorners = 8 elif shape == "tet4": ncorners = 4 (size, ) = cellsVtk.shape ncells = size / (1 + ncorners) assert ((1 + ncorners) * ncells == size) cellsVtk = numpy.reshape(cellsVtk, (ncells, 1 + ncorners))[:, 1:1 + ncorners] verticesVtk = data._get_points().to_array() (nvertices, spaceDim) = verticesVtk.shape
def run(self): from enthought.mayavi.sources.vtk_file_reader import VTKFileReader #import modules here from enthought.mayavi.modules import surface, glyph , axes, outline, orientation_axes, scalar_cut_plane from enthought.mayavi.sources.vtk_data_source import VTKDataSource from enthought.tvtk.api import tvtk #CitcomS filter from plugins.filter.CitcomSshowCaps import CitcomSshowCaps from plugins.filter.CitcomSreduce import CitcomSreduce import re script = self.script #DEFINES orange = (1.0,0.5,0) ################ #Read Meta information meta = "" try: vtk = open(self.filename, "r") vtk.readline() meta = vtk.readline() except IOError: print 'cannot open file' try: print "Reading meta-information" m = re.search('(?<=NX:)\d+', meta) nx = int(m.group(0)) print "NX: ", nx m = re.search('(?<=NY:)\d+', meta) ny = int(m.group(0)) print "NY: ", ny m = re.search('(?<=NZ:)\d+', meta) nz = int(m.group(0)) print "NZ: ", nz m = re.search('(?<=Radius_Inner:)(\d+|.)+', meta) print m.group(0) radius_inner = float(m.group(0)) print "Radius Inner: ", radius_inner except ValueError: print "Non-valid meta information in file..." vtk.close() ################ #Read Vtk file src_vtkf = VTKFileReader() src_vtkf.initialize(self.filename) ###########Display Data############ #Create new scene script.new_scene() script.add_source(src_vtkf) scap = CitcomSshowCaps() script.add_filter(scap) #Show ScalarCutPlane scp = scalar_cut_plane.ScalarCutPlane() script.add_module(scp) #Add filter for a reduce grid redu = CitcomSreduce() script.add_filter(redu) #Shows Glyph on reduce grid gly = glyph.Glyph() gly.glyph.glyph_source.scale = 0.082 gly.glyph.scale_mode = 'scale_by_scalar' gly.glyph.color_mode = 'color_by_scalar' script.add_module(gly) mm = gly.module_manager mm.scalar_lut_manager.use_default_range = False mm.scalar_lut_manager.data_range = 0.0, 1.0 ################### Create CORE ################################ #Load VTK Data Sets sphere = tvtk.SphereSource() sphere.radius = radius_inner sphere.theta_resolution = 24 sphere.phi_resolution = 24 # Create a mesh from the data created above. src = VTKDataSource() src.data = sphere.output script.add_source(src) #Show Surface surf_module = surface.Surface() surf_module.actor.property.color = orange script.add_module(surf_module)