예제 #1
0
def quadsActor(bounds, color):
    """Create solid, axis-aligned quads at 0 in Z.

    Args:
      bounds: [[[xmin, ymin], [xmax, ymax]], ...]
      color: [R, G, B, A]
    """
    points = vtk.vtkPoints()
    quads = vtk.vtkCellArray()
    colors = vtk.vtkUnsignedCharArray()
    colors.SetNumberOfComponents(4)
    for (index, bound) in enumerate(bounds):
        colors.InsertNextTuple4(*color)
        (low, high) = bound
        points.InsertNextPoint(low[0], low[1], 0)
        points.InsertNextPoint(high[0], low[1], 0)
        points.InsertNextPoint(high[0], high[1], 0)
        points.InsertNextPoint(low[0], high[1], 0)
        quad = vtk.vtkQuad()
        for i in range(4):
            quad.GetPointIds().SetId(i, 4 * index + i)
        quads.InsertNextCell(quad)
    poly_data = vtk.vtkPolyData()
    poly_data.SetPoints(points)
    poly_data.SetPolys(quads)
    poly_data.GetCellData().SetScalars(colors)
    mapper = vtk.vtkPolyDataMapper()
    set_mapper_input(mapper, poly_data)
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.RotateZ(180)
    actor.RotateY(180)
    return actor
예제 #2
0
파일: plot.py 프로젝트: SinghN/nutils
  def unstructuredgrid( self, points, npars=None ):
    """add unstructured grid"""

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

    import vtk

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

    cnt = 0
    for pts in points:

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

      vtkelem   = None

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

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

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

      cellpoints = vtkelem.GetPointIds()

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

    self.vtkMesh.SetPoints( vtkPoints )
예제 #3
0
    def buildPartialVTKGrid(self, factag):
        #get points required for factag
        pointsList = self.getPointsWithFactag(factag)

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

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

        #build the vtk elements
        for element in felements:
            type = element.getType()
            nodes = element.nodes
            if type == eTypes.TRI:
                cell = vtk.vtkTriangle()
            elif type == eTypes.QUAD:
                cell = vtk.vtkQuad()
            elif type == eTypes.TET:
                cell = vtk.vtkTetra()
            elif type == eTypes.PYRAMID:
                cell = vtk.vtkPyramid()
            elif type == eTypes.PRISM:
                cell = vtk.vtkWedge()  #prism
            elif type == eTypes.HEX:
                cell = vtk.vtkHexahedron()
            else:
                raise # throw an exception
            j = 0
            for n in nodes:
                localId = ptMap[int(n)]
                cell.GetPointIds().SetId(j,localId)
                j = j+1
            vtkgrid.InsertNextCell(cell.GetCellType(), cell.GetPointIds())
        return vtkgrid
예제 #4
0
 def _create_tecplot_shells(self, is_quads, quads, is_tris, tris):
     if is_quads:
         elements = quads
         for iface, face in enumerate(quads):
             elem = vtkQuad()
             epoints = elem.GetPointIds()
             epoints.SetId(0, face[0])
             epoints.SetId(1, face[1])
             epoints.SetId(2, face[2])
             epoints.SetId(3, face[3])
             self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())  #elem.GetCellType() = 5  # vtkTriangle
             #break
     if is_tris:
         elements = tris
         for iface, face in enumerate(tris):
             elem = vtkTriangle()
             epoints = elem.GetPointIds()
             epoints.SetId(0, face[0])
             epoints.SetId(1, face[1])
             epoints.SetId(2, face[2])
             self.grid.InsertNextCell(5, elem.GetPointIds())  #elem.GetCellType() = 5  # vtkTriangle
예제 #5
0
파일: VTKViewer.py 프로젝트: wrlife/Colon3D
  def load_point_cloud(self, points, colors=None, mesh=False):
    # first, generate quad mesh, if desired
    if mesh:
      mesh = vtk.vtkCellArray()
      if len(points.shape) != 3 or points.shape[2] != 3:
        raise Exception('For the meshing to work, the points array must have ' +
          'the form MxNx3')

      for i in xrange(points.shape[0] - 1):
        offset = i * points.shape[1]
        for j in xrange(points.shape[1] - 1):
          quad = vtk.vtkQuad()
          pids = quad.GetPointIds()
          pids.SetNumberOfIds(4)
          idx = offset + j
          pids.SetId(0, idx)
          pids.SetId(1, idx + 1)
          pids.SetId(2, idx + points.shape[1] + 1)
          pids.SetId(3, idx + points.shape[1])
          mesh.InsertNextCell(quad)

    poly_data = vtk.vtkPolyData()
    poly_data.SetPoints(self._convert_points_array(points))

    if mesh is not False:
      poly_data.SetPolys(mesh)
    else: # no mesh data; only show vertices
      vertices = vtk.vtkCellArray()
      vertices.InsertNextCell(points.shape[0], np.arange(points.shape[0]))
      poly_data.SetVerts(vertices)

    # Visualize
    actor = self._actor_from_poly_data(poly_data)
    actor.GetProperty().SetPointSize(self.point_size)

    if colors is not None:
      self._add_color_to_actor(actor, colors)

    return self._add_mesh_actor(actor)
예제 #6
0
    def set_quad_grid(self, name, nodes, elements, color, line_width=5, opacity=1.):
        """
        Makes a CQUAD4 grid
        """
        self.create_alternate_vtk_grid(name, color=color, line_width=line_width,
                                       opacity=opacity, representation='wire')

        nnodes = nodes.shape[0]
        nquads = elements.shape[0]
        #print(nodes)
        if nnodes == 0:
            return
        if nquads == 0:
            return

        #print('adding quad_grid %s; nnodes=%s nquads=%s' % (name, nnodes, nquads))
        points = vtk.vtkPoints()
        points.SetNumberOfPoints(nnodes)
        for nid, node in enumerate(nodes):
            #print(nid, node)
            points.InsertPoint(nid, *list(node))

        #assert vtkQuad().GetCellType() == 9, elem.GetCellType()
        self.alt_grids[name].Allocate(nquads, 1000)
        for element in elements:
            elem = vtk.vtkQuad()
            point_ids = elem.GetPointIds()
            point_ids.SetId(0, element[0])
            point_ids.SetId(1, element[1])
            point_ids.SetId(2, element[2])
            point_ids.SetId(3, element[3])
            self.alt_grids[name].InsertNextCell(9, elem.GetPointIds())
        self.alt_grids[name].SetPoints(points)

        self._add_alt_actors({name : self.alt_grids[name]})

        #if name in self.geometry_actors:
        self.geometry_actors[name].Modified()
예제 #7
0
파일: handle.py 프로젝트: UNESCO-IHE/uvcdat
def quad_poly_data(width, height):
    from vtk import vtkPoints, vtkQuad, vtkCellArray, vtkPolyData

    points = vtkPoints()
    points.InsertNextPoint((-1 * int(width / 2.0), int(height / 2.0), 0))
    points.InsertNextPoint((int(width / 2.0), int(height / 2.0), 0))
    points.InsertNextPoint((int(width / 2.0), -1 * int(height / 2.0), 0))
    points.InsertNextPoint((-1 * int(width / 2.0), -1 * int(height / 2.0), 0))

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

    arr = vtkCellArray()
    arr.InsertNextCell(quad)

    pd = vtkPolyData()
    pd.SetPoints(points)
    pd.SetPolys(arr)

    return pd
예제 #8
0
    def buildFullVTKGrid(self):
        # Create the points for VTK
        points = vtk.vtkPoints()
        for i in range(0, len(self.mesh.coords)/3):
            p = self.mesh.coords[(i*3):(i*3+3)]
            points.InsertNextPoint(p)

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

        #add the VTK elements to the mesh
        for element in self.mesh.elements:
            type = element.getType()
            nodes = element.nodes
            cell = vtk.vtkTriangle()
            if type == eTypes.TRI:
                cell = vtk.vtkTriangle()
            elif type == eTypes.QUAD:
                cell = vtk.vtkQuad()
            elif type == eTypes.TET:
                cell = vtk.vtkTetra()
            elif type == eTypes.PYRAMID:
                cell = vtk.vtkPyramid()
            elif type == eTypes.PRISM:
                cell = vtk.vtkWedge()  #prism
            elif type == eTypes.HEX:
                cell = vtk.vtkHexahedron()
            else:
                raise # throw an exception
            j = 0
            for n in nodes:
                cell.GetPointIds().SetId(j,n)
                j = j+1
            vtkgrid.InsertNextCell(cell.GetCellType(), cell.GetPointIds())
        return vtkgrid
예제 #9
0
    newNodes[2] = nodes[3]
    newNodes[3] = nodes[2]
      
  return newNodes

if VtkSupport():
  VTK_UNKNOWN = None
  VTK_EMPTY_CELL = vtk.vtkEmptyCell().GetCellType()
  VTK_VERTEX = vtk.vtkVertex().GetCellType()
  VTK_LINE = vtk.vtkLine().GetCellType()
  VTK_QUADRATIC_LINE = vtk.vtkQuadraticEdge().GetCellType()
  VTK_TRIANGLE = vtk.vtkTriangle().GetCellType()
  VTK_QUADRATIC_TRIANGLE = vtk.vtkQuadraticTriangle().GetCellType()
  VTK_TETRAHEDRON = vtk.vtkTetra().GetCellType()
  VTK_QUADRATIC_TETRAHEDRON = vtk.vtkQuadraticTetra().GetCellType()
  VTK_QUAD = vtk.vtkQuad().GetCellType()
  VTK_HEXAHEDRON = vtk.vtkHexahedron().GetCellType()
   
  vtkTypeIds = ( \
      VTK_UNKNOWN, \
      VTK_EMPTY_CELL, \
      VTK_VERTEX, \
      VTK_LINE, VTK_QUADRATIC_LINE, \
      VTK_TRIANGLE, VTK_QUADRATIC_TRIANGLE, VTK_QUAD, \
      VTK_TETRAHEDRON, VTK_QUADRATIC_TETRAHEDRON, VTK_HEXAHEDRON \
    )
   
  class VtkType(elements.ElementType):
    """
    Class defining a VTK element type
    """
예제 #10
0
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)
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
예제 #11
0
def rhombic_dodecahedron():
    # http://www.vtk.org/pipermail/vtkusers/2014-September/085077.html
    import vtk
    # This is a Rhombic Dodecahedron.

    # First, you need to store the vertex locations.
    vertex_locations = vtk.vtkPoints()
    vertex_locations.SetNumberOfPoints(14)
    vertex_locations.SetPoint( 0, (-0.816497, -0.816497,  0.00000))
    vertex_locations.SetPoint( 1, (-0.816497,  0.000000, -0.57735))
    vertex_locations.SetPoint( 2, (-0.816497,  0.000000,  0.57735))
    vertex_locations.SetPoint( 3, (-0.816497,  0.816497,  0.00000))
    vertex_locations.SetPoint( 4, ( 0.000000, -0.816497, -0.57735))
    vertex_locations.SetPoint( 5, ( 0.000000, -0.816497,  0.57735))
    vertex_locations.SetPoint( 6, ( 0.000000,  0.000000, -1.15470))
    vertex_locations.SetPoint( 7, ( 0.000000,  0.000000,  1.15470))
    vertex_locations.SetPoint( 8, ( 0.000000,  0.816497, -0.57735))
    vertex_locations.SetPoint( 9, ( 0.000000,  0.816497,  0.57735))
    vertex_locations.SetPoint(10, ( 0.816497, -0.816497,  0.00000))
    vertex_locations.SetPoint(11, ( 0.816497,  0.000000, -0.57735))
    vertex_locations.SetPoint(12, ( 0.816497,  0.000000,  0.57735))
    vertex_locations.SetPoint(13, ( 0.816497,  0.816497,  0.00000))

    # Next, you describe the polygons that represent the faces using the vertex
    # indices in the vtkPoints that stores the vertex locations. There are a
    #number
    # of ways to do this that you can find in examples on the Wiki.

    polygon_faces = vtk.vtkCellArray()

    q = vtk.vtkQuad()
    q.GetPointIds().SetId(0,  7)
    q.GetPointIds().SetId(1, 12)
    q.GetPointIds().SetId(2, 10)
    q.GetPointIds().SetId(3,  5)
    polygon_faces.InsertNextCell(q)

    q = vtk.vtkQuad()
    q.GetPointIds().SetId(0,  7)
    q.GetPointIds().SetId(1, 12)
    q.GetPointIds().SetId(2, 13)
    q.GetPointIds().SetId(3,  9)
    polygon_faces.InsertNextCell(q)

    q = vtk.vtkQuad()
    q.GetPointIds().SetId(0,  7)
    q.GetPointIds().SetId(1,  9)
    q.GetPointIds().SetId(2,  3)
    q.GetPointIds().SetId(3,  2)
    polygon_faces.InsertNextCell(q)

    q = vtk.vtkQuad()
    q.GetPointIds().SetId(0,  7)
    q.GetPointIds().SetId(1,  2)
    q.GetPointIds().SetId(2,  0)
    q.GetPointIds().SetId(3,  5)
    polygon_faces.InsertNextCell(q)

    q = vtk.vtkQuad()
    q.GetPointIds().SetId(0,  6)
    q.GetPointIds().SetId(1, 11)
    q.GetPointIds().SetId(2, 10)
    q.GetPointIds().SetId(3,  4)
    polygon_faces.InsertNextCell(q)

    q = vtk.vtkQuad()
    q.GetPointIds().SetId(0,  6)
    q.GetPointIds().SetId(1,  4)
    q.GetPointIds().SetId(2,  0)
    q.GetPointIds().SetId(3,  1)
    polygon_faces.InsertNextCell(q)

    q = vtk.vtkQuad()
    q.GetPointIds().SetId(0,  6)
    q.GetPointIds().SetId(1,  1)
    q.GetPointIds().SetId(2,  3)
    q.GetPointIds().SetId(3,  8)
    polygon_faces.InsertNextCell(q)

    q = vtk.vtkQuad()
    q.GetPointIds().SetId(0,  6)
    q.GetPointIds().SetId(1,  8)
    q.GetPointIds().SetId(2, 13)
    q.GetPointIds().SetId(3, 11)
    polygon_faces.InsertNextCell(q)

    q = vtk.vtkQuad()
    q.GetPointIds().SetId(0, 10)
    q.GetPointIds().SetId(1, 11)
    q.GetPointIds().SetId(2, 13)
    q.GetPointIds().SetId(3, 12)
    polygon_faces.InsertNextCell(q)

    q = vtk.vtkQuad()
    q.GetPointIds().SetId(0, 13)
    q.GetPointIds().SetId(1,  8)
    q.GetPointIds().SetId(2,  3)
    q.GetPointIds().SetId(3,  9)
    polygon_faces.InsertNextCell(q)

    q = vtk.vtkQuad()
    q.GetPointIds().SetId(0,  3)
    q.GetPointIds().SetId(1,  1)
    q.GetPointIds().SetId(2,  0)
    q.GetPointIds().SetId(3,  2)
    polygon_faces.InsertNextCell(q)

    q = vtk.vtkQuad()
    q.GetPointIds().SetId(0,  0)
    q.GetPointIds().SetId(1,  4)
    q.GetPointIds().SetId(2, 10)
    q.GetPointIds().SetId(3,  5)
    polygon_faces.InsertNextCell(q)

    # Next you create a vtkPolyData to store your face and vertex information
    #that
    # represents your polyhedron.
    pd = vtk.vtkPolyData()
    pd.SetPoints(vertex_locations)
    pd.SetPolys(polygon_faces)

    # If you wanted to be able to load in the saved file and select the entire
    # polyhedron, you would need to save it as a vtkUnstructuredGrid, and you
    #would
    # need to put the data into a vtkPolyhedron. This is a bit more involved
    #than
    # the vtkPolyData that I used above. For a more in-depth discussion, see:
    # http://www.vtk.org/Wiki/VTK/Polyhedron_Support

    # Based on the link above, I need to construct a face stream:
    face_stream = vtk.vtkIdList()
    face_stream.InsertNextId(polygon_faces.GetNumberOfCells())
    vertex_list = vtk.vtkIdList()

    polygon_faces.InitTraversal()
    while polygon_faces.GetNextCell(vertex_list) == 1:
        face_stream.InsertNextId(vertex_list.GetNumberOfIds())

        for j in range(vertex_list.GetNumberOfIds()):
            face_stream.InsertNextId(vertex_list.GetId(j))

    ug = vtk.vtkUnstructuredGrid()
    ug.SetPoints(vertex_locations)
    ug.InsertNextCell(vtk.VTK_POLYHEDRON, face_stream)

    #--------------#
    # output stuff #
    #--------------#

    writer = vtk.vtkUnstructuredGridWriter()
    writer.SetFileName("rhombic_dodecahedron.vtk")
    #writer.SetInputData(ug)
    writer.SetInput(ug)
    writer.Write()

    #---------------------#
    # visualization stuff #
    #---------------------#
    # mapper = vtk.vtkPolyDataMapper()
    # mapper.SetInputData(pd)
    mapper = vtk.vtkDataSetMapper()
    mapper.SetInput(ug)

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

    ren = vtk.vtkRenderer()
    ren.AddActor(actor)

    renw = vtk.vtkRenderWindow()
    renw.AddRenderer(ren)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renw)

    ren.ResetCamera()
    renw.Render()
    iren.Start()
예제 #12
0
    def load_ugrid_geometry(self, ugrid_filename, dirname, name='main', plot=True):
        #skip_reading = self.remove_old_openfoam_geometry(openfoam_filename)
        #if skip_reading:
        #    return
        if is_binary_file(ugrid_filename):
            model = UGRID(log=self.log, debug=True)
            base, fmt, ext = os.path.basename(ugrid_filename).split('.')
            is_2d = False
        else:
            base, ext = os.path.basename(ugrid_filename).split('.')
            model = UGRID2D_Reader(log=self.log, debug=True)
            is_2d = True

        self.model_type = 'ugrid'
        print('ugrid_filename = %s' % ugrid_filename)


        assert ext == 'ugrid', ugrid_filename
        model.read_ugrid(ugrid_filename)

        if is_2d:
            tris = model.tris
            quads = model.quads
        else:
            tris = model.tris - 1
            quads = model.quads - 1

        #self.nodes = nodes
        #self.tris  = tris
        #self.quads = quads
        #self.pids = pids

        #self.tets = tets
        #self.penta5s = penta5s
        #self.penta6s = penta6s
        #self.hexas = hexas

        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)

        diff_node_ids = model.check_hanging_nodes(stop_on_diff=False)
        if len(diff_node_ids):
            red = (1., 0., 0.)
            self.create_alternate_vtk_grid('hanging_nodes', color=red, line_width=5, opacity=1., point_size=10, representation='point')
            self._add_ugrid_nodes_to_grid('hanging_nodes', diff_node_ids, nodes)
            self._add_alt_actors(self.alt_grids)


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

        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())

        self.nElements = nelements
        self.grid.SetPoints(points)
        self.grid.Modified()
        print('update...')
        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 UGRID Surface', '']}
        cases = {}
        ID = 1

        if hasattr(model, 'pids'):
            form, cases = self._fill_ugrid3d_case(ugrid_filename, cases, ID, nnodes, nelements, model)
        else:
            form, cases = self._fill_ugrid2d_case(ugrid_filename, cases, ID, nnodes, nelements, model)

        if plot:
            self._finish_results_io2(form, cases)
