def _createSpheres(self): """Create all spheres according to self._internalPoints. """ # make sure we're all empty self._destroySpheres() for ptIdx in range(len(self._internalPoints)): pt = self._internalPoints[ptIdx] # each point gets potentially more than one sphere spheres = [] # then create and add the internal spheres radiusStep = self._getRadiusStep() # we do the mainSphere and the internal spheres in one go for i in range(self._config.numInternalSpheres + 1): sphere = vtk.vtkSphereSource() sphere.SetCenter(pt) sphere.SetRadius(self._config.radius - radiusStep * i) sphere.SetThetaResolution(self._config.thetaResolution) sphere.SetPhiResolution(self._config.phiResolution) # use calculator to add array with VolumeIndex calc = vtk.vtkArrayCalculator() calc.SetAttributeModeToUsePointData() calc.SetFunction('%d' % (ptIdx,)) calc.SetResultArrayName('VolumeIndex') calc.SetInput(sphere.GetOutput()) self._appendPolyData.AddInput(calc.GetOutput()) spheres.append((calc,sphere)) self._sphereSources.append(spheres)
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkArrayCalculator(), 'Processing.', ('vtkDataSet',), ('vtkDataSet',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def arrayCompare(self): calculator = vtk.vtkArrayCalculator() attributeData = None referenceAttributeData = None if self.Method == 'pointarray': attributeData = self.Mesh.GetPointData() referenceAttributeData = self.ReferenceMesh.GetPointData() calculator.SetAttributeModeToUsePointData() elif self.Method == 'cellarray': attributeData = self.Mesh.GetCellData() referenceAttributeData = self.ReferenceMesh.GetCellData() calculator.SetAttributeModeToUseCellData() if not self.ArrayName: self.PrintError('Error: No ArrayName.') if not referenceAttributeData.GetArray(self.ArrayName): self.PrintError('Error: Invalid ArrayName.') if not attributeData.GetArray(self.ArrayName): self.PrintError('Error: Invalid ArrayName.') referenceArrayName = 'Ref' + self.ArrayName meshPoints = self.Mesh.GetNumberOfPoints() referencePoints = self.ReferenceMesh.GetNumberOfPoints() pointsDifference = meshPoints - referencePoints self.PrintLog("Mesh points: " + str(meshPoints)) self.PrintLog("Reference Points: " + str(referencePoints)) if abs(pointsDifference) > 0: self.ResultLog = 'Uneven NumberOfPoints' return False refArray = referenceAttributeData.GetArray(self.ArrayName) refArray.SetName(referenceArrayName) attributeData.AddArray(refArray) calculator.SetInputData(self.Mesh) calculator.AddScalarVariable('a', self.ArrayName, 0) calculator.AddScalarVariable('b', referenceArrayName, 0) calculator.SetFunction("a - b") calculator.SetResultArrayName('ResultArray') calculator.Update() self.ResultData = calculator.GetOutput() if self.Method == 'pointarray': resultRange = self.ResultData.GetPointData().GetArray( 'ResultArray').GetRange() elif self.Method == 'cellarray': resultRange = self.ResultData.GetCellData().GetArray( 'ResultArray').GetRange() self.PrintLog('Result Range: ' + str(resultRange)) if max([abs(r) for r in resultRange]) < self.Tolerance: return True return False
def test_contours(self): cell = vtk.vtkUnstructuredGrid() cell.ShallowCopy(self.Cell) np = self.Cell.GetNumberOfPoints() ncomb = pow(2, np) scalar = vtk.vtkDoubleArray() scalar.SetName("scalar") scalar.SetNumberOfTuples(np) cell.GetPointData().SetScalars(scalar) incorrectCases = [] for i in range(1, ncomb - 1): c = Combination(np, i) for p in range(np): scalar.SetTuple1(p, c[p]) gradientFilter = vtk.vtkGradientFilter() gradientFilter.SetInputData(cell) gradientFilter.SetInputArrayToProcess(0, 0, 0, 0, 'scalar') gradientFilter.SetResultArrayName('grad') gradientFilter.Update() contourFilter = vtk.vtkContourFilter() contourFilter.SetInputConnection(gradientFilter.GetOutputPort()) contourFilter.SetNumberOfContours(1) contourFilter.SetValue(0, 0.5) contourFilter.Update() normalsFilter = vtk.vtkPolyDataNormals() normalsFilter.SetInputConnection(contourFilter.GetOutputPort()) normalsFilter.SetConsistency(0) normalsFilter.SetFlipNormals(0) normalsFilter.SetSplitting(0) calcFilter = vtk.vtkArrayCalculator() calcFilter.SetInputConnection(normalsFilter.GetOutputPort()) calcFilter.SetAttributeTypeToPointData() calcFilter.AddVectorArrayName('grad') calcFilter.AddVectorArrayName('Normals') calcFilter.SetResultArrayName('dir') calcFilter.SetFunction('dot(grad,Normals)') calcFilter.Update() out = vtk.vtkUnstructuredGrid() out.ShallowCopy(calcFilter.GetOutput()) numPts = out.GetNumberOfPoints() if numPts > 0: dirArray = out.GetPointData().GetArray('dir') for p in range(numPts): if (dirArray.GetTuple1(p) > 0.0): # all normals are reversed incorrectCases.append(i) break self.assertEquals(','.join([str(i) for i in incorrectCases]), '')
def Execute(self): if self.Surface == None: self.PrintError('Error: No input surface.') cleaner = vtk.vtkCleanPolyData() cleaner.SetInput(self.Surface) cleaner.Update() triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInput(cleaner.GetOutput()) triangleFilter.Update() self.Surface = triangleFilter.GetOutput() if self.ElementSizeMode == 'edgelength': self.TargetArea = 0.25 * 3.0**0.5 * self.TargetEdgeLength**2 elif self.ElementSizeMode == 'edgelengtharray': calculator = vtk.vtkArrayCalculator() calculator.SetInput(self.Surface) calculator.AddScalarArrayName(self.TargetEdgeLengthArrayName,0) calculator.SetFunction("%f^2 * 0.25 * sqrt(3) * %s^2" % (self.TargetEdgeLengthFactor,self.TargetEdgeLengthArrayName)) calculator.SetResultArrayName(self.TargetAreaArrayName) calculator.Update() self.MaxArea = 0.25 * 3.0**0.5 * self.MaxEdgeLength**2 self.MinArea = 0.25 * 3.0**0.5 * self.MinEdgeLength**2 self.Surface = calculator.GetOutput() surfaceRemeshing = vtkvmtk.vtkvmtkPolyDataSurfaceRemeshing() surfaceRemeshing.SetInput(self.Surface) if self.CellEntityIdsArrayName: surfaceRemeshing.SetCellEntityIdsArrayName(self.CellEntityIdsArrayName) if self.ElementSizeMode in ['area','edgelength']: surfaceRemeshing.SetElementSizeModeToTargetArea() elif self.ElementSizeMode in ['areaarray','edgelengtharray']: surfaceRemeshing.SetElementSizeModeToTargetAreaArray() surfaceRemeshing.SetTargetAreaArrayName(self.TargetAreaArrayName) else: self.PrintError('Error: unsupported ElementSizeMode.') surfaceRemeshing.SetTargetArea(self.TargetArea) surfaceRemeshing.SetTargetAreaFactor(self.TargetAreaFactor) surfaceRemeshing.SetMaxArea(self.MaxArea) surfaceRemeshing.SetMinArea(self.MinArea) surfaceRemeshing.SetNumberOfIterations(self.NumberOfIterations) surfaceRemeshing.SetNumberOfConnectivityOptimizationIterations(self.NumberOfConnectivityOptimizationIterations) surfaceRemeshing.SetRelaxation(self.Relaxation) surfaceRemeshing.SetMinAreaFactor(self.MinAreaFactor) surfaceRemeshing.SetAspectRatioThreshold(self.AspectRatioThreshold) surfaceRemeshing.SetInternalAngleTolerance(self.InternalAngleTolerance) surfaceRemeshing.SetNormalAngleTolerance(self.NormalAngleTolerance) surfaceRemeshing.SetCollapseAngleThreshold(self.CollapseAngleThreshold) surfaceRemeshing.SetPreserveBoundaryEdges(self.PreserveBoundaryEdges) surfaceRemeshing.Update() self.Surface = surfaceRemeshing.GetOutput() if self.Surface.GetSource(): self.Surface.GetSource().UnRegisterAllOutputs()
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__(self, module_manager, vtk.vtkArrayCalculator(), 'Processing.', ('vtkDataSet', ), ('vtkDataSet', ), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def addtoarray(polydata, inputarrayname, outputarrayname, value): """Add value to inputarray of polydata and store in outputarray.""" calc = vtk.vtkArrayCalculator() calc.SetInput(polydata) calc.AddScalarArrayName(inputarrayname, 0) calc.SetFunction('{0} + {1}'.format(inputarrayname, value)) calc.SetResultArrayName(outputarrayname) calc.Update() return calc.GetOutput()
def test_contours(self): cell = vtk.vtkUnstructuredGrid() cell.ShallowCopy(self.Cell) np = self.Cell.GetNumberOfPoints() ncomb = pow(2, np) scalar = vtk.vtkDoubleArray() scalar.SetName("scalar") scalar.SetNumberOfTuples(np) cell.GetPointData().SetScalars(scalar) incorrectCases = [] for i in range(1,ncomb-1): c = Combination(np, i) for p in range(np): scalar.SetTuple1(p, c[p]) gradientFilter = vtk.vtkGradientFilter() gradientFilter.SetInputData(cell) gradientFilter.SetInputArrayToProcess(0,0,0,0,'scalar') gradientFilter.SetResultArrayName('grad') gradientFilter.Update() contourFilter = vtk.vtkContourFilter() contourFilter.SetInputConnection(gradientFilter.GetOutputPort()) contourFilter.SetNumberOfContours(1) contourFilter.SetValue(0, 0.5) contourFilter.Update() normalsFilter = vtk.vtkPolyDataNormals() normalsFilter.SetInputConnection(contourFilter.GetOutputPort()) normalsFilter.SetConsistency(0) normalsFilter.SetFlipNormals(0) normalsFilter.SetSplitting(0) calcFilter = vtk.vtkArrayCalculator() calcFilter.SetInputConnection(normalsFilter.GetOutputPort()) calcFilter.SetAttributeTypeToPointData() calcFilter.AddVectorArrayName('grad') calcFilter.AddVectorArrayName('Normals') calcFilter.SetResultArrayName('dir') calcFilter.SetFunction('grad.Normals') calcFilter.Update() out = vtk.vtkUnstructuredGrid() out.ShallowCopy(calcFilter.GetOutput()) numPts = out.GetNumberOfPoints() if numPts > 0: dirArray = out.GetPointData().GetArray('dir') for p in range(numPts): if(dirArray.GetTuple1(p) > 0.0): # all normals are reversed incorrectCases.append(i) break self.assertEquals(','.join([str(i) for i in incorrectCases]), '')
def arrayCompare(self): calculator = vtk.vtkArrayCalculator() attributeData = None referenceAttributeData = None if self.Method == "pointarray": attributeData = self.Mesh.GetPointData() referenceAttributeData = self.ReferenceMesh.GetPointData() calculator.SetAttributeModeToUsePointData() elif self.Method == "cellarray": attributeData = self.Mesh.GetCellData() referenceAttributeData = self.ReferenceMesh.GetCellData() calculator.SetAttributeModeToUseCellData() if not self.ArrayName: self.PrintError("Error: No ArrayName.") if not referenceAttributeData.GetArray(self.ArrayName): self.PrintError("Error: Invalid ArrayName.") if not attributeData.GetArray(self.ArrayName): self.PrintError("Error: Invalid ArrayName.") referenceArrayName = "Ref" + self.ArrayName meshPoints = self.Mesh.GetNumberOfPoints() referencePoints = self.ReferenceMesh.GetNumberOfPoints() pointsDifference = meshPoints - referencePoints self.PrintLog("Mesh points: " + str(meshPoints)) self.PrintLog("Reference Points: " + str(referencePoints)) if abs(pointsDifference) > 0: self.ResultLog = "Uneven NumberOfPoints" return False refArray = referenceAttributeData.GetArray(self.ArrayName) refArray.SetName(referenceArrayName) attributeData.AddArray(refArray) calculator.SetInputData(self.Mesh) calculator.AddScalarVariable("a", self.ArrayName, 0) calculator.AddScalarVariable("b", referenceArrayName, 0) calculator.SetFunction("a - b") calculator.SetResultArrayName("ResultArray") calculator.Update() self.ResultData = calculator.GetOutput() if self.Method == "pointarray": resultRange = self.ResultData.GetPointData().GetArray("ResultArray").GetRange() elif self.Method == "cellarray": resultRange = self.ResultData.GetCellData().GetArray("ResultArray").GetRange() self.PrintLog("Result Range: " + str(resultRange)) if max([abs(r) for r in resultRange]) < self.Tolerance: return True return False
def multiplyarray(polydata, inputarray, outputarray, value): """Multiply inputarray of polydata by specified value and store in outputarray.""" calc = vtk.vtkArrayCalculator() calc.SetInput(polydata) calc.AddScalarArrayName(inputarray, 0) calc.SetFunction('{0} * {1}'.format(inputarray, value)) calc.SetResultArrayName(outputarray) calc.Update() return calc.GetOutput()
def vectornormalization(surface, inputarray, outputarray, iscelldata=False): """Add data array with the normalization of a vector field.""" calc = vtk.vtkArrayCalculator() calc.SetInput(surface) if iscelldata: calc.SetAttributeModeToUseCellData() calc.AddVectorArrayName(inputarray, 0, 1, 2) calc.SetFunction('norm(%s)' % inputarray) calc.SetResultArrayName(outputarray) calc.Update() return calc.GetOutput()
def DeformSurface(self): # interpolate and sample the displacement norms over the surface rbf = vtkvmtkcontrib.vtkvmtkRBFInterpolation2() rbf.SetSource(self.SourceSpheres) rbf.SetRBFTypeToBiharmonic() rbf.ComputeCoefficients() sampler = vtkvmtkcontrib.vtkvmtkPolyDataSampleFunction() sampler.SetInput(self.Surface) sampler.SetImplicitFunction(rbf) sampler.SetSampleArrayName("DisplacementNorms") sampler.Update() sampArray = sampler.GetOutput().GetPointData().GetArray("DisplacementNorms") ##Clamp the negative values to 0 and the positive values to one in a weight array calculator = vtk.vtkArrayCalculator() calculator.SetInput(sampler.GetOutput()) calculator.AddScalarArrayName("DisplacementNorms") calculator.SetFunction("if( DisplacementNorms > 0 , iHat, jHat)") calculator.SetResultArrayName("Weights") calculator.SetResultArrayType(vtk.VTK_FLOAT) calculator.Update() # Create the transform thinPlateSplineTransform = vtk.vtkThinPlateSplineTransform() thinPlateSplineTransform.SetBasisToR() thinPlateSplineTransform.SetSourceLandmarks(self.SourcePoints) thinPlateSplineTransform.SetTargetLandmarks(self.TargetPoints) transform = vtk.vtkTransform() transform.Identity() transform2 = vtk.vtkTransform() transform2.Identity() # Apply weighted transform transformFilter = vtk.vtkWeightedTransformFilter() transformFilter.SetInput(calculator.GetOutput()) transformFilter.SetNumberOfTransforms(3) transformFilter.SetWeightArray("Weights") transformFilter.SetTransform(thinPlateSplineTransform, 0) transformFilter.SetTransform(transform, 1) transformFilter.SetTransform(transform2, 2) transformFilter.Update() normalsFilter = vtk.vtkPolyDataNormals() normalsFilter.SetInput(transformFilter.GetOutput()) normalsFilter.Update() # FIXME: the normal filter apparently introduced some holes in some meshes (wtf?). This filter cleans the mesh cleanFilter = vtk.vtkCleanPolyData() cleanFilter.SetInput(normalsFilter.GetOutput()) cleanFilter.Update() self.DeformedSurface = cleanFilter.GetOutput()
def extract_contour(segmentation_path, contour_path, rgb_data=False): # build pipeline sys.stdout.write('Updating segmentation...'); sys.stdout.flush() segmentation = vtk.vtkMetaImageReader() segmentation.SetFileName(segmentation_path) segmentation.Update() print 'done.' if rgb_data: calculator_function = "mag(MetaImage)" else: calculator_function = "MetaImage * 255" sys.stdout.write('Updating calculator...'); sys.stdout.flush() calculator = vtk.vtkArrayCalculator() calculator.SetInputConnection(segmentation.GetOutputPort()) # Working on point data calculator.SetAttributeModeToUsePointData() calculator.AddScalarArrayName("MetaImage") # magnitude of input calculator.SetFunction("mag(MetaImage)") # The output array will be called resArray calculator.SetResultArrayName("magnitude") # Use AssignAttribute to make resArray the active scalar field aa = vtk.vtkAssignAttribute() aa.SetInputConnection(calculator.GetOutputPort()) aa.Assign("magnitude", "SCALARS", "POINT_DATA") aa.Update() print 'done.' # intensity is either (3 * 255^2)^0.5, or 1 if rgb_data: magnitude = 420.0 else: magnitude = 127 sys.stdout.write('Updating contour...'); sys.stdout.flush() contour = vtk.vtkContourFilter() contour.SetInputConnection(calculator.GetOutputPort()) contour.SetValue(0, magnitude) contour.Update() print 'done.' # write out data file in given format sys.stdout.write('Updating writer...'); sys.stdout.flush() writer = vtk.vtkXMLPolyDataWriter() writer.SetFileName(contour_path) writer.SetCompressorTypeToZLib() writer.SetInputConnection(contour.GetOutputPort()) writer.Write() print 'done.'
def testCalculator(dataset, attributeType, attributeTypeForCalc=None): calc = vtk.vtkArrayCalculator() calc.SetInputData(dataset) if attributeTypeForCalc is not None: calc.SetAttributeType(attributeTypeForCalc) calc.AddScalarArrayName("ID") calc.AddScalarArrayName("Square") calc.SetFunction("ID + Square / 24") calc.SetResultArrayName("Result") calc.Update() fd = calc.GetOutput().GetAttributes(attributeType) if not fd.HasArray("Result"): print( "ERROR: calculator did not produce result array when processing datatype %d" % (attributeType, ))
def set_scaled_scalars(self): debug ("In StructuredPointsProbe::set_scaled_scalars ()") out = self.fil.GetOutput() pd = out.GetPointData() sc = pd.GetScalars() if not sc: # no input scalars return if self.conv_scalar_var.get() == 0: orig_sc = self.prev_fil.GetOutput().GetPointData().GetScalars() if sc.IsA('vtkUnsignedShortArray') and \ sc.GetName() == 'sp_probe_us_data': pd.SetActiveScalars(orig_sc.GetName()) return calc = vtk.vtkArrayCalculator() calc.SetAttributeModeToUsePointData() s_min, s_max = sc.GetRange() # checking to see if input array is constant. avg = (s_max + s_min)*0.5 diff = 1 if (s_max > avg) and (avg > s_min): diff = s_max - s_min base = sc.CreateDataArray(sc.GetDataType()) base.SetNumberOfTuples(sc.GetNumberOfTuples()) base.SetNumberOfComponents(1) base.SetName('sp_probe_us_base') base.FillComponent(0, s_min) pd.AddArray(base) calc.SetInput(out) calc.AddScalarVariable("s", sc.GetName(), 0) calc.AddScalarVariable("sb", base.GetName(), 0) calc.SetFunction("(s - sb)*%f"%(65535.0/diff)) calc.SetResultArrayName('sp_probe_us_data') calc.Update() sc = calc.GetOutput().GetPointData().GetScalars() uca = vtk.vtkUnsignedShortArray() uca.SetName(sc.GetName()) uca.DeepCopy(sc) pd.AddArray(uca) pd.SetActiveScalars('sp_probe_us_data')
def calculator(inp, function, inp_arrays, out_array): """ Function to add vtk calculator Args: inp: InputConnection function: string with function expression inp_arrays: list of input point data arrays out_array: name of output array Returns: calc: calculator object """ calc = vtk.vtkArrayCalculator() for a in inp_arrays: calc.AddVectorArrayName(a) calc.SetInputData(inp.GetOutput()) calc.SetAttributeTypeToPointData() calc.SetFunction(function) calc.SetResultArrayName(out_array) calc.Update() return calc
def main(): args = parse_args() logging.basicConfig(level = getattr(logging, args.logging)) assert os.path.isfile(args.in_meshname), "Input mesh file not found!" data = mesh_io.read_dataset(args.in_meshname) logging.info("Read in {} points.".format(data.GetNumberOfPoints())) calc = vtk.vtkArrayCalculator() calc.SetInputData(data) calc.AddCoordinateScalarVariable("coordsX", 0) calc.AddCoordinateScalarVariable("coordsY", 1) calc.AddCoordinateScalarVariable("coordsZ", 2) calc.SetFunction(args.function) calc.SetResultArrayName("scalars") calc.Update() logging.info("Evaluated '{}' on the mesh.".format(args.function)) writer = vtk.vtkUnstructuredGridWriter() writer.SetInputData(calc.GetOutput()) writer.SetFileName(args.out_meshname) writer.Write() logging.info("Written output to {}.".format(args.out_meshname))
def Execute(self): if self.Surface == None: self.PrintError('Error: No input surface.') cleaner = vtk.vtkCleanPolyData() cleaner.SetInputData(self.Surface) cleaner.Update() triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInputConnection(cleaner.GetOutputPort()) triangleFilter.Update() self.Surface = triangleFilter.GetOutput() if self.ElementSizeMode == 'edgelength': self.TargetArea = 0.25 * 3.0**0.5 * self.TargetEdgeLength**2 elif self.ElementSizeMode == 'edgelengtharray': calculator = vtk.vtkArrayCalculator() calculator.SetInputData(self.Surface) calculator.AddScalarArrayName(self.TargetEdgeLengthArrayName, 0) calculator.SetFunction( "%f^2 * 0.25 * sqrt(3) * %s^2" % (self.TargetEdgeLengthFactor, self.TargetEdgeLengthArrayName)) calculator.SetResultArrayName(self.TargetAreaArrayName) calculator.Update() self.MaxArea = 0.25 * 3.0**0.5 * self.MaxEdgeLength**2 self.MinArea = 0.25 * 3.0**0.5 * self.MinEdgeLength**2 self.Surface = calculator.GetOutput() excludedIds = vtk.vtkIdList() if self.ExcludeEntityIds: for excludedId in self.ExcludeEntityIds: excludedIds.InsertNextId(excludedId) surfaceRemeshing = vtkvmtk.vtkvmtkPolyDataSurfaceRemeshing() surfaceRemeshing.SetInputData(self.Surface) if self.CellEntityIdsArrayName: surfaceRemeshing.SetCellEntityIdsArrayName( self.CellEntityIdsArrayName) if self.ElementSizeMode in ['area', 'edgelength']: surfaceRemeshing.SetElementSizeModeToTargetArea() elif self.ElementSizeMode in ['areaarray', 'edgelengtharray']: surfaceRemeshing.SetElementSizeModeToTargetAreaArray() surfaceRemeshing.SetTargetAreaArrayName(self.TargetAreaArrayName) else: self.PrintError('Error: unsupported ElementSizeMode.') surfaceRemeshing.SetTargetArea(self.TargetArea) surfaceRemeshing.SetTargetAreaFactor(self.TargetAreaFactor) surfaceRemeshing.SetTriangleSplitFactor(self.TriangleSplitFactor) surfaceRemeshing.SetMaxArea(self.MaxArea) surfaceRemeshing.SetMinArea(self.MinArea) surfaceRemeshing.SetNumberOfIterations(self.NumberOfIterations) surfaceRemeshing.SetNumberOfConnectivityOptimizationIterations( self.NumberOfConnectivityOptimizationIterations) surfaceRemeshing.SetRelaxation(self.Relaxation) surfaceRemeshing.SetMinAreaFactor(self.MinAreaFactor) surfaceRemeshing.SetAspectRatioThreshold(self.AspectRatioThreshold) surfaceRemeshing.SetInternalAngleTolerance(self.InternalAngleTolerance) surfaceRemeshing.SetNormalAngleTolerance(self.NormalAngleTolerance) surfaceRemeshing.SetCollapseAngleThreshold(self.CollapseAngleThreshold) surfaceRemeshing.SetPreserveBoundaryEdges(self.PreserveBoundaryEdges) surfaceRemeshing.SetExcludedEntityIds(excludedIds) surfaceRemeshing.Update() self.Surface = surfaceRemeshing.GetOutput()
def arrayCompare(self): if not self.ArrayName: self.PrintError('Error: No ArrayName.') attributeData = None referenceAttributeData = None calculator = vtk.vtkArrayCalculator() if self.Method in ['addpointarray', 'projection']: attributeData = self.Surface.GetPointData() referenceAttributeData = self.ReferenceSurface.GetPointData() calculator.SetAttributeModeToUsePointData() elif self.Method in ['addcellarray']: attributeData = self.Surface.GetCellData() referenceAttributeData = self.ReferenceSurface.GetCellData() calculator.SetAttributeModeToUseCellData() if not attributeData.GetArray(self.ArrayName): self.PrintError('Error: Invalid ArrayName.') if not referenceAttributeData.GetArray(self.ArrayName): self.PrintError('Error: Invalid ArrayName.') referenceArrayName = 'Ref' + self.ArrayName surfacePoints = self.Surface.GetNumberOfPoints() referencePoints = self.ReferenceSurface.GetNumberOfPoints() pointsDifference = surfacePoints - referencePoints if self.Method in ['addpointarray', 'addcellarray']: if abs(pointsDifference) > 0: self.ResultLog = 'Uneven NumberOfPoints' return False refArray = referenceAttributeData.GetArray(self.ArrayName) refArray.SetName(referenceArrayName) attributeData.AddArray(refArray) calculator.SetInput(self.Surface) elif self.Method in ['projection']: referenceAttributeData.GetArray( self.ArrayName).SetName(referenceArrayName) projection = vmtkscripts.vmtkSurfaceProjection() projection.Surface = self.Surface projection.ReferenceSurface = self.ReferenceSurface projection.Execute() calculator.SetInput(projection.Surface) calculator.AddScalarVariable('a', self.ArrayName, 0) calculator.AddScalarVariable('b', referenceArrayName, 0) calculator.SetFunction("a - b") calculator.SetResultArrayName('ResultArray') calculator.Update() self.ResultData = calculator.GetOutput() if self.Method in ['addpointarray', 'projection']: resultRange = self.ResultData.GetPointData().GetArray( 'ResultArray').GetRange() elif self.Method in ['addcellarray']: resultRange = self.ResultData.GetCellData().GetArray( 'ResultArray').GetRange() self.PrintLog('Result Range: ' + str(resultRange)) if max([abs(r) for r in resultRange]) < self.Tolerance: return True return False
def Execute(args): print("get average along line probes") cell_type = "point" if (cell_type == "cell"): vtk_process = vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS vtk_data_type = vtk.vtkDataObject.CELL else: vtk_process = vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS vtk_data_type = vtk.vtkDataObject.POINT reader = vmtkscripts.vmtkMeshReader() reader.InputFileName = args.mesh_file reader.Execute() mesh = reader.Mesh pass_filt = vtk.vtkPassArrays() pass_filt.SetInputData(mesh) pass_filt.AddArray(vtk_data_type, "velocity") pass_filt.Update() surf = vmtkscripts.vmtkMeshToSurface() surf.Mesh = pass_filt.GetOutput() surf.Execute() normals = vmtkscripts.vmtkSurfaceNormals() normals.Surface = surf.Surface #accept defaults normals.Execute() calc1 = vtk.vtkArrayCalculator() calc1.SetFunction( "velocity_X*-Normals_X+velocity_Y*-Normals_Y+velocity_Z*-Normals_Z") calc1.AddScalarVariable("velocity_X", "velocity_X", 0) calc1.AddScalarVariable("velocity_Y", "velocity_Y", 0) calc1.AddScalarVariable("velocity_Z", "velocity_Z", 0) calc1.SetResultArrayName("vdotn") calc1.SetInputData(normals.Surface) if (cell_type == "cell"): calc1.SetAttributeModeToUseCellData() else: calc1.SetAttributeModeToUsePointData() calc1.SetResultArrayType(vtk.VTK_DOUBLE) integrate_attrs = vtk.vtkIntegrateAttributes() integrate_attrs.SetInputConnection(calc1.GetOutputPort()) integrate_attrs.UpdateData() area = integrate_attrs.GetCellData().GetArray(0).GetValue(0) D = 2.0 * np.sqrt(area / np.pi) calc2 = vtk.vtkArrayCalculator() calc2.SetFunction("vdotn*10**6*60") calc2.AddScalarVariable("vdotn", "vdotn", 0) calc2.SetResultArrayName("Q") calc2.SetInputConnection(integrate_attrs.GetOutputPort()) if (cell_type == "cell"): calc2.SetAttributeModeToUseCellData() else: calc2.SetAttributeModeToUsePointData() calc2.SetResultArrayType(vtk.VTK_DOUBLE) calc2.UpdateData() calc3 = vtk.vtkArrayCalculator() calc3.SetFunction("vdotn/{0}*1050.0/0.0035*{1}".format(area, D)) calc3.AddScalarVariable("vdotn", "vdotn", 0) calc3.SetResultArrayName("Re") calc3.SetInputConnection(integrate_attrs.GetOutputPort()) if (cell_type == "cell"): calc3.SetAttributeModeToUseCellData() else: calc3.SetAttributeModeToUsePointData() calc3.SetResultArrayType(vtk.VTK_DOUBLE) calc3.UpdateData() over_time = vtk.vtkExtractDataArraysOverTime() over_time.SetInputConnection(calc3.GetOutputPort()) if (cell_type == "cell"): over_time.SetFieldAssociation(vtk_data_type) else: over_time.SetFieldAssociation(vtk_data_type) over_time.UpdateData() writer = vtk.vtkDelimitedTextWriter() writer.SetInputConnection(over_time.GetOutputPort()) writer.SetFileName(args.file_out) writer.Write()
reader.SetFileName( "/raid/home/ksansom/caseFiles/mri/PAD_proj/case1/fluent3/vtk_out/wall_outfile_node.vtu" ) reader.Update() N = reader.GetNumberOfTimeSteps() print(N) #N = test.GetNumberOfBlocks()ls #block = test.GetBlock(0) #for i in range(N): # print(i, test.GetMetaData(i).Get(vtk.vtkCompositeDataSet.NAME())) #grid = reader.GetOutput() #wallshear = grid.GetCellData().GetArray("x_wall_shear") #print(wallshear) calc1 = vtk.vtkArrayCalculator() calc1.SetFunction("sqrt(x_wall_shear^2+y_wall_shear^2+y_wall_shear^2)") calc1.AddScalarVariable("x_wall_shear", "x_wall_shear", 0) calc1.AddScalarVariable("y_wall_shear", "y_wall_shear", 0) calc1.AddScalarVariable("z_wall_shear", "z_wall_shear", 0) calc1.SetResultArrayName("WSS") calc1.SetInputConnection(reader.GetOutputPort()) calc1.SetAttributeModeToUsePointData() #calc1.SetAttributeModeToUseCellData() calc1.SetResultArrayType(vtk.VTK_FLOAT) x_WSS_grad = vtk.vtkGradientFilter() x_WSS_grad.SetInputConnection(calc1.GetOutputPort()) x_WSS_grad.ComputeGradientOn() x_WSS_grad.FasterApproximationOff() x_WSS_grad.SetResultArrayName("x_WSS_grad")
def LoadData(self): # Remove all old actors from renderer self.renderer.RemoveAllViewProps() # Put back nav menu menu_actor_list = self.menu.GetActorList() for m_actor in menu_actor_list: self.renderer.AddActor(m_actor) tree = self.ds.GetTree() # Parallel pipeline with no shrinkage to get TCoords self.TreeLevels = vtk.vtkTreeLevelsFilter() self.TreeLevels.SetInput(tree) VertexDegree = vtk.vtkVertexDegree() VertexDegree.SetInputConnection(self.TreeLevels.GetOutputPort(0)) TreeAggregation = vtk.vtkTreeFieldAggregator() TreeAggregation.LeafVertexUnitSizeOff() TreeAggregation.SetField('size') TreeAggregation.SetInputConnection(VertexDegree.GetOutputPort(0)) # Layout without shrinkage for generating texture coordinates strategy = vtk.vtkStackedTreeLayoutStrategy() strategy.UseRectangularCoordinatesOn() strategy.SetRootStartAngle(0.0) strategy.SetRootEndAngle(15.0) strategy.SetRingThickness(self.THICK) # layer thickness strategy.ReverseOn() strategy.SetShrinkPercentage(0.0) layout = vtk.vtkAreaLayout() layout.SetLayoutStrategy(strategy) layout.SetInputConnection(TreeAggregation.GetOutputPort(0)) layout.SetAreaArrayName("area") layout.SetSizeArrayName("num_in_vertex") areapoly = vtk.vtkTreeMapToPolyData() areapoly.SetInputConnection(layout.GetOutputPort(0)) areapoly.SetAddNormals(0) areapoly.SetInputArrayToProcess( 0, 0, 0, 4, "area") # 4 = vtkDataObject::FIELD_ASSOCIATION_VERTICES texPlane = vtk.vtkTextureMapToPlane() texPlane.SetInputConnection(areapoly.GetOutputPort(0)) texPlane.AutomaticPlaneGenerationOn() texPlane.Update() # Layout with shrinkage for generating geometry strategy0 = vtk.vtkStackedTreeLayoutStrategy() strategy0.UseRectangularCoordinatesOn() strategy0.SetRootStartAngle(0.0) strategy0.SetRootEndAngle(15.0) strategy0.SetRingThickness(self.THICK) # layer thickness strategy0.ReverseOn() strategy0.SetShrinkPercentage(self.SHRINK) layout0 = vtk.vtkAreaLayout() layout0.SetLayoutStrategy(strategy0) layout0.SetInputConnection(TreeAggregation.GetOutputPort(0)) layout0.SetAreaArrayName("area") layout0.SetSizeArrayName("num_in_vertex") areapoly0 = vtk.vtkTreeMapToPolyData() areapoly0.SetAddNormals(0) areapoly0.SetInputConnection(layout0.GetOutputPort(0)) areapoly0.SetInputArrayToProcess( 0, 0, 0, 4, "area") # 4 = vtkDataObject::FIELD_ASSOCIATION_VERTICES areapoly0.Update() # Copy over texture coordinates def transferTCoords(): input = paf.GetInputDataObject(0,0) refin = paf.GetInputList().GetItem(0) output = paf.GetPolyDataOutput() TCorig = refin.GetPointData().GetTCoords() TC = vtk.vtkFloatArray() TC.SetNumberOfComponents(TCorig.GetNumberOfComponents()) TC.SetNumberOfTuples(TCorig.GetNumberOfTuples()) TC.SetName('Texture Coordinates') for ii in range(TCorig.GetNumberOfTuples()): ff = TCorig.GetTuple2(ii) TC.SetTuple2(ii,ff[0],ff[1]) output.GetPointData().AddArray(TC) output.GetPointData().SetActiveTCoords('Texture Coordinates') paf = vtk.vtkProgrammableAttributeDataFilter() paf.SetInput(areapoly0.GetOutput()) paf.AddInput(texPlane.GetOutput()) paf.SetExecuteMethod(transferTCoords) # Need to find proper ordering of wavelet coeffs based on icicle layout # tree.GetVertexData().GetArray('area') is 4-component (Xmin,Xmax,Ymin,Ymax) print 'Reordering wavelet coeffs' out_polys = areapoly.GetOutputDataObject(0) isleaf = VN.vtk_to_numpy(out_polys.GetCellData().GetArray('leaf')) poly_bounds = VN.vtk_to_numpy(out_polys.GetCellData().GetArray('area')) vertex_ids = VN.vtk_to_numpy(out_polys.GetCellData().GetArray('vertex_ids')) self.LeafIds = vertex_ids[isleaf>0] self.LeafXmins = poly_bounds[isleaf>0,0] self.XOrderedLeafIds = self.LeafIds[self.LeafXmins.argsort()] # Grab texture images and color map self.GrabTextureImagesAndLUT() # For each node and corresponding image data in self.WCimageDataList, need to create a texture, # then pull out the correct rectangle from areapoly0 (using vtkExtractSelectedPolyDataIds # and create a mapper and actor and apply the texture. self.texture_list = [] self.tex_mapper_list = [] self.tex_actor_list = [] for ii in range(len(self.WCimageDataList)): # Set up texture with lookup table for matrix polys tex = vtk.vtkTexture() tex.SetInput(self.WCimageDataList[ii]) tex.SetLookupTable(self.lut) self.texture_list.append(tex) # Grab correct poly out of areapoly0 sel = vtk.vtkSelection() node = vtk.vtkSelectionNode() node.SetContentType(4) # 4 = indices node.SetFieldType(0) # 0 = cell id_array = N.array([ii],dtype='int64') id_list = VN.numpy_to_vtkIdTypeArray(id_array) node.SetSelectionList(id_list) sel.AddNode(node) ext_id_poly = vtk.vtkExtractSelectedPolyDataIds() ext_id_poly.SetInput(1, sel) ext_id_poly.SetInputConnection(0, areapoly0.GetOutputPort(0)) # ext_id_poly.Update() # print ext_id_poly.GetOutput() poly_tm = vtk.vtkTextureMapToPlane() poly_tm.SetInputConnection(ext_id_poly.GetOutputPort(0)) poly_tm.AutomaticPlaneGenerationOn() poly_tm.Update() # Separate mapper and actor for textured polys map2 = vtk.vtkPolyDataMapper() map2.SetInputConnection(poly_tm.GetOutputPort(0)) map2.ScalarVisibilityOff() self.tex_mapper_list.append(map2) act2 = vtk.vtkActor() act2.SetMapper(self.tex_mapper_list[ii]) act2.SetTexture(self.texture_list[ii]) act2.GetProperty().SetColor(1,1,1) act2.SetPickable(0) act2.SetPosition(0,0,0.1) # ??? self.tex_actor_list.append(act2) # Add textured polys to the view self.renderer.AddActor(self.tex_actor_list[ii]) # Layout with shrinkage for generating outline geometry for showing selections self.applycolors1 = vtk.vtkApplyColors() self.applycolors1.SetInputConnection(0,layout0.GetOutputPort(0)) self.applycolors1.AddInputConnection(1,self.output_link.GetOutputPort(0)) self.applycolors1.SetDefaultPointColor(self.theme.GetPointColor()) self.applycolors1.SetDefaultPointOpacity(self.theme.GetPointOpacity()) self.applycolors1.SetSelectedPointColor(self.theme.GetSelectedPointColor()) self.applycolors1.SetSelectedPointOpacity(self.theme.GetSelectedPointOpacity()) self.areapoly1 = vtk.vtkTreeMapToPolyData() self.areapoly1.SetInputConnection(self.applycolors1.GetOutputPort(0)) self.areapoly1.SetAddNormals(0) self.areapoly1.SetInputArrayToProcess( 0, 0, 0, 4, "area") # 4 = vtkDataObject::FIELD_ASSOCIATION_VERTICES # Separate mapper and actor for icicle polys outlines (pickable) map = vtk.vtkPolyDataMapper() map.SetInputConnection(self.areapoly1.GetOutputPort(0)) map.SetScalarModeToUseCellFieldData() map.SelectColorArray("vtkApplyColors color") map.SetScalarVisibility(True) act = vtk.vtkActor() act.SetMapper(map) act.GetProperty().SetColor(1,1,1) act.SetPickable(True) act.SetPosition(0,0,0) act.GetProperty().SetRepresentationToWireframe() act.GetProperty().SetLineWidth(4.0) self.icicle_actor = act # Add actor for selection highlight outlines self.renderer.AddActor(act) # Now need to set up data for generating "selection lines" which come from # xy or pcoords chart. Basic method is to create a new scalar array out of x-coord # of the texture coordinates, then do a Delaunay2D on the shrunken polys and contour # that at values obtained by finding what normalized distance along data set are # selected pedigree ids. self.calc = vtk.vtkArrayCalculator() self.calc.SetInputConnection(paf.GetOutputPort()) self.calc.SetAttributeModeToUsePointData() self.calc.AddScalarVariable("tcoords_X", "Texture Coordinates", 0) self.calc.SetFunction("tcoords_X") self.calc.SetResultArrayName("tcx") # self.calc.Update() # print VN.vtk_to_numpy(self.calc.GetOutput().GetPointData().GetArray('tcx')) self.group_contour = vtk.vtkContourFilter() self.group_contour.SetInputConnection(self.calc.GetOutputPort(0)) self.group_contour.SetInputArrayToProcess(0,0,0,0,'tcx') self.highlight_contour = vtk.vtkContourFilter() self.highlight_contour.SetInputConnection(self.calc.GetOutputPort(0)) self.highlight_contour.SetInputArrayToProcess(0,0,0,0,'tcx') # Separate mapper and actor group selection (pcoords or xy) lines map3 = vtk.vtkPolyDataMapper() map3.SetInputConnection(self.group_contour.GetOutputPort(0)) map3.SetScalarVisibility(0) act3 = vtk.vtkActor() act3.SetMapper(map3) act3.SetPickable(False) act3.SetPosition(0,0,0.2) act3.GetProperty().SetRepresentationToWireframe() act3.GetProperty().SetLineWidth(2.0) act3.GetProperty().SetColor(1,0,0) act3.GetProperty().SetOpacity(0.6) self.group_actor = act3 # Add actor for selection highlight outlines self.renderer.AddActor(act3) # Separate mapper and actor for individual (image_flow) selection highlight map4 = vtk.vtkPolyDataMapper() map4.SetInputConnection(self.highlight_contour.GetOutputPort(0)) map4.SetScalarVisibility(0) act4 = vtk.vtkActor() act4.SetMapper(map4) act4.SetPickable(False) act4.SetPosition(0,0,0.25) act4.GetProperty().SetRepresentationToWireframe() act4.GetProperty().SetLineWidth(3.0) act4.GetProperty().SetColor(0,0.5,1) act4.GetProperty().SetOpacity(0.6) self.highlight_actor = act4 # Add actor for selection highlight outlines self.renderer.AddActor(act4) # Get Ordered fractional positions for pedigree ids (for setting contour values) self.ped_id_fracs = self.ds.GetIdsFractionalPosition(self.XOrderedLeafIds) # Clear out selections on data change self.output_link.GetCurrentSelection().RemoveAllNodes() self.output_link.InvokeEvent("AnnotationChangedEvent") self.renderer.ResetCamera(self.icicle_actor.GetBounds())
def warp_surface(args): print("warp the surface ") reader = vmtkscripts.vmtkSurfaceReader() reader.InputFileName = args.surface reader.Execute() Surface = reader.Surface narrays = Surface.GetPointData().GetNumberOfArrays() has_normals = False for i in range(narrays): if ( Surface.GetPointData().GetArrayName(i) == "Normals"): has_normals = True break if(has_normals): normals = Surface print("already have") else: get_normals = vtk.vtkPolyDataNormals() get_normals.SetInputData(Surface) get_normals.SetFeatureAngle(30.0) # default get_normals.SetSplitting(True) get_normals.Update() get_normals.GetOutput().GetPointData().SetActiveVectors("Normals") normals = get_normals.GetOutput() print("normals generated") random = vtk.vtkRandomAttributeGenerator() random.SetInputData(normals) random.SetDataTypeToDouble() random.GeneratePointScalarsOn () random.SetComponentRange(-0.5, 0.5) random.Update() #n = random.GetOutput().GetPointData().GetNumberOfArrays() #for i in range(n): #print(random.GetOutput().GetPointData().GetArrayName(i)) calc = vtk.vtkArrayCalculator() calc.SetInputConnection(random.GetOutputPort()) calc.AddScalarArrayName("RandomPointScalars", 0) calc.AddVectorArrayName("Normals", 0, 1, 2) calc.SetFunction("Normals * RandomPointScalars") calc.SetResultArrayName("RandomLengthNormalVectors") calc.Update() warp = vtk.vtkWarpVector() warp.SetInputConnection(calc.GetOutputPort()) warp.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, "RandomLengthNormalVectors"); warp.SetScaleFactor(args.fuzz_scale) warp.Update() writer = vmtkscripts.vmtkSurfaceWriter() writer.OutputFileName = args.file_out writer.Input = warp.GetOutput() writer.Execute()
def compute_vonMisesStress_for_MV(inputfilename, outputfilename): # ====================================================================== # get system arguments ------------------------------------------------- # Path to input file and name of the output file #inputfilename = sys.argv[1] #outputfilename = sys.argv[2] print " " print "==================================================================================================" print "=== Execute Python script to analyze MV geometry in order for the HiFlow3-based MVR-Simulation ===" print "==================================================================================================" print " " # ====================================================================== # Read file if inputfilename[-4] == 'p': reader = vtk.vtkXMLPUnstructuredGridReader() reader.SetFileName(inputfilename) reader.Update() else: reader = vtk.vtkXMLUnstructuredGridReader() reader.SetFileName(inputfilename) reader.Update() print "Reading input files: DONE." # ====================================================================== # Compute displacement vector calc = vtk.vtkArrayCalculator() calc.SetInput(reader.GetOutput()) calc.SetAttributeModeToUsePointData() calc.AddScalarVariable('x', 'u0', 0) calc.AddScalarVariable('y', 'u1', 0) calc.AddScalarVariable('z', 'u2', 0) calc.SetFunction('x*iHat+y*jHat+z*kHat') calc.SetResultArrayName('DisplacementSolutionVector') calc.Update() # ====================================================================== # Compute strain tensor derivative = vtk.vtkCellDerivatives() derivative.SetInput(calc.GetOutput()) derivative.SetTensorModeToComputeStrain() derivative.Update() # ====================================================================== # Compute von Mises stress calc = vtk.vtkArrayCalculator() calc.SetInput(derivative.GetOutput()) calc.SetAttributeModeToUseCellData() calc.AddScalarVariable('Strain_0', 'Strain', 0) calc.AddScalarVariable('Strain_1', 'Strain', 1) calc.AddScalarVariable('Strain_2', 'Strain', 2) calc.AddScalarVariable('Strain_3', 'Strain', 3) calc.AddScalarVariable('Strain_4', 'Strain', 4) calc.AddScalarVariable('Strain_5', 'Strain', 5) calc.AddScalarVariable('Strain_6', 'Strain', 6) calc.AddScalarVariable('Strain_7', 'Strain', 7) calc.AddScalarVariable('Strain_8', 'Strain', 8) calc.SetFunction('sqrt( (2*700*Strain_0 + 28466*(Strain_0+Strain_4+Strain_8))^2 + (2*700*Strain_4 + 28466*(Strain_0+Strain_4+Strain_8))^2 + (2*700*Strain_8 + 28466*(Strain_0+Strain_4+Strain_8))^2 - ( (2*700*Strain_0 + 28466*(Strain_0+Strain_4+Strain_8))*(2*700*Strain_4 + 28466*(Strain_0+Strain_4+Strain_8)) ) - ( (2*700*Strain_0 + 28466*(Strain_0+Strain_4+Strain_8))*(2*700*Strain_8 + 28466*(Strain_0+Strain_4+Strain_8)) ) - ( (2*700*Strain_4 + 28466*(Strain_0+Strain_4+Strain_8))*(2*700*Strain_8 + 28466*(Strain_0+Strain_4+Strain_8)) ) + 3 * ((2*700*Strain_3)^2 + (2*700*Strain_6)^2 + (2*700*Strain_7)^2) )') calc.SetResultArrayName('vonMisesStress_forMV_mu700_lambda28466') calc.Update() print "Computation of displacement vectors, Cauchy strain and vom Mises stress: DONE." # ====================================================================== # Define dummy variable; get output of calc filter dummy = calc.GetOutput() # Get point data arrays u0, u1 and u2 pointData_u0 = dummy.GetPointData().GetArray('u0') pointData_u1 = dummy.GetPointData().GetArray('u1') pointData_u2 = dummy.GetPointData().GetArray('u2') # Set scalars dummy.GetPointData().SetScalars(pointData_u0) # ====================================================================== # Warp by scalar u0 warpScalar = vtk.vtkWarpScalar() warpScalar.SetInput(dummy) warpScalar.SetNormal(1.0,0.0,0.0) warpScalar.SetScaleFactor(1.0) warpScalar.SetUseNormal(1) warpScalar.Update() # Get output and set scalars dummy = warpScalar.GetOutput() dummy.GetPointData().SetScalars(pointData_u1) # ====================================================================== # Warp by scalar u1 warpScalar = vtk.vtkWarpScalar() warpScalar.SetInput(dummy) warpScalar.SetNormal(0.0,1.0,0.0) warpScalar.SetScaleFactor(1.0) warpScalar.SetUseNormal(1) warpScalar.Update() # Get output and set scalars dummy = warpScalar.GetOutput() dummy.GetPointData().SetScalars(pointData_u2) # ====================================================================== # Warp by scalar u2 warpScalar = vtk.vtkWarpScalar() warpScalar.SetInput(dummy) warpScalar.SetNormal(0.0,0.0,1.0) warpScalar.SetScaleFactor(1.0) warpScalar.SetUseNormal(1) warpScalar.Update() # Get ouput and add point data arrays that got deleted earlier dummy = warpScalar.GetOutput() dummy.GetPointData().AddArray(pointData_u0) dummy.GetPointData().AddArray(pointData_u1) # ====================================================================== # Write output to vtu writer = vtk.vtkXMLUnstructuredGridWriter() writer.SetDataModeToAscii() writer.SetFileName(outputfilename) writer.SetInput(dummy) writer.Write() # ====================================================================== print "Writing Extended VTU incl. von Mises Stress information: DONE." print "==============================================================" print " "
def post_proc_cfd_diff(parameter_list): dir_path = parameter_list[0] vtu_input = parameter_list[1] cell_type = parameter_list[1] vtu_output_1 = parameter_list[3] vtu_output_2 = parameter_list[4] N_peak = parameter_list[5] reader = vtk.vtkXMLUnstructuredGridReader() reader.SetFileName(os.path.join(dir_path, vtu_input)) reader.Update() N = reader.GetNumberOfTimeSteps() print(N) if (cell_type == "cell"): vtk_process = vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS vtk_data_type = vtk.vtkDataObject.CELL else: vtk_process = vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS vtk_data_type = vtk.vtkDataObject.POINT pass_arr = vtk.vtkPassArrays() pass_arr.SetInputConnection(reader.GetOutputPort()) pass_arr.AddArray(vtk_data_type, "absolute_pressure") pass_arr.AddArray(vtk_data_type, "x_wall_shear") pass_arr.AddArray(vtk_data_type, "y_wall_shear") pass_arr.AddArray(vtk_data_type, "z_wall_shear") calc1 = vtk.vtkArrayCalculator() calc1.SetFunction("sqrt(x_wall_shear^2+y_wall_shear^2+z_wall_shear^2)") calc1.AddScalarVariable("x_wall_shear", "x_wall_shear", 0) calc1.AddScalarVariable("y_wall_shear", "y_wall_shear", 0) calc1.AddScalarVariable("z_wall_shear", "z_wall_shear", 0) calc1.SetResultArrayName("WSS") calc1.SetInputConnection(pass_arr.GetOutputPort()) if (cell_type == "cell"): calc1.SetAttributeModeToUseCellData() else: calc1.SetAttributeModeToUsePointData() calc1.SetResultArrayType(vtk.VTK_DOUBLE) x_WSS_grad = vtk.vtkGradientFilter() x_WSS_grad.SetInputConnection(calc1.GetOutputPort()) x_WSS_grad.ComputeGradientOn() x_WSS_grad.FasterApproximationOff() x_WSS_grad.ComputeDivergenceOff() x_WSS_grad.ComputeVorticityOff() x_WSS_grad.ComputeQCriterionOff() x_WSS_grad.SetResultArrayName("x_WSS_grad") x_WSS_grad.SetInputArrayToProcess(0, 0, 0, vtk_process, "x_wall_shear") y_WSS_grad = vtk.vtkGradientFilter() y_WSS_grad.SetInputConnection(x_WSS_grad.GetOutputPort()) y_WSS_grad.ComputeGradientOn() y_WSS_grad.FasterApproximationOff() y_WSS_grad.ComputeDivergenceOff() y_WSS_grad.ComputeVorticityOff() y_WSS_grad.ComputeQCriterionOff() y_WSS_grad.SetResultArrayName("y_WSS_grad") y_WSS_grad.SetInputArrayToProcess(0, 0, 0, vtk_process, "y_wall_shear") z_WSS_grad = vtk.vtkGradientFilter() z_WSS_grad.SetInputConnection(y_WSS_grad.GetOutputPort()) z_WSS_grad.ComputeGradientOn() z_WSS_grad.FasterApproximationOff() z_WSS_grad.ComputeDivergenceOff() z_WSS_grad.ComputeVorticityOff() z_WSS_grad.ComputeQCriterionOff() z_WSS_grad.SetResultArrayName("z_WSS_grad") z_WSS_grad.SetInputArrayToProcess(0, 0, 0, vtk_process, "z_wall_shear") calc2 = vtk.vtkArrayCalculator() calc2.AddScalarVariable("x_component", "x_WSS_grad", 0) calc2.AddScalarVariable("y_component", "y_WSS_grad", 1) calc2.AddScalarVariable("z_component", "z_WSS_grad", 2) calc2.SetFunction("sqrt(x_component^2+y_component^2+z_component^2)") calc2.SetResultArrayName("WSSG") calc2.SetInputConnection(z_WSS_grad.GetOutputPort()) if (cell_type == "cell"): calc2.SetAttributeModeToUseCellData() else: calc2.SetAttributeModeToUsePointData() calc2.SetResultArrayType(vtk.VTK_DOUBLE) # initialize the output to include the peak values grid = vtk.vtkUnstructuredGrid() #N_peak = 3 reader.SetTimeStep(N_peak) calc2.Update() print("loading peak: {0} timestep to copy data".format( reader.GetTimeStep())) grid.DeepCopy(calc2.GetOutput()) reader.SetTimeStep(0) #reader.Update() calc2.Update() print("loading {0}th timestep for averaging initialization".format( reader.GetTimeStep())) stats = vtk.vtkTemporalStatistics() stats.SetInputConnection(calc2.GetOutputPort()) stats.ComputeMaximumOff() stats.ComputeMinimumOff() stats.ComputeStandardDeviationOff() stats.ComputeAverageOn() stats.Update() print("what's the time step after stats :{0}".format(reader.GetTimeStep())) grid_out = vtk.vtkUnstructuredGrid() grid_out.DeepCopy(stats.GetOutput()) if (cell_type == "cell"): out_data = grid_out.GetCellData() grid_data = grid.GetCellData() else: out_data = grid_out.GetPointData() grid_data = grid.GetPointData() print("update names") out_data.AddArray(grid_data.GetArray("WSS")) out_data.GetArray("WSS").SetName("WSS_peak") out_data.AddArray(grid_data.GetArray("WSSG")) out_data.GetArray("WSSG").SetName("WSSG_peak") out_data.AddArray(grid_data.GetArray("absolute_pressure")) out_data.GetArray("absolute_pressure").SetName("pressure_peak") out_data.GetArray("WSS_average").SetName("TAWSS") out_data.GetArray("WSSG_average").SetName("TAWSSG") out_data.GetArray("absolute_pressure_average").SetName("pressure_average") print("TAWSSVector") calc3 = vtk.vtkArrayCalculator() calc3.AddScalarVariable("x_wall_shear_average", "x_wall_shear_average", 0) calc3.AddScalarVariable("y_wall_shear_average", "y_wall_shear_average", 0) calc3.AddScalarVariable("z_wall_shear_average", "z_wall_shear_average", 0) calc3.SetFunction( "sqrt(x_wall_shear_average^2+y_wall_shear_average^2+z_wall_shear_average^2)" ) calc3.SetResultArrayName("TAWSSVector") calc3.SetInputData(grid_out) if (cell_type == "cell"): calc3.SetAttributeModeToUseCellData() else: calc3.SetAttributeModeToUsePointData() calc3.SetResultArrayType(vtk.VTK_DOUBLE) calc3.Update() print("OSI") calc4 = vtk.vtkArrayCalculator() calc4.AddScalarVariable("TAWSSVector", "TAWSSVector", 0) calc4.AddScalarVariable("TAWSS", "TAWSS", 0) calc4.SetFunction("0.5*(1.0-(TAWSSVector/(TAWSS)))") calc4.SetResultArrayName("OSI") calc4.SetInputConnection(calc3.GetOutputPort()) if (cell_type == "cell"): calc4.SetAttributeModeToUseCellData() else: calc4.SetAttributeModeToUsePointData() calc4.SetResultArrayType(vtk.VTK_DOUBLE) #calc4.Update() # peak ratios calc5 = vtk.vtkArrayCalculator() calc5.AddScalarVariable("WSS_peak", "WSS_peak", 0) calc5.AddScalarVariable("TAWSS", "TAWSS", 0) calc5.SetFunction("WSS_peak/TAWSS") calc5.SetResultArrayName("WSS_peak_q_TAWSS") calc5.SetInputConnection(calc4.GetOutputPort()) if (cell_type == "cell"): calc5.SetAttributeModeToUseCellData() else: calc5.SetAttributeModeToUsePointData() calc5.SetResultArrayType(vtk.VTK_DOUBLE) #calc5.Update() calc6 = vtk.vtkArrayCalculator() calc6.AddScalarVariable("WSSG_peak", "WSSG_peak", 0) calc6.AddScalarVariable("TAWSSG", "TAWSSG", 0) calc6.SetFunction("WSSG_peak/TAWSSG") calc6.SetResultArrayName("WSSG_peak_q_TAWSSG") calc6.SetInputConnection(calc5.GetOutputPort()) if (cell_type == "cell"): calc6.SetAttributeModeToUseCellData() else: calc6.SetAttributeModeToUsePointData() calc6.SetResultArrayType(vtk.VTK_DOUBLE) calc7 = vtk.vtkArrayCalculator() calc7.AddScalarVariable("pressure_peak", "pressure_peak", 0) calc7.AddScalarVariable("pressure_average", "pressure_average", 0) calc7.SetFunction("pressure_peak/pressure_average") calc7.SetResultArrayName("pressure_peak_q_pressure_average") calc7.SetInputConnection(calc6.GetOutputPort()) if (cell_type == "cell"): calc7.SetAttributeModeToUseCellData() else: calc7.SetAttributeModeToUsePointData() calc7.SetResultArrayType(vtk.VTK_DOUBLE) pass_filt = vtk.vtkPassArrays() pass_filt.SetInputConnection(calc7.GetOutputPort()) pass_filt.AddArray(vtk_data_type, "WSS_peak") pass_filt.AddArray(vtk_data_type, "WSSG_peak") pass_filt.AddArray(vtk_data_type, "pressure_peak") pass_filt.AddArray(vtk_data_type, "pressure_average") pass_filt.AddArray(vtk_data_type, "TAWSS") pass_filt.AddArray(vtk_data_type, "TAWSSG") pass_filt.AddArray(vtk_data_type, "OSI") pass_filt.AddArray(vtk_data_type, "WSS_peak_q_TAWSS") pass_filt.AddArray(vtk_data_type, "WSSG_peak_q_TAWSSG") pass_filt.AddArray(vtk_data_type, "pressure_peak_q_pressure_average") pass_filt.Update() #if(cell_type == "cell"): # print(pass_filt.GetOutput().GetCellData().GetArray("OSI").GetValue(0)) #else: # print(pass_filt.GetOutput().GetPointData().GetArray("OSI").GetValue(0)) writer2 = vtk.vtkXMLUnstructuredGridWriter() writer2.SetFileName(os.path.join(dir_path, vtu_output_2)) writer2.SetInputConnection(pass_filt.GetOutputPort()) writer2.Update()
# FieldData, PointData and CellData. rf = vtk.vtkRearrangeFields() rf.SetInputConnection(do2ds.GetOutputPort()) # Add an operation to "move TIME_LATE from DataObject's FieldData to # PointData" rf.AddOperation("MOVE", scalar, "DATA_OBJECT", "POINT_DATA") # Force the filter to execute. This is need to force the pipeline # to execute so that we can find the range of the array TIME_LATE rf.Update() # Set max to the second (GetRange returns [min,max]) of the "range of the # array called scalar in the PointData of the output of rf" max = rf.GetOutput().GetPointData().GetArray(scalar).GetRange()[1] # Use an ArrayCalculator to normalize TIME_LATE calc = vtk.vtkArrayCalculator() calc.SetInputConnection(rf.GetOutputPort()) # Working on point data calc.SetAttributeTypeToPointData() # Map scalar to s. When setting function, we can use s to # represent the array scalar (TIME_LATE) calc.AddScalarVariable("s", scalar, 0) # Divide scalar by max (applies division to all components of the array) calc.SetFunction("s / %f"%max) # The output array will be called resArray calc.SetResultArrayName("resArray") # Use AssignAttribute to make resArray the active scalar field aa = vtk.vtkAssignAttribute() aa.SetInputConnection(calc.GetOutputPort()) aa.Assign("resArray", "SCALARS", "POINT_DATA")
def translesional_result(centerline_file, wall_file,vtk_file_list, output_dir,minPoint=(0,0,0), prox_dist=5, dist_dist=5): # read centerline centerlineReader = vtk.vtkXMLPolyDataReader() centerlineReader.SetFileName(centerline_file) centerlineReader.Update() centerline = centerlineReader.GetOutput() # read vessel wall wallReader = vtk.vtkSTLReader() wallReader.SetFileName(wall_file) wallReader.Update() # read vtk files vtk_files = [] centerlines = [] if not os.path.exists(output_dir): os.makedirs(output_dir) if not os.path.exists(os.path.join(output_dir,"centerlines")): os.makedirs(os.path.join(output_dir,"centerlines")) # average filter averageFilter = vtk.vtkTemporalStatistics() for file_name in vtk_file_list: reader = vtk.vtkUnstructuredGridReader() reader.SetFileName(file_name) reader.Update() geomFilter = vtk.vtkGeometryFilter() geomFilter.SetInputData(reader.GetOutput()) geomFilter.Update() # scale up the CFD result transform = vtk.vtkTransform() transform.Scale(1000,1000,1000) transformFilter = vtk.vtkTransformPolyDataFilter() transformFilter.SetInputData(geomFilter.GetOutput()) transformFilter.SetTransform(transform) transformFilter.Update() vtk_files.append(transformFilter.GetOutput()) interpolator = vtk.vtkPointInterpolator() interpolator.SetSourceData(transformFilter.GetOutput()) interpolator.SetInputData(centerline) interpolator.Update() # convert to desired unit # get the first element pressure try: first_point_pressure = interpolator.GetOutput().GetPointData().GetArray("p").GetValue(0) except: first_point_pressure = 120 converter = vtk.vtkArrayCalculator() converter.SetInputData(interpolator.GetOutput()) converter.AddScalarArrayName("p") converter.SetFunction("120 + (p - {}) * 921 * 0.0075".format(first_point_pressure)) # 921 = mu/nu = density of blood, 0.0075 converts from Pascal to mmHg, offset 120mmHg at ica converter.SetResultArrayName("p(mmHg)") converter.Update() converter2 = vtk.vtkArrayCalculator() converter2.SetInputData(converter.GetOutput()) converter2.AddVectorArrayName("wallShearStress") converter2.SetFunction("wallShearStress * 921") # 921 = mu/nu = density of blood, 0.0075 converts from Pascal to mmHg, http://aboutcfd.blogspot.com/2017/05/wallshearstress-in-openfoam.html converter2.SetResultArrayName("wallShearStress(Pa)") converter2.Update() # output the probe centerline centerline_output_path = os.path.join( os.path.dirname(centerline_file), output_dir, "centerlines", "centerline_probe_{}.vtp".format(os.path.split(file_name)[1].split("_")[1].split(".")[0]) ) centerlines.append(converter2.GetOutput()) averageFilter.SetInputData(converter2.GetOutput()) averageFilter.Update() centerline = averageFilter.GetOutput() # extract lesion section # get the abscissas of min radius point # Create kd tree kDTree = vtk.vtkKdTreePointLocator() kDTree.SetDataSet(centerline) kDTree.BuildLocator() minIdx = kDTree.FindClosestPoint(minPoint) minPoint_absc = centerline.GetPointData().GetArray("Abscissas_average").GetTuple(minIdx)[0] thresholdFilter = vtk.vtkThreshold() thresholdFilter.ThresholdBetween(minPoint_absc-prox_dist,minPoint_absc+dist_dist) thresholdFilter.SetInputData(centerline) thresholdFilter.SetAllScalars(0) # important !!! thresholdFilter.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS,"Abscissas_average"); thresholdFilter.Update() # to vtkpolydata geometryFilter = vtk.vtkGeometryFilter() geometryFilter.SetInputData(thresholdFilter.GetOutput()) geometryFilter.Update() # get closest line connectFilter = vtk.vtkConnectivityFilter() connectFilter.SetExtractionModeToClosestPointRegion() connectFilter.SetClosestPoint(minPoint) connectFilter.SetInputData(geometryFilter.GetOutput()) connectFilter.Update() # compute result values abscissas = vtk_to_numpy(thresholdFilter.GetOutput().GetPointData().GetArray("Abscissas_average")) abscissas_unique, index = np.unique(sorted(abscissas), axis=0, return_index=True) pressure = vtk_to_numpy(thresholdFilter.GetOutput().GetPointData().GetArray("p(mmHg)_average")) pressure = [x for _, x in sorted(zip(abscissas,pressure))] pressure = [pressure[x] for x in index] pressure_gradient = np.diff(pressure)/np.diff(abscissas_unique) velocity = vtk_to_numpy(thresholdFilter.GetOutput().GetPointData().GetArray("U_average")) velocity = [math.sqrt(value[0]**2 + value[1]**2 +value[2]**2 ) for value in velocity] velocity = [x for _, x in sorted(zip(abscissas,velocity))] velocity = [velocity[x] for x in index] velocity_gradient = np.diff(velocity)/np.diff(abscissas_unique) vorticity = vtk_to_numpy(thresholdFilter.GetOutput().GetPointData().GetArray("vorticity_average")) vorticity = [math.sqrt(value[0]**2 + value[1]**2 +value[2]**2 ) for value in vorticity] vorticity = [x for _, x in sorted(zip(abscissas,vorticity))] vorticity = [vorticity[x] for x in index] vorticity_gradient = np.diff(vorticity)/np.diff(abscissas_unique) wss = vtk_to_numpy(thresholdFilter.GetOutput().GetPointData().GetArray("wallShearStress(Pa)_average")) wss = [math.sqrt(value[0]**2 + value[1]**2 +value[2]**2 ) for value in wss] wss = [wss[x] for x in index] wss = [x for _, x in sorted(zip(abscissas,wss))] wss_gradient = np.diff(wss)/np.diff(abscissas_unique) epsilon = 0.00001 p_ratio = np.mean(pressure[-4:-1])/(np.mean(pressure[0:3])+epsilon) u_ratio = np.mean(velocity[-4:-1])/(np.mean(velocity[0:3])+epsilon) w_ratio = np.mean(vorticity[-4:-1])/(np.mean(vorticity[0:3])+epsilon) wss_ratio = np.mean(wss[-4:-1])/(np.mean(wss[0:3])+epsilon) dp_ratio = np.mean(pressure_gradient[-4:-1])/(np.mean(pressure_gradient[0:3])+epsilon) du_ratio = np.mean(velocity_gradient[-4:-1])/(np.mean(velocity_gradient[0:3])+epsilon) dw_ratio = np.mean(vorticity_gradient[-4:-1])/(np.mean(vorticity_gradient[0:3])+epsilon) dwss_ratio = np.mean(wss_gradient[-4:-1])/(np.mean(wss_gradient[0:3])+epsilon) return_value = { 'translesion peak presssure(mmHg)': np.mean(heapq.nlargest(1, pressure)), 'translesion presssure ratio': p_ratio, 'translesion peak pressure gradient(mmHgmm^-1)': np.mean(heapq.nlargest(1, pressure_gradient)), 'translesion pressure gradient ratio': dp_ratio, 'translesion peak velocity(ms^-1)': np.mean(heapq.nlargest(1, velocity)), 'translesion velocity ratio': u_ratio, 'translesion velocity gradient ratio': du_ratio, 'translesion peak velocity gradient(ms^-1mm^-1)': np.mean(heapq.nlargest(1, velocity_gradient)), 'translesion peak vorticity(ms^-1)': np.mean(heapq.nlargest(1, vorticity)), 'translesion vorticity ratio': w_ratio, 'translesion vorticity gradient ratio': dw_ratio, 'translesion peak vorticity gradient(Pamm^-1)':np.mean(heapq.nlargest(1, vorticity_gradient)), 'translesion peak wss(Pa)': np.mean(heapq.nlargest(1, wss)), 'translesion peak wss gradient(Pamm^-1)': np.mean(heapq.nlargest(1, wss_gradient)), 'translesion wss ratio': wss_ratio, 'translesion wss gradient ratio': dwss_ratio, } return return_value
def Execute(self): if self.Mesh == None: self.PrintError('Error: No input mesh.') if not self.CellEntityIdsArrayName: self.PrintError('Error: No input CellEntityIdsArrayName.') return cellEntityIdsArray = self.Mesh.GetCellData().GetArray(self.CellEntityIdsArrayName) #cut off the volumetric elements wallThreshold = vtk.vtkThreshold() wallThreshold.SetInputData(self.Mesh) wallThreshold.ThresholdByUpper(self.SurfaceCellEntityId-0.5) wallThreshold.SetInputArrayToProcess(0,0,0,1,self.CellEntityIdsArrayName) wallThreshold.Update() meshToSurface = vmtkscripts.vmtkMeshToSurface() meshToSurface.Mesh = wallThreshold.GetOutput() meshToSurface.Execute() #Compute the normals for this surface, orientation should be right because the surface is closed #TODO: Add option for cell normals in vmtksurfacenormals normalsFilter = vtk.vtkPolyDataNormals() normalsFilter.SetInputData(meshToSurface.Surface) normalsFilter.SetAutoOrientNormals(1) normalsFilter.SetFlipNormals(0) normalsFilter.SetConsistency(1) normalsFilter.SplittingOff() normalsFilter.ComputePointNormalsOff() normalsFilter.ComputeCellNormalsOn() normalsFilter.Update() surfaceToMesh = vmtkscripts.vmtkSurfaceToMesh() surfaceToMesh.Surface = normalsFilter.GetOutput() surfaceToMesh.Execute() #Save the current normals wallWithBoundariesMesh = surfaceToMesh.Mesh savedNormals = vtk.vtkDoubleArray() savedNormals.DeepCopy(wallWithBoundariesMesh.GetCellData().GetNormals()) savedNormals.SetName('SavedNormals') wallWithBoundariesMesh.GetCellData().AddArray(savedNormals) #cut off the boundaries and other surfaces extrudeThresholdLower = vtk.vtkThreshold() extrudeThresholdLower.SetInputData(wallWithBoundariesMesh) extrudeThresholdLower.ThresholdByLower(self.ExtrudeCellEntityId+0.5) extrudeThresholdLower.SetInputArrayToProcess(0,0,0,1,self.CellEntityIdsArrayName) extrudeThresholdLower.Update() extrudeThresholdUpper = vtk.vtkThreshold() extrudeThresholdUpper.SetInputConnection(extrudeThresholdLower.GetOutputPort()) extrudeThresholdUpper.ThresholdByUpper(self.ExtrudeCellEntityId-0.5) extrudeThresholdUpper.SetInputArrayToProcess(0,0,0,1,self.CellEntityIdsArrayName) extrudeThresholdUpper.Update() meshToSurface = vmtkscripts.vmtkMeshToSurface() meshToSurface.Mesh = extrudeThresholdUpper.GetOutput() meshToSurface.Execute() #Compute cell normals without boundaries normalsFilter = vtk.vtkPolyDataNormals() normalsFilter.SetInputData(meshToSurface.Surface) normalsFilter.SetAutoOrientNormals(1) normalsFilter.SetFlipNormals(0) normalsFilter.SetConsistency(1) normalsFilter.SplittingOff() normalsFilter.ComputePointNormalsOn() normalsFilter.ComputeCellNormalsOn() normalsFilter.Update() wallWithoutBoundariesSurface = normalsFilter.GetOutput() normals = wallWithoutBoundariesSurface.GetCellData().GetNormals() savedNormals = wallWithoutBoundariesSurface.GetCellData().GetArray('SavedNormals') math = vtk.vtkMath() #If the normal are inverted, recompute the normals with flipping on if normals.GetNumberOfTuples() > 0 and math.Dot(normals.GetTuple3(0),savedNormals.GetTuple3(0)) < 0: normalsFilter = vtk.vtkPolyDataNormals() normalsFilter.SetInputData(meshToSurface.Surface) normalsFilter.SetAutoOrientNormals(1) normalsFilter.SetFlipNormals(1) normalsFilter.SetConsistency(1) normalsFilter.SplittingOff() normalsFilter.ComputePointNormalsOn() normalsFilter.ComputeCellNormalsOn() normalsFilter.Update() wallWithoutBoundariesSurface = normalsFilter.GetOutput() wallWithoutBoundariesSurface.GetPointData().GetNormals().SetName('Normals') wallWithoutBoundariesSurface.GetCellData().RemoveArray('SavedNormals') surfaceToMesh = vmtkscripts.vmtkSurfaceToMesh() surfaceToMesh.Surface = wallWithoutBoundariesSurface surfaceToMesh.Execute() #Offset to apply to the array wallOffset = 0 if self.IncludeSurfaceCells or self.IncludeOriginalSurfaceCells: wallOffset += 1 if self.IncludeSurfaceCells or self.IncludeExtrudedSurfaceCells: wallOffset+=1 boundaryLayer = vmtkscripts.vmtkBoundaryLayer2() boundaryLayer.Mesh = surfaceToMesh.Mesh boundaryLayer.WarpVectorsArrayName = 'Normals' boundaryLayer.NegateWarpVectors = False boundaryLayer.ThicknessArrayName = self.ThicknessArrayName boundaryLayer.ConstantThickness = self.ConstantThickness boundaryLayer.IncludeSurfaceCells = self.IncludeSurfaceCells boundaryLayer.NumberOfSubLayers = self.NumberOfSubLayers boundaryLayer.SubLayerRatio = self.SubLayerRatio boundaryLayer.Thickness = self.Thickness boundaryLayer.ThicknessRatio = self.Thickness boundaryLayer.MaximumThickness = self.MaximumThickness boundaryLayer.CellEntityIdsArrayName = self.CellEntityIdsArrayName boundaryLayer.IncludeExtrudedOpenProfilesCells = self.IncludeExtrudedOpenProfilesCells boundaryLayer.IncludeExtrudedSurfaceCells = self.IncludeExtrudedSurfaceCells boundaryLayer.IncludeOriginalSurfaceCells = self.IncludeOriginalSurfaceCells boundaryLayer.LayerEntityId = self.SurfaceCellEntityId boundaryLayer.SurfaceEntityId = self.InletOutletCellEntityId + 1 if cellEntityIdsArray != None: #Append the new surface ids idRange = cellEntityIdsArray.GetRange() boundaryLayer.OpenProfilesEntityId = idRange[1] + wallOffset + 2 boundaryLayer.Execute() if cellEntityIdsArray != None: #offset the previous cellentityids to make room for the new ones arrayCalculator = vtk.vtkArrayCalculator() arrayCalculator.SetInputData(self.Mesh) if vtk.vtkVersion.GetVTKMajorVersion()>=9 or (vtk.vtkVersion.GetVTKMajorVersion()>=8 and vtk.vtkVersion.GetVTKMinorVersion()>=1): arrayCalculator.SetAttributeTypeToCellData() else: arrayCalculator.SetAttributeModeToUseCellData() arrayCalculator.AddScalarVariable("entityid",self.CellEntityIdsArrayName,0) arrayCalculator.SetFunction("if( entityid > " + str(self.InletOutletCellEntityId-1) +", entityid + " + str(wallOffset) + ", entityid)") arrayCalculator.SetResultArrayName('CalculatorResult') arrayCalculator.Update() #This need to be copied in order to be of the right type (int) cellEntityIdsArray.DeepCopy(arrayCalculator.GetOutput().GetCellData().GetArray('CalculatorResult')) arrayCalculator.SetFunction("if( entityid > " + str(self.SurfaceCellEntityId-1) +", entityid + 1, entityid)") arrayCalculator.Update() ##This need to be copied in order to be of the right type (int) cellEntityIdsArray.DeepCopy(arrayCalculator.GetOutput().GetCellData().GetArray('CalculatorResult')) appendFilter = vtkvmtk.vtkvmtkAppendFilter() appendFilter.AddInput(self.Mesh) appendFilter.AddInput(boundaryLayer.Mesh) appendFilter.Update() self.Mesh = appendFilter.GetOutput()
def post_proc_cfd(dir_path, vtu_input, cell_type="point", vtu_output_1="calc_test_node.vtu", vtu_output_2="calc_test_node_stats.vtu", N_peak=3): reader = vtk.vtkXMLUnstructuredGridReader() reader.SetFileName(os.path.join(dir_path, vtu_input)) reader.Update() N = reader.GetNumberOfTimeSteps() print(N) #N = test.GetNumberOfBlocks()ls #block = test.GetBlock(0) #for i in range(N): # print(i, test.GetMetaData(i).Get(vtk.vtkCompositeDataSet.NAME())) #grid = reader.GetOutput() #wallshear = grid.GetCellData().GetArray("x_wall_shear") #print(wallshear) calc1 = vtk.vtkArrayCalculator() calc1.SetFunction("sqrt(x_wall_shear^2+y_wall_shear^2+z_wall_shear^2)") calc1.AddScalarVariable("x_wall_shear", "x_wall_shear",0) calc1.AddScalarVariable("y_wall_shear", "y_wall_shear",0) calc1.AddScalarVariable("z_wall_shear", "z_wall_shear",0) calc1.SetResultArrayName("WSS") calc1.SetInputConnection(reader.GetOutputPort()) if(cell_type == "cell"): calc1.SetAttributeModeToUseCellData() vtk_process = vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS vtk_data_type = vtk.vtkDataObject.CELL else: calc1.SetAttributeModeToUsePointData() vtk_process = vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS vtk_data_type = vtk.vtkDataObject.POINT calc1.SetResultArrayType(vtk.VTK_DOUBLE) x_WSS_grad = vtk.vtkGradientFilter() x_WSS_grad.SetInputConnection(calc1.GetOutputPort()) x_WSS_grad.ComputeGradientOn() x_WSS_grad.FasterApproximationOff() x_WSS_grad.SetResultArrayName("x_WSS_grad") x_WSS_grad.SetInputArrayToProcess(0, 0, 0, vtk_process, "x_wall_shear") y_WSS_grad = vtk.vtkGradientFilter() y_WSS_grad.SetInputConnection(x_WSS_grad.GetOutputPort()) y_WSS_grad.ComputeGradientOn() y_WSS_grad.FasterApproximationOff() y_WSS_grad.SetResultArrayName("y_WSS_grad") x_WSS_grad.SetInputArrayToProcess(0, 0, 0, vtk_process, "y_wall_shear") z_WSS_grad = vtk.vtkGradientFilter() z_WSS_grad.SetInputConnection(y_WSS_grad.GetOutputPort()) z_WSS_grad.ComputeGradientOn() z_WSS_grad.FasterApproximationOff() z_WSS_grad.SetResultArrayName("z_WSS_grad") z_WSS_grad.SetInputArrayToProcess(0, 0, 0, vtk_process, "z_wall_shear") calc2 = vtk.vtkArrayCalculator() calc2.AddScalarVariable("x_component", "x_WSS_grad",0) calc2.AddScalarVariable("y_component", "y_WSS_grad",1) calc2.AddScalarVariable("z_component", "z_WSS_grad",2) calc2.SetFunction("sqrt(x_component^2+y_component^2+z_component^2)") calc2.SetResultArrayName("WSSG") calc2.SetInputConnection(z_WSS_grad.GetOutputPort()) if(cell_type == "cell"): calc2.SetAttributeModeToUseCellData() else: calc2.SetAttributeModeToUsePointData() calc2.SetResultArrayType(vtk.VTK_DOUBLE) # initialize the output to include the peak values grid = vtk.vtkUnstructuredGrid() #N_peak = 3 reader.SetTimeStep(N_peak) print("loading {0}th timestep to copy data".format(N_peak)) calc2.Update() grid.DeepCopy(calc2.GetOutput()) #grid.SetNumberOfTimeSteps(1) #grid.SetTimeStep(0) #grid.Update() #sqrt((ddx({Wall shear-1}))**2 + (ddy({Wall shear-2}))**2 + (ddz({Wall shear-3}))**2)' def init_zero(in_array, sz_array): for i in range(sz_array): in_array.SetValue(i,0.0) def array_sum(out_array, in_array, sz_array): for i in range(sz_array): out_array.SetValue(i, out_array.GetValue(i) + in_array.GetValue(i)) def array_division(out_array, in_array, sz_array): for i in range(sz_array): out_array.SetValue(i, out_array.GetValue(i) / in_array.GetValue(i)) def array_avg(out_array, N): float_N = float(N) for i in range(N): out_array.SetValue(i, out_array.GetValue(i) / float_N) reader.SetTimeStep(0) print("loading {0}th timestep for averaging initialization".format(0)) reader.Update() calc2.Update() if(cell_type == "cell"): calc_data = calc2.GetOutput().GetCellData() grid_data = grid.GetCellData() n_sz = grid.GetNumberOfCells() else: calc_data = calc2.GetOutput().GetPointData() grid_data = grid.GetPointData() n_sz = grid.GetNumberOfPoints() TAWSS = vtk.vtkDoubleArray() TAWSS.DeepCopy(calc_data.GetArray("WSS")) TAWSS.SetName("TAWSS") TAWSSG = vtk.vtkDoubleArray() TAWSSG.DeepCopy(calc_data.GetArray("WSSG")) TAWSSG.SetName("TAWSSG") x_shear_avg = vtk.vtkDoubleArray() x_shear_avg.DeepCopy(calc_data.GetArray("x_wall_shear")) x_shear_avg.SetName("x_shear_avg") y_shear_avg = vtk.vtkDoubleArray() y_shear_avg.DeepCopy(calc_data.GetArray("y_wall_shear")) y_shear_avg.SetName("y_shear_avg") z_shear_avg = vtk.vtkDoubleArray() z_shear_avg.DeepCopy(calc_data.GetArray("z_wall_shear")) z_shear_avg.SetName("z_shear_avg") #TAWSSVector = vtk.vtkDoubleArray() #TAWSSVector.DeepCopy(calc_data.GetArray("z_wall_shear")) #TAWSSVector.SetName("TAWSSVector") #grid_data.AddArray(TAWSSVector) # def get_array_names(input): # N_point_array = input.GetOutput().GetPointData().GetNumberOfArrays() # N_WSS = 9999999 # for i in range(N_point_array): # name_WSS = input.GetOutput().GetPointData().GetArrayName(i) # if (name_WSS == "WSS"): # N_WSS = i # print(name_WSS) # # def array_sum(output, input_calc, N): # for i in range(N): # calc = output.GetValue(i) + input_calc.GetValue(i) # output.SetValue(i, calc) writer = vtk.vtkXMLUnstructuredGridWriter() #writer.SetFileName(os.path.join(out_dir,'test_outfile.vtu')) writer.SetFileName(os.path.join(dir_path, vtu_output_1)) writer.SetNumberOfTimeSteps(N) #writer.SetTimeStepRange(0,len(filelist)-1) writer.SetInputConnection(calc2.GetOutputPort()) writer.Start() #avg_map = {"TAWSS":"WSS", "TAWSSG": "WSSG", "x_shear_avg":"x_wall_shear", # "y_shear_avg":"y_wall_shear" , "z_shear_avg":"z_wall_shear"} for i in range(1,N): reader.SetTimeStep(i) print("Time step {0} for average calc".format(i)) reader.Update() calc2.Update() if(cell_type == "cell"): calc_data = calc2.GetOutput().GetCellData() else: calc_data = calc2.GetOutput().GetPointData() #get_array_names(calc2) array_sum(TAWSS, calc_data.GetArray("WSS"), n_sz) array_sum(TAWSSG, calc_data.GetArray("WSSG"), n_sz) array_sum(x_shear_avg, calc_data.GetArray("x_wall_shear"), n_sz) array_sum(y_shear_avg, calc_data.GetArray("y_wall_shear"), n_sz) array_sum(z_shear_avg, calc_data.GetArray("z_wall_shear"), n_sz) writer.WriteNextTime(reader.GetTimeStep()) writer.Stop() array_avg(TAWSS, N) array_avg(TAWSSG, N) array_avg(x_shear_avg, N) array_avg(y_shear_avg, N) array_avg(z_shear_avg, N) WSS_peak2mean = vtk.vtkDoubleArray() WSS_peak2mean.DeepCopy(grid_data.GetArray("WSS")) WSS_peak2mean.SetName("WSS_peak2mean") array_division(WSS_peak2mean, TAWSS, n_sz) WSSG_peak2mean = vtk.vtkDoubleArray() WSSG_peak2mean.DeepCopy(grid_data.GetArray("WSSG")) WSSG_peak2mean.SetName("WSSG_peak2mean") array_division(WSSG_peak2mean, TAWSSG, n_sz) grid_data.AddArray(TAWSS) grid_data.AddArray(TAWSSG) grid_data.AddArray(x_shear_avg) grid_data.AddArray(y_shear_avg) grid_data.AddArray(z_shear_avg) grid_data.AddArray(WSS_peak2mean) grid_data.AddArray(WSSG_peak2mean) print("got here") calc3 = vtk.vtkArrayCalculator() calc3.AddScalarVariable("x_shear_avg", "x_shear_avg",0) calc3.AddScalarVariable("y_shear_avg", "y_shear_avg",0) calc3.AddScalarVariable("z_shear_avg", "z_shear_avg",0) calc3.SetFunction("sqrt(x_shear_avg^2+y_shear_avg^2+z_shear_avg^2)") calc3.SetResultArrayName("TAWSSVector") calc3.SetInputData(grid) if(cell_type == "cell"): calc3.SetAttributeModeToUseCellData() else: calc3.SetAttributeModeToUsePointData() calc3.SetResultArrayType(vtk.VTK_DOUBLE) calc3.Update() calc4 = vtk.vtkArrayCalculator() calc4.AddScalarVariable("TAWSSVector", "TAWSSVector",0) calc4.AddScalarVariable("TAWSS", "TAWSS",0) calc4.SetFunction("0.5*(1.0-(TAWSSVector/(TAWSS)))") calc4.SetResultArrayName("OSI") calc4.SetInputConnection(calc3.GetOutputPort()) if(cell_type == "cell"): calc4.SetAttributeModeToUseCellData() else: calc4.SetAttributeModeToUsePointData() calc4.SetResultArrayType(vtk.VTK_DOUBLE) calc4.Update() pass_filt = vtk.vtkPassArrays() pass_filt.SetInputConnection(calc4.GetOutputPort()) pass_filt.AddArray(vtk_data_type, "WSS") pass_filt.AddArray(vtk_data_type, "WSSG") pass_filt.AddArray(vtk_data_type, "absolute_pressure") pass_filt.AddArray(vtk_data_type, "TAWSS") pass_filt.AddArray(vtk_data_type, "TAWSSG") pass_filt.AddArray(vtk_data_type, "OSI") pass_filt.AddArray(vtk_data_type, "WSS_peak2mean") pass_filt.AddArray(vtk_data_type, "WSSG_peak2mean") pass_filt.Update() #if(cell_type == "cell"): # print(pass_filt.GetOutput().GetCellData().GetArray("OSI").GetValue(0)) #else: # print(pass_filt.GetOutput().GetPointData().GetArray("OSI").GetValue(0)) writer2 = vtk.vtkXMLUnstructuredGridWriter() writer2.SetFileName(os.path.join(dir_path, vtu_output_2)) writer2.SetInputConnection(pass_filt.GetOutputPort()) writer2.Update()
def getFreeSurfaceActor(vtk_r, scale=[1, 1, 1], fsRange=None): aa = vtk.vtkAssignAttribute() aa.SetInputConnection(vtk_r.GetOutputPort()) aa.Assign('alpha.water', "SCALARS", "POINT_DATA") isoContour = vtk.vtkContourFilter() isoContour.SetInputConnection(aa.GetOutputPort()) isoContour.SetValue(0, 0.5) # isoContour.SetGenerateTriangles(0) isoContour.SetNumberOfContours(1) isoContourDataFilter = vtk.vtkCompositeDataGeometryFilter() isoContourDataFilter.SetInputConnection(isoContour.GetOutputPort()) transform = vtk.vtkTransform() transform.Scale(*scale) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputConnection(isoContourDataFilter.GetOutputPort()) tf.SetTransform(transform) # Use an ArrayCalculator to get the iso-contour elevation calc = vtk.vtkArrayCalculator() calc.SetInputConnection(tf.GetOutputPort()) calc.SetAttributeModeToUsePointData() calc.AddCoordinateScalarVariable("coordsZ", 2) calc.SetFunction("coordsZ") calc.SetResultArrayName("coordsZ") #--- Map the data isoContourMapper = vtk.vtkDataSetMapper() isoContourMapper.SetInputConnection(calc.GetOutputPort()) #---Select node property to display lutBlueRed = vtk.vtkLookupTable() lutBlueRed.SetHueRange(2. / 3., 0.) lutBlueRed.SetVectorModeToMagnitude() lutBlueRed.Build() scalarBar = vtk.vtkScalarBarActor() scalarBar.SetLookupTable(lutBlueRed) scalarBar.SetWidth(0.05) scalarBar.SetHeight(0.25) scalarBar.SetTitle("Z(m)") scalarBar.GetTitleTextProperty().SetColor(0., 0., 0.) scalarBar.GetLabelTextProperty().SetColor(0., 0., 0.) isoContourMapper.SelectColorArray("coordsZ") # isoContourMapper.SetScalarModeToUsePointData() isoContourMapper.SetScalarModeToUsePointFieldData() isoContourMapper.SetLookupTable(lutBlueRed) if fsRange is not None: isoContourMapper.SetScalarRange(*fsRange) isoContourMapper.SetUseLookupTableScalarRange(0) #---Add actor fsActor = vtk.vtkActor() fsActor.GetProperty().SetEdgeVisibility(0) fsActor.SetMapper(isoContourMapper) fsActor.GetProperty().SetOpacity(0.7) return fsActor, scalarBar
def extractTopSurface(self, surfaceNormalDirections, angleToleranceDeg): fullLeafletPolydata = self.getLeafletPolydata() if not fullLeafletPolydata or fullLeafletPolydata.GetNumberOfCells( ) == 0: # empty input mesh return None # Clean up input cleaner = vtk.vtkCleanPolyData() cleaner.SetInputData(fullLeafletPolydata) stripper = vtk.vtkTriangleFilter() stripper.SetInputConnection(cleaner.GetOutputPort()) # Compute point normals normals = vtk.vtkPolyDataNormals() normals.SetInputConnection(stripper.GetOutputPort()) #normals.SetInputData(fullLeafletPolydata) normals.AutoOrientNormalsOn() #normals.NonManifoldTraversalOn() normals.ComputePointNormalsOn() normals.ComputeCellNormalsOff() # Compute angle compared to surfaceNormalDirection calc = vtk.vtkArrayCalculator() calc.SetInputConnection(normals.GetOutputPort()) calc.SetAttributeTypeToPointData() calc.AddVectorArrayName("Normals") # Get angle difference function string for each normal: angleDiff = acos(dot(Normal, surfaceNormalDirection)) singleAngleDiffFuncStrs = [ ] # list of angle differences for each normal direction 'acos(Normals.(iHat*(0.4)+jHat*(0.3)+kHat*(0.2))))' for surfaceNormalDirection in surfaceNormalDirections: # make sure the surfaceNormalDirection vector is normalized normalizedSurfaceNormalDirection = np.array(surfaceNormalDirection) normalizedSurfaceNormalDirection = normalizedSurfaceNormalDirection / np.linalg.norm( surfaceNormalDirection) singleAngleDiffFuncStrs.append( "acos(Normals.(iHat*({0})+jHat*({1})+kHat*({2})))".format( normalizedSurfaceNormalDirection[0], normalizedSurfaceNormalDirection[1], normalizedSurfaceNormalDirection[2])) # Get function string that computes the minimum for all angle differences angleDiffFuncStr = "" # min(min(min(min(diff1,diff2),diff3),diff4),diff5) for i in range(len(singleAngleDiffFuncStrs) - 1): angleDiffFuncStr += "min(" for index, singleAngleDiffFuncStr in enumerate( singleAngleDiffFuncStrs): if index == 0: angleDiffFuncStr += singleAngleDiffFuncStr else: angleDiffFuncStr += "," + singleAngleDiffFuncStr + ")" print(angleDiffFuncStr) calc.SetResultArrayName('angleDiff') calc.SetFunction(angleDiffFuncStr) # Cut along specified threshold value (smooth cut through cells) threshold = vtk.vtkClipPolyData() threshold.SetInputConnection(calc.GetOutputPort()) angleToleranceRad = float(angleToleranceDeg) * math.pi / 180.0 threshold.SetValue(angleToleranceRad) threshold.SetInputArrayToProcess( 0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, "angleDiff") threshold.InsideOutOn() extractLargest = vtk.vtkPolyDataConnectivityFilter() extractLargest.SetExtractionModeToLargestRegion() extractLargest.SetInputConnection(threshold.GetOutputPort()) extractLargest.Update() polyData = vtk.vtkPolyData() polyData.ShallowCopy(extractLargest.GetOutput()) polyData.GetPointData().SetActiveScalars(None) return polyData
def test_composite(self): print "\nTEST VTK LAYERS" # set up some processing task s = vtk.vtkRTAnalyticSource() s.SetWholeExtent(-50, 50, -50, 50, -50, 50) rw = vtk.vtkRenderWindow() r = vtk.vtkRenderer() rw.AddRenderer(r) ac1 = vtk.vtkArrayCalculator() ac1.SetInputConnection(s.GetOutputPort()) ac1.SetAttributeModeToUsePointData() ac1.AddCoordinateVectorVariable("coords", 0, 1, 2) ac1.SetResultArrayName("Coords") ac1.SetFunction("coords") ac2 = vtk.vtkArrayCalculator() ac2.SetInputConnection(ac1.GetOutputPort()) ac2.SetAttributeModeToUsePointData() ac2.AddCoordinateVectorVariable("coords", 0, 1, 2) ac2.SetResultArrayName("radii") ac2.SetFunction("mag(coords)") cf = vtk.vtkContourFilter() cf.SetInputConnection(ac2.GetOutputPort()) cf.SetInputArrayToProcess(0, 0, 0, "vtkDataObject::FIELD_ASSOCIATION_POINTS", "radii") cf.SetNumberOfContours(1) cf.ComputeScalarsOff() cf.SetValue(0, 40) m = vtk.vtkPolyDataMapper() m.SetInputConnection(cf.GetOutputPort()) a = vtk.vtkActor() a.SetMapper(m) r.AddActor(a) rw.Render() r.ResetCamera() # make a cinema data store by defining the things that vary fname = "/tmp/test_vtk_composite/info.json" cs = file_store.FileStore(fname) cs.add_metadata({'type': 'composite-image-stack'}) cs.add_metadata({'store_type': 'FS'}) cs.add_metadata({'version': '0.1'}) cs.filename_pattern = "{phi}/{theta}/{vis}.png" cs.add_parameter("phi", store.make_parameter('phi', range(0, 200, 50))) cs.add_parameter("theta", store.make_parameter('theta', range(-180, 200, 45))) cs.add_layer("vis", store.make_parameter("vis", ['contour'])) contours = [15, 30, 55, 70, 85] cs.add_control("isoval", store.make_parameter('isoval', contours)) cs.assign_parameter_dependence("isoval", "vis", ['contour']) cs.add_field( "color", store.make_field( 'color', { 'white': 'rgb', 'red': 'rgb', 'depth': 'depth', 'lum': 'luminance', 'RTData': 'value', 'point_X': 'value', 'point_Y': 'value', 'point_Z': 'value' }), "isoval", contours) # associate control points with parameters of the data store cam = vtk_explorers.Camera([0, 0, 0], [0, 1, 0], 300.0, r.GetActiveCamera()) showcontour = vtk_explorers.ActorInLayer('contour', a) layertrack = explorers.Layer('vis', [showcontour]) controltrack = vtk_explorers.Contour('isoval', cf, 'SetValue') # additional specification necessary for the color field colorChoice = vtk_explorers.ColorList() colorChoice.AddSolidColor('white', [1, 1, 1]) colorChoice.AddSolidColor('red', [1, 0, 0]) colorChoice.AddDepth('depth') colorChoice.AddLuminance('lum') colorChoice.AddValueRender('RTData', vtk.VTK_SCALAR_MODE_USE_POINT_FIELD_DATA, 'RTData', 0, [0, 250]) colorChoice.AddValueRender('point_X', vtk.VTK_SCALAR_MODE_USE_POINT_FIELD_DATA, 'Coords', 0, [-50, 50]) colorChoice.AddValueRender('point_Y', vtk.VTK_SCALAR_MODE_USE_POINT_FIELD_DATA, 'Coords', 1, [-50, 50]) colorChoice.AddValueRender('point_Z', vtk.VTK_SCALAR_MODE_USE_POINT_FIELD_DATA, 'Coords', 2, [-50, 50]) colortrack = vtk_explorers.Color('color', colorChoice, a) paramNames = ['phi', 'theta', 'vis', 'isoval', 'color'] trackList = [cam, layertrack, controltrack, colortrack] e = vtk_explorers.ImageExplorer(cs, paramNames, trackList, rw) colortrack.imageExplorer = e e.explore() cs.save()
def testFinancialField(self): """ Demonstrate the use and manipulation of fields and use of vtkProgrammableDataObjectSource. This creates fields the hard way (as compared to reading a vtk field file), but shows you how to interface to your own raw data. The image should be the same as financialField.tcl """ xAxis = "INTEREST_RATE" yAxis = "MONTHLY_PAYMENT" zAxis = "MONTHLY_INCOME" scalar = "TIME_LATE" # Parse an ascii file and manually create a field. Then construct a # dataset from the field. dos = vtk.vtkProgrammableDataObjectSource() def parseFile(): f = open(VTK_DATA_ROOT + "/Data/financial.txt", "r") line = f.readline().split() # From the size calculate the number of lines. numPts = int(line[1]) numLines = (numPts - 1) / 8 + 1 # create the data object field = vtk.vtkFieldData() field.AllocateArrays(4) # read TIME_LATE - dependent variable while True: line = f.readline().split() if len(line) > 0: break timeLate = vtk.vtkFloatArray() timeLate.SetName(line[0]) for i in range(0, numLines): line = f.readline().split() for j in line: timeLate.InsertNextValue(float(j)) field.AddArray(timeLate) # MONTHLY_PAYMENT - independent variable while True: line = f.readline().split() if len(line) > 0: break monthlyPayment = vtk.vtkFloatArray() monthlyPayment.SetName(line[0]) for i in range(0, numLines): line = f.readline().split() for j in line: monthlyPayment.InsertNextValue(float(j)) field.AddArray(monthlyPayment) # UNPAID_PRINCIPLE - skip while True: line = f.readline().split() if len(line) > 0: break for i in range(0, numLines): line = f.readline() # LOAN_AMOUNT - skip while True: line = f.readline().split() if len(line) > 0: break for i in range(0, numLines): line = f.readline() # INTEREST_RATE - independent variable while True: line = f.readline().split() if len(line) > 0: break interestRate = vtk.vtkFloatArray() interestRate.SetName(line[0]) for i in range(0, numLines): line = f.readline().split() for j in line: interestRate.InsertNextValue(float(j)) field.AddArray(interestRate) # MONTHLY_INCOME - independent variable while True: line = f.readline().split() if len(line) > 0: break monthlyIncome = vtk.vtkFloatArray() monthlyIncome.SetName(line[0]) for i in range(0, numLines): line = f.readline().split() for j in line: monthlyIncome.InsertNextValue(float(j)) field.AddArray(monthlyIncome) dos.GetOutput().SetFieldData(field) dos.SetExecuteMethod(parseFile) # Create the dataset do2ds = vtk.vtkDataObjectToDataSetFilter() do2ds.SetInputConnection(dos.GetOutputPort()) do2ds.SetDataSetTypeToPolyData() #format: component#, arrayname, arraycomp, minArrayId, maxArrayId, normalize do2ds.DefaultNormalizeOn() do2ds.SetPointComponent(0, xAxis, 0) do2ds.SetPointComponent(1, yAxis, 0) do2ds.SetPointComponent(2, zAxis, 0) do2ds.Update() rf = vtk.vtkRearrangeFields() rf.SetInputConnection(do2ds.GetOutputPort()) rf.AddOperation("MOVE", scalar, "DATA_OBJECT", "POINT_DATA") rf.RemoveOperation("MOVE", scalar, "DATA_OBJECT", "POINT_DATA") rf.AddOperation("MOVE", scalar, "DATA_OBJECT", "POINT_DATA") rf.RemoveAllOperations() rf.AddOperation("MOVE", scalar, "DATA_OBJECT", "POINT_DATA") rf.Update() max = rf.GetOutput().GetPointData().GetArray(scalar).GetRange(0)[1] calc = vtk.vtkArrayCalculator() calc.SetInputConnection(rf.GetOutputPort()) calc.SetAttributeTypeToPointData() calc.SetFunction("s / %f" % max) calc.AddScalarVariable("s", scalar, 0) calc.SetResultArrayName("resArray") aa = vtk.vtkAssignAttribute() aa.SetInputConnection(calc.GetOutputPort()) aa.Assign("resArray", "SCALARS", "POINT_DATA") aa.Update() rf2 = vtk.vtkRearrangeFields() rf2.SetInputConnection(aa.GetOutputPort()) rf2.AddOperation("COPY", "SCALARS", "POINT_DATA", "DATA_OBJECT") # construct pipeline for original population popSplatter = vtk.vtkGaussianSplatter() popSplatter.SetInputConnection(rf2.GetOutputPort()) popSplatter.SetSampleDimensions(50, 50, 50) popSplatter.SetRadius(0.05) popSplatter.ScalarWarpingOff() popSurface = vtk.vtkContourFilter() popSurface.SetInputConnection(popSplatter.GetOutputPort()) popSurface.SetValue(0, 0.01) popMapper = vtk.vtkPolyDataMapper() popMapper.SetInputConnection(popSurface.GetOutputPort()) popMapper.ScalarVisibilityOff() popMapper.ImmediateModeRenderingOn() popActor = vtk.vtkActor() popActor.SetMapper(popMapper) popActor.GetProperty().SetOpacity(0.3) popActor.GetProperty().SetColor(.9, .9, .9) # construct pipeline for delinquent population lateSplatter = vtk.vtkGaussianSplatter() lateSplatter.SetInputConnection(aa.GetOutputPort()) lateSplatter.SetSampleDimensions(50, 50, 50) lateSplatter.SetRadius(0.05) lateSplatter.SetScaleFactor(0.05) lateSurface = vtk.vtkContourFilter() lateSurface.SetInputConnection(lateSplatter.GetOutputPort()) lateSurface.SetValue(0, 0.01) lateMapper = vtk.vtkPolyDataMapper() lateMapper.SetInputConnection(lateSurface.GetOutputPort()) lateMapper.ScalarVisibilityOff() lateActor = vtk.vtkActor() lateActor.SetMapper(lateMapper) lateActor.GetProperty().SetColor(1.0, 0.0, 0.0) # create axes popSplatter.Update() bounds = popSplatter.GetOutput().GetBounds() axes = vtk.vtkAxes() axes.SetOrigin(bounds[0], bounds[2], bounds[4]) axes.SetScaleFactor(popSplatter.GetOutput().GetLength() / 5.0) axesTubes = vtk.vtkTubeFilter() axesTubes.SetInputConnection(axes.GetOutputPort()) axesTubes.SetRadius(axes.GetScaleFactor() / 25.0) axesTubes.SetNumberOfSides(6) axesMapper = vtk.vtkPolyDataMapper() axesMapper.SetInputConnection(axesTubes.GetOutputPort()) axesActor = vtk.vtkActor() axesActor.SetMapper(axesMapper) # label the axes XText = vtk.vtkVectorText() XText.SetText(xAxis) XTextMapper = vtk.vtkPolyDataMapper() XTextMapper.SetInputConnection(XText.GetOutputPort()) XActor = vtk.vtkFollower() XActor.SetMapper(XTextMapper) XActor.SetScale(0.02, .02, .02) XActor.SetPosition(0.35, -0.05, -0.05) XActor.GetProperty().SetColor(0, 0, 0) YText = vtk.vtkVectorText() YText.SetText(yAxis) YTextMapper = vtk.vtkPolyDataMapper() YTextMapper.SetInputConnection(YText.GetOutputPort()) YActor = vtk.vtkFollower() YActor.SetMapper(YTextMapper) YActor.SetScale(0.02, .02, .02) YActor.SetPosition(-0.05, 0.35, -0.05) YActor.GetProperty().SetColor(0, 0, 0) ZText = vtk.vtkVectorText() ZText.SetText(zAxis) ZTextMapper = vtk.vtkPolyDataMapper() ZTextMapper.SetInputConnection(ZText.GetOutputPort()) ZActor = vtk.vtkFollower() ZActor.SetMapper(ZTextMapper) ZActor.SetScale(0.02, .02, .02) ZActor.SetPosition(-0.05, -0.05, 0.35) ZActor.GetProperty().SetColor(0, 0, 0) # Graphics stuff # ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) renWin.SetWindowName("vtk(-, Field.Data") renWin.SetSize(300, 300) # Add the actors to the renderer, set the background and size # ren.AddActor(axesActor) ren.AddActor(lateActor) ren.AddActor(XActor) ren.AddActor(YActor) ren.AddActor(ZActor) ren.AddActor(popActor) #it's last because its translucent) ren.SetBackground(1, 1, 1) camera = vtk.vtkCamera() camera.SetClippingRange(.274, 13.72) camera.SetFocalPoint(0.433816, 0.333131, 0.449) camera.SetPosition(-1.96987, 1.15145, 1.49053) camera.SetViewUp(0.378927, 0.911821, 0.158107) ren.SetActiveCamera(camera) XActor.SetCamera(camera) YActor.SetCamera(camera) ZActor.SetCamera(camera) # render and interact with data iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin) renWin.Render() img_file = "financialField3.png" vtk.test.Testing.compareImage( iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25) vtk.test.Testing.interact()
def testFinancialField(self): """ Demonstrate the use and manipulation of fields and use of vtkProgrammableDataObjectSource. This creates fields the hard way (as compared to reading a vtk field file), but shows you how to interface to your own raw data. The image should be the same as financialField.tcl """ xAxis = "INTEREST_RATE" yAxis = "MONTHLY_PAYMENT" zAxis = "MONTHLY_INCOME" scalar = "TIME_LATE" # Parse an ascii file and manually create a field. Then construct a # dataset from the field. dos = vtk.vtkProgrammableDataObjectSource() def parseFile(): f = open(VTK_DATA_ROOT + "/Data/financial.txt", "r") line = f.readline().split() # From the size calculate the number of lines. numPts = int(line[1]) numLines = (numPts - 1) / 8 + 1 # create the data object field = vtk.vtkFieldData() field.AllocateArrays(4) # read TIME_LATE - dependent variable while True: line = f.readline().split() if len(line) > 0: break; timeLate = vtk.vtkFloatArray() timeLate.SetName(line[0]) for i in range(0, numLines): line = f.readline().split() for j in line: timeLate.InsertNextValue(float(j)) field.AddArray(timeLate) # MONTHLY_PAYMENT - independent variable while True: line = f.readline().split() if len(line) > 0: break; monthlyPayment = vtk.vtkFloatArray() monthlyPayment.SetName(line[0]) for i in range(0, numLines): line = f.readline().split() for j in line: monthlyPayment.InsertNextValue(float(j)) field.AddArray(monthlyPayment) # UNPAID_PRINCIPLE - skip while True: line = f.readline().split() if len(line) > 0: break; for i in range(0, numLines): line = f.readline() # LOAN_AMOUNT - skip while True: line = f.readline().split() if len(line) > 0: break; for i in range(0, numLines): line = f.readline() # INTEREST_RATE - independent variable while True: line = f.readline().split() if len(line) > 0: break; interestRate = vtk.vtkFloatArray() interestRate.SetName(line[0]) for i in range(0, numLines): line = f.readline().split() for j in line: interestRate.InsertNextValue(float(j)) field.AddArray(interestRate) # MONTHLY_INCOME - independent variable while True: line = f.readline().split() if len(line) > 0: break; monthlyIncome = vtk.vtkFloatArray() monthlyIncome.SetName(line[0]) for i in range(0, numLines): line = f.readline().split() for j in line: monthlyIncome.InsertNextValue(float(j)) field.AddArray(monthlyIncome) dos.GetOutput().SetFieldData(field) dos.SetExecuteMethod(parseFile) # Create the dataset do2ds = vtk.vtkDataObjectToDataSetFilter() do2ds.SetInputConnection(dos.GetOutputPort()) do2ds.SetDataSetTypeToPolyData() #format: component#, arrayname, arraycomp, minArrayId, maxArrayId, normalize do2ds.DefaultNormalizeOn() do2ds.SetPointComponent(0, xAxis, 0) do2ds.SetPointComponent(1, yAxis, 0) do2ds.SetPointComponent(2, zAxis, 0) do2ds.Update() rf = vtk.vtkRearrangeFields() rf.SetInputConnection(do2ds.GetOutputPort()) rf.AddOperation("MOVE", scalar, "DATA_OBJECT", "POINT_DATA") rf.RemoveOperation("MOVE", scalar, "DATA_OBJECT", "POINT_DATA") rf.AddOperation("MOVE", scalar, "DATA_OBJECT", "POINT_DATA") rf.RemoveAllOperations() rf.AddOperation("MOVE", scalar, "DATA_OBJECT", "POINT_DATA") rf.Update() max = rf.GetOutput().GetPointData().GetArray(scalar).GetRange(0)[1] calc = vtk.vtkArrayCalculator() calc.SetInputConnection(rf.GetOutputPort()) calc.SetAttributeModeToUsePointData() calc.SetFunction("s / %f" % max) calc.AddScalarVariable("s", scalar, 0) calc.SetResultArrayName("resArray") aa = vtk.vtkAssignAttribute() aa.SetInputConnection(calc.GetOutputPort()) aa.Assign("resArray", "SCALARS", "POINT_DATA") aa.Update() rf2 = vtk.vtkRearrangeFields() rf2.SetInputConnection(aa.GetOutputPort()) rf2.AddOperation("COPY", "SCALARS", "POINT_DATA", "DATA_OBJECT") # construct pipeline for original population popSplatter = vtk.vtkGaussianSplatter() popSplatter.SetInputConnection(rf2.GetOutputPort()) popSplatter.SetSampleDimensions(50, 50, 50) popSplatter.SetRadius(0.05) popSplatter.ScalarWarpingOff() popSurface = vtk.vtkContourFilter() popSurface.SetInputConnection(popSplatter.GetOutputPort()) popSurface.SetValue(0, 0.01) popMapper = vtk.vtkPolyDataMapper() popMapper.SetInputConnection(popSurface.GetOutputPort()) popMapper.ScalarVisibilityOff() popMapper.ImmediateModeRenderingOn() popActor = vtk.vtkActor() popActor.SetMapper(popMapper) popActor.GetProperty().SetOpacity(0.3) popActor.GetProperty().SetColor(.9, .9, .9) # construct pipeline for delinquent population lateSplatter = vtk.vtkGaussianSplatter() lateSplatter.SetInputConnection(aa.GetOutputPort()) lateSplatter.SetSampleDimensions(50, 50, 50) lateSplatter.SetRadius(0.05) lateSplatter.SetScaleFactor(0.05) lateSurface = vtk.vtkContourFilter() lateSurface.SetInputConnection(lateSplatter.GetOutputPort()) lateSurface.SetValue(0, 0.01) lateMapper = vtk.vtkPolyDataMapper() lateMapper.SetInputConnection(lateSurface.GetOutputPort()) lateMapper.ScalarVisibilityOff() lateActor = vtk.vtkActor() lateActor.SetMapper(lateMapper) lateActor.GetProperty().SetColor(1.0, 0.0, 0.0) # create axes popSplatter.Update() bounds = popSplatter.GetOutput().GetBounds() axes = vtk.vtkAxes() axes.SetOrigin(bounds[0], bounds[2], bounds[4]) axes.SetScaleFactor(popSplatter.GetOutput().GetLength() / 5.0) axesTubes = vtk.vtkTubeFilter() axesTubes.SetInputConnection(axes.GetOutputPort()) axesTubes.SetRadius(axes.GetScaleFactor() / 25.0) axesTubes.SetNumberOfSides(6) axesMapper = vtk.vtkPolyDataMapper() axesMapper.SetInputConnection(axesTubes.GetOutputPort()) axesActor = vtk.vtkActor() axesActor.SetMapper(axesMapper) # label the axes XText = vtk.vtkVectorText() XText.SetText(xAxis) XTextMapper = vtk.vtkPolyDataMapper() XTextMapper.SetInputConnection(XText.GetOutputPort()) XActor = vtk.vtkFollower() XActor.SetMapper(XTextMapper) XActor.SetScale(0.02, .02, .02) XActor.SetPosition(0.35, -0.05, -0.05) XActor.GetProperty().SetColor(0, 0, 0) YText = vtk.vtkVectorText() YText.SetText(yAxis) YTextMapper = vtk.vtkPolyDataMapper() YTextMapper.SetInputConnection(YText.GetOutputPort()) YActor = vtk.vtkFollower() YActor.SetMapper(YTextMapper) YActor.SetScale(0.02, .02, .02) YActor.SetPosition(-0.05, 0.35, -0.05) YActor.GetProperty().SetColor(0, 0, 0) ZText = vtk.vtkVectorText() ZText.SetText(zAxis) ZTextMapper = vtk.vtkPolyDataMapper() ZTextMapper.SetInputConnection(ZText.GetOutputPort()) ZActor = vtk.vtkFollower() ZActor.SetMapper(ZTextMapper) ZActor.SetScale(0.02, .02, .02) ZActor.SetPosition(-0.05, -0.05, 0.35) ZActor.GetProperty().SetColor(0, 0, 0) # Graphics stuff # ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) renWin.SetWindowName("vtk(-, Field.Data") renWin.SetSize(300, 300) # Add the actors to the renderer, set the background and size # ren.AddActor(axesActor) ren.AddActor(lateActor) ren.AddActor(XActor) ren.AddActor(YActor) ren.AddActor(ZActor) ren.AddActor(popActor) #it's last because its translucent) ren.SetBackground(1, 1, 1) camera = vtk.vtkCamera() camera.SetClippingRange(.274, 13.72) camera.SetFocalPoint(0.433816, 0.333131, 0.449) camera.SetPosition(-1.96987, 1.15145, 1.49053) camera.SetViewUp(0.378927, 0.911821, 0.158107) ren.SetActiveCamera(camera) XActor.SetCamera(camera) YActor.SetCamera(camera) ZActor.SetCamera(camera) # render and interact with data iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin); renWin.Render() img_file = "financialField3.png" vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25) vtk.test.Testing.interact()
def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._inputPoints = None self._internalPoints = None self._config.radius = 5 self._config.thetaResolution = 8 # minimum 3 self._config.phiResolution = 8 # minimum 3 self._config.numInternalSpheres = 3 configList = [('Sphere radius:', 'radius', 'base:float', 'text', 'The radius of the spheres that will be created ' 'in world coordinate units.'), ('Theta resolution:', 'thetaResolution', 'base:int', 'text', 'Number of points in the longitudinal direction.'), ('Phi resolution:', 'phiResolution', 'base:int', 'text', 'Number of points in the latitudinal direction.'), ('Number of internal spheres:', 'numInternalSpheres', 'base:int', 'text', 'Number of spheres to create in the interior.')] self._appendPolyData = vtk.vtkAppendPolyData() if False: # checked on 20090314: dummy input is very definitely # required # we do need a dummy sphere, else the appender complains dummySphere = vtk.vtkSphereSource() dummySphere.SetRadius(0.0) # and a dummy calc, with -1 index # if we don't add the VolumeIndex array here as well, the append # polydata discards all the others calc = vtk.vtkArrayCalculator() calc.SetAttributeModeToUsePointData() calc.SetFunction('-1') calc.SetResultArrayName('VolumeIndex') calc.SetInput(dummySphere.GetOutput()) self._appendPolyData.AddInput(calc.GetOutput()) else: self._appendPolyData.AddInput(vtk.vtkPolyData()) # this will be a list of lists containing tuples # (vtkArrayCalculator, vtkSphereSource) self._sphereSources = [] # this will hold our shallow-copied output self._output = vtk.vtkPolyData() ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'vtkAppendPolyData' : self._appendPolyData}) self.sync_module_logic_with_config()
def centerline_probe_result(centerline_file,vtk_file_list, output_dir,minPoint=(0,0,0), bifurcationPoint=(0,0,0)): # read centerline centerlineReader = vtk.vtkXMLPolyDataReader() centerlineReader.SetFileName(centerline_file) centerlineReader.Update() centerline = centerlineReader.GetOutput() # read vtk files vtk_files = [] centerlines = [] if not os.path.exists(output_dir): os.makedirs(output_dir) if not os.path.exists(os.path.join(output_dir,"centerlines")): os.makedirs(os.path.join(output_dir,"centerlines")) # average filter averageFilter = vtk.vtkTemporalStatistics() for file_name in vtk_file_list: reader = vtk.vtkUnstructuredGridReader() reader.SetFileName(file_name) reader.Update() geomFilter = vtk.vtkGeometryFilter() geomFilter.SetInputData(reader.GetOutput()) geomFilter.Update() # scale up the CFD result transform = vtk.vtkTransform() transform.Scale(1000,1000,1000) # transformFilter = vtk.vtkTransformPolyDataFilter() transformFilter = vtk.vtkTransformFilter() transformFilter.SetInputData(geomFilter.GetOutput()) transformFilter.SetTransform(transform) transformFilter.Update() vtk_files.append(transformFilter.GetOutput()) interpolator = vtk.vtkPointInterpolator() interpolator.SetSourceData(transformFilter.GetOutput()) interpolator.SetInputData(centerline) interpolator.Update() # convert to desired unit # get the first element pressure try: first_point_pressure = interpolator.GetOutput().GetPointData().GetArray("p").GetValue(0) except: first_point_pressure = 120 converter = vtk.vtkArrayCalculator() converter.SetInputData(interpolator.GetOutput()) converter.AddScalarArrayName("p") converter.SetFunction("120 + (p - {}) * 921 * 0.0075".format(first_point_pressure)) # 921 = mu/nu = density of blood, 0.0075 converts from Pascal to mmHg, offset 120mmHg at ica converter.SetResultArrayName("p(mmHg)") converter.Update() # output the probe centerline centerline_output_path = os.path.join( os.path.dirname(centerline_file), output_dir, "centerlines", "centerline_probe_{}.vtp".format(os.path.split(file_name)[1].split("_")[1].split(".")[0]) ) centerlines.append(converter.GetOutput()) averageFilter.SetInputData(converter.GetOutput()) averageFilter.Update() writer = vtk.vtkXMLPolyDataWriter() writer.SetInputData(converter.GetOutput()) writer.SetFileName(centerline_output_path) writer.Update() centerline_output_path = os.path.join( os.path.dirname(centerline_file), output_dir, "centerlines", "centerline_probe_avg.vtp" ) writer = vtk.vtkXMLPolyDataWriter() writer.SetInputData(averageFilter.GetOutput()) writer.SetFileName(centerline_output_path) writer.Update() # plot result plot_result_path = os.path.join(os.path.dirname(centerline_file),output_dir,"result.png") dev_plot_result_path = os.path.join(os.path.dirname(centerline_file),output_dir,"result_dev.png") plot_array = [ "Radius_average", "U_average", "p(mmHg)_average", "vorticity_average", "Curvature_average", "Torsion_average" ] fit_dict = plot_centerline_result( averageFilter.GetOutput(), ["U_average","p(mmHg)_average"], #["Radius_average","U_average","p(mmHg)_average","vorticity_average","Curvature_average","Torsion_average"], plot_array, plot_result_path, dev_plot_result_path, minPoint = minPoint, bifurcationPoint = bifurcationPoint) # extract ica thresholdFilter = vtk.vtkThreshold() thresholdFilter.ThresholdBetween(0,999) thresholdFilter.SetInputData(averageFilter.GetOutput()) thresholdFilter.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS, "CenterlineIds_average") thresholdFilter.Update() if thresholdFilter.GetOutput().GetNumberOfPoints() == 0 or fit_dict == None: tqdm.write("Centerline file {} does not contain suitable number of CenterlineIds".format(centerline_file)) return_value = { 'radius mean(mm)': "NA", 'max radius gradient':"NA", 'radius min(mm)': "NA", 'pressure mean(mmHg)': "NA", 'max pressure gradient(mmHg)': "NA", 'in/out pressure gradient(mmHg)': "NA", 'velocity mean(ms^-1)': "NA", 'max velocity gradient(ms^-1)': "NA", 'peak velocity(ms^-1)': "NA", 'vorticity mean(s^-1)': "NA", 'peak vorticity(s^-1)': "NA" } else: # compute result values abscissas = vtk_to_numpy(thresholdFilter.GetOutput().GetPointData().GetArray("Abscissas_average")) radius = vtk_to_numpy(thresholdFilter.GetOutput().GetPointData().GetArray("Radius_average")) pressure = vtk_to_numpy(thresholdFilter.GetOutput().GetPointData().GetArray("p(mmHg)_average")) pressure_gradient = np.diff(pressure)/np.diff(abscissas) velocity = vtk_to_numpy(thresholdFilter.GetOutput().GetPointData().GetArray("U_average")) velocity = [math.sqrt(value[0]**2 + value[1]**2 +value[2]**2 ) for value in velocity] vorticity = vtk_to_numpy(thresholdFilter.GetOutput().GetPointData().GetArray("vorticity_average")) vorticity = [math.sqrt(value[0]**2 + value[1]**2 +value[2]**2 ) for value in vorticity] return_value = { 'radius mean(mm)': np.mean(radius), 'radius min(mm)': np.min(radius), 'max radius gradient': fit_dict["Radius_average"], 'pressure mean(mmHg)': np.mean(pressure), # 'max pressure gradient(mmHg)': np.mean(heapq.nlargest(5, pressure_gradient)), 'max pressure gradient(mmHg)': fit_dict["p(mmHg)_average"], 'in/out pressure gradient(mmHg)': np.mean(pressure[0:5]) - np.mean(pressure[-5:]), 'velocity mean(ms^-1)': np.mean(velocity), 'peak velocity(ms^-1)': np.mean(heapq.nlargest(5, velocity)), 'max velocity gradient(ms^-1)': fit_dict["U_average"], 'vorticity mean(s^-1)': np.mean(vorticity), 'peak vorticity(s^-1)': np.mean(heapq.nlargest(5, vorticity)) } # moving variance matrix mv_fields = [ "Radius_average", "U_average", "p(mmHg)_average", "vorticity_average", "Curvature_average", "Torsion_average" ] mv_windows = np.arange(3,10,2) plot_result_path = os.path.join(os.path.dirname(centerline_file),output_dir,"moving_variance.png") dev_plot_result_path = os.path.join(os.path.dirname(centerline_file),output_dir,"moving_variance_dev.png") mv_matrix_df, mv_dy_matrix_df = moving_variance_matrix(averageFilter.GetOutput(),mv_fields,mv_windows, minPoint = minPoint, bifurcationPoint = bifurcationPoint, result_path = plot_result_path, dev_result_path=dev_plot_result_path) return return_value, mv_matrix_df, mv_dy_matrix_df
def execute(self, obj, event): if self.timer_count == 10: self.timer_count = 0 warpVector = vtk.vtkWarpVector() warpVector.SetInputData(pd) warpVector.SetScaleFactor(0.1 * (self.timer_count + 1)) warpVector.Update() poly = warpVector.GetPolyDataOutput() getScalars = vtk.vtkExtractVectorComponents() getScalars.SetInputData(poly) getScalars.Update() vectorNorm = vtk.vtkVectorNorm() vectorNorm.SetInputData(poly) vectorNorm.Update() scalars = [] scalars.append( getScalars.GetVzComponent()) scalars.append( vectorNorm.GetOutput()) scalars.append( getScalars.GetVxComponent()) scalars.append( getScalars.GetVyComponent()) names = ("Z", "Mag", "X", "Y") for k, a in enumerate(self.actors): calc = vtk.vtkArrayCalculator() scalars[k].GetPointData().GetScalars().SetName(names[k]) calc.SetInputData(scalars[k]) calc.AddScalarArrayName(names[k]) calc.SetResultArrayName(names[k]) calc.SetFunction( "%s * 0.1 * %f" % (names[k], self.timer_count + 1)) calc.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(calc.GetOutput()) mapper.SetScalarRange(calc.GetOutput().GetScalarRange()) mapper.SetScalarModeToUsePointData() mapper.SetColorModeToMapScalars() mapper.Update() a.SetMapper(mapper) cb.scalar_bars[k].SetLookupTable(mapper.GetLookupTable()) iren = obj iren.GetRenderWindow().Render() time.sleep(0.3) if self.key == "Up": try: os.mkdir(self.directory) except: pass w2i = vtk.vtkWindowToImageFilter() w2i.SetInput(obj.GetRenderWindow()) w2i.Update() png = vtk.vtkPNGWriter() png.SetInputConnection(w2i.GetOutputPort()) png.SetFileName(self.directory + os.sep + "frame{:d}.png".format(self.timer_count)) png.Update() png.Write() self.timer_count += 1
# create a rendering window and renderer ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) renWin.StereoCapableWindowOn() iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) reader = vtk.vtkGenericEnSightReader() reader.SetCaseFileName("" + str(VTK_DATA_ROOT) + "/Data/EnSight/elements6-bin.case") reader.UpdateInformation() reader.GetOutputInformation(0).Set( vtk.vtkStreamingDemandDrivenPipeline.UPDATE_TIME_STEP(), 0.1) geom = vtk.vtkGeometryFilter() geom.SetInputConnection(reader.GetOutputPort()) calc = vtk.vtkArrayCalculator() calc.SetInputConnection(geom.GetOutputPort()) calc.SetAttributeModeToUsePointData() calc.SetFunction("pointTensors_XZ - pointTensors_YZ") calc.AddScalarVariable("pointTensors_XZ", "pointTensors", 5) calc.AddScalarVariable("pointTensors_YZ", "pointTensors", 4) calc.SetResultArrayName("test") mapper = vtk.vtkHierarchicalPolyDataMapper() mapper.SetInputConnection(calc.GetOutputPort()) mapper.SetColorModeToMapScalars() mapper.SetScalarModeToUsePointFieldData() mapper.ColorByArrayComponent("test", 0) mapper.SetScalarRange(-0.1, 0.1) actor = vtk.vtkActor() actor.SetMapper(mapper) # assign our actor to the renderer
def arrayCompare(self): if not self.ArrayName: self.PrintError('Error: No ArrayName.') attributeData = None referenceAttributeData = None calculator = vtk.vtkArrayCalculator() if self.Method in ['addpointarray','projection']: attributeData = self.Surface.GetPointData() referenceAttributeData = self.ReferenceSurface.GetPointData() calculator.SetAttributeModeToUsePointData() elif self.Method in ['addcellarray']: attributeData = self.Surface.GetCellData() referenceAttributeData = self.ReferenceSurface.GetCellData() calculator.SetAttributeModeToUseCellData() if not attributeData.GetArray(self.ArrayName): self.PrintError('Error: Invalid ArrayName.') if not referenceAttributeData.GetArray(self.ArrayName): self.PrintError('Error: Invalid ArrayName.') referenceArrayName = 'Ref' + self.ArrayName surfacePoints = self.Surface.GetNumberOfPoints() referencePoints = self.ReferenceSurface.GetNumberOfPoints() pointsDifference = surfacePoints - referencePoints if self.Method in ['addpointarray','addcellarray']: if abs(pointsDifference) > 0: self.ResultLog = 'Uneven NumberOfPoints' return False refArray = referenceAttributeData.GetArray(self.ArrayName) refArray.SetName(referenceArrayName) attributeData.AddArray(refArray) calculator.SetInput(self.Surface) elif self.Method in ['projection']: referenceAttributeData.GetArray(self.ArrayName).SetName(referenceArrayName) projection = vmtkscripts.vmtkSurfaceProjection() projection.Surface = self.Surface projection.ReferenceSurface = self.ReferenceSurface projection.Execute() calculator.SetInput(projection.Surface) calculator.AddScalarVariable('a',self.ArrayName,0) calculator.AddScalarVariable('b',referenceArrayName,0) calculator.SetFunction("a - b") calculator.SetResultArrayName('ResultArray') calculator.Update() self.ResultData = calculator.GetOutput() if self.Method in ['addpointarray','projection']: resultRange = self.ResultData.GetPointData().GetArray('ResultArray').GetRange() elif self.Method in ['addcellarray']: resultRange = self.ResultData.GetCellData().GetArray('ResultArray').GetRange() self.PrintLog('Result Range: ' + str(resultRange)) if max([abs(r) for r in resultRange]) < self.Tolerance: return True return False
def execute(self, obj, event): if self.timer_count == 10: self.timer_count = 0 warpVector = vtk.vtkWarpVector() warpVector.SetInputData(pd) warpVector.SetScaleFactor(0.1 * (self.timer_count + 1)) warpVector.Update() poly = warpVector.GetPolyDataOutput() getScalars = vtk.vtkExtractVectorComponents() getScalars.SetInputData(poly) getScalars.Update() vectorNorm = vtk.vtkVectorNorm() vectorNorm.SetInputData(poly) vectorNorm.Update() scalars = [] scalars.append(getScalars.GetVzComponent()) scalars.append(vectorNorm.GetOutput()) scalars.append(getScalars.GetVxComponent()) scalars.append(getScalars.GetVyComponent()) names = ("Z", "Mag", "X", "Y") for k, a in enumerate(self.actors): calc = vtk.vtkArrayCalculator() scalars[k].GetPointData().GetScalars().SetName(names[k]) calc.SetInputData(scalars[k]) calc.AddScalarArrayName(names[k]) calc.SetResultArrayName(names[k]) calc.SetFunction("%s * 0.1 * %f" % (names[k], self.timer_count + 1)) calc.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(calc.GetOutput()) mapper.SetScalarRange(calc.GetOutput().GetScalarRange()) mapper.SetScalarModeToUsePointData() mapper.SetColorModeToMapScalars() mapper.Update() a.SetMapper(mapper) cb.scalar_bars[k].SetLookupTable(mapper.GetLookupTable()) iren = obj iren.GetRenderWindow().Render() time.sleep(0.3) if self.key == "Up": try: os.mkdir(self.directory) except: pass w2i = vtk.vtkWindowToImageFilter() w2i.SetInput(obj.GetRenderWindow()) w2i.Update() png = vtk.vtkPNGWriter() png.SetInputConnection(w2i.GetOutputPort()) png.SetFileName(self.directory + os.sep + "frame{:d}.png".format(self.timer_count)) png.Update() png.Write() self.timer_count += 1
renderer.AddActor(outlineActor) renderer.AddActor(gridGeomActor) renderer.SetBackground(1, 1, 1) renderer.ResetCamera() renderer.GetActiveCamera().Elevation(60.0) renderer.GetActiveCamera().Azimuth(30.0) renderer.GetActiveCamera().Zoom(1.0) renWin.SetSize(300, 300) # interact with data renWin.Render() iren.Start() magnitudeCalcFilter = vtk.vtkArrayCalculator() magnitudeCalcFilter.SetInputConnection(rectGridReader.GetOutputPort()) magnitudeCalcFilter.AddVectorArrayName('vectors') # Set up here the array that is going to be used for the computation ('vectors') magnitudeCalcFilter.SetResultArrayName('magnitude') #Se agrega esta linea para usar la funcion mag (magitute) magnitudeCalcFilter.SetFunction("mag(vectors)") # Set up here the function that calculates the magnitude of a vector magnitudeCalcFilter.Update() #Extract the data from the result of the vtkCalculator points = vtk.vtkPoints() grid = magnitudeCalcFilter.GetOutput() grid.GetPoints(points) scalars = grid.GetPointData().GetArray('magnitude')
def extract_profiles_vtk(name): gridreader = vtk.vtkXMLStructuredGridReader() gridreader.SetFileName(name) gridreader.Update() grid = gridreader.GetOutput() data = grid.GetPointData() points = grid.GetPoints() dims = grid.GetDimensions() velocity = data.GetArray("Velocity") phase = data.GetArray("Phase") #data.SetActiveScalars("Phase") phase_image = vtk.vtkImageData() phase_image.SetSpacing(1.0, 1.0, 1.0) phase_image.SetOrigin(0.0, 0.0, 0.0) phase_image.SetDimensions(dims[0], dims[1], dims[2]) phase_image.GetPointData().SetScalars(phase) phase_image.GetPointData().SetVectors(velocity) extract = vtk.vtkExtractVOI() extract.SetInput(phase_image) extract.SetVOI(0, 0, 0, dims[1] - 1, 0, dims[2] - 1) extract.Update() #Create a contour #contour=vtk.vtkOutlineFilter() contour = vtk.vtkContourFilter() contour.SetInputConnection(extract.GetOutputPort()) #contour.SetInput(phase_image) contour.SetValue(0, 0.0) contour.Update() #cont_points=contour.GetOutput().GetPoints() probe = vtk.vtkProbeFilter() probe.SetInputConnection(contour.GetOutputPort()) probe.SetSource(extract.GetOutput()) probe.Update() filt_points = vtk.vtkMaskPoints() filt_points.SetInputConnection(probe.GetOutputPort()) #filt_points.SetMaximumNumberOfPoints(200) #filt_points.SetRandomMode(1) filt_points.SetOnRatio(10) arrow = vtk.vtkArrowSource() glyph = vtk.vtkGlyph3D() glyph.SetInputConnection(filt_points.GetOutputPort()) glyph.SetSourceConnection(arrow.GetOutputPort()) glyph.SetVectorModeToUseVector() glyph.SetScaleModeToScaleByVector() glyph.SetScaleFactor(400.0) glyphMapper = vtk.vtkPolyDataMapper() glyphMapper.SetInputConnection(glyph.GetOutputPort()) glyphActor = vtk.vtkActor() glyphActor.SetMapper(glyphMapper) glyphActor.GetProperty().SetColor(0.1, 0.5, 0.2) print glyphActor.GetProperty().GetColor() #print "Probe=", probe.GetOutput() calc = vtk.vtkArrayCalculator() calc.SetInput(probe.GetOutput()) #calc.AddVectorArrayName("Velocity",1,1,1) calc.AddScalarVariable("Vz", "Velocity", 2) calc.SetResultArrayName("Velocity comp 2") calc.SetFunction("Vz") #calc.SetResultArrayName("Velocity Magnitude") #calc.SetFunction("mag(Velocity)") calc.Update() print calc.GetOutput() xyplot = vtk.vtkXYPlotActor() vel = probe.GetOutput().GetPointData().GetArray("Velocity") #exam=vtk.vtkDoubleArray() #vel.GetData(0,vel.GetNumberOfTuples()-1,2,2,exam) xyplot.AddInput(calc.GetOutput()) #xyplot.GetPositionCoordinate().SetValue(0.0, 0.67, 0) #xyplot.GetPosition2Coordinate().SetValue(1.0, 0.33, 0) #relative to Position xyplot.SetXValuesToArcLength() #xyplot.SetNumberOfXLabels(6) #xyplot.SetTitle("Pressure vs. Arc Length (Zoomed View)") #xyplot.SetXTitle("") #xyplot.SetYTitle("P") #xyplot.SetXRange(.1, .35) #xyplot.SetYRange(.2, .4) xyplot.GetProperty().SetColor(0, 0, 0) xyplot.GetProperty().SetLineWidth(2) # Set text prop color (same color for backward compat with test) # Assign same object to all text props tprop = xyplot.GetTitleTextProperty() tprop.SetColor(xyplot.GetProperty().GetColor()) xyplot.SetAxisTitleTextProperty(tprop) xyplot.SetAxisLabelTextProperty(tprop) #glyph=vtk.vtkGlyph3D() #glyph.SetInput(contour.GetOutput()) contourMapper = vtk.vtkPolyDataMapper() #contourMapper.SetScalarRange(phase.GetRange()) contourMapper.SetInputConnection(contour.GetOutputPort()) sliceMapper = vtk.vtkImageMapper() #sliceMapper = vtk.vtkDataSetMapper() sliceMapper.SetInput(extract.GetOutput()) sliceMapper.SetColorLevel(1000) sliceMapper.SetColorWindow(2000) #sliceMapper.SetColorModeToMapScalars() #print polydata.GetClassName() contourActor = vtk.vtkActor() contourActor.SetMapper(contourMapper) sliceActor = vtk.vtkActor2D() sliceActor.SetMapper(sliceMapper) ren = vtk.vtkRenderer() #ren.AddActor(contourActor) ren.AddActor2D(sliceActor) #ren.AddActor(glyphActor) ren.SetBackground(0.1, 0.2, 0.4) #ren.SetColor(0.1,0.5,0.2) #ren.SetViewport(0, 0, .3, 1) ren2 = vtk.vtkRenderer() ren2.SetBackground(1, 1, 1) ren2.SetViewport(0.3, 0.0, 1.0, 1.0) ren2.AddActor2D(xyplot) renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) #renWin.AddRenderer(ren2) renWin.SetSize(500, 500) #win=vtk.vtkWindowToImageFilter() #win.SetInput(renWin) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) iren.Initialize() renWin.Render() iren.Start()