コード例 #1
0
ファイル: findboundaries.py プロジェクト: santiama/OOF3D
def makeTetraGrid(nCubes, flip=0):
    max_x=nCubes+1
    max_y=nCubes+1
    max_z=nCubes+1
    scale=20./nCubes #*(19./20)
    meshPoints = vtk.vtkPoints()
    meshPoints.SetNumberOfPoints(max_x*max_y*max_z)
    #i*(max_y)*(max_z)+j*(max_z)+k
    for i in xrange(max_x):
        for j in xrange(max_y):
            for k in xrange(max_z):
                meshPoints.InsertPoint(i*(max_y)*(max_z)+j*(max_z)+k,scale*i,scale*j,scale*k)

    nelements = 5*(max_x-1)*(max_y-1)*(max_z-1)
    meshGrid = vtk.vtkUnstructuredGrid()
    meshGrid.Allocate(nelements, nelements)
    meshGrid.SetPoints(meshPoints)

    for i in range(max_x-1):                  
        for j in range(max_y-1):              
            for k in range(max_z-1):
                ulf = (i+1)*(max_y)*(max_z)+j*(max_z)+k        # upper left front
                urf = (i+1)*(max_y)*(max_z)+(j+1)*(max_z)+k    # upper right front
                lrf = i*(max_y)*(max_z)+(j+1)*(max_z)+k        # lower right front
                llf = i*(max_y)*(max_z)+j*(max_z)+k            # lower left front 
                ulb = (i+1)*(max_y)*(max_z)+j*(max_z)+k+1      # upper left back
                urb = (i+1)*(max_y)*(max_z)+(j+1)*(max_z)+k+1  # upper right back 
                lrb = i*(max_y)*(max_z)+(j+1)*(max_z)+k+1      # lower right back
                llb = i*(max_y)*(max_z)+j*(max_z)+k+1          # lower left back
                
                point_order = [  # not flip
                    [[llf,urf,lrf,lrb],
                     [llf,ulf,urf,ulb],
                     [lrb,urf,urb,ulb],
                     [llf,lrb,llb,ulb],
                     [llf,ulb,urf,lrb]],
                    # flip
                    [[llf,ulf,lrf,llb],
                     [ulf,urf,lrf,urb],
                     [ulf,ulb,urb,llb],
                     [lrf,urb,lrb,llb],
                     [ulf,urb,lrf,llb]
                     ]]
                
                for o in point_order[flip]:
                    cell = vtk.vtkTetra()
                    id=0
                    for p in o:
                        cell.GetPointIds().SetId(id,p)
                        id+=1
                    meshGrid.InsertNextCell(cell.GetCellType(),cell.GetPointIds())

                flip = not flip

            if (max_z-1)%2==0:
                flip = not flip
        if (max_y-1)%2==0:
            flip = not flip

    return meshGrid
コード例 #2
0
ファイル: makeSampleMeshFiles.py プロジェクト: CusiniM/GEOSX
def make_cell_array(index_list):
    cells = vtk.vtkCellArray()
    n_nodes = len(index_list[0])

    for node_list in index_list:
        if n_nodes == 8:
            cell = vtk.vtkHexahedron()
        elif n_nodes == 4:
            cell = vtk.vtkTetra()
        elif n_nodes == 5:
            cell = vtk.vtkPyramid()
        elif n_nodes == 6:
            cell = vtk.vtkWedge()
        else:
            print(f'{n_nodes} nodes are not supported at this time')

        for ind, value in enumerate(node_list):
            cell.GetPointIds().SetId(ind, value)

        cells.InsertNextCell(cell)

    if n_nodes == 8:
        cell_type = vtk.VTK_HEXAHEDRON
    elif n_nodes == 4:
        cell_type = vtk.VTK_TETRA
    elif n_nodes == 5:
        cell_type = vtk.VTK_PYRAMID
    elif n_nodes == 6:
        cell_type = vtk.VTK_WEDGE

    return cells, cell_type
コード例 #3
0
    def testLinear(self):
        pts = vtk.vtkPoints()
        pts.SetNumberOfPoints(4)
        pts.InsertPoint(0, (0, 0, 0))
        pts.InsertPoint(1, (1, 0, 0))
        pts.InsertPoint(2, (0.5, 1, 0))
        pts.InsertPoint(3, (0.5, 0.5, 1))

        te = vtk.vtkTetra()
        ptIds = te.GetPointIds()
        for i in range(4):
            ptIds.SetId(i, i)

        ghosts = vtk.vtkUnsignedCharArray()
        ghosts.SetName("vtkGhostLevels")
        ghosts.SetNumberOfTuples(4)
        ghosts.SetValue(0, 1)
        ghosts.SetValue(1, 1)
        ghosts.SetValue(2, 1)
        ghosts.SetValue(3, 0)

        grid = vtk.vtkUnstructuredGrid()
        grid.Allocate(1, 1)
        grid.InsertNextCell(te.GetCellType(), te.GetPointIds())
        grid.SetPoints(pts)
        grid.GetPointData().AddArray(ghosts)

        dss = vtk.vtkDataSetSurfaceFilter()
        dss.SetInputData(grid)
        dss.Update()
        self.assertEqual(dss.GetOutput().GetNumberOfCells(), 3)
コード例 #4
0
    def testLinear(self):
        pts = vtk.vtkPoints()
        pts.SetNumberOfPoints(4)
        pts.InsertPoint(0, (0, 0, 0))
        pts.InsertPoint(1, (1, 0, 0))
        pts.InsertPoint(2, (0.5, 1, 0))
        pts.InsertPoint(3, (0.5, 0.5, 1))

        te = vtk.vtkTetra()
        ptIds = te.GetPointIds()
        for i in range(4):
            ptIds.SetId(i, i)

        ghosts = vtk.vtkUnsignedCharArray()
        ghosts.SetName(vtk.vtkDataSetAttributes.GhostArrayName())
        ghosts.SetNumberOfTuples(4)
        ghosts.SetValue(0, 1)
        ghosts.SetValue(1, 1)
        ghosts.SetValue(2, 1)
        ghosts.SetValue(3, 0)

        grid = vtk.vtkUnstructuredGrid()
        grid.Allocate(1, 1)
        grid.InsertNextCell(te.GetCellType(), te.GetPointIds())
        grid.SetPoints(pts)
        grid.GetPointData().AddArray(ghosts)

        dss = vtk.vtkDataSetSurfaceFilter()
        dss.SetInputData(grid)
        dss.Update()
        self.assertEqual(dss.GetOutput().GetNumberOfCells(), 3)
コード例 #5
0
def main():
    filenames = list()
    uGrids = list()

    uGrids.append(MakeUnstructuredGrid(vtk.vtkVertex()))
    filenames.append('Vertex.vtu')

    uGrids.append(MakePolyVertex())
    filenames.append('PolyVertex.vtu')

    uGrids.append(MakeUnstructuredGrid(vtk.vtkLine()))
    filenames.append('Line.vtu')

    uGrids.append(MakePolyLine())
    filenames.append('PolyLine.vtu')

    uGrids.append(MakeUnstructuredGrid(vtk.vtkTriangle()))
    filenames.append('Triangle.vtu')

    uGrids.append(MakeTriangleStrip())
    filenames.append('TriangleStrip.vtu')

    uGrids.append(MakePolygon())
    filenames.append('Polygon.vtu')

    uGrids.append(MakeUnstructuredGrid(vtk.vtkPixel()))
    filenames.append('Pixel.vtu')

    uGrids.append(MakeUnstructuredGrid(vtk.vtkQuad()))
    filenames.append('Quad.vtu')

    uGrids.append(MakeUnstructuredGrid(vtk.vtkTetra()))
    filenames.append('Tetra.vtu')

    uGrids.append(MakeUnstructuredGrid(vtk.vtkVoxel()))
    filenames.append('Voxel.vtu')

    uGrids.append(MakeUnstructuredGrid(vtk.vtkHexahedron()))
    filenames.append('Hexahedron.vtu')

    uGrids.append(MakeUnstructuredGrid(vtk.vtkWedge()))
    filenames.append('Wedge.vtu')

    uGrids.append(MakeUnstructuredGrid(vtk.vtkPyramid()))
    filenames.append('Pyramid.vtu')

    uGrids.append(MakeUnstructuredGrid(vtk.vtkPentagonalPrism()))
    filenames.append('PentagonalPrism.vtu')

    uGrids.append(MakeUnstructuredGrid(vtk.vtkHexagonalPrism()))
    filenames.append('HexagonalPrism.vtu')

    # Write each grid into  a file
    for i in range(0, len(uGrids)):
        print('Writing: ', filenames[i])
        writer = vtk.vtkXMLDataSetWriter()
        writer.SetFileName(filenames[i])
        writer.SetInputData(uGrids[i])
        writer.Write()
コード例 #6
0
def main():
    filenames = list()
    uGrids = list()

    uGrids.append(MakeUnstructuredGrid(vtk.vtkVertex()))
    filenames.append("Vertex.vtk")

    uGrids.append(MakePolyVertex())
    filenames.append("PolyVertex.vtk")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkLine()))
    filenames.append("Line.vtk")

    uGrids.append(MakePolyLine())
    filenames.append("PolyLine.vtk")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkTriangle()))
    filenames.append("Triangle.vtk")

    uGrids.append(MakeTriangleStrip())
    filenames.append("TriangleStrip.vtk")

    uGrids.append(MakePolygon())
    filenames.append("Polygon.vtk")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkPixel()))
    filenames.append("Pixel.vtk")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkQuad()))
    filenames.append("Quad.vtk")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkTetra()))
    filenames.append("Tetra.vtk")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkVoxel()))
    filenames.append("Voxel.vtk")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkHexahedron()))
    filenames.append("Hexahedron.vtk")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkWedge()))
    filenames.append("Wedge.vtk")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkPyramid()))
    filenames.append("Pyramid.vtk")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkPentagonalPrism()))
    filenames.append("PentagonalPrism.vtk")

    uGrids.append(MakeUnstructuredGrid(vtk.vtkHexagonalPrism()))
    filenames.append("HexagonalPrism.vtk")

    # Write each grid into  a file
    for i in range(0, len(uGrids)):
        print("Writing: ", filenames[i])
        writer = vtk.vtkUnstructuredGridWriter()
        writer.SetFileName(filenames[i])
        writer.SetInputData(uGrids[i])
        writer.Write()
コード例 #7
0
def create_cell(elem):
    tetra = vtk.vtkTetra()
    ids = tetra.GetPointIds()
    ids.SetId(0, elem[0])
    ids.SetId(1, elem[1])
    ids.SetId(2, elem[2])
    ids.SetId(3, elem[3])
    return tetra
コード例 #8
0
ファイル: vtk_output.py プロジェクト: tbetcke/PyPWDG
 def create_cell(elem):
     tetra = vtk.vtkTetra()
     ids = tetra.GetPointIds()
     ids.SetId(0, elem[0])
     ids.SetId(1, elem[1])
     ids.SetId(2, elem[2])
     ids.SetId(3, elem[3])
     return tetra
コード例 #9
0
ファイル: DataBase.py プロジェクト: zhangjunda23/VolumeData
    def GenTetraUnstructuredGrid(self, n: int, threshold=0):
        """
        构造四面体网格的非结构化体数据
        :param n:抽取个数,n需要被4整除
        :param threshold:小于threshold的点将被剔除
        :return:vtkUnstructuredGrid
        """

        if n % 4 != 0:  # 如果n不是4的倍数
            print("参数n需要被4整除")
            return None
        else:
            points = vtk.vtkPoints()  # 点的集合
            tetraArray = vtk.vtkCellArray()  # 四面体cell的集合
            tetraType = vtk.vtkTetra().GetCellType()

            if threshold == 0:
                randomData = self.RandomUnstructuredDataSet(
                    n)  # 先随机抽取n个非零值的数据点
            else:
                randomData = self.RandomUnstructuredDataSet(
                    n, threshold)  # 先随机抽取n个非零值的数据点
            pointCount = np.size(randomData, 0)

            for j in range(0, pointCount):  # 获取所有的点的位置坐标
                points.InsertNextPoint(randomData[j, 0], randomData[j, 1],
                                       randomData[j, 2])

            for k in range(0, int(pointCount / 4)):  # 定义四面体各个顶点的id,形成拓扑关系
                tetra = vtk.vtkTetra()  # 定义一个四面体

                for q in range(4):
                    tetra.GetPointIds().SetId(q, 4 * k + q)

                tetraArray.InsertNextCell(tetra)

            scalarArray = numpy2vtk(num_array=randomData[:, 3],
                                    array_type=vtk.VTK_FLOAT)

            uGrid = vtk.vtkUnstructuredGrid()
            uGrid.SetPoints(points)
            uGrid.GetPointData().SetScalars(scalarArray)
            uGrid.SetCells(tetraType, tetraArray)

            return uGrid
コード例 #10
0
def meshToUnstructeredGrid(mesh):
	
	"""Converts a FiPy mesh structure to a vtkUnstructuredGrid.
	
	Works for 2D and 3D meshes.
	
	Args:
		mesh (fipy.GmshImporter3D): Some Fipy mesh object.
		
	Returns:
		vtk.vtkUnstructuredGrid	
	"""
	
	
	# Get vertex coordinates
	coords=mesh.vertexCoords
	
	if len(coords)==2:
		x,y=coords
		dim=2
	else:
		x,y,z=coords
		dim=3
		
	# Insert them as points
	points = vtk.vtkPoints()
	for i in range(len(x)):
		if dim==2:
			points.InsertNextPoint(x[i], y[i],0)
		else:	
			points.InsertNextPoint(x[i], y[i],z[i])

	# Insert tetrahedrons
	verts=mesh._getOrderedCellVertexIDs().T
		
	cellArray = vtk.vtkCellArray()
	for j,vert in enumerate(verts):
		
		if dim==3:
			tetra = vtk.vtkTetra()
		else:
			tetra = vtk.vtkTriangle()
			
		for i,v in enumerate(vert):
			tetra.GetPointIds().SetId(i, v)
		cellArray.InsertNextCell(tetra)

	# Grid
	grid = vtk.vtkUnstructuredGrid()
	grid.SetPoints(points)
	
	if dim==3:
		grid.SetCells(vtk.VTK_TETRA, cellArray)
	else:
		grid.SetCells(vtk.VTK_TRIANGLE, cellArray)
	
	return grid
コード例 #11
0
def meshToUnstructeredGrid(mesh):
    """Converts a FiPy mesh structure to a vtkUnstructuredGrid.
	
	Works for 2D and 3D meshes.
	
	Args:
		mesh (fipy.GmshImporter3D): Some Fipy mesh object.
		
	Returns:
		vtk.vtkUnstructuredGrid	
	"""

    # Get vertex coordinates
    coords = mesh.vertexCoords

    if len(coords) == 2:
        x, y = coords
        dim = 2
    else:
        x, y, z = coords
        dim = 3

    # Insert them as points
    points = vtk.vtkPoints()
    for i in range(len(x)):
        if dim == 2:
            points.InsertNextPoint(x[i], y[i], 0)
        else:
            points.InsertNextPoint(x[i], y[i], z[i])

    # Insert tetrahedrons
    verts = mesh._getOrderedCellVertexIDs().T

    cellArray = vtk.vtkCellArray()
    for j, vert in enumerate(verts):

        if dim == 3:
            tetra = vtk.vtkTetra()
        else:
            tetra = vtk.vtkTriangle()

        for i, v in enumerate(vert):
            tetra.GetPointIds().SetId(i, v)
        cellArray.InsertNextCell(tetra)

    # Grid
    grid = vtk.vtkUnstructuredGrid()
    grid.SetPoints(points)

    if dim == 3:
        grid.SetCells(vtk.VTK_TETRA, cellArray)
    else:
        grid.SetCells(vtk.VTK_TRIANGLE, cellArray)

    return grid
コード例 #12
0
ファイル: vtk_tools.py プロジェクト: will214/fermi
def Vtk_cell_types():
    vtk_types = [
    ]  #(vtk_type, vtk_id, vtkCell) <= linear cell types found in VTK
    vtk_types.append(("VTK_TRIANGLE", 5, vtk.vtkTriangle()))
    vtk_types.append(("VTK_QUAD", 9, vtk.vtkQuad()))
    vtk_types.append(("VTK_TETRA", 10, vtk.vtkTetra()))
    vtk_types.append(("VTK_PYRAMID", 14, vtk.vtkPyramid()))
    vtk_types.append(("VTK_WEDGE", 13, vtk.vtkWedge()))
    vtk_types.append(("VTK_HEXAHEDRON", 12, vtk.vtkHexahedron()))

    return vtk_types
コード例 #13
0
ファイル: generalTools.py プロジェクト: hubitor/progs
def tetgen2vtk(name="mesh", arrayName="doubledNode"):
    """
    read tetgen output files into memory (ugrid)
    """
    ugrid = vtk.vtkUnstructuredGrid()
    points = vtk.vtkPoints()
    inFile = open(name + ".1.node", 'r')
    line = inFile.readline().split()
    nbnod = int(line[0])
    vtkArray = vtk.vtkIntArray()
    if arrayName:
        vtkArray.SetName(arrayName)
    vtkArray.SetNumberOfValues(nbnod)
    for i in range(nbnod):
        line = inFile.readline().split()
        points.InsertPoint(i, float(line[1]), float(line[2]), float(line[3]))
        try:
            vtkArray.SetValue(i,
                              int(line[4]) -
                              1)  #car on renumerote a nouveau a partir de 1
        except:
            vtkArray.SetValue(i, -1)

    ugrid.GetPointData().AddArray(vtkArray)
    inFile.close()
    ugrid.SetPoints(points)

    inFile = open(name + ".1.ele", 'r')
    line = inFile.readline().split()
    nbelm = int(line[0])
    materArray = vtk.vtkIntArray()
    materArray.SetName("material label")
    materArray.SetNumberOfValues(nbelm)
    for i in range(0, nbelm):
        line = inFile.readline().split()
        n1 = int(line[1]) - 1
        n2 = int(line[2]) - 1
        n3 = int(line[3]) - 1
        n4 = int(line[4]) - 1
        tetra = vtk.vtkTetra()
        tetra.GetPointIds().SetId(0, n1)
        tetra.GetPointIds().SetId(1, n2)
        tetra.GetPointIds().SetId(2, n3)
        tetra.GetPointIds().SetId(3, n4)
        ugrid.InsertNextCell(tetra.GetCellType(), tetra.GetPointIds())
        try:
            materArray.SetValue(i, int(line[5]))
        except:  # no material label
            materArray.SetValue(i, 1)

    ugrid.GetCellData().AddArray(materArray)
    inFile.close()

    return ugrid
コード例 #14
0
    def __init__(self):
        self.obj = None
        self.num_pts = -1
        self.vtk_pts = vtk.vtkPoints()
        self.vtk_cells = vtk.vtkCellArray()
        self.vtk_tetra = vtk.vtkTetra()

        self.vtk_props = []
        self.vtk_cells_type = []
        self.vtk_cells_id = []

        self.vtk_types = [
        ]  #(vtk_type, vtk_id, vtkCell) <= linear cell types found in VTK
        self.vtk_types.append(("VTK_TRIANGLE", 5, vtk.vtkTriangle()))
        self.vtk_types.append(("VTK_QUAD", 9, vtk.vtkQuad()))
        self.vtk_types.append(("VTK_TETRA", 10, vtk.vtkTetra()))
        self.vtk_types.append(("VTK_PYRAMID", 14, vtk.vtkPyramid()))
        self.vtk_types.append(("VTK_WEDGE", 13, vtk.vtkWedge()))
        self.vtk_types.append(("VTK_HEXAHEDRON", 12, vtk.vtkHexahedron()))

        print "\n+Vtk_writer"