예제 #13
0
    def load_shabp_geometry(self, shabp_filename, name='main', plot=True):
        self.eid_maps[name] = {}
        self.nid_maps[name] = {}

        #key = self.case_keys[self.icase]
        #case = self.result_cases[key]

        skip_reading = self._remove_old_geometry(shabp_filename)
        if skip_reading:
            return

        self.model = read_shabp(shabp_filename, log=self.log, debug=self.debug)
        self.model_type = 'shabp'  # model.model_type

        nodes, elements, patches, components, impact, shadow = self.model.getPointsElementsRegions(
        )
        #for nid,node in enumerate(nodes):
        #print "node[%s] = %s" %(nid,str(node))

        nnodes = len(nodes)
        self.nnodes = len(nodes)
        self.nelements = len(elements)
        #print("nnodes = ",self.nnodes)
        #print("nelements = ", self.nelements)

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

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

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

        assert len(nodes) > 0
        mmax = amax(nodes, axis=0)
        mmin = amin(nodes, axis=0)
        dim_max = (mmax - mmin).max()
        self.create_global_axes(dim_max)
        for nid, node in enumerate(nodes):
            points.InsertPoint(nid, *node)

        assert len(elements) > 0
        for eid, element in enumerate(elements):
            (p1, p2, p3, p4) = element
            elem = vtkQuad()
            elem.GetPointIds().SetId(0, p1)
            elem.GetPointIds().SetId(1, p2)
            elem.GetPointIds().SetId(2, p3)
            elem.GetPointIds().SetId(3, p4)
            self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())

        self.grid.SetPoints(points)
        #self.grid.GetPointData().SetScalars(self.gridResult)
        #print dir(self.grid) #.SetNumberOfComponents(0)
        #self.grid.GetCellData().SetNumberOfTuples(1);
        #self.grid.GetCellData().SetScalars(self.gridResult)
        self.grid.Modified()
        if hasattr(self.grid, 'Update'):
            self.grid.Update()

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

        self.isubcase_name_map = {1: ['S/HABP', '']}
        cases = {}
        ID = 1

        self.log.debug("nNodes=%i nElements=%i" %
                       (self.nnodes, self.nelements))
        form, cases = self._fill_shabp_geometry_case(cases, ID, nodes,
                                                     elements, patches,
                                                     components, impact,
                                                     shadow)
        self._finish_results_io2(form, cases)
예제 #14
0
def buildMesh(xNumCells, yNumCells, filename):
    
    polydata = vtk.vtkPolyData()
    points = vtk.vtkPoints()
    quads = vtk.vtkCellArray()

    counter = 0 
    
    xBase = 0
    yBase = 0
    
    xStep = quadLength/(xNumCells * 1.0) # Focing float division (python 2).
    yStep = quadHeight/(yNumCells * 1.0)
    
    branchId = vtk.vtkDoubleArray()
    branchId.SetName("branchId")

    
    # Three rectangles in space for a bifurcation.
    if bifurcation == True:
        stopAt = 3
    else:
        stopAt = 1

    for k in range(0, stopAt):
        if k == 1:
            xBase = - quadLength * (xQuads / 2)
            yBase = quadHeight * yQuads
            
        elif k == 2:
            xBase = + quadLength * (xQuads / 2) 
            yBase = quadHeight * yQuads     
                       
        # The framework for each quad. The total number is set by globals.
        for i in range(0, yQuads):
            for j in range(0, xQuads):
                
                    # For how ever many cells are within each main quad.
                    # The total number is decided by the function parameters.
                    for x in range(0, yNumCells):
                        for y in range(0, xNumCells):
                            
                            quad = vtk.vtkQuad()
                                                        
                            p0 = [y * xStep + xBase + (quadLength * j), 
                                  x * yStep + yBase + (quadHeight * i), 0]
                                  
                            p1 = [(y + 1) * xStep + xBase + (quadLength * j),
                                  x * yStep + yBase + (quadHeight * i), 0]
                                  
                            p2 = [(y + 1) * xStep + xBase + (quadLength * j), 
                                  (x + 1) * yStep + yBase + (quadHeight * i), 0]
                                  
                            p3 = [y * xStep + xBase + (quadLength * j),
                                  (x + 1) * yStep + yBase + (quadHeight * i), 0]
                                  
                            
                            points.InsertNextPoint(p0)
                            points.InsertNextPoint(p1)
                            points.InsertNextPoint(p2)
                            points.InsertNextPoint(p3)
                            
                            quad.GetPointIds().InsertId(0, counter)
                            quad.GetPointIds().InsertId(1, counter + 1)
                            quad.GetPointIds().InsertId(2, counter + 2)
                            quad.GetPointIds().InsertId(3, counter + 3)
                            counter += 4
                            
                            quads.InsertNextCell(quad)
                            branchId.InsertNextValue(k)

    polydata.SetPoints(points)
    polydata.SetPolys(quads)
    polydata.GetCellData().SetScalars(branchId)
    
    polyDataWriter = vtk.vtkXMLPolyDataWriter()
    polyDataWriter.SetFileName(filename)
    polyDataWriter.SetInputData(polydata)    
    polyDataWriter.Write()

    return polydata    
예제 #15
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()
예제 #16
0
def getVolumeVtkGrid(visMesh):
    """

    Returns:
        vtk.vtkUnstructuredGrid:
    """
    assert isinstance(visMesh, VisMesh)
    bClipPolyhedra = True

    vtkpoints = vtk.vtkPoints()
    for visPoint in visMesh.points:
        vtkpoints.InsertNextPoint(visPoint.x, visPoint.y, visPoint.z)

    vtkgrid = vtk.vtkUnstructuredGrid()
    vtkgrid.Allocate(len(visMesh.points), len(visMesh.points))
    vtkgrid.SetPoints(vtkpoints)

    quadType = vtk.vtkQuad().GetCellType()
    #  lineType = vtk.vtkLine().GetCellType()
    polygonType = vtk.vtkPolygon().GetCellType()
    polyhedronType = vtk.vtkPolyhedron().GetCellType()
    triangleType = vtk.vtkTriangle().GetCellType()
    voxelType = vtk.vtkVoxel().GetCellType()
    tetraType = vtk.vtkTetra().GetCellType()

    if visMesh.polygons != None:
        for visPolygon in visMesh.polygons:
            pts = vtk.vtkIdList()
            polygonPoints = visPolygon.pointIndices
            for p in polygonPoints:
                pts.InsertNextId(p)

            numPoints = len(polygonPoints)
            if numPoints == 4:
                vtkgrid.InsertNextCell(quadType, pts)
            elif numPoints == 3:
                vtkgrid.InsertNextCell(triangleType, pts)
            else:
                vtkgrid.InsertNextCell(polygonType, pts)
    #
    # replace any VisIrregularPolyhedron with a list of VisTetrahedron
    #
    if visMesh.visVoxels != None:
        for voxel in visMesh.visVoxels:
            pts = vtk.vtkIdList()
            polyhedronPoints = voxel.pointIndices
            for p in polyhedronPoints:
                pts.InsertNextId(p)
            vtkgrid.InsertNextCell(voxelType, pts)

    if visMesh.tetrahedra != None:
        for visTet in visMesh.tetrahedra:
            assert isinstance(visTet, VisTetrahedron)
            pts = vtk.vtkIdList()
            tetPoints = visTet.pointIndices
            for p in tetPoints:
                pts.InsertNextId(p)
            vtkgrid.InsertNextCell(tetraType, pts)

    bInitializedFaces = False
    if visMesh.irregularPolyhedra != None:
        for clippedPolyhedron in visMesh.irregularPolyhedra:
            if bClipPolyhedra == True:
                tets = createTetrahedra(clippedPolyhedron, visMesh)
                for visTet in tets:
                    pts = vtk.vtkIdList()
                    tetPoints = visTet.getPointIndices()
                    for p in tetPoints:
                        pts.InsertNextId(p)
                    vtkgrid.InsertNextCell(tetraType, pts)
            else:
                faceStreamList = vtk.vtkIdList()
                faceStream = getVtkFaceStream(clippedPolyhedron)
                for p in faceStream:
                    faceStreamList.InsertNextId(p)
                if bInitializedFaces == False and vtkgrid.GetNumberOfCells(
                ) > 0:
                    vtkgrid.InitializeFacesRepresentation(
                        vtkgrid.GetNumberOfCells())
                bInitializedFaces = True
                vtkgrid.InsertNextCell(polyhedronType, faceStreamList)

    vtkgrid.BuildLinks()
    # vtkgrid.Squeeze()
    return vtkgrid
        add_line([0, 0, 0], index_2d_to_3d_det(proj_pt), 0.0, 1.0, 0.0)

    # Draw the detector plane

    #add_sphere(det_r0c0, 1, 1, 0, 5.0)
    #add_sphere(det_r0cN, 1, 146.0/255.0, 20.0/255.0, 5.0)
    #add_sphere(det_rMc0, 116.0/255.0, 0, 189.0/255.0, 5.0)
    #add_sphere(det_rMcN, 46.0/255.0, 238.0/255.0, 1, 5.0)

    det_corners = vtkPoints()
    det_corners.InsertNextPoint(det_r0c0[0], det_r0c0[1], det_r0c0[2])
    det_corners.InsertNextPoint(det_rMc0[0], det_rMc0[1], det_rMc0[2])
    det_corners.InsertNextPoint(det_rMcN[0], det_rMcN[1], det_rMcN[2])
    det_corners.InsertNextPoint(det_r0cN[0], det_r0cN[1], det_r0cN[2])

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

    quads = vtkCellArray()
    quads.InsertNextCell(det_quad)

    det_poly_data = vtkPolyData()
    det_poly_data.SetPoints(det_corners)
    det_poly_data.SetPolys(quads)

    tex_coords = vtkFloatArray()
    tex_coords.SetNumberOfComponents(2)
    tex_coords.SetName('TextureCoordinates')
예제 #18
0
    def load_shabp_geometry(self, shabp_filename, name='main', plot=True):
        self.gui.eid_maps[name] = {}
        self.gui.nid_maps[name] = {}

        #key = self.case_keys[self.icase]
        #case = self.result_cases[key]

        skip_reading = self.gui._remove_old_geometry(shabp_filename)
        if skip_reading:
            return

        self.model = read_shabp(shabp_filename,
                                log=self.gui.log,
                                debug=self.gui.debug)
        self.gui.model_type = 'shabp'  # model.model_type

        nodes, elements, patches, components, impact, shadow = self.model.get_points_elements_regions(
        )
        #for nid,node in enumerate(nodes):
        #print "node[%s] = %s" %(nid,str(node))

        nnodes = len(nodes)
        nelements = len(elements)
        self.gui.nnodes = nnodes
        self.gui.nelements = nelements
        #print("nnodes = ",self.nnodes)
        #print("nelements = ", self.nelements)

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

        points = vtk.vtkPoints()
        points.SetNumberOfPoints(nnodes)

        assert len(nodes) > 0
        mmax = amax(nodes, axis=0)
        mmin = amin(nodes, axis=0)
        dim_max = (mmax - mmin).max()
        self.gui.create_global_axes(dim_max)
        for nid, node in enumerate(nodes):
            points.InsertPoint(nid, *node)

        assert len(elements) > 0
        for eid, element in enumerate(elements):
            (p1, p2, p3, p4) = element
            elem = vtkQuad()
            elem.GetPointIds().SetId(0, p1)
            elem.GetPointIds().SetId(1, p2)
            elem.GetPointIds().SetId(2, p3)
            elem.GetPointIds().SetId(3, p4)
            grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())

        grid.SetPoints(points)
        grid.Modified()
        if hasattr(grid, 'Update'):  # pragma: no cover
            grid.Update()

        # loadShabpResults - regions/loads
        self.gui.scalar_bar_actor.VisibilityOn()
        self.gui.scalar_bar_actor.Modified()

        self.gui.isubcase_name_map = {1: ['S/HABP', '']}
        cases = OrderedDict()
        ID = 1

        self.gui.log.debug("nNodes=%i nElements=%i" %
                           (self.gui.nnodes, self.gui.nelements))
        form, cases = self._fill_shabp_geometry_case(cases, ID, nodes,
                                                     elements, patches,
                                                     components, impact,
                                                     shadow)

        nelements = len(elements)
        node_ids = np.arange(1, nnodes + 1, dtype='int32')
        element_ids = np.arange(1, nelements + 1, dtype='int32')
        self.gui.node_ids = node_ids
        self.gui.element_ids = element_ids
        self.gui._finish_results_io2(form, cases)
    def transformLegacySrep(self, m3d_filename, outPrefix, epsilon):
        print('tranform legacy srep')
        outputUp = outPrefix + '/up.vtp'
        outputDown = outPrefix + '/down.vtp'
        outputCrest = outPrefix + '/crest.vtp'
        """
        The purpose of this part of code is to play around m3d to fit into the new s-rep format framework
        """

        up_spokes_polydata = vtk.vtkPolyData()
        down_spokes_polydata = vtk.vtkPolyData()
        crest_spokes_polydata = vtk.vtkPolyData()

        # read in m3d file
        s = srep.srep()
        s.readSrepFromM3D(m3d_filename)

        writer = vtk.vtkXMLPolyDataWriter()
        writer.SetDataModeToAscii()
        """
        Given an s-rep,
        1. read in medial points
        2. set spoke vectors as point data
        3. set spoke vector length as point data as well
        4. create a header that contains meta data (e.g., number of rows, number of columns, mesh type)
        5. create xml header
        """
        nRows = s.fig.numRows
        nCols = s.fig.numCols
        # create
        root = Element('s-rep')
        nRowsXMLElement = SubElement(root, 'nRows')
        nRowsXMLElement.text = str(nRows)

        nColsXMLElement = SubElement(root, 'nCols')
        nColsXMLElement.text = str(nCols)

        meshTypeXMLElement = SubElement(root, 'meshType')
        meshTypeXMLElement.text = 'Quad'

        colorXMLElement = SubElement(root, 'color')

        redXMLElement = SubElement(colorXMLElement, 'red')
        redXMLElement.text = str(0)

        greenXMLElement = SubElement(colorXMLElement, 'green')
        greenXMLElement.text = str(0.5)

        blueXMLElement = SubElement(colorXMLElement, 'blue')
        blueXMLElement.text = str(0)

        isMeanFlagXMLElement = SubElement(root, 'isMean')
        isMeanFlagXMLElement.text = 'False'

        meanStatPathXMLElement = SubElement(root, 'meanStatPath')
        meanStatPathXMLElement.text = ''
        # later this can be done as a parameter
        upSpokeXMLElement = SubElement(root, 'upSpoke')
        upSpokeXMLElement.text = os.path.join(outputUp)

        downSpokeXMLElement = SubElement(root, 'downSpoke')
        downSpokeXMLElement.text = os.path.join(outputDown)

        crestSpokeXMLElement = SubElement(root, 'crestSpoke')
        crestSpokeXMLElement.text = os.path.join(outputCrest)

        crestShiftXMLElement = SubElement(root, 'crestShift')
        crestShiftXMLElement.text = str(epsilon)

        file_handle = open(outPrefix + '/header.xml', 'w')
        file_handle.write(prettify(root))
        file_handle.close()

        # medial points and polygons first
        medial_points = vtk.vtkPoints()
        medial_points.SetDataTypeToDouble(
        )  # important, this fix the bug that new srep has different precision with legacy one, you can find it by runningapplyTps2NewSrep program
        medial_polys = vtk.vtkCellArray()

        # This will be curves
        crest_points = vtk.vtkPoints()
        crest_polys = vtk.vtkCellArray()
        #
        up_spoke_directions = vtk.vtkDoubleArray()
        up_spoke_directions.SetNumberOfComponents(3)
        up_spoke_directions.SetName("spokeDirection")

        up_spoke_lengths = vtk.vtkDoubleArray()
        up_spoke_lengths.SetNumberOfComponents(1)
        up_spoke_lengths.SetName("spokeLength")

        down_spoke_directions = vtk.vtkDoubleArray()
        down_spoke_directions.SetNumberOfComponents(3)
        down_spoke_directions.SetName("spokeDirection")

        down_spoke_lengths = vtk.vtkDoubleArray()
        down_spoke_lengths.SetNumberOfComponents(1)
        down_spoke_lengths.SetName("spokeLength")

        crest_spoke_directions = vtk.vtkDoubleArray()
        crest_spoke_directions.SetNumberOfComponents(3)
        crest_spoke_directions.SetName("spokeDirection")

        crest_spoke_lengths = vtk.vtkDoubleArray()
        crest_spoke_lengths.SetNumberOfComponents(1)
        crest_spoke_lengths.SetName("spokeLength")
        """
        Read in
          1. medial points,
          2. up spokeLength, up spokeDirection
          3. down spokeLength, down spokeDirection
        """
        for r in range(nRows):
            for c in range(nCols):
                current_atom = s.fig.atoms[r, c]
                current_point = current_atom.hub.P
                current_id = medial_points.InsertNextPoint(current_point)

                if r < nRows - 1 and c < nCols - 1:
                    quad = vtk.vtkQuad()
                    quad.GetPointIds().SetId(0, current_id)
                    quad.GetPointIds().SetId(1, current_id + nCols)
                    quad.GetPointIds().SetId(2, current_id + nCols + 1)
                    quad.GetPointIds().SetId(3, current_id + 1)
                    medial_polys.InsertNextCell(quad)

                current_up_spoke = current_atom.topSpoke
                current_up_spoke_direction = current_up_spoke.U
                up_spoke_directions.InsertNextTuple(current_up_spoke_direction)
                current_up_spoke_length = current_up_spoke.r
                up_spoke_lengths.InsertNextTuple1(current_up_spoke_length)

                current_down_spoke = current_atom.botSpoke
                current_down_spoke_direction = current_down_spoke.U
                down_spoke_directions.InsertNextTuple(
                    current_down_spoke_direction)
                current_down_spoke_length = current_down_spoke.r
                down_spoke_lengths.InsertNextTuple1(current_down_spoke_length)
        """
        Construct crest vtp
          1. read points, direction, and length in clockwise
          2. write it as a curve
        """
        # \TODO: There is a lot repeating of the same code. Need to think if I can abstract the repetition into a function
        # first row
        r = 0
        for c in range(nCols - 1):
            current_crest_atom = s.fig.atoms[r, c]
            current_crest_spoke = current_crest_atom.crestSpoke
            current_crest_spoke_direction = current_crest_spoke.U

            current_crest_point = current_crest_atom.hub.P + epsilon * current_crest_spoke_direction
            current_crest_point_id = crest_points.InsertNextPoint(
                current_crest_point)
            line = vtk.vtkLine()
            if current_crest_point_id > 0:
                line = vtk.vtkLine()
                line.GetPointIds().SetId(0, current_crest_point_id - 1)
                line.GetPointIds().SetId(1, current_crest_point_id)
                crest_polys.InsertNextCell(line)
            crest_spoke_directions.InsertNextTuple(
                current_crest_spoke_direction)
            current_crest_spoke_length = current_crest_spoke.r
            crest_spoke_lengths.InsertNextTuple1(current_crest_spoke_length)

        # last column
        c = nCols - 1
        for r in range(nRows - 1):
            current_crest_atom = s.fig.atoms[r, c]
            current_crest_spoke = current_crest_atom.crestSpoke
            current_crest_spoke_direction = current_crest_spoke.U

            current_crest_point = current_crest_atom.hub.P + epsilon * current_crest_spoke_direction
            current_crest_point_id = crest_points.InsertNextPoint(
                current_crest_point)
            line = vtk.vtkLine()
            if current_crest_point_id > 0:
                line = vtk.vtkLine()
                line.GetPointIds().SetId(0, current_crest_point_id - 1)
                line.GetPointIds().SetId(1, current_crest_point_id)
                crest_polys.InsertNextCell(line)
            crest_spoke_directions.InsertNextTuple(
                current_crest_spoke_direction)
            current_crest_spoke_length = current_crest_spoke.r
            crest_spoke_lengths.InsertNextTuple1(current_crest_spoke_length)

        # bottom row
        r = nRows - 1
        for c in range(nCols - 1, 0, -1):
            current_crest_atom = s.fig.atoms[r, c]
            current_crest_spoke = current_crest_atom.crestSpoke
            current_crest_spoke_direction = current_crest_spoke.U

            current_crest_point = current_crest_atom.hub.P + epsilon * current_crest_spoke_direction
            current_crest_point_id = crest_points.InsertNextPoint(
                current_crest_point)
            line = vtk.vtkLine()
            if current_crest_point_id > 0:
                line = vtk.vtkLine()
                line.GetPointIds().SetId(0, current_crest_point_id - 1)
                line.GetPointIds().SetId(1, current_crest_point_id)
                crest_polys.InsertNextCell(line)
            crest_spoke_directions.InsertNextTuple(
                current_crest_spoke_direction)
            current_crest_spoke_length = current_crest_spoke.r
            crest_spoke_lengths.InsertNextTuple1(current_crest_spoke_length)

        # first column
        c = 0
        for r in range(nRows - 1, 0, -1):
            current_crest_atom = s.fig.atoms[r, c]
            current_crest_spoke = current_crest_atom.crestSpoke
            current_crest_spoke_direction = current_crest_spoke.U

            current_crest_point = current_crest_atom.hub.P + epsilon * current_crest_spoke_direction
            current_crest_point_id = crest_points.InsertNextPoint(
                current_crest_point)
            line = vtk.vtkLine()
            if current_crest_point_id > 0:
                line = vtk.vtkLine()
                line.GetPointIds().SetId(0, current_crest_point_id - 1)
                line.GetPointIds().SetId(1, current_crest_point_id)
                crest_polys.InsertNextCell(line)
            crest_spoke_directions.InsertNextTuple(
                current_crest_spoke_direction)
            current_crest_spoke_length = current_crest_spoke.r
            crest_spoke_lengths.InsertNextTuple1(current_crest_spoke_length)
        # to complete loop
        line = vtk.vtkLine()
        line.GetPointIds().SetId(0, current_crest_point_id)
        line.GetPointIds().SetId(1, 0)
        crest_polys.InsertNextCell(line)

        polyLine = vtk.vtkPolyLine()
        polyLine.GetPointIds().SetNumberOfIds(
            crest_points.GetNumberOfPoints() + 1)
        for i in range(crest_points.GetNumberOfPoints()):
            # polyLine->GetPointIds()->SetId(i, i);
            polyLine.GetPointIds().SetId(i, i)

        polyLine.GetPointIds().SetId(crest_points.GetNumberOfPoints(), 0)
        cells = vtk.vtkCellArray()
        cells.InsertNextCell(polyLine)

        crest_spokes_polydata.SetPoints(crest_points)
        crest_spokes_polydata.SetLines(cells)
        crest_spokes_polydata.GetPointData().AddArray(crest_spoke_directions)
        crest_spokes_polydata.GetPointData().SetActiveVectors("spokeDirection")
        crest_spokes_polydata.GetPointData().AddArray(crest_spoke_lengths)
        crest_spokes_polydata.GetPointData().SetActiveScalars("spokeLength")
        writer.SetFileName(outputCrest)
        writer.SetInputData(crest_spokes_polydata)
        writer.Update()

        up_spokes_polydata.SetPoints(medial_points)
        up_spokes_polydata.SetPolys(medial_polys)
        up_spokes_polydata.GetPointData().AddArray(up_spoke_directions)
        up_spokes_polydata.GetPointData().SetActiveVectors("spokeDirection")
        up_spokes_polydata.GetPointData().AddArray(up_spoke_lengths)
        up_spokes_polydata.GetPointData().SetActiveScalars("spokeLength")
        writer.SetFileName(outputUp)
        writer.SetInputData(up_spokes_polydata)
        writer.Update()

        down_spokes_polydata.SetPoints(medial_points)
        down_spokes_polydata.SetPolys(medial_polys)
        down_spokes_polydata.GetPointData().AddArray(down_spoke_directions)
        down_spokes_polydata.GetPointData().SetActiveVectors("spokeDirection")
        down_spokes_polydata.GetPointData().AddArray(down_spoke_lengths)
        down_spokes_polydata.GetPointData().SetActiveScalars("spokeLength")
        writer.SetFileName(outputDown)
        writer.SetInputData(down_spokes_polydata)
        writer.Update()

        print('Finished transformation and save to files:')
        print(outputUp)
        print(outputDown)
        print(outputCrest)
            elem.GetPointIds().SetId(3, nidMap[nodeIDs[1]])
            elem.GetPointIds().SetId(4, nidMap[nodeIDs[3]])
            elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]])
        else:
            elem = vtk.vtkTriangle()
            elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]])
            elem.GetPointIds().SetId(1, nidMap[nodeIDs[2]])
            elem.GetPointIds().SetId(2, nidMap[nodeIDs[4]])
            Triax6cell = grid.InsertNextCell(elem.GetCellType(),
                                             elem.GetPointIds())
            Color.InsertTuple1(Triax6cell, 4)

    elif (isinstance(element, CQUAD4) or isinstance(element, CSHEAR)
          or isinstance(element, CQUADR)):
        nodeIDs = element.nodeIDs()
        elem = vtk.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]])
        Quad4cell = grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())
        Color.InsertTuple1(Quad4cell, 4)

    elif isinstance(element, CQUAD8):
        nodeIDs = element.nodeIDs()
        if None not in nodeIDs:
            elem = vtk.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]])
