Пример #1
0
def vtk_ensure_trilist(polydata):
    try:
        import vtk
        from vtk.util.numpy_support import vtk_to_numpy

        trilist = vtk_to_numpy(polydata.GetPolys().GetData())

        # 5 is the triangle type - if we have another type we need to
        # use a vtkTriangleFilter
        c = vtk.vtkCellTypes()
        polydata.GetCellTypes(c)

        if c.GetNumberOfTypes() != 1 or polydata.GetCellType(0) != 5:
            warnings.warn('Non-triangular mesh connectivity was detected - '
                          'this is currently unsupported and thus the '
                          'connectivity is being coerced into a triangular '
                          'mesh. This may have unintended consequences.')
            t_filter = vtk.vtkTriangleFilter()
            t_filter.SetInputData(polydata)
            t_filter.Update()
            trilist = vtk_to_numpy(t_filter.GetOutput().GetPolys().GetData())

        return trilist.reshape([-1, 4])[:, 1:]
    except Exception as e:
        warnings.warn(str(e))
        return None
Пример #2
0
def vtk_ensure_trilist(polydata):
    try:
        import vtk
        from vtk.util.numpy_support import vtk_to_numpy

        trilist = vtk_to_numpy(polydata.GetPolys().GetData())

        # 5 is the triangle type - if we have another type we need to
        # use a vtkTriangleFilter
        c = vtk.vtkCellTypes()
        polydata.GetCellTypes(c)

        if c.GetNumberOfTypes() != 1 or polydata.GetCellType(0) != 5:
            warnings.warn('Non-triangular mesh connectivity was detected - '
                          'this is currently unsupported and thus the '
                          'connectivity is being coerced into a triangular '
                          'mesh. This may have unintended consequences.')
            t_filter = vtk.vtkTriangleFilter()
            t_filter.SetInputData(polydata)
            t_filter.Update()
            trilist = vtk_to_numpy(t_filter.GetOutput().GetPolys().GetData())

        return trilist.reshape([-1, 4])[:, 1:]
    except Exception as e:
        warnings.warn(str(e))
        return None
Пример #3
0
	def get_node_data_n(self, file_name):
		"""
		Reads mesh information. Returns a numpy arrays of nodes & elements in 'abaqus' format.
		"""
		meshSource=vtk.vtkUnstructuredGridReader()
		meshSource.SetFileName(file_name)
		meshSource.Update()

		#get nodes & elements returned to numpy arrays
		nread=v2n(meshSource.GetOutput().GetPoints().GetData())
		#allocate for extra node numbers to be input
		node_data=np.zeros((np.shape(nread)[0],np.shape(nread)[1]+1))
		#reshape according to 'abaqus' standards (node num, coord1, 2 ...)
		node_data[:,0]=np.arange(np.shape(nread)[0])+1
		node_data[:,1:]=nread
		# print([np.shape(np.arange(np.shape(n)[0])].transpose()))
		e=v2n(meshSource.GetOutput().GetCells().GetData())

		#get cell types & reshape element array as needed.
		tcs=vtk.vtkCellTypes()
		meshSource.GetOutput().GetCellTypes(tcs)

		#reshape according to 'abaqus' standards (elem number, connectivity1 2 ...)
		if tcs.IsType(12)==1:
			self.mainCellType=12 #1st order quad
			element_data=np.resize(e,(int(len(e)/float(9)),9))
			element_data[:,0]=np.arange(np.shape(element_data)[0])+1
		elif tcs.IsType(24)==1:
			self.mainCellType=24 #2nd order tet
			element_data=np.resize(e,(int(len(e)/float(11)),11))
			element_data[:,0]=np.arange(np.shape(element_data)[0])+1
		# print(np.shape(node_data),np.shape(element_data)) #debug
		return node_data, element_data+1 #add one to the element number to match abaqus format