コード例 #15
0
ファイル: WriteVTU.py プロジェクト: MBrill/VTKExamples
def main():
    filename = get_program_parameters()
    colors = vtk.vtkNamedColors()

    points = vtk.vtkPoints()

    points.InsertNextPoint(0, 0, 0)
    points.InsertNextPoint(1, 0, 0)
    points.InsertNextPoint(1, 1, 0)
    points.InsertNextPoint(0, 1, 1)

    tetra = vtk.vtkTetra()

    tetra.GetPointIds().SetId(0, 0)
    tetra.GetPointIds().SetId(1, 1)
    tetra.GetPointIds().SetId(2, 2)
    tetra.GetPointIds().SetId(3, 3)

    cell_array = vtk.vtkCellArray()
    cell_array.InsertNextCell(tetra)

    unstructured_grid = vtk.vtkUnstructuredGrid()
    unstructured_grid.SetPoints(points)
    unstructured_grid.SetCells(vtk.VTK_TETRA, cell_array)

    # Write file
    writer = vtk.vtkXMLUnstructuredGridWriter()
    writer.SetFileName(filename)
    writer.SetInputData(unstructured_grid)
    writer.Write()

    # Read and display file for verification that it was written correclty
    reader = vtk.vtkXMLUnstructuredGridReader()
    reader.SetFileName(filename)
    reader.Update()

    mapper = vtk.vtkDataSetMapper()
    mapper.SetInputConnection(reader.GetOutputPort())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    renderer = vtk.vtkRenderer()
    render_window = vtk.vtkRenderWindow()
    render_window.AddRenderer(renderer)
    render_window_interactor = vtk.vtkRenderWindowInteractor()
    render_window_interactor.SetRenderWindow(render_window)

    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d("Green"))

    render_window.Render()
    render_window_interactor.Start()
コード例 #16
0
ファイル: vtk_tools.py プロジェクト: mvdcvp/CPlantBox
def vtk_cells(t):
    """ Creates vtkCells from an numpy array """
    cellArray = vtk.vtkCellArray()
    for vert in t:
        if t.shape[1] == 2:
            tetra = vtk.vtkLine()
        if t.shape[1] == 3:
            tetra = vtk.vtkTriangle()
        elif t.shape[1] == 4:
            tetra = vtk.vtkTetra()
        for i, v in enumerate(vert):
            tetra.GetPointIds().SetId(i, int(v))
        cellArray.InsertNextCell(tetra)
    return cellArray
コード例 #17
0
ファイル: lab_2.py プロジェクト: HnykinAndrew/Sem_4_labs
    def snapshot(self, snap_number):
        # Сетка в терминах VTK
        unstructuredGrid = vtk.vtkUnstructuredGrid()
        # Точки сетки в терминах VTK
        points = vtk.vtkPoints()

        # Скалярное поле на точках сетки
        smth = vtk.vtkDoubleArray()
        smth.SetName("smth")

        # Векторное поле на точках сетки
        vel = vtk.vtkDoubleArray()
        vel.SetNumberOfComponents(3)
        vel.SetName("vel")

        # Обходим все точки нашей расчётной сетки
        # Делаем это максимально неэффективным, зато наглядным образом
        for i in range(0, len(self.nodes[0])):
            # Вставляем новую точку в сетку VTK-снапшота
            points.InsertNextPoint(self.nodes[0, i], self.nodes[1, i],
                                   self.nodes[2, i])
            # Добавляем значение скалярного поля в этой точке
            smth.InsertNextValue(self.smth[i])
            # Добавляем значение векторного поля в этой точке
            vel.InsertNextTuple(
                (self.velocity[0, i], self.velocity[1, i], self.velocity[2,
                                                                         i]))

        # Грузим точки в сетку
        unstructuredGrid.SetPoints(points)

        # Присоединяем векторное и скалярное поля к точкам
        unstructuredGrid.GetPointData().AddArray(smth)
        unstructuredGrid.GetPointData().AddArray(vel)

        # А теперь пишем, как наши точки объединены в тетраэдры
        # Делаем это максимально неэффективным, зато наглядным образом
        for i in range(0, len(self.tetrs[0])):
            tetr = vtk.vtkTetra()
            for j in range(0, 4):
                tetr.GetPointIds().SetId(j, self.tetrs[j, i])
            unstructuredGrid.InsertNextCell(tetr.GetCellType(),
                                            tetr.GetPointIds())

        # Создаём снапшот в файле с заданным именем
        writer = vtk.vtkXMLUnstructuredGridWriter()
        writer.SetInputDataObject(unstructuredGrid)
        writer.SetFileName("pls_work" + str(snap_number) + ".vtu")
        writer.Write()
コード例 #18
0
def buildPolyData(vertices, faces=None, indexOffset=0):
    '''
    Build a ``vtkPolyData`` object from a list of vertices
    where faces represents the connectivity of the polygonal mesh.

    E.g. :
        - ``vertices=[[x1,y1,z1],[x2,y2,z2], ...]``
        - ``faces=[[0,1,2], [1,2,3], ...]``

    Use ``indexOffset=1`` if face numbering starts from 1 instead of 0.
    
    .. hint:: Example: `buildpolydata.py <https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/buildpolydata.py>`_
    
        .. image:: https://user-images.githubusercontent.com/32848391/51032546-bf4dac00-15a0-11e9-9e1e-035fff9c05eb.png
    '''
    sourcePoints = vtk.vtkPoints()
    sourceVertices = vtk.vtkCellArray()
    sourcePolygons = vtk.vtkCellArray()
    for pt in vertices:
        if len(pt) > 2:
            aid = sourcePoints.InsertNextPoint(pt[0], pt[1], pt[2])
        else:
            aid = sourcePoints.InsertNextPoint(pt[0], pt[1], 0)
        sourceVertices.InsertNextCell(1)
        sourceVertices.InsertCellPoint(aid)
    if faces:
        for f in faces:
            n = len(f)
            if n == 4:
                plg = vtk.vtkTetra()
            elif n == 3:
                plg = vtk.vtkTriangle()
            else:
                plg = vtk.vtkPolygon()
                plg.GetPointIds().SetNumberOfIds(n)
            for i in range(n):
                plg.GetPointIds().SetId(i, f[i] - indexOffset)
            sourcePolygons.InsertNextCell(plg)

    poly = vtk.vtkPolyData()
    poly.SetPoints(sourcePoints)
    poly.SetVerts(sourceVertices)
    if faces:
        poly.SetPolys(sourcePolygons)
    clp = vtk.vtkCleanPolyData()
    clp.SetInputData(poly)
    clp.PointMergingOn()
    clp.Update()
    return clp.GetOutput()
コード例 #19
0
def vtk_cells(t):
    """ creates vtkCells from an numpy array @param t, 
    currently vtkLine, vtkTriangle, andn vtkTetra are implemented"""
    cellArray = vtk.vtkCellArray()
    for vert in t:
        if t.shape[1] == 2:
            tetra = vtk.vtkLine()
        if t.shape[1] == 3:
            tetra = vtk.vtkTriangle()
        elif t.shape[1] == 4:
            tetra = vtk.vtkTetra()
        for i, v in enumerate(vert):
            tetra.GetPointIds().SetId(i, int(v))
        cellArray.InsertNextCell(tetra)
    return cellArray
コード例 #20
0
ファイル: pyfrp_gui_vtk.py プロジェクト: mehdah/PyFRAP
    def initTetras(self):
        """Sets up tetrahedras describing mesh."""

        verts = self.embryo.simulation.mesh.mesh._getOrderedCellVertexIDs().T

        cellArray = vtk.vtkCellArray()
        for j, vert in enumerate(verts):

            tetra = vtk.vtkTetra()

            for i, v in enumerate(vert):
                tetra.GetPointIds().SetId(i, v)
            cellArray.InsertNextCell(tetra)

        self.grid.SetCells(vtk.VTK_TETRA, cellArray)
コード例 #21
0
 def convert_mesh_to_grid(self, mesh):
     grid = vtkUnstructuredGrid()
     points = vtkPoints()
     cell_array = vtkCellArray()
     for v in vertices(mesh):
         vp = v.point()
         points.InsertNextPoint(vp.x(), vp.y(), vp.z())
     for c in cells(mesh):
         t = vtkTetra()
         for i, v in enumerate(c.entities(0)):
             t.GetPointIds().SetId(i, v)
         cell_array.InsertNextCell(t)
     grid.SetPoints(points)
     grid.SetCells(VTK_TETRA, cell_array)
     return grid
コード例 #22
0
ファイル: plot.py プロジェクト: SinghN/nutils
  def unstructuredgrid( self, points, npars=None ):
    """add unstructured grid"""

    points = _nansplit( points )
    #assert isinstance( points, (list,tuple,numpy.ndarray) ), 'Expected list of point arrays'

    import vtk

    vtkPoints = vtk.vtkPoints()
    vtkPoints.SetNumberOfPoints( sum(pts.shape[0] for pts in points) )

    cnt = 0
    for pts in points:

      np, ndims = pts.shape
      if not npars:
        npars = ndims

      vtkelem   = None

      if np == 2:
        vtkelem = vtk.vtkLine()
      elif np == 3:
        vtkelem = vtk.vtkTriangle()
      elif np == 4:  
        if npars == 2:
          vtkelem = vtk.vtkQuad()
        elif npars == 3:
          vtkelem = vtk.vtkTetra()
      elif np == 8:
        vtkelem = vtk.vtkVoxel() # TODO hexahedron for not rectilinear NOTE ordering changes!

      if not vtkelem:
        raise Exception( 'not sure what to do with cells with ndims=%d and npoints=%d' % (ndims,np) )

      if ndims < 3:
        pts = numpy.concatenate([pts,numpy.zeros(shape=(pts.shape[0],3-ndims))],axis=1)

      cellpoints = vtkelem.GetPointIds()

      for i,point in enumerate(pts):
        vtkPoints .SetPoint( cnt, point )
        cellpoints.SetId( i, cnt )
        cnt +=1
    
      self.vtkMesh.InsertNextCell( vtkelem.GetCellType(), cellpoints )

    self.vtkMesh.SetPoints( vtkPoints )
コード例 #23
0
ファイル: pyfrp_gui_vtk.py プロジェクト: alexblaessle/PyFRAP
	def initTetras(self):
		
		"""Sets up tetrahedras describing mesh."""
		
		verts=self.embryo.simulation.mesh.mesh._getOrderedCellVertexIDs().T
		
		cellArray = vtk.vtkCellArray()
		for j,vert in enumerate(verts):

			tetra = vtk.vtkTetra()
			
			for i,v in enumerate(vert):
				tetra.GetPointIds().SetId(i, v)
			cellArray.InsertNextCell(tetra)
			
		self.grid.SetCells(vtk.VTK_TETRA, cellArray)
コード例 #24
0
    def __init__(self):
        self.obj = None
        self.num_pts = 0
        self.vtk_pts = vtk.vtkPoints()
        self.vtk_cells = vtk.vtkCellArray()
        self.vtk_tetra = vtk.vtkTetra()

        self.vtk_props = []
        self.vtk_cells_type = []
        self.vtk_cells_id = []
        self.vtk_cells_props = []

        self.n_cells = 0
        self.n_pts = 0

        print "\n+Vtk_writer"
コード例 #25
0
ファイル: guiData.py プロジェクト: zwghit/ProteusCFD
    def buildPartialVTKGrid(self, factag):
        #get points required for factag
        pointsList = self.getPointsWithFactag(factag)

        #create a lookup table so we can map the
        #cells from the global list to a local list
        points = vtk.vtkPoints()
        localIdx = 0
        ptMap = {}
        for pt in pointsList:
            ptMap[int(pt)] = localIdx
            localIdx = localIdx + 1
            p = self.mesh.coords[(pt*3):(pt*3+3)]
            points.InsertNextPoint(p)
        
        vtkgrid = vtk.vtkUnstructuredGrid()
        vtkgrid.SetPoints(points)

        #get elements that have desired factag
        felements = self.getElementsWithFactag(factag)

        #build the vtk elements
        for element in felements:
            type = element.getType()
            nodes = element.nodes
            if type == eTypes.TRI:
                cell = vtk.vtkTriangle()
            elif type == eTypes.QUAD:
                cell = vtk.vtkQuad()
            elif type == eTypes.TET:
                cell = vtk.vtkTetra()
            elif type == eTypes.PYRAMID:
                cell = vtk.vtkPyramid()
            elif type == eTypes.PRISM:
                cell = vtk.vtkWedge()  #prism
            elif type == eTypes.HEX:
                cell = vtk.vtkHexahedron()
            else:
                raise # throw an exception
            j = 0
            for n in nodes:
                localId = ptMap[int(n)]
                cell.GetPointIds().SetId(j,localId)
                j = j+1
            vtkgrid.InsertNextCell(cell.GetCellType(), cell.GetPointIds())
        return vtkgrid
コード例 #26
0
    def buildPartialVTKGrid(self, factag):
        #get points required for factag
        pointsList = self.getPointsWithFactag(factag)

        #create a lookup table so we can map the
        #cells from the global list to a local list
        points = vtk.vtkPoints()
        localIdx = 0
        ptMap = {}
        for pt in pointsList:
            ptMap[int(pt)] = localIdx
            localIdx = localIdx + 1
            p = self.mesh.coords[(pt * 3):(pt * 3 + 3)]
            points.InsertNextPoint(p)

        vtkgrid = vtk.vtkUnstructuredGrid()
        vtkgrid.SetPoints(points)

        #get elements that have desired factag
        felements = self.getElementsWithFactag(factag)

        #build the vtk elements
        for element in felements:
            type = element.getType()
            nodes = element.nodes
            if type == eTypes.TRI:
                cell = vtk.vtkTriangle()
            elif type == eTypes.QUAD:
                cell = vtk.vtkQuad()
            elif type == eTypes.TET:
                cell = vtk.vtkTetra()
            elif type == eTypes.PYRAMID:
                cell = vtk.vtkPyramid()
            elif type == eTypes.PRISM:
                cell = vtk.vtkWedge()  #prism
            elif type == eTypes.HEX:
                cell = vtk.vtkHexahedron()
            else:
                raise  # throw an exception
            j = 0
            for n in nodes:
                localId = ptMap[int(n)]
                cell.GetPointIds().SetId(j, localId)
                j = j + 1
            vtkgrid.InsertNextCell(cell.GetCellType(), cell.GetPointIds())
        return vtkgrid
コード例 #27
0
def add_tetras(grid, nids, eids_tetras, nid_offset):
    """adds tet elements to the vtkUnstructuredGrid"""
    nelements = 0
    if eids_tetras is not None:
        nelements = eids_tetras.shape[0]
        eids = eids_tetras[:, 0]
        elem_nids = eids_tetras[:, 1:]
        #inids = np.searchsorted(nids, elem_nids)
        node_ids = elem_nids + nid_offset
        for unused_eid, node_idsi in zip(eids, node_ids):
            elem = vtkTetra()
            elem.GetPointIds().SetId(0, node_idsi[0])
            elem.GetPointIds().SetId(1, node_idsi[1])
            elem.GetPointIds().SetId(2, node_idsi[2])
            elem.GetPointIds().SetId(3, node_idsi[3])
            grid.InsertNextCell(10, elem.GetPointIds())
    return nelements
コード例 #28
0
def buildPolyData(vertices, faces=None, indexOffset=0):
    '''
    Build a vtkPolyData object from a list of vertices
    and the connectivity representing the faces of the polygonal mesh.

    E.g. faces=[[0,1,2], [1,2,3], ...], 
         vertices=[[x1,y1,z1],[x2,y2,z2], ...] 

    Use indexOffset=1 if face numbering starts from 1 instead of 0.
    '''
    sourcePoints = vtk.vtkPoints()
    sourceVertices = vtk.vtkCellArray()
    sourcePolygons = vtk.vtkCellArray()
    for pt in vertices:
        if len(pt) > 2:
            aid = sourcePoints.InsertNextPoint(pt[0], pt[1], pt[2])
        else:
            aid = sourcePoints.InsertNextPoint(pt[0], pt[1], 0)
        sourceVertices.InsertNextCell(1)
        sourceVertices.InsertCellPoint(aid)
    if faces:
        for f in faces:
            n = len(f)
            if n == 4:
                plg = vtk.vtkTetra()
            elif n == 3:
                plg = vtk.vtkTriangle()
            else:
                plg = vtk.vtkPolygon()
                plg.GetPointIds().SetNumberOfIds(n)
            for i in range(n):
                plg.GetPointIds().SetId(i, f[i] - indexOffset)
            sourcePolygons.InsertNextCell(plg)

    poly = vtk.vtkPolyData()
    poly.SetPoints(sourcePoints)
    poly.SetVerts(sourceVertices)
    if faces:
        poly.SetPolys(sourcePolygons)
    clp = vtk.vtkCleanPolyData()
    clp.SetInputData(poly)
    clp.PointMergingOn()
    clp.Update()
    return clp.GetOutput()
コード例 #29
0
def projectTetrahedron(pointIds, color, volDic, unstructuredGrid, colors):

    # tetraPoints = vtk.vtkPoints()
    # for i in range(4):
    #     tetraPoints.InsertNextPoint(points[i][0],points[i][1],points[i][2])

    tetra = vtk.vtkTetra()
    for i in range(4):
        tetra.GetPointIds().SetId(i, pointIds[i])

    cellId = unstructuredGrid.InsertNextCell(tetra.GetCellType(),
                                             tetra.GetPointIds())
    r = volDic[color]
    if color != 0:
        if r > 1000:
            colors.InsertTuple1(cellId, 999)
        else:
            colors.InsertTuple1(cellId, volDic[color])

    else:
        colors.InsertTuple1(cellId, 0)
コード例 #30
0
ファイル: IO.py プロジェクト: jrper/ParticleModule
def get_linear_cell(cell):
    """ Get equivalent linear cell to vtkCell cell"""
    if cell.GetCellType() in (vtk.VTK_POLY_LINE,):
        linear_cell = vtk.vtkLine()
        linear_cell.GetPoints().SetPoint(0, cell.GetPoints().GetPoint(0))
        linear_cell.GetPoints().SetPoint(1, cell.GetPoints().GetPoint(1))
    elif cell.GetCellType() in (vtk.VTK_QUADRATIC_TRIANGLE,):
        linear_cell = vtk.vtkTriangle()
        linear_cell.GetPoints().SetPoint(0, cell.GetPoints().GetPoint(0))
        linear_cell.GetPoints().SetPoint(1, cell.GetPoints().GetPoint(1))
        linear_cell.GetPoints().SetPoint(2, cell.GetPoints().GetPoint(2))
    elif cell.GetCellType() in (vtk.VTK_QUADRATIC_TETRA,):
        linear_cell = vtk.vtkTetra()
        linear_cell.GetPoints().SetPoint(0, cell.GetPoints().GetPoint(0))
        linear_cell.GetPoints().SetPoint(1, cell.GetPoints().GetPoint(1))
        linear_cell.GetPoints().SetPoint(2, cell.GetPoints().GetPoint(2))
        linear_cell.GetPoints().SetPoint(3, cell.GetPoints().GetPoint(3))
    else:
        linear_cell = cell

    return linear_cell