예제 #21
0
def setup_renderers(renwin, fg_ren, bg_ren):
    """Utility method to configure foreground and background renderer
    and insert them into different layers of the renderenwinindow.

    Use this if you want an incredibly cool gradient background!
    """

    # bit of code thanks to
    # http://www.bioengineering-research.com/vtk/BackgroundGradient.tcl
    # had to change approach though to using background renderer,
    # else transparent objects don't appear, and adding flat
    # shaded objects breaks the background gradient.
    # =================================================================

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

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

    uc = vtk.vtkUnsignedCharArray()
    uc.SetNumberOfComponents(4)
    uc.SetNumberOfTuples(4)
    uc.SetTuple4(0, 128, 128, 128, 255)  # bottom left RGBA
    uc.SetTuple4(1, 128, 128, 128, 255)  # bottom right RGBA
    uc.SetTuple4(2, 255, 255, 255, 255)  # top right RGBA
    uc.SetTuple4(3, 255, 255, 255, 255)  # tob left RGBA

    dta = vtk.vtkPolyData()
    dta.Allocate(1, 1)
    dta.InsertNextCell(quad.GetCellType(), quad.GetPointIds())
    dta.SetPoints(qpts)
    dta.GetPointData().SetScalars(uc)

    coord = vtk.vtkCoordinate()
    coord.SetCoordinateSystemToNormalizedDisplay()

    mapper2d = vtk.vtkPolyDataMapper2D()
    mapper2d.SetInput(dta)
    mapper2d.SetTransformCoordinate(coord)

    actor2d = vtk.vtkActor2D()
    actor2d.SetMapper(mapper2d)
    actor2d.GetProperty().SetDisplayLocationToBackground()

    bg_ren.AddActor(actor2d)
    bg_ren.SetLayer(0)  # seems to be background
    bg_ren.SetInteractive(0)

    fg_ren.SetLayer(1)  # and foreground

    renwin.SetNumberOfLayers(2)
    renwin.AddRenderer(fg_ren)
    renwin.AddRenderer(bg_ren)
예제 #22
0
    def load_degen_geom_geometry(self, csv_filename, dirname,
                                 name='main', plot=True):# pragma: no cover
        #key = self.case_keys[self.icase]
        #case = self.result_cases[key]

        skip_reading = self._remove_old_adb_geometry(csv_filename)
        if skip_reading:
            return

        model = DegenGeom(log=self.log, debug=False)
        self.model_type = 'vspaero'
        #self.model_type = model.model_type
        model.read_degen_geom(csv_filename)
        for name, comps in sorted(model.components.items()):
            print('name = %r' % name)
            #print(comp)
            print('------------')
            for comp in comps:
                nodes = comp.xyz
                elements = comp.elements
                nnodes = nodes.shape[0]
                nelements = elements.shape[0]

        self.nNodes = nnodes
        self.nElements = nelements

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

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

        assert nodes is not None

        nid = 0
        #print("nxyz_nodes=%s" % nxyz_nodes)
        mmax = amax(nodes, axis=0)
        mmin = amin(nodes, axis=0)
        dim_max = (mmax - mmin).max()
        self.create_global_axes(dim_max)

        for i in range(nnodes):
            points.InsertPoint(nid, nodes[i, :])
            nid += 1
        #self.log.info('nxyz_nodes=%s nwake_nodes=%s total=%s' % (
            #nnodes, nwake_nodes, nxyz_nodes + nwake_nodes))
        #self.log.info('nxyz_elements=%s nwake_elements=%s total=%s' % (
            #nxyz_elements, nwake_elements, nxyz_elements + nwake_elements))

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

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

        # load results - regions/loads
        self.scalarBar.VisibilityOn()
        self.scalarBar.Modified()

        #mach = model.machs[0]
        #alpha = model.alphas[0]
        #beta = model.betas[0]
        #note = ':  Mach=%.2f, alpha=%.1f, beta=%.1f' % (mach, alpha, beta)
        note = 'name=%s' % name
        self.iSubcaseNameMap = {1: ['OpenVSP%s' % note, '']}
        cases = {}
        ID = 1

        form, cases = self._fill_degen_geom_case(cases, ID, model, nnodes, nelements)
        self._finish_results_io2(form, cases)
예제 #23
0
    def load_abaqus_geometry(self, abaqus_filename, dirname, name='main', plot=True):
        """loads abaqus input files into the gui"""
        skip_reading = self._remove_old_cart3d_geometry(abaqus_filename)
        if skip_reading:
            return

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

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

        n_cohax4 = 0
        n_cax3 = 0
        n_cax4r = 0

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

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

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

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

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


        self.nNodes = nnodes
        self.nElements = nelements

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        note = ''
        self.iSubcaseNameMap = {1: ['Abaqus%s' % note, '']}
        #form = []
        cases = {}
        ID = 1
        form, cases, icase = self._fill_abaqus_case(cases, ID, nodes, nelements, model)
        #self._fill_cart3d_results(cases, form, icase, ID, model)
        self._finish_results_io2(form, cases)
예제 #24
0
    def load_su2_geometry(self, su2_filename, name='main', plot=True):
        #print("load_su2_geometry...")
        skip_reading = self._remove_old_geometry(su2_filename)
        if skip_reading:
            return

        model = SU2(log=self.log, debug=False)
        #self.model_type = model.model_type
        ndim, nodes, elements, regions = model.read_su2(su2_filename)

        nnodes = nodes.shape[0]
        nelements = 0
        for etype, elems in iteritems(elements):
            nsub_elements = elems.shape[0]
            if nsub_elements:
                nelements += nsub_elements
                #print('min of type = %s' % elems.min())
        assert nnodes > 0, nnodes
        assert nelements > 0, nelements

        self.nnodes = nnodes
        self.nelements = nelements

        self.log.info('nnodes=%s nelements=%s' % (self.nnodes, self.nelements))
        self.grid.Allocate(self.nelements, 1000)

        self.nid_map = {}

        assert nodes is not None
        nnodes = nodes.shape[0]
        if ndim == 3:
            xmax, ymax, zmax = nodes.max(axis=0)
            xmin, ymin, zmin = nodes.min(axis=0)
            self.log.info('xmax=%s xmin=%s' % (xmax, xmin))
            self.log.info('ymax=%s ymin=%s' % (ymax, ymin))
            self.log.info('zmax=%s zmin=%s' % (zmax, zmin))
            dim_max = max(xmax - xmin, ymax - ymin, zmax - zmin)
        elif ndim == 2:
            xmax, ymax = nodes.max(axis=0)
            xmin, ymin = nodes.min(axis=0)
            self.log.info('xmax=%s xmin=%s' % (xmax, xmin))
            self.log.info('ymax=%s ymin=%s' % (ymax, ymin))
            dim_max = max(xmax - xmin, ymax - ymin)

        self.create_global_axes(dim_max)

        if ndim == 2:
            nodes = np.hstack(
                [nodes, np.zeros((nnodes, 1), dtype=nodes.dtype)])
        #else:
        # ndim=3

        points = numpy_to_vtk_points(nodes)

        #nelements = 0
        #elements = {
        #5 : tris,
        #9 : quads,
        #}
        #print('dict =', elements)
        for etype, elems in iteritems(elements):
            #print(etype, elems)
            if isinstance(elems, list):
                #print('continue')
                continue
            #print(type(elems))
            nsub_elements = elems.shape[0]
            if nsub_elements == 0:
                #print('continue')
                continue
            #print('eid_min =', elems.min())
            assert nsub_elements > 0, nsub_elements
            if etype == 5:
                for eid in range(nsub_elements):
                    elem = vtkTriangle()
                    node_ids = elems[eid, :]
                    elem.GetPointIds().SetId(0, node_ids[0])
                    elem.GetPointIds().SetId(1, node_ids[1])
                    elem.GetPointIds().SetId(2, node_ids[2])
                    self.grid.InsertNextCell(5, elem.GetPointIds(
                    ))  #elem.GetCellType() = 5  # vtkTriangle
            elif etype == 9:
                for eid in range(nsub_elements):
                    elem = vtk.vtkQuad()
                    node_ids = elems[eid, :]
                    elem.GetPointIds().SetId(0, node_ids[0])
                    elem.GetPointIds().SetId(1, node_ids[1])
                    elem.GetPointIds().SetId(2, node_ids[2])
                    elem.GetPointIds().SetId(3, node_ids[3])
                    self.grid.InsertNextCell(elem.GetCellType(),
                                             elem.GetPointIds())
            else:
                raise NotImplementedError(etype)

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

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

        cases = {}
        self.isubcase_name_map = {}
        ID = 1

        form, cases = self._fill_su2_case(cases, ID, nelements, nnodes)
        self._finish_results_io2(form, cases)
예제 #25
0
    def load_plot3d_geometry(self, p3d_filename, dirname, name='main'):
        print("load_plot3d_geometry")
        self.nid_map = {}

        #key = self.case_keys[self.icase]
        #case = self.result_cases[key]

        skip_reading = self.removeOldGeometry(p3d_filename)
        if skip_reading:
            return

        model = Plot3d(log=self.log, debug=self.debug)
        #self.model_type = model.model_type
        model.read_plot3d(p3d_filename)

        npoints = 0
        nelements = 0
        for iblock, shape in sorted(iteritems(model.block_shapes)):
            npoints += shape[0] * shape[1] * shape[2]
            nelements += (shape[0] - 1)  * (shape[1] - 1) * (shape[2] - 1)
        nblocks = iblock
        self.nNodes = npoints
        self.nElements = nelements


        #nodes, elements, regions = model.getPointsElementsRegions()
        #for nid,node in enumerate(nodes):
            #print "node[%s] = %s" %(nid,str(node))

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

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

        nid = 0
        nid_base = 0

        eid_base = 0

        elem = vtkQuad()
        quad_type = elem.GetCellType()
        #nblocks = len(model.x)
        for iblock in range(nblocks):
            print("iblock =", iblock)
            nid_base = nid
            x = model.x[iblock]
            y = model.y[iblock]
            z = model.z[iblock]
            print("x.shape[%s] =" % iblock, x.shape)
            print(x)
            (ni, nj, nk) = x.shape
            assert nk == 1
            for k in range(nk):
                for j in range(nj):
                    for i in range(ni):
                        points.InsertPoint(nid, x[i, j, 0],
                                                y[i, j, 0],
                                                z[i, j, 0])
                        nid += 1

            for j in range(nj - 1):
                jstart = nid_base + j * ni
                for i in range(ni - 1):
                    elem = vtkQuad()

                    p1 = jstart + (i)
                    p2 = jstart + (i + 1)
                    p3 = jstart + (ni) + (i + 1)
                    p4 = jstart + (ni) + (i)

                    elem.GetPointIds().SetId(0, p1)
                    elem.GetPointIds().SetId(1, p2)
                    elem.GetPointIds().SetId(2, p3)
                    elem.GetPointIds().SetId(3, p4)
                    element = [p1, p2, p3, p4]
                    self.grid.InsertNextCell(quad_type, elem.GetPointIds())
                    print(element)
                #jstart += ni

            #nid_base += ni * nj * nk
            eid_base += (ni-1) * (nj-1) * (nk-1)
            break

        #print("eid = ", eid)
        self.grid.SetPoints(points)
        #print dir(self.grid) #.SetNumberOfComponents(0)
        #self.grid.GetCellData().SetNumberOfTuples(1);
        #self.grid.GetCellData().SetScalars(self.gridResult)
        self.grid.Modified()
        self.grid.Update()
        print("updated grid")

        #return

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

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

        #cases = self._fill_stl_case(cases, ID, elements)
        #self.finish_io()
        self.result_cases = cases
        self.case_keys = sorted(cases.keys())
        #print "case_keys = ",self.case_keys
        #print "type(case_keys) = ",type(self.case_keys)
        self.ncases = min(0, len(self.result_cases) - 1)  # number of keys in dictionary
        self.icase = 0 if self.ncases == 0 else -1
        self.cycle_results()  # start at nCase=0
예제 #26
0
    def _make_tecplot_geometry(self, model, quads_only=False):
        nodes = model.xyz
        nnodes = self.nNodes

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

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

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

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

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

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

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

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

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

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

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

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

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

        self.grid.SetPoints(points)
        #self.grid.GetPointData().SetScalars(self.gridResult)
        #print(dir(self.grid) #.SetNumberOfComponents(0))
        #self.grid.GetCellData().SetNumberOfTuples(1);
        #self.grid.GetCellData().SetScalars(self.gridResult)
        self.grid.Modified()
        if hasattr(self.grid, 'Update'):
            self.grid.Update()
        return is_surface
