def initialize (self): debug ("In CellToPointData::initialize ()") self.prev_data_type = "" self.fil = vtk.vtkCellDataToPointData () self.fil.SetInput (self.prev_fil.GetOutput ()) self._find_input_data_type() self.fil.Update ()
def VtuFieldGradient(inputVtu, fieldName): """ Return the gradient of a scalar field in a vtu """ tempVtu = vtu() # Add the points tempVtu.ugrid.SetPoints(inputVtu.ugrid.GetPoints()) # Add the cells tempVtu.ugrid.SetCells(inputVtu.ugrid.GetCellTypesArray(), inputVtu.ugrid.GetCellLocationsArray(), inputVtu.ugrid.GetCells()) # Add the field tempVtu.AddField(fieldName, inputVtu.GetScalarField(fieldName)) tempVtu.ugrid.GetPointData().SetActiveScalars(fieldName) gradientFilter = vtk.vtkCellDerivatives() gradientFilter.SetInput(tempVtu.ugrid) gradientFilter.Update() projectionFilter = vtk.vtkCellDataToPointData() projectionFilter.SetInputConnection(gradientFilter.GetOutputPort()) projectionFilter.Update() tempVtu = vtu() tempVtu.ugrid = PolyDataToUnstructuredGrid(projectionFilter.GetOutput()) return tempVtu.GetField(tempVtu.GetFieldNames()[-1])
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkCellDataToPointData(), 'Processing.', ('vtkDataSet',), ('vtkDataSet',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def get_pointdata(offset,filenameout='data',type='pvtu',attribute_mode='cell'): if type == 'vtu': filename=''.join([filenameout,repr(offset).zfill(4),'.vtu']) datareader = v.vtkXMLUnstructuredGridReader() elif type == 'pvtu': filename=''.join([filenameout,repr(offset).zfill(4),'.pvtu']) datareader = v.vtkXMLPUnstructuredGridReader() print '=== Reading ',filename,' ===' datareader.SetFileName(filename) datareader.Update() data = datareader.GetOutput() if attribute_mode == 'cell': c2p = v.vtkCellDataToPointData() c2p.SetInput(data) pointdata=c2p.GetOutput() pointdata.Update() else: pointdata = data vtk_points=data.GetPoints().GetData() points=ah.vtk2array(vtk_points) print '=== Done with reading data! ===' return {'pointdata': pointdata, 'points': points}
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 vtkCellDataToPointData(dataset): #f = vtk.vtkPointDataToCellData() f = vtk.vtkCellDataToPointData() f.PassCellDataOff() f.SetInputData(dataset) f.Update() return f.GetOutput()
def _volume(dimensions, origin, spacing, scalars, surface_alpha, resolution, blending, center): # Now we can actually construct the visualization grid = pyvista.UniformGrid() grid.dimensions = dimensions + 1 # inject data on the cells grid.origin = origin grid.spacing = spacing grid.cell_arrays['values'] = scalars # Add contour of enclosed volume (use GetOutput instead of # GetOutputPort below to avoid updating) grid_alg = vtk.vtkCellDataToPointData() grid_alg.SetInputDataObject(grid) grid_alg.SetPassCellData(False) grid_alg.Update() if surface_alpha > 0: grid_surface = vtk.vtkMarchingContourFilter() grid_surface.ComputeNormalsOn() grid_surface.ComputeScalarsOff() grid_surface.SetInputData(grid_alg.GetOutput()) grid_surface.SetValue(0, 0.1) grid_surface.Update() grid_mesh = vtk.vtkPolyDataMapper() grid_mesh.SetInputData(grid_surface.GetOutput()) else: grid_mesh = None mapper = vtk.vtkSmartVolumeMapper() if resolution is None: # native mapper.SetScalarModeToUseCellData() mapper.SetInputDataObject(grid) else: upsampler = vtk.vtkImageReslice() upsampler.SetInterpolationModeToLinear() # default anyway upsampler.SetOutputSpacing(*([resolution] * 3)) upsampler.SetInputConnection(grid_alg.GetOutputPort()) mapper.SetInputConnection(upsampler.GetOutputPort()) # Additive, AverageIntensity, and Composite might also be reasonable remap = dict(composite='Composite', mip='MaximumIntensity') getattr(mapper, f'SetBlendModeTo{remap[blending]}')() volume_pos = vtk.vtkVolume() volume_pos.SetMapper(mapper) dist = grid.length / (np.mean(grid.dimensions) - 1) volume_pos.GetProperty().SetScalarOpacityUnitDistance(dist) if center is not None and blending == 'mip': # We need to create a minimum intensity projection for the neg half mapper_neg = vtk.vtkSmartVolumeMapper() if resolution is None: # native mapper_neg.SetScalarModeToUseCellData() mapper_neg.SetInputDataObject(grid) else: mapper_neg.SetInputConnection(upsampler.GetOutputPort()) mapper_neg.SetBlendModeToMinimumIntensity() volume_neg = vtk.vtkVolume() volume_neg.SetMapper(mapper_neg) volume_neg.GetProperty().SetScalarOpacityUnitDistance(dist) else: volume_neg = None return grid, grid_mesh, volume_pos, volume_neg
def mapCellDataToPointData(input_Domain): p2c = vtk.vtkCellDataToPointData() p2c.SetInputData(input_Domain) p2c.PassCellDataOn() # p2c.SetInputArrayToProcess(0, 0, 0,vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, "ev1") p2c.Update() output = p2c.GetOutput() return output
def getPointData(self): self.getData() if self.data.GetPointData().GetNumberOfArrays() == 0: c2p = v.vtkCellDataToPointData() c2p.SetInput(self.data) self.pointdata=c2p.GetOutput() self.pointdata.Update() else: self.pointdata=self.data()
def getPointData(self): self.getData() if self.data.GetPointData().GetNumberOfArrays() == 0: c2p = v.vtkCellDataToPointData() c2p.SetInputData(self.data) self.pointdata=c2p.GetOutput() c2p.Update() else: self.pointdata=self.data
def CellDataToPointData(self): """ Transforms all cell-wise fields in the vtu to point-wise fields. All existing fields will remain. """ cdtpd=vtk.vtkCellDataToPointData() cdtpd.SetInput(self.ugrid) cdtpd.PassCellDataOn() cdtpd.Update() self.ugrid=cdtpd.GetUnstructuredGridOutput()
def CellDataToPointData(self): """ Transforms all cell-wise fields in the vtu to point-wise fields. All existing fields will remain. """ cdtpd=vtk.vtkCellDataToPointData() cdtpd.SetInputData(self.ugrid) cdtpd.PassCellDataOn() cdtpd.Update() self.ugrid=cdtpd.GetUnstructuredGridOutput()
def Run(profileFile): """Process all the Inlets specified by profileFile, solving the Navier- Stokes equations for steady flow down an infinite channel with the cross section of the inlet. Writes the point ID and the fluid velocity at that point, the velocity being such that the integral of the flow across the channel is unity. Currently output is written as vtkPolyData to files like "$GEOMETRYFILEBASENAME.inlet$ID.vtp" """ # Load the profile profile = Profile() profile.LoadFromFile(profileFile) surfaceFile = profile.StlFile surfaceFileScale = profile.StlFileUnit.SizeInMetres print profile.OutputXmlFile ipFinder = GeometryInletPointFinder(profile.OutputXmlFile) inletPointIndices = ipFinder.GetInletData() if len(inletPointIndices) == 0: print "WARNING: no inletPointIndices found. This may mean that HemeLb is run with no inlets inside the simulation domain (e.g., the inlets defined in the xml file reside outside of the physical geometry)." intersectionFinder = SurfaceIntersectionFinder() intersectionFinder.SetFileName(surfaceFile) intersectionFinder.SetFileUnitLength(surfaceFileScale) for inletId, inlet in enumerate(io for io in profile.Iolets if isinstance(io, Inlet)): print inletId, len(profile.Iolets), len(inletPointIndices) inletPointPD = inletPointIndices[inletId] intersectionFinder.SetIolet(inlet) tesselator = Tesselator() tesselator.SetInlet(inlet) tesselator.SetEdgeConnection(intersectionFinder.GetOutputPort()) tesselator.SetSitesConnection(inletPointPD.GetProducerPort()) solver = PoiseuilleSolver() solver.SetInputConnection(tesselator.GetOutputPort()) cellToPoint = vtk.vtkCellDataToPointData() cellToPoint.SetInputConnection(solver.GetOutputPort()) cellToPoint.Update() #writer = vtk.vtkXMLPolyDataWriter() writer = vtk.vtkPolyDataWriter() writer.SetFileTypeToASCII() writer.SetInputConnection(cellToPoint.GetOutputPort()) # print type(cellToPoint) #cellToPoint is of type vtkobject # print dir(cellToPoint) base, gmy = os.path.splitext(profile.OutputGeometryFile) writer.SetFileName(base + '.inlet%d.txt' % inletId) writer.Write() return base + '.inlet%d.txt' % inletId
def load_velocity(filename): import os if not os.path.exists(filename): return None from numpy import zeros from vtk import vtkPolyDataReader, vtkCellDataToPointData reader = vtkPolyDataReader() reader.SetFileName(filename) reader.ReadAllVectorsOn() reader.Update() data = reader.GetOutput() # Extracting triangulation information triangles = data.GetPolys().GetData() points = data.GetPoints() # Mapping data: cell -> point mapper = vtkCellDataToPointData() mapper.AddInputData(data) mapper.Update() mapped_data = mapper.GetOutput() # Extracting interpolate point data udata = mapped_data.GetPointData().GetArray(0) ntri = triangles.GetNumberOfTuples()/4 npts = points.GetNumberOfPoints() nvls = udata.GetNumberOfTuples() tri = zeros((ntri, 3)) x = zeros(npts) y = zeros(npts) ux = zeros(nvls) uy = zeros(nvls) for i in xrange(0, ntri): tri[i, 0] = triangles.GetTuple(4*i + 1)[0] tri[i, 1] = triangles.GetTuple(4*i + 2)[0] tri[i, 2] = triangles.GetTuple(4*i + 3)[0] for i in xrange(npts): pt = points.GetPoint(i) x[i] = pt[0] y[i] = pt[1] for i in xrange(0, nvls): U = udata.GetTuple(i) ux[i] = U[0] uy[i] = U[1] return (x, y, tri, ux, uy)
def Execute(self): if self.Surface == None: self.PrintError('Error: No Surface.') cellDataToPointDataFilter = vtk.vtkCellDataToPointData() cellDataToPointDataFilter.SetInputData(self.Surface) cellDataToPointDataFilter.PassCellDataOn() cellDataToPointDataFilter.Update() self.Surface = cellDataToPointDataFilter.GetPolyDataOutput()
def plot(self, struct): # creates self. data1, legend, filename, fieldname, dim, has_field, tracker, revision if not self.call_config(struct): return # creates self.src if not self.call_src(): return self.bounds = self.src.GetOutput().GetBounds() # si es cell data, lo transforma a point data, porque vtkWarpScalar parece ser que no soporta cell data. if self.data1.get('fielddomain') == 'cell': self.cdtpd = vtk.vtkCellDataToPointData() self.cdtpd.SetInputConnection(self.src.GetOutputPort()) self.warpT = vtk.vtkWarpScalar() self.warpT.SetInputConnection(self.cdtpd.GetOutputPort()) else: self.warpT = vtk.vtkWarpScalar() self.warpT.SetInputConnection(self.src.GetOutputPort()) self.wireM2 = vtk.vtkDataSetMapper() self.wireM2.SetInputConnection(self.warpT.GetOutputPort()) #self.wireM2.SetScalarRange(self.cdtpd.GetOutput().GetScalarRange()) # reverse rainbow [red->blue] -> [blue->red] self.look = self.wireM2.GetLookupTable() # self.wireM2.ScalarVisibilityOff() self.wireA2 = vtk.vtkActor() self.wireA2.SetMapper(self.wireM2) self.wireA2.GetProperty().SetRepresentationToSurface() self.wireA2.GetProperty().SetColor(Plot.edges_color) self.add_sw_2(self.wireA2) self.add_opacity_2([self.wireA2]) # Opacity: 100%/75%/50%/25%/0% self.rens[0].AddActor(self.wireA2) self.maxrange = self.src.GetOutput().GetScalarRange()[1] self.copy_params(struct) self.warpT.Update() # self.add_outline_2(self.src) self.add_outline_2(self.warpT) self.scalarrange.local_set(self.src.GetOutput().GetScalarRange()) self.add_scalarbar_2(self.look) self.done = True
def Run(profileFile): """Process all the Inlets specified by profileFile, solving the Navier- Stokes equations for steady flow down an infinite channel with the cross section of the inlet. Writes the point ID and the fluid velocity at that point, the velocity being such that the integral of the flow across the channel is unity. Currently output is written as vtkPolyData to files like "$GEOMETRYFILEBASENAME.inlet$ID.vtp" """ # Load the profile profile = Profile() profile.LoadFromFile(profileFile) surfaceFile = profile.StlFile surfaceFileScale = profile.StlFileUnit.SizeInMetres print profile.OutputXmlFile ipFinder = GeometryInletPointFinder(profile.OutputXmlFile) inletPointIndices = ipFinder.GetInletData() if len(inletPointIndices) == 0: print "WARNING: no inletPointIndices found. This may mean that HemeLb is run with no inlets inside the simulation domain (e.g., the inlets defined in the xml file reside outside of the physical geometry)." intersectionFinder = SurfaceIntersectionFinder() intersectionFinder.SetFileName(surfaceFile) intersectionFinder.SetFileUnitLength(surfaceFileScale) for inletId, inlet in enumerate(io for io in profile.Iolets if isinstance(io, Inlet)): print inletId, len(profile.Iolets), len(inletPointIndices) inletPointPD = inletPointIndices[inletId] intersectionFinder.SetIolet(inlet) tesselator = Tesselator() tesselator.SetInlet(inlet) tesselator.SetEdgeConnection(intersectionFinder.GetOutputPort()) tesselator.SetSitesConnection(inletPointPD.GetProducerPort()) #solver = PoiseuilleSolver() #solver.SetInputConnection(tesselator.GetOutputPort()) cellToPoint = vtk.vtkCellDataToPointData() cellToPoint.SetInputConnection(tesselator.GetOutputPort()) cellToPoint.Update() #writer = vtk.vtkXMLPolyDataWriter() writer = vtk.vtkPolyDataWriter() writer.SetFileTypeToASCII() writer.SetInputConnection(cellToPoint.GetOutputPort()) # print type(cellToPoint) #cellToPoint is of type vtkobject # print dir(cellToPoint) base, gmy = os.path.splitext(profile.OutputGeometryFile) writer.SetFileName(base + '.inlet%d.txt' % inletId) writer.Write() return base + '.inlet%d.txt' % inletId
def mapCellsToPoints(self): """ Transform cell data (i.e., data specified per cell) into point data (i.e., data specified at each vertex). The method of transformation is based on averaging the data values of all cells using a particular point. """ c2p = vtk.vtkCellDataToPointData() c2p.SetInputData(self.inputdata()) c2p.Update() self._mapper.SetScalarModeToUsePointData() return self._update(c2p.GetOutput())
def get_cell_field_as_point_data(self, fieldname): """ Return vtu cell field as point field. fieldname : `str` """ c2p = vtk.vtkCellDataToPointData() c2p.SetInputData(self.output) c2p.Update() outpoints = c2p.GetOutput() nodes = outpoints.GetPointData() array = vtk_to_numpy(nodes.GetArray(fieldname)) return array
def c2p(inp): """ VTK operation: cell to point. @param inp: input VTK object. @type inp: vtk.vtkobject @return: output VTK object. @rtype: vtk.vtkobject """ import vtk usp = vtk.vtkCellDataToPointData() usp.SetInput(inp) return usp
def _createPolyDataFilter(self): """Overrides baseclass implementation.""" self._vtkPolyDataFilter = vtk.vtkDataSetSurfaceFilter() if self._useCellScalars: # Sets data to point instead of just cells c2p = vtk.vtkCellDataToPointData() c2p.SetInputData(self._vtkDataSet) c2p.Update() #For contouring duplicate points seem to confuse it self._vtkPolyDataFilter.SetInputConnection(c2p.GetOutputPort()) else: self._vtkPolyDataFilter.SetInputData(self._vtkDataSet) self._resultDict["vtk_backend_filter"] = self._vtkPolyDataFilter
def _createPolyDataFilter(self): """Overrides baseclass implementation.""" self._vtkPolyDataFilter = vtk.vtkDataSetSurfaceFilter() if self._useCellScalars: # Sets data to point instead of just cells c2p = vtk.vtkCellDataToPointData() c2p.SetInputData(self._vtkDataSet) c2p.Update() # For contouring duplicate points seem to confuse it self._vtkPolyDataFilter.SetInputConnection(c2p.GetOutputPort()) else: self._vtkPolyDataFilter.SetInputData(self._vtkDataSet) self._resultDict["vtk_backend_filter"] = self._vtkPolyDataFilter
def read_vtp(name): """ opens a vtp and returns the vtkPolydata class, additionally, converts all cell datato point data (to plot the root system radius must be point data) @param name including the file extension ("name.vtp") """ reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(name) reader.Update() pd = reader.GetOutput() c2p = vtk.vtkCellDataToPointData() # set cell and point data c2p.SetPassCellData(True) c2p.SetInputData(pd) c2p.Update() return c2p.GetPolyDataOutput()
def load_velocity(filename): if not os.path.exists(filename): return None reader = vtk.vtkPolyDataReader() reader.SetFileName(filename) reader.ReadAllVectorsOn() reader.Update() data = reader.GetOutput() # Extracting triangulation information triangles = data.GetPolys().GetData() points = data.GetPoints() # Mapping data: cell -> point mapper = vtk.vtkCellDataToPointData() mapper.AddInputData(data) mapper.Update() mapped_data = mapper.GetOutput() # Extracting interpolate point data udata = mapped_data.GetPointData().GetArray(0) ntri = triangles.GetNumberOfTuples() / 4 npts = points.GetNumberOfPoints() nvls = udata.GetNumberOfTuples() tri = np.zeros((ntri, 3)) x = np.zeros(npts) y = np.zeros(npts) ux = np.zeros(nvls) uy = np.zeros(nvls) for i in xrange(0, ntri): tri[i, 0] = triangles.GetTuple(4 * i + 1)[0] tri[i, 1] = triangles.GetTuple(4 * i + 2)[0] tri[i, 2] = triangles.GetTuple(4 * i + 3)[0] for i in xrange(npts): pt = points.GetPoint(i) x[i] = pt[0] y[i] = pt[1] for i in xrange(0, nvls): U = udata.GetTuple(i) ux[i] = U[0] uy[i] = U[1] return (x, y, tri, ux, uy)
def extract(data,varname,attribute_mode='cell'): """Extracts variable "varname" from vtkfiles datastructure 'data'""" if attribute_mode == 'cell': vtk_values = data.GetCellData().GetArray(varname) elif attribute_mode == 'point': if data.GetPointData().GetNumberOfArrays() > 0: vtk_values = data.GetPointData().GetArray(varname) else: # Convert to pointdata first c2p = v.vtkCellDataToPointData() c2p.SetInput(data) pointdata=c2p.GetOutput() pointdata.Update() vtk_values = pointdata.GetPointData().GetScalars(varname) elif attribute_mode == 'topoint': c2p = v.vtkCellDataToPointData() c2p.SetInput(data) pointdata=c2p.GetOutput() pointdata.Update() vtk_values = pointdata.GetPointData().GetScalars(varname) else: print("attribute_mode is either 'cell' or 'point'") return ah.vtk2array(vtk_values)
def extract(data,varname,attribute_mode='cell'): '''Extracts variable "varname" from vtk datastructure "data"''' if attribute_mode == 'cell': vtk_values = data.GetCellData().GetArray(varname) elif attribute_mode == 'point': if data.GetPointData().GetNumberOfArrays() > 0: vtk_values = data.GetPointData().GetArray(varname) else: # Convert to pointdata first c2p = v.vtkCellDataToPointData() c2p.SetInput(data) pointdata=c2p.GetOutput() pointdata.Update() vtk_values = pointdata.GetPointData().GetScalars(varname) elif attribute_mode == 'topoint': c2p = v.vtkCellDataToPointData() c2p.SetInput(data) pointdata=c2p.GetOutput() pointdata.Update() vtk_values = pointdata.GetPointData().GetScalars(varname) else: print "attribute_mode is either 'cell' or 'point'" return (ah.vtk2array(vtk_values)).astype(np.float64)
def to_vtk(self) -> vtk.vtkActor: """Create a vtk actor from a ModelDataSet object.""" # calculate point data based on cell data cell_to_point = vtk.vtkCellDataToPointData() if len(self._modeldataset.data) > 1: polydata = JoinedPolyData.from_polydata(self._modeldataset.data) cell_to_point.SetInputConnection(polydata.GetOutputPort()) else: polydata = self._modeldataset.data[0] cell_to_point.SetInputData(polydata) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(cell_to_point.GetOutputPort()) # map cell data to pointdata if self._modeldataset.fields_info: field_info = self._modeldataset.active_field_info mapper.SetColorModeToMapScalars() mapper.SetScalarModeToUsePointData() mapper.SetScalarVisibility(True) mapper.SetLookupTable( field_info.legend_parameter.get_lookuptable()) mapper.SetScalarRange(field_info.legend_parameter.range) mapper.Update() actor = vtk.vtkActor() actor.SetMapper(mapper) # Assign Ladybug Tools colors if self._monochrome_color: actor.GetProperty().SetColor(self._monochrome_color) else: actor.GetProperty().SetColor(self._modeldataset.rgb_to_decimal()) if self._modeldataset.edge_visibility: actor.GetProperty().EdgeVisibilityOn() if self._modeldataset.display_mode == DisplayMode.Wireframe: actor.GetProperty().SetRepresentationToWireframe() # This is import for grids with sensor points instead of meshes elif self._modeldataset.display_mode == DisplayMode.Points: actor.GetProperty().SetPointSize(15) return actor
def cell_data_to_point_data(dataset, pass_cell_data=False): """Transforms cell data (i.e., data specified per cell) into point data (i.e., data specified at cell points). The method of transformation is based on averaging the data values of all cells using a particular point. Optionally, the input cell data can be passed through to the output as well. Parameters ---------- pass_cell_data : bool If enabled, pass the input cell data through to the output """ alg = vtk.vtkCellDataToPointData() alg.SetInputDataObject(dataset) alg.SetPassCellData(pass_cell_data) alg.Update() return _get_output(alg, active_scalar=dataset.active_scalar_name)
def Run(profileFile): """Process all the Inlets specified by profileFile, solving the Navier- Stokes equations for steady flow down an infinite channel with the cross section of the inlet. Writes the point ID and the fluid velocity at that point, the velocity being such that the integral of the flow across the channel is unity. Currently output is written as vtkPolyData to files like "$GEOMETRYFILEBASENAME.inlet$ID.vtp" """ # Load the profile profile = Profile() profile.LoadFromFile(profileFile) surfaceFile = profile.StlFile surfaceFileScale = profile.StlFileUnit.SizeInMetres ipFinder = GeometryInletPointFinder(profile.OutputGeometryFile) inletPointIndices = ipFinder.GetInletData() intersectionFinder = SurfaceIntersectionFinder() intersectionFinder.SetFileName(surfaceFile) intersectionFinder.SetFileUnitLength(surfaceFileScale) for inletId, inlet in enumerate(io for io in profile.Iolets if isinstance(io, Inlet)): inletPointPD = inletPointIndices[inletId] intersectionFinder.SetIolet(inlet) tesselator = Tesselator() tesselator.SetInlet(inlet) tesselator.SetEdgeConnection(intersectionFinder.GetOutputPort()) tesselator.SetSitesConnection(inletPointPD.GetProducerPort()) solver = PoiseuilleSolver() solver.SetInputConnection(tesselator.GetOutputPort()) cellToPoint = vtk.vtkCellDataToPointData() cellToPoint.SetInputConnection(solver.GetOutputPort()) cellToPoint.Update() writer = vtk.vtkXMLPolyDataWriter() writer.SetInputConnection(cellToPoint.GetOutputPort()) base, gmy = os.path.splitext(profile.OutputGeometryFile) writer.SetFileName(base + '.inlet%d.vtp' % inletId) 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 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 RequestData(self, request, inInfo, outInfo): # Get input/output of Proxy pdi = self.GetInputData(inInfo, 0, 0) pdo = self.GetOutputData(outInfo, 0) #### Perfrom task #### # Get the Points over the NumPy interface wpdi = dsa.WrapDataObject(pdi) # NumPy wrapped input if not hasattr(wpdi, 'Points'): raise _helpers.PVGeoError('Input data object does not have XYZ points.') points = np.array(wpdi.Points) # New NumPy array of poins so we dont destroy input # Now transfer data f = vtk.vtkCellDataToPointData() f.SetInputData(pdi) f.Update() d = f.GetOutput() pdo.ShallowCopy(interface.pointsToPolyData(points)) _helpers.copyArraysToPointData(d, pdo, 0) # 0 is point data return 1
def load(offset, filenameout="data", type="pvtu"): if type == "vtu": filename = "".join([filenameout, repr(offset).zfill(4), ".vtu"]) datareader = v.vtkXMLUnstructuredGridReader() elif type == "pvtu": filename = "".join([filenameout, repr(offset).zfill(4), ".pvtu"]) datareader = v.vtkXMLPUnstructuredGridReader() print "=== loading and converting to pointdata, file:", filename, " ===" datareader.SetFileName(filename) datareader.Update() c2p = v.vtkCellDataToPointData() c2p.SetInput(datareader.GetOutput()) pointdata = c2p.GetOutput() pointdata.Update() print "=== Done with loading pointdata ===" return pointdata
def load(offset, filenameout='data', type='pvtu'): if type == 'vtu': filename = ''.join([filenameout, repr(offset).zfill(4), '.vtu']) datareader = v.vtkXMLUnstructuredGridReader() elif type == 'pvtu': filename = ''.join([filenameout, repr(offset).zfill(4), '.pvtu']) datareader = v.vtkXMLPUnstructuredGridReader() print '=== loading and converting to pointdata, file:', filename, ' ===' datareader.SetFileName(filename) datareader.Update() c2p = v.vtkCellDataToPointData() c2p.SetInput(datareader.GetOutput()) pointdata = c2p.GetOutput() pointdata.Update() print '=== Done with loading pointdata ===' return pointdata
def main(): parser = argparse.ArgumentParser() parser.add_argument("--power", help="power level to convert") parser.add_argument("--step", help="step to use for power (default: take highest)") parser.add_argument("--prefix", default="tosoratti-probe-sensitivity", help="directory to use for VTU profiles " "(default: tosoratti-probe-sensitivity)") args = parser.parse_args() prefix = args.prefix power = int(args.power) if args.step: vtu = "%s-%d/Q_over_sigma%s.vtu" % (prefix, power, args.step) else: # Change (not creation) time - cf. mtime vtus = glob.glob('%s-%d/Q_over_sigma*.vtu' % (prefix, power)) vtus.sort(key=os.path.getctime) try: vtu = vtus[-1] except KeyError: raise RuntimeError("No VTUs found for power") reader = v.vtkXMLUnstructuredGridReader() reader.SetFileName(vtu) reader.Update() unstructured_grid = reader.GetOutput() cell_data_to_point_data = v.vtkCellDataToPointData() cell_data_to_point_data.SetInputData(unstructured_grid) cell_data_to_point_data.Update() point_grid = cell_data_to_point_data.GetOutput() points = point_grid.GetPoints() data = point_grid.GetPointData().GetScalars() for i in range(points.GetNumberOfPoints()): point = points.GetPoint(i) datum = data.GetComponent(i, 0) print("%lf %lf %g" % (point[0], point[1], datum))
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 readCellData_to_pointData(caseDir, timename, fieldNames, MeshData): validCells_index = MeshData['validCells_index'] polygon2triangle = MeshData['poly2tri'] VTU = MeshData['FieldData_usg'] # 1.2 read cell data dataNames = [] cellData = {} for fieldName in fieldNames: field = readField_(caseDir, timename, fieldName) for i, dataName in zip(range(0, len(field)), field.keys()): dataNames.append(dataName) celldata = vtk.vtkFloatArray() celldata.SetNumberOfValues(MeshData['triangles'].shape[0]) celldata.SetName(dataName) if field[dataName].shape[0] == 1: num = validCells_index.shape[0] cellData[dataName] = np.repeat(field[dataName], num) else: cellData[dataName] = field[dataName][ validCells_index] # only extract field values associated with polygons # print(cellData.keys()) index_cell = 0 for i in range(0, len(cellData[dataName])): for j in range(0, polygon2triangle[i]): celldata.SetValue(index_cell, cellData[dataName][i]) index_cell = index_cell + 1 VTU.GetCellData().AddArray(celldata) c2p = vtk.vtkCellDataToPointData() c2p.SetInputData(VTU) c2p.Update() pointdata = {} for dataName in dataNames: pointdata[dataName] = VN.vtk_to_numpy( c2p.GetOutput().GetPointData().GetArray(dataName)) return { 'pointData': pointdata, 'cellData': cellData, "x": MeshData["x"], "y": MeshData["y"] }
def __init__(self, case_dir, filename, time=None): self.filename = filename if time == None: self.time = self._getLatestTime(case_dir + "/postProcessing/surfaces/") else: self.time = str(time) file = case_dir + "/postProcessing/surfaces/" + self.time + "/" + filename reader = vtk.vtkDataSetReader() reader.SetFileName(file) reader.ReadAllScalarsOn() reader.ReadAllVectorsOn() reader.Update() data = reader.GetOutput() triangles = data.GetPolys().GetData() points = data.GetPoints() self.mapper = vtk.vtkCellDataToPointData() self.mapper.AddInputData(data) self.mapper.Update() self.ntri = triangles.GetNumberOfTuples() // 4 self.npts = points.GetNumberOfPoints() self.tri = np.zeros((self.ntri, 3)) self.x = np.zeros(self.npts) self.y = np.zeros(self.npts) for i in range(0, self.ntri): self.tri[i, 0] = triangles.GetTuple(4 * i + 1)[0] self.tri[i, 1] = triangles.GetTuple(4 * i + 2)[0] self.tri[i, 2] = triangles.GetTuple(4 * i + 3)[0] for i in range(0, self.npts): pt = points.GetPoint(i) self.x[i] = pt[0] self.y[i] = pt[1]
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 segs_to_polydata(rs, zoom_factor=10., param_names=["radius", "type", "creationTime"]): """ Creates vtkPolydata from a RootSystem or Plant using segments @param rs A RootSystem, Plant, or SegmentAnalyser @param zoom_factor The radial zoom factor, since root are sometimes too thin for vizualisation @param param_names Parameter names of scalar fields, that are copied to the polydata @return A vtkPolydata object of the root system """ if isinstance(rs, pb.Organism): ana = pb.SegmentAnalyser(rs) # for Organism like Plant or RootSystem else: ana = rs nodes = np_convert(ana.nodes) segs = np_convert(ana.segments) points = vtk_points(nodes) cells = vtk_cells(segs) pd = vtk.vtkPolyData() pd.SetPoints(points) pd.SetLines(cells) # check SetPolys for n in param_names: param = np.array(ana.getParameter(n)) if param.shape[0] == segs.shape[0]: if n == "radius": param *= zoom_factor data = vtk_data(param) data.SetName(n) pd.GetCellData().AddArray(data) else: print( "segs_to_polydata: Warning parameter " + n + " is sikpped because of wrong size", param.shape[0], "instead of", segs.shape[0]) c2p = vtk.vtkCellDataToPointData() c2p.SetPassCellData(True) c2p.SetInputData(pd) c2p.Update() return c2p.GetPolyDataOutput()
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 generate_arrays (self, outputGrid): if (self.vector_name.get () == "Source vector"): return outputGrid # Calculate vorticity debug ("Calculating vorticity...") self.fil.SetInput (outputGrid) self.fil.Update () outputGrid = self.fil.GetOutput () outputGrid.Update () # Convert vorticity to point data cellToPoint = vtk.vtkCellDataToPointData () cellToPoint.SetInput (outputGrid) cellToPoint.PassCellDataOff () cellToPoint.Update () outputGrid = cellToPoint.GetOutput () # Allow the user to constrain vorticity to one dimension (this # has the same effect as flattening the source array # (e.g. velocity) onto a plane). desiredDimensionIndex = self.dimension_to_allow.get () if desiredDimensionIndex != -1: vorticity = outputGrid.GetPointData ().GetArray ("Vorticity") for i in range(3): if i != desiredDimensionIndex: vorticity.FillComponent(i, 0.0) outputGrid.Update () # Extract vector norm vectorNorm = vtk.vtkVectorNorm () vectorNorm.SetAttributeModeToUsePointData () vectorNorm.SetInput (outputGrid) vectorNorm.Update () outputGrid = vectorNorm.GetOutput() return outputGrid
def getvtkimage(self, webargs, timestep): #Setup query DBSTRING = os.environ['db_connection_string'] conn = pyodbc.connect(DBSTRING, autocommit=True) cursor = conn.cursor() #url = "http://localhost:8000/cutout/getcutout/"+ token + "/" + dataset + "/" + datafield + "/" + ts + "," +te + "/" + xs + "," + xe +"/" + ys + "," + ye +"/" + zs + "," + ze w = webargs.split("/") ts = int(w[3].split(',')[0]) te = int(w[3].split(',')[1]) xs = int(w[4].split(',')[0]) xe = int(w[4].split(',')[1]) ys = int(w[5].split(',')[0]) ye = int(w[5].split(',')[1]) zs = int(w[6].split(',')[0]) ze = int(w[6].split(',')[1]) extent = (xs, ys, zs, xe, ye, ze) overlap = 2 #Used only on contours--vorticity and Q-criterion #Look for step parameters if (len(w) > 9): step = True; s = w[8].split(",") tstep = s[0] xstep = float(s[1]) ystep = float(s[2]) zstep = float(s[3]) filterwidth = w[9] else: step = False; xstep = 1 ystep = 1 zstep = 1 filterwidth = 1 cfieldlist = w[2].split(",") firstval = cfieldlist[0] maxrange = self.getmaxrange(w[1]) if ((firstval == 'vo') or (firstval == 'qc') or (firstval == 'cvo') or (firstval == 'qcc')): component = 'u' computation = firstval #We are doing a computation, so we need to know which one. #check to see if we have a threshold (only for contours) if (len(cfieldlist) > 1): threshold = float(cfieldlist[1]) else: threshold = .6 #New: We need an expanded cutout if contouring. Push the cutout out by 2 in all directions (unless at boundary). if ((firstval == 'cvo') or (firstval == 'qcc')): newextent = self.expandcutout(extent, maxrange[0], maxrange[1], maxrange[2], overlap) contour = True else: component = w[2] #There could be multiple components, so we will have to loop computation = '' #Split component into list and add them to the image #Check to see if we have a value for vorticity or q contour fieldlist = list(component) for field in fieldlist: print("Field = %s" % field) cursor.execute("{CALL turbdev.dbo.GetAnyCutout(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}",w[1], field, timestep, extent[0], extent[1], extent[2], xstep, ystep, zstep, 1,1,extent[3], extent[4], extent[5],filterwidth,1) #If data spans across multiple servers, we get multiple sets, so concatenate them. row = cursor.fetchone() raw = row[0] part = 0 print ("First part size is %d" % len(row[0])) while(cursor.nextset()): row = cursor.fetchone() raw = raw + row[0] part = part +1 print ("added part %d" % part) print ("Part size is %d" % len(row[0])) print ("Raw size is %d" % len(raw)) data = np.frombuffer(raw, dtype=np.float32) conn.close() vtkdata = numpy_support.numpy_to_vtk(data, deep=True, array_type=vtk.VTK_FLOAT) components = self.numcomponents(field) vtkdata.SetNumberOfComponents(components) vtkdata.SetName(self.componentname(field)) image = vtk.vtkImageData() if (step): xes = int(extent[3])/int(xstep)-1 yes = int(extent[4])/int(ystep)-1 zes = int(extent[5])/int(zstep)-1 image.SetExtent(extent[0], extent[0]+extent[3], extent[1], extent[1]+extent[4], extent[2], extenet[2]+extenet[5]) print("Step extent=" +str(xes)) print("xs=" + str(xstep) + " ys = "+ str(ystep) +" zs = " + str(zstep)) else: image.SetExtent(extent[0], extent[0]+extent[3]-1, extent[1], extent[1]+extent[4]-1, extent[2], extent[2]+extent[5]-1) image.GetPointData().SetVectors(vtkdata) if (step): #Magnify to original size image.SetSpacing(xstep,ystep,zstep) #Check if we need a rectilinear grid, and set it up if so. if (w[1] == 'channel'): ygrid = self.getygrid() #print("Ygrid: ") #print (ygrid) rg = vtk.vtkRectilinearGrid() #Not sure about contouring channel yet, so we are going back to original variables at this point. rg.SetExtent(xs, xs+xe-1, ys, ys+ye-1, zs, zs+ze-1) rg.GetPointData().SetVectors(vtkdata) xg = np.arange(float(xs),float(xe)) zg = np.arange(float(zs),float(ze)) for x in xg: xg[x] = 8*3.141592654/2048*x for z in zg: zg[z] = 3*3.141592654/2048*z vtkxgrid=numpy_support.numpy_to_vtk(xg, deep=True, array_type=vtk.VTK_FLOAT) vtkzgrid=numpy_support.numpy_to_vtk(zg, deep=True, array_type=vtk.VTK_FLOAT) vtkygrid=numpy_support.numpy_to_vtk(ygrid, deep=True, array_type=vtk.VTK_FLOAT) rg.SetXCoordinates(vtkxgrid) rg.SetZCoordinates(vtkzgrid) rg.SetYCoordinates(vtkygrid) image = rg #we rewrite the image since we may be doing a #computation below #See if we are doing a computation if (computation == 'vo'): vorticity = vtk.vtkCellDerivatives() vorticity.SetVectorModeToComputeVorticity() vorticity.SetTensorModeToPassTensors() vorticity.SetInputData(image) print("Computing Vorticity") vorticity.Update() elif (computation == 'cvo'): vorticity = vtk.vtkCellDerivatives() vorticity.SetVectorModeToComputeVorticity() vorticity.SetTensorModeToPassTensors() vorticity.SetInputData(image) print("Computing Voricity") vorticity.Update() mag = vtk.vtkImageMagnitude() cp = vtk.vtkCellDataToPointData() cp.SetInputData(vorticity.GetOutput()) print("Computing magnitude") cp.Update() image.GetPointData().SetScalars(cp.GetOutput().GetPointData().GetVectors()) mag.SetInputData(image) mag.Update() c = vtk.vtkContourFilter() c.SetValue(0,threshold) c.SetInputData(mag.GetOutput()) print("Computing Contour") c.Update() #Now we need to clip out the overlap box = vtk.vtkBox() #set box to requested size box.SetBounds(xs, xs+xe-1, ys, ys+ye-1, zs,zs+ze-1) clip = vtk.vtkClipPolyData() clip.SetClipFunction(box) clip.GenerateClippedOutputOn() clip.SetInputData(c.GetOutput()) clip.InsideOutOn() clip.Update() cropdata = clip.GetOutput() return cropdata elif (computation == 'qcc'): q = vtk.vtkGradientFilter() q.SetInputData(image) q.SetInputScalars(image.FIELD_ASSOCIATION_POINTS,"Velocity") q.ComputeQCriterionOn() q.Update() #newimage = vtk.vtkImageData() image.GetPointData().SetScalars(q.GetOutput().GetPointData().GetVectors("Q-criterion")) mag = vtk.vtkImageMagnitude() mag.SetInputData(image) mag.Update() c = vtk.vtkContourFilter() c.SetValue(0,threshold) c.SetInputData(mag.GetOutput()) c.Update() #clip out the overlap here box = vtk.vtkBox() #set box to requested size box.SetBounds(xs, xs+xe-1, ys, ys+ye-1, zs,zs+ze-1) clip = vtk.vtkClipPolyData() clip.SetClipFunction(box) clip.GenerateClippedOutputOn() clip.SetInputData(c.GetOutput()) clip.InsideOutOn() clip.Update() cropdata = clip.GetOutput() return cropdata else: return image
def __init__(self, parent=None): super(VTK_Widget1, self).__init__(parent) self.source_is_connected = False # vtk to point data self.c2p = vtk.vtkCellDataToPointData() self.opacityTransferFunction = vtk.vtkPiecewiseFunction() self.colorTransferFunction = vtk.vtkColorTransferFunction() # create a volume property for describing how the data will look self.volumeProperty = vtk.vtkVolumeProperty() self.volumeProperty.SetColor(self.colorTransferFunction) self.volumeProperty.SetScalarOpacity(self.opacityTransferFunction) self.volumeProperty.ShadeOn() self.volumeProperty.SetInterpolationTypeToLinear() # convert to unstructured grid volume self.triangleFilter = vtk.vtkDataSetTriangleFilter() self.triangleFilter.TetrahedraOnlyOn() self.triangleFilter.SetInputConnection(self.c2p.GetOutputPort()) # create a ray cast mapper self.compositeFunction = vtk.vtkUnstructuredGridBunykRayCastFunction() self.volumeMapper = vtk.vtkUnstructuredGridVolumeRayCastMapper() self.volumeMapper.SetRayCastFunction(self.compositeFunction) self.volumeMapper.SetInputConnection(self.triangleFilter.GetOutputPort()) # create a volume self.volume = vtk.vtkVolume() self.volume.SetMapper(self.volumeMapper) self.volume.SetProperty(self.volumeProperty) self.volume.VisibilityOff() # create the VTK widget for rendering self.vtkw=QVTKRenderWindowInteractor(self) self.ren = vtk.vtkRenderer() self.vtkw.GetRenderWindow().AddRenderer(self.ren) self.ren.AddVolume(self.volume) self.alphaSlider = QSlider(Qt.Horizontal) self.alphaSlider.setValue(50) self.alphaSlider.setRange(0,100) self.alphaSlider.setTickPosition(QSlider.NoTicks) self.connect(self.alphaSlider,SIGNAL("valueChanged(int)"),self.AdjustAlpha) self.alphaLabel = QLabel("alpha: ") # layout manager self.layout = QVBoxLayout() self.layout2 = QHBoxLayout() self.layout2.addWidget(self.alphaLabel) self.layout2.addWidget(self.alphaSlider) self.layout.addWidget(self.vtkw) self.layout.addSpacing(34) self.layout.addLayout(self.layout2) self.setLayout(self.layout) # initialize the interactor self.vtkw.Initialize() self.vtkw.Start()
def celldatatopointdata(polydata): """Convert celldata to pointdata.""" converter = vtk.vtkCellDataToPointData() converter.SetInput(polydata) converter.Update() return converter.GetOutput()
def deformableRegistration(self): """ Performs deformable image registration on images reconstructed from polygonal surfaces at a user-specified precision. If **animate** parameter is *True*, this also spawns a VTK interative rendering that can animate the deformation. Returns ------- cell_fields """ for r, mesh in enumerate(self.rmeshes): print(("Performing deformable image registration for object {:d}" .format(r + 1))) rimg, dimg, rpoly = self._poly2img(r) origin = rimg.GetOrigin() rimg.SetOrigin((0, 0, 0)) dimg.SetOrigin((0, 0, 0)) steplength = np.min(dimg.GetSpacing()) * 5.0 rimg = sitk.AntiAliasBinary(rimg) dimg = sitk.AntiAliasBinary(dimg) #peform the deformable registration register = sitk.FastSymmetricForcesDemonsRegistrationFilter() register.SetNumberOfIterations( self.deformableSettings['Iterations']) register.SetMaximumRMSError(self.deformableSettings['Maximum RMS']) register.SmoothDisplacementFieldOn() register.SetStandardDeviations( self.deformableSettings['Displacement Smoothing']) register.SmoothUpdateFieldOff() register.UseImageSpacingOn() register.SetMaximumUpdateStepLength(steplength) register.SetUseGradientType(0) disp_field = register.Execute(rimg, dimg) print(("...Elapsed iterations: {:d}" .format(register.GetElapsedIterations()))) print(("...Change in RMS error: {:6.3f}" .format(register.GetRMSChange()))) disp_field.SetOrigin(origin) #translate displacement field to VTK regular grid a = sitk.GetArrayFromImage(disp_field) disp = vtk.vtkImageData() disp.SetOrigin(disp_field.GetOrigin()) disp.SetSpacing(disp_field.GetSpacing()) disp.SetDimensions(disp_field.GetSize()) arr = numpy_to_vtk(a.ravel(), deep=True, array_type=vtk.VTK_DOUBLE) arr.SetNumberOfComponents(3) arr.SetName("Displacement") disp.GetPointData().SetVectors(arr) #calculate the strain from displacement field getStrain = vtk.vtkCellDerivatives() getStrain.SetInputData(disp) getStrain.SetTensorModeToComputeStrain() getStrain.Update() #add the strain tensor to the displacement field structured grid strains = getStrain.GetOutput() c2p = vtk.vtkCellDataToPointData() c2p.PassCellDataOff() c2p.SetInputData(strains) c2p.Update() disp = c2p.GetOutput() #use VTK probe filter to interpolate displacements and strains #to 3D meshes of cells and save as UnstructuredGrid (.vtu) # to visualize in ParaView; this is a linear interpolation print("...Interpolating displacements to 3D mesh.") if self.rigidInitial: #transform 3D Mesh tf = vtk.vtkTransformFilter() tf.SetInputData(mesh) tf.SetTransform(self.rigidTransforms[r]) tf.Update() mesh = tf.GetOutput() probe = vtk.vtkProbeFilter() probe.SetInputData(mesh) probe.SetSourceData(disp) probe.Update() field = probe.GetOutput() if self.display: probe2 = vtk.vtkProbeFilter() probe2.SetInputData(rpoly) probe2.SetSourceData(disp) probe2.Update() self.cell_fields.append(field) if self.saveFEA: idisp = field.GetPointData().GetVectors() bcs = np.zeros((len(self._snodes[r]), 3), float) for j, node in enumerate(self._snodes[r]): d = idisp.GetTuple3(node - 1) bcs[j, 0] = d[0] bcs[j, 1] = d[1] bcs[j, 2] = d[2] self._bcs.append(bcs) idWriter = vtk.vtkXMLUnstructuredGridWriter() idWriter.SetFileName( str(os.path.normpath(self._def_dir + os.sep + 'cell{:04d}.vtu'.format(r + 1)))) idWriter.SetInputData(self.cell_fields[r]) idWriter.Write() if self.display: self.animate(probe2.GetOutput(), r) print("Registration completed.")
def convertCell2Point(self, cellDataSet): """Apply filter vtkCellDataToPointData""" convert = vtk.vtkCellDataToPointData() convert.SetInput(cellDataSet) convert.Update() return convert
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
def getthresh(args): inputfile = args[0] outputfile = args[1] sx = args[2] ex = args[3] sy = args[4] ey = args[5] sz = args[6] ez = args[7] dataset = args[8] comptype = args[9] print ("Loading file, %s" % inputfile) #Determine if file is h5 or numpy if (inputfile.split(".")[1] == "npy"): rs = timeit.default_timer() vel = np.load(inputfile) re = timeit.default_timer() else: #read in file rs = timeit.default_timer() data_file = h5py.File(inputfile, 'r') vel = np.array(data_file[dataset]) data_file.close() re = timeit.default_timer() cs = timeit.default_timer() #convert numpy array to vtk vtkdata = numpy_support.numpy_to_vtk(vel.flat, deep=True, array_type=vtk.VTK_FLOAT) vtkdata.SetNumberOfComponents(3) vtkdata.SetName("Velocity") image = vtk.vtkImageData() image.GetPointData().SetVectors(vtkdata) image.SetExtent(sx,ex,sy,ey,sz,ez) #NOTE: Hardcoding Spacing image.SetSpacing(.006135923, .006135923, .006135923) print ("Doing computation") ce = timeit.default_timer() vs = timeit.default_timer() if (comptype == "v"): vorticity = vtk.vtkCellDerivatives() vorticity.SetVectorModeToComputeVorticity() vorticity.SetTensorModeToPassTensors() vorticity.SetInputData(image) vorticity.Update() elif (comptype == "q"): vorticity = vtk.vtkGradientFilter() vorticity.SetInputData(image) vorticity.SetInputScalars(image.FIELD_ASSOCIATION_POINTS,"Velocity") vorticity.ComputeQCriterionOn() vorticity.SetComputeGradient(0) vorticity.Update() ve = timeit.default_timer() #Generate contour for comparison c = vtk.vtkContourFilter() c.SetValue(0,1128) if (comptype == "q"): image.GetPointData().SetScalars(vorticity.GetOutput().GetPointData().GetVectors("Q-criterion")) else: image.GetPointData().SetScalars(vorticity.GetOutput().GetPointData().GetVectors()) c.SetInputData(image) c.Update() w = vtk.vtkXMLPolyDataWriter() w.SetEncodeAppendedData(0) #turn of base 64 encoding for fast write w.SetFileName("contour.vtp") w.SetInputData(c.GetOutput()) ws = timeit.default_timer() w.Write() ms = timeit.default_timer() if (comptype == "v"): mag = vtk.vtkImageMagnitude() cp = vtk.vtkCellDataToPointData() cp.SetInputData(vorticity.GetOutput()) cp.Update() image.GetPointData().SetScalars(cp.GetOutput().GetPointData().GetVectors()) mag.SetInputData(image) mag.Update() m = mag.GetOutput() m.GetPointData().RemoveArray("Velocity") else: image.GetPointData().SetScalars(vorticity.GetOutput().GetPointData().GetVectors("Q-criterion")) me = timeit.default_timer() print ("Thresholding.") ts = timeit.default_timer() t = vtk.vtkImageThreshold() #t = vtk.vtkThreshold() #sparse representation if (comptype == "q"): t.SetInputData(image) t.ThresholdByUpper(783.3) #.25*67.17^2 = 1127 #t.SetInputArrayToProcess(0,0,0, vorticity.GetOutput().FIELD_ASSOCIATION_POINTS, "Q-criterion") print("q criterion") else: t.SetInputData(m) t.SetInputArrayToProcess(0,0,0, mag.GetOutput().FIELD_ASSOCIATION_POINTS, "Magnitude") t.ThresholdByUpper(44.79) #44.79) #Set values in range to 1 and values out of range to 0 t.SetInValue(1) t.SetOutValue(0) #t.ReplaceInOn() #t.ReplaceOutOn() print("Update thresh") t.Update() #wt = vtk.vtkXMLImageDataWriter() #wt.SetInputData(t.GetOutput()) #wt.SetFileName("thresh.vti") #wt.Write() d = vtk.vtkImageDilateErode3D() d.SetInputData(t.GetOutput()) d.SetKernelSize(3,3,3) d.SetDilateValue(1) d.SetErodeValue(0) print ("Update dilate") d.Update() iis = vtk.vtkImageToImageStencil() iis.SetInputData(d.GetOutput()) iis.ThresholdByUpper(1) stencil = vtk.vtkImageStencil() stencil.SetInputConnection(2, iis.GetOutputPort()) stencil.SetBackgroundValue(0) #image.GetPointData().RemoveArray("Vorticity") #Set scalars to velocity so it can be cut by the stencil image.GetPointData().SetScalars(image.GetPointData().GetVectors()) #if (comptype == "q"): #Use this to get just q-criterion data instead of velocity data. Do we need both? # image.GetPointData().SetScalars(vorticity.GetOutput().GetPointData().GetScalars("Q-criterion")) stencil.SetInputData(image) print ("Update stencil") stencil.Update() te = timeit.default_timer() print("Setting up write") ws = timeit.default_timer() #Make velocity a vector again velarray = stencil.GetOutput().GetPointData().GetScalars() image.GetPointData().RemoveArray("Velocity") image.GetPointData().SetVectors(velarray) w = vtk.vtkXMLImageDataWriter() w.SetCompressorTypeToZLib() #w.SetCompressorTypeToNone() Need to figure out why this fails. w.SetEncodeAppendedData(0) #turn of base 64 encoding for fast write w.SetFileName(outputfile) w.SetInputData(image) if (0): w.SetCompressorTypeToZfp() w.GetCompressor().SetNx(ex-sx+1) w.GetCompressor().SetNy(ey-sy+1) w.GetCompressor().SetNz(ez-sz+1) w.GetCompressor().SetTolerance(1e-1) w.GetCompressor().SetNumComponents(3) w.Write() we = timeit.default_timer() print("Results:") print("Read time: %s" % str(re-rs)) print ("Convert to vtk: %s" % str(ce-cs)) if (comptype == "q"): print ("Q Computation: %s" % str(ve-vs)) print ("Q Magnitude: %s" % str(me-ms)) else: print ("Vorticity Computation: %s" % str(ve-vs)) print ("Vorticity Magnitude: %s" % str(me-ms)) print ("Threshold: %s" % str(te-ts)) print ("Write %s" % str(we-ws)) print ("Total time: %s" % str(we-rs))
def _cell_derivatives(narray, dataset, attribute_type, filter): if not dataset: raise RuntimeError("Need a dataset to compute _cell_derivatives.") # Reshape n dimensional vector to n by 1 matrix if len(narray.shape) == 1: narray = narray.reshape((narray.shape[0], 1)) ncomp = narray.shape[1] if attribute_type == "scalars" and ncomp != 1: raise RuntimeError("This function expects scalars. " + "Input shape " + str(narray.shape)) if attribute_type == "vectors" and ncomp != 3: raise RuntimeError("This function expects vectors. " + "Input shape " + str(narray.shape)) # numpy_to_vtk converts only contiguous arrays if not narray.flags.contiguous: narray = narray.copy() varray = numpy_support.numpy_to_vtk(narray) if attribute_type == "scalars": varray.SetName("scalars") else: varray.SetName("vectors") # create a dataset with only our array but the same geometry/topology ds = dataset.NewInstance() ds.UnRegister(None) ds.CopyStructure(dataset.VTKObject) if dsa.ArrayAssociation.FIELD == narray.Association: raise RuntimeError("Unknown data association. Data should be associated with points or cells.") if dsa.ArrayAssociation.POINT == narray.Association: # Work on point data if narray.shape[0] != dataset.GetNumberOfPoints(): raise RuntimeError("The number of points does not match the number of tuples in the array") if attribute_type == "scalars": ds.GetPointData().SetScalars(varray) else: ds.GetPointData().SetVectors(varray) elif dsa.ArrayAssociation.CELL == narray.Association: # Work on cell data if narray.shape[0] != dataset.GetNumberOfCells(): raise RuntimeError("The number of does not match the number of tuples in the array") # Since vtkCellDerivatives only works with point data, we need to convert # the cell data to point data first. ds2 = dataset.NewInstance() ds2.UnRegister(None) ds2.CopyStructure(dataset.VTKObject) if attribute_type == "scalars": ds2.GetCellData().SetScalars(varray) else: ds2.GetCellData().SetVectors(varray) c2p = vtk.vtkCellDataToPointData() c2p.SetInputData(ds2) c2p.Update() # Set the output to the ds dataset if attribute_type == "scalars": ds.GetPointData().SetScalars(c2p.GetOutput().GetPointData().GetScalars()) else: ds.GetPointData().SetVectors(c2p.GetOutput().GetPointData().GetVectors()) filter.SetInputData(ds) if dsa.ArrayAssociation.POINT == narray.Association: # Since the data is associated with cell and the query is on points # we have to convert to point data before returning c2p = vtk.vtkCellDataToPointData() c2p.SetInputConnection(filter.GetOutputPort()) c2p.Update() return c2p.GetOutput().GetPointData() elif dsa.ArrayAssociation.CELL == narray.Association: filter.Update() return filter.GetOutput().GetCellData() else: # We shall never reach here raise RuntimeError("Unknown data association. Data should be associated with points or cells.")
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
import vtk ur = vtk.vtkXMLUnstructuredGridReader() ur.SetFileName("pv_files/pv_insitu_20060/pv_insitu_20060_0_52.vtu") ur.Update() #force read the file ug = ur.GetOutput() #c.SetInputArrayToProcess(0,0,0, ug.FIELD_ASSOCIATION_CELLS, "rho") #convert numpy array to vtk c = vtk.vtkContourFilter() cp = vtk.vtkCellDataToPointData() cp.SetInputData(ug) cp.update() pd = cp.GetOutput() c.SetValue(0,1) c.SetValue(1,4) c.SetInputArrayToProcess(0,0,0, pd.FIELD_ASSOCIATION_POINTS, "grd") c.SetInputData(pd) c.Update() #save w = vtk.vtkXMLPolyDataWriter() w.SetInputData(c.GetOutput()) w.SetFileName("testout.vtp") w.Write()
def vortvelvolumei(args): #inputfile, outputfile, sx, ex, sy, ey, sz, ez, dataset): p = args[0] cubenum = args[1] print("Cube", cubenum) #Check for additonal parameters if (p["param1"] != ''): comptype = p["param1"] else: comptype = "q" #Default to q criterion if (p["param2"] != ''): thresh = float(p["param2"]) else: thresh = 783.3 #Default for q threshold on isotropic data inputfile = p["inputfile"] +str(cubenum) + ".npy" outputfile = p["outputfile"] + str(cubenum) + ".vti" #always VTK Image Data for this. sx = p["sx"] sy = p["sy"] sz = p["sz"] ex = p["ex"] ey = p["ey"] ez = p["ez"] print ("Loading file, %s" % inputfile) #Determine if file is h5 or numpy rs = timeit.default_timer() vel = np.load(inputfile) print ("File Loaded") re = timeit.default_timer() #convert numpy array to vtk cs = timeit.default_timer() #convert numpy array to vtk vtkdata = numpy_support.numpy_to_vtk(vel.flat, deep=True, array_type=vtk.VTK_FLOAT) vtkdata.SetNumberOfComponents(3) vtkdata.SetName("Velocity") image = vtk.vtkImageData() image.GetPointData().SetVectors(vtkdata) image.SetExtent(sx,ex,sy,ey,sz,ez) #NOTE: Hardcoding Spacing image.SetSpacing(.006135923, .006135923, .006135923) ce = timeit.default_timer() vs = timeit.default_timer() print ("Beginning computation: " + comptype) if (comptype == "v"): vorticity = vtk.vtkCellDerivatives() vorticity.SetVectorModeToComputeVorticity() vorticity.SetTensorModeToPassTensors() vorticity.SetInputData(image) vorticity.Update() elif (comptype == "q"): vorticity = vtk.vtkGradientFilter() vorticity.SetInputData(image) vorticity.SetInputScalars(image.FIELD_ASSOCIATION_POINTS,"Velocity") vorticity.ComputeQCriterionOn() vorticity.SetComputeGradient(0) vorticity.Update() ve = timeit.default_timer() print("Initial calculation done") ms = timeit.default_timer() if (comptype == "v"): mag = vtk.vtkImageMagnitude() cp = vtk.vtkCellDataToPointData() cp.SetInputData(vorticity.GetOutput()) cp.Update() image.GetPointData().SetScalars(cp.GetOutput().GetPointData().GetVectors()) mag.SetInputData(image) mag.Update() m = mag.GetOutput() m.GetPointData().RemoveArray("Velocity") else: image.GetPointData().SetScalars(vorticity.GetOutput().GetPointData().GetVectors("Q-criterion")) me = timeit.default_timer() print("Generating screenshot") c = vtk.vtkContourFilter() c.SetValue(0,thresh) c.SetInputData(image) c.Update() contour = c.GetOutput() mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(contour) mapper.ScalarVisibilityOn() mapper.SetScalarRange(-1,1) mapper.SetScalarModeToUsePointFieldData() mapper.ColorByArrayComponent("Velocity", 0) actor = vtk.vtkActor() actor.SetMapper(mapper) ren = vtk.vtkRenderer() ren.AddActor(actor) ren.SetBackground(1,1,1) camera = vtk.vtkCamera() ren.SetActiveCamera(camera) ren.ResetCamera() camera.Zoom(1.5) #This reduces the whitespace around the image renWin = vtk.vtkRenderWindow() renWin.SetSize(1024,1024) renWin.AddRenderer(ren) renWin.SetOffScreenRendering(1) windowToImageFilter = vtk.vtkWindowToImageFilter() windowToImageFilter.SetInput(renWin) windowToImageFilter.Update() w = vtk.vtkPNGWriter() pngfilename = p["outputfile"] + str(cubenum) + ".png" w.SetFileName(pngfilename) w.SetInputConnection(windowToImageFilter.GetOutputPort()) w.Write() #Shift camera angle and take snapshots around the cube. for aznum in range(4): camera.Azimuth(90) windowToImageFilter = vtk.vtkWindowToImageFilter() windowToImageFilter.SetInput(renWin) windowToImageFilter.Update() pngfilename = p["outputfile"] + str(cubenum) + "-r" + str(aznum)+ ".png" w.SetFileName(pngfilename) w.SetInputConnection(windowToImageFilter.GetOutputPort()) w.Write() camera.Elevation(90) #Rotate camera to top windowToImageFilter = vtk.vtkWindowToImageFilter() windowToImageFilter.SetInput(renWin) windowToImageFilter.Update() pngfilename = p["outputfile"] + str(cubenum) + "-t1.png" w.SetFileName(pngfilename) w.SetInputConnection(windowToImageFilter.GetOutputPort()) w.Write() camera.Elevation(180) #Rotate camera to bottom windowToImageFilter = vtk.vtkWindowToImageFilter() windowToImageFilter.SetInput(renWin) windowToImageFilter.Update() pngfilename = p["outputfile"] + str(cubenum) + "-b1.png" w.SetFileName(pngfilename) w.SetInputConnection(windowToImageFilter.GetOutputPort()) w.Write() print ("Thresholding.") ts = timeit.default_timer() t = vtk.vtkImageThreshold() #Dense represenation (0's included, structured grid) #t = vtk.vtkThreshold() #sparse representation if (comptype == "q"): t.SetInputData(image) t.ThresholdByUpper(thresh) #.25*67.17^2 = 1127 #t.SetInputArrayToProcess(0,0,0, vorticity.GetOutput().FIELD_ASSOCIATION_POINTS, "Q-criterion") print("q criterion") else: t.SetInputData(m) t.SetInputArrayToProcess(0,0,0, mag.GetOutput().FIELD_ASSOCIATION_POINTS, "Magnitude") t.ThresholdByUpper(thresh) #44.79) #Set values in range to 1 and values out of range to 0 t.SetInValue(1) t.SetOutValue(0) #t.ReplaceInOn() #t.ReplaceOutOn() print("Update thresh") t.Update() #wt = vtk.vtkXMLImageDataWriter() #wt.SetInputData(t.GetOutput()) #wt.SetFileName("thresh.vti") #wt.Write() d = vtk.vtkImageDilateErode3D() d.SetInputData(t.GetOutput()) d.SetKernelSize(4,4,4) d.SetDilateValue(1) d.SetErodeValue(0) print ("Update dilate") d.Update() iis = vtk.vtkImageToImageStencil() iis.SetInputData(d.GetOutput()) iis.ThresholdByUpper(1) stencil = vtk.vtkImageStencil() stencil.SetInputConnection(2, iis.GetOutputPort()) stencil.SetBackgroundValue(0) #image.GetPointData().RemoveArray("Vorticity") #Set scalars to velocity so it can be cut by the stencil image.GetPointData().SetScalars(image.GetPointData().GetVectors()) #if (comptype == "q"): #Use this to get just q-criterion data instead of velocity data. Do we need both? # image.GetPointData().SetScalars(vorticity.GetOutput().GetPointData().GetScalars("Q-criterion")) stencil.SetInputData(image) print ("Update stencil") stencil.Update() te = timeit.default_timer() print("Setting up write") ws = timeit.default_timer() #Make velocity a vector again velarray = stencil.GetOutput().GetPointData().GetScalars() image.GetPointData().RemoveArray("Velocity") image.GetPointData().SetVectors(velarray) w = vtk.vtkXMLImageDataWriter() w.SetCompressorTypeToZLib() #w.SetCompressorTypeToNone() Need to figure out why this fails. w.SetEncodeAppendedData(0) #turn of base 64 encoding for fast write w.SetFileName(outputfile) w.SetInputData(image) if (0): w.SetCompressorTypeToZfp() w.GetCompressor().SetNx(ex-sx+1) w.GetCompressor().SetNy(ey-sy+1) w.GetCompressor().SetNz(ez-sz+1) w.GetCompressor().SetTolerance(1e-2) w.GetCompressor().SetNumComponents(3) #result = w.Write() result = 1 #don't write for benchmarking we = timeit.default_timer() print("Results:") print("Read time: %s" % str(re-rs)) print ("Convert to vtk: %s" % str(ce-cs)) if (comptype == "q"): print ("Q Computation: %s" % str(ve-vs)) print ("Q Magnitude: %s" % str(me-ms)) else: print ("Vorticity Computation: %s" % str(ve-vs)) print ("Vorticity Magnitude: %s" % str(me-ms)) print ("Threshold: %s" % str(te-ts)) print ("Write %s" % str(we-ws)) print ("Total time: %s" % str(we-rs)) if (result): p["message"] = "Success" p["computetime"] = str(we-rs) return p #return the packet
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)
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) ren1.SetBackground(0.1,0.2,0.4) renWin.SetSize(256,256) # render the image iren.Initialize()