コード例 #31
0
    def _buildtetugrid(self, points, cells):
        if len(points) == 0:
            return None
        if not utils.isSequence(points[0]):
            return None

        ug = vtk.vtkUnstructuredGrid()
        sourcePoints = vtk.vtkPoints()
        varr = numpy_to_vtk(np.ascontiguousarray(points), deep=True)
        sourcePoints.SetData(varr)
        ug.SetPoints(sourcePoints)

        sourceTets = vtk.vtkCellArray()
        for f in cells:
            ele = vtk.vtkTetra()
            pid = ele.GetPointIds()
            for i, fi in enumerate(f):
                pid.SetId(i, fi)
            sourceTets.InsertNextCell(ele)
        ug.SetCells(vtk.VTK_TETRA, sourceTets)
        return ug
コード例 #32
0
def MakeTetra():
    # Make a tetrahedron.
    numberOfVertices = 4

    points = vtk.vtkPoints()
    points.InsertNextPoint(0, 0, 0)
    points.InsertNextPoint(1, 0, 0)
    points.InsertNextPoint(1, 1, 0)
    points.InsertNextPoint(0, 1, 1)

    tetra = vtk.vtkTetra()
    for i in range(0, numberOfVertices):
        tetra.GetPointIds().SetId(i, i)

    cellArray = vtk.vtkCellArray()
    cellArray.InsertNextCell(tetra)

    unstructuredGrid = vtk.vtkUnstructuredGrid()
    unstructuredGrid.SetPoints(points)
    unstructuredGrid.SetCells(vtk.VTK_TETRA, cellArray)

    return unstructuredGrid
コード例 #33
0
    def doLinear(self, ghosts, ncells):
        pts = vtk.vtkPoints()
        pts.SetNumberOfPoints(4)
        pts.InsertPoint(0, (0, 0, 0))
        pts.InsertPoint(1, (1, 0, 0))
        pts.InsertPoint(2, (0.5, 1, 0))
        pts.InsertPoint(3, (0.5, 0.5, 1))

        te = vtk.vtkTetra()
        ptIds = te.GetPointIds()
        for i in range(4):
            ptIds.SetId(i, i)

        grid = vtk.vtkUnstructuredGrid()
        grid.Allocate(1, 1)
        grid.InsertNextCell(te.GetCellType(), te.GetPointIds())
        grid.SetPoints(pts)
        grid.GetPointData().AddArray(ghosts)

        dss = vtk.vtkDataSetSurfaceFilter()
        dss.SetInputData(grid)
        dss.Update()
        self.assertEqual(dss.GetOutput().GetNumberOfCells(), ncells)
コード例 #34
0
def tetra(size=1):
    size = size / 2.0

    points = vtk.vtkPoints()
    points.InsertNextPoint(0, -size, -size)
    points.InsertNextPoint(-size, -size, size)
    points.InsertNextPoint(size, -size, size)
    points.InsertNextPoint(0, size, 0)

    tetra = vtk.vtkTetra()
    tetra.GetPointIds().SetId(0, 0)
    tetra.GetPointIds().SetId(1, 1)
    tetra.GetPointIds().SetId(2, 2)
    tetra.GetPointIds().SetId(3, 3)

    grid = vtk.vtkUnstructuredGrid()
    grid.SetPoints(points)
    grid.InsertNextCell(tetra.GetCellType(), tetra.GetPointIds())

    mesh = vtk.vtkDelaunay3D()  # vtk.vtkPassThroughFilter()
    mesh.SetInput(grid)

    return mesh
コード例 #35
0
    def doLinear(self, ghosts, ncells):
        pts = vtk.vtkPoints()
        pts.SetNumberOfPoints(4)
        pts.InsertPoint(0, (0, 0, 0))
        pts.InsertPoint(1, (1, 0, 0))
        pts.InsertPoint(2, (0.5, 1, 0))
        pts.InsertPoint(3, (0.5, 0.5, 1))

        te = vtk.vtkTetra()
        ptIds = te.GetPointIds()
        for i in range(4):
            ptIds.SetId(i, i)

        grid = vtk.vtkUnstructuredGrid()
        grid.Allocate(1, 1)
        grid.InsertNextCell(te.GetCellType(), te.GetPointIds())
        grid.SetPoints(pts)
        grid.GetPointData().AddArray(ghosts)

        dss = vtk.vtkDataSetSurfaceFilter()
        dss.SetInputData(grid)
        dss.Update()
        self.assertEqual(dss.GetOutput().GetNumberOfCells(), ncells)
コード例 #36
0
def convertXMLMeshToUGrid(mesh):

    connectivity = mesh.cells()
    coords = mesh.coordinates()

    points = vtk.vtkPoints()
    for coord in coords:
        points.InsertNextPoint(coord[0], coord[1], coord[2])

    cellarray = vtk.vtkCellArray()
    for cell in connectivity:
        tetra = vtk.vtkTetra()
        tetra.GetPointIds().SetId(0, cell[0])
        tetra.GetPointIds().SetId(1, cell[1])
        tetra.GetPointIds().SetId(2, cell[2])
        tetra.GetPointIds().SetId(3, cell[3])

        cellarray.InsertNextCell(tetra)

    ugrid = vtk.vtkUnstructuredGrid()
    ugrid.SetPoints(points)
    ugrid.SetCells(tetra.GetCellType(), cellarray)

    return ugrid
コード例 #37
0
    def buildFullVTKGrid(self):
        # Create the points for VTK
        points = vtk.vtkPoints()
        for i in range(0, len(self.mesh.coords) / 3):
            p = self.mesh.coords[(i * 3):(i * 3 + 3)]
            points.InsertNextPoint(p)

        #add the points and cells to unstructured grid
        vtkgrid = vtk.vtkUnstructuredGrid()
        vtkgrid.SetPoints(points)

        #add the VTK elements to the mesh
        for element in self.mesh.elements:
            type = element.getType()
            nodes = element.nodes
            cell = vtk.vtkTriangle()
            if type == eTypes.TRI:
                cell = vtk.vtkTriangle()
            elif type == eTypes.QUAD:
                cell = vtk.vtkQuad()
            elif type == eTypes.TET:
                cell = vtk.vtkTetra()
            elif type == eTypes.PYRAMID:
                cell = vtk.vtkPyramid()
            elif type == eTypes.PRISM:
                cell = vtk.vtkWedge()  #prism
            elif type == eTypes.HEX:
                cell = vtk.vtkHexahedron()
            else:
                raise  # throw an exception
            j = 0
            for n in nodes:
                cell.GetPointIds().SetId(j, n)
                j = j + 1
            vtkgrid.InsertNextCell(cell.GetCellType(), cell.GetPointIds())
        return vtkgrid
コード例 #38
0
def MakeTetrahedron():
    '''
      Make a tetrahedron.
    '''
    numberOfVertices = 4
 
    points = vtk.vtkPoints()
    points.InsertNextPoint(0, 0, 0)
    points.InsertNextPoint(1, 0, 0)
    points.InsertNextPoint(1, 1, 0)
    points.InsertNextPoint(0, 1, 1)
 
    tetra = vtk.vtkTetra()
    for i in range(0, numberOfVertices):
        tetra.GetPointIds().SetId(i, i)
 
    cellArray = vtk.vtkCellArray()
    cellArray.InsertNextCell(tetra)
 
    unstructuredGrid = vtk.vtkUnstructuredGrid()
    unstructuredGrid.SetPoints(points)
    unstructuredGrid.SetCells(vtk.VTK_TETRA, cellArray)
 
    return unstructuredGrid
コード例 #39
0
ファイル: guiData.py プロジェクト: zwghit/ProteusCFD
    def buildFullVTKGrid(self):
        # Create the points for VTK
        points = vtk.vtkPoints()
        for i in range(0, len(self.mesh.coords)/3):
            p = self.mesh.coords[(i*3):(i*3+3)]
            points.InsertNextPoint(p)

        #add the points and cells to unstructured grid
        vtkgrid = vtk.vtkUnstructuredGrid()
        vtkgrid.SetPoints(points)

        #add the VTK elements to the mesh
        for element in self.mesh.elements:
            type = element.getType()
            nodes = element.nodes
            cell = vtk.vtkTriangle()
            if type == eTypes.TRI:
                cell = vtk.vtkTriangle()
            elif type == eTypes.QUAD:
                cell = vtk.vtkQuad()
            elif type == eTypes.TET:
                cell = vtk.vtkTetra()
            elif type == eTypes.PYRAMID:
                cell = vtk.vtkPyramid()
            elif type == eTypes.PRISM:
                cell = vtk.vtkWedge()  #prism
            elif type == eTypes.HEX:
                cell = vtk.vtkHexahedron()
            else:
                raise # throw an exception
            j = 0
            for n in nodes:
                cell.GetPointIds().SetId(j,n)
                j = j+1
            vtkgrid.InsertNextCell(cell.GetCellType(), cell.GetPointIds())
        return vtkgrid
コード例 #40
0
    def _buildtetugrid(self, points, cells):
        ug = vtk.vtkUnstructuredGrid()

        if len(points) == 0:
            return ug
        if not utils.isSequence(points[0]):
            return ug

        if len(cells) == 0:
            return ug

        if not utils.isSequence(cells[0]):
            tets = []
            nf = cells[0] + 1
            for i, cl in enumerate(cells):
                if i == nf or i == 0:
                    k = i + 1
                    nf = cl + k
                    cell = [cells[j + k] for j in range(cl)]
                    tets.append(cell)
            cells = tets

        sourcePoints = vtk.vtkPoints()
        varr = numpy_to_vtk(np.ascontiguousarray(points), deep=True)
        sourcePoints.SetData(varr)
        ug.SetPoints(sourcePoints)

        sourceTets = vtk.vtkCellArray()
        for f in cells:
            ele = vtk.vtkTetra()
            pid = ele.GetPointIds()
            for i, fi in enumerate(f):
                pid.SetId(i, fi)
            sourceTets.InsertNextCell(ele)
        ug.SetCells(vtk.VTK_TETRA, sourceTets)
        return ug
コード例 #41
0
def readAbaqusMeshFromINP(
        mesh_filename,
        elem_types="all",
        verbose=1):

    myVTK.myPrint(verbose, "*** readAbaqusMeshFromINP: " + mesh_filename + " ***")

    points = vtk.vtkPoints()
    cell_array = vtk.vtkCellArray()

    mesh_file = open(mesh_filename, "r")

    context = ""
    for line in mesh_file:
        if (line[-1:] == "\n"): line = line[:-1]
        #myVTK.myPrint(verbose, "line =", line)

        if line.startswith("**"): continue

        if (context == "reading nodes"):
            if line.startswith("*"):
                context = ""
            else:
                splitted_line = line.split(",")
                points.InsertNextPoint([float(coord) for coord in splitted_line[1:4]])

        if (context == "reading elems"):
            if line.startswith("*"):
                context = ""
            else:
                splitted_line = line.split(",")
                assert (len(splitted_line) == 1+cell_n_points), "Wrong number of elements in line. Aborting."
                for k_point in xrange(cell_n_points): cell.GetPointIds().SetId(k_point, int(splitted_line[1+k_point])-1)
                cell_array.InsertNextCell(cell)

        if line.startswith("*NODE"):
            context = "reading nodes"
        if line.startswith("*ELEMENT"):
            if ("TYPE=F3D4" in line) and (("quad" in elem_types) or ("all" in elem_types)):
                context = "reading elems"
                cell_vtk_type = vtk.VTK_QUAD
                cell_n_points = 4
                cell = vtk.vtkQuad()
            elif ("TYPE=C3D4" in line) and (("tet" in elem_types) or ("all" in elem_types)):
                context = "reading elems"
                cell_vtk_type = vtk.VTK_TETRA
                cell_n_points = 4
                cell = vtk.vtkTetra()
            elif ("TYPE=C3D8" in line) and (("hex" in elem_types) or ("all" in elem_types)):
                context = "reading elems"
                cell_vtk_type = vtk.VTK_HEXAHEDRON
                cell_n_points = 8
                cell = vtk.vtkHexahedron()
            else:
                print "Warning: elements not read: " + line + "."

    mesh_file.close()

    ugrid = vtk.vtkUnstructuredGrid()
    ugrid.SetPoints(points)
    ugrid.SetCells(cell_vtk_type, cell_array)

    myVTK.myPrint(verbose, "n_cells = " + str(ugrid.GetNumberOfCells()))

    return ugrid
コード例 #42
0
ファイル: tetgen_io.py プロジェクト: umvarma/pynastran
    def load_tetgen_geometry(self, smesh_filename, dirname, plot=True):
        print("load_tetgen_geometry...")
        skipReading = self.removeOldGeometry(smesh_filename)
        if skipReading:
            return

        model = TetgenReader(log=self.log, debug=False)

        base_filename, ext = os.path.splitext(smesh_filename)
        node_filename = base_filename + '.node'
        ele_filename = base_filename + '.ele'
        if '.smesh' == ext:
            dimension_flag = 2
        elif '.ele' == ext:
            dimension_flag = 3
        else:
            raise RuntimeError('unsupported extension.  Use "smesh" or "ele".')
        model.read_tetgen(node_filename, smesh_filename, ele_filename, dimension_flag)
        nodes = model.nodes
        tris = model.tri
        tets = model.tet

        self.nNodes, three = nodes.shape
        ntris = 0
        ntets = 0
        if dimension_flag == 2:
            ntris, three = tris.shape
        elif dimension_flag == 3:
            ntets, four = tets.shape
        else:
            raise RuntimeError()
        self.nElements = ntris + ntets

        print("nNodes = ",self.nNodes)
        print("nElements = ", self.nElements)

        self.grid.Allocate(self.nElements, 1000)
        #self.gridResult.SetNumberOfComponents(self.nElements)
        self.grid2.Allocate(1, 1000)

        points = vtk.vtkPoints()
        points.SetNumberOfPoints(self.nNodes)
        #self.gridResult.Allocate(self.nNodes, 1000)
        #vectorReselt.SetNumberOfComponents(3)
        self.nidMap = {}
        #elem.SetNumberOfPoints(nNodes)
        if 0:
            fraction = 1. / self.nNodes  # so you can color the nodes by ID
            for nid, node in sorted(iteritems(nodes)):
                points.InsertPoint(nid - 1, *node)
                self.gridResult.InsertNextValue(nid * fraction)
                #print(str(element))

                #elem = vtk.vtkVertex()
                #elem.GetPointIds().SetId(0, i)
                #self.aQuadGrid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())
                #vectorResult.InsertTuple3(0, 0.0, 0.0, 1.0)

        assert nodes is not None
        nnodes, three = nodes.shape

        nid = 0
        print("nnodes=%s" % nnodes)
        for i in range(nnodes):
            points.InsertPoint(nid, nodes[i, :])
            nid += 1

        #elements -= 1
        if dimension_flag == 2:
            for (n0, n1, n2) in tris:
                elem = vtkTriangle()
                #node_ids = elements[eid, :]
                elem.GetPointIds().SetId(0, n0)
                elem.GetPointIds().SetId(1, n1)
                elem.GetPointIds().SetId(2, n2)
                self.grid.InsertNextCell(5, elem.GetPointIds())  #elem.GetCellType() = 5  # vtkTriangle
        elif dimension_flag == 3:
            for (n0, n1, n2, n3) in tets:
                elem = vtkTetra()
                assert elem.GetCellType() == 10, elem.GetCellType()
                elem.GetPointIds().SetId(0, n0)
                elem.GetPointIds().SetId(1, n1)
                elem.GetPointIds().SetId(2, n2)
                elem.GetPointIds().SetId(3, n3)
                self.grid.InsertNextCell(10, elem.GetPointIds())  #elem.GetCellType() = 5  # vtkTriangle
        else:
            raise RuntimeError()

        self.grid.SetPoints(points)
        self.grid.Modified()
        self.grid.Update()
        print("updated grid")

        # loadSTLResults - regions/loads
        self.TurnTextOn()
        self.scalarBar.VisibilityOff()
        self.scalarBar.Modified()

        cases = {}
        ID = 1

        #cases = self._fill_tetgen_case(cases, ID, elements)
        self._finish_results_io(cases)
コード例 #43
0
ファイル: organiseData.py プロジェクト: beauof/FSIViewer
def assignElements3Dlin(mesh, elements):
    
    numRows, numCols = elements.shape
    tet = vtk.vtkTetra()
    # TODO can we do this faster?
    for i in range(numRows):
        v0, v1, v2, v3, v4, v5, v6, v7, v8, v9 = elements[i, :]
        '''
        tet.GetPointIds().SetId(0, v0)
        tet.GetPointIds().SetId(1, v4)
        tet.GetPointIds().SetId(2, v6)
        tet.GetPointIds().SetId(3, v7)
        mesh.InsertNextCell(tet.GetCellType(), tet.GetPointIds())
        
        tet.GetPointIds().SetId(0, v6)
        tet.GetPointIds().SetId(1, v4)
        tet.GetPointIds().SetId(2, v5)
        tet.GetPointIds().SetId(3, v7)
        mesh.InsertNextCell(tet.GetCellType(), tet.GetPointIds())
        
        tet.GetPointIds().SetId(0, v4)
        tet.GetPointIds().SetId(1, v1)
        tet.GetPointIds().SetId(2, v5)
        tet.GetPointIds().SetId(3, v8)
        mesh.InsertNextCell(tet.GetCellType(), tet.GetPointIds())
        
        tet.GetPointIds().SetId(0, v6)
        tet.GetPointIds().SetId(1, v5)
        tet.GetPointIds().SetId(2, v2)
        tet.GetPointIds().SetId(3, v7)
        mesh.InsertNextCell(tet.GetCellType(), tet.GetPointIds())
        
        tet.GetPointIds().SetId(0, v4)
        tet.GetPointIds().SetId(1, v8)
        tet.GetPointIds().SetId(2, v5)
        tet.GetPointIds().SetId(3, v7)
        mesh.InsertNextCell(tet.GetCellType(), tet.GetPointIds())
        
        tet.GetPointIds().SetId(0, v2)
        tet.GetPointIds().SetId(1, v7)
        tet.GetPointIds().SetId(2, v5)
        tet.GetPointIds().SetId(3, v9)
        mesh.InsertNextCell(tet.GetCellType(), tet.GetPointIds())
        
        tet.GetPointIds().SetId(0, v7)
        tet.GetPointIds().SetId(1, v5)
        tet.GetPointIds().SetId(2, v9)
        tet.GetPointIds().SetId(3, v8)
        mesh.InsertNextCell(tet.GetCellType(), tet.GetPointIds())
        
        tet.GetPointIds().SetId(0, v7)
        tet.GetPointIds().SetId(1, v8)
        tet.GetPointIds().SetId(2, v9)
        tet.GetPointIds().SetId(3, v3)
        mesh.InsertNextCell(tet.GetCellType(), tet.GetPointIds())
        '''
        
        
        
        
        tet.GetPointIds().SetId(0, v0)
        tet.GetPointIds().SetId(1, v4)
        tet.GetPointIds().SetId(2, v6)
        tet.GetPointIds().SetId(3, v7)
        mesh.InsertNextCell(tet.GetCellType(), tet.GetPointIds())
        
        tet.GetPointIds().SetId(0, v4)
        tet.GetPointIds().SetId(1, v1)
        tet.GetPointIds().SetId(2, v5)
        tet.GetPointIds().SetId(3, v8)
        mesh.InsertNextCell(tet.GetCellType(), tet.GetPointIds())
        
        tet.GetPointIds().SetId(0, v6)
        tet.GetPointIds().SetId(1, v5)
        tet.GetPointIds().SetId(2, v2)
        tet.GetPointIds().SetId(3, v9)
        mesh.InsertNextCell(tet.GetCellType(), tet.GetPointIds())
        
        tet.GetPointIds().SetId(0, v7)
        tet.GetPointIds().SetId(1, v8)
        tet.GetPointIds().SetId(2, v9)
        tet.GetPointIds().SetId(3, v3)
        mesh.InsertNextCell(tet.GetCellType(), tet.GetPointIds())
        
        tet.GetPointIds().SetId(0, v6)
        tet.GetPointIds().SetId(1, v9)
        tet.GetPointIds().SetId(2, v7)
        tet.GetPointIds().SetId(3, v5)
        mesh.InsertNextCell(tet.GetCellType(), tet.GetPointIds())
        
        tet.GetPointIds().SetId(0, v7)
        tet.GetPointIds().SetId(1, v5)
        tet.GetPointIds().SetId(2, v9)
        tet.GetPointIds().SetId(3, v8)
        mesh.InsertNextCell(tet.GetCellType(), tet.GetPointIds())
        
        tet.GetPointIds().SetId(0, v6)
        tet.GetPointIds().SetId(1, v4)
        tet.GetPointIds().SetId(2, v5)
        tet.GetPointIds().SetId(3, v7)
        mesh.InsertNextCell(tet.GetCellType(), tet.GetPointIds())
        
        tet.GetPointIds().SetId(0, v4)
        tet.GetPointIds().SetId(1, v5)
        tet.GetPointIds().SetId(2, v7)
        tet.GetPointIds().SetId(3, v8)
        mesh.InsertNextCell(tet.GetCellType(), tet.GetPointIds())
    return mesh