예제 #27
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)
예제 #28
0
    def load_plot3d_geometry(self, p3d_filename, name='main'):
        print("load_plot3d_geometry")
        self.nid_map = {}

        #key = self.case_keys[self.icase]
        #case = self.result_cases[key]

        skip_reading = self._remove_old_geometry(p3d_filename)
        if skip_reading:
            return

        model = Plot3d(log=self.log, debug=self.debug)
        #self.model_type = model.model_type
        model.read_plot3d(p3d_filename)

        npoints = 0
        nelements = 0
        for iblock, shape in sorted(iteritems(model.block_shapes)):
            npoints += shape[0] * shape[1] * shape[2]
            nelements += (shape[0] - 1)  * (shape[1] - 1) * (shape[2] - 1)

        nblocks = len(model.block_shapes)
        self.nnodes = npoints
        self.nelements = nelements


        #nodes, elements, regions = model.getPointsElementsRegions()
        #for nid,node in enumerate(nodes):
            #print "node[%s] = %s" %(nid,str(node))

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

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

        nid = 0
        nid_base = 0

        eid_base = 0

        elem = vtkQuad()
        quad_type = elem.GetCellType()
        #nblocks = len(model.x)
        for iblock in range(nblocks):
            print("iblock =", iblock)
            nid_base = nid
            x = model.x[iblock]
            y = model.y[iblock]
            z = model.z[iblock]
            print("x.shape[%s] =" % iblock, x.shape)
            print(x)
            (ni, nj, nk) = x.shape
            assert nk == 1
            for k in range(nk):
                for j in range(nj):
                    for i in range(ni):
                        points.InsertPoint(
                            nid, x[i, j, 0], y[i, j, 0], z[i, j, 0])
                        nid += 1

            for j in range(nj - 1):
                jstart = nid_base + j * ni
                for i in range(ni - 1):
                    elem = vtkQuad()

                    p1 = jstart + (i)
                    p2 = jstart + (i + 1)
                    p3 = jstart + (ni) + (i + 1)
                    p4 = jstart + (ni) + (i)

                    elem.GetPointIds().SetId(0, p1)
                    elem.GetPointIds().SetId(1, p2)
                    elem.GetPointIds().SetId(2, p3)
                    elem.GetPointIds().SetId(3, p4)
                    element = [p1, p2, p3, p4]
                    self.grid.InsertNextCell(quad_type, elem.GetPointIds())
                    print(element)
                #jstart += ni

            #nid_base += ni * nj * nk
            eid_base += (ni-1) * (nj-1) * (nk-1)
            break

        #print("eid = ", eid)
        self.grid.SetPoints(points)
        #print dir(self.grid) #.SetNumberOfComponents(0)
        #self.grid.GetCellData().SetNumberOfTuples(1);
        #self.grid.GetCellData().SetScalars(self.gridResult)
        self.grid.Modified()
        self.grid.Update()
        self.log_info("updated grid")

        #return

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

        self.isubcase_name_map = {1: ['Plot3d', '']}
        cases = {}
        ID = 1

        #cases = self._fill_stl_case(cases, ID, elements)
        #self.finish_io()
        self.result_cases = cases
        self.case_keys = sorted(cases.keys())
        #print "case_keys = ",self.case_keys
        #print "type(case_keys) = ",type(self.case_keys)
        self.ncases = min(0, len(self.result_cases) - 1)  # number of keys in dictionary
        self.icase = 0 if self.ncases == 0 else -1
        self.cycle_results()  # start at ncase=0
예제 #29
0
    def _make_tecplot_geometry(self, model, quads_only=False):
        nodes = model.xyz
        nnodes = self.nNodes

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

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

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

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

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

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

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

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


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

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

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

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

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

        self.grid.SetPoints(points)
        #self.grid.GetPointData().SetScalars(self.gridResult)
        #print(dir(self.grid) #.SetNumberOfComponents(0))
        #self.grid.GetCellData().SetNumberOfTuples(1);
        #self.grid.GetCellData().SetScalars(self.gridResult)
        self.grid.Modified()
        if hasattr(self.grid, 'Update'):
            self.grid.Update()
        return is_surface
예제 #30
0
def find_2d_intersected_cells(intersecting_planes, parent_bit_mask, parent_id, origin, \
                              spacing, ndims, chunk_info, grid_desc):
  append = vtk.vtkAppendFilter()
  append.MergePointsOn()
  a1 = spacing[0]/2.0
  a2 = spacing[1]/2.0
  index = 1
  for j in range(ndims[1]-1):
    p2 = a2 + origin[1] + j*spacing[1]
    for i in range(ndims[0]-1):
      p1 = a1 + origin[0] + i*spacing[0]
      for plane in intersecting_planes:
        n1 = plane["nx"]
        n2 = plane["ny"]
        n3 = plane["nz"]
        p01 = plane["px"]
        p02 = plane["py"]
        p03 = plane["pz"]
        d = math.fabs(n1*(p1-p01) + n2*(p2-p02) + n3*(-p03))
        rhs = a1*math.fabs(n1) + a2*math.fabs(n2)
        if d < rhs or math.fabs(d-rhs) < 0.000001:
          ug = vtk.vtkUnstructuredGrid()

          points = vtk.vtkPoints()
          for pj in range(2):
            j_offset = pj*spacing[1]
            for pi in range(2):
              points.InsertNextPoint(p1 - a1 + pi*spacing[0], \
                                     p2 - a2 + j_offset, \
                                     0.0)

          ug.SetPoints(points)

          quad = vtk.vtkQuad()

          quad.GetPointIds().SetId(0, 0)
          quad.GetPointIds().SetId(1, 1)
          quad.GetPointIds().SetId(2, 3)
          quad.GetPointIds().SetId(3, 2)
       
          ug.InsertNextCell(quad.GetCellType(), quad.GetPointIds())

          gids = vtk.vtkIdTypeArray()
          gids.SetName("GlobalIds")
          if parent_id == 0:
            Dx = grid_desc["create_grid"][1]["Cx"]
            xc = range(chunk_info["x"][0], chunk_info["x"][1]+1)
            yc = range(chunk_info["y"][0], chunk_info["y"][1]+1)
            yindex = (yc[j]-1)*Dx
            gids.InsertNextTuple1(xc[i]+yindex)
          else:
            if parent_bit_mask == -1:
              gids.InsertNextTuple1(parent_id)
            else:
              gids.InsertNextTuple1(index*(2**parent_bit_mask) + parent_id)

          ug.GetCellData().AddArray(gids)
          ug.GetCellData().SetActiveGlobalIds("GlobalIds")

          append.AddInputData(ug)
          break
      index += 1
  if append.GetInputList().GetNumberOfItems():
    append.Update()
    return append.GetOutput()
  else:
    return None
예제 #31
0
    def load_shabp_geometry(self, shabpFilename, dirname, name='main', plot=True):
        self.nid_map = {}

        #key = self.case_keys[self.icase]
        #case = self.result_cases[key]

        skip_reading = self.removeOldGeometry(shabpFilename)
        if skip_reading:
            return

        self.model = SHABP(log=self.log, debug=self.debug)
        self.model_type = 'shabp' # model.model_type
        self.model.read_shabp(shabpFilename)

        nodes, elements, patches, components, impact, shadow = self.model.getPointsElementsRegions()
        #for nid,node in enumerate(nodes):
            #print "node[%s] = %s" %(nid,str(node))

        self.nNodes = len(nodes)
        self.nElements = len(elements)

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

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

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

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

        assert len(nodes) > 0
        mmax = amax(nodes, axis=0)
        mmin = amin(nodes, axis=0)
        dim_max = (mmax - mmin).max()
        self.create_global_axes(dim_max)
        for nid, node in enumerate(nodes):
            points.InsertPoint(nid, *node)

        assert len(elements) > 0
        for eid, element in enumerate(elements):
            (p1, p2, p3, p4) = element
            #print "element = ",element
            elem = vtkQuad()
            elem.GetPointIds().SetId(0, p1)
            elem.GetPointIds().SetId(1, p2)
            elem.GetPointIds().SetId(2, p3)
            elem.GetPointIds().SetId(3, p4)
            self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())

        #print("eid = ", eid)
        self.grid.SetPoints(points)
        #self.grid.GetPointData().SetScalars(self.gridResult)
        #print dir(self.grid) #.SetNumberOfComponents(0)
        #self.grid.GetCellData().SetNumberOfTuples(1);
        #self.grid.GetCellData().SetScalars(self.gridResult)
        self.grid.Modified()
        if hasattr(self.grid, 'Update'):
            self.grid.Update()

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

        self.iSubcaseNameMap = {1: ['S/HABP', '']}
        cases = {}
        ID = 1

        self.log.debug("nNodes=%i nElements=%i" % (self.nNodes, self.nElements))
        form, cases = self._fill_shabp_geometry_case(cases, ID, nodes, elements, patches, components, impact, shadow)
        self._finish_results_io2(form, cases)
예제 #32
0
    def load_panair_geometry(self, panairFileName, dirname):
        self.nidMap = {}

        #key = self.caseKeys[self.iCase]
        #case = self.resultCases[key]

        skipReading = self.removeOldGeometry(panairFileName)
        if skipReading:
            return

        model = PanairGrid(panairFileName, log=self.log, debug=self.debug)
        self.modelType = model.modelType
        model.read_panair()

        nodes, elements, regions = model.getPointsElementsRegions()
        #for nid,node in enumerate(nodes):
        #print "node[%s] = %s" %(nid,str(node))

        self.nNodes = len(nodes)
        self.nElements = len(elements)

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

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

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

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

        for nid, node in enumerate(nodes):
            points.InsertPoint(nid, *node)
        #print "nid = ",nid

        for eid, element in enumerate(elements):
            (p1, p2, p3, p4) = element
            #print "element = ",element
            elem = vtkQuad()
            elem.GetPointIds().SetId(0, p1)
            elem.GetPointIds().SetId(1, p2)
            elem.GetPointIds().SetId(2, p3)
            elem.GetPointIds().SetId(3, p4)
            self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())

        print("eid = ", eid)
        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")

        #return

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

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

        #print "nElements = ",nElements
        loads = []
        cases = self.fillPanairGeometryCase(cases, ID, nodes, elements,
                                            regions, loads)

        self.resultCases = cases
        self.caseKeys = sorted(cases.keys())
        print "caseKeys = ", self.caseKeys
        #print "type(caseKeys) = ",type(self.caseKeys)
        self.iCase = -1
        self.nCases = len(
            self.resultCases)  #- 1  # number of keys in dictionary
        if self.nCases > 1:
            self.nCases -= 1
        self.cycleResults()  # start at nCase=0
예제 #33
0
파일: wgs_io.py 프로젝트: hurlei/pyNastran
    def load_lawgs_geometry(self, lawgsFileName, dirname, name='main', plot=True):
        #key = self.case_keys[self.icase]
        #case = self.result_cases[key]

        skip_reading = self._remove_old_geometry(lawgsFileName)
        if skip_reading:
            return

        model = LaWGS(lawgsFileName)
        self.model_type = model.model_type
        model.readLaWGS()

        nodes, elements, regions = model.get_points_elements_regions()
        self.nNodes = len(nodes)
        self.nElements = len(elements)

        nodes = array(nodes, dtype='float32')
        elements = array(elements, dtype='int32')

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

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

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

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

        assert len(nodes) > 0, len(nodes)
        assert len(elements) > 0, len(elements)
        for nid, node in enumerate(nodes):
            points.InsertPoint(nid, *node)

        elem = vtkQuad()
        etype = elem.GetCellType()
        for eid, element in enumerate(elements):
            (p1, p2, p3, p4) = element
            elem = vtkQuad()
            pts = elem.GetPointIds()
            pts.SetId(0, p1)
            pts.SetId(1, p2)
            pts.SetId(2, p3)
            pts.SetId(3, p4)
            self.grid.InsertNextCell(etype, elem.GetPointIds())

        self.grid.SetPoints(points)
        #self.grid.GetPointData().SetScalars(self.gridResult)
        #print(dir(self.grid) #.SetNumberOfComponents(0))
        #self.grid.GetCellData().SetNumberOfTuples(1);
        #self.grid.GetCellData().SetScalars(self.gridResult)
        self.grid.Modified()
        if hasattr(self.grid, 'Update'):
            self.grid.Update()

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

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

        #print("nElements = %s" % nElements)
        form, cases = self._fill_lawgs_case(cases, ID, nodes, elements, regions)
        self._finish_results_io2(form, cases)
예제 #34
0
    def _make_tecplot_geometry(self, model, quads_only=False):
        nodes = model.xyz
        nnodes = self.nnodes
        grid = self.grid

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

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

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

        points = numpy_to_vtk_points(nodes)
        #for i in range(nnodes):
            #points.InsertPoint(i, nodes[i, :])

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

        nquads = len(quads)
        ntris = len(tris)
        nhexas = len(hexas)
        ntets = len(tets)

        nshells = nquads + ntris
        nsolids = ntets + nhexas
        if nshells:
            is_surface = True
            self._create_tecplot_shells(nquads, quads, ntris, tris)
            self.nelements = nshells

        elif nsolids:
            #if 0:
                #tris, quads = model.skin_elements()
                #is_tris = bool(len(tris))
                #is_quads = bool(len(quads))
                #self._create_tecplot_shells(is_quads, quads, is_tris, tris)
            #else:
            is_surface = False
            if is_surface:
                if nhexas:
                    free_faces = array(model.get_free_faces(), dtype='int32')# + 1
                    nfaces = len(free_faces)
                    self.nelements = nfaces
                    elements = free_faces
                    grid.Allocate(nfaces, 1000)

                    for face in free_faces:
                        elem = vtkQuad()
                        epoints = elem.GetPointIds()
                        epoints.SetId(0, face[0])
                        epoints.SetId(1, face[1])
                        epoints.SetId(2, face[2])
                        epoints.SetId(3, face[3])
                        #elem.GetCellType() = 5  # vtkTriangle
                        grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())
            else:
                # is_volume
                grid.Allocate(nsolids, 1000)
                self.nelements = nsolids
                if ntets:
                    for node_ids in tets:
                        elem = vtkTetra()
                        epoints = elem.GetPointIds()
                        epoints.SetId(0, node_ids[0])
                        epoints.SetId(1, node_ids[1])
                        epoints.SetId(2, node_ids[2])
                        epoints.SetId(3, node_ids[3])
                        #elem.GetCellType() = 5  # vtkTriangle
                        grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())


                if nhexas:
                    for node_ids in hexas:
                        elem = vtkHexahedron()
                        epoints = elem.GetPointIds()
                        epoints.SetId(0, node_ids[0])
                        epoints.SetId(1, node_ids[1])
                        epoints.SetId(2, node_ids[2])
                        epoints.SetId(3, node_ids[3])
                        epoints.SetId(4, node_ids[4])
                        epoints.SetId(5, node_ids[5])
                        epoints.SetId(6, node_ids[6])
                        epoints.SetId(7, node_ids[7])
                        #elem.GetCellType() = 5  # vtkTriangle
                        grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())
        else:
            raise NotImplementedError()

        grid.SetPoints(points)
        grid.Modified()
        if hasattr(grid, 'Update'):
            grid.Update()
        return is_surface
