示例#1
0
def add_user_geometry(alt_grid: vtk.vtkUnstructuredGrid,
                      geom_grid: vtk.vtkUnstructuredGrid, xyz: np.ndarray,
                      nid_map: Dict[int, int], nnodes: int, bars: np.ndarray,
                      tris: np.ndarray, quads: np.ndarray, nelements: int,
                      nbars: int, ntris: int, nquads: int) -> vtk.vtkPoints:
    """helper method for ``_add_user_geometry``"""
    # set points
    points = numpy_to_vtk_points(xyz, dtype='<f')

    if nelements > 0:
        for i in range(nnodes):
            elem = vtk.vtkVertex()
            elem.GetPointIds().SetId(0, i)
            alt_grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())
            geom_grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())
    else:
        for i in range(nnodes):
            elem = vtk.vtkVertex()
            elem.GetPointIds().SetId(0, i)
            alt_grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())

    if nbars:
        for i, bar in enumerate(bars[:, 1:]):
            g1 = nid_map[bar[0]]
            g2 = nid_map[bar[1]]
            elem = vtk.vtkLine()
            elem.GetPointIds().SetId(0, g1)
            elem.GetPointIds().SetId(1, g2)
            geom_grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())

    if ntris:
        for i, tri in enumerate(tris[:, 1:]):
            g1 = nid_map[tri[0]]
            g2 = nid_map[tri[1]]
            g3 = nid_map[tri[2]]
            elem = vtk.vtkTriangle()
            elem.GetPointIds().SetId(0, g1)
            elem.GetPointIds().SetId(1, g2)
            elem.GetPointIds().SetId(2, g3)
            geom_grid.InsertNextCell(5, elem.GetPointIds())

    if nquads:
        for i, quad in enumerate(quads[:, 1:]):
            g1 = nid_map[quad[0]]
            g2 = nid_map[quad[1]]
            g3 = nid_map[quad[2]]
            g4 = nid_map[quad[3]]
            elem = vtk.vtkQuad()
            point_ids = elem.GetPointIds()
            point_ids.SetId(0, g1)
            point_ids.SetId(1, g2)
            point_ids.SetId(2, g3)
            point_ids.SetId(3, g4)
            geom_grid.InsertNextCell(9, elem.GetPointIds())

    alt_grid.SetPoints(points)
    if nelements > 0:
        geom_grid.SetPoints(points)
    return points
  def addPointSet(self, data):
    """Add a set of points to the UnstructuredGrid vertexGrid (the source of our calculations)
    """
    
    logging.info("adding point set")
    
    size = len(data)

    # Create some landmarks, put them in UnstructuredGrid
    # Start off with some landmarks
    vertexPoints = vtk.vtkPoints()
    vertexPoints.SetNumberOfPoints(size)
    
    vertexGrid = vtk.vtkUnstructuredGrid()
    vertexGrid.Allocate(size, size)
    
    for id, (x, y, z) in enumerate(data):
      vertexPoints.InsertPoint(id, x, y, z)
      
      # Create vertices from them
      vertex = vtk.vtkVertex()
      vertex.GetPointIds().SetId(0, id)
      
      #Create an unstructured grid with the landmarks added
      vertexGrid.InsertNextCell(vertex.GetCellType(), vertex.GetPointIds())
    
    vertexGrid.SetPoints(vertexPoints)
    self.vertexGrids.append(vertexGrid)
        
    logging.info("done")
示例#3
0
文件: octree.py 项目: kliegeois/progs
    def addpts(self, pts, colour, size):
        dataset = vtk.vtkPolyData()
        dataset.Initialize()
        dataset.Allocate(len(pts), len(pts))

        for i, p in enumerate(pts):
            vertex = vtk.vtkVertex()
            ids = vertex.GetPointIds()
            ids.SetId(0, i)
            dataset.InsertNextCell(vertex.GetCellType(), ids)

        points = vtk.vtkPoints()
        points.SetNumberOfPoints(len(pts))
        dataset.SetPoints(points)
        i = 0
        for i, p in enumerate(pts):
            points.InsertPoint(i, p.x, p.y, p.z)
        points.Modified()

        mapper = vtk.vtkDataSetMapper()
        mapper.SetInputData(dataset)
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetPointSize(size)
        actor.GetProperty().SetColor(colour)
        self.actors.append(actor)
示例#4
0
def insert_value(points, vertices, zvalues, x, y, z):
    """pumping up the 3 arrays"""
    id = points.InsertNextPoint(x, y, 0.)
    vertex = vtk.vtkVertex()
    vertex.GetPointIds().InsertNextId(id)
    vertices.InsertNextCell(vertex)
    zvalues.InsertNextValue(z)
示例#5
0
    def __init__(self, pointlist=[]):
        points = vtk.vtkPoints()
        cellArr = vtk.vtkCellArray()
        Colors = vtk.vtkUnsignedCharArray()
        Colors.SetNumberOfComponents(3)
        Colors.SetName("Colors")
        
        n=0
        for p in pointlist:
            vert = vtk.vtkVertex()
            points.InsertNextPoint(p.x, p.y, p.z)
            vert.GetPointIds().SetId(0,n)
            cellArr.InsertNextCell( vert )
            col = clColor(p.cc())
            Colors.InsertNextTuple3( float(255)*col[0], float(255)*col[1], float(255)*col[2] )
            n=n+1
            
        polydata= vtk.vtkPolyData()
        polydata.SetPoints(points)
        polydata.SetVerts( cellArr )
        polydata.GetPointData().SetScalars(Colors)

        polydata.Modified()
        polydata.Update()
        self.src=polydata
        self.mapper = vtk.vtkPolyDataMapper()
        self.mapper.SetInput(self.src)
        self.SetMapper(self.mapper)
示例#6
0
    def __init__(self, pointlist=[]):
        points = vtk.vtkPoints()
        cellArr = vtk.vtkCellArray()
        Colors = vtk.vtkUnsignedCharArray()
        Colors.SetNumberOfComponents(3)
        Colors.SetName("Colors")

        n = 0
        for p in pointlist:
            vert = vtk.vtkVertex()
            points.InsertNextPoint(p.x, p.y, p.z)
            vert.GetPointIds().SetId(0, n)
            cellArr.InsertNextCell(vert)
            col = clColor(p.cc())
            Colors.InsertNextTuple3(
                float(255) * col[0],
                float(255) * col[1],
                float(255) * col[2])
            n = n + 1

        polydata = vtk.vtkPolyData()
        polydata.SetPoints(points)
        polydata.SetVerts(cellArr)
        polydata.GetPointData().SetScalars(Colors)

        polydata.Modified()
        polydata.Update()
        self.src = polydata
        self.mapper = vtk.vtkPolyDataMapper()
        self.mapper.SetInputData(self.src)
        self.SetMapper(self.mapper)