コード例 #44
0
ファイル: fast_io.py プロジェクト: saullocastro/pyNastran
    def load_fast_geometry(self, fgrid_filename, dirname, name='main', plot=True):
        skip_reading = self._remove_old_geometry(fgrid_filename)
        if skip_reading:
            return

        model = FGridReader(log=self.log, debug=False)

        base_filename, ext = os.path.splitext(fgrid_filename)
        if '.fgrid' == ext:
            dimension_flag = 3
        #elif '.ele' == ext:
            #dimension_flag = 3
        else:
            raise RuntimeError('unsupported extension.  Use "cogsg" or "front".')

        read_loads = True
        model.read_fgrid(fgrid_filename, dimension_flag)

        dimension_flag = 3
        nodes = model.nodes
        tris = model.tris - 1
        tets = model.tets - 1

        nnodes = nodes.shape[0]
        ntris = tris.shape[0]
        ntets = tets.shape[0]

        #print('node0 = %s' % str(nodes[0, :]))
        #print('node%i = %s' % (1, str(nodes[1, :])))
        #print('node%i = %s' % (2, str(nodes[2, :])))
        #print('node%i = %s' % (nnodes, str(nodes[-1, :])))
        #print('tris.max/min = ', tris.max(), tris.min())
        #print('tets.max/min = ', tets.max(), tets.min())
        #bcs = model.bcs
        #mapbc = model.mapbc
        #loads = model.loads

        self.nNodes = nnodes
        self.nElements = ntris + ntets

        #print("nNodes = %i" % self.nNodes)
        #print("nElements = %i" % self.nElements)

        self.grid.Allocate(self.nElements, 1000)
        #self.gridResult.SetNumberOfComponents(self.nElements)

        points = vtk.vtkPoints()
        points.SetNumberOfPoints(self.nNodes)
        self.nid_map = {}
        if 0:
            fraction = 1. / self.nNodes  # so you can color the nodes by ID
            for nid, node in sorted(iteritems(nodes)):
                points.InsertPoint(nid - 1, *node)
                self.gridResult.InsertNextValue(nid * fraction)

        assert nodes is not None
        nnodes = nodes.shape[0]

        nid = 0
        for i in range(nnodes):
            points.InsertPoint(nid, nodes[i, :])
            nid += 1

        if dimension_flag == 2:
            for (n0, n1, n2) in tris:
                elem = vtkTriangle()
                #node_ids = elements[eid, :]
                elem.GetPointIds().SetId(0, n0)
                elem.GetPointIds().SetId(1, n1)
                elem.GetPointIds().SetId(2, n2)
                self.grid.InsertNextCell(5, elem.GetPointIds())  #elem.GetCellType() = 5  # vtkTriangle
        elif dimension_flag == 3:
            if ntets:
                for (n0, n1, n2, n3) in tets:
                    elem = vtkTetra()
                    elem.GetPointIds().SetId(0, n0)
                    elem.GetPointIds().SetId(1, n1)
                    elem.GetPointIds().SetId(2, n2)
                    elem.GetPointIds().SetId(3, n3)
                    self.grid.InsertNextCell(10, elem.GetPointIds())  #elem.GetCellType() = 5  # vtkTriangle
        else:
            raise RuntimeError('dimension_flag=%r' % dimension_flag)

        self.grid.SetPoints(points)
        self.grid.Modified()
        if hasattr(self.grid, 'Update'):
            self.grid.Update()

        # regions/loads
        self. turn_text_on()
        self.scalarBar.Modified()

        cases = {}
        #cases = self.result_cases
        self._fill_fast_results(cases, model, results=False)
        self._finish_results_io(cases)
コード例 #45
0
ファイル: TestCellDerivs.py プロジェクト: 151706061/VTK
aHexahedronGrid.InsertNextCell(aHexahedron.GetCellType(),aHexahedron.GetPointIds())
aHexahedronGrid.SetPoints(hexahedronPoints)
aHexahedronMapper = vtk.vtkDataSetMapper()
aHexahedronMapper.SetInputData(aHexahedronGrid)
aHexahedronActor = vtk.vtkActor()
aHexahedronActor.SetMapper(aHexahedronMapper)
aHexahedronActor.AddPosition(2,0,0)
aHexahedronActor.GetProperty().BackfaceCullingOn()
# Tetra
tetraPoints = vtk.vtkPoints()
tetraPoints.SetNumberOfPoints(4)
tetraPoints.InsertPoint(0,0,0,0)
tetraPoints.InsertPoint(1,1,0,0)
tetraPoints.InsertPoint(2,0,1,0)
tetraPoints.InsertPoint(3,1,1,1)
aTetra = vtk.vtkTetra()
aTetra.GetPointIds().SetId(0,0)
aTetra.GetPointIds().SetId(1,1)
aTetra.GetPointIds().SetId(2,2)
aTetra.GetPointIds().SetId(3,3)
aTetraGrid = vtk.vtkUnstructuredGrid()
aTetraGrid.Allocate(1,1)
aTetraGrid.InsertNextCell(aTetra.GetCellType(),aTetra.GetPointIds())
aTetraGrid.SetPoints(tetraPoints)
aTetraMapper = vtk.vtkDataSetMapper()
aTetraMapper.SetInputData(aTetraGrid)
aTetraActor = vtk.vtkActor()
aTetraActor.SetMapper(aTetraMapper)
aTetraActor.AddPosition(4,0,0)
aTetraActor.GetProperty().BackfaceCullingOn()
# Wedge
コード例 #46
0
ファイル: tecplot_io.py プロジェクト: HibernantBear/pyNastran
    def _make_tecplot_geometry(self, model, quads_only=False):
        nodes = model.xyz
        nnodes = self.nNodes

        points = vtk.vtkPoints()
        points.SetNumberOfPoints(nnodes)
        #self.gridResult.Allocate(self.nNodes, 1000)
        #vectorReselt.SetNumberOfComponents(3)
        #self.nidMap = {}
        #elem.SetNumberOfPoints(nNodes)

        #assert nodes is not None
        #nnodes = nodes.shape[0]

        mmax = amax(nodes, axis=0)
        mmin = amin(nodes, axis=0)
        dim_max = (mmax - mmin).max()
        self.update_axes_length(dim_max)
        for i in range(nnodes):
            points.InsertPoint(i, nodes[i, :])

        #elements = model.elements
        quads = model.quad_elements
        hexas = model.hexa_elements
        tets = model.tet_elements
        tris = model.tri_elements

        is_quads = len(quads)
        is_tris = len(tris)
        is_hexas = len(hexas)
        is_tets = len(tets)

        is_shells = is_quads + is_tris
        is_solids = is_tets + is_hexas
        if is_shells:
            is_surface = True
            self.self._create_tecplot_shells(is_quads, quads, is_tris, tris)

        elif is_solids:
            if 0:
                tris, quads = model.skin_elements()
                is_tris = bool(len(tris))
                is_quads = bool(len(quads))
                self.self._create_tecplot_shells(is_quads, quads, is_tris, tris)
            else:
                if is_tets:
                    elements = tets
                    is_surface = False
                    self.nElements = model.nelements
                    self.grid.Allocate(self.nElements, 1000)

                    nelements = elements.shape[0]
                    for eid in range(nelements):
                        elem = vtkTetra()
                        node_ids = elements[eid, :]
                        epoints = elem.GetPointIds()
                        epoints.SetId(0, node_ids[0])
                        epoints.SetId(1, node_ids[1])
                        epoints.SetId(2, node_ids[2])
                        epoints.SetId(3, node_ids[3])
                        self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())  #elem.GetCellType() = 5  # vtkTriangle


                if is_hexas:
                    elements = hexas
                    is_surface = True
                    # is_surface = False
                    is_volume = not is_surface

                    if is_surface:
                        self.nElements = model.nelements
                        free_faces = array(model.get_free_faces(), dtype='int32')# + 1
                        nfaces = len(free_faces)
                        elements = free_faces
                        self.grid.Allocate(nfaces, 1000)

                        for face in free_faces:
                            elem = vtkQuad()
                            epoints = elem.GetPointIds()
                            epoints.SetId(0, face[0])
                            epoints.SetId(1, face[1])
                            epoints.SetId(2, face[2])
                            epoints.SetId(3, face[3])
                            self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())  #elem.GetCellType() = 5  # vtkTriangle

                    elif is_volume:
                        self.nElements = model.nelements
                        self.grid.Allocate(self.nElements, 1000)

                        nelements = elements.shape[0]
                        for eid in range(nelements):
                            elem = vtkHexahedron()
                            node_ids = elements[eid, :]
                            epoints = elem.GetPointIds()
                            epoints.SetId(0, node_ids[0])
                            epoints.SetId(1, node_ids[1])
                            epoints.SetId(2, node_ids[2])
                            epoints.SetId(3, node_ids[3])
                            epoints.SetId(4, node_ids[4])
                            epoints.SetId(5, node_ids[5])
                            epoints.SetId(6, node_ids[6])
                            epoints.SetId(7, node_ids[7])
                            self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())  #elem.GetCellType() = 5  # vtkTriangle
        else:
            raise NotImplementedError()

        self.grid.SetPoints(points)
        #self.grid.GetPointData().SetScalars(self.gridResult)
        #print(dir(self.grid) #.SetNumberOfComponents(0))
        #self.grid.GetCellData().SetNumberOfTuples(1);
        #self.grid.GetCellData().SetScalars(self.gridResult)
        self.grid.Modified()
        if hasattr(self.grid, 'Update'):
            self.grid.Update()
        return is_surface
コード例 #47
0
ファイル: nastranIO.py プロジェクト: xirxa/pynastran-locr
    def mapElements(self, points, points2, nidMap, model, j):
        self.eidMap = {}
        i = 0
        for (eid, element) in sorted(model.elements.iteritems()):
            self.eidMap[eid] = i
            #print element.type
            if isinstance(element, CTRIA3) or isinstance(element, CTRIAR):
                #print "ctria3"
                elem = vtkTriangle()
                nodeIDs = element.nodeIDs()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                self.grid.InsertNextCell(elem.GetCellType(),
                                         elem.GetPointIds())
            elif isinstance(element, CTRIA6):
                nodeIDs = element.nodeIDs()
                if None not in nodeIDs:
                    elem = vtkQuadraticTriangle()
                    elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]])
                    elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]])
                    elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]])
                else:
                    elem = vtkTriangle()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                self.grid.InsertNextCell(elem.GetCellType(),
                                         elem.GetPointIds())
            elif isinstance(element, CTRIAX6):
                # midside nodes are required, nodes out of order
                nodeIDs = element.nodeIDs()
                if None not in nodeIDs:
                    elem = vtkQuadraticTriangle()
                    elem.GetPointIds().SetId(3, nidMap[nodeIDs[1]])
                    elem.GetPointIds().SetId(4, nidMap[nodeIDs[3]])
                    elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]])
                else:
                    elem = vtkTriangle()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[2]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[4]])
                #a = [0,2,4]
                #msg = "CTRIAX6 %i %i %i" %(nidMap[nodeIDs[a[0]]],
                #                           nidMap[nodeIDs[a[1]]],
                #                           nidMap[nodeIDs[a[2]]] )
                #raise RuntimeError(msg)
                #sys.stdout.flush()

                #elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                #elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                #elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                self.grid.InsertNextCell(elem.GetCellType(),
                                         elem.GetPointIds())

            elif (isinstance(element, CQUAD4) or isinstance(element, CSHEAR) or
                  isinstance(element, CQUADR)):
                nodeIDs = element.nodeIDs()
                elem = vtkQuad()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]])
                self.grid.InsertNextCell(elem.GetCellType(),
                                         elem.GetPointIds())
            elif isinstance(element, CQUAD8):
                nodeIDs = element.nodeIDs()
                if None not in nodeIDs:
                    elem = vtkQuadraticQuad()
                    elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]])
                    elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]])
                    elem.GetPointIds().SetId(6, nidMap[nodeIDs[6]])
                    elem.GetPointIds().SetId(7, nidMap[nodeIDs[7]])
                else:
                    elem = vtkQuad()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]])
                self.grid.InsertNextCell(elem.GetCellType(),
                                         elem.GetPointIds())
            elif isinstance(element, CTETRA4):
                elem = vtkTetra()
                nodeIDs = element.nodeIDs()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]])
                self.grid.InsertNextCell(elem.GetCellType(),
                                         elem.GetPointIds())
            elif isinstance(element, CTETRA10):
                nodeIDs = element.nodeIDs()
                if None not in nodeIDs:
                    elem = vtkQuadraticTetra()
                    elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]])
                    elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]])
                    elem.GetPointIds().SetId(6, nidMap[nodeIDs[6]])
                    elem.GetPointIds().SetId(7, nidMap[nodeIDs[7]])
                    elem.GetPointIds().SetId(8, nidMap[nodeIDs[8]])
                    elem.GetPointIds().SetId(9, nidMap[nodeIDs[9]])
                else:
                    elem = vtkTetra()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]])
                self.grid.InsertNextCell(elem.GetCellType(),
                                         elem.GetPointIds())
            elif isinstance(element, CPENTA6):
                elem = vtkWedge()
                nodeIDs = element.nodeIDs()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]])
                elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]])
                elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]])
                self.grid.InsertNextCell(elem.GetCellType(),
                                         elem.GetPointIds())

            elif isinstance(element, CPENTA15):
                nodeIDs = element.nodeIDs()
                if None not in nodeIDs:
                    elem = vtkQuadraticWedge()
                    elem.GetPointIds().SetId(6, nidMap[nodeIDs[6]])
                    elem.GetPointIds().SetId(7, nidMap[nodeIDs[7]])
                    elem.GetPointIds().SetId(8, nidMap[nodeIDs[8]])
                    elem.GetPointIds().SetId(9, nidMap[nodeIDs[9]])
                    elem.GetPointIds().SetId(10, nidMap[nodeIDs[10]])
                    elem.GetPointIds().SetId(11, nidMap[nodeIDs[11]])
                    elem.GetPointIds().SetId(12, nidMap[nodeIDs[12]])
                    elem.GetPointIds().SetId(13, nidMap[nodeIDs[13]])
                    elem.GetPointIds().SetId(14, nidMap[nodeIDs[14]])
                else:
                    elem = vtkWedge()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]])
                elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]])
                elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]])
                self.grid.InsertNextCell(elem.GetCellType(),
                                         elem.GetPointIds())
            elif isinstance(element, CHEXA8):
                nodeIDs = element.nodeIDs()
                elem = vtkHexahedron()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]])
                elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]])
                elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]])
                elem.GetPointIds().SetId(6, nidMap[nodeIDs[6]])
                elem.GetPointIds().SetId(7, nidMap[nodeIDs[7]])
                self.grid.InsertNextCell(elem.GetCellType(),
                                         elem.GetPointIds())
            elif isinstance(element, CHEXA20):
                nodeIDs = element.nodeIDs()
                #print "nodeIDs = ",nodeIDs
                if None not in nodeIDs:
                    elem = vtkQuadraticHexahedron()
                    elem.GetPointIds().SetId(8, nidMap[nodeIDs[8]])
                    elem.GetPointIds().SetId(9, nidMap[nodeIDs[9]])
                    elem.GetPointIds().SetId(10, nidMap[nodeIDs[10]])
                    elem.GetPointIds().SetId(11, nidMap[nodeIDs[11]])
                    elem.GetPointIds().SetId(12, nidMap[nodeIDs[12]])
                    elem.GetPointIds().SetId(13, nidMap[nodeIDs[13]])
                    elem.GetPointIds().SetId(14, nidMap[nodeIDs[14]])
                    elem.GetPointIds().SetId(15, nidMap[nodeIDs[15]])
                    elem.GetPointIds().SetId(16, nidMap[nodeIDs[16]])
                    elem.GetPointIds().SetId(17, nidMap[nodeIDs[17]])
                    elem.GetPointIds().SetId(18, nidMap[nodeIDs[18]])
                    elem.GetPointIds().SetId(19, nidMap[nodeIDs[19]])
                else:
                    elem = vtkHexahedron()

                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]])
                elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]])
                elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]])
                elem.GetPointIds().SetId(6, nidMap[nodeIDs[6]])
                elem.GetPointIds().SetId(7, nidMap[nodeIDs[7]])
                self.grid.InsertNextCell(elem.GetCellType(),
                                         elem.GetPointIds())
            elif (isinstance(element, LineElement) or
                  isinstance(element, SpringElement)):
                elem = vtk.vtkLine()
                nodeIDs = element.nodeIDs()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                self.grid.InsertNextCell(elem.GetCellType(),
                                         elem.GetPointIds())
            ###
            elif isinstance(element, CONM2):  # not perfectly located
                del self.eidMap[eid]
                i -= 1

                nid = element.Nid()
                c = element.Centroid()
                elem = vtk.vtkVertex()
                #elem = vtk.vtkSphere()
                #elem.SetRadius(1.0)
                #print str(element)

                points2.InsertPoint(j, *c)
                elem.GetPointIds().SetId(0, j)
                #elem.SetCenter(points.GetPoint(nidMap[nid]))
                self.grid2.InsertNextCell(elem.GetCellType(),
                                          elem.GetPointIds())
                j += 1
            else:
                del self.eidMap[eid]
                i -= 1

                print("skipping %s" % (element.type))
            i += 1
        ###
        self.grid.SetPoints(points)
        self.grid2.SetPoints(points2)
        #self.grid.GetPointData().SetScalars(self.gridResult)
        #print dir(self.grid) #.SetNumberOfComponents(0)
        #self.grid.GetCellData().SetNumberOfTuples(1);
        #self.grid.GetCellData().SetScalars(self.gridResult)
        self.grid.Modified()
        self.grid2.Modified()
        self.grid.Update()
        self.grid2.Update()
        print("updated grid")