Пример #4
0
def add_unstructured_grid(vtk_dataset, tecplot_dataset):
    assert (vtk_dataset)
    assert (vtk_dataset.GetDataObjectType()
            in [vtk.VTK_UNSTRUCTURED_GRID, vtk.VTK_POLY_DATA])

    num_cells = vtk_dataset.GetNumberOfCells()
    num_points = vtk_dataset.GetNumberOfPoints()

    if tecplot_dataset.num_variables == 0:
        # Add the XYZ variables - a dataset needs one variable before you can add a zone
        tecplot_dataset.add_variable('x', dtypes=[FieldDataType.Float])
        tecplot_dataset.add_variable('y', dtypes=[FieldDataType.Float])
        tecplot_dataset.add_variable('z', dtypes=[FieldDataType.Float])

    zone_name = "NO ZONE NAME"

    if num_cells:
        cell_types = set()
        cell_type_array = vtk.vtkCellTypes()
        vtk_dataset.GetCellTypes(cell_type_array)
        for i in range(cell_type_array.GetNumberOfTypes()):
            cell_types.add(cell_type_array.GetCellType(i))
        if len(cell_types) > 1:
            print("Multiple cell types found: ", cell_types)
        zn_type = get_best_zone_type(cell_types)

        face_map = None
        if is_unstructured_zone(zn_type):
            zone = tecplot_dataset.add_fe_zone(zn_type, zone_name, num_points,
                                               num_cells)
        elif is_polytope_zone(zn_type):
            face_map = get_face_map(vtk_dataset, zn_type)
            zone = tecplot_dataset.add_poly_zone(zn_type, zone_name,
                                                 num_points, num_cells,
                                                 len(face_map))
    else:
        # No Cells!
        zone = tecplot_dataset.add_ordered_zone(zone_name, (num_points, 1, 1))

    # Write XYZ values
    xyz_points = get_points(vtk_dataset)
    zone.values(0)[:] = xyz_points[0]
    zone.values(1)[:] = xyz_points[1]
    zone.values(2)[:] = xyz_points[2]

    # TODO - Figure out how to use FieldData
    #fd = vtk_dataset.GetFieldData()

    pd = vtk_dataset.GetPointData()
    add_point_data(pd, zone)

    if num_cells:
        cd = vtk_dataset.GetCellData()
        add_cell_data(cd, zone)
        if is_polytope_zone(zone.zone_type):
            add_face_map(vtk_dataset, zone, face_map)
        else:
            add_connectivity_data(vtk_dataset, zone)
    return zone
Пример #5
0
def extract_boundary(ugrid):
    """Extract the boundary elements from an unstructured grid, provided it already contains them.

    Args:

    ugrid (vtkUnstructuredGrid): The grid with which to work.

    Results:

    out_grid (vtkUnstructuredGrid): Grid containing the boundary of ugrid"""

    out_grid = vtk.vtkUnstructuredGrid()
    pts = vtk.vtkPoints()
    pts.DeepCopy(ugrid.GetPoints())
    out_grid.SetPoints(pts)
    out_grid.GetCellData().CopyStructure(ugrid.GetCellData())

    celltypes = vtk.vtkCellTypes()

    ugrid.GetCellTypes(celltypes)

    if any([celltypes.IsType(ct) for ct in TYPES_3D]):
        dim = 3
    elif any([celltypes.IsType(ct) for ct in TYPES_2D]):
        dim = 2
    elif any([celltypes.IsType(ct) for ct in TYPES_1D]):
        dim = 1
    else:
        dim = 0

    def get_dimension(cell):
        cellType = cell.GetCellType()
        if cellType in TYPES_3D:
            return 3
        elif cellType in TYPES_2D:
            return 2
        elif cellType in TYPES_1D:
            return 1
        else:
            return 0

    ncells = ugrid.GetNumberOfCells()
    ncda = ugrid.GetCellData().GetNumberOfArrays()

    for i in range(ncda):
        out_grid.GetCellData().GetArray(i).SetName(ugrid.GetCellData().GetArray(i).GetName())

    cell_data = ugrid.GetCellData()
    for i in range(ncells):
        cell = ugrid.GetCell(i)
        if dim > get_dimension(cell):
            out_grid.InsertNextCell(cell.GetCellType(),
                                    cell.GetPointIds())
            for j in range(ncda):
                out_data = out_grid.GetCellData().GetArray(j)
                out_data.InsertNextTuple(cell_data.GetArray(j).GetTuple(i))

    return out_grid
Пример #6
0
def get_number_of_cell_types(surf):
    """Get number of cell types of `surf`.

    Parameters
    ----------
    surf : BSDataSet
        Input data.

    Returns
    -------
    int
        Number of cell types.
    """
    lid = vtkCellTypes()
    surf.GetCellTypes(lid)
    return lid.GetNumberOfTypes()
Пример #7
0
def get_cell_types(surf):
    """Get cell types of `surf`.

    Parameters
    ----------
    surf : BSDataSet
        Input data.

    Returns
    -------
    cell_types : 1D ndarray
        Array of cell types.
    """
    lid = vtkCellTypes()
    surf.GetCellTypes(lid)
    types = [lid.GetCellType(i) for i in range(lid.GetNumberOfTypes())]
    return np.asarray(types)