def writeLegacyVTK():
    # This is where the data is for testing purposes.
    print "Current working directory:", os.getcwd()
    
    if os.path.isdir("vtk") == False:
        os.makedirs("vtk")
        print "Cretated vtk output directory..."
    
    if os.path.isdir("files") == False:
        os.makedirs("files")
        print "Created files ouptut directory..."
        

    # Working with the task mesh.
    taskMeshReader = vtk.vtkXMLPolyDataReader()
    taskMeshReader.SetFileName(meshSet[0])
    taskMeshReader.Update()

    taskMesh = taskMeshReader.GetOutput()

    # Get the range of branch labels.
    labelRange = [0, 0]
    taskMesh.GetCellData().GetScalars().GetRange(labelRange, 0)

    # Convert label range to a list of labels.
    labelRange = range(int(labelRange[0]), int(labelRange[1]) + 1)
    print "Labels found in task mesh:", labelRange


    # Store the number of rings for each label. 
    numRingsPerLabel = {}

    # For every label in the range of labels we want to extract all cells/quads.
    for label in labelRange:
        # Use this filter to extract the cells for a given label value.
        branchSelector = vtk.vtkThreshold()
        branchSelector.SetInputData(taskMesh)
        branchSelector.ThresholdBetween(label,label);
        branchSelector.Update()

        taskMeshBranch = branchSelector.GetOutput()

        # New vtkPoints for storing reordered points.
        reorderedPoints = vtk.vtkPoints()

        # New vtkCellArray for storing reordeced cells.
        reorderedCellArray = vtk.vtkCellArray()
        numQuadRowsPerBranch = taskMeshBranch.GetNumberOfCells() / numQuadsPerRing;
        numRingsPerLabel[label] = numQuadRowsPerBranch
        ringIds = range(0, numQuadRowsPerBranch);

        # Working with rows in reverse order: UPSTREAM.
        ringIds.reverse()


        rowBase = 0
        # Iterate over the rings in reverse order.
        for ringNum in ringIds:
            # Iterate over the cells in normal order.
            for cellNum in range(0, numQuadsPerRing):
                # Calculate the 'real' cell id and get the corresponding cell.
                cellId = ringNum * numQuadsPerRing + cellNum
                cell = taskMeshBranch.GetCell(cellId)

                # The ids to be written to the TXT file.
                pointIdList = [cell.GetNumberOfPoints()]

                # Write the appropriate points to TXT file.
                for pPos in range(0, cell.GetNumberOfPoints()):
                    newPoint = False
                    if ringNum == ringIds[0]:
                        if cellNum == 0:
                            newPoint = True
                        elif pPos == 1 or pPos == 2:
                            newPoint = True
                    else:
                        if cellNum == 0:
                            if pPos == 0 or pPos == 1:
                                newPoint = True
                        else:
                            if pPos == 1:
                                newPoint = True

                    if newPoint == True:

                        # Inserting a new point...
                        point = taskMeshBranch.GetPoint(cell.GetPointId(pPos))
                        # ... with a new id.
                        newId = reorderedPoints.InsertNextPoint(point)
                        pointIdList.append(newId)

                        # To make it easier for remembering the number of points instered in a row.
                        if cellNum == 0 and pPos == 0:
                            rowBasePrev = newId
                    else:
                        # Perhaps this can be done in a nicer way.
                        # Calculate the id of a previously inserted point.
                        if ringNum == ringIds[0]:
                            if cellNum == 1:
                                if pPos == 0:
                                    pointIdList.append(1L)
                                elif pPos == 3:
                                    pointIdList.append(2L)
                            else:
                                if pPos == 0:
                                    pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 2))
                                elif pPos == 3:
                                    pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 3))
                        elif ringNum == ringIds[1]:
                            if cellNum == 0:
                                if pPos == 2:
                                    pointIdList.append(1L)
                                elif pPos == 3:
                                    pointIdList.append(0L)
                            else:
                                if pPos == 0:
                                    pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 1))
                                elif pPos == 2:
                                    pointIdList.append(long(cellNum * 2 + 2))
                                elif pPos == 3:
                                    if cellNum == 1:
                                        pointIdList.append(1L)
                                    else:
                                        pointIdList.append(long(cellNum * 2))
                        else:
                            if cellNum == 0:
                                if pPos == 2:
                                    pointIdList.append(long(rowBase + 1))
                                elif pPos == 3:
                                    pointIdList.append(long(rowBase))
                            else:
                                if pPos == 0:
                                    pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 1))
                                elif pPos == 2:
                                    pointIdList.append(long(rowBase + cellNum + 1))
                                elif pPos == 3:
                                    pointIdList.append(long(rowBase + cellNum))

                # print pointIdList, rowBase

                # Insert the ids into the cell array.
                newCell = vtk.vtkQuad()
                newCell.GetPointIds().Reset()
                for id in pointIdList[1:]:
                    newCell.GetPointIds().InsertNextId(id)
                reorderedCellArray.InsertNextCell(newCell)

            rowBase = rowBasePrev

        # print '\n'
        print "Inserted", reorderedPoints.GetNumberOfPoints(), "task mesh points for label", label, "..."
        print "Inserted", reorderedCellArray.GetNumberOfCells(), "task mesh cells for label", label, "..."

        # Create new vtkPolyData object for the new reordered mesh.
        reorderedTaskMeshBranch = vtk.vtkPolyData()

        # Put the reordered points and cells into the reordered mesh.
        reorderedTaskMeshBranch.SetPoints(reorderedPoints)
        reorderedTaskMeshBranch.SetPolys(reorderedCellArray)

        # Write the VTK file.
        reorderedMeshWriter = vtk.vtkXMLPolyDataWriter()
        reorderedMeshWriter.SetInputData(reorderedTaskMeshBranch)
        reorderedMeshWriter.SetFileName(taskVTKFiles[label])
        reorderedMeshWriter.Update()

    print "Rings per label:", numRingsPerLabel, "..."
    ringsPerLabelVals = numRingsPerLabel.values()

    # Check all rings per label values are the same.
    assert ringsPerLabelVals[1:] == ringsPerLabelVals[:-1], "All values of rings per label must be identical. Generated output is invalid ..."

    # Working with EC mesh.

    ecMeshReader = vtk.vtkXMLPolyDataReader()
    ecMeshReader.SetFileName(meshSet[1])
    ecMeshReader.Update()

    # Original ECs mesh to work with.
    ecMesh = ecMeshReader.GetOutput()
    print "There are", ecMesh.GetNumberOfCells(), "ECs in total ..."

    # For every label in the range of labels we want to extract all ECs.
    for label in labelRange:

        # Keep track of how many branches we need to skip.
        numECsPerLabel = numQuadsPerRing * numRingsPerLabel[label] * numECsPerQuad
        ecCellOffset = label * numECsPerLabel

        print "ecCellOffset", ecCellOffset

        # Collect cell ids to select.
        selectionIds = vtk.vtkIdTypeArray()
        for sId in range(0, numECsPerLabel):
            selectionIds.InsertNextValue(ecCellOffset + sId)

        # Create selecion node.
        selectionNode = vtk.vtkSelectionNode()
        selectionNode.SetFieldType(selectionNode.CELL)
        selectionNode.SetContentType(selectionNode.INDICES)
        selectionNode.SetSelectionList(selectionIds)

        # Create selection.
        selection = vtk.vtkSelection()
        selection.AddNode(selectionNode)

        # Use vtkSelection filter.
        selectionExtractor = vtk.vtkExtractSelection()
        selectionExtractor.SetInputData(0, ecMesh)
        selectionExtractor.SetInputData(1, selection)
        selectionExtractor.Update()

        extractedECs = selectionExtractor.GetOutput()

        # Ring ids list for traversal.
        ringIds = range(0, numRingsPerLabel[label])
        ringIds.reverse()

        # Number of ECs rows is the number of ECs per quad.
        rowIds = range(0, numECsPerCol)
        rowIds.reverse()

        # The ECs are organised in rings of blocks of cells.
        # New vtkCellArray for storing reordeced cells.
        reorderedCellArray = vtk.vtkCellArray()

        # Iterate over the rings in reverse order.
        for ringNum in ringIds:
            # Iterate over the 'imaginary' quads of cells in normal order.
            for quadNum in range(0, numQuadsPerRing):
                # Iterate over the rows of cells in reverse order.
                # Calculate the 'real' id for the 'imaginary' quad.
                quadId = ringNum * numQuadsPerRing + quadNum
                # Iterate over rows of cells in reverse order.
                for rowNum in rowIds:
                    # Iterate over the rows of cells in normal order.
                    for ecNum in range(0, numECsPerRow):
                        # Calculate the 'real' ec cell id and get the corresponding cell.
                        ecId = quadId * numECsPerQuad + rowNum * numECsPerRow + ecNum
                        ecCell = extractedECs.GetCell(ecId)
                        reorderedCellArray.InsertNextCell(ecCell)

        # Create new vtkPolyData object for the new reordered mesh.
        reorderedECMeshBranch = vtk.vtkPolyData()

        # Insert our new points.
        reorderedECMeshBranch.SetPoints(extractedECs.GetPoints())

        # Set the reordered cells to the reordered ECs mesh.
        reorderedECMeshBranch.SetPolys(reorderedCellArray)

        # New vtkPoints for storing reordered points.
        reorderedPoints = vtk.vtkPoints()

        # New vtkCellArray for storing reordeced cells.
        reorderedCellArray = vtk.vtkCellArray()

        rowBase = 0
        # Iterate over quads in normal order because they have been reordered.
        for quadNum in range(0, numRingsPerLabel[label] * numQuadsPerRing):
            # Iterate over rows in normal order because they have been reordered.
            for rowNum in range(0, numECsPerCol):
                # Iterate over the ECs in the row in normal order.
                for ecNum in range(0, numECsPerRow):
                    # Calculate the 'real' ec cell id and get the corresponding cell.
                    ecId = quadNum * numECsPerQuad + rowNum * numECsPerRow + ecNum
                    ecCell = reorderedECMeshBranch.GetCell(ecId)

                    # The ids to be written to the TXT file.
                    pointIdList = [ecCell.GetNumberOfPoints()]

                    # Write the appropriate points to the TXT file.
                    for pPos in range(0, ecCell.GetNumberOfPoints()):
                        newPoint = False
                        if rowNum == 0:
                            if ecNum == 0:
                                newPoint = True
                            elif pPos == 1 or pPos == 2:
                                newPoint = True
                        else:
                            if ecNum == 0:
                                if pPos == 0 or pPos == 1:
                                    newPoint = True
                            else:
                                if pPos == 1:
                                    newPoint = True

                        if newPoint == True:

                            # Inserting a new point...
                            point = reorderedECMeshBranch.GetPoint(ecCell.GetPointId(pPos))
                            # ... with a new id.
                            newId = reorderedPoints.InsertNextPoint(point)
                            pointIdList.append(newId)


                            if ecNum == 0 and pPos == 0:
                                rowBasePrev = newId
                        else:
                            # Perhaps this can be done in a nicer way.
                            # Calculate the ide of a previously inserted point.
                            if rowNum == 0:
                                if ecNum == 1:
                                    if pPos == 0:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 3))
                                    elif pPos == 3:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 4))
                                else:
                                    if pPos == 0:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 2))
                                    elif pPos == 3:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 3))
                            elif rowNum == 1:
                                if ecNum == 0:
                                    if pPos == 2:
                                        pointIdList.append(long(rowBase + 1))
                                    elif pPos == 3:
                                        pointIdList.append(long(rowBase))
                                else:
                                    if pPos == 0:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 1))
                                    elif pPos == 2:
                                        pointIdList.append(long(rowBase + ecNum * 2 + 2))
                                    elif pPos == 3:
                                        if ecNum == 1:
                                            pointIdList.append(long(rowBase + 1))
                                        else:
                                            pointIdList.append(long(rowBase + ecNum * 2))
                            else:
                                if ecNum == 0:
                                    if pPos == 2:
                                        pointIdList.append(long(rowBase + 1))
                                    elif pPos == 3:
                                        pointIdList.append(long(rowBase))
                                else:
                                    if pPos == 0:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 1))
                                    elif pPos == 2:
                                        pointIdList.append(long(rowBase + ecNum + 1))
                                    elif pPos == 3:
                                        pointIdList.append(long(rowBase + ecNum))

                    # print pointIdList, rowBase

                    # Insert the ids into the cell array.
                    newCell = vtk.vtkQuad()
                    newCell.GetPointIds().Reset()
                    for id in pointIdList[1:]:
                        newCell.GetPointIds().InsertNextId(id)
                    reorderedCellArray.InsertNextCell(newCell)

                rowBase = rowBasePrev

        # print '\n'
        print "There are", reorderedPoints.GetNumberOfPoints(), "ECs points for label", label, "..."
        print "There are", reorderedCellArray.GetNumberOfCells(), "ECs cells for label", label, "..."

        # Create new vtkPolyData object for the new reordered mesh.
        reorderedECs = vtk.vtkPolyData()

        # Put the reordered points and cells into the mesh.
        reorderedECs.SetPoints(reorderedPoints)
        reorderedECs.SetPolys(reorderedCellArray)

        # Write the VTK EC mesh file.
        reorderedMeshWriter = vtk.vtkXMLPolyDataWriter()
        reorderedMeshWriter.SetInputData(reorderedECs)
        reorderedMeshWriter.SetFileName(ecVTKFiles[label])
        reorderedMeshWriter.Update()

        # Use VTK centroid filter to get the centroids in the right order
        # from the reorderedECMeshBranch.
        centroidFilter = vtk.vtkCellCenters()
        centroidFilter.SetInputData(reorderedECs)
        centroidFilter.Update()

        # Create a vertex cell for each point.
        pointsToVerticesFilter = vtk.vtkVertexGlyphFilter()
        pointsToVerticesFilter.SetInputData(centroidFilter.GetOutput())
        pointsToVerticesFilter.Update()

        reorderedCentroidBranch = pointsToVerticesFilter.GetOutput()

        # Write the VTK EC centrouid file.
        centroidWriter = vtk.vtkXMLPolyDataWriter()
        centroidWriter.SetInputData(reorderedCentroidBranch)
        centroidWriter.SetFileName(ecCentroidVTKFiles[label])
        centroidWriter.Update()

        # Write the centroids to the TXT points and cells files.
        for cId in range(0, reorderedCentroidBranch.GetNumberOfCells()):
            centCell = reorderedCentroidBranch.GetCell(cId)
            centIds = [centCell.GetNumberOfPoints()]

            # Write centroid ids.
            ptId = centCell.GetPointId(0)
            centIds.append(ptId)

            # Write centroid points.
            point = reorderedCentroidBranch.GetPoint(ptId)




    # Working with SMC mesh.
    # Working with SMC mesh.
    # Working with SMC mesh.
    smcMeshReader = vtk.vtkXMLPolyDataReader()
    smcMeshReader.SetFileName(meshSet[2])
    smcMeshReader.Update()

    # Original SMCs mesh to work with.
    smcMesh = smcMeshReader.GetOutput()
    print "There are", smcMesh.GetNumberOfCells(), "SMCs in total ..."

    # For every label in the range of labels we want to extract all SMCs.
    for label in labelRange:

        # Keep track of how many branches we need to skip.
        numSMCsPerLabel = numQuadsPerRing * numRingsPerLabel[label] * numSMCsPerQuad
        smcCellOffset = label * numSMCsPerLabel

        print "smcCellOffset", smcCellOffset

        # Collect cell ids to select.
        selectionIds = vtk.vtkIdTypeArray()
        for sId in range(0, numSMCsPerLabel):
            selectionIds.InsertNextValue(smcCellOffset + sId)

        # Create selecion node.
        selectionNode = vtk.vtkSelectionNode()
        selectionNode.SetFieldType(selectionNode.CELL)
        selectionNode.SetContentType(selectionNode.INDICES)
        selectionNode.SetSelectionList(selectionIds)

        # Create selection.
        selection = vtk.vtkSelection()
        selection.AddNode(selectionNode)

        # Use vtkSelection filter.
        selectionExtractor = vtk.vtkExtractSelection()
        selectionExtractor.SetInputData(0, smcMesh)
        selectionExtractor.SetInputData(1, selection)
        selectionExtractor.Update()

        extractedSMCs = selectionExtractor.GetOutput()

        # Ring ids list for traversal.
        ringIds = range(0, numRingsPerLabel[label])
        ringIds.reverse()

        # Number of SMCs rows is the number of ECs per quad times 13.
        rowIds = range(0, numSMCsPerCol)
        rowIds.reverse()

        # The SMCs are organised in rings of blocks of cells.
        # New vtkCellArray for storing reordeced cells.
        reorderedCellArray = vtk.vtkCellArray()

        # Iterate over the rings in reverse order.
        for ringNum in ringIds:
            # Iterate over the 'imaginary' quads of cells in normal order.
            for quadNum in range(0, numQuadsPerRing):
                # Iterate over the rows of cells in reverse order.
                # Calculate the 'real' id for the 'imaginary' quad.
                quadId = ringNum * numQuadsPerRing + quadNum
                # Iterate over rows of cells in reverse order.
                for rowNum in rowIds:
                    # Iterate over the rows of cells in normal order.
                    for smcNum in range(0, numSMCsPerRow):
                        # Calculate the 'real' smc cell id and get the corresponding cell.
                        smcId = quadId * numSMCsPerQuad + rowNum * numSMCsPerRow + smcNum
                        smcCell = extractedSMCs.GetCell(smcId)
                        reorderedCellArray.InsertNextCell(smcCell)

        # Create new vtkPolyData object for the new reordered mesh.
        reorderedSMCMeshBranch = vtk.vtkPolyData()

        # Insert our new points.
        reorderedSMCMeshBranch.SetPoints(extractedSMCs.GetPoints())

        # Set the reordered cells to the reordered SMCs mesh.
        reorderedSMCMeshBranch.SetPolys(reorderedCellArray)

        # New vtkPoints for storing reordered points.
        reorderedPoints = vtk.vtkPoints()

        # New vtkCellArray for storing reordeced cells.
        reorderedCellArray = vtk.vtkCellArray()

        rowBase = 0
        # Iterate over quads in normal order because they have been reordered.
        for quadNum in range(0, numRingsPerLabel[label] * numQuadsPerRing):
            # Iterate over rows in normal order because they have been reordered.
            for rowNum in range(0, numSMCsPerCol):
                # Iterate over the SMCs in the row in normal order.
                for smcNum in range(0, numSMCsPerRow):
                    # Calculate the 'real' smc cell id and get the corresponding cell.
                    smcId = quadNum * numSMCsPerQuad + rowNum * numSMCsPerRow + smcNum
                    smcCell = reorderedSMCMeshBranch.GetCell(smcId)

                    # The ids to be written to the TXT file.
                    pointIdList = [smcCell.GetNumberOfPoints()]

                    # Write the appropriate points to the TXT file.
                    for pPos in range(0, smcCell.GetNumberOfPoints()):
                        newPoint = False
                        if rowNum == 0:
                            if smcNum == 0:
                                newPoint = True
                            elif pPos == 1 or pPos == 2:
                                newPoint = True
                        else:
                            if smcNum == 0:
                                if pPos == 0 or pPos == 1:
                                    newPoint = True
                            else:
                                if pPos == 1:
                                    newPoint = True
                        if newPoint == True:

                            # Inserting a new point...
                            point = reorderedSMCMeshBranch.GetPoint(smcCell.GetPointId(pPos))
                            # with a new id.
                            newId = reorderedPoints.InsertNextPoint(point)
                            pointIdList.append(newId)

                            if smcNum == 0 and pPos == 0:
                                rowBasePrev = newId
                        else:
                            # Perhaps this can be done in a nicer way.
                            # Calculate the ide of a previously inserted point.
                            if rowNum == 0:
                                if smcNum == 1:
                                    if pPos == 0:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 3))
                                    elif pPos == 3:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 4))
                                else:
                                    if pPos == 0:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 2))
                                    elif pPos == 3:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 3))
                            elif rowNum == 1:
                                if smcNum == 0:
                                    if pPos == 2:
                                        pointIdList.append(long(rowBase + 1))
                                    elif pPos == 3:
                                        pointIdList.append(long(rowBase))
                                else:
                                    if pPos == 0:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 1))
                                    elif pPos == 2:
                                        pointIdList.append(long(rowBase + smcNum * 2 + 2))
                                    elif pPos == 3:
                                        if smcNum == 1:
                                            pointIdList.append(long(rowBase + 1))
                                        else:
                                            pointIdList.append(long(rowBase + smcNum * 2))
                            else:
                                if smcNum == 0:
                                    if pPos == 2:
                                        pointIdList.append(long(rowBase + 1))
                                    elif pPos == 3:
                                        pointIdList.append(long(rowBase))
                                else:
                                    if pPos == 0:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 1))
                                    elif pPos == 2:
                                        pointIdList.append(long(rowBase + smcNum + 1))
                                    elif pPos == 3:
                                        pointIdList.append(long(rowBase + smcNum))

                    # print pointIdList, rowBase

                    # Insert the ids into the cell array.
                    newCell = vtk.vtkQuad()
                    newCell.GetPointIds().Reset()
                    for id in pointIdList[1:]:
                        newCell.GetPointIds().InsertNextId(id)
                    reorderedCellArray.InsertNextCell(newCell)

                rowBase = rowBasePrev

        # print '\n'
        print "There are", reorderedPoints.GetNumberOfPoints(), "SMCs points for label", label, "..."
        print "There are", reorderedCellArray.GetNumberOfCells(), "SMCs cells for label", label, "..."

        # Create new vtkPolyData object for the new reordered mesh.
        reorderedSMCs = vtk.vtkPolyData()

        # Put the reordered points and cells in to the mesh.
        reorderedSMCs.SetPoints(reorderedPoints)
        reorderedSMCs.SetPolys(reorderedCellArray)

        # Write the VTK SMC mesh file.
        reorderedMeshWriter = vtk.vtkXMLPolyDataWriter()
        reorderedMeshWriter.SetInputData(reorderedSMCs)
        reorderedMeshWriter.SetFileName(smcVTKFiles[label])
        reorderedMeshWriter.Update()

    print "All done ..."
    print "... Except the last configuration_info.txt file ..."

    configFile = open("files/configuration_info.txt", 'w')
    configFile.write("Processors information\n")
    configFile.write("Total number of points per branch (vtk points) = %d\t\tm = %d n = %d\n" \
    % ((numQuadsPerRing + 1) * (numRingsPerLabel[0] + 1), (numQuadsPerRing + 1), (numRingsPerLabel[0] + 1)))
    configFile.write("Total number of cells per branch (vtk cells) = %d\t\tm = %d n = %d\n" \
    % (numQuadsPerRing * numRingsPerLabel[0], numQuadsPerRing, numRingsPerLabel[0]))
    configFile.write("Total number of SMC mesh points per processor mesh (vtk points) = %d\t\tm = %d n = %d\n" \
    % ((numSMCsPerCol + 1) * (numSMCsPerRow + 1), (numSMCsPerCol + 1), (numSMCsPerRow + 1)))
    configFile.write("Total number of SMC mesh cells per processor mesh (vtk cells) = %d\t\tm = %d n = %d\n" \
    % (numSMCsPerCol * numSMCsPerRow, numSMCsPerCol, numSMCsPerRow))
    configFile.write("Total number of EC mesh points per processor mesh (vtk points) = %d\t\tm = %d n = %d\n" \
    % ((numECsPerCol + 1) * (numECsPerRow + 1), (numECsPerCol + 1), (numECsPerRow + 1)))
    configFile.write("Total number of EC mesh cells per processor mesh (vtk cells) = %d\t\tm = %d n = %d\n" \
    % (numECsPerCol *numECsPerRow, numECsPerCol, numECsPerRow))
    configFile.write("Total number of EC mesh centeroid points per processor mesh (vtk points) = %d\t\tm = %d n = %d\n" \
    % (numECsPerCol *numECsPerRow, numECsPerCol, numECsPerRow))
    configFile.write("Total number of EC mesh centeroid cells per processor mesh (vtk cells) = %d\t\tm = %d n = %d\n" \
    % (numECsPerCol *numECsPerRow, numECsPerCol, numECsPerRow))

    configFile.close()

    print "Now it is all done for real ..."
예제 #36
0
    def _make_avus_geometry(self, model, quads_only=False):
        nodes = model.nodes
        #nnodes = self.nnodes

        grid = self.parent.grid

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

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

        nquads = len(quads)
        ntris = len(tris)
        nhexas = len(hexas)
        ntets = len(tets)

        is_shells = nquads + ntris
        is_solids = ntets + nhexas
        if is_shells:
            is_surface = True
            if nquads:
                elements = quads
                for face in quads:
                    elem = vtkQuad()
                    epoints = elem.GetPointIds()
                    epoints.SetId(0, face[0])
                    epoints.SetId(1, face[1])
                    epoints.SetId(2, face[2])
                    epoints.SetId(3, face[3])
                    #elem.GetCellType() = 5  # vtkTriangle
                    grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())
            if ntris:
                elements = tris
                for face in tris:
                    elem = vtkTriangle()
                    epoints = elem.GetPointIds()
                    epoints.SetId(0, face[0])
                    epoints.SetId(1, face[1])
                    epoints.SetId(2, face[2])
                    #elem.GetCellType() = 5  # vtkTriangle
                    grid.InsertNextCell(5, elem.GetPointIds())

        elif is_solids:
            if ntets:
                elements = tets
                is_surface = False
                self.nelements = model.nelements
                grid.Allocate(self.nelements, 1000)

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


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

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

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

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

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

        grid.SetPoints(points)
        grid.Modified()
        if hasattr(grid, 'Update'):
            grid.Update()
        return is_surface