コード例 #48
0
points = vtk.vtkPoints()
points.InsertNextPoint(0, 0, 0)
points.InsertNextPoint(1, 0, 0)
points.InsertNextPoint(1, 1, 0)
points.InsertNextPoint(0, 1, 1)
points.InsertNextPoint(5, 5, 5)
points.InsertNextPoint(6, 5, 5)
points.InsertNextPoint(6, 6, 5)
points.InsertNextPoint(5, 6, 6)

# The first tetrahedron
unstructuredGrid1 = vtk.vtkUnstructuredGrid()
unstructuredGrid1.SetPoints(points)

tetra = vtk.vtkTetra()

tetra.GetPointIds().SetId(0, 0)
tetra.GetPointIds().SetId(1, 1)
tetra.GetPointIds().SetId(2, 2)
tetra.GetPointIds().SetId(3, 3)

cellArray = vtk.vtkCellArray()
cellArray.InsertNextCell(tetra)
unstructuredGrid1.SetCells(vtk.VTK_TETRA, cellArray)

# The second tetrahedron
unstructuredGrid2 = vtk.vtkUnstructuredGrid()
unstructuredGrid2.SetPoints(points)

tetra = vtk.vtkTetra()
コード例 #49
0
ファイル: demoGui.py プロジェクト: xirxa/pynastran-locr
    def mapElements(self, points, points2, nidMap, model, j):
        for eid, element in sorted(model.elements.iteritems()):
            if isinstance(element, CTRIA3):
                #print "ctria3"
                elem = vtkTriangle()
                nodeIDs = element.nodeIDs()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                self.grid.InsertNextCell(
                    elem.GetCellType(), elem.GetPointIds())
            elif isinstance(element, CTRIA6):
                nodeIDs = element.nodeIDs()
                if None not in nodeIDs:
                    elem = vtkQuadraticTriangle()
                    elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]])
                    elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]])
                    elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]])
                else:
                    elem = vtkTriangle()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                self.grid.InsertNextCell(
                    elem.GetCellType(), elem.GetPointIds())
            elif isinstance(element, CQUAD4):
                nodeIDs = element.nodeIDs()
                elem = vtkQuad()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]])
                self.grid.InsertNextCell(
                    elem.GetCellType(), elem.GetPointIds())
            elif isinstance(element, CQUAD8):
                nodeIDs = element.nodeIDs()
                if None not in nodeIDs:
                    elem = vtkQuadraticQuad()
                    elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]])
                    elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]])
                    elem.GetPointIds().SetId(6, nidMap[nodeIDs[6]])
                    elem.GetPointIds().SetId(7, nidMap[nodeIDs[7]])
                else:
                    elem = vtkQuad()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]])
                self.grid.InsertNextCell(
                    elem.GetCellType(), elem.GetPointIds())
            elif isinstance(element, CTETRA4):
                elem = vtkTetra()
                nodeIDs = element.nodeIDs()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]])
                self.grid.InsertNextCell(
                    elem.GetCellType(), elem.GetPointIds())
            elif isinstance(element, CTETRA10):
                nodeIDs = element.nodeIDs()
                if None not in nodeIDs:
                    elem = vtkQuadraticTetra()
                    elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]])
                    elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]])
                    elem.GetPointIds().SetId(6, nidMap[nodeIDs[6]])
                    elem.GetPointIds().SetId(7, nidMap[nodeIDs[7]])
                    elem.GetPointIds().SetId(8, nidMap[nodeIDs[8]])
                    elem.GetPointIds().SetId(9, nidMap[nodeIDs[9]])
                else:
                    elem = vtkTetra()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]])
                self.grid.InsertNextCell(
                    elem.GetCellType(), elem.GetPointIds())
            elif isinstance(element, CPENTA6):
                elem = vtkWedge()
                nodeIDs = element.nodeIDs()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]])
                elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]])
                elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]])
                self.grid.InsertNextCell(
                    elem.GetCellType(), elem.GetPointIds())

            elif isinstance(element, CPENTA15):
                nodeIDs = element.nodeIDs()
                if None not in nodeIDs:
                    elem = vtkQuadraticWedge()
                    elem.GetPointIds().SetId(6, nidMap[nodeIDs[6]])
                    elem.GetPointIds().SetId(7, nidMap[nodeIDs[7]])
                    elem.GetPointIds().SetId(8, nidMap[nodeIDs[8]])
                    elem.GetPointIds().SetId(9, nidMap[nodeIDs[9]])
                    elem.GetPointIds().SetId(10, nidMap[nodeIDs[10]])
                    elem.GetPointIds().SetId(11, nidMap[nodeIDs[11]])
                    elem.GetPointIds().SetId(12, nidMap[nodeIDs[12]])
                    elem.GetPointIds().SetId(13, nidMap[nodeIDs[13]])
                    elem.GetPointIds().SetId(14, nidMap[nodeIDs[14]])
                else:
                    elem = vtkWedge()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]])
                elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]])
                elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]])
                self.grid.InsertNextCell(
                    elem.GetCellType(), elem.GetPointIds())
            elif isinstance(element, CHEXA8):
                nodeIDs = element.nodeIDs()
                elem = vtkHexahedron()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]])
                elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]])
                elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]])
                elem.GetPointIds().SetId(6, nidMap[nodeIDs[6]])
                elem.GetPointIds().SetId(7, nidMap[nodeIDs[7]])
                self.grid.InsertNextCell(
                    elem.GetCellType(), elem.GetPointIds())
            elif isinstance(element, CHEXA20):
                nodeIDs = element.nodeIDs()
                #print "nodeIDs = ",nodeIDs
                if None not in nodeIDs:
                    elem = vtkQuadraticHexahedron()
                    elem.GetPointIds().SetId(8, nidMap[nodeIDs[8]])
                    elem.GetPointIds().SetId(9, nidMap[nodeIDs[9]])
                    elem.GetPointIds().SetId(10, nidMap[nodeIDs[10]])
                    elem.GetPointIds().SetId(11, nidMap[nodeIDs[11]])
                    elem.GetPointIds().SetId(12, nidMap[nodeIDs[12]])
                    elem.GetPointIds().SetId(13, nidMap[nodeIDs[13]])
                    elem.GetPointIds().SetId(14, nidMap[nodeIDs[14]])
                    elem.GetPointIds().SetId(15, nidMap[nodeIDs[15]])
                    elem.GetPointIds().SetId(16, nidMap[nodeIDs[16]])
                    elem.GetPointIds().SetId(17, nidMap[nodeIDs[17]])
                    elem.GetPointIds().SetId(18, nidMap[nodeIDs[18]])
                    elem.GetPointIds().SetId(19, nidMap[nodeIDs[19]])
                else:
                    elem = vtkHexahedron()

                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]])
                elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]])
                elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]])
                elem.GetPointIds().SetId(6, nidMap[nodeIDs[6]])
                elem.GetPointIds().SetId(7, nidMap[nodeIDs[7]])
                self.grid.InsertNextCell(
                    elem.GetCellType(), elem.GetPointIds())
            elif isinstance(element, LineElement) or isinstance(element, SpringElement):
                elem = vtk.vtkLine()
                nodeIDs = element.nodeIDs()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                self.grid.InsertNextCell(
                    elem.GetCellType(), elem.GetPointIds())
            ###
            elif isinstance(element, CONM2):  # not perfectly located
                nid = element.Nid()
                c = element.Centroid()
                elem = vtk.vtkVertex()
                #elem = vtk.vtkSphere()
                #elem.SetRadius(1.0)
                #print str(element)

                points2.InsertPoint(j, *c)
                elem.GetPointIds().SetId(0, j)
                #elem.SetCenter(points.GetPoint(nidMap[nid]))
                self.grid2.InsertNextCell(
                    elem.GetCellType(), elem.GetPointIds())
                j += 1
            else:
                print "skipping %s" % (element.type)

        ###
        self.grid.SetPoints(points)
        self.grid2.SetPoints(points2)
        self.grid.Update()
        self.grid2.Update()