Пример #8
0
    def get_node_data_n(self, file_name):
        """
		Reads mesh information. Returns a numpy arrays of nodes & elements in 'abaqus' format.
		"""
        meshSource = vtk.vtkUnstructuredGridReader()
        meshSource.SetFileName(file_name)
        meshSource.Update()

        #get nodes & elements returned to numpy arrays
        nread = v2n(meshSource.GetOutput().GetPoints().GetData())
        #allocate for extra node numbers to be input
        node_data = np.zeros((np.shape(nread)[0], np.shape(nread)[1] + 1))
        #reshape according to 'abaqus' standards (node num, coord1, 2 ...)
        node_data[:, 0] = np.arange(np.shape(nread)[0]) + 1
        node_data[:, 1:] = nread
        # print([np.shape(np.arange(np.shape(n)[0])].transpose()))
        e = v2n(meshSource.GetOutput().GetCells().GetData())

        #get cell types & reshape element array as needed.
        tcs = vtk.vtkCellTypes()
        meshSource.GetOutput().GetCellTypes(tcs)

        #reshape according to 'abaqus' standards (elem number, connectivity1 2 ...)
        if tcs.IsType(12) == 1:
            mainCellType = 12  #1st order quad
            element_data = np.resize(e, (int(len(e) / float(9)), 9))
            element_data[:, 0] = np.arange(np.shape(element_data)[0]) + 1
            print('Quaaad')  #debug
            self.ui.quadButton.setChecked(True)
        elif tcs.IsType(24) == 1:
            mainCellType = 24  #2nd order tet
            element_data = np.resize(e, (int(len(e) / float(11)), 11))
            element_data[:, 0] = np.arange(np.shape(element_data)[0]) + 1
            print('Tet tet tet')  #debug
            self.ui.tetButton.setChecked(True)
        # print(np.shape(node_data),np.shape(element_data)) #debug
        return node_data, element_data + 1  #add one to the element number to match abaqus format