예제 #37
0
def rhombicuboctahedron():
    import vtk
    # First, you need to store the vertex locations.

    import numpy as np
    fu = 1  # full unit
    hu = .5  # half unit
    d = np.sqrt((fu ** 2) / 2)  # diag
    hh = hu + d  # half height

    # left view faces us

    import utool as ut
    import six
    import itertools
    counter = ut.partial(six.next, itertools.count(0))

    vertex_locations = vtk.vtkPoints()
    vertex_locations.SetNumberOfPoints(24)

    p1, p2, p3 = np.array([
        (-hu, -hu, hh),
        ( hu, -hu, hh),
        ( hu,  hu, hh),
        (-hu,  hu, hh),
    ]).T
    plist = [p1, p2, p3]

    # three of the six main faces
    #perms = list(itertools.permutations((0, 1, 2), 3))
    perms = [(0, 1, 2), (0, 2, 1), (2, 0, 1)]

    vertex_array = []

    # VERTEXES
    # left, up, back
    vplist = ['L', 'U', 'B', 'R', 'D', 'F']
    vpdict = {}
    print('perms = %r' % (perms,))
    for x in range(3):
        vp = vplist[x]
        p = np.vstack(ut.take(plist, perms[x])).T
        counts = [counter() for z in range(4)]
        vpdict[vp] = counts
        vertex_array.extend(p.tolist())
        vertex_locations.SetPoint(counts[0], p[0])
        vertex_locations.SetPoint(counts[1], p[1])
        vertex_locations.SetPoint(counts[2], p[2])
        vertex_locations.SetPoint(counts[3], p[3])

    # three more of the six main faces
    perms = [(0, 1, 2), (0, 2, 1), (2, 0, 1)]
    plist[-1] = -plist[-1]
    # right, down, front
    print('perms = %r' % (perms,))
    for x in range(3):
        p = np.vstack(ut.take(plist, perms[x])).T
        counts = [counter() for z in range(4)]
        vp = vplist[x + 3]
        vpdict[vp] = counts
        vertex_array.extend(p.tolist())
        vertex_locations.SetPoint(counts[0], p[0])
        vertex_locations.SetPoint(counts[1], p[1])
        vertex_locations.SetPoint(counts[2], p[2])
        vertex_locations.SetPoint(counts[3], p[3])

    pd = vtk.vtkPolyData()
    pd.SetPoints(vertex_locations)

    polygon_faces = vtk.vtkCellArray()

    face_dict = {
        'L': [vpdict['L'][0], vpdict['L'][1], vpdict['L'][2], vpdict['L'][3]],
        'D': [vpdict['D'][0], vpdict['D'][1], vpdict['D'][2], vpdict['D'][3]],
        'U': [vpdict['U'][0], vpdict['U'][1], vpdict['U'][2], vpdict['U'][3]],
        'F': [vpdict['F'][0], vpdict['F'][1], vpdict['F'][2], vpdict['F'][3]],
        'R': [vpdict['R'][0], vpdict['R'][1], vpdict['R'][2], vpdict['R'][3]],
        'B': [vpdict['B'][0], vpdict['B'][1], vpdict['B'][2], vpdict['B'][3]],
        'FL': [ vpdict['L'][0], vpdict['L'][3], vpdict['F'][2], vpdict['F'][3], ],
        'BL': [ vpdict['L'][1], vpdict['L'][2], vpdict['B'][2], vpdict['B'][3], ],
        'UL': [ vpdict['L'][2], vpdict['L'][3], vpdict['U'][3], vpdict['U'][2], ],
        'DL': [ vpdict['L'][0], vpdict['L'][1], vpdict['D'][2], vpdict['D'][3], ],
        'UFL': [ vpdict['L'][3], vpdict['F'][2], vpdict['U'][3], ],
        'DFL': [ vpdict['L'][0], vpdict['F'][3], vpdict['D'][3], ],
        'UBL': [ vpdict['L'][2], vpdict['B'][2], vpdict['U'][2], ],
        'DBL': [ vpdict['L'][1], vpdict['B'][3], vpdict['D'][2], ],
        'UFR': [ vpdict['R'][3], vpdict['F'][1], vpdict['U'][0], ],
        'DFR': [ vpdict['R'][0], vpdict['F'][0], vpdict['D'][0], ],
        'UBR': [ vpdict['R'][2], vpdict['B'][1], vpdict['U'][1], ],
        'DBR': [ vpdict['R'][1], vpdict['B'][0], vpdict['D'][1], ],
        'FR': [ vpdict['R'][3], vpdict['R'][0], vpdict['F'][0], vpdict['F'][1], ],
        'BR': [ vpdict['R'][2], vpdict['R'][1], vpdict['B'][0], vpdict['B'][1], ],
        'UR': [ vpdict['R'][3], vpdict['R'][2], vpdict['U'][1], vpdict['U'][0], ],
        'DR': [ vpdict['R'][1], vpdict['R'][0], vpdict['D'][0], vpdict['D'][1], ],
        'DF': [ vpdict['F'][0], vpdict['F'][3], vpdict['D'][3], vpdict['D'][0], ],
        'DB': [ vpdict['B'][3], vpdict['B'][0], vpdict['D'][1], vpdict['D'][2], ],
        'UF': [ vpdict['F'][1], vpdict['F'][2], vpdict['U'][3], vpdict['U'][0], ],
        'UB': [ vpdict['B'][2], vpdict['B'][1], vpdict['U'][1], vpdict['U'][2], ],
    }

    for key, vert_ids in face_dict.items():
        #if key != 'L':
        #    continue
        if len(vert_ids) == 4:
            q = vtk.vtkQuad()
        else:
            q = vtk.vtkTriangle()
        for count, idx in enumerate(vert_ids):
            q.GetPointIds().SetId(count, idx)
        polygon_faces.InsertNextCell(q)

    # Next you create a vtkPolyData to store your face and vertex information
    #that
    # represents your polyhedron.
    pd = vtk.vtkPolyData()
    pd.SetPoints(vertex_locations)
    pd.SetPolys(polygon_faces)

    face_stream = vtk.vtkIdList()
    face_stream.InsertNextId(polygon_faces.GetNumberOfCells())
    vertex_list = vtk.vtkIdList()

    polygon_faces.InitTraversal()
    while polygon_faces.GetNextCell(vertex_list) == 1:
        face_stream.InsertNextId(vertex_list.GetNumberOfIds())

        for j in range(vertex_list.GetNumberOfIds()):
            face_stream.InsertNextId(vertex_list.GetId(j))

    ug = vtk.vtkUnstructuredGrid()
    ug.SetPoints(vertex_locations)
    ug.InsertNextCell(vtk.VTK_POLYHEDRON, face_stream)

    #writer = vtk.vtkUnstructuredGridWriter()
    #writer.SetFileName("rhombicuboctahedron.vtk")
    ##writer.SetInputData(ug)
    #writer.SetInput(ug)
    #writer.Write()

    mapper = vtk.vtkDataSetMapper()
    mapper.SetInput(ug)

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

    if 1:
        # Read the image data from a file
        import utool as ut

        textureCoords = vtk.vtkFloatArray()
        textureCoords.SetNumberOfComponents(3)
        #coords = ut.take(vertex_array, face_dict['L'])
        #for coord in coords:
        #    textureCoords.InsertNextTuple(tuple(coord))
        textureCoords.InsertNextTuple((0, 0, 0))
        textureCoords.InsertNextTuple((1, 0, 0))
        textureCoords.InsertNextTuple((1, 1, 0))
        textureCoords.InsertNextTuple((0, 1, 0))

        # Create texture object
        fpath = ut.grab_test_imgpath('zebra.png')
        reader = vtk.vtkPNGReader()
        reader.SetFileName(fpath)

        texture = vtk.vtkTexture()
        texture.SetInput(reader.GetOutput())
        texture.RepeatOff()
        texture.InterpolateOff()

        ptdat = pd.GetPointData()
        ptdat.SetTCoords(textureCoords)

        actor.SetTexture(texture)

    ren = vtk.vtkRenderer()
    ren.AddActor(actor)

    renw = vtk.vtkRenderWindow()
    renw.AddRenderer(ren)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renw)

    ren.ResetCamera()
    renw.Render()
    iren.Start()
예제 #38
0
def main():
    grid = vtk.vtkUnstructuredGrid()
    grid_mapper = vtk.vtkDataSetMapper()
    if vtk.VTK_VERSION >= 6:
        grid_mapper.SetInputData(grid)
    else:
        grid_mapper.SetInput(grid)
    #if vtk.VTK_VERSION[0] <= 5:
    #    grid_mapper.SetInputConnection(grid.GetProducerPort())
    #else:
    #    grid_mapper.SetInputData(grid)

    nodes = np.array([
        [0., 0., 0.],
        [1., 0., 0.],
        [1., 1., 0.],
        [0., 2., 1.],
    ],
                     dtype='float32')

    points = vtk.vtkPoints()
    points.SetNumberOfPoints(4)
    points_array = numpy_to_vtk(
        num_array=nodes,
        deep=True,
        array_type=vtk.VTK_FLOAT,
    )
    nelements = 1
    grid.Allocate(nelements, 1000)
    grid.SetPoints(points)
    elem = vtk.vtkQuad()
    pts = elem.GetPointIds()
    pts.SetId(0, 0)
    pts.SetId(1, 1)
    pts.SetId(2, 2)
    pts.SetId(3, 3)
    grid.InsertNextCell(elem.GetCellType(), pts)
    grid.Modified()

    forces = np.array([
        [0., 0.1, 0.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., .3],
    ],
                      dtype='float32')

    rend = vtk.vtkRenderer()
    if 1:
        maskPts = vtk.vtkMaskPoints()
        if vtk.VTK_VERSION <= 5:
            maskPts.SetInputConnection(grid.GetProducerPort())
        else:
            maskPts.SetInputData(grid)

        arrow = vtk.vtkArrowSource()
        arrow.SetTipResolution(16)
        arrow.SetTipLength(0.3)
        arrow.SetTipRadius(0.1)

        glyph = vtk.vtkGlyph3D()
        glyph.SetSourceConnection(arrow.GetOutputPort())
        glyph.SetInputConnection(maskPts.GetOutputPort())
        glyph.SetVectorModeToUseNormal()
        glyph.SetScaleFactor(1)
        glyph.SetColorModeToColorByVector()
        glyph.SetScaleModeToScaleByVector()
        glyph.OrientOn()
        glyph.Update()

        glyph_mapper = vtk.vtkPolyDataMapper()
        glyph_mapper.SetInputConnection(glyph.GetOutputPort())
        glyph_mapper.SetScalarModeToUsePointFieldData()
        glyph_mapper.SetColorModeToMapScalars()
        glyph_mapper.ScalarVisibilityOn()
        glyph_mapper.SelectColorArray('Elevation')
        # Colour by scalars.
        #glyph_mapper.SetScalarRange(scalarRangeElevation)

        glyph_actor = vtk.vtkActor()
        glyph_actor.SetMapper(glyph_mapper)
        glyph_actor.RotateX(-45)
        glyph_actor.RotateZ(45)
        rend.AddViewProp(glyph_actor)
        #rend.AddActor(glyph_actor)

    geom_actor = vtk.vtkActor()
    geom_actor.SetMapper(grid_mapper)
    # ------------------------------------------------------------
    # Create the RenderWindow, Renderer and Interactor
    # ------------------------------------------------------------
    renWin = vtk.vtkRenderWindow()
    iren = vtk.vtkRenderWindowInteractor()

    renWin.AddRenderer(rend)
    iren.SetRenderWindow(renWin)

    # add actors
    #rend.AddViewProp(geom_actor)
    #rend.AddViewProp(edgeActor)
    rend.AddActor(geom_actor)
    #rend.AddViewProp(glyph_actor)
    #rend.AddActor2D(scalarBar)

    rend.SetBackground(0.7, 0.8, 1.0)
    renWin.SetSize(800, 800)
    renWin.Render()
    iren.Start()
예제 #39
0
    def load_panair_geometry(self, panairFileName, dirname, plot=True):
        self.nidMap = {}

        #key = self.caseKeys[self.iCase]
        #case = self.resultCases[key]

        skipReading = self.removeOldGeometry(panairFileName)
        if skipReading:
            return

        model = PanairGrid(log=self.log, debug=self.debug)
        self.modelType = model.modelType
        model.read_panair(panairFileName)

        nodes, elements, regions = model.getPointsElementsRegions()
        #for nid,node in enumerate(nodes):
            #print "node[%s] = %s" %(nid,str(node))

        self.nNodes = len(nodes)
        self.nElements = len(elements)

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

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

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

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

        assert len(nodes) > 0
        mmax = amax(nodes, axis=0)
        mmin = amin(nodes, axis=0)
        dim_max = (mmax - mmin).max()
        self.update_axes_length(dim_max)
        for nid, node in enumerate(nodes):
            points.InsertPoint(nid, *node)

        assert len(elements) > 0
        for eid, element in enumerate(elements):
            (p1, p2, p3, p4) = element
            #print "element = ",element
            elem = vtkQuad()
            elem.GetPointIds().SetId(0, p1)
            elem.GetPointIds().SetId(1, p2)
            elem.GetPointIds().SetId(2, p3)
            elem.GetPointIds().SetId(3, p4)
            self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())

        #print("eid = ", eid)
        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()
        if hasattr(self.grid, 'Update'):
            self.grid.Update()
            self.grid2.Update()
            print("updated grid")

        #return

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

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

        #print "nElements = ",nElements
        loads = []
        cases = self.fillPanairGeometryCase(cases, ID, nodes, elements, regions, loads)
        self._finish_results_io(cases)
예제 #40
0
def readAbaqusMesh(mesh_filename, elem_types="all", verbose=True):

    if (verbose): print "*** readAbaqusMesh ***"

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

    mesh_file = open(mesh_filename, "r")

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

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

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

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

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

    mesh_file.close()

    if (verbose): print "Creating UGrid..."

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

    if (verbose): print "nb_cells = " + str(ugrid.GetNumberOfCells())

    return ugrid
예제 #41
0
파일: utils.py 프로젝트: fvpolpeta/devide
def setup_renderers(renwin, fg_ren, bg_ren):
    """Utility method to configure foreground and background renderer
    and insert them into different layers of the renderenwinindow.

    Use this if you want an incredibly cool gradient background!
    """
    
    # bit of code thanks to 
    # http://www.bioengineering-research.com/vtk/BackgroundGradient.tcl
    # had to change approach though to using background renderer,
    # else transparent objects don't appear, and adding flat
    # shaded objects breaks the background gradient.
    # =================================================================
    
    qpts = vtk.vtkPoints()
    qpts.SetNumberOfPoints(4)
    qpts.InsertPoint(0, 0, 0, 0)
    qpts.InsertPoint(1, 1, 0, 0)
    qpts.InsertPoint(2, 1, 1, 0)
    qpts.InsertPoint(3, 0, 1, 0)

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

    uc = vtk.vtkUnsignedCharArray()
    uc.SetNumberOfComponents(4)
    uc.SetNumberOfTuples(4)
    uc.SetTuple4(0, 128, 128, 128, 255) # bottom left RGBA
    uc.SetTuple4(1, 128, 128, 128, 255) # bottom right RGBA
    uc.SetTuple4(2, 255, 255, 255, 255) # top right RGBA
    uc.SetTuple4(3, 255, 255, 255, 255) # tob left RGBA

    dta = vtk.vtkPolyData()
    dta.Allocate(1,1)
    dta.InsertNextCell(quad.GetCellType(), quad.GetPointIds())
    dta.SetPoints(qpts)
    dta.GetPointData().SetScalars(uc)

    coord = vtk.vtkCoordinate()
    coord.SetCoordinateSystemToNormalizedDisplay()

    mapper2d = vtk.vtkPolyDataMapper2D()
    mapper2d.SetInput(dta)
    mapper2d.SetTransformCoordinate(coord)

    actor2d = vtk.vtkActor2D()
    actor2d.SetMapper(mapper2d)
    actor2d.GetProperty().SetDisplayLocationToBackground()

    bg_ren.AddActor(actor2d)
    bg_ren.SetLayer(0) # seems to be background
    bg_ren.SetInteractive(0)

    fg_ren.SetLayer(1) # and foreground

    renwin.SetNumberOfLayers(2)
    renwin.AddRenderer(fg_ren)
    renwin.AddRenderer(bg_ren)
예제 #42
0
파일: quad.py 프로젝트: tjssmy/CuviewerPy
p8 = [0.0, 0.0, 0.0]
p9 = [1, 1.0, 1.0]

# Add the points to a vtkPoints object
points = vtk.vtkPoints()
pid = points.InsertNextPoint(p0)
points.InsertNextPoint(p1)
points.InsertNextPoint(p2)
points.InsertNextPoint(p3)
points.InsertNextPoint(p4)
points.InsertNextPoint(p5)
points.InsertNextPoint(p6)
points.InsertNextPoint(p7)

# Create a quad on the four points
quad = vtk.vtkQuad()
quad.GetPointIds().SetId(0, 0)
quad.GetPointIds().SetId(1, 1)
quad.GetPointIds().SetId(2, 2)
quad.GetPointIds().SetId(3, 3)

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

points.InsertNextPoint(p8)
pid = points.InsertNextPoint(p9)

line = vtk.vtkLine()
예제 #43
0
    def load_avl_geometry(self, avl_filename,
                          name='main', plot=True):
        model_name = name
        #key = self.case_keys[self.icase]
        #case = self.result_cases[key]

        #skip_reading = self._remove_old_adb_geometry(adb_filename)
        #if skip_reading:
            #return

        log = self.gui.log
        model = read_avl(avl_filename, log=log, debug=False)
        self.gui.model_type = 'avl'
        nodes, elements, line_elements, surfaces = model.get_nodes_elements()
        #self.model_type = model.model_type

        nxyz_nodes = nodes.shape[0]
        nquad_elements = elements.shape[0]
        nline_elements = 0
        if line_elements:
            nline_elements = line_elements.shape[0]
            assert nline_elements > 0, nline_elements

        nnodes = nxyz_nodes
        nelements = nquad_elements + nline_elements
        self.gui.nnodes = nnodes
        self.gui.nelements = nelements

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

        points = vtk.vtkPoints()
        points.SetNumberOfPoints(self.gui.nnodes)
        #vectorReselt.SetNumberOfComponents(3)
        self.gui.nid_map = {}

        assert nodes is not None

        nid = 0
        #print('nxyz_nodes=%s' % nxyz_nodes)
        mmax = amax(nodes, axis=0)
        mmin = amin(nodes, axis=0)
        dim_max = (mmax - mmin).max()
        self.gui.create_global_axes(dim_max)
        for i in range(nxyz_nodes):
            points.InsertPoint(nid, nodes[i, :])
            nid += 1
        log.info('nnodes=%s nquad_elements=%s nline_elements=%s' % (
            nxyz_nodes, nquad_elements, nline_elements))

        #elements -= 1
        for eid in range(nquad_elements):
            elem = vtkQuad()
            node_ids = elements[eid, :]
            point_ids = elem.GetPointIds()
            point_ids.SetId(0, node_ids[0])
            point_ids.SetId(1, node_ids[1])
            point_ids.SetId(2, node_ids[2])
            point_ids.SetId(3, node_ids[3])
            grid.InsertNextCell(elem.GetCellType(), point_ids)

        for eid in range(nline_elements):
            elem = vtkLine()
            node_ids = line_elements[eid, :]
            point_ids = elem.GetPointIds()
            point_ids.SetId(0, node_ids[0])
            point_ids.SetId(1, node_ids[1])
            grid.InsertNextCell(elem.GetCellType(), point_ids)

        grid.SetPoints(points)
        grid.Modified()

        # load results - regions/loads
        self.gui.scalar_bar_actor.VisibilityOn()
        self.gui.scalar_bar_actor.Modified()

        note = ''
        self.gui.isubcase_name_map = {1: ['AVL%s' % note, '']}
        cases = OrderedDict()
        ID = 1

        form, cases, node_ids, element_ids = self._fill_avl_case(
            cases, ID, nnodes, nelements, surfaces)
        self.gui.node_ids = node_ids
        self.gui.element_ids = element_ids
        self.gui._finish_results_io2(model_name, form, cases)
