def initVTK(self, key): print "initializing VTK objects" self.__setMinMaxRange(key) self.__normalize(key) # Create our Data object vtk.vtkStructuredGrid() self.vtkStructuredGrid = vtk.vtkStructuredGrid() self.vtkStructuredGrid.SetDimensions([128]*3) # Set up Points self.vtkPoints = vtk.vtkPoints() self.vtkPoints.Allocate(128*3) # Set up Cells # self.vtkCells = vtk.vtkCellArray() # Setup the velocity vectors self.vtkVectors = vtk.vtkDoubleArray() self.vtkVectors.SetNumberOfComponents(3) self.vtkVectors.SetNumberOfTuples(self.sdfIdent.size) # Setup the Scalars self.vtkScalars = vtk.vtkDoubleArray() self.vtkScalars.SetName(key) # Allocate points, cells, scalars, and vector fields self.AllocateData(self.sdfIdent.size, key) # Now attach newly allocated objects to the grid self.vtkStructuredGrid.SetPoints(self.vtkPoints) # self.vtkStructuredGrid.SetVerts(self.vtkCells) self.vtkStructuredGrid.GetPointData().SetVectors(self.vtkVectors) self.vtkStructuredGrid.GetPointData().SetScalars(self.vtkScalars) self.vtkStructuredGrid.GetPointData().SetActiveScalars(key)
def createGrid(self, cube, pt, color=(1., 1., 1.), radius=1.0, show_mesh_as_surface=False): n0, n1 = cube.data.shape sg = vtk.vtkStructuredGrid() sg = vtk.vtkStructuredGrid() sg.SetDimensions(1, n0, n1) sg.SetPoints(pt) mp, ac = None, None # show mesh as a surface if show_mesh_as_surface: mp = vtk.vtkDataSetMapper() mp.SetInputData(sg) ac = vtk.vtkActor() ac.SetMapper(mp) # show the grid as tubes ed = vtk.vtkExtractEdges() et = vtk.vtkTubeFilter() em = vtk.vtkPolyDataMapper() ea = vtk.vtkActor() et.SetRadius(0.01) ed.SetInputData(sg) et.SetInputConnection(ed.GetOutputPort()) em.SetInputConnection(et.GetOutputPort()) ea.SetMapper(em) ea.GetProperty().SetColor(color) return [ea, ac], et, ed, em, sg, pt, mp
def test_multi_block_init_vtk(): multi = vtk.vtkMultiBlockDataSet() multi.SetBlock(0, vtk.vtkRectilinearGrid()) multi.SetBlock(1, vtk.vtkStructuredGrid()) multi = pyvista.MultiBlock(multi) assert isinstance(multi, pyvista.MultiBlock) assert multi.n_blocks == 2 assert isinstance(multi.GetBlock(0), pyvista.RectilinearGrid) assert isinstance(multi.GetBlock(1), pyvista.StructuredGrid) multi = vtk.vtkMultiBlockDataSet() multi.SetBlock(0, vtk.vtkRectilinearGrid()) multi.SetBlock(1, vtk.vtkStructuredGrid()) multi = pyvista.MultiBlock(multi, deep=True) assert isinstance(multi, pyvista.MultiBlock) assert multi.n_blocks == 2 assert isinstance(multi.GetBlock(0), pyvista.RectilinearGrid) assert isinstance(multi.GetBlock(1), pyvista.StructuredGrid) # Test nested structure multi = vtk.vtkMultiBlockDataSet() multi.SetBlock(0, vtk.vtkRectilinearGrid()) multi.SetBlock(1, vtk.vtkImageData()) nested = vtk.vtkMultiBlockDataSet() nested.SetBlock(0, vtk.vtkUnstructuredGrid()) nested.SetBlock(1, vtk.vtkStructuredGrid()) multi.SetBlock(2, nested) # Wrap the nested structure multi = pyvista.MultiBlock(multi) assert isinstance(multi, pyvista.MultiBlock) assert multi.n_blocks == 3 assert isinstance(multi.GetBlock(0), pyvista.RectilinearGrid) assert isinstance(multi.GetBlock(1), pyvista.UniformGrid) assert isinstance(multi.GetBlock(2), pyvista.MultiBlock)
def createPipeline(cube, pngfile, color=(1., 1., 1.), radius=1.0, show_mesh_as_surface=False, nlines=10): n0, n1 = cube.data.shape numPoints = n0 * n1 sg = vtk.vtkStructuredGrid() pt = vtk.vtkPoints() #pt.SetNumberOfPoints(numPoints) coords = cube.coords() lats = coords[0].points lons = coords[1].points steps0 = n0 // nlines steps1 = n1 // nlines k = 0 for i1 in range(0, n1, steps1): for i0 in range(0, n0, steps0): x = radius * math.cos(lats[i0, i1] * math.pi / 180.) * math.cos( lons[i0, i1] * math.pi / 180.) y = radius * math.cos(lats[i0, i1] * math.pi / 180.) * math.sin( lons[i0, i1] * math.pi / 180.) z = radius * math.sin(lats[i0, i1] * math.pi / 180.) pt.InsertPoint(k, x, y, z) k += 1 sg = vtk.vtkStructuredGrid() sg.SetDimensions(1, n0, n1) sg.SetPoints(pt) mp, ac = None, None # show mesh as a surface if show_mesh_as_surface: mp = vtk.vtkDataSetMapper() mp.SetInputData(sg) ac = vtk.vtkActor() ac.SetMapper(mp) # show the grid as tubes ed = vtk.vtkExtractEdges() et = vtk.vtkTubeFilter() em = vtk.vtkPolyDataMapper() ea = vtk.vtkActor() et.SetRadius(0.01) ed.SetInputData(sg) et.SetInputConnection(ed.GetOutputPort()) em.SetInputConnection(et.GetOutputPort()) ea.SetMapper(em) ea.GetProperty().SetColor(color) return [ea], em, et, ed, mp, sg
def get_sgrid_map(): """ Create the structured grid of the map """ map_grid = vtk.vtkStructuredGrid() points = vtk.vtkPoints() coordinate_texture = vtk.vtkFloatArray() coordinate_texture.SetNumberOfComponents(2) scalars = vtk.vtkIntArray() left = max(TOP_LEFT[1], BOTTOM_LEFT[1]) top = min(TOP_LEFT[0], TOP_RIGHT[0]) data_map = filter_data_map() for i, row in enumerate(data_map): for j, altitude in enumerate(row): latitude = top - i * delta_degree longitude = left + j * delta_degree points.InsertNextPoint( coordinate_earth(latitude, longitude, altitude)) l, m = get_texture_coord(latitude, longitude) coordinate_texture.InsertNextTuple((l, m)) scalars.InsertNextValue(altitude) map_grid.SetPoints(points) dim_y, dim_x = data_map.shape map_grid.SetDimensions(dim_x, dim_y, 1) map_grid.GetPointData().SetTCoords(coordinate_texture) map_grid.GetPointData().SetScalars(scalars) return map_grid
def buildBasePipeline(self): self.pointArray = vtk.vtkDoubleArray() self.points = vtk.vtkPoints() self.sgrid = vtk.vtkStructuredGrid() self.c2p = vtk.vtkCellDataToPointData() self.sgridGeomFilter = vtk.vtkStructuredGridGeometryFilter() self.contour = vtk.vtkContourFilter() self.mapper = vtk.vtkPolyDataMapper() self.actor = vtk.vtkActor() self.pointArray.SetNumberOfComponents(3) self.pointArray.SetName('coordinates') self.pointArray.SetVoidArray(self.xyz, self.numPoints * 3, 1) # connect self.points.SetData(self.pointArray) self.sgrid.SetDimensions(self.nx1, self.ny1, 1) self.sgrid.SetPoints(self.points) self.c2p.PassCellDataOn() self.c2p.SetInputData(self.sgrid) self.sgridGeomFilter.SetInputData(self.c2p.GetOutput()) self.contour.SetInputConnection( self.sgridGeomFilter.GetOutputPort() ) # Connection(self.sgridGeomFilter.GetOutputPort()) #Connection(self.cell2Points.GetOutputPort()) self.mapper.SetInputConnection(self.contour.GetOutputPort()) self.mapper.UseLookupTableScalarRangeOn() self.actor.SetMapper(self.mapper)
def createGrid(total_size: float, grid_elements: int): """Returns a vtkStrucutredGrid. :param total_size: Total size of the grid i.e. How long is each dimension. \ Each indivdual element has size equal to total_size/grid_dims :type size: float :param grid_dims: Number of grid points in x/y/z :type grid_dims: int :return: grid :rtype: vtkStructuredGrid """ grid = vtk.vtkStructuredGrid() grid.SetDimensions((grid_elements, grid_elements, grid_elements)) points = vtk.vtkPoints() points.SetNumberOfPoints(grid_elements**3) pID = 0 start = -total_size / 2 d = total_size / (grid_elements - 1) for i in range(0, grid_elements): for j in range(0, grid_elements): for k in range(0, grid_elements): x = start + d * k y = start + d * j z = start + d * i points.SetPoint(pID, x, y, z) pID += 1 grid.SetPoints(points) return grid
def export2vts(self, filename): import vtk grid = self.info['grid'] # Set grid points points = vtk.vtkPoints() for z in range(grid[2]): for y in range(grid[1]): for x in range(grid[0]): points.InsertNextPoint([x, y, z]) struGrid = vtk.vtkStructuredGrid() struGrid.SetDimensions(grid) struGrid.SetPoints(points) struGrid.Update() # Set point data grid_pt_num = struGrid.GetNumberOfPoints() array = vtk.vtkIntArray() array.SetNumberOfComponents(1) # this is 3 for a vector array.SetNumberOfTuples(grid_pt_num) array.SetName('MicrostructureID') matPoint = self.microstructure.reshape([grid_pt_num]) for i in range(grid_pt_num): array.SetValue(i, matPoint[i]) struGrid.GetPointData().AddArray(array) struGrid.Update() # Write output file outWriter = vtk.vtkXMLStructuredGridWriter() outWriter.SetDataModeToBinary() outWriter.SetCompressorTypeToZLib() outWriter.SetFileName(filename + '.vts') outWriter.SetInput(struGrid) outWriter.Update() outWriter.Write()
def testStructured(self): rt = vtk.vtkRTAnalyticSource() rt.SetWholeExtent(-5, 5, -5, 5, -5, 5) rt.Update() i = rt.GetOutput() st = vtk.vtkStructuredGrid() st.SetDimensions(i.GetDimensions()) nps = i.GetNumberOfPoints() ps = vtk.vtkPoints() ps.SetNumberOfPoints(nps) for idx in xrange(nps): ps.SetPoint(idx, i.GetPoint(idx)) st.SetPoints(ps) s = vtk.vtkSphere() s.SetRadius(2) s.SetCenter(0,0,0) c = vtk.vtkTableBasedClipDataSet() c.SetInputData(st) c.SetClipFunction(s) c.SetInsideOut(1) c.Update() self.assertEqual(c.GetOutput().GetNumberOfCells(), 64)
def loadNodes(self, fname, nx, ny, nz): """ Reads in the points of the grid, ususally in a file called nodewise fname = nodes file nx = number of cells in the easting(x) direction ny = number of cells in the northing (y) direction nz = number of cells in depth, positive up This method results in the generation of a VtkStructuredGrid """ self.nx = nx self.ny = ny self.nz = nz X = np.loadtxt(fname, comments="#") self.points = np.reshape( np.array((X[:, 2], X[:, 3], X[:, 4])).T, (nx, ny, nz, 3)) # work directly with VTK structures self.sGrid = vtk.vtkStructuredGrid() self.sGrid.SetDimensions(124, 88, 4) vtk_points = vtk.vtkPoints() for iz in range(nz): for iy in range(ny): for ix in range(nx): vtk_points.InsertNextPoint(self.points[ix, iy, iz][0], self.points[ix, iy, iz][1], self.points[ix, iy, iz][2]) self.sGrid.SetPoints(vtk_points)
def testStructured(self): rt = vtk.vtkRTAnalyticSource() rt.SetWholeExtent(-5, 5, -5, 5, -5, 5) rt.Update() i = rt.GetOutput() st = vtk.vtkStructuredGrid() st.SetDimensions(i.GetDimensions()) nps = i.GetNumberOfPoints() ps = vtk.vtkPoints() ps.SetNumberOfPoints(nps) for idx in range(nps): ps.SetPoint(idx, i.GetPoint(idx)) st.SetPoints(ps) s = vtk.vtkSphere() s.SetRadius(2) s.SetCenter(0,0,0) c = vtk.vtkTableBasedClipDataSet() c.SetInputData(st) c.SetClipFunction(s) c.SetInsideOut(1) c.Update() self.assertEqual(c.GetOutput().GetNumberOfCells(), 64)
def get_structured_grid(dimensions=(2, 2, 2), origin=(0., 0., 0.), spacing=(1., 1., 1.), array_name="color", color=(1., 1., 1.)): """Create a vtkStructuredGrid.""" dimensions = np.asarray(dimensions) mesh = vtk.vtkStructuredGrid() mesh.SetDimensions(*dimensions) counter = 0 number_of_points = np.prod(dimensions) points = vtk.vtkPoints() points.SetNumberOfPoints(number_of_points) for k in range(dimensions[2]): for j in range(dimensions[1]): for i in range(dimensions[0]): point = origin + np.multiply([i, j, k], spacing) points.SetPoint(counter, point) counter += 1 mesh.SetPoints(points) number_of_cells = np.prod(dimensions - 1) array = np.tile(color, (number_of_cells, 1)) add_mesh_cell_array( mesh=mesh, array_name=array_name, array=array, ) mesh.Modified() return mesh
def _write_vtk_box(box_points, filename, dimensions): """ Private method that writes a vtk file containing FFD control points. :param numpy.ndarray box_points: coordinates of the FFD control points. :param string filename: name of the output file. :param list dimensions: dimension of the lattice in (x, y, z) directions. """ # setup points and vertices points = vtk.vtkPoints() for index in range(0, box_points.shape[1]): ind = points.InsertNextPoint(box_points[0, index], box_points[1, index], box_points[2, index]) grid = vtk.vtkStructuredGrid() grid.SetPoints(points) grid.SetDimensions(dimensions) grid.Modified() writer = vtk.vtkStructuredGridWriter() writer.SetFileName(filename) if vtk.VTK_MAJOR_VERSION <= 5: grid.Update() writer.SetInput(grid) else: writer.SetInputData(grid) writer.Write()
def _write_vtk_box(box_points, filename, dimensions): """ Private method that writes a vtk file containing FFD control points. :param numpy.ndarray box_points: coordinates of the FFD control points. :param string filename: name of the output file. :param list dimensions: dimension of the lattice in (x, y, z) directions. .. warning:: If you want to visualize in paraview the inner points, you have to slice the lattice because paraview does not visualize them automatically even in the wireframe visualization. """ # setup points and vertices points = vtk.vtkPoints() for index in range(0, box_points.shape[1]): points.InsertNextPoint(box_points[0, index], box_points[1, index], box_points[2, index]) grid = vtk.vtkStructuredGrid() grid.SetPoints(points) grid.SetDimensions(dimensions) grid.Modified() writer = vtk.vtkStructuredGridWriter() writer.SetFileName(filename) if vtk.VTK_MAJOR_VERSION <= 5: grid.Update() writer.SetInput(grid) else: writer.SetInputData(grid) writer.Write()
def putMaskOnVTKGrid(data,grid,actorColor=None,deep=True): #Ok now looking msk = data.mask imsk = VN.numpy_to_vtk(msk.astype(numpy.int).flat,deep=deep) mapper = None if msk is not numpy.ma.nomask: msk = VN.numpy_to_vtk(numpy.logical_not(msk).astype(numpy.uint8).flat,deep=deep) if actorColor is not None: grid2 = vtk.vtkStructuredGrid() grid2.CopyStructure(grid) geoFilter = vtk.vtkDataSetSurfaceFilter() if grid.IsA("vtkStructuredGrid"): grid2.GetPointData().SetScalars(imsk) #grid2.SetCellVisibilityArray(imsk) p2c = vtk.vtkPointDataToCellData() p2c.SetInputData(grid2) geoFilter.SetInputConnection(p2c.GetOutputPort()) else: grid2.GetCellData().SetScalars(imsk) geoFilter.SetInputData(grid) geoFilter.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(geoFilter.GetOutput()) lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(1) r,g,b = actorColor lut.SetNumberOfTableValues(2) lut.SetTableValue(0,r/100.,g/100.,b/100.) lut.SetTableValue(1,r/100.,g/100.,b/100.) mapper.SetLookupTable(lut) mapper.SetScalarRange(1,1) if grid.IsA("vtkStructuredGrid"): grid.SetPointVisibilityArray(msk) #grid.SetCellVisibilityArray(msk) return mapper
def write_3d_scalar_fields_as_vtk_point_data(dat, result_filename, scale_factor=1.0): vtk_p = vtk.vtkPoints() x_vec,y_vec,z_vec = [np.array(x)*scale_factor for x in dat["grid_points"]] fields_dat = dat["fields"] xlen = len(x_vec) ylen = len(y_vec) zlen = len(z_vec) vtk_fields = [] for fi in fields_dat: vfi = vtk.vtkDoubleArray() vfi.SetName(fi["name"]) vtk_fields.append(vfi) n_fields = len(vtk_fields) for zi in range(zlen): for yi in range(ylen): for xi in range(xlen): vtk_p.InsertNextPoint([x_vec[xi],y_vec[yi],z_vec[zi]]) for i in range(n_fields): vtk_fields[i].InsertNextValue(fields_dat[i]["data"][xi, yi, zi]) vtk_grid = vtk.vtkStructuredGrid() vtk_grid.SetDimensions(xlen,ylen,zlen) vtk_grid.SetPoints(vtk_p) for i in range(n_fields): vtk_grid.GetPointData().AddArray(vtk_fields[i]) #print(vtk_grid) writer = vtk.vtkXMLStructuredGridWriter() writer.SetFileName(result_filename) writer.SetInputData(vtk_grid) writer.Write()
def __create_structured_grid(ptsMat, dims, models=None): """An internal helper to build out structured grids""" # Adjust if result was 2D: if ptsMat.shape[1] == 2: # Figure out which dim is null nullDim = dims.index(None) ptsMat = np.insert(ptsMat, nullDim, np.zeros(ptsMat.shape[0]), axis=1) if ptsMat.shape[1] != 3: raise RuntimeError('Points of the mesh are improperly defined.') # Convert the points vtkPts = vtk.vtkPoints() vtkPts.SetData(nps.numpy_to_vtk(ptsMat, deep=True)) # Uncover hidden dimension for i, d in enumerate(dims): if d is None: dims[i] = 0 dims[i] = dims[i] + 1 output = vtk.vtkStructuredGrid() output.SetDimensions(dims[0], dims[1], dims[2]) # note this subtracts 1 output.SetPoints(vtkPts) # Assign the model('s) to the object return assign_cell_data(output, models=models)
def create_mesh(M,P,T): n_naca_pts = 50 write_test_file(M,P,T,-5.,5.,nsections=5) wing=create_wing('current_wing','output') n_sections=len(wing) n_section_pts = 2*n_naca_pts-1 # build mesh vtk_model = vtk.vtkStructuredGrid() vtk_model.SetDimensions(n_section_pts,n_sections,1) # build points vtk_points = vtk.vtkPoints() for j in xrange(n_sections): upper_pts = numpy.array([wing[j][1],wing[j][3]]).T lower_pts = numpy.array([wing[j][2],wing[j][4]]).T section_pts = numpy.concatenate((lower_pts[::-1],upper_pts[1:])) for i in xrange(n_section_pts): vtk_points.InsertNextPoint(section_pts[i,0],wing[j][0],section_pts[i,1]) # set points vtk_model.SetPoints(vtk_points) # convert to poly data pdata_filter = vtk.vtkGeometryFilter() if vtk.VTK_MAJOR_VERSION <= 5: pdata_filter.SetInput(vtk_model) else: pdata_filter.SetInputData(vtk_model) pdata_filter.Update() poly_data = pdata_filter.GetOutput() # compute normals norms = vtk.vtkPolyDataNormals() if vtk.VTK_MAJOR_VERSION <= 5: norms.SetInput(poly_data) else: norms.SetInputData(poly_data) norms.ComputePointNormalsOff() norms.ComputeCellNormalsOn() norms.ConsistencyOn() norms.Update() # clean poly data clean_poly = vtk.vtkCleanPolyData() clean_poly.ToleranceIsAbsoluteOn() clean_poly.SetAbsoluteTolerance(1.e-6) if vtk.VTK_MAJOR_VERSION <= 5: clean_poly.SetInput(norms.GetOutput()) else: clean_poly.SetInputData(norms.GetOutput()) clean_poly.Update() # write output mesh writer = vtk.vtkXMLPolyDataWriter() if vtk.VTK_MAJOR_VERSION <= 5: writer.SetInput(clean_poly.GetOutput()) else: writer.SetInputData(clean_poly.GetOutput()) writer.SetFileName('output.vtp') writer.Write()
def export2vts(self, filename): import vtk grid = self.info['grid'] # Set grid points points = vtk.vtkPoints() for z in range (grid[2]): for y in range (grid[1]): for x in range (grid[0]): points.InsertNextPoint( [x , y , z ] ) struGrid = vtk.vtkStructuredGrid() struGrid.SetDimensions( grid ) struGrid.SetPoints( points ) struGrid.Update() # Set point data grid_pt_num = struGrid.GetNumberOfPoints() array = vtk.vtkIntArray() array.SetNumberOfComponents(1) # this is 3 for a vector array.SetNumberOfTuples(grid_pt_num) array.SetName('MicrostructureID') matPoint = self.microstructure.reshape( [grid_pt_num] ) for i in range(grid_pt_num): array.SetValue(i, matPoint[i]) struGrid.GetPointData().AddArray(array) struGrid.Update() # Write output file outWriter = vtk.vtkXMLStructuredGridWriter() outWriter.SetDataModeToBinary() outWriter.SetCompressorTypeToZLib() outWriter.SetFileName( filename + '.vts' ) outWriter.SetInput(struGrid) outWriter.Update() outWriter.Write()
def cone(c1,h_max,phi,n=100,name='temp'): c1 = np.array(c1) phi = np.radians(phi) r_max = h_max/np.tan(phi) hyp = h_max/np.sin(phi) circ = 2*np.pi*r_max nr = np.round(n*hyp/circ).astype('int') nr1 = nr+1 theta = np.linspace(0,2*np.pi,n+1) h = np.linspace(0,h_max,nr+1) r = h/np.tan(phi) X = np.outer(np.cos(theta), r) Y = np.outer(np.sin(theta), r) Z = np.outer(np.ones(theta.shape[0]), h) gridpoints = np.stack([X.flat, Y.flat, Z.flat], axis=1) gridpoints += c1 points = vtk.vtkPoints() points.SetData(vtknp.numpy_to_vtk(gridpoints)) grid = vtk.vtkStructuredGrid() grid.SetDimensions(nr1, n+1, 1) grid.SetPoints(points) addCoordData(grid,gridpoints) writer = vtk.vtkStructuredGridWriter() writer.SetFileName(name+'.vtk') writer.SetInputData(grid) writer.Write()
def GetvtkStructuredGrid(self): """Returns the instance of vtkStructuredGrid""" from vtk import vtkStructuredGrid try: return self.vtkstructuredgrid except AttributeError: self.vtkstructuredgrid = vtkStructuredGrid() return self.vtkstructuredgrid
def GetvtkStructuredGridProbe(self): """Returns the instance of the vtkStructuredGrid""" from vtk import vtkStructuredGrid try: return self.probegrid except AttributeError: self.probegrid = vtkStructuredGrid() return self.probegrid
def getVTKsgrid(grid): shape=[i for i in reversed(grid.shape[:-1])] print 'Creating vtk structured grid with shape %s'%str(shape) pts=getVTKpoints(grid) sgrid=vtk.vtkStructuredGrid() #@UndefinedVariable sgrid.SetPoints(pts) sgrid.SetExtent(0,shape[0]-1,0,shape[1]-1,0,shape[2]-1) return sgrid
def putMaskOnVTKGrid(data,grid,actorColor=None,cellData=True,deep=True): #Ok now looking msk = data.mask imsk = numpy_to_vtk_wrapper(msk.astype(numpy.int).flat,deep=deep) mapper = None if msk is not numpy.ma.nomask and not numpy.allclose(msk,False): if actorColor is not None: if grid.IsA("vtkStructuredGrid"): grid2 = vtk.vtkStructuredGrid() else: grid2 = vtk.vtkUnstructuredGrid() grid2.CopyStructure(grid) geoFilter = vtk.vtkDataSetSurfaceFilter() lut = vtk.vtkLookupTable() r,g,b = actorColor lut.SetNumberOfTableValues(2) if not cellData: grid2.GetPointData().RemoveArray( vtk.vtkDataSetAttributes.GhostArrayName()) grid2.GetPointData().SetScalars(imsk) #grid2.SetCellVisibilityArray(imsk) #p2c = vtk.vtkPointDataToCellData() #p2c.SetInputData(grid2) #geoFilter.SetInputConnection(p2c.GetOutputPort()) geoFilter.SetInputData(grid2) lut.SetTableValue(0,r/100.,g/100.,b/100.,1.) lut.SetTableValue(1,r/100.,g/100.,b/100.,1.) else: grid2.GetCellData().RemoveArray( vtk.vtkDataSetAttributes.GhostArrayName()) grid2.GetCellData().SetScalars(imsk) geoFilter.SetInputData(grid2) lut.SetTableValue(0,r/100.,g/100.,b/100.,0.) lut.SetTableValue(1,r/100.,g/100.,b/100.,1.) geoFilter.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(geoFilter.GetOutput()) mapper.SetLookupTable(lut) mapper.SetScalarRange(0,1) # The ghost array now stores information about hidden (blanked) # points/cells. Setting an array entry to the bitwise value # `vtkDataSetAttributes.HIDDEN(CELL|POINT)` will blank the cell/point. flatMask = msk.flat ghost = numpy.zeros(len(flatMask), dtype=numpy.uint8) invalidMaskValue = vtk.vtkDataSetAttributes.HIDDENCELL if cellData else \ vtk.vtkDataSetAttributes.HIDDENPOINT for i, isInvalid in enumerate(flatMask): if isInvalid: ghost[i] = invalidMaskValue ghost = numpy_to_vtk_wrapper(ghost, deep=deep) ghost.SetName(vtk.vtkDataSetAttributes.GhostArrayName()) if cellData: grid.GetCellData().AddArray(ghost) else: grid.GetPointData().AddArray(ghost) return mapper
def __init__(self, numLats, numLons, radius=1.0, coords='cartesian'): # this is to convert from structured to unstructured grid self.appendGrids = vtk.vtkAppendFilter() # create grid numLats1, numLons1 = numLats + 1, numLons + 1 lats = numpy.linspace(-numpy.pi / 2., numpy.pi / 2., numLats1) lons = numpy.linspace(0., 2 * numpy.pi, numLons1) llons, llats = numpy.meshgrid(lons, lats) llats = llats.flat llons = llons.flat # vertices in Cartesian space self.xyz = numpy.zeros((numLats1 * numLons1, 3), numpy.float64) rrho = radius * numpy.cos(llats) self.xyz[:, 0] = rrho * numpy.cos(llons) self.xyz[:, 1] = rrho * numpy.sin(llons) self.xyz[:, 2] = radius * numpy.sin(llats) # coordinates self.pointArray = self.xyz if coords == 'spherical': self.pointArray[:, 0] = llons self.pointArray[:, 1] = llats self.pointArray[:, 2] = 0.0 # compute the cell areas, enforce positiveness (not sure why all the areas are negative) self.areas = -igAreas.getCellAreas(self.xyz, n0=numLats1, n1=numLons1) self.vareas = vtk.vtkDoubleArray() self.vareas.SetName('cell_areas') self.vareas.SetNumberOfComponents(1) self.vareas.SetNumberOfTuples(numLats * numLons) self.vareas.SetVoidArray(self.areas, numLats * numLons, 1) # create the VTK unstructured grid self.vxyz = vtk.vtkDoubleArray() self.vxyz.SetNumberOfComponents(3) ntot = numLats1 * numLons1 self.vxyz.SetNumberOfTuples(ntot) self.vxyz.SetVoidArray(self.pointArray, 3 * ntot, 1) self.pts = vtk.vtkPoints() self.pts.SetNumberOfPoints(ntot) self.pts.SetData(self.vxyz) self.sgrid = vtk.vtkStructuredGrid() self.sgrid.SetDimensions(numLons1, numLats1, 1) self.sgrid.SetPoints(self.pts) self.sgrid.GetCellData().SetScalars(self.vareas) self.appendGrids.AddInputData(self.sgrid) self.appendGrids.Update() self.grid = self.appendGrids.GetOutput()
def set_vtk_unstructured(self): vts = vtk.vtkStructuredGrid() vts.SetDimensions(Nz, Ny, Nx) vts.SetPoints(pts) for array in self.vtk_props: vts.GetPointData().AddArray(array) self.obj = vtk_data print "|_Vtk_writer.to_vtkstructured"
def update_const(self, index, tcd): if not self.stat_init: print('Error: call initialize() before update()') else: # index = next(self.stat_numcalpts) # tcd = self.cds[index] hdf5_file_name = next(self.g) copyfile(self.base_file, hdf5_file_name) self.fastmech_change_cd(hdf5_file_name, tcd) self.fastmech_BCs(hdf5_file_name) for path in self.execute(["Fastmech.exe", hdf5_file_name]): print(path, end="") SGrid = vtk.vtkStructuredGrid() self.create_vtk_structured_grid(SGrid, hdf5_file_name) cellLocator2D = vtk.vtkCellLocator() cellLocator2D.SetDataSet(SGrid) # cellLocator2D.SetNumberOfCellsPerBucket(10); cellLocator2D.BuildLocator() WSE_2D = SGrid.GetPointData().GetScalars('WSE') IBC_2D = SGrid.GetPointData().GetScalars('IBC') Velocity_2D = SGrid.GetPointData().GetScalars('Velocity') simwse = np.zeros(self.meas_wse.shape[0]) measwse = np.zeros(self.meas_wse.shape[0]) for counter, line in enumerate(self.meas_wse): point2D = [line[0] - self.xoffset, line[1] - self.yoffset, 0.0] pt1 = [line[0] - self.xoffset, line[1] - self.yoffset, 10.0] pt2 = [line[0] - self.xoffset, line[1] - self.yoffset, -10] idlist1 = vtk.vtkIdList() cellLocator2D.FindCellsAlongLine(pt1, pt2, 0.0, idlist1) cellid = idlist1.GetId(0) # cellid = cellLocator2D.FindCell(point2D) # print (isCellWet(SGrid, point2D, cellid, IBC_2D)) tmpwse = self.getCellValue(SGrid, point2D, cellid, WSE_2D) if tcd == self.cdmin: self.meas_and_sim_wse[counter, 0] = line[2] # print counter simwse[counter] = tmpwse measwse[counter] = line[2] # print(cellid, line[2], tmpwse) self.meas_and_sim_wse[:, index + 1] = simwse self.rmse_data[index] = self.rmse(simwse, measwse) self.cd_val[index] = tcd # print(self.rmse_data[index]) # print(self.cd_val) # print(self.rmse_data) trmse = np.column_stack( (self.cd_val.flatten(), self.rmse_data.flatten())) # print(trmse) np.savetxt(self.rmse_file, trmse, delimiter=',') np.savetxt(self.meas_vs_sim_file, self.meas_and_sim_wse, delimiter=',') return trmse
def __init__(self, scanType, geomType, pitchAndRoll): self.headersize = 17 self.header = {} self.scanType = scanType self.geomType = geomType self.pitchAndRoll = pitchAndRoll if geomType == 'rays' or geomType == 'gates': self.scan = vtk.vtkPolyData() elif geomType == 'sweep': self.scan = vtk.vtkStructuredGrid()
def __init__(self, center_shp, tension, nx, ny, width): self.cl = centerline(center_shp) self.tension = tension self.width = width self.nx = nx self.ny = ny self.xgrid = np.zeros(self.nx * self.ny, dtype=np.double) self.ygrid = np.zeros(self.nx * self.ny, dtype=np.double) self.sgrid = vtk.vtkStructuredGrid() self.sg_points = vtk.vtkPoints() self.__buildXYGrid()
def CopyGrid(grid): """ Copies a vtk structured, unstructured, or polydata object """ if isinstance(grid, vtk.vtkUnstructuredGrid): gridcopy = vtk.vtkUnstructuredGrid() elif isinstance(grid, vtk.vtkStructuredGrid): gridcopy = vtk.vtkStructuredGrid() elif isinstance(grid, vtk.vtkPolyData): gridcopy = vtk.vtkPolyData() gridcopy.DeepCopy(grid) return gridcopy
def toVTK(self): """Convert the 2D grid to a ``vtkStructuredGrid`` object.""" import vtk from vtk.util import numpy_support as nps output = vtk.vtkStructuredGrid() # TODO: build! # Build out all nodes in the mesh # Add to output return output
def genGridOnPoints(data1,data2,gm,deep=True): continents = False xm,xM,ym,yM = None, None, None, None useStructuredGrid = True try: g=data1.getGrid() x = g.getLongitude()[:] y = g.getLatitude()[:] continents=True wrap=[0,360] if isinstance(g,cdms2.gengrid.AbstractGenericGrid): # Ok need unstrctured grid useStructuredGrid = False except: #hum no grid that's much easier x=data1.getAxis(-1)[:] y=data1.getAxis(-2)[:] wrap=None if x.ndim==1: y = y[:,numpy.newaxis]*numpy.ones(x.shape)[numpy.newaxis,:] x = x[numpy.newaxis,:]*numpy.ones(y.shape) x=x.flatten() y=y.flatten() sh =list(x.shape) sh.append(1) x=numpy.reshape(x,sh) y=numpy.reshape(y,sh) #Ok we have our points in 2D let's create unstructured points grid xm=x.min() xM=x.max() ym=y.min() yM=y.max() z = numpy.zeros(x.shape) m3 = numpy.concatenate((x,y),axis=1) m3 = numpy.concatenate((m3,z),axis=1) deep = True pts = vtk.vtkPoints() ## Convert nupmy array to vtk ones ppV = numpy_to_vtk_wrapper(m3,deep=deep) pts.SetData(ppV) projection = vcs.elements["projection"][gm.projection] xm,xM,ym,yM = getRange(gm,xm,xM,ym,yM) geo, geopts = project(pts,projection,[xm,xM,ym,yM]) ## Sets the vertics into the grid if useStructuredGrid: vg = vtk.vtkStructuredGrid() vg.SetDimensions(y.shape[1],y.shape[0],1) else: vg = vtk.vtkUnstructuredGrid() vg.SetPoints(geopts) return vg,xm,xM,ym,yM,continents,wrap,geo
def update_var(self, cnt, tcd, q=0): if not self.stat_init: print('Error: call initialize() before update()') else: # index = next(self.stat_numcalpts) # tcd = self.cds[index] hdf5_file_name = next(self.g) copyfile(self.base_file, hdf5_file_name) self.fastmech_change_var_cd2(hdf5_file_name, tcd) if q != 0: self.Q = q self.fastmech_BCs(hdf5_file_name) for path in self.execute(["Fastmech.exe", hdf5_file_name]): print(path, end="") SGrid = vtk.vtkStructuredGrid() self.create_vtk_structured_grid(SGrid, hdf5_file_name) cellLocator2D = vtk.vtkCellLocator() cellLocator2D.SetDataSet(SGrid) # cellLocator2D.SetNumberOfCellsPerBucket(10); cellLocator2D.BuildLocator() WSE_2D = SGrid.GetPointData().GetScalars('WSE') IBC_2D = SGrid.GetPointData().GetScalars('IBC') Velocity_2D = SGrid.GetPointData().GetScalars('Velocity') simwse = np.zeros(self.meas_wse.shape[0]) measwse = np.zeros(self.meas_wse.shape[0]) for counter, line in enumerate(self.meas_wse): point2D = [line[0] - self.xoffset, line[1] - self.yoffset, 0.0] pt1 = [line[0] - self.xoffset, line[1] - self.yoffset, 10.0] pt2 = [line[0] - self.xoffset, line[1] - self.yoffset, -10] idlist1 = vtk.vtkIdList() cellLocator2D.FindCellsAlongLine(pt1, pt2, 0.0, idlist1) cellid = idlist1.GetId(0) tmpwse = self.getCellValue(SGrid, point2D, cellid, WSE_2D) simwse[counter] = tmpwse measwse[counter] = line[2] print(cellid, line[2], tmpwse) self.resdf.loc[cnt, self.dfcols[0]] = cnt for key in tcd: self.resdf.loc[cnt, self.dfcols[int(key + 1)]] = tcd[key] self.resdf.loc[cnt, 'rmse'] = self.rmse(simwse, measwse) self.resdf.loc[cnt, 'Discharge'] = self.Q # trmse = np.column_stack((self.cd0_var_vals.flatten(), self.cd1_var_vals.flatten(), self.rmse_var_data.flatten())) # print(trmse) # # np.savetxt(self.rmse_file, trmse, delimiter=',') self.resdf.to_csv(self.rmse_file) # np.savetxt(self.meas_vs_sim_file, self.meas_and_sim_wse_var, delimiter=',') return self.resdf
def plotGrid3d(field, color=(0.5, 0.1, 0.1), radius=1.0): import vtk pt = vtk.vtkPoints() sg = vtk.vtkStructuredGrid() mp = vtk.vtkDataSetMapper() ac = vtk.vtkActor() # connect sg.SetPoints(pt) mp.SetInputData(sg) ac.SetMapper(mp) # set ac.GetProperty().SetColor(color) latIndex, lonIndex = 0, 1 iBegLat = field.grid.lower_bounds[ESMF.StaggerLoc.CORNER][latIndex] iEndLat = field.grid.upper_bounds[ESMF.StaggerLoc.CORNER][latIndex] iBegLon = field.grid.lower_bounds[ESMF.StaggerLoc.CORNER][lonIndex] iEndLon = field.grid.upper_bounds[ESMF.StaggerLoc.CORNER][lonIndex] lats = field.grid.get_coords(latIndex, ESMF.StaggerLoc.CORNER)[iBegLat:iEndLat, iBegLon:iEndLon] lons = field.grid.get_coords(lonIndex, ESMF.StaggerLoc.CORNER)[iBegLat:iEndLat, iBegLon:iEndLon] n0, n1 = lats.shape numPoints = n0 * n1 pt.SetNumberOfPoints(numPoints) sg.SetDimensions(1, n0, n1) # fill in the points k = 0 for i1 in range(n1): for i0 in range(n0): x = radius * math.cos(lats[i0, i1] * math.pi / 180.) * math.cos( lons[i0, i1] * math.pi / 180.) y = radius * math.cos(lats[i0, i1] * math.pi / 180.) * math.sin( lons[i0, i1] * math.pi / 180.) z = radius * math.sin(lats[i0, i1] * math.pi / 180.) pt.SetPoint(k, x, y, z) k += 1 # show edges ed = vtk.vtkExtractEdges() et = vtk.vtkTubeFilter() et.SetRadius(0.01) em = vtk.vtkPolyDataMapper() ea = vtk.vtkActor() ed.SetInputData(sg) et.SetInputConnection(ed.GetOutputPort()) em.SetInputConnection(et.GetOutputPort()) ea.SetMapper(em) actors = [ac, ea] return actors, mp, sg, pt
def __init__(self, theta0, dLambda, dTheta, dRadius, n1, n2, n3,): ntot = (n1 + 1) * (n2 + 1) * (n3 + 1) dXi1 = 1.0/float(n1) dXi2 = 1.0/float(n2) dXi3 = 1.0/float(n3) self.ptArray = vtk.vtkDoubleArray() self.ptArray.SetNumberOfComponents(3) self.ptArray.SetNumberOfTuples(ntot) self.data = vtk.vtkDoubleArray() self.data.SetNumberOfComponents(3) # vector self.data.SetNumberOfTuples(ntot) index = 0 for i3 in range(n3 + 1): for i2 in range(n2 + 1): for i1 in range(n1 + 1): lam = 0.0 + i1*dLambda/float(n1) the = theta0 + i2*dTheta/float(n2) rad = 1.0 + i3*dRadius/float(n3) x = rad * numpy.cos(the) * numpy.cos(lam) y = rad * numpy.cos(the) * numpy.sin(lam) z = rad * numpy.sin(the) self.ptArray.SetTuple(index, (x, y, z)) xi1 = 0.0 + i1*dXi1 xi2 = 0.0 + i2*dXi2 xi3 = 0.0 + i3*dXi3 basisFunc = -8.*(xi2 - 0.75)*(xi3 - 0.25)*(xi1 - 0.5) rho = numpy.sqrt(x**2 + y**2) thetaHat = numpy.array([-z*numpy.cos(lam), -z*numpy.sin(lam), rho]) / rad rHat = numpy.array([x, y, z]) / rad basisVec = numpy.cross(thetaHat, rHat) / rad vx, vy, vz = basisFunc*basisVec self.data.SetTuple(index, (vx, vy, vz)) index += 1 self.pts = vtk.vtkPoints() self.pts.SetData(self.ptArray) self.grid = vtk.vtkStructuredGrid() self.grid.SetDimensions(n1 + 1, n2 + 1, n3 + 1) self.grid.SetPoints(self.pts) self.grid.GetPointData().SetScalars(self.data)
def mesh(x,y,z, rgb=None, color='g', normals=True, renderer=None): np1,np2 = x.shape npts = np1*np2 allPoints = vtk.vtkPoints() allPoints.SetNumberOfPoints(npts) for i,xi in enumerate([x,y,z]): flt = xi.ravel() ci = numpy_support.numpy_to_vtk(flt, deep=False) allPoints.GetData().CopyComponent(i,ci,0) # grid = vtk.vtkStructuredGrid() grid.SetDimensions(1,np2,np1) grid.SetPoints(allPoints) if rgb is not None: cols = vtk.vtkUnsignedCharArray() cols.SetNumberOfComponents(3) cols.SetName("Colors") cols.SetNumberOfTuples(npts) for i,cc in enumerate(rgb): cj = (cc.ravel()*255).astype(np.uint8) ci = numpy_support.numpy_to_vtk(cj, deep=True) cols.CopyComponent(i,ci,0) # grid.GetPointData().SetScalars(cols) # if normals: conv = vtk.vtkStructuredGridGeometryFilter() vtkConnectDataInput(grid, conv) normals = vtk.vtkPolyDataNormals() vtkConnectOutputInput(conv, normals) mapped = vtk.vtkPolyDataMapper() vtkConnectOutputInput(normals, mapped) else: mapped = vtk.vtkDataSetMapper() vtkConnectDataInput(grid, mapped) # grac = vtk.vtkActor() grac.SetMapper(mapped) if rgb is None: color = colors.to_rgb(color) grac.GetProperty().SetColor(*color) # if renderer is not None: renderer.AddActor2D(grac) # return grac
def __init__( self, Data=None, tag=None, DataOrder=None, DataType=None, shape=None, \ vtkFile="out.vtu", vtkFileType=None, DataFormat="ascii", newFile=True, \ DataLabel=None ): # ------------------------------------------------- # # --- call fieldDataManager initialization --- # # ------------------------------------------------- # super().__init__( Data=Data, tag=tag, DataOrder=DataOrder, \ DataType=DataType, shape=shape, DataLabel=DataLabel ) # ------------------------------------------------- # # --- vtk native variables --- # # ------------------------------------------------- # self.vtkFile = vtkFile self.DataFormat = DataFormat # ------------------------------------------------- # # --- inspect vtkFileType --- # # ------------------------------------------------- # extention = ( vtkFile.split( "." ) )[-1] if ( extention == "vti" ): self.vtkFileType = "ImageData" self.image = vtk.vtkImageData() elif ( extention == "vts" ): self.vtkFileType = "StructuredGrid" self.sGrid = vtk.vtkStructuredGrid() elif ( extention == "vtu" ): self.vtkFileType = "UnstructuredGrid" self.uGrid = vtk.vtkUnstructuredGrid() elif ( extention == "vtp" ): self.vtkFileType = "PolyData" self.pData = vtk.vtkPolyData() else: print( "[vtkDataWriter] Unknown extention :: {0}".format( extention ) ) print( "[vtkDataWriter] vtkFile :: {0}".format( vtkFile ) ) print( "[vtkDataWriter] please specify extention from .vti, .vts, .vtu " ) sys.exit() # ------------------------------------------------- # # --- single Data convert --- # # ------------------------------------------------- # if ( ( Data is not None ) and ( tag is not None ) ): if ( self.vtkFileType == "ImageData" ): self.convert__imageData2vti( tag=tag ) if ( self.vtkFileType == "StructuredGrid" ): self.convert__pointData2vts( tag=tag ) if ( self.vtkFileType == "UnstructuredGrid" ): self.convert__pointData2vtu( tag=tag ) if ( self.vtkFileType == "PolyData" ): self.generate__surfacePolyData( tag=tag )
def addGrid(self, grid): nx, ny, nz = grid.shape[1:] self.display.append(True) self.grids.append(vtk.vtkStructuredGrid()) self.grids[-1].SetExtent(0, nz-1, 0, ny-1, 0, nx-1) p = vtk.vtkPoints() shp = grid.shape grid.shape = (3, nx*ny*nz) p.SetData(vtknp.numpy_to_vtk(np.ascontiguousarray(grid.T), deep=True, array_type=vtknp.get_vtk_array_type(grid.dtype))) grid.shape = shp self.grids[-1].SetPoints(p) #Couleur color = np.random.rand(3) #Create a vtkOutlineFilter to draw the bounding box of the data set. ol = vtk.vtkOutlineFilter() if (vtk.vtkVersion().GetVTKMajorVersion()>=6): ol.SetInputData(self.grids[-1]) else: ol.SetInput(self.grids[-1]) olm = vtk.vtkPolyDataMapper() olm.SetInputConnection(ol.GetOutputPort()) ola = vtk.vtkActor() ola.SetMapper(olm) ola.GetProperty().SetColor(color) s=vtk.vtkShrinkFilter() if (vtk.vtkVersion().GetVTKMajorVersion()>=6): s.SetInputData(self.grids[-1]) else: s.SetInput(self.grids[-1]) s.SetShrinkFactor(0.8) # mapper = vtk.vtkDataSetMapper() #map.SetInputData(data) mapper.SetInputConnection(s.GetOutputPort()) act = vtk.vtkLODActor() act.SetMapper(mapper) #act.GetProperty().SetRepresentationToWireframe() #act.GetProperty().SetRepresentationToPoints() act.GetProperty().SetColor(color) act.GetProperty().SetEdgeColor(color) act.GetProperty().EdgeVisibilityOff() self.actors.append(act) self.setBounds() self.ren.SetActiveCamera(self.cam)
def saveVectorField(self): nxv, nyv = 101, 101 vi = mint.VectorInterp() vi.setGrid(self.grid) vi.buildLocator(numCellsPerBucket=100, periodX=0.) xx, yy = numpy.meshgrid( numpy.linspace(self.xymin[0], self.xymax[0], nxv), numpy.linspace(self.xymin[1], self.xymax[1], nyv)) xyz = numpy.zeros((nxv * nyv, 3), numpy.float64) xyz[:, 0] = xx.flat xyz[:, 1] = yy.flat vi.findPoints(xyz) vectors_edge = vi.getEdgeVectors(self.data, placement=mint.CELL_BY_CELL_DATA) vectors_face = vi.getFaceVectors(self.data, placement=mint.CELL_BY_CELL_DATA) ptsData = vtk.vtkDoubleArray() ptsData.SetNumberOfComponents(3) ptsData.SetNumberOfTuples(nxv * nyv) ptsData.SetVoidArray(xyz, nxv * nyv * 3, 1) pts = vtk.vtkPoints() pts.SetData(ptsData) # add vector field vecDataEdge = vtk.vtkDoubleArray() vecDataEdge.SetName('vector_edge') vecDataEdge.SetNumberOfComponents(3) vecDataEdge.SetNumberOfTuples(nxv * nyv) vecDataEdge.SetVoidArray(vectors_edge, nxv * nyv * 3, 1) vecDataFace = vtk.vtkDoubleArray() vecDataFace.SetName('vector_face') vecDataFace.SetNumberOfComponents(3) vecDataFace.SetNumberOfTuples(nxv * nyv) vecDataFace.SetVoidArray(vectors_face, nxv * nyv * 3, 1) sgrid = vtk.vtkStructuredGrid() sgrid.SetDimensions((nxv, nyv, 1)) sgrid.SetPoints(pts) sgrid.GetPointData().AddArray(vecDataEdge) sgrid.GetPointData().AddArray(vecDataFace) writer = vtk.vtkStructuredGridWriter() writer.SetFileName('vectors.vtk') writer.SetInputData(sgrid) writer.Update()
def plotWithVTK(n, x, u): # Stockage des donnees au format VTK pts = vtk.vtkPoints() pts.SetData(numpy_support.numpy_to_vtk(x)) uvtk = numpy_support.numpy_to_vtk(u) uvtk.SetName("u") data = vtk.vtkStructuredGrid() nn = n + [1]*(3 - len(n)) data.SetDimensions(nn) data.SetPoints(pts) data.GetPointData().SetScalars(uvtk) data.Update() # Sortie fichier w = vtk.vtkXMLStructuredGridWriter() w.SetFileName("poisson.vts") w.SetInput(data) w.Write()
def testStructured2D(self): planes = ['XY', 'XZ', 'YZ'] expectedNCells = [42, 34, 68] for plane, nCells in zip(planes,expectedNCells): rt = vtk.vtkRTAnalyticSource() if plane == 'XY': rt.SetWholeExtent(-5, 5, -5, 5, 0, 0) elif plane == 'XZ': rt.SetWholeExtent(-5, 5, 0, 0, -5, 5) else: rt.SetWholeExtent(0, 0, -5, 5, -5, 5) rt.Update() i = rt.GetOutput() st = vtk.vtkStructuredGrid() st.SetDimensions(i.GetDimensions()) nps = i.GetNumberOfPoints() ps = vtk.vtkPoints() ps.SetNumberOfPoints(nps) for idx in range(nps): ps.SetPoint(idx, i.GetPoint(idx)) st.SetPoints(ps) cyl = vtk.vtkCylinder() cyl.SetRadius(2) cyl.SetCenter(0,0,0) transform = vtk.vtkTransform() transform.RotateWXYZ(45,20,1,10) cyl.SetTransform(transform) c = vtk.vtkTableBasedClipDataSet() c.SetInputData(st) c.SetClipFunction(cyl) c.SetInsideOut(1) c.Update() self.assertEqual(c.GetOutput().GetNumberOfCells(), nCells)
def genGridOnPoints(data1,gm,deep=True,grid=None,geo=None): continents = False xm,xM,ym,yM = None, None, None, None useStructuredGrid = True try: g=data1.getGrid() if grid is None: x = g.getLongitude()[:] y = g.getLatitude()[:] xm = x[0] xM = x[-1] ym = y[0] yM = y[-1] continents=True wrap=[0,360] if isinstance(g,cdms2.gengrid.AbstractGenericGrid): # Ok need unstrctured grid useStructuredGrid = False except: #hum no grid that's much easier wrap=None if grid is None: x=data1.getAxis(-1)[:] y=data1.getAxis(-2)[:] xm = x[0] xM = x[-1] ym = y[0] yM = y[-1] if grid is None: if x.ndim==1: y = y[:,numpy.newaxis]*numpy.ones(x.shape)[numpy.newaxis,:] x = x[numpy.newaxis,:]*numpy.ones(y.shape) x=x.flatten() y=y.flatten() sh =list(x.shape) sh.append(1) x=numpy.reshape(x,sh) y=numpy.reshape(y,sh) #Ok we have our points in 2D let's create unstructured points grid if xm is None: xm=x.min() if xM is None: xM=x.max() if ym is None: ym=y.min() if yM is None: yM=y.max() z = numpy.zeros(x.shape) m3 = numpy.concatenate((x,y),axis=1) m3 = numpy.concatenate((m3,z),axis=1) deep = True pts = vtk.vtkPoints() ## Convert nupmy array to vtk ones ppV = numpy_to_vtk_wrapper(m3,deep=deep) pts.SetData(ppV) else: xm,xM,ym,yM,tmp,tmp2 = grid.GetPoints().GetBounds() vg = grid projection = vcs.elements["projection"][gm.projection] xm,xM,ym,yM = getRange(gm,xm,xM,ym,yM) if geo is None: geo, geopts = project(pts,projection,[xm,xM,ym,yM]) ## Sets the vertices into the grid if grid is None: if useStructuredGrid: vg = vtk.vtkStructuredGrid() vg.SetDimensions(data1.shape[1],data1.shape[0],1) else: vg = vtk.vtkUnstructuredGrid() vg.SetPoints(geopts) else: vg=grid out={"vtk_backend_grid":vg, "xm":xm, "xM":xM, "ym":ym, "yM":yM, "continents":continents, "wrap":wrap, "geo":geo, } return out
os.remove("test-dim.vtk") assert(r.GetOutput().GetExtent() == (0,2,0,2,0,2)) w.SetInputData(rg) w.SetFileName("test-dim.vtk") w.SetWriteExtent(True) w.Write() r.Modified() r.Update() assert(r.GetOutput().GetExtent() == (1,3,1,3,1,3)) sg = vtk.vtkStructuredGrid() extents = (1, 3, 1, 3, 1, 3) sg.SetExtent(extents) ptsa = vtk.vtkFloatArray() ptsa.SetNumberOfComponents(3) ptsa.SetNumberOfTuples(27) # We don't really care about point coordinates being correct for i in range(27): ptsa.InsertNextTuple3(0, 0, 0) pts = vtk.vtkPoints() pts.SetData(ptsa) sg.SetPoints(pts) w = vtk.vtkStructuredGridWriter() w.SetInputData(sg) w.SetFileName("test-dim.vtk")
from NACA import create_wing import numpy import vtk import dakota_utils n_naca_pts = 50 wing=create_wing("/home/david/Documents/Projet/Optim_INSA_5GMM/examples/Dakota/test_wing/TEST",n_naca_pts) # desole pour le chemin n_sections=len(wing) n_section_pts = 2*n_naca_pts-1 # build mesh vtk_model = vtk.vtkStructuredGrid() vtk_model.SetDimensions(n_section_pts,n_sections,1) # build points vtk_points = vtk.vtkPoints() for j in xrange(n_sections): upper_pts = numpy.array([wing[j][1],wing[j][3]]).T lower_pts = numpy.array([wing[j][2],wing[j][4]]).T section_pts = numpy.concatenate((lower_pts[::-1],upper_pts[1:])) for i in xrange(n_section_pts): vtk_points.InsertNextPoint(section_pts[i,0],wing[j][0],section_pts[i,1]) # set points vtk_model.SetPoints(vtk_points) # convert to poly data pdata_filter = vtk.vtkGeometryFilter() if vtk.VTK_MAJOR_VERSION <= 5: pdata_filter.SetInput(vtk_model) else: pdata_filter.SetInputData(vtk_model)
def create_mesh_linear_interp(filename,root,tip,span,n_sections,n_naca_points=150): if n_sections%2 == 0: raise ValueError("Merci de donner un nombre de sections impair") if type(root) is not list: raise TypeError("Le deuxieme argument doit etre une liste contenant M,P,T et Chord pour la section root.") if type(tip) is not list: raise TypeError("Le troisieme argument doit etre une liste contenant M,P,T et Chord pour la section tip.") if type(filename) is not str: raise TypeError("Le premier argument doit etre un string (nom du fichier de sortie).") if len(root)!=4: raise ValueError("Le deuxieme argument doit etre une liste contenant 4 valeurs (M,P,T,Chord).") if len(tip)!=4: raise ValueError("Le troisieme argument doit etre une liste contenant 4 valeurs (M,P,T,Chord).") ind_root=(n_sections-1)//2 semi_span = span/2. theta = numpy.linspace(0.,numpy.pi,n_sections) y_list = -semi_span*numpy.cos(theta) y_list[ind_root]=0. # souvent 10^-16 m_root,p_root,t_root,chord_root=root m_tip,p_tip,t_tip,chord_tip=tip Xu_tip,Xl_tip,Yu_tip,Yl_tip = NACA.create(m_tip,p_tip,t_tip,chord_tip,n_naca_points) upper_tip = numpy.array([Xu_tip,Yu_tip]).T lower_tip = numpy.array([Xl_tip,Yl_tip]).T tip_section = numpy.concatenate((lower_tip[::-1],upper_tip[1:])) Xu_root,Xl_root,Yu_root,Yl_root = NACA.create(m_root,p_root,t_root,chord_root,n_naca_points) upper_root = numpy.array([Xu_root,Yu_root]).T lower_root = numpy.array([Xl_root,Yl_root]).T root_section = numpy.concatenate((lower_root[::-1],upper_root[1:])) # build mesh vtk_model = vtk.vtkStructuredGrid() vtk_model.SetDimensions(2*n_naca_points-1,n_sections,1) # build points vtk_points = vtk.vtkPoints() for i in xrange(n_sections): r = numpy.abs(y_list[i])/semi_span current_section = (1.-r)*root_section + r*tip_section for j in xrange(2*n_naca_points-1): vtk_points.InsertNextPoint(current_section[j,0],y_list[i],current_section[j,1]) # set points vtk_model.SetPoints(vtk_points) # convert to poly data pdata_filter = vtk.vtkGeometryFilter() if vtk.VTK_MAJOR_VERSION <= 5: pdata_filter.SetInput(vtk_model) else: pdata_filter.SetInputData(vtk_model) pdata_filter.Update() poly_data = pdata_filter.GetOutput() # compute normals norms = vtk.vtkPolyDataNormals() if vtk.VTK_MAJOR_VERSION <= 5: norms.SetInput(poly_data) else: norms.SetInputData(poly_data) norms.ComputePointNormalsOff() norms.ComputeCellNormalsOn() norms.ConsistencyOn() norms.Update() # clean poly data clean_poly = vtk.vtkCleanPolyData() clean_poly.ToleranceIsAbsoluteOn() clean_poly.SetAbsoluteTolerance(1.e-6) if vtk.VTK_MAJOR_VERSION <= 5: clean_poly.SetInput(norms.GetOutput()) else: clean_poly.SetInputData(norms.GetOutput()) clean_poly.Update() # write output mesh writer = vtk.vtkXMLPolyDataWriter() if vtk.VTK_MAJOR_VERSION <= 5: writer.SetInput(clean_poly.GetOutput()) else: writer.SetInputData(clean_poly.GetOutput()) writer.SetFileName(filename+'.vtp') writer.Write()
# In the case of Windows, these classes cause a crash. classWindowsExceptions = set([ "vtkWin32VideoSource", # Update() works the first time but a subsequent run calls up the webcam which crashes on close. "vtkCMLMoleculeReader", "vtkCPExodusIIInSituReader", "vtkMINCImageWriter", "vtkQtInitialization" ]) classExceptions = set() emptyPD = vtk.vtkPolyData() emptyID = vtk.vtkImageData() emptySG = vtk.vtkStructuredGrid() emptyUG = vtk.vtkUnstructuredGrid() emptyRG = vtk.vtkRectilinearGrid() # This will hold the classes to be tested. vtkClasses = set() classNames = None # Keep a record of the classes tested. nonexistentClasses = set() abstractClasses = set() noConcreteImplementation = set() noUpdate = set() noShutdown = set() noSetInput = set() noObserver = set()
def render_geometry(self, vx, vy, vz, mv, **kwargs): """ create geometry """ self.hasData = False gridData = kwargs.get('gridData', True) if gridData: self.gridfunc = vtk.vtkStructuredGrid() else: self.gridfunc = vtk.vtkRectilinearGrid() # check data structure if type(vx) is not numpy.ndarray or type(vy) is not numpy.ndarray: logging.error('X,Y vectors must be numpy arrays') return False if type(vz) is not numpy.ndarray: logging.error('Z vector must be numpy array') return False if isinstance(mv, (list, tuple)) and len(mv) > 0: logging.error('V scalars must be numpy array') return False if len(vx) == 0 or len(vy) == 0 or len(vz) == 0: logging.error('Zero size data') return False mva = isinstance(mv, numpy.ndarray) and mv.any() if vz.ndim != 2: logging.error('Z must be 2 dimensional numpy matrix') return False if vz[0].size != vy.size: logging.error('Y dimension not match') return False if vz.transpose()[0].size != vx.size: logging.error('X dimension not match') return False if mva: if mv.size != vz.size or vz[0].size != mv[0].size or vz[1].size != mv[1].size: logging.error('Z and V dimension not match') return False Nx = vx.size Ny = vy.size Nz = vz.size # put data, z, into a 2D structured grid self.Points = vtk.vtkPoints() [self.Points.InsertNextPoint(vx[i], vy[j], vz[i, j]) for j in xrange(Ny) for i in xrange(Nx)] if gridData: self.gridfunc.SetDimensions(Nx, Ny, 1) self.gridfunc.SetPoints(self.Points) else: xCoords = vtk.vtkFloatArray() [xCoords.InsertNextValue(vx[i]) for i in xrange(Nx)] yCoords = vtk.vtkFloatArray() [yCoords.InsertNextValue(vy[j]) for j in xrange(Ny)] s = list(vz.flatten()) vz = numpy.array(s) # vz.sort() Nz = vz.size zCoords = vtk.vtkFloatArray() [zCoords.InsertNextValue(vz[k]) for k in xrange(Nz)] vCoords = vtk.vtkFloatArray() [vCoords.InsertNextValue(n) for n in xrange(1)] self.gridfunc.SetDimensions(Nx, Ny, 1) self.gridfunc.SetXCoordinates(xCoords) self.gridfunc.SetYCoordinates(yCoords) self.gridfunc.SetZCoordinates(vCoords) # get scalar field from z/v-values self.Colors = vtk.vtkFloatArray() self.Colors.SetNumberOfComponents(1) self.Colors.SetNumberOfTuples(Nx * Ny) pt = mv if mva else vz [self.Colors.InsertComponent(i + j * Nx, 0, pt[i, j]) for j in xrange(Ny) for i in xrange(Nx)] self.gridfunc.GetPointData().SetScalars(self.Colors) self.hasData = True # scaling Xrange = vx.max() - vx.min() Yrange = vy.max() - vy.min() # filter none Zrange = numpy.nanmax(vz) - numpy.nanmin(vz) # must have x or y ranges if 0 in (Xrange, Yrange): logging.error('Zero X or Y Axis Range: %s', (Xrange, Yrange)) self.hasData = False raise Exception('Zero X or Y Axis Range: %s', (Xrange, Yrange)) self.XLimit = (vx.min(), vx.max()) self.YLimit = (vy.min(), vy.max()) self.ZLimit = (numpy.nanmin(vz), numpy.nanmax(vz)) # check for constant Z range if Zrange == 0: Zrange = max(Xrange, Yrange) self.XScale = float(Zrange) / float(Xrange) self.YScale = float(Zrange) / float(Yrange) self.ZScale = float(Zrange) / float(Zrange) # fire callbacks if self.hasData: self.fireCallbacks(callback='OnDataRange') logging.debug('Parameters: %s' % str(( Nx, Ny, Nz, ':', Xrange, Yrange, Zrange, ':', self.XScale, self.YScale, self.ZScale, ':', self.XLimit, self.YLimit, self.ZLimit))) return self.hasData
mbw.PointData.append(na2, 'foo') assert mbw.GetBlock(0).GetPointData().GetNumberOfArrays() == 1 assert mbw.GetBlock(1).GetPointData().GetNumberOfArrays() == 0 assert mbw.GetBlock(0).GetPointData().GetArray(0).GetName() == 'foo' mbw.PointData.append(algs.max(na2), "maxfoo") assert mbw.GetBlock(0).GetPointData().GetNumberOfArrays() == 2 assert mbw.GetBlock(1).GetPointData().GetNumberOfArrays() == 1 assert mbw.GetBlock(0).GetPointData().GetArray(1).GetName() == 'maxfoo' # -------------------------------------- mb = vtk.vtkMultiBlockDataSet() mb.SetBlock(0, vtk.vtkImageData()) mb.SetBlock(1, vtk.vtkImageData()) assert dsa.WrapDataObject(mb).Points is na mb = vtk.vtkMultiBlockDataSet() mb.SetBlock(0, vtk.vtkStructuredGrid()) mb.SetBlock(1, vtk.vtkImageData()) assert dsa.WrapDataObject(mb).Points is na mb = vtk.vtkMultiBlockDataSet() sg = vtk.vtkStructuredGrid() sg.SetPoints(vtk.vtkPoints()) mb.SetBlock(0, sg) mb.SetBlock(1, vtk.vtkImageData()) assert dsa.WrapDataObject(mb).Points.Arrays[0] is not na assert dsa.WrapDataObject(mb).Points.Arrays[1] is na
def GetSource(dataType): s = vtk.vtkRTAnalyticSource() if dataType == 'ImageData': return s elif dataType == 'UnstructuredGrid': dst = vtk.vtkDataSetTriangleFilter() dst.SetInputConnection(s.GetOutputPort()) return dst elif dataType == 'RectilinearGrid': s.Update() input = s.GetOutput() rg = vtk.vtkRectilinearGrid() rg.SetExtent(input.GetExtent()) dims = input.GetDimensions() spacing = input.GetSpacing() x = vtk.vtkFloatArray() x.SetNumberOfTuples(dims[0]) for i in range(dims[0]): x.SetValue(i, spacing[0]*i) y = vtk.vtkFloatArray() y.SetNumberOfTuples(dims[1]) for i in range(dims[1]): y.SetValue(i, spacing[1]*i) z = vtk.vtkFloatArray() z.SetNumberOfTuples(dims[2]) for i in range(dims[2]): z.SetValue(i, spacing[2]*i) rg.SetXCoordinates(x) rg.SetYCoordinates(y) rg.SetZCoordinates(z) rg.GetPointData().ShallowCopy(input.GetPointData()) pf.SetInputData(rg) return pf elif dataType == 'StructuredGrid': s.Update() input = s.GetOutput() sg = vtk.vtkStructuredGrid() sg.SetExtent(input.GetExtent()) pts = vtk.vtkPoints() sg.SetPoints(pts) npts = input.GetNumberOfPoints() for i in range(npts): pts.InsertNextPoint(input.GetPoint(i)) sg.GetPointData().ShallowCopy(input.GetPointData()) pf.SetInputData(sg) return pf elif dataType == 'Table': s.Update() input = s.GetOutput() table = vtk.vtkTable() RTData = input.GetPointData().GetArray(0) nbTuples = RTData.GetNumberOfTuples() array = vtk.vtkFloatArray() array.SetName("RTData") array.SetNumberOfTuples(nbTuples) for i in range(0, nbTuples): array.SetTuple1(i, float(RTData.GetTuple1(i))) table.AddColumn(array) pf.SetInputData(table) return pf
def build_mesh(filename,semi_span,root_chord,tip_chord,root_m,root_p,tip_m,tip_p,t,nu=50,nv=21): # build root section Xu,Xl,Yu,Yl = create_naca(root_m,root_p,t,C=root_chord,n=nu) upper = numpy.array([Xu,Yu]).T lower = numpy.array([Xl,Yl]).T root_section = numpy.concatenate((lower[::-1],upper[1:])) # set x position root_section[:,0]-=0.25*root_chord # build tip section Xu,Xl,Yu,Yl = create_naca(tip_m,tip_p,t,C=tip_chord,n=nu) upper = numpy.array([Xu,Yu]).T lower = numpy.array([Xl,Yl]).T tip_section = numpy.concatenate((lower[::-1],upper[1:])) # set x position tip_section[:,0]-=0.25*tip_chord # build mesh vtk_model = vtk.vtkStructuredGrid() vtk_model.SetDimensions(2*nu-1,nv,1) # build points vtk_points = vtk.vtkPoints() theta = numpy.linspace(0.,numpy.pi,nv) y_array = -semi_span*numpy.cos(theta) #y_array = numpy.linspace(-semi_span,semi_span,nv) for j,y in enumerate(y_array): r = abs(y)/semi_span current_section = (1.-r)*root_section+r*tip_section for i in xrange(2*nu-1): vtk_points.InsertNextPoint(current_section[i,0],y,current_section[i,1]) # set points vtk_model.SetPoints(vtk_points) # convert to poly data pdata_filter = vtk.vtkGeometryFilter() if vtk.VTK_MAJOR_VERSION <= 5: pdata_filter.SetInput(vtk_model) else: pdata_filter.SetInputData(vtk_model) pdata_filter.Update() poly_data = pdata_filter.GetOutput() # compute normals norms = vtk.vtkPolyDataNormals() if vtk.VTK_MAJOR_VERSION <= 5: norms.SetInput(poly_data) else: norms.SetInputData(poly_data) norms.ComputePointNormalsOff() norms.ComputeCellNormalsOn() norms.ConsistencyOn() norms.Update() # clean poly data clean_poly = vtk.vtkCleanPolyData() clean_poly.ToleranceIsAbsoluteOn() clean_poly.SetAbsoluteTolerance(1.e-6) if vtk.VTK_MAJOR_VERSION <= 5: clean_poly.SetInput(norms.GetOutput()) else: clean_poly.SetInputData(norms.GetOutput()) clean_poly.Update() # write output mesh writer = vtk.vtkXMLPolyDataWriter() if vtk.VTK_MAJOR_VERSION <= 5: writer.SetInput(clean_poly.GetOutput()) else: writer.SetInputData(clean_poly.GetOutput()) writer.SetFileName(filename) writer.Write()
blankedPlane = vtk.vtkStructuredGridGeometryFilter() blankedPlane.SetInputConnection(blankIt.GetOutputPort()) blankedPlane.SetExtent(0, 100, 0, 100, 0, 0) planeMapper = vtk.vtkPolyDataMapper() planeMapper.SetInputConnection(blankedPlane.GetOutputPort()) planeMapper.SetScalarRange(0.197813, 0.710419) planeActor = vtk.vtkActor() planeActor.SetMapper(planeMapper) # The second blanking technique uses grid data values to create the blanking. # Here we borrow the image data and threshold on that. # anotherGrid = vtk.vtkStructuredGrid() anotherGrid.CopyStructure(plane.GetOutput()) anotherGrid.GetPointData().SetScalars(blankImage.GetPointData().GetScalars()) blankGrid = vtk.vtkBlankStructuredGrid() blankGrid.SetInputData(anotherGrid) blankGrid.SetArrayName("blankScalars") blankGrid.SetMinBlankingValue(-0.5) blankGrid.SetMaxBlankingValue(0.5) blankedPlane2 = vtk.vtkStructuredGridGeometryFilter() blankedPlane2.SetInputConnection(blankGrid.GetOutputPort()) blankedPlane2.SetExtent(0, 100, 0, 100, 0, 0) planeMapper2 = vtk.vtkPolyDataMapper() planeMapper2.SetInputConnection(blankedPlane2.GetOutputPort())
points = vtk.vtkPoints() points.InsertNextPoint(-1,1,0) points.InsertNextPoint(0,1,0) points.InsertNextPoint(1,1,0) points.InsertNextPoint(-1,0,0) points.InsertNextPoint(0,0,0) points.InsertNextPoint(1,0,0) points.InsertNextPoint(-1,-1,0) points.InsertNextPoint(0,-1,0) points.InsertNextPoint(1,-1,0) faceColors = vtk.vtkFloatArray() faceColors.InsertNextValue(0) faceColors.InsertNextValue(1) faceColors.InsertNextValue(1) faceColors.InsertNextValue(2) sgrid = vtk.vtkStructuredGrid() sgrid.SetDimensions(3,3,1) sgrid.SetPoints(points) sgrid.GetCellData().SetScalars(faceColors) Cell2Point = vtk.vtkCellDataToPointData() Cell2Point.SetInputData(sgrid) Cell2Point.PassCellDataOn() Cell2Point.Update() mapper = vtk.vtkDataSetMapper() mapper.SetInputData(Cell2Point.GetStructuredGridOutput()) mapper.SetScalarModeToUsePointData() mapper.SetScalarRange(0,2) actor = vtk.vtkActor() actor.SetMapper(mapper) # Add the actors to the renderer, set the background and size ren1.AddActor(actor)
VTK_DATA_ROOT = vtkGetDataRoot() # Remove cullers so single vertex will render ren1 = vtk.vtkRenderer() ren1.GetCullers().RemoveAllItems() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) cell = vtk.vtkGenericCell() ptIds = vtk.vtkIdList() # 0D ZeroDPts = vtk.vtkPoints() ZeroDPts.SetNumberOfPoints(1) ZeroDPts.SetPoint(0,0,0,0) ZeroDGrid = vtk.vtkStructuredGrid() ZeroDGrid.SetDimensions(1,1,1) ZeroDGrid.SetPoints(ZeroDPts) ZeroDGrid.GetCell(0) ZeroDGrid.GetCell(0,cell) ZeroDGrid.GetCellPoints(0,ptIds) ZeroDGeom = vtk.vtkStructuredGridGeometryFilter() ZeroDGeom.SetInputData(ZeroDGrid) ZeroDGeom.SetExtent(0,2,0,2,0,2) ZeroDMapper = vtk.vtkPolyDataMapper() ZeroDMapper.SetInputConnection(ZeroDGeom.GetOutputPort()) ZeroDActor = vtk.vtkActor() ZeroDActor.SetMapper(ZeroDMapper) ZeroDActor.SetPosition(0,0,0) ren1.AddActor(ZeroDActor) # 1D - X
def GetSource(dataType): s = vtk.vtkRTAnalyticSource() # Fake serial source if rank == 0: s.Update() if dataType == 'ImageData': return s.GetOutput() elif dataType == 'UnstructuredGrid': dst = vtk.vtkDataSetTriangleFilter() dst.SetInputData(s.GetOutput()) dst.Update() return dst.GetOutput() elif dataType == 'RectilinearGrid': input = s.GetOutput() rg = vtk.vtkRectilinearGrid() rg.SetExtent(input.GetExtent()) dims = input.GetDimensions() spacing = input.GetSpacing() x = vtk.vtkFloatArray() x.SetNumberOfTuples(dims[0]) for i in range(dims[0]): x.SetValue(i, spacing[0]*i) y = vtk.vtkFloatArray() y.SetNumberOfTuples(dims[1]) for i in range(dims[1]): y.SetValue(i, spacing[1]*i) z = vtk.vtkFloatArray() z.SetNumberOfTuples(dims[2]) for i in range(dims[2]): z.SetValue(i, spacing[2]*i) rg.SetXCoordinates(x) rg.SetYCoordinates(y) rg.SetZCoordinates(z) rg.GetPointData().ShallowCopy(input.GetPointData()) return rg elif dataType == 'StructuredGrid': input = s.GetOutput() sg = vtk.vtkStructuredGrid() sg.SetExtent(input.GetExtent()) pts = vtk.vtkPoints() sg.SetPoints(pts) npts = input.GetNumberOfPoints() for i in xrange(npts): pts.InsertNextPoint(input.GetPoint(i)) sg.GetPointData().ShallowCopy(input.GetPointData()) return sg
def create_mesh_linear_interp(m_root,p_root,t_root,m_tip,p_tip,t_tip,ystart,yend,chord,n_sections,n_naca_points=150): if n_sections%2 == 0: raise ValueError("Merci de donner un nombre de sections impair") ind_root=(n_sections-1)//2 semi_span = (ystart-yend)/2 theta = numpy.linspace(0.,numpy.pi,n_sections) y_list = -semi_span*numpy.cos(theta) y_list[ind_root]=0. # souvent 10^-16 Xu_tip,Xl_tip,Yu_tip,Yl_tip = create(m_tip,p_tip,t_tip,chord,n_naca_points) upper_tip = numpy.array([Xu_tip,Yu_tip]).T lower_tip = numpy.array([Xl_tip,Yl_tip]).T tip_section = numpy.concatenate((upper_tip[::-1],lower_tip[1:])) Xu_root,Xl_root,Yu_root,Yl_root = create(m_root,p_root,t_root,chord,n_naca_points) upper_root = numpy.array([Xu_root,Yu_root]).T lower_root = numpy.array([Xl_root,Yl_root]).T root_section = numpy.concatenate((upper_root[::-1],lower_root[1:])) # build mesh vtk_model = vtk.vtkStructuredGrid() vtk_model.SetDimensions(2*n_naca_points-1,n_sections,1) # build points vtk_points = vtk.vtkPoints() for i in xrange(n_sections): r = numpy.abs(y_list[i])/semi_span current_section = (1.-r)*root_section + r*tip_section for j in xrange(2*n_naca_points-1): vtk_points.InsertNextPoint(current_section[j,0],y_list[i],current_section[j,1]) # set points vtk_model.SetPoints(vtk_points) # convert to poly data pdata_filter = vtk.vtkGeometryFilter() if vtk.VTK_MAJOR_VERSION <= 5: pdata_filter.SetInput(vtk_model) else: pdata_filter.SetInputData(vtk_model) pdata_filter.Update() poly_data = pdata_filter.GetOutput() # compute normals norms = vtk.vtkPolyDataNormals() if vtk.VTK_MAJOR_VERSION <= 5: norms.SetInput(poly_data) else: norms.SetInputData(poly_data) norms.ComputePointNormalsOff() norms.ComputeCellNormalsOn() norms.ConsistencyOn() norms.Update() # clean poly data clean_poly = vtk.vtkCleanPolyData() clean_poly.ToleranceIsAbsoluteOn() clean_poly.SetAbsoluteTolerance(1.e-6) if vtk.VTK_MAJOR_VERSION <= 5: clean_poly.SetInput(norms.GetOutput()) else: clean_poly.SetInputData(norms.GetOutput()) clean_poly.Update() # write output mesh writer = vtk.vtkXMLPolyDataWriter() if vtk.VTK_MAJOR_VERSION <= 5: writer.SetInput(clean_poly.GetOutput()) else: writer.SetInputData(clean_poly.GetOutput()) writer.SetFileName('output.vtp') writer.Write()
ExtractGrid1.SetIncludeBoundary(0) ExtractGrid2 = vtk.vtkExtractGrid() ExtractGrid2.SetInputData(output) ExtractGrid2.SetVOI(29,56,0,32,0,24) ExtractGrid2.SetSampleRate(1,1,1) ExtractGrid2.SetIncludeBoundary(0) LineSourceWidget0 = vtk.vtkLineSource() LineSourceWidget0.SetPoint1(3.05638,-3.00497,28.2211) LineSourceWidget0.SetPoint2(3.05638,3.95916,28.2211) LineSourceWidget0.SetResolution(20) mbds = vtk.vtkMultiBlockDataSet() mbds.SetNumberOfBlocks(3) i = 0 while i < 3: locals()[get_variable_name("ExtractGrid", i, "")].Update() locals()[get_variable_name("sg", i, "")] = vtk.vtkStructuredGrid() locals()[get_variable_name("sg", i, "")].ShallowCopy(locals()[get_variable_name("ExtractGrid", i, "")].GetOutput()) mbds.SetBlock(i,locals()[get_variable_name("sg", i, "")]) del locals()[get_variable_name("sg", i, "")] i = i + 1 Stream0 = vtk.vtkStreamTracer() Stream0.SetInputData(mbds) Stream0.SetSourceConnection(LineSourceWidget0.GetOutputPort()) Stream0.SetIntegrationStepUnit(2) Stream0.SetMaximumPropagation(20) Stream0.SetInitialIntegrationStep(0.5) Stream0.SetIntegrationDirection(0) Stream0.SetIntegratorType(0) Stream0.SetMaximumNumberOfSteps(2000) Stream0.SetTerminalSpeed(1e-12)