示例#7
0
def getABPointsFromTTTSectors(ugrid_sectors, verbose=True):

    if (verbose): print '*** getABPointsFromTTTSectors ***'

    nb_points = ugrid_sectors.GetNumberOfPoints()
    nb_cells = ugrid_sectors.GetNumberOfCells()

    nb_csects = 12
    nb_rsects = 3
    nb_slices = nb_points / (nb_rsects + 1) / (nb_csects + 1)
    if (verbose): print "nb_slices =", nb_slices

    zmin = ugrid_sectors.GetPoint(0)[2]
    zmax = ugrid_sectors.GetPoint(ugrid_sectors.GetNumberOfPoints() - 1)[2]

    dist_btw_slices = abs(zmin - zmax) / (nb_slices - 1)
    if (verbose): print "dist_btw_slices =", dist_btw_slices

    A = ugrid_sectors.GetPoints().GetPoint(0)
    B = ugrid_sectors.GetPoints().GetPoint(6)
    C = ugrid_sectors.GetPoints().GetPoint(3)
    D = ugrid_sectors.GetPoints().GetPoint(9)

    #print A
    #print B
    #print C
    #print D

    Px = ((A[0] * B[1] - A[1] * B[0]) * (C[0] - D[0]) - (A[0] - B[0]) *
          (C[0] * D[1] - C[1] * D[0])) / ((A[0] - B[0]) * (C[1] - D[1]) -
                                          (A[1] - B[1]) * (C[0] - D[0]))
    Py = ((A[0] * B[1] - A[1] * B[0]) * (C[1] - D[1]) - (A[1] - B[1]) *
          (C[0] * D[1] - C[1] * D[0])) / ((A[0] - B[0]) * (C[1] - D[1]) -
                                          (A[1] - B[1]) * (C[0] - D[0]))

    #print Px
    #print Py

    A = [Px, Py, zmin]
    B = [Px, Py, zmax]

    if (verbose): print "A =", A
    if (verbose): print "B =", B

    points_AB = vtk.vtkPoints()
    points_AB.InsertNextPoint(A)
    points_AB.InsertNextPoint(B)

    cells_AB = vtk.vtkCellArray()
    cell_AB = vtk.vtkVertex()
    cell_AB.GetPointIds().SetId(0, 0)
    cells_AB.InsertNextCell(cell_AB)
    cell_AB.GetPointIds().SetId(0, 1)
    cells_AB.InsertNextCell(cell_AB)

    AB_ugrid = vtk.vtkUnstructuredGrid()
    AB_ugrid.SetPoints(points_AB)
    AB_ugrid.SetCells(vtk.VTK_VERTEX, cells_AB)

    return points_AB
示例#8
0
    def _add_ugrid_nodes_to_grid(self, name, diff_node_ids, nodes):
        """
        based on:
          _add_nastran_nodes_to_grid
        """
        nnodes = nodes.shape[0]
        assert nnodes > 0, nnodes
        # if nnodes == 0:
            # return
        nnodes = len(diff_node_ids)
        points = vtk.vtkPoints()
        points.SetNumberOfPoints(nnodes)

        for nid in diff_node_ids:
            node = nodes[nid, :]
            print('nid=%s node=%s' % (nid, node))
            points.InsertPoint(nid, *node)

            if 1:
                elem = vtk.vtkVertex()
                elem.GetPointIds().SetId(0, nid)
            else:
                elem = vtk.vtkSphere()
                sphere_size = self._get_sphere_size(dim_max)
                elem.SetRadius(sphere_size)
                elem.SetCenter(points.GetPoint(nid))

            self.alt_grids[name].InsertNextCell(elem.GetCellType(), elem.GetPointIds())
        self.alt_grids[name].SetPoints(points)
示例#9
0
    def _add_ugrid_nodes_to_grid(self, name, diff_node_ids, nodes):
        """
        based on:
          _add_nastran_nodes_to_grid
        """
        nnodes = nodes.shape[0]
        assert nnodes > 0, nnodes
        # if nnodes == 0:
        # return
        nnodes = len(diff_node_ids)
        points = vtk.vtkPoints()
        points.SetNumberOfPoints(nnodes)

        for nid in diff_node_ids:
            node = nodes[nid, :]
            self.log.info('nid=%s node=%s' % (nid, node))
            points.InsertPoint(nid, *node)

            #if 1:
            elem = vtk.vtkVertex()
            elem.GetPointIds().SetId(0, nid)
            #else:
            #elem = vtk.vtkSphere()
            #sphere_size = self._get_sphere_size(dim_max)
            #elem.SetRadius(sphere_size)
            #elem.SetCenter(points.GetPoint(nid))

            self.alt_grids[name].InsertNextCell(elem.GetCellType(),
                                                elem.GetPointIds())
        self.alt_grids[name].SetPoints(points)
示例#10
0
def createPolyData(pts, sdata, vdata):

    points = vtk.vtkPoints()

    vertices = vtk.vtkCellArray()

    scalars = vtk.vtkFloatArray()
    scalars.SetNumberOfComponents(1)
    scalars.SetName('myscalars')

    vectors = vtk.vtkFloatArray()
    vectors.SetNumberOfComponents(3)
    vectors.SetName('myvectors')

    for no, p in enumerate(pts):
        points.InsertNextPoint(p[0], p[1], p[2])
        vertex = vtk.vtkVertex()
        vertex.GetPointIds().SetId(0, no)
        vertices.InsertNextCell(vertex)
        scalars.InsertNextValue(sdata[no])
        vectors.InsertNextTuple3(vdata[no][0], vdata[no][1], vdata[no][2])

    #grid  = vtk.vtkUnstructuredGrid()
    grid = vtk.vtkPolyData()
    grid.SetPoints(points)
    #grid.SetCells(vtk.vtkVertex().GetCellType(), vertices) # ugrid
    grid.SetVerts(vertices)  # polydata
    grid.GetPointData().AddArray(scalars)
    grid.GetPointData().AddArray(vectors)

    return grid
示例#11
0
def nice_sphere(radius, subdivisions, center=(0, 0, 0)):
    platonic_solid = vtk.vtkPlatonicSolidSource()
    platonic_solid.SetSolidTypeToIcosahedron()
    platonic_solid = platonic_solid.GetOutput()
    platonic_solid.Update()

    points = []
    for i in range(platonic_solid.GetNumberOfCells()):
        cell = platonic_solid.GetCell(i)
        a = platonic_solid.GetPoint(cell.GetPointId(0))
        b = platonic_solid.GetPoint(cell.GetPointId(1))
        c = platonic_solid.GetPoint(cell.GetPointId(2))

        points += [a, b, c] \
               + subdivide(a, b, c, subdivisions)

    vtkPoints = vtk.vtkPoints()
    for point in points:
        vtkPoints.InsertNextPoint(center[0] + point[0] * radius,
                                  center[1] + point[1] * radius,
                                  center[2] + point[2] * radius)
    poly = vtk.vtkPolyData()
    poly.SetPoints(vtkPoints)
    cells = vtk.vtkCellArray()
    for i in range(len(points)):
        vertex = vtk.vtkVertex()
        vertex.GetPointIds().SetId(0, i)
        cells.InsertNextCell(vertex)
    poly.SetVerts(cells)
    return poly
示例#12
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()
示例#13
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()
示例#14
0
def geom_viz(geomData, filename='sample.vtp'):
    """
    DESCRIPTION
    -----------
    geom_viz(geomData, filename='geom.vtp')
    Generate a simple point centered vtp file to visualize grain ID.
    PARAMETERS
    ----------
    geomData: numpy.array
    Grain ID populated in a numpy array representing the extruded
    microstructure.
    filename: str
    Output VTP file name.
    RETURNS
    -------
    NOTES
    ----
    """
    polydata = vtk.vtkPolyData()
    points = vtk.vtkPoints()
    vertices = vtk.vtkCellArray()

    gids = vtk.vtkFloatArray()
    gids.SetNumberOfComponents(1)
    gids.SetName("GrainID")

    # iterating through CPFFT data
    cnt = 0
    x, y, z = geomData.shape
    for i in range(x):
        for j in range(y):
            for k in range(z):
                # set position
                points.InsertNextPoint(i, j, k)
                vertex = vtk.vtkVertex()
                vertex.GetPointIds().SetId(0, cnt)
                cnt += 1
                vertices.InsertNextCell(vertex)
                # set Grain ID
                gids.InsertNextTuple1(geomData[i, j, k])
    # finish the vtp object
    polydata.SetPoints(points)
    polydata.SetVerts(vertices)
    polydata.GetPointData().SetScalars(gids)
    polydata.Modified()

    if vtk.VTK_MAJOR_VERSION <= 5:
        polydata.Update()

    writer = vtk.vtkXMLPolyDataWriter()
    writer.SetFileName(filename)

    if vtk.VTK_MAJOR_VERSION <= 5:
        writer.SetInput(polydata)
    else:
        writer.SetInputData(polydata)

    writer.Write()