예제 #44
0
def SimpleFindStrips(poly, coord):
    # Just do the cells in their given order
    # This method reduces the number of polys in the 20x20x20 by a factor of 3.623
    # reduces the number of polys in the 100x100x100 by 2.216
    #dirs=[0,1,2]
    #dirs.remove(coord)
    bounds = poly.GetBounds()
    numCells = poly.GetNumberOfCells()
    current = vtk.vtkGenericCell()
    newcell = vtk.vtkGenericCell()
    poly.GetCell(0, current)
    sharedpts = vtk.vtkIdList()
    sharedpts.DeepCopy(current.GetPointIds())
    newPoints = vtk.vtkPoints()
    newPoints.DeepCopy(poly.GetPoints())
    consolidatedpoly = vtk.vtkPolyData()
    consolidatedpoly.Allocate(1000,1000)
    consolidatedpoly.SetPoints(newPoints)
    x = [0,0,0]
    for i in xrange(1,numCells):
        poly.GetCell(i, newcell)
        # check if this cell shares an edge
        sharedpts.IntersectWith(newcell.GetPointIds())
        # if they share an edge, the current cell becomes the union of the 2 cells
        if sharedpts.GetNumberOfIds() == 2:
            quad = vtk.vtkQuad()
            ptIds = []
            for j in xrange(4):
                if sharedpts.IsId(current.GetPointIds().GetId(j)) == -1:
                    ptIds.append(j)
            if ptIds == [0,3]: ptIds.reverse()
            current.GetPoints().GetPoint(ptIds[0],x)
            quad.GetPointIds().InsertId(0,current.GetPointIds().GetId(ptIds[0]))
            quad.GetPoints().InsertPoint(0,x)
            current.GetPoints().GetPoint(ptIds[1],x)
            quad.GetPointIds().InsertId(1,current.GetPointIds().GetId(ptIds[1]))
            quad.GetPoints().InsertPoint(1,x)

            ptIds = []
            for j in xrange(4):
                if sharedpts.IsId(newcell.GetPointIds().GetId(j)) == -1:
                    ptIds.append(j)
            if ptIds == [0,3]: ptIds.reverse()
            newcell.GetPoints().GetPoint(ptIds[0],x)
            quad.GetPointIds().InsertId(2,newcell.GetPointIds().GetId(ptIds[0]))
            quad.GetPoints().InsertPoint(2,x)
            newcell.GetPoints().GetPoint(ptIds[1],x)
            quad.GetPointIds().InsertId(3,newcell.GetPointIds().GetId(ptIds[1]))
            quad.GetPoints().InsertPoint(3,x)

            current.DeepCopy(quad)
            #consolidatedpoly.InsertNextCell(current.GetCellType(),current.GetPointIds())
        else:
            consolidatedpoly.InsertNextCell(current.GetCellType(),current.GetPointIds())
            current.DeepCopy(newcell)
        sharedpts.DeepCopy(current.GetPointIds())

    consolidatedpoly.InsertNextCell(current.GetCellType(),current.GetPointIds())
    cleaner = vtk.vtkCleanPolyData()
    cleaner.SetInput(consolidatedpoly)
    consolidatedpoly = cleaner.GetOutput()
    consolidatedpoly.Squeeze()
    consolidatedpoly.Update()
    return consolidatedpoly
def readAbaqusMeshFromINP(
        mesh_filename,
        elem_types="all",
        verbose=1):

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

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

    mesh_file = open(mesh_filename, "r")

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

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

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

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

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

    mesh_file.close()

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

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

    return ugrid
예제 #46
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, .5, 1, 0)
        tetraPoints.InsertPoint(3, .5, .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, .5, .5)
        wedgePoints.InsertPoint(3, 1, 1, 0)
        wedgePoints.InsertPoint(4, 1, 0, 0)
        wedgePoints.InsertPoint(5, 1, .5, .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, .5, .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, .5, .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
        if hasattr(vtk, 'vtkRIBProperty'):
            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(.1, .2, .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(.3, 1, .5)
        ren.AddActor(aPolygonActor);aPolygonActor.GetProperty().SetDiffuseColor(1, .4, .5)
        ren.AddActor(aTriangleStripActor);aTriangleStripActor.GetProperty().SetDiffuseColor(.3, .7, 1)
        ren.AddActor(aLineActor);aLineActor.GetProperty().SetDiffuseColor(.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(.2, .4, .7)
        ren.AddActor(aHexaActor);aHexaActor.GetProperty().SetDiffuseColor(.7, .5, 1)

        if hasattr(vtk, 'vtkRIBLight'):
            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)

        # bascially have IO/Export ?
        if hasattr(vtk, 'vtkRIBExporter'):
            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()
예제 #47
0
    def load_degen_geom_geometry(self, csv_filename, dirname, name='main', plot=True):
        #key = self.case_keys[self.icase]
        #case = self.result_cases[key]

        skip_reading = self._remove_old_adb_geometry(csv_filename)
        if skip_reading:
            return

        model = DegenGeom(log=self.log, debug=False)
        self.model_type = 'vspaero'
        #self.model_type = model.model_type
        model.read_degen_geom(csv_filename)
        for name, comps in sorted(model.components.items()):
            print('name = %r' % name)
            #print(comp)
            print('------------')
            for comp in comps:
                nodes = comp.xyz
                elements = comp.elements
                nnodes = nodes.shape[0]
                nelements = elements.shape[0]

        self.nNodes = nnodes
        self.nElements = nelements

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

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

        assert nodes is not None

        nid = 0
        #print("nxyz_nodes=%s" % nxyz_nodes)
        mmax = amax(nodes, axis=0)
        mmin = amin(nodes, axis=0)
        dim_max = (mmax - mmin).max()
        self.create_global_axes(dim_max)

        for i in range(nnodes):
            points.InsertPoint(nid, nodes[i, :])
            nid += 1
        #self.log.info('nxyz_nodes=%s nwake_nodes=%s total=%s' % (
            #nnodes, nwake_nodes, nxyz_nodes + nwake_nodes))
        #self.log.info('nxyz_elements=%s nwake_elements=%s total=%s' % (
            #nxyz_elements, nwake_elements, nxyz_elements + nwake_elements))

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

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

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

        #mach = model.machs[0]
        #alpha = model.alphas[0]
        #beta = model.betas[0]
        #note = ':  Mach=%.2f, alpha=%.1f, beta=%.1f' % (mach, alpha, beta)
        note = 'name=%s' % name
        self.iSubcaseNameMap = {1: ['OpenVSP%s' % note, '']}
        cases = {}
        ID = 1

        form, cases = self._fill_degen_geom_case(cases, ID, model, nnodes, nelements)
        self._finish_results_io2(form, cases)
예제 #48
0
    def load_panair_geometry(self, panair_filename, name='main', plot=True):
        model_name = name
        self.gui.nid_map = {}
        #key = self.case_keys[self.icase]
        #case = self.result_cases[key]

        skip_reading = self.gui._remove_old_geometry(panair_filename)
        if skip_reading:
            return

        model = PanairGrid(log=self.gui.log, debug=self.gui.debug)
        self.gui.model_type = model.model_type
        model.read_panair(panair_filename)
        self.gui.geom_model = model
        # get_wakes=True shows explicit wakes
        #
        # TODO: bad for results...what about just not adding it to the patches/bcs?
        nodes, elements, regions, kt, cp_norm = model.get_points_elements_regions(
            get_wakes=True)

        self.gui.nnodes = len(nodes)
        self.gui.nelements = len(elements)

        #print("nnodes = ",self.nnodes)
        #print("nelements = ", self.nelements)

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

        points = vtk.vtkPoints()
        points.SetNumberOfPoints(self.gui.nnodes)

        assert len(nodes) > 0
        mmax = amax(nodes, axis=0)
        mmin = amin(nodes, axis=0)
        dim_max = (mmax - mmin).max()
        self.gui.create_global_axes(dim_max)
        points = numpy_to_vtk_points(nodes)

        assert len(elements) > 0
        elem = vtkQuad()
        quad_type = elem.GetCellType()
        create_vtk_cells_of_constant_element_type(grid, elements, quad_type)

        grid.SetPoints(points)
        grid.Modified()

        # loadPanairResults - regions/loads
        if plot:
            self.gui.scalar_bar_actor.VisibilityOn()
            self.gui.scalar_bar_actor.Modified()

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

        loads = []
        form, cases, node_ids, element_ids = self._fill_panair_geometry_case(
            cases, ID, nodes, elements, regions, kt, cp_norm, loads)
        self.gui.node_ids = node_ids
        self.gui.element_ids = element_ids

        #if plot:
        self.gui._finish_results_io2(model_name, form, cases)
예제 #49
0
def rhombicuboctahedron():
    import vtk
    # First, you need to store the vertex locations.

    import numpy as np
    fu = 1  # full unit
    hu = .5  # half unit
    d = np.sqrt((fu**2) / 2)  # diag
    hh = hu + d  # half height

    # left view faces us

    import utool as ut
    import six
    import itertools
    counter = ut.partial(six.next, itertools.count(0))

    vertex_locations = vtk.vtkPoints()
    vertex_locations.SetNumberOfPoints(24)

    p1, p2, p3 = np.array([
        (-hu, -hu, hh),
        (hu, -hu, hh),
        (hu, hu, hh),
        (-hu, hu, hh),
    ]).T
    plist = [p1, p2, p3]

    # three of the six main faces
    #perms = list(itertools.permutations((0, 1, 2), 3))
    perms = [(0, 1, 2), (0, 2, 1), (2, 0, 1)]

    vertex_array = []

    # VERTEXES
    # left, up, back
    vplist = ['L', 'U', 'B', 'R', 'D', 'F']
    vpdict = {}
    print('perms = %r' % (perms, ))
    for x in range(3):
        vp = vplist[x]
        p = np.vstack(ut.take(plist, perms[x])).T
        counts = [counter() for z in range(4)]
        vpdict[vp] = counts
        vertex_array.extend(p.tolist())
        vertex_locations.SetPoint(counts[0], p[0])
        vertex_locations.SetPoint(counts[1], p[1])
        vertex_locations.SetPoint(counts[2], p[2])
        vertex_locations.SetPoint(counts[3], p[3])

    # three more of the six main faces
    perms = [(0, 1, 2), (0, 2, 1), (2, 0, 1)]
    plist[-1] = -plist[-1]
    # right, down, front
    print('perms = %r' % (perms, ))
    for x in range(3):
        p = np.vstack(ut.take(plist, perms[x])).T
        counts = [counter() for z in range(4)]
        vp = vplist[x + 3]
        vpdict[vp] = counts
        vertex_array.extend(p.tolist())
        vertex_locations.SetPoint(counts[0], p[0])
        vertex_locations.SetPoint(counts[1], p[1])
        vertex_locations.SetPoint(counts[2], p[2])
        vertex_locations.SetPoint(counts[3], p[3])

    pd = vtk.vtkPolyData()
    pd.SetPoints(vertex_locations)

    polygon_faces = vtk.vtkCellArray()

    face_dict = {
        'L': [vpdict['L'][0], vpdict['L'][1], vpdict['L'][2], vpdict['L'][3]],
        'D': [vpdict['D'][0], vpdict['D'][1], vpdict['D'][2], vpdict['D'][3]],
        'U': [vpdict['U'][0], vpdict['U'][1], vpdict['U'][2], vpdict['U'][3]],
        'F': [vpdict['F'][0], vpdict['F'][1], vpdict['F'][2], vpdict['F'][3]],
        'R': [vpdict['R'][0], vpdict['R'][1], vpdict['R'][2], vpdict['R'][3]],
        'B': [vpdict['B'][0], vpdict['B'][1], vpdict['B'][2], vpdict['B'][3]],
        'FL': [
            vpdict['L'][0],
            vpdict['L'][3],
            vpdict['F'][2],
            vpdict['F'][3],
        ],
        'BL': [
            vpdict['L'][1],
            vpdict['L'][2],
            vpdict['B'][2],
            vpdict['B'][3],
        ],
        'UL': [
            vpdict['L'][2],
            vpdict['L'][3],
            vpdict['U'][3],
            vpdict['U'][2],
        ],
        'DL': [
            vpdict['L'][0],
            vpdict['L'][1],
            vpdict['D'][2],
            vpdict['D'][3],
        ],
        'UFL': [
            vpdict['L'][3],
            vpdict['F'][2],
            vpdict['U'][3],
        ],
        'DFL': [
            vpdict['L'][0],
            vpdict['F'][3],
            vpdict['D'][3],
        ],
        'UBL': [
            vpdict['L'][2],
            vpdict['B'][2],
            vpdict['U'][2],
        ],
        'DBL': [
            vpdict['L'][1],
            vpdict['B'][3],
            vpdict['D'][2],
        ],
        'UFR': [
            vpdict['R'][3],
            vpdict['F'][1],
            vpdict['U'][0],
        ],
        'DFR': [
            vpdict['R'][0],
            vpdict['F'][0],
            vpdict['D'][0],
        ],
        'UBR': [
            vpdict['R'][2],
            vpdict['B'][1],
            vpdict['U'][1],
        ],
        'DBR': [
            vpdict['R'][1],
            vpdict['B'][0],
            vpdict['D'][1],
        ],
        'FR': [
            vpdict['R'][3],
            vpdict['R'][0],
            vpdict['F'][0],
            vpdict['F'][1],
        ],
        'BR': [
            vpdict['R'][2],
            vpdict['R'][1],
            vpdict['B'][0],
            vpdict['B'][1],
        ],
        'UR': [
            vpdict['R'][3],
            vpdict['R'][2],
            vpdict['U'][1],
            vpdict['U'][0],
        ],
        'DR': [
            vpdict['R'][1],
            vpdict['R'][0],
            vpdict['D'][0],
            vpdict['D'][1],
        ],
        'DF': [
            vpdict['F'][0],
            vpdict['F'][3],
            vpdict['D'][3],
            vpdict['D'][0],
        ],
        'DB': [
            vpdict['B'][3],
            vpdict['B'][0],
            vpdict['D'][1],
            vpdict['D'][2],
        ],
        'UF': [
            vpdict['F'][1],
            vpdict['F'][2],
            vpdict['U'][3],
            vpdict['U'][0],
        ],
        'UB': [
            vpdict['B'][2],
            vpdict['B'][1],
            vpdict['U'][1],
            vpdict['U'][2],
        ],
    }

    for key, vert_ids in face_dict.items():
        #if key != 'L':
        #    continue
        if len(vert_ids) == 4:
            q = vtk.vtkQuad()
        else:
            q = vtk.vtkTriangle()
        for count, idx in enumerate(vert_ids):
            q.GetPointIds().SetId(count, idx)
        polygon_faces.InsertNextCell(q)

    # Next you create a vtkPolyData to store your face and vertex information
    #that
    # represents your polyhedron.
    pd = vtk.vtkPolyData()
    pd.SetPoints(vertex_locations)
    pd.SetPolys(polygon_faces)

    face_stream = vtk.vtkIdList()
    face_stream.InsertNextId(polygon_faces.GetNumberOfCells())
    vertex_list = vtk.vtkIdList()

    polygon_faces.InitTraversal()
    while polygon_faces.GetNextCell(vertex_list) == 1:
        face_stream.InsertNextId(vertex_list.GetNumberOfIds())

        for j in range(vertex_list.GetNumberOfIds()):
            face_stream.InsertNextId(vertex_list.GetId(j))

    ug = vtk.vtkUnstructuredGrid()
    ug.SetPoints(vertex_locations)
    ug.InsertNextCell(vtk.VTK_POLYHEDRON, face_stream)

    #writer = vtk.vtkUnstructuredGridWriter()
    #writer.SetFileName("rhombicuboctahedron.vtk")
    ##writer.SetInputData(ug)
    #writer.SetInput(ug)
    #writer.Write()

    mapper = vtk.vtkDataSetMapper()
    mapper.SetInput(ug)

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

    if 1:
        # Read the image data from a file
        import utool as ut

        textureCoords = vtk.vtkFloatArray()
        textureCoords.SetNumberOfComponents(3)
        #coords = ut.take(vertex_array, face_dict['L'])
        #for coord in coords:
        #    textureCoords.InsertNextTuple(tuple(coord))
        textureCoords.InsertNextTuple((0, 0, 0))
        textureCoords.InsertNextTuple((1, 0, 0))
        textureCoords.InsertNextTuple((1, 1, 0))
        textureCoords.InsertNextTuple((0, 1, 0))

        # Create texture object
        fpath = ut.grab_test_imgpath('zebra.png')
        reader = vtk.vtkPNGReader()
        reader.SetFileName(fpath)

        texture = vtk.vtkTexture()
        texture.SetInput(reader.GetOutput())
        texture.RepeatOff()
        texture.InterpolateOff()

        ptdat = pd.GetPointData()
        ptdat.SetTCoords(textureCoords)

        actor.SetTexture(texture)

    ren = vtk.vtkRenderer()
    ren.AddActor(actor)

    renw = vtk.vtkRenderWindow()
    renw.AddRenderer(ren)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renw)

    ren.ResetCamera()
    renw.Render()
    iren.Start()
예제 #50
0
    def load_openfoam_geometry(self, openfoam_filename, dirname, mesh_3d, plot=True):
        #key = self.caseKeys[self.iCase]
        #case = self.resultCases[key]

        skip_reading = self.remove_old_openfoam_geometry(openfoam_filename)
        if skip_reading:
            return
        #print('self.modelType=%s' % self.modelType)
        print('mesh_3d = %s' % mesh_3d)
        if mesh_3d in ['hex', 'shell']:
            model = BlockMesh(log=self.log, debug=False) # log=self.log, debug=False
        elif mesh_3d == 'faces':
            model = BlockMesh(log=self.log, debug=False) # log=self.log, debug=False
            boundary = Boundary(log=self.log, debug=False)


        self.modelType = 'openfoam'
        #self.modelType = model.modelType
        print('openfoam_filename = %s' % openfoam_filename)

        is_face_mesh = False
        if mesh_3d == 'hex':
            is_3d_blockmesh = True
            is_surface_blockmesh = False
            (nodes, hexas, quads, names, patches) = model.read_openfoam(openfoam_filename)
        elif mesh_3d == 'shell':
            is_3d_blockmesh = False
            is_surface_blockmesh = True
            (nodes, hexas, quads, names, patches) = model.read_openfoam(openfoam_filename)
        elif mesh_3d == 'faces':
            is_3d_blockmesh = False
            is_surface_blockmesh = False
            is_face_mesh = True
            #(nodes, hexas, quads, names, patches) = model.read_openfoam(openfoam_filename)
        else:
            raise RuntimeError(mesh_3d)

        tris = []


        if mesh_3d == 'hex':
            self.nElements = len(hexas)
        elif mesh_3d == 'shell':
            self.nElements = len(quads)
        elif mesh_3d == 'faces':
            point_filename = os.path.join(dirname, 'points')
            face_filename = os.path.join(dirname, 'faces')
            boundary_filename = os.path.join(dirname, 'boundary')
            assert os.path.exists(face_filename), print_bad_path(face_filename)
            assert os.path.exists(point_filename), print_bad_path(point_filename)
            assert os.path.exists(boundary_filename), print_bad_path(boundary_filename)

            hexas = None
            patches = None
            nodes, quads, names = boundary.read_openfoam(
                point_filename, face_filename, boundary_filename)
            self.nElements = len(quads) + len(tris)
        else:
            raise RuntimeError(mesh_3d)

        self.nNodes = len(nodes)
        print("nNodes = %s" % self.nNodes)
        print("nElements = %s" % self.nElements)


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

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

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

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

        nid = 0
        #print("nnodes=%s" % nnodes)
        mmax = amax(nodes, axis=0)
        mmin = amin(nodes, axis=0)
        dim_max = (mmax - mmin).max()
        self.update_axes_length(dim_max)

        f = open('points.bdf', 'wb')
        f.write('CEND\n')
        f.write('BEGIN BULK\n')

        unames = unique(names)
        for pid in unames:
            f.write('PSHELL,%i,1,0.1\n' % pid)
        f.write('MAT1,1,1.0e7,,0.3\n')

        if is_face_mesh:
            unodes = unique(quads)
            unodes.sort()
            # should stop plotting duplicate nodes
            for inode, node in enumerate(nodes):
                if inode in unodes:
                    f.write('GRID,%i,,%s,%s,%s\n' % (inode + 1, node[0], node[1], node[2], ))
                points.InsertPoint(inode, node)
        else:
            #print(nodes)
            for inode, node in enumerate(nodes):
                points.InsertPoint(inode, node)

        #elements -= 1
        normals = None
        if is_3d_blockmesh:
            nelements, three = hexas.shape
            for eid, element in enumerate(hexas):
                #print(element)
                elem = vtkHexahedron()
                elem.GetPointIds().SetId(0, element[0])
                elem.GetPointIds().SetId(1, element[1])
                elem.GetPointIds().SetId(2, element[2])
                elem.GetPointIds().SetId(3, element[3])
                elem.GetPointIds().SetId(4, element[4])
                elem.GetPointIds().SetId(5, element[5])
                elem.GetPointIds().SetId(6, element[6])
                elem.GetPointIds().SetId(7, element[7])
                self.grid.InsertNextCell(elem.GetCellType(),
                                         elem.GetPointIds())

                #elem = vtkTriangle()
                #node_ids = elements[eid, :]
                #elem.GetPointIds().SetId(0, node_ids[0])
                #elem.GetPointIds().SetId(1, node_ids[1])
                #elem.GetPointIds().SetId(2, node_ids[2])

                #elem.GetCellType() = 5  # vtkTriangle
                #self.grid.InsertNextCell(5, elem.GetPointIds())
        elif is_surface_blockmesh:
            nelements, four = quads.shape
            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())
        elif is_face_mesh:
            elems = quads
            nelements = quads.shape[0]
            nnames = len(names)
            normals = zeros((nelements, 3), dtype='float32')
            if nnames != nelements:
                msg = 'nnames=%s nelements=%s names.max=%s names.min=%s' % (
                    nnames, nelements, names.max(), names.min())
                raise RuntimeError(msg)
            for eid, element in enumerate(elems):
                #print('element = %s' % element)
                ineg = where(element == -1)[0]

                nnodes = 4
                if ineg:
                    nnodes = ineg.max()

                #pid = 1
                pid = names[eid]
                if nnodes == 3: # triangle!
                    f.write('CTRIA3,%i,%i,%i,%i,%i\n' % (
                        eid+1, pid, element[0]+1, element[1]+1, element[2]+1))
                    elem = vtkTriangle()
                    a = nodes[element[1], :] - nodes[element[0], :]
                    b = nodes[element[2], :] - nodes[element[0], :]
                    n = cross(a, b)
                    normals[eid, :] = n / norm(n)

                    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())
                elif nnodes == 4:
                    f.write('CQUAD4,%i,%i,%i,%i,%i,%i\n' % (
                        eid+1, pid, element[0]+1, element[1]+1, element[2]+1, element[3]+1))
                    a = nodes[element[2], :] - nodes[element[0], :]
                    b = nodes[element[3], :] - nodes[element[1], :]
                    n = cross(a, b)
                    normals[eid, :] = n / norm(n)

                    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())
                else:
                    raise RuntimeError('nnodes=%s' % nnodes)
        else:
            msg = 'is_surface_blockmesh=%s is_face_mesh=%s; pick one' % (
                is_surface_blockmesh, is_face_mesh)
            raise RuntimeError(msg)

        self.nElements = nelements
        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")

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

        #assert loads is not None
        #if 'Mach' in loads:
            #avgMach = mean(loads['Mach'])
            #note = ':  avg(Mach)=%g' % avgMach
        #else:
            #note = ''
        #self.iSubcaseNameMap = {1: ['Cart3d%s' % note, '']}
        self.iSubcaseNameMap = {0: ['OpenFoam BlockMeshDict', '']}
        cases = {}
        ID = 1

        #print("nElements = ",nElements)
        f.write('ENDDATA\n')
        f.close()

        if mesh_3d == 'hex':
            form, cases = self._fill_openfoam_case(cases, ID, nodes, nelements, patches, names, normals, is_surface_blockmesh)
        elif mesh_3d == 'shell':
            form, cases = self._fill_openfoam_case(cases, ID, nodes, nelements, patches, names, normals, is_surface_blockmesh)
        elif mesh_3d == 'faces':
            if len(names) == nelements:
                is_surface_blockmesh = True
            form, cases = self._fill_openfoam_case(cases, ID, nodes, nelements, patches,
                                                   names, normals, is_surface_blockmesh)
        else:
            raise RuntimeError(mesh_3d)

        if plot:
            self._finish_results_io2(form, cases)
