def plotbathy3d(self, clims=None, zscale=None, **kwargs): """ Adds 3D plot of the bathymetry to the current scene """ # Create a new scene if there isn't one if 'fig' not in self.__dict__: self.newscene() if zscale is None: zscale = self.zscale depth = -self.dv if clims == None: clims = [depth.min(), depth.max()] # Create an unstructured grid object to interpolate cells onto points points = np.column_stack((self.xp, self.yp, 0.0 * self.xp)) tri_type = tvtk.Polygon().cell_type cells = self.cells for ii in range(self.Nc): nf = self.nfaces[ii] cells[ii, nf::] = cells[ii, 0] ug = tvtk.UnstructuredGrid(points=points) ug.set_cells(tri_type, cells) ug.cell_data.scalars = depth ug.cell_data.scalars.name = 'suntans_depth' # Interpolate the cell data onto the points F = mlab.pipeline.cell_to_point_data(ug) dp = mlab.pipeline.probe_data(F, self.xp, self.yp, 0.0 * self.xp) # Now set up a new object with the 3D points points = np.column_stack((self.xp, self.yp, dp * zscale)) ug = tvtk.UnstructuredGrid(points=points) ug.set_cells(tri_type, self.cells) ug.cell_data.scalars = depth ug.cell_data.scalars.name = 'suntans_depth' #ug.point_data.scalars = dp*self.zscale #ug.point_data.scalars.name = 'suntans_depth_nodes' # Plot as a 3D surface src = mlab.pipeline.add_dataset(ug) h = mlab.pipeline.surface(src, vmin=clims[0], vmax=clims[1], **kwargs) return h
def vf3d_vtu(field, name): """ Function that wtrites a .vtu file ---Inputs--- field - Vector field which will be added to the vtk file numpy.array([x,y,z,u,v,w]) name - Name of the .vtu field --- C.Losada de la Lastra 2015 """ [X, Y, Z, U, V, W] = field #3d velocity field #achieve the correct format Pnts = F3d_2_vtkFromat(N.array([X, Y, Z])) velF = F3d_2_vtkFromat(N.array([U, V, W])) #name the vtu file if name == None: vtu = 'vf3VTU.vtu' else: vtu = name + '.vtu' #Generate and write the .vtu file Ugrid = tvtk.UnstructuredGrid() Ugrid.points = Pnts Ugrid.point_data.vectors = velF Ugrid.point_data.vectors.name = 'velocity' write_data(Ugrid, vtu) return vtu
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 writeUnstructuredGrid(self, points, cell_types, offset, cell_array, cellData): ug = tvtk.UnstructuredGrid(points=points) ug.set_cells(cell_types, offset, cell_array) ug.cell_data.scalars = cellData ug.cell_data.scalars.name = 'MaterialID' import PythonFCST as fcst ob = fcst.mesh.distanceSD(self.image, voxelsize=self.scale, material=0) ob.calcPSD(20) field_data = ob.imPSD.flatten() field_data = np.delete(field_data, np.where(field_data == 0)) field_data = np.append(field_data, self.cellData2) ug.cell_data.add_array(field_data) ug.cell_data.get_array(1).name = 'KnudsenRadius' ug.cell_data.update() writer = tvtk.UnstructuredGridWriter(file_name=self.filename) try: writer.set_input_data(ug) except: writer.set_input(ug) writer.update() writer.write()
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 plotvtk3D(self): """ 3D plot using the vtk libraries """ from tvtk.api import tvtk from mayavi import mlab # Plot the data on a 3D grid xy = np.column_stack((self.grd.xp,self.grd.yp)) dvp = self.F(xy) vertexag = 50.0 points = np.column_stack((self.grd.xp,self.grd.yp,dvp*vertexag)) tri_type = tvtk.Triangle().cell_type #tet_type = tvtk.Tetra().cell_type ug = tvtk.UnstructuredGrid(points=points) ug.set_cells(tri_type, self.grd.cells) ug.cell_data.scalars = self.grd.dv ug.cell_data.scalars.name = 'depths' f=mlab.gcf() f.scene.background = (0.,0.,0.) d = mlab.pipeline.add_dataset(ug) h=mlab.pipeline.surface(d,colormap='gist_earth') mlab.colorbar(object=h,orientation='vertical') mlab.view(0,0) outfile = self.suntanspath+'/depths.png' f.scene.save(outfile) print('Figure saved to %s.'%outfile)
def save_waveforms_vtk(result, outfile, **kwds): ''' Save a waveforms result to a VTK file. ''' from tvtk.api import tvtk, write_data arrs = result.array_data_by_type() paths = arrs['path'] pscalar = arrs['pscalar'] # flatten points = list() pathids = list() times = list() scalars = list() npaths, nsteps, four = paths.shape for ipath in range(npaths): for istep in range(nsteps): points.append(paths[ipath][istep][1:]) pathids.append(ipath) times.append(paths[ipath][istep][0]) scalars.append(pscalar[ipath][istep]) ug = tvtk.UnstructuredGrid() ug.points = points ug.point_data.scalars = scalars ug.point_data.scalars.name = 'current' # fixme: should get from result ug.point_data.add_array(times) ug.point_data.get_array(1).name = 'time' ug.point_data.add_array(pathids) ug.point_data.get_array(2).name = 'pathid' write_data(ug, outfile) return
def save_evaluate_vtk(result, outfile, **kwds): ''' Save a evaluation result to a VTK file. ''' from tvtk.api import tvtk, write_data points = result.parent_by_type('volume').array_data_by_type()['points'] filter = tvtk.AppendFilter() pot = result.array_data_by_type()['scalar'] pd = tvtk.PolyData(points=points) pd.point_data.scalars = pot.T pd.point_data.scalars.name = result.name pd.cell_data.scalars = pot.T pd.cell_data.scalars.name = result.name if False: filter.add_input_data(pd) filter.update() ug = tvtk.UnstructuredGrid() ug.shallow_copy(filter.get_output()) write_data(ug, outfile) else: write_data(pd, outfile) return
def save_current_vtk(result, outfile, **kwds): ''' Save current assuming no structure between starting points ''' from tvtk.api import tvtk, write_data cres = result dres = cres.parent_by_type('drift') # drift values = numpy.hstack([a.data for a in cres.arrays if a.type == 'pscalar']) points4 = numpy.vstack([a.data for a in dres.arrays if a.type == 'path']) assert len(values) == len(points4) points = points4[:, :3] npoints = len(points) print 'shapes: %s %s' % (str(values.shape), str(points.shape)) ug = tvtk.UnstructuredGrid() point_type = tvtk.Vertex().cell_type cell_types = numpy.array([point_type] * npoints) cell_array = tvtk.CellArray() cells = numpy.array([npoints] + range(npoints)) cell_array.set_cells(point_type, cells) ug.set_cells(1, cell_array) ug.points = points ug.point_data.scalars = values ug.point_data.scalars.name = 'current' write_data(ug, outfile)
def save_drift_vtk(result, outname, **kwds): ''' Save a drift result into a VTK file. ''' outname = osp.splitext(outname)[0] from tvtk.api import tvtk, write_data arrs = result.array_data_by_name() for thing in ['potential', 'gradient', 'velocity']: points = arrs[thing + '_points'] values = arrs[thing] npoints = len(points) ug = tvtk.UnstructuredGrid() point_type = tvtk.Vertex().cell_type cell_types = numpy.array([point_type] * npoints) cell_array = tvtk.CellArray() cells = numpy.array([npoints] + range(npoints)) cell_array.set_cells(point_type, cells) ug.set_cells(1, cell_array) ug.points = points ug.point_data.scalars = values ug.point_data.scalars.name = thing fname = '%s-%s.vtk' % (outname, thing) print 'writing %s' % fname write_data(ug, fname)
def VTKCellDataSet(self): """Returns a TVTK `DataSet` representing the cells of this mesh """ cvi = self._orderedCellVertexIDs.swapaxes(0, 1) from fipy.tools import numerix if isinstance(cvi, numerix.ma.masked_array): counts = cvi.count(axis=1)[:, None] cells = numerix.ma.concatenate((counts, cvi), axis=1).compressed() else: counts = numerix.array([cvi.shape[1]]*cvi.shape[0])[:, None] cells = numerix.concatenate((counts, cvi), axis=1).flatten() try: from tvtk.api import tvtk except ImportError as e: from enthought.tvtk.api import tvtk num = counts.shape[0] cps_type = self._VTKCellType cell_types = numerix.array([cps_type]*num) cell_array = tvtk.CellArray() cell_array.set_cells(num, cells) points = self.vertexCoords points = self._toVTK3D(points) ug = tvtk.UnstructuredGrid(points=points) offset = numerix.cumsum(counts[:, 0]+1) if len(offset) > 0: offset -= offset[0] ug.set_cells(cell_types, offset, cell_array) return ug
def get_complete_structure(tetrahedrons): """ Visualize the complete tetrahedron mesh of all regions of the tetrahedron mesh :param tetrahedrons: list of tetrahedrons (of type Tetrahedron) :return: data for mayavi data source """ vertices = list() tets = list() index = 0 for tetrahedron in tetrahedrons: tet_vertices_indices = [] for i in range(4): v = tetrahedron.get_vertex(i) vertices.append([v.x, v.y, v.z]) tet_vertices_indices.append(index) index += 1 tets.append(tet_vertices_indices) vertices = np.array(vertices) tets = np.array(tets) tet_type = tvtk.Tetra().cell_type unstructured_grid = tvtk.UnstructuredGrid(points=vertices) unstructured_grid.set_cells(tet_type, tets) return unstructured_grid
def VTKFaceDataSet(self): """Returns a TVTK `DataSet` representing the face centers of this mesh """ try: from tvtk.api import tvtk except ImportError as e: from enthought.tvtk.api import tvtk points = self.faceCenters points = self._toVTK3D(numerix.array(points)) ug = tvtk.UnstructuredGrid(points=points) num = len(points) counts = numerix.array([1] * num)[..., numerix.newaxis] cells = numerix.arange(self.numberOfFaces)[..., numerix.newaxis] cells = numerix.concatenate((counts, cells), axis=1) cell_types = numerix.array([tvtk.Vertex().cell_type]*num) cell_array = tvtk.CellArray() cell_array.set_cells(num, cells) counts = numerix.array([1] * num) offset = numerix.cumsum(counts+1) if len(offset) > 0: offset -= offset[0] ug.set_cells(cell_types, offset, cell_array) return ug
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 initMixedTvtk2D(self): """ Initialise the actual 2 dimensional tvtk object This is for a mixed data type """ poly_type = tvtk.Polygon().cell_type #poly_type = tvtk.Polyhedron().cell_type self.ug = tvtk.UnstructuredGrid(points=self.points) cells = np.array(self.cells[self.cells.mask==False]) cell_array = tvtk.CellArray() cell_array.set_cells(self.Nc,cells) offsets = np.cumsum(self.nfaces) offsets = offsets - offsets[0] poly_types = [poly_type for ii in range(self.Nc)] pdb.set_trace() self.ug.set_cells(np.array(poly_types),offsets, cell_array) self.ug.cell_data.scalars = self.data self.ug.cell_data.scalars.name = 'suntans_scalar'
def initMixedTvtk2D(self): """ Initialise the actual 2 dimensional tvtk object This is for a mixed data type """ poly_type = tvtk.Polygon().cell_type ug = tvtk.UnstructuredGrid(points=self.points) # Fill all of the cells with the first points # this is a bit of a hack but works... cells = self.cells for ii in range(self.Nc): nf = self.nfaces[ii] cells[ii, nf::] = cells[ii, 0] #offsets, cells = self.to_metismesh() ##cells = np.array(self.cells[self.cells.mask==False]) #cell_array = tvtk.CellArray() #cell_array.set_cells(self.Nc,cells) ##offsets = np.cumsum(self.nfaces) ##offsets = offsets - offsets[0] #poly_types = [poly_type for ii in range(self.Nc)] ## ##self.ug.set_cells(np.array(poly_types),offsets, cell_array) ## For a single cell type ug.set_cells(poly_type, self.cells) ug.cell_data.scalars = self.data ug.cell_data.scalars.name = 'suntans_scalar' return ug
def typeUnstructuredGrid_Plane(xyz, ikle): cellUG = tvtk.CellArray() cellUG.set_cells(len(ikle), np.insert(ikle, 0, 3, axis=1).ravel()) typeUG = tvtk.UnstructuredGrid(points=xyz) typeUG.set_cells(5 * np.ones(len(ikle)), 7 * np.arange(len(ikle)), cellUG) return typeUG
def _get_vtk_structure(self): ug = tvtk.UnstructuredGrid() cell_array, cell_offsets, cell_types = self.vtk_cell_data n_cells = cell_types.shape[0] ug.points = self.vtk_X vtk_cell_array = tvtk.CellArray() vtk_cell_array.set_cells(n_cells, cell_array) ug.set_cells(cell_types, cell_offsets, vtk_cell_array) return ug
def to_vtk(self): points = self.vtk_points() cell_types = self.vtk_cell_types() cell_array = self.vtk_cell_array() offsets = self.vtk_offsets() vtk_grid = tvtk.UnstructuredGrid(points=points) vtk_grid.set_cells(cell_types, offsets, cell_array) return vtk_grid
def clusters2blobs(gr): ''' Given a graph object return a tvtk data object with blbos. ''' from tvtk.api import tvtk, write_data all_points = list() blob_cells = list() datasetnames = set() values = list() for node, ndata in gr.nodes.data(): if ndata['code'] != 'b': continue vals = dict() thickness = 1.0 for key, val in ndata.items(): if key == 'corners': pts = orderpoints(val) continue if key == 'span': thickness = val continue if key == 'code': continue datasetnames.add(key) vals[key] = val pts, cells = extrude(pts, thickness) all_points += pts blob_cells.append((len(pts), cells)) values.append(vals) ugrid = tvtk.UnstructuredGrid(points=all_points) ptype = tvtk.Polyhedron().cell_type offset = 0 for npts, cells in blob_cells: cell_ids = [len(cells)] for cell in cells: cell_ids.append(len(cell)) cell_ids += [offset + cid for cid in cell] ugrid.insert_next_cell(ptype, cell_ids) offset += npts ugrid.cell_data.scalars = list(range(len(values))) ugrid.cell_data.scalars.name = "indices" narrays = 1 for datasetname in sorted(datasetnames): arr = numpy.asarray([vals.get(datasetname, 0.0) for vals in values], dtype=float) ugrid.cell_data.add_array(arr) ugrid.cell_data.get_array(narrays).name = datasetname narrays += 1 return ugrid
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 initTvtk2D(self): """ Initialise the actual 2 dimensional tvtk object """ tri_type = tvtk.Triangle().cell_type self.ug = tvtk.UnstructuredGrid(points=self.points) self.ug.set_cells(tri_type, self.cells) self.ug.cell_data.scalars = self.data self.ug.cell_data.scalars.name = 'suntans_scalar'
def generate_unstrgrid_mesh(self, filter=0): points = global_variable.NODE_COORDINATES self.index = where(self.density >= (1.0 - filter))[0].tolist() cells = (global_variable.ELEMENT_ATTRIBUTES[self.index, :] - 1) if global_variable.GRID_TYPE == 'Polygon': cell_tpye = tvtk.Polygon().cell_type if global_variable.GRID_TYPE == 'Hexahedron': cell_tpye = tvtk.Hexahedron().cell_type grid = tvtk.UnstructuredGrid(points=points) grid.set_cells(cell_tpye, cells) return grid
def writeUnstructuredGrid(self,points, cell_types, offset, cell_array, cellData): ug = tvtk.UnstructuredGrid(points=points) ug.set_cells(cell_types, offset, cell_array) ug.cell_data.scalars=cellData ug.cell_data.scalars.name='MaterialID' writer=tvtk.UnstructuredGridWriter(file_name=self.filename) try: writer.set_input_data(ug) except: writer.set_input(ug) writer.update() writer.write()
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 make_mb_dataset(): fpath = get_example_data('pyramid_ug.vtu') r = tvtk.XMLUnstructuredGridReader(file_name=fpath) r.update() ug0 = r.output ug1 = tvtk.UnstructuredGrid() ug1.deep_copy(ug0) pts = ug1.points.to_array() pts[:, 0] += 10.0 ug1.points = pts mb = tvtk.MultiBlockDataSet() mb.set_block(0, ug0) mb.set_block(1, ug1) return mb
def plotbathy3d(self,clims=None,**kwargs): """ Adds 3D plot of the bathymetry to the current scene """ # Create a new scene if there isn't one if not self.__dict__.has_key('fig'): self.newscene() depth = -self.dv if clims==None: clim = [depth.min(), depth.max()] # Create an unstructured grid object to interpolate cells onto points points = np.column_stack((self.xp,self.yp,0.0*self.xp)) tri_type = tvtk.Triangle().cell_type ug = tvtk.UnstructuredGrid(points=points) ug.set_cells(tri_type, self.cells) ug.cell_data.scalars = depth ug.cell_data.scalars.name = 'suntans_depth' # Interpolate the cell data onto the points F = mlab.pipeline.cell_to_point_data(ug) dp = mlab.pipeline.probe_data(F,self.xp,self.yp,0.0*self.xp) # Now set up a new object with the 3D points points = np.column_stack((self.xp,self.yp,dp*self.zscale)) ug = tvtk.UnstructuredGrid(points=points) ug.set_cells(tri_type, self.cells) ug.cell_data.scalars = depth ug.cell_data.scalars.name = 'suntans_depth' # Plot as a 3D surface src = mlab.pipeline.add_dataset(ug) h=mlab.pipeline.surface(src,vmin=clim[0],vmax=clim[1],**kwargs) return h
def _dump_arrays(self, filename): from tvtk.api import tvtk n = self.numPoints cells = np.arange(n) cells.shape = (n, 1) cell_type = tvtk.Vertex().cell_type ug = tvtk.UnstructuredGrid(points=self.points.transpose()) ug.set_cells(cell_type, cells) from mayavi.core.dataset_manager import DatasetManager dsm = DatasetManager(dataset=ug) for name, field in self.data: dsm.add_array(field.transpose(), name) dsm.activate(name) from tvtk.api import write_data write_data(ug, filename)
def create_mb_dataset(): mydir = os.path.dirname(__file__) path = os.path.join(mydir, os.pardir, 'data', 'fire_ug.vtu') r = tvtk.XMLUnstructuredGridReader(file_name=path) r.update() ug0 = r.output ug1 = tvtk.UnstructuredGrid() ug1.deep_copy(ug0) pts = ug1.points.to_array() pts[:, 2] += 3.0 ug1.points = pts mb = tvtk.MultiBlockDataSet() mb.set_block(0, ug0) mb.set_block(1, ug1) return mb
def blobs(blobs): ''' Given a data structure which is a list of blobs, each blob is a dict: { points=[[x1,y1,z1], [x2,y2,z2],...], values=dict(name1=val1, name2=val2), thickness=1.0, # optional } return an unstructured grid ''' datasetnames = set() all_points = list() blob_cells = [] for blob in blobs: myvalnames = list(blob['values'].keys()) datasetnames = datasetnames.union(myvalnames) pts = orderpoints(blob['points']) pts, cells = extrude(pts, blob.get('thickness', 1.0)) all_points += pts blob_cells.append((len(pts), cells)) ugrid = tvtk.UnstructuredGrid(points=all_points) ptype = tvtk.Polyhedron().cell_type offset = 0 for npts, cells in blob_cells: cell_ids = [len(cells)] for cell in cells: cell_ids.append(len(cell)) cell_ids += [offset + cid for cid in cell] ugrid.insert_next_cell(ptype, cell_ids) offset += npts ugrid.cell_data.scalars = list(range(len(blobs))) ugrid.cell_data.scalars.name = "indices" print(datasetnames) narrays = 1 for datasetname in sorted(datasetnames): arr = [b["values"].get(datasetname, 0.0) for b in blobs] ugrid.cell_data.add_array(arr) ugrid.cell_data.get_array(narrays).name = datasetname narrays += 1 return ugrid