def computeABPointsFromTTTSectors(
        ugrid_sectors,
        verbose=1):

    myVTK.myPrint(verbose, "*** computeABPointsFromTTTSectors ***")

    n_points = ugrid_sectors.GetNumberOfPoints()
    n_cells = ugrid_sectors.GetNumberOfCells()

    n_csects = 12
    n_rsects = 3
    n_slices = n_points / (n_rsects+1) / (n_csects+1)
    myVTK.myPrint(verbose-1, "n_slices =", n_slices)

    zmin = ugrid_sectors.GetPoint(0)[2]
    zmax = ugrid_sectors.GetPoint(ugrid_sectors.GetNumberOfPoints()-1)[2]

    dist_btw_slices = abs(zmin-zmax)/(n_slices-1)
    myVTK.myPrint(verbose-1, "dist_btw_slices =", dist_btw_slices)

    A = ugrid_sectors.GetPoints().GetPoint(0)
    B = ugrid_sectors.GetPoints().GetPoint(6)
    C = ugrid_sectors.GetPoints().GetPoint(3)
    D = ugrid_sectors.GetPoints().GetPoint(9)

    #print A
    #print B
    #print C
    #print D

    Px = ((A[0]*B[1]-A[1]*B[0])*(C[0]-D[0])-(A[0]-B[0])*(C[0]*D[1]-C[1]*D[0]))/((A[0]-B[0])*(C[1]-D[1])-(A[1]-B[1])*(C[0]-D[0]))
    Py = ((A[0]*B[1]-A[1]*B[0])*(C[1]-D[1])-(A[1]-B[1])*(C[0]*D[1]-C[1]*D[0]))/((A[0]-B[0])*(C[1]-D[1])-(A[1]-B[1])*(C[0]-D[0]))

    #print Px
    #print Py

    A = [Px, Py, zmin]
    B = [Px, Py, zmax]

    myVTK.myPrint(verbose-1, "A =", A)
    myVTK.myPrint(verbose-1, "B =", B)

    points_AB = vtk.vtkPoints()
    points_AB.InsertNextPoint(A)
    points_AB.InsertNextPoint(B)

    cells_AB = vtk.vtkCellArray()
    cell_AB  = vtk.vtkVertex()
    cell_AB.GetPointIds().SetId(0, 0)
    cells_AB.InsertNextCell(cell_AB)
    cell_AB.GetPointIds().SetId(0, 1)
    cells_AB.InsertNextCell(cell_AB)

    AB_ugrid = vtk.vtkUnstructuredGrid()
    AB_ugrid.SetPoints(points_AB)
    AB_ugrid.SetCells(vtk.VTK_VERTEX, cells_AB)

    return points_AB
示例#16
0
def geom_viz(geomData, filename='sample.vtp'):
    """
    DESCRIPTION
    -----------
    geom_viz(geomData, filename='geom.vtp')
    Generate a simple point centered vtp file to visualize grain ID.
    PARAMETERS
    ----------
    geomData: numpy.array
    Grain ID populated in a numpy array representing the extruded
    microstructure.
    filename: str
    Output VTP file name.
    RETURNS
    -------
    NOTES
    ----
    """
    polydata = vtk.vtkPolyData()
    points = vtk.vtkPoints()
    vertices = vtk.vtkCellArray()

    gids = vtk.vtkFloatArray()
    gids.SetNumberOfComponents(1)
    gids.SetName("GrainID")

    # iterating through CPFFT data
    cnt = 0
    x, y, z = geomData.shape
    for i in range(x):
        for j in range(y):
            for k in range(z):
                # set position
                points.InsertNextPoint(i, j, k)
                vertex = vtk.vtkVertex()
                vertex.GetPointIds().SetId(0, cnt)
                cnt += 1
                vertices.InsertNextCell(vertex)
                # set Grain ID
                gids.InsertNextTuple1(geomData[i, j, k])
    # finish the vtp object
    polydata.SetPoints(points)
    polydata.SetVerts(vertices)
    polydata.GetPointData().SetScalars(gids)
    polydata.Modified()

    if vtk.VTK_MAJOR_VERSION <= 5:
        polydata.Update()

    writer = vtk.vtkXMLPolyDataWriter()
    writer.SetFileName(filename)

    if vtk.VTK_MAJOR_VERSION <= 5:
        writer.SetInput(polydata)
    else:
        writer.SetInputData(polydata)

    writer.Write()
def CreateVertexFromPoint(ugrid):

    vertices = vtk.vtkCellArray()
    for p in range(ugrid.GetNumberOfPoints()):
        vert = vtk.vtkVertex()
        vert.GetPointIds().SetId(0, p)
        vertices.InsertNextCell(vert)

    ugrid.SetCells(1, vertices)
示例#18
0
    def _add_user_points(self, user_points, name, color,
                         csv_points_filename='', point_size=4):
        """
        Helper method for adding csv nodes to the gui

        Parameters
        ----------
        user_points : (n, 3) float ndarray
            the points to add
        name : str
            name of the geometry actor
        color : List[float, float, float]
            RGB values; [0. to 1.]
        point_size : int; default=4
            the nominal point size
        """
        if name in self.gui.geometry_actors:
            msg = 'Name: %s is already in geometry_actors\nChoose a different name.' % name
            raise ValueError(msg)
        if len(name) == 0:
            msg = 'Invalid Name: name=%r' % name
            raise ValueError(msg)

        # create grid
        self.gui.create_alternate_vtk_grid(name, color=color, line_width=5, opacity=1.0,
                                           point_size=point_size, representation='point')

        npoints = user_points.shape[0]
        if npoints == 0:
            raise RuntimeError('npoints=0 in %r' % csv_points_filename)
        if len(user_points.shape) == 1:
            user_points = user_points.reshape(1, npoints)

        # allocate grid
        self.gui.alt_grids[name].Allocate(npoints, 1000)

        # set points
        points = vtk.vtkPoints()
        points.SetNumberOfPoints(npoints)

        for i, point in enumerate(user_points):
            points.InsertPoint(i, *point)
            elem = vtk.vtkVertex()
            elem.GetPointIds().SetId(0, i)
            self.gui.alt_grids[name].InsertNextCell(elem.GetCellType(), elem.GetPointIds())
        self.gui.alt_grids[name].SetPoints(points)

        # create actor/mapper
        self._add_alt_geometry(self.gui.alt_grids[name], name)

        # set representation to points
        self.gui.geometry_properties[name].representation = 'point'
        actor = self.gui.geometry_actors[name]
        prop = actor.GetProperty()
        prop.SetRepresentationToPoints()
        prop.SetPointSize(point_size)