예제 #51
0
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)
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
예제 #52
0
    def loadGeometry(self, bdf_filename):
        model = BDF()
        model.readBDF(bdf_filename)

        nNodes = model.nNodes()
        nElements = model.nElements()
        nCAeros = model.nCAeros()

        #print "nNodes = ",nNodes
        print "nElements = ", nElements

        self.grid = vtk.vtkUnstructuredGrid()
        self.grid2 = vtk.vtkUnstructuredGrid()
        #self.aQuadGrid.Allocate(nElements+nNodes, 1000)

        if 'CONM2' in model.cardCount:
            nCONM2 = model.cardCount['CONM2']
        else:
            nCONM2 = 0
        self.grid.Allocate(nElements, 1000)
        self.grid2.Allocate(nCAeros + nCONM2, 1000)

        points = vtk.vtkPoints()
        points.SetNumberOfPoints(nNodes)
        nidMap = {}
        i = 0
        #elem.SetNumberOfPoints(nNodes)
        for nid, node in sorted(model.nodes.iteritems()):
            #print "i = ",i
            point = node.Position()
            #print "point = ",point
            #sys.stdout.flush()
            #aVoxel = vtk.vtkPixel()
            #print "made voxel"; sys.stdout.flush()
            points.InsertPoint(i, *point)

            #print str(element)

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

            nidMap[nid] = i
            i += 1

        j = 0
        points2 = vtk.vtkPoints()
        points2.SetNumberOfPoints(nCAeros * 4 + nCONM2)
        for eid, element in sorted(model.caeros.iteritems()):
            if isinstance(element, CAERO1):
                cpoints = element.Points()
                elem = vtkQuad()
                elem.GetPointIds().SetId(0, j)
                elem.GetPointIds().SetId(1, j + 1)
                elem.GetPointIds().SetId(2, j + 2)
                elem.GetPointIds().SetId(3, j + 3)
                points2.InsertPoint(j, *cpoints[0])
                points2.InsertPoint(j + 1, *cpoints[1])
                points2.InsertPoint(j + 2, *cpoints[2])
                points2.InsertPoint(j + 3, *cpoints[3])
                self.grid2.InsertNextCell(
                    elem.GetCellType(), elem.GetPointIds())
                j += 4
        self.mapElements(points, points2, nidMap, model, j)
예제 #53
0
def rhombic_dodecahedron():
    # http://www.vtk.org/pipermail/vtkusers/2014-September/085077.html
    import vtk
    # This is a Rhombic Dodecahedron.

    # First, you need to store the vertex locations.
    vertex_locations = vtk.vtkPoints()
    vertex_locations.SetNumberOfPoints(14)
    vertex_locations.SetPoint(0, (-0.816497, -0.816497, 0.00000))
    vertex_locations.SetPoint(1, (-0.816497, 0.000000, -0.57735))
    vertex_locations.SetPoint(2, (-0.816497, 0.000000, 0.57735))
    vertex_locations.SetPoint(3, (-0.816497, 0.816497, 0.00000))
    vertex_locations.SetPoint(4, (0.000000, -0.816497, -0.57735))
    vertex_locations.SetPoint(5, (0.000000, -0.816497, 0.57735))
    vertex_locations.SetPoint(6, (0.000000, 0.000000, -1.15470))
    vertex_locations.SetPoint(7, (0.000000, 0.000000, 1.15470))
    vertex_locations.SetPoint(8, (0.000000, 0.816497, -0.57735))
    vertex_locations.SetPoint(9, (0.000000, 0.816497, 0.57735))
    vertex_locations.SetPoint(10, (0.816497, -0.816497, 0.00000))
    vertex_locations.SetPoint(11, (0.816497, 0.000000, -0.57735))
    vertex_locations.SetPoint(12, (0.816497, 0.000000, 0.57735))
    vertex_locations.SetPoint(13, (0.816497, 0.816497, 0.00000))

    # Next, you describe the polygons that represent the faces using the vertex
    # indices in the vtkPoints that stores the vertex locations. There are a
    #number
    # of ways to do this that you can find in examples on the Wiki.

    polygon_faces = vtk.vtkCellArray()

    q = vtk.vtkQuad()
    q.GetPointIds().SetId(0, 7)
    q.GetPointIds().SetId(1, 12)
    q.GetPointIds().SetId(2, 10)
    q.GetPointIds().SetId(3, 5)
    polygon_faces.InsertNextCell(q)

    q = vtk.vtkQuad()
    q.GetPointIds().SetId(0, 7)
    q.GetPointIds().SetId(1, 12)
    q.GetPointIds().SetId(2, 13)
    q.GetPointIds().SetId(3, 9)
    polygon_faces.InsertNextCell(q)

    q = vtk.vtkQuad()
    q.GetPointIds().SetId(0, 7)
    q.GetPointIds().SetId(1, 9)
    q.GetPointIds().SetId(2, 3)
    q.GetPointIds().SetId(3, 2)
    polygon_faces.InsertNextCell(q)

    q = vtk.vtkQuad()
    q.GetPointIds().SetId(0, 7)
    q.GetPointIds().SetId(1, 2)
    q.GetPointIds().SetId(2, 0)
    q.GetPointIds().SetId(3, 5)
    polygon_faces.InsertNextCell(q)

    q = vtk.vtkQuad()
    q.GetPointIds().SetId(0, 6)
    q.GetPointIds().SetId(1, 11)
    q.GetPointIds().SetId(2, 10)
    q.GetPointIds().SetId(3, 4)
    polygon_faces.InsertNextCell(q)

    q = vtk.vtkQuad()
    q.GetPointIds().SetId(0, 6)
    q.GetPointIds().SetId(1, 4)
    q.GetPointIds().SetId(2, 0)
    q.GetPointIds().SetId(3, 1)
    polygon_faces.InsertNextCell(q)

    q = vtk.vtkQuad()
    q.GetPointIds().SetId(0, 6)
    q.GetPointIds().SetId(1, 1)
    q.GetPointIds().SetId(2, 3)
    q.GetPointIds().SetId(3, 8)
    polygon_faces.InsertNextCell(q)

    q = vtk.vtkQuad()
    q.GetPointIds().SetId(0, 6)
    q.GetPointIds().SetId(1, 8)
    q.GetPointIds().SetId(2, 13)
    q.GetPointIds().SetId(3, 11)
    polygon_faces.InsertNextCell(q)

    q = vtk.vtkQuad()
    q.GetPointIds().SetId(0, 10)
    q.GetPointIds().SetId(1, 11)
    q.GetPointIds().SetId(2, 13)
    q.GetPointIds().SetId(3, 12)
    polygon_faces.InsertNextCell(q)

    q = vtk.vtkQuad()
    q.GetPointIds().SetId(0, 13)
    q.GetPointIds().SetId(1, 8)
    q.GetPointIds().SetId(2, 3)
    q.GetPointIds().SetId(3, 9)
    polygon_faces.InsertNextCell(q)

    q = vtk.vtkQuad()
    q.GetPointIds().SetId(0, 3)
    q.GetPointIds().SetId(1, 1)
    q.GetPointIds().SetId(2, 0)
    q.GetPointIds().SetId(3, 2)
    polygon_faces.InsertNextCell(q)

    q = vtk.vtkQuad()
    q.GetPointIds().SetId(0, 0)
    q.GetPointIds().SetId(1, 4)
    q.GetPointIds().SetId(2, 10)
    q.GetPointIds().SetId(3, 5)
    polygon_faces.InsertNextCell(q)

    # Next you create a vtkPolyData to store your face and vertex information
    #that
    # represents your polyhedron.
    pd = vtk.vtkPolyData()
    pd.SetPoints(vertex_locations)
    pd.SetPolys(polygon_faces)

    # If you wanted to be able to load in the saved file and select the entire
    # polyhedron, you would need to save it as a vtkUnstructuredGrid, and you
    #would
    # need to put the data into a vtkPolyhedron. This is a bit more involved
    #than
    # the vtkPolyData that I used above. For a more in-depth discussion, see:
    # http://www.vtk.org/Wiki/VTK/Polyhedron_Support

    # Based on the link above, I need to construct a face stream:
    face_stream = vtk.vtkIdList()
    face_stream.InsertNextId(polygon_faces.GetNumberOfCells())
    vertex_list = vtk.vtkIdList()

    polygon_faces.InitTraversal()
    while polygon_faces.GetNextCell(vertex_list) == 1:
        face_stream.InsertNextId(vertex_list.GetNumberOfIds())

        for j in range(vertex_list.GetNumberOfIds()):
            face_stream.InsertNextId(vertex_list.GetId(j))

    ug = vtk.vtkUnstructuredGrid()
    ug.SetPoints(vertex_locations)
    ug.InsertNextCell(vtk.VTK_POLYHEDRON, face_stream)

    #--------------#
    # output stuff #
    #--------------#

    writer = vtk.vtkUnstructuredGridWriter()
    writer.SetFileName("rhombic_dodecahedron.vtk")
    #writer.SetInputData(ug)
    writer.SetInput(ug)
    writer.Write()

    #---------------------#
    # visualization stuff #
    #---------------------#
    # mapper = vtk.vtkPolyDataMapper()
    # mapper.SetInputData(pd)
    mapper = vtk.vtkDataSetMapper()
    mapper.SetInput(ug)

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

    ren = vtk.vtkRenderer()
    ren.AddActor(actor)

    renw = vtk.vtkRenderWindow()
    renw.AddRenderer(ren)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renw)

    ren.ResetCamera()
    renw.Render()
    iren.Start()
예제 #54
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()
예제 #55
0
    def load_panair_geometry(self, panair_filename, dirname, name='main', plot=True):
        self.nid_map = {}

        #key = self.case_keys[self.icase]
        #case = self.result_cases[key]

        skip_reading = self._remove_old_geometry(panair_filename)
        if skip_reading:
            return

        model = PanairGrid(log=self.log, debug=self.debug)
        self.model_type = model.model_type
        model.read_panair(panair_filename)

        nodes, elements, regions, kt, cp_norm = model.get_points_elements_regions()
        #for nid, node in enumerate(nodes):
            #print "node[%s] = %s" % (nid, str(node))

        self.nNodes = len(nodes)
        self.nElements = len(elements)

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

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

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

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

        assert len(nodes) > 0
        mmax = amax(nodes, axis=0)
        mmin = amin(nodes, axis=0)
        dim_max = (mmax - mmin).max()
        self.create_global_axes(dim_max)
        for nid, node in enumerate(nodes):
            points.InsertPoint(nid, *node)

        assert len(elements) > 0
        elem = vtkQuad()
        quad_type = elem.GetCellType()
        for eid, element in enumerate(elements):
            (p1, p2, p3, p4) = element
            elem = vtkQuad()
            elem.GetPointIds().SetId(0, p1)
            elem.GetPointIds().SetId(1, p2)
            elem.GetPointIds().SetId(2, p3)
            elem.GetPointIds().SetId(3, p4)
            self.grid.InsertNextCell(quad_type, elem.GetPointIds())

        self.grid.SetPoints(points)
        #self.grid.GetPointData().SetScalars(self.gridResult)
        #print dir(self.grid) #.SetNumberOfComponents(0)
        #self.grid.GetCellData().SetNumberOfTuples(1);
        #self.grid.GetCellData().SetScalars(self.gridResult)
        self.grid.Modified()
        if hasattr(self.grid, 'Update'):
            self.grid.Update()

        # loadPanairResults - regions/loads
        self. turn_text_on()
        if plot:
            self.scalarBar.VisibilityOn()
            self.scalarBar.Modified()

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

        #print "nElements = ", nElements
        loads = []
        form, cases = self._fill_panair_geometry_case(
            cases, ID, nodes, elements, regions, kt, cp_norm, loads)
        #if plot:
        self._finish_results_io2(form, cases)
예제 #56
0
    def load_abaqus_geometry(self, abaqus_filename, name='main', plot=True):
        """loads abaqus input files into the gui"""
        model_name = name
        skip_reading = self.gui._remove_old_geometry(abaqus_filename)
        if skip_reading:
            return

        self.gui.eid_maps[name] = {}
        self.gui.nid_maps[name] = {}
        model = Abaqus(log=self.gui.log, debug=False)
        self.gui.model_type = 'abaqus'
        #self.model_type = model.model_type
        model.read_abaqus_inp(abaqus_filename)

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

        n_cohax4 = 0
        n_cax3 = 0
        n_cax4r = 0

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

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

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

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

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

        self.gui.nnodes = nnodes
        self.gui.nelements = nelements

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        grid.SetPoints(points)
        grid.Modified()

        # loadCart3dResults - regions/loads
        self.gui.scalar_bar_actor.VisibilityOn()
        self.gui.scalar_bar_actor.Modified()

        note = ''
        self.gui.isubcase_name_map = {1: ['Abaqus%s' % note, '']}
        #form = []
        cases = OrderedDict()
        ID = 1
        form, cases, unused_icase, node_ids, element_ids = self._fill_abaqus_case(
            cases, ID, nodes, nelements, model)
        #self._fill_cart3d_results(cases, form, icase, ID, model)

        self.gui.node_ids = node_ids
        self.gui.element_ids = element_ids
        self.gui._finish_results_io2(model_name, form, cases)