コード例 #50
0
    def testCells(self):

        # Demonstrates all cell types
        #
        # NOTE: the use of NewInstance/DeepCopy is included to increase
        # regression coverage.  It is not required in most applications.

        ren = vtk.vtkRenderer()
        # turn off all cullers
        ren.GetCullers().RemoveAllItems()

        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)
        renWin.SetSize(300, 150)
        iRen = vtk.vtkRenderWindowInteractor()
        iRen.SetRenderWindow(renWin)

        # create a scene with one of each cell type

        # Voxel

        voxelPoints = vtk.vtkPoints()
        voxelPoints.SetNumberOfPoints(8)
        voxelPoints.InsertPoint(0, 0, 0, 0)
        voxelPoints.InsertPoint(1, 1, 0, 0)
        voxelPoints.InsertPoint(2, 0, 1, 0)
        voxelPoints.InsertPoint(3, 1, 1, 0)
        voxelPoints.InsertPoint(4, 0, 0, 1)
        voxelPoints.InsertPoint(5, 1, 0, 1)
        voxelPoints.InsertPoint(6, 0, 1, 1)
        voxelPoints.InsertPoint(7, 1, 1, 1)

        aVoxel = vtk.vtkVoxel()
        aVoxel.GetPointIds().SetId(0, 0)
        aVoxel.GetPointIds().SetId(1, 1)
        aVoxel.GetPointIds().SetId(2, 2)
        aVoxel.GetPointIds().SetId(3, 3)
        aVoxel.GetPointIds().SetId(4, 4)
        aVoxel.GetPointIds().SetId(5, 5)
        aVoxel.GetPointIds().SetId(6, 6)
        aVoxel.GetPointIds().SetId(7, 7)

        bVoxel = aVoxel.NewInstance()
        bVoxel.DeepCopy(aVoxel)

        aVoxelGrid = vtk.vtkUnstructuredGrid()
        aVoxelGrid.Allocate(1, 1)
        aVoxelGrid.InsertNextCell(aVoxel.GetCellType(), aVoxel.GetPointIds())
        aVoxelGrid.SetPoints(voxelPoints)

        aVoxelMapper = vtk.vtkDataSetMapper()
        aVoxelMapper.SetInputData(aVoxelGrid)

        aVoxelActor = vtk.vtkActor()
        aVoxelActor.SetMapper(aVoxelMapper)
        aVoxelActor.GetProperty().BackfaceCullingOn()

        # Hexahedron

        hexahedronPoints = vtk.vtkPoints()
        hexahedronPoints.SetNumberOfPoints(8)
        hexahedronPoints.InsertPoint(0, 0, 0, 0)
        hexahedronPoints.InsertPoint(1, 1, 0, 0)
        hexahedronPoints.InsertPoint(2, 1, 1, 0)
        hexahedronPoints.InsertPoint(3, 0, 1, 0)
        hexahedronPoints.InsertPoint(4, 0, 0, 1)
        hexahedronPoints.InsertPoint(5, 1, 0, 1)
        hexahedronPoints.InsertPoint(6, 1, 1, 1)
        hexahedronPoints.InsertPoint(7, 0, 1, 1)

        aHexahedron = vtk.vtkHexahedron()
        aHexahedron.GetPointIds().SetId(0, 0)
        aHexahedron.GetPointIds().SetId(1, 1)
        aHexahedron.GetPointIds().SetId(2, 2)
        aHexahedron.GetPointIds().SetId(3, 3)
        aHexahedron.GetPointIds().SetId(4, 4)
        aHexahedron.GetPointIds().SetId(5, 5)
        aHexahedron.GetPointIds().SetId(6, 6)
        aHexahedron.GetPointIds().SetId(7, 7)

        bHexahedron = aHexahedron.NewInstance()
        bHexahedron.DeepCopy(aHexahedron)

        aHexahedronGrid = vtk.vtkUnstructuredGrid()
        aHexahedronGrid.Allocate(1, 1)
        aHexahedronGrid.InsertNextCell(aHexahedron.GetCellType(), aHexahedron.GetPointIds())
        aHexahedronGrid.SetPoints(hexahedronPoints)

        aHexahedronMapper = vtk.vtkDataSetMapper()
        aHexahedronMapper.SetInputData(aHexahedronGrid)

        aHexahedronActor = vtk.vtkActor()
        aHexahedronActor.SetMapper(aHexahedronMapper)
        aHexahedronActor.AddPosition(2, 0, 0)
        aHexahedronActor.GetProperty().BackfaceCullingOn()

        # Tetra

        tetraPoints = vtk.vtkPoints()
        tetraPoints.SetNumberOfPoints(4)
        tetraPoints.InsertPoint(0, 0, 0, 0)
        tetraPoints.InsertPoint(1, 1, 0, 0)
        tetraPoints.InsertPoint(2, 0.5, 1, 0)
        tetraPoints.InsertPoint(3, 0.5, 0.5, 1)

        aTetra = vtk.vtkTetra()
        aTetra.GetPointIds().SetId(0, 0)
        aTetra.GetPointIds().SetId(1, 1)
        aTetra.GetPointIds().SetId(2, 2)
        aTetra.GetPointIds().SetId(3, 3)

        bTetra = aTetra.NewInstance()
        bTetra.DeepCopy(aTetra)

        aTetraGrid = vtk.vtkUnstructuredGrid()
        aTetraGrid.Allocate(1, 1)
        aTetraGrid.InsertNextCell(aTetra.GetCellType(), aTetra.GetPointIds())
        aTetraGrid.SetPoints(tetraPoints)

        aTetraCopy = vtk.vtkUnstructuredGrid()
        aTetraCopy.ShallowCopy(aTetraGrid)

        aTetraMapper = vtk.vtkDataSetMapper()
        aTetraMapper.SetInputData(aTetraCopy)

        aTetraActor = vtk.vtkActor()
        aTetraActor.SetMapper(aTetraMapper)
        aTetraActor.AddPosition(4, 0, 0)
        aTetraActor.GetProperty().BackfaceCullingOn()

        # Wedge

        wedgePoints = vtk.vtkPoints()
        wedgePoints.SetNumberOfPoints(6)
        wedgePoints.InsertPoint(0, 0, 1, 0)
        wedgePoints.InsertPoint(1, 0, 0, 0)
        wedgePoints.InsertPoint(2, 0, 0.5, 0.5)
        wedgePoints.InsertPoint(3, 1, 1, 0)
        wedgePoints.InsertPoint(4, 1, 0, 0)
        wedgePoints.InsertPoint(5, 1, 0.5, 0.5)

        aWedge = vtk.vtkWedge()
        aWedge.GetPointIds().SetId(0, 0)
        aWedge.GetPointIds().SetId(1, 1)
        aWedge.GetPointIds().SetId(2, 2)
        aWedge.GetPointIds().SetId(3, 3)
        aWedge.GetPointIds().SetId(4, 4)
        aWedge.GetPointIds().SetId(5, 5)

        bWedge = aWedge.NewInstance()
        bWedge.DeepCopy(aWedge)

        aWedgeGrid = vtk.vtkUnstructuredGrid()
        aWedgeGrid.Allocate(1, 1)
        aWedgeGrid.InsertNextCell(aWedge.GetCellType(), aWedge.GetPointIds())
        aWedgeGrid.SetPoints(wedgePoints)

        aWedgeCopy = vtk.vtkUnstructuredGrid()
        aWedgeCopy.DeepCopy(aWedgeGrid)

        aWedgeMapper = vtk.vtkDataSetMapper()
        aWedgeMapper.SetInputData(aWedgeCopy)

        aWedgeActor = vtk.vtkActor()
        aWedgeActor.SetMapper(aWedgeMapper)
        aWedgeActor.AddPosition(6, 0, 0)
        aWedgeActor.GetProperty().BackfaceCullingOn()

        # Pyramid

        pyramidPoints = vtk.vtkPoints()
        pyramidPoints.SetNumberOfPoints(5)
        pyramidPoints.InsertPoint(0, 0, 0, 0)
        pyramidPoints.InsertPoint(1, 1, 0, 0)
        pyramidPoints.InsertPoint(2, 1, 1, 0)
        pyramidPoints.InsertPoint(3, 0, 1, 0)
        pyramidPoints.InsertPoint(4, 0.5, 0.5, 1)

        aPyramid = vtk.vtkPyramid()
        aPyramid.GetPointIds().SetId(0, 0)
        aPyramid.GetPointIds().SetId(1, 1)
        aPyramid.GetPointIds().SetId(2, 2)
        aPyramid.GetPointIds().SetId(3, 3)
        aPyramid.GetPointIds().SetId(4, 4)

        bPyramid = aPyramid.NewInstance()
        bPyramid.DeepCopy(aPyramid)

        aPyramidGrid = vtk.vtkUnstructuredGrid()
        aPyramidGrid.Allocate(1, 1)
        aPyramidGrid.InsertNextCell(aPyramid.GetCellType(), aPyramid.GetPointIds())
        aPyramidGrid.SetPoints(pyramidPoints)

        aPyramidMapper = vtk.vtkDataSetMapper()
        aPyramidMapper.SetInputData(aPyramidGrid)

        aPyramidActor = vtk.vtkActor()
        aPyramidActor.SetMapper(aPyramidMapper)
        aPyramidActor.AddPosition(8, 0, 0)
        aPyramidActor.GetProperty().BackfaceCullingOn()

        # Pixel

        pixelPoints = vtk.vtkPoints()
        pixelPoints.SetNumberOfPoints(4)
        pixelPoints.InsertPoint(0, 0, 0, 0)
        pixelPoints.InsertPoint(1, 1, 0, 0)
        pixelPoints.InsertPoint(2, 0, 1, 0)
        pixelPoints.InsertPoint(3, 1, 1, 0)

        aPixel = vtk.vtkPixel()
        aPixel.GetPointIds().SetId(0, 0)
        aPixel.GetPointIds().SetId(1, 1)
        aPixel.GetPointIds().SetId(2, 2)
        aPixel.GetPointIds().SetId(3, 3)

        bPixel = aPixel.NewInstance()
        bPixel.DeepCopy(aPixel)

        aPixelGrid = vtk.vtkUnstructuredGrid()
        aPixelGrid.Allocate(1, 1)
        aPixelGrid.InsertNextCell(aPixel.GetCellType(), aPixel.GetPointIds())
        aPixelGrid.SetPoints(pixelPoints)

        aPixelMapper = vtk.vtkDataSetMapper()
        aPixelMapper.SetInputData(aPixelGrid)

        aPixelActor = vtk.vtkActor()
        aPixelActor.SetMapper(aPixelMapper)
        aPixelActor.AddPosition(0, 0, 2)
        aPixelActor.GetProperty().BackfaceCullingOn()

        # Quad

        quadPoints = vtk.vtkPoints()
        quadPoints.SetNumberOfPoints(4)
        quadPoints.InsertPoint(0, 0, 0, 0)
        quadPoints.InsertPoint(1, 1, 0, 0)
        quadPoints.InsertPoint(2, 1, 1, 0)
        quadPoints.InsertPoint(3, 0, 1, 0)

        aQuad = vtk.vtkQuad()
        aQuad.GetPointIds().SetId(0, 0)
        aQuad.GetPointIds().SetId(1, 1)
        aQuad.GetPointIds().SetId(2, 2)
        aQuad.GetPointIds().SetId(3, 3)

        bQuad = aQuad.NewInstance()
        bQuad.DeepCopy(aQuad)

        aQuadGrid = vtk.vtkUnstructuredGrid()
        aQuadGrid.Allocate(1, 1)
        aQuadGrid.InsertNextCell(aQuad.GetCellType(), aQuad.GetPointIds())
        aQuadGrid.SetPoints(quadPoints)

        aQuadMapper = vtk.vtkDataSetMapper()
        aQuadMapper.SetInputData(aQuadGrid)

        aQuadActor = vtk.vtkActor()
        aQuadActor.SetMapper(aQuadMapper)
        aQuadActor.AddPosition(2, 0, 2)
        aQuadActor.GetProperty().BackfaceCullingOn()

        # Triangle

        trianglePoints = vtk.vtkPoints()
        trianglePoints.SetNumberOfPoints(3)
        trianglePoints.InsertPoint(0, 0, 0, 0)
        trianglePoints.InsertPoint(1, 1, 0, 0)
        trianglePoints.InsertPoint(2, 0.5, 0.5, 0)

        triangleTCoords = vtk.vtkFloatArray()
        triangleTCoords.SetNumberOfComponents(2)
        triangleTCoords.SetNumberOfTuples(3)
        triangleTCoords.InsertTuple2(0, 1, 1)
        triangleTCoords.InsertTuple2(1, 2, 2)
        triangleTCoords.InsertTuple2(2, 3, 3)

        aTriangle = vtk.vtkTriangle()
        aTriangle.GetPointIds().SetId(0, 0)
        aTriangle.GetPointIds().SetId(1, 1)
        aTriangle.GetPointIds().SetId(2, 2)

        bTriangle = aTriangle.NewInstance()
        bTriangle.DeepCopy(aTriangle)

        aTriangleGrid = vtk.vtkUnstructuredGrid()
        aTriangleGrid.Allocate(1, 1)
        aTriangleGrid.InsertNextCell(aTriangle.GetCellType(), aTriangle.GetPointIds())
        aTriangleGrid.SetPoints(trianglePoints)
        aTriangleGrid.GetPointData().SetTCoords(triangleTCoords)

        aTriangleMapper = vtk.vtkDataSetMapper()
        aTriangleMapper.SetInputData(aTriangleGrid)

        aTriangleActor = vtk.vtkActor()
        aTriangleActor.SetMapper(aTriangleMapper)
        aTriangleActor.AddPosition(4, 0, 2)
        aTriangleActor.GetProperty().BackfaceCullingOn()

        # Polygon

        polygonPoints = vtk.vtkPoints()
        polygonPoints.SetNumberOfPoints(4)
        polygonPoints.InsertPoint(0, 0, 0, 0)
        polygonPoints.InsertPoint(1, 1, 0, 0)
        polygonPoints.InsertPoint(2, 1, 1, 0)
        polygonPoints.InsertPoint(3, 0, 1, 0)

        aPolygon = vtk.vtkPolygon()
        aPolygon.GetPointIds().SetNumberOfIds(4)
        aPolygon.GetPointIds().SetId(0, 0)
        aPolygon.GetPointIds().SetId(1, 1)
        aPolygon.GetPointIds().SetId(2, 2)
        aPolygon.GetPointIds().SetId(3, 3)

        bPolygon = aPolygon.NewInstance()
        bPolygon.DeepCopy(aPolygon)

        aPolygonGrid = vtk.vtkUnstructuredGrid()
        aPolygonGrid.Allocate(1, 1)
        aPolygonGrid.InsertNextCell(aPolygon.GetCellType(), aPolygon.GetPointIds())
        aPolygonGrid.SetPoints(polygonPoints)

        aPolygonMapper = vtk.vtkDataSetMapper()
        aPolygonMapper.SetInputData(aPolygonGrid)

        aPolygonActor = vtk.vtkActor()
        aPolygonActor.SetMapper(aPolygonMapper)
        aPolygonActor.AddPosition(6, 0, 2)
        aPolygonActor.GetProperty().BackfaceCullingOn()

        # Triangle Strip

        triangleStripPoints = vtk.vtkPoints()
        triangleStripPoints.SetNumberOfPoints(5)
        triangleStripPoints.InsertPoint(0, 0, 1, 0)
        triangleStripPoints.InsertPoint(1, 0, 0, 0)
        triangleStripPoints.InsertPoint(2, 1, 1, 0)
        triangleStripPoints.InsertPoint(3, 1, 0, 0)
        triangleStripPoints.InsertPoint(4, 2, 1, 0)

        triangleStripTCoords = vtk.vtkFloatArray()
        triangleStripTCoords.SetNumberOfComponents(2)
        triangleStripTCoords.SetNumberOfTuples(3)
        triangleStripTCoords.InsertTuple2(0, 1, 1)
        triangleStripTCoords.InsertTuple2(1, 2, 2)
        triangleStripTCoords.InsertTuple2(2, 3, 3)
        triangleStripTCoords.InsertTuple2(3, 4, 4)
        triangleStripTCoords.InsertTuple2(4, 5, 5)

        aTriangleStrip = vtk.vtkTriangleStrip()
        aTriangleStrip.GetPointIds().SetNumberOfIds(5)
        aTriangleStrip.GetPointIds().SetId(0, 0)
        aTriangleStrip.GetPointIds().SetId(1, 1)
        aTriangleStrip.GetPointIds().SetId(2, 2)
        aTriangleStrip.GetPointIds().SetId(3, 3)
        aTriangleStrip.GetPointIds().SetId(4, 4)

        bTriangleStrip = aTriangleStrip.NewInstance()
        bTriangleStrip.DeepCopy(aTriangleStrip)

        aTriangleStripGrid = vtk.vtkUnstructuredGrid()
        aTriangleStripGrid.Allocate(1, 1)
        aTriangleStripGrid.InsertNextCell(aTriangleStrip.GetCellType(), aTriangleStrip.GetPointIds())
        aTriangleStripGrid.SetPoints(triangleStripPoints)
        aTriangleStripGrid.GetPointData().SetTCoords(triangleStripTCoords)

        aTriangleStripMapper = vtk.vtkDataSetMapper()
        aTriangleStripMapper.SetInputData(aTriangleStripGrid)

        aTriangleStripActor = vtk.vtkActor()
        aTriangleStripActor.SetMapper(aTriangleStripMapper)
        aTriangleStripActor.AddPosition(8, 0, 2)
        aTriangleStripActor.GetProperty().BackfaceCullingOn()

        # Line

        linePoints = vtk.vtkPoints()
        linePoints.SetNumberOfPoints(2)
        linePoints.InsertPoint(0, 0, 0, 0)
        linePoints.InsertPoint(1, 1, 1, 0)

        aLine = vtk.vtkLine()
        aLine.GetPointIds().SetId(0, 0)
        aLine.GetPointIds().SetId(1, 1)

        bLine = aLine.NewInstance()
        bLine.DeepCopy(aLine)

        aLineGrid = vtk.vtkUnstructuredGrid()
        aLineGrid.Allocate(1, 1)
        aLineGrid.InsertNextCell(aLine.GetCellType(), aLine.GetPointIds())
        aLineGrid.SetPoints(linePoints)

        aLineMapper = vtk.vtkDataSetMapper()
        aLineMapper.SetInputData(aLineGrid)

        aLineActor = vtk.vtkActor()
        aLineActor.SetMapper(aLineMapper)
        aLineActor.AddPosition(0, 0, 4)
        aLineActor.GetProperty().BackfaceCullingOn()

        # Poly line

        polyLinePoints = vtk.vtkPoints()
        polyLinePoints.SetNumberOfPoints(3)
        polyLinePoints.InsertPoint(0, 0, 0, 0)
        polyLinePoints.InsertPoint(1, 1, 1, 0)
        polyLinePoints.InsertPoint(2, 1, 0, 0)

        aPolyLine = vtk.vtkPolyLine()
        aPolyLine.GetPointIds().SetNumberOfIds(3)
        aPolyLine.GetPointIds().SetId(0, 0)
        aPolyLine.GetPointIds().SetId(1, 1)
        aPolyLine.GetPointIds().SetId(2, 2)

        bPolyLine = aPolyLine.NewInstance()
        bPolyLine.DeepCopy(aPolyLine)

        aPolyLineGrid = vtk.vtkUnstructuredGrid()
        aPolyLineGrid.Allocate(1, 1)
        aPolyLineGrid.InsertNextCell(aPolyLine.GetCellType(), aPolyLine.GetPointIds())
        aPolyLineGrid.SetPoints(polyLinePoints)

        aPolyLineMapper = vtk.vtkDataSetMapper()
        aPolyLineMapper.SetInputData(aPolyLineGrid)

        aPolyLineActor = vtk.vtkActor()
        aPolyLineActor.SetMapper(aPolyLineMapper)
        aPolyLineActor.AddPosition(2, 0, 4)
        aPolyLineActor.GetProperty().BackfaceCullingOn()

        # Vertex

        vertexPoints = vtk.vtkPoints()
        vertexPoints.SetNumberOfPoints(1)
        vertexPoints.InsertPoint(0, 0, 0, 0)

        aVertex = vtk.vtkVertex()
        aVertex.GetPointIds().SetId(0, 0)

        bVertex = aVertex.NewInstance()
        bVertex.DeepCopy(aVertex)

        aVertexGrid = vtk.vtkUnstructuredGrid()
        aVertexGrid.Allocate(1, 1)
        aVertexGrid.InsertNextCell(aVertex.GetCellType(), aVertex.GetPointIds())
        aVertexGrid.SetPoints(vertexPoints)

        aVertexMapper = vtk.vtkDataSetMapper()
        aVertexMapper.SetInputData(aVertexGrid)

        aVertexActor = vtk.vtkActor()
        aVertexActor.SetMapper(aVertexMapper)
        aVertexActor.AddPosition(0, 0, 6)
        aVertexActor.GetProperty().BackfaceCullingOn()

        # Poly Vertex

        polyVertexPoints = vtk.vtkPoints()
        polyVertexPoints.SetNumberOfPoints(3)
        polyVertexPoints.InsertPoint(0, 0, 0, 0)
        polyVertexPoints.InsertPoint(1, 1, 0, 0)
        polyVertexPoints.InsertPoint(2, 1, 1, 0)

        aPolyVertex = vtk.vtkPolyVertex()
        aPolyVertex.GetPointIds().SetNumberOfIds(3)
        aPolyVertex.GetPointIds().SetId(0, 0)
        aPolyVertex.GetPointIds().SetId(1, 1)
        aPolyVertex.GetPointIds().SetId(2, 2)

        bPolyVertex = aPolyVertex.NewInstance()
        bPolyVertex.DeepCopy(aPolyVertex)

        aPolyVertexGrid = vtk.vtkUnstructuredGrid()
        aPolyVertexGrid.Allocate(1, 1)
        aPolyVertexGrid.InsertNextCell(aPolyVertex.GetCellType(), aPolyVertex.GetPointIds())
        aPolyVertexGrid.SetPoints(polyVertexPoints)

        aPolyVertexMapper = vtk.vtkDataSetMapper()
        aPolyVertexMapper.SetInputData(aPolyVertexGrid)

        aPolyVertexActor = vtk.vtkActor()
        aPolyVertexActor.SetMapper(aPolyVertexMapper)
        aPolyVertexActor.AddPosition(2, 0, 6)
        aPolyVertexActor.GetProperty().BackfaceCullingOn()

        # Pentagonal prism

        pentaPoints = vtk.vtkPoints()
        pentaPoints.SetNumberOfPoints(10)
        pentaPoints.InsertPoint(0, 0.25, 0.0, 0.0)
        pentaPoints.InsertPoint(1, 0.75, 0.0, 0.0)
        pentaPoints.InsertPoint(2, 1.0, 0.5, 0.0)
        pentaPoints.InsertPoint(3, 0.5, 1.0, 0.0)
        pentaPoints.InsertPoint(4, 0.0, 0.5, 0.0)
        pentaPoints.InsertPoint(5, 0.25, 0.0, 1.0)
        pentaPoints.InsertPoint(6, 0.75, 0.0, 1.0)
        pentaPoints.InsertPoint(7, 1.0, 0.5, 1.0)
        pentaPoints.InsertPoint(8, 0.5, 1.0, 1.0)
        pentaPoints.InsertPoint(9, 0.0, 0.5, 1.0)

        aPenta = vtk.vtkPentagonalPrism()
        aPenta.GetPointIds().SetId(0, 0)
        aPenta.GetPointIds().SetId(1, 1)
        aPenta.GetPointIds().SetId(2, 2)
        aPenta.GetPointIds().SetId(3, 3)
        aPenta.GetPointIds().SetId(4, 4)
        aPenta.GetPointIds().SetId(5, 5)
        aPenta.GetPointIds().SetId(6, 6)
        aPenta.GetPointIds().SetId(7, 7)
        aPenta.GetPointIds().SetId(8, 8)
        aPenta.GetPointIds().SetId(9, 9)

        bPenta = aPenta.NewInstance()
        bPenta.DeepCopy(aPenta)

        aPentaGrid = vtk.vtkUnstructuredGrid()
        aPentaGrid.Allocate(1, 1)
        aPentaGrid.InsertNextCell(aPenta.GetCellType(), aPenta.GetPointIds())
        aPentaGrid.SetPoints(pentaPoints)

        aPentaCopy = vtk.vtkUnstructuredGrid()
        aPentaCopy.DeepCopy(aPentaGrid)

        aPentaMapper = vtk.vtkDataSetMapper()
        aPentaMapper.SetInputData(aPentaCopy)

        aPentaActor = vtk.vtkActor()
        aPentaActor.SetMapper(aPentaMapper)
        aPentaActor.AddPosition(10, 0, 0)
        aPentaActor.GetProperty().BackfaceCullingOn()

        # Hexagonal prism

        hexaPoints = vtk.vtkPoints()
        hexaPoints.SetNumberOfPoints(12)
        hexaPoints.InsertPoint(0, 0.0, 0.0, 0.0)
        hexaPoints.InsertPoint(1, 0.5, 0.0, 0.0)
        hexaPoints.InsertPoint(2, 1.0, 0.5, 0.0)
        hexaPoints.InsertPoint(3, 1.0, 1.0, 0.0)
        hexaPoints.InsertPoint(4, 0.5, 1.0, 0.0)
        hexaPoints.InsertPoint(5, 0.0, 0.5, 0.0)
        hexaPoints.InsertPoint(6, 0.0, 0.0, 1.0)
        hexaPoints.InsertPoint(7, 0.5, 0.0, 1.0)
        hexaPoints.InsertPoint(8, 1.0, 0.5, 1.0)
        hexaPoints.InsertPoint(9, 1.0, 1.0, 1.0)
        hexaPoints.InsertPoint(10, 0.5, 1.0, 1.0)
        hexaPoints.InsertPoint(11, 0.0, 0.5, 1.0)

        aHexa = vtk.vtkHexagonalPrism()
        aHexa.GetPointIds().SetId(0, 0)
        aHexa.GetPointIds().SetId(1, 1)
        aHexa.GetPointIds().SetId(2, 2)
        aHexa.GetPointIds().SetId(3, 3)
        aHexa.GetPointIds().SetId(4, 4)
        aHexa.GetPointIds().SetId(5, 5)
        aHexa.GetPointIds().SetId(6, 6)
        aHexa.GetPointIds().SetId(7, 7)
        aHexa.GetPointIds().SetId(8, 8)
        aHexa.GetPointIds().SetId(9, 9)
        aHexa.GetPointIds().SetId(10, 10)
        aHexa.GetPointIds().SetId(11, 11)

        bHexa = aHexa.NewInstance()
        bHexa.DeepCopy(aHexa)

        aHexaGrid = vtk.vtkUnstructuredGrid()
        aHexaGrid.Allocate(1, 1)
        aHexaGrid.InsertNextCell(aHexa.GetCellType(), aHexa.GetPointIds())
        aHexaGrid.SetPoints(hexaPoints)

        aHexaCopy = vtk.vtkUnstructuredGrid()
        aHexaCopy.DeepCopy(aHexaGrid)

        aHexaMapper = vtk.vtkDataSetMapper()
        aHexaMapper.SetInputData(aHexaCopy)

        aHexaActor = vtk.vtkActor()
        aHexaActor.SetMapper(aHexaMapper)
        aHexaActor.AddPosition(12, 0, 0)
        aHexaActor.GetProperty().BackfaceCullingOn()

        # RIB property
        aRIBProperty = vtk.vtkRIBProperty()
        aRIBProperty.SetVariable("Km", "float")
        aRIBProperty.SetSurfaceShader("LGVeinedmarble")
        aRIBProperty.SetVariable("veinfreq", "float")
        aRIBProperty.AddVariable("warpfreq", "float")
        aRIBProperty.AddVariable("veincolor", "color")
        aRIBProperty.AddParameter("veinfreq", " 2")
        aRIBProperty.AddParameter("veincolor", "1.0000 1.0000 0.9412")
        bRIBProperty = vtk.vtkRIBProperty()
        bRIBProperty.SetVariable("Km", "float")
        bRIBProperty.SetParameter("Km", "1.0")
        bRIBProperty.SetDisplacementShader("dented")
        bRIBProperty.SetSurfaceShader("plastic")
        aProperty = vtk.vtkProperty()
        bProperty = vtk.vtkProperty()

        aTriangleActor.SetProperty(aProperty)
        aTriangleStripActor.SetProperty(bProperty)

        ren.SetBackground(0.1, 0.2, 0.4)

        ren.AddActor(aVoxelActor)
        aVoxelActor.GetProperty().SetDiffuseColor(1, 0, 0)
        ren.AddActor(aHexahedronActor)
        aHexahedronActor.GetProperty().SetDiffuseColor(1, 1, 0)
        ren.AddActor(aTetraActor)
        aTetraActor.GetProperty().SetDiffuseColor(0, 1, 0)
        ren.AddActor(aWedgeActor)
        aWedgeActor.GetProperty().SetDiffuseColor(0, 1, 1)
        ren.AddActor(aPyramidActor)
        aPyramidActor.GetProperty().SetDiffuseColor(1, 0, 1)
        ren.AddActor(aPixelActor)
        aPixelActor.GetProperty().SetDiffuseColor(0, 1, 1)
        ren.AddActor(aQuadActor)
        aQuadActor.GetProperty().SetDiffuseColor(1, 0, 1)
        ren.AddActor(aTriangleActor)
        aTriangleActor.GetProperty().SetDiffuseColor(0.3, 1, 0.5)
        ren.AddActor(aPolygonActor)
        aPolygonActor.GetProperty().SetDiffuseColor(1, 0.4, 0.5)
        ren.AddActor(aTriangleStripActor)
        aTriangleStripActor.GetProperty().SetDiffuseColor(0.3, 0.7, 1)
        ren.AddActor(aLineActor)
        aLineActor.GetProperty().SetDiffuseColor(0.2, 1, 1)
        ren.AddActor(aPolyLineActor)
        aPolyLineActor.GetProperty().SetDiffuseColor(1, 1, 1)
        ren.AddActor(aVertexActor)
        aVertexActor.GetProperty().SetDiffuseColor(1, 1, 1)
        ren.AddActor(aPolyVertexActor)
        aPolyVertexActor.GetProperty().SetDiffuseColor(1, 1, 1)
        ren.AddActor(aPentaActor)
        aPentaActor.GetProperty().SetDiffuseColor(0.2, 0.4, 0.7)
        ren.AddActor(aHexaActor)
        aHexaActor.GetProperty().SetDiffuseColor(0.7, 0.5, 1)

        aRIBLight = vtk.vtkRIBLight()
        aRIBLight.ShadowsOn()
        aLight = vtk.vtkLight()

        aLight.PositionalOn()
        aLight.SetConeAngle(25)

        ren.AddLight(aLight)

        ren.ResetCamera()
        ren.GetActiveCamera().Azimuth(30)
        ren.GetActiveCamera().Elevation(20)
        ren.GetActiveCamera().Dolly(2.8)
        ren.ResetCameraClippingRange()

        aLight.SetFocalPoint(ren.GetActiveCamera().GetFocalPoint())
        aLight.SetPosition(ren.GetActiveCamera().GetPosition())

        # write to the temp directory if possible, otherwise use .
        dir = tempfile.gettempdir()

        atext = vtk.vtkTexture()
        pnmReader = vtk.vtkBMPReader()
        pnmReader.SetFileName(VTK_DATA_ROOT + "/Data/masonry.bmp")
        atext.SetInputConnection(pnmReader.GetOutputPort())
        atext.InterpolateOff()
        aTriangleActor.SetTexture(atext)
        rib = vtk.vtkRIBExporter()
        rib.SetInput(renWin)
        rib.SetFilePrefix(dir + "/cells")
        rib.SetTexturePrefix(dir + "/cells")
        rib.Write()
        os.remove(dir + "/cells.rib")

        iv = vtk.vtkIVExporter()
        iv.SetInput(renWin)
        iv.SetFileName(dir + "/cells.iv")
        iv.Write()
        os.remove(dir + "/cells.iv")

        obj = vtk.vtkOBJExporter()
        obj.SetInput(renWin)
        obj.SetFilePrefix(dir + "/cells")
        obj.Write()
        os.remove(dir + "/cells.obj")
        os.remove(dir + "/cells.mtl")

        vrml = vtk.vtkVRMLExporter()
        vrml.SetInput(renWin)
        # vrml.SetStartWrite(vrml.SetFileName(dir + "/cells.wrl"))
        # vrml.SetEndWrite(vrml.SetFileName("/a/acells.wrl"))
        vrml.SetFileName(dir + "/cells.wrl")
        vrml.SetSpeed(5.5)
        vrml.Write()
        os.remove(dir + "/cells.wrl")

        oogl = vtk.vtkOOGLExporter()
        oogl.SetInput(renWin)
        oogl.SetFileName(dir + "/cells.oogl")
        oogl.Write()
        os.remove(dir + "/cells.oogl")

        # the UnRegister calls are because make object is the same as New,
        # and causes memory leaks. (Python does not treat NewInstance the same as New).
        def DeleteCopies():
            bVoxel.UnRegister(None)
            bHexahedron.UnRegister(None)
            bTetra.UnRegister(None)
            bWedge.UnRegister(None)
            bPyramid.UnRegister(None)
            bPixel.UnRegister(None)
            bQuad.UnRegister(None)
            bTriangle.UnRegister(None)
            bPolygon.UnRegister(None)
            bTriangleStrip.UnRegister(None)
            bLine.UnRegister(None)
            bPolyLine.UnRegister(None)
            bVertex.UnRegister(None)
            bPolyVertex.UnRegister(None)
            bPenta.UnRegister(None)
            bHexa.UnRegister(None)

        DeleteCopies()

        # render and interact with data

        renWin.Render()

        img_file = "cells.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
