def makeVoxelGrid(nCubes): max_x=nCubes+1 max_y=nCubes+1 max_z=nCubes+1 scale=20./nCubes #*(19./20) meshPoints = vtk.vtkPoints() meshPoints.SetNumberOfPoints(max_x*max_y*max_z) #i*(max_y)*(max_z)+j*(max_z)+k for i in xrange(max_x): for j in xrange(max_y): for k in xrange(max_z): meshPoints.InsertPoint(i*(max_y)*(max_z)+j*(max_z)+k,scale*i,scale*j,scale*k) nelements = (max_x-1)*(max_y-1)*(max_z-1) meshGrid = vtk.vtkUnstructuredGrid() meshGrid.Allocate(nelements, nelements) meshGrid.SetPoints(meshPoints) for i in range(max_x-1): for j in range(max_y-1): for k in range(max_z-1): cell = vtk.vtkHexahedron() # This is the order we need such that the normals point out. cell.GetPointIds().SetId(0, (i+1)*(max_y)*(max_z)+j*(max_z)+k) # upper left front cell.GetPointIds().SetId(1, (i+1)*(max_y)*(max_z)+(j+1)*(max_z)+k) # upper right front cell.GetPointIds().SetId(2, i*(max_y)*(max_z)+(j+1)*(max_z)+k) # lower right front cell.GetPointIds().SetId(3, i*(max_y)*(max_z)+j*(max_z)+k) # lower left front node index cell.GetPointIds().SetId(4, (i+1)*(max_y)*(max_z)+j*(max_z)+k+1) # upper left back cell.GetPointIds().SetId(5, (i+1)*(max_y)*(max_z)+(j+1)*(max_z)+k+1) # upper right back cell.GetPointIds().SetId(6, i*(max_y)*(max_z)+(j+1)*(max_z)+k+1) # lower right back cell.GetPointIds().SetId(7, i*(max_y)*(max_z)+j*(max_z)+k+1) # lower left back meshGrid.InsertNextCell(cell.GetCellType(), cell.GetPointIds()) return meshGrid
def findPointsInCell(points, cell, verbose=1): ugrid_cell = vtk.vtkUnstructuredGrid() ugrid_cell.SetPoints(cell.GetPoints()) cell = vtk.vtkHexahedron() for k_point in xrange(8): cell.GetPointIds().SetId(k_point, k_point) cell_array_cell = vtk.vtkCellArray() cell_array_cell.InsertNextCell(cell) ugrid_cell.SetCells(vtk.VTK_HEXAHEDRON, cell_array_cell) geometry_filter = vtk.vtkGeometryFilter() geometry_filter.SetInputData(ugrid_cell) geometry_filter.Update() cell_boundary = geometry_filter.GetOutput() pdata_points = vtk.vtkPolyData() pdata_points.SetPoints(points) enclosed_points_filter = vtk.vtkSelectEnclosedPoints() enclosed_points_filter.SetSurfaceData(cell_boundary) enclosed_points_filter.SetInputData(pdata_points) enclosed_points_filter.Update() points_in_cell = [k_point for k_point in xrange(points.GetNumberOfPoints()) if enclosed_points_filter.GetOutput().GetPointData().GetArray('SelectedPoints').GetTuple(k_point)[0]] return points_in_cell
def makeVoxelGrid(cubesize, scale): max_x=cubesize max_y=cubesize max_z=cubesize meshPoints = vtk.vtkPoints() meshPoints.SetNumberOfPoints(max_x*max_y*max_z) #i*(max_y)*(max_z)+j*(max_z)+k for i in xrange(max_x): for j in xrange(max_y): for k in xrange(max_z): meshPoints.InsertPoint(i*(max_y)*(max_z)+j*(max_z)+k,scale*i,scale*j,scale*k) nelements = (max_x-1)*(max_y-1)*(max_z-1) meshGrid = vtk.vtkUnstructuredGrid() meshGrid.Allocate(nelements, nelements) meshGrid.SetPoints(meshPoints) for i in range(max_x-1): for j in range(max_y-1): for k in range(max_z-1): cell = vtk.vtkHexahedron() cell.GetPointIds().SetId(0, i*(max_y)*(max_z)+j*(max_z)+k) # lower left front node index cell.GetPointIds().SetId(1, i*(max_y)*(max_z)+(j+1)*(max_z)+k) # lower right front cell.GetPointIds().SetId(2, (i+1)*(max_y)*(max_z)+(j+1)*(max_z)+k) # upper right front cell.GetPointIds().SetId(3, (i+1)*(max_y)*(max_z)+j*(max_z)+k) # upper left front cell.GetPointIds().SetId(4, i*(max_y)*(max_z)+j*(max_z)+k+1) # lower left back cell.GetPointIds().SetId(5, i*(max_y)*(max_z)+(j+1)*(max_z)+k+1) # lower right back cell.GetPointIds().SetId(6, (i+1)*(max_y)*(max_z)+(j+1)*(max_z)+k+1) # upper right back cell.GetPointIds().SetId(7, (i+1)*(max_y)*(max_z)+j*(max_z)+k+1) # upper left back meshGrid.InsertNextCell(cell.GetCellType(), cell.GetPointIds()) return meshGrid
def getHex(el): hex = vtk.vtkHexahedron() hex.GetPointIds().SetId(0, el[0]) hex.GetPointIds().SetId(1, el[1]) hex.GetPointIds().SetId(2, el[2]) hex.GetPointIds().SetId(3, el[3]) hex.GetPointIds().SetId(4, el[4]) hex.GetPointIds().SetId(5, el[5]) hex.GetPointIds().SetId(6, el[6]) hex.GetPointIds().SetId(7, el[7]) return hex
def defineMesh(self,nodes,elements): self._points = vtk.vtkPoints() self._hexs = vtk.vtkUnstructuredGrid() #vtk.vtkCellArray() for i in range(len(nodes)): self._points.InsertNextPoint(nodes[i].x(),nodes[i].y(),nodes[i].z()) for el in elements: hexa = vtk.vtkHexahedron() conn = el.connectivite() for ii,n in enumerate(conn): hexa.GetPointIds().SetId(ii,n) self._hexs.InsertNextCell(hexa.GetCellType(), hexa.GetPointIds()) self._hexs.SetPoints(self._points)
def boxesActor(boxes, color = (0, 0, 0, 100), wireframe=False): """Create a vtkActor representing a list of hexahedron. The hexahedrons are assumed to be aligned with the coordinate axis, and are given using their extremal points. Args: box: [[[xmin, ymin, zmin], [xmax, ymax, zmax]], ...] color: RGBA color wireframe: if True, the boxes are drawn in wireframe mode """ grid = vtk.vtkUnstructuredGrid() points = vtk.vtkPoints() colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(4) colors.SetName("Colors") for (index, box) in enumerate(boxes): colors.InsertNextTuple4(color[0], color[1], color[2], 100) P0 = [box[0][0], box[0][1], box[0][2]] P1 = [box[1][0], box[0][1], box[0][2]] P2 = [box[1][0], box[1][1], box[0][2]] P3 = [box[0][0], box[1][1], box[0][2]] P4 = [box[0][0], box[0][1], box[1][2]] P5 = [box[1][0], box[0][1], box[1][2]] P6 = [box[1][0], box[1][1], box[1][2]] P7 = [box[0][0], box[1][1], box[1][2]] points.InsertNextPoint(P0) points.InsertNextPoint(P1) points.InsertNextPoint(P2) points.InsertNextPoint(P3) points.InsertNextPoint(P4) points.InsertNextPoint(P5) points.InsertNextPoint(P6) points.InsertNextPoint(P7) hexa = vtk.vtkHexahedron() hexa.GetPointIds().SetNumberOfIds(8) for i in range(8): hexa.GetPointIds().SetId(i, 8 * index + i) grid.InsertNextCell(hexa.GetCellType(), hexa.GetPointIds()) grid.SetPoints(points) grid.GetCellData().SetScalars(colors) mapper = vtk.vtkDataSetMapper() set_mapper_input(mapper, grid) actor = vtk.vtkActor() actor.SetMapper(mapper) if wireframe: actor.GetProperty().SetRepresentationToWireframe() actor.GetProperty().SetLineWidth(2.) return actor
def create_actor_hexahedron(grid, color, **kwargs): """ Creates a VTK actor for rendering voxels using hexahedron elements. :param grid: grid :type grid: ndarray :param color: actor color :type color: list :return: a VTK actor :rtype: vtkActor """ # Keyword arguments array_name = kwargs.get('name', "") array_index = kwargs.get('index', 0) # Create hexahedron elements points = vtk.vtkPoints() hexarray = vtk.vtkCellArray() for j, pt in enumerate(grid): tmp = vtk.vtkHexahedron() fb = pt[0] for i, v in enumerate(fb): points.InsertNextPoint(v) tmp.GetPointIds().SetId(i, i + (j * 8)) ft = pt[-1] for i, v in enumerate(ft): points.InsertNextPoint(v) tmp.GetPointIds().SetId(i + 4, i + 4 + (j * 8)) hexarray.InsertNextCell(tmp) # Create an unstructured grid object and add points & hexahedron elements ugrid = vtk.vtkUnstructuredGrid() ugrid.SetPoints(points) ugrid.SetCells(tmp.GetCellType(), hexarray) # ugrid.InsertNextCell(tmp.GetCellType(), tmp.GetPointIds()) # Map unstructured grid to the graphics primitives mapper = vtk.vtkDataSetMapper() mapper.SetInputDataObject(ugrid) mapper.SetArrayName(array_name) mapper.SetArrayId(array_index) # Create an actor and set its properties actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(*color) # Return the actor return actor
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
def makeHexahedra(xSideLength=1.0, ySideLength=1.0, zSideLength=1.0): """ This function makes a generic hexahedra object with the given side lengths. The angles between every edge will be 90 degrees. The sides will be parallel x,y,z axes of the global coordinate system. .. NOTE:: The side lengths have default values of 1.0. If no input is given, then the variables will be defined with the given default value. In this case, the value is 1.0 :param xSideLength: float, the length of the side that runs parallel with the x-axis :param ySideLength: float, the length of the side that runs parallel with the y-axis :param zSideLength: float, the length of the side that runs parallel with the z-axis :return: vtkUnstructuredGrid, vtkPoints, An object from the vtk module that is used to define shapes. Also return the original points that were used to define the hexahedra. """ coords = np.array([[0.0, 0.0, 0.0], # Define the points that make up the hexahedra [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 1.0], [1.0, 1.0, 1.0], [0.0, 1.0, 1.0]]) # multiply the coordinates by the side length. .. NOTE:: This is not matrix multiplication. coords = coords*np.array([xSideLength, ySideLength, zSideLength]) hex = vtk.vtkHexahedron() # Initialize the hexahedron class instance. points = vtk.vtkPoints() # Initialize a vtkPoints class instance. This is specific to the VTK module that is used for visualization. for i in range(8): # Iterate over a list with 8 indicies (.. NOTE:: 'range(8)' is a bulit in function of python). points.InsertNextPoint(coords[i]) # Insert the ith coord into the points object. hex.GetPointIds().SetId(i, i) # While we are iteration from 0 to 7, insert the point ids uGrid = vtk.vtkUnstructuredGrid() # Initialize the vtk unstructured grid object. uGrid.SetPoints(points) # Set the points in the uGrid as the points that we previously defined. uGrid.InsertNextCell(hex.GetCellType(), hex.GetPointIds()) # Set the hexahedra that we previously defined as the only cell in the grid. return uGrid, points
def MakeHexahedron(): ''' A regular hexagon (cube) with all faces square and three squares around each vertex is created below. Setup the coordinates of eight points (the two faces must be in counter clockwise order as viewed from the outside). As an exercise you can modify the coordinates of the points to create seven topologically distinct convex hexahedras. ''' numberOfVertices = 8 # Create the points points = vtk.vtkPoints() points.InsertNextPoint(0.0, 0.0, 0.0) points.InsertNextPoint(1.0, 0.0, 0.0) points.InsertNextPoint(1.0, 1.0, 0.0) points.InsertNextPoint(0.0, 1.0, 0.0) points.InsertNextPoint(0.0, 0.0, 1.0) points.InsertNextPoint(1.0, 0.0, 1.0) points.InsertNextPoint(1.0, 1.0, 1.0) points.InsertNextPoint(0.0, 1.0, 1.0) # Create a hexahedron from the points hex_ = vtk.vtkHexahedron() for i in range(0, numberOfVertices): hex_.GetPointIds().SetId(i, i) # Add the points and hexahedron to an unstructured grid uGrid = vtk.vtkUnstructuredGrid() uGrid.SetPoints(points) uGrid.InsertNextCell(hex_.GetCellType(), hex_.GetPointIds()) return uGrid
def getPointsInCell( points, cell, verbose=0): mypy.my_print(verbose, "*** getPointsInCell ***") ugrid_cell = vtk.vtkUnstructuredGrid() ugrid_cell.SetPoints(cell.GetPoints()) cell = vtk.vtkHexahedron() for k_point in xrange(8): cell.GetPointIds().SetId(k_point, k_point) cell_array_cell = vtk.vtkCellArray() cell_array_cell.InsertNextCell(cell) ugrid_cell.SetCells(vtk.VTK_HEXAHEDRON, cell_array_cell) geometry_filter = vtk.vtkGeometryFilter() if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): geometry_filter.SetInputData(ugrid_cell) else: geometry_filter.SetInput(ugrid_cell) geometry_filter.Update() cell_boundary = geometry_filter.GetOutput() pdata_points = vtk.vtkPolyData() pdata_points.SetPoints(points) enclosed_points_filter = vtk.vtkSelectEnclosedPoints() enclosed_points_filter.SetSurfaceData(cell_boundary) if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): enclosed_points_filter.SetInputData(pdata_points) else: enclosed_points_filter.SetInput(pdata_points) enclosed_points_filter.Update() points_in_cell = [k_point for k_point in xrange(points.GetNumberOfPoints()) if enclosed_points_filter.GetOutput().GetPointData().GetArray('SelectedPoints').GetTuple1(k_point)] return points_in_cell
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
def __init__(self, inputobj=None, ): vtk.vtkActor.__init__(self) BaseGrid.__init__(self) inputtype = str(type(inputobj)) self._data = None self._polydata = None ################### if inputobj is None: self._data = vtk.vtkUnstructuredGrid() elif utils.isSequence(inputobj): pts, cells, celltypes = inputobj self._data = vtk.vtkUnstructuredGrid() if not utils.isSequence(cells[0]): tets=[] nf=cells[0]+1 for i, cl in enumerate(cells): if i==nf or i==0: k = i+1 nf = cl+k cell = [cells[j+k] for j in range(cl)] tets.append(cell) cells = tets # This would fill the points and use those to define orientation vpts = numpy_to_vtk(np.ascontiguousarray(pts), deep=True) points = vtk.vtkPoints() points.SetData(vpts) self._data.SetPoints(points) # This fill the points and use cells to define orientation # points = vtk.vtkPoints() # for c in cells: # for pid in c: # points.InsertNextPoint(pts[pid]) # self._data.SetPoints(points) # Fill cells # https://vtk.org/doc/nightly/html/vtkCellType_8h_source.html for i, ct in enumerate(celltypes): cell_conn = cells[i] if ct == vtk.VTK_HEXAHEDRON: cell = vtk.vtkHexahedron() elif ct == vtk.VTK_TETRA: cell = vtk.vtkTetra() elif ct == vtk.VTK_VOXEL: cell = vtk.vtkVoxel() elif ct == vtk.VTK_WEDGE: cell = vtk.vtkWedge() elif ct == vtk.VTK_PYRAMID: cell = vtk.vtkPyramid() elif ct == vtk.VTK_HEXAGONAL_PRISM: cell = vtk.vtkHexagonalPrism() elif ct == vtk.VTK_PENTAGONAL_PRISM: cell = vtk.vtkPentagonalPrism() else: print("UGrid: cell type", ct, "not implemented. Skip.") continue cpids = cell.GetPointIds() for j, pid in enumerate(cell_conn): cpids.SetId(j, pid) self._data.InsertNextCell(ct, cpids) elif "UnstructuredGrid" in inputtype: self._data = inputobj elif isinstance(inputobj, str): from vedo.io import download, loadUnStructuredGrid if "https://" in inputobj: inputobj = download(inputobj, verbose=False) self._data = loadUnStructuredGrid(inputobj) else: colors.printc("UGrid(): cannot understand input type:\n", inputtype, c='r') return # self._mapper = vtk.vtkDataSetMapper() self._mapper = vtk.vtkPolyDataMapper() self._mapper.SetInterpolateScalarsBeforeMapping(settings.interpolateScalarsBeforeMapping) if settings.usePolygonOffset: self._mapper.SetResolveCoincidentTopologyToPolygonOffset() pof, pou = settings.polygonOffsetFactor, settings.polygonOffsetUnits self._mapper.SetResolveCoincidentTopologyPolygonOffsetParameters(pof, pou) self.GetProperty().SetInterpolationToFlat() if not self._data: return # now fill the representation of the vtk unstr grid sf = vtk.vtkShrinkFilter() sf.SetInputData(self._data) sf.SetShrinkFactor(1.0) sf.Update() gf = vtk.vtkGeometryFilter() gf.SetInputData(sf.GetOutput()) # gf.SetInputData(self._data) gf.Update() self._polydata = gf.GetOutput() self._mapper.SetInputData(self._polydata) sc = None if self.useCells: sc = self._polydata.GetCellData().GetScalars() else: sc = self._polydata.GetPointData().GetScalars() if sc: self._mapper.SetScalarRange(sc.GetRange()) self.SetMapper(self._mapper)
def mapElements(self, points, points2, nidMap, model, j): #self.eidMap = {} i = 0 for (eid, element) in sorted(model.elements.iteritems()): self.eidMap[eid] = i #print element.type if isinstance(element, CTRIA3) or isinstance(element, CTRIAR): elem = vtkTriangle() nodeIDs = element.nodeIDs() elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]]) elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]]) elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]]) self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) elif isinstance(element, CTRIA6): nodeIDs = element.nodeIDs() if None not in nodeIDs: elem = vtkQuadraticTriangle() elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]]) elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]]) elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]]) else: elem = vtkTriangle() elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]]) elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]]) elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]]) self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) elif isinstance(element, CTRIAX6): # midside nodes are required, nodes out of order nodeIDs = element.nodeIDs() if None not in nodeIDs: elem = vtkQuadraticTriangle() elem.GetPointIds().SetId(3, nidMap[nodeIDs[1]]) elem.GetPointIds().SetId(4, nidMap[nodeIDs[3]]) elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]]) else: elem = vtkTriangle() elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]]) elem.GetPointIds().SetId(1, nidMap[nodeIDs[2]]) elem.GetPointIds().SetId(2, nidMap[nodeIDs[4]]) #a = [0,2,4] #msg = "CTRIAX6 %i %i %i" %(nidMap[nodeIDs[a[0]]], # nidMap[nodeIDs[a[1]]], # nidMap[nodeIDs[a[2]]] ) #raise RuntimeError(msg) #sys.stdout.flush() #elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]]) #elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]]) #elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]]) self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) elif (isinstance(element, CQUAD4) or isinstance(element, CSHEAR) or isinstance(element, CQUADR)): nodeIDs = element.nodeIDs() elem = vtkQuad() elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]]) elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]]) elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]]) elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]]) self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) elif isinstance(element, CQUAD8): nodeIDs = element.nodeIDs() if None not in nodeIDs: elem = vtkQuadraticQuad() elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]]) elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]]) elem.GetPointIds().SetId(6, nidMap[nodeIDs[6]]) elem.GetPointIds().SetId(7, nidMap[nodeIDs[7]]) else: elem = vtkQuad() elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]]) elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]]) elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]]) elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]]) self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) elif isinstance(element, CTETRA4): elem = vtkTetra() nodeIDs = element.nodeIDs() elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]]) elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]]) elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]]) elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]]) self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) elif isinstance(element, CTETRA10): nodeIDs = element.nodeIDs() if None not in nodeIDs: elem = vtkQuadraticTetra() elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]]) elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]]) elem.GetPointIds().SetId(6, nidMap[nodeIDs[6]]) elem.GetPointIds().SetId(7, nidMap[nodeIDs[7]]) elem.GetPointIds().SetId(8, nidMap[nodeIDs[8]]) elem.GetPointIds().SetId(9, nidMap[nodeIDs[9]]) else: elem = vtkTetra() elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]]) elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]]) elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]]) elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]]) self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) elif isinstance(element, CPENTA6): elem = vtkWedge() nodeIDs = element.nodeIDs() elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]]) elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]]) elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]]) elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]]) elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]]) elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]]) self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) elif isinstance(element, CPENTA15): nodeIDs = element.nodeIDs() if None not in nodeIDs: elem = vtkQuadraticWedge() elem.GetPointIds().SetId(6, nidMap[nodeIDs[6]]) elem.GetPointIds().SetId(7, nidMap[nodeIDs[7]]) elem.GetPointIds().SetId(8, nidMap[nodeIDs[8]]) elem.GetPointIds().SetId(9, nidMap[nodeIDs[9]]) elem.GetPointIds().SetId(10, nidMap[nodeIDs[10]]) elem.GetPointIds().SetId(11, nidMap[nodeIDs[11]]) elem.GetPointIds().SetId(12, nidMap[nodeIDs[12]]) elem.GetPointIds().SetId(13, nidMap[nodeIDs[13]]) elem.GetPointIds().SetId(14, nidMap[nodeIDs[14]]) else: elem = vtkWedge() elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]]) elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]]) elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]]) elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]]) elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]]) elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]]) self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) elif isinstance(element, CHEXA8): nodeIDs = element.nodeIDs() elem = vtkHexahedron() elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]]) elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]]) elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]]) elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]]) elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]]) elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]]) elem.GetPointIds().SetId(6, nidMap[nodeIDs[6]]) elem.GetPointIds().SetId(7, nidMap[nodeIDs[7]]) self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) elif isinstance(element, CHEXA20): nodeIDs = element.nodeIDs() #print "nodeIDs = ",nodeIDs if None not in nodeIDs: elem = vtkQuadraticHexahedron() elem.GetPointIds().SetId(8, nidMap[nodeIDs[8]]) elem.GetPointIds().SetId(9, nidMap[nodeIDs[9]]) elem.GetPointIds().SetId(10, nidMap[nodeIDs[10]]) elem.GetPointIds().SetId(11, nidMap[nodeIDs[11]]) elem.GetPointIds().SetId(12, nidMap[nodeIDs[12]]) elem.GetPointIds().SetId(13, nidMap[nodeIDs[13]]) elem.GetPointIds().SetId(14, nidMap[nodeIDs[14]]) elem.GetPointIds().SetId(15, nidMap[nodeIDs[15]]) elem.GetPointIds().SetId(16, nidMap[nodeIDs[16]]) elem.GetPointIds().SetId(17, nidMap[nodeIDs[17]]) elem.GetPointIds().SetId(18, nidMap[nodeIDs[18]]) elem.GetPointIds().SetId(19, nidMap[nodeIDs[19]]) else: elem = vtkHexahedron() elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]]) elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]]) elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]]) elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]]) elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]]) elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]]) elem.GetPointIds().SetId(6, nidMap[nodeIDs[6]]) elem.GetPointIds().SetId(7, nidMap[nodeIDs[7]]) self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) elif (isinstance(element, LineElement) or isinstance(element, SpringElement) or element.type in ['CBUSH', 'CBUSH1D', 'CFAST', 'CROD', 'CONROD', 'CELAS1', 'CELAS2', 'CELAS3', 'CELAS4', 'CDAMP1', 'CDAMP2', 'CDAMP3', 'CDAMP4', 'CDAMP5', 'CVISC', ]): nodeIDs = element.nodeIDs() if None not in nodeIDs: # used to be 0... elem = vtk.vtkLine() try: elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]]) elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]]) except KeyError: print "nodeIDs =", nodeIDs print str(element) continue self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) elif isinstance(element, CONM2): # not perfectly located del self.eidMap[eid] i -= 1 #nid = element.Nid() c = element.Centroid() elem = vtk.vtkVertex() #elem = vtk.vtkSphere() #elem.SetRadius(1.0) #print str(element) points2.InsertPoint(j, *c) elem.GetPointIds().SetId(0, j) #elem.SetCenter(points.GetPoint(nidMap[nid])) self.grid2.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) j += 1 else: del self.eidMap[eid] self.log_info("skipping %s" % element.type) continue i += 1 self.grid.SetPoints(points) self.grid2.SetPoints(points2) #self.grid.GetPointData().SetScalars(self.gridResult) #print dir(self.grid) #.SetNumberOfComponents(0) #self.grid.GetCellData().SetNumberOfTuples(1); #self.grid.GetCellData().SetScalars(self.gridResult) self.grid.Modified() self.grid2.Modified() self.grid.Update() self.grid2.Update() self.log_info("updated grid") cases = {} nelements = len(model.elements) print "len(elements) =", nelements pids = [] # zeros(nelements, 'int32') nxs = [] nys = [] nzs = [] i = 0 for eid, element in sorted(model.elements.iteritems()): pids.append(element.Pid()) if isinstance(element, ShellElement): (nx, ny, nz) = element.Normal() else: nx = ny = nz = 0.0 nxs.append(nx) nys.append(ny) nzs.append(nz) self.iSubcaseNameMap = {1: ['Nastran', '']} # subcaseID, resultType, vectorSize, location, dataFormat if 1: cases[(0, 'Pid', 1, 'centroid', '%.0f')] = pids # if not a flat plate??? #if min(nxs) == max(nxs) and min(nxs) != 0.0: # subcaseID, resultType, vectorSize, location, dataFormat cases[(0, 'Normal_x', 1, 'centroid', '%.1f')] = nxs cases[(0, 'Normal_y', 1, 'centroid', '%.1f')] = nys cases[(0, 'Normal_z', 1, 'centroid', '%.1f')] = nzs self.log.info(cases.keys()) self.finish_io(cases)
lst = normalize([(0, 1, 0),(0, 0, 0),(0,.5,.5),(1, 1, 0),(1,.0,.0),(1,.5,.5)]) for x,y,z in lst: points.InsertNextPoint(x+4,y,z) cell = vtk.vtkWedge() for i in range(len(lst)): cell.GetPointIds().SetId(i, i+np) UG.InsertNextCell(cell.GetCellType(), cell.GetPointIds() ) # vtkHexahedron np = points.GetNumberOfPoints() lst = normalize([(0, 0, 0),(1, 0, 0),(1, 1, 0),(0, 1, 0), (0, 0, 1),(1, 0,.6),(1, 1,.6),(0, 1, 1)]) for x,y,z in lst: points.InsertNextPoint(x+6,y,z) cell = vtk.vtkHexahedron() for i in range(len(lst)): cell.GetPointIds().SetId(i, i+np) UG.InsertNextCell(cell.GetCellType(), cell.GetPointIds() ) # vtkVoxel np = points.GetNumberOfPoints() lst = normalize([(0, 0, 0),(1, 0, 0),(0, 1, 0),(1, 1, 0), (0, 0, 1),(1, 0, 1),(0, 1, 1),(1, 1, 1)]) for x,y,z in lst: points.InsertNextPoint(x+8,y,z) cell = vtk.vtkVoxel() for i in range(len(lst)): cell.GetPointIds().SetId(i, i+np) UG.InsertNextCell(cell.GetCellType(), cell.GetPointIds() )
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) 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()
else: elem = vtk.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]]) Penta15cell = grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) Color.InsertTuple1(Penta15cell, 4) elif isinstance(element, CHEXA8): continue nodeIDs = element.nodeIDs() elem = vtk.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]]) Hexa8cell = grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) Color.InsertTuple1(Hexa8cell, 4) elif isinstance(element, CHEXA20): continue nodeIDs = element.nodeIDs() if None not in nodeIDs:
P7 = [0.0, 1.0, 1.0] # Create the points points = vtk.vtkPoints() 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 hexahedron from the points hex = vtk.vtkHexahedron() hex.GetPointIds().SetId(0,0) hex.GetPointIds().SetId(1,1) hex.GetPointIds().SetId(2,2) hex.GetPointIds().SetId(3,3) hex.GetPointIds().SetId(4,4) hex.GetPointIds().SetId(5,5) hex.GetPointIds().SetId(6,6) hex.GetPointIds().SetId(7,7) # Add the hexahedron to a cell array hexs = vtk.vtkCellArray() hexs.InsertNextCell(hex) # Add the points and hexahedron to an unstructured grid uGrid = vtk.vtkUnstructuredGrid()
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 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
def build_3d_grid(parent_bit_mask, parent_id, origin, spacing, ndims, chunk_info, grid_desc): if "slice" in grid_desc: return cells_on_slice_planes(parent_bit_mask, parent_id, origin, \ spacing, ndims, chunk_info, grid_desc) ug = vtk.vtkUnstructuredGrid() points = vtk.vtkPoints() for k in range(ndims[2]): k_offset = k*spacing[2] for j in range(ndims[1]): j_offset = j*spacing[1] for i in range(ndims[0]): points.InsertNextPoint(origin[0] + i*spacing[0], \ origin[1] + j_offset, \ origin[2] + k_offset) ug.SetPoints(points) hex = vtk.vtkHexahedron() for k in range(ndims[2]-1): kl_offset = k*ndims[1]*ndims[0] ku_offset = (k+1)*ndims[1]*ndims[0] for j in range(ndims[1]-1): jl_offset = j*ndims[0] ju_offset = (j + 1)*ndims[0] ll = jl_offset + kl_offset uu = ju_offset + ku_offset lu = jl_offset + ku_offset ul = ju_offset + kl_offset for i in range(ndims[0]-1): hex.GetPointIds().SetId(0, i + ll) hex.GetPointIds().SetId(1, i + 1 + ll) hex.GetPointIds().SetId(2, i + 1 + ul) hex.GetPointIds().SetId(3, i + ul) hex.GetPointIds().SetId(4, i + lu) hex.GetPointIds().SetId(5, i + 1 + lu) hex.GetPointIds().SetId(6, i + 1 + uu) hex.GetPointIds().SetId(7, i + uu) ug.InsertNextCell(hex.GetCellType(), hex.GetPointIds()) gids = vtk.vtkIdTypeArray() gids.SetName("GlobalIds") if parent_id == 0: Dx = grid_desc["create_grid"][1]["Cx"] Dy = grid_desc["create_grid"][1]["Cy"] xc = range(chunk_info["x"][0], chunk_info["x"][1]+1) yc = range(chunk_info["y"][0], chunk_info["y"][1]+1) zc = range(chunk_info["z"][0], chunk_info["z"][1]+1) for k in range(ndims[2]-1): zindex = (zc[k]-1)*Dx*Dy for j in range(ndims[1]-1): yindex = (yc[j]-1)*Dx for i in range(ndims[0]-1): gids.InsertNextTuple1(xc[i]+yindex+zindex) else: for i in range(ug.GetNumberOfCells()): if parent_bit_mask == -1: gids.InsertNextTuple1(parent_id) else: gids.InsertNextTuple1((i+1)*(2**parent_bit_mask) + parent_id) ug.GetCellData().AddArray(gids) ug.GetCellData().SetActiveGlobalIds("GlobalIds") return ug
def find_3d_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 a3 = spacing[2]/2.0 index = 1 for k in range(ndims[2]-1): p3 = a3 + origin[2] + k*spacing[2] 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*(p3-p03)) rhs = a1*math.fabs(n1) + a2*math.fabs(n2) + a3*math.fabs(n3) if d < rhs or math.fabs(d-rhs) < 0.000001: ug = vtk.vtkUnstructuredGrid() points = vtk.vtkPoints() for pk in range(2): k_offset = pk*spacing[2] 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, \ p3 - a3 + k_offset) ug.SetPoints(points) hex = vtk.vtkHexahedron() hex.GetPointIds().SetId(0, 0) hex.GetPointIds().SetId(1, 1) hex.GetPointIds().SetId(2, 3) hex.GetPointIds().SetId(3, 2) hex.GetPointIds().SetId(4, 4) hex.GetPointIds().SetId(5, 5) hex.GetPointIds().SetId(6, 7) hex.GetPointIds().SetId(7, 6) ug.InsertNextCell(hex.GetCellType(), hex.GetPointIds()) gids = vtk.vtkIdTypeArray() gids.SetName("GlobalIds") if parent_id == 0: Dx = grid_desc["create_grid"][1]["Cx"] Dy = grid_desc["create_grid"][1]["Cy"] xc = range(chunk_info["x"][0], chunk_info["x"][1]+1) yc = range(chunk_info["y"][0], chunk_info["y"][1]+1) zc = range(chunk_info["z"][0], chunk_info["z"][1]+1) zindex = (zc[k]-1)*Dx*Dy yindex = (yc[j]-1)*Dx gids.InsertNextTuple1(xc[i]+yindex+zindex) 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
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
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()
material_number = vtk.vtkIntArray() material_number.SetNumberOfValues(base.GetNumberOfCells()*(num_surfaces-1)) material_number.SetName("material") if opts.verbose: print "Inserting", base.GetNumberOfCells()*(num_surfaces-1), "hexahedra in", out_vtu ptids = vtk.vtkIdList() current_hexid = 0 for cellid in range(base.GetNumberOfCells()): if base.GetCellType(cellid) != 9: print "Cannot form a valid cosflow mesh with non-quads in the base" print cellid, base.GetCellType(cellid) sys.exit(2) base.GetCellPoints(cellid, ptids) quad_pts = [ptids.GetId(pt) for pt in range(4)] for surf_num in range(num_surfaces-1): hex = vtk.vtkHexahedron().GetPointIds() contains_shifted_points = False if clockwise[cellid]: for pt in range(4): hex.SetId(pt, quad_pts[pt]+surf_num*num_pts) hex.SetId(pt+4, quad_pts[pt]+(surf_num+1)*num_pts) contains_shifted_points = contains_shifted_points or pt_shifted[quad_pts[pt]+surf_num*num_pts] or pt_shifted[quad_pts[pt]+(surf_num+1)*num_pts] else: hex.SetId(0, quad_pts[3]+surf_num*num_pts) hex.SetId(1, quad_pts[2]+surf_num*num_pts) hex.SetId(2, quad_pts[1]+surf_num*num_pts) hex.SetId(3, quad_pts[0]+surf_num*num_pts) hex.SetId(4, quad_pts[3]+(surf_num+1)*num_pts) hex.SetId(5, quad_pts[2]+(surf_num+1)*num_pts) hex.SetId(6, quad_pts[1]+(surf_num+1)*num_pts) hex.SetId(7, quad_pts[0]+(surf_num+1)*num_pts)
ids.SetId(4,26) ids.SetId(5,27) ids.SetId(6,29) ids.SetId(7,30) ugrid.InsertNextCell(vox.GetCellType(),ids) # triangle tri = vtk.vtkTriangle() ids.SetNumberOfIds(3) ids.SetId(0,31) ids.SetId(1,32) ids.SetId(2,33) ugrid.InsertNextCell(tri.GetCellType(),ids) # 8 hexes hexa = vtk.vtkHexahedron() ids.SetNumberOfIds(8) ids.SetId(0,34) ids.SetId(1,35) ids.SetId(3,37) ids.SetId(2,38) ids.SetId(4,43) ids.SetId(5,44) ids.SetId(7,46) ids.SetId(6,47) ugrid.InsertNextCell(hexa.GetCellType(),ids) ids.SetId(0,35) ids.SetId(1,36) ids.SetId(3,38) ids.SetId(2,39)
def metis_reorder(verbose, vtk_data): """ Reorder a mesh using METIS @type verbose: bool @param verbose: whether to print progress to screen @type vtk_data: vtkDataSet @param vtk_data: contains a mesh to be reordered using METIS. @rtype: vtkDataSet @return: the mesh which has been reordered """ if verbose: print " Metis Reorder: Finding all adjacent nodes" atn = {} # stands for "attached to node". note, in a finite element all nodes are attached to each other for ptid in range(vtk_data.GetNumberOfPoints()): atn[ptid+1] = [] # metis expects point ids starting at 1 for cellid in range(vtk_data.GetNumberOfCells()): the_cell = vtk_data.GetCell(cellid) num_pts = the_cell.GetNumberOfPoints() noc = [the_cell.GetPointId(ptid)+1 for ptid in range(num_pts)] # stands for "nodes of cell" - the "+1" is so metis gets point ids starting at 1 for ptid in range(num_pts): atn[noc[ptid]] += noc else: print "Reordering has not yet been implemented for this type of mesh" # it's easy enough to do: just need to build the atn for each node if verbose: print " Metis Reorder: Forming sets of links" num_links = 0 # this double-counts links, as a link between ptid A and B is also a link between ptid B and A for ptid in range(vtk_data.GetNumberOfPoints()): atn[ptid+1] = map(str, set(atn[ptid+1]) - set([ptid+1])) num_links += len(atn[ptid+1]) if verbose: print " Metis Reorder: Outputting to METIS graph" f = open("for_metis.txt", 'w') f.write(str(vtk_data.GetNumberOfPoints()) + " " + str(num_links/2) + "\n") for ptid in range(vtk_data.GetNumberOfPoints()): f.write(" ".join(atn[ptid+1]) + "\n") f.close() if verbose: print " Metis Reorder: Doing the reordering" cmd = os.path.join("/apps/geomodel/svn/branch5/source/metis-4.0.3/", "onmetis") cmd += " " + "for_metis.txt" subprocess.call(cmd, shell=True) f = open("for_metis.txt.iperm", 'r') iperm = [int(nn) for nn in f.readlines()] # note, that .iperm file starts with ordering 0, not 1. f.close() if verbose: print "Building re-ordered mesh" sld = vtk.vtkUnstructuredGrid() rpts = vtk.vtkPoints() rpts.SetNumberOfPoints(vtk_data.GetNumberOfPoints()) for ptid in range(vtk_data.GetNumberOfPoints()): xyz = vtk_data.GetPoint(ptid) rpts.InsertPoint(iperm[ptid], xyz) sld.SetPoints(rpts) sld.Update() ptids = vtk.vtkIdList() for cellid in range(vtk_data.GetNumberOfCells()): hex = vtk.vtkHexahedron().GetPointIds() # generalise this stuff for other cell types vtk_data.GetCellPoints(cellid, ptids) for pt in range(8): hex.SetId(pt, iperm[ptids.GetId(pt)]) sld.InsertNextCell(12, hex) return sld
def addVoxels( ugrid, verbose=1): myVTK.myPrint(verbose, "*** addVoxels ***") n_points = ugrid.GetPoints().GetNumberOfPoints() seed_point = int(n_points/2) point_locator = myVTK.getPointLocator(ugrid) n_closest_points = 100 closest_points = vtk.vtkIdList() point_locator.FindClosestNPoints( n_closest_points, ugrid.GetPoint(seed_point), closest_points) P0 = numpy.array(ugrid.GetPoint(closest_points.GetId(0))) #print "P0 = " + str(P0) P1 = numpy.array(ugrid.GetPoint(closest_points.GetId(1))) #print "P1 = " + str(P1) X = P1-P0 dX = numpy.linalg.norm(X) X /= dX #print "X = " + str(X) #print "dX = " + str(dX) for k_point in xrange(2, n_closest_points): #print "k_point = " + str(k_point) P2 = numpy.array(ugrid.GetPoint(closest_points.GetId(k_point))) Y = P2-P0 dY = numpy.linalg.norm(Y) Y /= dY #print "P2 = " + str(P2) #print "Y = " + str(Y) #print "dY = " + str(dY) #print "numpy.dot(Y, X) = " + str(numpy.dot(Y, X)) if (abs(numpy.dot(Y, X)) < 0.001): Y = P2-P0 dY = numpy.linalg.norm(Y) Y /= dY break #print "Y = " + str(Y) #print "dY = " + str(dY) Z = numpy.cross(X, Y) dZ_list = [] for k_point in xrange(2, n_closest_points): #print "k_point = " + str(k_point) P3 = numpy.array(ugrid.GetPoint(closest_points.GetId(k_point))) ZZ = P3-P0 dZ = numpy.linalg.norm(ZZ) ZZ /= dZ #print "P3 = " + str(P3) #print "ZZ = " + str(ZZ) #print "dZ = " + str(dZ) #print "numpy.dot(ZZ, Z) = " + str(numpy.dot(ZZ, Z)) if (abs(numpy.dot(ZZ, Z)) > 0.999): dZ_list.append(dZ) dZ = min(dZ_list) #print "Z = " + str(Z) #print "dZ = " + str(dZ) #print "numpy.dot(Y, X) = " + str(numpy.dot(Y, X)) #print "numpy.dot(Z, X) = " + str(numpy.dot(Z, X)) #print "numpy.dot(Z, Y) = " + str(numpy.dot(Z, Y)) points = vtk.vtkPoints() point_locator = vtk.vtkPointLocator() point_locator.InitPointInsertion(points, ugrid.GetBounds()) radius = min(dX, dY, dZ)/2 cell = vtk.vtkHexahedron() cell_array = vtk.vtkCellArray() for k_point in xrange(n_points): P = numpy.array(ugrid.GetPoint(k_point)) point_ids = [] for pm_Z in [-1,+1]: for pm_Y in [-1,+1]: if (pm_Y == -1): pm_X_list = [-1,+1] elif (pm_Y == +1): pm_X_list = [+1,-1] for pm_X in pm_X_list: PP = P + pm_Z * (dZ/2) * Z + pm_Y * (dY/2) * Y + pm_X * (dX/2) * X if (points.GetNumberOfPoints() == 0): point_id = point_locator.InsertNextPoint(PP) else: point_id = point_locator.FindClosestInsertedPoint(PP) dist = numpy.linalg.norm(points.GetPoint(point_id)-PP) if (dist > radius): point_id = point_locator.InsertNextPoint(PP) #point_id = point_locator.IsInsertedPoint(PP) #if (point_id == -1): #point_id = point_locator.InsertNextPoint(PP) point_ids.append(point_id) for i in xrange(8): cell.GetPointIds().SetId(i, point_ids[i]) cell_array.InsertNextCell(cell) new_ugrid = vtk.vtkUnstructuredGrid() new_ugrid.SetPoints(points) new_ugrid.SetCells(vtk.VTK_HEXAHEDRON, cell_array) n_arrays = ugrid.GetPointData().GetNumberOfArrays() for k_array in xrange(n_arrays): new_ugrid.GetCellData().AddArray(ugrid.GetPointData().GetArray(k_array)) return new_ugrid
def mapElements(self, points, points2, nidMap, model, j): self.eidMap = {} i = 0 for (eid, element) in sorted(model.elements.iteritems()): self.eidMap[eid] = i #print element.type if isinstance(element, CTRIA3) or isinstance(element, CTRIAR): #print "ctria3" elem = vtkTriangle() nodeIDs = element.nodeIDs() elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]]) elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]]) elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]]) self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) elif isinstance(element, CTRIA6): nodeIDs = element.nodeIDs() if None not in nodeIDs: elem = vtkQuadraticTriangle() elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]]) elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]]) elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]]) else: elem = vtkTriangle() elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]]) elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]]) elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]]) self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) elif isinstance(element, CTRIAX6): # midside nodes are required, nodes out of order nodeIDs = element.nodeIDs() if None not in nodeIDs: elem = vtkQuadraticTriangle() elem.GetPointIds().SetId(3, nidMap[nodeIDs[1]]) elem.GetPointIds().SetId(4, nidMap[nodeIDs[3]]) elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]]) else: elem = vtkTriangle() elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]]) elem.GetPointIds().SetId(1, nidMap[nodeIDs[2]]) elem.GetPointIds().SetId(2, nidMap[nodeIDs[4]]) #a = [0,2,4] #msg = "CTRIAX6 %i %i %i" %(nidMap[nodeIDs[a[0]]], # nidMap[nodeIDs[a[1]]], # nidMap[nodeIDs[a[2]]] ) #raise RuntimeError(msg) #sys.stdout.flush() #elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]]) #elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]]) #elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]]) self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) elif (isinstance(element, CQUAD4) or isinstance(element, CSHEAR) or isinstance(element, CQUADR)): nodeIDs = element.nodeIDs() elem = vtkQuad() elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]]) elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]]) elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]]) elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]]) self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) elif isinstance(element, CQUAD8): nodeIDs = element.nodeIDs() if None not in nodeIDs: elem = vtkQuadraticQuad() elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]]) elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]]) elem.GetPointIds().SetId(6, nidMap[nodeIDs[6]]) elem.GetPointIds().SetId(7, nidMap[nodeIDs[7]]) else: elem = vtkQuad() elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]]) elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]]) elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]]) elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]]) self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) elif isinstance(element, CTETRA4): elem = vtkTetra() nodeIDs = element.nodeIDs() elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]]) elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]]) elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]]) elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]]) self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) elif isinstance(element, CTETRA10): nodeIDs = element.nodeIDs() if None not in nodeIDs: elem = vtkQuadraticTetra() elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]]) elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]]) elem.GetPointIds().SetId(6, nidMap[nodeIDs[6]]) elem.GetPointIds().SetId(7, nidMap[nodeIDs[7]]) elem.GetPointIds().SetId(8, nidMap[nodeIDs[8]]) elem.GetPointIds().SetId(9, nidMap[nodeIDs[9]]) else: elem = vtkTetra() elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]]) elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]]) elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]]) elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]]) self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) elif isinstance(element, CPENTA6): elem = vtkWedge() nodeIDs = element.nodeIDs() elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]]) elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]]) elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]]) elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]]) elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]]) elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]]) self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) elif isinstance(element, CPENTA15): nodeIDs = element.nodeIDs() if None not in nodeIDs: elem = vtkQuadraticWedge() elem.GetPointIds().SetId(6, nidMap[nodeIDs[6]]) elem.GetPointIds().SetId(7, nidMap[nodeIDs[7]]) elem.GetPointIds().SetId(8, nidMap[nodeIDs[8]]) elem.GetPointIds().SetId(9, nidMap[nodeIDs[9]]) elem.GetPointIds().SetId(10, nidMap[nodeIDs[10]]) elem.GetPointIds().SetId(11, nidMap[nodeIDs[11]]) elem.GetPointIds().SetId(12, nidMap[nodeIDs[12]]) elem.GetPointIds().SetId(13, nidMap[nodeIDs[13]]) elem.GetPointIds().SetId(14, nidMap[nodeIDs[14]]) else: elem = vtkWedge() elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]]) elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]]) elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]]) elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]]) elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]]) elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]]) self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) elif isinstance(element, CHEXA8): nodeIDs = element.nodeIDs() elem = vtkHexahedron() elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]]) elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]]) elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]]) elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]]) elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]]) elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]]) elem.GetPointIds().SetId(6, nidMap[nodeIDs[6]]) elem.GetPointIds().SetId(7, nidMap[nodeIDs[7]]) self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) elif isinstance(element, CHEXA20): nodeIDs = element.nodeIDs() #print "nodeIDs = ",nodeIDs if None not in nodeIDs: elem = vtkQuadraticHexahedron() elem.GetPointIds().SetId(8, nidMap[nodeIDs[8]]) elem.GetPointIds().SetId(9, nidMap[nodeIDs[9]]) elem.GetPointIds().SetId(10, nidMap[nodeIDs[10]]) elem.GetPointIds().SetId(11, nidMap[nodeIDs[11]]) elem.GetPointIds().SetId(12, nidMap[nodeIDs[12]]) elem.GetPointIds().SetId(13, nidMap[nodeIDs[13]]) elem.GetPointIds().SetId(14, nidMap[nodeIDs[14]]) elem.GetPointIds().SetId(15, nidMap[nodeIDs[15]]) elem.GetPointIds().SetId(16, nidMap[nodeIDs[16]]) elem.GetPointIds().SetId(17, nidMap[nodeIDs[17]]) elem.GetPointIds().SetId(18, nidMap[nodeIDs[18]]) elem.GetPointIds().SetId(19, nidMap[nodeIDs[19]]) else: elem = vtkHexahedron() elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]]) elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]]) elem.GetPointIds().SetId(2, nidMap[nodeIDs[2]]) elem.GetPointIds().SetId(3, nidMap[nodeIDs[3]]) elem.GetPointIds().SetId(4, nidMap[nodeIDs[4]]) elem.GetPointIds().SetId(5, nidMap[nodeIDs[5]]) elem.GetPointIds().SetId(6, nidMap[nodeIDs[6]]) elem.GetPointIds().SetId(7, nidMap[nodeIDs[7]]) self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) elif (isinstance(element, LineElement) or isinstance(element, SpringElement)): elem = vtk.vtkLine() nodeIDs = element.nodeIDs() elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]]) elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]]) self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) ### elif isinstance(element, CONM2): # not perfectly located del self.eidMap[eid] i -= 1 nid = element.Nid() c = element.Centroid() elem = vtk.vtkVertex() #elem = vtk.vtkSphere() #elem.SetRadius(1.0) #print str(element) points2.InsertPoint(j, *c) elem.GetPointIds().SetId(0, j) #elem.SetCenter(points.GetPoint(nidMap[nid])) self.grid2.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) j += 1 else: del self.eidMap[eid] i -= 1 print("skipping %s" % (element.type)) i += 1 ### self.grid.SetPoints(points) self.grid2.SetPoints(points2) #self.grid.GetPointData().SetScalars(self.gridResult) #print dir(self.grid) #.SetNumberOfComponents(0) #self.grid.GetCellData().SetNumberOfTuples(1); #self.grid.GetCellData().SetScalars(self.gridResult) self.grid.Modified() self.grid2.Modified() self.grid.Update() self.grid2.Update() print("updated grid")
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()
def read(self): self.num_times = 1 self.times = [0.0] filename = self.config['filename'] # check if we are reading a ground or air conc if filename.find('Gconc') != -1: dim = 2 cell_type = vtk.VTK_QUAD else: dim = 3 cell_type = vtk.VTK_HEXAHEDRON print 'reading data...' data = np.genfromtxt(filename, delimiter=',') data = reorder.reorder(data, 0, dim) print 'done' num_pts = data.shape[0] var = vtk.vtkFloatArray() varname = os.path.basename(filename).split('_')[0] var.SetName(varname) var.SetNumberOfValues(num_pts) print 'creating points...' pts = vtk.vtkPoints() pts.SetNumberOfPoints(num_pts) if dim == 2: for i in xrange(0, num_pts): pts.SetPoint(i, data[i,0], data[i,1], 0.0) var.SetValue(i, data[i,2]) else: for i in xrange(0, num_pts): pts.SetPoint(i, data[i,0], data[i,1], data[i,2]) var.SetValue(i, data[i,3]) print 'done' print 'creating cells...' cell_array = vtk.vtkCellArray() coord_x, indices = np.unique(data[:,0], return_index=True) indices_x = np.append(indices, num_pts) if dim == 2: for i in xrange(0, coord_x.shape[0]-1): for j in xrange(0, indices_x[i+1]-indices_x[i]-1): quad = vtk.vtkQuad() quad.GetPointIds().SetId(0, indices_x[i] +j) quad.GetPointIds().SetId(1, indices_x[i+1]+j) quad.GetPointIds().SetId(2, indices_x[i+1]+j+1) quad.GetPointIds().SetId(3, indices_x[i] +j+1) cell_array.InsertNextCell(quad) else: for i in xrange(0, coord_x.shape[0]-1): plane_b = data[indices_x[i]:indices_x[i+1]] coord_y_b, indices_y_b = np.unique(plane_b[:,1], return_index=True) indices_y_b = np.append(indices_y_b, plane_b.shape[0]) plane_f = data[indices_x[i+1]:indices_x[i+2]] coord_y_f, indices_y_f = np.unique(plane_f[:,1], return_index=True) indices_y_f = np.append(indices_y_f, plane_f.shape[0]) for j in xrange(0, coord_y_b.shape[0]-1): for k in xrange(0, indices_y_b[j+2]-indices_y_b[j+1]-1): hexa = vtk.vtkHexahedron() p = [] p.append(indices_x[i] +indices_y_b[j] +k ) p.append(indices_x[i] +indices_y_b[j+1]+k ) p.append(indices_x[i] +indices_y_b[j+1]+k+1) p.append(indices_x[i] +indices_y_b[j] +k+1) p.append(indices_x[i+1]+indices_y_f[j] +k ) p.append(indices_x[i+1]+indices_y_f[j+1]+k ) p.append(indices_x[i+1]+indices_y_f[j+1]+k+1) p.append(indices_x[i+1]+indices_y_f[j] +k+1) hexa = vtk.vtkHexahedron() for l in range(0,8): hexa.GetPointIds().SetId(l, p[l]) cell_array.InsertNextCell(hexa) print 'done' self.grid.append(vtk.vtkUnstructuredGrid()) self.grid[0].SetPoints(pts) self.grid[0].SetCells(cell_type, cell_array) self.grid[0].GetPointData().SetScalars(var)
def main(): colors = vtk.vtkNamedColors() # Setup the coordinates of eight points # (the two faces must be in counter clockwise order as viewed from the # outside) pointCoords = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 1.0], [1.0, 1.0, 1.0], [0.0, 1.0, 1.0]] # Create the points and a hexahedron from the points. points = vtk.vtkPoints() hexa = vtk.vtkHexahedron() for i in range(0, len(pointCoords)): points.InsertNextPoint(pointCoords[i]) hexa.GetPointIds().SetId(i, i) # Add the hexahedron to a cell array. hexs = vtk.vtkCellArray() hexs.InsertNextCell(hexa) # Add the points and hexahedron to an unstructured grid. uGrid = vtk.vtkUnstructuredGrid() uGrid.SetPoints(points) uGrid.InsertNextCell(hexa.GetCellType(), hexa.GetPointIds()) # Extract the outer (polygonal) surface. surface = vtk.vtkDataSetSurfaceFilter() surface.SetInputData(uGrid) surface.Update() aBeamMapper = vtk.vtkDataSetMapper() aBeamMapper.SetInputConnection(surface.GetOutputPort()) aBeamActor = vtk.vtkActor() aBeamActor.SetMapper(aBeamMapper) aBeamActor.AddPosition(0, 0, 0) aBeamActor.GetProperty().SetColor(colors.GetColor3d("Yellow")) aBeamActor.GetProperty().SetOpacity(0.60) aBeamActor.GetProperty().EdgeVisibilityOn() aBeamActor.GetProperty().SetEdgeColor(colors.GetColor3d("Black")) aBeamActor.GetProperty().SetLineWidth(1.5) # Create a plane to cut, here it cuts in the XZ direction # (xz normal=(1,0,0) XY =(0,0,1), YZ =(0,1,0) plane = vtk.vtkPlane() plane.SetOrigin(0.5, 0, 0) plane.SetNormal(1, 0, 0) # Create cutter cutter = vtk.vtkCutter() cutter.SetCutFunction(plane) cutter.SetInputData(aBeamActor.GetMapper().GetInput()) cutter.Update() cutterMapper = vtk.vtkPolyDataMapper() cutterMapper.SetInputConnection(cutter.GetOutputPort()) # Create plane actor planeActor = vtk.vtkActor() planeActor.GetProperty().SetColor(colors.GetColor3d("Red")) planeActor.GetProperty().SetLineWidth(2) planeActor.SetMapper(cutterMapper) # Create a renderer, render window, and interactor renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.SetWindowName("Dataset Surface") renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) # Add the actors to the scene renderer.AddActor(aBeamActor) renderer.AddActor(planeActor) renderer.SetBackground(colors.GetColor3d("Seashell")) renderer.ResetCamera() renderer.GetActiveCamera().Azimuth(30) renderer.GetActiveCamera().Elevation(30) # Render and interact renderWindow.Render() renderWindowInteractor.Start()
def add_3d_bar_element(bar_type, ptype, pid_ref, n1, n2, xform, ugrid, node0, points_list, add_to_ugrid=True): """adds a 3d bar element to the unstructured grid""" if ptype in ['PBARL']: dim1 = dim2 = pid_ref.dim #bar_type = pid_ref.Type elif ptype in ['PBEAML']: dim1 = pid_ref.dim[0, :] dim2 = pid_ref.dim[-1, :] else: dim1 = dim2 = None if bar_type == 'BAR': pointsi = bar_faces(n1, n2, xform, dim1, dim2) elem = vtk.vtkHexahedron() point_ids = elem.GetPointIds() point_ids.SetId(0, node0 + 0) point_ids.SetId(1, node0 + 1) point_ids.SetId(2, node0 + 2) point_ids.SetId(3, node0 + 3) point_ids.SetId(4, node0 + 4) point_ids.SetId(5, node0 + 5) point_ids.SetId(6, node0 + 6) point_ids.SetId(7, node0 + 7) if add_to_ugrid: ugrid.InsertNextCell(12, point_ids) points_list.append(pointsi) node0 += 8 return node0 elif bar_type == 'ROD': faces, pointsi, dnode = rod_faces(n1, n2, xform, dim1, dim2) face_idlist = faces_to_element_facelist(faces, node0) node0 += dnode elif bar_type == 'TUBE': faces, pointsi, dnode = tube_faces(n1, n2, xform, dim1, dim2) face_idlist = faces_to_element_facelist(faces, node0) node0 += dnode elif bar_type == 'BOX': faces, pointsi = box_faces(n1, n2, xform, dim1, dim2) face_idlist = faces_to_element_facelist(faces, node0) node0 += 16 elif bar_type == 'L': faces, pointsi = l_faces(n1, n2, xform, dim1, dim2) face_idlist = faces_to_element_facelist(faces, node0) node0 += 12 elif bar_type == 'CHAN': faces, pointsi = chan_faces(n1, n2, xform, dim1, dim2) face_idlist = faces_to_element_facelist(faces, node0) node0 += 16 elif bar_type == 'CHAN1': faces, pointsi = chan1_faces(n1, n2, xform, dim1, dim2) face_idlist = faces_to_element_facelist(faces, node0) node0 += 16 elif bar_type == 'T': faces, pointsi = t_faces(n1, n2, xform, dim1, dim2) face_idlist = faces_to_element_facelist(faces, node0) node0 += 16 elif bar_type == 'T1': faces, pointsi = t1_faces(n1, n2, xform, dim1, dim2) face_idlist = faces_to_element_facelist(faces, node0) node0 += 16 elif bar_type == 'T2': faces, pointsi = t2_faces(n1, n2, xform, dim1, dim2) face_idlist = faces_to_element_facelist(faces, node0) node0 += 16 elif bar_type == 'I': faces, pointsi = i_faces(n1, n2, xform, dim1, dim2) assert pointsi.shape[0] == 24, pointsi.shape face_idlist = faces_to_element_facelist(faces, node0) node0 += 24 elif bar_type == 'I1': faces, pointsi = i1_faces(n1, n2, xform, dim1, dim2) assert pointsi.shape[0] == 24, pointsi.shape face_idlist = faces_to_element_facelist(faces, node0) node0 += 24 elif bar_type == 'H': faces, pointsi = h_faces(n1, n2, xform, dim1, dim2) assert pointsi.shape[0] == 24, pointsi.shape face_idlist = faces_to_element_facelist(faces, node0) node0 += 24 elif bar_type == 'Z': faces, pointsi = z_faces(n1, n2, xform, dim1, dim2) face_idlist = faces_to_element_facelist(faces, node0) node0 += 16 elif bar_type == 'HEXA': faces, pointsi = hexa_faces(n1, n2, xform, dim1, dim2) face_idlist = faces_to_element_facelist(faces, node0) node0 += 12 elif bar_type == 'HAT': faces, pointsi = hat_faces(n1, n2, xform, dim1, dim2) face_idlist = faces_to_element_facelist(faces, node0) node0 += 24 else: print('skipping 3d bar_type = %r' % bar_type) return node0 if add_to_ugrid: ugrid.InsertNextCell(vtk.VTK_POLYHEDRON, face_idlist) points_list.append(pointsi) return node0
def getVoxels(ugrid, verbose=0): mypy.my_print(verbose, "*** getVoxels ***") n_points = ugrid.GetPoints().GetNumberOfPoints() seed_point = int(n_points / 2) point_locator = myvtk.getPointLocator(ugrid) n_closest_points = 100 closest_points = vtk.vtkIdList() point_locator.FindClosestNPoints(n_closest_points, ugrid.GetPoint(seed_point), closest_points) P0 = numpy.empty(3) P1 = numpy.empty(3) P2 = numpy.empty(3) P3 = numpy.empty(3) ugrid.GetPoint(closest_points.GetId(0), P0) #print "P0 = "+str(P0) ugrid.GetPoint(closest_points.GetId(1), P1) #print "P1 = "+str(P1) X = P1 - P0 dX = numpy.linalg.norm(X) X /= dX #print "X = "+str(X) #print "dX = "+str(dX) for k_point in xrange(2, n_closest_points): #print "k_point = "+str(k_point) ugrid.GetPoint(closest_points.GetId(k_point), P2) Y = P2 - P0 dY = numpy.linalg.norm(Y) Y /= dY #print "P2 = "+str(P2) #print "Y = "+str(Y) #print "dY = "+str(dY) #print "numpy.dot(Y, X) = "+str(numpy.dot(Y, X)) if (abs(numpy.dot(Y, X)) < 0.001): Y = P2 - P0 dY = numpy.linalg.norm(Y) Y /= dY break #print "Y = "+str(Y) #print "dY = "+str(dY) Z = numpy.cross(X, Y) dZ_list = [] for k_point in xrange(2, n_closest_points): #print "k_point = "+str(k_point) ugrid.GetPoint(closest_points.GetId(k_point), P3) ZZ = P3 - P0 dZ = numpy.linalg.norm(ZZ) ZZ /= dZ #print "P3 = "+str(P3) #print "ZZ = "+str(ZZ) #print "dZ = "+str(dZ) #print "numpy.dot(ZZ, Z) = "+str(numpy.dot(ZZ, Z)) if (abs(numpy.dot(ZZ, Z)) > 0.999): dZ_list.append(dZ) dZ = min(dZ_list) #print "Z = "+str(Z) #print "dZ = "+str(dZ) #print "numpy.dot(Y, X) = "+str(numpy.dot(Y, X)) #print "numpy.dot(Z, X) = "+str(numpy.dot(Z, X)) #print "numpy.dot(Z, Y) = "+str(numpy.dot(Z, Y)) points = vtk.vtkPoints() point_locator = vtk.vtkPointLocator() point_locator.InitPointInsertion(points, ugrid.GetBounds()) radius = min(dX, dY, dZ) / 2 cell = vtk.vtkHexahedron() cell_array = vtk.vtkCellArray() P = numpy.empty(3) PPP = numpy.empty(3) for k_point in xrange(n_points): ugrid.GetPoint(k_point, P) point_ids = [] for pm_Z in [-1, +1]: for pm_Y in [-1, +1]: if (pm_Y == -1): pm_X_list = [-1, +1] elif (pm_Y == +1): pm_X_list = [+1, -1] for pm_X in pm_X_list: PP = P + pm_Z * (dZ / 2) * Z + pm_Y * ( dY / 2) * Y + pm_X * (dX / 2) * X if (points.GetNumberOfPoints() == 0): point_id = point_locator.InsertNextPoint(PP) else: point_id = point_locator.FindClosestInsertedPoint(PP) points.GetPoint(point_id, PPP) dist = numpy.linalg.norm(PPP - PP) if (dist > radius): point_id = point_locator.InsertNextPoint(PP) #point_id = point_locator.IsInsertedPoint(PP) #if (point_id == -1): #point_id = point_locator.InsertNextPoint(PP) point_ids.append(point_id) for i in xrange(8): cell.GetPointIds().SetId(i, point_ids[i]) cell_array.InsertNextCell(cell) new_ugrid = vtk.vtkUnstructuredGrid() new_ugrid.SetPoints(points) new_ugrid.SetCells(vtk.VTK_HEXAHEDRON, cell_array) n_arrays = ugrid.GetPointData().GetNumberOfArrays() for k_array in xrange(n_arrays): new_ugrid.GetCellData().AddArray( ugrid.GetPointData().GetArray(k_array)) return new_ugrid
files = glob.glob1("Spherical_3D", "*_grid") files = [f for f in files if (args.initial is None or int(f.split("_")[0]) >= args.initial) \ and (args.final is None or int(f.split("_")[0]) <= args.final)] files = sorted(files, key = lambda f: int(f.split("_")[0])) f3d = Spherical_3D(files[0]) ntheta = f3d.ntheta nphi = f3d.nphi nr = f3d.nr rs = f3d.rs thetas = f3d.thetas phis = np.linspace(0, 2*np.pi, nphi+1) VTK_HEXAHEDRON = vtk.vtkHexahedron().GetCellType() ugrid = vtk.vtkUnstructuredGrid() # Add the points points = vtk.vtkPoints() points.SetDataTypeToDouble() index = 0 xyzToNode = [[[] for j in xrange(ntheta)] for i in xrange(nr)] for i, r in enumerate(rs): for j, theta in enumerate(thetas): for k, phi in enumerate(phis[:-1]): points.InsertNextPoint(r*np.cos(phi)*np.sin(theta), \ r*np.sin(phi)*np.sin(theta), \ r*np.cos(theta))
meshMapper.SetInput(surface) meshMapper.ScalarVisibilityOff() # do not use scalar data for coloring meshActor = vtk.vtkActor() meshActor.SetMapper(meshMapper) meshActor.GetProperty().SetOpacity(0.2) meshActor.GetProperty().SetColor(1.0, 1.0, 0) meshActor.GetProperty().BackfaceCullingOn() boxpoints = vtk.vtkPoints() for n in range(8): P = [ rotatedbox[0][(n / 1) % 2], rotatedbox[1][(n / 2) % 2], rotatedbox[2][(n / 4) % 2] ] boxpoints.InsertNextPoint(list(np.dot(R.T, np.array(P)))) box = vtk.vtkHexahedron() for n, i in enumerate([0, 1, 3, 2, 4, 5, 7, 6]): box.GetPointIds().SetId(n, i) boxgrid = vtk.vtkUnstructuredGrid() boxgrid.SetPoints(boxpoints) boxgrid.InsertNextCell(box.GetCellType(), box.GetPointIds()) boxsurfaceFilter = vtk.vtkDataSetSurfaceFilter() boxsurfaceFilter.SetInput(boxgrid) boxsurfaceFilter.Update() boxsurface = boxsurfaceFilter.GetOutput() boxMapper = vtk.vtkDataSetMapper() boxMapper.SetInput(boxsurface) boxActor = vtk.vtkActor() boxActor.SetMapper(boxMapper) boxActor.GetProperty().SetLineWidth(2.0)
def RenderAEMmodel(self): self.renWin.RemoveRenderer(self.renderer) self.renderer = vtk.vtkRenderer() points_free = vtk.vtkPoints() points_fix = vtk.vtkPoints() uGrid_free = vtk.vtkUnstructuredGrid() uGrid_fix = vtk.vtkUnstructuredGrid() for e in self.AEMmodel.Elements: for crd in self.AEMmodel.Elements[e]['edge_coord']: if crd[2]==0.0: if self.AEMmodel.Elements[e]['dof']=='free': points_free.InsertNextPoint([crd[0],crd[1],0.0]) else: points_fix.InsertNextPoint([crd[0],crd[1],0.0]) else: if self.AEMmodel.Elements[e]['dof']=='free': points_free.InsertNextPoint([crd[0],crd[1],-self.AEMmodel.Elements[e]['thickness']]) else: points_fix.InsertNextPoint([crd[0],crd[1],-self.AEMmodel.Elements[e]['thickness']]) uGrid_free.SetPoints(points_free) uGrid_fix.SetPoints(points_fix) nn=0 for e in self.AEMmodel.Elements: if self.AEMmodel.Elements[e]['dof']=='fix':continue hexa=vtk.vtkHexahedron () for (i,n) in enumerate(range(nn,nn+8)):hexa.GetPointIds().SetId(i,n) nn+=8 uGrid_free.InsertNextCell(hexa.GetCellType(), hexa.GetPointIds()) nn=0 for e in self.AEMmodel.Elements: if self.AEMmodel.Elements[e]['dof']=='free':continue hexa=vtk.vtkHexahedron () for (i,n) in enumerate(range(nn,nn+8)):hexa.GetPointIds().SetId(i,n) nn+=8 uGrid_fix.InsertNextCell(hexa.GetCellType(), hexa.GetPointIds()) # create actor and mapper actor_fix = vtk.vtkActor() actor_free= vtk.vtkActor() mapper_fix = vtk.vtkDataSetMapper() mapper_free = vtk.vtkDataSetMapper() mapper_fix.SetInputData(uGrid_fix) mapper_free.SetInputData(uGrid_free) color=vtk.vtkNamedColors() actor_fix.SetMapper(mapper_fix) actor_fix.GetProperty().EdgeVisibilityOn() if 'Boundary' in self.DisplayMode: actor_fix.GetProperty().SetColor(color.GetColor3ub('Blue')) else: actor_fix.GetProperty().SetColor(color.GetColor3ub('Ivory')) actor_free.SetMapper(mapper_free) actor_free.GetProperty().EdgeVisibilityOn() actor_free.GetProperty().SetColor(color.GetColor3ub('Ivory')) self.renderer.AddActor(actor_fix) self.renderer.AddActor(actor_free) #add steel actor if 'Steel' in self.DisplayMode: pts = vtk.vtkPoints() lines = vtk.vtkCellArray() linesPolyData = vtk.vtkPolyData() for s in self.AEMmodel.Steel: [x0,y0,xf,yf]=self.AEMmodel.Steel[s]['coord'] pts.InsertNextPoint([x0,y0,0.01]) pts.InsertNextPoint([xf,yf,0.01]) ni=0 for s in self.AEMmodel.Steel: sline = vtk.vtkLine() sline.GetPointIds().SetId(0,ni) sline.GetPointIds().SetId(1,ni+1) ni+=2 lines.InsertNextCell(sline) linesPolyData.SetPoints(pts) linesPolyData.SetLines(lines) mapper_steel = vtk.vtkPolyDataMapper() mapper_steel.SetInputData(linesPolyData) actor_steel = vtk.vtkActor() actor_steel.SetMapper(mapper_steel) actor_steel.GetProperty().SetColor(color.GetColor3ub('Red')) self.renderer.AddActor(actor_steel) #add steel actor if 'ElementNo' in self.DisplayMode: esize=self.AEMmodel.ElementSize for e in self.AEMmodel.Elements: eid='{}'.format(self.AEMmodel.Elements[e]['id']) c=self.AEMmodel.Elements[e]['centre'] XText = vtk.vtkVectorText() XText.SetText(eid) XTextMapper = vtk.vtkPolyDataMapper() XTextMapper.SetInputConnection(XText.GetOutputPort()) XActor = vtk.vtkFollower() XActor.SetMapper(XTextMapper) XActor.SetScale(0.25*esize,0.25*esize,0.25*esize) XActor.SetPosition(c[0]-0.25*esize,c[1]-0.25*esize,c[2]+0.25*esize) XActor.GetProperty().SetColor(color.GetColor3ub('Green')) self.renderer.AddActor(XActor) interactor = vtk.vtkInteractorStyleImage() self.renWinInteract.SetInteractorStyle(interactor) self.renWin.AddRenderer(self.renderer) self.renWin.Render()
def mixed_type_unstructured_grid(): """A slightly more complex example of how to generate an unstructured grid with different cell types. Returns a created unstructured grid. """ pts = np.array( [ [0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1], # tetra [2, 0, 0], [3, 0, 0], [3, 1, 0], [2, 1, 0], [2, 0, 1], [3, 0, 1], [3, 1, 1], [2, 1, 1], # Hex ], dtype='float32') # shift the points so we can show both. pts[:, 1] += 2.0 npoints = len(pts) forces = pts # The cells must be int64 because numpy_to_vtkIdTypeArray requires that. # I think it depends on what vtkIdTypeArray() was built with. # nnodes_tetra, (nodes_tetra1) # nnodes_hexa, (nodes_hexa1) cells = np.array( [ 4, 0, 1, 2, 3, # tetra 8, 4, 5, 6, 7, 8, 9, 10, 11 # hex ], dtype='int64') # The offsets for the cells (i.e., the indices where the cells start) # one for each element cell_offsets = np.array([0, 5], dtype='int32') # add one element_type for each element tetra_type = vtk.vtkTetra().GetCellType() # VTK_TETRA == 10 hex_type = vtk.vtkHexahedron().GetCellType() # VTK_HEXAHEDRON == 12 cell_types = np.array([tetra_type, hex_type], dtype='int32') # Create the array of cells vtk_cells = vtk.vtkCellArray() vtk_cells_id_type = numpy_to_vtkIdTypeArray(cells, deep=1) # ncells = 2 vtk_cells.SetCells(2, vtk_cells_id_type) # Now create the unstructured grid ug = vtk.vtkUnstructuredGrid() points_data = numpy_to_vtk(pts, deep=1) points = vtk.vtkPoints() points.SetNumberOfPoints(npoints) points.SetData(points_data) ug.SetPoints(points) # Now just set the cell types and reuse the ug locations and cells #ug.SetCells(cell_types, cell_offsets, vtk_cell_array) ug.SetCells( numpy_to_vtk( cell_types, deep=1, array_type=vtk.vtkUnsignedCharArray().GetDataType(), ), numpy_to_vtk(cell_offsets, deep=1, array_type=vtk.vtkIdTypeArray().GetDataType()), vtk_cells, ) return ug, forces
def from_fea(mesh: pywim.fea.model.Mesh, inc: pywim.fea.result.Increment, outputs: List[str]): points = vtk.vtkPoints() points.SetNumberOfPoints(len(mesh.nodes)) for n in mesh.nodes: points.SetPoint(n.id - 1, n.x, n.y, n.z) grid = vtk.vtkUnstructuredGrid() grid.SetPoints(points) nels = 0 for g in mesh.elements: for c in g.connectivity: if g.type == 'HEXL8' or g.type == 'VOXL' or g.type == 'VOXLA': e = vtk.vtkHexahedron() elif g.type == 'TETL4': e = vtk.vtkTetra() elif g.type == 'WEDL6': e = vtk.vtkWedge() elif g.type == 'PSL4': e = vtk.vtkQuad() elif g.type == 'PSL3': e = vtk.vtkTriangle() elif g.type == 'PSQ6': e = vtk.vtkQuadraticTriangle() else: raise Exception('Unsupported element type: %s' % g.type) ids = e.GetPointIds() i = 0 for nid in c.nodes: ids.SetId(i, nid - 1) i += 1 grid.InsertNextCell(e.GetCellType(), ids) nels += 1 celldata = grid.GetCellData() pointdata = grid.GetPointData() def add_node_results(res: List[pywim.fea.result.Result]): array = vtk.vtkFloatArray() array.SetName(res.name) array.SetNumberOfComponents(res.size) for v in res.values: if res.size == 1: array.InsertNextTuple1(v.data[0]) elif res.size == 3: array.InsertNextTuple3(v.data[0], v.data[1], v.data[2]) elif res.size == 6: array.InsertNextTuple6(v.data[0], v.data[1], v.data[2], v.data[3], v.data[5], v.data[4]) pointdata.AddArray(array) def add_gp_results(res: List[pywim.fea.result.ResultMult]): ngps = 1 for v in res.values: ngps = max(ngps, len(v.values)) # Build a dictionary of element Id to index for quicker searching eid2index = {} index = 0 nlayers = 0 nsectpts = 0 nonlay_ngps = 0 for v in res.values: eid2index[v.id] = index index += 1 if v.values[0].layer == 0: nonlay_ngps = max(nonlay_ngps, len(v.values)) else: nlayers = max(nlayers, max([sv.layer for sv in v.values])) nsectpts = max(nsectpts, max([sv.section_point for sv in v.values])) lay_gp_iter = None nonlay_gp_iter = list(range(nonlay_ngps)) if nlayers > 0: ngps = int(round(ngps / (nlayers * nsectpts))) lay_gp_iter = [] for l in range(nlayers): for k in range(nsectpts): for g in range(ngps): lay_gp_iter.append((l, k, g)) # This is a severe limitation right now: # For layered data we are assuming all elements have the same number of # layers and section points, but we do check each element for total # gauss # pts to handle differences (e.g. WEDL6 vs HEXL8) def get_gauss_point_data(layered_output, elv, gpid): if not layered_output: g = gpid g_out_of_range = elv.values[0].layer > 0 else: this_ngps = int(round(len(elv.values) / (nlayers * nsectpts))) g = this_ngps * (gpid[0] * nsectpts + gpid[1]) + gpid[2] g_out_of_range = gpid[2] >= this_ngps or elv.values[ 0].layer == 0 if len(elv.values) < (g + 1) or g_out_of_range: return [0., 0., 0., 0., 0., 0.] else: return elv.values[g].data for gp_iter in (nonlay_gp_iter, lay_gp_iter): if gp_iter is None: continue for gp in gp_iter: if type(gp) is int: layered_output = False out_name = '{}_G{}'.format(res.name, gp + 1) else: layered_output = True out_name = '{}_L{}_K{}_G{}'.format(res.name, gp[0] + 1, gp[1] + 1, gp[2] + 1) array = vtk.vtkFloatArray() array.SetName(out_name) array.SetNumberOfComponents(res.size) for eid in range(1, nels + 1): elv = res.values[eid2index[eid]] if elv.id != eid: print('Element id mismatch: {} != {}'.format( eid, elv.id)) gpdata = get_gauss_point_data(layered_output, elv, gp) # last two vals intentionally swapped because VTU ordering is XX, YY, ZZ, XY, YZ, XZ if res.size == 1: array.InsertNextTuple1(gpdata[0]) elif res.size == 3: array.InsertNextTuple3(gpdata[0], gpdata[1], gpdata[2]) elif res.size == 6: array.InsertNextTuple6(gpdata[0], gpdata[1], gpdata[2], gpdata[3], gpdata[5], gpdata[4]) celldata.AddArray(array) def add_elem_results(res: List[pywim.fea.result.Result]): array = vtk.vtkFloatArray() array.SetName(res.name) array.SetNumberOfComponents(res.size) for e in res.values: if res.size == 1: array.InsertNextTuple1(e.data[0]) elif res.size == 3: array.InsertNextTuple3(e.data[0], e.data[1], e.data[2]) elif res.size == 6: array.InsertNextTuple6(e.data[0], e.data[1], e.data[2], e.data[3], e.data[5], e.data[4]) celldata.AddArray(array) def add_region_results_by_element(reg_result: RegionResult): elem_stats = reg_result.element_stats() wall_array = vtk.vtkFloatArray() wall_array.SetName('{}_wall'.format(reg_result.name)) wall_array.SetNumberOfComponents(3) skin_array = vtk.vtkFloatArray() skin_array.SetName('{}_skin'.format(reg_result.name)) skin_array.SetNumberOfComponents(3) infill_array = vtk.vtkFloatArray() infill_array.SetName('{}_infill'.format(reg_result.name)) infill_array.SetNumberOfComponents(3) for e in elem_stats.element_regions: if len(e.walls.gauss_point_data) > 0: wall_array.InsertNextTuple3(e.walls.min, e.walls.mean, e.walls.max) else: wall_array.InsertNextTuple3(float('NaN'), float('NaN'), float('NaN')) if len(e.skin.gauss_point_data) > 0: skin_array.InsertNextTuple3(e.skin.min, e.skin.mean, e.skin.max) else: skin_array.InsertNextTuple3(float('NaN'), float('NaN'), float('NaN')) if len(e.infill.gauss_point_data) > 0: infill_array.InsertNextTuple3(e.infill.min, e.infill.mean, e.infill.max) else: infill_array.InsertNextTuple3(float('NaN'), float('NaN'), float('NaN')) celldata.AddArray(wall_array) celldata.AddArray(skin_array) celldata.AddArray(infill_array) if 'node' in outputs: for res in inc.node_results: print('\t\tTranslating {} Node Result'.format(res.name)) add_node_results(res) if 'element' in outputs: for res in inc.element_results: print('\t\tTranslating {} Element Result'.format(res.name)) add_elem_results(res) ''' For now, region specific results are restricted to gauss point data. ''' if 'region' in outputs: try: mat_type = inc.gauss_point_results['material_type'] except StopIteration: raise Exception( 'No material_type information at the gauss points exists. Unable to detect regions.' ) for res in inc.gauss_point_results: if res.name == 'material_type': continue reg_result = region_filter(mat_type, res) if reg_result is None: print( '\tRegion filter on {} gauss point result not supported, skipping this result' .format(res.name)) continue print('\t\tTranslating {} Region Result By Element'.format( res.name)) add_region_results_by_element(reg_result) if 'gauss_point' in outputs: for res in inc.gauss_point_results: if res.name == 'material_type': continue print('\t\tTranslating {} Gauss Point Result'.format(res.name)) add_gp_results(res) return grid
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)
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.AddSurfaceShaderParameter("veinfreq", " 2") aRIBProperty.AddSurfaceShaderParameter("veincolor", "1.0000 1.0000 0.9412") bRIBProperty = vtk.vtkRIBProperty() bRIBProperty.SetVariable("Km", "float") bRIBProperty.SetSurfaceShaderParameter("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() ren.AddLight(aRIBLight) aLight = vtk.vtkLight() aLight.PositionalOn() aLight.SetConeAngle(10.0) aLight.SetIntensity(20.0) ren.AddLight(aLight) ren.ResetCamera() ren.GetActiveCamera().Azimuth(30) ren.GetActiveCamera().Elevation(20) ren.GetActiveCamera().Dolly(2.8) ren.ResetCameraClippingRange() # 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) aRIBLight.SetFocalPoint(ren.GetActiveCamera().GetFocalPoint()) aRIBLight.SetPosition(ren.GetActiveCamera().GetPosition()) aLight.SetFocalPoint(ren.GetActiveCamera().GetFocalPoint()) aLight.SetPosition(ren.GetActiveCamera().GetPosition()) # bascially have IO/Export ? if hasattr(vtk, 'vtkRIBExporter'): rib = vtk.vtkRIBExporter() rib.SetInput(renWin) rib.SetFilePrefix(dir + '/cells') rib.SetTexturePrefix(dir + '/cells') rib.Write() 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()
def readDynaMesh(lsdyna_mesh_filename, cell_type='hexahedron', verbose=0): myVTK.myPrint(verbose, "*** readDynaMesh: "+lsdyna_mesh_filename+" ***") points = vtk.vtkPoints() if (cell_type == 'vertex'): cell_vtk_type = vtk.VTK_VERTEX cell = vtk.vtkVertex() cell_array = vtk.vtkCellArray() elif (cell_type == 'hexahedron'): cell_vtk_type = vtk.VTK_HEXAHEDRON cell = vtk.vtkHexahedron() cell_array = vtk.vtkCellArray() else: print 'Wrong cell type. Aborting.' exit() myVTK.myPrint(verbose-1, "Reading Dyna mesh file...") mesh_file = open(lsdyna_mesh_filename, 'r') context = '' for line in mesh_file: if (line[-1:] == '\n'): line = line[:-1] #myVTK.myPrint(verbose-1, "line ="+line) if line.startswith('$'): continue if (context == 'reading nodes'): if line.startswith('*'): context = '' else: splitted_line = line.split(',') points.InsertNextPoint([float(coord) for coord in splitted_line[1:4]]) if (cell_type == 'vertex'): cell.GetPointIds().SetId(0, points.GetNumberOfPoints()-1) cell_array.InsertNextCell(cell) if (context == 'reading elems'): if line.startswith('*'): context = '' else: splitted_line = line.split(',') if (len(splitted_line) == 3): continue if (cell_type == 'hexahedron'): for k_node in xrange(8): cell.GetPointIds().SetId(k_node, int(splitted_line[2+k_node])-1) cell_array.InsertNextCell(cell) if line.startswith('*NODE'): context = 'reading nodes' if line.startswith('*ELEMENT_SOLID'): context = 'reading elems' mesh_file.close() myVTK.myPrint(verbose-1, "Creating VTK mesh...") ugrid = vtk.vtkUnstructuredGrid() ugrid.SetPoints(points) ugrid.SetCells(cell_vtk_type, cell_array) return ugrid
def readDynaMeshStructured(lsdyna_mesh_file_name, cell_type='hexahedron', verbose=True): if (verbose): print '*** readDynaMesh ***' points = vtk.vtkPoints() if (cell_type == 'vertex'): cell_vtk_type = vtk.VTK_VERTEX cell = vtk.vtkVertex() cell_array = vtk.vtkCellArray() elif (cell_type == 'hexahedron'): cell_vtk_type = vtk.VTK_HEXAHEDRON cell = vtk.vtkHexahedron() cell_array = vtk.vtkCellArray() else: print 'Wrong cell type. Aborting.' exit() if (verbose): print 'Reading Dyna mesh file...' cnt = 1 mesh_file = open(lsdyna_mesh_file_name, '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(',') splitted_line = [] splitted_line.append(line[0:8].replace(" ", "")) splitted_line.append(line[8:24].replace(" ", "")) splitted_line.append(line[25:25 + 16].replace(" ", "")) splitted_line.append(line[25 + 17:50 + 17].replace(" ", "")) print splitted_line points.InsertNextPoint( [float(coord) for coord in splitted_line[1:4]]) if (cell_type == 'vertex'): cell.GetPointIds().SetId(0, points.GetNumberOfPoints() - 1) cell_array.InsertNextCell(cell) if (context == 'reading elems'): if line.startswith('*'): context = '' else: if (cnt % 2 == 0): splitted_line = [] splitted_line.append(line[0:8].replace(" ", "")) splitted_line.append(line[9:16].replace(" ", "")) splitted_line.append(line[17:24].replace(" ", "")) splitted_line.append(line[25:32].replace(" ", "")) splitted_line.append(line[33:40].replace(" ", "")) splitted_line.append(line[41:48].replace(" ", "")) splitted_line.append(line[49:56].replace(" ", "")) splitted_line.append(line[57:64].replace(" ", "")) if (len(splitted_line) == 3): continue if (cell_type == 'hexahedron'): for num_node in range(8): cell.GetPointIds().SetId( num_node, int(splitted_line[num_node]) - 1) cell_array.InsertNextCell(cell) cnt = cnt + 1 if line.startswith('*NODE'): context = 'reading nodes' if line.startswith('*ELEMENT_SOLID'): context = 'reading elems' mesh_file.close() if (verbose): print 'Creating VTK mesh...' ugrid = vtk.vtkUnstructuredGrid() ugrid.SetPoints(points) ugrid.SetCells(cell_vtk_type, cell_array) return ugrid
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 """
def __init__(self, parent = None): QtGui.QMainWindow.__init__(self, parent) self.state = {"test", "stuff", "other"} self.frame = QtGui.QFrame() self.resize(1000,600) self.setWindowTitle('ProteusCFD') self.move(100,100) self.vl = QtGui.QGridLayout() self.vl.setSpacing(10) self.frame.setLayout(self.vl) self.setCentralWidget(self.frame) #create tabs dialog and add it to the layout self.tabs = QtGui.QTabWidget() self.vl.addWidget(self.tabs,0,0) #Setup our tree view self.treeWidget = QtGui.QTreeWidget() self.treeWidget.setHeaderHidden(True) self.addItems(self.treeWidget.invisibleRootItem()) self.treeWidget.itemChanged.connect (self.handleChanged) self.tabs.addTab(self.treeWidget, "Tree") #setup some dummy tabs tab1 = QtGui.QWidget() self.tabs.addTab(tab1, "tab1") tab2 = QtGui.QWidget() self.tabs.addTab(tab2, "tab2") #draw the tabs self.tabs.show() #Setup our menu and actions exitAction = QtGui.QAction('Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Exit application') exitAction.triggered.connect(self.close) saveAction = QtGui.QAction('Save', self) saveAction.setShortcut('Ctril+S') saveAction.setStatusTip('Save config') saveAction.triggered.connect(self.save) loadAction = QtGui.QAction('Load', self) loadAction.setStatusTip('Load config') loadAction.triggered.connect(self.load) self.menubar = self.menuBar() fileMenu = self.menubar.addMenu('&File') fileMenu.addAction(exitAction) fileMenu.addAction(saveAction) fileMenu.addAction(loadAction) self.statusBar().showMessage('Waiting...') #Setup our vtk widget self.vtkWidget = QVTKRenderWindowInteractor(self.frame) self.vl.addWidget(self.vtkWidget, 0, 300) self.ren = vtk.vtkRenderer() self.ren.SetBackground(.5,.8,.5) self.ren.ResetCamera() self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() #create the points P0 = [0.0, 0.0, 0.0] P1 = [1.0, 0.0, 0.0] P2 = [1.0, 1.0, 0.0] P3 = [0.0, 1.0, 0.0] P4 = [0.0, 0.0, 1.0] P5 = [1.0, 0.0, 1.0] P6 = [1.0, 1.0, 1.0] P7 = [0.0, 1.0, 1.0] # Create the points points = vtk.vtkPoints() 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 hex hex = vtk.vtkHexahedron() hex.GetPointIds().SetId(0,0) hex.GetPointIds().SetId(1,1) hex.GetPointIds().SetId(2,2) hex.GetPointIds().SetId(3,3) hex.GetPointIds().SetId(4,4) hex.GetPointIds().SetId(5,5) hex.GetPointIds().SetId(6,6) hex.GetPointIds().SetId(7,7) #create the cells and insert them cells = vtk.vtkCellArray() cells.InsertNextCell(hex) #add the points and cells to unstructured grid grid = vtk.vtkUnstructuredGrid() grid.SetPoints(points) grid.InsertNextCell(hex.GetCellType(), hex.GetPointIds()) #visualize the grid mapper = vtk.vtkDataSetMapper() mapper.SetInput(grid) self.vtkActorList = [] # Create an actor self.vtkActorList.append(vtk.vtkActor()) self.vtkActorList[0].SetMapper(mapper) # Create source source = vtk.vtkSphereSource() source.SetCenter(10, 0, 0) source.SetRadius(5.0) # Create a mapper mapper2 = vtk.vtkPolyDataMapper() mapper2.SetInputConnection(source.GetOutputPort()) # Create an actor self.vtkActorList.append(vtk.vtkActor()) self.vtkActorList[1].SetMapper(mapper2) for actor in self.vtkActorList: self.ren.AddActor(actor) self.show() self.iren.Initialize()
def readDynaMesh(lsdyna_mesh_filename, cell_type="hexahedron", verbose=0): mypy.my_print(verbose, "*** readDynaMesh: "+lsdyna_mesh_filename+" ***") points = vtk.vtkPoints() if (cell_type == "vertex"): cell_vtk_type = vtk.VTK_VERTEX cell = vtk.vtkVertex() cell_array = vtk.vtkCellArray() elif (cell_type == "hexahedron"): cell_vtk_type = vtk.VTK_HEXAHEDRON cell = vtk.vtkHexahedron() cell_array = vtk.vtkCellArray() else: assert (0),\ "Wrong cell type. Aborting." mypy.my_print(verbose-1, "Reading Dyna mesh file...") mesh_file = open(lsdyna_mesh_filename, "r") context = "" for line in mesh_file: if (line[-1:] == "\n"): line = line[:-1] #mypy.my_print(verbose-1, "line ="+line) if line.startswith("$"): continue if (context == "reading nodes"): if line.startswith("*"): context = "" else: splitted_line = line.split(",") points.InsertNextPoint([float(coord) for coord in splitted_line[1:4]]) if (cell_type == "vertex"): cell.GetPointIds().SetId(0, points.GetNumberOfPoints()-1) cell_array.InsertNextCell(cell) if (context == "reading elems"): if line.startswith("*"): context = "" else: splitted_line = line.split(",") if (len(splitted_line) == 3): continue if (cell_type == "hexahedron"): for k_node in range(8): cell.GetPointIds().SetId(k_node, int(splitted_line[2+k_node])-1) cell_array.InsertNextCell(cell) if line.startswith("*NODE"): context = "reading nodes" if line.startswith("*ELEMENT_SOLID"): context = "reading elems" mesh_file.close() mypy.my_print(verbose-1, "Creating VTK mesh...") ugrid = vtk.vtkUnstructuredGrid() ugrid.SetPoints(points) ugrid.SetCells(cell_vtk_type, cell_array) return ugrid
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'): # pragma: no cover grid.Update() return is_surface
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
if len(nod.loc)==2: xyz.InsertPoint(nod.localID, nod.loc[0]+nodDof[0], nod.loc[1]+nodDof[1], 0.) uvw.SetTuple3(nod.localID, nodDof[0], nodDof[1], 0.) elif len(nod.loc)==3: xyz.InsertPoint(nod.localID, nod.loc[0]+nodDof[0], nod.loc[1]+nodDof[1], nod.loc[2]+nodDof[2]) uvw.SetTuple3(nod.localID, nodDof[0], nodDof[1], nodDof[2]) else: raise "node.loc has wrong length for plotting" # Initialize grid and element types ug = vtk.vtkUnstructuredGrid() ug.SetPoints(xyz) line_type = vtk.vtkLine().GetCellType() quad_type = vtk.vtkQuad().GetCellType() hexa_type = vtk.vtkHexahedron().GetCellType() # Extract element connectivities and element output variables count = 0; idList = vtk.vtkIdList(); idList.Allocate(8) for el in mc.elements: if(el.type=='CBAR' or el.type=='CBAR1' or el.type=='CBARX' or el.type=='CBEAMX'): el_type = line_type Jg.SetValue(count, 1.) elif(el.type=='CQUAD'): el_type = quad_type Jg.SetValue(count, np.mean([eh.getJg(el,ip,dc,2) for ip in range(4)])) elif(el.type=='CHEXA'): el_type = hexa_type
def __init__(self, parent = None): super(VTKFrame, self).__init__(parent) self.vtkWidget = QVTKRenderWindowInteractor(self) vl = QtGui.QVBoxLayout(self) vl.addWidget(self.vtkWidget) vl.setContentsMargins(0, 0, 0, 0) self.ren = vtk.vtkRenderer() self.ren.SetBackground(0.1, 0.2, 0.4) self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() # Create source #Setup the coordinates of eight points #(the two faces must be in counter clockwise order as viewd from the outside) P0 = [0.0, 0.0, 0.0]; P1 = [1.0, 0.0, 0.0]; P2 = [1.0, 1.0, 0.0]; P3 = [0.0, 1.0, 0.0]; P4 = [0.0, 0.0, 1.0]; P5 = [1.0, 0.0, 1.0]; P6 = [1.0, 1.0, 1.0]; P7 = [0.0, 1.0, 1.0]; #Create the points points = vtk.vtkPoints(); 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 hexahedron from the points hexa = vtk.vtkHexahedron(); hexa.GetPointIds().SetId(0,0); hexa.GetPointIds().SetId(1,1); hexa.GetPointIds().SetId(2,2); hexa.GetPointIds().SetId(3,3); hexa.GetPointIds().SetId(4,4); hexa.GetPointIds().SetId(5,5); hexa.GetPointIds().SetId(6,6); hexa.GetPointIds().SetId(7,7); #Add the hexahedron to a cell array hexs = vtk.vtkCellArray(); hexs.InsertNextCell(hexa); #Add the points and hexahedron to an unstructured grid uGrid =vtk.vtkUnstructuredGrid(); uGrid.SetPoints(points); uGrid.InsertNextCell(hexa.GetCellType(), hexa.GetPointIds()); surface=vtk.vtkDataSetSurfaceFilter() surface.SetInput(uGrid) surface.Update() aBeamMapper = vtk.vtkDataSetMapper() aBeamMapper.SetInput(surface.GetOutput()) #aBeamMapper.SetInput(uGrid) aBeamActor = vtk.vtkActor() aBeamActor.SetMapper(aBeamMapper) aBeamActor.AddPosition(0,0,0) aBeamActor.GetProperty().SetColor(1,1,0) aBeamActor.GetProperty().SetOpacity(0.60) aBeamActor.GetProperty().EdgeVisibilityOn() aBeamActor.GetProperty().SetEdgeColor(1,1,1) aBeamActor.GetProperty().SetLineWidth(1.5) #create a plane to cut,here it cuts in the XZ direction (xz normal=(1,0,0);XY =(0,0,1),YZ =(0,1,0) plane=vtk.vtkPlane() plane.SetOrigin(0.5,0,0) plane.SetNormal(1,0,0) #create cutter cutter=vtk.vtkCutter() cutter.SetCutFunction(plane) cutter.SetInput(aBeamActor.GetMapper().GetInput()) cutter.Update() cutterMapper=vtk.vtkDataSetMapper() cutterMapper.SetInputConnection( cutter.GetOutputPort()) #create plane actor planeActor=vtk.vtkActor() planeActor.GetProperty().SetColor(1,0.5,0.5) planeActor.GetProperty().SetLineWidth(2) planeActor.SetMapper(cutterMapper) #Add the actor to the scene self.ren.AddActor(aBeamActor) self.ren.AddActor(planeActor) self.ren.ResetCamera() self._initialized = False
def load_openfoam_geometry(self, openfoam_filename, mesh_3d, name='main', plot=True, **kwargs): #key = self.caseKeys[self.iCase] #case = self.resultCases[key] #skip_reading = self.remove_old_openfoam_geometry(openfoam_filename) skip_reading = self.gui._remove_old_geometry(openfoam_filename) if skip_reading: return log = self.gui.log reset_labels = True #self.log.info('self.modelType=%s' % self.modelType) log.info('mesh_3d = %s' % mesh_3d) if mesh_3d in ['hex', 'shell']: model = BlockMesh(log=log, debug=False) # log=self.log, debug=False elif mesh_3d == 'faces': model = BlockMesh(log=log, debug=False) # log=self.log, debug=False boundary = Boundary(log=log, debug=False) self.gui.modelType = 'openfoam' #self.modelType = model.modelType log.info('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.gui.nelements = len(hexas) elif mesh_3d == 'shell': self.gui.nelements = len(quads) elif mesh_3d == 'faces': dirname = os.path.dirname(openfoam_filename) 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.gui.nelements = len(quads) + len(tris) else: raise RuntimeError(mesh_3d) self.gui.nnodes = len(nodes) log = self.gui.log log.debug("nnodes = %s" % self.gui.nnodes) log.debug("nelements = %s" % self.gui.nelements) grid = self.gui.grid grid.Allocate(self.gui.nelements, 1000) self.gui.nid_map = {} assert nodes is not None nnodes = nodes.shape[0] xmax, ymax, zmax = nodes.max(axis=0) xmin, ymin, zmin = nodes.min(axis=0) nodes -= np.array([xmin, ymin, zmin]) log.info('xmax=%s xmin=%s' % (xmax, xmin)) log.info('ymax=%s ymin=%s' % (ymax, ymin)) log.info('zmax=%s zmin=%s' % (zmax, zmin)) dim_max = max(xmax - xmin, ymax - ymin, zmax - zmin) #dim_max = (mmax - mmin).max() assert dim_max > 0 # breaks the model without subracting off the delta #self.update_axes_length(dim_max) self.gui.create_global_axes(dim_max) #print('is_face_mesh=%s is_3d_blockmesh=%s is_surface_blockmesh=%s' % ( #is_face_mesh, is_3d_blockmesh, is_surface_blockmesh)) with open('points.bdf', 'w') as bdf_file: bdf_file.write('CEND\n') bdf_file.write('BEGIN BULK\n') unames = unique(names) for pid in unames: bdf_file.write('PSHELL,%i,1,0.1\n' % pid) bdf_file.write('MAT1,1,1.0e7,,0.3\n') if is_face_mesh: points = vtk.vtkPoints() points.SetNumberOfPoints(self.gui.nnodes) unodes = unique(quads) unodes.sort() # should stop plotting duplicate nodes for inode, node in enumerate(nodes): if inode in unodes: bdf_file.write('GRID,%i,,%s,%s,%s\n' % ( inode + 1, node[0], node[1], node[2], )) points.InsertPoint(inode, node) else: points = numpy_to_vtk_points(nodes) #elements -= 1 normals = None if is_3d_blockmesh: nelements = hexas.shape[0] cell_type_hexa8 = vtkHexahedron().GetCellType() create_vtk_cells_of_constant_element_type( grid, hexas, cell_type_hexa8) elif is_surface_blockmesh: nelements = quads.shape[0] cell_type_quad4 = vtkQuad().GetCellType() create_vtk_cells_of_constant_element_type( grid, quads, cell_type_quad4) 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): ineg = where(element == -1)[0] nnodes = 4 if ineg: nnodes = ineg.max() #pid = 1 pid = names[eid] if nnodes == 3: # triangle! bdf_file.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]) grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) elif nnodes == 4: bdf_file.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]) 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) bdf_file.write('ENDDATA\n') self.gui.nelements = nelements grid.SetPoints(points) grid.Modified() if hasattr(grid, 'Update'): # pragma: no cover grid.Update() self.gui.scalarBar.VisibilityOn() self.gui.scalarBar.Modified() self.gui.isubcase_name_map = {0: ['OpenFoam BlockMeshDict', '']} cases = OrderedDict() ID = 1 #print("nElements = ",nElements) if mesh_3d == 'hex': form, cases, node_ids, element_ids = self._fill_openfoam_case( cases, ID, nodes, nelements, patches, names, normals, is_surface_blockmesh) elif mesh_3d == 'shell': form, cases, node_ids, element_ids = 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, node_ids, element_ids = self._fill_openfoam_case( cases, ID, nodes, nelements, patches, names, normals, is_surface_blockmesh) else: raise RuntimeError(mesh_3d) self.gui.node_ids = node_ids self.gui.element_ids = element_ids if plot: self.gui._finish_results_io2(form, cases, reset_labels=reset_labels) else: self.gui._set_results(form, cases)
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
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) aHexahedronGrid = vtk.vtkUnstructuredGrid() aHexahedronGrid.Allocate(1, 1) aHexahedronGrid.InsertNextCell(aHexahedron.GetCellType(), aHexahedron.GetPointIds()) aHexahedronGrid.SetPoints(hexahedronPoints)
def __init__(self, parent=None): super(VTKFrame, self).__init__(parent) self.vtkWidget = QVTKRenderWindowInteractor(self) vl = QtGui.QVBoxLayout(self) vl.addWidget(self.vtkWidget) vl.setContentsMargins(0, 0, 0, 0) self.ren = vtk.vtkRenderer() self.ren.SetBackground(0.1, 0.2, 0.4) self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() # Create source #Setup the coordinates of eight points #(the two faces must be in counter clockwise order as viewd from the outside) P0 = [0.0, 0.0, 0.0] P1 = [1.0, 0.0, 0.0] P2 = [1.0, 1.0, 0.0] P3 = [0.0, 1.0, 0.0] P4 = [0.0, 0.0, 1.0] P5 = [1.0, 0.0, 1.0] P6 = [1.0, 1.0, 1.0] P7 = [0.0, 1.0, 1.0] #Create the points points = vtk.vtkPoints() 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 hexahedron from the points hexa = vtk.vtkHexahedron() hexa.GetPointIds().SetId(0, 0) hexa.GetPointIds().SetId(1, 1) hexa.GetPointIds().SetId(2, 2) hexa.GetPointIds().SetId(3, 3) hexa.GetPointIds().SetId(4, 4) hexa.GetPointIds().SetId(5, 5) hexa.GetPointIds().SetId(6, 6) hexa.GetPointIds().SetId(7, 7) #Add the hexahedron to a cell array hexs = vtk.vtkCellArray() hexs.InsertNextCell(hexa) #Add the points and hexahedron to an unstructured grid uGrid = vtk.vtkUnstructuredGrid() uGrid.SetPoints(points) uGrid.InsertNextCell(hexa.GetCellType(), hexa.GetPointIds()) surface = vtk.vtkDataSetSurfaceFilter() surface.SetInput(uGrid) surface.Update() aBeamMapper = vtk.vtkDataSetMapper() aBeamMapper.SetInput(surface.GetOutput()) #aBeamMapper.SetInput(uGrid) aBeamActor = vtk.vtkActor() aBeamActor.SetMapper(aBeamMapper) aBeamActor.AddPosition(0, 0, 0) aBeamActor.GetProperty().SetColor(1, 1, 0) aBeamActor.GetProperty().SetOpacity(0.60) aBeamActor.GetProperty().EdgeVisibilityOn() aBeamActor.GetProperty().SetEdgeColor(1, 1, 1) aBeamActor.GetProperty().SetLineWidth(1.5) #create a plane to cut,here it cuts in the XZ direction (xz normal=(1,0,0);XY =(0,0,1),YZ =(0,1,0) plane = vtk.vtkPlane() plane.SetOrigin(0.5, 0, 0) plane.SetNormal(1, 0, 0) #create cutter cutter = vtk.vtkCutter() cutter.SetCutFunction(plane) cutter.SetInput(aBeamActor.GetMapper().GetInput()) cutter.Update() cutterMapper = vtk.vtkDataSetMapper() cutterMapper.SetInputConnection(cutter.GetOutputPort()) #create plane actor planeActor = vtk.vtkActor() planeActor.GetProperty().SetColor(1, 0.5, 0.5) planeActor.GetProperty().SetLineWidth(2) planeActor.SetMapper(cutterMapper) #Add the actor to the scene self.ren.AddActor(aBeamActor) self.ren.AddActor(planeActor) self.ren.ResetCamera() self._initialized = False
def readDynaMesh(lsdyna_mesh_filename, cell_type='hexahedron', verbose=0): mypy.my_print(verbose, "*** readDynaMesh: "+lsdyna_mesh_filename+" ***") points = vtk.vtkPoints() if (cell_type == 'vertex'): cell_vtk_type = vtk.VTK_VERTEX cell = vtk.vtkVertex() cell_array = vtk.vtkCellArray() elif (cell_type == 'hexahedron'): cell_vtk_type = vtk.VTK_HEXAHEDRON cell = vtk.vtkHexahedron() cell_array = vtk.vtkCellArray() else: print 'Wrong cell type. Aborting.' exit() mypy.my_print(verbose-1, "Reading Dyna mesh file...") mesh_file = open(lsdyna_mesh_filename, 'r') context = '' for line in mesh_file: if (line[-1:] == '\n'): line = line[:-1] #mypy.my_print(verbose-1, "line ="+line) if line.startswith('$'): continue if (context == 'reading nodes'): if line.startswith('*'): context = '' else: splitted_line = line.split(',') points.InsertNextPoint([float(coord) for coord in splitted_line[1:4]]) if (cell_type == 'vertex'): cell.GetPointIds().SetId(0, points.GetNumberOfPoints()-1) cell_array.InsertNextCell(cell) if (context == 'reading elems'): if line.startswith('*'): context = '' else: splitted_line = line.split(',') if (len(splitted_line) == 3): continue if (cell_type == 'hexahedron'): for k_node in xrange(8): cell.GetPointIds().SetId(k_node, int(splitted_line[2+k_node])-1) cell_array.InsertNextCell(cell) if line.startswith('*NODE'): context = 'reading nodes' if line.startswith('*ELEMENT_SOLID'): context = 'reading elems' mesh_file.close() mypy.my_print(verbose-1, "Creating VTK mesh...") ugrid = vtk.vtkUnstructuredGrid() ugrid.SetPoints(points) ugrid.SetCells(cell_vtk_type, cell_array) return ugrid