def qualityCompare(self): meshQuality = vtk.vtkMeshQuality() meshQuality.SetInputData(self.Mesh) meshQuality.RatioOn() meshQuality.Update() meshQualityOutput = meshQuality.GetOutput() referenceQuality = vtk.vtkMeshQuality() referenceQuality.SetInputData(self.ReferenceMesh) referenceQuality.RatioOn() referenceQuality.Update() referenceQualityOutput = referenceQuality.GetOutput() self.PrintLog("Mesh points: " + str(meshQualityOutput.GetNumberOfPoints())) self.PrintLog("Reference Points: " + str(referenceQualityOutput.GetNumberOfPoints())) meshQualityRange = meshQualityOutput.GetCellData().GetArray("Quality").GetRange() referenceQualityRange = referenceQualityOutput.GetCellData().GetArray("Quality").GetRange() qualityRangeDifference = ( meshQualityRange[0] - referenceQualityRange[0], meshQualityRange[1] - referenceQualityRange[1], ) self.PrintLog("Mesh Quality Range: " + str(meshQualityRange)) self.PrintLog("Reference Quality Range: " + str(referenceQualityRange)) self.PrintLog("Quality Range Difference: " + str(qualityRangeDifference)) if max(abs(d) for d in qualityRangeDifference) < self.Tolerance: return True return False
def qualityCompare(self): meshQuality = vtk.vtkMeshQuality() meshQuality.SetInputData(self.Mesh) meshQuality.RatioOn() meshQuality.Update() meshQualityOutput = meshQuality.GetOutput() referenceQuality = vtk.vtkMeshQuality() referenceQuality.SetInputData(self.ReferenceMesh) referenceQuality.RatioOn() referenceQuality.Update() referenceQualityOutput = referenceQuality.GetOutput() self.PrintLog("Mesh points: "+ str(meshQualityOutput.GetNumberOfPoints())) self.PrintLog("Reference Points: " +str(referenceQualityOutput.GetNumberOfPoints())) meshQualityRange = meshQualityOutput.GetCellData().GetArray("Quality").GetRange() referenceQualityRange = referenceQualityOutput.GetCellData().GetArray("Quality").GetRange() qualityRangeDifference = (meshQualityRange[0] - referenceQualityRange[0],meshQualityRange[1] - referenceQualityRange[1]) self.PrintLog("Mesh Quality Range: "+ str(meshQualityRange)) self.PrintLog("Reference Quality Range: "+ str(referenceQualityRange)) self.PrintLog("Quality Range Difference: "+ str(qualityRangeDifference)) if max(abs(d) for d in qualityRangeDifference) < self.Tolerance: return True return False
def computePolyQualityMinAngle(polydata): ''' Returns [ min, average, max, variance, number of cells ] of Minmum included Angleof the polydata's triangles. Acceptable range = [30°,60°] for equilateral unit triangle = 60° reference: Verdict reference manual, Stimpson, 2007 ''' qual = vtk.vtkMeshQuality() qual.SetInput(polydata) qual.VolumeOn() qual.RatioOn() qual.SetTriangleQualityMeasureToMinAngle() qual.Update() return [ qual.GetOutput().GetFieldData().GetArray( "Mesh Triangle Quality").GetValue(0), qual.GetOutput().GetFieldData().GetArray( "Mesh Triangle Quality").GetValue(1), qual.GetOutput().GetFieldData().GetArray( "Mesh Triangle Quality").GetValue(2), qual.GetOutput().GetFieldData().GetArray( "Mesh Triangle Quality").GetValue(3), qual.GetOutput().GetFieldData().GetArray( "Mesh Triangle Quality").GetValue(4) ]
def computePolyQualityAspectFrobenius(polydata): ''' Returns [ min, average, max, variance, number of cells ] of Aspect Frobenius of the polydata's triangles. Aspect Frobenius is defined as q = ( ||L0||^2+||L1||^2+||L2||^2 ) / ( 4*Area*sqrt(3) ) Acceptable range = [1,1.3] for equilateral unit triangle = 1 reference: Verdict reference manual, Stimpson, 2007 ''' qual = vtk.vtkMeshQuality() qual.SetInput(polydata) qual.VolumeOn() qual.RatioOn() qual.SetTriangleQualityMeasureToAspectFrobenius() qual.Update() return [ qual.GetOutput().GetFieldData().GetArray( "Mesh Triangle Quality").GetValue(0), qual.GetOutput().GetFieldData().GetArray( "Mesh Triangle Quality").GetValue(1), qual.GetOutput().GetFieldData().GetArray( "Mesh Triangle Quality").GetValue(2), qual.GetOutput().GetFieldData().GetArray( "Mesh Triangle Quality").GetValue(3), qual.GetOutput().GetFieldData().GetArray( "Mesh Triangle Quality").GetValue(4) ]
def computePolyQualityRadiusRatio(polydata): ''' Returns [ min, average, max, variance, number of cells ] of Radius Ratio of the polydata's triangles. Radius ratio is defined as q = ( R ) / ( 2r ) where R = circumradius ( = L0*L1*L2 / ( 2*r*(L0+L1+L2) ) ) and r = inradius ( r = 2*Area/(L0+L1+L2) ) Acceptable range = [1,1.3] for equilateral unit triangle = 1 reference: Verdict reference manual, Stimpson, 2007 ''' qual = vtk.vtkMeshQuality() qual.SetInput(polydata) qual.VolumeOn() qual.RatioOn() qual.SetTriangleQualityMeasureToRadiusRatio() qual.Update() return [ qual.GetOutput().GetFieldData().GetArray( "Mesh Triangle Quality").GetValue(0), qual.GetOutput().GetFieldData().GetArray( "Mesh Triangle Quality").GetValue(1), qual.GetOutput().GetFieldData().GetArray( "Mesh Triangle Quality").GetValue(2), qual.GetOutput().GetFieldData().GetArray( "Mesh Triangle Quality").GetValue(3), qual.GetOutput().GetFieldData().GetArray( "Mesh Triangle Quality").GetValue(4) ]
def computePolyQualityAspectRatio(polydata): ''' Returns [ min, average, max, variance, number of cells ] of aspect ratio of the polydata's triangles. Aspect Ratio is defined as q = Lmax / ( 2 * sqrt(3) * r ) = Lmax*(L0+L1+L2) / (4*sqrt(3)*Area) where Lmax = largest edge and r = inradius ( r = 2*Area/(L0+L1+L2) ) Acceptable range = [1,1.3] for equilateral unit triangle = 1 reference: Verdict reference manual, Stimpson, 2007 ''' qual = vtk.vtkMeshQuality() qual.SetInput(polydata) qual.VolumeOn() qual.RatioOn() qual.SetTriangleQualityMeasureToAspectRatio() qual.Update() return [ qual.GetOutput().GetFieldData().GetArray( "Mesh Triangle Quality").GetValue(1), qual.GetOutput().GetFieldData().GetArray( "Mesh Triangle Quality").GetValue(2), 0, qual.GetOutput().GetFieldData().GetArray( "Mesh Triangle Quality").GetValue(3), qual.GetOutput().GetFieldData().GetArray( "Mesh Triangle Quality").GetValue(4) ]
def computePolyQualityEdgeRatio(polydata): ''' Returns [ min, average, max, variance, number of cells ] of edge ratio of the polydata's triangles. Edge Ratio is defined as q = Lmax / Lmin where Lmax = largest edge Lmin = smallest edge Acceptable range = [1,1.3] for equilateral unit triangle = 1 reference: Verdict reference manual, Stimpson, 2007 ''' qual = vtk.vtkMeshQuality() qual.SetInput(polydata) qual.VolumeOn() qual.RatioOn() qual.SetTriangleQualityMeasureToAspectRatio() qual.Update() return [ qual.GetOutput().GetFieldData().GetArray( "Mesh Triangle Quality").GetValue(0), qual.GetOutput().GetFieldData().GetArray( "Mesh Triangle Quality").GetValue(1), qual.GetOutput().GetFieldData().GetArray( "Mesh Triangle Quality").GetValue(2), qual.GetOutput().GetFieldData().GetArray( "Mesh Triangle Quality").GetValue(3), qual.GetOutput().GetFieldData().GetArray( "Mesh Triangle Quality").GetValue(4) ]
def test_linear_copy_surf_elem(): cells = np.array([8, 0, 1, 2, 3, 4, 5, 6, 7, 6, 8, 9, 10, 11, 12, 13], np.int32) celltypes = np.array([vtk.VTK_QUADRATIC_QUAD, vtk.VTK_QUADRATIC_TRIANGLE], np.uint8) cell0 = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.5, 0.1, 0.0], [1.1, 0.5, 0.0], [0.5, 0.9, 0.0], [0.1, 0.5, 0.0]] cell1 = [[0.0, 0.0, 1.0], [1.0, 0.0, 1.0], [0.5, 0.5, 1.0], [0.5, 0.0, 1.3], [0.7, 0.7, 1.3], [0.1, 0.1, 1.3]] points = np.vstack((cell0, cell1)) if VTK9: grid = pyvista.UnstructuredGrid(cells, celltypes, points, deep=False) else: offset = np.array([0, 9]) grid = pyvista.UnstructuredGrid(offset, cells, celltypes, points, deep=False) lgrid = grid.linear_copy() qfilter = vtk.vtkMeshQuality() qfilter.SetInputData(lgrid) qfilter.Update() qual = pyvista.wrap(qfilter.GetOutput())['Quality'] assert np.allclose(qual, [1, 1.4], atol=0.01)
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkMeshQuality(), 'Processing.', ('vtkDataSet',), ('vtkDataSet',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def __init__(self, parent=None): super(VTKFrame, self).__init__(parent) self.vtkWidget = QVTKRenderWindowInteractor(self) vl = QtGui.QVBoxLayout(self) vl.addWidget(self.vtkWidget) vl.setContentsMargins(0, 0, 0, 0) self.ren = vtk.vtkRenderer() self.ren.SetBackground(0.1, 0.2, 0.4) self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() # Create source source = vtk.vtkSphereSource() source.Update() triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInputConnection(source.GetOutputPort()) triangleFilter.Update() # Create a mapper and actor sphereMapper = vtk.vtkDataSetMapper() sphereMapper.SetInputConnection(triangleFilter.GetOutputPort()) sphereActor = vtk.vtkActor() sphereActor.SetMapper(sphereMapper) mesh = triangleFilter.GetOutput() qualityFilter = vtk.vtkMeshQuality() qualityFilter.SetInput(mesh) qualityFilter.SetTriangleQualityMeasureToArea() qualityFilter.Update() qualityMesh = qualityFilter.GetOutput() #qualityArray = vtk.vtkDoubleArray.SafeDownCase(qualityMesh.GetCellData().GetArray("Quality")) selectCells = vtk.vtkThreshold() selectCells.ThresholdByLower(0.02) selectCells.SetInputArrayToProcess( 0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS, vtk.vtkDataSetAttributes.SCALARS) selectCells.SetInput(qualityMesh) selectCells.Update() ug = selectCells.GetOutput() # Create a mapper and actor mapper = vtk.vtkDataSetMapper() mapper.SetInput(ug) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(1, 0, 0) actor.GetProperty().SetRepresentationToWireframe() actor.GetProperty().SetLineWidth(5) self.ren.AddActor(sphereActor) self.ren.AddActor(actor) self.ren.ResetCamera() self._initialized = False
def computeTriangleQualityMinAngle(vtkCell): ''' Returns [ min, average, max, variance, number of cells ] of Minmum included Angleof the polydata's triangles. Acceptable range = [30°,60°] for equilateral unit triangle = 60° reference: Verdict reference manual, Stimpson, 2007 ''' qual = vtk.vtkMeshQuality() return qual.TriangleMinAngle(vtkCell)
def computeTriangleQualityAspectFrobenius(vtkCell): ''' Returns [ min, average, max, variance, number of cells ] of Aspect Frobenius of the polydata's triangles. Aspect Frobenius is defined as q = ( ||L0||^2+||L1||^2+||L2||^2 ) / ( 4*Area*sqrt(3) ) Acceptable range = [1,1.3] for equilateral unit triangle = 1 reference: Verdict reference manual, Stimpson, 2007 ''' qual = vtk.vtkMeshQuality() return qual.TriangleAspectFrobenius(vtkCell)
def compute_cells_area(m): """ numpy array with cells area """ areaf = vtk.vtkMeshQuality() areaf.SetInputData(m) areaf.SetTriangleQualityMeasureToArea() areaf.SaveCellQualityOn() ##default: quality is stored as cell data areaf.Update() vtk_x = areaf.GetOutput().GetCellData().GetArray("Quality") np_x = nps.vtk_to_numpy(vtk_x) return np_x
def _getElementMetrics(self): for k, p in self.polydatas.items(): # create a deformed polydata object for deformed metrics warp = vtk.vtkWarpVector() warp.SetInputData(p) warp.SetScaleFactor(1) p.GetPointData().SetActiveVectors('displacement') warp.Update() warped = warp.GetOutput() # Use the MeshQuality filter with the metric set to volume to quickly get cell volumes # for reference and deformed cases. mesh_quality = vtk.vtkMeshQuality() mesh_quality.SetTetQualityMeasureToVolume() mesh_quality.SetInputData(p) mesh_quality.Update() r_volumes = mesh_quality.GetOutput().GetCellData().GetArray("Quality") r_volumes.SetName('Reference Volume') p.GetCellData().AddArray(r_volumes) mesh_quality2 = vtk.vtkMeshQuality() mesh_quality2.SetTetQualityMeasureToVolume() mesh_quality2.SetInputData(warped) mesh_quality2.Update() d_volumes = mesh_quality2.GetOutput().GetCellData().GetArray("Quality") d_volumes.SetName('Deformed Volume') p.GetCellData().AddArray(d_volumes) # CellCenters filter generates new polydata with points at centroids. Grab these points # data array and add it to polydata for reference and deformed. cell_centers = vtk.vtkCellCenters() cell_centers.VertexCellsOff() cell_centers.SetInputData(p) cell_centers.Update() r_centroids = cell_centers.GetOutput().GetPoints().GetData() r_centroids.SetName('Reference Centroid') p.GetCellData().AddArray(r_centroids) cell_centers2 = vtk.vtkCellCenters() cell_centers2.VertexCellsOff() cell_centers2.SetInputData(warped) cell_centers2.Update() d_centroids = cell_centers2.GetOutput().GetPoints().GetData() d_centroids.SetName('Deformed Centroid') p.GetCellData().AddArray(d_centroids)
def calculate_area(mesh): quality = vtk.vtkMeshQuality() quality.SetInputData(mesh) quality.SetTriangleQualityMeasureToArea() quality.Update() area = quality.GetOutput().GetCellData().GetArray("Quality") result = np.array( [area.GetValue(i) for i in range(area.GetNumberOfTuples())]) return result
def computeTriangleQualityRadiusRatio(vtkCell): ''' Returns [ min, average, max, variance, number of cells ] of Radius Ratio of the polydata's triangles. Radius ratio is defined as q = ( R ) / ( 2r ) where R = circumradius ( = L0*L1*L2 / ( 2*r*(L0+L1+L2) ) ) and r = inradius ( r = 2*Area/(L0+L1+L2) ) Acceptable range = [1,1.3] for equilateral unit triangle = 1 reference: Verdict reference manual, Stimpson, 2007 ''' qual = vtk.vtkMeshQuality() return qual.TriangleRadiusRatio(vtkCell)
def computeTriangleQualityEdgeRatio(vtkCell): ''' Returns edge ratio of the triangular cell. Edge Ratio is defined as q = Lmax / Lmin where Lmax = largest edge Lmin = smallest edge Acceptable range = [1,1.3] for equilateral unit triangle = 1 reference: Verdict reference manual, Stimpson, 2007 ''' qual = vtk.vtkMeshQuality() return qual.TriangleEdgeRatio(vtkCell)
def computeTriangleQualityAspectRatio(vtkCell): ''' Returns aspect ratio of the triangle. Aspect Ratio is defined as q = Lmax / ( 2 * sqrt(3) * r ) = Lmax*(L0+L1+L2) / (4*sqrt(3)*Area) where Lmax = largest edge and r = inradius ( r = 2*Area/(L0+L1+L2) ) Acceptable range = [1,1.3] for equilateral unit triangle = 1 reference: Verdict reference manual, Stimpson, 2007 ''' qual = vtk.vtkMeshQuality() return qual.TriangleAspectRatio(vtkCell)
def __init__(self, img, threshold, xysmoothing, zsmoothing, color, alpha): dataImporter = vtk.vtkImageImport() simg = np.ascontiguousarray(img, np.uint8) dataImporter.CopyImportVoidPointer(simg.data, len(simg.data)) dataImporter.SetDataScalarTypeToUnsignedChar() dataImporter.SetNumberOfScalarComponents(1) dataImporter.SetDataExtent(0, simg.shape[2]-1, 0, simg.shape[1]-1, 0, simg.shape[0]-1) dataImporter.SetWholeExtent(0, simg.shape[2]-1, 0, simg.shape[1]-1, 0, simg.shape[0]-1) self.__smoother = vtk.vtkImageGaussianSmooth() self.__smoother.SetStandardDeviation(xysmoothing, xysmoothing, zsmoothing) self.__smoother.SetInputConnection(dataImporter.GetOutputPort()) self.__threshold = vtk.vtkImageThreshold() self.__threshold.SetInputConnection(self.__smoother.GetOutputPort()) self.__threshold.ThresholdByUpper(threshold) self.__threshold.ReplaceInOn() self.__threshold.SetInValue(1) self.__threshold.ReplaceOutOn() self.__threshold.SetOutValue(0) self.__threshold.Update() contour = vtk.vtkDiscreteMarchingCubes() contour.SetInputConnection(self.__threshold.GetOutputPort()) contour.ComputeNormalsOn() contour.SetValue(0, 1) contour.Update() smoother = vtk.vtkWindowedSincPolyDataFilter() smoother.SetInputConnection(contour.GetOutputPort()) smoother.NonManifoldSmoothingOn() smoother.NormalizeCoordinatesOn() smoother.Update() triangleCellNormals=vtk.vtkPolyDataNormals() triangleCellNormals.SetInputConnection(smoother.GetOutputPort()) triangleCellNormals.ComputeCellNormalsOn() triangleCellNormals.ComputePointNormalsOff() triangleCellNormals.ConsistencyOn() triangleCellNormals.AutoOrientNormalsOn() triangleCellNormals.Update() triangleCellAn = vtk.vtkMeshQuality() triangleCellAn.SetInputConnection(triangleCellNormals.GetOutputPort()) triangleCellAn.SetTriangleQualityMeasureToArea() triangleCellAn.SaveCellQualityOn() triangleCellAn.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(triangleCellAn.GetOutputPort()) mapper.ScalarVisibilityOn() mapper.SetScalarRange(.3, 1) mapper.SetScalarModeToUsePointData() colorLookupTable = vtk.vtkLookupTable() colorLookupTable.SetHueRange(.6, 1) colorLookupTable.Build() mapper.SetLookupTable(colorLookupTable) self.SetMapper(mapper) self.GetProperty().SetColor(*color) self.GetProperty().SetOpacity(alpha)
def minimal_length(patchData): """ Compute minimal length as sqrt of smallest area on a patch. """ areaFilter = vtk.vtkMeshQuality() areaFilter.SetInputData(patchData) areaFilter.SetTriangleQualityMeasureToArea() areaFilter.SetQuadQualityMeasureToArea() areaFilter.Update() area = dsa.WrapDataObject(areaFilter.GetOutput()) area = area.CellData["Quality"] return np.sqrt(np.min(area))
def test_2D(self): self.tube.make_2D(self.h / 2) v1 = self.tube.element_volumes() writer = writers.VTKWriter(self.tube, "dummy.vtk") obj = writer.make_vtk_object() meshQuality = vtk.vtkMeshQuality() meshQuality.SetInputData(obj) meshQuality.SetQuadQualityMeasureToArea() meshQuality.Update() res = meshQuality.GetOutput() vols = vtk_to_numpy(res.GetCellData().GetArray("Quality")) * self.h self.assertTrue(np.allclose(v1, vols, rtol=1e-4))
def test_3D(self): v1 = self.tube.element_volumes() writer = writers.VTKWriter(self.tube, "dummy.vtk") obj = writer.make_vtk_object() meshQuality = vtk.vtkMeshQuality() meshQuality.SetInputData(obj) meshQuality.SetHexQualityMeasureToVolume() meshQuality.Update() res = meshQuality.GetOutput() vols = vtk_to_numpy(res.GetCellData().GetArray("Quality")) err = np.abs(v1 - vols) / np.abs(vols) self.assertTrue(np.allclose(v1, vols, rtol=1e-4))
def compute_vtk_volume(data_vtu_in, method="vtk"): volume = 0 if method == "vtk": quality = vtk.vtkMeshQuality() for cell_id in range(data_vtu_in.GetNumberOfCells()): cell_curr = data_vtu_in.GetCell(cell_id) vol_curr = quality.TetVolume(cell_curr) volume = volume + vol_curr elif method == "abaqus": if data_vtu_in.GetCellData().HasArray("EVOL"): cell_volume_array = data_vtu_in.GetCellData().GetArray("EVOL") for cell_id in range(cell_volume_array.GetNumberOfTuples()): vol_curr = cell_volume_array.GetValue(cell_id) volume = volume + vol_curr print("Volume from '%s': %f" % (method, volume)) return volume
def generateMeshPolyData(points): pts = v.vtkPoints() for p in points: pts.InsertNextPoint(p) pd = v.vtkPolyData() pd.SetPoints(pts) # Create a IdFilter to preserve original point ids idf = v.vtkIdFilter() idf.SetIdsArrayName('origIds') idf.PointIdsOn() idf.SetInputData(pd) # Create a 2D Delaunay triangulation d2d = v.vtkDelaunay2D() d2d.SetInputConnection(idf.GetOutputPort()) # Create mesh quality cell data array to filter out # boundary triangles mq = v.vtkMeshQuality() mq.SetInputConnection(d2d.GetOutputPort()) mq.SetTriangleQualityMeasureToAspectRatio() mq.SaveCellQualityOn() mq.Update() # Generate the polydata with mesh plateTriPoly = mq.GetOutput() plateTri = plateTriPoly.GetPolys() # Map the connectivity to original point ids newTriangles = v.vtkCellArray() plateTri.InitTraversal() triIds = v.vtkIdList() origIds = plateTriPoly.GetPointData().GetArray('origIds') aspectRatioArray = plateTriPoly.GetCellData().GetArray('Quality') triangleIndex = 0 while plateTri.GetNextCell(triIds): # Keep only the equilateral triangles to get rid of boundary triangles aspectRatio = aspectRatioArray.GetTuple1(triangleIndex) triangleIndex += 1 if aspectRatio < 1.5: newTriangles.InsertNextCell(3) for i in range(3): newTriangles.InsertCellPoint( int(origIds.GetTuple1(triIds.GetId(i)))) pd.SetPolys(newTriangles) return pd
def __init__(self, parent = None): super(VTKFrame, self).__init__(parent) self.vtkWidget = QVTKRenderWindowInteractor(self) vl = QtGui.QVBoxLayout(self) vl.addWidget(self.vtkWidget) vl.setContentsMargins(0, 0, 0, 0) self.ren = vtk.vtkRenderer() self.ren.SetBackground(0.1, 0.2, 0.4) self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() # Create source source = vtk.vtkSphereSource() source.Update() triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInputConnection(source.GetOutputPort()) triangleFilter.Update() mesh = triangleFilter.GetOutput() qualityFilter = vtk.vtkMeshQuality() qualityFilter.SetInput(mesh) qualityFilter.SetTriangleQualityMeasureToArea() qualityFilter.Update() polydata = vtk.vtkPolyData() polydata.ShallowCopy(qualityFilter.GetOutput()) # Create a mapper and actor mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(polydata.GetProducerPort()) mapper.SetScalarRange(polydata.GetScalarRange()) actor = vtk.vtkActor() actor.SetMapper(mapper) self.ren.AddActor(actor) self.ren.ResetCamera() self._initialized = False
def computeUgridQualityFrobeniusNorm(ugrid): ''' reference: Verdict reference manual, Stimpson, 2007 ''' qual = vtk.vtkMeshQuality() qual.SetInput(ugrid) qual.VolumeOn() qual.RatioOn() qual.SetTetQualityMeasureToFrobeniusNorm() qual.Update() return [ qual.GetOutput().GetFieldData().GetArray( "Mesh Tetrahedron Quality").GetValue(0), qual.GetOutput().GetFieldData().GetArray( "Mesh Tetrahedron Quality").GetValue(1), qual.GetOutput().GetFieldData().GetArray( "Mesh Tetrahedron Quality").GetValue(2), qual.GetOutput().GetFieldData().GetArray( "Mesh Tetrahedron Quality").GetValue(3), qual.GetOutput().GetFieldData().GetArray( "Mesh Tetrahedron Quality").GetValue(4) ]
def _clean(self, data): """Removes cells that have area less than 1e-10. Also runs the data through vtkCleanPolyData(). """ data.BuildLinks() area = vtk.vtkMeshQuality() area.SetTriangleQualityMeasureToArea() area.SetInputData(data) area.Update() area = dsa.WrapDataObject(area.GetOutput()).CellData["Quality"] for i in range(data.GetNumberOfCells()): if area[i] < 1e-10: data.DeleteCell(i) data.RemoveDeletedCells() cleaner = vtk.vtkCleanPolyData() cleaner.SetInputData(data) cleaner.Update() return cleaner.GetOutput()
def main(): mr = vtk.vtkUnstructuredGridReader() iq = vtk.vtkMeshQuality() mr.SetFileName(fname) mr.Update() ug = mr.GetOutput() iq.SetInputConnection(mr.GetOutputPort()) # Here we define the various mesh types and labels for output. meshTypes = [[ 'Triangle', 'Triangle', [['QualityMeasureToEdgeRatio', ' Edge Ratio:'], ['QualityMeasureToAspectRatio', ' Aspect Ratio:'], ['QualityMeasureToRadiusRatio', ' Radius Ratio:'], ['QualityMeasureToAspectFrobenius', ' Frobenius Norm:'], ['QualityMeasureToMinAngle', ' Minimal Angle:']] ], [ 'Quad', 'Quadrilateral', [['QualityMeasureToEdgeRatio', ' Edge Ratio:'], ['QualityMeasureToAspectRatio', ' Aspect Ratio:'], ['QualityMeasureToRadiusRatio', ' Radius Ratio:'], [ 'QualityMeasureToMedAspectFrobenius', ' Average Frobenius Norm:' ], [ 'QualityMeasureToMaxAspectFrobenius', ' Maximal Frobenius Norm:' ], ['QualityMeasureToMinAngle', ' Minimal Angle:']] ], [ 'Tet', 'Tetrahedron', [['QualityMeasureToEdgeRatio', ' Edge Ratio:'], ['QualityMeasureToAspectRatio', ' Aspect Ratio:'], ['QualityMeasureToRadiusRatio', ' Radius Ratio:'], ['QualityMeasureToAspectFrobenius', ' Frobenius Norm:'], ['QualityMeasureToMinAngle', ' Minimal Dihedral Angle:'], ['QualityMeasureToCollapseRatio', ' Collapse Ratio:']] ], [ 'Hex', 'Hexahedron', [['QualityMeasureToEdgeRatio', ' Edge Ratio:']] ]] if ug.GetNumberOfCells() > 0: res = '' for meshType in meshTypes: if meshType[0] == 'Tet': res += '\n%s%s\n %s' % ( 'Tetrahedral', ' quality of the mesh:', mr.GetFileName()) elif meshType[0] == 'Hex': res += '\n%s%s\n %s' % ( 'Hexahedral', ' quality of the mesh:', mr.GetFileName()) else: res += '\n%s%s\n %s' % (meshType[1], ' quality of the mesh:', mr.GetFileName()) for measure in meshType[2]: eval('iq.Set' + meshType[0] + measure[0] + '()') iq.Update() res += '\n%s\n%s' % ( measure[1], DumpQualityStats(iq, 'Mesh ' + meshType[1] + ' Quality')) res += '\n' print res
#!/usr/bin/env python import sys for i in range(0, len(sys.argv)): if sys.argv[i] == '-A' and i < len(sys.argv)-1: sys.path = sys.path + [sys.argv[i+1]] import vtk from vtk.util.misc import vtkGetDataRoot filename = vtkGetDataRoot() + '/Data/tetraMesh.vtk' reader = vtk.vtkUnstructuredGridReader() reader.SetFileName(filename) a = vtk.vtkMeshQuality() a.SetInputConnection(reader.GetOutputPort()) a.VolumeOn() a.RatioOn() a.Update() mesh = a.GetOutput().GetFieldData().GetScalars() for i in range(mesh.GetNumberOfTuples()): print mesh.GetTuple2(i) sys.exit(0)
def Plot_uGridQual(grid): """ Plots quality of a unstructured grid while ignoring pyramids and wedges """ # Create quality filter qual_filter = vtk.vtkMeshQuality() if vtk.vtkVersion().GetVTKMajorVersion() >5: qual_filter.SetInput(grid) else: qual_filter.SetInputData(grid) qual_filter.SetHexQualityMeasureToScaledJacobian() qual_filter.SetTetQualityMeasureToScaledJacobian() qual_filter.SaveCellQualityOn qual_filter.Update() qual_out = qual_filter.GetOutput() # Get quality as array qual = VN.vtk_to_numpy(qual_out.GetCellData().GetScalars()) # If unstructured then replace quality of pyramids and wedges wtih nans if str(grid)[:5] =='vtkUnstructuredGrid': # Get cell types celltypes = VN.vtk_to_numpy(qual_out.GetCellTypesArray()) # Set quality of wedges and pyramids to 1 wedge_pyr_celltypes = [vtk.vtkWedge().GetCellType(), vtk.vtkPyramid().GetCellType()] qual[np.in1d(celltypes, wedge_pyr_celltypes)] = 1 # Reinsert quality array back into uGrid vtkfloat = VN.numpy_to_vtk(np.ascontiguousarray(qual), deep=True) qual_out.GetCellData().SetScalars(vtkfloat) # otherwise, negate the grid quality else: qual = -qual vtkfloat = VN.numpy_to_vtk(np.ascontiguousarray(qual), deep=True) qual_out.GetCellData().SetScalars(vtkfloat) ################################# Plotting ################################# # Create mapper mapper = vtk.vtkDataSetMapper() if vtk.vtkVersion().GetVTKMajorVersion() >5: mapper.SetInput(qual_out) else: mapper.SetInputData(qual_out) mapper.SetScalarRange(np.nanmin(qual), np.nanmax(qual)) # Create Actor actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetRepresentationToSurface() actor.GetProperty().EdgeVisibilityOn() actor.GetProperty().SetColor(1, 1, 1) actor.GetProperty().LightingOff() # Add FEM Actor to renderer window ren = vtk.vtkRenderer() ren.SetBackground(0.3, 0.3, 0.3) renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Allow user to interact istyle = vtk.vtkInteractorStyleTrackballCamera() iren.SetInteractorStyle(istyle) # Add surface to display ren.AddActor(actor) # Add scalar bar scalarBar = vtk.vtkScalarBarActor() scalarBar.SetLookupTable(mapper.GetLookupTable()) scalarBar.SetTitle('Quality') scalarBar.SetNumberOfLabels(5) ren.AddActor(scalarBar) # Render iren.Initialize() renWin.Render() renWin.SetWindowName('FEM Element Quality') iren.Start()
def main(): mr = vtk.vtkUnstructuredGridReader() iq = vtk.vtkMeshQuality() mr.SetFileName(fname) mr.Update() ug = mr.GetOutput() iq.SetInputConnection(mr.GetOutputPort()) # Here we define the various mesh types and labels for output. meshTypes = [['Triangle', 'Triangle', [['QualityMeasureToEdgeRatio', ' Edge Ratio:'], ['QualityMeasureToAspectRatio', ' Aspect Ratio:'], ['QualityMeasureToRadiusRatio', ' Radius Ratio:'], ['QualityMeasureToAspectFrobenius', ' Frobenius Norm:'], ['QualityMeasureToMinAngle', ' Minimal Angle:'] ] ], ['Quad', 'Quadrilateral', [['QualityMeasureToEdgeRatio', ' Edge Ratio:'], ['QualityMeasureToAspectRatio', ' Aspect Ratio:'], ['QualityMeasureToRadiusRatio', ' Radius Ratio:'], ['QualityMeasureToMedAspectFrobenius', ' Average Frobenius Norm:'], ['QualityMeasureToMaxAspectFrobenius', ' Maximal Frobenius Norm:'], ['QualityMeasureToMinAngle', ' Minimal Angle:'] ] ], ['Tet', 'Tetrahedron', [['QualityMeasureToEdgeRatio', ' Edge Ratio:'], ['QualityMeasureToAspectRatio', ' Aspect Ratio:'], ['QualityMeasureToRadiusRatio', ' Radius Ratio:'], ['QualityMeasureToAspectFrobenius', ' Frobenius Norm:'], ['QualityMeasureToMinAngle', ' Minimal Dihedral Angle:'], ['QualityMeasureToCollapseRatio', ' Collapse Ratio:'] ] ], ['Hex', 'Hexahedron', [['QualityMeasureToEdgeRatio', ' Edge Ratio:'] ] ] ] if ug.GetNumberOfCells() > 0 : res = '' for meshType in meshTypes: if meshType[0] == 'Tet': res += '\n%s%s\n %s' % ('Tetrahedral', ' quality of the mesh:', mr.GetFileName()) elif meshType[0] == 'Hex': res += '\n%s%s\n %s' % ('Hexahedral', ' quality of the mesh:', mr.GetFileName()) else: res += '\n%s%s\n %s' % (meshType[1], ' quality of the mesh:', mr.GetFileName()) for measure in meshType[2]: eval('iq.Set' + meshType[0] + measure[0] + '()') iq.Update() res += '\n%s\n%s' % (measure[1], DumpQualityStats(iq, 'Mesh ' + meshType[1] + ' Quality')) res += '\n' print res
def read_data_and_differentiate(pod_mode_dir,num_modes,num_points,num_boundary_faces,num_dimensions,num_components,correct_for_cell_volumes, \ u,v,w,dudx,dudy,dudz,dvdx,dvdy,dvdz,dwdx,dwdy,dwdz,\ uF,vF,wF,dudxF,dudyF,dudzF,dvdxF,dvdyF,dvdzF,dwdxF,dwdyF,dwdzF,cell_volume,norm,calibrate_coefficients): u_read = np.array(np.zeros((num_points,3), dtype=np.float64)) dudx_read = np.array(np.zeros((num_points,3,3), dtype=np.float64)) uF_read = np.array(np.zeros((num_boundary_faces,3), dtype=np.float64)) dudxF_read = np.array(np.zeros((num_boundary_faces,3,3), dtype=np.float64)) # .................................................. # Read meanfield and spatially differentiate filename = pod_mode_dir + "/spatial_meanfield.vtk" print ' Reading file ', filename.strip() reader = vtk.vtkUnstructuredGridReader() reader.ReadAllScalarsOn() reader.ReadAllVectorsOn() reader.ReadAllTensorsOn() reader.SetFileName(filename) reader.Update() grid = vtk.vtkUnstructuredGrid() grid.DeepCopy(reader.GetOutput()) # get cell volumes if (correct_for_cell_volumes=="true"): cell_volume[:] = VN.vtk_to_numpy(grid.GetPointData().GetScalars("cell_volume")) else: cell_volume[:] = 1.0 # get mean velocity field within volume u_read = VN.vtk_to_numpy(grid.GetPointData().GetVectors("u")) u[:,0] = u_read[:,0].copy() v[:,0] = u_read[:,1].copy() w[:,0] = u_read[:,2].copy() grid.GetPointData().SetVectors(grid.GetPointData().GetVectors("u")) # get mean velocity derivative field within volume differentiator = vtk.vtkCellDerivatives() differentiator.SetTensorModeToComputeGradient() differentiator.SetInput(grid) differentiator.Update() cell_to_point_data = vtk.vtkCellDataToPointData() cell_to_point_data.SetInput(differentiator.GetOutput()) cell_to_point_data.Update() grid.GetPointData().SetTensors(cell_to_point_data.GetOutput().GetPointData().GetTensors()) dudx_read = VN.vtk_to_numpy(cell_to_point_data.GetOutput().GetPointData().GetTensors()) dudx[:,0] = dudx_read[:,0].copy() dvdx[:,0] = dudx_read[:,1].copy() dwdx[:,0] = dudx_read[:,2].copy() dudy[:,0] = dudx_read[:,3].copy() dvdy[:,0] = dudx_read[:,4].copy() dwdy[:,0] = dudx_read[:,5].copy() dudz[:,0] = dudx_read[:,6].copy() dvdz[:,0] = dudx_read[:,7].copy() dwdz[:,0] = dudx_read[:,8].copy() # extract boundary surface data if( (calibrate_coefficients=="none") or (calibrate_coefficients=="constant") ): geom_filter = vtk.vtkDataSetSurfaceFilter() geom_filter.SetInput(grid) geom_filter.Update() boundary_faces = vtk.vtkPolyData() boundary_faces = geom_filter.GetOutput() point_to_cell_data = vtk.vtkPointDataToCellData() point_to_cell_data.SetInput(geom_filter.GetOutput()) point_to_cell_data.Update() # get mean velocity field on boundary surface uF_read = VN.vtk_to_numpy(point_to_cell_data.GetOutput().GetCellData().GetVectors("u")) uF[:,0] = uF_read[:,0] vF[:,0] = uF_read[:,1] wF[:,0] = uF_read[:,2] # get mean derivative velocity field on boundary surface dudxF_read = VN.vtk_to_numpy(point_to_cell_data.GetOutput().GetCellData().GetTensors()) dudxF[:,0] = dudxF_read[:,0] dvdxF[:,0] = dudxF_read[:,1] dwdxF[:,0] = dudxF_read[:,2] dudyF[:,0] = dudxF_read[:,3] dvdyF[:,0] = dudxF_read[:,4] dwdyF[:,0] = dudxF_read[:,5] dudzF[:,0] = dudxF_read[:,6] dvdzF[:,0] = dudxF_read[:,7] dwdzF[:,0] = dudxF_read[:,8] # get boundary face normals norm_filter = vtk.vtkPolyDataNormals() norm_filter.ComputeCellNormalsOn() norm_filter.SetInput(boundary_faces) norm_filter.Update() area_filter = vtk.vtkMeshQuality() area_filter.SetQuadQualityMeasureToArea() area_filter.SetTriangleQualityMeasureToArea() area_filter.SetInput(boundary_faces) area_filter.Update() for j in range(0,num_boundary_faces): area = area_filter.GetOutput().GetCellData().GetArray("Quality").GetComponent(j,0) norm[j,:] = norm_filter.GetOutput().GetCellData().GetNormals().GetTuple(j) norm[j,:] = norm[j,:] * area # .................................................. # Read modes and spatially differentiate for j in range(0,num_modes): j_index = j+1 filename = pod_mode_dir + '/POD.spatial_mode_' + '%04d'%j_index + '.vtk' print ' Reading file ', filename.strip(), 'file number ', j_index, ' of ', num_modes reader.SetFileName(filename) reader.Update() # get mode velocity field within volume u_read = VN.vtk_to_numpy(reader.GetOutput().GetPointData().GetVectors("u")) u[:,j_index] = u_read[:,0] v[:,j_index] = u_read[:,1] w[:,j_index] = u_read[:,2] # get mode velocity derivative fields within volume grid.GetPointData().SetVectors(reader.GetOutput().GetPointData().GetVectors("u")) differentiator.SetInput(grid) differentiator.Update() cell_to_point_data.SetInput(differentiator.GetOutput()) cell_to_point_data.Update() grid.GetPointData().SetTensors(cell_to_point_data.GetOutput().GetPointData().GetTensors()) dudx_read = VN.vtk_to_numpy(cell_to_point_data.GetOutput().GetPointData().GetTensors()) dudx[:,j_index] = dudx_read[:,0] dvdx[:,j_index] = dudx_read[:,1] dwdx[:,j_index] = dudx_read[:,2] dudy[:,j_index] = dudx_read[:,3] dvdy[:,j_index] = dudx_read[:,4] dwdy[:,j_index] = dudx_read[:,5] dudz[:,j_index] = dudx_read[:,6] dvdz[:,j_index] = dudx_read[:,7] dwdz[:,j_index] = dudx_read[:,8] # extract boundary surface data if( (calibrate_coefficients=="none") or (calibrate_coefficients=="constant") ): geom_filter.SetInput(grid) geom_filter.Update() boundary_faces = geom_filter.GetOutput() point_to_cell_data.SetInput(geom_filter.GetOutput()) point_to_cell_data.Update() # get mode velocity field on boundary surface uF_read = VN.vtk_to_numpy(point_to_cell_data.GetOutput().GetCellData().GetVectors("u")) uF[:,j_index] = uF_read[:,0] vF[:,j_index] = uF_read[:,1] wF[:,j_index] = uF_read[:,2] # get mean derivative velocity field on boundary surface dudxF_read = VN.vtk_to_numpy(point_to_cell_data.GetOutput().GetCellData().GetTensors()) dudxF[:,j_index] = dudxF_read[:,0] dvdxF[:,j_index] = dudxF_read[:,1] dwdxF[:,j_index] = dudxF_read[:,2] dudyF[:,j_index] = dudxF_read[:,3] dvdyF[:,j_index] = dudxF_read[:,4] dwdyF[:,j_index] = dudxF_read[:,5] dudzF[:,j_index] = dudxF_read[:,6] dvdzF[:,j_index] = dudxF_read[:,7] dwdzF[:,j_index] = dudxF_read[:,8] # .................................................. # zero appropriate coefficients if (num_dimensions<3): dudz[:,:] = 0.0 dvdz[:,:] = 0.0 dwdz[:,:] = 0.0 if (num_dimensions<2): dudy[:,:] = 0.0 dvdy[:,:] = 0.0 dwdy[:,:] = 0.0 if (num_components<3): w[:,:] = 0.0 dwdx[:,:] = 0.0 dwdy[:,:] = 0.0 dwdz[:,:] = 0.0 if (num_components<2): v[:,:] = 0.0 dvdx[:,:] = 0.0 dvdy[:,:] = 0.0 dvdz[:,:] = 0.0 if( (calibrate_coefficients=="none") or (calibrate_coefficients=="constant") ): if (num_dimensions<3): dudzF[:,:] = 0.0 dvdzF[:,:] = 0.0 dwdzF[:,:] = 0.0 if (num_dimensions<2): dudyF[:,:] = 0.0 dvdyF[:,:] = 0.0 dwdyF[:,:] = 0.0 if (num_components<3): wF[:,j_index] = 0.0 dwdxF[:,:] = 0.0 dwdyF[:,:] = 0.0 dwdzF[:,:] = 0.0 if (num_components<2): vF[:,:] = 0.0 dvdxF[:,:] = 0.0 dvdyF[:,:] = 0.0 dvdzF[:,:] = 0.0
def read_data_and_differentiate(pod_mode_dir,num_modes,num_points,num_boundary_faces,num_dimensions,num_components,correct_for_cell_volumes, \ u,v,w,dudx,dudy,dudz,dvdx,dvdy,dvdz,dwdx,dwdy,dwdz,\ uF,vF,wF,dudxF,dudyF,dudzF,dvdxF,dvdyF,dvdzF,dwdxF,dwdyF,dwdzF,cell_volume,norm,calibrate_coefficients): u_read = np.array(np.zeros((num_points, 3), dtype=np.float64)) dudx_read = np.array(np.zeros((num_points, 3, 3), dtype=np.float64)) uF_read = np.array(np.zeros((num_boundary_faces, 3), dtype=np.float64)) dudxF_read = np.array( np.zeros((num_boundary_faces, 3, 3), dtype=np.float64)) # .................................................. # Read meanfield and spatially differentiate filename = pod_mode_dir + "/spatial_meanfield.vtk" print ' Reading file ', filename.strip() reader = vtk.vtkUnstructuredGridReader() reader.ReadAllScalarsOn() reader.ReadAllVectorsOn() reader.ReadAllTensorsOn() reader.SetFileName(filename) reader.Update() grid = vtk.vtkUnstructuredGrid() grid.DeepCopy(reader.GetOutput()) # get cell volumes if (correct_for_cell_volumes == "true"): cell_volume[:] = VN.vtk_to_numpy( grid.GetPointData().GetScalars("cell_volume")) else: cell_volume[:] = 1.0 # get mean velocity field within volume u_read = VN.vtk_to_numpy(grid.GetPointData().GetVectors("u")) u[:, 0] = u_read[:, 0].copy() v[:, 0] = u_read[:, 1].copy() w[:, 0] = u_read[:, 2].copy() grid.GetPointData().SetVectors(grid.GetPointData().GetVectors("u")) # get mean velocity derivative field within volume differentiator = vtk.vtkCellDerivatives() differentiator.SetTensorModeToComputeGradient() differentiator.SetInput(grid) differentiator.Update() cell_to_point_data = vtk.vtkCellDataToPointData() cell_to_point_data.SetInput(differentiator.GetOutput()) cell_to_point_data.Update() grid.GetPointData().SetTensors( cell_to_point_data.GetOutput().GetPointData().GetTensors()) dudx_read = VN.vtk_to_numpy( cell_to_point_data.GetOutput().GetPointData().GetTensors()) dudx[:, 0] = dudx_read[:, 0].copy() dvdx[:, 0] = dudx_read[:, 1].copy() dwdx[:, 0] = dudx_read[:, 2].copy() dudy[:, 0] = dudx_read[:, 3].copy() dvdy[:, 0] = dudx_read[:, 4].copy() dwdy[:, 0] = dudx_read[:, 5].copy() dudz[:, 0] = dudx_read[:, 6].copy() dvdz[:, 0] = dudx_read[:, 7].copy() dwdz[:, 0] = dudx_read[:, 8].copy() # extract boundary surface data if ((calibrate_coefficients == "none") or (calibrate_coefficients == "constant")): geom_filter = vtk.vtkDataSetSurfaceFilter() geom_filter.SetInput(grid) geom_filter.Update() boundary_faces = vtk.vtkPolyData() boundary_faces = geom_filter.GetOutput() point_to_cell_data = vtk.vtkPointDataToCellData() point_to_cell_data.SetInput(geom_filter.GetOutput()) point_to_cell_data.Update() # get mean velocity field on boundary surface uF_read = VN.vtk_to_numpy( point_to_cell_data.GetOutput().GetCellData().GetVectors("u")) uF[:, 0] = uF_read[:, 0] vF[:, 0] = uF_read[:, 1] wF[:, 0] = uF_read[:, 2] # get mean derivative velocity field on boundary surface dudxF_read = VN.vtk_to_numpy( point_to_cell_data.GetOutput().GetCellData().GetTensors()) dudxF[:, 0] = dudxF_read[:, 0] dvdxF[:, 0] = dudxF_read[:, 1] dwdxF[:, 0] = dudxF_read[:, 2] dudyF[:, 0] = dudxF_read[:, 3] dvdyF[:, 0] = dudxF_read[:, 4] dwdyF[:, 0] = dudxF_read[:, 5] dudzF[:, 0] = dudxF_read[:, 6] dvdzF[:, 0] = dudxF_read[:, 7] dwdzF[:, 0] = dudxF_read[:, 8] # get boundary face normals norm_filter = vtk.vtkPolyDataNormals() norm_filter.ComputeCellNormalsOn() norm_filter.SetInput(boundary_faces) norm_filter.Update() area_filter = vtk.vtkMeshQuality() area_filter.SetQuadQualityMeasureToArea() area_filter.SetTriangleQualityMeasureToArea() area_filter.SetInput(boundary_faces) area_filter.Update() for j in range(0, num_boundary_faces): area = area_filter.GetOutput().GetCellData().GetArray( "Quality").GetComponent(j, 0) norm[j, :] = norm_filter.GetOutput().GetCellData().GetNormals( ).GetTuple(j) norm[j, :] = norm[j, :] * area # .................................................. # Read modes and spatially differentiate for j in range(0, num_modes): j_index = j + 1 filename = pod_mode_dir + '/POD.spatial_mode_' + '%04d' % j_index + '.vtk' print ' Reading file ', filename.strip( ), 'file number ', j_index, ' of ', num_modes reader.SetFileName(filename) reader.Update() # get mode velocity field within volume u_read = VN.vtk_to_numpy( reader.GetOutput().GetPointData().GetVectors("u")) u[:, j_index] = u_read[:, 0] v[:, j_index] = u_read[:, 1] w[:, j_index] = u_read[:, 2] # get mode velocity derivative fields within volume grid.GetPointData().SetVectors( reader.GetOutput().GetPointData().GetVectors("u")) differentiator.SetInput(grid) differentiator.Update() cell_to_point_data.SetInput(differentiator.GetOutput()) cell_to_point_data.Update() grid.GetPointData().SetTensors( cell_to_point_data.GetOutput().GetPointData().GetTensors()) dudx_read = VN.vtk_to_numpy( cell_to_point_data.GetOutput().GetPointData().GetTensors()) dudx[:, j_index] = dudx_read[:, 0] dvdx[:, j_index] = dudx_read[:, 1] dwdx[:, j_index] = dudx_read[:, 2] dudy[:, j_index] = dudx_read[:, 3] dvdy[:, j_index] = dudx_read[:, 4] dwdy[:, j_index] = dudx_read[:, 5] dudz[:, j_index] = dudx_read[:, 6] dvdz[:, j_index] = dudx_read[:, 7] dwdz[:, j_index] = dudx_read[:, 8] # extract boundary surface data if ((calibrate_coefficients == "none") or (calibrate_coefficients == "constant")): geom_filter.SetInput(grid) geom_filter.Update() boundary_faces = geom_filter.GetOutput() point_to_cell_data.SetInput(geom_filter.GetOutput()) point_to_cell_data.Update() # get mode velocity field on boundary surface uF_read = VN.vtk_to_numpy( point_to_cell_data.GetOutput().GetCellData().GetVectors("u")) uF[:, j_index] = uF_read[:, 0] vF[:, j_index] = uF_read[:, 1] wF[:, j_index] = uF_read[:, 2] # get mean derivative velocity field on boundary surface dudxF_read = VN.vtk_to_numpy( point_to_cell_data.GetOutput().GetCellData().GetTensors()) dudxF[:, j_index] = dudxF_read[:, 0] dvdxF[:, j_index] = dudxF_read[:, 1] dwdxF[:, j_index] = dudxF_read[:, 2] dudyF[:, j_index] = dudxF_read[:, 3] dvdyF[:, j_index] = dudxF_read[:, 4] dwdyF[:, j_index] = dudxF_read[:, 5] dudzF[:, j_index] = dudxF_read[:, 6] dvdzF[:, j_index] = dudxF_read[:, 7] dwdzF[:, j_index] = dudxF_read[:, 8] # .................................................. # zero appropriate coefficients if (num_dimensions < 3): dudz[:, :] = 0.0 dvdz[:, :] = 0.0 dwdz[:, :] = 0.0 if (num_dimensions < 2): dudy[:, :] = 0.0 dvdy[:, :] = 0.0 dwdy[:, :] = 0.0 if (num_components < 3): w[:, :] = 0.0 dwdx[:, :] = 0.0 dwdy[:, :] = 0.0 dwdz[:, :] = 0.0 if (num_components < 2): v[:, :] = 0.0 dvdx[:, :] = 0.0 dvdy[:, :] = 0.0 dvdz[:, :] = 0.0 if ((calibrate_coefficients == "none") or (calibrate_coefficients == "constant")): if (num_dimensions < 3): dudzF[:, :] = 0.0 dvdzF[:, :] = 0.0 dwdzF[:, :] = 0.0 if (num_dimensions < 2): dudyF[:, :] = 0.0 dvdyF[:, :] = 0.0 dwdyF[:, :] = 0.0 if (num_components < 3): wF[:, j_index] = 0.0 dwdxF[:, :] = 0.0 dwdyF[:, :] = 0.0 dwdzF[:, :] = 0.0 if (num_components < 2): vF[:, :] = 0.0 dvdxF[:, :] = 0.0 dvdyF[:, :] = 0.0 dvdzF[:, :] = 0.0
def _getECMstrain(self): """ Generates tetrahedrons from object centroids in the reference and deformed states. The highest quality tetrahedron (edge ratio closest to 1) is used to construct a linear system of equations, :math:`\|\mathbf{w}\|^2 - \|\mathbf{W}\|^2 = \mathbf{W}.\mathbf{E}.\mathbf{W}`, where, :math:`\mathbf{W}` are the reference tetrahedron edges (as vectors) and :math:`\mathbf{w}` are the deformed tetrahedron edges, to solve for Green-Lagrange strain, :math:`\mathbf{E}`. Returns ------- ecm_strain """ #get the ECM strain rc = np.array(self.rcentroids) dc = np.array(self.dcentroids) if rc.shape[0] < 4: print(("WARNING: There are less than 4 objects in the space; " "therefore, tissue strain was not calculated.")) return da = numpy_to_vtk(rc) p = vtk.vtkPoints() p.SetData(da) pd = vtk.vtkPolyData() pd.SetPoints(p) tet = vtk.vtkDelaunay3D() tet.SetInputData(pd) tet.Update() quality = vtk.vtkMeshQuality() quality.SetInputData(tet.GetOutput()) quality.Update() mq = quality.GetOutput().GetCellData().GetArray("Quality") mq = vtk_to_numpy(mq) try: #tet with edge ratio closest to 1 btet = np.argmin(abs(mq - 1.0)) except: return idlist = tet.GetOutput().GetCell(btet).GetPointIds() P = np.zeros((4, 3), float) p = np.zeros((4, 3), float) for i in range(idlist.GetNumberOfIds()): P[i, :] = rc[idlist.GetId(i), :] p[i, :] = dc[idlist.GetId(i), :] X = np.array([P[1, :] - P[0, :], P[2, :] - P[0, :], P[3, :] - P[0, :], P[3, :] - P[1, :], P[3, :] - P[2, :], P[2, :] - P[1, :]], float) x = np.array([p[1, :] - p[0, :], p[2, :] - p[0, :], p[3, :] - p[0, :], p[3, :] - p[1, :], p[3, :] - p[2, :], p[2, :] - p[1, :]], float) #assemble the system dX = np.zeros((6, 6), float) ds = np.zeros((6, 1), float) for i in range(6): dX[i, 0] = 2 * X[i, 0] ** 2 dX[i, 1] = 2 * X[i, 1] ** 2 dX[i, 2] = 2 * X[i, 2] ** 2 dX[i, 3] = 4 * X[i, 0] * X[i, 1] dX[i, 4] = 4 * X[i, 0] * X[i, 2] dX[i, 5] = 4 * X[i, 1] * X[i, 2] ds[i, 0] = np.linalg.norm( x[i, :]) ** 2 - np.linalg.norm(X[i, :]) ** 2 E = np.linalg.solve(dX, ds) E = np.array([[E[0, 0], E[3, 0], E[4, 0]], [E[3, 0], E[1, 0], E[5, 0]], [E[4, 0], E[5, 0], E[2, 0]]], float) self.ecm_strain = E
def Plot_uGridQual(grid): """ Plots quality of a unstructured grid while ignoring pyramids and wedges """ # Create quality filter qual_filter = vtk.vtkMeshQuality() if vtk.vtkVersion().GetVTKMajorVersion() > 5: qual_filter.SetInput(grid) else: qual_filter.SetInputData(grid) qual_filter.SetHexQualityMeasureToScaledJacobian() qual_filter.SetTetQualityMeasureToScaledJacobian() qual_filter.SaveCellQualityOn qual_filter.Update() qual_out = qual_filter.GetOutput() # Get quality as array qual = VN.vtk_to_numpy(qual_out.GetCellData().GetScalars()) # If unstructured then replace quality of pyramids and wedges wtih nans if str(grid)[:5] == 'vtkUnstructuredGrid': # Get cell types celltypes = VN.vtk_to_numpy(qual_out.GetCellTypesArray()) # Set quality of wedges and pyramids to 1 wedge_pyr_celltypes = [ vtk.vtkWedge().GetCellType(), vtk.vtkPyramid().GetCellType() ] qual[np.in1d(celltypes, wedge_pyr_celltypes)] = 1 # Reinsert quality array back into uGrid vtkfloat = VN.numpy_to_vtk(np.ascontiguousarray(qual), deep=True) qual_out.GetCellData().SetScalars(vtkfloat) # otherwise, negate the grid quality else: qual = -qual vtkfloat = VN.numpy_to_vtk(np.ascontiguousarray(qual), deep=True) qual_out.GetCellData().SetScalars(vtkfloat) ################################# Plotting ################################# # Create mapper mapper = vtk.vtkDataSetMapper() if vtk.vtkVersion().GetVTKMajorVersion() > 5: mapper.SetInput(qual_out) else: mapper.SetInputData(qual_out) mapper.SetScalarRange(np.nanmin(qual), np.nanmax(qual)) # Create Actor actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetRepresentationToSurface() actor.GetProperty().EdgeVisibilityOn() actor.GetProperty().SetColor(1, 1, 1) actor.GetProperty().LightingOff() # Add FEM Actor to renderer window ren = vtk.vtkRenderer() ren.SetBackground(0.3, 0.3, 0.3) renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Allow user to interact istyle = vtk.vtkInteractorStyleTrackballCamera() iren.SetInteractorStyle(istyle) # Add surface to display ren.AddActor(actor) # Add scalar bar scalarBar = vtk.vtkScalarBarActor() scalarBar.SetLookupTable(mapper.GetLookupTable()) scalarBar.SetTitle('Quality') scalarBar.SetNumberOfLabels(5) ren.AddActor(scalarBar) # Render iren.Initialize() renWin.Render() renWin.SetWindowName('FEM Element Quality') iren.Start()
smoother.Update() ##calc cell normal triangleCellNormals = vtk.vtkPolyDataNormals() if vtk.VTK_MAJOR_VERSION <= 5: triangleCellNormals.SetInput(smoother.GetOutput()) else: triangleCellNormals.SetInputConnection(smoother.GetOutputPort()) triangleCellNormals.ComputeCellNormalsOn() triangleCellNormals.ComputePointNormalsOff() triangleCellNormals.ConsistencyOn() triangleCellNormals.AutoOrientNormalsOn() triangleCellNormals.Update() #creates vtkPolyData ##calc cell area triangleCellAN = vtk.vtkMeshQuality() if vtk.VTK_MAJOR_VERSION <= 5: triangleCellAN.SetInput(triangleCellNormals.GetOutput()) else: triangleCellAN.SetInputConnection(triangleCellNormals.GetOutputPort()) triangleCellAN.SetTriangleQualityMeasureToArea() triangleCellAN.SaveCellQualityOn() #default triangleCellAN.Update() #creates vtkDataSet PointNormalArray = triangleCellNormals.GetOutput().GetCellData( ).GetNormals() qualityArray = triangleCellAN.GetOutput().GetCellData().GetArray("Quality") if (PointNormalArray.GetNumberOfTuples() != qualityArray.GetNumberOfTuples()): print "Error! Sizes of normal array and area array dont equal!"
##calc cell normal triangle_cell_normals = vtk.vtkPolyDataNormals() if vtk.VTK_MAJOR_VERSION <= 5: triangle_cell_normals.SetInput(smoother.GetOutput()) else: triangle_cell_normals.SetInputConnection(smoother.GetOutputPort()) triangle_cell_normals.ComputeCellNormalsOn() triangle_cell_normals.ComputePointNormalsOff() triangle_cell_normals.ConsistencyOn() triangle_cell_normals.AutoOrientNormalsOn() triangle_cell_normals.Update() #creates vtkPolyData ##calc cell area triangle_cell_mesh_quality = vtk.vtkMeshQuality() if vtk.VTK_MAJOR_VERSION <= 5: triangle_cell_mesh_quality.SetInput(triangle_cell_normals.GetOutput()) else: triangle_cell_mesh_quality.SetInputConnection(triangle_cell_normals.GetOutputPort()) triangle_cell_mesh_quality.SetTriangleQualityMeasureToArea() triangle_cell_mesh_quality.SaveCellQualityOn() #default triangle_cell_mesh_quality.Update() #creates vtkDataSet point_normal_array = triangle_cell_normals.GetOutput().GetCellData().GetNormals() quality_array = triangle_cell_mesh_quality.GetOutput().GetCellData().GetArray("Quality") if point_normal_array.GetNumberOfTuples() != qualityArray.GetNumberOfTuples(): print "Error! Sizes of normal array and area array dont equal!" exit(1)
def _getECMstrain(self): """ Generates tetrahedrons from object centroids in the reference and deformed states. The highest quality tetrahedron (edge ratio closest to 1) is used to construct a linear system of equations, :math:`\|\mathbf{w}\|^2 - \|\mathbf{W}\|^2 = \mathbf{W}.\mathbf{E}.\mathbf{W}`, where, :math:`\mathbf{W}` are the reference tetrahedron edges (as vectors) and :math:`\mathbf{w}` are the deformed tetrahedron edges, to solve for Green-Lagrange strain, :math:`\mathbf{E}`. Returns ------- ecm_strain """ #get the ECM strain rc = np.array(self.rcentroids) dc = np.array(self.dcentroids) if rc.shape[0] < 4: print(("WARNING: There are less than 4 objects in the space; " "therefore, tissue strain was not calculated.")) return da = numpy_to_vtk(rc) p = vtk.vtkPoints() p.SetData(da) pd = vtk.vtkPolyData() pd.SetPoints(p) tet = vtk.vtkDelaunay3D() tet.SetInputData(pd) tet.Update() quality = vtk.vtkMeshQuality() quality.SetInputData(tet.GetOutput()) quality.Update() mq = quality.GetOutput().GetCellData().GetArray("Quality") mq = vtk_to_numpy(mq) try: #tet with edge ratio closest to 1 btet = np.argmin(abs(mq - 1.0)) except: return idlist = tet.GetOutput().GetCell(btet).GetPointIds() P = np.zeros((4, 3), float) p = np.zeros((4, 3), float) for i in range(idlist.GetNumberOfIds()): P[i, :] = rc[idlist.GetId(i), :] p[i, :] = dc[idlist.GetId(i), :] X = np.array([ P[1, :] - P[0, :], P[2, :] - P[0, :], P[3, :] - P[0, :], P[3, :] - P[1, :], P[3, :] - P[2, :], P[2, :] - P[1, :] ], float) x = np.array([ p[1, :] - p[0, :], p[2, :] - p[0, :], p[3, :] - p[0, :], p[3, :] - p[1, :], p[3, :] - p[2, :], p[2, :] - p[1, :] ], float) #assemble the system dX = np.zeros((6, 6), float) ds = np.zeros((6, 1), float) for i in range(6): dX[i, 0] = 2 * X[i, 0]**2 dX[i, 1] = 2 * X[i, 1]**2 dX[i, 2] = 2 * X[i, 2]**2 dX[i, 3] = 4 * X[i, 0] * X[i, 1] dX[i, 4] = 4 * X[i, 0] * X[i, 2] dX[i, 5] = 4 * X[i, 1] * X[i, 2] ds[i, 0] = np.linalg.norm(x[i, :])**2 - np.linalg.norm(X[i, :])**2 E = np.linalg.solve(dX, ds) E = np.array([[E[0, 0], E[3, 0], E[4, 0]], [E[3, 0], E[1, 0], E[5, 0]], [E[4, 0], E[5, 0], E[2, 0]]], float) self.ecm_strain = E
def main(): mr = vtk.vtkUnstructuredGridReader() iq = vtk.vtkMeshQuality() mr.SetFileName(fname) mr.Update() ug = mr.GetOutput() iq.SetInputConnection(mr.GetOutputPort()) # Here we define the various mesh types and labels for output. meshTypes = [ [ "Triangle", "Triangle", [ ["QualityMeasureToEdgeRatio", " Edge Ratio:"], ["QualityMeasureToAspectRatio", " Aspect Ratio:"], ["QualityMeasureToRadiusRatio", " Radius Ratio:"], ["QualityMeasureToAspectFrobenius", " Frobenius Norm:"], ["QualityMeasureToMinAngle", " Minimal Angle:"], ], ], [ "Quad", "Quadrilateral", [ ["QualityMeasureToEdgeRatio", " Edge Ratio:"], ["QualityMeasureToAspectRatio", " Aspect Ratio:"], ["QualityMeasureToRadiusRatio", " Radius Ratio:"], ["QualityMeasureToMedAspectFrobenius", " Average Frobenius Norm:"], ["QualityMeasureToMaxAspectFrobenius", " Maximal Frobenius Norm:"], ["QualityMeasureToMinAngle", " Minimal Angle:"], ], ], [ "Tet", "Tetrahedron", [ ["QualityMeasureToEdgeRatio", " Edge Ratio:"], ["QualityMeasureToAspectRatio", " Aspect Ratio:"], ["QualityMeasureToRadiusRatio", " Radius Ratio:"], ["QualityMeasureToAspectFrobenius", " Frobenius Norm:"], ["QualityMeasureToMinAngle", " Minimal Dihedral Angle:"], ["QualityMeasureToCollapseRatio", " Collapse Ratio:"], ], ], ["Hex", "Hexahedron", [["QualityMeasureToEdgeRatio", " Edge Ratio:"]]], ] if ug.GetNumberOfCells() > 0: res = "" for meshType in meshTypes: if meshType[0] == "Tet": res += "\n%s%s\n %s" % ("Tetrahedral", " quality of the mesh:", mr.GetFileName()) elif meshType[0] == "Hex": res += "\n%s%s\n %s" % ("Hexahedral", " quality of the mesh:", mr.GetFileName()) else: res += "\n%s%s\n %s" % (meshType[1], " quality of the mesh:", mr.GetFileName()) for measure in meshType[2]: eval("iq.Set" + meshType[0] + measure[0] + "()") iq.Update() res += "\n%s\n%s" % (measure[1], DumpQualityStats(iq, "Mesh " + meshType[1] + " Quality")) res += "\n" print(res)