示例#19
0
    def single_pick(self, caller):
        # caller.RemoveObservers('RotateEvent')
        clickcoords = caller.GetEventPosition()
        retval = self.picker.Pick(clickcoords[0], clickcoords[1], 0, self.ren)

        if 0:
            node_id = self.picker.GetPointId()
            points = self.grid.GetPoints()
            vertices = vtk.vtkCellArray()
            vertices.InsertNextCell(1, node_id)

            point = vtk.vtkPolyData()
            point.SetPoints(points)
            point.SetVerts(vertices)

            mapper = vtk.vtkPolyDataMapper()
            mapper.SetInputData(point)

            actor = vtk.vtkActor()
            actor.SetMapper(mapper)
            actor.GetProperty().SetPointSize(6)

            self.actors.append(actor)
            self.ren.AddActor(actor)
            self.iren.Render()

        if retval:
            node_id = self.picker.GetPointId()
            self.node_ids.append(node_id)

            points = self.grid.GetPoints()
            vertex = vtk.vtkVertex()
            vertex.GetPointIds().SetId(0, node_id)

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

            mapper = vtk.vtkDataSetMapper()
            mapper.SetInputData(grid)

            colors = vtk.vtkNamedColors()
            actor = vtk.vtkActor()
            actor.SetMapper(mapper)
            actor.GetProperty().SetColor(colors.GetColor3d("Tomato"))
            # actor.GetProperty().SetOpacity(.5)
            actor.GetProperty().SetPointSize(10)

            self.actors.append(actor)
            self.ren.AddActor(actor)
        else:
            self.clear_actors()

        caller.Render()
def pcRender(pc,
             color_pt=(0, 0, 1),
             pointSize=0.5,
             color_bg=(0.2, 0.2, 0.2),
             size_win=(640, 640)):
    polydata = vtk.vtkPolyData()
    points = vtk.vtkPoints()
    vertices = vtk.vtkCellArray()
    #    vtkDepth = vtk.vtkDoubleArray()

    for point in pc:
        pointId = points.InsertNextPoint(point[1], point[2], point[0])
        vertex = vtk.vtkVertex()
        vertex.GetPointIds().SetId(0, 0)
        #        vtkDepth.InsertNextValue(point[2])
        vertices.InsertNextCell(1)
        vertices.InsertCellPoint(pointId)

    vertices.Modified()
    points.Modified()
    #    vtkDepth.Modified()

    polydata.SetPoints(points)
    polydata.SetVerts(vertices)
    #    polydata.GetPointData().SetScalars(vtkDepth)

    # Setup actor and mapper
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(polydata)
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetPointSize(pointSize)
    actor.GetProperty().SetColor(color_pt)

    # Setup render window, renderer, and interactor
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetSize(size_win)
    renderWindow.SetWindowName("Point cloud")
    renderWindow.SetPosition(200, 0)
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()

    renderWindowInteractor.SetRenderWindow(renderWindow)
    renderer.AddActor(actor)
    renderer.SetBackground(color_bg)

    renderWindow.Render()
    m_pInteractorStyle = vtk.vtkInteractorStyleTrackballCamera()
    renderWindowInteractor.SetInteractorStyle(m_pInteractorStyle)
    renderWindow.Render()
    renderWindowInteractor.Initialize()
    renderWindowInteractor.Start()
示例#21
0
def create_unstructured_point_grid(points, npoints):
    """creates a point grid"""
    ugrid = vtk.vtkUnstructuredGrid()
    ugrid.SetPoints(points)

    cell_type_vertex = vtk.vtkVertex().GetCellType()
    etypes = [cell_type_vertex]
    elements = [np.arange(npoints, dtype='int32').reshape(npoints, 1)]
    create_vtk_cells_of_constant_element_types(ugrid, elements, etypes)
    ugrid.SetPoints(points)
    ugrid.Modified()
    return ugrid
示例#22
0
 def convert_points_to_polydata(self, points):
     polydata = vtkPolyData()
     points_array = vtkPoints()
     vertex_array = vtkCellArray()
     for p in points:
         points_array.InsertNextPoint(p[0], p[1], p[2])
     for i in range(self.nv):
         v = vtkVertex()
         v.GetPointIds().SetId(0, i)
         vertex_array.InsertNextCell(v)
     polydata.SetPoints(points_array)
     polydata.SetVerts(vertex_array)
     return polydata