def main():
    colors = vtk.vtkNamedColors()

    # Create polydata to slice the grid with. In this case, use a cone. This
    # could
    # be any polydata including a stl file.
    cone = vtk.vtkConeSource()
    cone.SetResolution(50)
    cone.SetDirection(0, 0, -1)
    cone.SetHeight(3.0)
    cone.CappingOn()
    cone.Update()

    # Implicit function that will be used to slice the mesh
    implicitPolyDataDistance = vtk.vtkImplicitPolyDataDistance()
    implicitPolyDataDistance.SetInput(cone.GetOutput())

    # create a grid
    dimension = 51
    xCoords = vtk.vtkFloatArray()
    for x, i in enumerate(np.linspace(-1.0, 1.0, dimension)):
        xCoords.InsertNextValue(i)

    yCoords = vtk.vtkFloatArray()
    for y, i in enumerate(np.linspace(-1.0, 1.0, dimension)):
        yCoords.InsertNextValue(i)

    zCoords = vtk.vtkFloatArray()
    for z, i in enumerate(np.linspace(-1.0, 1.0, dimension)):
        zCoords.InsertNextValue(i)

    # # create a grid - if not using numpy
    # dimension = 51
    # xCoords = vtk.vtkFloatArray()
    # for i in range(0, dimension):
    #     xCoords.InsertNextValue(-1.0 + i * 2.0 / (dimension - 1))
    #
    # yCoords = vtk.vtkFloatArray()
    # for i in range(0, dimension):
    #     yCoords.InsertNextValue(-1.0 + i * 2.0 / (dimension - 1))
    #
    # zCoords = vtk.vtkFloatArray()
    # for i in range(0, dimension):
    #     zCoords.InsertNextValue(-1.0 + i * 2.0 / (dimension - 1))

    # The coordinates are assigned to the rectilinear grid. Make sure that
    # the number of values in each of the XCoordinates, YCoordinates,
    # and ZCoordinates is equal to what is defined in SetDimensions().
    rgrid = vtk.vtkRectilinearGrid()
    rgrid.SetDimensions(xCoords.GetNumberOfTuples(),
                        yCoords.GetNumberOfTuples(),
                        zCoords.GetNumberOfTuples())
    rgrid.SetXCoordinates(xCoords)
    rgrid.SetYCoordinates(yCoords)
    rgrid.SetZCoordinates(zCoords)

    # Create an array to hold distance information
    signedDistances = vtk.vtkFloatArray()
    signedDistances.SetNumberOfComponents(1)
    signedDistances.SetName('SignedDistances')

    # Evaluate the signed distance function at all of the grid points
    for pointId in range(0, rgrid.GetNumberOfPoints()):
        p = rgrid.GetPoint(pointId)
        signedDistance = implicitPolyDataDistance.EvaluateFunction(p)
        signedDistances.InsertNextValue(signedDistance)

    # Add the SignedDistances to the grid
    rgrid.GetPointData().SetScalars(signedDistances)

    # Use vtkClipDataSet to slice the grid with the polydata
    clipper = vtk.vtkClipDataSet()
    clipper.SetInputData(rgrid)
    clipper.InsideOutOn()
    clipper.SetValue(0.0)
    clipper.GenerateClippedOutputOn()
    clipper.Update()

    # --- mappers, actors, render, etc. ---
    # mapper and actor to view the cone
    coneMapper = vtk.vtkPolyDataMapper()
    coneMapper.SetInputConnection(cone.GetOutputPort())
    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMapper)

    # geometry filter to view the background grid
    geometryFilter = vtk.vtkRectilinearGridGeometryFilter()
    geometryFilter.SetInputData(rgrid)
    geometryFilter.SetExtent(0, dimension, 0, dimension, int(dimension / 2), int(dimension / 2))
    geometryFilter.Update()

    rgridMapper = vtk.vtkPolyDataMapper()
    rgridMapper.SetInputConnection(geometryFilter.GetOutputPort())
    rgridMapper.SetScalarRange(
        rgrid.GetPointData().GetArray('SignedDistances').GetRange())

    wireActor = vtk.vtkActor()
    wireActor.SetMapper(rgridMapper)
    wireActor.GetProperty().SetRepresentationToWireframe()

    # mapper and actor to view the clipped mesh
    clipperMapper = vtk.vtkDataSetMapper()
    clipperMapper.SetInputConnection(clipper.GetOutputPort())
    clipperMapper.ScalarVisibilityOff()

    clipperOutsideMapper = vtk.vtkDataSetMapper()
    clipperOutsideMapper.SetInputConnection(clipper.GetOutputPort(1))
    clipperOutsideMapper.ScalarVisibilityOff()

    clipperActor = vtk.vtkActor()
    clipperActor.SetMapper(clipperMapper)
    clipperActor.GetProperty().SetColor(colors.GetColor3d('Banana'))

    clipperOutsideActor = vtk.vtkActor()
    clipperOutsideActor.SetMapper(clipperOutsideMapper)
    clipperOutsideActor.GetProperty().SetColor(
        colors.GetColor3d('Banana'))

    # A renderer and render window
    # Create a renderer, render window, and interactor
    leftViewport = [0.0, 0.0, 0.5, 1.0]
    leftRenderer = vtk.vtkRenderer()
    leftRenderer.SetViewport(leftViewport)
    leftRenderer.SetBackground(colors.GetColor3d('SteelBlue'))

    rightViewport = [0.5, 0.0, 1.0, 1.0]
    rightRenderer = vtk.vtkRenderer()
    rightRenderer.SetViewport(rightViewport)
    rightRenderer.SetBackground(colors.GetColor3d('CadetBlue'))

    # add the actors
    leftRenderer.AddActor(wireActor)
    leftRenderer.AddActor(clipperActor)
    rightRenderer.AddActor(clipperOutsideActor)

    renwin = vtk.vtkRenderWindow()
    renwin.SetSize(640, 480)
    renwin.AddRenderer(leftRenderer)
    renwin.AddRenderer(rightRenderer)
    renwin.SetWindowName('ClipDataSetWithPolyData')

    # An interactor
    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renwin)

    # Share the camera

    leftRenderer.GetActiveCamera().SetPosition(0, -1, 0)
    leftRenderer.GetActiveCamera().SetFocalPoint(0, 0, 0)
    leftRenderer.GetActiveCamera().SetViewUp(0, 0, 1)
    leftRenderer.GetActiveCamera().Azimuth(30)
    leftRenderer.GetActiveCamera().Elevation(30)
    leftRenderer.ResetCamera()
    rightRenderer.SetActiveCamera(leftRenderer.GetActiveCamera())

    renwin.Render()
    interactor.Start()

    # Generate a report
    ct = vtk.vtkCellTypes()

    numberOfCells = clipper.GetOutput().GetNumberOfCells()
    print('------------------------')
    print('The clipped dataset(inside) contains a\n', clipper.GetOutput().GetClassName(), 'that has', numberOfCells,
          'cells')
    cellMap = dict()
    for i in range(0, numberOfCells):
        cellMap[clipper.GetOutput().GetCellType(i)] = cellMap.get(clipper.GetOutput().GetCellType(i), 0) + 1

    for k, v in cellMap.items():
        print('\tCell type ', ct.GetClassNameFromTypeId(k), 'occurs', v, 'times.')
        
    numberOfCells = clipper.GetClippedOutput().GetNumberOfCells()
    print('------------------------')
    print('The clipped dataset(outside) contains a\n', clipper.GetClippedOutput().GetClassName(), 'that has',
          numberOfCells, 'cells')
    outsideCellMap = dict()
    for i in range(0, numberOfCells):
        outsideCellMap[clipper.GetClippedOutput().GetCellType(i)] = outsideCellMap.get(
            clipper.GetClippedOutput().GetCellType(i), 0) + 1

    for k, v in outsideCellMap.items():
        print('\tCell type ', ct.GetClassNameFromTypeId(k), 'occurs', v, 'times.')