コード例 #51
0
ファイル: abaqus_io.py プロジェクト: hurlei/pyNastran
    def load_abaqus_geometry(self, abaqus_filename, dirname, name='main', plot=True):
        """loads abaqus input files into the gui"""
        skip_reading = self._remove_old_cart3d_geometry(abaqus_filename)
        if skip_reading:
            return

        self.eid_map = {}
        self.nid_map = {}
        model = Abaqus(log=self.log, debug=False)
        self.model_type = 'abaqus'
        #self.model_type = model.model_type
        model.read_abaqus_inp(abaqus_filename)

        n_r2d2 = 0
        n_cpe3 = 0
        n_cpe4 = 0
        n_cpe4r = 0
        n_coh2d4 = 0
        n_c3d10h = 0

        n_cohax4 = 0
        n_cax3 = 0
        n_cax4r = 0

        nnodes = 0
        nelements = 0
        all_nodes = []
        for part_name, part in iteritems(model.parts):
            nids = part.nids - 1
            nodes = part.nodes

            nnodes += nodes.shape[0]
            if part.r2d2 is not None:
                n_r2d2 += part.r2d2.shape[0]
            if part.cpe3 is not None:
                n_cpe3 += part.cpe3.shape[0]
            if part.cpe4 is not None:
                n_cpe4 += part.cpe4.shape[0]
            if part.cpe4r is not None:
                n_cpe4r += part.cpe4r.shape[0]
            if part.coh2d4 is not None:
                n_coh2d4 += part.coh2d4.shape[0]

            if part.cohax4 is not None:
                n_cohax4 += part.cohax4.shape[0]
            if part.cax3 is not None:
                n_cax3 += part.cax3.shape[0]
            if part.cax4r is not None:
                n_cax4r += part.cax4r.shape[0]

            if part.c3d10h is not None:
                n_c3d10h += part.c3d10h.shape[0]

            all_nodes.append(nodes)
        nelements += n_r2d2 + n_cpe3 + n_cpe4 + n_cpe4r + n_coh2d4 + n_c3d10h + n_cohax4 + n_cax3 + n_cax4r
        assert nelements > 0, nelements
        #nodes = model.nodes
        #elements = model.elements


        self.nNodes = nnodes
        self.nElements = nelements

        self.grid.Allocate(self.nElements, 1000)

        points = vtk.vtkPoints()
        points.SetNumberOfPoints(self.nNodes)
        self.nid_map = {}

        assert nodes is not None
        nnodes = nodes.shape[0]

        if len(all_nodes) == 1:
            nodes = all_nodes[0]
        else:
            nodes = np.vstack(all_nodes)

        mmax = np.amax(nodes, axis=0)
        mmin = np.amin(nodes, axis=0)
        dim_max = (mmax - mmin).max()
        self.create_global_axes(dim_max)

        data_type = vtk.VTK_FLOAT
        points_array = numpy_to_vtk(
            num_array=nodes,
            deep=True,
            array_type=data_type
        )
        points.SetData(points_array)

        nid_offset = -1
        for part_name, part in iteritems(model.parts):
            nnodesi = part.nodes.shape[0]

            n_r2d2 = 0
            n_cpe3 = 0
            n_cpe4 = 0
            n_cpe4r = 0
            n_coh2d4 = 0
            n_c3d10h = 0

            n_cohax4 = 0
            n_cax3 = 0
            n_cax4r = 0
            if part.r2d2 is not None:
                n_r2d2 += part.r2d2.shape[0]
            if part.cpe3 is not None:
                n_cpe3 += part.cpe3.shape[0]
            if part.cpe4 is not None:
                n_cpe4 += part.cpe4.shape[0]
            if part.cpe4r is not None:
                n_cpe4r += part.cpe4r.shape[0]

            if part.coh2d4 is not None:
                n_coh2d4 += part.coh2d4.shape[0]
            if part.cohax4 is not None:
                n_cohax4 += part.cohax4.shape[0]
            if part.cax3 is not None:
                n_cax3 += part.cax3.shape[0]
            if part.cax4r is not None:
                n_cax4r += part.cax4r.shape[0]

            # solids
            if part.c3d10h is not None:
                n_c3d10h += part.c3d10h.shape[0]

            if n_r2d2:
                eids = part.r2d2[:, 0]
                node_ids = part.r2d2[:, 1:] + nid_offset
                for eid, node_ids in zip(eids, node_ids):
                    elem = vtkLine()
                    elem.GetPointIds().SetId(0, node_ids[0])
                    elem.GetPointIds().SetId(1, node_ids[1])
                    self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())

            if n_cpe3:
                eids = part.cpe3[:, 0]
                node_ids = part.cpe3[:, 1:] + nid_offset
                for eid, node_ids in zip(eids, node_ids):
                    elem = vtkTriangle()
                    elem.GetPointIds().SetId(0, node_ids[0])
                    elem.GetPointIds().SetId(1, node_ids[1])
                    elem.GetPointIds().SetId(2, node_ids[2])
                    self.grid.InsertNextCell(5, elem.GetPointIds())

            if n_cpe4:
                eids = part.cpe4[:, 0]
                node_ids = part.cpe4[:, 1:] + nid_offset
                for eid, node_ids in zip(eids, node_ids):
                    elem = vtkQuad()
                    elem.GetPointIds().SetId(0, node_ids[0])
                    elem.GetPointIds().SetId(1, node_ids[1])
                    elem.GetPointIds().SetId(2, node_ids[2])
                    elem.GetPointIds().SetId(3, node_ids[3])
                    self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())

            if n_cpe4r:
                eids = part.cpe4r[:, 0]
                node_ids = part.cpe4r[:, 1:] + nid_offset
                for eid, node_ids in zip(eids, node_ids):
                    elem = vtkQuad()
                    elem.GetPointIds().SetId(0, node_ids[0])
                    elem.GetPointIds().SetId(1, node_ids[1])
                    elem.GetPointIds().SetId(2, node_ids[2])
                    elem.GetPointIds().SetId(3, node_ids[3])
                    self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())

            if n_coh2d4:
                eids = part.coh2d4[:, 0]
                node_ids = part.coh2d4[:, 1:] + nid_offset
                for eid, node_ids in zip(eids, node_ids):
                    elem = vtkQuad()
                    elem.GetPointIds().SetId(0, node_ids[0])
                    elem.GetPointIds().SetId(1, node_ids[1])
                    elem.GetPointIds().SetId(2, node_ids[2])
                    elem.GetPointIds().SetId(3, node_ids[3])
                    self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())

            if n_cohax4:
                eids = part.cohax4[:, 0]
                node_ids = part.cohax4[:, 1:] + nid_offset
                for eid, node_ids in zip(eids, node_ids):
                    elem = vtkQuad()
                    elem.GetPointIds().SetId(0, node_ids[0])
                    elem.GetPointIds().SetId(1, node_ids[1])
                    elem.GetPointIds().SetId(2, node_ids[2])
                    elem.GetPointIds().SetId(3, node_ids[3])
                    self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())

            if n_cax3:
                eids = part.cax3[:, 0]
                node_ids = part.cax3[:, 1:] + nid_offset
                for eid, node_ids in zip(eids, node_ids):
                    elem = vtkTriangle()
                    elem.GetPointIds().SetId(0, node_ids[0])
                    elem.GetPointIds().SetId(1, node_ids[1])
                    elem.GetPointIds().SetId(2, node_ids[2])
                    self.grid.InsertNextCell(5, elem.GetPointIds())

            if n_cax4r:
                eids = part.cax4r[:, 0]
                node_ids = part.cax4r[:, 1:] + nid_offset
                for eid, node_ids in zip(eids, node_ids):
                    elem = vtkQuad()
                    elem.GetPointIds().SetId(0, node_ids[0])
                    elem.GetPointIds().SetId(1, node_ids[1])
                    elem.GetPointIds().SetId(2, node_ids[2])
                    elem.GetPointIds().SetId(3, node_ids[3])
                    self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())

            # solids
            if n_c3d10h:
                eids = part.c3d10h[:, 0]
                node_ids = part.c3d10h[:, 1:] + nid_offset
                for eid, node_ids in zip(eids, node_ids):
                #for eid, node_ids in part.c3d10h:
                    elem = vtkTetra()
                    elem.GetPointIds().SetId(0, node_ids[0])
                    elem.GetPointIds().SetId(1, node_ids[1])
                    elem.GetPointIds().SetId(2, node_ids[2])
                    elem.GetPointIds().SetId(3, node_ids[3])
                    self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())
            nid_offset += nnodesi

        self.grid.SetPoints(points)
        self.grid.Modified()
        if hasattr(self.grid, 'Update'):
            self.grid.Update()

        # loadCart3dResults - regions/loads
        #self.turn_text_on()
        self.scalarBar.VisibilityOn()
        self.scalarBar.Modified()

        note = ''
        self.iSubcaseNameMap = {1: ['Abaqus%s' % note, '']}
        #form = []
        cases = {}
        ID = 1
        form, cases, icase = self._fill_abaqus_case(cases, ID, nodes, nelements, model)
        #self._fill_cart3d_results(cases, form, icase, ID, model)
        self._finish_results_io2(form, cases)
コード例 #52
0
ファイル: vtu_io.py プロジェクト: cpknowles/dolfin-adjoint
def write_vtu(filename, fns, index = None, t = None):
    """
    Write the supplied Function or Function s to a vtu or pvtu file with the
    supplied filename base. If the Function s are defined on multiple function
    spaces then separate output files are written for each function space. The
    optional integer index can be used to add an index to the output filenames.
    If t is supplied then a scalar field equal to t and with name "time" is added
    to the output files.

    All Function s should be on the same mesh and have unique names. In 1D all
    Function s must have Lagrange basis functions (continuous or discontinous)
    with degree 0 to 3. In 2D and 3D all Function s must have Lagrange basis
    functions (continuous or discontinuous) with degree 0 to 2.
    """

    if isinstance(fns, dolfin.Function):
        return write_vtu(filename, [fns], index = index, t = t)
    if not isinstance(filename, str):
        raise InvalidArgumentException("filename must be a string")
    if not isinstance(fns, list):
        raise InvalidArgumentException("fns must be a Function or a list of Function s")
    if len(fns) == 0:
        raise InvalidArgumentException("fns must include at least one Function")
    for fn in fns:
        if not isinstance(fn, dolfin.Function):
            raise InvalidArgumentException("fns must be a Function or a list of Function s")
    if not index is None and not isinstance(index, int):
        raise InvalidArgumentException("index must be an integer")
    if not t is None and not isinstance(t, (float, dolfin.Constant)):
        raise InvalidArgumentException("t must be a float or Constant")

    mesh = fns[0].function_space().mesh()
    dim = mesh.geometry().dim()
    if not dim in [1, 2, 3]:
        raise NotImplementedException("Mesh dimension %i not supported by write_vtu" % dim)

    def expand_sub_fns(fn):
        n_sub_spaces = fn.function_space().num_sub_spaces()
        if n_sub_spaces > 1:
            fns = fn.split(deepcopy = True)
            for i, sfn in enumerate(copy.copy(fns)):
                sfn.rename("%s_%i" % (fn.name(), i + 1), "%s_%i" % (fn.name(), i + 1))
                if sfn.function_space().num_sub_spaces() > 0:
                    fns.remove(sfn)
                    fns += expand_sub_fns(sfn)
            return fns
        elif n_sub_spaces == 1:
            e = fn.function_space().ufl_element().extract_component(0)[1]
            space = dolfin.FunctionSpace(mesh, e.family(), e.degree())
            sfn = dolfin.Function(space, name = "%s_1" % fn.name())
            sfn.vector()[:] = fn.vector()
            return [sfn]
        else:
            return [fn]

    nfns = []
    for i, fn in enumerate(fns):
        space = fn.function_space()
        if not space.mesh().id() == mesh.id():
            raise InvalidArgumentException("Require exactly one mesh in write_vtu")
        n_sub_spaces = space.num_sub_spaces()
        nfns += expand_sub_fns(fn)
    fns = nfns;  del(nfns)

    spaces = []
    lfns = OrderedDict()
    for fn in fns:
        space = fn.function_space()
        assert(space.mesh().id() == mesh.id())
        e = space.ufl_element()
        assert(e.cell().geometric_dimension() == dim)
        assert(e.cell().topological_dimension() == dim)
        if (not e.family() in ["Lagrange", "Discontinuous Lagrange"]
            or not dim in [1, 2, 3]
            or (dim == 1 and not e.degree() in [1, 2, 3])
            or (dim in [2, 3] and not e.degree() in [1, 2])) and \
          (not e.family() == "Discontinuous Lagrange"
            or not dim in [1, 2, 3]
            or not e.degree() == 0):
            raise NotImplementedException('Element family "%s" with degree %i in %i dimension(s) not supported by write_vtu' % (e.family(), e.degree(), dim))
        if e in lfns:
            lfns[e].append(fn)
        else:
            spaces.append(space)
            lfns[e] = [fn]
    fns = lfns

    if len(spaces) == 1:
        filenames = [filename]
    else:
        filenames = []
        for space in spaces:
            e = space.ufl_element()
            lfilename = "%s_P%i" % (filename, e.degree())
            if e.family() == "Discontinuous Lagrange":
                lfilename = "%s_DG" % lfilename
            filenames.append(lfilename)

    if not t is None:
        for space in spaces:
            lt = dolfin.Function(space, name = "time")
            if isinstance(t, float):
                lt.vector()[:] = t
            else:
                lt.assign(t)
            fns[space.ufl_element()].append(lt)

    names = {e:[] for e in fns}
    for e in fns:
        for fn in fns[e]:
            name = fn.name()
            if name in names[e]:
                raise InvalidArgumentException("Duplicate Function name: %s" % name)
            names[e].append(name)

    for filename, space in zip(filenames, spaces):
        e = space.ufl_element()
        degree = e.degree()

        vtu = vtk.vtkUnstructuredGrid()

        dof = space.dofmap()
        nodes = set()
        for i in xrange(mesh.num_cells()):
            cell =  dof.cell_dofs(i)
            for node in cell:
                nodes.add(node)
        nodes = numpy.array(sorted(list(nodes)), dtype = numpy.intc)

        if degree == 0:
            xspace = dolfin.FunctionSpace(mesh, "CG", 1)
            xdof = xspace.dofmap()
            xnodes = set()
            for i in xrange(mesh.num_cells()):
                cell =  xdof.cell_dofs(i)
                for node in cell:
                    xnodes.add(node)
            xnodes = numpy.array(sorted(list(xnodes)), dtype = numpy.intc)
        else:
            xspace = space
            xdof = dof
            xnodes = nodes
        xnode_map = {node:i for i, node in enumerate(xnodes)}

        x = dolfin.interpolate(dolfin.Expression("x[0]"), xspace).vector().gather(xnodes)
        if dim > 1:
            y = dolfin.interpolate(dolfin.Expression("x[1]"), xspace).vector().gather(xnodes)
        if dim > 2:
            z = dolfin.interpolate(dolfin.Expression("x[2]"), xspace).vector().gather(xnodes)
        n = x.shape[0]

        points = vtk.vtkPoints()
        points.SetDataTypeToDouble()
        points.SetNumberOfPoints(n)
        if dim == 1:
            for i in xrange(n):
                points.SetPoint(i, x[i], 0.0, 0.0)
        elif dim == 2:
            for i in xrange(n):
                points.SetPoint(i, x[i], y[i], 0.0)
        else:
            for i in xrange(n):
                points.SetPoint(i, x[i], y[i], z[i])
        vtu.SetPoints(points)

        id_list = vtk.vtkIdList()
        if dim == 1:
            if degree in [0, 1]:
                cell_type = vtk.vtkLine().GetCellType()
                id_list.SetNumberOfIds(2)
                cell_map = None
            elif degree == 2:
                cell_type = vtk.vtkQuadraticEdge().GetCellType()
                id_list.SetNumberOfIds(3)
                cell_map = None
            else:
                cell_type = vtk.vtkCubicLine().GetCellType()
                id_list.SetNumberOfIds(4)
                cell_map = None
        elif dim == 2:
            if degree in [0, 1]:
                cell_type = vtk.vtkTriangle().GetCellType()
                id_list.SetNumberOfIds(3)
                cell_map = None
            else:
                cell_type = vtk.vtkQuadraticTriangle().GetCellType()
                id_list.SetNumberOfIds(6)
                cell_map = {0:0, 1:1, 2:2, 3:5, 4:3, 5:4}
        else:
            if degree in [0, 1]:
                cell_type = vtk.vtkTetra().GetCellType()
                id_list.SetNumberOfIds(4)
                cell_map = None
            else:
                cell_type = vtk.vtkQuadraticTetra().GetCellType()
                id_list.SetNumberOfIds(10)
                cell_map = {0:0, 1:1, 2:2, 3:3, 4:9, 5:6, 6:8, 7:7, 8:5, 9:4}
        for i in xrange(mesh.num_cells()):
            cell = xdof.cell_dofs(i)
            assert(len(cell) == id_list.GetNumberOfIds())
            if not cell_map is None:
                cell = [cell[cell_map[j]] for j in xrange(len(cell))]
            for j in xrange(len(cell)):
                id_list.SetId(j, xnode_map[cell[j]])
            vtu.InsertNextCell(cell_type, id_list)

        if degree == 0:
            for fn in fns[e]:
                if not fn.value_rank() == 0:
                    raise NotImplementException("Function rank %i not supported by write_vtu" % fn.value_rank())
                data = fn.vector().gather(nodes)
                cell_data = vtk.vtkDoubleArray()
                cell_data.SetNumberOfComponents(1)
                cell_data.SetNumberOfValues(mesh.num_cells())
                cell_data.SetName(fn.name())
                for i, datum in enumerate(data):
                    cell_data.SetValue(i, datum)
                vtu.GetCellData().AddArray(cell_data)
            vtu.GetCellData().SetActiveScalars(names[e][0])
        else:
            for fn in fns[e]:
                if not fn.value_rank() == 0:
                    raise NotImplementException("Function rank %i not supported by write_vtu" % fn.value_rank())
                data = fn.vector().gather(nodes)
                point_data = vtk.vtkDoubleArray()
                point_data.SetNumberOfComponents(1)
                point_data.SetNumberOfValues(n)
                point_data.SetName(fn.name())
                for i, datum in enumerate(data):
                    point_data.SetValue(i, datum)
                vtu.GetPointData().AddArray(point_data)
            vtu.GetPointData().SetActiveScalars(names[e][0])

        if dolfin.MPI.num_processes() > 1:
            writer = vtk.vtkXMLPUnstructuredGridWriter()
            writer.SetNumberOfPieces(dolfin.MPI.num_processes())
            writer.SetStartPiece(dolfin.MPI.process_number())
            writer.SetEndPiece(dolfin.MPI.process_number())
            ext = ".pvtu"
        else:
            writer = vtk.vtkXMLUnstructuredGridWriter()
            ext = ".vtu"
        if index is None:
            filename = "%s%s" % (filename, ext)
        else:
            filename = "%s_%i%s" % (filename, index, ext)
        writer.SetFileName(filename)
        writer.SetDataModeToAppended()
        writer.EncodeAppendedDataOff()
        writer.SetCompressorTypeToZLib()
        writer.GetCompressor().SetCompressionLevel(9)
        writer.SetBlockSize(2 ** 15)
        writer.SetInput(vtu)
        writer.Write()
        if not writer.GetProgress() == 1.0 or not writer.GetErrorCode() == 0:
            raise IOException("Failed to write vtu file: %s" % filename)

    return