示例#23
0
文件: plot.py 项目: SinghN/nutils
  def vertices( self, 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:
      if pts.shape[1] < 3:
        pts = numpy.concatenate([pts,numpy.zeros(shape=(pts.shape[0],3-pts.shape[1]))],axis=1)

      for point in pts:
        vtkPoints .SetPoint( cnt, point )
        cellpoints = vtk.vtkVertex().GetPointIds()
        cellpoints.SetId( 0, cnt )
        self.vtkMesh.InsertNextCell( vtk.vtkVertex().GetCellType(), cellpoints )
        cnt +=1

    self.vtkMesh.SetPoints( vtkPoints )
示例#24
0
    def pick_depth_ids(self, xmin, ymin, xmax, ymax):
        """
        Does an area pick of all the ids inside the box, even the ones
        behind the front elements
        """
        retval = self.area_picker.AreaPick(xmin, ymin, xmax, ymax, self.ren)
        # self.area_picker.Pick()
        frustum = self.area_picker.GetFrustum()  # vtkPlanes

        ids = vtk.vtkIdFilter()
        ids.SetInputData(self.grid)
        # ids.CellIdsOn()
        ids.PointIdsOn()
        ids.SetIdsArrayName("Ids")

        # get the cells/points inside the frustum
        selected_frustum = vtk.vtkExtractSelectedFrustum()
        selected_frustum.SetFieldType(True)
        selected_frustum.SetFrustum(frustum)
        selected_frustum.SetInputConnection(ids.GetOutputPort())
        selected_frustum.Update()
        picked_grid = selected_frustum.GetOutput()
        if picked_grid:
            point_ids = None
            points = picked_grid.GetPointData()
            if points is not None:
                ids = points.GetArray('Ids')
                if ids is not None:
                    point_ids = vtk_to_numpy(ids)
                    if len(point_ids) != 0:
                        self.node_ids.extend(point_ids)
                        points = self.grid.GetPoints()
                        _grid = vtk.vtkUnstructuredGrid()
                        _grid.SetPoints(points)
                        for node_id in point_ids:
                            vertex = vtk.vtkVertex()
                            vertex.GetPointIds().SetId(0, node_id)
                            _grid.InsertNextCell(vertex.GetCellType(),
                                                 vertex.GetPointIds())
                        mapper = vtk.vtkDataSetMapper()
                        mapper.SetInputData(_grid)
                        colors = vtk.vtkNamedColors()
                        actor = vtk.vtkActor()
                        actor.SetMapper(mapper)
                        actor.GetProperty().SetColor(
                            colors.GetColor3d("Tomato"))
                        # actor.GetProperty().SetOpacity(.5)
                        actor.GetProperty().SetPointSize(10)
                        self.actors.append(actor)
                        self.ren.AddActor(actor)
        self.iren.Render()
示例#25
0
def write_vtp(filename, data):

    import vtk
    from vtk.util import numpy_support

    print ' --> Writing ({})'.format(filename)

    writer = vtk.vtkXMLPolyDataWriter()
    writer.SetFileName(filename)

    polydata = vtk.vtkPolyData()

    points = vtk.vtkPoints()
    cells = vtk.vtkCellArray()
    labels = []

    # --------------------------------------------------------------------------
    pid = 0
    kid = 0
    for key in data.keys():

        pdata = data[key]
        #print key, '-->', kid, len(pdata)

        for p in pdata:
            points.InsertNextPoint(p[0], p[1], p[2])
            pid += 1

            cell = vtk.vtkVertex()
            cell.GetPointIds().SetId(0, pid - 1)
            cells.InsertNextCell(cell)

            labels.append(kid)
        kid += 1

    polydata.SetPoints(points)
    polydata.SetPolys(cells)

    VTK_data = numpy_support.numpy_to_vtk(num_array=np.array(labels))
    VTK_data.SetName('plabels')
    polydata.GetPointData().AddArray(VTK_data)

    VTK_data2 = numpy_support.numpy_to_vtk(num_array=np.array(labels))
    VTK_data2.SetName('clabels')
    polydata.GetCellData().AddArray(VTK_data2)

    writer.SetInputData(polydata)
    writer.Write()
示例#26
0
def MakeVertex():
    # A vertex is a cell that represents a 3D point
    numberOfVertices = 1

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

    vertex = vtk.vtkVertex()
    for i in range(0, numberOfVertices):
        vertex.GetPointIds().SetId(i, i)

    ug = vtk.vtkUnstructuredGrid()
    ug.SetPoints(points)
    ug.InsertNextCell(vertex.GetCellType(), vertex.GetPointIds())

    return ug
示例#27
0
def set_mass_grid(alt_grids: Dict[str, vtk.vtkUnstructuredGrid],
                  model: BDF, nodes, node_ids) -> None:
    #nmass = len(model.masses)
    #eid_array = np.full(nmass, -1, dtype='int32')
    #mass_array = np.full(nmass, np.nan, dtype='float32')
    #xyz_array = np.full((nmass, 3), np.nan, dtype='float32')
    i = 0
    eids = []
    mass = []
    xyz = []
    mass_grid = vtk.vtkUnstructuredGrid()
    for eid, element in model.masses.items():
        if element.type == 'CONM2':
            nid = element.nid
            inid = np.searchsorted(node_ids, nid)
            xyz_nid = nodes[inid, :]
            centroid = element.offset(xyz_nid)

            #eid_array[i] = eid
            #mass_array[i] = element.mass
            #xyz_array[i, :] = centroid
            eids.append(eid)
            mass.append(element.mass)
            xyz.append(centroid)
            vtk_elem = vtk.vtkVertex()
            vtk_elem.GetPointIds().SetId(0, inid)
            mass_grid.InsertNextCell(vtk_elem.GetCellType(), vtk_elem.GetPointIds())
        else:
            model.log.debug(f'skipping:\n{str(elem)}')
            continue
        i += 1
    eid_array = np.array(eids, dtype='int32')[:i]
    mass_array = np.array(mass, dtype='float32')[:i]
    xyz_array = np.array(xyz, dtype='float32')[:i, :]

    vtk_points = numpy_to_vtk_points(xyz_array, points=None, dtype='<f', deep=1)
    mass_grid.SetPoints(vtk_points)

    # add vectors
    vtk_eids = numpy_to_vtk(eid_array, deep=0, array_type=None)
    vtk_mass = numpy_to_vtk(mass_array, deep=0, array_type=None)
    vtk_eids.SetName('Mass ID')
    vtk_mass.SetName('Mass')
    #point_data = mass_grid.GetPointData()
    cell_data = mass_grid.GetCellData()
    cell_data.AddArray(vtk_mass)
    alt_grids['mass'] = mass_grid
示例#28
0
def points_to_poly_data(poly_data, points, cells):

    poly_data = poly_data['poly_data']

    point_list = vtk.vtkPoints()

    for i in range(len(points)):
        point_list.InsertNextPoint(points[i][0], points[i][1], points[i][2])

    cell_array = vtk.vtkCellArray()

    for i in range(len(cells)):
        pts = cells[i]

        if len(pts) == 1:
            cell = vtk.vtkVertex()
            ids = cell.GetPointIds()
            ids.SetId(0, pts[0])
        if len(pts) == 2:
            cell = vtk.vtkLine()
            ids = cell.GetPointIds()
            ids.SetId(0, pts[0])
            ids.SetId(1, pts[1])
        elif len(pts) == 3:
            cell = vtk.vtkTriangle()
            ids = cell.GetPointIds()
            ids.SetId(0, pts[0])
            ids.SetId(1, pts[1])
            ids.SetId(2, pts[2])
        elif len(pts) == 4:
            cell = vtk.vtkQuad()
            ids = cell.GetPointIds()
            ids.SetId(0, pts[0])
            ids.SetId(1, pts[1])
            ids.SetId(2, pts[2])
            ids.SetId(3, pts[3])
        else:
            continue

        cell_array.InsertNextCell(cell)

    poly_data.Reset()

    poly_data.SetPoints(point_list)
    poly_data.SetVerts(cell_array)
    poly_data.SetLines(cell_array)
    poly_data.SetPolys(cell_array)
def extractEdges(pdata):

    interfaces = vtk.vtkPolyData()
    dim = getDim(pdata)

    if dim == -1:
        raise ValueError(
            "Error in interfaces class, please clean your polydata.")
        exit()
    if dim == 0:
        raise ValueError(
            "Error dimension in interfaces class, please verify your polydata."
        )
        exit()

    if dim == 1:
        cells = vtk.vtkCellArray()

        for i in np.arange(pdata.GetNumberOfPoints()):
            vertex = vtk.vtkVertex()
            vertex.GetPointIds().SetId(0, i)
            cells.InsertNextCell(vertex)

        interfaces.SetPoints(pdata.GetPoints())
        interfaces.SetVerts(cells)

    elif dim == 2:
        extractEdges = vtk.vtkExtractEdges()
        extractEdges.SetInputData(pdata)
        extractEdges.Update()
        interfaces.DeepCopy(extractEdges.GetOutput())
    else:
        triangleFilter = vtk.vtkTriangleFilter()
        triangleFilter.SetInputData(pdata)
        triangleFilter.Update()
        interfaces.DeepCopy(triangleFilter.GetOutput())

    ## test

    interfaces = clean(interfaces)

    # if pdata.GetNumberOfPoints () != interfaces.GetNumberOfPoints ():
    #     raise ValueError ("Error : interfaces and pdata have not the same number of points.")
    #     exit ()
    #
    return interfaces
示例#30
0
def addVertices(ugrid, verbose=0):

    myVTK.myPrint(verbose, "*** addVertices ***")

    cell = vtk.vtkVertex()
    cell_array = vtk.vtkCellArray()

    n_points = ugrid.GetPoints().GetNumberOfPoints()
    for k_point in xrange(n_points):
        cell.GetPointIds().SetId(0, k_point)
        cell_array.InsertNextCell(cell)

    ugrid.SetCells(vtk.VTK_VERTEX, cell_array)

    n_arrays = ugrid.GetPointData().GetNumberOfArrays()
    for k_array in xrange(n_arrays):
        ugrid.GetCellData().AddArray(ugrid.GetPointData().GetArray(k_array))
示例#31
0
def addVertices(
        ugrid,
        verbose=1):

    myVTK.myPrint(verbose, "*** addVertices ***")

    cell = vtk.vtkVertex()
    cell_array = vtk.vtkCellArray()

    n_points = ugrid.GetPoints().GetNumberOfPoints()
    for k_point in xrange(n_points):
        cell.GetPointIds().SetId(0, k_point)
        cell_array.InsertNextCell(cell)

    ugrid.SetCells(vtk.VTK_VERTEX, cell_array)

    n_arrays = ugrid.GetPointData().GetNumberOfArrays()
    for k_array in xrange(n_arrays):
        ugrid.GetCellData().AddArray(ugrid.GetPointData().GetArray(k_array))
示例#32
0
    def Update(self):
        with open(self.FileName) as file:
            if 'OFF' != file.readline().strip():
                raise ('Not a valid OFF header')

            n_verts, n_faces, n_dontknow = tuple(
                [int(s) for s in file.readline().strip().split(' ')])

            surf = vtk.vtkPolyData()
            points = vtk.vtkPoints()
            cells = vtk.vtkCellArray()

            for i_vert in range(n_verts):
                p = [float(s) for s in file.readline().strip().split(' ')]
                points.InsertNextPoint(p[0], p[1], p[2])

            for i_face in range(n_faces):

                t = [int(s) for s in file.readline().strip().split(' ')]

                if (t[0] == 1):
                    vertex = vtk.vtkVertex()
                    vertex.GetPointIds().SetId(0, t[1])
                    cells.InsertNextCell(line)
                elif (t[0] == 2):
                    line = vtk.vtkLine()
                    line.GetPointIds().SetId(0, t[1])
                    line.GetPointIds().SetId(1, t[2])
                    cells.InsertNextCell(line)
                elif (t[0] == 3):
                    triangle = vtk.vtkTriangle()
                    triangle.GetPointIds().SetId(0, t[1])
                    triangle.GetPointIds().SetId(1, t[2])
                    triangle.GetPointIds().SetId(2, t[3])
                    cells.InsertNextCell(triangle)

            surf.SetPoints(points)
            surf.SetPolys(cells)

            self.Output = surf
示例#33
0
def CreateSpiral(sphereRadius=4,
                 numberOfSpiralSamples=64,
                 numberOfSpiralTurns=4):

    sphere = vtk.vtkPolyData()
    sphere_points = vtk.vtkPoints()
    lines = vtk.vtkCellArray()
    vertices = vtk.vtkCellArray()

    c = 2.0 * float(numberOfSpiralTurns)
    prevPid = -1

    for i in range(numberOfSpiralSamples):
        p = [0, 0, 0]
        #angle = i * 180.0/numberOfSpiralSamples * math.pi/180.0
        angle = (i * math.pi) / numberOfSpiralSamples
        p[0] = sphereRadius * math.sin(angle) * math.cos(c * angle)
        p[1] = sphereRadius * math.sin(angle) * math.sin(c * angle)
        p[2] = sphereRadius * math.cos(angle)

        pid = sphere_points.InsertNextPoint(p)

        if (prevPid != -1):
            line = vtk.vtkLine()
            line.GetPointIds().SetId(0, prevPid)
            line.GetPointIds().SetId(1, pid)
            lines.InsertNextCell(line)

        prevPid = pid

        vertex = vtk.vtkVertex()
        vertex.GetPointIds().SetId(0, pid)

        vertices.InsertNextCell(vertex)

    sphere.SetVerts(vertices)
    sphere.SetLines(lines)
    sphere.SetPoints(sphere_points)

    return sphere
示例#34
0
 def __createPolyData(self):
     print 'creating vtkPolyData...'
     self.points = vtk.vtkPoints()
     self.polydata  = vtk.vtkPolyData()
     self.vertices = vtk.vtkCellArray()
     self.lines = vtk.vtkCellArray()
     
     self.polydata.SetPoints(self.points)
     self.polydata.SetVerts(self.vertices)
     self.polydata.SetLines(self.lines)
     
     # points
     self.scalars = vtk.vtkFloatArray()
     self.scalars.SetNumberOfComponents(1)
     self.polydata.GetPointData().SetScalars(self.scalars)
  
     nmap={}
     i=0
     for nod in self.truss.nodes:
         nmap[nod.nb]=i
         self.points.InsertPoint(i, nod.x, nod.y, 0.0)
         self.scalars.InsertNextValue(nod.nb)
         # node cells
         vertex = vtk.vtkVertex()
         vertex.GetPointIds().SetId(0, i)
         self.vertices.InsertNextCell(vertex)
         i+=1
     self.points.Modified()
     self.vertices.Modified()
     
     for bar in self.truss.bars:
         line = vtk.vtkLine()
         ids = line.GetPointIds()
         ids.SetNumberOfIds(2)
         for j in range(len(bar.nodes)):
             ids.SetId(j, nmap[bar.nodes[j].nb])
         self.lines.InsertNextCell(line) 
     self.lines.Modified()
示例#35
0
 def display(self, step, lamda):
     
     self.steplabel.setText("step # %d" % step)
     self.loadlabel.setText("lambda = %2.8f" % lamda)
     
     self.points.Reset()
     self.vertices.Reset()
     self.lines.Reset()
     self.scalars.Reset()
     
     # points
     nmap={}
     i=0
     for nod in self.truss.nodes:
         nmap[nod.nb]=i
         self.points.InsertPoint(i, nod.x, nod.y, 0.0)
         self.scalars.InsertNextValue(nod.nb)
         # node cells
         vertex = vtk.vtkVertex()
         vertex.GetPointIds().SetId(0, i)
         self.vertices.InsertNextCell(vertex)
         i+=1
     self.points.Modified()
     self.vertices.Modified()
     
     for bar in self.truss.bars:
         line = vtk.vtkLine()
         ids = line.GetPointIds()
         ids.SetNumberOfIds(2)
         for j in range(len(bar.nodes)):
             ids.SetId(j, nmap[bar.nodes[j].nb])
         self.lines.InsertNextCell(line) 
     self.lines.Modified()
     
     self.polydata.Modified()
     
     self.render()
示例#36
0
def main():
    colors = vtk.vtkNamedColors()

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

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

    vertices = vtk.vtkCellArray()
    vertices.InsertNextCell(vertex)

    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)
    polydata.SetVerts(vertices)

    # Setup actor and mapper
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(polydata)
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetPointSize(30)
    actor.GetProperty().SetColor(colors.GetColor3d('PeachPuff'))

    # Setup render window, renderer, and interactor
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetWindowName('Vertex')
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)
    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d('DarkGreen'))

    renderWindow.Render()
    renderWindowInteractor.Start()
