def stripGrid(vtk_grid): # Strip out masked points. if vtk_grid.IsA("vtkStructuredGrid"): if vtk_grid.GetCellBlanking(): visArray = vtk_grid.GetCellVisibilityArray() visArray.SetName("BlankingArray") vtk_grid.GetCellData().AddArray(visArray) thresh = vtk.vtkThreshold() thresh.SetInputData(vtk_grid) thresh.ThresholdByUpper(0.5) thresh.SetInputArrayToProcess(0, 0, 0, "vtkDataObject::FIELD_ASSOCIATION_CELLS", "BlankingArray") thresh.Update() vtk_grid = thresh.GetOutput() elif vtk_grid.GetPointBlanking(): visArray = vtk_grid.GetPointVisibilityArray() visArray.SetName("BlankingArray") vtk_grid.GetPointData().AddArray(visArray) thresh = vtk.vtkThreshold() thresh.SetInputData(vtk_grid) thresh.SetUpperThreshold(0.5) thresh.SetInputArrayToProcess(0, 0, 0, "vtkDataObject::FIELD_ASSOCIATION_POINTS", "BlankingArray") thresh.Update() vtk_grid = thresh.GetOutput() return vtk_grid
def threshold_filter_pd(self): threshold = vtk.vtkThreshold() threshold.SetInputData(self.polydata) threshold.ThresholdByUpper(self.min_H_value) threshold.Update() polydata = threshold.GetOutput() normals = list(map(tuple, numpy_support.vtk_to_numpy( polydata.GetPointData().GetArray("Normals")))) c = vtk.vtkLongLongArray() c.SetName("c") for n in normals: x, y, z = n if abs(x) > abs(y): c.InsertNextTuple1(1) elif abs(z) > abs(y): c.InsertNextTuple1(2) else: c.InsertNextTuple1(0) polydata.GetPointData().AddArray(c) threshold = vtk.vtkThreshold() threshold.SetInputData(polydata) threshold.SetInputArrayToProcess(0, 0, 0, 0, "c") threshold.ThresholdByUpper(1) threshold.Update() polydata = threshold.GetOutput() polydata.GetPointData().RemoveArray("c") return polydata
def save_lesion(output_file, input_file, field, limits): reader = v.vtkXMLUnstructuredGridReader() reader.SetFileName(input_file) reader.Update() threshold = v.vtkThreshold() threshold.SetInput(reader.GetOutput()) if limits[0] is None: threshold.ThresholdByLower(limits[1]) elif limits[1] is None: threshold.ThresholdByUpper(limits[0]) else: threshold.ThresholdBetween(*limits) threshold.SetInputArrayToProcess(0, 0, 0, v.vtkDataObject.FIELD_ASSOCIATION_CELLS, field) threshold.Update() extract_surface = v.vtkDataSetSurfaceFilter() extract_surface.SetInput(threshold.GetOutput()) extract_surface.Update() writer = v.vtkXMLPolyDataWriter() writer.SetFileName(output_file) writer.SetInput(extract_surface.GetOutput()) writer.Write()
def write_boundary_edge_cells(self, edge_cell_ids): '''Write a PolyData surface containing the cells incident to boundary edges. This is for debugging. ''' cell_mask = vtk.vtkIntArray() cell_mask.SetNumberOfValues(num_cells) cell_mask.SetName("CellMask") for i in range(num_cells): cell_mask.SetValue(i, 0) surface.GetCellData().AddArray(cell_mask) for cell_id in edge_cell_ids: cell_mask.SetValue(cell_id, 1) thresh = vtk.vtkThreshold() thresh.SetInputData(surface) thresh.ThresholdBetween(1, 1) thresh.SetInputArrayToProcess( 0, 0, 0, "vtkDataObject::FIELD_ASSOCIATION_CELLS", "CellMask") thresh.Update() surfacefilter = vtk.vtkDataSetSurfaceFilter() surfacefilter.SetInputData(thresh.GetOutput()) surfacefilter.Update() edge_cells = surfacefilter.GetOutput() writer = vtk.vtkXMLPolyDataWriter() writer.SetFileName("boundary_edge_cells.vtp") writer.SetInputData(edge_cells) writer.Write()
def vti2vtu(vti, threshold=0.1, field='rho', output_file=None): """ Returns unstructured grid for existing voxels based on threshold filtering output: file or vtk object - highly inefficient - allocates a full geometry before threshold """ p2c = vtk.vtkPointDataToCellData() p2c.SetInputData(vti) p2c.PassPointDataOn() p2c.Update() t = vtk.vtkThreshold() t.SetInputData(p2c.GetOutput()) t.ThresholdByUpper(threshold) t.SetInputArrayToProcess(0, 0, 0, 0, field) t.Update() print('# of Cells (unstructured):', t.GetOutput().GetNumberOfCells(), 'vs. vti: ', vti.GetNumberOfPoints()) if output_file: sw = vtk.vtkXMLUnstructuredGridWriter() sw.SetFileName(output_file) sw.SetInputData(t.GetOutput()) sw.Write() else: return t.GetOutput()
def threshold_vtk_data(data_vtu_in, array_type, array_name, lower_thr=None, upper_thr=None): threshold_filter = vtk.vtkThreshold() threshold_filter.SetInputData(data_vtu_in) if array_type == "cell": threshold_filter.SetInputArrayToProcess( 0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS, array_name) elif array_type == "point": threshold_filter.SetInputArrayToProcess( 0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, array_name) if (lower_thr == None) and (upper_thr != None): threshold_filter.ThresholdByUpper(upper_thr) print("-- select %ss where %s > %s" % (array_type, array_name, upper_thr)) elif (lower_thr != None) and (upper_thr == None): print("-- select %ss where %s < %s" % (array_type, array_name, lower_thr)) threshold_filter.ThresholdByLower(lower_thr) elif (lower_thr != None) and (upper_thr != None): print("-- select %ss where %s between %s and %s" % (array_type, array_name, lower_thr, upper_thr)) threshold_filter.ThresholdBetween(lower_thr, upper_thr) threshold_filter.Update() data_vtu_out = threshold_filter.GetOutput() return data_vtu_out
def testUnstructured(self): rt = vtk.vtkRTAnalyticSource() rt.SetWholeExtent(-5, 5, -5, 5, -5, 5) t = vtk.vtkThreshold() t.SetInputConnection(rt.GetOutputPort()) t.ThresholdByUpper(-10) s = vtk.vtkSphere() s.SetRadius(2) s.SetCenter(0,0,0) c = vtk.vtkTableBasedClipDataSet() c.SetInputConnection(t.GetOutputPort()) c.SetClipFunction(s) c.SetInsideOut(1) c.Update() self.assertEqual(c.GetOutput().GetNumberOfCells(), 64) eg = vtk.vtkEnSightGoldReader() eg.SetCaseFileName(VTK_DATA_ROOT + "/Data/EnSight/elements.case") eg.Update() pl = vtk.vtkPlane() pl.SetOrigin(3.5, 3.5, 0.5) pl.SetNormal(0, 0, 1) c.SetInputConnection(eg.GetOutputPort()) c.SetClipFunction(pl) c.SetInsideOut(1) c.Update() data = c.GetOutputDataObject(0).GetBlock(0) self.assertEqual(data.GetNumberOfCells(), 75) rw = vtk.vtkRenderWindow() ren = vtk.vtkRenderer() rw.AddRenderer(ren) mapper = vtk.vtkDataSetMapper() mapper.SetInputData(data) actor = vtk.vtkActor() actor.SetMapper(mapper) ren.AddActor(actor) ac = ren.GetActiveCamera() ac.SetPosition(-7.9, 9.7, 14.6) ac.SetFocalPoint(3.5, 3.5, 0.5) ac.SetViewUp(0.08, 0.93, -0.34) rw.Render() ren.ResetCameraClippingRange() rtTester = vtk.vtkTesting() for arg in sys.argv[1:]: rtTester.AddArgument(arg) rtTester.AddArgument("-V") rtTester.AddArgument("tableBasedClip.png") rtTester.SetRenderWindow(rw) rw.Render() rtResult = rtTester.RegressionTest(10)
def RequestData(): import vtk import numpy as np from vtk.util import numpy_support as npvtk # Get input data pdin = self.GetInput() # Threshold construct thresh1 = vtk.vtkThreshold() thresh1.SetInputData(pdin) # Apply a threshold filter according to the CoastMask if coast and open_sea: thresh1.ThresholdBetween(1, 2) if coast and not open_sea: thresh1.ThresholdBetween(1, 1.5) if not coast and open_sea: thresh1.ThresholdBetween(1.5, 2) if not coast and not open_sea: thresh1.ThresholdBetween(0, 0.5) # Just the ground # Apply threshold on CoastMask thresh1.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS, "coast mask") # Update filter thresh1.Update() # Grab the vtkField from threshold filter field = thresh1.GetOutput() field.GetCellData().RemoveArray("coast mask") # Remove the coast mask (no longer needed) # Update the output port pdout = self.GetOutput().ShallowCopy(field)
def separate_regions(dataset, regionIdArrayName='RegionId', regionIds=None): dataset_dsa = wdo(dataset) if regionIds is None: regionIds = np.unique(dataset_dsa.PointData[regionIdArrayName]) regions = [] for regionId in regionIds: threshold = vtk.vtkThreshold() threshold.SetInputData(dataset) threshold.ThresholdBetween(regionId, regionId) threshold.SetInputArrayToProcess(0, 0, 0, 0, regionIdArrayName) threshold.AllScalarsOff() threshold.Update() region = threshold.GetOutput() if isinstance(dataset, vtk.vtkPolyData): surfFilter = vtk.vtkDataSetSurfaceFilter() surfFilter.SetInputData(region) surfFilter.Update() region = surfFilter.GetOutput() regions.append(region) return regions
def threshold(self, low=0, high=100): threshold = vtk.vtkThreshold() threshold.SetInputConnection(self.mesh.GetOutputPort()) threshold.ThresholdBetween(low, high) threshold.Update() # choose scalars??? return threshold
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkThreshold(), 'Processing.', ('vtkDataSet',), ('vtkUnstructuredGrid',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def thresholdUGrid(ugrid_mesh, field_support, field_name, threshold_value, threshold_by_upper_or_lower, verbose=0): myVTK.myPrint(verbose, "*** thresholdUGrid ***") threshold = vtk.vtkThreshold() if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): threshold.SetInputData(ugrid_mesh) else: threshold.SetInput(ugrid_mesh) if (field_support == "points"): association = vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS elif (field_support == "cells"): association = vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS threshold.SetInputArrayToProcess(0, 0, 0, association, field_name) if (threshold_by_upper_or_lower == "upper"): threshold.ThresholdByUpper(threshold_value) elif (threshold_by_upper_or_lower == "lower"): threshold.ThresholdByLower(threshold_value) threshold.Update() ugrid_thresholded_mesh = threshold.GetOutput() return ugrid_thresholded_mesh
def threshold(polydata, arrayname, valuerange=[0, 1], iscelldata=True, allscalars=True): """Extract those cells from polydata whose pointdata/celldata values are within a specified range. For pointdata, cells are included if scalar values of all cell points are within the range (allscalars=True) or if the scalar value of at least one of the cell points is within the range (allscalar=False). """ thresholdfilter = vtk.vtkThreshold() thresholdfilter.SetInput(polydata) thresholdfilter.ThresholdBetween(valuerange[0], valuerange[1]) if iscelldata: thresholdfilter.SetInputArrayToProcess( 0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS, arrayname) else: thresholdfilter.SetInputArrayToProcess( 0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, arrayname) if allscalars: thresholdfilter.AllScalarsOn() else: thresholdfilter.AllScalarsOff() thresholdfilter.Update() surfacefilter = vtk.vtkDataSetSurfaceFilter() surfacefilter.SetInput(thresholdfilter.GetOutput()) surfacefilter.Update() return surfacefilter.GetOutput()
def get_surface_faces(surface): '''Get the faces from the surface mesh using the ModelFaceID data array. ''' face_ids = surface.GetCellData().GetArray('ModelFaceID') face_ids_range = 2 * [0] face_ids.GetRange(face_ids_range, 0) min_id = int(face_ids_range[0]) max_id = int(face_ids_range[1]) ## Extract face geometry. # faces = [] for i in range(min_id, max_id + 1): threshold = vtk.vtkThreshold() threshold.SetInputData(surface) threshold.SetInputArrayToProcess(0, 0, 0, 1, 'ModelFaceID') threshold.ThresholdBetween(i, i) threshold.Update() surfacer = vtk.vtkDataSetSurfaceFilter() surfacer.SetInputData(threshold.GetOutput()) surfacer.Update() faces.append(surfacer.GetOutput()) return faces
def get_domain_with_node_ids(mesh_vtu, domain_id_list): # -- add copy of element point ids to mesh pointIdFilter = vtk.vtkIdFilter() pointIdFilter.SetInputData(mesh_vtu) pointIdFilter.SetPointIds(True) pointIdFilter.SetCellIds(False) pointIdFilter.SetIdsArrayName("originalPointIDs") pointIdFilter.Update() mesh = pointIdFilter.GetUnstructuredGridOutput() # -- NUMPY - VTK mesh_wrapped = dsa.WrapDataObject(mesh) # -- extract element block ids material_array_name = "ElementBlockIds" element_block_id_array = mesh_wrapped.CellData[material_array_name] # -- create empty array for selection element_selection_array_name = "ElementSelection" element_selection_array = np.zeros(algs.shape(element_block_id_array)[0]) # -- assign selection id = 1 for elements in domain_id_list for domain_id in domain_id_list: element_selection_array[element_block_id_array == domain_id] = 1 # -- add selection array to mesh mesh_wrapped.CellData.append(element_selection_array, element_selection_array_name) # -- extract parts of mesh that have been selected selector = vtk.vtkThreshold() selector.SetInputData(mesh) selector.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS, element_selection_array_name) selector.ThresholdBetween(1, 1) selector.Update() subgrid = selector.GetOutput() return subgrid
def threshold(polydata, arrayname, valuerange=[0, 1], iscelldata=True, allscalars=True): """Extract those cells from polydata whose pointdata/celldata values are within a specified range. For pointdata, cells are included if scalar values of all cell points are within the range (allscalars=True) or if the scalar value of at least one of the cell points is within the range (allscalar=False). """ thresholdfilter = vtk.vtkThreshold() thresholdfilter.SetInput(polydata) thresholdfilter.ThresholdBetween(valuerange[0], valuerange[1]) if iscelldata: thresholdfilter.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject. FIELD_ASSOCIATION_CELLS, arrayname) else: thresholdfilter.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject. FIELD_ASSOCIATION_POINTS, arrayname) if allscalars: thresholdfilter.AllScalarsOn() else: thresholdfilter.AllScalarsOff() thresholdfilter.Update() surfacefilter = vtk.vtkDataSetSurfaceFilter() surfacefilter.SetInput(thresholdfilter.GetOutput()) surfacefilter.Update() return surfacefilter.GetOutput()
def get_surface_faces(surface_mesh, bc_faces): '''Get the faces from the surface mesh. The faces are vtkPolyData objects with cell data arrays. ''' print("\n========== get_surface_faces ==========") face_ids = surface_mesh.GetCellData().GetArray(VtkDataNames.ModelFaceID) face_ids_range = 2 * [0] face_ids.GetRange(face_ids_range, 0) min_id = int(face_ids_range[0]) max_id = int(face_ids_range[1]) print("[get_surface_faces] Face IDs range: {0:d} {1:d}".format( min_id, max_id)) ## Extract face geometry. # for i in range(min_id, max_id + 1): if i not in bc_faces: continue print("[get_surface_faces] ----- Face ID {0:d} ----".format(i)) print("[get_surface_faces] Face name: {0:s} ".format(bc_faces[i].name)) threshold = vtk.vtkThreshold() threshold.SetInputData(surface_mesh) threshold.SetInputArrayToProcess(0, 0, 0, 1, VtkDataNames.ModelFaceID) threshold.ThresholdBetween(i, i) threshold.Update() surfacer = vtk.vtkDataSetSurfaceFilter() surfacer.SetInputData(threshold.GetOutput()) surfacer.Update() bc_faces[i].set_mesh(surfacer.GetOutput()) print("[get_surface_faces] Face number of points: %d" % bc_faces[i].mesh.GetNumberOfPoints()) print("[get_surface_faces] Face number of cells: %d" % bc_faces[i].mesh.GetNumberOfCells())
def vtp2vtuPolyhedron(vtpObject): """ Convert a Polydata to individual polyhedron cells in a vtu grid """ # Find individual conFilt = vtk.vtkPolyDataConnectivityFilter() conFilt.SetInputData(vtpObject) conFilt.SetExtractionMode(5) conFilt.SetColorRegions(1) conFilt.Update() # phAppFilt = vtk.vtkAppendFilter() # phAppFilt.MergePointsOn() for nr in np.arange(conFilt.GetNumberOfExtractedRegions()): thresh = vtk.vtkThreshold() thresh.SetInputConnection(conFilt.GetOutputPort()) thresh.ThresholdBetween(nr - .1, nr + .1) thresh.SetInputArrayToProcess(1, 0, 0, 0, "Regionid") thresh.Update() # Convert to a Polyhedron and add to the append filter phAppFilt.AddInputData( makePolyhedronCell(vtu2vtp(thresh.GetOutput()), returnGrid=True)) phAppFilt.Update() # Return the grid return phAppFilt.GetOutput()
def getThresholdedUGrid( ugrid, field_support, field_name, threshold_value, threshold_by_upper_or_lower, verbose=0): mypy.my_print(verbose, "*** getThresholdedUGrid ***") threshold = vtk.vtkThreshold() if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): threshold.SetInputData(ugrid) else: threshold.SetInput(ugrid) if (field_support == "points"): association = vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS elif (field_support == "cells"): association = vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS threshold.SetInputArrayToProcess(0, 0, 0, association, field_name) if (threshold_by_upper_or_lower == "upper"): threshold.ThresholdByUpper(threshold_value) elif (threshold_by_upper_or_lower == "lower"): threshold.ThresholdByLower(threshold_value) threshold.Update() thresholded_ugrid = threshold.GetOutput() return thresholded_ugrid
def CreateSurfaceCells(self, inMesh): #Remove the surface cells from the mesh cellDimFilter = vtkvmtk.vtkvmtkCellDimensionFilter() cellDimFilter.SetInputData(inMesh) cellDimFilter.ThresholdByUpper(3) cellDimFilter.Update() volumetricMesh = cellDimFilter.GetOutput() #Get new surface cells geomFilter = vtk.vtkGeometryFilter() geomFilter.SetInputConnection(cellDimFilter.GetOutputPort()) geomFilter.Update() newSurfaceCells = geomFilter.GetOutput() #If the celEntityIdArray exist, project the original entity ids cellEntityIdsArray = newSurfaceCells.GetCellData().GetArray( self.CellEntityIdsArrayName) if (cellEntityIdsArray != None): #Convert the surface cells to poly data surfaceCellsToSurface = vmtkscripts.vmtkMeshToSurface() surfaceCellsToSurface.Mesh = newSurfaceCells surfaceCellsToSurface.Execute() #Get the original surface cells meshThreshold = vtk.vtkThreshold() meshThreshold.SetInputData(self.Mesh) meshThreshold.ThresholdByUpper(self.WallCellEntityId + 0.5) meshThreshold.SetInputArrayToProcess(0, 0, 0, 1, self.CellEntityIdsArrayName) meshThreshold.Update() meshToSurface = vmtkscripts.vmtkMeshToSurface() meshToSurface.Mesh = meshThreshold.GetOutput() meshToSurface.Execute() #Project the entity ids form the old surface cells to the new surface cells #TODO: This is hackish(need for a tolerance), find a beeter way projector = vtkvmtk.vtkvmtkSurfaceProjectCellArray() projector.SetInputData(surfaceCellsToSurface.Surface) projector.SetReferenceSurface(meshToSurface.Surface) projector.SetProjectedArrayName(self.CellEntityIdsArrayName) projector.SetDefaultValue(self.WallCellEntityId) projector.SetDistanceTolerance(self.Tolerance) projector.Update() #Convert the surface cells back to unstructured grid surfaceToMesh = vmtkscripts.vmtkSurfaceToMesh() surfaceToMesh.Surface = projector.GetOutput() surfaceToMesh.Execute() newSurfaceCells = surfaceToMesh.Mesh #append the new surface cells to the volumetric elements appendFilter = vtkvmtk.vtkvmtkAppendFilter() appendFilter.AddInput(volumetricMesh) appendFilter.AddInput(newSurfaceCells) appendFilter.Update() return appendFilter.GetOutput()
def extract_lsa_surface(aneurysm: vtk.vtkPolyData, inputArrayName: str): threshold = vtk.vtkThreshold() threshold.SetInputData(aneurysm) threshold.SetInputArrayToProcess(0, 0, 0, 0, inputArrayName) threshold.ThresholdByUpper(1) threshold.AllScalarsOn() threshold.Update() return threshold.GetOutput()
def __init__(self, percent=50, invert=False, **kwargs): FilterBase.__init__(self, inputType='vtkDataSet', outputType='vtkUnstructuredGrid', **kwargs) self.__invert = invert if percent < 1.0: percent *= 100 self.__percent = percent # NOTE: not decimal percent self.__filter = vtk.vtkThreshold() self.__input_array = [None, None]
def initialize (self): debug ("In Threshold::initialize ()") self.fil = vtk.vtkThreshold () self.fil.SetInput (self.prev_fil.GetOutput ()) self.data_name = self.mod_m.get_scalar_data_name () dr = self.mod_m.get_scalar_data_range () self.fil.ThresholdBetween (dr[0], dr[1]) self.fil.Update ()
def __init__(self, filename, colour=[1.0, 0.0, 0.0], visibility=True, opacity=1.0, pickable=True): """ Creates a new surface model. :param filename: path to vtk grid file. :param colour: (R,G,B) where each are floats [0-1] :param visibility: boolean, True|False :param opacity: float [0,1] :param pickable: boolean, True|False """ super(VTKUnstructuredGridModel, self).__init__(colour, visibility, opacity, pickable) self.source_file = None self.reader = None self.source = None self.cell_data_name = None self.threshold = None if filename is not None: vf.validate_is_file(filename) if filename.endswith(".vtk"): self.reader = vtk.vtkUnstructuredGridReader() elif filename.endswith(".vtu"): self.reader = vtk.vtkXMLUnstructuredGridReader() else: raise TypeError("File is not .vtu or .vtk extension") self.reader.SetFileName(filename) self.reader.Update() self.source = self.reader.GetOutput() self.source_file = filename self.name = os.path.basename(self.source_file) else: raise ValueError("Filename not specified") self.threshold = vtk.vtkThreshold() self.threshold.SetInputData(self.source) self.threshold.Update() self.thresholded_data = self.threshold.GetOutput() self.mapper = vtk.vtkDataSetMapper() self.mapper.SetInputData(self.thresholded_data) self.mapper.Update() self.actor.SetMapper(self.mapper) self.cell_data_name = self.source.GetCellData().GetArrayName(0)
def CreateSurfaceCells(self,inMesh): #Remove the surface cells from the mesh cellDimFilter = vtkvmtkcontrib.vtkvmtkCellDimensionFilter() cellDimFilter.SetInput(inMesh) cellDimFilter.ThresholdByUpper(3) cellDimFilter.Update() volumetricMesh = cellDimFilter.GetOutput() #Get new surface cells geomFilter = vtk.vtkGeometryFilter() geomFilter.SetInput(cellDimFilter.GetOutput()) geomFilter.Update() newSurfaceCells = geomFilter.GetOutput() #If the celEntityIdArray exist, project the original entity ids cellEntityIdsArray = newSurfaceCells.GetCellData().GetArray(self.CellEntityIdsArrayName) if (cellEntityIdsArray != None): #Convert the surface cells to poly data surfaceCellsToSurface = vmtkscripts.vmtkMeshToSurface() surfaceCellsToSurface.Mesh = newSurfaceCells surfaceCellsToSurface.Execute() #Get the original surface cells meshThreshold = vtk.vtkThreshold() meshThreshold.SetInput(self.Mesh) meshThreshold.ThresholdByUpper(self.WallCellEntityId+0.5) meshThreshold.SetInputArrayToProcess(0,0,0,1,self.CellEntityIdsArrayName) meshThreshold.Update() meshToSurface = vmtkscripts.vmtkMeshToSurface() meshToSurface.Mesh = meshThreshold.GetOutput() meshToSurface.Execute() #Project the entity ids form the old surface cells to the new surface cells #TODO: This is hackish(need for a tolerance), find a beeter way projector = vtkvmtkcontrib.vtkvmtkSurfaceProjectCellArray() projector.SetInput(surfaceCellsToSurface.Surface) projector.SetReferenceSurface(meshToSurface.Surface) projector.SetProjectedArrayName(self.CellEntityIdsArrayName) projector.SetDefaultValue(self.WallCellEntityId) projector.SetDistanceTolerance(self.Tolerance) projector.Update() #Convert the surface cells back to unstructured grid surfaceToMesh = vmtkscripts.vmtkSurfaceToMesh() surfaceToMesh.Surface = projector.GetOutput() surfaceToMesh.Execute() newSurfaceCells = surfaceToMesh.Mesh #append the new surface cells to the volumetric elements appendFilter = vtkvmtk.vtkvmtkAppendFilter() appendFilter.AddInput(volumetricMesh) appendFilter.AddInput(newSurfaceCells) appendFilter.Update() return appendFilter.GetOutput()
def _plotInternalCustomBoxfill(self): """Implements the logic to render a custom boxfill.""" self._mappers = [] self._customBoxfillArgs = self._prepContours() tmpLevels = self._customBoxfillArgs["tmpLevels"] tmpColors = self._customBoxfillArgs["tmpColors"] tmpOpacities = self._customBoxfillArgs["tmpOpacities"] style = self._gm.fillareastyle luts = [] geos = [] wholeDataMin, wholeDataMax = vcs.minmax(self._originalData1) _colorMap = self.getColorMap() for i, l in enumerate(tmpLevels): # Ok here we are trying to group together levels can be, a join # will happen if: next set of levels continues where one left off # AND pattern is identical # TODO this should really just be a single polydata/mapper/actor: for j, color in enumerate(tmpColors[i]): mapper = vtk.vtkPolyDataMapper() lut = vtk.vtkLookupTable() th = vtk.vtkThreshold() th.ThresholdBetween(l[j], l[j + 1]) # th.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort()) th.SetInputData(self._vtkDataSetFittedToViewport) geoFilter2 = vtk.vtkDataSetSurfaceFilter() geoFilter2.SetInputConnection(th.GetOutputPort()) # Make the polydata output available here for patterning later geoFilter2.Update() geos.append(geoFilter2) mapper.SetInputConnection(geoFilter2.GetOutputPort()) lut.SetNumberOfTableValues(1) r, g, b, a = self.getColorIndexOrRGBA(_colorMap, color) if style == 'solid': tmpOpacity = tmpOpacities[j] if tmpOpacity is None: tmpOpacity = a / 100. else: tmpOpacity = tmpOpacities[j] / 100. lut.SetTableValue(0, r / 100., g / 100., b / 100., tmpOpacity) else: lut.SetTableValue(0, 1., 1., 1., 0.) mapper.SetLookupTable(lut) mapper.SetScalarRange(l[j], l[j + 1]) luts.append([lut, [l[j], l[j + 1], False]]) # Store the mapper only if it's worth it? # Need to do it with the whole slab min/max for animation # purposes if not (l[j + 1] < wholeDataMin or l[j] > wholeDataMax): self._mappers.append(mapper) self._resultDict["vtk_backend_luts"] = luts if len(geos) > 0: self._resultDict["vtk_backend_geofilters"] = geos
def __init__(self, parent=None): super(VTKFrame, self).__init__(parent) self.vtkWidget = QVTKRenderWindowInteractor(self) vl = QtGui.QVBoxLayout(self) vl.addWidget(self.vtkWidget) vl.setContentsMargins(0, 0, 0, 0) self.ren = vtk.vtkRenderer() self.ren.SetBackground(0.1, 0.2, 0.4) self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() # Create source source = vtk.vtkSphereSource() source.Update() triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInputConnection(source.GetOutputPort()) triangleFilter.Update() # Create a mapper and actor sphereMapper = vtk.vtkDataSetMapper() sphereMapper.SetInputConnection(triangleFilter.GetOutputPort()) sphereActor = vtk.vtkActor() sphereActor.SetMapper(sphereMapper) mesh = triangleFilter.GetOutput() qualityFilter = vtk.vtkMeshQuality() qualityFilter.SetInput(mesh) qualityFilter.SetTriangleQualityMeasureToArea() qualityFilter.Update() qualityMesh = qualityFilter.GetOutput() #qualityArray = vtk.vtkDoubleArray.SafeDownCase(qualityMesh.GetCellData().GetArray("Quality")) selectCells = vtk.vtkThreshold() selectCells.ThresholdByLower(0.02) selectCells.SetInputArrayToProcess( 0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS, vtk.vtkDataSetAttributes.SCALARS) selectCells.SetInput(qualityMesh) selectCells.Update() ug = selectCells.GetOutput() # Create a mapper and actor mapper = vtk.vtkDataSetMapper() mapper.SetInput(ug) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(1, 0, 0) actor.GetProperty().SetRepresentationToWireframe() actor.GetProperty().SetLineWidth(5) self.ren.AddActor(sphereActor) self.ren.AddActor(actor) self.ren.ResetCamera() self._initialized = False
def get_surface_faces(self): '''Get the faces from the surface mesh using the ModelFaceID data array. The faces are vtkPolyData objects with cell data arrays. ''' self.logger.info("========== get_surface_faces ==========") face_ids = self.surface.GetCellData().GetArray( VtkDataNames.ModelFaceID) if face_ids == None: self.logger.error("No ModelFaceID data.") return face_ids_range = 2 * [0] face_ids.GetRange(face_ids_range, 0) min_id = int(face_ids_range[0]) max_id = int(face_ids_range[1]) self.logger.info("Face IDs range: {0:d} {1:d}".format(min_id, max_id)) ## Extract face geometry. # mesh_faces = {} for i in range(min_id, max_id + 1): #print("[Mesh.get_surface_faces] ---------- ID {0:d} ---------".format(i)) threshold = vtk.vtkThreshold() threshold.SetInputData(self.surface) threshold.SetInputArrayToProcess(0, 0, 0, 1, VtkDataNames.ModelFaceID) threshold.ThresholdBetween(i, i) threshold.Update() surfacer = vtk.vtkDataSetSurfaceFilter() surfacer.SetInputData(threshold.GetOutput()) surfacer.Update() mesh_faces[i] = Face(i, surfacer.GetOutput()) #print("Mesh.[get_surface_faces] Face number of points: %d" % mesh_faces[i].GetNumberOfPoints()) #print("Mesh.[get_surface_faces] Face number of cells: %d" % mesh_faces[i].GetNumberOfCells()) #write_surface_mesh("surface", mesh_faces[i], str(i)) #_for i in range(min_id, max_id+1) self.boundary_faces = mesh_faces center = [0.0, 0.0, 0.0] total_num_pts = 0 for fid, face in self.boundary_faces.items(): npts = face.surface.GetNumberOfPoints() ncells = face.surface.GetNumberOfCells() self.logger.info(" id:{0:d} num cells: {1:d}".format( face.model_face_id, ncells)) for i in range(0, npts): point = face.surface.GetPoint(i) center[0] += point[0] center[1] += point[1] center[2] += point[2] total_num_pts += npts center[0] /= total_num_pts center[1] /= total_num_pts center[2] /= total_num_pts self.center = center
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__(self, module_manager, vtk.vtkThreshold(), 'Processing.', ('vtkDataSet', ), ('vtkUnstructuredGrid', ), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def get_region_mesh(mesh, region_id): ''' Extract a mesh region from a mesh using a region ID. ''' thresholder = vtk.vtkThreshold() thresholder.SetInputData(mesh); thresholder.SetInputArrayToProcess(0,0,0,1,"ModelRegionID"); thresholder.ThresholdBetween(region_id, region_id); thresholder.Update(); return thresholder.GetOutput()
def _plotInternalCustomBoxfill(self): """Implements the logic to render a custom boxfill.""" self._mappers = [] self._customBoxfillArgs = self._prepContours() tmpLevels = self._customBoxfillArgs["tmpLevels"] tmpColors = self._customBoxfillArgs["tmpColors"] tmpOpacities = self._customBoxfillArgs["tmpOpacities"] style = self._gm.fillareastyle luts = [] geos = [] wholeDataMin, wholeDataMax = vcs.minmax(self._originalData1) _colorMap = self.getColorMap() assert(style != 'solid' or len(tmpLevels) == 1) for i, l in enumerate(tmpLevels): # Ok here we are trying to group together levels can be, a join # will happen if: next set of levels continues where one left off # AND pattern is identical # TODO this should really just be a single polydata/mapper/actor: for j, color in enumerate(tmpColors[i]): mapper = vtk.vtkPolyDataMapper() lut = vtk.vtkLookupTable() th = vtk.vtkThreshold() th.ThresholdBetween(l[j], l[j + 1]) th.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort()) geoFilter2 = vtk.vtkDataSetSurfaceFilter() geoFilter2.SetInputConnection(th.GetOutputPort()) # Make the polydata output available here for patterning later geoFilter2.Update() geos.append(geoFilter2) mapper.SetInputConnection(geoFilter2.GetOutputPort()) lut.SetNumberOfTableValues(1) r, g, b, a = self.getColorIndexOrRGBA(_colorMap, color) if style == 'solid': tmpOpacity = tmpOpacities[j] if tmpOpacity is None: tmpOpacity = a / 100. else: tmpOpacity = tmpOpacities[j] / 100. lut.SetTableValue(0, r / 100., g / 100., b / 100., tmpOpacity) else: lut.SetTableValue(0, 1., 1., 1., 0.) mapper.SetLookupTable(lut) mapper.SetScalarRange(l[j], l[j + 1]) luts.append([lut, [l[j], l[j + 1], False]]) # Store the mapper only if it's worth it? # Need to do it with the whole slab min/max for animation # purposes if not (l[j + 1] < wholeDataMin or l[j] > wholeDataMax): self._mappers.append(mapper) self._resultDict["vtk_backend_luts"] = luts if len(geos) > 0: self._resultDict["vtk_backend_geofilters"] = geos
def GET_THRESHOLD_SURFACE(self, Surface, array_name, value): thresh = vtk.vtkThreshold() thresh.SetInputData(Surface) thresh.ThresholdByUpper(value) thresh.SetInputArrayToProcess( 0, 0, 0, "vtkDataObject::FIELD_ASSOCIATION_POINTS", array_name) thresh.Update() vtk_grid = thresh.GetOutput() return vtk_grid
def ThresholdMesh(self): thresholder = vtk.vtkThreshold() thresholder.SetInputData(self.InitialMesh) if (self.ThresholdUpper): thresholder.ThresholdByUpper(self.Threshold) else: thresholder.ThresholdByLower(self.Threshold) thresholder.SetInputArrayToProcess(0,0,0,1,self.ArrayName) thresholder.Update() self.Mesh = thresholder.GetOutput()
def ThresholdMesh(self): thresholder = vtk.vtkThreshold() thresholder.SetInputData(self.InitialMesh) if (self.ThresholdUpper): thresholder.ThresholdByUpper(self.Threshold) else: thresholder.ThresholdByLower(self.Threshold) thresholder.SetInputArrayToProcess(0, 0, 0, 1, self.ArrayName) thresholder.Update() self.Mesh = thresholder.GetOutput()
def _plotInternalBoxfill(self): """Implements the logic to render a non-custom boxfill.""" #Prep mapper mapper = vtk.vtkPolyDataMapper() self._mappers = [ mapper, ] if self._gm.ext_1 and self._gm.ext_2: mapper.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort()) self._resultDict["vtk_backend_geofilters"] = \ [self._vtkPolyDataFilter,] else: thr = vtk.vtkThreshold() thr.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort()) if not self._gm.ext_1 and not self._gm.ext_2: thr.ThresholdBetween(self._contourLevels[0], self._contourLevels[-1]) elif self._gm.ext_1 and not self._gm.ext_2: thr.ThresholdByLower(self._contourLevels[-1]) elif not self._gm.ext_1 and self._gm.ext_2: thr.ThresholdByUpper(self._contourLevels[0]) geoFilter2 = vtk.vtkDataSetSurfaceFilter() geoFilter2.SetInputConnection(thr.GetOutputPort()) mapper.SetInputConnection(geoFilter2.GetOutputPort()) self._resultDict["vtk_backend_geofilters"] = [ geoFilter2, ] ## Colortable bit # make sure length match numLevels = len(self._contourLevels) while len(self._contourColors) < numLevels: self._contourColors.append(self._contourColors[-1]) lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(numLevels) for i in range(numLevels): r, g, b = self._colorMap.index[self._contourColors[i]] lut.SetTableValue(i, r / 100., g / 100., b / 100.) mapper.SetLookupTable(lut) if numpy.allclose(self._contourLevels[0], -1.e20): lmn = mn - 1. else: lmn = self._contourLevels[0] if numpy.allclose(self._contourLevels[-1], 1.e20): lmx = mx + 1. else: lmx = self._contourLevels[-1] mapper.SetScalarRange(lmn, lmx) self._resultDict["vtk_backend_luts"] = [ [lut, [lmn, lmx, True]], ]
def _defineElementSetsByMaterialID(self): for k, v in self.elset_mapping.items(): for k2, v2 in self.polydatas.items(): threshold = vtk.vtkThreshold() threshold.SetInputData(v2) threshold.ThresholdBetween(int(k) - 0.5, int(k) + 0.5) threshold.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS, "Material ID") threshold.Update() self.element_sets[v][k2] = threshold.GetOutput()
def cellthreshold(polydata, arrayname, start=0, end=1): threshold = vtk.vtkThreshold() threshold.SetInputData(polydata) threshold.SetInputArrayToProcess(0,0,0,vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS,arrayname) threshold.ThresholdBetween(start,end) threshold.Update() surfer = vtk.vtkDataSetSurfaceFilter() surfer.SetInputConnection(threshold.GetOutputPort()) surfer.Update() return surfer.GetOutput()
def Threshold(vtkdata, labels, threshold_min, threshold_max): threshold = vtk.vtkThreshold() threshold.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, "RegionId") threshold.SetInputData(vtkdata) threshold.ThresholdBetween(threshold_min,threshold_max) threshold.Update() geometry = vtk.vtkGeometryFilter() geometry.SetInputData(threshold.GetOutput()) geometry.Update() return geometry.GetOutput()
def setupThresholdAlgorithm(self): """Threshold algorithm method for mesh visualization This method implements the threshold algorithm used within the filter pipeline. Based on the settings of the slider widgets, the visibility of physical groups is enabled oder disabled. """ self.thresholdAlgorithm = vtk.vtkThreshold() # use vtkThreshold filter class of vtk library self.thresholdAlgorithm.SetInputDataObject(self.mesh) # set mesh to plot as input data object self.thresholdAlgorithm.SetInputArrayToProcess(0, 0, 0, self.scalars[0].value, self.scalars[1]) # args: (idx, port, connection, field, name) self.thresholdAlgorithm.Update() # update threshold algorithm self.mesh=pv.wrap(self.thresholdAlgorithm.GetOutput()) # update mesh once and connect it with with the algorithm output
def makeUnstructVTKVOIThres(vtkObj,extent,limits): """Make volume of interest and threshold for rectilinear grid.""" # Check for the input cellCore = vtk.vtkExtractUnstructuredGrid() cellCore.SetExtent(extent) cellCore.SetInput(vtkObj) cellThres = vtk.vtkThreshold() cellThres.AllScalarsOn() cellThres.SetInputConnection(cellCore.GetOutputPort()) cellThres.ThresholdBetween(limits[0],limits[1]) cellThres.Update() return cellThres.GetOutput(), cellCore.GetOutput()
def pointthreshold(polydata, arrayname, start=0, end=1,alloff=0): threshold = vtk.vtkThreshold() threshold.SetInputData(polydata) threshold.SetInputArrayToProcess(0,0,0,vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS,arrayname) threshold.ThresholdBetween(start,end) if (alloff): threshold.AllScalarsOff() threshold.Update() surfer = vtk.vtkDataSetSurfaceFilter() surfer.SetInputConnection(threshold.GetOutputPort()) surfer.Update() return surfer.GetOutput()
def thresFilt(vtkObj,arrName,value,thType='Upper'): thresFilt = vtk.vtkThreshold() thresFilt.SetInputData(vtkObj) if thType in 'Upper': thresFilt.ThresholdByUpper(value) elif thType in 'Lower': thresFilt.ThresholdByLower(value) elif thType in 'Between': thresFilt.ThresholdBetween(value[0],value[1]) thresFilt.AllScalarsOn() thresFilt.SetInputArrayToProcess(0,0,0,vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS,arrName) thresFilt.Update() return thresFilt.GetOutput()
def _plotInternalBoxfill(self): """Implements the logic to render a non-custom boxfill.""" # Prep mapper mapper = vtk.vtkPolyDataMapper() self._mappers = [mapper] if self._gm.ext_1 and self._gm.ext_2: mapper.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort()) self._resultDict["vtk_backend_geofilters"] = \ [self._vtkPolyDataFilter] else: thr = vtk.vtkThreshold() thr.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort()) if not self._gm.ext_1 and not self._gm.ext_2: thr.ThresholdBetween(self._contourLevels[0], self._contourLevels[-1]) elif self._gm.ext_1 and not self._gm.ext_2: thr.ThresholdByLower(self._contourLevels[-1]) elif not self._gm.ext_1 and self._gm.ext_2: thr.ThresholdByUpper(self._contourLevels[0]) geoFilter2 = vtk.vtkDataSetSurfaceFilter() geoFilter2.SetInputConnection(thr.GetOutputPort()) mapper.SetInputConnection(geoFilter2.GetOutputPort()) self._resultDict["vtk_backend_geofilters"] = [geoFilter2] # Colortable bit # make sure length match numLevels = len(self._contourLevels) while len(self._contourColors) < numLevels: self._contourColors.append(self._contourColors[-1]) lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(numLevels) _colorMap = self.getColorMap() for i in range(numLevels): r, g, b, a = self.getColorIndexOrRGBA(_colorMap, self._contourColors[i]) lut.SetTableValue(i, r / 100., g / 100., b / 100., a / 100.) mapper.SetLookupTable(lut) if numpy.allclose(self._contourLevels[0], -1.e20): lmn = self._min - 1. else: lmn = self._contourLevels[0] if numpy.allclose(self._contourLevels[-1], 1.e20): lmx = self._mx + 1. else: lmx = self._contourLevels[-1] mapper.SetScalarRange(lmn, lmx) self._resultDict["vtk_backend_luts"] = [[lut, [lmn, lmx, True]]]
def removeEndCaps(self): self.PrintLog("Using thresholding to remove endcaps.") th = vtk.vtkThreshold() th.SetInputData(self.Surface) th.SetInputArrayToProcess(0, 0, 0, 1, self.CellEntityIdsArrayName) th.ThresholdBetween(self.EndcapsThresholdLow, self.EndcapsThresholdHigh) th.Update() gf = vtk.vtkGeometryFilter() gf.SetInputConnection(th.GetOutputPort()) gf.Update() self.DoubleSurface = gf.GetOutput()
def Execute(self): if self.Surface == None and self.Mesh == None: self.PrintError('Error: No Surface or Mesh.') if self.Surface != None and self.Mesh != None: self.PrintError('Error: Both Surface and Mesh, expecting only one.') input = self.Surface or self.Mesh th = vtk.vtkThreshold() th.SetInputData(input) th.SetInputArrayToProcess(0, 0, 0, 1, self.CellEntityIdsArrayName) th.ThresholdBetween(self.LowThreshold, self.HighThreshold) th.Update() if self.Mesh != None: self.Mesh = th.GetOutput() else: assert self.Surface != None gf = vtk.vtkGeometryFilter() gf.SetInputConnection(th.GetOutputPort()) gf.Update() self.Surface = gf.GetOutput()
def get_vtk_by_group(vtkdata, group_lower, group_upper=None): """ Get submesh by material group id. Parameters ---------- vtkdata : VTK object Mesh, scalar, vector and tensor data. group_lower : int The lower material id. group_lower : int The Upper material id. Returns ------- slection : VTK object Mesh, scalar, vector and tensor data. """ selection = vtk.vtkThreshold() if vtk_version < 6: selection.SetInput(vtkdata) else: selection.SetInputData(vtkdata) selection.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS, "mat_id") if group_upper is None: group_upper = group_lower selection.ThresholdBetween(group_lower, group_upper) selection.Update() return selection.GetOutput()
def thresholdUGrid( ugrid_mesh, field_support, field_name, threshold_value, threshold_by_upper_or_lower, verbose=1): myVTK.myPrint(verbose, "*** thresholdUGrid ***") threshold = vtk.vtkThreshold() threshold.SetInputData(ugrid_mesh) if (field_support == "points"): association = vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS elif (field_support == "cells"): association = vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS threshold.SetInputArrayToProcess(0, 0, 0, association, field_name) if (threshold_by_upper_or_lower == "upper"): threshold.ThresholdByUpper(threshold_value) elif (threshold_by_upper_or_lower == "lower"): threshold.ThresholdByLower(threshold_value) threshold.Update() ugrid_thresholded_mesh = threshold.GetOutput() return ugrid_thresholded_mesh
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 _plotInternal(self): prepedContours = self._prepContours() tmpLevels = prepedContours["tmpLevels"] tmpIndices = prepedContours["tmpIndices"] tmpColors = prepedContours["tmpColors"] tmpOpacities = prepedContours["tmpOpacities"] style = self._gm.fillareastyle # self._patternActors = [] mappers = [] luts = [] geos = [] wholeDataMin, wholeDataMax = vcs.minmax(self._originalData1) plotting_dataset_bounds = self.getPlottingBounds() x1, x2, y1, y2 = plotting_dataset_bounds _colorMap = self.getColorMap() self._patternActors = [] for i, l in enumerate(tmpLevels): # Ok here we are trying to group together levels can be, a join # will happen if: next set of levels contnues where one left off # AND pattern is identical # TODO this should really just be a single polydata that is # colored by scalars: for j, color in enumerate(tmpColors[i]): mapper = vtk.vtkPolyDataMapper() lut = vtk.vtkLookupTable() th = vtk.vtkThreshold() th.ThresholdBetween(l[j], l[j + 1]) th.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort()) geoFilter2 = vtk.vtkDataSetSurfaceFilter() geoFilter2.SetInputConnection(th.GetOutputPort()) # Make the polydata output available here for patterning later geoFilter2.Update() geos.append(geoFilter2) mapper.SetInputConnection(geoFilter2.GetOutputPort()) lut.SetNumberOfTableValues(1) r, g, b, a = self.getColorIndexOrRGBA(_colorMap, color) if style == 'solid': tmpOpacity = tmpOpacities[j] if tmpOpacity is None: tmpOpacity = a / 100. else: tmpOpacity = tmpOpacities[j] / 100. lut.SetTableValue( 0, r / 100., g / 100., b / 100., tmpOpacity) else: lut.SetTableValue(0, 1., 1., 1., 0.) mapper.SetLookupTable(lut) mapper.SetScalarRange(l[j], l[j + 1]) luts.append([lut, [l[j], l[j + 1], True]]) # Store the mapper only if it's worth it? # Need to do it with the whole slab min/max for animation # purposes if not (l[j + 1] < wholeDataMin or l[j] > wholeDataMax): mappers.append(mapper) # Since pattern creation requires a single color, assuming the # first c = self.getColorIndexOrRGBA(_colorMap, tmpColors[i][0]) act = fillareautils.make_patterned_polydata(geoFilter2.GetOutput(), fillareastyle=style, fillareaindex=tmpIndices[i], fillareacolors=c, fillareaopacity=tmpOpacities[i], size=(x2 - x1, y2 - y1)) if act is not None: self._patternActors.append(act) self._resultDict["vtk_backend_luts"] = luts if len(geos) > 0: self._resultDict["vtk_backend_geofilters"] = geos """ numLevels = len(self._contourLevels) if mappers == []: # ok didn't need to have special banded contours mapper = vtk.vtkPolyDataMapper() mappers = [mapper] # Colortable bit # make sure length match while len(self._contourColors) < numLevels: self._contourColors.append(self._contourColors[-1]) lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(numLevels) for i in range(numLevels): r, g, b, a = self._colorMap.index[self._contourColors[i]] lut.SetTableValue(i, r / 100., g / 100., b / 100., a / 100.) mapper.SetLookupTable(lut) if numpy.allclose(self._contourLevels[0], -1.e20): lmn = self._min - 1. else: lmn = self._contourLevels[0] if numpy.allclose(self._contourLevels[-1], 1.e20): lmx = self._max + 1. else: lmx = self._contourLevels[-1] mapper.SetScalarRange(lmn, lmx) self._resultDict["vtk_backend_luts"] = [[lut, [lmn, lmx, True]]] """ if self._maskedDataMapper is not None: # Note that this is different for meshfill -- others prepend. mappers.append(self._maskedDataMapper) # Add a second mapper for wireframe meshfill: if self._gm.mesh: lineMappers = [] wireLUT = vtk.vtkLookupTable() wireLUT.SetNumberOfTableValues(1) wireLUT.SetTableValue(0, 0, 0, 0) for polyMapper in mappers: lineMapper = vtk.vtkPolyDataMapper() lineMapper.SetInputConnection( polyMapper.GetInputConnection(0, 0)) lineMapper._useWireFrame = True # 'noqa' comments disable pep8 checking for these lines. There # is not a readable way to shorten them due to the unwieldly # method name. # # Setup depth resolution so lines stay above points: polyMapper.SetResolveCoincidentTopologyPolygonOffsetParameters(0, 1) # noqa polyMapper.SetResolveCoincidentTopologyToPolygonOffset() lineMapper.SetResolveCoincidentTopologyPolygonOffsetParameters(1, 1) # noqa lineMapper.SetResolveCoincidentTopologyToPolygonOffset() lineMapper.SetLookupTable(wireLUT) lineMappers.append(lineMapper) mappers.extend(lineMappers) # And now we need actors to actually render this thing actors = [] vp = self._resultDict.get( 'ratio_autot_viewport', [self._template.data.x1, self._template.data.x2, self._template.data.y1, self._template.data.y2]) dataset_renderer = None xScale, yScale = (1, 1) for mapper in mappers: act = vtk.vtkActor() act.SetMapper(mapper) if hasattr(mapper, "_useWireFrame"): prop = act.GetProperty() prop.SetRepresentationToWireframe() if self._vtkGeoTransform is None: # If using geofilter on wireframed does not get wrppaed not # sure why so sticking to many mappers act = vcs2vtk.doWrap(act, plotting_dataset_bounds, self._dataWrapModulo) # TODO See comment in boxfill. if mapper is self._maskedDataMapper: actors.append([act, self._maskedDataMapper, plotting_dataset_bounds]) else: actors.append([act, plotting_dataset_bounds]) # create a new renderer for this mapper # (we need one for each mapper because of cmaera flips) dataset_renderer, xScale, yScale = self._context().fitToViewport( act, vp, wc=plotting_dataset_bounds, geoBounds=self._vtkDataSet.GetBounds(), geo=self._vtkGeoTransform, priority=self._template.data.priority, create_renderer=(dataset_renderer is None)) for act in self._patternActors: if self._vtkGeoTransform is None: # If using geofilter on wireframed does not get wrapped not sure # why so sticking to many mappers self._context().fitToViewport( act, vp, wc=plotting_dataset_bounds, geoBounds=self._vtkDataSet.GetBounds(), geo=self._vtkGeoTransform, priority=self._template.data.priority, create_renderer=True) actors.append([act, plotting_dataset_bounds]) self._resultDict["vtk_backend_actors"] = actors kwargs = {"vtk_backend_grid": self._vtkDataSet, "dataset_bounds": self._vtkDataSetBounds, "plotting_dataset_bounds": plotting_dataset_bounds, "vtk_backend_geo": self._vtkGeoTransform} if ("ratio_autot_viewport" in self._resultDict): kwargs["ratio_autot_viewport"] = vp self._template.plot(self._context().canvas, self._data1, self._gm, bg=self._context().bg, X=numpy.arange(min(x1, x2), max(x1, x2) * 1.1, abs(x2 - x1) / 10.), Y=numpy.arange(min(y1, y2), max(y1, y2) * 1.1, abs(y2 - y1) / 10.), **kwargs) legend = getattr(self._gm, "legend", None) if self._gm.ext_1: if isinstance(self._contourLevels[0], list): if numpy.less(abs(self._contourLevels[0][0]), 1.e20): # Ok we need to add the ext levels self._contourLevels.insert( 0, [-1.e20, self._contourLevels[0][0]]) else: if numpy.less(abs(self._contourLevels[0]), 1.e20): # need to add an ext self._contourLevels.insert(0, -1.e20) if self._gm.ext_2: if isinstance(self._contourLevels[-1], list): if numpy.less(abs(self._contourLevels[-1][1]), 1.e20): # need ext self._contourLevels.append([self._contourLevels[-1][1], 1.e20]) else: if numpy.less(abs(self._contourLevels[-1]), 1.e20): # need exts self._contourLevels.append(1.e20) patternArgs = {} patternArgs['style'] = self._gm.fillareastyle patternArgs['index'] = self._gm.fillareaindices if patternArgs['index'] is None: patternArgs['index'] = [1, ] patternArgs['opacity'] = self._gm.fillareaopacity self._resultDict.update( self._context().renderColorBar(self._template, self._contourLevels, self._contourColors, legend, self.getColorMap(), **patternArgs)) if self._context().canvas._continents is None: self._useContinents = False if self._useContinents: projection = vcs.elements["projection"][self._gm.projection] continents_renderer, xScale, yScale = self._context().plotContinents( plotting_dataset_bounds, projection, self._dataWrapModulo, vp, self._template.data.priority, vtk_backend_grid=self._vtkDataSet, dataset_bounds=self._vtkDataSetBounds)
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 ..."
from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # Test sub pixel positioning (A round about way of getting an iso surface.) # See cubed sphere for the surface before sub pixel poisitioning. sphere = vtk.vtkSphere() sphere.SetCenter(1,1,1) sphere.SetRadius(0.9) sample = vtk.vtkSampleFunction() sample.SetImplicitFunction(sphere) sample.SetModelBounds(0,2,0,2,0,2) sample.SetSampleDimensions(30,30,30) sample.ComputeNormalsOff() sample.Update() threshold1 = vtk.vtkThreshold() threshold1.SetInputConnection(sample.GetOutputPort()) threshold1.ThresholdByLower(0.001) geometry = vtk.vtkGeometryFilter() geometry.SetInputConnection(threshold1.GetOutputPort()) grad = vtk.vtkImageGradient() grad.SetDimensionality(3) grad.SetInputConnection(sample.GetOutputPort()) grad.Update() mult = vtk.vtkImageMathematics() mult.SetOperationToMultiply() mult.SetInput1Data(sample.GetOutput()) mult.SetInput2Data(sample.GetOutput()) itosp = vtk.vtkImageToStructuredPoints() itosp.SetInputConnection(mult.GetOutputPort()) itosp.SetVectorInputData(grad.GetOutput())
renWin = vtk.vtkRenderWindow() renWin.SetSize(400,400) ############################################################################# # Case 1: Image type. # Open the file. reader_image = vtk.vtkNetCDFCFReader() reader_image.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/tos_O1_2001-2002.nc") reader_image.SetOutputTypeToImage() # Set the arrays we want to load. reader_image.UpdateMetaData() reader_image.SetVariableArrayStatus("tos",1) reader_image.SphericalCoordinatesOff() aa_image = vtk.vtkAssignAttribute() aa_image.SetInputConnection(reader_image.GetOutputPort()) aa_image.Assign("tos","SCALARS","POINT_DATA") thresh_image = vtk.vtkThreshold() thresh_image.SetInputConnection(aa_image.GetOutputPort()) thresh_image.ThresholdByLower(10000) surface_image = vtk.vtkDataSetSurfaceFilter() surface_image.SetInputConnection(thresh_image.GetOutputPort()) mapper_image = vtk.vtkPolyDataMapper() mapper_image.SetInputConnection(surface_image.GetOutputPort()) mapper_image.SetScalarRange(270,310) actor_image = vtk.vtkActor() actor_image.SetMapper(mapper_image) ren_image = vtk.vtkRenderer() ren_image.AddActor(actor_image) ren_image.SetViewport(0.0,0.0,0.5,0.5) renWin.AddRenderer(ren_image) ############################################################################# # Case 2: Rectilinear type.
nonMax.SetVectorInputData(imgGradient.GetOutput()) nonMax.SetDimensionality(2) pad = vtk.vtkImageConstantPad() pad.SetInputConnection(imgGradient.GetOutputPort()) pad.SetOutputNumberOfScalarComponents(3) pad.SetConstant(0) pad.Update() i2sp1 = vtk.vtkImageToStructuredPoints() i2sp1.SetInputConnection(nonMax.GetOutputPort()) i2sp1.SetVectorInputData(pad.GetOutput()) # link edgles imgLink = vtk.vtkLinkEdgels() imgLink.SetInputConnection(i2sp1.GetOutputPort()) imgLink.SetGradientThreshold(2) # threshold links thresholdEdgels = vtk.vtkThreshold() thresholdEdgels.SetInputConnection(imgLink.GetOutputPort()) thresholdEdgels.ThresholdByUpper(10) thresholdEdgels.AllScalarsOff() gf = vtk.vtkGeometryFilter() gf.SetInputConnection(thresholdEdgels.GetOutputPort()) i2sp = vtk.vtkImageToStructuredPoints() i2sp.SetInputConnection(imgMagnitude.GetOutputPort()) i2sp.SetVectorInputData(pad.GetOutput()) i2sp.Update() # subpixel them spe = vtk.vtkSubPixelPositionEdgels() spe.SetInputConnection(gf.GetOutputPort()) spe.SetGradMapsData(i2sp.GetOutput()) strip = vtk.vtkStripper() strip.SetInputConnection(spe.GetOutputPort())
def _plotInternal(self): tmpLevels = [] tmpColors = [] indices = self._gm.fillareaindices if indices is None: indices = [1] while len(indices) < len(self._contourColors): indices.append(indices[-1]) if len(self._contourLevels) > len(self._contourColors): raise RuntimeError( "You asked for %i levels but provided only %i colors\n" "Graphic Method: %s of type %s\nLevels: %s" % (len(self._contourLevels), len(self._contourColors), self._gm.name, self._gm.g_name, repr(self._contourLevels))) elif len(self._contourLevels) < len(self._contourColors) - 1: warnings.warn( "You asked for %i lgridevels but provided %i colors, extra " "ones will be ignored\nGraphic Method: %s of type %s" % (len(self._contourLevels), len(self._contourColors), self._gm.name, self._gm.g_name)) for i, l in enumerate(self._contourLevels): if i == 0: C = [self._contourColors[i]] if numpy.allclose(self._contourLevels[0][0], -1.e20): # ok it's an extension arrow L = [self._scalarRange[0] - 1., self._contourLevels[0][1]] else: L = list(self._contourLevels[i]) I = [indices[i]] else: if l[0] == L[-1] and I[-1] == indices[i]: # Ok same type lets keep going if numpy.allclose(l[1], 1.e20): L.append(self._scalarRange[1] + 1.) else: L.append(l[1]) C.append(self._contourColors[i]) else: # ok we need new contouring tmpLevels.append(L) tmpColors.append(C) C = [self._contourColors[i]] L = self._contourLevels[i] I = [indices[i]] tmpLevels.append(L) tmpColors.append(C) mappers = [] luts = [] cots = [] geos = [] for i, l in enumerate(tmpLevels): # Ok here we are trying to group together levels can be, a join # will happen if: next set of levels contnues where one left off # AND pattern is identical wholeDataMin, wholeDataMax = vcs.minmax(self._originalData1) # TODO this should really just be a single polydata that is # colored by scalars: for j, color in enumerate(tmpColors[i]): mapper = vtk.vtkPolyDataMapper() lut = vtk.vtkLookupTable() th = vtk.vtkThreshold() th.ThresholdBetween(l[j], l[j+1]) th.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort()) geoFilter2 = vtk.vtkDataSetSurfaceFilter() geoFilter2.SetInputConnection(th.GetOutputPort()) geos.append(geoFilter2) mapper.SetInputConnection(geoFilter2.GetOutputPort()) lut.SetNumberOfTableValues(1) r, g, b = self._colorMap.index[color] lut.SetTableValue(0, r/100., g/100., b/100.) mapper.SetLookupTable(lut) mapper.SetScalarRange(l[j], l[j+1]) luts.append([lut, [l[j], l[j+1], True]]) # Store the mapper only if it's worth it? # Need to do it with the whole slab min/max for animation # purposes if not (l[j+1] < wholeDataMin or l[j] > wholeDataMax): mappers.append(mapper) self._resultDict["vtk_backend_luts"] = luts if len(cots) > 0: self._resultDict["vtk_backend_contours"] = cots if len(geos) > 0: self._resultDict["vtk_backend_geofilters"] = geos numLevels = len(self._contourLevels) if mappers == []: # ok didn't need to have special banded contours mapper = vtk.vtkPolyDataMapper() mappers = [mapper] # Colortable bit # make sure length match while len(self._contourColors) < numLevels: self._contourColors.append(self._contourColors[-1]) lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(numLevels) for i in range(numLevels): r, g, b = self._colorMap.index[self._contourColors[i]] lut.SetTableValue(i, r / 100., g / 100., b / 100.) mapper.SetLookupTable(lut) if numpy.allclose(self._contourLevels[0], -1.e20): lmn = mn - 1. else: lmn = self._contourLevels[0] if numpy.allclose(self._contourLevels[-1], 1.e20): lmx = mx + 1. else: lmx = self._contourLevels[-1] mapper.SetScalarRange(lmn, lmx) self._resultDict["vtk_backend_luts"] = [[lut, [lmn, lmx, True]]] if self._maskedDataMapper is not None: # Note that this is different for meshfill -- others prepend. mappers.append(self._maskedDataMapper) # This is also different for meshfill, others use # vcs.utils.getworldcoordinates x1, x2, y1, y2 = vcs2vtk.getRange(self._gm, self._vtkDataSetBounds[0], self._vtkDataSetBounds[1], self._vtkDataSetBounds[2], self._vtkDataSetBounds[3]) # Add a second mapper for wireframe meshfill: if self._gm.mesh: lineMappers = [] wireLUT = vtk.vtkLookupTable() wireLUT.SetNumberOfTableValues(1) wireLUT.SetTableValue(0, 0, 0, 0) for polyMapper in mappers: lineMapper = vtk.vtkPolyDataMapper() lineMapper.SetInputConnection( polyMapper.GetInputConnection(0, 0)) lineMapper._useWireFrame = True # 'noqa' comments disable pep8 checking for these lines. There # is not a readable way to shorten them due to the unwieldly # method name. # # Setup depth resolution so lines stay above points: polyMapper.SetResolveCoincidentTopologyPolygonOffsetParameters(0, 1) # noqa polyMapper.SetResolveCoincidentTopologyToPolygonOffset() lineMapper.SetResolveCoincidentTopologyPolygonOffsetParameters(1, 1) # noqa lineMapper.SetResolveCoincidentTopologyToPolygonOffset() lineMapper.SetLookupTable(wireLUT) lineMappers.append(lineMapper) mappers.extend(lineMappers) # And now we need actors to actually render this thing actors = [] for mapper in mappers: act = vtk.vtkActor() act.SetMapper(mapper) if hasattr(mapper, "_useWireFrame"): prop = act.GetProperty() prop.SetRepresentationToWireframe() if self._vtkGeoTransform is None: # If using geofilter on wireframed does not get wrppaed not # sure why so sticking to many mappers act = vcs2vtk.doWrap(act, [x1, x2, y1, y2], self._dataWrapModulo) # TODO See comment in boxfill. if mapper is self._maskedDataMapper: actors.append([act, self._maskedDataMapper, [x1, x2, y1, y2]]) else: actors.append([act, [x1, x2, y1, y2]]) # create a new renderer for this mapper # (we need one for each mapper because of cmaera flips) ren = self._context.fitToViewport( act, [self._template.data.x1, self._template.data.x2, self._template.data.y1, self._template.data.y2], wc=[x1, x2, y1, y2], geo=self._vtkGeoTransform, priority=self._template.data.priority) self._resultDict["vtk_backend_actors"] = actors self._template.plot(self._context.canvas, self._data1, self._gm, bg=self._context.bg, X=numpy.arange(self._vtkDataSetBounds[0], self._vtkDataSetBounds[1] * 1.1, (self._vtkDataSetBounds[1] - self._vtkDataSetBounds[0]) / 10.), Y=numpy.arange(self._vtkDataSetBounds[2], self._vtkDataSetBounds[3] * 1.1, (self._vtkDataSetBounds[3] - self._vtkDataSetBounds[2]) / 10.)) legend = getattr(self._gm, "legend", None) if self._gm.ext_1: if isinstance(self._contourLevels[0], list): if numpy.less(abs(self._contourLevels[0][0]), 1.e20): # Ok we need to add the ext levels self._contourLevels.insert(0, [-1.e20, levs[0][0]]) else: if numpy.less(abs(self._contourLevels[0]), 1.e20): # need to add an ext self._contourLevels.insert(0, -1.e20) if self._gm.ext_2: if isinstance(self._contourLevels[-1], list): if numpy.less(abs(self._contourLevels[-1][1]), 1.e20): # need ext self._contourLevels.append([self._contourLevels[-1][1], 1.e20]) else: if numpy.less(abs(self._contourLevels[-1]), 1.e20): # need exts self._contourLevels.append(1.e20) self._resultDict.update( self._context.renderColorBar(self._template, self._contourLevels, self._contourColors, legend, self._colorMap)) if self._context.canvas._continents is None: self._useContinents = False if self._useContinents: projection = vcs.elements["projection"][self._gm.projection] self._context.plotContinents(x1, x2, y1, y2, projection, self._dataWrapModulo, self._template)
def Execute(self): if self.Surface == None: self.PrintError('Error: No input surface.') wallEntityOffset = 1 if self.SkipCapping or not self.BoundaryLayerOnCaps: self.PrintLog("Not capping surface") surface = self.Surface cellEntityIdsArray = vtk.vtkIntArray() cellEntityIdsArray.SetName(self.CellEntityIdsArrayName) cellEntityIdsArray.SetNumberOfTuples(surface.GetNumberOfCells()) cellEntityIdsArray.FillComponent(0,0.0) surface.GetCellData().AddArray(cellEntityIdsArray) else: self.PrintLog("Capping surface") capper = vmtkscripts.vmtkSurfaceCapper() capper.Surface = self.Surface capper.Interactive = 0 capper.Method = self.CappingMethod capper.TriangleOutput = 0 capper.CellEntityIdOffset = wallEntityOffset capper.Execute() surface = capper.Surface if self.SkipRemeshing: remeshedSurface = surface else: self.PrintLog("Remeshing surface") remeshing = vmtkscripts.vmtkSurfaceRemeshing() remeshing.Surface = surface remeshing.CellEntityIdsArrayName = self.CellEntityIdsArrayName remeshing.TargetEdgeLength = self.TargetEdgeLength remeshing.MaxEdgeLength = self.MaxEdgeLength remeshing.MinEdgeLength = self.MinEdgeLength remeshing.TargetEdgeLengthFactor = self.TargetEdgeLengthFactor remeshing.TargetEdgeLengthArrayName = self.TargetEdgeLengthArrayName remeshing.TriangleSplitFactor = self.TriangleSplitFactor remeshing.ElementSizeMode = self.ElementSizeMode if self.RemeshCapsOnly: remeshing.ExcludeEntityIds = [wallEntityOffset] remeshing.Execute() remeshedSurface = remeshing.Surface if self.BoundaryLayer: projection = vmtkscripts.vmtkSurfaceProjection() projection.Surface = remeshedSurface projection.ReferenceSurface = surface projection.Execute() normals = vmtkscripts.vmtkSurfaceNormals() normals.Surface = projection.Surface normals.NormalsArrayName = 'Normals' normals.Execute() surfaceToMesh = vmtkscripts.vmtkSurfaceToMesh() surfaceToMesh.Surface = normals.Surface surfaceToMesh.Execute() self.PrintLog("Generating boundary layer") placeholderCellEntityId = 9999 boundaryLayer = vmtkscripts.vmtkBoundaryLayer() boundaryLayer.Mesh = surfaceToMesh.Mesh boundaryLayer.WarpVectorsArrayName = 'Normals' boundaryLayer.NegateWarpVectors = True boundaryLayer.ThicknessArrayName = self.TargetEdgeLengthArrayName if self.ElementSizeMode == 'edgelength': boundaryLayer.ConstantThickness = True else: boundaryLayer.ConstantThickness = False boundaryLayer.IncludeSurfaceCells = 0 boundaryLayer.NumberOfSubLayers = self.NumberOfSubLayers boundaryLayer.NumberOfSubsteps = self.NumberOfSubsteps boundaryLayer.Relaxation = self.Relaxation boundaryLayer.LocalCorrectionFactor = self.LocalCorrectionFactor boundaryLayer.SubLayerRatio = self.SubLayerRatio boundaryLayer.Thickness = self.BoundaryLayerThicknessFactor * self.TargetEdgeLength boundaryLayer.ThicknessRatio = self.BoundaryLayerThicknessFactor * self.TargetEdgeLengthFactor boundaryLayer.MaximumThickness = self.BoundaryLayerThicknessFactor * self.MaxEdgeLength if not self.BoundaryLayerOnCaps: boundaryLayer.SidewallCellEntityId = placeholderCellEntityId boundaryLayer.InnerSurfaceCellEntityId = wallEntityOffset boundaryLayer.Execute() meshToSurface = vmtkscripts.vmtkMeshToSurface() meshToSurface.Mesh = boundaryLayer.InnerSurfaceMesh meshToSurface.Execute() innerSurface = meshToSurface.Surface if not self.BoundaryLayerOnCaps: self.PrintLog("Capping inner surface") capper = vmtkscripts.vmtkSurfaceCapper() capper.Surface = innerSurface capper.Interactive = 0 capper.Method = self.CappingMethod capper.TriangleOutput = 1 capper.CellEntityIdOffset = wallEntityOffset capper.Execute() self.PrintLog("Remeshing endcaps") remeshing = vmtkscripts.vmtkSurfaceRemeshing() remeshing.Surface = capper.Surface remeshing.CellEntityIdsArrayName = self.CellEntityIdsArrayName remeshing.TargetEdgeLength = self.TargetEdgeLength * self.EndcapsEdgeLengthFactor remeshing.MaxEdgeLength = self.MaxEdgeLength remeshing.MinEdgeLength = self.MinEdgeLength remeshing.TargetEdgeLengthFactor = self.TargetEdgeLengthFactor * self.EndcapsEdgeLengthFactor remeshing.TargetEdgeLengthArrayName = self.TargetEdgeLengthArrayName remeshing.TriangleSplitFactor = self.TriangleSplitFactor remeshing.ElementSizeMode = self.ElementSizeMode remeshing.ExcludeEntityIds = [wallEntityOffset] remeshing.Execute() innerSurface = remeshing.Surface self.PrintLog("Computing sizing function") sizingFunction = vtkvmtk.vtkvmtkPolyDataSizingFunction() sizingFunction.SetInputData(innerSurface) sizingFunction.SetSizingFunctionArrayName(self.SizingFunctionArrayName) sizingFunction.SetScaleFactor(self.VolumeElementScaleFactor) sizingFunction.Update() surfaceToMesh2 = vmtkscripts.vmtkSurfaceToMesh() surfaceToMesh2.Surface = sizingFunction.GetOutput() surfaceToMesh2.Execute() self.PrintLog("Generating volume mesh") tetgen = vmtkscripts.vmtkTetGen() tetgen.Mesh = surfaceToMesh2.Mesh tetgen.GenerateCaps = 0 tetgen.UseSizingFunction = 1 tetgen.SizingFunctionArrayName = self.SizingFunctionArrayName tetgen.CellEntityIdsArrayName = self.CellEntityIdsArrayName tetgen.Order = 1 tetgen.Quality = 1 tetgen.PLC = 1 tetgen.NoBoundarySplit = 1 tetgen.RemoveSliver = 1 tetgen.OutputSurfaceElements = 0 tetgen.OutputVolumeElements = 1 tetgen.Execute() #w = vtk.vtkXMLUnstructuredGridWriter() #w.SetInput(tetgen.Mesh) #w.SetFileName('tet.vtu') #w.Write() if tetgen.Mesh.GetNumberOfCells() == 0 and surfaceToMesh.Mesh.GetNumberOfCells() > 0: self.PrintLog('An error occurred during tetrahedralization. Will only output surface mesh and boundary layer.') surfaceToMesh.Mesh.GetCellData().GetArray(self.CellEntityIdsArrayName).FillComponent(0,wallEntityOffset) self.PrintLog("Assembling final mesh") appendFilter = vtkvmtk.vtkvmtkAppendFilter() appendFilter.AddInputData(surfaceToMesh.Mesh) appendFilter.AddInputData(boundaryLayer.Mesh) appendFilter.AddInputData(tetgen.Mesh) #appendFilter.AddInput(boundaryLayer.InnerSurfaceMesh) if not self.BoundaryLayerOnCaps: threshold = vtk.vtkThreshold() threshold.SetInputData(surfaceToMesh2.Mesh) threshold.ThresholdByUpper(1.5) threshold.SetInputArrayToProcess(0,0,0,1,self.CellEntityIdsArrayName) threshold.Update() endcaps = threshold.GetOutput() appendFilter.AddInputData(endcaps) appendFilter.Update() self.Mesh = appendFilter.GetOutput() if not self.BoundaryLayerOnCaps: cellEntityIdsArray = self.Mesh.GetCellData().GetArray(self.CellEntityIdsArrayName) def VisitNeighbors(i, cellEntityId): cellPointIds = vtk.vtkIdList() self.Mesh.GetCellPoints(i,cellPointIds) neighborPointIds = vtk.vtkIdList() neighborPointIds.SetNumberOfIds(1) pointNeighborCellIds = vtk.vtkIdList() neighborCellIds = vtk.vtkIdList() for j in range(cellPointIds.GetNumberOfIds()): neighborPointIds.SetId(0,cellPointIds.GetId(j)) self.Mesh.GetCellNeighbors(i,neighborPointIds,pointNeighborCellIds) for k in range(pointNeighborCellIds.GetNumberOfIds()): neighborCellIds.InsertNextId(pointNeighborCellIds.GetId(k)) for j in range(neighborCellIds.GetNumberOfIds()): cellId = neighborCellIds.GetId(j) neighborCellEntityId = cellEntityIdsArray.GetTuple1(cellId) neighborCellType = self.Mesh.GetCellType(cellId) if neighborCellType not in [vtk.VTK_TRIANGLE, vtk.VTK_QUADRATIC_TRIANGLE, vtk.VTK_QUAD]: continue if neighborCellEntityId != placeholderCellEntityId: continue cellEntityIdsArray.SetTuple1(cellId,cellEntityId) VisitNeighbors(cellId,cellEntityId) for i in range(self.Mesh.GetNumberOfCells()): cellEntityId = cellEntityIdsArray.GetTuple1(i) cellType = self.Mesh.GetCellType(i) if cellType not in [vtk.VTK_TRIANGLE, vtk.VTK_QUADRATIC_TRIANGLE, vtk.VTK_QUAD]: continue if cellEntityId in [0, 1, placeholderCellEntityId]: continue VisitNeighbors(i,cellEntityId) else: self.PrintLog("Computing sizing function") sizingFunction = vtkvmtk.vtkvmtkPolyDataSizingFunction() sizingFunction.SetInputData(remeshedSurface) sizingFunction.SetSizingFunctionArrayName(self.SizingFunctionArrayName) sizingFunction.SetScaleFactor(self.VolumeElementScaleFactor) sizingFunction.Update() self.PrintLog("Converting surface to mesh") surfaceToMesh = vmtkscripts.vmtkSurfaceToMesh() surfaceToMesh.Surface = sizingFunction.GetOutput() surfaceToMesh.Execute() self.PrintLog("Generating volume mesh") tetgen = vmtkscripts.vmtkTetGen() tetgen.Mesh = surfaceToMesh.Mesh tetgen.GenerateCaps = 0 tetgen.UseSizingFunction = 1 tetgen.SizingFunctionArrayName = self.SizingFunctionArrayName tetgen.CellEntityIdsArrayName = self.CellEntityIdsArrayName tetgen.Order = 1 tetgen.Quality = 1 tetgen.PLC = 1 tetgen.NoBoundarySplit = 1 tetgen.RemoveSliver = 1 tetgen.OutputSurfaceElements = 1 tetgen.OutputVolumeElements = 1 tetgen.Execute() self.Mesh = tetgen.Mesh if self.Mesh.GetNumberOfCells() == 0 and surfaceToMesh.Mesh.GetNumberOfCells() > 0: self.PrintLog('An error occurred during tetrahedralization. Will only output surface mesh.') self.Mesh = surfaceToMesh.Mesh if self.Tetrahedralize: tetrahedralize = vtkvmtk.vtkvmtkUnstructuredGridTetraFilter() tetrahedralize.SetInputData(self.Mesh) tetrahedralize.Update() self.Mesh = tetrahedralize.GetOutput() self.RemeshedSurface = remeshedSurface
renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) iren.SetDesiredUpdateRate(3) # Create the reader for the data # This is the data the will be volume rendered reader = vtk.vtkStructuredPointsReader() reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/ironProt.vtk") # create a reader for the other data that will # be contoured and displayed as a polygonal mesh reader2 = vtk.vtkSLCReader() reader2.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/neghip.slc") # convert from vtkImageData to vtkUnstructuredGrid, remove # any cells where all values are below 80 thresh = vtk.vtkThreshold() thresh.ThresholdByUpper(80) thresh.AllScalarsOff() thresh.SetInputConnection(reader.GetOutputPort()) # make sure we have only tetrahedra trifilter = vtk.vtkDataSetTriangleFilter() trifilter.SetInputConnection(thresh.GetOutputPort()) # Create transfer mapping scalar value to opacity opacityTransferFunction = vtk.vtkPiecewiseFunction() opacityTransferFunction.AddPoint(80,0.0) opacityTransferFunction.AddPoint(120,0.2) opacityTransferFunction.AddPoint(255,0.2) # Create transfer mapping scalar value to color colorTransferFunction = vtk.vtkColorTransferFunction() colorTransferFunction.AddRGBPoint(80.0,0.0,0.0,0.0) colorTransferFunction.AddRGBPoint(120.0,0.0,0.0,1.0)
def Execute(self): if not self.Mesh: self.PrintError('Error: No input mesh.') return if not self.CellEntityIdsArrayName: self.PrintError('Error: No input CellEntityIdsArrayName.') return if not self.vmtkRenderer: self.vmtkRenderer = vmtkrenderer.vmtkRenderer() self.vmtkRenderer.Initialize() self.OwnRenderer = 1 self.vmtkRenderer.RegisterScript(self) threshold = vtk.vtkThreshold() threshold.SetInput(self.Mesh) threshold.ThresholdByUpper(self.VolumeCellEntityId+0.5) threshold.SetInputArrayToProcess(0,0,0,1,self.CellEntityIdsArrayName) threshold.Update() boundaryMesh = threshold.GetOutput() boundaryMesh.GetCellData().SetActiveScalars(self.CellEntityIdsArrayName) boundaryMapper = vtk.vtkDataSetMapper() boundaryMapper.SetInput(boundaryMesh) boundaryMapper.ScalarVisibilityOn() boundaryMapper.SetScalarModeToUseCellData() boundaryMapper.SetScalarRange(boundaryMesh.GetCellData().GetScalars().GetRange()) boundaryActor = vtk.vtkActor() boundaryActor.SetMapper(boundaryMapper) self.vmtkRenderer.Renderer.AddActor(boundaryActor) wallThreshold = vtk.vtkThreshold() wallThreshold.SetInput(boundaryMesh) wallThreshold.ThresholdByLower(self.WallCellEntityId+0.5) wallThreshold.SetInputArrayToProcess(0,0,0,1,self.CellEntityIdsArrayName) wallThreshold.Update() wallMeshToSurface = vtk.vtkGeometryFilter() wallMeshToSurface.SetInput(wallThreshold.GetOutput()) wallMeshToSurface.Update() boundaryReferenceSystems = vtkvmtk.vtkvmtkBoundaryReferenceSystems() boundaryReferenceSystems.SetInput(wallMeshToSurface.GetOutput()) boundaryReferenceSystems.SetBoundaryRadiusArrayName("BoundaryRadius") boundaryReferenceSystems.SetBoundaryNormalsArrayName("BoundaryNormals") boundaryReferenceSystems.SetPoint1ArrayName("Point1Array") boundaryReferenceSystems.SetPoint2ArrayName("Point2Array") boundaryReferenceSystems.Update() self.ReferenceSystems = boundaryReferenceSystems.GetOutput() cellEntityIdsArray = vtk.vtkIntArray() cellEntityIdsArray.SetName(self.CellEntityIdsArrayName) cellEntityIdsArray.SetNumberOfTuples(self.ReferenceSystems.GetNumberOfPoints()) self.ReferenceSystems.GetPointData().AddArray(cellEntityIdsArray) wallMeshToSurface = vtk.vtkGeometryFilter() wallMeshToSurface.SetInput(boundaryMesh) wallMeshToSurface.Update() boundarySurface = wallMeshToSurface.GetOutput() pointCells = vtk.vtkIdList() surfaceCellEntityIdsArray = vtk.vtkIntArray() surfaceCellEntityIdsArray.DeepCopy(boundarySurface.GetCellData().GetArray(self.CellEntityIdsArrayName)) self.PrintLog('') for i in range(self.ReferenceSystems.GetNumberOfPoints()): pointId = boundarySurface.FindPoint(self.ReferenceSystems.GetPoint(i)) boundarySurface.GetPointCells(pointId,pointCells) cellId = pointCells.GetId(0) cellEntityId = surfaceCellEntityIdsArray.GetValue(cellId) cellEntityIdsArray.SetValue(i,cellEntityId) origin = self.ReferenceSystems.GetPoint(i) normal = self.ReferenceSystems.GetPointData().GetArray("BoundaryNormals").GetTuple3(i) radius = self.ReferenceSystems.GetPointData().GetArray("BoundaryRadius").GetTuple1(i) logLine = 'CellEntityId: %d\n' % cellEntityId logLine += ' Origin: %f, %f, %f\n' % (origin[0],origin[1],origin[2]) logLine += ' Normal: %f, %f, %f\n' % (normal[0],normal[1],normal[2]) logLine += ' Radius: %f\n' % radius self.PrintLog(logLine) self.ReferenceSystems.GetPointData().SetActiveScalars(self.CellEntityIdsArrayName) labelsMapper = vtk.vtkLabeledDataMapper(); labelsMapper.SetInput(self.ReferenceSystems) labelsMapper.SetLabelModeToLabelScalars() labelsActor = vtk.vtkActor2D() labelsActor.SetMapper(labelsMapper) self.vmtkRenderer.Renderer.AddActor(labelsActor) self.vmtkRenderer.Render() if self.OwnRenderer: self.vmtkRenderer.Deallocate()
def smoothMultipleSegments(self): import vtkSegmentationCorePython as vtkSegmentationCore # Generate merged labelmap of all visible segments segmentationNode = self.scriptedEffect.parameterSetNode().GetSegmentationNode() visibleSegmentIds = vtk.vtkStringArray() segmentationNode.GetDisplayNode().GetVisibleSegmentIDs(visibleSegmentIds) if visibleSegmentIds.GetNumberOfValues() == 0: logging.info("Smoothing operation skipped: there are no visible segments") return mergedImage = vtkSegmentationCore.vtkOrientedImageData() if not segmentationNode.GenerateMergedLabelmapForAllSegments(mergedImage, vtkSegmentationCore.vtkSegmentation.EXTENT_UNION_OF_SEGMENTS_PADDED, None, visibleSegmentIds): logging.error('Failed to apply smoothing: cannot get list of visible segments') return segmentLabelValues = [] # list of [segmentId, labelValue] for i in range(visibleSegmentIds.GetNumberOfValues()): segmentId = visibleSegmentIds.GetValue(i) segmentLabelValues.append([segmentId, i+1]) # Perform smoothing in voxel space ici = vtk.vtkImageChangeInformation() ici.SetInputData(mergedImage) ici.SetOutputSpacing(1, 1, 1) ici.SetOutputOrigin(0, 0, 0) # Convert labelmap to combined polydata # vtkDiscreteFlyingEdges3D cannot be used here, as in the output of that filter, # each labeled region is completely disconnected from neighboring regions, and # for joint smoothing it is essential for the points to move together. convertToPolyData = vtk.vtkDiscreteMarchingCubes() convertToPolyData.SetInputConnection(ici.GetOutputPort()) convertToPolyData.SetNumberOfContours(len(segmentLabelValues)) contourIndex = 0 for segmentId, labelValue in segmentLabelValues: convertToPolyData.SetValue(contourIndex, labelValue) contourIndex += 1 # Low-pass filtering using Taubin's method smoothingFactor = self.scriptedEffect.doubleParameter("JointTaubinSmoothingFactor") smoothingIterations = 100 # according to VTK documentation 10-20 iterations could be enough but we use a higher value to reduce chance of shrinking passBand = pow(10.0, -4.0*smoothingFactor) # gives a nice range of 1-0.0001 from a user input of 0-1 smoother = vtk.vtkWindowedSincPolyDataFilter() smoother.SetInputConnection(convertToPolyData.GetOutputPort()) smoother.SetNumberOfIterations(smoothingIterations) smoother.BoundarySmoothingOff() smoother.FeatureEdgeSmoothingOff() smoother.SetFeatureAngle(90.0) smoother.SetPassBand(passBand) smoother.NonManifoldSmoothingOn() smoother.NormalizeCoordinatesOn() # Extract a label threshold = vtk.vtkThreshold() threshold.SetInputConnection(smoother.GetOutputPort()) # Convert to polydata geometryFilter = vtk.vtkGeometryFilter() geometryFilter.SetInputConnection(threshold.GetOutputPort()) # Convert polydata to stencil polyDataToImageStencil = vtk.vtkPolyDataToImageStencil() polyDataToImageStencil.SetInputConnection(geometryFilter.GetOutputPort()) polyDataToImageStencil.SetOutputSpacing(1,1,1) polyDataToImageStencil.SetOutputOrigin(0,0,0) polyDataToImageStencil.SetOutputWholeExtent(mergedImage.GetExtent()) # Convert stencil to image stencil = vtk.vtkImageStencil() emptyBinaryLabelMap = vtk.vtkImageData() emptyBinaryLabelMap.SetExtent(mergedImage.GetExtent()) emptyBinaryLabelMap.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1) vtkSegmentationCore.vtkOrientedImageDataResample.FillImage(emptyBinaryLabelMap, 0) stencil.SetInputData(emptyBinaryLabelMap) stencil.SetStencilConnection(polyDataToImageStencil.GetOutputPort()) stencil.ReverseStencilOn() stencil.SetBackgroundValue(1) # General foreground value is 1 (background value because of reverse stencil) imageToWorldMatrix = vtk.vtkMatrix4x4() mergedImage.GetImageToWorldMatrix(imageToWorldMatrix) for segmentId, labelValue in segmentLabelValues: threshold.ThresholdBetween(labelValue, labelValue) stencil.Update() smoothedBinaryLabelMap = vtkSegmentationCore.vtkOrientedImageData() smoothedBinaryLabelMap.ShallowCopy(stencil.GetOutput()) smoothedBinaryLabelMap.SetImageToWorldMatrix(imageToWorldMatrix) # Write results to segments directly, bypassing masking slicer.vtkSlicerSegmentationsModuleLogic.SetBinaryLabelmapToSegment(smoothedBinaryLabelMap, segmentationNode, segmentId, slicer.vtkSlicerSegmentationsModuleLogic.MODE_REPLACE, smoothedBinaryLabelMap.GetExtent())