コード例 #53
0
ファイル: nastranIO.py プロジェクト: sukhbinder/cyNastran
    def mapElements(self, points, points2, nidMap, model, j):
        #self.eidMap = {}
        i = 0
        for (eid, element) in sorted(model.elements.iteritems()):
            self.eidMap[eid] = i
            #print element.type
            if isinstance(element, CTRIA3) or isinstance(element, CTRIAR):
                elem = vtkTriangle()
                nodeIDs = element.nodeIDs()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                self.grid.InsertNextCell(elem.GetCellType(),
                                         elem.GetPointIds())
            elif isinstance(element, CTRIA6):
                nodeIDs = element.nodeIDs()
                if None not in nodeIDs:
                    elem = vtkQuadraticTriangle()
                    elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]])
                    elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]])
                    elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]])
                else:
                    elem = vtkTriangle()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                self.grid.InsertNextCell(elem.GetCellType(),
                                         elem.GetPointIds())
            elif isinstance(element, CTRIAX6):
                # midside nodes are required, nodes out of order
                nodeIDs = element.nodeIDs()
                if None not in nodeIDs:
                    elem = vtkQuadraticTriangle()
                    elem.GetPointIds().SetId(3, nidMap[nodeIDs[1]])
                    elem.GetPointIds().SetId(4, nidMap[nodeIDs[3]])
                    elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]])
                else:
                    elem = vtkTriangle()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[2]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[4]])
                #a = [0,2,4]
                #msg = "CTRIAX6 %i %i %i" %(nidMap[nodeIDs[a[0]]],
                #                           nidMap[nodeIDs[a[1]]],
                #                           nidMap[nodeIDs[a[2]]] )
                #raise RuntimeError(msg)
                #sys.stdout.flush()

                #elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                #elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                #elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                self.grid.InsertNextCell(elem.GetCellType(),
                                         elem.GetPointIds())

            elif (isinstance(element, CQUAD4) or isinstance(element, CSHEAR) or
                  isinstance(element, CQUADR)):
                nodeIDs = element.nodeIDs()
                elem = vtkQuad()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]])
                self.grid.InsertNextCell(elem.GetCellType(),
                                         elem.GetPointIds())
            elif isinstance(element, CQUAD8):
                nodeIDs = element.nodeIDs()
                if None not in nodeIDs:
                    elem = vtkQuadraticQuad()
                    elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]])
                    elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]])
                    elem.GetPointIds().SetId(6, nidMap[nodeIDs[6]])
                    elem.GetPointIds().SetId(7, nidMap[nodeIDs[7]])
                else:
                    elem = vtkQuad()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]])
                self.grid.InsertNextCell(elem.GetCellType(),
                                         elem.GetPointIds())
            elif isinstance(element, CTETRA4):
                elem = vtkTetra()
                nodeIDs = element.nodeIDs()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]])
                self.grid.InsertNextCell(elem.GetCellType(),
                                         elem.GetPointIds())
            elif isinstance(element, CTETRA10):
                nodeIDs = element.nodeIDs()
                if None not in nodeIDs:
                    elem = vtkQuadraticTetra()
                    elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]])
                    elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]])
                    elem.GetPointIds().SetId(6, nidMap[nodeIDs[6]])
                    elem.GetPointIds().SetId(7, nidMap[nodeIDs[7]])
                    elem.GetPointIds().SetId(8, nidMap[nodeIDs[8]])
                    elem.GetPointIds().SetId(9, nidMap[nodeIDs[9]])
                else:
                    elem = vtkTetra()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]])
                self.grid.InsertNextCell(elem.GetCellType(),
                                         elem.GetPointIds())
            elif isinstance(element, CPENTA6):
                elem = vtkWedge()
                nodeIDs = element.nodeIDs()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]])
                elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]])
                elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]])
                self.grid.InsertNextCell(elem.GetCellType(),
                                         elem.GetPointIds())

            elif isinstance(element, CPENTA15):
                nodeIDs = element.nodeIDs()
                if None not in nodeIDs:
                    elem = vtkQuadraticWedge()
                    elem.GetPointIds().SetId(6, nidMap[nodeIDs[6]])
                    elem.GetPointIds().SetId(7, nidMap[nodeIDs[7]])
                    elem.GetPointIds().SetId(8, nidMap[nodeIDs[8]])
                    elem.GetPointIds().SetId(9, nidMap[nodeIDs[9]])
                    elem.GetPointIds().SetId(10, nidMap[nodeIDs[10]])
                    elem.GetPointIds().SetId(11, nidMap[nodeIDs[11]])
                    elem.GetPointIds().SetId(12, nidMap[nodeIDs[12]])
                    elem.GetPointIds().SetId(13, nidMap[nodeIDs[13]])
                    elem.GetPointIds().SetId(14, nidMap[nodeIDs[14]])
                else:
                    elem = vtkWedge()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]])
                elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]])
                elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]])
                self.grid.InsertNextCell(elem.GetCellType(),
                                         elem.GetPointIds())
            elif isinstance(element, CHEXA8):
                nodeIDs = element.nodeIDs()
                elem = vtkHexahedron()
                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]])
                elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]])
                elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]])
                elem.GetPointIds().SetId(6, nidMap[nodeIDs[6]])
                elem.GetPointIds().SetId(7, nidMap[nodeIDs[7]])
                self.grid.InsertNextCell(elem.GetCellType(),
                                         elem.GetPointIds())
            elif isinstance(element, CHEXA20):
                nodeIDs = element.nodeIDs()
                #print "nodeIDs = ",nodeIDs
                if None not in nodeIDs:
                    elem = vtkQuadraticHexahedron()
                    elem.GetPointIds().SetId(8, nidMap[nodeIDs[8]])
                    elem.GetPointIds().SetId(9, nidMap[nodeIDs[9]])
                    elem.GetPointIds().SetId(10, nidMap[nodeIDs[10]])
                    elem.GetPointIds().SetId(11, nidMap[nodeIDs[11]])
                    elem.GetPointIds().SetId(12, nidMap[nodeIDs[12]])
                    elem.GetPointIds().SetId(13, nidMap[nodeIDs[13]])
                    elem.GetPointIds().SetId(14, nidMap[nodeIDs[14]])
                    elem.GetPointIds().SetId(15, nidMap[nodeIDs[15]])
                    elem.GetPointIds().SetId(16, nidMap[nodeIDs[16]])
                    elem.GetPointIds().SetId(17, nidMap[nodeIDs[17]])
                    elem.GetPointIds().SetId(18, nidMap[nodeIDs[18]])
                    elem.GetPointIds().SetId(19, nidMap[nodeIDs[19]])
                else:
                    elem = vtkHexahedron()

                elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]])
                elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]])
                elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]])
                elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]])
                elem.GetPointIds().SetId(6, nidMap[nodeIDs[6]])
                elem.GetPointIds().SetId(7, nidMap[nodeIDs[7]])
                self.grid.InsertNextCell(elem.GetCellType(),
                                         elem.GetPointIds())
            elif (isinstance(element, LineElement) or
                  isinstance(element, SpringElement) or
                  element.type in ['CBUSH', 'CBUSH1D', 'CFAST', 'CROD', 'CONROD',
                      'CELAS1', 'CELAS2', 'CELAS3', 'CELAS4',
                      'CDAMP1', 'CDAMP2', 'CDAMP3', 'CDAMP4', 'CDAMP5', 'CVISC', ]):

                    nodeIDs = element.nodeIDs()
                    if None not in nodeIDs:  # used to be 0...
                        elem = vtk.vtkLine()
                        try:
                            elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
                            elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]])
                        except KeyError:
                            print "nodeIDs =", nodeIDs
                            print str(element)
                            continue
                        self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())
            elif isinstance(element, CONM2):  # not perfectly located
                del self.eidMap[eid]
                i -= 1

                #nid = element.Nid()
                c = element.Centroid()
                elem = vtk.vtkVertex()
                #elem = vtk.vtkSphere()
                #elem.SetRadius(1.0)
                #print str(element)

                points2.InsertPoint(j, *c)
                elem.GetPointIds().SetId(0, j)
                #elem.SetCenter(points.GetPoint(nidMap[nid]))
                self.grid2.InsertNextCell(elem.GetCellType(), elem.GetPointIds())
                j += 1
            else:
                del self.eidMap[eid]
                self.log_info("skipping %s" % element.type)
                continue
            i += 1

        self.grid.SetPoints(points)
        self.grid2.SetPoints(points2)
        #self.grid.GetPointData().SetScalars(self.gridResult)
        #print dir(self.grid) #.SetNumberOfComponents(0)
        #self.grid.GetCellData().SetNumberOfTuples(1);
        #self.grid.GetCellData().SetScalars(self.gridResult)
        self.grid.Modified()
        self.grid2.Modified()
        self.grid.Update()
        self.grid2.Update()
        self.log_info("updated grid")

        cases = {}
        nelements = len(model.elements)
        print "len(elements) =", nelements
        pids = [] # zeros(nelements, 'int32')
        nxs = []
        nys = []
        nzs = []
        i = 0
        for eid, element in sorted(model.elements.iteritems()):
            pids.append(element.Pid())
            if isinstance(element, ShellElement):
                (nx, ny, nz) = element.Normal()
            else:
                nx = ny = nz = 0.0
            nxs.append(nx)
            nys.append(ny)
            nzs.append(nz)

        self.iSubcaseNameMap = {1: ['Nastran', '']}

        # subcaseID, resultType, vectorSize, location, dataFormat
        if 1:
                cases[(0, 'Pid', 1, 'centroid', '%.0f')] = pids

            # if not a flat plate???
            #if min(nxs) == max(nxs) and min(nxs) != 0.0:
                # subcaseID, resultType, vectorSize, location, dataFormat
                cases[(0, 'Normal_x', 1, 'centroid', '%.1f')] = nxs
                cases[(0, 'Normal_y', 1, 'centroid', '%.1f')] = nys
                cases[(0, 'Normal_z', 1, 'centroid', '%.1f')] = nzs
        self.log.info(cases.keys())
        self.finish_io(cases)
コード例 #54
0
ファイル: usm3d_io.py プロジェクト: sukhbinder/cyNastran
    def load_usm3d_geometry(self, cogsg_filename, dirname):
        #print "load_usm3d_geometry..."
        skipReading = self.removeOldGeometry(cogsg_filename)
        if skipReading:
            return

        model = Usm3dReader(log=self.log, debug=False)

        base_filename, ext = os.path.splitext(cogsg_filename)
        #node_filename = base_filename + '.node'
        #ele_filename = base_filename + '.ele'
        if '.cogsg' == ext:
            dimension_flag = 3
        #elif '.ele' == ext:
            #dimension_flag = 3
        else:
            raise RuntimeError('unsupported extension.  Use "cogsg" or "front".')

        read_loads = True
        if self.is_centroidal:
            read_loads = False
        nodes, tris_tets, tris, bcs, mapbc, loads, flo_filename = model.read_usm3d(base_filename, dimension_flag, read_loads=read_loads)
        del tris_tets
        nodes = model.nodes
        tris = model.tris
        tets = model.tets
        bcs = model.bcs
        mapbc = model.mapbc
        loads = model.loads

        self.out_filename = None
        if flo_filename is not None:
            self.out_filename = flo_filename

        bcmap_to_bc_name = model.bcmap_to_bc_name

        self.nNodes, three = nodes.shape
        ntris = 0
        ntets = 0
        if tris is not None:
            ntris, three = tris.shape

        if dimension_flag == 2:
            pass
        elif dimension_flag == 3:
            ntets, four = tets.shape
            ntets = 0
        else:
            raise RuntimeError()
        self.nElements = ntris + ntets

        print("nNodes = ",self.nNodes)
        print("nElements = ", self.nElements)

        self.grid.Allocate(self.nElements, 1000)
        #self.gridResult.SetNumberOfComponents(self.nElements)
        self.grid2.Allocate(1, 1000)

        points = vtk.vtkPoints()
        points.SetNumberOfPoints(self.nNodes)
        #self.gridResult.Allocate(self.nNodes, 1000)
        #vectorReselt.SetNumberOfComponents(3)
        self.nidMap = {}
        #elem.SetNumberOfPoints(nNodes)
        if 0:
            fraction = 1. / self.nNodes  # so you can color the nodes by ID
            for nid, node in sorted(nodes.iteritems()):
                points.InsertPoint(nid - 1, *node)
                self.gridResult.InsertNextValue(nid * fraction)
                #print str(element)

                #elem = vtk.vtkVertex()
                #elem.GetPointIds().SetId(0, i)
                #self.aQuadGrid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())
                #vectorResult.InsertTuple3(0, 0.0, 0.0, 1.0)

        assert nodes is not None
        nnodes, three = nodes.shape

        nid = 0
        #print "nnodes=%s" % nnodes
        for i in xrange(nnodes):
            points.InsertPoint(nid, nodes[i, :])
            nid += 1

        #elements -= 1
        if ntris:
            for (n0, n1, n2) in tris:
                elem = vtkTriangle()
                #node_ids = elements[eid, :]
                elem.GetPointIds().SetId(0, n0)
                elem.GetPointIds().SetId(1, n1)
                elem.GetPointIds().SetId(2, n2)
                self.grid.InsertNextCell(5, elem.GetPointIds())  #elem.GetCellType() = 5  # vtkTriangle

        if dimension_flag == 2:
            pass
        elif dimension_flag == 3:
            if ntets:
                for (n0, n1, n2, n3) in tets:
                    elem = vtkTetra()
                    #assert elem.GetCellType() == 10, elem.GetCellType()
                    elem.GetPointIds().SetId(0, n0)
                    elem.GetPointIds().SetId(1, n1)
                    elem.GetPointIds().SetId(2, n2)
                    elem.GetPointIds().SetId(3, n3)
                    self.grid.InsertNextCell(10, elem.GetPointIds())  #elem.GetCellType() = 5  # vtkTriangle
        else:
            raise RuntimeError('dimension_flag=%r' % dimension_flag)

        self.grid.SetPoints(points)
        self.grid.Modified()
        self.grid.Update()
        print("updated grid")

        # regions/loads
        self.TurnTextOn()
        self.scalarBar.Modified()

        cases = {}
        #cases = self.resultCases
        self._fill_usm3d_results(cases, bcs, mapbc, bcmap_to_bc_name, loads)
コード例 #55
0
ファイル: vtutools.py プロジェクト: Nasrollah/fluidity
  if type.GetElementTypeId() == elements.ELEMENT_QUAD:
    newNodes = copy.deepcopy(nodes)
    newNodes[2] = nodes[3]
    newNodes[3] = nodes[2]
      
  return newNodes

if VtkSupport():
  VTK_UNKNOWN = None
  VTK_EMPTY_CELL = vtk.vtkEmptyCell().GetCellType()
  VTK_VERTEX = vtk.vtkVertex().GetCellType()
  VTK_LINE = vtk.vtkLine().GetCellType()
  VTK_QUADRATIC_LINE = vtk.vtkQuadraticEdge().GetCellType()
  VTK_TRIANGLE = vtk.vtkTriangle().GetCellType()
  VTK_QUADRATIC_TRIANGLE = vtk.vtkQuadraticTriangle().GetCellType()
  VTK_TETRAHEDRON = vtk.vtkTetra().GetCellType()
  VTK_QUADRATIC_TETRAHEDRON = vtk.vtkQuadraticTetra().GetCellType()
  VTK_QUAD = vtk.vtkQuad().GetCellType()
  VTK_HEXAHEDRON = vtk.vtkHexahedron().GetCellType()
   
  vtkTypeIds = ( \
      VTK_UNKNOWN, \
      VTK_EMPTY_CELL, \
      VTK_VERTEX, \
      VTK_LINE, VTK_QUADRATIC_LINE, \
      VTK_TRIANGLE, VTK_QUADRATIC_TRIANGLE, VTK_QUAD, \
      VTK_TETRAHEDRON, VTK_QUADRATIC_TETRAHEDRON, VTK_HEXAHEDRON \
    )
   
  class VtkType(elements.ElementType):
    """