示例#37
0
def readDynaMesh(lsdyna_mesh_filename,
                 cell_type='hexahedron',
                 verbose=0):

    myVTK.myPrint(verbose, "*** readDynaMesh: "+lsdyna_mesh_filename+" ***")

    points = vtk.vtkPoints()

    if (cell_type == 'vertex'):
        cell_vtk_type = vtk.VTK_VERTEX
        cell = vtk.vtkVertex()
        cell_array = vtk.vtkCellArray()
    elif (cell_type == 'hexahedron'):
        cell_vtk_type = vtk.VTK_HEXAHEDRON
        cell = vtk.vtkHexahedron()
        cell_array = vtk.vtkCellArray()
    else:
        print 'Wrong cell type. Aborting.'
        exit()

    myVTK.myPrint(verbose-1, "Reading Dyna mesh file...")

    mesh_file = open(lsdyna_mesh_filename, 'r')

    context = ''
    for line in mesh_file:
        if (line[-1:] == '\n'): line = line[:-1]
        #myVTK.myPrint(verbose-1, "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 (cell_type == 'vertex'):
                    cell.GetPointIds().SetId(0, points.GetNumberOfPoints()-1)
                    cell_array.InsertNextCell(cell)

        if (context == 'reading elems'):
            if line.startswith('*'):
                context = ''
            else:
                splitted_line = line.split(',')
                if (len(splitted_line) == 3): continue
                if (cell_type == 'hexahedron'):
                    for k_node in xrange(8):
                        cell.GetPointIds().SetId(k_node, int(splitted_line[2+k_node])-1)
                cell_array.InsertNextCell(cell)

        if line.startswith('*NODE'): context = 'reading nodes'
        if line.startswith('*ELEMENT_SOLID'): context = 'reading elems'

    mesh_file.close()

    myVTK.myPrint(verbose-1, "Creating VTK mesh...")

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

    return ugrid
