def GetTree(self): """Returns a full vtkTree based on data loaded in LoadData().""" if self.data_loaded: vertex_id = vtk.vtkIdTypeArray() vertex_id.SetName('vertex_ids') for ii in range(len(self.cp)): vertex_id.InsertNextValue(ii) NINvtk = VN.numpy_to_vtk(self.NumberInNet, deep=True) NINvtk.SetName('num_in_vertex') SCALESvtk = VN.numpy_to_vtk(self.Scales, deep=True) SCALESvtk.SetName('scale') # This array will default to empty strings BLANKvtk = vtk.vtkStringArray() BLANKvtk.SetNumberOfComponents(1) BLANKvtk.SetNumberOfTuples(self.NumberInNet.shape[0]) BLANKvtk.SetName('blank') # Build tree out of CP list of "is a child of" # remembering that Matlab indices are 1-based and numpy/VTK 0-based print 'Building graph' dg = vtk.vtkMutableDirectedGraph() edge_id = vtk.vtkIdTypeArray() edge_id.SetName('edge_ids') for ii in range(self.cp.size): dg.AddVertex() for ii in range(self.cp.size): if self.cp[ii] > 0: # CP already zero-based dg.AddGraphEdge(self.cp[ii],ii) # Method for use with wrappers -- AddEdge() in C++ edge_id.InsertNextValue(ii) dg.GetVertexData().AddArray(NINvtk) dg.GetVertexData().AddArray(SCALESvtk) dg.GetVertexData().AddArray(vertex_id) dg.GetVertexData().SetActiveScalars('scale') dg.GetVertexData().SetActivePedigreeIds('vertex_ids') dg.GetEdgeData().AddArray(edge_id) dg.GetEdgeData().SetActivePedigreeIds('edge_ids') tree = vtk.vtkTree() tree.CheckedShallowCopy(dg) return tree else: raise IOError, "Can't get tree until data is loaded successfully"
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 test_id_array(self): """Test if a vtkIdTypeArray is converted correctly.""" arr = vtk.vtkIdTypeArray() arr.SetNumberOfTuples(10) for i in range(10): arr.SetValue(i, i) np = array_handler.vtk2array(arr) self.assertEqual(numpy.all(np == range(10)), True)
def numpy_to_vtkIdTypeArray(num_array, deep=0): isize = vtk.vtkIdTypeArray().GetDataTypeSize() dtype = num_array.dtype if isize == 4: if dtype != numpy.int32: raise ValueError, \ 'Expecting a numpy.int32 array, got %s instead.' % (str(dtype)) else: if dtype != numpy.int64: raise ValueError, \ 'Expecting a numpy.int64 array, got %s instead.' % (str(dtype)) return numpy_to_vtk(num_array, deep, vtkConstants.VTK_ID_TYPE)
def __init__(self, times, slider_repres): self._stimes = set(times) self._opacity = 1.0 self._time_step = (max(self._stimes) - min(self._stimes)) \ / len(self._stimes) self._time = min(times) self._slider_repres = slider_repres self._current_id = vtk.vtkIdTypeArray() self._renderer = renderer self._renderer_window = renderer_window self._times = times self._image_counter = 0 self._recording = False
def WriteTecplotMeshFile(self): if (self.OutputFileName == ''): self.PrintError('Error: no OutputFileName.') self.PrintLog('Writing Tecplot file.') triangleFilter = vtk.vtkDataSetTriangleFilter() triangleFilter.SetInputData(self.Mesh) triangleFilter.Update() self.Mesh = triangleFilter.GetOutput() f=open(self.OutputFileName, 'w') line = "VARIABLES = X,Y,Z" arrayNames = [] for i in range(self.Mesh.GetPointData().GetNumberOfArrays()): array = self.Mesh.GetPointData().GetArray(i) arrayName = array.GetName() if arrayName == None: continue if (arrayName[-1]=='_'): continue arrayNames.append(arrayName) if (array.GetNumberOfComponents() == 1): line = line + ',' + arrayName else: for j in range(array.GetNumberOfComponents()): line = line + ',' + arrayName + str(j) line = line + '\n' f.write(line) tetraCellIdArray = vtk.vtkIdTypeArray() tetraCellType = 10 self.Mesh.GetIdsOfCellsOfType(tetraCellType,tetraCellIdArray) numberOfTetras = tetraCellIdArray.GetNumberOfTuples() line = "ZONE " + "N=" + str(self.Mesh.GetNumberOfPoints()) + ',' + "E=" + str(numberOfTetras) + ',' + "F=FEPOINT" + ',' + "ET=TETRAHEDRON" + '\n' f.write(line) for i in range(self.Mesh.GetNumberOfPoints()): point = self.Mesh.GetPoint(i) line = str(point[0]) + ' ' + str(point[1]) + ' ' + str(point[2]) for arrayName in arrayNames: array = self.Mesh.GetPointData().GetArray(arrayName) for j in range(array.GetNumberOfComponents()): line = line + ' ' + str(array.GetComponent(i,j)) line = line + '\n' f.write(line) for i in range(numberOfTetras): cellPointIds = self.Mesh.GetCell(tetraCellIdArray.GetValue(i)).GetPointIds() line = '' for j in range(cellPointIds.GetNumberOfIds()): if (j>0): line = line + ' ' line = line + str(cellPointIds.GetId(j)+1) line = line + '\n' f.write(line)
def numpy2vtkDataArrayInt(npa): # print npa[1][0] size0, size1 = npa.shape data = vtk.vtkIdTypeArray() data.SetNumberOfComponents(4) # data.SetName("CELLS") for i in range(size0): n0 = int(npa[i, 0]) n1 = int(npa[i, 1]) n2 = int(npa[i, 2]) n3 = int(npa[i, 3]) data.InsertNextTuple4(n0, n1, n2, n3) return data
def build_2d_grid(parent_bit_mask, parent_id, origin, spacing, ndims, chunk_info, grid_desc): if "slice" in grid_desc: return cells_on_slice_planes(parent_bit_mask, parent_id, origin, \ spacing, ndims, chunk_info, grid_desc) ug = vtk.vtkUnstructuredGrid() points = vtk.vtkPoints() for j in range(ndims[1]): j_offset = j*spacing[1] for i in range(ndims[0]): points.InsertNextPoint(origin[0] + i*spacing[0], \ origin[1] + j_offset, \ 0.0) ug.SetPoints(points) quad = vtk.vtkQuad() for j in range(ndims[1]-1): jl_offset = j*ndims[0] ju_offset = (j+1)*ndims[0] for i in range(ndims[0]-1): quad.GetPointIds().SetId(0, i + jl_offset) quad.GetPointIds().SetId(1, i + 1 + jl_offset) quad.GetPointIds().SetId(2, i + 1 + ju_offset) quad.GetPointIds().SetId(3, i + ju_offset) ug.InsertNextCell(quad.GetCellType(), quad.GetPointIds()) gids = vtk.vtkIdTypeArray() gids.SetName("GlobalIds") if parent_id == 0: Dx = grid_desc["create_grid"][1]["Cx"] xc = range(chunk_info["x"][0], chunk_info["x"][1]+1) yc = range(chunk_info["y"][0], chunk_info["y"][1]+1) for j in range(ndims[1]-1): yindex = (yc[j]-1)*Dx for i in range(ndims[0]-1): gids.InsertNextTuple1(xc[i]+yindex) else: for i in range(ug.GetNumberOfCells()): if parent_bit_mask == -1: gids.InsertNextTuple1(parent_id) else: gids.InsertNextTuple1((i+1)*(2**parent_bit_mask) + parent_id) ug.GetCellData().AddArray(gids) ug.GetCellData().SetActiveGlobalIds("GlobalIds") return ug
def trimesh_to_vtk(trimesh): r"""Return a `vtkPolyData` representation of a :map:`TriMesh` instance Parameters ---------- trimesh : :map:`TriMesh` The menpo :map:`TriMesh` object that needs to be converted to a `vtkPolyData` Returns ------- `vtk_mesh` : `vtkPolyData` A VTK mesh representation of the Menpo :map:`TriMesh` data Raises ------ ValueError: If the input trimesh is not 3D. """ import vtk from vtk.util.numpy_support import numpy_to_vtk, numpy_to_vtkIdTypeArray if trimesh.n_dims != 3: raise ValueError("trimesh_to_vtk() only works on 3D TriMesh instances") mesh = vtk.vtkPolyData() points = vtk.vtkPoints() points.SetData(numpy_to_vtk(trimesh.points, deep=1)) mesh.SetPoints(points) cells = vtk.vtkCellArray() # Seemingly, VTK may be compiled as 32 bit or 64 bit. # We need to make sure that we convert the trilist to the correct dtype # based on this. See numpy_to_vtkIdTypeArray() for details. isize = vtk.vtkIdTypeArray().GetDataTypeSize() req_dtype = np.int32 if isize == 4 else np.int64 cells.SetCells( trimesh.n_tris, numpy_to_vtkIdTypeArray( np.hstack((np.ones(trimesh.n_tris)[:, None] * 3, trimesh.trilist)).astype(req_dtype).ravel(), deep=1, ), ) mesh.SetPolys(cells) return mesh
def picker_callback(self,obj,event): extract = vtk.vtkExtractSelectedFrustum() fPlanes=obj.GetFrustum() #collection of planes based on unscaled display #scale frustum to account for the zaspect scaledPlanes=vtk.vtkPlanes() scaledNormals=vtk.vtkDoubleArray() scaledNormals.SetNumberOfComponents(3) scaledNormals.SetNumberOfTuples(6) scaledOrigins=vtk.vtkPoints() for j in range(6): i=fPlanes.GetPlane(j) k=i.GetOrigin() q=i.GetNormal() scaledOrigins.InsertNextPoint(k[0],k[1],k[2]/float(self.Zaspect)) scaledNormals.SetTuple(j,(q[0],q[1],q[2]*float(self.Zaspect))) scaledPlanes.SetNormals(scaledNormals) scaledPlanes.SetPoints(scaledOrigins) extract.SetFrustum(scaledPlanes) extract.SetInputData(self.vtkPntsPolyData) extract.Update() extracted = extract.GetOutput() ids = vtk.vtkIdTypeArray() ids = extracted.GetPointData().GetArray("vtkOriginalPointIds") if ids: #store them in an array for an undo operation self.lastSelectedIds=ids for i in range(ids.GetNumberOfTuples()): #turn them red self.colors.SetTuple(ids.GetValue(i),(255,0,0)) self.bool_pnt[ids.GetValue(i)]=False self.vtkPntsPolyData.GetPointData().SetScalars(self.colors) self.vtkPntsPolyData.Modified() self.ui.vtkWidget.update() #set flag on ui to show that data has been modified self.unsaved_changes=True
def _highlight_picker_node(self, cell_id, grid, node_xyz): """won't handle multiple cell_ids/node_xyz""" point_id = find_point_id_closest_to_xyz(grid, cell_id, node_xyz) ids = vtk.vtkIdTypeArray() ids.SetNumberOfComponents(1) ids.InsertNextValue(point_id) selection_node = vtk.vtkSelectionNode() #selection_node.SetContainingCellsOn() #selection_node.Initialize() selection_node.SetFieldType(vtk.vtkSelectionNode.POINT) selection_node.SetContentType(vtk.vtkSelectionNode.INDICES) selection_node.SetSelectionList(ids) actor = self._highlight_picker_by_selection_node( grid, selection_node, representation='points') return actor
def GetSelection(ids, inverse=False): selNode = vtk.vtkSelectionNode() selNode.SetContentType(vtk.vtkSelectionNode.BLOCKS) idArray = vtk.vtkIdTypeArray() idArray.SetNumberOfTuples(len(ids)) for i in range(len(ids)): idArray.SetValue(i, ids[i]) selNode.SetSelectionList(idArray) if inverse: selNode.GetProperties().Set(vtk.vtkSelectionNode.INVERSE(), 1) sel = vtk.vtkSelection() sel.AddNode(selNode) return sel
def create_vtk_selection_node_by_cell_ids(cell_ids): if isinstance(cell_ids, integer_types): cell_ids = [cell_ids] else: for cell_id in cell_ids: assert isinstance(cell_id, integer_types), type(cell_id) ids = vtk.vtkIdTypeArray() ids.SetNumberOfComponents(1) for cell_id in cell_ids: ids.InsertNextValue(cell_id) selection_node = vtk.vtkSelectionNode() selection_node.SetFieldType(vtk.vtkSelectionNode.CELL) selection_node.SetContentType(vtk.vtkSelectionNode.INDICES) selection_node.SetSelectionList(ids) return selection_node
def setPoints( self, point_data ): self.vtkPoints.SetData( point_data ) ncells = point_data.GetNumberOfTuples() cells = vtk.vtkIdTypeArray() cell_data_array = np.empty( 2*ncells, dtype=np.int64 ) cell_data_array[1:2*ncells:2] = range( ncells ) cell_data_array[0:2*ncells:2] = 1 # cell_data_array = np.array( range( ncells ), dtype=np.int64 ) cells.SetVoidArray( cell_data_array, 2*ncells, 1 ) self.vtkCells.SetCells ( ncells, cells ) # self.vtkCells.InsertNextCell( cell ) # for iCell in range( ncells ): # self.vtkCells.InsertNextCell( 1 ) # self.vtkCells.InsertCellPoint( iCell ) cellData = self.vtkCells.GetData () print " Cell Data:\n %s " % str( [ cellData.GetValue(iCell) for iCell in range(cellData.GetNumberOfTuples())] ) self.vtkCells.Modified() self.vtkPoints.Modified()
def numpy_to_vtkIdTypeArray(num_array, deep=0): """ Notes ----- This was pulled from VTK and modified to eliminate numpy 1.14 warnings. VTK uses a BSD license, so it's OK to do that. """ isize = vtk.vtkIdTypeArray().GetDataTypeSize() dtype = num_array.dtype if isize == 4: if dtype != np.int32: raise ValueError('Expecting a numpy.int32 array, got %s instead.' % (str(dtype))) else: if dtype != np.int64: raise ValueError('Expecting a numpy.int64 array, got %s instead.' % (str(dtype))) return numpy_to_vtk(num_array, deep, vtkConstants.VTK_ID_TYPE)
def readUnstructuredGrid(filename, tets_only=False): extension = os.path.splitext(filename)[1] if extension == ".vtk": reader = vtk.vtkUnstructuredGridReader() reader.SetFileName(filename) reader.Update() #return reader.GetOutput() elif extension == ".vtu": reader = vtk.vtkXMLUnstructuredGridReader() reader.SetFileName(filename) reader.Update() #return reader.GetOutput() else: print("Bad extension: %s", extension) return None if tets_only: # may renumber points! print("reading unstructured grid keeping only tets -> this may result in renumbered points!") # select tets only ug = reader.GetOutput() ids = vtk.vtkIdTypeArray() ids.SetNumberOfComponents(1) for i in range(ug.GetNumberOfCells()): if ug.GetCellType(i) == vtk.VTK_TETRA: ids.InsertNextValue(i) 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, ug) extractSelection.SetInputData(1, selection) extractSelection.Update() return extractSelection.GetOutput() else: return reader.GetOutput()
def create_vtk_selection_node_by_point_ids(point_ids): if isinstance(point_ids, integer_types): point_ids = [point_ids] else: for point_id in point_ids: assert isinstance(point_id, integer_types), type(point_id) ids = vtk.vtkIdTypeArray() ids.SetNumberOfComponents(1) for point_id in point_ids: ids.InsertNextValue(point_id) selection_node = vtk.vtkSelectionNode() #selection_node.SetContainingCellsOn() #selection_node.Initialize() selection_node.SetFieldType(vtk.vtkSelectionNode.POINT) selection_node.SetContentType(vtk.vtkSelectionNode.INDICES) selection_node.SetSelectionList(ids) return selection_node
def trimesh_to_vtk(trimesh): r"""Return a `vtkPolyData` representation of a :map:`TriMesh` instance Parameters ---------- trimesh : :map:`TriMesh` The menpo :map:`TriMesh` object that needs to be converted to a `vtkPolyData` Returns ------- `vtk_mesh` : `vtkPolyData` A VTK mesh representation of the Menpo :map:`TriMesh` data Raises ------ ValueError: If the input trimesh is not 3D. """ import vtk from vtk.util.numpy_support import numpy_to_vtk, numpy_to_vtkIdTypeArray if trimesh.n_dims != 3: raise ValueError('trimesh_to_vtk() only works on 3D TriMesh instances') mesh = vtk.vtkPolyData() points = vtk.vtkPoints() points.SetData(numpy_to_vtk(trimesh.points, deep=1)) mesh.SetPoints(points) cells = vtk.vtkCellArray() # Seemingly, VTK may be compiled as 32 bit or 64 bit. # We need to make sure that we convert the trilist to the correct dtype # based on this. See numpy_to_vtkIdTypeArray() for details. isize = vtk.vtkIdTypeArray().GetDataTypeSize() req_dtype = np.int32 if isize == 4 else np.int64 cells.SetCells(trimesh.n_tris, numpy_to_vtkIdTypeArray( np.hstack((np.ones(trimesh.n_tris)[:, None] * 3, trimesh.trilist)).astype(req_dtype).ravel(), deep=1)) mesh.SetPolys(cells) return mesh
def set_polydata_triangles(polydata, triangles): """Set polydata triangles with a numpy array (ndarrays Nx3 int). Parameters ---------- polydata : vtkPolyData triangles : array (N, 3) triangles, represented as 2D ndarrays (Nx3) """ isize = vtk.vtkIdTypeArray().GetDataTypeSize() req_dtype = np.int32 if isize == 4 else np.int64 vtk_triangles = np.hstack(np.c_[np.ones(len(triangles), dtype=req_dtype) * 3, triangles.astype(req_dtype)]) vtk_triangles = numpy_support.numpy_to_vtkIdTypeArray(vtk_triangles, deep=True) vtk_cells = vtk.vtkCellArray() vtk_cells.SetCells(len(triangles), vtk_triangles) polydata.SetPolys(vtk_cells) return polydata
def set_polydata_triangles(polydata, triangles): """Set polydata triangles with a numpy array (ndarrays Nx3 int). Parameters ---------- polydata : vtkPolyData triangles : array (N, 3) triangles, represented as 2D ndarrays (Nx3) """ vtk_cells = vtk.vtkCellArray() if vtk.vtkVersion.GetVTKMajorVersion() >= 9: vtk_cells = numpy_to_vtk_cells(triangles, is_coords=False) else: isize = vtk.vtkIdTypeArray().GetDataTypeSize() req_dtype = np.int32 if isize == 4 else np.int64 all_triangles =\ np.insert(triangles, 0, 3, axis=1).astype(req_dtype).flatten() vtk_triangles = numpy_support.numpy_to_vtkIdTypeArray(all_triangles, deep=True) vtk_cells.SetCells(len(triangles), vtk_triangles) polydata.SetPolys(vtk_cells) return polydata
xM = data2[:,1].max() ym = data2[:,0].min() yM = data2[:,0].max() N = data2.shape[0] m2 = numpy.ascontiguousarray(numpy.transpose(data2,(0,2,1))) nVertices = m2.shape[-2] m2.resize((m2.shape[0]*m2.shape[1],m2.shape[2])) m2=m2[...,::-1] # here we add dummy levels, might want to reconsider converting "trimData" to "reOrderData" and use actual levels? m3=numpy.concatenate((m2,numpy.zeros((m2.shape[0],1))),axis=1) except Exception,err: # Ok no mesh on file, will do with lat/lon pass if m3 is not None: #Create unstructured grid points vg = vtk.vtkUnstructuredGrid() lst = vtk.vtkIdTypeArray() cells = vtk.vtkCellArray() numberOfCells = N lst.SetNumberOfComponents(nVertices + 1) lst.SetNumberOfTuples(numberOfCells) for i in range(N): tuple = [None] * (nVertices + 1) tuple[0] = nVertices for j in range(nVertices): tuple[j + 1] = i * nVertices + j lst.SetTuple(i, tuple) ## ??? TODO ??? when 3D use CUBE? cells.SetCells(numberOfCells, lst) vg.SetCells(vtk.VTK_POLYGON, cells) else: #Ok a simple structured grid is enough
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()
# Get variables out of Matlab structure print 'Transferring variables from Matlab structures' gW = MatInput['gW'] Data = MatInput['Data'] X = MatInput['X'] # WC = MatInput['WavCoeffs'] # Instead of using WC, which has already been ordered within Matlab WavCoeffsOrig = Data['MatWavCoeffs'][0,0].T # Structures are accessed like this: PROJ = Data['Projections'][0,0] CP = gW['cp'][0,0][0] # CP ends up as 'uint16'... Not sure why 16-bit... # Making a list of numpy arrays because cell array structure is a pain... PIN = [] # Points In Net NIN = [] # Number In Net vertex_id = vtk.vtkIdTypeArray() vertex_id.SetName('vertex_ids') for ii in range(gW['PointsInNet'][0,0].shape[1]): PIN.append(gW['PointsInNet'][0,0][0,ii][0]-1) # 0-based indices NIN.append(gW['PointsInNet'][0,0][0,ii][0].size) vertex_id.InsertNextValue(ii) NINarray = N.array(NIN) NINvtk = VN.numpy_to_vtk(NINarray) NINvtk.SetName('num_in_vertex') SCALESvtk = VN.numpy_to_vtk(gW['Scales'][0,0][0]) SCALESvtk.SetName('scale') # Build tree out of CP list of "is a child of" # remembering that Matlab indices are 1-based and numpy/VTK 0-based print 'Building graph'
def ReducePolyData2D(inPoly, outPoly, closed): """ FIXME """ inPts = inPoly.GetPoints() if inPts is None: return 0 n = inPts.GetNumberOfPoints() if (n < 3): return 0 p0 = inPts.GetPoint(0) p1 = inPts.GetPoint(n-1) minusNth = p0[0] == p1[0] and p0[1] == p1[1] and p0[2] == p1[2] if ( minusNth and closed == 1): n = n - 1 # frenet unit tangent vector and state of kappa (zero or non-zero) f = n*[frenet((0.0,0.0,0.0), False)] # calculate the tangent vector by forward differences for i in range(n): p0 = inPts.GetPoint(i) p1 = inPts.GetPoint( ( i + 1 ) % n) tL = math.sqrt(vtk.vtkMath.Distance2BetweenPoints( p0, p1 ) ) if ( tL == 0.0 ): tL = 1.0 f[i].t = ((p1[0] - p0[0])/tL, (p1[1] - p0[1])/tL, (p1[2] - p0[2])/tL) # calculate kappa from tangent vectors by forward differences # mark those points that have very low curvature eps = 1.0e-10 for i in range(n): t0 = f[i].t t1 = f[(i+1) % n].t f[i].state = math.fabs(vtk.vtkMath.Dot(t0,t1) - 1.0) < eps tempPts = vtk.vtkPoints() # mark keepers ids = vtk.vtkIdTypeArray() # for now, insist on keeping the first point for closure ids.InsertNextValue(0) for i in range(1, n): pre = f[( i - 1 + n ) % n].state # means fik != 1 cur = f[i].state # means fik = 1 nex = f[( i + 1 ) % n].state # possible vertex bend patterns for keep: pre cur nex # 0 0 1 # 0 1 1 # 0 0 0 # 0 1 0 # definite delete pattern # 1 1 1 keep = False if ( pre and cur and nex ): keep = False elif (not pre and not cur and nex ): keep = True elif (not pre and cur and nex ): keep = True elif ( not pre and not cur and not nex ): keep = True elif ( not pre and cur and not nex ): keep = True if ( keep ): ids.InsertNextValue( i ) for i in range(ids.GetNumberOfTuples()): tempPts.InsertNextPoint( inPts.GetPoint( ids.GetValue( i ) ) ) if ( closed == 1): tempPts.InsertNextPoint( inPts.GetPoint( ids.GetValue( 0 ) ) ) outPoly = ConvertPointSequenceToPolyData( tempPts, closed) ids = None#.Delete() tempPts = None#.Delete() return 1
def writeHdf5(): if timeStep < 0.01: exit("Timestep is too small, choose 0.01 or larger") # This is where the data is for testing purposes. print "Current working directory:", os.getcwd() print taskMeshIn numQuadsPerRing = circQuads # Working with the task mesh junt to figure out the quads and rows numbers. taskMeshReader = vtk.vtkXMLPolyDataReader() taskMeshReader.SetFileName(taskMeshIn) taskMeshReader.Update() taskMesh = taskMeshReader.GetOutput() print taskMesh.GetNumberOfPoints() # Get the range of branch labels. labelRange = [0, 0] taskMesh.GetCellData().GetScalars().GetRange(labelRange, 0) # Convert label range to a list of labels. labelRange = range(int(labelRange[0]), int(labelRange[1]) + 1) print "Labels found in task mesh:", labelRange # Store the number of rings for each label. numRingsPerLabel = {} # For every label in the range of labels we want to extract all cells/quads. for label in labelRange: # Use this filter to extract the cells for a given label value. branchSelector = vtk.vtkThreshold() branchSelector.SetInputData(taskMesh) branchSelector.ThresholdBetween(label,label); branchSelector.Update() taskMeshBranch = branchSelector.GetOutput() numQuadRowsPerBranch = taskMeshBranch.GetNumberOfCells() / numQuadsPerRing; numRingsPerLabel[label] = numQuadRowsPerBranch atpFiles = glob.glob(atpMeshPattern) parentFile = h5py.File(atpHdf5Files[0], 'w') leftBranchFile = h5py.File(atpHdf5Files[1], 'w') rightBranchFile = h5py.File(atpHdf5Files[2], 'w') for atpIndex in range(0, len(atpFiles), int(timeStep / originalTimeStep)): print "Time step " + str(atpIndex * timeStep ) atpMeshReader = vtk.vtkXMLPolyDataReader() atpMeshReader.SetFileName(atpFiles[atpIndex]) atpMeshReader.Update() atpMesh = atpMeshReader.GetOutput() # For every label in the range of labels we want to extract all ECs. for label in labelRange: # Keep track of how many branches we need to skip. numECsPerLabel = numQuadsPerRing * numRingsPerLabel[label] * numECsPerQuad atpCellOffset = label * numECsPerLabel # Collect cell ids to select. selectionIds = vtk.vtkIdTypeArray() for sId in range(0, numECsPerLabel): selectionIds.InsertNextValue(atpCellOffset + sId) # Create selecion node. selectionNode = vtk.vtkSelectionNode() selectionNode.SetFieldType(selectionNode.CELL) selectionNode.SetContentType(selectionNode.INDICES) selectionNode.SetSelectionList(selectionIds) # Create selection. selection = vtk.vtkSelection() selection.AddNode(selectionNode) # Use vtkSelection filter. selectionExtractor = vtk.vtkExtractSelection() selectionExtractor.SetInputData(0, atpMesh) selectionExtractor.SetInputData(1, selection) selectionExtractor.Update() extractedCells = selectionExtractor.GetOutput() # Ring ids list for traversal. ringIds = range(0, numRingsPerLabel[label]) ringIds.reverse() # Number of ECs rows is the number of ECs per quad. rowIds = range(0, numECsPerCol) rowIds.reverse() # Decide which h5 files to write to. pointsOf = '' if label == 0: pointsOf = parentFile elif label == 1: pointsOf = leftBranchFile elif label == 2: pointsOf = rightBranchFile dset = pointsOf.create_dataset("/" + str(atpIndex), (numECsPerLabel,), 'f') i = 0 # Iterate over the rings in reverse order. for ringNum in ringIds: # Iterate over the 'imaginary' quads of cells in normal order. for quadNum in range(0, numQuadsPerRing): # Iterate over the rows of cells in reverse order. # Calculate the 'real' id for the 'imaginary' quad. quadId = ringNum * numQuadsPerRing + quadNum # Iterate over rows of cells in reverse order. for rowNum in rowIds: # Iterate over the rows of cells in normal order. for cellNum in range(0, numECsPerRow): # Calculate the 'real' ec cell id and get the corresponding cell. realId = quadId * numECsPerQuad + rowNum * numECsPerRow + cellNum atpVal = extractedCells.GetCellData().GetArray("ATP").GetValue(realId) # Write the value to the txt file. dset[i] = atpVal i += 1 parentFile.close() leftBranchFile.close() rightBranchFile.close() print "All done ..."
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 = {y: x for x, y in vtk_to_meshio_type.items()} # 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.items(): numcells, num_local_nodes = data.shape if meshio_type[:7] == "polygon": vtk_type = meshio_to_vtk_type[meshio_type[:7]] else: 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 node_pick(self, pos): picker = vtk.vtkPointPicker() picker.SetTolerance(0.005) picker.Pick(pos[0], pos[1], 0, self.GetDefaultRenderer()) _id = picker.GetPointId() if _id != -1: if _id < self.node_count: if self.last_selection == 'Node %s' % str(_id): self.should_it_render = False self.did_it_render = True return True self.last_selection = 'Node %s' % str(_id) ids = vtk.vtkIdTypeArray() ids.SetNumberOfComponents(1) ids.InsertNextValue(_id) self.picked_type = 'Node' self.picked_id = self.node_ids[_id] #print 'picked type = %s, id = %s' % (self.picked_type, self.picked_id) selectionNode = vtk.vtkSelectionNode() selectionNode.SetFieldType(vtk.vtkSelectionNode.POINT) selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES) selectionNode.SetSelectionList(ids) selection = vtk.vtkSelection() selection.AddNode(selectionNode) extractSelection = vtk.vtkExtractSelection() extractSelection.SetInputData(0, self.Data) extractSelection.SetInputData(1, selection) extractSelection.Update() selected = vtk.vtkUnstructuredGrid() selected.ShallowCopy(extractSelection.GetOutput()) self.selectedMapper.SetInputData(selected) #self.selectedActor = vtk_widget.vtkActor() self.selectedActor.SetMapper(self.selectedMapper) self.selectedActor.GetProperty().EdgeVisibilityOn() # this makes cells not blue? #self.selectedActor.GetProperty().SetColor(0, 0.5, 0) self.selectedActor.GetProperty().SetEdgeColor(0.5, 0.5, 0) self.selectedActor.GetProperty().SetPointSize(6) self.should_it_render = True return True else: self.picked_id = None return False return self.cell_pick(_id) else: self.picked_id = None return False
def WriteLifeVMeshFile(self): if (self.OutputFileName == ''): self.PrintError('Error: no OutputFileName.') self.PrintLog('Writing LifeV file.') self.Mesh.BuildLinks() cellEntityIdsArray = vtk.vtkIntArray() cellEntityIdsArray.DeepCopy(self.Mesh.GetCellData().GetArray(self.CellEntityIdsArrayName)) tetraCellType = 10 triangleCellType = 5 f=open(self.OutputFileName, 'w') line = "MeshVersionFormatted 1\n\n" line += "Dimension\n" line += "3\n\n" line += "Vertices\n" line += "%d\n" % self.Mesh.GetNumberOfPoints() f.write(line) for i in range(self.Mesh.GetNumberOfPoints()): point = self.Mesh.GetPoint(i) pointCells = vtk.vtkIdList() self.Mesh.GetPointCells(i,pointCells) minTriangleCellEntityId = -1 tetraCellEntityId = -1 for j in range(pointCells.GetNumberOfIds()): cellId = pointCells.GetId(j) if self.Mesh.GetCellType(cellId) == triangleCellType: cellEntityId = cellEntityIdsArray.GetValue(cellId) if cellEntityId < minTriangleCellEntityId or minTriangleCellEntityId == -1: minTriangleCellEntityId = cellEntityId else: tetraCellEntityId = cellEntityIdsArray.GetValue(cellId) cellEntityId = tetraCellEntityId if minTriangleCellEntityId != -1: cellEntityId = minTriangleCellEntityId line = "%f %f %f %d\n" % (point[0], point[1], point[2], cellEntityId) f.write(line) line = "\n" tetraCellIdArray = vtk.vtkIdTypeArray() self.Mesh.GetIdsOfCellsOfType(tetraCellType,tetraCellIdArray) numberOfTetras = tetraCellIdArray.GetNumberOfTuples() line += "Tetrahedra\n" line += "%d\n" % numberOfTetras f.write(line) for i in range(numberOfTetras): tetraCellId = tetraCellIdArray.GetValue(i) cellPointIds = self.Mesh.GetCell(tetraCellId).GetPointIds() line = '' for j in range(cellPointIds.GetNumberOfIds()): if j>0: line += ' ' line += "%d" % (cellPointIds.GetId(j)+1) line += ' %d\n' % 1 f.write(line) line = "\n" triangleCellIdArray = vtk.vtkIdTypeArray() self.Mesh.GetIdsOfCellsOfType(triangleCellType,triangleCellIdArray) numberOfTriangles = triangleCellIdArray.GetNumberOfTuples() line += "Triangles\n" line += "%d\n" % numberOfTriangles f.write(line) for i in range(numberOfTriangles): triangleCellId = triangleCellIdArray.GetValue(i) cellPointIds = self.Mesh.GetCell(triangleCellId).GetPointIds() line = '' for j in range(cellPointIds.GetNumberOfIds()): if j>0: line += ' ' line += "%d" % (cellPointIds.GetId(j)+1) cellEntityId = cellEntityIdsArray.GetValue(triangleCellId) line += ' %d\n' % cellEntityId f.write(line)
def _generate_vtk_mesh(points, cells): 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, 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()
lsv_reader = vtk.vtkArrayReader() lsv_reader.SetFileName(os.path.join(lsa_data_path,"CH_LeftSingularVectors.txt")) rsv_reader = vtk.vtkArrayReader() rsv_reader.SetFileName(os.path.join(lsa_data_path,"CH_RightSingularVectors.txt")) sv_reader = vtk.vtkArrayReader() sv_reader.SetFileName(os.path.join(lsa_data_path,"CH_SingluarValues.txt")) power_weighting = vtk.vtkPowerWeighting() power_weighting.SetInputConnection(0, sv_reader.GetOutputPort()) power_weighting.SetPower(-0.5) # Setup the query pipeline ... query_document_array = vtk.vtkIdTypeArray() query_document_array.SetName("document") query_text_array = vtk.vtkUnicodeStringArray() query_text_array.SetName("text") query_document_array.InsertNextValue(query_document_array.GetNumberOfTuples()) query_text_array.InsertNextValue(unicode(query_string)) query_document_table = vtk.vtkTable() query_document_table.AddColumn(query_document_array) query_document_table.AddColumn(query_text_array) query_document_reader = vtk.vtkPassThrough() query_document_reader.SetInputConnection(0, query_document_table.GetProducerPort())
def remove_non_visible_faces( polydata, positions=[[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]], remove_visible=False, ): polydata.BuildLinks() mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(polydata) mapper.Update() actor = vtk.vtkActor() actor.SetMapper(mapper) renderer = vtk.vtkRenderer() renderer.AddActor(actor) render_window = vtk.vtkRenderWindow() render_window.AddRenderer(renderer) render_window.SetSize(800, 800) render_window.OffScreenRenderingOn() camera = renderer.GetActiveCamera() renderer.ResetCamera() pos = np.array(camera.GetPosition()) fp = np.array(camera.GetFocalPoint()) v = pos - fp mag = np.linalg.norm(v) vn = v / mag id_filter = vtk.vtkIdFilter() id_filter.SetInputData(polydata) id_filter.PointIdsOn() id_filter.Update() set_points = None for position in positions: pos = fp + np.array(position) * mag camera.SetPosition(pos.tolist()) renderer.ResetCamera() render_window.Render() select_visible_points = vtk.vtkSelectVisiblePoints() select_visible_points.SetInputData(id_filter.GetOutput()) select_visible_points.SetRenderer(renderer) # select_visible_points.SelectInvisibleOn() select_visible_points.Update() output = select_visible_points.GetOutput() id_points = numpy_support.vtk_to_numpy( output.GetPointData().GetAbstractArray("vtkIdFilter_Ids") ) if set_points is None: set_points = set(id_points.tolist()) else: set_points.update(id_points.tolist()) # id_list = vtk.vtkIdList() # output.GetVerts().GetCell(1000, id_list) if remove_visible: set_points = set(range(polydata.GetNumberOfPoints())) - set_points cells_ids = set() for p_id in set_points: id_list = vtk.vtkIdList() polydata.GetPointCells(p_id, id_list) for i in range(id_list.GetNumberOfIds()): cells_ids.add(id_list.GetId(i)) try: id_list = numpy_support.numpy_to_vtkIdTypeArray(np.array(list(cells_ids), dtype=np.int64)) except ValueError: id_list = vtk.vtkIdTypeArray() selection_node = vtk.vtkSelectionNode() selection_node.SetFieldType(vtk.vtkSelectionNode.CELL) selection_node.SetContentType(vtk.vtkSelectionNode.INDICES) selection_node.SetSelectionList(id_list) selection = vtk.vtkSelection() selection.AddNode(selection_node) extract_selection = vtk.vtkExtractSelection() extract_selection.SetInputData(0, polydata) extract_selection.SetInputData(1, selection) extract_selection.Update() geometry_filter = vtk.vtkGeometryFilter() geometry_filter.SetInputData(extract_selection.GetOutput()) geometry_filter.Update() clean_polydata = vtk.vtkCleanPolyData() clean_polydata.SetInputData(geometry_filter.GetOutput()) clean_polydata.Update() return clean_polydata.GetOutput()
def main(): """ ^y | 8----9----10---11 | / | / | / | 4----5----6----7 | / | / | / | 0----1----2----3 --> x """ ugrid = vtk.vtkUnstructuredGrid() xyzs = [ [0., 0., 0.], [1., 0., 0.], [2., 0., 0.], [3., 0., 0.], [0., 1., 0.], [1., 1., 0.], [2., 1., 0.], [3., 1., 0.], [0., 2., 0.], [1., 2., 0.], [2., 2., 0.], [3., 2., 0.], ] # we make the lower triangle first, then the upper one to finish off the quad # go accross each row, left to right tris = [ [0, 1, 5], [0, 5, 4], [1, 2, 6], [1, 6, 5], [2, 3, 7], [2, 7, 6], [4, 5, 9], [4, 9, 8], [5, 6, 10], [5, 10, 9], [6, 7, 11], [6, 11, 10], ] ids_to_show = [0, 1, #2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] ids_to_show_updated = [ 0, 1, #2, 3, #4, 5, 6, 7, 8, 9, 10, 11, 12] nnodes = len(xyzs) points = vtk.vtkPoints() points.SetNumberOfPoints(nnodes) nid = 0 for i, xyz in enumerate(xyzs): points.InsertPoint(nid, *xyz) nid += 1 for tri in tris: elem = vtk.vtkTriangle() (n1, n2, n3) = tri elem.GetPointIds().SetId(0, n1) elem.GetPointIds().SetId(1, n2) elem.GetPointIds().SetId(2, n3) ugrid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) ugrid.SetPoints(points) grid_mapper = vtk.vtkDataSetMapper() if vtk.VTK_MAJOR_VERSION <= 5: grid_mapper.SetInputConnection(ugrid.GetProducerPort()) else: grid_mapper.SetInputData(ugrid) input_actor = vtk.vtkActor() input_actor.SetMapper(grid_mapper) render_window = vtk.vtkRenderWindow() camera = vtk.vtkCamera() interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(render_window) print("There are %s input points" % ugrid.GetNumberOfPoints()) print("There are %s input cells" % ugrid.GetNumberOfCells()) ids = vtk.vtkIdTypeArray() ids.SetNumberOfComponents(1) ids.Allocate(len(ids_to_show)) for id_to_show in ids_to_show: ids.InsertNextValue(id_to_show) selection_node = vtk.vtkSelectionNode() selection_node.SetFieldType(vtk.vtkSelectionNode.CELL) selection_node.SetContentType(vtk.vtkSelectionNode.INDICES) selection_node.SetSelectionList(ids) selection = vtk.vtkSelection() selection.AddNode(selection_node) extract_selection = vtk.vtkExtractSelection() if vtk.VTK_MAJOR_VERSION <= 5: extract_selection.SetInput(0, ugrid) extract_selection.SetInput(1, selection) else: extract_selection.SetInputData(0, ugrid) extract_selection.SetInputData(1, selection) extract_selection.Update() # In selection grid_selected = vtk.vtkUnstructuredGrid() grid_selected.ShallowCopy(extract_selection.GetOutput()) print("There are %s points in the selection" % grid_selected.GetNumberOfPoints()) print("There are %s cells in the selection" % grid_selected.GetNumberOfCells()) # Get points that are NOT in the selection # invert the selection selection_node.GetProperties().Set(vtk.vtkSelectionNode.INVERSE(), 1) extract_selection.Update() not_selected = vtk.vtkUnstructuredGrid() not_selected.ShallowCopy(extract_selection.GetOutput()) print("There are %s points NOT in the selection" % not_selected.GetNumberOfPoints()) print("There are %s cells NOT in the selection" % not_selected.GetNumberOfCells()) selected_mapper = vtk.vtkDataSetMapper() if vtk.VTK_MAJOR_VERSION <= 5: selected_mapper.SetInputConnection(grid_selected.GetProducerPort()) else: selected_mapper.SetInputData(grid_selected) selected_actor = vtk.vtkActor() selected_actor.SetMapper(selected_mapper) not_selected_mapper = vtk.vtkDataSetMapper() if vtk.VTK_MAJOR_VERSION <= 5: not_selected_mapper.SetInputConnection(not_selected.GetProducerPort()) else: not_selected_mapper.SetInputData(not_selected) not_selected_actor = vtk.vtkActor() not_selected_actor.SetMapper(not_selected_mapper) # There will be one render window render_window = vtk.vtkRenderWindow() render_window.SetSize(900, 300) # And one interactor interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(render_window) # Define viewport ranges # (xmin, ymin, xmax, ymax) left_viewport = [0.0, 0.0, 0.5, 1.0] right_viewport = [0.5, 0.0, 1.0, 1.0] # Create a camera for all renderers camera = vtk.vtkCamera() # Setup the renderers left_renderer = vtk.vtkRenderer() render_window.AddRenderer(left_renderer) left_renderer.SetViewport(left_viewport) left_renderer.SetBackground(.6, .5, .4) left_renderer.SetActiveCamera(camera) right_renderer = vtk.vtkRenderer() render_window.AddRenderer(right_renderer) right_renderer.SetViewport(right_viewport) right_renderer.SetBackground(.3, .1, .4) right_renderer.SetActiveCamera(camera) right_renderer.AddActor(selected_actor) left_renderer.AddActor(input_actor) right_renderer.AddActor(not_selected_actor) right_renderer.ResetCamera() interactor.Start() #----------------- ids.Reset() ids.Allocate(len(ids_to_show_updated)) for id_to_show in ids_to_show_updated: ids.InsertNextValue(id_to_show) ids.Modified() grid_selected.Modified() #ids.Update() ids.Modified() #selection_node.Update() selection_node.Modified() #selection.Update() selection.Modified() extract_selection.Update() extract_selection.Modified() #grid_selected.Update() grid_selected.Modified() selected_mapper.Update() selected_mapper.Modified() #selected_actor.Update() selected_actor.Modified() right_renderer.Modified() #right_renderer.Update() interactor.Modified() #interactor.Update() #----------------- render_window.Render() render_window.Modified()
def writeHdf5(): if timeStep < 0.01: exit("Timestep is too small, choose 0.01 or larger") # This is where the data is for testing purposes. print("Current working directory:", os.getcwd()) numQuadsPerRing = circQuads # Working with the task mesh junt to figure out the quads and rows numbers. taskMeshReader = vtk.vtkXMLPolyDataReader() taskMeshReader.SetFileName(taskMeshIn) taskMeshReader.Update() taskMesh = taskMeshReader.GetOutput() # Get the range of branch labels. labelRange = [0, 0] taskMesh.GetCellData().GetScalars().GetRange(labelRange, 0) # Convert label range to a list of labels. labelRange = range(int(labelRange[0]), int(labelRange[1]) + 1) print("Labels found in task mesh:", labelRange) # Store the number of rings for each label. numRingsPerLabel = {} # For every label in the range of labels we want to extract all cells/quads. for label in labelRange: # Use this filter to extract the cells for a given label value. branchSelector = vtk.vtkThreshold() branchSelector.SetInputData(taskMesh) branchSelector.ThresholdBetween(label, label) branchSelector.Update() taskMeshBranch = branchSelector.GetOutput() numQuadRowsPerBranch = taskMeshBranch.GetNumberOfCells( ) / numQuadsPerRing numRingsPerLabel[label] = numQuadRowsPerBranch atpFiles = sorted(glob.glob(atpMeshPattern)) parentFile = h5py.File(atpHdf5Files[0], 'w') leftBranchFile = h5py.File(atpHdf5Files[1], 'w') rightBranchFile = h5py.File(atpHdf5Files[2], 'w') for atpIndex in range(0, len(atpFiles), int(timeStep / originalTimeStep)): print("Time step" + str(atpIndex * timeStep)) print("Reading", atpFiles[atpIndex], "at index", atpIndex) atpMeshReader = vtk.vtkXMLPolyDataReader() atpMeshReader.SetFileName(atpFiles[atpIndex]) atpMeshReader.Update() atpMesh = atpMeshReader.GetOutput() # For every label in the range of labels we want to extract all ECs. for label in labelRange: # Keep track of how many branches we need to skip. numECsPerLabel = numQuadsPerRing * numRingsPerLabel[ label] * numECsPerQuad atpCellOffset = label * numECsPerLabel # Collect cell ids to select. selectionIds = vtk.vtkIdTypeArray() for sId in range(0, int(numECsPerLabel)): selectionIds.InsertNextValue(int(atpCellOffset) + sId) # Create selecion node. selectionNode = vtk.vtkSelectionNode() selectionNode.SetFieldType(selectionNode.CELL) selectionNode.SetContentType(selectionNode.INDICES) selectionNode.SetSelectionList(selectionIds) # Create selection. selection = vtk.vtkSelection() selection.AddNode(selectionNode) # Use vtkSelection filter. selectionExtractor = vtk.vtkExtractSelection() selectionExtractor.SetInputData(0, atpMesh) selectionExtractor.SetInputData(1, selection) selectionExtractor.Update() extractedCells = selectionExtractor.GetOutput() # Ring ids list for traversal. ringIds = range(0, int(numRingsPerLabel[label])) ringIds = list(ringIds) ringIds.reverse() # Number of ECs rows is the number of ECs per quad. rowIds = range(0, numECsPerCol) rowIds = list(rowIds) rowIds.reverse() # Decide which h5 files to write to. pointsOf = '' if label == 0: pointsOf = parentFile elif label == 1: pointsOf = leftBranchFile elif label == 2: pointsOf = rightBranchFile dset = pointsOf.create_dataset("/" + str(atpIndex), (numECsPerLabel, ), 'f') i = 0 # Iterate over the rings in reverse order. for ringNum in ringIds: # Iterate over the 'imaginary' quads of cells in normal order. for quadNum in range(0, numQuadsPerRing): # Iterate over the rows of cells in reverse order. # Calculate the 'real' id for the 'imaginary' quad. quadId = ringNum * numQuadsPerRing + quadNum # Iterate over rows of cells in reverse order. for rowNum in rowIds: # Iterate over the rows of cells in normal order. for cellNum in range(0, numECsPerRow): # Calculate the 'real' ec cell id and get the corresponding cell. realId = quadId * numECsPerQuad + rowNum * numECsPerRow + cellNum atpVal = extractedCells.GetCellData().GetArray( "ATP").GetValue(realId) # Insert the value into the dataset. dset[i] = atpVal i += 1 parentFile.close() leftBranchFile.close() rightBranchFile.close() print("All done ...")
def cell_pick(self, _id): if _id != -1: if self.last_selection == 'Element %s' % str(_id): self.should_it_render = False self.did_it_render = True return True camera_pos = self.camera.GetPosition() self.last_selection = 'Element %s' % str(_id) cell = self.Data.GetCell(_id) points = cell.GetPoints() count = points.GetNumberOfPoints() ids = vtk.vtkIdTypeArray() ids.SetNumberOfComponents(1) ids.InsertNextValue(_id) self.picked_type = 'Element' self.picked_id = self.element_ids[_id] point_list = vtk.vtkPoints() cell_list = vtk.vtkCellArray() f = 0.05 if count == 4: xyz = points.GetPoint(0) xyz = [camera_pos[0] + (xyz[0] - camera_pos[0])*f, camera_pos[1] + (xyz[1] - camera_pos[1])*f, camera_pos[2] + (xyz[2] - camera_pos[2])*f] point_list.InsertNextPoint(xyz) xyz = points.GetPoint(1) xyz = [camera_pos[0] + (xyz[0] - camera_pos[0])*f, camera_pos[1] + (xyz[1] - camera_pos[1])*f, camera_pos[2] + (xyz[2] - camera_pos[2])*f] point_list.InsertNextPoint(xyz) xyz = points.GetPoint(2) xyz = [camera_pos[0] + (xyz[0] - camera_pos[0])*f, camera_pos[1] + (xyz[1] - camera_pos[1])*f, camera_pos[2] + (xyz[2] - camera_pos[2])*f] point_list.InsertNextPoint(xyz) xyz = points.GetPoint(3) xyz = [camera_pos[0] + (xyz[0] - camera_pos[0])*f, camera_pos[1] + (xyz[1] - camera_pos[1])*f, camera_pos[2] + (xyz[2] - camera_pos[2])*f] point_list.InsertNextPoint(xyz) cell = vtk.vtkQuad() point_ids = cell.GetPointIds() point_ids.SetId(0, 0) point_ids.SetId(1, 1) point_ids.SetId(2, 2) point_ids.SetId(3, 3) elif count == 3: xyz = points.GetPoint(0) xyz = [camera_pos[0] + (xyz[0] - camera_pos[0])*f, camera_pos[1] + (xyz[1] - camera_pos[1])*f, camera_pos[2] + (xyz[2] - camera_pos[2])*f] point_list.InsertNextPoint(xyz) xyz = points.GetPoint(1) xyz = [camera_pos[0] + (xyz[0] - camera_pos[0])*f, camera_pos[1] + (xyz[1] - camera_pos[1])*f, camera_pos[2] + (xyz[2] - camera_pos[2])*f] point_list.InsertNextPoint(xyz) xyz = points.GetPoint(2) xyz = [camera_pos[0] + (xyz[0] - camera_pos[0])*f, camera_pos[1] + (xyz[1] - camera_pos[1])*f, camera_pos[2] + (xyz[2] - camera_pos[2])*f] point_list.InsertNextPoint(xyz) cell = vtk.vtkTriangle() point_ids = cell.GetPointIds() point_ids.SetId(0, 0) point_ids.SetId(1, 1) point_ids.SetId(2, 2) elif count == 2: xyz = points.GetPoint(0) xyz = [camera_pos[0] + (xyz[0] - camera_pos[0])*f, camera_pos[1] + (xyz[1] - camera_pos[1])*f, camera_pos[2] + (xyz[2] - camera_pos[2])*f] point_list.InsertNextPoint(xyz) xyz = points.GetPoint(1) xyz = [camera_pos[0] + (xyz[0] - camera_pos[0])*f, camera_pos[1] + (xyz[1] - camera_pos[1])*f, camera_pos[2] + (xyz[2] - camera_pos[2])*f] point_list.InsertNextPoint(xyz) cell = vtk.vtkLine() point_ids = cell.GetPointIds() point_ids.SetId(0, 0) point_ids.SetId(1, 1) cell_list.InsertNextCell(cell) poly_data = vtk.vtkPolyData() poly_data.SetPoints(point_list) poly_data.SetPolys(cell_list) poly_data.SetLines(cell_list) idFilter = vtk.vtkIdFilter() idFilter.SetInputData(poly_data) idFilter.SetIdsArrayName("SelectedIds") idFilter.Update() surfaceFilter = vtk.vtkDataSetSurfaceFilter() surfaceFilter.SetInputConnection(idFilter.GetOutputPort()) surfaceFilter.Update() input = surfaceFilter.GetOutput() self.selectedMapper.SetInputData(input) self.selectedMapper.ScalarVisibilityOff() self.selectedActor.SetMapper(self.selectedMapper) self.selectedActor.GetProperty().EdgeVisibilityOn() # this makes cells not blue? #self.selectedActor.GetProperty().SetColor(0, 0.5, 0) self.selectedActor.GetProperty().SetEdgeColor(0.5, 0.5, 0) self.selectedActor.GetProperty().SetLineWidth(3) self.selectedActor.GetProperty().SetOpacity(0.5) self.should_it_render = True return True else: return False
- You need to make sure you hold a reference to a Numpy array you want to import into VTK. If not you'll get a segfault (in the best case). The same holds in reverse when you convert a VTK array to a numpy array -- don't delete the VTK array. Created by Prabhu Ramachandran in Feb. 2008. """ import vtk import vtkConstants import numpy # Useful constants for VTK arrays. VTK_ID_TYPE_SIZE = vtk.vtkIdTypeArray().GetDataTypeSize() if VTK_ID_TYPE_SIZE == 4: ID_TYPE_CODE = numpy.int32 elif VTK_ID_TYPE_SIZE == 8: ID_TYPE_CODE = numpy.int64 VTK_LONG_TYPE_SIZE = vtk.vtkLongArray().GetDataTypeSize() if VTK_LONG_TYPE_SIZE == 4: LONG_TYPE_CODE = numpy.int32 ULONG_TYPE_CODE = numpy.uint32 elif VTK_LONG_TYPE_SIZE == 8: LONG_TYPE_CODE = numpy.int64 ULONG_TYPE_CODE = numpy.uint64 def get_vtk_array_type(numpy_array_type):
def writeLegacyVTK(): # This is where the data is for testing purposes. print "Current working directory:", os.getcwd() if os.path.isdir("vtk") == False: os.makedirs("vtk") print "Cretated vtk output directory..." if os.path.isdir("files") == False: os.makedirs("files") print "Created files ouptut directory..." # Working with the task mesh. taskMeshReader = vtk.vtkXMLPolyDataReader() taskMeshReader.SetFileName(meshSet[0]) taskMeshReader.Update() taskMesh = taskMeshReader.GetOutput() # Get the range of branch labels. labelRange = [0, 0] taskMesh.GetCellData().GetScalars().GetRange(labelRange, 0) # Convert label range to a list of labels. labelRange = range(int(labelRange[0]), int(labelRange[1]) + 1) print "Labels found in task mesh:", labelRange # Store the number of rings for each label. numRingsPerLabel = {} # For every label in the range of labels we want to extract all cells/quads. for label in labelRange: # Use this filter to extract the cells for a given label value. branchSelector = vtk.vtkThreshold() branchSelector.SetInputData(taskMesh) branchSelector.ThresholdBetween(label,label); branchSelector.Update() taskMeshBranch = branchSelector.GetOutput() # New vtkPoints for storing reordered points. reorderedPoints = vtk.vtkPoints() # New vtkCellArray for storing reordeced cells. reorderedCellArray = vtk.vtkCellArray() numQuadRowsPerBranch = taskMeshBranch.GetNumberOfCells() / numQuadsPerRing; numRingsPerLabel[label] = numQuadRowsPerBranch ringIds = range(0, numQuadRowsPerBranch); # Working with rows in reverse order: UPSTREAM. ringIds.reverse() rowBase = 0 # Iterate over the rings in reverse order. for ringNum in ringIds: # Iterate over the cells in normal order. for cellNum in range(0, numQuadsPerRing): # Calculate the 'real' cell id and get the corresponding cell. cellId = ringNum * numQuadsPerRing + cellNum cell = taskMeshBranch.GetCell(cellId) # The ids to be written to the TXT file. pointIdList = [cell.GetNumberOfPoints()] # Write the appropriate points to TXT file. for pPos in range(0, cell.GetNumberOfPoints()): newPoint = False if ringNum == ringIds[0]: if cellNum == 0: newPoint = True elif pPos == 1 or pPos == 2: newPoint = True else: if cellNum == 0: if pPos == 0 or pPos == 1: newPoint = True else: if pPos == 1: newPoint = True if newPoint == True: # Inserting a new point... point = taskMeshBranch.GetPoint(cell.GetPointId(pPos)) # ... with a new id. newId = reorderedPoints.InsertNextPoint(point) pointIdList.append(newId) # To make it easier for remembering the number of points instered in a row. if cellNum == 0 and pPos == 0: rowBasePrev = newId else: # Perhaps this can be done in a nicer way. # Calculate the id of a previously inserted point. if ringNum == ringIds[0]: if cellNum == 1: if pPos == 0: pointIdList.append(1L) elif pPos == 3: pointIdList.append(2L) else: if pPos == 0: pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 2)) elif pPos == 3: pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 3)) elif ringNum == ringIds[1]: if cellNum == 0: if pPos == 2: pointIdList.append(1L) elif pPos == 3: pointIdList.append(0L) else: if pPos == 0: pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 1)) elif pPos == 2: pointIdList.append(long(cellNum * 2 + 2)) elif pPos == 3: if cellNum == 1: pointIdList.append(1L) else: pointIdList.append(long(cellNum * 2)) else: if cellNum == 0: if pPos == 2: pointIdList.append(long(rowBase + 1)) elif pPos == 3: pointIdList.append(long(rowBase)) else: if pPos == 0: pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 1)) elif pPos == 2: pointIdList.append(long(rowBase + cellNum + 1)) elif pPos == 3: pointIdList.append(long(rowBase + cellNum)) # print pointIdList, rowBase # Insert the ids into the cell array. newCell = vtk.vtkQuad() newCell.GetPointIds().Reset() for id in pointIdList[1:]: newCell.GetPointIds().InsertNextId(id) reorderedCellArray.InsertNextCell(newCell) rowBase = rowBasePrev # print '\n' print "Inserted", reorderedPoints.GetNumberOfPoints(), "task mesh points for label", label, "..." print "Inserted", reorderedCellArray.GetNumberOfCells(), "task mesh cells for label", label, "..." # Create new vtkPolyData object for the new reordered mesh. reorderedTaskMeshBranch = vtk.vtkPolyData() # Put the reordered points and cells into the reordered mesh. reorderedTaskMeshBranch.SetPoints(reorderedPoints) reorderedTaskMeshBranch.SetPolys(reorderedCellArray) # Write the VTK file. reorderedMeshWriter = vtk.vtkXMLPolyDataWriter() reorderedMeshWriter.SetInputData(reorderedTaskMeshBranch) reorderedMeshWriter.SetFileName(taskVTKFiles[label]) reorderedMeshWriter.Update() print "Rings per label:", numRingsPerLabel, "..." ringsPerLabelVals = numRingsPerLabel.values() # Check all rings per label values are the same. assert ringsPerLabelVals[1:] == ringsPerLabelVals[:-1], "All values of rings per label must be identical. Generated output is invalid ..." # Working with EC mesh. ecMeshReader = vtk.vtkXMLPolyDataReader() ecMeshReader.SetFileName(meshSet[1]) ecMeshReader.Update() # Original ECs mesh to work with. ecMesh = ecMeshReader.GetOutput() print "There are", ecMesh.GetNumberOfCells(), "ECs in total ..." # For every label in the range of labels we want to extract all ECs. for label in labelRange: # Keep track of how many branches we need to skip. numECsPerLabel = numQuadsPerRing * numRingsPerLabel[label] * numECsPerQuad ecCellOffset = label * numECsPerLabel print "ecCellOffset", ecCellOffset # Collect cell ids to select. selectionIds = vtk.vtkIdTypeArray() for sId in range(0, numECsPerLabel): selectionIds.InsertNextValue(ecCellOffset + sId) # Create selecion node. selectionNode = vtk.vtkSelectionNode() selectionNode.SetFieldType(selectionNode.CELL) selectionNode.SetContentType(selectionNode.INDICES) selectionNode.SetSelectionList(selectionIds) # Create selection. selection = vtk.vtkSelection() selection.AddNode(selectionNode) # Use vtkSelection filter. selectionExtractor = vtk.vtkExtractSelection() selectionExtractor.SetInputData(0, ecMesh) selectionExtractor.SetInputData(1, selection) selectionExtractor.Update() extractedECs = selectionExtractor.GetOutput() # Ring ids list for traversal. ringIds = range(0, numRingsPerLabel[label]) ringIds.reverse() # Number of ECs rows is the number of ECs per quad. rowIds = range(0, numECsPerCol) rowIds.reverse() # The ECs are organised in rings of blocks of cells. # New vtkCellArray for storing reordeced cells. reorderedCellArray = vtk.vtkCellArray() # Iterate over the rings in reverse order. for ringNum in ringIds: # Iterate over the 'imaginary' quads of cells in normal order. for quadNum in range(0, numQuadsPerRing): # Iterate over the rows of cells in reverse order. # Calculate the 'real' id for the 'imaginary' quad. quadId = ringNum * numQuadsPerRing + quadNum # Iterate over rows of cells in reverse order. for rowNum in rowIds: # Iterate over the rows of cells in normal order. for ecNum in range(0, numECsPerRow): # Calculate the 'real' ec cell id and get the corresponding cell. ecId = quadId * numECsPerQuad + rowNum * numECsPerRow + ecNum ecCell = extractedECs.GetCell(ecId) reorderedCellArray.InsertNextCell(ecCell) # Create new vtkPolyData object for the new reordered mesh. reorderedECMeshBranch = vtk.vtkPolyData() # Insert our new points. reorderedECMeshBranch.SetPoints(extractedECs.GetPoints()) # Set the reordered cells to the reordered ECs mesh. reorderedECMeshBranch.SetPolys(reorderedCellArray) # New vtkPoints for storing reordered points. reorderedPoints = vtk.vtkPoints() # New vtkCellArray for storing reordeced cells. reorderedCellArray = vtk.vtkCellArray() rowBase = 0 # Iterate over quads in normal order because they have been reordered. for quadNum in range(0, numRingsPerLabel[label] * numQuadsPerRing): # Iterate over rows in normal order because they have been reordered. for rowNum in range(0, numECsPerCol): # Iterate over the ECs in the row in normal order. for ecNum in range(0, numECsPerRow): # Calculate the 'real' ec cell id and get the corresponding cell. ecId = quadNum * numECsPerQuad + rowNum * numECsPerRow + ecNum ecCell = reorderedECMeshBranch.GetCell(ecId) # The ids to be written to the TXT file. pointIdList = [ecCell.GetNumberOfPoints()] # Write the appropriate points to the TXT file. for pPos in range(0, ecCell.GetNumberOfPoints()): newPoint = False if rowNum == 0: if ecNum == 0: newPoint = True elif pPos == 1 or pPos == 2: newPoint = True else: if ecNum == 0: if pPos == 0 or pPos == 1: newPoint = True else: if pPos == 1: newPoint = True if newPoint == True: # Inserting a new point... point = reorderedECMeshBranch.GetPoint(ecCell.GetPointId(pPos)) # ... with a new id. newId = reorderedPoints.InsertNextPoint(point) pointIdList.append(newId) if ecNum == 0 and pPos == 0: rowBasePrev = newId else: # Perhaps this can be done in a nicer way. # Calculate the ide of a previously inserted point. if rowNum == 0: if ecNum == 1: if pPos == 0: pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 3)) elif pPos == 3: pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 4)) else: if pPos == 0: pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 2)) elif pPos == 3: pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 3)) elif rowNum == 1: if ecNum == 0: if pPos == 2: pointIdList.append(long(rowBase + 1)) elif pPos == 3: pointIdList.append(long(rowBase)) else: if pPos == 0: pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 1)) elif pPos == 2: pointIdList.append(long(rowBase + ecNum * 2 + 2)) elif pPos == 3: if ecNum == 1: pointIdList.append(long(rowBase + 1)) else: pointIdList.append(long(rowBase + ecNum * 2)) else: if ecNum == 0: if pPos == 2: pointIdList.append(long(rowBase + 1)) elif pPos == 3: pointIdList.append(long(rowBase)) else: if pPos == 0: pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 1)) elif pPos == 2: pointIdList.append(long(rowBase + ecNum + 1)) elif pPos == 3: pointIdList.append(long(rowBase + ecNum)) # print pointIdList, rowBase # Insert the ids into the cell array. newCell = vtk.vtkQuad() newCell.GetPointIds().Reset() for id in pointIdList[1:]: newCell.GetPointIds().InsertNextId(id) reorderedCellArray.InsertNextCell(newCell) rowBase = rowBasePrev # print '\n' print "There are", reorderedPoints.GetNumberOfPoints(), "ECs points for label", label, "..." print "There are", reorderedCellArray.GetNumberOfCells(), "ECs cells for label", label, "..." # Create new vtkPolyData object for the new reordered mesh. reorderedECs = vtk.vtkPolyData() # Put the reordered points and cells into the mesh. reorderedECs.SetPoints(reorderedPoints) reorderedECs.SetPolys(reorderedCellArray) # Write the VTK EC mesh file. reorderedMeshWriter = vtk.vtkXMLPolyDataWriter() reorderedMeshWriter.SetInputData(reorderedECs) reorderedMeshWriter.SetFileName(ecVTKFiles[label]) reorderedMeshWriter.Update() # Use VTK centroid filter to get the centroids in the right order # from the reorderedECMeshBranch. centroidFilter = vtk.vtkCellCenters() centroidFilter.SetInputData(reorderedECs) centroidFilter.Update() # Create a vertex cell for each point. pointsToVerticesFilter = vtk.vtkVertexGlyphFilter() pointsToVerticesFilter.SetInputData(centroidFilter.GetOutput()) pointsToVerticesFilter.Update() reorderedCentroidBranch = pointsToVerticesFilter.GetOutput() # Write the VTK EC centrouid file. centroidWriter = vtk.vtkXMLPolyDataWriter() centroidWriter.SetInputData(reorderedCentroidBranch) centroidWriter.SetFileName(ecCentroidVTKFiles[label]) centroidWriter.Update() # Write the centroids to the TXT points and cells files. for cId in range(0, reorderedCentroidBranch.GetNumberOfCells()): centCell = reorderedCentroidBranch.GetCell(cId) centIds = [centCell.GetNumberOfPoints()] # Write centroid ids. ptId = centCell.GetPointId(0) centIds.append(ptId) # Write centroid points. point = reorderedCentroidBranch.GetPoint(ptId) # Working with SMC mesh. # Working with SMC mesh. # Working with SMC mesh. smcMeshReader = vtk.vtkXMLPolyDataReader() smcMeshReader.SetFileName(meshSet[2]) smcMeshReader.Update() # Original SMCs mesh to work with. smcMesh = smcMeshReader.GetOutput() print "There are", smcMesh.GetNumberOfCells(), "SMCs in total ..." # For every label in the range of labels we want to extract all SMCs. for label in labelRange: # Keep track of how many branches we need to skip. numSMCsPerLabel = numQuadsPerRing * numRingsPerLabel[label] * numSMCsPerQuad smcCellOffset = label * numSMCsPerLabel print "smcCellOffset", smcCellOffset # Collect cell ids to select. selectionIds = vtk.vtkIdTypeArray() for sId in range(0, numSMCsPerLabel): selectionIds.InsertNextValue(smcCellOffset + sId) # Create selecion node. selectionNode = vtk.vtkSelectionNode() selectionNode.SetFieldType(selectionNode.CELL) selectionNode.SetContentType(selectionNode.INDICES) selectionNode.SetSelectionList(selectionIds) # Create selection. selection = vtk.vtkSelection() selection.AddNode(selectionNode) # Use vtkSelection filter. selectionExtractor = vtk.vtkExtractSelection() selectionExtractor.SetInputData(0, smcMesh) selectionExtractor.SetInputData(1, selection) selectionExtractor.Update() extractedSMCs = selectionExtractor.GetOutput() # Ring ids list for traversal. ringIds = range(0, numRingsPerLabel[label]) ringIds.reverse() # Number of SMCs rows is the number of ECs per quad times 13. rowIds = range(0, numSMCsPerCol) rowIds.reverse() # The SMCs are organised in rings of blocks of cells. # New vtkCellArray for storing reordeced cells. reorderedCellArray = vtk.vtkCellArray() # Iterate over the rings in reverse order. for ringNum in ringIds: # Iterate over the 'imaginary' quads of cells in normal order. for quadNum in range(0, numQuadsPerRing): # Iterate over the rows of cells in reverse order. # Calculate the 'real' id for the 'imaginary' quad. quadId = ringNum * numQuadsPerRing + quadNum # Iterate over rows of cells in reverse order. for rowNum in rowIds: # Iterate over the rows of cells in normal order. for smcNum in range(0, numSMCsPerRow): # Calculate the 'real' smc cell id and get the corresponding cell. smcId = quadId * numSMCsPerQuad + rowNum * numSMCsPerRow + smcNum smcCell = extractedSMCs.GetCell(smcId) reorderedCellArray.InsertNextCell(smcCell) # Create new vtkPolyData object for the new reordered mesh. reorderedSMCMeshBranch = vtk.vtkPolyData() # Insert our new points. reorderedSMCMeshBranch.SetPoints(extractedSMCs.GetPoints()) # Set the reordered cells to the reordered SMCs mesh. reorderedSMCMeshBranch.SetPolys(reorderedCellArray) # New vtkPoints for storing reordered points. reorderedPoints = vtk.vtkPoints() # New vtkCellArray for storing reordeced cells. reorderedCellArray = vtk.vtkCellArray() rowBase = 0 # Iterate over quads in normal order because they have been reordered. for quadNum in range(0, numRingsPerLabel[label] * numQuadsPerRing): # Iterate over rows in normal order because they have been reordered. for rowNum in range(0, numSMCsPerCol): # Iterate over the SMCs in the row in normal order. for smcNum in range(0, numSMCsPerRow): # Calculate the 'real' smc cell id and get the corresponding cell. smcId = quadNum * numSMCsPerQuad + rowNum * numSMCsPerRow + smcNum smcCell = reorderedSMCMeshBranch.GetCell(smcId) # The ids to be written to the TXT file. pointIdList = [smcCell.GetNumberOfPoints()] # Write the appropriate points to the TXT file. for pPos in range(0, smcCell.GetNumberOfPoints()): newPoint = False if rowNum == 0: if smcNum == 0: newPoint = True elif pPos == 1 or pPos == 2: newPoint = True else: if smcNum == 0: if pPos == 0 or pPos == 1: newPoint = True else: if pPos == 1: newPoint = True if newPoint == True: # Inserting a new point... point = reorderedSMCMeshBranch.GetPoint(smcCell.GetPointId(pPos)) # with a new id. newId = reorderedPoints.InsertNextPoint(point) pointIdList.append(newId) if smcNum == 0 and pPos == 0: rowBasePrev = newId else: # Perhaps this can be done in a nicer way. # Calculate the ide of a previously inserted point. if rowNum == 0: if smcNum == 1: if pPos == 0: pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 3)) elif pPos == 3: pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 4)) else: if pPos == 0: pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 2)) elif pPos == 3: pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 3)) elif rowNum == 1: if smcNum == 0: if pPos == 2: pointIdList.append(long(rowBase + 1)) elif pPos == 3: pointIdList.append(long(rowBase)) else: if pPos == 0: pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 1)) elif pPos == 2: pointIdList.append(long(rowBase + smcNum * 2 + 2)) elif pPos == 3: if smcNum == 1: pointIdList.append(long(rowBase + 1)) else: pointIdList.append(long(rowBase + smcNum * 2)) else: if smcNum == 0: if pPos == 2: pointIdList.append(long(rowBase + 1)) elif pPos == 3: pointIdList.append(long(rowBase)) else: if pPos == 0: pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 1)) elif pPos == 2: pointIdList.append(long(rowBase + smcNum + 1)) elif pPos == 3: pointIdList.append(long(rowBase + smcNum)) # print pointIdList, rowBase # Insert the ids into the cell array. newCell = vtk.vtkQuad() newCell.GetPointIds().Reset() for id in pointIdList[1:]: newCell.GetPointIds().InsertNextId(id) reorderedCellArray.InsertNextCell(newCell) rowBase = rowBasePrev # print '\n' print "There are", reorderedPoints.GetNumberOfPoints(), "SMCs points for label", label, "..." print "There are", reorderedCellArray.GetNumberOfCells(), "SMCs cells for label", label, "..." # Create new vtkPolyData object for the new reordered mesh. reorderedSMCs = vtk.vtkPolyData() # Put the reordered points and cells in to the mesh. reorderedSMCs.SetPoints(reorderedPoints) reorderedSMCs.SetPolys(reorderedCellArray) # Write the VTK SMC mesh file. reorderedMeshWriter = vtk.vtkXMLPolyDataWriter() reorderedMeshWriter.SetInputData(reorderedSMCs) reorderedMeshWriter.SetFileName(smcVTKFiles[label]) reorderedMeshWriter.Update() print "All done ..." print "... Except the last configuration_info.txt file ..." configFile = open("files/configuration_info.txt", 'w') configFile.write("Processors information\n") configFile.write("Total number of points per branch (vtk points) = %d\t\tm = %d n = %d\n" \ % ((numQuadsPerRing + 1) * (numRingsPerLabel[0] + 1), (numQuadsPerRing + 1), (numRingsPerLabel[0] + 1))) configFile.write("Total number of cells per branch (vtk cells) = %d\t\tm = %d n = %d\n" \ % (numQuadsPerRing * numRingsPerLabel[0], numQuadsPerRing, numRingsPerLabel[0])) configFile.write("Total number of SMC mesh points per processor mesh (vtk points) = %d\t\tm = %d n = %d\n" \ % ((numSMCsPerCol + 1) * (numSMCsPerRow + 1), (numSMCsPerCol + 1), (numSMCsPerRow + 1))) configFile.write("Total number of SMC mesh cells per processor mesh (vtk cells) = %d\t\tm = %d n = %d\n" \ % (numSMCsPerCol * numSMCsPerRow, numSMCsPerCol, numSMCsPerRow)) configFile.write("Total number of EC mesh points per processor mesh (vtk points) = %d\t\tm = %d n = %d\n" \ % ((numECsPerCol + 1) * (numECsPerRow + 1), (numECsPerCol + 1), (numECsPerRow + 1))) configFile.write("Total number of EC mesh cells per processor mesh (vtk cells) = %d\t\tm = %d n = %d\n" \ % (numECsPerCol *numECsPerRow, numECsPerCol, numECsPerRow)) configFile.write("Total number of EC mesh centeroid points per processor mesh (vtk points) = %d\t\tm = %d n = %d\n" \ % (numECsPerCol *numECsPerRow, numECsPerCol, numECsPerRow)) configFile.write("Total number of EC mesh centeroid cells per processor mesh (vtk cells) = %d\t\tm = %d n = %d\n" \ % (numECsPerCol *numECsPerRow, numECsPerCol, numECsPerRow)) configFile.close() print "Now it is all done for real ..."
def to_vtk(bdf): # type: (BDF) -> VTKData import vtk # TODO: use pynastran numpy_to_vtk from vtk.util.numpy_support import numpy_to_vtk nid_list = [] nid_dict = {} node_pos = np.empty((len(bdf.nodes), 3), dtype=np.float64) i = 0 for node in itervalues(bdf.nodes): node_pos[i] = node.get_position() nid = node.nid nid_list.append(nid) nid_dict[nid] = i i += 1 _points = vtk.vtkPoints() _points.SetData(numpy_to_vtk(node_pos)) points = vtk.vtkPoints() points.DeepCopy(_points) cells = [] cell_types = [] cell_count = 0 elem_types = [] eid_list = [] eid_dict = {} _nastran_to_vtk = nastran_to_vtk bdf_data_to_plot = chain(itervalues(bdf.nodes), itervalues(bdf.elements), itervalues(bdf.rigid_elements)) category_list = [] for elem in bdf_data_to_plot: elem_type = elem.type cell_type, add_method, category = _nastran_to_vtk.get( elem_type, (None, None, None)) if cell_type is None: continue cell_types.append(cell_type) elem_types.append(elem_type) eid = add_method(elem, cells, nid_dict) # returns element/grid id eid_list.append(eid) eid_dict[eid] = cell_count category_list.append(categories[category]) cell_count += 1 cells = np.array(cells, dtype=np.int64) id_array = vtk.vtkIdTypeArray() id_array.SetVoidArray(cells, len(cells), 1) vtk_cells = vtk.vtkCellArray() vtk_cells.SetCells(cell_count, id_array) cell_types = np.array(cell_types, 'B') vtk_cell_types = numpy_to_vtk(cell_types) cell_locations = np.array([i for i in range(cell_count)]) vtk_cell_locations = numpy_to_vtk(cell_locations, deep=1, array_type=vtk.VTK_ID_TYPE) ugrid = vtk.vtkUnstructuredGrid() ugrid.SetPoints(points) ugrid.SetCells(vtk_cell_types, vtk_cell_locations, vtk_cells) vtk_cell_locations.SetName('index') ugrid.GetCellData().AddArray(vtk_cell_locations) _elem_types = vtk.vtkStringArray() _elem_types.SetName('element_type') _elem_types.SetNumberOfValues(len(elem_types)) for i in range(len(elem_types)): _elem_types.SetValue(i, elem_types[i]) ugrid.GetCellData().AddArray(_elem_types) _cat_arr = np.array(category_list, dtype=np.int64) _cat = vtk.vtkIdTypeArray() _cat.SetNumberOfValues(len(category_list)) _cat.SetVoidArray(_cat_arr, len(_cat_arr), 1) _cat.SetName('category') ugrid.GetCellData().AddArray(_cat) id_array = numpy_to_vtk(np.array(eid_list), deep=1, array_type=vtk.VTK_ID_TYPE) # id_array = vtk.vtkIdTypeArray() # id_array.SetVoidArray(eid_list, len(eid_list), 1) id_array.SetName('element_id') ugrid.GetCellData().AddArray(id_array) copy = vtk.vtkUnstructuredGrid() copy.DeepCopy(ugrid) vtk_data = VTKData(copy, nid_list, nid_dict, eid_list, eid_dict) return vtk_data
def main(): colors = vtk.vtkNamedColors() # colors.SetColor('leftBkg', [0.6, 0.5, 0.4, 1.0]) # colors.SetColor('centreBkg', [0.3, 0.1, 0.4, 1.0]) # colors.SetColor('rightBkg', [0.4, 0.5, 0.6, 1.0]) sphereSource = vtk.vtkSphereSource() sphereSource.Update() print('There are %s input points' % sphereSource.GetOutput().GetNumberOfPoints()) print('There are %s input cells' % sphereSource.GetOutput().GetNumberOfCells()) ids = vtk.vtkIdTypeArray() ids.SetNumberOfComponents(1) # Specify that we want to extract cells 10 through 19 i = 10 while i < 20: ids.InsertNextValue(i) i += 1 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.SetInputConnection(0, sphereSource.GetOutputPort()) 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 selectionNode.GetProperties().Set(vtk.vtkSelectionNode.INVERSE(), 1) # invert the selection 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()) backfaces = vtk.vtkProperty() backfaces.SetColor(colors.GetColor3d('Gold')) inputMapper = vtk.vtkDataSetMapper() inputMapper.SetInputConnection(sphereSource.GetOutputPort()) inputActor = vtk.vtkActor() inputActor.SetMapper(inputMapper) inputActor.SetBackfaceProperty(backfaces) inputActor.GetProperty().SetColor(colors.GetColor3d('MistyRose')) selectedMapper = vtk.vtkDataSetMapper() selectedMapper.SetInputData(selected) selectedActor = vtk.vtkActor() selectedActor.SetMapper(selectedMapper) selectedActor.SetBackfaceProperty(backfaces) selectedActor.GetProperty().SetColor(colors.GetColor3d('MistyRose')) notSelectedMapper = vtk.vtkDataSetMapper() notSelectedMapper.SetInputData(notSelected) notSelectedActor = vtk.vtkActor() notSelectedActor.SetMapper(notSelectedMapper) notSelectedActor.SetBackfaceProperty(backfaces) notSelectedActor.GetProperty().SetColor(colors.GetColor3d('MistyRose')) # There will be one render window renderWindow = vtk.vtkRenderWindow() renderWindow.SetSize(900, 300) renderWindow.SetWindowName('ExtractSelectionCells') # 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, 0.66, 1.0] rightViewport = [0.66, 0.0, 1.0, 1.0] # Create a camera for all renderers camera = vtk.vtkCamera() # Setup the renderers leftRenderer = vtk.vtkRenderer() renderWindow.AddRenderer(leftRenderer) leftRenderer.SetViewport(leftViewport) leftRenderer.SetBackground(colors.GetColor3d('BurlyWood')) leftRenderer.SetActiveCamera(camera) centerRenderer = vtk.vtkRenderer() renderWindow.AddRenderer(centerRenderer) centerRenderer.SetViewport(centerViewport) centerRenderer.SetBackground(colors.GetColor3d('orchid_dark')) centerRenderer.SetActiveCamera(camera) rightRenderer = vtk.vtkRenderer() renderWindow.AddRenderer(rightRenderer) rightRenderer.SetViewport(rightViewport) rightRenderer.SetBackground(colors.GetColor3d('CornflowerBlue')) rightRenderer.SetActiveCamera(camera) leftRenderer.AddActor(inputActor) centerRenderer.AddActor(selectedActor) rightRenderer.AddActor(notSelectedActor) leftRenderer.ResetCamera() renderWindow.Render() interactor.Start()
def writeLegacyVTK(): # This is where the data is for testing purposes. print("Current working directory:", os.getcwd()) if os.path.isdir("vtk") == False: os.makedirs("vtk") print("Cretated vtk output directory...") if os.path.isdir("files") == False: os.makedirs("files") print("Created files ouptut directory...") # Working with the task mesh. taskMeshReader = vtk.vtkXMLPolyDataReader() taskMeshReader.SetFileName(meshSet[0]) taskMeshReader.Update() taskMesh = taskMeshReader.GetOutput() # Get the range of branch labels. labelRange = [0, 0] taskMesh.GetCellData().GetScalars().GetRange(labelRange, 0) # Convert label range to a list of labels. labelRange = range(int(labelRange[0]), int(labelRange[1]) + 1) print("Labels found in task mesh:", labelRange) # Store the number of rings for each label. numRingsPerLabel = {} # For every label in the range of labels we want to extract all cells/quads. for label in labelRange: # Use this filter to extract the cells for a given label value. branchSelector = vtk.vtkThreshold() branchSelector.SetInputData(taskMesh) branchSelector.ThresholdBetween(label, label) branchSelector.Update() taskMeshBranch = branchSelector.GetOutput() # New vtkPoints for storing reordered points. reorderedPoints = vtk.vtkPoints() # New vtkCellArray for storing reordeced cells. reorderedCellArray = vtk.vtkCellArray() numQuadRowsPerBranch = taskMeshBranch.GetNumberOfCells( ) / numQuadsPerRing numRingsPerLabel[label] = numQuadRowsPerBranch # Working with rows in reverse order: UPSTREAM. ringIds = range(0, int(numQuadRowsPerBranch)) ringIds = list(ringIds) ringIds.reverse() rowBase = 0 # Iterate over the rings in reverse order. for ringNum in ringIds: # print("ringNum", ringNum) # Iterate over the cells in normal order. for cellNum in range(0, int(numQuadsPerRing)): # Calculate the 'real' cell id and get the corresponding cell. cellId = ringNum * numQuadsPerRing + cellNum cell = taskMeshBranch.GetCell(cellId) # The ids to be written to the TXT file. pointIdList = [cell.GetNumberOfPoints()] # Write the appropriate points to TXT file. for pPos in range(0, cell.GetNumberOfPoints()): newPoint = False if ringNum == ringIds[0]: if cellNum == 0: newPoint = True elif pPos == 1 or pPos == 2: newPoint = True else: if cellNum == 0: if pPos == 0 or pPos == 1: newPoint = True else: if pPos == 1: newPoint = True if newPoint == True: # Inserting a new point... point = taskMeshBranch.GetPoint(cell.GetPointId(pPos)) # ... with a new id. newId = reorderedPoints.InsertNextPoint(point) pointIdList.append(newId) # To make it easier for remembering the number of points instered in a row. if cellNum == 0 and pPos == 0: rowBasePrev = newId else: # Perhaps this can be done in a nicer way. # Calculate the id of a previously inserted point. if ringNum == ringIds[0]: if cellNum == 1: if pPos == 0: pointIdList.append(1) elif pPos == 3: pointIdList.append(2) else: if pPos == 0: pointIdList.append( int(reorderedPoints.GetNumberOfPoints( ) - 2)) elif pPos == 3: pointIdList.append( int(reorderedPoints.GetNumberOfPoints( ) - 3)) elif ringNum == ringIds[1]: if cellNum == 0: if pPos == 2: pointIdList.append(1) elif pPos == 3: pointIdList.append(0) else: if pPos == 0: pointIdList.append( int(reorderedPoints.GetNumberOfPoints( ) - 1)) elif pPos == 2: pointIdList.append(int(cellNum * 2 + 2)) elif pPos == 3: if cellNum == 1: pointIdList.append(1) else: pointIdList.append(int(cellNum * 2)) else: if cellNum == 0: if pPos == 2: pointIdList.append(int(rowBase + 1)) elif pPos == 3: pointIdList.append(int(rowBase)) else: if pPos == 0: pointIdList.append( int(reorderedPoints.GetNumberOfPoints( ) - 1)) elif pPos == 2: pointIdList.append( int(rowBase + cellNum + 1)) elif pPos == 3: pointIdList.append(int(rowBase + cellNum)) # print(pointIdList, rowBase) # Insert the ids into the cell array. newCell = vtk.vtkQuad() newCell.GetPointIds().Reset() for id in pointIdList[1:]: newCell.GetPointIds().InsertNextId(id) reorderedCellArray.InsertNextCell(newCell) rowBase = rowBasePrev # print('\n') print("Inserted", reorderedPoints.GetNumberOfPoints(), "task mesh points for label", label, "...") print("Inserted", reorderedCellArray.GetNumberOfCells(), "task mesh cells for label", label, "...") # Create new vtkPolyData object for the new reordered mesh. reorderedTaskMeshBranch = vtk.vtkPolyData() # Put the reordered points and cells into the reordered mesh. reorderedTaskMeshBranch.SetPoints(reorderedPoints) reorderedTaskMeshBranch.SetPolys(reorderedCellArray) # Write the VTK file. reorderedMeshWriter = vtk.vtkXMLPolyDataWriter() reorderedMeshWriter.SetInputData(reorderedTaskMeshBranch) reorderedMeshWriter.SetFileName(taskVTKFiles[label]) reorderedMeshWriter.Update() print("Rings per label:", numRingsPerLabel, "...") ringsPerLabelVals = numRingsPerLabel.values() # Check all rings per label values are the same. # assert ringsPerLabelVals[1:] == ringsPerLabelVals[:-1], "All values of rings per label must be identical. Generated output is invalid ..." print(ringsPerLabelVals) # Working with EC mesh. ecMeshReader = vtk.vtkXMLPolyDataReader() ecMeshReader.SetFileName(meshSet[1]) ecMeshReader.Update() # Original ECs mesh to work with. ecMesh = ecMeshReader.GetOutput() print("There are", ecMesh.GetNumberOfCells(), "ECs in total ...") # For every label in the range of labels we want to extract all ECs. for label in labelRange: # Keep track of how many branches we need to skip. numECsPerLabel = numQuadsPerRing * numRingsPerLabel[ label] * numECsPerQuad ecCellOffset = label * numECsPerLabel print("ecCellOffset", ecCellOffset) # Collect cell ids to select. selectionIds = vtk.vtkIdTypeArray() for sId in range(0, int(numECsPerLabel)): selectionIds.InsertNextValue(int(ecCellOffset) + sId) # Create selecion node. selectionNode = vtk.vtkSelectionNode() selectionNode.SetFieldType(selectionNode.CELL) selectionNode.SetContentType(selectionNode.INDICES) selectionNode.SetSelectionList(selectionIds) # Create selection. selection = vtk.vtkSelection() selection.AddNode(selectionNode) # Use vtkSelection filter. selectionExtractor = vtk.vtkExtractSelection() selectionExtractor.SetInputData(0, ecMesh) selectionExtractor.SetInputData(1, selection) selectionExtractor.Update() extractedECs = selectionExtractor.GetOutput() # Ring ids list for traversal. ringIds = range(0, int(numRingsPerLabel[label])) ringIds = list(ringIds) ringIds.reverse() # Number of ECs rows is the number of ECs per quad. rowIds = range(0, numECsPerCol) rowIds = list(rowIds) rowIds.reverse() # The ECs are organised in rings of blocks of cells. # New vtkCellArray for storing reordeced cells. reorderedCellArray = vtk.vtkCellArray() # Iterate over the rings in reverse order. for ringNum in ringIds: # Iterate over the 'imaginary' quads of cells in normal order. for quadNum in range(0, numQuadsPerRing): # Iterate over the rows of cells in reverse order. # Calculate the 'real' id for the 'imaginary' quad. quadId = ringNum * numQuadsPerRing + quadNum # Iterate over rows of cells in reverse order. for rowNum in rowIds: # Iterate over the rows of cells in normal order. for ecNum in range(0, numECsPerRow): # Calculate the 'real' ec cell id and get the corresponding cell. ecId = quadId * numECsPerQuad + rowNum * numECsPerRow + ecNum ecCell = extractedECs.GetCell(ecId) reorderedCellArray.InsertNextCell(ecCell) # Create new vtkPolyData object for the new reordered mesh. reorderedECMeshBranch = vtk.vtkPolyData() # Insert our new points. reorderedECMeshBranch.SetPoints(extractedECs.GetPoints()) # Set the reordered cells to the reordered ECs mesh. reorderedECMeshBranch.SetPolys(reorderedCellArray) # New vtkPoints for storing reordered points. reorderedPoints = vtk.vtkPoints() # New vtkCellArray for storing reordeced cells. reorderedCellArray = vtk.vtkCellArray() rowBase = 0 # Iterate over quads in normal order because they have been reordered. for quadNum in range(0, int(numRingsPerLabel[label]) * numQuadsPerRing): # Iterate over rows in normal order because they have been reordered. for rowNum in range(0, numECsPerCol): # Iterate over the ECs in the row in normal order. for ecNum in range(0, numECsPerRow): # Calculate the 'real' ec cell id and get the corresponding cell. ecId = quadNum * numECsPerQuad + rowNum * numECsPerRow + ecNum ecCell = reorderedECMeshBranch.GetCell(ecId) # The ids to be written to the TXT file. pointIdList = [ecCell.GetNumberOfPoints()] # Write the appropriate points to the TXT file. for pPos in range(0, ecCell.GetNumberOfPoints()): newPoint = False if rowNum == 0: if ecNum == 0: newPoint = True elif pPos == 1 or pPos == 2: newPoint = True else: if ecNum == 0: if pPos == 0 or pPos == 1: newPoint = True else: if pPos == 1: newPoint = True if newPoint == True: # Inserting a new point... point = reorderedECMeshBranch.GetPoint( ecCell.GetPointId(pPos)) # ... with a new id. newId = reorderedPoints.InsertNextPoint(point) pointIdList.append(newId) if ecNum == 0 and pPos == 0: rowBasePrev = newId else: # Perhaps this can be done in a nicer way. # Calculate the ide of a previously inserted point. if rowNum == 0: if ecNum == 1: if pPos == 0: pointIdList.append( int(reorderedPoints. GetNumberOfPoints() - 3)) elif pPos == 3: pointIdList.append( int(reorderedPoints. GetNumberOfPoints() - 4)) else: if pPos == 0: pointIdList.append( int(reorderedPoints. GetNumberOfPoints() - 2)) elif pPos == 3: pointIdList.append( int(reorderedPoints. GetNumberOfPoints() - 3)) elif rowNum == 1: if ecNum == 0: if pPos == 2: pointIdList.append(int(rowBase + 1)) elif pPos == 3: pointIdList.append(int(rowBase)) else: if pPos == 0: pointIdList.append( int(reorderedPoints. GetNumberOfPoints() - 1)) elif pPos == 2: pointIdList.append( int(rowBase + ecNum * 2 + 2)) elif pPos == 3: if ecNum == 1: pointIdList.append(int(rowBase + 1)) else: pointIdList.append( int(rowBase + ecNum * 2)) else: if ecNum == 0: if pPos == 2: pointIdList.append(int(rowBase + 1)) elif pPos == 3: pointIdList.append(int(rowBase)) else: if pPos == 0: pointIdList.append( int(reorderedPoints. GetNumberOfPoints() - 1)) elif pPos == 2: pointIdList.append( int(rowBase + ecNum + 1)) elif pPos == 3: pointIdList.append(int(rowBase + ecNum)) # print(pointIdList, rowBase) # Insert the ids into the cell array. newCell = vtk.vtkQuad() newCell.GetPointIds().Reset() for id in pointIdList[1:]: newCell.GetPointIds().InsertNextId(id) reorderedCellArray.InsertNextCell(newCell) rowBase = rowBasePrev # print('\n') print("There are", reorderedPoints.GetNumberOfPoints(), "ECs points for label", label, "...") print("There are", reorderedCellArray.GetNumberOfCells(), "ECs cells for label", label, "...") # Create new vtkPolyData object for the new reordered mesh. reorderedECs = vtk.vtkPolyData() # Put the reordered points and cells into the mesh. reorderedECs.SetPoints(reorderedPoints) reorderedECs.SetPolys(reorderedCellArray) # Write the VTK EC mesh file. reorderedMeshWriter = vtk.vtkXMLPolyDataWriter() reorderedMeshWriter.SetInputData(reorderedECs) reorderedMeshWriter.SetFileName(ecVTKFiles[label]) reorderedMeshWriter.Update() # Use VTK centroid filter to get the centroids in the right order # from the reorderedECMeshBranch. centroidFilter = vtk.vtkCellCenters() centroidFilter.SetInputData(reorderedECs) centroidFilter.Update() # Create a vertex cell for each point. pointsToVerticesFilter = vtk.vtkVertexGlyphFilter() pointsToVerticesFilter.SetInputData(centroidFilter.GetOutput()) pointsToVerticesFilter.Update() reorderedCentroidBranch = pointsToVerticesFilter.GetOutput() # Write the VTK EC centrouid file. centroidWriter = vtk.vtkXMLPolyDataWriter() centroidWriter.SetInputData(reorderedCentroidBranch) centroidWriter.SetFileName(ecCentroidVTKFiles[label]) centroidWriter.Update() # Write the centroids to the TXT points and cells files. for cId in range(0, reorderedCentroidBranch.GetNumberOfCells()): centCell = reorderedCentroidBranch.GetCell(cId) centIds = [centCell.GetNumberOfPoints()] # Write centroid ids. ptId = centCell.GetPointId(0) centIds.append(ptId) # Write centroid points. point = reorderedCentroidBranch.GetPoint(ptId) # Working with SMC mesh. # Working with SMC mesh. # Working with SMC mesh. smcMeshReader = vtk.vtkXMLPolyDataReader() smcMeshReader.SetFileName(meshSet[2]) smcMeshReader.Update() # Original SMCs mesh to work with. smcMesh = smcMeshReader.GetOutput() print("There are", smcMesh.GetNumberOfCells(), "SMCs in total ...") # For every label in the range of labels we want to extract all SMCs. for label in labelRange: # Keep track of how many branches we need to skip. numSMCsPerLabel = numQuadsPerRing * numRingsPerLabel[ label] * numSMCsPerQuad smcCellOffset = label * numSMCsPerLabel print("smcCellOffset", smcCellOffset) # Collect cell ids to select. selectionIds = vtk.vtkIdTypeArray() for sId in range(0, int(numSMCsPerLabel)): selectionIds.InsertNextValue(int(smcCellOffset) + sId) # Create selecion node. selectionNode = vtk.vtkSelectionNode() selectionNode.SetFieldType(selectionNode.CELL) selectionNode.SetContentType(selectionNode.INDICES) selectionNode.SetSelectionList(selectionIds) # Create selection. selection = vtk.vtkSelection() selection.AddNode(selectionNode) # Use vtkSelection filter. selectionExtractor = vtk.vtkExtractSelection() selectionExtractor.SetInputData(0, smcMesh) selectionExtractor.SetInputData(1, selection) selectionExtractor.Update() extractedSMCs = selectionExtractor.GetOutput() # Ring ids list for traversal. ringIds = range(0, int(numRingsPerLabel[label])) ringIds = list(ringIds) ringIds.reverse() # Number of SMCs rows is the number of ECs per quad times 13. rowIds = range(0, numSMCsPerCol) rowIds = list(rowIds) rowIds.reverse() # The SMCs are organised in rings of blocks of cells. # New vtkCellArray for storing reordeced cells. reorderedCellArray = vtk.vtkCellArray() # Iterate over the rings in reverse order. for ringNum in ringIds: # Iterate over the 'imaginary' quads of cells in normal order. for quadNum in range(0, numQuadsPerRing): # Iterate over the rows of cells in reverse order. # Calculate the 'real' id for the 'imaginary' quad. quadId = ringNum * numQuadsPerRing + quadNum # Iterate over rows of cells in reverse order. for rowNum in rowIds: # Iterate over the rows of cells in normal order. for smcNum in range(0, numSMCsPerRow): # Calculate the 'real' smc cell id and get the corresponding cell. smcId = quadId * numSMCsPerQuad + rowNum * numSMCsPerRow + smcNum smcCell = extractedSMCs.GetCell(smcId) reorderedCellArray.InsertNextCell(smcCell) # Create new vtkPolyData object for the new reordered mesh. reorderedSMCMeshBranch = vtk.vtkPolyData() # Insert our new points. reorderedSMCMeshBranch.SetPoints(extractedSMCs.GetPoints()) # Set the reordered cells to the reordered SMCs mesh. reorderedSMCMeshBranch.SetPolys(reorderedCellArray) # New vtkPoints for storing reordered points. reorderedPoints = vtk.vtkPoints() # New vtkCellArray for storing reordeced cells. reorderedCellArray = vtk.vtkCellArray() rowBase = 0 # Iterate over quads in normal order because they have been reordered. for quadNum in range(0, int(numRingsPerLabel[label]) * numQuadsPerRing): # Iterate over rows in normal order because they have been reordered. for rowNum in range(0, numSMCsPerCol): # Iterate over the SMCs in the row in normal order. for smcNum in range(0, numSMCsPerRow): # Calculate the 'real' smc cell id and get the corresponding cell. smcId = quadNum * numSMCsPerQuad + rowNum * numSMCsPerRow + smcNum smcCell = reorderedSMCMeshBranch.GetCell(smcId) # The ids to be written to the TXT file. pointIdList = [smcCell.GetNumberOfPoints()] # Write the appropriate points to the TXT file. for pPos in range(0, smcCell.GetNumberOfPoints()): newPoint = False if rowNum == 0: if smcNum == 0: newPoint = True elif pPos == 1 or pPos == 2: newPoint = True else: if smcNum == 0: if pPos == 0 or pPos == 1: newPoint = True else: if pPos == 1: newPoint = True if newPoint == True: # Inserting a new point... point = reorderedSMCMeshBranch.GetPoint( smcCell.GetPointId(pPos)) # with a new id. newId = reorderedPoints.InsertNextPoint(point) pointIdList.append(newId) if smcNum == 0 and pPos == 0: rowBasePrev = newId else: # Perhaps this can be done in a nicer way. # Calculate the ide of a previously inserted point. if rowNum == 0: if smcNum == 1: if pPos == 0: pointIdList.append( int(reorderedPoints. GetNumberOfPoints() - 3)) elif pPos == 3: pointIdList.append( int(reorderedPoints. GetNumberOfPoints() - 4)) else: if pPos == 0: pointIdList.append( int(reorderedPoints. GetNumberOfPoints() - 2)) elif pPos == 3: pointIdList.append( int(reorderedPoints. GetNumberOfPoints() - 3)) elif rowNum == 1: if smcNum == 0: if pPos == 2: pointIdList.append(int(rowBase + 1)) elif pPos == 3: pointIdList.append(int(rowBase)) else: if pPos == 0: pointIdList.append( int(reorderedPoints. GetNumberOfPoints() - 1)) elif pPos == 2: pointIdList.append( int(rowBase + smcNum * 2 + 2)) elif pPos == 3: if smcNum == 1: pointIdList.append(int(rowBase + 1)) else: pointIdList.append( int(rowBase + smcNum * 2)) else: if smcNum == 0: if pPos == 2: pointIdList.append(int(rowBase + 1)) elif pPos == 3: pointIdList.append(int(rowBase)) else: if pPos == 0: pointIdList.append( int(reorderedPoints. GetNumberOfPoints() - 1)) elif pPos == 2: pointIdList.append( int(rowBase + smcNum + 1)) elif pPos == 3: pointIdList.append( int(rowBase + smcNum)) # print(pointIdList, rowBase) # Insert the ids into the cell array. newCell = vtk.vtkQuad() newCell.GetPointIds().Reset() for id in pointIdList[1:]: newCell.GetPointIds().InsertNextId(id) reorderedCellArray.InsertNextCell(newCell) rowBase = rowBasePrev # print('\n') print("There are", reorderedPoints.GetNumberOfPoints(), "SMCs points for label", label, "...") print("There are", reorderedCellArray.GetNumberOfCells(), "SMCs cells for label", label, "...") # Create new vtkPolyData object for the new reordered mesh. reorderedSMCs = vtk.vtkPolyData() # Put the reordered points and cells in to the mesh. reorderedSMCs.SetPoints(reorderedPoints) reorderedSMCs.SetPolys(reorderedCellArray) # Write the VTK SMC mesh file. reorderedMeshWriter = vtk.vtkXMLPolyDataWriter() reorderedMeshWriter.SetInputData(reorderedSMCs) reorderedMeshWriter.SetFileName(smcVTKFiles[label]) reorderedMeshWriter.Update() print("All done ...") print("... Except the last configuration_info.txt file ...") configFile = open("files/configuration_info.txt", 'w') configFile.write("Processors information\n") configFile.write("Total number of points per branch (vtk points) = %d\t\tm = %d n = %d\n" \ % ((numQuadsPerRing + 1) * (numRingsPerLabel[0] + 1), (numQuadsPerRing + 1), (numRingsPerLabel[0] + 1))) configFile.write("Total number of cells per branch (vtk cells) = %d\t\tm = %d n = %d\n" \ % (numQuadsPerRing * numRingsPerLabel[0], numQuadsPerRing, numRingsPerLabel[0])) configFile.write("Total number of SMC mesh points per processor mesh (vtk points) = %d\t\tm = %d n = %d\n" \ % ((numSMCsPerCol + 1) * (numSMCsPerRow + 1), (numSMCsPerCol + 1), (numSMCsPerRow + 1))) configFile.write("Total number of SMC mesh cells per processor mesh (vtk cells) = %d\t\tm = %d n = %d\n" \ % (numSMCsPerCol * numSMCsPerRow, numSMCsPerCol, numSMCsPerRow)) configFile.write("Total number of EC mesh points per processor mesh (vtk points) = %d\t\tm = %d n = %d\n" \ % ((numECsPerCol + 1) * (numECsPerRow + 1), (numECsPerCol + 1), (numECsPerRow + 1))) configFile.write("Total number of EC mesh cells per processor mesh (vtk cells) = %d\t\tm = %d n = %d\n" \ % (numECsPerCol *numECsPerRow, numECsPerCol, numECsPerRow)) configFile.write("Total number of EC mesh centeroid points per processor mesh (vtk points) = %d\t\tm = %d n = %d\n" \ % (numECsPerCol *numECsPerRow, numECsPerCol, numECsPerRow)) configFile.write("Total number of EC mesh centeroid cells per processor mesh (vtk cells) = %d\t\tm = %d n = %d\n" \ % (numECsPerCol *numECsPerRow, numECsPerCol, numECsPerRow)) configFile.close() print("Now it is all done for real ...")
if (trilabel[tri_id] == 0): #if not labeled yet trilabel[tri_id] = region_id neighb = find_celledge_neighbors(tri_id, tri) #print('Neighbors ', neighb) for j in range(len(neighb)): if trilabel[neighb[j]] == 0: #see if the triangles tri_id and neighb[j] are on the different sides of the line #i.e. if they share any pair of points of the line if not triangles_on_any_line(tri_id, neighb[j], tri, lines): tri_stack.append(neighb[j]) # In[11]: array = vtk.vtkIdTypeArray() array.SetName(array_name) array.SetNumberOfComponents(1) array.SetNumberOfTuples(trilabel.shape[0]) for i in range(trilabel.shape[0]): array.SetTuple1(i, trilabel[i]) mesh.GetCellData().AddArray(array) wr = vtk.vtkPolyDataWriter() wr.SetFileName(output_mesh) wr.SetInputData(mesh) wr.Write()
def rasterizeFibers(self,fiberNode,labelNode,labelValue=1,samplingDistance=0.1): """Trace through the given fiber bundles and set the corresponding pixels in the given labelNode volume""" print('rasterizing...') rasToIJK = vtk.vtkMatrix4x4() labelNode.GetRASToIJKMatrix(rasToIJK) labelArray = slicer.util.array(labelNode.GetID()) polyData = fiberNode.GetPolyData() cellCount = polyData.GetNumberOfCells() selection = vtk.vtkSelection() selectionNode = vtk.vtkSelectionNode() selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL) selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES) extractor = vtk.vtkExtractSelectedPolyDataIds() extractor.SetInputData(0, polyData) resampler = vtk.vtkPolyDataPointSampler() resampler.GenerateEdgePointsOn() resampler.GenerateVertexPointsOff() resampler.GenerateInteriorPointsOff() resampler.GenerateVerticesOff() resampler.SetDistance(samplingDistance) cellIds = vtk.vtkIdTypeArray() # as a compromise between memory blowup (for large fiberbundles) and not # eating time in the python loop, resample CELLS_TO_PROCESS at once. CELLS_TO_PROCESS = 100 for startCellId in xrange(0, cellCount, CELLS_TO_PROCESS): # generate list of cell Ids to sample cellIdsAr = numpy.arange(startCellId, min(cellCount, startCellId + CELLS_TO_PROCESS)) cellIds.SetVoidArray(cellIdsAr, cellIdsAr.size, 1) # update the selection node to extract those cells selectionNode.SetSelectionList(cellIds) selection.AddNode(selectionNode) selection.Modified() extractor.SetInputData(1, selection) extractor.Update() resampler.SetInputConnection(extractor.GetOutputPort()) resampler.Update() # get the resampler output # note: to test without resampling, just use # `pdSubset = extractor.GetOutput()` instead pdSubset = resampler.GetOutput() pointCount = pdSubset.GetNumberOfPoints() points = pdSubset.GetPoints() for pointIndex in xrange(pointCount): point = points.GetPoint(pointIndex) ijkFloat = rasToIJK.MultiplyPoint(point+(1,))[:3] # skip any negative indices to avoid wrap-around # to the other side of the image. if (any(coord < 0 for coord in ijkFloat)): continue ijk = [int(round(element)) for element in ijkFloat] ijk.reverse() try: # paint the voxels labelArray[tuple(ijk)] = labelValue except IndexError: pass # reset the selection node selection.RemoveAllNodes() labelNode.GetImageData().Modified() labelNode.Modified() print('finished')
def buildPolyData(vertices, faces=None, lines=None, indexOffset=0, fast=True): """ Build a ``vtkPolyData`` object from a list of vertices where faces represents the connectivity of the polygonal mesh. E.g. : - ``vertices=[[x1,y1,z1],[x2,y2,z2], ...]`` - ``faces=[[0,1,2], [1,2,3], ...]`` Use ``indexOffset=1`` if face numbering starts from 1 instead of 0. if fast=False the mesh is built "manually" by setting polygons and triangles one by one. This is the fallback case when a mesh contains faces of different number of vertices. """ if len(vertices[0]) < 3: # make sure it is 3d vertices = np.c_[np.array(vertices), np.zeros(len(vertices))] if len(vertices[0]) == 2: vertices = np.c_[np.array(vertices), np.zeros(len(vertices))] poly = vtk.vtkPolyData() sourcePoints = vtk.vtkPoints() sourcePoints.SetData( numpy_to_vtk(np.ascontiguousarray(vertices), deep=True)) poly.SetPoints(sourcePoints) if lines is not None: # Create a cell array to store the lines in and add the lines to it linesarr = vtk.vtkCellArray() for i in range(1, len(lines) - 1): vline = vtk.vtkLine() vline.GetPointIds().SetId(0, lines[i]) vline.GetPointIds().SetId(1, lines[i + 1]) linesarr.InsertNextCell(vline) poly.SetLines(linesarr) if faces is None: sourceVertices = vtk.vtkCellArray() for i in range(len(vertices)): sourceVertices.InsertNextCell(1) sourceVertices.InsertCellPoint(i) poly.SetVerts(sourceVertices) return poly ################### # faces exist sourcePolygons = vtk.vtkCellArray() faces = np.array(faces) if len(faces.shape) == 2 and indexOffset == 0 and fast: #################### all faces are composed of equal nr of vtxs, FAST ast = np.int32 if vtk.vtkIdTypeArray().GetDataTypeSize() != 4: ast = np.int64 nf, nc = faces.shape hs = np.hstack((np.zeros(nf)[:, None] + nc, faces)).astype(ast).ravel() arr = numpy_to_vtkIdTypeArray(hs, deep=True) sourcePolygons.SetCells(nf, arr) else: ########################################## manually add faces, SLOW showbar = False if len(faces) > 25000: showbar = True pb = ProgressBar(0, len(faces), ETA=False) for f in faces: n = len(f) if n == 3: ele = vtk.vtkTriangle() pids = ele.GetPointIds() for i in range(3): pids.SetId(i, f[i] - indexOffset) sourcePolygons.InsertNextCell(ele) elif n == 4: # do not use vtkTetra() because it fails # with dolfin faces orientation ele0 = vtk.vtkTriangle() ele1 = vtk.vtkTriangle() ele2 = vtk.vtkTriangle() ele3 = vtk.vtkTriangle() if indexOffset: for i in [0, 1, 2, 3]: f[i] -= indexOffset f0, f1, f2, f3 = f pid0 = ele0.GetPointIds() pid1 = ele1.GetPointIds() pid2 = ele2.GetPointIds() pid3 = ele3.GetPointIds() pid0.SetId(0, f0) pid0.SetId(1, f1) pid0.SetId(2, f2) pid1.SetId(0, f0) pid1.SetId(1, f1) pid1.SetId(2, f3) pid2.SetId(0, f1) pid2.SetId(1, f2) pid2.SetId(2, f3) pid3.SetId(0, f2) pid3.SetId(1, f3) pid3.SetId(2, f0) sourcePolygons.InsertNextCell(ele0) sourcePolygons.InsertNextCell(ele1) sourcePolygons.InsertNextCell(ele2) sourcePolygons.InsertNextCell(ele3) else: ele = vtk.vtkPolygon() pids = ele.GetPointIds() pids.SetNumberOfIds(n) for i in range(n): pids.SetId(i, f[i] - indexOffset) sourcePolygons.InsertNextCell(ele) if showbar: pb.print("converting mesh... ") poly.SetPolys(sourcePolygons) return poly
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 = {y: x for x, y in vtk_to_meshio_type.items()} # 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.items(): numcells, num_local_nodes = data.shape if meshio_type[:7] == "polygon": vtk_type = meshio_to_vtk_type[meshio_type[:7]] else: 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 _set_cells(cells, n_cells, id_typ_arr): vtk_arr = vtk.vtkIdTypeArray() array2vtk(id_typ_arr, vtk_arr) cells.SetCells(n_cells, vtk_arr)
def convert2VPD(M,clean=False): """Convert pyFormex data to vtkPolyData. Convert a pyFormex Mesh or Coords object into vtkPolyData. This is limited to vertices, lines, and polygons. Lines should already be ordered (with connectedLineElems for instance). Parameters: - `M`: a Mesh or Coords type. If M is a Coords type it will be saved as VERTS. Else... - `clean`: if True, the resulting vtkdata will be cleaned by calling cleanVPD. Returns a vtkPolyData. """ from vtk import vtkPolyData,vtkPoints,vtkIdTypeArray,vtkCellArray print('STARTING CONVERSION FOR DATA OF TYPE %s '%type(M)) if type(M) == Coords: M = Mesh(M,arange(M.ncoords())) Nelems = M.nelems() # Number of elements Ncxel = M.nplex() # # Number of nodes per element # create a vtkPolyData variable vpd=vtkPolyData() # creating vtk coords pts = vtkPoints() ntype=gnat(pts.GetDataType()) coordsv = n2v(asarray(M.coords,order='C',dtype=ntype),deep=1) #.copy() # deepcopy array conversion for C like array of vtk, it is necessary to avoid memry data loss pts.SetNumberOfPoints(M.ncoords()) pts.SetData(coordsv) vpd.SetPoints(pts) # create vtk connectivity elms = vtkIdTypeArray() ntype=gnat(vtkIdTypeArray().GetDataType()) elmsv = concatenate([Ncxel*ones(Nelems).reshape(-1,1),M.elems],axis=1) elmsv = n2v(asarray(elmsv,order='C',dtype=ntype),deep=1) #.copy() # deepcopy array conversion for C like array of vtk, it is necessary to avoid memry data loss elms.DeepCopy(elmsv) # set vtk Cell data datav = vtkCellArray() datav.SetCells(Nelems,elms) if Ncxel == 1: try: print("setting VERTS for data with %s maximum number of point for cell "%Ncxel) vpd.SetVerts(datav) except: raise ValueError,"Error in saving VERTS" elif Ncxel == 2: try: print ("setting LINES for data with %s maximum number of point for cell "%Ncxel) vpd.SetLines(datav) except: raise ValueError,"Error in saving LINES" else: try: print ("setting POLYS for data with %s maximum number of point for cell "%Ncxel) vpd.SetPolys(datav) except: raise ValueError,"Error in saving POLYS" vpd.Update() if clean: vpd=cleanVPD(vpd) return vpd
def Pick(self, selectionX, selectionY, selectionZ, renderer=None): self.ids.Reset() if renderer is None: print "Renderer has not been set!" return self.Renderer = renderer ray_result = picking_ray([selectionX, selectionY, selectionZ], renderer) if ray_result != -1: self.selection_point = ray_result[0] self.PickPosition = ray_result[1] self.p1World = ray_result[2] self.p2World = ray_result[3] else: return tol = self.Tolerance self.FindCellsAlongLine(self.p1World[:3], self.p2World[:3], tol, self.ids) self.ClosestCellId = -1 self.ClosestCellGlobalId = -1 # determine which cells are actually intersected data = self.GetDataSet() global_ids = data.GetCellData().GetGlobalIds() self.id_array.Reset() self.global_id_array.Reset() self.id_list = [] self.global_id_list = [] t = mutable(0.) x = [0, 0, 0] pcoords = [0, 0, 0] subId = mutable(0) OFFSET_ELEMENT = vtk_globals.OFFSET_ELEMENT my_int = int for i in xrange(self.ids.GetNumberOfIds()): id = self.ids.GetId(i) cell = data.GetCell(id) try: if not self.cells_to_pick_from[cell.GetCellType()]: continue except IndexError: continue nodes_exist = False if cell.IntersectWithLine(self.p1World[:3], self.p2World[:3], tol, t, x, pcoords, subId): self.id_array.InsertNextValue(id) self.id_list.append(id) global_id = my_int(global_ids.GetTuple(id)[0]) self.global_id_list.append(global_id) self.global_id_array.InsertNextValue(global_id) #print global_id if global_id < OFFSET_ELEMENT: nodes_exist = True if nodes_exist: new_id_array = vtk.vtkIdTypeArray() new_id_array.ShallowCopy(self.id_array) new_global_id_array = vtk.vtkIdTypeArray() new_global_id_array.ShallowCopy(self.global_id_array) for i in xrange(self.id_array.GetNumberOfTuples()): global_id = my_int(self.global_id_array.GetTuple(i)[0]) id = my_int(self.id_array.GetTuple(i)[0]) if global_id < OFFSET_ELEMENT: new_global_id_array.InsertNextValue(global_id) new_id_array.InsertNextValue(id) new_global_id_array.Squeeze() new_id_array.Squeeze() self.id_array.Reset() self.global_id_array.Reset() self.id_array.ShallowCopy(new_id_array) self.global_id_array.ShallowCopy(new_global_id_array) else: self.id_array.Squeeze() self.global_id_array.Squeeze() self.update_ids()
def writeHdf5(): # This is where the data is for testing purposes. print("Current working directory:", os.getcwd()) print(taskMeshIn) numQuadsPerRing = circQuads # Working with the task mesh junt to figure out the quads and rows numbers. taskMeshReader = vtk.vtkXMLPolyDataReader() taskMeshReader.SetFileName(taskMeshIn) taskMeshReader.Update() taskMesh = taskMeshReader.GetOutput() print(taskMesh.GetNumberOfPoints()) ecMeshReader = vtk.vtkXMLPolyDataReader() ecMeshReader.SetFileName(ecMeshIn) ecMeshReader.Update() ecMesh = ecMeshReader.GetOutput() print(ecMesh.GetNumberOfPoints()) # Get the range of branch labels. labelRange = [0, 0] taskMesh.GetCellData().GetScalars().GetRange(labelRange, 0) # Convert label range to a list of labels. labelRange = range(int(labelRange[0]), int(labelRange[1]) + 1) print("Labels found in task mesh:", labelRange) # Store the number of rings for each label. numRingsPerLabel = {} # For every label in the range of labels we want to extract all cells/quads. for label in labelRange: # Use this filter to extract the cells for a given label value. branchSelector = vtk.vtkThreshold() branchSelector.SetInputData(taskMesh) branchSelector.ThresholdBetween(label, label) branchSelector.Update() taskMeshBranch = branchSelector.GetOutput() numQuadRowsPerBranch = taskMeshBranch.GetNumberOfCells( ) / numQuadsPerRing numRingsPerLabel[label] = numQuadRowsPerBranch # Working with EC mesh only atpMeshReader = vtk.vtkXMLPolyDataReader() atpMeshReader.SetFileName(atpMeshIn) atpMeshReader.Update() # Original ECs mesh to work with. atpMesh = atpMeshReader.GetOutput() print("There are", atpMesh.GetNumberOfCells(), "ATP values in total ...") parentFile = h5py.File(atpHdf5Files[0], 'w') leftBranchFile = h5py.File(atpHdf5Files[1], 'w') rightBranchFile = h5py.File(atpHdf5Files[2], 'w') appendPolyData = vtk.vtkAppendPolyData() # For every label in the range of labels we want to extract all ECs. for label in labelRange: ecMeshReader = vtk.vtkXMLPolyDataReader() ecMeshReader.SetFileName(ecVTPFiles[label]) ecMeshReader.Update() tmpPolyData = ecMeshReader.GetOutput() # Keep track of how many branches we need to skip. numECsPerLabel = numQuadsPerRing * numRingsPerLabel[ label] * numECsPerQuad atpCellOffset = label * numECsPerLabel print("atpCellOffset", atpCellOffset) # Collect cell ids to select. selectionIds = vtk.vtkIdTypeArray() for sId in range(0, int(numECsPerLabel)): selectionIds.InsertNextValue(int(atpCellOffset) + sId) # Create selecion node. selectionNode = vtk.vtkSelectionNode() selectionNode.SetFieldType(selectionNode.CELL) selectionNode.SetContentType(selectionNode.INDICES) selectionNode.SetSelectionList(selectionIds) # Create selection. selection = vtk.vtkSelection() selection.AddNode(selectionNode) # Use vtkSelection filter. selectionExtractor = vtk.vtkExtractSelection() selectionExtractor.SetInputData(0, atpMesh) selectionExtractor.SetInputData(1, selection) selectionExtractor.Update() extractedCells = selectionExtractor.GetOutput() # Ring ids list for traversal. ringIds = range(0, int(numRingsPerLabel[label])) ringIds = list(ringIds) ringIds.reverse() # Number of ECs rows is the number of ECs per quad. rowIds = range(0, numECsPerCol) rowIds = list(rowIds) rowIds.reverse() reorderedATPArray = vtk.vtkDoubleArray() reorderedATPArray.SetName("initialATP") # Decide which TXT files to write to. pointsOf = '' if label == 0: pointsOf = parentFile elif label == 1: pointsOf = leftBranchFile elif label == 2: pointsOf = rightBranchFile print("Writing H5 file for ECs ATP:") print(pointsOf) dset = pointsOf.create_dataset("/atp", (numECsPerLabel, ), 'f') i = 0 # Iterate over the rings in reverse order. for ringNum in ringIds: # Iterate over the 'imaginary' quads of cells in normal order. for quadNum in range(0, numQuadsPerRing): # Iterate over the rows of cells in reverse order. # Calculate the 'real' id for the 'imaginary' quad. quadId = ringNum * numQuadsPerRing + quadNum # Iterate over rows of cells in reverse order. for rowNum in rowIds: # Iterate over the rows of cells in normal order. for cellNum in range(0, numECsPerRow): # Calculate the 'real' ec cell id and get the corresponding cell. realId = quadId * numECsPerQuad + rowNum * numECsPerRow + cellNum atpVal = extractedCells.GetCellData().GetArray( "initialATP").GetValue(realId) reorderedATPArray.InsertNextValue(atpVal) # Write the value to the txt file. dset[i] = atpVal i += 1 tmpPolyData.GetCellData().SetScalars(reorderedATPArray) appendPolyData.AddInputData(tmpPolyData) parentFile.close() leftBranchFile.close() rightBranchFile.close() print("Writing reorderd ATP map for verification...") appendPolyData.Update() reorderedATPWriter = vtk.vtkXMLPolyDataWriter() reorderedATPWriter.SetInputData(appendPolyData.GetOutput()) reorderedATPWriter.SetFileName("vtk/reordered_atp.vtp") reorderedATPWriter.Update() print("All done ...")
neighb = find_celledge_neighbors(tri_id, tri) #print('Neighbors ', neighb) for j in range( len(neighb) ): if trilabel[neighb[j]]==0: #see if the triangles tri_id and neighb[j] are on the different sides of the line #i.e. if they share any pair of points of the line if not triangles_on_any_line(tri_id, neighb[j], tri, lines): tri_stack.append(neighb[j]) # In[11]: array = vtk.vtkIdTypeArray() array.SetName(array_name) array.SetNumberOfComponents(1) array.SetNumberOfTuples(trilabel.shape[0]) for i in range(trilabel.shape[0]): array.SetTuple1(i, trilabel[i]) mesh.GetCellData().AddArray(array) wr = vtk.vtkPolyDataWriter() wr.SetFileName(output_mesh) wr.SetInputData(mesh) wr.Write()
def GenerateTetrInFile(self): self.PrintLog('Generating Tetr .in file.') f=open(self.OutputFileName, 'w') line = '$title' + '\n' f.write(line) line = self.OutputFileName + '\n' f.write(line) line = '\n' f.write(line) line = '$compress' + '\n' f.write(line) line = 'gzip -f' + '\n' f.write(line) line = '\n' f.write(line) self.NormalizationTransform.Identity() if (self.NormalizationEntity != ''): sectionBoundaryPointIds = self.GetSectionBoundaryPointIds(self.NormalizationEntity) sectionProperties = SectionProperties() sectionProperties.Mesh = self.Mesh sectionProperties.NormalizationTransform = self.NormalizationTransform sectionProperties.SectionBoundaryPointIds = sectionBoundaryPointIds sectionProperties.Execute() self.NormalizationRadius = sectionProperties.Radius if (self.NormalizationRadius != 0.0) & (self.NormalizationRadius != 1.0): self.NormalizationTransform.Scale(1.0/self.NormalizationRadius,1.0/self.NormalizationRadius,1.0/self.NormalizationRadius) line = '$radius' + '\n' f.write(line) line = str(self.NormalizationRadius) + '\n' f.write(line) line = '\n' f.write(line) line = '$viscosity' + '\n' f.write(line) line = str(0.035) + '\n' f.write(line) line = '\n' f.write(line) line = '$density' + '\n' f.write(line) line = str(1.06) + '\n' f.write(line) line = '\n' f.write(line) line = '$red' + '\n' f.write(line) line = str(0) + '\n' f.write(line) line = '\n' f.write(line) line = '$alpha' + '\n' f.write(line) line = str(0) + '\n' f.write(line) line = '\n' f.write(line) line = '$nsolve' + '\n' f.write(line) line = '22' + '\n' f.write(line) line = '\n' f.write(line) line = '$Uzawa_PC' + '\n' f.write(line) line = '1' + '\n' f.write(line) line = '\n' f.write(line) line = '$node' + '\n' f.write(line) line = str(self.Mesh.GetNumberOfPoints()) + '\n' f.write(line) for i in range(self.Mesh.GetNumberOfPoints()): point = [0.0,0.0,0.0] self.NormalizationTransform.TransformPoint(self.Mesh.GetPoint(i),point) line = str(i+1) + ' ' + str(point[0]) + ' ' + str(point[1]) + ' ' + str(point[2]) + '\n' f.write(line) line = '\n' f.write(line) line = '$elem' + '\n' f.write(line) quadratidTetraCellType = 24 quadraticTetraCellIds = vtk.vtkIdTypeArray() self.Mesh.GetIdsOfCellsOfType(quadratidTetraCellType,quadraticTetraCellIds) line = str(quadraticTetraCellIds.GetNumberOfTuples()) + '\n' f.write(line) for i in range(quadraticTetraCellIds.GetNumberOfTuples()): line = str(i+1) + ' ' cell = self.Mesh.GetCell(quadraticTetraCellIds.GetValue(i)) line += str(cell.GetPointId(0)+1) + ' ' line += str(cell.GetPointId(4)+1) + ' ' line += str(cell.GetPointId(1)+1) + ' ' line += str(cell.GetPointId(5)+1) + ' ' line += str(cell.GetPointId(2)+1) + ' ' line += str(cell.GetPointId(6)+1) + ' ' line += str(cell.GetPointId(7)+1) + ' ' line += str(cell.GetPointId(8)+1) + ' ' line += str(cell.GetPointId(9)+1) + ' ' line += str(cell.GetPointId(3)+1) + ' ' line += '\n' f.write(line) # inletEntities = self.InletEntities # reversedInlets = self.ReverseInlets # inletEntitiesReversed = zip(inletEntities,reversedInlets) # for inletEntityReversed in inletEntitiesReversed: # inletEntity = inletEntityReversed[0] # reversedInlet = inletEntityReversed[1] # if (inletEntity == ''): # continue for inletEntity in self.InletEntities: reversedInlet = inletEntity in self.ReverseInletEntities line = '\n' f.write(line) line = '$binlet' + ' (' + inletEntity + ') ' + '\n' f.write(line) entityArray = self.Mesh.GetPointData().GetArray(inletEntity) numberOfEntityNodes = 0 for i in range(entityArray.GetNumberOfTuples()): if (entityArray.GetComponent(i,0) != 1.0): continue numberOfEntityNodes += 1 line = str(numberOfEntityNodes) + '\n' f.write(line) for i in range(entityArray.GetNumberOfTuples()): if (entityArray.GetComponent(i,0) != 1.0): continue line = str(i+1) + '\n' f.write(line) sectionBoundaryPointIds = self.GetSectionBoundaryPointIds(inletEntity) sectionProperties = SectionProperties() sectionProperties.Mesh = self.Mesh sectionProperties.NormalizationTransform = self.NormalizationTransform sectionProperties.SectionBoundaryPointIds = sectionBoundaryPointIds if not reversedInlet: sectionProperties.FlipOutwardNormal = 1 else: sectionProperties.FlipOutwardNormal = 0 sectionProperties.Execute() line = str(sectionProperties.Radius) + '\n' f.write(line) line = str(sectionProperties.Origin[0]) + ' ' + str(sectionProperties.Origin[1]) + ' ' + str(sectionProperties.Origin[2]) + '\n' f.write(line) line = str(sectionProperties.Normal[0]) + ' ' + str(sectionProperties.Normal[1]) + ' ' + str(sectionProperties.Normal[2]) + '\n' f.write(line) #TODO: for every inlet insert fourier coefficients given points of waveform (spline-interpolate points beforehands to get them equispaced). if (self.OutletEntity != ''): line = '\n' f.write(line) line = '$boutlet' + ' (' + self.OutletEntity + ') ' + '\n' f.write(line) entityArray = self.Mesh.GetPointData().GetArray(self.OutletEntity) numberOfEntityNodes = 0 for i in range(entityArray.GetNumberOfTuples()): if (entityArray.GetComponent(i,0) != 1.0): continue numberOfEntityNodes += 1 line = str(numberOfEntityNodes) + '\n' f.write(line) for i in range(entityArray.GetNumberOfTuples()): if (entityArray.GetComponent(i,0) != 1.0): continue line = str(i+1) + '\n' f.write(line) sectionBoundaryPointIds = self.GetSectionBoundaryPointIds(self.OutletEntity) sectionProperties = SectionProperties() sectionProperties.Mesh = self.Mesh sectionProperties.NormalizationTransform = self.NormalizationTransform sectionProperties.SectionBoundaryPointIds = sectionBoundaryPointIds sectionProperties.FlipOutwardNormal = 0 sectionProperties.Execute() line = str(sectionProperties.Radius) + '\n' f.write(line) line = str(sectionProperties.Origin[0]) + ' ' + str(sectionProperties.Origin[1]) + ' ' + str(sectionProperties.Origin[2]) + '\n' f.write(line) line = str(sectionProperties.Normal[0]) + ' ' + str(sectionProperties.Normal[1]) + ' ' + str(sectionProperties.Normal[2]) + '\n' f.write(line) if (self.WallEntity != ''): line = '\n' f.write(line) line = '$bwall' + '\n' f.write(line) entityArray = self.Mesh.GetPointData().GetArray(self.WallEntity) numberOfEntityNodes = 0 for i in range(entityArray.GetNumberOfTuples()): if (entityArray.GetComponent(i,0) != 1.0): continue numberOfEntityNodes += 1 line = str(numberOfEntityNodes) + '\n' f.write(line) for i in range(entityArray.GetNumberOfTuples()): if (entityArray.GetComponent(i,0) != 1.0): continue line = str(i+1) + '\n' f.write(line) wallPointIdsMap = vtk.vtkIdList() if (self.WriteWNodeSection == 1): line = '\n' f.write(line) line = '$wnode' + '\n' f.write(line) line = str(numberOfEntityNodes) + '\n' f.write(line) count = 0 wallPointIdsMap.SetNumberOfIds(entityArray.GetNumberOfTuples()) extractSurface = vtk.vtkGeometryFilter() extractSurface.SetInput(self.Mesh) extractSurface.Update() normalsFilter = vtk.vtkPolyDataNormals() normalsFilter.SetInput(extractSurface.GetOutput()) normalsFilter.AutoOrientNormalsOn() normalsFilter.ConsistencyOn() normalsFilter.Update() normalsSurface = normalsFilter.GetOutput() locator = vtk.vtkMergePoints() locator.SetDataSet(normalsSurface) locator.BuildLocator() for i in range(entityArray.GetNumberOfTuples()): if (entityArray.GetComponent(i,0) != 1.0): wallPointIdsMap.SetId(i,-1) continue wallPointIdsMap.SetId(i,count) point = self.Mesh.GetPoint(i) surfacePointId = locator.FindClosestPoint(point) normal = normalsSurface.GetPointData().GetNormals().GetTuple3(surfacePointId) line = str(count+1) + ' ' + str(i+1) + ' ' + str(normal[0]) + ' ' + str(normal[1]) + ' ' + str(normal[2]) + '\n' f.write(line) count += 1 if (self.WriteWElemSection == 1): line = '\n' f.write(line) line = '$welem' + '\n' f.write(line) dataArray = vtk.vtkIntArray() dataArray.SetNumberOfComponents(8) for i in range(self.Mesh.GetNumberOfCells()): qtetra = self.Mesh.GetCell(i) for j in range(qtetra.GetNumberOfFaces()): face = qtetra.GetFace(j) isBoundaryFace = 1 for k in range(face.GetNumberOfPoints()): if (entityArray.GetComponent(face.GetPointId(k),0) != 1.0): isBoundaryFace = 0 break if (isBoundaryFace == 0): continue dataArray.InsertNextValue(i) dataArray.InsertNextValue(j) for k in range(face.GetNumberOfPoints()): dataArray.InsertNextValue(face.GetPointId(k)) line = str(dataArray.GetNumberOfTuples()) + '\n' f.write(line) for i in range(dataArray.GetNumberOfTuples()): line = str(i+1) + ' ' line += str(int(dataArray.GetComponent(i,0))+1) + ' ' faceId = int(dataArray.GetComponent(i,1)) newTetrFaceIdsMap = [2, 4, 3, 1] line += str(newTetrFaceIdsMap[faceId]) + ' ' for j in range(2,dataArray.GetNumberOfComponents()): line += str(wallPointIdsMap.GetId(int(dataArray.GetComponent(i,j)))+1) + ' ' line += '\n' f.write(line) if (self.HistoryEntity != ''): line = '\n' f.write(line) line = '$history' + '\n' f.write(line) entityArray = self.Mesh.GetPointData().GetArray(self.HistoryEntity) numberOfEntityNodes = 0 for i in range(entityArray.GetNumberOfTuples()): if (entityArray.GetComponent(i,0) != 1.0): continue numberOfEntityNodes += 1 line = str(numberOfEntityNodes) + '\n' f.write(line) for i in range(entityArray.GetNumberOfTuples()): if (entityArray.GetComponent(i,0) != 1.0): continue line = str(i+1) + '\n' f.write(line) self.WriteTimeSteps(f)
def ExtractSelection(fileList): # Report our CWD just for testing purposes. print "CWD:", os.getcwd() ringOffset = numQuadsPerRing * numSMCsPerCol * 4 branchOffset = numRingsPerBranch * ringOffset # Prepare selection id array. selectionIds = vtk.vtkIdTypeArray() for branch in branches: thisBranchOffset = branch * branchOffset # print thisBranchOffset, for ring in range(numRingsPerBranch): thisRingOffset = ring * ringOffset # print thisRingOffset, for cell in range(numSMCsPerCol): thisOffset = start + thisBranchOffset + thisRingOffset + cell # print thisOffset, selectionIds.InsertNextValue(thisOffset) # Create selection node. selectionNode = vtk.vtkSelectionNode() selectionNode.SetFieldType(selectionNode.CELL) selectionNode.SetContentType(selectionNode.INDICES) selectionNode.SetSelectionList(selectionIds) # Create selection. selection = vtk.vtkSelection() selection.AddNode(selectionNode) sortNicely(fileList) # Process every file by extracting selection. for inFile in fileList: print 'Reading file', inFile reader = vtk.vtkXMLUnstructuredGridReader() reader.SetFileName(inFile) print '\tExtracting ', selectionIds.GetNumberOfTuples(), 'cells...' selectionExtractor = vtk.vtkExtractSelection() selectionExtractor.SetInputConnection(reader.GetOutputPort()) if vtk.vtkVersion().GetVTKMajorVersion() > 5: selectionExtractor.SetInputData(1, selection) else: selectionExtractor.SetInput(1, selection) baseName = os.path.basename(inFile) number = [int(s) for s in re.split('([0-9]+)', baseName) if s.isdigit()] outFile = outputPattern + str(number[0]) + '.vtu' print '\t\tSaving file', outFile writer = vtk.vtkXMLUnstructuredGridWriter() writer.SetInputConnection(selectionExtractor.GetOutputPort()) writer.SetFileName(outFile) writer.Update() print '\n' print 'All done...'
def GenerateTetrInFile(self): self.PrintLog('Generating Tetr .in file.') f = open(self.OutputFileName, 'w') line = '$title' + '\n' f.write(line) line = self.OutputFileName + '\n' f.write(line) line = '\n' f.write(line) line = '$compress' + '\n' f.write(line) line = 'gzip -f' + '\n' f.write(line) line = '\n' f.write(line) self.NormalizationTransform.Identity() if (self.NormalizationEntity != ''): sectionBoundaryPointIds = self.GetSectionBoundaryPointIds( self.NormalizationEntity) sectionProperties = SectionProperties() sectionProperties.Mesh = self.Mesh sectionProperties.NormalizationTransform = self.NormalizationTransform sectionProperties.SectionBoundaryPointIds = sectionBoundaryPointIds sectionProperties.Execute() self.NormalizationRadius = sectionProperties.Radius if (self.NormalizationRadius != 0.0) & (self.NormalizationRadius != 1.0): self.NormalizationTransform.Scale(1.0 / self.NormalizationRadius, 1.0 / self.NormalizationRadius, 1.0 / self.NormalizationRadius) line = '$radius' + '\n' f.write(line) line = str(self.NormalizationRadius) + '\n' f.write(line) line = '\n' f.write(line) line = '$viscosity' + '\n' f.write(line) line = str(0.035) + '\n' f.write(line) line = '\n' f.write(line) line = '$density' + '\n' f.write(line) line = str(1.06) + '\n' f.write(line) line = '\n' f.write(line) line = '$red' + '\n' f.write(line) line = str(0) + '\n' f.write(line) line = '\n' f.write(line) line = '$alpha' + '\n' f.write(line) line = str(0) + '\n' f.write(line) line = '\n' f.write(line) line = '$nsolve' + '\n' f.write(line) line = '22' + '\n' f.write(line) line = '\n' f.write(line) line = '$Uzawa_PC' + '\n' f.write(line) line = '1' + '\n' f.write(line) line = '\n' f.write(line) line = '$node' + '\n' f.write(line) line = str(self.Mesh.GetNumberOfPoints()) + '\n' f.write(line) for i in range(self.Mesh.GetNumberOfPoints()): point = [0.0, 0.0, 0.0] self.NormalizationTransform.TransformPoint(self.Mesh.GetPoint(i), point) line = str(i + 1) + ' ' + str(point[0]) + ' ' + str( point[1]) + ' ' + str(point[2]) + '\n' f.write(line) line = '\n' f.write(line) line = '$elem' + '\n' f.write(line) quadratidTetraCellType = 24 quadraticTetraCellIds = vtk.vtkIdTypeArray() self.Mesh.GetIdsOfCellsOfType(quadratidTetraCellType, quadraticTetraCellIds) line = str(quadraticTetraCellIds.GetNumberOfTuples()) + '\n' f.write(line) for i in range(quadraticTetraCellIds.GetNumberOfTuples()): line = str(i + 1) + ' ' cell = self.Mesh.GetCell(quadraticTetraCellIds.GetValue(i)) line += str(cell.GetPointId(0) + 1) + ' ' line += str(cell.GetPointId(4) + 1) + ' ' line += str(cell.GetPointId(1) + 1) + ' ' line += str(cell.GetPointId(5) + 1) + ' ' line += str(cell.GetPointId(2) + 1) + ' ' line += str(cell.GetPointId(6) + 1) + ' ' line += str(cell.GetPointId(7) + 1) + ' ' line += str(cell.GetPointId(8) + 1) + ' ' line += str(cell.GetPointId(9) + 1) + ' ' line += str(cell.GetPointId(3) + 1) + ' ' line += '\n' f.write(line) # inletEntities = self.InletEntities # reversedInlets = self.ReverseInlets # inletEntitiesReversed = zip(inletEntities,reversedInlets) # for inletEntityReversed in inletEntitiesReversed: # inletEntity = inletEntityReversed[0] # reversedInlet = inletEntityReversed[1] # if (inletEntity == ''): # continue for inletEntity in self.InletEntities: reversedInlet = inletEntity in self.ReverseInletEntities line = '\n' f.write(line) line = '$binlet' + ' (' + inletEntity + ') ' + '\n' f.write(line) entityArray = self.Mesh.GetPointData().GetArray(inletEntity) numberOfEntityNodes = 0 for i in range(entityArray.GetNumberOfTuples()): if (entityArray.GetComponent(i, 0) != 1.0): continue numberOfEntityNodes += 1 line = str(numberOfEntityNodes) + '\n' f.write(line) for i in range(entityArray.GetNumberOfTuples()): if (entityArray.GetComponent(i, 0) != 1.0): continue line = str(i + 1) + '\n' f.write(line) sectionBoundaryPointIds = self.GetSectionBoundaryPointIds( inletEntity) sectionProperties = SectionProperties() sectionProperties.Mesh = self.Mesh sectionProperties.NormalizationTransform = self.NormalizationTransform sectionProperties.SectionBoundaryPointIds = sectionBoundaryPointIds if not reversedInlet: sectionProperties.FlipOutwardNormal = 1 else: sectionProperties.FlipOutwardNormal = 0 sectionProperties.Execute() line = str(sectionProperties.Radius) + '\n' f.write(line) line = str(sectionProperties.Origin[0]) + ' ' + str( sectionProperties.Origin[1]) + ' ' + str( sectionProperties.Origin[2]) + '\n' f.write(line) line = str(sectionProperties.Normal[0]) + ' ' + str( sectionProperties.Normal[1]) + ' ' + str( sectionProperties.Normal[2]) + '\n' f.write(line) #TODO: for every inlet insert fourier coefficients given points of waveform (spline-interpolate points beforehands to get them equispaced). if (self.OutletEntity != ''): line = '\n' f.write(line) line = '$boutlet' + ' (' + self.OutletEntity + ') ' + '\n' f.write(line) entityArray = self.Mesh.GetPointData().GetArray(self.OutletEntity) numberOfEntityNodes = 0 for i in range(entityArray.GetNumberOfTuples()): if (entityArray.GetComponent(i, 0) != 1.0): continue numberOfEntityNodes += 1 line = str(numberOfEntityNodes) + '\n' f.write(line) for i in range(entityArray.GetNumberOfTuples()): if (entityArray.GetComponent(i, 0) != 1.0): continue line = str(i + 1) + '\n' f.write(line) sectionBoundaryPointIds = self.GetSectionBoundaryPointIds( self.OutletEntity) sectionProperties = SectionProperties() sectionProperties.Mesh = self.Mesh sectionProperties.NormalizationTransform = self.NormalizationTransform sectionProperties.SectionBoundaryPointIds = sectionBoundaryPointIds sectionProperties.FlipOutwardNormal = 0 sectionProperties.Execute() line = str(sectionProperties.Radius) + '\n' f.write(line) line = str(sectionProperties.Origin[0]) + ' ' + str( sectionProperties.Origin[1]) + ' ' + str( sectionProperties.Origin[2]) + '\n' f.write(line) line = str(sectionProperties.Normal[0]) + ' ' + str( sectionProperties.Normal[1]) + ' ' + str( sectionProperties.Normal[2]) + '\n' f.write(line) if (self.WallEntity != ''): line = '\n' f.write(line) line = '$bwall' + '\n' f.write(line) entityArray = self.Mesh.GetPointData().GetArray(self.WallEntity) numberOfEntityNodes = 0 for i in range(entityArray.GetNumberOfTuples()): if (entityArray.GetComponent(i, 0) != 1.0): continue numberOfEntityNodes += 1 line = str(numberOfEntityNodes) + '\n' f.write(line) for i in range(entityArray.GetNumberOfTuples()): if (entityArray.GetComponent(i, 0) != 1.0): continue line = str(i + 1) + '\n' f.write(line) wallPointIdsMap = vtk.vtkIdList() if (self.WriteWNodeSection == 1): line = '\n' f.write(line) line = '$wnode' + '\n' f.write(line) line = str(numberOfEntityNodes) + '\n' f.write(line) count = 0 wallPointIdsMap.SetNumberOfIds(entityArray.GetNumberOfTuples()) extractSurface = vtk.vtkGeometryFilter() extractSurface.SetInputData(self.Mesh) extractSurface.Update() normalsFilter = vtk.vtkPolyDataNormals() normalsFilter.SetInputConnection( extractSurface.GetOutputPort()) normalsFilter.AutoOrientNormalsOn() normalsFilter.ConsistencyOn() normalsFilter.Update() normalsSurface = normalsFilter.GetOutput() locator = vtk.vtkMergePoints() locator.SetDataSet(normalsSurface) locator.BuildLocator() for i in range(entityArray.GetNumberOfTuples()): if (entityArray.GetComponent(i, 0) != 1.0): wallPointIdsMap.SetId(i, -1) continue wallPointIdsMap.SetId(i, count) point = self.Mesh.GetPoint(i) surfacePointId = locator.FindClosestPoint(point) normal = normalsSurface.GetPointData().GetNormals( ).GetTuple3(surfacePointId) line = str(count + 1) + ' ' + str(i + 1) + ' ' + str( normal[0]) + ' ' + str(normal[1]) + ' ' + str( normal[2]) + '\n' f.write(line) count += 1 if (self.WriteWElemSection == 1): line = '\n' f.write(line) line = '$welem' + '\n' f.write(line) dataArray = vtk.vtkIntArray() dataArray.SetNumberOfComponents(8) for i in range(self.Mesh.GetNumberOfCells()): qtetra = self.Mesh.GetCell(i) for j in range(qtetra.GetNumberOfFaces()): face = qtetra.GetFace(j) isBoundaryFace = 1 for k in range(face.GetNumberOfPoints()): if (entityArray.GetComponent( face.GetPointId(k), 0) != 1.0): isBoundaryFace = 0 break if (isBoundaryFace == 0): continue dataArray.InsertNextValue(i) dataArray.InsertNextValue(j) for k in range(face.GetNumberOfPoints()): dataArray.InsertNextValue(face.GetPointId(k)) line = str(dataArray.GetNumberOfTuples()) + '\n' f.write(line) for i in range(dataArray.GetNumberOfTuples()): line = str(i + 1) + ' ' line += str(int(dataArray.GetComponent(i, 0)) + 1) + ' ' faceId = int(dataArray.GetComponent(i, 1)) newTetrFaceIdsMap = [2, 4, 3, 1] line += str(newTetrFaceIdsMap[faceId]) + ' ' for j in range(2, dataArray.GetNumberOfComponents()): line += str( wallPointIdsMap.GetId( int(dataArray.GetComponent(i, j))) + 1) + ' ' line += '\n' f.write(line) if (self.HistoryEntity != ''): line = '\n' f.write(line) line = '$history' + '\n' f.write(line) entityArray = self.Mesh.GetPointData().GetArray(self.HistoryEntity) numberOfEntityNodes = 0 for i in range(entityArray.GetNumberOfTuples()): if (entityArray.GetComponent(i, 0) != 1.0): continue numberOfEntityNodes += 1 line = str(numberOfEntityNodes) + '\n' f.write(line) for i in range(entityArray.GetNumberOfTuples()): if (entityArray.GetComponent(i, 0) != 1.0): continue line = str(i + 1) + '\n' f.write(line) self.WriteTimeSteps(f)
def writeHdf5(): # This is where the data is for testing purposes. print "Current working directory:", os.getcwd() print taskMeshIn numQuadsPerRing = circQuads # Working with the task mesh junt to figure out the quads and rows numbers. taskMeshReader = vtk.vtkXMLPolyDataReader() taskMeshReader.SetFileName(taskMeshIn) taskMeshReader.Update() taskMesh = taskMeshReader.GetOutput() print taskMesh.GetNumberOfPoints() ecMeshReader = vtk.vtkXMLPolyDataReader() ecMeshReader.SetFileName(ecMeshIn) ecMeshReader.Update() ecMesh = ecMeshReader.GetOutput() print ecMesh.GetNumberOfPoints() # Get the range of branch labels. labelRange = [0, 0] taskMesh.GetCellData().GetScalars().GetRange(labelRange, 0) # Convert label range to a list of labels. labelRange = range(int(labelRange[0]), int(labelRange[1]) + 1) print "Labels found in task mesh:", labelRange # Store the number of rings for each label. numRingsPerLabel = {} # For every label in the range of labels we want to extract all cells/quads. for label in labelRange: # Use this filter to extract the cells for a given label value. branchSelector = vtk.vtkThreshold() branchSelector.SetInputData(taskMesh) branchSelector.ThresholdBetween(label,label); branchSelector.Update() taskMeshBranch = branchSelector.GetOutput() numQuadRowsPerBranch = taskMeshBranch.GetNumberOfCells() / numQuadsPerRing; numRingsPerLabel[label] = numQuadRowsPerBranch # Working with EC mesh only atpMeshReader = vtk.vtkXMLPolyDataReader() atpMeshReader.SetFileName(atpMeshIn) atpMeshReader.Update() # Original ECs mesh to work with. atpMesh = atpMeshReader.GetOutput() print "There are", atpMesh.GetNumberOfCells(), "ATP values in total ..." parentFile = h5py.File(atpHdf5Files[0], 'w') leftBranchFile = h5py.File(atpHdf5Files[1], 'w') rightBranchFile = h5py.File(atpHdf5Files[2], 'w') appendPolyData = vtk.vtkAppendPolyData(); # For every label in the range of labels we want to extract all ECs. for label in labelRange: ecMeshReader = vtk.vtkXMLPolyDataReader() ecMeshReader.SetFileName(ecVTPFiles[label]) ecMeshReader.Update() tmpPolyData = ecMeshReader.GetOutput() # Keep track of how many branches we need to skip. numECsPerLabel = numQuadsPerRing * numRingsPerLabel[label] * numECsPerQuad atpCellOffset = label * numECsPerLabel print "atpCellOffset", atpCellOffset # Collect cell ids to select. selectionIds = vtk.vtkIdTypeArray() for sId in range(0, numECsPerLabel): selectionIds.InsertNextValue(atpCellOffset + sId) # Create selecion node. selectionNode = vtk.vtkSelectionNode() selectionNode.SetFieldType(selectionNode.CELL) selectionNode.SetContentType(selectionNode.INDICES) selectionNode.SetSelectionList(selectionIds) # Create selection. selection = vtk.vtkSelection() selection.AddNode(selectionNode) # Use vtkSelection filter. selectionExtractor = vtk.vtkExtractSelection() selectionExtractor.SetInputData(0, atpMesh) selectionExtractor.SetInputData(1, selection) selectionExtractor.Update() extractedCells = selectionExtractor.GetOutput() # Ring ids list for traversal. ringIds = range(0, numRingsPerLabel[label]) ringIds.reverse() # Number of ECs rows is the number of ECs per quad. rowIds = range(0, numECsPerCol) rowIds.reverse() reorderedATPArray = vtk.vtkDoubleArray() reorderedATPArray.SetName("initialATP") # Decide which TXT files to write to. pointsOf = '' if label == 0: pointsOf = parentFile elif label == 1: pointsOf = leftBranchFile elif label == 2: pointsOf = rightBranchFile print "Writing H5 file for ECs ATP:" print pointsOf dset = pointsOf.create_dataset("/atp", (numECsPerLabel,), 'f') i = 0 # Iterate over the rings in reverse order. for ringNum in ringIds: # Iterate over the 'imaginary' quads of cells in normal order. for quadNum in range(0, numQuadsPerRing): # Iterate over the rows of cells in reverse order. # Calculate the 'real' id for the 'imaginary' quad. quadId = ringNum * numQuadsPerRing + quadNum # Iterate over rows of cells in reverse order. for rowNum in rowIds: # Iterate over the rows of cells in normal order. for cellNum in range(0, numECsPerRow): # Calculate the 'real' ec cell id and get the corresponding cell. realId = quadId * numECsPerQuad + rowNum * numECsPerRow + cellNum atpVal = extractedCells.GetCellData().GetArray("initialATP").GetValue(realId) reorderedATPArray.InsertNextValue(atpVal) # Write the value to the txt file. dset[i] = atpVal i += 1 tmpPolyData.GetCellData().SetScalars(reorderedATPArray) appendPolyData.AddInputData(tmpPolyData) parentFile.close() leftBranchFile.close() rightBranchFile.close() print "Writing reorderd ATP map for verification..." appendPolyData.Update() reorderedATPWriter = vtk.vtkXMLPolyDataWriter() reorderedATPWriter.SetInputData(appendPolyData.GetOutput()) reorderedATPWriter.SetFileName("vtk/reordered_atp.vtp") reorderedATPWriter.Update() print "All done ..."
def main(): sphere_source = vtk.vtkSphereSource() sphere_source.Update() print("There are %s input points" % sphere_source.GetOutput().GetNumberOfPoints()) print("There are %s input cells" % sphere_source.GetOutput().GetNumberOfCells()) ids = vtk.vtkIdTypeArray() ids.SetNumberOfComponents(1) # Specify that we want to extract cells 10 through 19 i = 10 while i < 20: ids.InsertNextValue(i) i += 1 selection_node = vtk.vtkSelectionNode() selection_node.SetFieldType(vtk.vtkSelectionNode.CELL) selection_node.SetContentType(vtk.vtkSelectionNode.INDICES) selection_node.SetSelectionList(ids) selection = vtk.vtkSelection() selection.AddNode(selection_node) extract_selection = vtk.vtkExtractSelection() if vtk.VTK_MAJOR_VERSION <= 5: extract_selection.SetInputConnection(0, sphere_source.GetOutputPort()) extract_selection.SetInput(1, selection) else: extract_selection.SetInputConnection(0, sphere_source.GetOutputPort()) extract_selection.SetInputData(1, selection) extract_selection.Update() # In selection grid_selected = vtk.vtkUnstructuredGrid() grid_selected.ShallowCopy(extract_selection.GetOutput()) print("There are %s points in the selection" % grid_selected.GetNumberOfPoints()) print("There are %s cells in the selection" % grid_selected.GetNumberOfCells()) # Get points that are NOT in the selection # invert the selection selection_node.GetProperties().Set(vtk.vtkSelectionNode.INVERSE(), 1) extract_selection.Update() not_selected = vtk.vtkUnstructuredGrid() not_selected.ShallowCopy(extract_selection.GetOutput()) print("There are %s points NOT in the selection" % not_selected.GetNumberOfPoints()) print("There are %s cells NOT in the selection" % not_selected.GetNumberOfCells()) backfaces = vtk.vtkProperty() backfaces.SetColor(1, 0, 0) input_mapper = vtk.vtkDataSetMapper() input_mapper.SetInputConnection(sphere_source.GetOutputPort()) input_actor = vtk.vtkActor() input_actor.SetMapper(input_mapper) input_actor.SetBackfaceProperty(backfaces) selected_mapper = vtk.vtkDataSetMapper() if vtk.VTK_MAJOR_VERSION <= 5: selected_mapper.SetInputConnection(grid_selected.GetProducerPort()) else: selected_mapper.SetInputData(grid_selected) selected_actor = vtk.vtkActor() selected_actor.SetMapper(selected_mapper) selected_actor.SetBackfaceProperty(backfaces) not_selected_mapper = vtk.vtkDataSetMapper() if vtk.VTK_MAJOR_VERSION <= 5: not_selected_mapper.SetInputConnection(not_selected.GetProducerPort()) else: not_selected_mapper.SetInputData(not_selected) not_selected_actor = vtk.vtkActor() not_selected_actor.SetMapper(not_selected_mapper) not_selected_actor.SetBackfaceProperty(backfaces) # There will be one render window render_window = vtk.vtkRenderWindow() render_window.SetSize(900, 300) # And one interactor interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(render_window) # Define viewport ranges # (xmin, ymin, xmax, ymax) left_viewport = [0.0, 0.0, 0.5, 1.0] center_viewport = [0.33, 0.0, .66, 1.0] right_viewport = [0.66, 0.0, 1.0, 1.0] # Create a camera for all renderers camera = vtk.vtkCamera() # Setup the renderers left_renderer = vtk.vtkRenderer() render_window.AddRenderer(left_renderer) left_renderer.SetViewport(left_viewport) left_renderer.SetBackground(.6, .5, .4) left_renderer.SetActiveCamera(camera) center_renderer = vtk.vtkRenderer() render_window.AddRenderer(center_renderer) center_renderer.SetViewport(center_viewport) center_renderer.SetBackground(.3, .1, .4) center_renderer.SetActiveCamera(camera) right_renderer = vtk.vtkRenderer() render_window.AddRenderer(right_renderer) right_renderer.SetViewport(right_viewport) right_renderer.SetBackground(.4, .5, .6) right_renderer.SetActiveCamera(camera) left_renderer.AddActor(input_actor) center_renderer.AddActor(selected_actor) right_renderer.AddActor(not_selected_actor) left_renderer.ResetCamera() render_window.Render() interactor.Start()