def Create_Topo(Slope,Plane): ugrid = vtk.vtkUnstructuredGrid() gridreader=vtk.vtkUnstructuredGridReader() gridreader.SetFileName(Slope) gridreader.Update() ugrid = gridreader.GetOutput() GeomFilt1 = vtk.vtkGeometryFilter() GeomFilt1.SetInput(ugrid) GeomFilt1.Update() x = GeomFilt1.GetOutput() u = vtk.vtkUnstructuredGrid() bgridreader=vtk.vtkXMLUnstructuredGridReader() bgridreader.SetFileName(Plane) bgridreader.Update() u = bgridreader.GetOutput() GeomFilt2 = vtk.vtkGeometryFilter() GeomFilt2.SetInput(u) GeomFilt2.Update() y = GeomFilt2.GetOutput() append = vtk.vtkAppendPolyData() append.AddInput(x) append.AddInput(y) data = append.GetOutput() d = vtk.vtkDelaunay3D() d.SetInput(data) d.Update d.BoundingTriangulationOff() d.SetTolerance(0.00001) d.SetAlpha(0) d.Update() z = d.GetOutput() return z
def Creating_z(Plane,Slope,Sediment,Start_time,End_time,Time_step): vtuObject = vtktools.vtu(Plane) vtuObject.GetFieldNames() gradient = vtuObject.GetScalarField('u') ugrid = vtk.vtkUnstructuredGrid() gridreader=vtk.vtkXMLUnstructuredGridReader() gridreader.SetFileName(Plane) gridreader.Update() ugrid = gridreader.GetOutput() points = ugrid.GetPoints() nPoints = ugrid.GetNumberOfPoints() for p in range(0,nPoints): x = (points.GetPoint(p)[:2] + (gradient[p],)) points.SetPoint(p,x) ugrid.Update() ################################################################################################################### t = Start_time dt = Time_step et = End_time while t <= et: Import = Sediment + str(t) +'000000.vtu' NewSave = Sediment + str(t) + '_sed_slope.pvd' vtuObjectSed = vtktools.vtu(Import) vtuObjectSed.GetFieldNames() gradientSed = vtuObjectSed.GetScalarField('u') sedgrid = vtk.vtkUnstructuredGrid() sedgridreader=vtk.vtkXMLUnstructuredGridReader() sedgridreader.SetFileName(Import) sedgridreader.Update() sedgrid = sedgridreader.GetOutput() s = sedgrid.GetPoints() for p in range(0,nPoints): x = ((s.GetPoint(p)[0],) + (s.GetPoint(p)[1],) + ((gradientSed[p]+gradient[p]),)) s.SetPoint(p,x) writer = vtk.vtkUnstructuredGridWriter() writer.SetFileName(NewSave) writer.SetInput(sedgrid) writer.Update() writer.Write() t += dt writer = vtk.vtkUnstructuredGridWriter() writer.SetFileName(Slope) writer.SetInput(ugrid) writer.Update() writer.Write()
def removeOldGeometry(self, fileName): if fileName is None: self.grid = vtk.vtkUnstructuredGrid() self.gridResult = vtk.vtkFloatArray() #self.emptyResult = vtk.vtkFloatArray() #self.vectorResult = vtk.vtkFloatArray() self.grid2 = vtk.vtkUnstructuredGrid() self.scalarBar.VisibilityOff() skipReading = True else: self.TurnTextOff() self.grid.Reset() self.grid2.Reset() self.gridResult = vtk.vtkFloatArray() self.gridResult.Reset() self.gridResult.Modified() self.eidMap = {} self.nidMap = {} self.resultCases = {} self.nCases = 0 try: del self.caseKeys del self.iCase del self.iSubcaseNameMap except: print "cant delete geo" pass ### #print dir(self) skipReading = False self.scalarBar.VisibilityOff() self.scalarBar.Modified() return skipReading
def test_contours(self): cell = vtk.vtkUnstructuredGrid() cell.ShallowCopy(self.Cell) np = self.Cell.GetNumberOfPoints() ncomb = pow(2, np) scalar = vtk.vtkDoubleArray() scalar.SetName("scalar") scalar.SetNumberOfTuples(np) cell.GetPointData().SetScalars(scalar) incorrectCases = [] for i in range(1,ncomb-1): c = Combination(np, i) for p in range(np): scalar.SetTuple1(p, c[p]) gradientFilter = vtk.vtkGradientFilter() gradientFilter.SetInputData(cell) gradientFilter.SetInputArrayToProcess(0,0,0,0,'scalar') gradientFilter.SetResultArrayName('grad') gradientFilter.Update() contourFilter = vtk.vtkContourFilter() contourFilter.SetInputConnection(gradientFilter.GetOutputPort()) contourFilter.SetNumberOfContours(1) contourFilter.SetValue(0, 0.5) contourFilter.Update() normalsFilter = vtk.vtkPolyDataNormals() normalsFilter.SetInputConnection(contourFilter.GetOutputPort()) normalsFilter.SetConsistency(0) normalsFilter.SetFlipNormals(0) normalsFilter.SetSplitting(0) calcFilter = vtk.vtkArrayCalculator() calcFilter.SetInputConnection(normalsFilter.GetOutputPort()) calcFilter.SetAttributeTypeToPointData() calcFilter.AddVectorArrayName('grad') calcFilter.AddVectorArrayName('Normals') calcFilter.SetResultArrayName('dir') calcFilter.SetFunction('grad.Normals') calcFilter.Update() out = vtk.vtkUnstructuredGrid() out.ShallowCopy(calcFilter.GetOutput()) numPts = out.GetNumberOfPoints() if numPts > 0: dirArray = out.GetPointData().GetArray('dir') for p in range(numPts): if(dirArray.GetTuple1(p) > 0.0): # all normals are reversed incorrectCases.append(i) break self.assertEquals(','.join([str(i) for i in incorrectCases]), '')
def __init__(self, *args, **kwargs): self.grid = vtk.vtkUnstructuredGrid() #gridResult = vtk.vtkFloatArray() #self.emptyResult = vtk.vtkFloatArray() #self.vectorResult = vtk.vtkFloatArray() self.grid2 = vtk.vtkUnstructuredGrid() # edges self.edgeActor = vtk.vtkActor() self.edgeMapper = vtk.vtkPolyDataMapper() self.is_edges = kwargs['is_edges'] self.is_nodal = kwargs['is_nodal'] self.is_centroidal = kwargs['is_centroidal'] self.magnify = kwargs['magnify'] self.debug = True gui_parent = kwargs['gui_parent'] if 'log' in kwargs: self.log = kwargs['log'] del kwargs['log'] del kwargs['gui_parent'] del kwargs['is_edges'] del kwargs['is_nodal'] del kwargs['is_centroidal'] del kwargs['magnify'] #del kwargs['rotation'] wx.Panel.__init__(self, *args, **kwargs) NastranIO.__init__(self) Cart3dIO.__init__(self) LaWGS_IO.__init__(self) PanairIO.__init__(self) STL_IO.__init__(self) TetgenIO.__init__(self) Usm3dIO.__init__(self) self.nCases = 0 #print("is_edges = %r" % self.is_edges) self.widget = pyWidget(self, -1) window = self.widget.GetRenderWindow() self.iren = vtk.vtkRenderWindowInteractor() if platform.system == 'Windows': self.iren.SetRenderWindow(window) self.iText = 0 self.textActors = {}
def makeEdgeVTKObject(mesh,model): """ Make and return a edge based VTK object for a simpeg mesh and model. Input: :param mesh, SimPEG TensorMesh object - mesh to be transfer to VTK :param model, dictionary of numpy.array - Name('s) and array('s). Property array must be order hstack(Ex,Ey,Ez) Output: :rtype: vtkUnstructuredGrid object :return: vtkObj """ ## Convert simpeg mesh to VTK properties # Convert mesh nodes to vtkPoints vtkPts = vtk.vtkPoints() vtkPts.SetData(npsup.numpy_to_vtk(mesh.gridN,deep=1)) # Define the face "cells" # Using VTK_QUAD cell for faces (see VTK file format) nodeMat = mesh.r(np.arange(mesh.nN,dtype='int64'),'N','N','M') def edgeR(mat,length): return mat.T.reshape((length,1)) # First direction nTEx = np.prod(mesh.nEx) ExCellBlock = np.hstack([ 2*np.ones((nTEx,1),dtype='int64'),edgeR(nodeMat[:-1,:,:],nTEx),edgeR(nodeMat[1:,:,:],nTEx)]) # Second direction if mesh.dim >= 2: nTEy = np.prod(mesh.nEy) EyCellBlock = np.hstack([ 2*np.ones((nTEy,1),dtype='int64'),edgeR(nodeMat[:,:-1,:],nTEy),edgeR(nodeMat[:,1:,:],nTEy)]) # Third direction if mesh.dim == 3: nTEz = np.prod(mesh.nEz) EzCellBlock = np.hstack([ 2*np.ones((nTEz,1),dtype='int64'),edgeR(nodeMat[:,:,:-1],nTEz),edgeR(nodeMat[:,:,1:],nTEz)]) # Cells -cell array ECellArr = vtk.vtkCellArray() ECellArr.SetNumberOfCells(mesh.nE) ECellArr.SetCells(mesh.nE,npsup.numpy_to_vtkIdTypeArray(np.vstack([ExCellBlock,EyCellBlock,EzCellBlock]),deep=1)) # Cell type ECellType = npsup.numpy_to_vtk(vtk.VTK_LINE*np.ones(mesh.nE,dtype='uint8'),deep=1) # Cell location ECellLoc = npsup.numpy_to_vtkIdTypeArray(np.arange(0,mesh.nE*3,3,dtype='int64'),deep=1) ## Make the object vtkObj = vtk.vtkUnstructuredGrid() # Set the objects properties vtkObj.SetPoints(vtkPts) vtkObj.SetCells(ECellType,ECellLoc,ECellArr) # Assign the model('s) to the object for item in model.iteritems(): # Convert numpy array vtkDoubleArr = npsup.numpy_to_vtk(item[1],deep=1) vtkDoubleArr.SetName(item[0]) vtkObj.GetCellData().AddArray(vtkDoubleArr) vtkObj.GetCellData().SetActiveScalars(model.keys()[0]) vtkObj.Update() return vtkObj
def makeTetraGrid(nCubes, flip=0): max_x=nCubes+1 max_y=nCubes+1 max_z=nCubes+1 scale=20./nCubes #*(19./20) meshPoints = vtk.vtkPoints() meshPoints.SetNumberOfPoints(max_x*max_y*max_z) #i*(max_y)*(max_z)+j*(max_z)+k for i in xrange(max_x): for j in xrange(max_y): for k in xrange(max_z): meshPoints.InsertPoint(i*(max_y)*(max_z)+j*(max_z)+k,scale*i,scale*j,scale*k) nelements = 5*(max_x-1)*(max_y-1)*(max_z-1) meshGrid = vtk.vtkUnstructuredGrid() meshGrid.Allocate(nelements, nelements) meshGrid.SetPoints(meshPoints) for i in range(max_x-1): for j in range(max_y-1): for k in range(max_z-1): ulf = (i+1)*(max_y)*(max_z)+j*(max_z)+k # upper left front urf = (i+1)*(max_y)*(max_z)+(j+1)*(max_z)+k # upper right front lrf = i*(max_y)*(max_z)+(j+1)*(max_z)+k # lower right front llf = i*(max_y)*(max_z)+j*(max_z)+k # lower left front ulb = (i+1)*(max_y)*(max_z)+j*(max_z)+k+1 # upper left back urb = (i+1)*(max_y)*(max_z)+(j+1)*(max_z)+k+1 # upper right back lrb = i*(max_y)*(max_z)+(j+1)*(max_z)+k+1 # lower right back llb = i*(max_y)*(max_z)+j*(max_z)+k+1 # lower left back point_order = [ # not flip [[llf,urf,lrf,lrb], [llf,ulf,urf,ulb], [lrb,urf,urb,ulb], [llf,lrb,llb,ulb], [llf,ulb,urf,lrb]], # flip [[llf,ulf,lrf,llb], [ulf,urf,lrf,urb], [ulf,ulb,urb,llb], [lrf,urb,lrb,llb], [ulf,urb,lrf,llb] ]] for o in point_order[flip]: cell = vtk.vtkTetra() id=0 for p in o: cell.GetPointIds().SetId(id,p) id+=1 meshGrid.InsertNextCell(cell.GetCellType(),cell.GetPointIds()) flip = not flip if (max_z-1)%2==0: flip = not flip if (max_y-1)%2==0: flip = not flip return meshGrid
def makeVoxelGrid(nCubes): max_x=nCubes+1 max_y=nCubes+1 max_z=nCubes+1 scale=20./nCubes #*(19./20) meshPoints = vtk.vtkPoints() meshPoints.SetNumberOfPoints(max_x*max_y*max_z) #i*(max_y)*(max_z)+j*(max_z)+k for i in xrange(max_x): for j in xrange(max_y): for k in xrange(max_z): meshPoints.InsertPoint(i*(max_y)*(max_z)+j*(max_z)+k,scale*i,scale*j,scale*k) nelements = (max_x-1)*(max_y-1)*(max_z-1) meshGrid = vtk.vtkUnstructuredGrid() meshGrid.Allocate(nelements, nelements) meshGrid.SetPoints(meshPoints) for i in range(max_x-1): for j in range(max_y-1): for k in range(max_z-1): cell = vtk.vtkHexahedron() # This is the order we need such that the normals point out. cell.GetPointIds().SetId(0, (i+1)*(max_y)*(max_z)+j*(max_z)+k) # upper left front cell.GetPointIds().SetId(1, (i+1)*(max_y)*(max_z)+(j+1)*(max_z)+k) # upper right front cell.GetPointIds().SetId(2, i*(max_y)*(max_z)+(j+1)*(max_z)+k) # lower right front cell.GetPointIds().SetId(3, i*(max_y)*(max_z)+j*(max_z)+k) # lower left front node index cell.GetPointIds().SetId(4, (i+1)*(max_y)*(max_z)+j*(max_z)+k+1) # upper left back cell.GetPointIds().SetId(5, (i+1)*(max_y)*(max_z)+(j+1)*(max_z)+k+1) # upper right back cell.GetPointIds().SetId(6, i*(max_y)*(max_z)+(j+1)*(max_z)+k+1) # lower right back cell.GetPointIds().SetId(7, i*(max_y)*(max_z)+j*(max_z)+k+1) # lower left back meshGrid.InsertNextCell(cell.GetCellType(), cell.GetPointIds()) return meshGrid
def create_vessel_actor(ref_data): # vessel_ref_data = ref_data points = vtk.vtkPoints() # insert each properties of points into obj. for i in xrange(len(ref_data)): x = ref_data[i][0] y = ref_data[i][1] z = ref_data[i][2] points.InsertPoint(i, x, y, z) poly = vtk.vtkPolyVertex() poly.GetPointIds().SetNumberOfIds(len(ref_data)) cont = 0 while cont < len(ref_data): poly.GetPointIds().SetId(cont, cont) cont += 1 grid = vtk.vtkUnstructuredGrid() grid.SetPoints(points) grid.InsertNextCell(poly.GetCellType(), poly.GetPointIds()) mapper = vtk.vtkDataSetMapper() if sys.hexversion == 34015984: mapper.SetInputData(grid) if sys.hexversion == 34015728: mapper.SetInput(grid) actor = vtk.vtkActor() actor.SetMapper(mapper) return actor
def show_beta_sheets(renderer): for sheet in sheet_defs: # helix = helix_defs[1] aPolyLineGrid = vtk.vtkUnstructuredGrid() aPolyLineGrid.Allocate(5, 1) (polyLinePoints, aPolyLine) = make_polyline(sheet) # # Create a tube filter to represent the lines as tubes. Set up the # # associated mapper and actor. # tuber = vtk.vtkTubeFilter() # tuber.SetInputConnection(appendF.GetOutputPort()) # tuber.SetRadius(0.1) # lineMapper = vtk.vtkPolyDataMapper() # lineMapper.SetInputConnection(tuber.GetOutputPort()) # lineActor = vtk.vtkActor() # lineActor.SetMapper(lineMapper) aPolyLineGrid.InsertNextCell(aPolyLine.GetCellType(), aPolyLine.GetPointIds()) aPolyLineGrid.SetPoints(polyLinePoints) aPolyLineMapper = vtk.vtkDataSetMapper() aPolyLineMapper.SetInput(aPolyLineGrid) aPolyLineActor = vtk.vtkActor() aPolyLineActor.SetMapper(aPolyLineMapper) aPolyLineActor.GetProperty().SetDiffuseColor(1, 1, 1) renderer.AddActor(aPolyLineActor)
def __init__(self, pos, cell): """Construct basic VTK-representation of a set of atomic positions. pos: NumPy array of dtype float and shape ``(n,3)`` Cartesian positions of the atoms. cell: Instance of vtkUnitCellModule of subclass thereof Holds information equivalent to that of atoms.get_cell(). """ # Make sure position argument is a valid array if not isinstance(pos, np.ndarray): pos = np.array(pos) assert pos.dtype == float and pos.shape[1:] == (3,) vtkBaseGrid.__init__(self, len(pos), cell) # Convert positions to VTK array npy2da = vtkDoubleArrayFromNumPyArray(pos) vtk_pda = npy2da.get_output() del npy2da # Transfer atomic positions to VTK points self.vtk_pts = vtkPoints() self.vtk_pts.SetData(vtk_pda) # Create a VTK unstructured grid of these points self.vtk_ugd = vtkUnstructuredGrid() self.vtk_ugd.SetWholeBoundingBox(self.cell.get_bounding_box()) self.vtk_ugd.SetPoints(self.vtk_pts) # Extract the VTK point data set self.set_point_data(self.vtk_ugd.GetPointData())
def Gen_uGrid(new_pt, new_fc): """ Generates a vtk unstructured grid given points and triangular faces""" ints = np.ones(len(new_fc), 'int')*3 cells = np.hstack((ints.reshape(-1, 1), np.vstack(new_fc))) # Generate vtk mesh # Convert points to vtkfloat object points = np.vstack(new_pt) vtkArray = VN.numpy_to_vtk(np.ascontiguousarray(points), deep=True)#, deep=True) points = vtk.vtkPoints() points.SetData(vtkArray) # Convert to vtk arrays tritype = vtk.vtkTriangle().GetCellType()*np.ones(len(new_fc), 'int') cell_type = np.ascontiguousarray(tritype).astype('uint8') cell_type = VN.numpy_to_vtk(cell_type, deep=True) offset = np.cumsum(np.hstack(ints + 1)) offset = np.ascontiguousarray(np.delete(np.insert(offset, 0, 0), -1)).astype('int64') # shift offset = VN.numpy_to_vtkIdTypeArray(offset, deep=True) cells = np.ascontiguousarray(np.hstack(cells).astype('int64')) vtkcells = vtk.vtkCellArray() vtkcells.SetCells(cells.shape[0], VN.numpy_to_vtkIdTypeArray(cells, deep=True)) # Create unstructured grid uGrid = vtk.vtkUnstructuredGrid() uGrid.SetPoints(points) uGrid.SetCells(cell_type, offset, vtkcells) return uGrid
def pca(self): """Performs Principle Component Analysis on the alignedGrids. Also calculates the mean shape. """ logging.info("running pca") size = len(self.alignedGrids) self.filterPCA.SetNumberOfInputs(size) for id, grid in enumerate(self.alignedGrids): self.filterPCA.SetInput(id, grid) self.filterPCA.Update() #Get the eigenvalues evals = self.filterPCA.GetEvals() #Now let's get mean ^^ b = vtk.vtkFloatArray() b.SetNumberOfComponents(0) b.SetNumberOfTuples(0) mean = vtk.vtkUnstructuredGrid() mean.DeepCopy(self.alignedGrids[0]) #Get the mean shape: self.filterPCA.GetParameterisedShape(b, mean) self.meanShape.append(mean) #get the meanpositions for pos in range(self.meanShape[0].GetNumberOfCells()): bounds = self.meanShape[0].GetCell(pos).GetBounds() self.meanPositions.append((bounds[0],bounds[2])) logging.info("done")
def addPointSet(self, data): """Add a set of points to the UnstructuredGrid vertexGrid (the source of our calculations) """ logging.info("adding point set") size = len(data) # Create some landmarks, put them in UnstructuredGrid # Start off with some landmarks vertexPoints = vtk.vtkPoints() vertexPoints.SetNumberOfPoints(size) vertexGrid = vtk.vtkUnstructuredGrid() vertexGrid.Allocate(size, size) for id, (x, y, z) in enumerate(data): vertexPoints.InsertPoint(id, x, y, z) # Create vertices from them vertex = vtk.vtkVertex() vertex.GetPointIds().SetId(0, id) #Create an unstructured grid with the landmarks added vertexGrid.InsertNextCell(vertex.GetCellType(), vertex.GetPointIds()) vertexGrid.SetPoints(vertexPoints) self.vertexGrids.append(vertexGrid) logging.info("done")
def represent_map(self, map_id): """Creates the vtkPoints collection of points representing the network map given in parameter (map name), and the wrapping vtkPolyVertex and vtkUnstructuredGrid. Registers the points in the right position in the ordered vtk_units list.""" net_struct_u = self.network_structure.units u_gids = self.network_structure.maps[map_id] pts = None # if len(net_struct_u[net_struct_u.index(u_gids[0])].coords) == 2: # pts = vtk.vtkPoints2D() # else: # pts = vtk.vtkPoints() pts = vtk.vtkPoints() grid = vtk.vtkUnstructuredGrid() pv = vtk.vtkPolyVertex() l = [] for p_gid in u_gids: p_i = net_struct_u.index(p_gid) coords = net_struct_u[p_i].coords if len(coords) == 2: coords = (coords[0], coords[1], 0) l.append(pts.InsertNextPoint(coords)) self.vtk_units[p_i] = (grid, l[len(l) - 1]) # necessay if using SetId and not InsertId in the next loop: pv.GetPointIds().SetNumberOfIds(len(l)) for i in range(len(l)): pv.GetPointIds().SetId(i, l[i]) # vtkPoints -> vtkPolyVertex -> vtkUnstructuredGrid grid.InsertNextCell(pv.GetCellType(), pv.GetPointIds()) grid.SetPoints(pts) return (grid, len(l))
def MakePentagonalPrism(): numberOfVertices = 10 # Create the points points = vtk.vtkPoints() points.InsertNextPoint(11, 10, 10) points.InsertNextPoint(13, 10, 10) points.InsertNextPoint(14, 12, 10) points.InsertNextPoint(12, 14, 10) points.InsertNextPoint(10, 12, 10) points.InsertNextPoint(11, 10, 14) points.InsertNextPoint(13, 10, 14) points.InsertNextPoint(14, 12, 14) points.InsertNextPoint(12, 14, 14) points.InsertNextPoint(10, 12, 14) # Pentagonal Prism pentagonalPrism = vtk.vtkPentagonalPrism() for i in range(0, numberOfVertices): pentagonalPrism.GetPointIds().SetId(i, i) # Add the points and hexahedron to an unstructured grid uGrid = vtk.vtkUnstructuredGrid() uGrid.SetPoints(points) uGrid.InsertNextCell(pentagonalPrism.GetCellType(), pentagonalPrism.GetPointIds()) return uGrid
def testLinear(self): pts = vtk.vtkPoints() pts.SetNumberOfPoints(4) pts.InsertPoint(0, (0, 0, 0)) pts.InsertPoint(1, (1, 0, 0)) pts.InsertPoint(2, (0.5, 1, 0)) pts.InsertPoint(3, (0.5, 0.5, 1)) te = vtk.vtkTetra() ptIds = te.GetPointIds() for i in range(4): ptIds.SetId(i, i) ghosts = vtk.vtkUnsignedCharArray() ghosts.SetName("vtkGhostLevels") ghosts.SetNumberOfTuples(4) ghosts.SetValue(0, 1) ghosts.SetValue(1, 1) ghosts.SetValue(2, 1) ghosts.SetValue(3, 0) grid = vtk.vtkUnstructuredGrid() grid.Allocate(1, 1) grid.InsertNextCell(te.GetCellType(), te.GetPointIds()) grid.SetPoints(pts) grid.GetPointData().AddArray(ghosts) dss = vtk.vtkDataSetSurfaceFilter() dss.SetInputData(grid) dss.Update() self.assertEqual(dss.GetOutput().GetNumberOfCells(), 3)
def doNonLinear(self, ghosts, ncells): pts = vtk.vtkPoints() pts.SetNumberOfPoints(10) pts.InsertPoint(0, (0, 0, 0)) pts.InsertPoint(1, (1, 0, 0)) pts.InsertPoint(2, (0.5, 1, 0)) pts.InsertPoint(3, (0.5, 0.5, 1)) pts.InsertPoint(4, (0.5, 0, 0)) pts.InsertPoint(5, (1.25, 0.5, 0)) pts.InsertPoint(6, (0.25, 0.5, 0)) pts.InsertPoint(7, (0.25, 0.25, 0.5)) pts.InsertPoint(8, (0.75, 0.25, 0.5)) pts.InsertPoint(9, (0.5, 0.75, 0.5)) te = vtk.vtkQuadraticTetra() ptIds = te.GetPointIds() for i in range(10): ptIds.SetId(i, i) grid = vtk.vtkUnstructuredGrid() grid.Allocate(1, 1) grid.InsertNextCell(te.GetCellType(), te.GetPointIds()) grid.SetPoints(pts) grid.GetPointData().AddArray(ghosts) ugg = vtk.vtkUnstructuredGridGeometryFilter() ugg.SetInputData(grid) dss = vtk.vtkDataSetSurfaceFilter() dss.SetNonlinearSubdivisionLevel(2) dss.SetInputConnection(ugg.GetOutputPort()) dss.Update() self.assertEqual(dss.GetOutput().GetNumberOfCells(), ncells)
def MakeWedge(): ''' A wedge consists of two triangular ends and three rectangular faces. ''' numberOfVertices = 6 points = vtk.vtkPoints() points.InsertNextPoint(0, 1, 0) points.InsertNextPoint(0, 0, 0) points.InsertNextPoint(0, .5, .5) points.InsertNextPoint(1, 1, 0) points.InsertNextPoint(1, 0.0, 0.0) points.InsertNextPoint(1, .5, .5) wedge = vtk.vtkWedge() for i in range(0, numberOfVertices): wedge.GetPointIds().SetId(i, i) ug = vtk.vtkUnstructuredGrid() ug.SetPoints(points) ug.InsertNextCell(wedge.GetCellType(), wedge.GetPointIds()) return ug
def MakeHexagonalPrism(): ''' 3D: hexagonal prism: a wedge with an hexagonal base. Be careful, the base face ordering is different from wedge. ''' numberOfVertices = 12 points = vtk.vtkPoints() points.InsertNextPoint(0.0, 0.0, 1.0) points.InsertNextPoint(1.0, 0.0, 1.0) points.InsertNextPoint(1.5, 0.5, 1.0) points.InsertNextPoint(1.0, 1.0, 1.0) points.InsertNextPoint(0.0, 1.0, 1.0) points.InsertNextPoint(-0.5, 0.5, 1.0) points.InsertNextPoint(0.0, 0.0, 0.0) points.InsertNextPoint(1.0, 0.0, 0.0) points.InsertNextPoint(1.5, 0.5, 0.0) points.InsertNextPoint(1.0, 1.0, 0.0) points.InsertNextPoint(0.0, 1.0, 0.0) points.InsertNextPoint(-0.5, 0.5, 0.0) hexagonalPrism = vtk.vtkHexagonalPrism() for i in range(0, numberOfVertices): hexagonalPrism.GetPointIds().SetId(i, i) ug = vtk.vtkUnstructuredGrid() ug.InsertNextCell(hexagonalPrism.GetCellType(), hexagonalPrism.GetPointIds()) ug.SetPoints(points) return ug
def MakePyramid(): ''' Make a regular square pyramid. ''' numberOfVertices = 5 points = vtk.vtkPoints() p = [ [1.0, 1.0, 0.0], [-1.0, 1.0, 0.0], [-1.0, -1.0, 0.0], [1.0, -1.0, 0.0], [0.0, 0.0, 1.0] ] for pt in p: points.InsertNextPoint(pt) pyramid = vtk.vtkPyramid() for i in range(0, numberOfVertices): pyramid.GetPointIds().SetId(i, i) ug = vtk.vtkUnstructuredGrid() ug.SetPoints(points) ug.InsertNextCell(pyramid.GetCellType(), pyramid.GetPointIds()) return ug
def findPointsInCell(points, cell, verbose=1): ugrid_cell = vtk.vtkUnstructuredGrid() ugrid_cell.SetPoints(cell.GetPoints()) cell = vtk.vtkHexahedron() for k_point in xrange(8): cell.GetPointIds().SetId(k_point, k_point) cell_array_cell = vtk.vtkCellArray() cell_array_cell.InsertNextCell(cell) ugrid_cell.SetCells(vtk.VTK_HEXAHEDRON, cell_array_cell) geometry_filter = vtk.vtkGeometryFilter() geometry_filter.SetInputData(ugrid_cell) geometry_filter.Update() cell_boundary = geometry_filter.GetOutput() pdata_points = vtk.vtkPolyData() pdata_points.SetPoints(points) enclosed_points_filter = vtk.vtkSelectEnclosedPoints() enclosed_points_filter.SetSurfaceData(cell_boundary) enclosed_points_filter.SetInputData(pdata_points) enclosed_points_filter.Update() points_in_cell = [k_point for k_point in xrange(points.GetNumberOfPoints()) if enclosed_points_filter.GetOutput().GetPointData().GetArray('SelectedPoints').GetTuple(k_point)[0]] return points_in_cell
def MakeVoxel(): ''' A voxel is a representation of a regular grid in 3-D space. ''' numberOfVertices = 8 points = vtk.vtkPoints() points.InsertNextPoint(0, 0, 0) points.InsertNextPoint(1, 0, 0) points.InsertNextPoint(0, 1, 0) points.InsertNextPoint(1, 1, 0) points.InsertNextPoint(0, 0, 1) points.InsertNextPoint(1, 0, 1) points.InsertNextPoint(0, 1, 1) points.InsertNextPoint(1, 1, 1) voxel = vtk.vtkVoxel() for i in range(0, numberOfVertices): voxel.GetPointIds().SetId(i, i) ug = vtk.vtkUnstructuredGrid() ug.SetPoints(points) ug.InsertNextCell(voxel.GetCellType(), voxel.GetPointIds()) return ug
def selectCell(self, cellId): if cellId in (None, -1): return ids = vtk.vtkIdTypeArray(); ids.SetNumberOfComponents(1); ids.InsertNextValue(cellId); selectionNode = vtk.vtkSelectionNode(); selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL); selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES); selectionNode.SetSelectionList(ids); selection = vtk.vtkSelection(); selection.AddNode(selectionNode); extractSelection = vtk.vtkExtractSelection(); extractSelection.SetInputData(0, self.actor.GetMapper().GetInput()); extractSelection.SetInputData(1, selection); extractSelection.Update(); selected = vtk.vtkUnstructuredGrid(); selected.ShallowCopy(extractSelection.GetOutput()); self.selectedMapper.SetInputData(selected); self.selectedMapper.Update()
def create_vessel_actor(ref_data): vessel_ref_data = ref_data points = vtk.vtkPoints() # insert each properties of points into obj. for i in range(vessel_ref_data.get_len_of_vassel_value()): x = vessel_ref_data.get_abscissa_value_at(i) y = vessel_ref_data.get_ordinate_value_at(i) z = vessel_ref_data.get_iso_value_at(i) points.InsertPoint(i, x, y, z) poly = vtk.vtkPolyVertex() poly.GetPointIds().SetNumberOfIds(vessel_ref_data.get_len_of_vassel_value()) cont = 0 while cont < vessel_ref_data.get_len_of_vassel_value(): poly.GetPointIds().SetId(cont, cont) cont += 1 grid = vtk.vtkUnstructuredGrid() grid.SetPoints(points) grid.InsertNextCell(poly.GetCellType(), poly.GetPointIds()) mapper = vtk.vtkDataSetMapper() if sys.hexversion == 34015984: mapper.SetInputData(grid) elif sys.hexversion == 34015728: mapper.SetInput(grid) actor = vtk.vtkActor() actor.SetMapper(mapper) return actor
def GetNormalLines(vtx, normals, scale): """ Returns polydata with lines to visualize normals. This can be used for either vertex or face normals; just specify the normals start points with "vtx". """ linePoints = vtk.vtkPoints() aLine = vtk.vtkLine() aLineGrid = vtk.vtkUnstructuredGrid() aLineGrid.Allocate(1, 1) aLineGrid.SetPoints(linePoints) for i in xrange(vtx.GetNumberOfTuples()): xyz0 = vtx.GetTuple3(i) nxyz = normals.GetTuple3(i) linePoints.InsertNextPoint(xyz0[0], xyz0[1], xyz0[2]) linePoints.InsertNextPoint(xyz0[0]+nxyz[0]*scale, xyz0[1]+nxyz[1]*scale, xyz0[2]+nxyz[2]*scale) aLine.GetPointIds().SetId(0, 2*i) aLine.GetPointIds().SetId(1, 2*i+1) aLineGrid.InsertNextCell(aLine.GetCellType(), aLine.GetPointIds()) return aLineGrid
def asVtkUnstructuredGrid(self): ''' Return object as a vtk.vtkUnstructuredMesh instance. .. note:: This method uses the compiled vtk module (which is a wrapper atop the c++ VTK library) -- in contrast to :obj:`UnstructuredMesh.getVTKRepresentation`, which uses the pyvtk module (python-only implementation of VTK i/o supporting only VTK File Format version 2). ''' import vtk # vertices pts=vtk.vtkPoints() for ip in range(self.getNumberOfVertices()): pts.InsertNextPoint(self.getVertex(ip).getCoordinates()) # cells cells,cellTypes=vtk.vtkCellArray(),[] for ic in range(self.getNumberOfCells()): c=self.getCell(ic) cgt=c.getGeometryType() cellGeomTypeMap={ CellGeometryType.CGT_TRIANGLE_1: (vtk.vtkTriangle,vtk.VTK_TRIANGLE), CellGeometryType.CGT_QUAD: (vtk.vtkQuad,vtk.VTK_QUAD), CellGeometryType.CGT_TETRA: (vtk.vtkTetra,vtk.VTK_TETRA), CellGeometryType.CGT_HEXAHEDRON: (vtk.vtkHexahedron,vtk.VTK_HEXAHEDRON), CellGeometryType.CGT_TRIANGLE_2: (vtk.vtkQuadraticTriangle,vtk.VTK_QUADRATIC_TRIANGLE) } c2klass,c2type=cellGeomTypeMap[cgt] # instantiate the VTK cell with the correct type c2=c2klass() verts=c.getVertices() # those should be all instances of Vertex...? Hopefully so. for i,v in enumerate(verts): c2.GetPointIds().SetId(i,v.getNumber()) cells.InsertNextCell(c2) cellTypes.append(c2type) ret=vtk.vtkUnstructuredGrid() ret.SetPoints(pts) ret.SetCells(cellTypes,cells) return ret
def convert_to_vtk(self, pvar_list): """ Convert particle data into vtk format and return the vtk objects. call signature: convert_to_vtk(self, pvar_list) Keyword arguments: *pvar_list*: List of particle objects. """ import numpy as np import vtk for pvar in pvar_list: points = np.vstack([pvar.xp, pvar.yp, pvar.zp]) vtk_grid_data = vtk.vtkUnstructuredGrid() vtk_points = vtk.vtkPoints() # Add the data to the vtk points. for point_idx in range(points.shape[1]): vtk_points.InsertNextPoint(points[:, point_idx]) # Add the vtk points to the vtk grid. vtk_grid_data.SetPoints(vtk_points) self.vtk_grid_data.append(vtk_grid_data)
def __init___(self, scene, V, opacity=1, color='gray'): self.scene = scene self.frame = scene.frame self.V = V n_voxels = len(V) size = V.bin_size pts = vtk.vtkPoints() pts.SetNumberOfPoints(8 * n_voxels) grid = vtk.vtkUnstructuredGrid() grid.Allocate(n_voxels, 1) vx = vtk.vtkVoxel() for i, q in enumerate(V): pos = q * size + V.low_range pts.InsertPoint(i * 8 + 0, *pos) pts.InsertPoint(i * 8 + 1, *(pos + (size,0,0))) pts.InsertPoint(i * 8 + 2, *(pos + (0,size,0))) pts.InsertPoint(i * 8 + 3, *(pos + (size,size,0))) pts.InsertPoint(i * 8 + 4, *(pos + (0,0,size))) pts.InsertPoint(i * 8 + 5, *(pos + (size,0,size))) pts.InsertPoint(i * 8 + 6, *(pos + (0,size,size))) pts.InsertPoint(i * 8 + 7, *(pos + (size,size,size))) for j in range(8): vx.GetPointIds().SetId(j, i * 8 + j) grid.InsertNextCell(vx.GetCellType(), vx.GetPointIds()) grid.SetPoints(pts) mapper = vtk.vtkDataSetMapper() mapper.SetInput(grid) self.actor = vtk.vtkActor() self.actor.SetMapper(mapper) #self.actor.GetProperty().SetDiffuseColor(*name_to_rgb_float(color)) self.actor.GetProperty().SetColor(*name_to_rgb_float(color)) self.actor.GetProperty().SetOpacity(opacity) self.frame.ren.AddActor(self.actor)
def Execute(self): gridData = vtk.vtkUnstructuredGrid() gridData = dsa.WrapDataObject(gridData) gridData.SetPoints(self.ArrayDict['Points']) if self.FlattenListOfCells: cellPointIds, cellLocations = self._ConvertListToFlatCellsArray(self.ArrayDict['Cells']['CellPointIds']) gridData.SetCells(self.ArrayDict['Cells']['CellTypes'], cellLocations, cellPointIds) else: gridData.SetCells(self.ArrayDict['Cells']['CellTypes'], self.ArrayDict['Cells']['CellLocations'], self.ArrayDict['Cells']['CellPointIds']) if 'PointData' in self.ArrayDict.keys(): for pointKey, pointData in self.ArrayDict['PointData'].items(): gridData.PointData.append(pointData, pointKey) if 'CellData' in self.ArrayDict.keys(): for cellKey, cellData in self.ArrayDict['CellData'].items(): gridData.CellData.append(cellData, cellKey) self.Mesh = gridData.VTKObject
[0, 4, 7, 3], [4, 5, 6, 7], [5, 1, 2, 6], [0, 1, 5, 4], [2, 3, 7, 6], ] faceId = vtk.vtkIdList() faceId.InsertNextId(6) # Number faces that make up the cell. for face in faceList: # Loop over all the faces faceId.InsertNextId(len(face)) # Number of points in face [faceId.InsertNextId(i) for i in face] # Insert the pointIds for the face ugrid = vtk.vtkUnstructuredGrid() ugrid.SetPoints(points) ugrid.InsertNextCell(vtk.VTK_POLYHEDRON, faceId) #------------------------------------- if 1: ug = ugrid grid_mapper = vtk.vtkDataSetMapper() vtk_version = int(VTK_VERSION[0]) grid_mapper.SetInputData(ug) #------------------------------------- #Create a mapper and actor #mapper = vtk.vtkPolyDataMapper() #mapper.SetInputConnection(text_source.GetOutputPort())
def point_deprecated(points,colors,opacity=1): ''' Create 3d points and generate only one actor for all points. Similar with dots but here you can color every point or class of points with a different color. ''' #return dots(points,color=(1,0,0),opacity=1) if np.array(colors).ndim==1: return dots(points,colors,opacity) points_=vtk.vtkCellArray() pointscalars=vtk.vtkFloatArray() #lookuptable=vtk.vtkLookupTable() lookuptable=_lookup(colors) scalarmin=0 if colors.ndim==2: scalarmax=colors.shape[0]-1 if colors.ndim==1: scalarmax=0 if points.ndim==2: points_no=points.shape[0] else: points_no=1 polyVertexPoints = vtk.vtkPoints() polyVertexPoints.SetNumberOfPoints(points_no) aPolyVertex = vtk.vtkPolyVertex() aPolyVertex.GetPointIds().SetNumberOfIds(points_no) cnt=0 if points.ndim>1: for point in points: pointscalars.SetNumberOfComponents(1) polyVertexPoints.InsertPoint(cnt, point[0], point[1], point[2]) pointscalars.InsertNextTuple1(cnt) aPolyVertex.GetPointIds().SetId(cnt, cnt) cnt+=1 else: polyVertexPoints.InsertPoint(cnt, points[0], points[1], points[2]) aPolyVertex.GetPointIds().SetId(cnt, cnt) cnt+=1 aPolyVertexGrid = vtk.vtkUnstructuredGrid() aPolyVertexGrid.Allocate(1, 1) aPolyVertexGrid.InsertNextCell(aPolyVertex.GetCellType(), aPolyVertex.GetPointIds()) aPolyVertexGrid.SetPoints(polyVertexPoints) aPolyVertexGrid.GetPointData().SetScalars(pointscalars) aPolyVertexMapper = vtk.vtkDataSetMapper() aPolyVertexMapper.SetInput(aPolyVertexGrid) aPolyVertexMapper.SetLookupTable(lookuptable) aPolyVertexMapper.SetColorModeToMapScalars() aPolyVertexMapper.SetScalarRange(scalarmin,scalarmax) aPolyVertexMapper.SetScalarModeToUsePointData() aPolyVertexActor = vtk.vtkActor() aPolyVertexActor.SetMapper(aPolyVertexMapper) #aPolyVertexActor.GetProperty().SetColor(color) aPolyVertexActor.GetProperty().SetOpacity(opacity) return aPolyVertexActor
def __init__( self, inputobj=None, ): vtk.vtkActor.__init__(self) BaseGrid.__init__(self) inputtype = str(type(inputobj)) self._data = None self._polydata = None ################### if inputobj is None: self._data = vtk.vtkUnstructuredGrid() # elif utils.isSequence(inputobj):pass # TODO elif "UnstructuredGrid" in inputtype: self._data = inputobj elif isinstance(inputobj, str): from vedo.io import download, loadUnStructuredGrid if "https://" in inputobj: inputobj = download(inputobj) self._data = loadUnStructuredGrid(inputobj) else: colors.printc("UGrid(): cannot understand input type:\n", inputtype, c=1) return self._mapper = vtk.vtkPolyDataMapper() self._mapper.SetInterpolateScalarsBeforeMapping( settings.interpolateScalarsBeforeMapping) if settings.usePolygonOffset: self._mapper.SetResolveCoincidentTopologyToPolygonOffset() pof, pou = settings.polygonOffsetFactor, settings.polygonOffsetUnits self._mapper.SetResolveCoincidentTopologyPolygonOffsetParameters( pof, pou) self.GetProperty().SetInterpolationToFlat() if not self._data: return sf = vtk.vtkShrinkFilter() sf.SetInputData(self._data) sf.SetShrinkFactor(1.0) sf.Update() gf = vtk.vtkGeometryFilter() gf.SetInputData(sf.GetOutput()) gf.Update() self._polydata = gf.GetOutput() self._mapper.SetInputData(self._polydata) sc = None if self.useCells: sc = self._polydata.GetCellData().GetScalars() else: sc = self._polydata.GetPointData().GetScalars() if sc: self._mapper.SetScalarRange(sc.GetRange()) self.SetMapper(self._mapper)
def vtk(case, mu, lhs, name='solution', index=None, ndigits=4): mesh = case.triangulation(mu, lines=False) points = vtklib.vtkPoints() points.SetData( vtknp.numpy_to_vtk(np.vstack([mesh.x, mesh.y, np.zeros(mesh.x.shape)]).T, deep=True)) celldata = np.hstack( [3 * np.ones((mesh.triangles.shape[0], 1), dtype=int), mesh.triangles]) cells = vtklib.vtkCellArray() cells.SetCells(mesh.triangles.shape[0], vtknp.numpy_to_vtkIdTypeArray(celldata.ravel(), deep=True)) grid = vtklib.vtkUnstructuredGrid() grid.SetPoints(points) grid.SetCells(vtklib.VTK_TRIANGLE, cells) fields = {} for field in case.bases: try: sol = case.solution(lhs, field, mu, lift=True) except KeyError: continue data = vtknp.numpy_to_vtk(sol, deep=True) data.SetName(field) grid.GetPointData().AddArray(data) filename = name
def _generate_vtk_mesh(points, cells): import vtk from vtk.util import numpy_support mesh = vtk.vtkUnstructuredGrid() # set points vtk_points = vtk.vtkPoints() # Not using a deep copy here results in a segfault. vtk_array = numpy_support.numpy_to_vtk(points, deep=True) vtk_points.SetData(vtk_array) mesh.SetPoints(vtk_points) # Set cells. meshio_to_vtk_type = { 'vertex': vtk.VTK_VERTEX, 'line': vtk.VTK_LINE, 'triangle': vtk.VTK_TRIANGLE, 'quad': vtk.VTK_QUAD, 'tetra': vtk.VTK_TETRA, 'hexahedron': vtk.VTK_HEXAHEDRON, 'wedge': vtk.VTK_WEDGE, 'pyramid': vtk.VTK_PYRAMID } # create cell_array. It's a one-dimensional vector with # (num_points2, p0, p1, ... ,pk, numpoints1, p10, p11, ..., p1k, ... cell_types = [] cell_offsets = [] cell_connectivity = [] len_array = 0 for meshio_type, data in cells.iteritems(): numcells, num_local_nodes = data.shape vtk_type = meshio_to_vtk_type[meshio_type] # add cell types cell_types.append(numpy.empty(numcells, dtype=numpy.ubyte)) cell_types[-1].fill(vtk_type) # add cell offsets cell_offsets.append( numpy.arange(len_array, len_array + numcells * (num_local_nodes + 1), num_local_nodes + 1, dtype=numpy.int64)) cell_connectivity.append( numpy.c_[num_local_nodes * numpy.ones(numcells, dtype=data.dtype), data].flatten()) len_array += len(cell_connectivity[-1]) cell_types = numpy.concatenate(cell_types) cell_offsets = numpy.concatenate(cell_offsets) cell_connectivity = numpy.concatenate(cell_connectivity) connectivity = vtk.util.numpy_support.numpy_to_vtkIdTypeArray( cell_connectivity.astype(numpy.int64), deep=1) # wrap the data into a vtkCellArray cell_array = vtk.vtkCellArray() cell_array.SetCells(len(cell_types), connectivity) # Add cell data to the mesh mesh.SetCells( numpy_support.numpy_to_vtk( cell_types, deep=1, array_type=vtk.vtkUnsignedCharArray().GetDataType()), numpy_support.numpy_to_vtk( cell_offsets, deep=1, array_type=vtk.vtkIdTypeArray().GetDataType()), cell_array) return mesh
def main(): pointSource = vtk.vtkPointSource() pointSource.SetNumberOfPoints(50) pointSource.Update() print("There are %s input points\n" % pointSource.GetOutput().GetNumberOfPoints()) ids = vtk.vtkIdTypeArray() ids.SetNumberOfComponents(1) # Set values i = 10 while i < 20: ids.InsertNextValue(i) i += 1 selectionNode = vtk.vtkSelectionNode() selectionNode.SetFieldType(1) # POINT # CELL_DATA = 0 # POINT_DATA = 1 # FIELD_DATA = 2 # VERTEX_DATA = 3 # EDGE_DATA = 4 selectionNode.SetContentType(4) # INDICES # SELECTIONS = 0 # GLOBALIDS = 1 # PEDIGREEIDS = 2 # VALUES = 3 # INDICES = 4 # FRUSTUM = 5 # LOCATIONS = 6 # THRESHOLDS = 7 # BLOCKS = 8 selectionNode.SetSelectionList(ids) selection = vtk.vtkSelection() selection.AddNode(selectionNode) extractSelection = vtk.vtkExtractSelection() extractSelection.SetInputConnection(0, pointSource.GetOutputPort()) if vtk.VTK_MAJOR_VERSION <= 5: extractSelection.SetInput(1, selection) else: extractSelection.SetInputData(1, selection) extractSelection.Update() # In selection selected = vtk.vtkUnstructuredGrid() selected.ShallowCopy(extractSelection.GetOutput()) print("There are %s points in the selection" % selected.GetNumberOfPoints()) print("There are %s cells in the selection" % selected.GetNumberOfCells()) # Get points that are NOT in the selection # invert the selection selectionNode.GetProperties().Set(vtk.vtkSelectionNode.INVERSE(), 1) extractSelection.Update() notSelected = vtk.vtkUnstructuredGrid() notSelected.ShallowCopy(extractSelection.GetOutput()) print("There are %s points NOT in the selection" % notSelected.GetNumberOfPoints()) print("There are %s cells NOT in the selection" % notSelected.GetNumberOfCells()) inputMapper = vtk.vtkDataSetMapper() inputMapper.SetInputConnection(pointSource.GetOutputPort()) inputActor = vtk.vtkActor() inputActor.SetMapper(inputMapper) selectedMapper = vtk.vtkDataSetMapper() if vtk.VTK_MAJOR_VERSION <= 5: selectedMapper.SetInputConnection(selected.GetProducerPort()) else: selectedMapper.SetInputData(selected) selectedActor = vtk.vtkActor() selectedActor.SetMapper(selectedMapper) notSelectedMapper = vtk.vtkDataSetMapper() if vtk.VTK_MAJOR_VERSION <= 5: notSelectedMapper.SetInputConnection(notSelected.GetProducerPort()) else: notSelectedMapper.SetInputData(notSelected) notSelectedActor = vtk.vtkActor() notSelectedActor.SetMapper(notSelectedMapper) # There will be one render window renderWindow = vtk.vtkRenderWindow() renderWindow.SetSize(900, 300) # And one interactor interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renderWindow) # Define viewport ranges # (xmin, ymin, xmax, ymax) leftViewport = [0.0, 0.0, 0.33, 1.0] centerViewport = [0.33, 0.0, .66, 1.0] rightViewport = [0.66, 0.0, 1.0, 1.0] # Setup the renderers leftRenderer = vtk.vtkRenderer() renderWindow.AddRenderer(leftRenderer) leftRenderer.SetViewport(leftViewport) leftRenderer.SetBackground(.6, .5, .4) centerRenderer = vtk.vtkRenderer() renderWindow.AddRenderer(centerRenderer) centerRenderer.SetViewport(centerViewport) centerRenderer.SetBackground(.3, .1, .4) rightRenderer = vtk.vtkRenderer() renderWindow.AddRenderer(rightRenderer) rightRenderer.SetViewport(rightViewport) rightRenderer.SetBackground(.4, .5, .6) leftRenderer.AddActor(inputActor) centerRenderer.AddActor(selectedActor) rightRenderer.AddActor(notSelectedActor) leftRenderer.ResetCamera() centerRenderer.ResetCamera() rightRenderer.ResetCamera() renderWindow.Render() interactor.Start()
def post_proc_cfd(dir_path, vtu_input, cell_type="point", vtu_output_1="calc_test_node.vtu", vtu_output_2="calc_test_node_stats.vtu", N_peak=3): reader = vtk.vtkXMLUnstructuredGridReader() reader.SetFileName(os.path.join(dir_path, vtu_input)) reader.Update() N = reader.GetNumberOfTimeSteps() print(N) #N = test.GetNumberOfBlocks()ls #block = test.GetBlock(0) #for i in range(N): # print(i, test.GetMetaData(i).Get(vtk.vtkCompositeDataSet.NAME())) #grid = reader.GetOutput() #wallshear = grid.GetCellData().GetArray("x_wall_shear") #print(wallshear) calc1 = vtk.vtkArrayCalculator() calc1.SetFunction("sqrt(x_wall_shear^2+y_wall_shear^2+z_wall_shear^2)") calc1.AddScalarVariable("x_wall_shear", "x_wall_shear",0) calc1.AddScalarVariable("y_wall_shear", "y_wall_shear",0) calc1.AddScalarVariable("z_wall_shear", "z_wall_shear",0) calc1.SetResultArrayName("WSS") calc1.SetInputConnection(reader.GetOutputPort()) if(cell_type == "cell"): calc1.SetAttributeModeToUseCellData() vtk_process = vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS vtk_data_type = vtk.vtkDataObject.CELL else: calc1.SetAttributeModeToUsePointData() vtk_process = vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS vtk_data_type = vtk.vtkDataObject.POINT calc1.SetResultArrayType(vtk.VTK_DOUBLE) x_WSS_grad = vtk.vtkGradientFilter() x_WSS_grad.SetInputConnection(calc1.GetOutputPort()) x_WSS_grad.ComputeGradientOn() x_WSS_grad.FasterApproximationOff() x_WSS_grad.SetResultArrayName("x_WSS_grad") x_WSS_grad.SetInputArrayToProcess(0, 0, 0, vtk_process, "x_wall_shear") y_WSS_grad = vtk.vtkGradientFilter() y_WSS_grad.SetInputConnection(x_WSS_grad.GetOutputPort()) y_WSS_grad.ComputeGradientOn() y_WSS_grad.FasterApproximationOff() y_WSS_grad.SetResultArrayName("y_WSS_grad") x_WSS_grad.SetInputArrayToProcess(0, 0, 0, vtk_process, "y_wall_shear") z_WSS_grad = vtk.vtkGradientFilter() z_WSS_grad.SetInputConnection(y_WSS_grad.GetOutputPort()) z_WSS_grad.ComputeGradientOn() z_WSS_grad.FasterApproximationOff() z_WSS_grad.SetResultArrayName("z_WSS_grad") z_WSS_grad.SetInputArrayToProcess(0, 0, 0, vtk_process, "z_wall_shear") calc2 = vtk.vtkArrayCalculator() calc2.AddScalarVariable("x_component", "x_WSS_grad",0) calc2.AddScalarVariable("y_component", "y_WSS_grad",1) calc2.AddScalarVariable("z_component", "z_WSS_grad",2) calc2.SetFunction("sqrt(x_component^2+y_component^2+z_component^2)") calc2.SetResultArrayName("WSSG") calc2.SetInputConnection(z_WSS_grad.GetOutputPort()) if(cell_type == "cell"): calc2.SetAttributeModeToUseCellData() else: calc2.SetAttributeModeToUsePointData() calc2.SetResultArrayType(vtk.VTK_DOUBLE) # initialize the output to include the peak values grid = vtk.vtkUnstructuredGrid() #N_peak = 3 reader.SetTimeStep(N_peak) print("loading {0}th timestep to copy data".format(N_peak)) calc2.Update() grid.DeepCopy(calc2.GetOutput()) #grid.SetNumberOfTimeSteps(1) #grid.SetTimeStep(0) #grid.Update() #sqrt((ddx({Wall shear-1}))**2 + (ddy({Wall shear-2}))**2 + (ddz({Wall shear-3}))**2)' def init_zero(in_array, sz_array): for i in range(sz_array): in_array.SetValue(i,0.0) def array_sum(out_array, in_array, sz_array): for i in range(sz_array): out_array.SetValue(i, out_array.GetValue(i) + in_array.GetValue(i)) def array_division(out_array, in_array, sz_array): for i in range(sz_array): out_array.SetValue(i, out_array.GetValue(i) / in_array.GetValue(i)) def array_avg(out_array, N): float_N = float(N) for i in range(N): out_array.SetValue(i, out_array.GetValue(i) / float_N) reader.SetTimeStep(0) print("loading {0}th timestep for averaging initialization".format(0)) reader.Update() calc2.Update() if(cell_type == "cell"): calc_data = calc2.GetOutput().GetCellData() grid_data = grid.GetCellData() n_sz = grid.GetNumberOfCells() else: calc_data = calc2.GetOutput().GetPointData() grid_data = grid.GetPointData() n_sz = grid.GetNumberOfPoints() TAWSS = vtk.vtkDoubleArray() TAWSS.DeepCopy(calc_data.GetArray("WSS")) TAWSS.SetName("TAWSS") TAWSSG = vtk.vtkDoubleArray() TAWSSG.DeepCopy(calc_data.GetArray("WSSG")) TAWSSG.SetName("TAWSSG") x_shear_avg = vtk.vtkDoubleArray() x_shear_avg.DeepCopy(calc_data.GetArray("x_wall_shear")) x_shear_avg.SetName("x_shear_avg") y_shear_avg = vtk.vtkDoubleArray() y_shear_avg.DeepCopy(calc_data.GetArray("y_wall_shear")) y_shear_avg.SetName("y_shear_avg") z_shear_avg = vtk.vtkDoubleArray() z_shear_avg.DeepCopy(calc_data.GetArray("z_wall_shear")) z_shear_avg.SetName("z_shear_avg") #TAWSSVector = vtk.vtkDoubleArray() #TAWSSVector.DeepCopy(calc_data.GetArray("z_wall_shear")) #TAWSSVector.SetName("TAWSSVector") #grid_data.AddArray(TAWSSVector) # def get_array_names(input): # N_point_array = input.GetOutput().GetPointData().GetNumberOfArrays() # N_WSS = 9999999 # for i in range(N_point_array): # name_WSS = input.GetOutput().GetPointData().GetArrayName(i) # if (name_WSS == "WSS"): # N_WSS = i # print(name_WSS) # # def array_sum(output, input_calc, N): # for i in range(N): # calc = output.GetValue(i) + input_calc.GetValue(i) # output.SetValue(i, calc) writer = vtk.vtkXMLUnstructuredGridWriter() #writer.SetFileName(os.path.join(out_dir,'test_outfile.vtu')) writer.SetFileName(os.path.join(dir_path, vtu_output_1)) writer.SetNumberOfTimeSteps(N) #writer.SetTimeStepRange(0,len(filelist)-1) writer.SetInputConnection(calc2.GetOutputPort()) writer.Start() #avg_map = {"TAWSS":"WSS", "TAWSSG": "WSSG", "x_shear_avg":"x_wall_shear", # "y_shear_avg":"y_wall_shear" , "z_shear_avg":"z_wall_shear"} for i in range(1,N): reader.SetTimeStep(i) print("Time step {0} for average calc".format(i)) reader.Update() calc2.Update() if(cell_type == "cell"): calc_data = calc2.GetOutput().GetCellData() else: calc_data = calc2.GetOutput().GetPointData() #get_array_names(calc2) array_sum(TAWSS, calc_data.GetArray("WSS"), n_sz) array_sum(TAWSSG, calc_data.GetArray("WSSG"), n_sz) array_sum(x_shear_avg, calc_data.GetArray("x_wall_shear"), n_sz) array_sum(y_shear_avg, calc_data.GetArray("y_wall_shear"), n_sz) array_sum(z_shear_avg, calc_data.GetArray("z_wall_shear"), n_sz) writer.WriteNextTime(reader.GetTimeStep()) writer.Stop() array_avg(TAWSS, N) array_avg(TAWSSG, N) array_avg(x_shear_avg, N) array_avg(y_shear_avg, N) array_avg(z_shear_avg, N) WSS_peak2mean = vtk.vtkDoubleArray() WSS_peak2mean.DeepCopy(grid_data.GetArray("WSS")) WSS_peak2mean.SetName("WSS_peak2mean") array_division(WSS_peak2mean, TAWSS, n_sz) WSSG_peak2mean = vtk.vtkDoubleArray() WSSG_peak2mean.DeepCopy(grid_data.GetArray("WSSG")) WSSG_peak2mean.SetName("WSSG_peak2mean") array_division(WSSG_peak2mean, TAWSSG, n_sz) grid_data.AddArray(TAWSS) grid_data.AddArray(TAWSSG) grid_data.AddArray(x_shear_avg) grid_data.AddArray(y_shear_avg) grid_data.AddArray(z_shear_avg) grid_data.AddArray(WSS_peak2mean) grid_data.AddArray(WSSG_peak2mean) print("got here") calc3 = vtk.vtkArrayCalculator() calc3.AddScalarVariable("x_shear_avg", "x_shear_avg",0) calc3.AddScalarVariable("y_shear_avg", "y_shear_avg",0) calc3.AddScalarVariable("z_shear_avg", "z_shear_avg",0) calc3.SetFunction("sqrt(x_shear_avg^2+y_shear_avg^2+z_shear_avg^2)") calc3.SetResultArrayName("TAWSSVector") calc3.SetInputData(grid) if(cell_type == "cell"): calc3.SetAttributeModeToUseCellData() else: calc3.SetAttributeModeToUsePointData() calc3.SetResultArrayType(vtk.VTK_DOUBLE) calc3.Update() calc4 = vtk.vtkArrayCalculator() calc4.AddScalarVariable("TAWSSVector", "TAWSSVector",0) calc4.AddScalarVariable("TAWSS", "TAWSS",0) calc4.SetFunction("0.5*(1.0-(TAWSSVector/(TAWSS)))") calc4.SetResultArrayName("OSI") calc4.SetInputConnection(calc3.GetOutputPort()) if(cell_type == "cell"): calc4.SetAttributeModeToUseCellData() else: calc4.SetAttributeModeToUsePointData() calc4.SetResultArrayType(vtk.VTK_DOUBLE) calc4.Update() pass_filt = vtk.vtkPassArrays() pass_filt.SetInputConnection(calc4.GetOutputPort()) pass_filt.AddArray(vtk_data_type, "WSS") pass_filt.AddArray(vtk_data_type, "WSSG") pass_filt.AddArray(vtk_data_type, "absolute_pressure") pass_filt.AddArray(vtk_data_type, "TAWSS") pass_filt.AddArray(vtk_data_type, "TAWSSG") pass_filt.AddArray(vtk_data_type, "OSI") pass_filt.AddArray(vtk_data_type, "WSS_peak2mean") pass_filt.AddArray(vtk_data_type, "WSSG_peak2mean") pass_filt.Update() #if(cell_type == "cell"): # print(pass_filt.GetOutput().GetCellData().GetArray("OSI").GetValue(0)) #else: # print(pass_filt.GetOutput().GetPointData().GetArray("OSI").GetValue(0)) writer2 = vtk.vtkXMLUnstructuredGridWriter() writer2.SetFileName(os.path.join(dir_path, vtu_output_2)) writer2.SetInputConnection(pass_filt.GetOutputPort()) writer2.Update()
import sys if len(sys.argv) != 4: print('requires 3 arguments: .mesh file, .param file, output vtu file') exit(-1) #open topology file with open(sys.argv[1]) as f: mesh = json.load(f) #open parameter file with open(sys.argv[2]) as f: param = json.load(f) #init the vtk datastructure vtu = vtk.vtkUnstructuredGrid() vtuwriter = vtk.vtkXMLUnstructuredGridWriter() vtuwriter.SetFileName(sys.argv[3]) vtuwriter.SetInputData(vtu) vtu_points = vtk.vtkPoints() vtu_triangles = vtk.vtkCellArray() vtu_points.SetNumberOfPoints(len(mesh['mesh']['vertex'])) # elevation isn't stored in the param or mesh file, so compute from the z like mesher does vtu_cells = {'Elevation': vtk.vtkFloatArray()} vtu_cells['Elevation'].SetName('elevation') # loop over the mesh elements and reconstruct the triangle for e in mesh['mesh']['elem']:
def __init__(self, inputobj=None, c=('r','y','lg','lb','b'), #('b','lb','lg','y','r') alpha=(0.5, 1), alphaUnit=1, mapper='tetra', ): BaseGrid.__init__(self) self.useArray = 0 inputtype = str(type(inputobj)) #printc('TetMesh inputtype', inputtype) ################### if inputobj is None: self._data = vtk.vtkUnstructuredGrid() elif isinstance(inputobj, vtk.vtkUnstructuredGrid): self._data = inputobj elif isinstance(inputobj, vtk.vtkRectilinearGrid): r2t = vtk.vtkRectilinearGridToTetrahedra() r2t.SetInputData(inputobj) r2t.RememberVoxelIdOn() r2t.SetTetraPerCellTo6() r2t.Update() self._data = r2t.GetOutput() elif isinstance(inputobj, vtk.vtkDataSet): r2t = vtk.vtkDataSetTriangleFilter() r2t.SetInputData(inputobj) #r2t.TetrahedraOnlyOn() r2t.Update() self._data = r2t.GetOutput() elif isinstance(inputobj, str): from vedo.io import download, loadUnStructuredGrid if "https://" in inputobj: inputobj = download(inputobj, verbose=False) ug = loadUnStructuredGrid(inputobj) tt = vtk.vtkDataSetTriangleFilter() tt.SetInputData(ug) tt.SetTetrahedraOnly(True) tt.Update() self._data = tt.GetOutput() elif utils.isSequence(inputobj): # if "ndarray" not in inputtype: # inputobj = np.array(inputobj) self._data = self._buildtetugrid(inputobj[0], inputobj[1]) ################### if 'tetra' in mapper: self._mapper = vtk.vtkProjectedTetrahedraMapper() elif 'ray' in mapper: self._mapper = vtk.vtkUnstructuredGridVolumeRayCastMapper() elif 'zs' in mapper: self._mapper = vtk.vtkUnstructuredGridVolumeZSweepMapper() elif isinstance(mapper, vtk.vtkMapper): self._mapper = mapper else: printc('Unknown mapper type', [mapper], c='r') raise RuntimeError() self._mapper.SetInputData(self._data) self.SetMapper(self._mapper) self.color(c).alpha(alpha) if alphaUnit: self.GetProperty().SetScalarOpacityUnitDistance(alphaUnit) # remember stuff: self._color = c self._alpha = alpha self._alphaUnit = alphaUnit
#!/usr/bin/env python from pyadh import * comm = Comm.init() cmeshTools.commInit() import vtk vtkMesh = vtk.vtkUnstructuredGrid() reader = vtk.vtkXMLUnstructuredGridReader() reader.SetFileName('mymesh.vtu') reader.SetOutput(vtkMesh) reader.Update() mesh = MeshTools.Mesh() mesh.cmesh = cmeshTools.CMesh() from pyadh import cvtkviewers as cvtkviewers cvtkviewers.getMeshFromVTKUnstructuredGrid(vtkMesh, mesh.cmesh) if mesh.nNodes_element == 2: cmeshTools.computeGeometricInfo_edge(mesh.cmesh) elif mesh.nNodes_element == 3: cmeshTools.computeGeometricInfo_triangle(mesh.cmesh) else: cmeshTools.computeGeometricInfo_tetrahedron(mesh.cmesh) mesh.buildFromC(mesh.cmesh) from pyadh import vtkViewers as vtkViewers vtkViewers.viewMesh(mesh) cmeshTools.commDestroy()
def read_data_and_differentiate(pod_mode_dir,num_modes,num_points,num_boundary_faces,num_dimensions,num_components,correct_for_cell_volumes, \ u,v,w,dudx,dudy,dudz,dvdx,dvdy,dvdz,dwdx,dwdy,dwdz,\ uF,vF,wF,dudxF,dudyF,dudzF,dvdxF,dvdyF,dvdzF,dwdxF,dwdyF,dwdzF,cell_volume,norm,calibrate_coefficients): u_read = np.array(np.zeros((num_points, 3), dtype=np.float64)) dudx_read = np.array(np.zeros((num_points, 3, 3), dtype=np.float64)) uF_read = np.array(np.zeros((num_boundary_faces, 3), dtype=np.float64)) dudxF_read = np.array( np.zeros((num_boundary_faces, 3, 3), dtype=np.float64)) # .................................................. # Read meanfield and spatially differentiate filename = pod_mode_dir + "/spatial_meanfield.vtk" print ' Reading file ', filename.strip() reader = vtk.vtkUnstructuredGridReader() reader.ReadAllScalarsOn() reader.ReadAllVectorsOn() reader.ReadAllTensorsOn() reader.SetFileName(filename) reader.Update() grid = vtk.vtkUnstructuredGrid() grid.DeepCopy(reader.GetOutput()) # get cell volumes if (correct_for_cell_volumes == "true"): cell_volume[:] = VN.vtk_to_numpy( grid.GetPointData().GetScalars("cell_volume")) else: cell_volume[:] = 1.0 # get mean velocity field within volume u_read = VN.vtk_to_numpy(grid.GetPointData().GetVectors("u")) u[:, 0] = u_read[:, 0].copy() v[:, 0] = u_read[:, 1].copy() w[:, 0] = u_read[:, 2].copy() grid.GetPointData().SetVectors(grid.GetPointData().GetVectors("u")) # get mean velocity derivative field within volume differentiator = vtk.vtkCellDerivatives() differentiator.SetTensorModeToComputeGradient() differentiator.SetInput(grid) differentiator.Update() cell_to_point_data = vtk.vtkCellDataToPointData() cell_to_point_data.SetInput(differentiator.GetOutput()) cell_to_point_data.Update() grid.GetPointData().SetTensors( cell_to_point_data.GetOutput().GetPointData().GetTensors()) dudx_read = VN.vtk_to_numpy( cell_to_point_data.GetOutput().GetPointData().GetTensors()) dudx[:, 0] = dudx_read[:, 0].copy() dvdx[:, 0] = dudx_read[:, 1].copy() dwdx[:, 0] = dudx_read[:, 2].copy() dudy[:, 0] = dudx_read[:, 3].copy() dvdy[:, 0] = dudx_read[:, 4].copy() dwdy[:, 0] = dudx_read[:, 5].copy() dudz[:, 0] = dudx_read[:, 6].copy() dvdz[:, 0] = dudx_read[:, 7].copy() dwdz[:, 0] = dudx_read[:, 8].copy() # extract boundary surface data if ((calibrate_coefficients == "none") or (calibrate_coefficients == "constant")): geom_filter = vtk.vtkDataSetSurfaceFilter() geom_filter.SetInput(grid) geom_filter.Update() boundary_faces = vtk.vtkPolyData() boundary_faces = geom_filter.GetOutput() point_to_cell_data = vtk.vtkPointDataToCellData() point_to_cell_data.SetInput(geom_filter.GetOutput()) point_to_cell_data.Update() # get mean velocity field on boundary surface uF_read = VN.vtk_to_numpy( point_to_cell_data.GetOutput().GetCellData().GetVectors("u")) uF[:, 0] = uF_read[:, 0] vF[:, 0] = uF_read[:, 1] wF[:, 0] = uF_read[:, 2] # get mean derivative velocity field on boundary surface dudxF_read = VN.vtk_to_numpy( point_to_cell_data.GetOutput().GetCellData().GetTensors()) dudxF[:, 0] = dudxF_read[:, 0] dvdxF[:, 0] = dudxF_read[:, 1] dwdxF[:, 0] = dudxF_read[:, 2] dudyF[:, 0] = dudxF_read[:, 3] dvdyF[:, 0] = dudxF_read[:, 4] dwdyF[:, 0] = dudxF_read[:, 5] dudzF[:, 0] = dudxF_read[:, 6] dvdzF[:, 0] = dudxF_read[:, 7] dwdzF[:, 0] = dudxF_read[:, 8] # get boundary face normals norm_filter = vtk.vtkPolyDataNormals() norm_filter.ComputeCellNormalsOn() norm_filter.SetInput(boundary_faces) norm_filter.Update() area_filter = vtk.vtkMeshQuality() area_filter.SetQuadQualityMeasureToArea() area_filter.SetTriangleQualityMeasureToArea() area_filter.SetInput(boundary_faces) area_filter.Update() for j in range(0, num_boundary_faces): area = area_filter.GetOutput().GetCellData().GetArray( "Quality").GetComponent(j, 0) norm[j, :] = norm_filter.GetOutput().GetCellData().GetNormals( ).GetTuple(j) norm[j, :] = norm[j, :] * area # .................................................. # Read modes and spatially differentiate for j in range(0, num_modes): j_index = j + 1 filename = pod_mode_dir + '/POD.spatial_mode_' + '%04d' % j_index + '.vtk' print ' Reading file ', filename.strip( ), 'file number ', j_index, ' of ', num_modes reader.SetFileName(filename) reader.Update() # get mode velocity field within volume u_read = VN.vtk_to_numpy( reader.GetOutput().GetPointData().GetVectors("u")) u[:, j_index] = u_read[:, 0] v[:, j_index] = u_read[:, 1] w[:, j_index] = u_read[:, 2] # get mode velocity derivative fields within volume grid.GetPointData().SetVectors( reader.GetOutput().GetPointData().GetVectors("u")) differentiator.SetInput(grid) differentiator.Update() cell_to_point_data.SetInput(differentiator.GetOutput()) cell_to_point_data.Update() grid.GetPointData().SetTensors( cell_to_point_data.GetOutput().GetPointData().GetTensors()) dudx_read = VN.vtk_to_numpy( cell_to_point_data.GetOutput().GetPointData().GetTensors()) dudx[:, j_index] = dudx_read[:, 0] dvdx[:, j_index] = dudx_read[:, 1] dwdx[:, j_index] = dudx_read[:, 2] dudy[:, j_index] = dudx_read[:, 3] dvdy[:, j_index] = dudx_read[:, 4] dwdy[:, j_index] = dudx_read[:, 5] dudz[:, j_index] = dudx_read[:, 6] dvdz[:, j_index] = dudx_read[:, 7] dwdz[:, j_index] = dudx_read[:, 8] # extract boundary surface data if ((calibrate_coefficients == "none") or (calibrate_coefficients == "constant")): geom_filter.SetInput(grid) geom_filter.Update() boundary_faces = geom_filter.GetOutput() point_to_cell_data.SetInput(geom_filter.GetOutput()) point_to_cell_data.Update() # get mode velocity field on boundary surface uF_read = VN.vtk_to_numpy( point_to_cell_data.GetOutput().GetCellData().GetVectors("u")) uF[:, j_index] = uF_read[:, 0] vF[:, j_index] = uF_read[:, 1] wF[:, j_index] = uF_read[:, 2] # get mean derivative velocity field on boundary surface dudxF_read = VN.vtk_to_numpy( point_to_cell_data.GetOutput().GetCellData().GetTensors()) dudxF[:, j_index] = dudxF_read[:, 0] dvdxF[:, j_index] = dudxF_read[:, 1] dwdxF[:, j_index] = dudxF_read[:, 2] dudyF[:, j_index] = dudxF_read[:, 3] dvdyF[:, j_index] = dudxF_read[:, 4] dwdyF[:, j_index] = dudxF_read[:, 5] dudzF[:, j_index] = dudxF_read[:, 6] dvdzF[:, j_index] = dudxF_read[:, 7] dwdzF[:, j_index] = dudxF_read[:, 8] # .................................................. # zero appropriate coefficients if (num_dimensions < 3): dudz[:, :] = 0.0 dvdz[:, :] = 0.0 dwdz[:, :] = 0.0 if (num_dimensions < 2): dudy[:, :] = 0.0 dvdy[:, :] = 0.0 dwdy[:, :] = 0.0 if (num_components < 3): w[:, :] = 0.0 dwdx[:, :] = 0.0 dwdy[:, :] = 0.0 dwdz[:, :] = 0.0 if (num_components < 2): v[:, :] = 0.0 dvdx[:, :] = 0.0 dvdy[:, :] = 0.0 dvdz[:, :] = 0.0 if ((calibrate_coefficients == "none") or (calibrate_coefficients == "constant")): if (num_dimensions < 3): dudzF[:, :] = 0.0 dvdzF[:, :] = 0.0 dwdzF[:, :] = 0.0 if (num_dimensions < 2): dudyF[:, :] = 0.0 dvdyF[:, :] = 0.0 dwdyF[:, :] = 0.0 if (num_components < 3): wF[:, j_index] = 0.0 dwdxF[:, :] = 0.0 dwdyF[:, :] = 0.0 dwdzF[:, :] = 0.0 if (num_components < 2): vF[:, :] = 0.0 dvdxF[:, :] = 0.0 dvdyF[:, :] = 0.0 dvdzF[:, :] = 0.0
# QuadraticEdge edgePoints = vtk.vtkPoints() edgePoints.SetNumberOfPoints(3) edgePoints.InsertPoint(0, 0, 0, 0) edgePoints.InsertPoint(1, 1.0, 0, 0) edgePoints.InsertPoint(2, 0.5, 0.25, 0) edgeScalars = vtk.vtkFloatArray() edgeScalars.SetNumberOfTuples(3) edgeScalars.InsertValue(0, 0.0) edgeScalars.InsertValue(1, 0.0) edgeScalars.InsertValue(2, 0.9) aEdge = vtk.vtkQuadraticEdge() aEdge.GetPointIds().SetId(0, 0) aEdge.GetPointIds().SetId(1, 1) aEdge.GetPointIds().SetId(2, 2) aEdgeGrid = vtk.vtkUnstructuredGrid() aEdgeGrid.Allocate(1, 1) aEdgeGrid.InsertNextCell(aEdge.GetCellType(), aEdge.GetPointIds()) aEdgeGrid.SetPoints(edgePoints) aEdgeGrid.GetPointData().SetScalars(edgeScalars) edgeContours = vtk.vtkContourFilter() edgeContours.SetInputData(aEdgeGrid) edgeContours.SetValue(0, 0.5) aEdgeContourMapper = vtk.vtkDataSetMapper() aEdgeContourMapper.SetInputConnection(edgeContours.GetOutputPort()) aEdgeContourMapper.ScalarVisibilityOff() aEdgeMapper = vtk.vtkDataSetMapper() aEdgeMapper.SetInputData(aEdgeGrid) aEdgeMapper.ScalarVisibilityOff() aEdgeActor = vtk.vtkActor() aEdgeActor.SetMapper(aEdgeMapper)
def PointsToGrid(self, xo, yo, zo, dx, dy, dz, grid=None): """Convert XYZ points to a ``vtkUnstructuredGrid``. """ if not checkNumpy(): raise _helpers.PVGeoError( "`VoxelizePoints` cannot work with versions of NumPy below 1.10.x . You must update NumPy." ) return None if grid is None: grid = vtk.vtkUnstructuredGrid() # TODO: Check dtypes on all arrays. Need to be floats if self.__estimateGrid: x, y, z = self.EstimateUniformSpacing(xo, yo, zo) else: x, y, z = xo, yo, zo dx, dy, dz = self.__dx, self.__dy, self.__dz if isinstance(dx, np.ndarray) and len(dx) != len(x): raise _helpers.PVGeoError( 'X-Cell spacings are not properly defined for all points.') if isinstance(dy, np.ndarray) and len(dy) != len(y): raise _helpers.PVGeoError( 'X-Cell spacings are not properly defined for all points.') if isinstance(dz, np.ndarray) and len(dz) != len(z): raise _helpers.PVGeoError( 'X-Cell spacings are not properly defined for all points.') numCells = len(x) # Generate cell nodes for all points in data set #- Bottom c_n1 = np.stack(((x - dx / 2), (y - dy / 2), (z - dz / 2)), axis=1) c_n2 = np.stack(((x + dx / 2), (y - dy / 2), (z - dz / 2)), axis=1) c_n3 = np.stack(((x - dx / 2), (y + dy / 2), (z - dz / 2)), axis=1) c_n4 = np.stack(((x + dx / 2), (y + dy / 2), (z - dz / 2)), axis=1) #- Top c_n5 = np.stack(((x - dx / 2), (y - dy / 2), (z + dz / 2)), axis=1) c_n6 = np.stack(((x + dx / 2), (y - dy / 2), (z + dz / 2)), axis=1) c_n7 = np.stack(((x - dx / 2), (y + dy / 2), (z + dz / 2)), axis=1) c_n8 = np.stack(((x + dx / 2), (y + dy / 2), (z + dz / 2)), axis=1) #- Concatenate all_nodes = np.concatenate( (c_n1, c_n2, c_n3, c_n4, c_n5, c_n6, c_n7, c_n8), axis=0) # Search for unique nodes and use the min cell size as the tolerance TOLERANCE = np.min([dx, dy]) / 2.0 # Round XY plane by the tolerance txy = np.around(all_nodes[:, 0:2] / TOLERANCE) all_nodes[:, 0:2] = txy unique_nodes, ind_nodes = np.unique(all_nodes, return_inverse=True, axis=0) unique_nodes[:, 0:2] *= TOLERANCE numPts = len(unique_nodes) # Make the cells pts = vtk.vtkPoints() cells = vtk.vtkCellArray() # insert unique nodes as points if self.__estimateGrid: unique_nodes[:, 0:2] = RotationTool.Rotate(unique_nodes[:, 0:2], -self.__angle) self.AddFieldData(grid) # Add unique nodes as points in output pts.SetData(nps.numpy_to_vtk(unique_nodes)) cnt = 0 arridx = np.zeros(numCells) for i in range(numCells): # OPTIMIZE: may be complicated but can be speed up vox = vtk.vtkVoxel() for j in range(8): vox.GetPointIds().SetId(j, ind_nodes[j * numCells + i]) cells.InsertNextCell(vox) arridx[i] = i cnt += 8 grid.SetPoints(pts) grid.SetCells(vtk.VTK_VOXEL, cells) #VoxelizePoints.AddCellData(grid, arridx, 'Voxel ID') # For testing return grid
def __tree_mesh_to_vtk(mesh, models=None): """ Constructs a :class:`pyvista.UnstructuredGrid` object of this tree mesh and the given models as ``cell_arrays`` of that ``pyvista`` dataset. Parameters ---------- mesh : discretize.TreeMesh The tree mesh to convert to a :class:`pyvista.UnstructuredGrid` models : dict(numpy.ndarray) Name('s) and array('s). Match number of cells """ # Make the data parts for the vtu object # Points ptsMat = np.vstack((mesh.gridN, mesh.gridhN)) # Adjust if result was 2D (voxels are pixels in 2D): VTK_CELL_TYPE = _vtk.VTK_VOXEL if ptsMat.shape[1] == 2: # Add Z values of 0.0 if 2D ptsMat = np.c_[ptsMat, np.zeros(ptsMat.shape[0])] VTK_CELL_TYPE = _vtk.VTK_PIXEL if ptsMat.shape[1] != 3: raise RuntimeError("Points of the mesh are improperly defined.") # Rotate the points to the cartesian system ptsMat = np.dot(ptsMat, mesh.rotation_matrix) # Grab the points vtkPts = _vtk.vtkPoints() vtkPts.SetData(_nps.numpy_to_vtk(ptsMat, deep=True)) # Cells cellArray = [c for c in mesh] cellConn = np.array([cell.nodes for cell in cellArray]) cellsMat = np.concatenate( (np.ones((cellConn.shape[0], 1), dtype=int) * cellConn.shape[1], cellConn), axis=1, ).ravel() cellsArr = _vtk.vtkCellArray() cellsArr.SetNumberOfCells(cellConn.shape[0]) cellsArr.SetCells( cellConn.shape[0], _nps.numpy_to_vtk(cellsMat, deep=True, array_type=_vtk.VTK_ID_TYPE), ) # Make the object output = _vtk.vtkUnstructuredGrid() output.SetPoints(vtkPts) output.SetCells(VTK_CELL_TYPE, cellsArr) # Add the level of refinement as a cell array cell_levels = np.array([cell._level for cell in cellArray]) refineLevelArr = _nps.numpy_to_vtk(cell_levels, deep=1) refineLevelArr.SetName("octreeLevel") output.GetCellData().AddArray(refineLevelArr) ubc_order = mesh._ubc_order # order_ubc will re-order from treemesh ordering to UBC ordering # need the opposite operation un_order = np.empty_like(ubc_order) un_order[ubc_order] = np.arange(len(ubc_order)) order = _nps.numpy_to_vtk(un_order) order.SetName("index_cell_corner") output.GetCellData().AddArray(order) # Assign the model('s) to the object return assign_cell_data(output, models=models)
def ReadNGNEUTMeshFile(self): if (self.InputFileName == ''): self.PrintError('Error: no InputFileName.') self.PrintLog('Reading ngneut mesh file.') f = open(self.InputFileName, 'r') self.Mesh = vtk.vtkUnstructuredGrid() self.MeshPoints = vtk.vtkPoints() line = f.readline() numberOfPoints = int(line) self.MeshPoints.SetNumberOfPoints(numberOfPoints) for i in range(numberOfPoints): line = f.readline() splitLine = line.strip().split() point = [ float(splitLine[0]), float(splitLine[1]), float(splitLine[2]) ] self.MeshPoints.SetPoint(i, point) self.Mesh.SetPoints(self.MeshPoints) self.Mesh.Allocate(numberOfPoints * 4, 1000) line = f.readline() numberOfVolumeCells = int(line) cellEntityIdArray = vtk.vtkIntArray() cellEntityIdArray.SetName(self.CellEntityIdsArrayName) for i in range(numberOfVolumeCells): line = f.readline() splitLine = line.strip().split() cellType = -1 numberOfCellPoints = len(splitLine) - 1 pointIds = vtk.vtkIdList() if numberOfCellPoints == 4: cellType = 10 # pointIds.InsertNextId(int(splitLine[0+1])-1) # pointIds.InsertNextId(int(splitLine[1+1])-1) # pointIds.InsertNextId(int(splitLine[2+1])-1) # pointIds.InsertNextId(int(splitLine[3+1])-1) pointIds.InsertNextId(int(splitLine[1 + 1]) - 1) pointIds.InsertNextId(int(splitLine[2 + 1]) - 1) pointIds.InsertNextId(int(splitLine[3 + 1]) - 1) pointIds.InsertNextId(int(splitLine[0 + 1]) - 1) elif numberOfCellPoints == 10: cellType = 24 # pointIds.InsertNextId(int(splitLine[0+1])-1) # pointIds.InsertNextId(int(splitLine[1+1])-1) # pointIds.InsertNextId(int(splitLine[2+1])-1) # pointIds.InsertNextId(int(splitLine[3+1])-1) # pointIds.InsertNextId(int(splitLine[4+1])-1) # pointIds.InsertNextId(int(splitLine[7+1])-1) # pointIds.InsertNextId(int(splitLine[5+1])-1) # pointIds.InsertNextId(int(splitLine[6+1])-1) # pointIds.InsertNextId(int(splitLine[8+1])-1) # pointIds.InsertNextId(int(splitLine[9+1])-1) pointIds.InsertNextId(int(splitLine[1 + 1]) - 1) pointIds.InsertNextId(int(splitLine[2 + 1]) - 1) pointIds.InsertNextId(int(splitLine[3 + 1]) - 1) pointIds.InsertNextId(int(splitLine[0 + 1]) - 1) pointIds.InsertNextId(int(splitLine[7 + 1]) - 1) pointIds.InsertNextId(int(splitLine[9 + 1]) - 1) pointIds.InsertNextId(int(splitLine[8 + 1]) - 1) pointIds.InsertNextId(int(splitLine[4 + 1]) - 1) pointIds.InsertNextId(int(splitLine[5 + 1]) - 1) pointIds.InsertNextId(int(splitLine[6 + 1]) - 1) entityId = int(splitLine[0]) cellEntityIdArray.InsertNextValue(entityId) self.Mesh.InsertNextCell(cellType, pointIds) if self.VolumeElementsOnly == 0: line = f.readline() numberOfSurfaceCells = int(line) for i in range(numberOfSurfaceCells): line = f.readline() splitLine = line.strip().split() cellType = -1 numberOfCellPoints = len(splitLine) - 1 pointIds = vtk.vtkIdList() if numberOfCellPoints == 3: cellType = 5 for j in range(numberOfCellPoints): pointIds.InsertNextId(int(splitLine[j + 1]) - 1) elif numberOfCellPoints == 6: cellType = 22 for j in range(3): pointIds.InsertNextId(int(splitLine[j + 1]) - 1) pointIds.InsertNextId(int(splitLine[5 + 1]) - 1) pointIds.InsertNextId(int(splitLine[3 + 1]) - 1) pointIds.InsertNextId(int(splitLine[4 + 1]) - 1) entityId = int(splitLine[0]) cellEntityIdArray.InsertNextValue(entityId) self.Mesh.InsertNextCell(cellType, pointIds) self.Mesh.Squeeze() self.Mesh.GetCellData().AddArray(cellEntityIdArray)
def Display(atomnetwork,channel): renWin = vtk.vtkRenderWindow() renWin.SetSize(600, 600) renWin.SetWindowName('Channel view test') renderer = vtk.vtkRenderer() atoms = atomnetwork.atoms #atoms = atomnetwork for i in range(len(atoms)): atom = vtk.vtkSphereSource() atom.SetCenter(atoms[i][1]) atom.SetRadius(0.04) atomMapper = vtk.vtkPolyDataMapper() atomActor = vtk.vtkActor() atomMapper.SetInputConnection(atom.GetOutputPort()) atomActor.SetMapper(atomMapper) atomActor.GetProperty().SetColor(0.9804, 0.9216, 0.8431) renderer.AddViewProp(atomActor) initials = channel.nodes #test code #initials = [[0, [3.190295850833425, 0.8755507257066707, 2.456838230302852], 1.5088341084285433], [1, [1.1083746175913838, 0.19310377416061847, 5.545615109204309], 1.395878894814294], [2, [0.16072723136374067, 3.9351370561729335, 5.356215528814367], 1.3964483726943062], [3, [1.9748328675382072, 4.033670883989947, 2.1370451794264467], 1.235088970054386], [4, [0.9214256508857486, 1.1748713352351365, 1.5565669858442992], 1.1195247343236383], [5, [2.401335408641232, 3.6907907651916476, 0.10418166251447392], 1.2816998243989537], [6, [0.7388113212217622, 0.9332478908561466, 5.324351976395488], 1.3720916114003], [7, [0.780053889480055, 0.7037759112780848, 5.305620009992378], 1.3422207104331099], [8, [0.8062328350612087, 1.030695449900831, 5.433452109901365], 1.3872567955007895], [9, [1.4342284218232422, 3.562010219494333, 0.3122492683885111], 1.4016814054440634], [10, [1.9859518281340114, 3.6748715011934325, 1.2688627931343748], 1.1195246579752263]] points = vtk.vtkPoints() points.SetNumberOfPoints(len(initials)) for j in range(len(initials)): points.InsertPoint(initials[j][0],initials[j][1]) connections = channel.connections #test code #connections = [[0,1],[0,2],[0,4],[2,4],[2,5],[3,7],[3,9],[5,6],[5,1],[7,10],[8,9]] linkedIdList = vtk.vtkIdList() #linkedIdList.InsertNextId(len(connections)) for k in range(len(connections)): #linkedIdList.InsertNextId(2) linkedIdList.InsertNextId(connections[k][0]) linkedIdList.InsertNextId(connections[k][1]) uGrid = vtk.vtkUnstructuredGrid() uGrid.InsertNextCell(vtk.VTK_LINE, linkedIdList) uGrid.SetPoints(points) uGridMapper = vtk.vtkDataSetMapper() uGridActor = vtk.vtkActor() uGridMapper.SetInputData(uGrid) uGridActor.SetMapper(uGridMapper) uGridActor.GetProperty().SetColor(0.3,0.7,0.9) renderer.AddViewProp(uGridActor) renderer.SetBackground(0.0,0.3,0.1) renderer.ResetCamera() renderer.GetActiveCamera().Azimuth(30) renderer.GetActiveCamera().Elevation(-30) renderer.GetActiveCamera().Zoom(1) renderer.ResetCameraClippingRange() renWin.AddRenderer(renderer) iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin) iRen.Initialize() renWin.Render() return iRen
voxelScalars.InsertValue(2, 0) voxelScalars.InsertValue(3, 0) voxelScalars.InsertValue(4, 0) voxelScalars.InsertValue(5, 0) voxelScalars.InsertValue(6, 0) voxelScalars.InsertValue(7, 0) aVoxel = vtk.vtkVoxel() aVoxel.GetPointIds().SetId(0, 0) aVoxel.GetPointIds().SetId(1, 1) aVoxel.GetPointIds().SetId(2, 2) aVoxel.GetPointIds().SetId(3, 3) aVoxel.GetPointIds().SetId(4, 4) aVoxel.GetPointIds().SetId(5, 5) aVoxel.GetPointIds().SetId(6, 6) aVoxel.GetPointIds().SetId(7, 7) aVoxelGrid = vtk.vtkUnstructuredGrid() aVoxelGrid.Allocate(1, 1) aVoxelGrid.InsertNextCell(aVoxel.GetCellType(), aVoxel.GetPointIds()) aVoxelGrid.SetPoints(voxelPoints) aVoxelGrid.GetPointData().SetScalars(voxelScalars) voxelContours = vtk.vtkContourFilter() voxelContours.SetInputData(aVoxelGrid) voxelContours.SetValue(0, .5) aVoxelContourMapper = vtk.vtkDataSetMapper() aVoxelContourMapper.SetInputConnection(voxelContours.GetOutputPort()) aVoxelContourMapper.ScalarVisibilityOff() aVoxelMapper = vtk.vtkDataSetMapper() aVoxelMapper.SetInputData(aVoxelGrid) aVoxelMapper.ScalarVisibilityOff() aVoxelActor = vtk.vtkActor() aVoxelActor.SetMapper(aVoxelMapper)
def readMSHGrid(mshfilename): fdata = open(mshfilename, "r") lines = fdata.readlines() startelem = 0 startnode = 0 cnt = 0 cellArray = vtk.vtkCellArray() points = vtk.vtkPoints() for line in lines: if ("$Elements" in line): startelem = 1 continue if ("$EndElements" in line): startelem = 0 continue if ("$Nodes" in line): startnode = 1 continue if ("$EndNodes" in line): startnode = 0 continue if (startnode == 1): try: x = float(line.strip().split()[1]) y = float(line.strip().split()[2]) z = float(line.strip().split()[3]) points.InsertNextPoint(x, y, z) except IndexError: continue if (startelem == 1): try: elmtype = int(line.strip().split()[1]) if (elmtype == 4): tetra = vtk.vtkTetra() tetra.GetPointIds().SetId(0, int(line.strip().split()[5]) - 1) tetra.GetPointIds().SetId(1, int(line.strip().split()[6]) - 1) tetra.GetPointIds().SetId(2, int(line.strip().split()[7]) - 1) tetra.GetPointIds().SetId(3, int(line.strip().split()[8]) - 1) cellArray.InsertNextCell(tetra) except IndexError: continue ugrid = vtk.vtkUnstructuredGrid() ugrid.SetPoints(points) ugrid.SetCells(10, cellArray) #writeUGrid(ugrid, "test.vtk") return ugrid
def ReadTecplotMeshFile(self): self.PrintLog('Reading Tecplot surface file.') if self.InputFileName[-3:] == '.gz': import gzip f = gzip.open(self.InputFileName, 'r') else: f = open(self.InputFileName, 'r') line = f.readline() if line.split()[0] == 'TITLE': line = f.readline() if (line.split()[0] == 'VARIABLES') | (line.split('=')[0] == 'VARIABLES'): arrayNames = line.split('=')[1].strip().split(',') arrayNames[0:3] = [] self.PrintLog("ArrayNames" + str(arrayNames)) line = f.readline() if line.split()[0] == 'ZONE': lineNid = line.find('N=') lineN = line[lineNid:lineNid + line[lineNid:].find(',')].split('=')[1] numberOfNodes = int(lineN) lineEid = line.find('E=') lineE = line[lineEid:lineEid + line[lineEid:].find(',')].split('=')[1] numberOfElements = int(lineE) self.PrintLog("Reading " + str(numberOfNodes) + " nodes.") points = vtk.vtkPoints() cells = vtk.vtkCellArray() points.SetNumberOfPoints(numberOfNodes) self.Mesh = vtk.vtkUnstructuredGrid() self.Mesh.SetPoints(points) for arrayName in arrayNames: array = vtk.vtkDoubleArray() array.SetName(arrayName) array.SetNumberOfTuples(numberOfNodes) self.Mesh.GetPointData().AddArray(array) data = f.read().split() dataCounter = 0 for i in range(numberOfNodes): point = [ float(data[dataCounter]), float(data[dataCounter + 1]), float(data[dataCounter + 2]) ] dataCounter += 3 points.SetPoint(i, point) for j in range(len(arrayNames)): self.Mesh.GetPointData().GetArray(arrayNames[j]).SetComponent( i, 0, float(data[dataCounter])) dataCounter += 1 self.PrintLog("Reading " + str(numberOfElements) + " elements.") cellIds = vtk.vtkIdList() for i in range(numberOfElements): cellIds.Initialize() cellIds.InsertNextId(int(data[dataCounter]) - 1) dataCounter += 1 cellIds.InsertNextId(int(data[dataCounter]) - 1) dataCounter += 1 cellIds.InsertNextId(int(data[dataCounter]) - 1) dataCounter += 1 cellIds.InsertNextId(int(data[dataCounter]) - 1) dataCounter += 1 legal = 1 for j in range(cellIds.GetNumberOfIds()): if cellIds.GetId(j) < 0: legal = 0 break if not legal: continue cells.InsertNextCell(cellIds) self.Mesh.SetCells(10, cells) self.Mesh.Update()
def writeVTK(mesh, fileName, models=None): """ Function to write a VTU file from a SimPEG TreeMesh and model. """ import vtk from vtk import vtkXMLUnstructuredGridWriter as Writer, VTK_VERSION from vtk.util.numpy_support import numpy_to_vtk, numpy_to_vtkIdTypeArray if str(type(mesh)).split( )[-1][1:-2] not in 'SimPEG.Mesh.TreeMesh.TreeMesh': raise IOError('mesh is not a SimPEG TreeMesh.') # Make the data parts for the vtu object # Points mesh.number() ptsMat = mesh._gridN + mesh.x0 vtkPts = vtk.vtkPoints() vtkPts.SetData(numpy_to_vtk(ptsMat, deep=True)) # Cells cellConn = np.array([c.nodes for c in mesh], dtype=np.int64) cellsMat = np.concatenate((np.ones( (cellConn.shape[0], 1), dtype=np.int64) * cellConn.shape[1], cellConn), axis=1).ravel() cellsArr = vtk.vtkCellArray() cellsArr.SetNumberOfCells(cellConn.shape[0]) cellsArr.SetCells(cellConn.shape[0], numpy_to_vtkIdTypeArray(cellsMat, deep=True)) # Make the object vtuObj = vtk.vtkUnstructuredGrid() vtuObj.SetPoints(vtkPts) vtuObj.SetCells(vtk.VTK_VOXEL, cellsArr) # Add the level of refinement as a cell array cellSides = np.array([ np.array(vtuObj.GetCell(i).GetBounds()).reshape( (3, 2)).dot(np.array([-1, 1])) for i in np.arange(vtuObj.GetNumberOfCells()) ]) uniqueLevel, indLevel = np.unique(np.prod(cellSides, axis=1), return_inverse=True) refineLevelArr = numpy_to_vtk(indLevel.max() - indLevel, deep=1) refineLevelArr.SetName('octreeLevel') vtuObj.GetCellData().AddArray(refineLevelArr) # Assign the model('s) to the object if models is not None: for item in six.iteritems(models): # Convert numpy array vtkDoubleArr = numpy_to_vtk(item[1], deep=1) vtkDoubleArr.SetName(item[0]) vtuObj.GetCellData().AddArray(vtkDoubleArr) # Make the writer vtuWriteFilter = Writer() if float(VTK_VERSION.split('.')[0]) >= 6: vtuWriteFilter.SetInputData(vtuObj) else: vtuWriteFilter.SetInput(vtuObj) vtuWriteFilter.SetFileName(fileName) # Write the file vtuWriteFilter.Update()
def resample_to_2d_1d(pdi, pdi_frac, pdo, geom): # geom_types=ns.vtk_to_numpy(geom.GetCellTypesArray()) geom_locations=ns.vtk_to_numpy(geom.GetCellLocationsArray()) geom_2d_id=np.where(geom_types==VTK_TRIANGLE)[0] n_2d_cells=geom_2d_id.size #print geom_2d_id #geom_2d_locations=geom_locations[geom_2d_id] geom_1d_id=np.where(geom_types==VTK_LINE)[0] n_1d_cells=geom_1d_id.size #print geom_1d_id geom_1d_locations=geom_locations[geom_1d_id] # should check that there are both 2d and 1d elements other # similarly we should check that there are only triangles in the pdi # create a sampling dataset aux_dataset=vtk.vtkUnstructuredGrid() # compute centroids input_copy = geom.NewInstance() input_copy.UnRegister(None) input_copy.ShallowCopy(geom) geom_centers=vtk.vtkCellCenters() geom_centers.SetInputData(geom) geom_centers.Update() output=geom_centers.GetOutput() barycenters=ns.vtk_to_numpy(output.GetPoints().GetData()).reshape(-1,3) barycenters_2d=barycenters[geom_2d_id] #print barycenters_2d # shift right half of points barycenters_2d[:,0]=np.where(barycenters_2d[:,0]<X_FR, barycenters_2d[:,0]-X_SHIFT_LEFT, barycenters_2d[:,0]+X_SHIFT_RIGHT) # compute 1d avarage points cell_data=ns.vtk_to_numpy(geom.GetCells().GetData()) grid = np.meshgrid( [0,1,2], geom_1d_locations ) grid = map(np.ravel, grid) cell_data_selection=grid[0]+grid[1] array_of_1d_cells=(cell_data[cell_data_selection]) assert(len(array_of_1d_cells)>0) geom_points_y=ns.vtk_to_numpy(geom.GetPoints().GetData())[:,1] x_points=np.array((0)) y_points=np.array((0)) # trapezoid rule """ def weights(N): return np.array([0.5] + (N-2)*[1.0] + [0.5]) average_weights=np.outer( weights(AVERAGE_POINTS_X), weights(AVERAGE_POINTS_Y)).flatten() # reference grid x=np.linspace(-X_SHIFT_LEFT, X_SHIFT_RIGHT, AVERAGE_POINTS_X) y=np.linspace(0,1,AVERAGE_POINTS_Y) """ def weights(N): # trapezoidal weights return np.array([0.5] + (N-2)*[1.0] + [0.5]) # midpoint rule in both directions (avoid problems at boundary) average_weights=np.outer( np.ones(AVERAGE_POINTS_Y), np.ones(AVERAGE_POINTS_X) ).flatten() # reference grid N=float(AVERAGE_POINTS_X) dx=(X_SHIFT_RIGHT + X_SHIFT_LEFT)/N x=np.linspace(X_FR-X_SHIFT_LEFT+dx/2, X_FR+X_SHIFT_RIGHT-dx/2,N) N=float(AVERAGE_POINTS_Y) y=np.linspace(1/(2*N),1-1/(2*N),N) #print "weights: ", average_weights #print "y: ", y ref_x, ref_y=map(np.ravel, np.meshgrid(x,y)) #print "y: ", ref_y #print "x: ", ref_x assert( np.all(array_of_1d_cells[0::3]==2) ) p0=geom_points_y[array_of_1d_cells[1::3]] p1=geom_points_y[array_of_1d_cells[2::3]] x_points=np.tile(ref_x, geom_1d_id.size) yy,y0=np.meshgrid(ref_y,p0) yy,y1=np.meshgrid(ref_y,p1) y_points=(y0*yy+y1*(1-yy)).ravel() #print average_weights.size, x_points.size, y_points.size assert(x_points.size==y_points.size) assert(AVERAGE_POINTS_X*AVERAGE_POINTS_Y==average_weights.size) z_points=np.zeros(len(x_points)) points_1d=np.hstack(( x_points.reshape((-1,1)), y_points.reshape((-1,1)), z_points.reshape((-1,1)) )) #print points_1d barycenters_2d.shape=(-1,3) points_1d.shape=(-1,3) #all_points=append(barycenters_2d, points_1d) #all_points.shape=(-1,3) # make a dataset # probe on fracture dataset points_f=vtk.vtkPoints() points_f.SetData(ns.numpy_to_vtk(points_1d, deep=1)) point_set_f=vtk.vtkUnstructuredGrid() point_set_f.SetPoints(points_f) probe_f=vtk.vtkProbeFilter() probe_f.SetSourceData(pdi_frac) probe_f.SetInputData(point_set_f) probe_f.Update() out_f=probe_f.GetOutput() probe_data_f=out_f.GetPointData() # probe on continuum dataset points=vtk.vtkPoints() points.SetData(ns.numpy_to_vtk(barycenters_2d, deep=1)) point_set=vtk.vtkUnstructuredGrid() point_set.SetPoints(points) probe=vtk.vtkProbeFilter() probe.SetSourceData(pdi) probe.SetInputData(point_set) probe.Update() out=probe.GetOutput() probe_data=out.GetPointData() # reconstruct element arrays pdo.DeepCopy(geometry) cell_data=pdo.GetCellData() for i_array in range(cell_data.GetNumberOfArrays()): cell_data.RemoveArray(i_array) point_data=pdo.GetPointData() for i_array in range(point_data.GetNumberOfArrays()): point_data.RemoveArray(i_array) assert(probe_data.GetNumberOfArrays() == probe_data_f.GetNumberOfArrays() ) for i_array in range(probe_data.GetNumberOfArrays()): vtk_array=probe_data.GetArray(i_array) array=ns.vtk_to_numpy(vtk_array) n_components=vtk_array.GetNumberOfComponents() n_tuples=vtk_array.GetNumberOfTuples() assert(n_tuples == n_2d_cells) array.shape=(n_tuples,n_components) vtk_array_f=probe_data_f.GetArray(i_array) array_f=ns.vtk_to_numpy(vtk_array_f) n_components_f=vtk_array_f.GetNumberOfComponents() n_tuples_f=vtk_array_f.GetNumberOfTuples() assert(n_components == n_components_f) assert( n_1d_cells*len(average_weights) == n_tuples_f) assert( array.dtype == array_f.dtype) array_f.shape=(n_1d_cells, len(average_weights), n_components) #print vtk_array.GetName() #print array_f.shape #print array_f new_array=np.zeros((pdo.GetNumberOfCells(),n_components), dtype=array.dtype) new_array[geom_2d_id,:]=array new_array[geom_1d_id,:]=np.average(array_f, weights=average_weights, axis=1) new_vtk_array=ns.numpy_to_vtk(new_array, deep=1) new_vtk_array.SetName(vtk_array.GetName()) cell_data.AddArray(new_vtk_array) #ids=ns.numpy_to_vtk(np.arange(n_2d_cells+n_1d_cells), deep=1) #ids.SetName('ids') #cell_data.AddArray(ids) '''
def addfiber_matid(mesh, V, casename, endo_angle, epi_angle, infarct_endo_angle, infarct_epi_angle, casedir, matid, isepiflip, isendoflip): fiberV = Function(V) sheetV = Function(V) sheetnormV = Function(V) #endofilename = casedir + 'endocardium.stl' #epifilename = casedir + 'epicardium.stl' #endofilename = casename + '_endo.stl' #epifilename = casename + '_epi.stl' #pdata_endo = readSTL(endofilename) #pdata_epi = readSTL(epifilename) ugrid=vtk_py.convertXMLMeshToUGrid(mesh) pdata = vtk_py.convertUGridtoPdata(ugrid) C = vtk_py.getcentroid(pdata) ztop = pdata.GetBounds()[5] C = [C[0], C[1], ztop-0.05] clippedheart = vtk_py.clipheart(pdata, C, [0,0,1], True) epi, endo= vtk_py.splitDomainBetweenEndoAndEpi(clippedheart) cleanepipdata = vtk.vtkCleanPolyData() if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): cleanepipdata.SetInputData(epi) else: cleanepipdata.SetInput(epi) cleanepipdata.Update() pdata_epi = cleanepipdata.GetOutput() cleanendopdata = vtk.vtkCleanPolyData() if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): cleanendopdata.SetInputData(endo) else: cleanendopdata.SetInput(endo) cleanendopdata.Update() pdata_endo = cleanendopdata.GetOutput() L_epi = pdata_epi.GetBounds()[5] - pdata_epi.GetBounds()[4] L_endo = pdata_endo.GetBounds()[5] - pdata_endo.GetBounds()[4] if(L_endo > L_epi): pdata_epi = temp pdata_epi = pdata_endo pdata_endo = temp # Quad points gdim = mesh.geometry().dim() xdofmap = V.sub(0).dofmap().dofs() ydofmap = V.sub(1).dofmap().dofs() zdofmap = V.sub(2).dofmap().dofs() if(dolfin.dolfin_version() != '1.6.0'): xq = V.tabulate_dof_coordinates().reshape((-1, gdim)) xq0 = xq[xdofmap] else: xq = V.dofmap().tabulate_all_coordinates(mesh).reshape((-1, gdim)) xq0 = xq[xdofmap] # Create an unstructured grid of Gauss Points points = vtk.vtkPoints() ugrid = vtk.vtkUnstructuredGrid() cnt = 0; for pt in xq0: points.InsertNextPoint([pt[0], pt[1], pt[2]]) cnt += 1 ugrid.SetPoints(points) CreateVertexFromPoint(ugrid) addLocalProlateSpheroidalDirections(ugrid, pdata_endo, pdata_epi, type_of_support="cell", epiflip=isepiflip, endoflip=isendoflip) addLocalFiberOrientation_infarct(ugrid, endo_angle, epi_angle, infarct_endo_angle, infarct_epi_angle, matid) fiber_vector = ugrid.GetCellData().GetArray("fiber vectors") sheet_vector = ugrid.GetCellData().GetArray("sheet vectors") sheetnorm_vector = ugrid.GetCellData().GetArray("sheet normal vectors") cnt = 0 for pt in xq0: fvec = fiber_vector.GetTuple(cnt) svec = sheet_vector.GetTuple(cnt) nvec = sheetnorm_vector.GetTuple(cnt) fvecnorm = sqrt(fvec[0]**2 + fvec[1]**2 + fvec[2]**2) svecnorm = sqrt(svec[0]**2 + svec[1]**2 + svec[2]**2) nvecnorm = sqrt(nvec[0]**2 + nvec[1]**2 + nvec[2]**2) if(abs(fvecnorm - 1.0) > 1e-7 or abs(svecnorm - 1.0) > 1e-6 or abs(nvecnorm - 1.0) > 1e-7): print (fvecnorm) print (svecnorm) print (nvecnorm) #print(xdofmap[cnt], ydofmap[cnt], zdofmap[cnt]) fiberV.vector()[xdofmap[cnt]] = fvec[0]; fiberV.vector()[ydofmap[cnt]] = fvec[1]; fiberV.vector()[zdofmap[cnt]] = fvec[2]; sheetV.vector()[xdofmap[cnt]] = svec[0]; sheetV.vector()[ydofmap[cnt]] = svec[1]; sheetV.vector()[zdofmap[cnt]] = svec[2]; sheetnormV.vector()[xdofmap[cnt]] = nvec[0]; sheetnormV.vector()[ydofmap[cnt]] = nvec[1]; sheetnormV.vector()[zdofmap[cnt]] = nvec[2]; cnt += 1 writeXMLUGrid(ugrid, "test.vtu") return fiberV, sheetV, sheetnormV
def resample_to_2d_1d(pdi, pdo, geom): # geom_types = ns.vtk_to_numpy(geom.GetCellTypesArray()) geom_locations = ns.vtk_to_numpy(geom.GetCellLocationsArray()) geom_2d_id = np.where(geom_types == VTK_TRIANGLE)[0] n_2d_cells = geom_2d_id.size #print geom_2d_id geom_2d_locations = geom_locations[geom_2d_id] geom_1d_id = np.where(geom_types == VTK_LINE)[0] n_1d_cells = geom_1d_id.size #print geom_1d_id geom_1d_locations = geom_locations[geom_1d_id] # should check that there are both 2d and 1d elements other # similarly we should check that there are only triangles in the pdi # create a sampling dataset aux_dataset = vtk.vtkUnstructuredGrid() # compute centroids input_copy = geom.NewInstance() input_copy.UnRegister(None) input_copy.ShallowCopy(geom) geom_centers = vtk.vtkCellCenters() geom_centers.SetInputData(geom) geom_centers.Update() output = geom_centers.GetOutput() barycenters = ns.vtk_to_numpy(output.GetPoints().GetData()).reshape(-1, 3) barycenters_2d = barycenters[geom_2d_id] #print barycenters_2d # shift right half of points barycenters_2d[:, 0] = np.where(barycenters_2d[:, 0] < 0, barycenters_2d[:, 0] + LEFT_SHIFT, barycenters_2d[:, 0] + RIGHT_SHIFT) # compute 1d avarage points cell_data = ns.vtk_to_numpy(geom.GetCells().GetData()) grid = np.meshgrid([0, 1, 2], geom_1d_locations) grid = map(np.ravel, grid) cell_data_selection = grid[0] + grid[1] array_of_1d_cells = (cell_data[cell_data_selection]) assert (len(array_of_1d_cells) > 0) geom_points_y = ns.vtk_to_numpy(geom.GetPoints().GetData())[:, 1] x_points = np.array((0)) y_points = np.array((0)) # reference grid x = np.linspace(LEFT_SHIFT, RIGHT_SHIFT, AVERAGE_POINTS) y = np.linspace(0, 1, AVERAGE_POINTS) ref_x, ref_y = map(np.ravel, np.meshgrid(x, y)) assert (np.all(array_of_1d_cells[0::3] == 2)) p0 = geom_points_y[array_of_1d_cells[1::3]] p1 = geom_points_y[array_of_1d_cells[2::3]] x_points = np.tile(ref_x, geom_1d_id.size) yy, y0 = np.meshgrid(ref_y, p0) yy, y1 = np.meshgrid(ref_y, p1) y_points = (y0 * yy + y1 * (1 - yy)).ravel() assert (x_points.size == y_points.size) z_points = np.zeros(len(x_points)) points_1d = np.hstack((x_points.reshape((-1, 1)), y_points.reshape( (-1, 1)), z_points.reshape((-1, 1)))) #print points_1d all_points = append(barycenters_2d, points_1d) all_points.shape = (-1, 3) # make a probe dataset points = vtk.vtkPoints() points.SetData(make_vtk_array(all_points, "points")) point_set = vtk.vtkUnstructuredGrid() point_set.SetPoints(points) probe = vtk.vtkProbeFilter() probe.SetSourceData(pdi) probe.SetInputData(point_set) probe.Update() out = probe.GetOutput() probe_data = out.GetPointData() # reconstruct element arrays pdo.DeepCopy(geometry) cell_data = pdo.GetCellData() for i_array in range(probe_data.GetNumberOfArrays()): # make interpolation array vtk_array = probe_data.GetArray(i_array) array_name = vtk_array.GetName() n_components = vtk_array.GetNumberOfComponents() n_tuples = vtk_array.GetNumberOfTuples() array = ns.vtk_to_numpy(vtk_array) array.shape = (n_tuples, n_components) new_array = np.zeros((pdo.GetNumberOfCells(), n_components), dtype=array.dtype) new_array[geom_2d_id, :] = array[0:n_2d_cells, :] array_1d = array[n_2d_cells:, :].reshape( n_1d_cells, AVERAGE_POINTS * AVERAGE_POINTS, n_components) new_array[geom_1d_id, :] = np.average(array_1d, axis=1) new_vtk_array = ns.numpy_to_vtk(new_array, deep=1) cell_data.AddArray( make_vtk_array(new_array, "interpol_" + vtk_array.GetName())) # compute difference array vtk_geometry_array = pdo.GetCellData().GetArray(array_name) if vtk_geometry_array: assert_eq(vtk_geometry_array.GetNumberOfComponents(), new_array.shape[1]) assert_eq(vtk_geometry_array.GetNumberOfTuples(), new_array.shape[0]) geometry_array = ns.vtk_to_numpy(vtk_geometry_array) geometry_array.shape = new_array.shape difference = geometry_array - new_array cell_data.AddArray( make_vtk_array(difference, "diff_" + vtk_array.GetName()))
def _get_bar_yz_arrays(self, model, bar_beam_eids, scale, debug): lines_bar_y = [] lines_bar_z = [] points_list = [] bar_types = { # PBEAML/PBARL "ROD": [], "TUBE": [], "TUBE2" : [], "I": [], "CHAN": [], "T": [], "BOX": [], "BAR": [], "CROSS": [], "H": [], "T1": [], "I1": [], "CHAN1": [], "Z": [], "CHAN2": [], "T2": [], "BOX1": [], "HEXA": [], "HAT": [], "HAT1": [], "DBOX": [], # was 12 'bar' : [], # PBAR 'beam' : [], # PBEAM 'pbcomp' : [], # PBCOMP # PBEAML specfic "L" : [], } # for GROUP="MSCBML0" allowed_types = [ 'BAR', 'BOX', 'BOX1', 'CHAN', 'CHAN1', 'CHAN2', 'CROSS', 'DBOX', 'H', 'HAT', 'HAT1', 'HEXA', 'I', 'I1', 'L', 'ROD', 'T', 'T1', 'T2', 'TUBE', 'TUBE2', 'Z', 'bar', 'beam', 'pbcomp', ] # bar_types['bar'] = [ [...], [...], [...] ] #bar_types = defaultdict(lambda : defaultdict(list)) found_bar_types = set() #neids = len(self.element_ids) for bar_type, data in bar_types.items(): eids = [] lines_bar_y = [] lines_bar_z = [] bar_types[bar_type] = (eids, lines_bar_y, lines_bar_z) #bar_types[bar_type] = [eids, lines_bar_y, lines_bar_z] ugrid = vtk.vtkUnstructuredGrid() node0 = 0 nid_release_map = defaultdict(list) #debug = True bar_nids = set() #print('bar_beam_eids = %s' % bar_beam_eids) for eid in bar_beam_eids: if eid not in self.eid_map: self.log.error('eid=%s is not a valid bar/beam element...' % eid) if debug: # pragma: no cover print('eid=%s is not a valid bar/beam element...' % eid) continue #unused_ieid = self.eid_map[eid] elem = model.elements[eid] pid_ref = elem.pid_ref if pid_ref is None: pid_ref = model.Property(elem.pid) assert not isinstance(pid_ref, integer_types), elem ptype = pid_ref.type bar_type = _get_bar_type(ptype, pid_ref) if debug: # pragma: no cover print('%s' % elem) print(' bar_type = %s' % bar_type) found_bar_types.add(bar_type) (nid1, nid2) = elem.node_ids bar_nids.update([nid1, nid2]) node1 = model.nodes[nid1] node2 = model.nodes[nid2] n1 = node1.get_position() n2 = node2.get_position() # wa/wb are not considered in i_offset # they are considered in ihat i = n2 - n1 Li = norm(i) ihat = i / Li if elem.pa != 0: nid_release_map[nid1].append((eid, elem.pa)) if elem.pb != 0: nid_release_map[nid2].append((eid, elem.pb)) if isinstance(elem.offt, int): continue unused_v, wa, wb, xform = rotate_v_wa_wb( model, elem, n1, n2, node1, node2, ihat, i, eid, Li, model.log) if wb is None: # one or more of v, wa, wb are bad continue yhat = xform[1, :] zhat = xform[2, :] ## concept has a GOO #if debug: # pragma: no cover #print(' centroid = %s' % centroid) #print(' ihat = %s' % ihat) #print(' yhat = %s' % yhat) #print(' zhat = %s' % zhat) #print(' scale = %s' % scale) #if eid == 616211: #print(' check - eid=%s yhat=%s zhat=%s v=%s i=%s n%s=%s n%s=%s' % ( #eid, yhat, zhat, v, i, nid1, n1, nid2, n2)) #print('adding bar %s' % bar_type) #print(' centroid=%s' % centroid) #print(' yhat=%s len=%s' % (yhat, np.linalg.norm(yhat))) #print(' zhat=%s len=%s' % (zhat, np.linalg.norm(zhat))) #print(' Li=%s scale=%s' % (Li, scale)) if bar_type not in allowed_types: msg = 'bar_type=%r allowed=[%s]' % (bar_type, ', '.join(allowed_types)) raise RuntimeError(msg) if bar_type in BEAM_GEOM_TYPES: node0 = add_3d_bar_element( bar_type, ptype, pid_ref, n1+wa, n2+wb, xform, ugrid, node0, points_list) centroid = (n1 + n2) / 2. bar_types[bar_type][0].append(eid) bar_types[bar_type][1].append((centroid, centroid + yhat * Li * scale)) bar_types[bar_type][2].append((centroid, centroid + zhat * Li * scale)) if node0: # and '3d_bars' not in self.alt_grids: def update_grid_function(unused_nid_map, ugrid, points, nodes): # pragma: no cover """custom function to update the 3d bars""" points_list = [] node0b = 0 for eid in bar_beam_eids: elem = self.model.elements[eid] pid_ref = elem.pid_ref if pid_ref is None: pid_ref = self.model.Property(elem.pid) assert not isinstance(pid_ref, integer_types), elem ptype = pid_ref.type bar_type = _get_bar_type(ptype, pid_ref) #nids = elem.nodes (nid1, nid2) = elem.node_ids node1 = model.nodes[nid1] node2 = model.nodes[nid2] i1, i2 = np.searchsorted(self.node_ids, [nid1, nid2]) n1 = nodes[i1, :] n2 = nodes[i2, :] #centroid = (n1 + n2) / 2. i = n2 - n1 Li = norm(i) ihat = i / Li unused_v, wa, wb, xform = rotate_v_wa_wb( model, elem, n1, n2, node1, node2, ihat, i, eid, Li, model.log) if wb is None: # one or more of v, wa, wb are bad continue ugridi = None node0b = add_3d_bar_element( bar_type, ptype, pid_ref, n1+wa, n2+wb, xform, ugridi, node0b, points_list, add_to_ugrid=False) points_array = _make_points_array(points_list) points_array2 = numpy_to_vtk( num_array=points_array, deep=1, array_type=vtk.VTK_FLOAT, ) points.SetData(points_array2) ugrid.SetPoints(points) points.Modified() ugrid.Modified() return if points_list: if not sys.argv[0].startswith('test_'): update_grid_function = None self.gui.create_alternate_vtk_grid( '3d_bars', color=BLUE_FLOAT, opacity=0.2, representation='surface', is_visible=True, follower_function=update_grid_function, ugrid=ugrid, ) points_array = _make_points_array(points_list) points = numpy_to_vtk_points(points_array) ugrid.SetPoints(points) #print('bar_types =', bar_types) for bar_type in list(bar_types): bars = bar_types[bar_type] if len(bars[0]) == 0: del bar_types[bar_type] continue #bar_types[bar_type][1] = np.array(bars[1], dtype='float32') # lines_bar_y #bar_types[bar_type][2] = np.array(bars[2], dtype='float32') # lines_bar_z debug = False if debug: # pragma: no cover #np.set_printoptions(formatter={'float': '{: 0.3f}'.format}) for bar_type, data in sorted(bar_types.items()): eids, lines_bar_y, lines_bar_z = data if len(eids): #print('barsi =', barsi) #print('bar_type = %r' % bar_type) for eid, line_y, line_z in zip(eids, lines_bar_y, lines_bar_z): print('eid=%s centroid=%s cy=%s cz=%s' % ( eid, line_y[0], line_y[1], line_z[1])) #print('found_bar_types =', found_bar_types) #no_axial_torsion = (no_axial, no_torsion) #no_shear_bending = (no_shear_y, no_shear_z, no_bending_y, no_bending_z) #no_dofs = (no_bending, no_bending_bad, no_6_16, no_0_456, #no_0_56, no_56_456, no_0_6, no_0_16) return bar_nids, bar_types, nid_release_map
def saveTrajectory(sols, outputFile): """ Save the trajectory to VTK file @param sols list of return values of odeint @param filename """ # number of contours nContours = len(sols) # number of points for each contour nptsContour = [sol.shape[0] for sol in sols] # total number of points npts = functools.reduce(lambda x, y: x + y, nptsContour) # total number of segments nSegs = functools.reduce(lambda x, y: x + y, [nps - 1 for nps in nptsContour]) # number of space dimensions ndims = 3 pvals = numpy.zeros((npts, 3), numpy.float64) tarr = vtk.vtkDoubleArray() tpts = vtk.vtkPoints() tgrid = vtk.vtkUnstructuredGrid() tarr.SetNumberOfComponents(ndims) tarr.SetNumberOfTuples(npts) tpts.SetNumberOfPoints(npts) ptIds = vtk.vtkIdList() ptIds.SetNumberOfIds(2) tgrid.Allocate(nSegs, 1) # create the points and the unstructured grid that goes with it offset1 = 0 offset2 = 0 for iContour in range(nContours): ns = nptsContour[iContour] # store points for i in range(ns): pvals[i + offset1, :] = sols[iContour][i] pvals[i + offset1, 0] = max(0., min(360., pvals[i + offset1, 0])) pvals[i + offset1, 1] = max(-90., min(90., pvals[i + offset1, 1])) offset1 += ns # create new cells/segments for i in range(ns - 1): ptIds.SetId(0, i + offset2) ptIds.SetId(1, i + 1 + offset2) tgrid.InsertNextCell(vtk.VTK_LINE, ptIds) offset2 += ns # connect tpts.SetData(tarr) tgrid.SetPoints(tpts) tarr.SetVoidArray(pvals, npts * 3, 1) # save writer = vtk.vtkUnstructuredGridWriter() writer.SetFileName(outputFile) writer.SetInputData(tgrid) writer.Update()
def testCells(self): # Demonstrates all cell types # # NOTE: the use of NewInstance/DeepCopy is included to increase # regression coverage. It is not required in most applications. ren = vtk.vtkRenderer() # turn off all cullers ren.GetCullers().RemoveAllItems() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) renWin.SetSize(300, 150) iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin) # create a scene with one of each cell type # Voxel voxelPoints = vtk.vtkPoints() voxelPoints.SetNumberOfPoints(8) voxelPoints.InsertPoint(0, 0, 0, 0) voxelPoints.InsertPoint(1, 1, 0, 0) voxelPoints.InsertPoint(2, 0, 1, 0) voxelPoints.InsertPoint(3, 1, 1, 0) voxelPoints.InsertPoint(4, 0, 0, 1) voxelPoints.InsertPoint(5, 1, 0, 1) voxelPoints.InsertPoint(6, 0, 1, 1) voxelPoints.InsertPoint(7, 1, 1, 1) aVoxel = vtk.vtkVoxel() aVoxel.GetPointIds().SetId(0, 0) aVoxel.GetPointIds().SetId(1, 1) aVoxel.GetPointIds().SetId(2, 2) aVoxel.GetPointIds().SetId(3, 3) aVoxel.GetPointIds().SetId(4, 4) aVoxel.GetPointIds().SetId(5, 5) aVoxel.GetPointIds().SetId(6, 6) aVoxel.GetPointIds().SetId(7, 7) bVoxel = aVoxel.NewInstance() bVoxel.DeepCopy(aVoxel) aVoxelGrid = vtk.vtkUnstructuredGrid() aVoxelGrid.Allocate(1, 1) aVoxelGrid.InsertNextCell(aVoxel.GetCellType(), aVoxel.GetPointIds()) aVoxelGrid.SetPoints(voxelPoints) aVoxelMapper = vtk.vtkDataSetMapper() aVoxelMapper.SetInputData(aVoxelGrid) aVoxelActor = vtk.vtkActor() aVoxelActor.SetMapper(aVoxelMapper) aVoxelActor.GetProperty().BackfaceCullingOn() # Hexahedron hexahedronPoints = vtk.vtkPoints() hexahedronPoints.SetNumberOfPoints(8) hexahedronPoints.InsertPoint(0, 0, 0, 0) hexahedronPoints.InsertPoint(1, 1, 0, 0) hexahedronPoints.InsertPoint(2, 1, 1, 0) hexahedronPoints.InsertPoint(3, 0, 1, 0) hexahedronPoints.InsertPoint(4, 0, 0, 1) hexahedronPoints.InsertPoint(5, 1, 0, 1) hexahedronPoints.InsertPoint(6, 1, 1, 1) hexahedronPoints.InsertPoint(7, 0, 1, 1) aHexahedron = vtk.vtkHexahedron() aHexahedron.GetPointIds().SetId(0, 0) aHexahedron.GetPointIds().SetId(1, 1) aHexahedron.GetPointIds().SetId(2, 2) aHexahedron.GetPointIds().SetId(3, 3) aHexahedron.GetPointIds().SetId(4, 4) aHexahedron.GetPointIds().SetId(5, 5) aHexahedron.GetPointIds().SetId(6, 6) aHexahedron.GetPointIds().SetId(7, 7) bHexahedron = aHexahedron.NewInstance() bHexahedron.DeepCopy(aHexahedron) aHexahedronGrid = vtk.vtkUnstructuredGrid() aHexahedronGrid.Allocate(1, 1) aHexahedronGrid.InsertNextCell(aHexahedron.GetCellType(), aHexahedron.GetPointIds()) aHexahedronGrid.SetPoints(hexahedronPoints) aHexahedronMapper = vtk.vtkDataSetMapper() aHexahedronMapper.SetInputData(aHexahedronGrid) aHexahedronActor = vtk.vtkActor() aHexahedronActor.SetMapper(aHexahedronMapper) aHexahedronActor.AddPosition(2, 0, 0) aHexahedronActor.GetProperty().BackfaceCullingOn() # Tetra tetraPoints = vtk.vtkPoints() tetraPoints.SetNumberOfPoints(4) tetraPoints.InsertPoint(0, 0, 0, 0) tetraPoints.InsertPoint(1, 1, 0, 0) tetraPoints.InsertPoint(2, .5, 1, 0) tetraPoints.InsertPoint(3, .5, .5, 1) aTetra = vtk.vtkTetra() aTetra.GetPointIds().SetId(0, 0) aTetra.GetPointIds().SetId(1, 1) aTetra.GetPointIds().SetId(2, 2) aTetra.GetPointIds().SetId(3, 3) bTetra = aTetra.NewInstance() bTetra.DeepCopy(aTetra) aTetraGrid = vtk.vtkUnstructuredGrid() aTetraGrid.Allocate(1, 1) aTetraGrid.InsertNextCell(aTetra.GetCellType(), aTetra.GetPointIds()) aTetraGrid.SetPoints(tetraPoints) aTetraCopy = vtk.vtkUnstructuredGrid() aTetraCopy.ShallowCopy(aTetraGrid) aTetraMapper = vtk.vtkDataSetMapper() aTetraMapper.SetInputData(aTetraCopy) aTetraActor = vtk.vtkActor() aTetraActor.SetMapper(aTetraMapper) aTetraActor.AddPosition(4, 0, 0) aTetraActor.GetProperty().BackfaceCullingOn() # Wedge wedgePoints = vtk.vtkPoints() wedgePoints.SetNumberOfPoints(6) wedgePoints.InsertPoint(0, 0, 1, 0) wedgePoints.InsertPoint(1, 0, 0, 0) wedgePoints.InsertPoint(2, 0, .5, .5) wedgePoints.InsertPoint(3, 1, 1, 0) wedgePoints.InsertPoint(4, 1, 0, 0) wedgePoints.InsertPoint(5, 1, .5, .5) aWedge = vtk.vtkWedge() aWedge.GetPointIds().SetId(0, 0) aWedge.GetPointIds().SetId(1, 1) aWedge.GetPointIds().SetId(2, 2) aWedge.GetPointIds().SetId(3, 3) aWedge.GetPointIds().SetId(4, 4) aWedge.GetPointIds().SetId(5, 5) bWedge = aWedge.NewInstance() bWedge.DeepCopy(aWedge) aWedgeGrid = vtk.vtkUnstructuredGrid() aWedgeGrid.Allocate(1, 1) aWedgeGrid.InsertNextCell(aWedge.GetCellType(), aWedge.GetPointIds()) aWedgeGrid.SetPoints(wedgePoints) aWedgeCopy = vtk.vtkUnstructuredGrid() aWedgeCopy.DeepCopy(aWedgeGrid) aWedgeMapper = vtk.vtkDataSetMapper() aWedgeMapper.SetInputData(aWedgeCopy) aWedgeActor = vtk.vtkActor() aWedgeActor.SetMapper(aWedgeMapper) aWedgeActor.AddPosition(6, 0, 0) aWedgeActor.GetProperty().BackfaceCullingOn() # Pyramid pyramidPoints = vtk.vtkPoints() pyramidPoints.SetNumberOfPoints(5) pyramidPoints.InsertPoint(0, 0, 0, 0) pyramidPoints.InsertPoint(1, 1, 0, 0) pyramidPoints.InsertPoint(2, 1, 1, 0) pyramidPoints.InsertPoint(3, 0, 1, 0) pyramidPoints.InsertPoint(4, .5, .5, 1) aPyramid = vtk.vtkPyramid() aPyramid.GetPointIds().SetId(0, 0) aPyramid.GetPointIds().SetId(1, 1) aPyramid.GetPointIds().SetId(2, 2) aPyramid.GetPointIds().SetId(3, 3) aPyramid.GetPointIds().SetId(4, 4) bPyramid = aPyramid.NewInstance() bPyramid.DeepCopy(aPyramid) aPyramidGrid = vtk.vtkUnstructuredGrid() aPyramidGrid.Allocate(1, 1) aPyramidGrid.InsertNextCell(aPyramid.GetCellType(), aPyramid.GetPointIds()) aPyramidGrid.SetPoints(pyramidPoints) aPyramidMapper = vtk.vtkDataSetMapper() aPyramidMapper.SetInputData(aPyramidGrid) aPyramidActor = vtk.vtkActor() aPyramidActor.SetMapper(aPyramidMapper) aPyramidActor.AddPosition(8, 0, 0) aPyramidActor.GetProperty().BackfaceCullingOn() # Pixel pixelPoints = vtk.vtkPoints() pixelPoints.SetNumberOfPoints(4) pixelPoints.InsertPoint(0, 0, 0, 0) pixelPoints.InsertPoint(1, 1, 0, 0) pixelPoints.InsertPoint(2, 0, 1, 0) pixelPoints.InsertPoint(3, 1, 1, 0) aPixel = vtk.vtkPixel() aPixel.GetPointIds().SetId(0, 0) aPixel.GetPointIds().SetId(1, 1) aPixel.GetPointIds().SetId(2, 2) aPixel.GetPointIds().SetId(3, 3) bPixel = aPixel.NewInstance() bPixel.DeepCopy(aPixel) aPixelGrid = vtk.vtkUnstructuredGrid() aPixelGrid.Allocate(1, 1) aPixelGrid.InsertNextCell(aPixel.GetCellType(), aPixel.GetPointIds()) aPixelGrid.SetPoints(pixelPoints) aPixelMapper = vtk.vtkDataSetMapper() aPixelMapper.SetInputData(aPixelGrid) aPixelActor = vtk.vtkActor() aPixelActor.SetMapper(aPixelMapper) aPixelActor.AddPosition(0, 0, 2) aPixelActor.GetProperty().BackfaceCullingOn() # Quad quadPoints = vtk.vtkPoints() quadPoints.SetNumberOfPoints(4) quadPoints.InsertPoint(0, 0, 0, 0) quadPoints.InsertPoint(1, 1, 0, 0) quadPoints.InsertPoint(2, 1, 1, 0) quadPoints.InsertPoint(3, 0, 1, 0) aQuad = vtk.vtkQuad() aQuad.GetPointIds().SetId(0, 0) aQuad.GetPointIds().SetId(1, 1) aQuad.GetPointIds().SetId(2, 2) aQuad.GetPointIds().SetId(3, 3) bQuad = aQuad.NewInstance() bQuad.DeepCopy(aQuad) aQuadGrid = vtk.vtkUnstructuredGrid() aQuadGrid.Allocate(1, 1) aQuadGrid.InsertNextCell(aQuad.GetCellType(), aQuad.GetPointIds()) aQuadGrid.SetPoints(quadPoints) aQuadMapper = vtk.vtkDataSetMapper() aQuadMapper.SetInputData(aQuadGrid) aQuadActor = vtk.vtkActor() aQuadActor.SetMapper(aQuadMapper) aQuadActor.AddPosition(2, 0, 2) aQuadActor.GetProperty().BackfaceCullingOn() # Triangle trianglePoints = vtk.vtkPoints() trianglePoints.SetNumberOfPoints(3) trianglePoints.InsertPoint(0, 0, 0, 0) trianglePoints.InsertPoint(1, 1, 0, 0) trianglePoints.InsertPoint(2, .5, .5, 0) triangleTCoords = vtk.vtkFloatArray() triangleTCoords.SetNumberOfComponents(2) triangleTCoords.SetNumberOfTuples(3) triangleTCoords.InsertTuple2(0, 1, 1) triangleTCoords.InsertTuple2(1, 2, 2) triangleTCoords.InsertTuple2(2, 3, 3) aTriangle = vtk.vtkTriangle() aTriangle.GetPointIds().SetId(0, 0) aTriangle.GetPointIds().SetId(1, 1) aTriangle.GetPointIds().SetId(2, 2) bTriangle = aTriangle.NewInstance() bTriangle.DeepCopy(aTriangle) aTriangleGrid = vtk.vtkUnstructuredGrid() aTriangleGrid.Allocate(1, 1) aTriangleGrid.InsertNextCell(aTriangle.GetCellType(), aTriangle.GetPointIds()) aTriangleGrid.SetPoints(trianglePoints) aTriangleGrid.GetPointData().SetTCoords(triangleTCoords) aTriangleMapper = vtk.vtkDataSetMapper() aTriangleMapper.SetInputData(aTriangleGrid) aTriangleActor = vtk.vtkActor() aTriangleActor.SetMapper(aTriangleMapper) aTriangleActor.AddPosition(4, 0, 2) aTriangleActor.GetProperty().BackfaceCullingOn() # Polygon polygonPoints = vtk.vtkPoints() polygonPoints.SetNumberOfPoints(4) polygonPoints.InsertPoint(0, 0, 0, 0) polygonPoints.InsertPoint(1, 1, 0, 0) polygonPoints.InsertPoint(2, 1, 1, 0) polygonPoints.InsertPoint(3, 0, 1, 0) aPolygon = vtk.vtkPolygon() aPolygon.GetPointIds().SetNumberOfIds(4) aPolygon.GetPointIds().SetId(0, 0) aPolygon.GetPointIds().SetId(1, 1) aPolygon.GetPointIds().SetId(2, 2) aPolygon.GetPointIds().SetId(3, 3) bPolygon = aPolygon.NewInstance() bPolygon.DeepCopy(aPolygon) aPolygonGrid = vtk.vtkUnstructuredGrid() aPolygonGrid.Allocate(1, 1) aPolygonGrid.InsertNextCell(aPolygon.GetCellType(), aPolygon.GetPointIds()) aPolygonGrid.SetPoints(polygonPoints) aPolygonMapper = vtk.vtkDataSetMapper() aPolygonMapper.SetInputData(aPolygonGrid) aPolygonActor = vtk.vtkActor() aPolygonActor.SetMapper(aPolygonMapper) aPolygonActor.AddPosition(6, 0, 2) aPolygonActor.GetProperty().BackfaceCullingOn() # Triangle Strip triangleStripPoints = vtk.vtkPoints() triangleStripPoints.SetNumberOfPoints(5) triangleStripPoints.InsertPoint(0, 0, 1, 0) triangleStripPoints.InsertPoint(1, 0, 0, 0) triangleStripPoints.InsertPoint(2, 1, 1, 0) triangleStripPoints.InsertPoint(3, 1, 0, 0) triangleStripPoints.InsertPoint(4, 2, 1, 0) triangleStripTCoords = vtk.vtkFloatArray() triangleStripTCoords.SetNumberOfComponents(2) triangleStripTCoords.SetNumberOfTuples(3) triangleStripTCoords.InsertTuple2(0, 1, 1) triangleStripTCoords.InsertTuple2(1, 2, 2) triangleStripTCoords.InsertTuple2(2, 3, 3) triangleStripTCoords.InsertTuple2(3, 4, 4) triangleStripTCoords.InsertTuple2(4, 5, 5) aTriangleStrip = vtk.vtkTriangleStrip() aTriangleStrip.GetPointIds().SetNumberOfIds(5) aTriangleStrip.GetPointIds().SetId(0, 0) aTriangleStrip.GetPointIds().SetId(1, 1) aTriangleStrip.GetPointIds().SetId(2, 2) aTriangleStrip.GetPointIds().SetId(3, 3) aTriangleStrip.GetPointIds().SetId(4, 4) bTriangleStrip = aTriangleStrip.NewInstance() bTriangleStrip.DeepCopy(aTriangleStrip) aTriangleStripGrid = vtk.vtkUnstructuredGrid() aTriangleStripGrid.Allocate(1, 1) aTriangleStripGrid.InsertNextCell(aTriangleStrip.GetCellType(), aTriangleStrip.GetPointIds()) aTriangleStripGrid.SetPoints(triangleStripPoints) aTriangleStripGrid.GetPointData().SetTCoords(triangleStripTCoords) aTriangleStripMapper = vtk.vtkDataSetMapper() aTriangleStripMapper.SetInputData(aTriangleStripGrid) aTriangleStripActor = vtk.vtkActor() aTriangleStripActor.SetMapper(aTriangleStripMapper) aTriangleStripActor.AddPosition(8, 0, 2) aTriangleStripActor.GetProperty().BackfaceCullingOn() # Line linePoints = vtk.vtkPoints() linePoints.SetNumberOfPoints(2) linePoints.InsertPoint(0, 0, 0, 0) linePoints.InsertPoint(1, 1, 1, 0) aLine = vtk.vtkLine() aLine.GetPointIds().SetId(0, 0) aLine.GetPointIds().SetId(1, 1) bLine = aLine.NewInstance() bLine.DeepCopy(aLine) aLineGrid = vtk.vtkUnstructuredGrid() aLineGrid.Allocate(1, 1) aLineGrid.InsertNextCell(aLine.GetCellType(), aLine.GetPointIds()) aLineGrid.SetPoints(linePoints) aLineMapper = vtk.vtkDataSetMapper() aLineMapper.SetInputData(aLineGrid) aLineActor = vtk.vtkActor() aLineActor.SetMapper(aLineMapper) aLineActor.AddPosition(0, 0, 4) aLineActor.GetProperty().BackfaceCullingOn() # Poly line polyLinePoints = vtk.vtkPoints() polyLinePoints.SetNumberOfPoints(3) polyLinePoints.InsertPoint(0, 0, 0, 0) polyLinePoints.InsertPoint(1, 1, 1, 0) polyLinePoints.InsertPoint(2, 1, 0, 0) aPolyLine = vtk.vtkPolyLine() aPolyLine.GetPointIds().SetNumberOfIds(3) aPolyLine.GetPointIds().SetId(0, 0) aPolyLine.GetPointIds().SetId(1, 1) aPolyLine.GetPointIds().SetId(2, 2) bPolyLine = aPolyLine.NewInstance() bPolyLine.DeepCopy(aPolyLine) aPolyLineGrid = vtk.vtkUnstructuredGrid() aPolyLineGrid.Allocate(1, 1) aPolyLineGrid.InsertNextCell(aPolyLine.GetCellType(), aPolyLine.GetPointIds()) aPolyLineGrid.SetPoints(polyLinePoints) aPolyLineMapper = vtk.vtkDataSetMapper() aPolyLineMapper.SetInputData(aPolyLineGrid) aPolyLineActor = vtk.vtkActor() aPolyLineActor.SetMapper(aPolyLineMapper) aPolyLineActor.AddPosition(2, 0, 4) aPolyLineActor.GetProperty().BackfaceCullingOn() # Vertex vertexPoints = vtk.vtkPoints() vertexPoints.SetNumberOfPoints(1) vertexPoints.InsertPoint(0, 0, 0, 0) aVertex = vtk.vtkVertex() aVertex.GetPointIds().SetId(0, 0) bVertex = aVertex.NewInstance() bVertex.DeepCopy(aVertex) aVertexGrid = vtk.vtkUnstructuredGrid() aVertexGrid.Allocate(1, 1) aVertexGrid.InsertNextCell(aVertex.GetCellType(), aVertex.GetPointIds()) aVertexGrid.SetPoints(vertexPoints) aVertexMapper = vtk.vtkDataSetMapper() aVertexMapper.SetInputData(aVertexGrid) aVertexActor = vtk.vtkActor() aVertexActor.SetMapper(aVertexMapper) aVertexActor.AddPosition(0, 0, 6) aVertexActor.GetProperty().BackfaceCullingOn() # Poly Vertex polyVertexPoints = vtk.vtkPoints() polyVertexPoints.SetNumberOfPoints(3) polyVertexPoints.InsertPoint(0, 0, 0, 0) polyVertexPoints.InsertPoint(1, 1, 0, 0) polyVertexPoints.InsertPoint(2, 1, 1, 0) aPolyVertex = vtk.vtkPolyVertex() aPolyVertex.GetPointIds().SetNumberOfIds(3) aPolyVertex.GetPointIds().SetId(0, 0) aPolyVertex.GetPointIds().SetId(1, 1) aPolyVertex.GetPointIds().SetId(2, 2) bPolyVertex = aPolyVertex.NewInstance() bPolyVertex.DeepCopy(aPolyVertex) aPolyVertexGrid = vtk.vtkUnstructuredGrid() aPolyVertexGrid.Allocate(1, 1) aPolyVertexGrid.InsertNextCell(aPolyVertex.GetCellType(), aPolyVertex.GetPointIds()) aPolyVertexGrid.SetPoints(polyVertexPoints) aPolyVertexMapper = vtk.vtkDataSetMapper() aPolyVertexMapper.SetInputData(aPolyVertexGrid) aPolyVertexActor = vtk.vtkActor() aPolyVertexActor.SetMapper(aPolyVertexMapper) aPolyVertexActor.AddPosition(2, 0, 6) aPolyVertexActor.GetProperty().BackfaceCullingOn() # Pentagonal prism pentaPoints = vtk.vtkPoints() pentaPoints.SetNumberOfPoints(10) pentaPoints.InsertPoint(0, 0.25, 0.0, 0.0) pentaPoints.InsertPoint(1, 0.75, 0.0, 0.0) pentaPoints.InsertPoint(2, 1.0, 0.5, 0.0) pentaPoints.InsertPoint(3, 0.5, 1.0, 0.0) pentaPoints.InsertPoint(4, 0.0, 0.5, 0.0) pentaPoints.InsertPoint(5, 0.25, 0.0, 1.0) pentaPoints.InsertPoint(6, 0.75, 0.0, 1.0) pentaPoints.InsertPoint(7, 1.0, 0.5, 1.0) pentaPoints.InsertPoint(8, 0.5, 1.0, 1.0) pentaPoints.InsertPoint(9, 0.0, 0.5, 1.0) aPenta = vtk.vtkPentagonalPrism() aPenta.GetPointIds().SetId(0, 0) aPenta.GetPointIds().SetId(1, 1) aPenta.GetPointIds().SetId(2, 2) aPenta.GetPointIds().SetId(3, 3) aPenta.GetPointIds().SetId(4, 4) aPenta.GetPointIds().SetId(5, 5) aPenta.GetPointIds().SetId(6, 6) aPenta.GetPointIds().SetId(7, 7) aPenta.GetPointIds().SetId(8, 8) aPenta.GetPointIds().SetId(9, 9) bPenta = aPenta.NewInstance() bPenta.DeepCopy(aPenta) aPentaGrid = vtk.vtkUnstructuredGrid() aPentaGrid.Allocate(1, 1) aPentaGrid.InsertNextCell(aPenta.GetCellType(), aPenta.GetPointIds()) aPentaGrid.SetPoints(pentaPoints) aPentaCopy = vtk.vtkUnstructuredGrid() aPentaCopy.DeepCopy(aPentaGrid) aPentaMapper = vtk.vtkDataSetMapper() aPentaMapper.SetInputData(aPentaCopy) aPentaActor = vtk.vtkActor() aPentaActor.SetMapper(aPentaMapper) aPentaActor.AddPosition(10, 0, 0) aPentaActor.GetProperty().BackfaceCullingOn() # Hexagonal prism hexaPoints = vtk.vtkPoints() hexaPoints.SetNumberOfPoints(12) hexaPoints.InsertPoint(0, 0.0, 0.0, 0.0) hexaPoints.InsertPoint(1, 0.5, 0.0, 0.0) hexaPoints.InsertPoint(2, 1.0, 0.5, 0.0) hexaPoints.InsertPoint(3, 1.0, 1.0, 0.0) hexaPoints.InsertPoint(4, 0.5, 1.0, 0.0) hexaPoints.InsertPoint(5, 0.0, 0.5, 0.0) hexaPoints.InsertPoint(6, 0.0, 0.0, 1.0) hexaPoints.InsertPoint(7, 0.5, 0.0, 1.0) hexaPoints.InsertPoint(8, 1.0, 0.5, 1.0) hexaPoints.InsertPoint(9, 1.0, 1.0, 1.0) hexaPoints.InsertPoint(10, 0.5, 1.0, 1.0) hexaPoints.InsertPoint(11, 0.0, 0.5, 1.0) aHexa = vtk.vtkHexagonalPrism() aHexa.GetPointIds().SetId(0, 0) aHexa.GetPointIds().SetId(1, 1) aHexa.GetPointIds().SetId(2, 2) aHexa.GetPointIds().SetId(3, 3) aHexa.GetPointIds().SetId(4, 4) aHexa.GetPointIds().SetId(5, 5) aHexa.GetPointIds().SetId(6, 6) aHexa.GetPointIds().SetId(7, 7) aHexa.GetPointIds().SetId(8, 8) aHexa.GetPointIds().SetId(9, 9) aHexa.GetPointIds().SetId(10, 10) aHexa.GetPointIds().SetId(11, 11) bHexa = aHexa.NewInstance() bHexa.DeepCopy(aHexa) aHexaGrid = vtk.vtkUnstructuredGrid() aHexaGrid.Allocate(1, 1) aHexaGrid.InsertNextCell(aHexa.GetCellType(), aHexa.GetPointIds()) aHexaGrid.SetPoints(hexaPoints) aHexaCopy = vtk.vtkUnstructuredGrid() aHexaCopy.DeepCopy(aHexaGrid) aHexaMapper = vtk.vtkDataSetMapper() aHexaMapper.SetInputData(aHexaCopy) aHexaActor = vtk.vtkActor() aHexaActor.SetMapper(aHexaMapper) aHexaActor.AddPosition(12, 0, 0) aHexaActor.GetProperty().BackfaceCullingOn() # RIB property aRIBProperty = vtk.vtkRIBProperty() aRIBProperty.SetVariable("Km", "float") aRIBProperty.SetSurfaceShader("LGVeinedmarble") aRIBProperty.SetVariable("veinfreq", "float") aRIBProperty.AddVariable("warpfreq", "float") aRIBProperty.AddVariable("veincolor", "color") aRIBProperty.AddParameter("veinfreq", " 2") aRIBProperty.AddParameter("veincolor", "1.0000 1.0000 0.9412") bRIBProperty = vtk.vtkRIBProperty() bRIBProperty.SetVariable("Km", "float") bRIBProperty.SetParameter("Km", "1.0") bRIBProperty.SetDisplacementShader("dented") bRIBProperty.SetSurfaceShader("plastic") aProperty = vtk.vtkProperty() bProperty = vtk.vtkProperty() aTriangleActor.SetProperty(aProperty) aTriangleStripActor.SetProperty(bProperty) ren.SetBackground(.1, .2, .4) ren.AddActor(aVoxelActor) aVoxelActor.GetProperty().SetDiffuseColor(1, 0, 0) ren.AddActor(aHexahedronActor) aHexahedronActor.GetProperty().SetDiffuseColor(1, 1, 0) ren.AddActor(aTetraActor) aTetraActor.GetProperty().SetDiffuseColor(0, 1, 0) ren.AddActor(aWedgeActor) aWedgeActor.GetProperty().SetDiffuseColor(0, 1, 1) ren.AddActor(aPyramidActor) aPyramidActor.GetProperty().SetDiffuseColor(1, 0, 1) ren.AddActor(aPixelActor) aPixelActor.GetProperty().SetDiffuseColor(0, 1, 1) ren.AddActor(aQuadActor) aQuadActor.GetProperty().SetDiffuseColor(1, 0, 1) ren.AddActor(aTriangleActor) aTriangleActor.GetProperty().SetDiffuseColor(.3, 1, .5) ren.AddActor(aPolygonActor) aPolygonActor.GetProperty().SetDiffuseColor(1, .4, .5) ren.AddActor(aTriangleStripActor) aTriangleStripActor.GetProperty().SetDiffuseColor(.3, .7, 1) ren.AddActor(aLineActor) aLineActor.GetProperty().SetDiffuseColor(.2, 1, 1) ren.AddActor(aPolyLineActor) aPolyLineActor.GetProperty().SetDiffuseColor(1, 1, 1) ren.AddActor(aVertexActor) aVertexActor.GetProperty().SetDiffuseColor(1, 1, 1) ren.AddActor(aPolyVertexActor) aPolyVertexActor.GetProperty().SetDiffuseColor(1, 1, 1) ren.AddActor(aPentaActor) aPentaActor.GetProperty().SetDiffuseColor(.2, .4, .7) ren.AddActor(aHexaActor) aHexaActor.GetProperty().SetDiffuseColor(.7, .5, 1) aRIBLight = vtk.vtkRIBLight() aRIBLight.ShadowsOn() aLight = vtk.vtkLight() aLight.PositionalOn() aLight.SetConeAngle(25) ren.AddLight(aLight) ren.ResetCamera() ren.GetActiveCamera().Azimuth(30) ren.GetActiveCamera().Elevation(20) ren.GetActiveCamera().Dolly(2.8) ren.ResetCameraClippingRange() aLight.SetFocalPoint(ren.GetActiveCamera().GetFocalPoint()) aLight.SetPosition(ren.GetActiveCamera().GetPosition()) # write to the temp directory if possible, otherwise use . dir = tempfile.gettempdir() atext = vtk.vtkTexture() pnmReader = vtk.vtkBMPReader() pnmReader.SetFileName(VTK_DATA_ROOT + "/Data/masonry.bmp") atext.SetInputConnection(pnmReader.GetOutputPort()) atext.InterpolateOff() aTriangleActor.SetTexture(atext) rib = vtk.vtkRIBExporter() rib.SetInput(renWin) rib.SetFilePrefix(dir + '/cells') rib.SetTexturePrefix(dir + '/cells') rib.Write() os.remove(dir + '/cells.rib') iv = vtk.vtkIVExporter() iv.SetInput(renWin) iv.SetFileName(dir + "/cells.iv") iv.Write() os.remove(dir + '/cells.iv') obj = vtk.vtkOBJExporter() obj.SetInput(renWin) obj.SetFilePrefix(dir + "/cells") obj.Write() os.remove(dir + '/cells.obj') os.remove(dir + '/cells.mtl') vrml = vtk.vtkVRMLExporter() vrml.SetInput(renWin) #vrml.SetStartWrite(vrml.SetFileName(dir + "/cells.wrl")) #vrml.SetEndWrite(vrml.SetFileName("/a/acells.wrl")) vrml.SetFileName(dir + "/cells.wrl") vrml.SetSpeed(5.5) vrml.Write() os.remove(dir + '/cells.wrl') oogl = vtk.vtkOOGLExporter() oogl.SetInput(renWin) oogl.SetFileName(dir + "/cells.oogl") oogl.Write() os.remove(dir + '/cells.oogl') # the UnRegister calls are because make object is the same as New, # and causes memory leaks. (Python does not treat NewInstance the same as New). def DeleteCopies(): bVoxel.UnRegister(None) bHexahedron.UnRegister(None) bTetra.UnRegister(None) bWedge.UnRegister(None) bPyramid.UnRegister(None) bPixel.UnRegister(None) bQuad.UnRegister(None) bTriangle.UnRegister(None) bPolygon.UnRegister(None) bTriangleStrip.UnRegister(None) bLine.UnRegister(None) bPolyLine.UnRegister(None) bVertex.UnRegister(None) bPolyVertex.UnRegister(None) bPenta.UnRegister(None) bHexa.UnRegister(None) DeleteCopies() # render and interact with data renWin.Render() img_file = "cells.png" vtk.test.Testing.compareImage( iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25) vtk.test.Testing.interact()
import vtk from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() tetraPoints = vtk.vtkPoints() tetraPoints.SetNumberOfPoints(4) tetraPoints.InsertPoint(0, 0, 0, 0) tetraPoints.InsertPoint(1, 1, 0, 0) tetraPoints.InsertPoint(2, .5, 1, 0) tetraPoints.InsertPoint(3, .5, .5, 1) aTetra = vtk.vtkTetra() aTetra.GetPointIds().SetId(0, 0) aTetra.GetPointIds().SetId(1, 1) aTetra.GetPointIds().SetId(2, 2) aTetra.GetPointIds().SetId(3, 3) aTetraGrid = vtk.vtkUnstructuredGrid() aTetraGrid.Allocate(1, 1) aTetraGrid.InsertNextCell(aTetra.GetCellType(), aTetra.GetPointIds()) aTetraGrid.SetPoints(tetraPoints) sub = vtk.vtkSubdivideTetra() sub.SetInputData(aTetraGrid) shrinker = vtk.vtkShrinkFilter() shrinker.SetInputConnection(sub.GetOutputPort()) mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(shrinker.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(0.7400, 0.9900, 0.7900) # define graphics stuff ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow()
sizes.SetNumberOfComponents(1) sizes.SetNumberOfTuples(3) sizes.SetValue(0, 1) sizes.SetValue(1, 2) sizes.SetValue(2, 3) polyVertexPoints = vtk.vtkPoints() polyVertexPoints.SetNumberOfPoints(3) polyVertexPoints.InsertPoint(0, 0.0, 0.0, 0.0) polyVertexPoints.InsertPoint(1, 2.5, 0.0, 0.0) polyVertexPoints.InsertPoint(2, 5.0, 0.0, 0.0) aPolyVertex = vtk.vtkPolyVertex() aPolyVertex.GetPointIds().SetNumberOfIds(3) aPolyVertex.GetPointIds().SetId(0, 0) aPolyVertex.GetPointIds().SetId(1, 1) aPolyVertex.GetPointIds().SetId(2, 2) aPolyVertexGrid = vtk.vtkUnstructuredGrid() aPolyVertexGrid.Allocate(1, 1) aPolyVertexGrid.InsertNextCell(aPolyVertex.GetCellType(), aPolyVertex.GetPointIds()) aPolyVertexGrid.SetPoints(polyVertexPoints) aPolyVertexGrid.GetPointData().SetScalars(sizes) aPolyVertexGrid.GetPointData().AddArray(colors) sphere = vtk.vtkSphereSource() sphere.SetRadius(1.0) sphere.Update() glyphs = vtk.vtkGlyph3D() glyphs.ScalingOn() glyphs.SetColorModeToColorByScalar() glyphs.SetScaleModeToScaleByScalar() glyphs.SetScaleFactor(1) glyphs.SetInputData(aPolyVertexGrid)
def meshgrid_slice(meshgrid, x0, x1, y0, y1, main): #Data Parameter ndata = len(meshgrid[:, 0]) nx = len(np.unique(meshgrid[:, 0])) ny = len(np.unique(meshgrid[:, 1])) nz = int(ndata / nx / ny) minx = min(meshgrid[:, 0]) miny = min(meshgrid[:, 1]) delx = meshgrid[nz, 0] - meshgrid[nz - 1, 0] dely = meshgrid[nz * nx, 1] - meshgrid[nz * nx - 1, 1] #Mesh Creation d = (delx + dely) / 2 r = ((x1 - x0)**2 + (y1 - y0)**2)**0.5 dr = r / (int(r / d)) mesh = np.zeros((4, 4)) nsec = int(r / d) + 1 section = np.zeros((nsec * nz, 4)) for i in range(nsec): x = x0 + dr * i * (x1 - x0) / r y = y0 + dr * i * (y1 - y0) / r nmx = int((x0 + d * i * (x1 - x0) / r - minx) / delx) nmy = int((y0 + d * i * (y1 - y0) / r - miny) / dely) #--Interpolasi Liniar for h in range(nz): section[i * nz + h, 0] = x section[i * nz + h, 1] = y #Neighbors mesh[0, :] = meshgrid[(nx * (nmy + 0) + nmx + 0) * nz + h, :] mesh[1, :] = meshgrid[(nx * (nmy + 0) + nmx + 1) * nz + h, :] mesh[2, :] = meshgrid[(nx * (nmy + 1) + nmx + 0) * nz + h, :] mesh[3, :] = meshgrid[(nx * (nmy + 1) + nmx + 1) * nz + h, :] #Elevation Interpolation a0 = ((mesh[1, 2] - mesh[0, 2]) / (mesh[1, 0] - mesh[0, 0]) * (section[i * nz + h, 0] - mesh[0, 0])) + mesh[0, 2] b0 = ((mesh[3, 2] - mesh[2, 2]) / (mesh[3, 0] - mesh[2, 0]) * (section[i * nz + h, 0] - mesh[2, 0])) + mesh[2, 2] section[i * nz + h, 2] = ((b0 - a0) / (mesh[2, 1] - mesh[0, 1]) * (section[i * nz + h, 1] - mesh[0, 1])) + a0 a0 = ((mesh[1, 3] - mesh[0, 3]) / (mesh[1, 0] - mesh[0, 0]) * (section[i * nz + h, 0] - mesh[0, 0])) + mesh[0, 3] b0 = ((mesh[3, 3] - mesh[2, 3]) / (mesh[3, 0] - mesh[2, 0]) * (section[i * nz + h, 0] - mesh[2, 0])) + mesh[2, 3] section[i * nz + h, 3] = np.log10(((b0 - a0) / (mesh[2, 1] - mesh[0, 1]) * (section[i * nz + h, 1] - mesh[0, 1])) + a0) #--Creating Vtk Object #Create Polygon points = vtk.vtkPoints() mesh = vtk.vtkUnstructuredGrid() scalar = vtk.vtkDoubleArray() #Filling Points for i in range(nsec * nz): points.InsertNextPoint(section[i, 0], section[i, 1], section[i, 2]) #Insert Cells quad = vtk.vtkQuad() for i in range(nsec - 1): for h in range(nz - 1): quad.GetPointIds().SetId(0, nz * i + 0) quad.GetPointIds().SetId(1, nz * i + 1) quad.GetPointIds().SetId(2, nz * (i + 1) + 1) quad.GetPointIds().SetId(3, nz * (i + 1) + 0) mesh.InsertNextCell(quad.GetCellType(), quad.GetPointIds()) #Cell Scalar Value value = (section[nz * i + 0, 3] + section[nz * i + 1, 3] + section[nz * (i + 1) + 1, 3] + section[nz * (i + 1) + 0, 3]) / 4 scalar.InsertNextTuple([np.log10(value) * 0.5]) mesh.SetPoints(points) mesh.GetCellData().SetScalars(scalar) main.mesh_renderer(mesh) return section #point = np.array([[795727, 9197285, 0, 0], [795727, 9197285, 0, 0]]) #data = np.loadtxt("D:\WORK\MODEL_WNI\data\mesh_adj.txt") #a = xyzv_krigging(data, point)
def write_vtk(self, datadir="data", file_name="nulls.vtk", binary=False): """ write_vtk(datadir='data', file_name='nulls.vtk', binary=False) Write the null point into a vtk file. Parameters ---------- datadir : string Target data directory. file_name : string Target file name. binary : bool Write file in binary or ASCII format. """ import os as os try: import vtk as vtk from vtk.util import numpy_support as VN except: print("Warning: no vtk library found.") writer = vtk.vtkUnstructuredGridWriter() if binary: writer.SetFileTypeToBinary() else: writer.SetFileTypeToASCII() writer.SetFileName(os.path.join(datadir, file_name)) grid_data = vtk.vtkUnstructuredGrid() points = vtk.vtkPoints() # Write the null points. for null in self.nulls: points.InsertNextPoint(null) if self.nulls: eigen_values_vtk = [] eigen_values = [] eigen_vectors_vtk = [] eigen_vectors = [] fan_vectors_vtk = [] fan_vectors = [] for dim in range(self.eigen_values.shape[1]): # Write out the eigen values. eigen_values.append(self.eigen_values[:, dim].copy()) eigen_values_vtk.append(VN.numpy_to_vtk(eigen_values[-1])) eigen_values_vtk[-1].SetName("eigen_value_{0}".format(dim)) grid_data.GetPointData().AddArray(eigen_values_vtk[-1]) # Write out the eigen vectors. eigen_vectors.append(self.eigen_vectors[:, dim, :].copy()) eigen_vectors_vtk.append(VN.numpy_to_vtk(eigen_vectors[-1])) eigen_vectors_vtk[-1].SetName("eigen_vector_{0}".format(dim)) grid_data.GetPointData().AddArray(eigen_vectors_vtk[-1]) # Write out the fan vectors.. if dim < self.eigen_values.shape[1] - 1: fan_vectors.append(self.fan_vectors[:, dim, :].copy()) fan_vectors_vtk.append(VN.numpy_to_vtk(fan_vectors[-1])) fan_vectors_vtk[-1].SetName("fan_vector_{0}".format(dim)) grid_data.GetPointData().AddArray(fan_vectors_vtk[-1]) # Write out the sign for the vector field tracing. sign_trace_vtk = VN.numpy_to_vtk(self.sign_trace) sign_trace_vtk.SetName("sign_trace") grid_data.GetPointData().AddArray(sign_trace_vtk) # Write out the fan plane normal. normals_vtk = VN.numpy_to_vtk(self.normals) normals_vtk.SetName("normal") grid_data.GetPointData().AddArray(normals_vtk) grid_data.SetPoints(points) # Ensure compatability between vtk 5 and 6. try: writer.SetInputData(grid_data) except: writer.SetInput(grid_data) writer.Write()