示例#38
0
    def load_bedge_geometry(self, bedge_filename, name='main', plot=True):
        #skip_reading = self.remove_old_openfoam_geometry(openfoam_filename)
        #if skip_reading:
        #    return

        self.gui.modelType = 'bedge'

        model = read_bedge(bedge_filename)
        self.gui.log.info('bedge_filename = %s' % bedge_filename)
        nnodes = model.nodes.shape[0]
        nbars = model.bars.shape[0]
        nelements = nbars

        nodes = model.nodes
        self.gui.nelements = nelements
        self.gui.nnodes = nnodes

        self.gui.log.debug("nNodes = %s" % self.gui.nnodes)
        self.gui.log.debug("nElements = %s" % self.gui.nelements)
        assert nelements > 0, nelements

        black = (0., 0., 0.)
        self.gui.create_alternate_vtk_grid('nodes',
                                           color=black,
                                           line_width=5,
                                           opacity=1.,
                                           point_size=3,
                                           representation='point')
        alt_grid = self.gui.alt_grids['nodes']
        alt_grid.Allocate(nnodes, 1000)

        grid = self.gui.grid
        grid.Allocate(self.gui.nelements, 1000)

        points = numpy_to_vtk_points(nodes)

        mmax = np.amax(nodes, axis=0)
        mmin = np.amin(nodes, axis=0)
        unused_dim_max = (mmax - mmin).max()
        self.gui.log.info('max = %s' % mmax)
        self.gui.log.info('min = %s' % mmin)
        #print('dim_max =', dim_max)
        #self.update_axes_length(dim_max)

        etype = 1  # vtk.vtkVertex().GetCellType()
        #elements = np.arange(0, len(nodes), dtype='int32')
        #assert len(elements) == len(nodes)
        #create_vtk_cells_of_constant_element_type(alt_grid, elements, etype)
        for inode, unused_node in enumerate(nodes):
            elem = vtk.vtkVertex()
            elem.GetPointIds().SetId(0, inode)
            alt_grid.InsertNextCell(etype, elem.GetPointIds())

        bars = model.bars

        etype = 3  # vtkLine().GetCellType()
        create_vtk_cells_of_constant_element_type(grid, bars, etype)

        self.gui.nelements = nelements
        alt_grid.SetPoints(points)
        grid.SetPoints(points)
        grid.Modified()
        if hasattr(grid, 'Update'):  # pragma: no cover
            grid.Update()
        #print("updated grid")

        # loadBedgeResults - regions/loads
        #self.TurnTextOn()
        self.gui.scalarBar.VisibilityOn()
        self.gui.scalarBar.Modified()

        self.gui.isubcase_name_map = {1: ['AFLR BEDGE', '']}
        cases = OrderedDict()
        ID = 1

        self.gui._add_alt_actors(self.gui.alt_grids)
        form, cases = self._fill_bedge_case(bedge_filename, cases, ID, nnodes,
                                            nelements, model)
        if plot:
            self.gui._finish_results_io2(form, cases)
示例#39
0
    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()
示例#40
0
import vtk, os, sys
from vtk.test import Testing

ss = vtk.vtkSphereSource() #make mesh to test with

af = vtk.vtkElevationFilter() #add some attributes
af.SetInputConnection(ss.GetOutputPort())

ef = vtk.vtkExtractEdges() #make lines to test
ef.SetInputConnection(af.GetOutputPort())

gf = vtk.vtkGlyph3D() #make verts to test
pts = vtk.vtkPoints()
pts.InsertNextPoint(0,0,0)
verts = vtk.vtkCellArray()
avert = vtk.vtkVertex()
avert.GetPointIds().SetId(0, 0)
verts.InsertNextCell(avert)
onevertglyph = vtk.vtkPolyData()
onevertglyph.SetPoints(pts)
onevertglyph.SetVerts(verts)
gf.SetSourceData(onevertglyph)
gf.SetInputConnection(af.GetOutputPort())

testwrites = ["points","lines","mesh"]
failed = False
for datasetString in testwrites:
  if datasetString == "points":
    toshow=gf
  elif datasetString == "lines":
    toshow = ef
示例#41
0
#!/usr/bin/env python

import vtk

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

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

vertices = vtk.vtkCellArray()
vertices.InsertNextCell(vertex)

polydata = vtk.vtkPolyData()
polydata.SetPoints(points)
polydata.SetVerts(vertices)


# Setup actor and mapper
mapper = vtk.vtkPolyDataMapper()
if vtk.VTK_MAJOR_VERSION <= 5:
    mapper.SetInputConnection(polydata.GetProducerPort())
else:
    mapper.SetInputData(polydata)

actor = vtk.vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetPointSize(10)

