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 get_number_of_points_and_boundary_faces(pod_mode_dir,calibrate_coefficients): filename = pod_mode_dir+"/spatial_meanfield.vtk" reader = vtk.vtkUnstructuredGridReader() reader.ReadAllScalarsOn() reader.ReadAllVectorsOn() reader.ReadAllTensorsOn() reader.SetFileName(filename) reader.Update() num_points = reader.GetOutput().GetNumberOfPoints() if( (calibrate_coefficients=="none") or (calibrate_coefficients=="constant") ): geom_filter = vtk.vtkDataSetSurfaceFilter() geom_filter.SetInput(reader.GetOutput()) geom_filter.Update() boundary_faces = vtk.vtkPolyData() boundary_faces = geom_filter.GetOutput() point_to_cell_data = vtk.vtkPointDataToCellData() point_to_cell_data.SetInput(geom_filter.GetOutput()) point_to_cell_data.Update() num_boundary_faces = point_to_cell_data.GetOutput().GetNumberOfCells() else: num_boundary_faces = 1 return num_points, num_boundary_faces
def pointToCellData(): print "Using angle: " + str(angle) atpFiles = glob.glob(str(angle) + '/*.vtp') if not atpFiles: exit("No atp files found") if not os.path.exists(str(angle) + '_new'): os.makedirs(str(angle) + '_new') for inputFile in atpFiles: print 'Reading', inputFile atpReader = vtk.vtkXMLPolyDataReader() atpReader.SetFileName(inputFile) atpReader.Update() atpDataset = atpReader.GetOutput() pointToCell = vtk.vtkPointDataToCellData() pointToCell.SetInputData(atpDataset) pointToCell.PassPointDataOn() pointToCell.Update() newArray = pointToCell.GetOutput() # Remove the point data arrays, they exist as cell data newArray.GetPointData().RemoveArray('ATP') newArray.GetPointData().RemoveArray('tau') newArray.GetCellData().RemoveArray('p') atpWriter = vtk.vtkXMLPolyDataWriter() atpWriter.SetInputData(newArray) atpWriter.SetFileName(str(angle) + '_new/' + inputFile[3:]) atpWriter.Update()
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkPointDataToCellData(), 'Processing.', ('vtkDataSet',), ('vtkDataSet',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def vti2vtu(vti, threshold=0.1, field='rho', output_file=None): """ Returns unstructured grid for existing voxels based on threshold filtering output: file or vtk object - highly inefficient - allocates a full geometry before threshold """ p2c = vtk.vtkPointDataToCellData() p2c.SetInputData(vti) p2c.PassPointDataOn() p2c.Update() t = vtk.vtkThreshold() t.SetInputData(p2c.GetOutput()) t.ThresholdByUpper(threshold) t.SetInputArrayToProcess(0, 0, 0, 0, field) t.Update() print('# of Cells (unstructured):', t.GetOutput().GetNumberOfCells(), 'vs. vti: ', vti.GetNumberOfPoints()) if output_file: sw = vtk.vtkXMLUnstructuredGridWriter() sw.SetFileName(output_file) sw.SetInputData(t.GetOutput()) sw.Write() else: return t.GetOutput()
def get_number_of_points_and_boundary_faces(pod_mode_dir, calibrate_coefficients): filename = pod_mode_dir + "/spatial_meanfield.vtk" reader = vtk.vtkUnstructuredGridReader() reader.ReadAllScalarsOn() reader.ReadAllVectorsOn() reader.ReadAllTensorsOn() reader.SetFileName(filename) reader.Update() num_points = reader.GetOutput().GetNumberOfPoints() if ((calibrate_coefficients == "none") or (calibrate_coefficients == "constant")): geom_filter = vtk.vtkDataSetSurfaceFilter() geom_filter.SetInput(reader.GetOutput()) geom_filter.Update() boundary_faces = vtk.vtkPolyData() boundary_faces = geom_filter.GetOutput() point_to_cell_data = vtk.vtkPointDataToCellData() point_to_cell_data.SetInput(geom_filter.GetOutput()) point_to_cell_data.Update() num_boundary_faces = point_to_cell_data.GetOutput().GetNumberOfCells() else: num_boundary_faces = 1 return num_points, num_boundary_faces
def __init__(self, filename, clean=False, pointData=False): Reader.__init__(self, filename) self._vtkReader = vtk.vtkXMLPolyDataReader() self._fileName = filename self._vtkReader.SetFileName(self._fileName) self._vtkReader.Update() internalData = self._transform() if clean: internalData = self._clean(internalData) if pointData: interp = vtk.vtkPointDataToCellData() interp.SetInputData(internalData) interp.PassPointDataOff() interp.Update() internalData = interp.GetOutput() internalData.BuildLinks() n = internalData.GetNumberOfCells() pids = np.arange(n) internalData.GetAttributes(vtk.vtkDataObject.CELL).SetPedigreeIds( numpy_to_vtk(pids)) boundaryData = self._extract_boundary_data(internalData) bDict = {'boundary': boundaryData} mark_boundary_cells(internalData, bDict) self._data = self._assemble_multiblock_data(internalData, boundaryData)
def mapPointDataToCellData(input_Domain): p2c = vtk.vtkPointDataToCellData() p2c.SetInputData(input_Domain) p2c.PassPointDataOn() # p2c.SetInputArrayToProcess(0, 0, 0,vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, "ev1") p2c.Update() output = p2c.GetOutput() return output
def _createPolyDataFilter(self): """Overrides baseclass implementation.""" self._vtkPolyDataFilter = vtk.vtkDataSetSurfaceFilter() if self._useCellScalars: p2c = vtk.vtkPointDataToCellData() p2c.SetInputData(self._vtkDataSet) self._vtkPolyDataFilter.SetInputConnection(p2c.GetOutputPort()) else: self._vtkPolyDataFilter.SetInputData(self._vtkDataSet)
def _createPolyDataFilter(self): """Overrides baseclass implementation.""" self._vtkPolyDataFilter = vtk.vtkDataSetSurfaceFilter() if self._useCellScalars: p2c = vtk.vtkPointDataToCellData() p2c.SetInputData(self._vtkDataSet) self._vtkPolyDataFilter.SetInputConnection(p2c.GetOutputPort()) else: self._vtkPolyDataFilter.SetInputData(self._vtkDataSet)
def Execute(self): if self.Surface == None: self.PrintError('Error: No Surface.') pointDataToCellDataFilter = vtk.vtkPointDataToCellData() pointDataToCellDataFilter.SetInputData(self.Surface) pointDataToCellDataFilter.PassPointDataOn() pointDataToCellDataFilter.Update() self.Surface = pointDataToCellDataFilter.GetPolyDataOutput()
def Execute(self): if self.Surface == None: self.PrintError('Error: No Surface.') pointDataToCellDataFilter = vtk.vtkPointDataToCellData() pointDataToCellDataFilter.SetInputData(self.Surface) pointDataToCellDataFilter.PassPointDataOn() pointDataToCellDataFilter.Update() self.Surface = pointDataToCellDataFilter.GetPolyDataOutput()
def get_geo(file_name): # Read the source file. reader = vtkXMLUnstructuredGridReader() reader.SetFileName(file_name) reader.Update() output = reader.GetOutput() # name of the array with geometry information geoname = 'vtkValidPointMask' # check if array is a cell- or point-data array cell_data = output.GetCellData() cell = has_array(geoname, cell_data) # convert to cell-data if array is point-data if not cell: point_data = output.GetPointData() point = has_array(geoname, point_data) if not point: print(' Array {:s} is missing'.format(geo)) raise SystemExit(' Aborting...') print(' Converting point data to cell data') p2c = vtkPointDataToCellData() p2c.SetInputData(output) #p2c.PassPointDataOn() p2c.Update() cell_data = p2c.GetOutput().GetCellData() # set up grid sys_bound = array(output.GetBounds()) ncells = output.GetNumberOfCells() cell_bound = zeros(6) output.GetCellBounds(0, cell_bound) grid = Grid(sys_bound, ncells, cell_bound) for i in range(ncells): bound = zeros(6) output.GetCellBounds(i, bound) grid.set_cell(i, bound) # read cell data geo = {} for n in range(cell_data.GetNumberOfArrays()): name = cell_data.GetArrayName(n) if geoname not in name: continue #print(name) A = vtk_to_numpy(cell_data.GetArray(n)) data = zeros(grid.dim, A.dtype) for i in range(A.shape[0]): data[grid.get_cell_index(i)] = A[i] geo = data return geo
def cut_polydata_with_another(poly1, poly2, plane_info): """ Cuts the first VTK PolyData with another Args: poly1: 1st VTK PolyData poly2: 2nd VTK PolyData inside: whether inside or outside gets kept (bool) Returns: poly: cut VTK PolyData """ implicit = vtk.vtkImplicitPolyDataDistance() implicit.SetInput(poly2) signedDistances = vtk.vtkFloatArray() signedDistances.SetNumberOfComponents(1) signedDistances.SetName("SignedDistances") # Evaluate the signed distance function at all of the grid points points = poly1.GetPoints() ctr, nrm = plane_info for pointId in range(points.GetNumberOfPoints()): p = points.GetPoint(pointId) signedDistance = implicit.EvaluateFunction(p) plane_sign = np.sum(np.array(p - ctr) * nrm) signedDistance = np.abs( signedDistance) if plane_sign < 0 else signedDistance signedDistances.InsertNextValue(signedDistance) poly1.GetPointData().SetScalars(signedDistances) ##clipper = vtk.vtkClipPolyData() #clipper = vtk.vtkExtractPolyDataGeometry() ##clipper.SetClipFunction(implicit) #clipper.SetImplicitFunction(implicit) #clipper.SetInputData(poly1) ##clipper.SetInsideOut(inside) #clipper.SetExtractInside(inside) #clipper.SetExtractBoundaryCells(True) #clipper.Update() p2c = vtk.vtkPointDataToCellData() p2c.SetInputData(poly1) p2c.Update() poly1 = p2c.GetOutput() clipper = threshold_polydata(poly1, 'SignedDistances', (0., np.inf)) connectivity = vtk.vtkPolyDataConnectivityFilter() #connectivity.SetInputData(clipper.GetOutput()) connectivity.SetInputData(clipper) connectivity.SetExtractionModeToLargestRegion() connectivity.Update() poly = connectivity.GetOutput() return poly
def mapPointsToCells(self): """ Transform point data (i.e., data specified per point) into cell data (i.e., data specified per cell). The method of transformation is based on averaging the data values of all points defining a particular cell. |mesh_map2cell| |mesh_map2cell.py|_ """ p2c = vtk.vtkPointDataToCellData() p2c.SetInputData(self.polydata(False)) p2c.Update() self._mapper.SetScalarModeToUseCellData() return self._update(p2c.GetOutput())
def func_to_m_dim_field(self, functionarray, fieldname, ofilename, cell=False): """ Add a multidimensional field to the vtu file (which will be saved directly as "ofilename" by providing am array of three argument functions. Parameters ---------- functionarray : `array` of objects fieldname : `str` ofilename : `str` """ mdim = len(functionarray) for function in functionarray: if callable(function) is False: print("functionarray is not containing functions only.") raise TypeError fieldarray = np.zeros((len(self.points), mdim)) for i, _ in enumerate(fieldarray): for j, func in enumerate(functionarray): if self.dim == 2: fieldarray[i, j] = func(self.points[i, 0], self.points[i, 1], 0.0) else: fieldarray[i, j] = func(self.points[i, 0], self.points[i, 1], self.points[i, 2]) field_vtk = numpy_to_vtk(fieldarray) r = self.pdata.AddArray(field_vtk) self.pdata.GetArray(r).SetName(fieldname) if cell is True: p2c = vtk.vtkPointDataToCellData() p2c.SetInputData(self.output) p2c.Update() outcells = p2c.GetOutput() cells = outcells.GetCellData() array = cells.GetArray(fieldname) cells_orig = self.output.GetCellData() cells_orig.AddArray(array) self.pdata.RemoveArray(fieldname) writer = vtk.vtkXMLUnstructuredGridWriter() writer.SetFileName(ofilename) writer.SetInputData(self.output) writer.Write()
def point_data_to_cell_data(dataset, pass_point_data=False): """Transforms point data (i.e., data specified per node) into cell data (i.e., data specified within cells). Optionally, the input point data can be passed through to the output. See aslo: :func:`vtki.DataSetFilters.cell_data_to_point_data` Parameters ---------- pass_point_data : bool If enabled, pass the input point data through to the output """ alg = vtk.vtkPointDataToCellData() alg.SetInputDataObject(dataset) alg.SetPassPointData(pass_point_data) alg.Update() return _get_output(alg, active_scalar=dataset.active_scalar_name)
def _createPolyDataFilter(self): """This is only used when we use the grid stored in the file for all plots.""" self._vtkPolyDataFilter = vtk.vtkDataSetSurfaceFilter() if self._hasCellData == self._needsCellData: self._vtkPolyDataFilter.SetInputData(self._vtkDataSet) elif self._hasCellData: # use cells but needs points c2p = vtk.vtkCellDataToPointData() c2p.PassCellDataOn() c2p.SetInputData(self._vtkDataSet) self._vtkPolyDataFilter.SetInputConnection(c2p.GetOutputPort()) else: # use points but needs cells p2c = vtk.vtkPointDataToCellData() p2c.SetInputData(self._vtkDataSet) # For contouring duplicate points seem to confuse it self._vtkPolyDataFilter.SetInputConnection(p2c.GetOutputPort()) self._vtkPolyDataFilter.Update() self._resultDict["vtk_backend_filter"] = self._vtkPolyDataFilter vp = self._resultDict.get('ratio_autot_viewport', [ self._template.data.x1, self._template.data.x2, self._template.data.y1, self._template.data.y2 ]) plotting_dataset_bounds = self.getPlottingBounds() xScale, yScale, xc, yc, yd, flipX, flipY = self._context( ).computeScaleToFitViewport(vp, wc=plotting_dataset_bounds, geoBounds=self._vtkDataSetBoundsNoMask, geo=self._vtkGeoTransform) self._vtkPolyDataFilter.Update() self._vtkDataSetFittedToViewport = self._vtkPolyDataFilter.GetOutput() self._vtkDataSetBoundsNoMask = self._vtkDataSetFittedToViewport.GetBounds( ) self._context_xScale = xScale self._context_yScale = yScale self._context_xc = xc self._context_yc = yc self._context_yd = yd self._context_flipX = flipX if not self._vtkGeoTransform else None self._context_flipY = flipY if not self._vtkGeoTransform else None self._resultDict['surface_scale'] = (xScale, yScale)
def test_dataset(ds): p2c = vtk.vtkPointDataToCellData() p2c.SetInputData(ds) p2c.Update() d1 = dsa.WrapDataObject(p2c.GetOutput()) vtkm_p2c = vtk.vtkmAverageToCells() vtkm_p2c.SetInputData(ds) vtkm_p2c.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, "RTData") vtkm_p2c.Update() d2 = dsa.WrapDataObject(vtkm_p2c.GetOutput()) rtD1 = d1.PointData['RTData'] rtD2 = d2.PointData['RTData'] assert (algs.max(algs.abs(rtD1 - rtD2)) < 10E-4)
def _createPolyDataFilter(self): """This is only used when we use the grid stored in the file for all plots.""" self._vtkPolyDataFilter = vtk.vtkDataSetSurfaceFilter() if self._hasCellData == self._needsCellData: self._vtkPolyDataFilter.SetInputData(self._vtkDataSet) elif self._hasCellData: # use cells but needs points c2p = vtk.vtkCellDataToPointData() c2p.PassCellDataOn() c2p.SetInputData(self._vtkDataSet) self._vtkPolyDataFilter.SetInputConnection(c2p.GetOutputPort()) else: # use points but needs cells p2c = vtk.vtkPointDataToCellData() p2c.SetInputData(self._vtkDataSet) # For contouring duplicate points seem to confuse it self._vtkPolyDataFilter.SetInputConnection(p2c.GetOutputPort()) self._vtkPolyDataFilter.Update() self._resultDict["vtk_backend_filter"] = self._vtkPolyDataFilter # create an actor and a renderer for the surface mesh. # this is used for displaying point information using the hardware selection mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort()) act = vtk.vtkActor() act.SetMapper(mapper) vp = self._resultDict.get('ratio_autot_viewport', [ self._template.data.x1, self._template.data.x2, self._template.data.y1, self._template.data.y2 ]) plotting_dataset_bounds = self.getPlottingBounds() surface_renderer, xScale, yScale = self._context().fitToViewport( act, vp, wc=plotting_dataset_bounds, geoBounds=self._vtkDataSetBoundsNoMask, geo=self._vtkGeoTransform, priority=self._template.data.priority, create_renderer=True) self._resultDict['surface_renderer'] = surface_renderer self._resultDict['surface_scale'] = (xScale, yScale) if (surface_renderer): surface_renderer.SetDraw(False)
def putMaskOnVTKGrid(data, grid, actorColor=None, cellData=True, 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 and not numpy.allclose(msk, False): msk = VN.numpy_to_vtk(numpy.logical_not(msk).astype(numpy.uint8).flat, deep=deep) if actorColor is not None: if grid.IsA("vtkStructuredGrid"): grid2 = vtk.vtkStructuredGrid() else: grid2 = vtk.vtkUnstructuredGrid() grid2.CopyStructure(grid) geoFilter = vtk.vtkDataSetSurfaceFilter() if not cellData: 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"): if not cellData: grid.SetPointVisibilityArray(msk) else: grid.SetCellVisibilityArray(msk) return mapper
def point_data_to_cell_data(self, fieldname, ofilename): """ convert pointdata to cell data of field "fieldname" Parameters ---------- fieldname : `str` ofilename : `str` """ p2c = vtk.vtkPointDataToCellData() p2c.SetInputData(self.output) p2c.Update() outcells = p2c.GetOutput() cells = outcells.GetCellData() array = cells.GetArray(fieldname) cells_orig = self.output.GetCellData() cells_orig.AddArray(array) writer = vtk.vtkXMLUnstructuredGridWriter() writer.SetFileName(ofilename) writer.SetInputData(self.output) writer.Write()
def _createPolyDataFilter(self): """This is only used when we use the grid stored in the file for all plots.""" self._vtkPolyDataFilter = vtk.vtkDataSetSurfaceFilter() if self._hasCellData == self._needsCellData: self._vtkPolyDataFilter.SetInputData(self._vtkDataSet) elif self._hasCellData: # use cells but needs points c2p = vtk.vtkCellDataToPointData() c2p.PassCellDataOn() c2p.SetInputData(self._vtkDataSet) self._vtkPolyDataFilter.SetInputConnection(c2p.GetOutputPort()) else: # use points but needs cells p2c = vtk.vtkPointDataToCellData() p2c.SetInputData(self._vtkDataSet) # For contouring duplicate points seem to confuse it self._vtkPolyDataFilter.SetInputConnection(p2c.GetOutputPort()) self._vtkPolyDataFilter.Update() self._resultDict["vtk_backend_filter"] = self._vtkPolyDataFilter # create an actor and a renderer for the surface mesh. # this is used for displaying point information using the hardware selection mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort()) act = vtk.vtkActor() act.SetMapper(mapper) vp = self._resultDict.get( 'ratio_autot_viewport', [self._template.data.x1, self._template.data.x2, self._template.data.y1, self._template.data.y2]) plotting_dataset_bounds = self.getPlottingBounds() surface_renderer, xScale, yScale = self._context().fitToViewport( act, vp, wc=plotting_dataset_bounds, geoBounds=self._vtkDataSet.GetBounds(), geo=self._vtkGeoTransform, priority=self._template.data.priority, create_renderer=True) self._resultDict['surface_renderer'] = surface_renderer self._resultDict['surface_scale'] = (xScale, yScale) if (surface_renderer): surface_renderer.SetDraw(False)
def func_to_field(self, function, fieldname, ofilename, cell=False): """ Add a field to the vtu file (which will be saved directly as "ofilename" by providing a three argument function(x,y,z) Parameters ---------- function : `function` fieldname : `str` ofilename : `str` cell : `bool` """ if callable(function) is False: print("function is not a function") raise TypeError fieldarray = np.zeros(len(self.points)) for i, _ in enumerate(fieldarray): if self.dim == 2: fieldarray[i] = function(self.points[i, 0], self.points[i, 1], 0.0) else: fieldarray[i] = function(self.points[i, 0], self.points[i, 1], self.points[i, 2]) field_vtk = numpy_to_vtk(fieldarray) r = self.pdata.AddArray(field_vtk) self.pdata.GetArray(r).SetName(fieldname) if cell is True: p2c = vtk.vtkPointDataToCellData() p2c.SetInputData(self.output) p2c.Update() outcells = p2c.GetOutput() cells = outcells.GetCellData() array = cells.GetArray(fieldname) cells_orig = self.output.GetCellData() cells_orig.AddArray(array) self.pdata.RemoveArray(fieldname) writer = vtk.vtkXMLUnstructuredGridWriter() writer.SetFileName(ofilename) writer.SetInputData(self.output) writer.Write()
def test_dataset(ds): p2c = vtk.vtkPointDataToCellData() p2c.SetInputData(ds) p2c.Update() c2p = vtk.vtkCellDataToPointData() c2p.SetInputConnection(p2c.GetOutputPort()) c2p.Update() d1 = dsa.WrapDataObject(c2p.GetOutput()) c2p = vtk.vtkmAverageToPoints() c2p.SetInputData(p2c.GetOutput()) c2p.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS, "RTData") c2p.Update() d2 = dsa.WrapDataObject(c2p.GetOutput()) rtD1 = d1.PointData['RTData'] rtD2 = d2.PointData['RTData'] assert (algs.max(algs.abs(rtD1 - rtD2)) < 10E-4)
def test_dataset(ds): p2c = vtk.vtkPointDataToCellData() p2c.SetInputData(ds) p2c.Update() c2p = vtk.vtkCellDataToPointData() c2p.SetInputConnection(p2c.GetOutputPort()) c2p.Update() d1 = dsa.WrapDataObject(c2p.GetOutput()) c2p = vtk.vtkmAverageToPoints() c2p.SetInputData(p2c.GetOutput()) c2p.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS, "RTData") c2p.Update() d2 = dsa.WrapDataObject(c2p.GetOutput()) rtD1 = d1.PointData['RTData'] rtD2 = d2.PointData['RTData'] assert (algs.max(algs.abs(rtD1 - rtD2)) < 10E-4)
def vtk_point_to_cell_interpolation(self, uGrid, varName=''): """Interpolate all point data to cell in an unstructured grid In VTK, it is a simple average of data for all points defining a cell. Parameters ---------- uGrid: vtkUnstructuredGrid object varName: {string} -- optional variable name; if specified, only this variable will be processed (not implemented yet) Returns ------- """ #first check whether there is already a cell data named "varName" pointDataNames, cellDataNames = self.get_uGRid_all_field_names(uGrid) print("pointDataNames, cellDataNames =", pointDataNames, cellDataNames) if varName in cellDataNames: print("varName = ", varName, "is already in the point data. Nothing to be done.") return p2c_interpolator = vtk.vtkPointDataToCellData() p2c_interpolator.SetInputData(uGrid) p2c_interpolator.Update() celldata = p2c_interpolator.GetOutput().GetCellData() #print("Interpolated cell data = ", celldata) uGridCellData = uGrid.GetCellData() for i in range(celldata.GetNumberOfArrays()): uGridCellData.AddArray(celldata.GetArray(i))
def read_data_and_differentiate(pod_mode_dir,num_modes,num_points,num_boundary_faces,num_dimensions,num_components,correct_for_cell_volumes, \ u,v,w,dudx,dudy,dudz,dvdx,dvdy,dvdz,dwdx,dwdy,dwdz,\ uF,vF,wF,dudxF,dudyF,dudzF,dvdxF,dvdyF,dvdzF,dwdxF,dwdyF,dwdzF,cell_volume,norm,calibrate_coefficients): u_read = np.array(np.zeros((num_points,3), dtype=np.float64)) dudx_read = np.array(np.zeros((num_points,3,3), dtype=np.float64)) uF_read = np.array(np.zeros((num_boundary_faces,3), dtype=np.float64)) dudxF_read = np.array(np.zeros((num_boundary_faces,3,3), dtype=np.float64)) # .................................................. # Read meanfield and spatially differentiate filename = pod_mode_dir + "/spatial_meanfield.vtk" print ' Reading file ', filename.strip() reader = vtk.vtkUnstructuredGridReader() reader.ReadAllScalarsOn() reader.ReadAllVectorsOn() reader.ReadAllTensorsOn() reader.SetFileName(filename) reader.Update() grid = vtk.vtkUnstructuredGrid() grid.DeepCopy(reader.GetOutput()) # get cell volumes if (correct_for_cell_volumes=="true"): cell_volume[:] = VN.vtk_to_numpy(grid.GetPointData().GetScalars("cell_volume")) else: cell_volume[:] = 1.0 # get mean velocity field within volume u_read = VN.vtk_to_numpy(grid.GetPointData().GetVectors("u")) u[:,0] = u_read[:,0].copy() v[:,0] = u_read[:,1].copy() w[:,0] = u_read[:,2].copy() grid.GetPointData().SetVectors(grid.GetPointData().GetVectors("u")) # get mean velocity derivative field within volume differentiator = vtk.vtkCellDerivatives() differentiator.SetTensorModeToComputeGradient() differentiator.SetInput(grid) differentiator.Update() cell_to_point_data = vtk.vtkCellDataToPointData() cell_to_point_data.SetInput(differentiator.GetOutput()) cell_to_point_data.Update() grid.GetPointData().SetTensors(cell_to_point_data.GetOutput().GetPointData().GetTensors()) dudx_read = VN.vtk_to_numpy(cell_to_point_data.GetOutput().GetPointData().GetTensors()) dudx[:,0] = dudx_read[:,0].copy() dvdx[:,0] = dudx_read[:,1].copy() dwdx[:,0] = dudx_read[:,2].copy() dudy[:,0] = dudx_read[:,3].copy() dvdy[:,0] = dudx_read[:,4].copy() dwdy[:,0] = dudx_read[:,5].copy() dudz[:,0] = dudx_read[:,6].copy() dvdz[:,0] = dudx_read[:,7].copy() dwdz[:,0] = dudx_read[:,8].copy() # extract boundary surface data if( (calibrate_coefficients=="none") or (calibrate_coefficients=="constant") ): geom_filter = vtk.vtkDataSetSurfaceFilter() geom_filter.SetInput(grid) geom_filter.Update() boundary_faces = vtk.vtkPolyData() boundary_faces = geom_filter.GetOutput() point_to_cell_data = vtk.vtkPointDataToCellData() point_to_cell_data.SetInput(geom_filter.GetOutput()) point_to_cell_data.Update() # get mean velocity field on boundary surface uF_read = VN.vtk_to_numpy(point_to_cell_data.GetOutput().GetCellData().GetVectors("u")) uF[:,0] = uF_read[:,0] vF[:,0] = uF_read[:,1] wF[:,0] = uF_read[:,2] # get mean derivative velocity field on boundary surface dudxF_read = VN.vtk_to_numpy(point_to_cell_data.GetOutput().GetCellData().GetTensors()) dudxF[:,0] = dudxF_read[:,0] dvdxF[:,0] = dudxF_read[:,1] dwdxF[:,0] = dudxF_read[:,2] dudyF[:,0] = dudxF_read[:,3] dvdyF[:,0] = dudxF_read[:,4] dwdyF[:,0] = dudxF_read[:,5] dudzF[:,0] = dudxF_read[:,6] dvdzF[:,0] = dudxF_read[:,7] dwdzF[:,0] = dudxF_read[:,8] # get boundary face normals norm_filter = vtk.vtkPolyDataNormals() norm_filter.ComputeCellNormalsOn() norm_filter.SetInput(boundary_faces) norm_filter.Update() area_filter = vtk.vtkMeshQuality() area_filter.SetQuadQualityMeasureToArea() area_filter.SetTriangleQualityMeasureToArea() area_filter.SetInput(boundary_faces) area_filter.Update() for j in range(0,num_boundary_faces): area = area_filter.GetOutput().GetCellData().GetArray("Quality").GetComponent(j,0) norm[j,:] = norm_filter.GetOutput().GetCellData().GetNormals().GetTuple(j) norm[j,:] = norm[j,:] * area # .................................................. # Read modes and spatially differentiate for j in range(0,num_modes): j_index = j+1 filename = pod_mode_dir + '/POD.spatial_mode_' + '%04d'%j_index + '.vtk' print ' Reading file ', filename.strip(), 'file number ', j_index, ' of ', num_modes reader.SetFileName(filename) reader.Update() # get mode velocity field within volume u_read = VN.vtk_to_numpy(reader.GetOutput().GetPointData().GetVectors("u")) u[:,j_index] = u_read[:,0] v[:,j_index] = u_read[:,1] w[:,j_index] = u_read[:,2] # get mode velocity derivative fields within volume grid.GetPointData().SetVectors(reader.GetOutput().GetPointData().GetVectors("u")) differentiator.SetInput(grid) differentiator.Update() cell_to_point_data.SetInput(differentiator.GetOutput()) cell_to_point_data.Update() grid.GetPointData().SetTensors(cell_to_point_data.GetOutput().GetPointData().GetTensors()) dudx_read = VN.vtk_to_numpy(cell_to_point_data.GetOutput().GetPointData().GetTensors()) dudx[:,j_index] = dudx_read[:,0] dvdx[:,j_index] = dudx_read[:,1] dwdx[:,j_index] = dudx_read[:,2] dudy[:,j_index] = dudx_read[:,3] dvdy[:,j_index] = dudx_read[:,4] dwdy[:,j_index] = dudx_read[:,5] dudz[:,j_index] = dudx_read[:,6] dvdz[:,j_index] = dudx_read[:,7] dwdz[:,j_index] = dudx_read[:,8] # extract boundary surface data if( (calibrate_coefficients=="none") or (calibrate_coefficients=="constant") ): geom_filter.SetInput(grid) geom_filter.Update() boundary_faces = geom_filter.GetOutput() point_to_cell_data.SetInput(geom_filter.GetOutput()) point_to_cell_data.Update() # get mode velocity field on boundary surface uF_read = VN.vtk_to_numpy(point_to_cell_data.GetOutput().GetCellData().GetVectors("u")) uF[:,j_index] = uF_read[:,0] vF[:,j_index] = uF_read[:,1] wF[:,j_index] = uF_read[:,2] # get mean derivative velocity field on boundary surface dudxF_read = VN.vtk_to_numpy(point_to_cell_data.GetOutput().GetCellData().GetTensors()) dudxF[:,j_index] = dudxF_read[:,0] dvdxF[:,j_index] = dudxF_read[:,1] dwdxF[:,j_index] = dudxF_read[:,2] dudyF[:,j_index] = dudxF_read[:,3] dvdyF[:,j_index] = dudxF_read[:,4] dwdyF[:,j_index] = dudxF_read[:,5] dudzF[:,j_index] = dudxF_read[:,6] dvdzF[:,j_index] = dudxF_read[:,7] dwdzF[:,j_index] = dudxF_read[:,8] # .................................................. # zero appropriate coefficients if (num_dimensions<3): dudz[:,:] = 0.0 dvdz[:,:] = 0.0 dwdz[:,:] = 0.0 if (num_dimensions<2): dudy[:,:] = 0.0 dvdy[:,:] = 0.0 dwdy[:,:] = 0.0 if (num_components<3): w[:,:] = 0.0 dwdx[:,:] = 0.0 dwdy[:,:] = 0.0 dwdz[:,:] = 0.0 if (num_components<2): v[:,:] = 0.0 dvdx[:,:] = 0.0 dvdy[:,:] = 0.0 dvdz[:,:] = 0.0 if( (calibrate_coefficients=="none") or (calibrate_coefficients=="constant") ): if (num_dimensions<3): dudzF[:,:] = 0.0 dvdzF[:,:] = 0.0 dwdzF[:,:] = 0.0 if (num_dimensions<2): dudyF[:,:] = 0.0 dvdyF[:,:] = 0.0 dwdyF[:,:] = 0.0 if (num_components<3): wF[:,j_index] = 0.0 dwdxF[:,:] = 0.0 dwdyF[:,:] = 0.0 dwdzF[:,:] = 0.0 if (num_components<2): vF[:,:] = 0.0 dvdxF[:,:] = 0.0 dvdyF[:,:] = 0.0 dvdzF[:,:] = 0.0
#!/usr/bin/env python import vtk poly = vtk.vtkPolyData() pts = vtk.vtkPoints() pts.InsertNextPoint( 0,0,0 ) pts.InsertNextPoint( 1,0,0 ) pts.InsertNextPoint( 1,1,0 ) pts.InsertNextPoint( 0,1,0 ) scalars = vtk.vtkFloatArray() scalars.SetName('foo') for i in range(0,4): scalars.InsertNextValue(float(i+1)) poly.GetPointData().SetScalars(scalars) cells = vtk.vtkCellArray() cells.InsertNextCell(0) cells.InsertNextCell(1) for i in range(0,4): cells.InsertCellPoint(i) poly.SetPoints(pts) poly.SetPolys(cells) print('PolyData has {} points and {} cells'.format(poly.GetNumberOfPoints(),poly.GetNumberOfCells())) celldata=vtk.vtkPointDataToCellData() celldata.SetInputData(poly) celldata.Update() # --- end of script ---
# Read some data with point data attributes. The data is from a # plastic blow molding process (e.g., to make plastic bottles) and # consists of two logical components: a mold and a parison. The # parison is the hot plastic that is being molded, and the mold is # clamped around the parison to form its shape. reader = vtk.vtkUnstructuredGridReader() reader.SetFileName(VTK_DATA_ROOT + "/Data/blow.vtk") reader.SetScalarsName("thickness9") reader.SetVectorsName("displacement9") # Convert the point data to cell data. The point data is passed # through the filter so it can be warped. The vtkThresholdFilter then # thresholds based on cell scalar values and extracts a portion of the # parison whose cell scalar values lie between 0.25 and 0.75. p2c = vtk.vtkPointDataToCellData() p2c.SetInputConnection(reader.GetOutputPort()) p2c.PassPointDataOn() warp = vtk.vtkWarpVector() warp.SetInput(p2c.GetUnstructuredGridOutput()) thresh = vtk.vtkThreshold() thresh.SetInputConnection(warp.GetOutputPort()) thresh.ThresholdBetween(0.25, 0.75) thresh.SetInputArrayToProcess(1, 0, 0, 0, "thickness9") #thresh.SetAttributeModeToUseCellData() # This is used to extract the mold from the parison. connect = vtk.vtkConnectivityFilter() connect.SetInputConnection(thresh.GetOutputPort()) connect.SetExtractionModeToSpecifiedRegions() connect.AddSpecifiedRegion(0)
def plot2D(self,data1,data2,tmpl,gm): #Preserve time and z axis for plotting these inof in rendertemplate t = data1.getTime() if data1.ndim>2: z = data1.getAxis(-3) else: z = None data1 = self.trimData2D(data1) # Ok get3 only the last 2 dims if gm.g_name!="Gfm": data2 = self.trimData2D(data2) ug,xm,xM,ym,yM,continents,wrap,geo,cellData = vcs2vtk.genGrid(data1,data2,gm,deep=False) #Now applies the actual data on each cell if isinstance(gm,boxfill.Gfb) and gm.boxfill_type=="log10": data1=numpy.ma.log10(data1) data = vcs2vtk.numpy_to_vtk_wrapper(data1.filled(0.).flat, deep=False) if cellData: ug.GetCellData().SetScalars(data) else: ug.GetPointData().SetScalars(data) try: cmap = vcs.elements["colormap"][cmap] except: cmap = vcs.elements["colormap"][self.canvas.getcolormapname()] color = getattr(gm,"missing",None) if color is not None: color = cmap.index[color] missingMapper = vcs2vtk.putMaskOnVTKGrid(data1,ug,color,cellData,deep=False) lut = vtk.vtkLookupTable() mn,mx=vcs.minmax(data1) #Ok now we have grid and data let's use the mapper mapper = vtk.vtkPolyDataMapper() legend = None if isinstance(gm,(meshfill.Gfm,boxfill.Gfb)): geoFilter = vtk.vtkDataSetSurfaceFilter() if cellData: p2c = vtk.vtkPointDataToCellData() p2c.SetInputData(ug) geoFilter.SetInputConnection(p2c.GetOutputPort()) else: geoFilter.SetInputData(ug) geoFilter.Update() if isinstance(gm,(isofill.Gfi,isoline.Gi,meshfill.Gfm)) or \ (isinstance(gm,boxfill.Gfb) and gm.boxfill_type=="custom"): #Now this filter seems to create the good polydata sFilter = vtk.vtkDataSetSurfaceFilter() if cellData: # Sets data to point instead of just cells c2p = vtk.vtkCellDataToPointData() c2p.SetInputData(ug) c2p.Update() if self.debug: vcs2vtk.dump2VTK(c2p) #For contouring duplicate points seem to confuse it if ug.IsA("vtkUntructuredGrid"): cln = vtk.vtkCleanUnstructuredGrid() cln.SetInputConnection(c2p.GetOutputPort()) if self.debug: vcs2vtk.dump2VTK(cln) sFilter.SetInputConnection(cln.GetOutputPort()) else: sFilter.SetInputConnection(c2p.GetOutputPort()) else: sFilter.SetInputData(ug) sFilter.Update() if self.debug: vcs2vtk.dump2VTK(sFilter) if isinstance(gm,isoline.Gi): cot = vtk.vtkContourFilter() if cellData: cot.SetInputData(sFilter.GetOutput()) else: cot.SetInputData(ug) levs = gm.levels if (isinstance(gm,isoline.Gi) and numpy.allclose( levs[0],[0.,1.e20])) or numpy.allclose(levs,1.e20): levs = vcs.mkscale(mn,mx) if len(levs)==1: # constant value ? levs = [levs[0],levs[0]+.00001] Ncolors = len(levs) if isinstance(gm,(isofill.Gfi,meshfill.Gfm)): levs2 = vcs.mkscale(mn,mx) if len(levs2)==1: # constant value ? levs2 = [levs2[0],levs2[0]+.00001] levs=[] for i in range(len(levs2)-1): levs.append([levs2[i],levs2[i+1]]) else: if isinstance(gm.levels[0],(list,tuple)): if isinstance(gm,isoline.Gi): levs = [x[0] for x in gm.levels] else: levs = gm.levels else: levs = [] levs2=gm.levels if numpy.allclose(levs2[0],1.e20): levs2[0]=-1.e20 for i in range(len(levs2)-1): levs.append([levs2[i],levs2[i+1]]) if isinstance(gm,isoline.Gi): levs = levs2 Nlevs=len(levs) Ncolors = Nlevs ## Figure out colors if isinstance(gm,boxfill.Gfb): cols = gm.fillareacolors if cols is None: cols = vcs.getcolors(levs2,split=0) elif isinstance(gm,(isofill.Gfi,meshfill.Gfm)): cols = gm.fillareacolors if cols==[1,]: cols = vcs.getcolors(levs2,split=0) if isinstance(cols,(int,float)): cols=[cols,] elif isinstance(gm,isoline.Gi): cols = gm.linecolors if isinstance(gm,isoline.Gi): cot.SetNumberOfContours(Nlevs) if levs[0]==1.e20: levs[0]=-1.e20 for i in range(Nlevs): cot.SetValue(i,levs[i]) cot.SetValue(Nlevs,levs[-1]) cot.Update() mapper.SetInputConnection(cot.GetOutputPort()) mappers = [] else: mappers = [] LEVS = [] INDX = [] COLS = [] indices = gm.fillareaindices if indices is None: indices=[1,] while len(indices)<len(cols): indices.append(indices[-1]) for i,l in enumerate(levs): if i==0: C = [cols[i],] if numpy.allclose(levs[0][0],-1.e20): ## ok it's an extension arrow L=[mn-1.,levs[0][1]] else: L = list(levs[i]) I = [indices[i],] else: if l[0] == L[-1] and I[-1]==indices[i]: # Ok same type lets keep going if numpy.allclose(l[1],1.e20): L.append(mx+1.) else: L.append(l[1]) C.append(cols[i]) else: # ok we need new contouring LEVS.append(L) COLS.append(C) INDX.append(I) C = [cols[i],] L = levs[i] I = [indices[i],] LEVS.append(L) COLS.append(C) INDX.append(I) for i,l in enumerate(LEVS): # Ok here we are trying to group together levels can be, a join will happen if: # next set of levels contnues where one left off AND pattern is identical if isinstance(gm,isofill.Gfi): mapper = vtk.vtkPolyDataMapper() lut = vtk.vtkLookupTable() cot = vtk.vtkBandedPolyDataContourFilter() cot.ClippingOn() cot.SetInputData(sFilter.GetOutput()) cot.SetNumberOfContours(len(l)) cot.SetClipTolerance(0.) for j,v in enumerate(l): cot.SetValue(j,v) #cot.SetScalarModeToIndex() cot.Update() mapper.SetInputConnection(cot.GetOutputPort()) lut.SetNumberOfTableValues(len(COLS[i])) for j,color in enumerate(COLS[i]): r,g,b = cmap.index[color] lut.SetTableValue(j,r/100.,g/100.,b/100.) #print l[j],vcs.colors.rgb2str(r*2.55,g*2.55,b*2.55),l[j+1] mapper.SetLookupTable(lut) mapper.SetScalarRange(0,len(l)-1) mapper.SetScalarModeToUseCellData() else: for j,color in enumerate(COLS[i]): mapper = vtk.vtkPolyDataMapper() lut = vtk.vtkLookupTable() th = vtk.vtkThreshold() th.ThresholdBetween(l[j],l[j+1]) th.SetInputConnection(geoFilter.GetOutputPort()) geoFilter2 = vtk.vtkDataSetSurfaceFilter() geoFilter2.SetInputConnection(th.GetOutputPort()) mapper.SetInputConnection(geoFilter2.GetOutputPort()) lut.SetNumberOfTableValues(1) r,g,b = cmap.index[color] lut.SetTableValue(0,r/100.,g/100.,b/100.) mapper.SetLookupTable(lut) mapper.SetScalarRange(l[j],l[j+1]) mappers.append([mapper,]) #png = vtk.vtkPNGReader() #png.SetFileName("/git/uvcdat/Packages/vcs/Share/uvcdat_texture.png") #T=vtk.vtkTexture() #T.SetInputConnection(png.GetOutputPort()) if isinstance(gm,isofill.Gfi): mappers.append([mapper,]) else: #Boxfill (non custom)/Meshfill if isinstance(gm,boxfill.Gfb): if numpy.allclose(gm.level_1,1.e20) or numpy.allclose(gm.level_2,1.e20): levs = vcs.mkscale(mn,mx) if len(levs)==1: # constant value ? levs = [levs[0],levs[0]+.00001] legend = vcs.mklabels(levs) dx = (levs[-1]-levs[0])/(gm.color_2-gm.color_1+1) levs = numpy.arange(levs[0],levs[-1]+dx,dx) else: if gm.boxfill_type=="log10": levslbls = vcs.mkscale(numpy.ma.log10(gm.level_1),numpy.ma.log10(gm.level_2)) levs = vcs.mkevenlevels(numpy.ma.log10(gm.level_1), numpy.ma.log10(gm.level_2), nlev=(gm.color_2-gm.color_1)+1) else: levslbls = vcs.mkscale(gm.level_1,gm.level_2) levs = vcs.mkevenlevels(gm.level_1,gm.level_2,nlev=(gm.color_2-gm.color_1)+1) if len(levs)>25: ## Too many colors/levels need to prettyfy this for legend legend = vcs.mklabels(levslbls) ## Make sure extremes are in legd2=vcs.mklabels([levs[0],levs[-1]]) legend.update(legd2) else: legend = vcs.mklabels(levs) if gm.boxfill_type=="log10": for k in legend.keys(): legend[float(numpy.ma.log10(legend[k]))] = legend[k] del(legend[k]) #dx = (levs[-1]-levs[0])/(gm.color_2-gm.color_1+1) #levs = numpy.arange(levs[0],levs[-1]+dx,dx) cols = range(gm.color_1,gm.color_2+1) else: if numpy.allclose(gm.levels,1.e20): levs = vcs.mkscale(mn,mx) else: levs = gm.levels if numpy.allclose(levs[0],1.e20): levs[0]=-1.e20 cols = gm.fillareacolors if cols==[1,]: cols = vcs.getcolors(levs) Nlevs = len(levs) Ncolors = Nlevs-1 #Prep mapper mappers=[] mapper = vtk.vtkPolyDataMapper() thr = vtk.vtkThreshold() thr.SetInputConnection(geoFilter.GetOutputPort()) if not gm.ext_1 in ["y",1,True] and not gm.ext_2 in ["y",1,True] : thr.ThresholdBetween(levs[0],levs[-1]) elif gm.ext_1 in ["y",1,True] and not gm.ext_2 in ["y",1,True] : thr.ThresholdByLower(levs[-1]) elif not gm.ext_1 in ["y",1,True] and gm.ext_2 in ["y",1,True] : thr.ThresholdByUpper(levs[0]) thr.Update() geoFilter2 = vtk.vtkDataSetSurfaceFilter() geoFilter2.SetInputConnection(thr.GetOutputPort()) if gm.ext_1 in ["y",1,True] and gm.ext_2 in ["y",1,True] : mapper.SetInputConnection(geoFilter.GetOutputPort()) else: mapper.SetInputConnection(geoFilter2.GetOutputPort()) if mappers == []: # ok didn't need to have special banded contours mappers=[mapper,] ## Colortable bit # make sure length match while len(cols)<Ncolors: cols.append(cols[-1]) lut.SetNumberOfTableValues(Ncolors) for i in range(Ncolors): r,g,b = cmap.index[cols[i]] lut.SetTableValue(i,r/100.,g/100.,b/100.) mapper.SetLookupTable(lut) if numpy.allclose(levs[0],-1.e20): lmn = mn-1. else: lmn= levs[0] if numpy.allclose(levs[-1],1.e20): lmx = mx+1. else: lmx= levs[-1] mapper.SetScalarRange(lmn,lmx) if missingMapper is not None: if isinstance(gm,meshfill.Gfm): mappers.append(missingMapper) else: mappers.insert(0,missingMapper) x1,x2,y1,y2 = vcs2vtk.getRange(gm,xm,xM,ym,yM) if tmpl.data.priority != 0: # And now we need actors to actually render this thing for mapper in mappers: act = vtk.vtkActor() if isinstance(mapper,list): act.SetMapper(mapper[0]) else: mapper.Update() act.SetMapper(mapper) if geo is None: act = vcs2vtk.doWrap(act,[x1,x2,y1,y2],wrap) if isinstance(mapper,list): #act.GetMapper().ScalarVisibilityOff() #act.SetTexture(mapper[1]) pass # create a new renderer for this mapper # (we need one for each mapper because of cmaera flips) ren = self.createRenderer() self.renWin.AddRenderer(ren) self.setLayer(ren,tmpl.data.priority) ren.AddActor(act) vcs2vtk.fitToViewport(act,ren,[tmpl.data.x1,tmpl.data.x2,tmpl.data.y1,tmpl.data.y2],wc=[x1,x2,y1,y2],geo=geo) if isinstance(gm,meshfill.Gfm): tmpl.plot(self.canvas,data1,gm, bg=self.bg, X=numpy.arange(xm,xM*1.1,(xM-xm)/10.), Y=numpy.arange(ym,yM*1.1,(yM-ym)/10.)) else: self.renderTemplate(tmpl,data1,gm,t,z) if isinstance(gm,(isofill.Gfi,meshfill.Gfm,boxfill.Gfb)): if getattr(gm,"legend",None) is not None: legend = gm.legend if gm.ext_1 in ["y",1,True] and not numpy.allclose(levs[0],-1.e20): if isinstance(levs,numpy.ndarray): levs=levs.tolist() if not (isinstance(levs[0],list) and numpy.less_equal(levs[0][0],-1.e20)): levs.insert(0,-1.e20) if gm.ext_2 in ["y",1,True] and not numpy.allclose(levs[-1],1.e20): if isinstance(levs,numpy.ndarray): levs=levs.tolist() if not (isinstance(levs[-1],list) and numpy.greater_equal(levs[-1][-1],1.e20)): levs.append(1.e20) self.renderColorBar(tmpl,levs,cols,legend,cmap) if self.canvas._continents is None: continents = False if continents: projection = vcs.elements["projection"][gm.projection] self.plotContinents(x1,x2,y1,y2,projection,wrap,tmpl)
def main(): colors = vtk.vtkNamedColors() # Create an image source1 = vtk.vtkImageCanvasSource2D() source1.SetScalarTypeToUnsignedChar() source1.SetNumberOfScalarComponents(3) source1.SetExtent(0, 100, 0, 100, 0, 0) source1.SetDrawColor(0, 0, 0, 1) source1.FillBox(0, 100, 0, 100) source1.SetDrawColor(255, 0, 0, 1) source1.FillBox(10, 20, 10, 20) source1.FillBox(40, 50, 20, 30) source1.Update() # Convert the image to a polydata imageDataGeometryFilter = vtk.vtkImageDataGeometryFilter() # imageDataGeometryFilter = vtk.vtkStructuredPointsGeometryFilter() imageDataGeometryFilter.SetInputConnection(source1.GetOutputPort()) imageDataGeometryFilter.Update() # p2c = vtk.vtkPointDataToCellData() # p2c.SetInputConnection(imageDataGeometryFilter.GetOutputPort()) # stripper = vtk.vtkStripper() # stripper.SetInputConnection(p2c.GetOutputPort()) # # stripper.PassCellDataAsFieldDataOn() p2c = vtk.vtkPointDataToCellData() p2c.PassPointDataOn() # p2c.SetInputConnection(source1.GetOutputPort()) # geom_filter = vtk.vtkGeometryFilter() # geom_filter.SetInputConnection(p2c.GetOutputPort()) # p2c.SetInputConnection(imageDataGeometryFilter.GetOutputPort()) # stripper = vtk.vtkStripper() # stripper.SetInputConnection(p2c.GetOutputPort()) # stripper.PassCellDataAsFieldDataOn() sphere = vtk.vtkSphereSource() # Create a mapper and actor mapper = vtk.vtkPolyDataMapper() # mapper = vtk.vtkPolyDataMapper2D() # mapper.SetScalarModeToUseCellData() mapper.SetInputConnection(imageDataGeometryFilter.GetOutputPort()) # mapper.SetInputConnection(geom_filter.GetOutputPort()) # mapper.SetInputConnection(p2c.GetOutputPort()) # mapper.SetInputConnection(sphere.GetOutputPort()) actor = vtk.vtkActor() # actor.GetProperty().BackfaceCullingOn() # actor.GetProperty().LightingOff() # actor.GetProperty().ShadingOn() # actor.GetProperty().SetAmbient(1.0) # actor.GetProperty().SetDiffuse(0.0) # actor.GetProperty().SetSpecular(0.0) # actor.GetProperty().SetInterpolationToGouraud() # actor.GetProperty().SetInterpolationToFlat() # interp = actor.GetProperty().GetInterpolation() # # # print('interp ',interp ) # actor.GetProperty().SetInterpolationToFlat() # actor.GetProperty().SetInterpolation(0) # interp = actor.GetProperty().GetInterpolation() # print('interp ', interp) actor.SetMapper(mapper) actor.GetProperty().SetInterpolationToFlat() actor.GetProperty().BackfaceCullingOn() actor.GetProperty().LightingOff() actor.GetProperty().ShadingOn() actor.GetProperty().SetAmbient(1.0) actor.GetProperty().SetDiffuse(0.0) actor.GetProperty().SetSpecular(0.0) actor.GetProperty().SetInterpolationToGouraud() actor.GetProperty().SetInterpolationToFlat() # Visualization renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderer.AddActor(actor) renderer.SetBackground( colors.GetColor3d("white")) # Background color white renderWindow.Render() renderWindowInteractor.Start()
rgrid = vtk.vtkRectilinearGrid() rgrid.SetDimensions(n) rgrid.SetXCoordinates(x) rgrid.SetYCoordinates(y) rgrid.SetZCoordinates(z) rgrid.GetPointData().ShallowCopy(igrid.GetPointData()) to_tets = vtk.vtkRectilinearGridToTetrahedra() to_tets.SetInputData(rgrid) to_tets.Update() tets = to_tets.GetOutput() tets.GetPointData().ShallowCopy(rgrid.GetPointData()) w = dsa.WrapDataObject(tets) p_to_c = vtk.vtkPointDataToCellData() p_to_c.SetInputConnection(to_tets.GetOutputPort()) p_to_c.Update() ctets = p_to_c.GetOutput() vtu = dsa.WrapDataObject(p_to_c.GetOutput()) samples = SampleTetrahedra(vtu, 'noise', nSamples) wrtr = vtk.vtkXMLUnstructuredGridWriter() wrtr.SetFileName('tet-samples.vtu') wrtr.SetInputData(samples.VTKObject) wrtr.Write()
def pointdatatocelldata(polydata): """Convert pointdata to celldata.""" converter = vtk.vtkPointDataToCellData() converter.SetInput(polydata) converter.Update() return converter.GetOutput()
def read_data_and_differentiate(pod_mode_dir,num_modes,num_points,num_boundary_faces,num_dimensions,num_components,correct_for_cell_volumes, \ u,v,w,dudx,dudy,dudz,dvdx,dvdy,dvdz,dwdx,dwdy,dwdz,\ uF,vF,wF,dudxF,dudyF,dudzF,dvdxF,dvdyF,dvdzF,dwdxF,dwdyF,dwdzF,cell_volume,norm,calibrate_coefficients): u_read = np.array(np.zeros((num_points, 3), dtype=np.float64)) dudx_read = np.array(np.zeros((num_points, 3, 3), dtype=np.float64)) uF_read = np.array(np.zeros((num_boundary_faces, 3), dtype=np.float64)) dudxF_read = np.array( np.zeros((num_boundary_faces, 3, 3), dtype=np.float64)) # .................................................. # Read meanfield and spatially differentiate filename = pod_mode_dir + "/spatial_meanfield.vtk" print ' Reading file ', filename.strip() reader = vtk.vtkUnstructuredGridReader() reader.ReadAllScalarsOn() reader.ReadAllVectorsOn() reader.ReadAllTensorsOn() reader.SetFileName(filename) reader.Update() grid = vtk.vtkUnstructuredGrid() grid.DeepCopy(reader.GetOutput()) # get cell volumes if (correct_for_cell_volumes == "true"): cell_volume[:] = VN.vtk_to_numpy( grid.GetPointData().GetScalars("cell_volume")) else: cell_volume[:] = 1.0 # get mean velocity field within volume u_read = VN.vtk_to_numpy(grid.GetPointData().GetVectors("u")) u[:, 0] = u_read[:, 0].copy() v[:, 0] = u_read[:, 1].copy() w[:, 0] = u_read[:, 2].copy() grid.GetPointData().SetVectors(grid.GetPointData().GetVectors("u")) # get mean velocity derivative field within volume differentiator = vtk.vtkCellDerivatives() differentiator.SetTensorModeToComputeGradient() differentiator.SetInput(grid) differentiator.Update() cell_to_point_data = vtk.vtkCellDataToPointData() cell_to_point_data.SetInput(differentiator.GetOutput()) cell_to_point_data.Update() grid.GetPointData().SetTensors( cell_to_point_data.GetOutput().GetPointData().GetTensors()) dudx_read = VN.vtk_to_numpy( cell_to_point_data.GetOutput().GetPointData().GetTensors()) dudx[:, 0] = dudx_read[:, 0].copy() dvdx[:, 0] = dudx_read[:, 1].copy() dwdx[:, 0] = dudx_read[:, 2].copy() dudy[:, 0] = dudx_read[:, 3].copy() dvdy[:, 0] = dudx_read[:, 4].copy() dwdy[:, 0] = dudx_read[:, 5].copy() dudz[:, 0] = dudx_read[:, 6].copy() dvdz[:, 0] = dudx_read[:, 7].copy() dwdz[:, 0] = dudx_read[:, 8].copy() # extract boundary surface data if ((calibrate_coefficients == "none") or (calibrate_coefficients == "constant")): geom_filter = vtk.vtkDataSetSurfaceFilter() geom_filter.SetInput(grid) geom_filter.Update() boundary_faces = vtk.vtkPolyData() boundary_faces = geom_filter.GetOutput() point_to_cell_data = vtk.vtkPointDataToCellData() point_to_cell_data.SetInput(geom_filter.GetOutput()) point_to_cell_data.Update() # get mean velocity field on boundary surface uF_read = VN.vtk_to_numpy( point_to_cell_data.GetOutput().GetCellData().GetVectors("u")) uF[:, 0] = uF_read[:, 0] vF[:, 0] = uF_read[:, 1] wF[:, 0] = uF_read[:, 2] # get mean derivative velocity field on boundary surface dudxF_read = VN.vtk_to_numpy( point_to_cell_data.GetOutput().GetCellData().GetTensors()) dudxF[:, 0] = dudxF_read[:, 0] dvdxF[:, 0] = dudxF_read[:, 1] dwdxF[:, 0] = dudxF_read[:, 2] dudyF[:, 0] = dudxF_read[:, 3] dvdyF[:, 0] = dudxF_read[:, 4] dwdyF[:, 0] = dudxF_read[:, 5] dudzF[:, 0] = dudxF_read[:, 6] dvdzF[:, 0] = dudxF_read[:, 7] dwdzF[:, 0] = dudxF_read[:, 8] # get boundary face normals norm_filter = vtk.vtkPolyDataNormals() norm_filter.ComputeCellNormalsOn() norm_filter.SetInput(boundary_faces) norm_filter.Update() area_filter = vtk.vtkMeshQuality() area_filter.SetQuadQualityMeasureToArea() area_filter.SetTriangleQualityMeasureToArea() area_filter.SetInput(boundary_faces) area_filter.Update() for j in range(0, num_boundary_faces): area = area_filter.GetOutput().GetCellData().GetArray( "Quality").GetComponent(j, 0) norm[j, :] = norm_filter.GetOutput().GetCellData().GetNormals( ).GetTuple(j) norm[j, :] = norm[j, :] * area # .................................................. # Read modes and spatially differentiate for j in range(0, num_modes): j_index = j + 1 filename = pod_mode_dir + '/POD.spatial_mode_' + '%04d' % j_index + '.vtk' print ' Reading file ', filename.strip( ), 'file number ', j_index, ' of ', num_modes reader.SetFileName(filename) reader.Update() # get mode velocity field within volume u_read = VN.vtk_to_numpy( reader.GetOutput().GetPointData().GetVectors("u")) u[:, j_index] = u_read[:, 0] v[:, j_index] = u_read[:, 1] w[:, j_index] = u_read[:, 2] # get mode velocity derivative fields within volume grid.GetPointData().SetVectors( reader.GetOutput().GetPointData().GetVectors("u")) differentiator.SetInput(grid) differentiator.Update() cell_to_point_data.SetInput(differentiator.GetOutput()) cell_to_point_data.Update() grid.GetPointData().SetTensors( cell_to_point_data.GetOutput().GetPointData().GetTensors()) dudx_read = VN.vtk_to_numpy( cell_to_point_data.GetOutput().GetPointData().GetTensors()) dudx[:, j_index] = dudx_read[:, 0] dvdx[:, j_index] = dudx_read[:, 1] dwdx[:, j_index] = dudx_read[:, 2] dudy[:, j_index] = dudx_read[:, 3] dvdy[:, j_index] = dudx_read[:, 4] dwdy[:, j_index] = dudx_read[:, 5] dudz[:, j_index] = dudx_read[:, 6] dvdz[:, j_index] = dudx_read[:, 7] dwdz[:, j_index] = dudx_read[:, 8] # extract boundary surface data if ((calibrate_coefficients == "none") or (calibrate_coefficients == "constant")): geom_filter.SetInput(grid) geom_filter.Update() boundary_faces = geom_filter.GetOutput() point_to_cell_data.SetInput(geom_filter.GetOutput()) point_to_cell_data.Update() # get mode velocity field on boundary surface uF_read = VN.vtk_to_numpy( point_to_cell_data.GetOutput().GetCellData().GetVectors("u")) uF[:, j_index] = uF_read[:, 0] vF[:, j_index] = uF_read[:, 1] wF[:, j_index] = uF_read[:, 2] # get mean derivative velocity field on boundary surface dudxF_read = VN.vtk_to_numpy( point_to_cell_data.GetOutput().GetCellData().GetTensors()) dudxF[:, j_index] = dudxF_read[:, 0] dvdxF[:, j_index] = dudxF_read[:, 1] dwdxF[:, j_index] = dudxF_read[:, 2] dudyF[:, j_index] = dudxF_read[:, 3] dvdyF[:, j_index] = dudxF_read[:, 4] dwdyF[:, j_index] = dudxF_read[:, 5] dudzF[:, j_index] = dudxF_read[:, 6] dvdzF[:, j_index] = dudxF_read[:, 7] dwdzF[:, j_index] = dudxF_read[:, 8] # .................................................. # zero appropriate coefficients if (num_dimensions < 3): dudz[:, :] = 0.0 dvdz[:, :] = 0.0 dwdz[:, :] = 0.0 if (num_dimensions < 2): dudy[:, :] = 0.0 dvdy[:, :] = 0.0 dwdy[:, :] = 0.0 if (num_components < 3): w[:, :] = 0.0 dwdx[:, :] = 0.0 dwdy[:, :] = 0.0 dwdz[:, :] = 0.0 if (num_components < 2): v[:, :] = 0.0 dvdx[:, :] = 0.0 dvdy[:, :] = 0.0 dvdz[:, :] = 0.0 if ((calibrate_coefficients == "none") or (calibrate_coefficients == "constant")): if (num_dimensions < 3): dudzF[:, :] = 0.0 dvdzF[:, :] = 0.0 dwdzF[:, :] = 0.0 if (num_dimensions < 2): dudyF[:, :] = 0.0 dvdyF[:, :] = 0.0 dwdyF[:, :] = 0.0 if (num_components < 3): wF[:, j_index] = 0.0 dwdxF[:, :] = 0.0 dwdyF[:, :] = 0.0 dwdzF[:, :] = 0.0 if (num_components < 2): vF[:, :] = 0.0 dvdxF[:, :] = 0.0 dvdyF[:, :] = 0.0 dvdzF[:, :] = 0.0
#!/usr/bin/env python import vtk poly = vtk.vtkPolyData() pts = vtk.vtkPoints() pts.InsertNextPoint(0, 0, 0) pts.InsertNextPoint(1, 0, 0) pts.InsertNextPoint(1, 1, 0) pts.InsertNextPoint(0, 1, 0) scalars = vtk.vtkFloatArray() scalars.SetName('foo') for i in range(0, 4): scalars.InsertNextValue(float(i + 1)) poly.GetPointData().SetScalars(scalars) cells = vtk.vtkCellArray() cells.InsertNextCell(0) cells.InsertNextCell(1) for i in range(0, 4): cells.InsertCellPoint(i) poly.SetPoints(pts) poly.SetPolys(cells) print('PolyData has {} points and {} cells'.format(poly.GetNumberOfPoints(), poly.GetNumberOfCells())) celldata = vtk.vtkPointDataToCellData() celldata.SetInputData(poly) celldata.Update() # --- end of script ---
for j in range(3): node_id = int(surface_ebc_data[i][1 + j]) - 1 pressure_value = pressure_data[node_id] vtk_id = cell_point_id_list.GetId(j) pressure_array.SetTuple1(vtk_id, pressure_value) # add pressure point array surface_polydata.GetPointData().AddArray(pressure_array) pressure_array.SetName("pressure") surface_polydata.Update() # convert to cell data surface_polydata_cell = vtk.vtkPointDataToCellData() if vtk.VTK_MAJOR_VERSION == 6: surface_polydata_cell.SetInputData(surface_polydata) else: surface_polydata_cell.SetInput(surface_polydata) surface_polydata_cell.PassPointDataOn() surface_polydata_cell.Update() # create polydata normal object and set cell normals on surface_polydata_cell_normals = vtk.vtkPolyDataNormals() # surface_polydata_cell_normals.SetFlipNormals(1) surface_polydata_cell_normals.ComputeCellNormalsOn() surface_polydata_cell_normals.SetInputConnection( surface_polydata_cell.GetOutputPort()) surface_polydata_cell_normals.Update()
def pointdatatocelldata(polydata): """Convert pointdata to celldata.""" converter = vtk.vtkPointDataToCellData() converter.SetInput(polydata) converter.Update() return converter.GetOutput()
def main(args): parser = argparse.ArgumentParser( description= 'Render a DSM from a DTM and polygons representing buildings.') parser.add_argument("--input_vtp_path", type=str, help="Input buildings polygonal file (.vtp)") parser.add_argument( "--input_obj_paths", nargs="*", help="List of input building (.obj) file paths. " "Building object files start " "with a digit, road object files start with \"Road\". " "All obj files start with comments specifying the offsets " "that are added the coordinats. There are three comment lines, " "one for each coordinate: \"#c offset: value\" where c is x, y and z.") parser.add_argument("input_dtm", help="Input digital terain model (DTM)") parser.add_argument("output_dsm", help="Output digital surface model (DSM)") parser.add_argument("--render_png", action="store_true", help="Do not save the DSM, render into a PNG instead.") parser.add_argument( "--render_cls", action="store_true", help="Render a buildings mask: render buildings label (6), " "background (2) and no DTM.") parser.add_argument("--buildings_only", action="store_true", help="Do not use the DTM, use only the buildings.") parser.add_argument("--debug", action="store_true", help="Save intermediate results") args = parser.parse_args(args) # open the DTM dtm = gdal.Open(args.input_dtm, gdal.GA_ReadOnly) if not dtm: raise RuntimeError("Error: Failed to open DTM {}".format( args.input_dtm)) dtmDriver = dtm.GetDriver() dtmDriverMetadata = dtmDriver.GetMetadata() dsm = None dtmBounds = [0.0, 0.0, 0.0, 0.0] if dtmDriverMetadata.get(gdal.DCAP_CREATE) == "YES": print("Create destination image " "size:({}, {}) ...".format(dtm.RasterXSize, dtm.RasterYSize)) # georeference information projection = dtm.GetProjection() transform = dtm.GetGeoTransform() gcpProjection = dtm.GetGCPProjection() gcps = dtm.GetGCPs() options = ["COMPRESS=DEFLATE"] # ensure that space will be reserved for geographic corner coordinates # (in DMS) to be set later if (dtmDriver.ShortName == "NITF" and not projection): options.append("ICORDS=G") if args.render_cls: eType = gdal.GDT_Byte else: eType = gdal.GDT_Float32 dsm = dtmDriver.Create(args.output_dsm, xsize=dtm.RasterXSize, ysize=dtm.RasterYSize, bands=1, eType=eType, options=options) if (projection): # georeference through affine geotransform dsm.SetProjection(projection) dsm.SetGeoTransform(transform) else: # georeference through GCPs dsm.SetGCPs(gcps, gcpProjection) gdal.GCPsToGeoTransform(gcps, transform) corners = [[0, 0], [0, dtm.RasterYSize], [dtm.RasterXSize, dtm.RasterYSize], [dtm.RasterXSize, 0]] geoCorners = numpy.zeros((4, 2)) for i, corner in enumerate(corners): geoCorners[i] = [ transform[0] + corner[0] * transform[1] + corner[1] * transform[2], transform[3] + corner[0] * transform[4] + corner[1] * transform[5] ] dtmBounds[0] = numpy.min(geoCorners[:, 0]) dtmBounds[1] = numpy.max(geoCorners[:, 0]) dtmBounds[2] = numpy.min(geoCorners[:, 1]) dtmBounds[3] = numpy.max(geoCorners[:, 1]) if args.render_cls: # label for no building dtmRaster = numpy.full([dtm.RasterYSize, dtm.RasterXSize], 2) nodata = 0 else: print("Reading the DTM {} size: ({}, {})\n" "\tbounds: ({}, {}), ({}, {})...".format( args.input_dtm, dtm.RasterXSize, dtm.RasterYSize, dtmBounds[0], dtmBounds[1], dtmBounds[2], dtmBounds[3])) dtmRaster = dtm.GetRasterBand(1).ReadAsArray() nodata = dtm.GetRasterBand(1).GetNoDataValue() print("Nodata: {}".format(nodata)) else: raise RuntimeError( "Driver {} does not supports Create().".format(dtmDriver)) # read the buildings polydata, set Z as a scalar and project to XY plane print("Reading the buildings ...") # labels for buildings and elevated roads labels = [6, 17] if (args.input_vtp_path and os.path.isfile(args.input_vtp_path)): polyReader = vtk.vtkXMLPolyDataReader() polyReader.SetFileName(args.input_vtp_path) polyReader.Update() polyVtkList = [polyReader.GetOutput()] elif (args.input_obj_paths): # buildings start with numbers # optional elevated roads start with Road*.obj bldg_re = re.compile(".*/?[0-9][^/]*\\.obj") bldg_files = [f for f in args.input_obj_paths if bldg_re.match(f)] print(bldg_files) road_re = re.compile(".*/?Road[^/]*\\.obj") road_files = [f for f in args.input_obj_paths if road_re.match(f)] files = [bldg_files, road_files] files = [x for x in files if x] print(road_files) if len(files) >= 2: print("Found {} buildings and {} roads".format( len(files[0]), len(files[1]))) elif len(files) == 1: print("Found {} buildings".format(len(files[0]))) else: raise RuntimeError("No OBJ files found in {}".format( args.input_obj_paths)) polyVtkList = [] for category in range(len(files)): append = vtk.vtkAppendPolyData() for i, fileName in enumerate(files[category]): offset = [0.0, 0.0, 0.0] gdal_utils.read_offset(fileName, offset) print("Offset: {}".format(offset)) transform = vtk.vtkTransform() transform.Translate(offset[0], offset[1], offset[2]) objReader = vtk.vtkOBJReader() objReader.SetFileName(fileName) transformFilter = vtk.vtkTransformFilter() transformFilter.SetTransform(transform) transformFilter.SetInputConnection(objReader.GetOutputPort()) append.AddInputConnection(transformFilter.GetOutputPort()) append.Update() polyVtkList.append(append.GetOutput()) else: raise RuntimeError( "Must provide either --input_vtp_path, or --input_obj_paths") arrayName = "Elevation" append = vtk.vtkAppendPolyData() for category in range(len(polyVtkList)): poly = dsa.WrapDataObject(polyVtkList[category]) polyElevation = poly.Points[:, 2] if args.render_cls: # label for buildings polyElevation[:] = labels[category] polyElevationVtk = numpy_support.numpy_to_vtk(polyElevation) polyElevationVtk.SetName(arrayName) poly.PointData.SetScalars(polyElevationVtk) append.AddInputDataObject(polyVtkList[category]) append.Update() # Create the RenderWindow, Renderer ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.OffScreenRenderingOn() renWin.SetSize(dtm.RasterXSize, dtm.RasterYSize) renWin.SetMultiSamples(0) renWin.AddRenderer(ren) # show the buildings trisBuildingsFilter = vtk.vtkTriangleFilter() trisBuildingsFilter.SetInputDataObject(append.GetOutput()) trisBuildingsFilter.Update() p2cBuildings = vtk.vtkPointDataToCellData() p2cBuildings.SetInputConnection(trisBuildingsFilter.GetOutputPort()) p2cBuildings.PassPointDataOn() p2cBuildings.Update() buildingsScalarRange = p2cBuildings.GetOutput().GetCellData().GetScalars( ).GetRange() if (args.debug): polyWriter = vtk.vtkXMLPolyDataWriter() polyWriter.SetFileName("p2c.vtp") polyWriter.SetInputConnection(p2cBuildings.GetOutputPort()) polyWriter.Write() buildingsMapper = vtk.vtkPolyDataMapper() buildingsMapper.SetInputDataObject(p2cBuildings.GetOutput()) buildingsActor = vtk.vtkActor() buildingsActor.SetMapper(buildingsMapper) ren.AddActor(buildingsActor) if (args.render_png): print("Render into a PNG ...") # Show the terrain. print("Converting the DTM into a surface ...") # read the DTM as a VTK object dtmReader = vtk.vtkGDALRasterReader() dtmReader.SetFileName(args.input_dtm) dtmReader.Update() dtmVtk = dtmReader.GetOutput() # Convert the terrain into a polydata. surface = vtk.vtkImageDataGeometryFilter() surface.SetInputDataObject(dtmVtk) # Make sure the polygons are planar, so need to use triangles. tris = vtk.vtkTriangleFilter() tris.SetInputConnection(surface.GetOutputPort()) # Warp the surface by scalar values warp = vtk.vtkWarpScalar() warp.SetInputConnection(tris.GetOutputPort()) warp.SetScaleFactor(1) warp.UseNormalOn() warp.SetNormal(0, 0, 1) warp.Update() dsmScalarRange = warp.GetOutput().GetPointData().GetScalars().GetRange( ) dtmMapper = vtk.vtkPolyDataMapper() dtmMapper.SetInputConnection(warp.GetOutputPort()) dtmActor = vtk.vtkActor() dtmActor.SetMapper(dtmMapper) ren.AddActor(dtmActor) ren.ResetCamera() camera = ren.GetActiveCamera() camera.ParallelProjectionOn() camera.SetParallelScale((dtmBounds[3] - dtmBounds[2]) / 2) if (args.buildings_only): scalarRange = buildingsScalarRange else: scalarRange = [ min(dsmScalarRange[0], buildingsScalarRange[0]), max(dsmScalarRange[1], buildingsScalarRange[1]) ] lut = vtk.vtkColorTransferFunction() lut.AddRGBPoint(scalarRange[0], 0.23, 0.30, 0.75) lut.AddRGBPoint((scalarRange[0] + scalarRange[1]) / 2, 0.86, 0.86, 0.86) lut.AddRGBPoint(scalarRange[1], 0.70, 0.02, 0.15) dtmMapper.SetLookupTable(lut) dtmMapper.SetColorModeToMapScalars() buildingsMapper.SetLookupTable(lut) if (args.buildings_only): ren.RemoveActor(dtmActor) renWin.Render() windowToImageFilter = vtk.vtkWindowToImageFilter() windowToImageFilter.SetInput(renWin) windowToImageFilter.SetInputBufferTypeToRGBA() windowToImageFilter.ReadFrontBufferOff() windowToImageFilter.Update() writerPng = vtk.vtkPNGWriter() writerPng.SetFileName(args.output_dsm + ".png") writerPng.SetInputConnection(windowToImageFilter.GetOutputPort()) writerPng.Write() else: print("Render into a floating point buffer ...") ren.ResetCamera() camera = ren.GetActiveCamera() camera.ParallelProjectionOn() camera.SetParallelScale((dtmBounds[3] - dtmBounds[2]) / 2) distance = camera.GetDistance() focalPoint = [(dtmBounds[0] + dtmBounds[1]) * 0.5, (dtmBounds[3] + dtmBounds[2]) * 0.5, (buildingsScalarRange[0] + buildingsScalarRange[1]) * 0.5 ] position = [focalPoint[0], focalPoint[1], focalPoint[2] + distance] camera.SetFocalPoint(focalPoint) camera.SetPosition(position) valuePass = vtk.vtkValuePass() valuePass.SetRenderingMode(vtk.vtkValuePass.FLOATING_POINT) # use the default scalar for point data valuePass.SetInputComponentToProcess(0) valuePass.SetInputArrayToProcess( vtk.VTK_SCALAR_MODE_USE_POINT_FIELD_DATA, arrayName) passes = vtk.vtkRenderPassCollection() passes.AddItem(valuePass) sequence = vtk.vtkSequencePass() sequence.SetPasses(passes) cameraPass = vtk.vtkCameraPass() cameraPass.SetDelegatePass(sequence) ren.SetPass(cameraPass) # We have to render the points first, otherwise we get a segfault. renWin.Render() valuePass.SetInputArrayToProcess( vtk.VTK_SCALAR_MODE_USE_CELL_FIELD_DATA, arrayName) renWin.Render() elevationFlatVtk = valuePass.GetFloatImageDataArray(ren) valuePass.ReleaseGraphicsResources(renWin) print("Writing the DSM ...") elevationFlat = numpy_support.vtk_to_numpy(elevationFlatVtk) # VTK X,Y corresponds to numpy cols,rows. VTK stores arrays # in Fortran order. elevationTranspose = numpy.reshape(elevationFlat, [dtm.RasterXSize, dtm.RasterYSize], "F") # changes from cols, rows to rows,cols. elevation = numpy.transpose(elevationTranspose) # numpy rows increase as you go down, Y for VTK images increases as you go up elevation = numpy.flip(elevation, 0) if args.buildings_only: dsmElevation = elevation else: # elevation has nans in places other than buildings dsmElevation = numpy.fmax(dtmRaster, elevation) dsm.GetRasterBand(1).WriteArray(dsmElevation) if nodata: dsm.GetRasterBand(1).SetNoDataValue(nodata)
def plot2D(self,data1,data2,tmpl,gm,ren): self.setLayer(ren,tmpl.data.priority) ug,xm,xM,ym,yM,continents,wrap = vcs2vtk.genUnstructuredGrid(data1,data2,gm) #Now applies the actual data on each cell if isinstance(gm,boxfill.Gfb) and gm.boxfill_type=="log10": data1=numpy.ma.log10(data1) data = VN.numpy_to_vtk(data1.filled(0.).flat,deep=True) if ug.IsA("vtkUnstructuredGrid"): ug.GetCellData().SetScalars(data) else: ug.GetPointData().SetScalars(data) try: cmap = vcs.elements["colormap"][cmap] except: cmap = vcs.elements["colormap"][self.canvas.getcolormapname()] color = getattr(gm,"missing",None) if color is not None: color = cmap.index[color] missingMapper = vcs2vtk.putMaskOnVTKGrid(data1,ug,color) lut = vtk.vtkLookupTable() mn,mx=vcs.minmax(data1) #Ok now we have grid and data let's use the mapper mapper = vtk.vtkPolyDataMapper() legend = None if isinstance(gm,boxfill.Gfb): geoFilter = vtk.vtkGeometryFilter() if ug.IsA("vtkUnstructuredGrid"): geoFilter.SetInputData(ug) else: p2c = vtk.vtkPointDataToCellData() p2c.SetInputData(ug) geoFilter = vtk.vtkDataSetSurfaceFilter() geoFilter.SetInputConnection(p2c.GetOutputPort()) geoFilter.Update() if isinstance(gm,(isofill.Gfi,isoline.Gi,meshfill.Gfm)) or \ (isinstance(gm,boxfill.Gfb) and gm.boxfill_type=="custom"): if ug.IsA("vtkUnstructuredGrid"): # Sets data to point instead of just cells c2p = vtk.vtkCellDataToPointData() c2p.SetInputData(ug) c2p.Update() if self.debug: vcs2vtk.dump2VTK(c2p) #For contouring duplicate points seem to confuse it cln = vtk.vtkCleanUnstructuredGrid() cln.SetInputConnection(c2p.GetOutputPort()) if self.debug: vcs2vtk.dump2VTK(cln) #Now this filter seems to create the good polydata sFilter = vtk.vtkDataSetSurfaceFilter() if ug.IsA("vtkUnstructuredGrid"): sFilter.SetInputConnection(cln.GetOutputPort()) else: sFilter.SetInputData(ug) sFilter.Update() if self.debug: vcs2vtk.dump2VTK(sFilter) if isinstance(gm,isoline.Gi): cot = vtk.vtkContourFilter() if ug.IsA("vtkUnstructuredGrid"): cot.SetInputData(sFilter.GetOutput()) else: cot.SetInputData(ug) levs = gm.levels if (isinstance(gm,isoline.Gi) and numpy.allclose( levs[0],[0.,1.e20])) or numpy.allclose(levs,1.e20): levs = vcs.mkscale(mn,mx) Ncolors = len(levs) if isinstance(gm,(isofill.Gfi,meshfill.Gfm)): levs2 = vcs.mkscale(mn,mx) levs=[] for i in range(len(levs2)-1): levs.append([levs2[i],levs2[i+1]]) else: if isinstance(gm.levels[0],(list,tuple)): if isinstance(gm,isoline.Gi): levs = [x[0] for x in gm.levels] else: levs = gm.levels else: levs = [] levs2=gm.levels if numpy.allclose(levs2[0],1.e20): levs2[0]=-1.e20 for i in range(len(levs2)-1): levs.append([levs2[i],levs2[i+1]]) if isinstance(gm,isoline.Gi): levs = levs2 Nlevs=len(levs) Ncolors = Nlevs ## Figure out colors if isinstance(gm,boxfill.Gfb): cols = gm.fillareacolors if cols is None: cols = vcs.getcolors(levs2,split=0) elif isinstance(gm,isofill.Gfi): cols = gm.fillareacolors if cols==[1,]: cols = vcs.getcolors(levs2,split=0) elif isinstance(gm,isoline.Gi): cols = gm.linecolors if isinstance(gm,isoline.Gi): cot.SetNumberOfContours(Nlevs) if levs[0]==1.e20: levs[0]=-1.e20 for i in range(Nlevs): cot.SetValue(i,levs[i]) cot.SetValue(Nlevs,levs[-1]) cot.Update() mapper.SetInputConnection(cot.GetOutputPort()) mappers = [] else: mappers = [] LEVS = [] INDX = [] COLS = [] indices = gm.fillareaindices if indices is None: indices=[1,] while len(indices)<len(cols): indices.append(indices[-1]) for i,l in enumerate(levs): if i==0: C = [cols[i],] if numpy.allclose(levs[0][0],-1.e20): ## ok it's an extension arrow L=[mn-1.,levs[0][1]] else: L = levs[i] I = [indices[i],] else: if l[0] == L[-1] and I[-1]==indices[i]: # Ok same type lets keep going if numpy.allclose(l[1],1.e20): L.append(mx+1.) else: L.append(l[1]) C.append(cols[i]) else: # ok we need new contouring LEVS.append(L) COLS.append(C) INDX.append(I) C = [cols[i],] L = levs[i] I = [indices[i],] LEVS.append(L) COLS.append(C) INDX.append(I) for i,l in enumerate(LEVS): # Ok here we are trying to group together levels can be, a join will happen if: # next set of levels contnues where one left off AND pattern is identical if isinstance(gm,isofill.Gfi): mapper = vtk.vtkPolyDataMapper() lut = vtk.vtkLookupTable() cot = vtk.vtkBandedPolyDataContourFilter() cot.ClippingOn() cot.SetInputData(sFilter.GetOutput()) cot.SetNumberOfContours(len(l)) for j,v in enumerate(l): cot.SetValue(j,v) #cot.SetScalarModeToIndex() cot.Update() mapper.SetInputConnection(cot.GetOutputPort()) lut.SetNumberOfTableValues(len(COLS[i])) for j,color in enumerate(COLS[i]): r,g,b = cmap.index[color] lut.SetTableValue(j,r/100.,g/100.,b/100.) #print l[j],vcs.colors.rgb2str(r*2.55,g*2.55,b*2.55),l[j+1] mapper.SetLookupTable(lut) mapper.SetScalarRange(0,len(l)-1) mapper.SetScalarModeToUseCellData() else: for j,color in enumerate(COLS[i]): mapper = vtk.vtkPolyDataMapper() lut = vtk.vtkLookupTable() th = vtk.vtkThreshold() th.ThresholdBetween(l[j],l[j+1]) th.SetInputConnection(geoFilter.GetOutputPort()) geoFilter2 = vtk.vtkDataSetSurfaceFilter() geoFilter2.SetInputConnection(th.GetOutputPort()) mapper.SetInputConnection(geoFilter2.GetOutputPort()) lut.SetNumberOfTableValues(1) r,g,b = cmap.index[color] lut.SetTableValue(0,r/100.,g/100.,b/100.) mapper.SetLookupTable(lut) mapper.SetScalarRange(l[j],l[j+1]) mappers.append([mapper,]) #png = vtk.vtkPNGReader() #png.SetFileName("/git/uvcdat/Packages/vcs/Share/uvcdat_texture.png") #T=vtk.vtkTexture() #T.SetInputConnection(png.GetOutputPort()) if isinstance(gm,isofill.Gfi): mappers.append([mapper,]) else: #Boxfill/Meshfill mappers=[] mapper.SetInputData(geoFilter.GetOutput()) if isinstance(gm,boxfill.Gfb): if numpy.allclose(gm.level_1,1.e20) or numpy.allclose(gm.level_2,1.e20): levs = vcs.mkscale(mn,mx) legend = vcs.mklabels(levs) dx = (levs[-1]-levs[0])/(gm.color_2-gm.color_1+1) levs = numpy.arange(levs[0],levs[-1]+dx,dx) else: if gm.boxfill_type=="log10": levs = vcs.mkscale(numpy.ma.log10(gm.level_1),numpy.ma.log10(gm.level_2)) else: levs = vcs.mkscale(gm.level_1,gm.level_2) legend = vcs.mklabels(levs) if gm.boxfill_type=="log10": for k in legend.keys(): legend[float(numpy.ma.log10(legend[k]))] = legend[k] del(legend[k]) levs = numpy.arange(levs[0],levs[1],(levs[1]-levs[0])/(gm.color_2-gm.color_1+1)) cols = range(gm.color_1,gm.color_2+1) else: if numpy.allclose(gm.levels,1.e20): levs = vcs.mkscale(mn,mx) else: levs = gm.levels if numpy.allclose(levs[0],1.e20): levs[0]=-1.e20 cols = gm.fillareacolors if cols==[1,]: cols = vcs.getcolors(levs) Nlevs = len(levs) Ncolors = Nlevs-1 if mappers == []: # ok didn't need to have special banded contours mappers=[mapper,] ## Colortable bit # make sure length match while len(cols)<Ncolors: cols.append(cols[-1]) lut.SetNumberOfTableValues(Ncolors) for i in range(Ncolors): r,g,b = cmap.index[cols[i]] lut.SetTableValue(i,r/100.,g/100.,b/100.) mapper.SetLookupTable(lut) if numpy.allclose(levs[0],-1.e20): lmn = mn-1. else: lmn= levs[0] if numpy.allclose(levs[-1],1.e20): lmx = mx+1. else: lmx= levs[-1] mapper.SetScalarRange(lmn,lmx) if missingMapper is not None: mappers.insert(0,missingMapper) x1,x2,y1,y2 = vcs2vtk.getRange(gm,xm,xM,ym,yM) if tmpl.data.priority != 0: # And now we need actors to actually render this thing for mapper in mappers: act = vtk.vtkActor() if isinstance(mapper,list): act.SetMapper(mapper[0]) else: mapper.Update() act.SetMapper(mapper) #act = vcs2vtk.doWrap(act,[x1,x2,y1,y2],wrap) if isinstance(mapper,list): #act.GetMapper().ScalarVisibilityOff() #act.SetTexture(mapper[1]) pass ren.AddActor(act) vcs2vtk.fitToViewport(act,ren,[tmpl.data.x1,tmpl.data.x2,tmpl.data.y1,tmpl.data.y2],[x1,x2,y1,y2]) self.renderTemplate(ren,tmpl,data1,gm) if isinstance(gm,(isofill.Gfi,meshfill.Gfm,boxfill.Gfb)): if getattr(gm,"legend",None) is not None: legend = gm.legend self.renderColorBar(ren,tmpl,levs,cols,legend,cmap) if self.canvas._continents is None: continents = False if continents: projection = vcs.elements["projection"][gm.projection] self.plotContinents(x1,x2,y1,y2,projection,wrap,ren,tmpl)
def readFile(self,filename,verbose=False,ts = 0): #ts required only for ensight files self.filename=os.path.abspath(filename) if os.path.splitext(self.filename)[1] == '.vtk': self.readVTK() elif os.path.splitext(self.filename)[1] == '.CASE': self.readEnSight(ts) self.reader.Update() self.output = self.reader.GetOutput() self.outputPort = self.reader.GetOutputPort() #a workaround: in binary vtk files (OpenFOAM, Truchas), the arrays are given, but with no information #if they are scalars or vectors, therefore vectors are not rotated from 2D to 3D #it's probably a bug in current implementation of VTK self.pointData = self.output.GetPointData() self.cellData = self.output.GetCellData() if not self.pointData.GetVectors(): self.pointData.SetVectors(self.pointData.GetArray(self.velArray[self.solver])) self.cellData.SetVectors(self.cellData.GetArray(self.velArray[self.solver])) #transformations: self.transform = vtk.vtkTransform() #transform is a matrix, and identity at the beginning, which is immediately multiplied by using Translate, Rotate etc. self.transform.PostMultiply() #required to apply the transformation in the given order if self.sim=='2D': self.transform.RotateX(90) if self.solver in ['Gerris','Thetis']: self.transform.Scale(1.,0.,1.) if 'rotated' in self.filename: self.transform.Translate(0,0,-4.22) self.transform.RotateY(-10) #it is in XZ plane if self.solver == 'Gerris' and ('propagation' in self.filename or 'runup' in self.filename or 'stillwater' in self.filename): self.transform.Translate(0,0,-1)#the water level is originally at z=1 self.transformFilter=vtk.vtkTransformFilter() self.transformFilter.SetInputConnection(self.outputPort) self.transformFilter.SetTransform(self.transform) self.transformFilter.Update() self.output = self.transformFilter.GetOutput() self.outputPort = self.transformFilter.GetOutputPort() if self.output.GetCellData().GetNumberOfArrays() == 0: self.converter = vtk.vtkPointDataToCellData() self.converter.SetInputConnection(self.outputPort) self.converter.PassPointDataOn() self.converter.Update() self.output=self.converter.GetOutput() #later on output will always have at least cell data self.outputPort = self.converter.GetOutputPort() elif self.output.GetPointData().GetNumberOfArrays() == 0: self.converter = vtk.vtkCellDataToPointData() self.converter.SetInputConnection(self.outputPort) self.converter.PassCellDataOn() self.converter.Update() self.output=self.converter.GetOutput() #later on output will always have at least point data self.outputPort = self.converter.GetOutputPort() #self.output.Update() self.pointData = self.output.GetPointData() self.cellData = self.output.GetCellData() self.getArrayNames(verbose) self.Ncells=self.output.GetNumberOfCells() #self.header = self.reader.GetHeader() self.time=-1
def plot2D(self,data1,data2,tmpl,gm): ug,xm,xM,ym,yM,continents,wrap,geo,cellData = vcs2vtk.genGrid(data1,data2,gm) #Now applies the actual data on each cell if isinstance(gm,boxfill.Gfb) and gm.boxfill_type=="log10": data1=numpy.ma.log10(data1) data = VN.numpy_to_vtk(data1.filled(0.).flat,deep=True) if cellData: ug.GetCellData().SetScalars(data) else: ug.GetPointData().SetScalars(data) try: cmap = vcs.elements["colormap"][cmap] except: cmap = vcs.elements["colormap"][self.canvas.getcolormapname()] color = getattr(gm,"missing",None) if color is not None: color = cmap.index[color] missingMapper = vcs2vtk.putMaskOnVTKGrid(data1,ug,color,cellData) lut = vtk.vtkLookupTable() mn,mx=vcs.minmax(data1) #Ok now we have grid and data let's use the mapper mapper = vtk.vtkPolyDataMapper() legend = None if isinstance(gm,(meshfill.Gfm,boxfill.Gfb)): geoFilter = vtk.vtkDataSetSurfaceFilter() if cellData: p2c = vtk.vtkPointDataToCellData() p2c.SetInputData(ug) geoFilter.SetInputConnection(p2c.GetOutputPort()) else: geoFilter.SetInputData(ug) geoFilter.Update() if isinstance(gm,(isofill.Gfi,isoline.Gi,meshfill.Gfm)) or \ (isinstance(gm,boxfill.Gfb) and gm.boxfill_type=="custom"): #Now this filter seems to create the good polydata sFilter = vtk.vtkDataSetSurfaceFilter() if cellData: # Sets data to point instead of just cells c2p = vtk.vtkCellDataToPointData() c2p.SetInputData(ug) c2p.Update() if self.debug: vcs2vtk.dump2VTK(c2p) #For contouring duplicate points seem to confuse it if ug.IsA("vtkUntructuredGrid"): cln = vtk.vtkCleanUnstructuredGrid() cln.SetInputConnection(c2p.GetOutputPort()) if self.debug: vcs2vtk.dump2VTK(cln) sFilter.SetInputConnection(cln.GetOutputPort()) else: sFilter.SetInputConnection(c2p.GetOutputPort()) else: sFilter.SetInputData(ug) sFilter.Update() if self.debug: vcs2vtk.dump2VTK(sFilter) if isinstance(gm,isoline.Gi): cot = vtk.vtkContourFilter() if cellData: cot.SetInputData(sFilter.GetOutput()) else: cot.SetInputData(ug) levs = gm.levels if (isinstance(gm,isoline.Gi) and numpy.allclose( levs[0],[0.,1.e20])) or numpy.allclose(levs,1.e20): levs = vcs.mkscale(mn,mx) Ncolors = len(levs) if isinstance(gm,(isofill.Gfi,meshfill.Gfm)): levs2 = vcs.mkscale(mn,mx) levs=[] for i in range(len(levs2)-1): levs.append([levs2[i],levs2[i+1]]) else: if isinstance(gm.levels[0],(list,tuple)): if isinstance(gm,isoline.Gi): levs = [x[0] for x in gm.levels] else: levs = gm.levels else: levs = [] levs2=gm.levels if numpy.allclose(levs2[0],1.e20): levs2[0]=-1.e20 for i in range(len(levs2)-1): levs.append([levs2[i],levs2[i+1]]) if isinstance(gm,isoline.Gi): levs = levs2 Nlevs=len(levs) Ncolors = Nlevs ## Figure out colors if isinstance(gm,boxfill.Gfb): cols = gm.fillareacolors if cols is None: cols = vcs.getcolors(levs2,split=0) elif isinstance(gm,(isofill.Gfi,meshfill.Gfm)): cols = gm.fillareacolors if cols==[1,]: cols = vcs.getcolors(levs2,split=0) elif isinstance(gm,isoline.Gi): cols = gm.linecolors if isinstance(gm,isoline.Gi): cot.SetNumberOfContours(Nlevs) if levs[0]==1.e20: levs[0]=-1.e20 for i in range(Nlevs): cot.SetValue(i,levs[i]) cot.SetValue(Nlevs,levs[-1]) cot.Update() mapper.SetInputConnection(cot.GetOutputPort()) mappers = [] else: mappers = [] LEVS = [] INDX = [] COLS = [] indices = gm.fillareaindices if indices is None: indices=[1,] while len(indices)<len(cols): indices.append(indices[-1]) for i,l in enumerate(levs): if i==0: C = [cols[i],] if numpy.allclose(levs[0][0],-1.e20): ## ok it's an extension arrow L=[mn-1.,levs[0][1]] else: L = levs[i] I = [indices[i],] else: if l[0] == L[-1] and I[-1]==indices[i]: # Ok same type lets keep going if numpy.allclose(l[1],1.e20): L.append(mx+1.) else: L.append(l[1]) C.append(cols[i]) else: # ok we need new contouring LEVS.append(L) COLS.append(C) INDX.append(I) C = [cols[i],] L = levs[i] I = [indices[i],] LEVS.append(L) COLS.append(C) INDX.append(I) for i,l in enumerate(LEVS): # Ok here we are trying to group together levels can be, a join will happen if: # next set of levels contnues where one left off AND pattern is identical if isinstance(gm,isofill.Gfi): mapper = vtk.vtkPolyDataMapper() lut = vtk.vtkLookupTable() cot = vtk.vtkBandedPolyDataContourFilter() cot.ClippingOn() cot.SetInputData(sFilter.GetOutput()) cot.SetNumberOfContours(len(l)) for j,v in enumerate(l): cot.SetValue(j,v) #cot.SetScalarModeToIndex() cot.Update() mapper.SetInputConnection(cot.GetOutputPort()) lut.SetNumberOfTableValues(len(COLS[i])) for j,color in enumerate(COLS[i]): r,g,b = cmap.index[color] lut.SetTableValue(j,r/100.,g/100.,b/100.) #print l[j],vcs.colors.rgb2str(r*2.55,g*2.55,b*2.55),l[j+1] mapper.SetLookupTable(lut) mapper.SetScalarRange(0,len(l)-1) mapper.SetScalarModeToUseCellData() else: for j,color in enumerate(COLS[i]): mapper = vtk.vtkPolyDataMapper() lut = vtk.vtkLookupTable() th = vtk.vtkThreshold() th.ThresholdBetween(l[j],l[j+1]) th.SetInputConnection(geoFilter.GetOutputPort()) geoFilter2 = vtk.vtkDataSetSurfaceFilter() geoFilter2.SetInputConnection(th.GetOutputPort()) mapper.SetInputConnection(geoFilter2.GetOutputPort()) lut.SetNumberOfTableValues(1) r,g,b = cmap.index[color] lut.SetTableValue(0,r/100.,g/100.,b/100.) mapper.SetLookupTable(lut) mapper.SetScalarRange(l[j],l[j+1]) mappers.append([mapper,]) #png = vtk.vtkPNGReader() #png.SetFileName("/git/uvcdat/Packages/vcs/Share/uvcdat_texture.png") #T=vtk.vtkTexture() #T.SetInputConnection(png.GetOutputPort()) if isinstance(gm,isofill.Gfi): mappers.append([mapper,]) else: #Boxfill (non custom)/Meshfill if isinstance(gm,boxfill.Gfb): if numpy.allclose(gm.level_1,1.e20) or numpy.allclose(gm.level_2,1.e20): levs = vcs.mkscale(mn,mx) legend = vcs.mklabels(levs) dx = (levs[-1]-levs[0])/(gm.color_2-gm.color_1+1) levs = numpy.arange(levs[0],levs[-1]+dx,dx) else: if gm.boxfill_type=="log10": levs = vcs.mkscale(numpy.ma.log10(gm.level_1),numpy.ma.log10(gm.level_2)) else: levs = vcs.mkscale(gm.level_1,gm.level_2) legend = vcs.mklabels(levs) if gm.boxfill_type=="log10": for k in legend.keys(): legend[float(numpy.ma.log10(legend[k]))] = legend[k] del(legend[k]) dx = (levs[-1]-levs[0])/(gm.color_2-gm.color_1+1) levs = numpy.arange(levs[0],levs[-1]+dx,dx) cols = range(gm.color_1,gm.color_2+1) else: if numpy.allclose(gm.levels,1.e20): levs = vcs.mkscale(mn,mx) else: levs = gm.levels if numpy.allclose(levs[0],1.e20): levs[0]=-1.e20 cols = gm.fillareacolors if cols==[1,]: cols = vcs.getcolors(levs) Nlevs = len(levs) Ncolors = Nlevs-1 #Prep mapper mappers=[] mapper = vtk.vtkPolyDataMapper() thr = vtk.vtkThreshold() thr.SetInputConnection(geoFilter.GetOutputPort()) if not gm.ext_1 in ["y",1,True] and not gm.ext_2 in ["y",1,True] : thr.ThresholdBetween(levs[0],levs[-1]) elif gm.ext_1 in ["y",1,True] and not gm.ext_2 in ["y",1,True] : thr.ThresholdByLower(levs[-1]) elif not gm.ext_1 in ["y",1,True] and gm.ext_2 in ["y",1,True] : thr.ThresholdByUpper(levs[0]) thr.Update() geoFilter2 = vtk.vtkDataSetSurfaceFilter() geoFilter2.SetInputConnection(thr.GetOutputPort()) if gm.ext_1 in ["y",1,True] and gm.ext_2 in ["y",1,True] : mapper.SetInputConnection(geoFilter.GetOutputPort()) else: mapper.SetInputConnection(geoFilter2.GetOutputPort()) if mappers == []: # ok didn't need to have special banded contours mappers=[mapper,] ## Colortable bit # make sure length match while len(cols)<Ncolors: cols.append(cols[-1]) lut.SetNumberOfTableValues(Ncolors) for i in range(Ncolors): r,g,b = cmap.index[cols[i]] lut.SetTableValue(i,r/100.,g/100.,b/100.) mapper.SetLookupTable(lut) if numpy.allclose(levs[0],-1.e20): lmn = mn-1. else: lmn= levs[0] if numpy.allclose(levs[-1],1.e20): lmx = mx+1. else: lmx= levs[-1] mapper.SetScalarRange(lmn,lmx) if missingMapper is not None: mappers.insert(0,missingMapper) x1,x2,y1,y2 = vcs2vtk.getRange(gm,xm,xM,ym,yM) if tmpl.data.priority != 0: # And now we need actors to actually render this thing for mapper in mappers: act = vtk.vtkActor() if isinstance(mapper,list): act.SetMapper(mapper[0]) else: mapper.Update() act.SetMapper(mapper) if geo is None: act = vcs2vtk.doWrap(act,[x1,x2,y1,y2],wrap) if isinstance(mapper,list): #act.GetMapper().ScalarVisibilityOff() #act.SetTexture(mapper[1]) pass # create a new renderer for this mapper (we need one for each mapper because of cmaera flips) ren = vtk.vtkRenderer() self.renWin.AddRenderer(ren) self.setLayer(ren,tmpl.data.priority) ren.AddActor(act) vcs2vtk.fitToViewport(act,ren,[tmpl.data.x1,tmpl.data.x2,tmpl.data.y1,tmpl.data.y2],wc=[x1,x2,y1,y2],geo=geo) if isinstance(gm,meshfill.Gfm): tmpl.plot(self.canvas,data1,gm,bg=self.bg,X=numpy.arange(xm,xM*1.1,(xM-xm)/10.),Y=numpy.arange(ym,yM*1.1,(yM-ym)/10.)) else: self.renderTemplate(tmpl,data1,gm) if isinstance(gm,(isofill.Gfi,meshfill.Gfm,boxfill.Gfb)): if getattr(gm,"legend",None) is not None: legend = gm.legend if gm.ext_1 in ["y",1,True] and not numpy.allclose(levs[0],1.e20): if isinstance(levs,numpy.ndarray): levs=levs.tolist() levs.insert(0,-1.e20) if gm.ext_2 in ["y",1,True] and not numpy.allclose(levs[0],1.e20): if isinstance(levs,numpy.ndarray): levs=levs.tolist() levs.append(1.e20) self.renderColorBar(tmpl,levs,cols,legend,cmap) if self.canvas._continents is None: continents = False if continents: projection = vcs.elements["projection"][gm.projection] self.plotContinents(x1,x2,y1,y2,projection,wrap,tmpl)
def _interpMaterials(self, polydata): self.ecm_materials = {} self.pcm_materials = {} probe = vtk.vtkProbeFilter() probe.SetSourceData(self.macro_data) probe.SetInputData(polydata) probe.PassPointArraysOff() probe.PassCellArraysOn() probe.Update() to_cell = vtk.vtkPointDataToCellData() to_cell.SetInputData(probe.GetOutput()) to_cell.Update() mapped_data = to_cell.GetOutput() materialIDs = numpy_support.vtk_to_numpy( mapped_data.GetCellData().GetArray('ElementSetID')).astype(int) ksi = numpy_support.vtk_to_numpy( mapped_data.GetCellData().GetArray('ksi')) E = numpy_support.vtk_to_numpy(mapped_data.GetCellData().GetArray('E')) v = numpy_support.vtk_to_numpy(mapped_data.GetCellData().GetArray('v')) beta = numpy_support.vtk_to_numpy( mapped_data.GetCellData().GetArray('beta')) phi = numpy_support.vtk_to_numpy( mapped_data.GetCellData().GetArray('phi')) permeability = numpy_support.vtk_to_numpy( mapped_data.GetCellData().GetArray('permeability')) m = numpy_support.vtk_to_numpy(mapped_data.GetCellData().GetArray('m')) alpha = numpy_support.vtk_to_numpy( mapped_data.GetCellData().GetArray('alpha')) unique_materialIDs = np.sort(np.unique(materialIDs)) pcm_counter = 0 pcm_offset = unique_materialIDs.size for i, matid in enumerate(unique_materialIDs): idx = np.argwhere(materialIDs == matid) ecm_ids = np.intersect1d(idx.ravel(), self.ecm_set) pcm_ids = np.intersect1d(idx.ravel(), self.pcm_set) E_ratio = self.options['Material Properties']['PCM E ratio'] v_ratio = self.options['Material Properties']['PCM v ratio'] beta_ratio = self.options['Material Properties']['PCM beta ratio'] perm_ratio = self.options['Material Properties']['PCM perm ratio'] self.ecm_materials[i + 3] = { 'E': E[idx[0]][0], 'v': v[idx[0]][0], 'beta': beta[idx[0]][0], 'phi': phi[idx[0]][0], 'permeability': permeability[idx[0]][0], 'm': m[idx[0]][0], 'alpha': alpha[idx[0]][0], 'ksi': ksi[idx[0], :][0], 'element_ids': ecm_ids } materialIDs[ecm_ids] = i + 3 if pcm_ids.any(): self.pcm_materials[pcm_counter + 3 + pcm_offset] = { 'E': E[idx[0]][0] * E_ratio, 'v': v[idx[0]][0] * v_ratio, 'beta': beta[idx[0]][0] * beta_ratio, 'phi': phi[idx[0]][0], 'permeability': permeability[idx[0]][0] * perm_ratio, 'm': m[idx[0]][0], 'alpha': alpha[idx[0]][0], 'element_ids': pcm_ids } materialIDs[pcm_ids] = pcm_counter + 3 + pcm_offset pcm_counter += 1 return materialIDs
# Read some data with point data attributes. The data is from a # plastic blow molding process (e.g., to make plastic bottles) and # consists of two logical components: a mold and a parison. The # parison is the hot plastic that is being molded, and the mold is # clamped around the parison to form its shape. reader = vtk.vtkUnstructuredGridReader() reader.SetFileName(VTK_DATA_ROOT + "/Data/blow.vtk") reader.SetScalarsName("thickness9") reader.SetVectorsName("displacement9") # Convert the point data to cell data. The point data is passed # through the filter so it can be warped. The vtkThresholdFilter then # thresholds based on cell scalar values and extracts a portion of the # parison whose cell scalar values lie between 0.25 and 0.75. p2c = vtk.vtkPointDataToCellData() p2c.SetInputConnection(reader.GetOutputPort()) p2c.PassPointDataOn() warp = vtk.vtkWarpVector() warp.SetInputConnection(p2c.GetOutputPort()) thresh = vtk.vtkThreshold() thresh.SetInputConnection(warp.GetOutputPort()) thresh.ThresholdBetween(0.25, 0.75) thresh.SetInputArrayToProcess(1, 0, 0, 0, "thickness9") #thresh.SetAttributeModeToUseCellData() # This is used to extract the mold from the parison. connect = vtk.vtkConnectivityFilter() connect.SetInputConnection(thresh.GetOutputPort()) connect.SetExtractionModeToSpecifiedRegions() connect.AddSpecifiedRegion(0)
sample.Update() # The cut plane plane = vtk.vtkPlane() plane.SetOrigin(0,0,0) plane.SetNormal(normal) # Cut the volume quickly cut = vtk.vtkFlyingEdgesPlaneCutter() cut.SetInputConnection(sample.GetOutputPort()) cut.SetPlane(plane) cut.ComputeNormalsOff() cut.Update() # Create cell data pd2cd = vtk.vtkPointDataToCellData() pd2cd.SetInputConnection(cut.GetOutputPort()) pd2cd.PassPointDataOn() pd2cd.Update() cutMapper = vtk.vtkPolyDataMapper() cutMapper.SetInputConnection(pd2cd.GetOutputPort()) cutActor = vtk.vtkActor() cutActor.SetMapper(cutMapper); cutActor.GetProperty().SetColor(0.1,0.1,0.1) cutActor.GetProperty().SetRepresentationToWireframe() # Clip a cylinder shell to produce a a trim loop. shell = vtk.vtkCylinderSource() shell.SetCenter(0,0,0)
# NOTE: This test only works if the current directory is writable # try: filename = "plyWriter.ply" channel = open(filename, "wb") channel.close() ss = vtk.vtkSphereSource() ss.SetPhiResolution(10) ss.SetThetaResolution(20) ele = vtk.vtkSimpleElevationFilter() ele.SetInputConnection(ss.GetOutputPort()) pd2cd = vtk.vtkPointDataToCellData() pd2cd.SetInputConnection(ele.GetOutputPort()) # First way or writing w = vtk.vtkPLYWriter() w.SetInputConnection(pd2cd.GetOutputPort()) w.SetFileName(filename) w.SetFileTypeToBinary() w.SetDataByteOrderToLittleEndian() w.SetColorModeToUniformCellColor() w.SetColor(255, 0, 0) w.Write() r = vtk.vtkPLYReader() r.SetFileName(filename) r.Update()