def create_sample_element(cell_type, order=3, visualize=True): try: import vtk from vtkmodules.util.numpy_support import vtk_to_numpy except ImportError: raise ImportError("python bindings for vtk cannot be found") cell_type = cell_type.upper() vtk_cell_type = getattr(vtk, cell_type, None) if vtk_cell_type is None: raise ValueError("unknown cell type: '%s'" % cell_type) source = vtk.vtkCellTypeSource() source.SetCellType(vtk_cell_type) source.SetBlocksDimensions(1, 1, 1) if "LAGRANGE" in cell_type: source.SetCellOrder(order) source.Update() grid = source.GetOutput() if visualize: filename = "sample_%s.vtu" % cell_type.lower() print("cell type: %s" % cell_type) print("output: %s" % filename) writer = vtk.vtkXMLUnstructuredGridWriter() writer.SetFileName(filename) writer.SetCompressorTypeToNone() writer.SetDataModeToAscii() writer.SetInputData(grid) writer.Write() cell = grid.GetCell(0) points = vtk_to_numpy(cell.GetPoints().GetData()).T dim = cell.GetCellDimension() points = points[0:dim] if cell_type in VTK_LAGRANGE_SIMPLICES: from pyvisfile.vtk.vtk_ordering import vtk_lagrange_simplex_node_tuples nodes = np.array(vtk_lagrange_simplex_node_tuples(dim, order)) error = la.norm(nodes / order - points.T) print("error[%d]: %.5e" % (order, error)) assert error < 5.0e-7 if visualize: filename = "sample_%s" % cell_type.lower() plot_node_ordering(filename, points, show=False) if cell_type in VTK_LAGRANGE_SIMPLICES: filename = "sample_%s_new" % cell_type.lower() plot_node_ordering(filename, nodes.T, show=False)
def main(): cellName = get_program_parameters() # Store the cell class names in a dictionary. cellMap = dict() cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_LINE)] = vtk.VTK_LINE cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_QUADRATIC_EDGE)] = vtk.VTK_QUADRATIC_EDGE cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_CUBIC_LINE)] = vtk.VTK_CUBIC_LINE cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_TRIANGLE)] = vtk.VTK_TRIANGLE cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_QUADRATIC_TRIANGLE)] = vtk.VTK_QUADRATIC_TRIANGLE cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_QUAD)] = vtk.VTK_QUAD cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_QUADRATIC_QUAD)] = vtk.VTK_QUADRATIC_QUAD cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_TETRA)] = vtk.VTK_TETRA cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_HEXAHEDRON)] = vtk.VTK_HEXAHEDRON cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_WEDGE)] = vtk.VTK_WEDGE cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_PYRAMID)] = vtk.VTK_PYRAMID cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_QUADRATIC_WEDGE)] = vtk.VTK_QUADRATIC_WEDGE cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_QUADRATIC_PYRAMID)] = vtk.VTK_QUADRATIC_PYRAMID cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_QUADRATIC_HEXAHEDRON)] = vtk.VTK_QUADRATIC_HEXAHEDRON cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_QUADRATIC_TETRA)] = vtk.VTK_QUADRATIC_TETRA if cellName not in cellMap: print('Cell type ', cellName, ' is not supported.') return source = vtk.vtkCellTypeSource() source.SetCellType(cellMap[cellName]) source.Update() print('Cell: ', cellName) originalPoints = source.GetOutput().GetPoints() points = vtk.vtkPoints() points.SetNumberOfPoints(source.GetOutput().GetNumberOfPoints()) rng = vtk.vtkMinimalStandardRandomSequence() rng.SetSeed(5070) # for testing for i in range(0, points.GetNumberOfPoints()): perturbation = [0.0] * 3 for j in range(0, 3): rng.Next() perturbation[j] = rng.GetRangeValue(-0.1, 0.1) currentPoint = [0.0] * 3 originalPoints.GetPoint(i, currentPoint) points.SetPoint(i, currentPoint[0] + perturbation[0], currentPoint[1] + perturbation[1], currentPoint[2] + perturbation[2]) source.GetOutput().SetPoints(points) numCells = source.GetOutput().GetNumberOfCells() print('Number of cells: ', numCells) idArray = vtk.vtkIntArray() idArray.SetNumberOfTuples(numCells) for i in range(0, numCells): idArray.InsertTuple1(i, i + 1) idArray.SetName('Ids') source.GetOutput().GetCellData().AddArray(idArray) source.GetOutput().GetCellData().SetActiveScalars('Ids') shrink = vtk.vtkShrinkFilter() shrink.SetInputConnection(source.GetOutputPort()) shrink.SetShrinkFactor(.8) tessellate = vtk.vtkTessellatorFilter() tessellate.SetInputConnection(shrink.GetOutputPort()) tessellate.SetMaximumNumberOfSubdivisions(3) # Create a lookup table to map cell data to colors. lut = vtk.vtkLookupTable() colorSeries = vtk.vtkColorSeries() seriesEnum = colorSeries.BREWER_QUALITATIVE_SET3 colorSeries.SetColorScheme(seriesEnum) colorSeries.BuildLookupTable(lut, colorSeries.ORDINAL) # Fill in a few known colors, the rest will be generated if needed. colors = vtk.vtkNamedColors() # Create a mapper and actor. mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(source.GetOutputPort()) mapper.SetInputConnection(shrink.GetOutputPort()) mapper.SetScalarRange(0, numCells + 1) mapper.SetLookupTable(lut) mapper.SetScalarModeToUseCellData() mapper.SetResolveCoincidentTopologyToPolygonOffset() if (source.GetCellType() == vtk.VTK_QUADRATIC_PYRAMID or source.GetCellType() == vtk.VTK_QUADRATIC_WEDGE): mapper.SetInputConnection(shrink.GetOutputPort()) else: mapper.SetInputConnection(tessellate.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().EdgeVisibilityOn() # actor.GetProperty().SetLineWidth(3) textProperty = vtk.vtkTextProperty() textProperty.SetFontSize(20) textProperty.SetJustificationToCentered() textProperty.SetColor(colors.GetColor3d('Lamp_Black')) textMapper = vtk.vtkTextMapper() textMapper.SetInput(cellName) textMapper.SetTextProperty(textProperty) textActor = vtk.vtkActor2D() textActor.SetMapper(textMapper) textActor.SetPosition(320, 20) # Create a renderer, render window, and interactor. renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.SetWindowName('CellTypeSource') renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) # Add the actors to the scene. renderer.AddViewProp(textActor) renderer.AddActor(actor) renderer.SetBackground(colors.GetColor3d('Silver')) renderer.ResetCamera() renderer.GetActiveCamera().Azimuth(30) renderer.GetActiveCamera().Elevation(30) renderer.ResetCameraClippingRange() # Render and interact. renderWindow.SetSize(640, 480) renderWindow.Render() renderWindowInteractor.Start()
def create_sample_element(cell_type, order=3, visualize=True): from distutils.version import LooseVersion if LooseVersion(vtk.VTK_VERSION) > "8.2.0": vtk_version = (2, 2) else: vtk_version = (2, 1) cell_type = cell_type.upper() vtk_cell_type = getattr(vtk, cell_type, None) if vtk_cell_type is None: raise ValueError("unknown cell type: '%s'" % cell_type) source = vtk.vtkCellTypeSource() source.SetCellType(vtk_cell_type) source.SetBlocksDimensions(1, 1, 1) if "LAGRANGE" in cell_type: source.SetCellOrder(order) # 0 - single precision; 1 - double precision source.SetOutputPrecision(1) source.Update() grid = source.GetOutput() cell = grid.GetCell(0) points = vtk_to_numpy(cell.GetPoints().GetData()).copy().T dim = cell.GetCellDimension() points = points[0:dim] basename = f"sample_{cell_type.lower()}" if visualize: filename = f"{basename}.vtu" print("vtk xml version:", vtk_version) print("cell type: %s" % cell_type) print("output: %s" % filename) writer = vtk.vtkXMLUnstructuredGridWriter() writer.SetFileName(filename) writer.SetCompressorTypeToNone() writer.SetDataModeToAscii() writer.SetInputData(grid) writer.Write() # NOTE: vtkCellTypeSource always tesselates a square and the way it does # that to get tetrahedra changed in # https://gitlab.kitware.com/vtk/vtk/-/merge_requests/6529 if LooseVersion(vtk.VTK_VERSION) > "8.2.0" \ and cell_type == "VTK_LAGRANGE_TETRAHEDRON": rot = np.array([ [1, -1, 0], [0, 1, -1], [0, 0, 2] ]) points = rot @ points if cell_type in VTK_LAGRANGE_SIMPLICES: from pyvisfile.vtk.vtk_ordering import ( vtk_lagrange_simplex_node_tuples, vtk_lagrange_simplex_node_tuples_to_permutation) node_tuples = vtk_lagrange_simplex_node_tuples(dim, order, vtk_version=vtk_version) vtk_lagrange_simplex_node_tuples_to_permutation(node_tuples) nodes = np.array(node_tuples) / order error = la.norm(nodes - points.T) elif cell_type in VTK_LAGRANGE_QUADS: from pyvisfile.vtk.vtk_ordering import ( vtk_lagrange_quad_node_tuples, vtk_lagrange_quad_node_tuples_to_permutation) node_tuples = vtk_lagrange_quad_node_tuples(dim, order, vtk_version=vtk_version) vtk_lagrange_quad_node_tuples_to_permutation(node_tuples) nodes = np.array(node_tuples) / order error = la.norm(nodes - points.T) else: error = None # NOTE: skipping the curve check because the ordering is off in the # vtkCellTypeSource output # https://gitlab.kitware.com/vtk/vtk/-/merge_requests/6555 if LooseVersion(vtk.VTK_VERSION) <= "8.2.0" \ and cell_type == "VTK_LAGRANGE_CURVE": error = None if error is not None: if error < 5.0e-15: print(f"\033[92m[PASSED] order {order:2d} error {error:.5e}\033[0m") else: print(f"\033[91m[FAILED] order {order:2d} error {error:.5e}\033[0m") if not visualize: return filename = f"{basename}_vtk" plot_node_ordering(filename, points, show=False) if cell_type in (VTK_LAGRANGE_SIMPLICES + VTK_LAGRANGE_QUADS): filename = f"{basename}_pyvisfile" plot_node_ordering(filename, nodes.T, show=False)
#!/usr/bin/env python import vtk # Test filter input validity check on datasets with linear and nonlinear cells linearCells = vtk.vtkCellTypeSource() linearCells.SetCellType(vtk.VTK_HEXAHEDRON) linearCells.Update() assert (vtk.vtkContour3DLinearGrid.CanFullyProcessDataObject( linearCells.GetOutput(), 'DistanceToCenter')) # Test filter input validity check on datasets with linear and nonlinear cells quadraticCells = vtk.vtkCellTypeSource() quadraticCells.SetCellType(vtk.VTK_QUADRATIC_HEXAHEDRON) quadraticCells.Update() assert (not vtk.vtkContour3DLinearGrid.CanFullyProcessDataObject( quadraticCells.GetOutput(), 'DistanceToCenter')) # Test vtkContour3DLinearGrid on mixed cell types as well as on wedges and # pyramids. # Control test parameters mergePoints = 1 interpolateAttr = 1 computeNormals = 1 # Manually create an unstructured grid with a mix of cells. We have: quad; # 3x3x3 volume; triangle; 3x3x3 structured grid; pixel; pyramid; wedge. Total # of 76 points, 21 cells. ugrid = vtk.vtkUnstructuredGrid() pts = vtk.vtkPoints() pts.SetNumberOfPoints(76)
ghostArray.Modified() removeGhosts.Modified() removeGhosts.Update() if outPD.GetNumberOfCells() != numOrigCells-1: print("Should have had one less cell but did not", outPD.GetNumberOfCells(), numOrigCells) sys.exit(1) # =================== testing polydata ======================== disk = vtk.vtkDiskSource() disk.SetRadialResolution(2) disk.SetCircumferentialResolution(9) disk.Update() CheckFilter(disk.GetOutput()) # =================== testing unstructured grid ======================== cellTypeSource = vtk.vtkCellTypeSource() cellTypeSource.SetBlocksDimensions(4, 5, 6) cellTypeSource.Update() CheckFilter(cellTypeSource.GetOutput()) print("SUCCESS") sys.exit(0)
#!/usr/bin/env python import vtk # Test filter input validity check on datasets with linear and nonlinear cells linearCells = vtk.vtkCellTypeSource() linearCells.SetCellType(vtk.VTK_HEXAHEDRON) linearCells.Update() assert(vtk.vtkContour3DLinearGrid.CanProcessDataObject(linearCells.GetOutput(), 'DistanceToCenter')) # Test filter input validity check on datasets with linear and nonlinear cells quadraticCells = vtk.vtkCellTypeSource() quadraticCells.SetCellType(vtk.VTK_QUADRATIC_HEXAHEDRON) quadraticCells.Update() assert(not vtk.vtkContour3DLinearGrid.CanProcessDataObject(quadraticCells.GetOutput(), 'DistanceToCenter')) # Test vtkContour3DLinearGrid on mixed cell types as well as on wedges and # pyramids. # Control test parameters mergePoints = 1 interpolateAttr = 1 computeNormals = 1 # Manually create an unstructured grid with a mix of cells. We have: quad; # 3x3x3 volume; triangle; 3x3x3 structured grid; pixel; pyramid; wedge. Total # of 76 points, 21 cells. ugrid = vtk.vtkUnstructuredGrid() pts = vtk.vtkPoints() pts.SetNumberOfPoints(76) ugrid.SetPoints(pts) pts.SetPoint(0, 0,0,0)