# Setup render window, renderer, and interactor
renderer = vtk.vtkRenderer()
示例#42
0
  Permute VTK node ordering into default node ordering
  """
    
  newNodes = nodes
  
  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, \
示例#43
0
    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)
示例#44
0
    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")
示例#45
0
    def load_bedge_geometry(self, bedge_filename, dirname, name='main', plot=True):
        #skip_reading = self.remove_old_openfoam_geometry(openfoam_filename)
        #if skip_reading:
        #    return

        self.modelType = 'bedge'

        model = read_bedge(bedge_filename)
        print('bedge_filename = %s' % bedge_filename)
        nnodes = model.nodes.shape[0]
        nbars = model.bars.shape[0]
        nelements = nbars

        nodes = model.nodes
        self.nElements = nelements
        self.nNodes = nnodes

        print("nNodes = %s" % self.nNodes)
        print("nElements = %s" % self.nElements)
        assert nelements > 0, nelements

        black = (0., 0., 0.)
        self.create_alternate_vtk_grid(
            'nodes', color=black, line_width=5, opacity=1., point_size=3,
            representation='point')
        self.alt_grids['nodes'].Allocate(nnodes, 1000)
        self.grid.Allocate(self.nElements, 1000)

        points = vtk.vtkPoints()
        points.SetNumberOfPoints(self.nNodes)

        mmax = np.amax(nodes, axis=0)
        mmin = np.amin(nodes, axis=0)
        dim_max = (mmax - mmin).max()
        self.log.info('max = %s' % mmax)
        self.log.info('min = %s' % mmin)
        #print('dim_max =', dim_max)
        #self.update_axes_length(dim_max)

        for inode, node in enumerate(nodes):
            points.InsertPoint(inode, node)

            elem = vtk.vtkVertex()
            elem.GetPointIds().SetId(0, inode)
            self.alt_grids['nodes'].InsertNextCell(elem.GetCellType(), elem.GetPointIds())

        bars = model.bars
        for eid, element in enumerate(bars):
            elem = vtk.vtkLine()
            n1, n2 = element
            try:
                elem.GetPointIds().SetId(0, n1)
                elem.GetPointIds().SetId(1, n2)
            except KeyError:
                print("nodeIDs =", element)
                print(str(element))
                continue
            self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())

        self.nElements = nelements
        self.alt_grids['nodes'].SetPoints(points)
        self.grid.SetPoints(points)
        self.grid.Modified()
        if hasattr(self.grid, 'Update'):
            self.grid.Update()
        #print("updated grid")

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

        self.iSubcaseNameMap = {1: ['AFLR BEDGE', '']}
        cases = {}
        ID = 1

        self._add_alt_actors(self.alt_grids)
        form, cases = self._fill_bedge_case(bedge_filename, cases, ID, nnodes, nelements, model)
        if plot:
            self._finish_results_io2(form, cases)
示例#46
0
    def serveVTKGeoJSON(self, datasetString):
        '''
        Deliver a geojson encoded serialized vtkpolydata file and render it
        over the canonical cpipe scene.
        '''

        if vtkOK == False:
            return """<html><head></head><body>VTK python bindings are not loadable, be sure VTK is installed on the server and its PATHS are set appropriately.</body><html>"""

        ss = vtk.vtkNetCDFCFReader() #get test data
        ss.SphericalCoordinatesOff()
        ss.SetOutputTypeToImage()
        datadir = cherrypy.request.app.config['/data']['tools.staticdir.dir']
        datadir = os.path.join(datadir, 'assets')
        datafile = os.path.join(datadir, 'clt.nc')
        ss.SetFileName(datafile)

        sf = vtk.vtkDataSetSurfaceFilter() #convert to polydata
        sf.SetInputConnection(ss.GetOutputPort())

        cf = vtk.vtkContourFilter() #add some attributes
        cf.SetInputConnection(sf.GetOutputPort())
        cf.SetInputArrayToProcess(0,0,0,"vtkDataObject::FIELD_ASSOCIATION_POINTS", "clt")
        cf.SetNumberOfContours(10)
        sf.Update()
        drange = sf.GetOutput().GetPointData().GetArray(0).GetRange()
        for x in range(0,10):
          cf.SetValue(x,x*0.1*(drange[1]-drange[0])+drange[0])
        cf.ComputeScalarsOn()

        ef = vtk.vtkExtractEdges() #make lines to test
        ef.SetInputConnection(sf.GetOutputPort())

        gf = vtk.vtkGlyph3D() #make verts to test
        pts = vtk.vtkPoints()
        pts.InsertNextPoint(0,0,0)
        verts = vtk.vtkCellArray()
        avert = vtk.vtkVertex()
        avert.GetPointIds().SetId(0, 0)
        verts.InsertNextCell(avert)
        onevertglyph = vtk.vtkPolyData()
        onevertglyph.SetPoints(pts)
        onevertglyph.SetVerts(verts)
        gf.SetSourceData(onevertglyph)
        gf.SetInputConnection(sf.GetOutputPort())

        if datasetString == "points":
            toshow = gf
        elif datasetString == "lines":
            toshow = ef
        elif datasetString == "contour":
            toshow = cf
        else:
            toshow = sf
        gw = vtk.vtkGeoJSONWriter()
        gw.SetInputConnection(toshow.GetOutputPort())
        gw.SetScalarFormat(2);
        if True:
            gw.SetFileName("/Source/CPIPES/buildogs/deploy/dataset.gj")
            gw.Write()
            f = file("/Source/CPIPES/buildogs/deploy/dataset.gj")
            gj = str(f.readlines())
        else:
            gw.WriteToOutputStringOn()
            gw.Write()
            gj = "['"+str(gw.RegisterAndGetOutputString()).replace('\n','')+"']"

        res = ("""
  <html>
    <head>
      <script type="text/javascript" src="/common/js/gl-matrix.js"></script>
      <script type="text/javascript" src="/lib/geoweb.min.js"></script>
      <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
      <script type="text/javascript">
      function makedata() {
        var datasetString = %(gjfile)s.join('\\n');

        var data = new ogs.vgl.geojsonReader().getPrimitives(datasetString);
        var geoms = data.geoms;

        var mapper = new ogs.vgl.mapper();
        mapper.setGeometryData(geoms[0]);
        """ +
        self.gjShader +
        """
        var actor = new ogs.vgl.actor();
        actor.setMapper(mapper);
        actor.setMaterial(mat);
        return actor;
      }
      </script>
      <script type="text/javascript">
      function main() {
        var mapOptions = {
          zoom : 1,
          center : ogs.geo.latlng(0.0, 0.0),
          source : '/data/assets/land_shallow_topo_2048.png'
        };
        var myMap = ogs.geo.map(document.getElementById("glcanvas"), mapOptions);

        var planeLayer = ogs.geo.featureLayer({
          "opacity" : 1,
          "showAttribution" : 1,
          "visible" : 1
         },
         makedata()
         );
        myMap.addLayer(planeLayer);
      }
      </script>

      <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css" />
      <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
      <script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
    </head>
    <body onload="main()">
      <canvas id="glcanvas" width="800" height="600"></canvas>
    </body>
  </html>
""") % {'gjfile' :gj}

        return res
示例#47
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()
示例#48
0
    def load_surf_geometry(self, surf_filename, dirname, plot=True):
        #skip_reading = self.remove_old_openfoam_geometry(openfoam_filename)
        #if skip_reading:
        #    return

        model = SurfReader()

        self.model_type = 'surf'
        print('surf_filename = %s' % surf_filename)

        model.read_surf(surf_filename)
        nnodes = model.nodes.shape[0]
        ntris = model.tris.shape[0]
        nquads = model.quads.shape[0]
        nelements = ntris + nquads

        nodes = model.nodes
        self.nElements = nelements
        self.nNodes = nnodes

        print("nNodes = %s" % self.nNodes)
        print("nElements = %s" % self.nElements)
        assert nelements > 0, nelements

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

        points = vtk.vtkPoints()
        points.SetNumberOfPoints(self.nNodes)

        mmax = amax(nodes, axis=0)
        mmin = amin(nodes, axis=0)
        dim_max = (mmax - mmin).max()
        self.create_global_axes(dim_max)
        self.log.info('max = %s' % mmax)
        self.log.info('min = %s' % mmin)

        for inode, node in enumerate(nodes):
            points.InsertPoint(inode, node)

        tris = model.tris - 1
        quads = model.quads - 1


        if ntris:
            for eid, element in enumerate(tris):
                elem = vtkTriangle()
                elem.GetPointIds().SetId(0, element[0])
                elem.GetPointIds().SetId(1, element[1])
                elem.GetPointIds().SetId(2, element[2])
                self.grid.InsertNextCell(elem.GetCellType(),
                                         elem.GetPointIds())
        if nquads:
            for eid, element in enumerate(quads):
                elem = vtkQuad()
                elem.GetPointIds().SetId(0, element[0])
                elem.GetPointIds().SetId(1, element[1])
                elem.GetPointIds().SetId(2, element[2])
                elem.GetPointIds().SetId(3, element[3])
                self.grid.InsertNextCell(elem.GetCellType(),
                                         elem.GetPointIds())

        model.read_surf_failnode(surf_filename)
        if len(model.nodes_failed):
            if 'failed_nodes' not in self.alt_grids:
                yellow = (1., 1., 0.)
                self.create_alternate_vtk_grid('failed_nodes', color=yellow, line_width=3, opacity=1.0)

            ifailed = where(model.nodes_failed == 1)[0]
            nfailed = len(ifailed)
            self.alt_grids['failed_nodes'].Allocate(nfailed, 1000)
            grid2 = self.alt_grids['failed_nodes']
            points2 = vtk.vtkPoints()
            points2.SetNumberOfPoints(nfailed)

            for j, nid in enumerate(model.nodes_failed):
                elem = vtk.vtkVertex()
                c = nodes[nid - 1, :]
                print(nid, c)
                points2.InsertPoint(j, *c)
                elem.GetPointIds().SetId(0, j)
                self.alt_grids['failed_nodes'].InsertNextCell(elem.GetCellType(), elem.GetPointIds())
            self.alt_grids['failed_nodes'].SetPoints(points2)
            self._add_alt_actors(self.alt_grids)

            actor = self.geometry_actors['failed_nodes']
            actor.Modified()
            prop = actor.GetProperty()
            prop.SetRepresentationToPoints()
            prop.SetPointSize(10)


            # self.

        self.nElements = nelements
        self.grid.SetPoints(points)
        self.grid.Modified()
        if hasattr(self.grid, 'Update'):
            self.grid.Update()
        #print("updated grid")

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

        self.iSubcaseNameMap = {1: ['AFLR Surface', '']}
        cases = {}
        ID = 1

        form, cases = self._fill_surf_case(surf_filename, cases, ID, nnodes, nelements, model)
        if plot:
            self._finish_results_io2(form, cases)