def _readMesh(self): from enthought.tvtk.api import tvtk import tables import numpy filename = "../meshes/reverseslip_%s_%04dm.h5" % (shape, res) h5 = tables.openFile(filename, 'r') cells = h5.root.topology.cells[:] (ncells, ncorners) = cells.shape vertices = h5.root.geometry.vertices[:] / 1e+3 (nvertices, spaceDim) = vertices.shape h5.close() if shape == "tet4": assert (spaceDim == 3) assert (ncorners == 4) cellType = tvtk.Tetra().cell_type else: raise ValueError("Unknown shape '%s'." % shape) data = tvtk.UnstructuredGrid() data.points = vertices data.set_cells(cellType, cells) return data
def _readData(self): from enthought.tvtk.api import tvtk import tables import numpy filename = "../results/strikeslip_%s_%04dm.h5" % (shape, res) h5 = tables.openFile(filename, 'r') cells = h5.root.topology.cells[:] (ncells, ncorners) = cells.shape vertices = h5.root.geometry.vertices[:] / 1e+3 (nvertices, spaceDim) = vertices.shape disp = h5.root.solution.snapshot0.displacements[:] h5.close() if shape == "tet4": assert(spaceDim == 3) assert(ncorners == 4) cellType = tvtk.Tetra().cell_type elif shape == "hex8": assert(spaceDim == 3) assert(ncorners == 8) cellType = tvtk.Hexahedron().cell_type else: raise ValueError("Unknown shape '%s'." % shape) data = tvtk.UnstructuredGrid() data.points = vertices data.set_cells(cellType, cells) data.point_data.vectors = disp data.point_data.vectors.name = "Displacement [m]" return data
def _writeVtkFile(self): """ Function to write out vertex and cell info along with stress-related quantities. """ from enthought.tvtk.api import tvtk # Set up mesh info for VTK file. mesh = tvtk.UnstructuredGrid(points=self.vertArray) mesh.set_cells(self.cellType, self.cells) # Add scalar fields. pressureName = "pressure" devInvariant2Name = "dev_invar2" dpPlasPresTermName = "dp_plas_pres_term" dpPlasStressTermName = "dp_plas_stress_term" dpPlasYieldFuncName = "dp_plas_yield_func" mesh.cell_data.scalars = self.pressure mesh.cell_data.scalars.name = pressureName s2 = mesh.cell_data.add_array(self.devInvariant2) mesh.cell_data.get_array(s2).name = devInvariant2Name s3 = mesh.cell_data.add_array(self.dpPlasPresTerm) mesh.cell_data.get_array(s3).name = dpPlasPresTermName s4 = mesh.cell_data.add_array(self.dpPlasStressTerm) mesh.cell_data.get_array(s4).name = dpPlasStressTermName s5 = mesh.cell_data.add_array(self.dpPlasYieldFunc) mesh.cell_data.get_array(s5).name = dpPlasYieldFuncName mesh.update() # Write VTK file w = tvtk.XMLDataSetWriter(file_name=self.vtkOutputFile, input=mesh) w.write() return
def single_type_ug(): """Simple example showing how to create an unstructured grid consisting of cells of a single type. """ points = array( [ [0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1], # tets [1, 0, 0], [2, 0, 0], [1, 1, 0], [1, 0, 1], [2, 0, 0], [3, 0, 0], [2, 1, 0], [2, 0, 1], ], 'f') tets = array([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]) tet_type = tvtk.Tetra().cell_type ug = tvtk.UnstructuredGrid(points=points) ug.set_cells(tet_type, tets) return ug
def _calc_grid(self, radius, resolution_x, resolution_y): fil = self.probe_filter coords = [] if self.Selected_Source == 'CitcomSGrid': for i in xrange(12): coords += self.citcomsgrid.coords_of_cap( radius, self.theta, self.phi, i) grid = tvtk.UnstructuredGrid() #Connectivity for 2d-Data #There is no need to interpolate with the CitcomS grid surface. If this is however #wanted uncomment this code to create the CitcomS surface information #for capnr in xrange(12): # i=1 # for n in xrange((resolution_x+1)*(resolution_y+1) - (resolution_x+1)): # if i%(resolution_x+1)!=0 : # n0 = n+(capnr*((resolution_x+1)*(resolution_y+1))) # n1 = n0+1 # n2 = n0+resolution_y+1 # n3 = n2+1 # grid.insert_next_cell(8,[n0,n1,n2,n3]) # i+=1 ## grid.points = coords fil.input = grid if self.Selected_Source == 'Sphere': sphere = tvtk.SphereSource() sphere.radius = radius sphere.theta_resolution = resolution_x sphere.phi_resolution = resolution_y #Rotate the Sphere so that the poles are at the right location transL = tvtk.Transform() trans1 = tvtk.TransformPolyDataFilter() trans2 = tvtk.TransformPolyDataFilter() trans1.input = sphere.output transL.rotate_y(90) transL.update() trans1.transform = transL trans1.update() trans2.input = trans1.output transL.rotate_z(90) transL.update() trans2.transform = transL trans2.update() fil.input = trans2.output fil.update()
def mixed_type_ug(): """A slightly more complex example of how to generate an unstructured grid with different cell types. Returns a created unstructured grid. """ points = array( [ [0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1], # tetra [2, 0, 0], [3, 0, 0], [3, 1, 0], [2, 1, 0], [2, 0, 1], [3, 0, 1], [3, 1, 1], [2, 1, 1], # Hex ], 'f') # shift the points so we can show both. points[:, 1] += 2.0 # The cells cells = array([ 4, 0, 1, 2, 3, # tetra 8, 4, 5, 6, 7, 8, 9, 10, 11 # hex ]) # The offsets for the cells, i.e. the indices where the cells # start. offset = array([0, 5]) tetra_type = tvtk.Tetra().cell_type # VTK_TETRA == 10 hex_type = tvtk.Hexahedron().cell_type # VTK_HEXAHEDRON == 12 cell_types = array([tetra_type, hex_type]) # Create the array of cells unambiguously. cell_array = tvtk.CellArray() cell_array.set_cells(2, cells) # Now create the UG. ug = tvtk.UnstructuredGrid(points=points) # Now just set the cell types and reuse the ug locations and cells. ug.set_cells(cell_types, offset, cell_array) return ug
def setUp(self): datasets = [ tvtk.ImageData(), tvtk.StructuredPoints(), tvtk.RectilinearGrid(), tvtk.StructuredGrid(), tvtk.PolyData(), tvtk.UnstructuredGrid(), ] exts = ['.vti', '.vti', '.vtr', '.vts', '.vtp', '.vtu'] self.datasets = datasets self.exts = exts
def unstructured_grid(): points = array( [ [0, 1.2, 0.6], [1, 0, 0], [0, 1, 0], [1, 1, 1], # tetra [1, 0, -0.5], [2, 0, 0], [2, 1.5, 0], [0, 1, 0], [1, 0, 0], [1.5, -0.2, 1], [1.6, 1, 1.5], [1, 1, 1], # Hex ], 'f') # The cells cells = array([ 4, 0, 1, 2, 3, # tetra 8, 4, 5, 6, 7, 8, 9, 10, 11 # hex ]) # The offsets for the cells, i.e. the indices where the cells # start. offset = array([0, 5]) tetra_type = tvtk.Tetra().cell_type # VTK_TETRA == 10 hex_type = tvtk.Hexahedron().cell_type # VTK_HEXAHEDRON == 12 cell_types = array([tetra_type, hex_type]) # Create the array of cells unambiguously. cell_array = tvtk.CellArray() cell_array.set_cells(2, cells) # Now create the UG. ug = tvtk.UnstructuredGrid(points=points) # Now just set the cell types and reuse the ug locations and cells. ug.set_cells(cell_types, offset, cell_array) scalars = random.random(points.shape[0]) ug.point_data.scalars = scalars ug.point_data.scalars.name = 'scalars' return ug
def update_pipeline(self): print 'update_pipeline' if len(self.inputs) == 0 or len(self.inputs[0].outputs) == 0: return self.grid = tvtk.UnstructuredGrid() ## Way of doing this without a deep_copy (idea: copy input to output, with additional arrays tagged on)? self.grid.deep_copy(self.inputs[0].outputs[0]) # Add a blank input field by default self.input_fields.append(self.input_field) self._set_outputs([self.grid])
def update_pipeline(self): # Called when we drag filter under another VTK file debug('update_pipeline') """Override this method so that it *updates* the tvtk pipeline when data upstream is known to have changed. This method is invoked (automatically) when the input fires a `pipeline_changed` event. """ # Do nothing if there is no input. if len(self.inputs) == 0: return magn = linalg.norm earth_radius = 6378000.0 # By default we set the input to the first output of the first input self.grid = tvtk.UnstructuredGrid() self.grid.deep_copy(self.inputs[0].reader.output) ## WAY OF DOING THIS WITHOUT A DEEP COPY? #self.inputs[0].outputs[0] ## DOESN'T WORK WITH update_data() # Split array by column into the cartesian coordinates xyz = array(self.grid.points) x = xyz[:,0] y = xyz[:,1] z = xyz[:,2] xyz_squared = xyz**2 r_squared = xyz_squared.sum(axis=1) r = sqrt(r_squared) self.longitude = arctan2(y, x) self.colatitude = 1.3 * arccos(z/r) self.initial_depth = earth_radius - r # Now we do vector correction self.unit_r = column_stack((x/r, y/r, z/r)) len_lon = sqrt(x**2 + y**2) self.unit_lon = column_stack((y/len_lon, -1*x/len_lon, zeros(len(x)))) self.unit_lat = cross(self.unit_r, self.unit_lon) # Correct current vector array current_vector_array = self.inputs[0].outputs[0].point_data.vectors.name self._correct_vector_array(current_vector_array) self._apply_stretch() # Propagate the data_changed event - let modules that depend on this filter know that pipeline has changed self.pipeline_changed = True
def initialize(self): """ """ (nvertices, spaceDim) = self.vertices.shape (ncells, ncorners) = self.cells.shape assert(spaceDim == 3) assert(ncorners == 3) cellType = tvtk.Triangle().cell_type dataVtk = tvtk.UnstructuredGrid() dataVtk.points = self.vertices dataVtk.set_cells(cellType, self.cells) self.dataVtk = dataVtk return
def create_dataset(self): """Create a tvtk.UnstructuredGrid dataset from the Mesh instance of the file source.""" mesh = self.mesh n_nod, dim = self.n_nod, self.dim if dim < 3: nod_zz = nm.zeros((n_nod, 3 - dim), dtype=mesh.coors.dtype) points = nm.c_[mesh.coors, nod_zz] else: points = mesh.coors dataset = tvtk.UnstructuredGrid(points=points) cell_types = [] cells = [] offset = [0] n_cells = [1] for ig, desc in enumerate(mesh.descs): conn = mesh.get_conn(desc) n_cell, n_cv = conn.shape n_cells.append(n_cell) aux = nm.empty(n_cell, dtype=nm.int32) aux.fill(vtk_cell_types[desc]) cell_types.append(aux) aux = nm.empty((n_cell, n_cv + 1), dtype=nm.int32) aux[:, 0] = n_cv aux[:, 1:] = conn cells.append(aux.ravel()) offset.append(aux.shape[1]) cells = nm.concatenate(cells) cell_types = nm.concatenate(cell_types) offset = nm.repeat(offset, n_cells) offset = nm.cumsum(offset)[:-1] cell_array = tvtk.CellArray() cell_array.set_cells(mesh.n_el, cells) dataset.set_cells(cell_types, offset, cell_array) return dataset
def update_pipeline(self): if len(self.inputs) == 0 or len(self.inputs[0].outputs) == 0: return self.grid = tvtk.UnstructuredGrid() ## This doesn't work - there must be more to copy. #self.grid.points = tvtk.Points() #self.grid.points.deep_copy(self.inputs[0].outputs[0].points) self.grid.deep_copy(self.inputs[0].outputs[0]) self.dimensions = size(self.grid.points[0]) for i in range(self.dimensions): self._dimension_list.append(i) self.active_tensor = self.inputs[0].outputs[0].point_data.tensors.name self._set_outputs([self.grid])
def make_data(): points = N.array( [ [0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1], # tets [1, 0, 0], [2, 0, 0], [1, 1, 0], [1, 0, 1], [2, 0, 0], [3, 0, 0], [2, 1, 0], [2, 0, 1], ], 'f') tets = N.array([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]) tet_type = tvtk.Tetra().cell_type ug = tvtk.UnstructuredGrid(points=points) ug.set_cells(tet_type, tets) # Setup the point attributes. temp = N.random.random(12) v = N.random.randn(12, 3) ten = N.random.randn(12, 9) a = tvtk.FloatArray(name='p') a.from_array(N.random.randn(12)) ug.point_data.add_array(a) ug.point_data.scalars = temp ug.point_data.scalars.name = 't' ug.point_data.vectors = v ug.point_data.vectors.name = 'v' ug.point_data.tensors = ten ug.point_data.tensors.name = 'ten' # Setup the cell attributes. temp = N.random.random(3) v = N.random.randn(3, 3) ten = N.random.randn(3, 9) ug.cell_data.scalars = temp ug.cell_data.scalars.name = 't' ug.cell_data.vectors = v ug.cell_data.vectors.name = 'v' ug.cell_data.tensors = ten ug.cell_data.tensors.name = 'ten' return ug
def test_tvtk_dataset_name(self): "Can tvtk datasets can be converted to names correctly." datasets = [ tvtk.ImageData(), tvtk.StructuredPoints(), tvtk.RectilinearGrid(), tvtk.StructuredGrid(), tvtk.PolyData(), tvtk.UnstructuredGrid(), tvtk.Property(), # Not a dataset! 'foo', # Not a TVTK object. ] expect = [ 'image_data', 'image_data', 'rectilinear_grid', 'structured_grid', 'poly_data', 'unstructured_grid', 'none', 'none' ] result = [pipeline_info.get_tvtk_dataset_name(d) for d in datasets] self.assertEqual(result, expect)
def read(self, filename): reader = VTKDataReader() data = reader.read(filename) cells = data['cells'] vertices = data['vertices'] (ncells, ncorners) = cells.shape (nvertices, spaceDim) = vertices.shape vtkData = tvtk.UnstructuredGrid() vtkData.points = vertices assert(spaceDim == 3) assert(ncorners == 3) cellType = tvtk.Triangle().cell_type vtkData.set_cells(cellType, cells) # Displacement vector displacement = data['vertex_fields']['displacement'] array = tvtk.FloatArray() array.from_array(displacement.squeeze()) array.name = "Displacement (m)" vtkData.point_data.vectors = array vtkData.point_data.vectors.name = "Displacement (m)" # Compute velocity magnitude velocity = data['vertex_fields']['velocity'] velocityLog = ((velocity[:,0]**2 + velocity[:,1]**2 + velocity[:,2]**2)**0.5) array = tvtk.FloatArray() array.from_array(velocityLog.squeeze()) array.name = "Velocity (m/s)" vtkData.point_data.scalars = array vtkData.point_data.scalars.name = "Velocity (m/s)" return vtkData
def _writeVtkFile(self): """ Function to write out vertex and cell info along with principal axes computed as vectors. """ from enthought.tvtk.api import tvtk # Set up mesh info for VTK file. mesh = tvtk.UnstructuredGrid(points=self.vertArray) mesh.set_cells(self.cellType, self.cells) # Add scalar fields. minEigenName = "min_eigenvalue" intEigenName = "int_eigenvalue" maxEigenName = "max_eigenvalue" mesh.cell_data.scalars = self.minEigenValue mesh.cell_data.scalars.name = minEigenName s2 = mesh.cell_data.add_array(self.intEigenValue) mesh.cell_data.get_array(s2).name = intEigenName s3 = mesh.cell_data.add_array(self.maxEigenValue) mesh.cell_data.get_array(s3).name = maxEigenName mesh.update() # Add vector fields and write VTK file minAxisName = "min_principal_axis" intAxisName = "int_principal_axis" maxAxisName = "max_principal_axis" mesh.cell_data.vectors = self.minPrincAxis mesh.cell_data.vectors.name = minAxisName v2 = mesh.cell_data.add_array(self.intPrincAxis) mesh.cell_data.get_array(v2).name = intAxisName v3 = mesh.cell_data.add_array(self.maxPrincAxis) mesh.cell_data.get_array(v3).name = maxAxisName mesh.update() w = tvtk.UnstructuredGridWriter(file_name=self.vtkOutputFile, input=mesh) w.write() return
def create_dataset(self): """Create a tvtk.UnstructuredGrid dataset from the Mesh instance of the file source.""" mesh = self.mesh n_nod, dim = self.n_nod, self.dim n_el, n_els, n_e_ps = mesh.n_el, mesh.n_els, mesh.n_e_ps if dim == 2: nod_zz = nm.zeros((n_nod, 1), dtype=mesh.coors.dtype) points = nm.c_[mesh.coors, nod_zz] else: points = mesh.coors dataset = tvtk.UnstructuredGrid(points=points) cell_types = [] cells = [] offset = [0] for ig, conn in enumerate(mesh.conns): cell_types += [vtk_cell_types[mesh.descs[ig]]] * n_els[ig] nn = nm.array([conn.shape[1]] * n_els[ig]) aux = nm.c_[nn[:, None], conn] cells.extend(aux.ravel()) offset.extend([aux.shape[1]] * n_els[ig]) cells = nm.array(cells) cell_types = nm.array(cell_types) offset = nm.cumsum(offset)[:-1] cell_array = tvtk.CellArray() cell_array.set_cells(n_el, cells) dataset.set_cells(cell_types, offset, cell_array) return dataset
def _readData(self): from enthought.tvtk.api import tvtk import tables import numpy filename = "../projection/pylith_%s_%04dm.h5" % (shape, res) h5 = tables.openFile(filename, 'r') cells = h5.root.topology.cells[:] (ncells, ncorners) = cells.shape vertices = h5.root.geometry.vertices[:] / 1e+3 (nvertices, spaceDim) = vertices.shape error = h5.root.difference.pylith_1_0_analytic.snapshot0.displacements[:] disp = h5.root.projection.data.pylith_1_0.snapshot0.displacements[:] dispE = h5.root.projection.data.analytic.snapshot0.displacements[:] h5.close() if shape == "tet4": assert(spaceDim == 3) assert(ncorners == 4) cellType = tvtk.Tetra().cell_type elif shape == "hex8": assert(spaceDim == 3) assert(ncorners == 8) cellType = tvtk.Hexahedron().cell_type else: raise ValueError("Unknown shape '%s'." % shape) errorLog10 = numpy.log10(error) data = tvtk.UnstructuredGrid() data.points = vertices data.set_cells(cellType, cells) data.cell_data.scalars = errorLog10 data.cell_data.scalars.name = "log10(Error [m])" return data
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 mshplot3D(mesh, scale=[1, 1, 1], elm_ids=[], labels=[0, 0, 0]): ''' Plot 3D meshes (and optionally label vertices, elements, and edges) @param mesh A 3D mesh object @param elm_ids Numpy array of elements that will be plotted. If left empty, all elements are plotted. @param labels (\c bool) List of three elements indicateting what should be labeled. By default, nothing is labeled labels[0]=True labels vertices labels[1]=True labels elements labels[2]=True labels edges @param scale (\c int) List indicating the scaling of the vertices -- this is used to scale the z-direction for a thin mesh. By default, there is no scaling, i.e. scale = [1, 1, 1] @see msh.mesh.Mesh3D @author Matt Ueckermann ''' if type(elm_ids) is not int: if len(elm_ids) == 0: elm_ids = np.arange(len(mesh.elm)) #Figure out how many vertices are in each element type n_vert_in_type = [len(int_el_pqr(element=element, dim=3)[0]) \ for element in mesh.u_elm_type] #Now create the TVTK data-structures for the 'cells' and 'offsets' #cells give [#verts, vert1id, vert2id...,vertnid, #verts ...] #offsets gives the id's in the cells list where #verts are listed. So above # it is [0, n+1] cells = np.array([], dtype=int) offset = np.array([], dtype=int) for elm, elm_type in zip(mesh.elm[elm_ids, :], mesh.elm_type[elm_ids]): n_vt = n_vert_in_type[elm_type] offset = np.append(offset, len(cells)) cells = np.append(cells, [n_vt] + elm[:n_vt].tolist()) #Also have to create a list of element-types -- to do that we have to #convert from my numbering system to the TVTK numbering system if mesh.dim == 3: type_convert = np.array([tvtk.Tetra().cell_type,\ tvtk.Hexahedron().cell_type, tvtk.Wedge().cell_type]) elif mesh.dim == 2: type_convert = np.array([tvtk.Triangle().cell_type,\ tvtk.Quad().cell_type]) cell_types = mesh.u_elm_type[mesh.elm_type[elm_ids]] cell_types = type_convert[cell_types] #To help visualize the mesh, we color it be the distance from the origin if mesh.dim == 3: x, y, z = mesh.vert[:].T elif mesh.dim == 2: x, y = mesh.vert[:, :2].T z = np.zeros_like(x) dist = np.sqrt(x**2 + y**2 + z**2) #and we scale the x, y, z, coordinates according the the assigned 'scale' points = np.column_stack((x * scale[0], y * scale[1], z * scale[2])) #Now we create the data-structures cell_array = tvtk.CellArray() cell_array.set_cells(len(offset), cells) ug = tvtk.UnstructuredGrid(points=points) ug.set_cells(cell_types, offset, cell_array) ug.point_data.scalars = dist.ravel() ug.point_data.scalars.name = 'Distance from Origin' #Next we set the new data-structures as a mayavi source src = sources.vtk_data_source.VTKDataSource(data=ug) #Extract the edges from the grid edges = mlab.pipeline.extract_edges(src) #Use a shorter name for the elements elm = mesh.elm[elm_ids, :] if any(labels) and len(elm) > 20: string = "WARNING:\nAre you sure you want to label more than 20" + \ "elements in 3D? -- Labels are very memory" + \ "(apparently -- who would have guessed?) \nY(es) to proceed:" answer = raw_input(string) if answer.lower() not in ['yes', 'y', 'yes']: labels = [0, 0, 0] #Next add labels if desired: maxdist = np.max(dist) / 2. if labels[0]: #Vertex labels for i in xrange(len(offset)): for vnum in elm[i, :]: if vnum >= 0: mlab.text3d(points[vnum, 0], points[vnum, 1], \ points[vnum, 2], '%d' % vnum, \ color=(0, 0, 0), scale=0.02*maxdist) if labels[1]: #element labels for i in xrange(len(offset)): if elm_ids[i] < 0: elm_label = mesh.numelm + elm_ids[i] else: elm_label = elm_ids[i] x = np.mean(points[elm[i, :cells[offset[i]]], 0]) y = np.mean(points[elm[i, :cells[offset[i]]], 1]) z = np.mean(points[elm[i, :cells[offset[i]]], 2]) mlab.text3d(x, y, z, '%d' % elm_label, color=(0.3, 0.3, 0.9), \ scale=0.03*maxdist) if labels[2]: #edge labels if len(elm_ids) < len(mesh.elm): elm2ed = connect_elm2ed(mesh.elm2elm[:], mesh.ed2ed) ed_ids = np.unique(elm2ed[elm_ids]) ed_ids = ed_ids[ed_ids >= 0] ed2ed = mesh.ed2ed[ed_ids, :] else: ed_ids = np.arange(len(mesh.ed2ed)) ed2ed = mesh.ed2ed[:] for i in xrange(len(ed2ed)): n = 8 if ed2ed[i, -1] < 0: n = 7 x = np.mean(points[ed2ed[i, 4:n], 0]) y = np.mean(points[ed2ed[i, 4:n], 1]) z = np.mean(points[ed2ed[i, 4:n], 2]) mlab.text3d(x, y, z, '%d' % ed_ids[i], color=(0.3, 0.9, 0.3), \ scale=0.03*maxdist) #And plot them! mlab.pipeline.surface(edges, opacity=0.4, line_width=2) mlab.axes() mlab.title('3D mesh', size=0.5, height=0.95) #mlab.show() return cells, offset, cell_types
def _computeVectorInfo(self): """Function to compute vectors in global coordinates and CFF. """ from enthought.tvtk.api import tvtk # Compute stress vectors in global coordinates. strikeStress = numpy.tile(numpy.expand_dims(self.stressVec[:, 0], 1), (1, 3)) strikeStressArr = self.stressScaleFactor * self.strikeVec * strikeStress strikeStressVec = tvtk.DoubleArray(name='left_lateral_shear') strikeStressVec.from_array(strikeStressArr) dipStress = numpy.tile(numpy.expand_dims(self.stressVec[:, 1], 1), (1, 3)) dipStressArr = self.stressScaleFactor * self.dipVec * dipStress dipStressVec = tvtk.DoubleArray(name='up_dip_shear') dipStressVec.from_array(dipStressArr) normalStress = numpy.tile(numpy.expand_dims(self.stressVec[:, 2], 1), (1, 3)) normalStressArr = self.stressScaleFactor * self.normalVec * normalStress normalStressVec = tvtk.DoubleArray(name='normal_stress') normalStressVec.from_array(normalStressArr) shearStressArr = strikeStressArr + dipStressArr shearStressVec = tvtk.DoubleArray(name='in_plane_shear') shearStressVec.from_array(shearStressArr) # Compute slip vectors in global coordinates. strikeSlip = numpy.tile(numpy.expand_dims(self.slipVec[:, 0], 1), (1, 3)) strikeSlipArr = self.slipScaleFactor * self.strikeVec * strikeSlip strikeSlipVec = tvtk.DoubleArray(name='left_lateral_slip') strikeSlipVec.from_array(strikeSlipArr) dipSlip = numpy.tile(numpy.expand_dims(self.slipVec[:, 1], 1), (1, 3)) dipSlipArr = self.slipScaleFactor * self.dipVec * dipSlip dipSlipVec = tvtk.DoubleArray(name='up_dip_slip') dipSlipVec.from_array(dipSlipArr) normalSlip = numpy.tile(numpy.expand_dims(self.slipVec[:, 2], 1), (1, 3)) normalSlipArr = self.slipScaleFactor * self.normalVec * normalSlip normalSlipVec = tvtk.DoubleArray(name='normal_slip') normalSlipVec.from_array(normalSlipArr) slipArr = strikeSlipArr + dipSlipArr slipVec = tvtk.DoubleArray(name='in_plane_slip') slipVec.from_array(slipArr) # Compute CFF shearMag = self.stressScaleFactor * \ numpy.sqrt(numpy.square(self.stressVec[:, 0]) + \ numpy.square(self.stressVec[:, 1])) shearDirVec = numpy.array(self.shearDirection, dtype=numpy.float64) shearDirMat = numpy.tile(shearDirVec, (self.numVerts, 1)) shearSlipDot = shearStressVec * shearDirMat shearSlipSign = numpy.sign(numpy.sum(shearSlipDot, axis=1)) CffArr = shearSlipSign * shearMag + \ self.stressScaleFactor * self.frictionCoeff * self.stressVec[:, 2] CFF = tvtk.DoubleArray(name='CFF') CFF.from_array(CffArr) # Set up mesh info for output VTK file mesh = tvtk.UnstructuredGrid(points=self.vertArray) mesh.set_cells(self.cellType, self.cells) # Add computed values to mesh object. mesh.point_data.add_array(strikeStressVec) mesh.point_data.add_array(dipStressVec) mesh.point_data.add_array(normalStressVec) mesh.point_data.add_array(shearStressVec) mesh.point_data.add_array(strikeSlipVec) mesh.point_data.add_array(dipSlipVec) mesh.point_data.add_array(normalSlipVec) mesh.point_data.add_array(slipVec) mesh.point_data.scalars = CFF # Write results to VTK file w = tvtk.XMLDataSetWriter(file_name=self.faultOutputFile, input=mesh) w.write() return
def _CffPredefined(self, refStress, newStress, vtkOutputFile): """Function to compute CFF for predefined planes and output results to a file. """ from enthought.tvtk.api import tvtk beta = math.atan(self.frictionCoeff) / 2.0 sinBeta = math.sin(beta) cosBeta = math.cos(beta) sin2Beta = math.sin(2.0 * beta) cos2Beta = math.cos(2.0 * beta) sinCosBeta = sinBeta * cosBeta sinBetaSq = sinBeta * sinBeta cosBetaSq = cosBeta * cosBeta cff = numpy.empty((self.numStressPoints), dtype=numpy.float64) failDir1 = numpy.empty((self.numStressPoints, self.spaceDim), dtype=numpy.float64) failDir2 = numpy.empty((self.numStressPoints, self.spaceDim), dtype=numpy.float64) effFrictionCoeff = self.frictionCoeff * (1.0 - self.skemptonCoeff) presFac = -self.skemptonCoeff / 3.0 vec1 = numpy.array([cosBeta, 0.0, sinBeta], dtype=numpy.float64) vec2 = numpy.array([cosBeta, 0.0, -sinBeta], dtype=numpy.float64) # Loop over stress points, compute total stress and the associated # principal stresses, as well as the stress difference, and then # compute CFF. for point in range(self.numStressPoints): totStress = newStress[point, :] deltaStress = newStress[point, :] - refStress[point, :] (totPrincStress, totPrincAxes) = self._princStress(totStress) # Rotate stress changes into principal axis coordinate system for # total stress. deltaStressMat = numpy.array( [(deltaStress[0], deltaStress[3], deltaStress[5]), (deltaStress[3], deltaStress[1], deltaStress[4]), (deltaStress[5], deltaStress[4], deltaStress[2])], dtype=numpy.float64) prod1 = numpy.dot(totPrincAxes, deltaStressMat) deltaStressRot = numpy.dot(prod1, totPrincAxes.transpose()) s33 = deltaStressRot[0, 0] * sinBetaSq - \ 2.0 * deltaStressRot[0, 2] * sinCosBeta + \ deltaStressRot[2, 2] * cosBetaSq s13 = 0.5 * (deltaStressRot[2, 2] - deltaStressRot[0, 0]) * sin2Beta + \ deltaStressRot[0, 2] * cos2Beta deltaNormStress = deltaStress[0] + deltaStress[1] + deltaStress[2] # Compute CFF depending on which model is used if self.isotropicPoroelastic: cff[point] = s13 + self.frictionCoeff * \ (s33 + presFac * deltaNormStress) else: cff[point] = s13 + effFrictionCoeff * s33 # Get failure planes by rotating vector in principal axis coordinate # system into global coordinate system. # NOTE: make sure I'm applying the rotation the right way. failDir1[point, :] = numpy.dot(totPrincAxes.transpose(), vec1) failDir2[point, :] = numpy.dot(totPrincAxes.transpose(), vec2) # Set up mesh info for VTK file mesh = tvtk.UnstructuredGrid(points=self.vertArray) mesh.set_cells(self.cellType, self.cells) # Add output fields and write VTK file # For now, output cff as a scalar, failDir1 as a vector, and failDir2 as # a general array. cffName = "cff" failDir1Name = "failure_plane_1" failDir2Name = "failure_plane_2" mesh.cell_data.scalars = cff mesh.cell_data.scalars.name = cffName mesh.cell_data.vectors = failDir1 mesh.cell_data.vectors.name = failDir1Name mesh.cell_data.add_array(failDir2) w = tvtk.UnstructuredGridWriter(file_name=vtkOutputFile, input=mesh) w.write() return
def __citcom2vtk(self,t,f,nproc_surf,nx_redu,ny_redu,nz_redu): """Method to convert one timestep from a hdf file to a Vtk file. This Method is used by the method initialize. Initialize reads the necessary meta information from the hdf file""" hexagrid = tvtk.UnstructuredGrid() hexagrid.allocate(1,1) vtkordered_velo = tvtk.FloatArray() nx = self._nx ny = self._ny nz = self._nz counter = 0 el_nx_redu = nx_redu + 1 el_ny_redu = ny_redu + 1 el_nz_redu = nz_redu + 1 ordered_points = [] #reset Sequences for points ordered_temperature = [] ordered_velocity = [] ordered_viscosity = [] for capnr in xrange(nproc_surf): cap = f.root._f_getChild("cap%02d" % capnr) temp_coords = [] # reset Coordinates, Velocity, Temperature Sequence temp_vel = [] temp_temp = [] temp_visc = [] #Information from hdf hdf_coords = cap.coord[:] hdf_velocity = cap.velocity[t] hdf_temperature = cap.temperature[t] hdf_viscosity = cap.viscosity[t] #Create Iterator to change data representation nx_redu_iter = self.reduce_iter(nx,nx_redu) ny_redu_iter = self.reduce_iter(ny,ny_redu) nz_redu_iter = self.reduce_iter(nz,nz_redu) #vtk_i = self.vtk_iter(el_nx_redu,el_ny_redu,el_nz_redu) # read citcom data - zxy (z fastest) for j in xrange(el_ny_redu): j_redu = ny_redu_iter.next() nx_redu_iter = self.reduce_iter(nx,nx_redu) for i in xrange(el_nx_redu): i_redu = nx_redu_iter.next() nz_redu_iter = self.reduce_iter(nz,nz_redu) for k in xrange(el_nz_redu): k_redu = nz_redu_iter.next() colat, lon, r = map(float,hdf_coords[i_redu,j_redu,k_redu]) x_coord, y_coord, z_coord = self.RTF2XYZ(colat,lon,r) ordered_points.append((x_coord,y_coord,z_coord)) ordered_temperature.append(float(hdf_temperature[i_redu,j_redu,k_redu])) ordered_viscosity.append(float(hdf_viscosity[i_redu,j_redu,k_redu])) vel_colat, vel_lon , vel_r = map(float,hdf_velocity[i_redu,j_redu,k_redu]) x_velo, y_velo, z_velo = self.velocity2cart(vel_colat,vel_lon,vel_r, colat,lon , r) ordered_velocity.append((x_velo,y_velo,z_velo)) ##Delete Objects for GC del hdf_coords del hdf_velocity del hdf_temperature del hdf_viscosity #Create Connectivity info if counter==0: i=1 #Counts X Direction j=1 #Counts Y Direction k=1 #Counts Z Direction for n in xrange((el_nx_redu*el_ny_redu*el_nz_redu)-(el_nz_redu*el_nx_redu)): if (i%el_nz_redu)==0: #X-Values!!! j+=1 #Count Y-Values if (j%el_nx_redu)==0: k+=1 #Count Z-Values if i%el_nz_redu!=0 and j%el_nx_redu!=0: #Check if Box can be created #Get Vertnumbers n0 = n+(capnr*(el_nx_redu*el_ny_redu*el_nz_redu)) n1 = n0+el_nz_redu n2 = n1+el_nz_redu*el_nx_redu n3 = n0+el_nz_redu*el_nx_redu n4 = n0+1 n5 = n4+el_nz_redu n6 = n5+el_nz_redu*el_nx_redu n7 = n4+el_nz_redu*el_nx_redu #Created Polygon Box hexagrid.insert_next_cell(12,[n0,n1,n2,n3,n4,n5,n6,n7]) i+=1 #Store Arrays in Vtk conform Datastructures self.__vtkordered_temp.from_array(ordered_temperature) self.__vtkordered_visc.from_array(ordered_viscosity) vtkordered_velo.from_array(ordered_velocity) self.__vtkordered_temp.name = 'Temperature' self.__vtkordered_visc.name = 'Viscosity' hexagrid.point_data.scalars = self.__vtkordered_temp vtkordered_velo.name = 'Velocity' hexagrid.point_data.vectors = vtkordered_velo hexagrid.points = ordered_points self.progress += 1 return hexagrid