def addSource(self, algo_name, parent): pid = str(parent) parentProxy = helper.idToProxy(parent) if parentProxy: simple.SetActiveSource(parentProxy) else: pid = '0' # Create new source/filter cmdLine = 'simple.' + algo_name + '()' newProxy = eval(cmdLine) # Create its representation and render simple.Show() simple.Render() simple.ResetCamera() # Add node to pipeline self.pipeline.addNode(pid, newProxy.GetGlobalIDAsString()) # Handle domains helper.apply_domains(parentProxy, newProxy.GetGlobalIDAsString()) # Create LUT if need be if pid == '0': self.lutManager.registerFieldData( newProxy.GetPointDataInformation()) self.lutManager.registerFieldData( newProxy.GetCellDataInformation()) # Return the newly created proxy pipeline node return helper.getProxyAsPipelineNode(newProxy.GetGlobalIDAsString(), self.lutManager)
def initialize(self): # Bring used components self.registerVtkWebProtocol( pv_protocols.ParaViewWebStartupRemoteConnection( _FileOpener.dsHost, _FileOpener.dsPort, _FileOpener.rsHost, _FileOpener.rsPort)) self.registerVtkWebProtocol( pv_protocols.ParaViewWebFileListing(_FileOpener.pathToList, "Home")) self.registerVtkWebProtocol(pv_protocols.ParaViewWebMouseHandler()) self.registerVtkWebProtocol(pv_protocols.ParaViewWebViewPort()) self.registerVtkWebProtocol( pv_protocols.ParaViewWebViewPortImageDelivery()) self.registerVtkWebProtocol( pv_protocols.ParaViewWebViewPortGeometryDelivery()) self.registerVtkWebProtocol(pv_protocols.ParaViewWebTimeHandler()) # Update authentication key to use self.updateSecret(_FileOpener.authKey) # Create default pipeline if _FileOpener.fileToLoad: _FileOpener.reader = simple.OpenDataFile(_FileOpener.fileToLoad) simple.Show() _FileOpener.view = simple.Render() _FileOpener.view.ViewSize = [800, 800] # If this is running on a Mac DO NOT use Offscreen Rendering #view.UseOffscreenRendering = 1 simple.ResetCamera() else: _FileOpener.view = simple.GetRenderView() simple.Render() _FileOpener.view.ViewSize = [800, 800] simple.SetActiveView(_FileOpener.view)
def testUserInput(): fileName = QtGui.QFileDialog.getOpenFileName(getMainWindow(), 'Open file',) if fileName: smp.OpenDataFile(fileName, guiName=os.path.basename(fileName)) smp.Show() smp.ResetCamera() smp.Render()
def loadData(self): global dataPath mainpath = os.path.join(dataPath, "main") if os.path.isdir(mainpath): files = os.listdir(mainpath) for file in files: fullpath = os.path.join(mainpath, file) if os.path.isfile(fullpath): self.srcObj = simple.OpenDataFile(fullpath) simple.SetActiveSource(self.srcObj) self.rep = simple.GetDisplayProperties() simple.Hide() print 'Loaded %s into scene' % fullpath else: print 'Error: ' + mainpath + ' does not exist\n' raise Exception("The main directory does not exist") surfacespath = os.path.join(dataPath, "surfaces") files = os.listdir(surfacespath) for file in files: fullpath = os.path.join(surfacespath, file) if os.path.isfile(fullpath): self._loadSurfaceWithProperties(fullpath) simple.SetActiveSource(self.srcObj) simple.ResetCamera() simple.Render()
def openRelativeFile(self, relativePath): fileToLoad = [] if type(relativePath) == list: for file in relativePath: fileToLoad.append(os.path.join(self.baseDir, file)) else: fileToLoad.append(os.path.join(self.baseDir, relativePath)) reader = simple.OpenDataFile(fileToLoad) name = fileToLoad[0].split("/")[-1] if len(name) > 15: name = name[:15] + '*' simple.RenameSource(name, reader) simple.Show() simple.Render() simple.ResetCamera() # Add node to pipeline self.pipeline.addNode('0', reader.GetGlobalIDAsString()) # Create LUT if need be self.lutManager.registerFieldData(reader.GetPointDataInformation()) self.lutManager.registerFieldData(reader.GetCellDataInformation()) return helper.getProxyAsPipelineNode(reader.GetGlobalIDAsString(), self.lutManager)
def render(self): self.view = paraview.CreateRenderView() self.source = paraview.DICOMReaderdirectory( FileName=self.directory_path) self.display = paraview.Show(self.source, self.view) paraview.ResetCamera() camera = paraview.GetActiveCamera() self.view.CenterOfRotation = camera.GetFocalPoint() self.view.CameraParallelProjection = 1 self.view.Background = [0, 0, 0] self.current_slice = self.display.Slice self.display.Representation = self.representation self.display.ColorArrayName = self.array_name paraview.ColorBy(self.display, self.array_name) color_map = paraview.GetColorTransferFunction(self.array_name, self.display) opacity_map = paraview.GetOpacityTransferFunction( self.array_name, self.display) scale_min = color_map.RGBPoints[0] scale_max = color_map.RGBPoints[-4] scale_middle = (scale_max - scale_min) / 2 self.scale_range = (scale_min, scale_max) color_map.RGBPoints = [ scale_min, 0.0, 0.0, 0.0, scale_max, 1.0, 1.0, 1.0, ] opacity_map.Points = [ scale_min, 0.0, 0.5, 0.0, scale_middle, 0.5, 0.5, 0.0, scale_max, 1.0, 0.5, 0.0, ] paraview.Render(self.view)
def resetCamera(self, view): """ RPC callback to reset camera. """ view = self.getView(view) simple.ResetCamera(view) try: view.CenterOfRotation = view.CameraFocalPoint except: pass self.getApplication().InvalidateCache(view.SMProxy) return view.GetGlobalIDAsString()
def resetCamera(self): view = self.getView('-1') simple.Render(view) simple.ResetCamera(view) try: view.CenterOfRotation = view.CameraFocalPoint except: pass self.getApplication().InvalidateCache(view.SMProxy) self.getApplication().InvokeEvent('UpdateEvent') return view.GetGlobalIDAsString()
def showWaterTableDepth(self, visibility): if visibility: self.waterTableRepresentation.Visibility = 1 self.viewSubSurface.InteractionMode = '3D' self.viewSubSurface.CameraParallelProjection = 0 else: self.waterTableRepresentation.Visibility = 0 self.viewSubSurface.InteractionMode = '2D' self.viewSubSurface.CameraParallelProjection = 1 self.viewSubSurface.CameraFocalPoint = [0, 0, 0] self.viewSubSurface.CameraPosition = [0, 0, 1] self.viewSubSurface.CameraViewUp = [0, 1, 0] simple.ResetCamera(self.viewSubSurface) self.viewSubSurface.CenterOfRotation = self.viewSubSurface.CameraFocalPoint
def initialize(self): # Bring used components self.registerVtkWebProtocol( pv_protocols.ParaViewWebStartupRemoteConnection( _FileOpener.dsHost, _FileOpener.dsPort, _FileOpener.rsHost, _FileOpener.rsPort)) self.registerVtkWebProtocol( pv_protocols.ParaViewWebFileListing(_FileOpener.pathToList, "Home")) self.registerVtkWebProtocol(pv_protocols.ParaViewWebMouseHandler()) self.registerVtkWebProtocol(pv_protocols.ParaViewWebViewPort()) self.registerVtkWebProtocol( pv_protocols.ParaViewWebViewPortImageDelivery()) self.registerVtkWebProtocol( pv_protocols.ParaViewWebViewPortGeometryDelivery()) self.registerVtkWebProtocol(pv_protocols.ParaViewWebTimeHandler()) # Update authentication key to use self.updateSecret(_FileOpener.authKey) # Create default pipeline if _FileOpener.fileToLoad: _FileOpener.reader = simple.OpenDataFile(_FileOpener.fileToLoad) simple.Show() _FileOpener.view = simple.Render() _FileOpener.view.ViewSize = [800, 800] # If this is running on a Mac DO NOT use Offscreen Rendering #view.UseOffscreenRendering = 1 simple.ResetCamera() else: _FileOpener.view = simple.GetRenderView() simple.Render() _FileOpener.view.ViewSize = [800, 800] # test to prove server's working # independently from the web components #c = simple.Cone() #c.Resolution = 128 #simple.Hide(c) #p = simple.ProcessIdScalars() #r = simple.Show(p) #a = p.PointData.GetArray('ProcessId') #r.ColorArrayName = 'ProcessId' #simple.AssignLookupTable(a,'Cool to Warm') #simple.Render() #simple.SaveScreenshot('/usr/common/graphics/ParaView/4.2.0-PDACS/data/test.png') simple.SetActiveView(_FileOpener.view)
def openFile(self, path): reader = simple.OpenDataFile(path) simple.RenameSource( path.split("/")[-1], reader) simple.Show() simple.Render() simple.ResetCamera() # Add node to pipeline self.pipeline.addNode('0', reader.GetGlobalIDAsString()) # Create LUT if need be self.lutManager.registerFieldData(reader.GetPointDataInformation()) self.lutManager.registerFieldData(reader.GetCellDataInformation()) return helper.getProxyAsPipelineNode(reader.GetGlobalIDAsString(), self.lutManager)
def openFile(self, files): id = "" if _FileOpener.reader: try: simple.Delete(_FileOpener.reader) except: _FileOpener.reader = None try: _FileOpener.reader = simple.OpenDataFile(files) simple.Show() simple.Render() simple.ResetCamera() id = _FileOpener.reader.GetGlobalIDAsString() except: _FileOpener.reader = None return id
def UpdatePipeline(self, time=0): """ Probe dataset and dump images to the disk """ self.file_name_generator.update_active_arguments(time=time) self.slice.SMProxy.InvokeEvent('UserEvent', 'HideWidget') self.view_proxy.CameraParallelProjection = 1 self.view_proxy.CameraViewUp = self.viewup self.view_proxy.CameraFocalPoint = [0, 0, 0] self.view_proxy.CameraPosition = self.slice.SliceType.Normal self.slice.SliceType.Origin = [ (self.dataBounds[0] + self.dataBounds[1]) / 2, (self.dataBounds[2] + self.dataBounds[3]) / 2, (self.dataBounds[4] + self.dataBounds[5]) / 2 ] simple.Render() simple.ResetCamera() self.view_proxy.CameraParallelScale = self.view_proxy.CameraParallelScale / self.parallelScaleRatio for step in range(int(self.number_of_steps)): self.slice.SliceType.Origin = [ self.origin[0] + float(step) * self.origin_inc[0], self.origin[1] + float(step) * self.origin_inc[1], self.origin[2] + float(step) * self.origin_inc[2] ] # Loop over each color withour changing geometry for name in self.colorByArray: # Choose color by self.sliceRepresentation.ColorArrayName = ( self.colorByArray[name]["type"], name) self.sliceRepresentation.LookupTable = self.colorByArray[name][ "lut"] self.file_name_generator.update_active_arguments( sliceColor=name) # Update file name pattern self.file_name_generator.update_active_arguments( slicePosition=step) simple.Render() simple.WriteImage(self.file_name_generator.get_fullpath()) # Generate metadata self.file_name_generator.update_label_arguments(sliceColor="Color by:") self.file_name_generator.WriteMetaData() self.view_proxy.CameraParallelProjection = 0
def scaleAxis(axis, scale): """Use to scale an axis visually""" import paraview.simple as pvs sc = [1, 1, 1] # Default Scale sc[axis] = scale for f in pvs.GetSources().values(): # get active view rv = pvs.GetActiveViewOrCreate('RenderView') # get display properties disp = pvs.GetDisplayProperties(f, view=rv) # Set the scale for the data axis disp.Scale = sc disp.DataAxesGrid.Scale = sc disp.PolarAxes.Scale = sc # Update the view pvs.RenderAllViews() pvs.ResetCamera() return None
def test2(): w = simple.Wavelet() c = simple.Contour(ComputeScalars=1, Isosurfaces=range(50, 250, 10)) r = simple.Show(c) lut = simple.GetLookupTableForArray("RTData", 1, RGBPoints=[ 43.34006881713867, 0.23, 0.299, 0.754, 160.01158714294434, 0.865, 0.865, 0.865, 276.68310546875, 0.706, 0.016, 0.15 ]) r.LookupTable = lut r.ColorArrayName = ('POINT_DATA', 'RTData') view = simple.Render() exp = ThreeSixtyImageStackExporter( FileNameGenerator('/tmp/z', 'w_{theta}_{phi}.jpg'), view, [0, 0, 0], 100, [0, 0, 1], [10, 20]) exp.UpdatePipeline() exp = ThreeSixtyImageStackExporter( FileNameGenerator('/tmp/y', 'cone_{theta}_{phi}.jpg'), view, [0, 0, 0], 100, [0, 1, 0], [10, 20]) exp.UpdatePipeline() exp = ThreeSixtyImageStackExporter( FileNameGenerator('/tmp/x', 'cone_{theta}_{phi}.jpg'), view, [0, 0, 0], 100, [1, 0, 0], [10, 20]) exp.UpdatePipeline() simple.ResetCamera() simple.Hide(c) slice = SliceExplorer( FileNameGenerator('/tmp/slice', 'w_{sliceColor}_{slicePosition}.jpg'), view, w, {"RTData": { "lut": lut, "type": 'POINT_DATA' }}, 50, [0, 1, 0]) slice.UpdatePipeline()
def makeSphere(): smp.Sphere() smp.Show() smp.ResetCamera() smp.Render()
def norm_slices_along_points(pointsNm, dataNm, numSlices=10, exportpath='', ext='.csv'): """ This macro takes a series of points and a data source to be sliced. The points are used to construct a path through the data source and a slice is added at intervals of that path along the vector of that path at that point. This constructs `numSlices` slices through the dataset `dataNm`. Parameters ---------- pointsNm : string The string name of the points source to construct the path. dataNm : string The string name of the data source to slice. Make sure this data source is slice-able. numSlices : int, optional The number of slices along the path. exportpath : string, optional The absolute file path of where to save each slice ext : string, optional The file extension for saving out the slices. Default to '.csv' Notes ----- Make sure the input data source is slice-able. The SciPy module is required for this macro. """ # import the simple module from the paraview and other needed libraries import paraview.simple as pvs import numpy as np from scipy.spatial import cKDTree from vtk.util import numpy_support as nps from vtk.numpy_interface import dataset_adapter as dsa # exportpath: Where to save data. Absolute path: # Specify Points for the Line Source: line = pvs.servermanager.Fetch(pvs.FindSource(pointsNm)) # Specify data set to be sliced data = pvs.FindSource(dataNm) # get active view renderView = pvs.GetActiveViewOrCreate('RenderView') # Get the Points over the NumPy interface wpdi = dsa.WrapDataObject(line) # NumPy wrapped points points = np.array( wpdi.Points) # New NumPy array of points so we dont destroy input numPoints = line.GetNumberOfPoints() tree = cKDTree(points) dist, ptsi = tree.query(points[0], k=numPoints) # iterate of points in order (skips last point): num = 0 for i in range(0, numPoints - 1, numPoints / numSlices): # get normal pts1 = points[ptsi[i]] pts2 = points[ptsi[i + 1]] x1, y1, z1 = pts1[0], pts1[1], pts1[2] x2, y2, z2 = pts2[0], pts2[1], pts2[2] norm = [x2 - x1, y2 - y1, z2 - z1] # create slice slc = pvs.Slice(Input=data) slc.SliceType = 'Plane' # set origin at points slc.SliceType.Origin = [x1, y1, z1] # set normal as vector from current point to next point slc.SliceType.Normal = norm if exportpath != '': # save out slice with good metadata: TODO: change name # This will use a value from the point data to add to the name #num = wpdi.PointData['Advance LL (S-558)'][ptsi[i]] filename = path + 'Slice_%d%s' % (num, ext) print(filename) pvs.SaveData(filename, proxy=slc) num += 1 pvs.Show(slc, renderView) pvs.RenderAllViews() pvs.ResetCamera()
def reset_camera_to_yz_plane(self): paraview.ResetCamera(self.view) self.view.CameraPosition = [285.67, 39.75, 29.85] self.view.CameraViewUp = [0.0, 0.0, -1.0]
def resetCamera(self): simple.Render(self.renderView) simple.ResetCamera(self.renderView) self.renderView.CenterOfRotation = self.renderView.CameraFocalPoint
def manySlicesAlongAxis(dataNm, rng, axis=0, exportpath='', ext='.csv'): """ Description ----------- Parameters ---------- `dataNm` : string - The string name of the data source to slice. - Make sure this data source is slice-able. `numSlices` : int, optional - The number of slices along the path. `exportpath` : string, optional - The absolute file path of where to save each slice `ext` : string, optional - The file extension for saving out the slices. - Default to '.csv' Notes ----- - Make sure the input data source is slice-able. - The SciPy module is required for this macro. """ # exportpath: Where to save data. Absolute path: if axis not in (0, 1, 2): raise Exception('Axis choice must be 0, 1, or 2 (x, y, or z)') # Specify data set to be sliced data = pvs.FindSource(dataNm) # get active view renderView = pvs.GetActiveViewOrCreate('RenderView') def getNorm(): norm = [0, 0, 0] norm[axis] = 1 return norm def updateOrigin(og, i): og[axis] = rng[i] return og norm = getNorm() num = 0 inputs = [] for i in range(len(rng)): # create slice slc = pvs.Slice(Input=data) slc.SliceType = 'Plane' # set origin at points og = slc.SliceType.Origin og = updateOrigin(og, i) # set normal as vector from current point to next point slc.SliceType.Normal = norm if exportpath != '': # save out slice with good metadata: TODO: change name # This will use a value from the point data to add to the name #num = wpdi.PointData['Advance LL (S-558)'][ptsi[i]] filename = path + 'Slice_%d%s' % (num, ext) print(filename) pvs.SaveData(filename, proxy=slc) num += 1 inputs.append(slc) #pvs.Show(slc, renderView) # Now append all slices into once source for easy management app = pvs.AppendDatasets(Input=inputs) pvs.RenameSource('%s-Slices' % dataNm, app) pvs.Show(app, renderView) pvs.RenderAllViews() pvs.ResetCamera() return app
def resetCamera(self, view_id): view = self.getView(view_id) simple.ResetCamera(view) view.CenterOfRotation = view.CameraFocalPoint self.getApplication().InvokeEvent('UpdateEvent')
def resetCamera(self): simple.Render(self.renderView) simple.ResetCamera(self.renderView) self.renderView.CenterOfRotation = self.renderView.CameraFocalPoint self.getApplication().InvokeEvent('UpdateEvent')
def reset_camera_to_xy_plane(self): paraview.ResetCamera(self.view) self.view.CameraPosition = [39.75, 39.75, -194.1] self.view.CameraViewUp = [0.0, 1.0, 0.0]
def reset_camera_to_xz_plane(self): paraview.ResetCamera(self.view) self.view.CameraPosition = [39.75, 256.26, 29.85] self.view.CameraViewUp = [0.0, 0.0, -1.0]
isoValues = [77.26, 117.18, 157.09, 197.0, 236.92] # ----------------------------------------------------------------------------- # Data Generation # ----------------------------------------------------------------------------- db = LayerDataSetBuilder(clip, outputDir, { 'type': 'spherical', 'phi': range(-10, 11, 10), 'theta': range(-10, 11, 10) }, [400, 400]) # Setup view with camera position view = db.getView() simple.Show(wavelet, view) simple.Render(view) simple.ResetCamera(view) simple.Hide(wavelet, view) db.start() layerIdx = 0 for layer in cores: # Select only one layer contour.Isosurfaces = isoValues[layerIdx] # Capture each field of each layer for field in fields: db.setActiveLayer(layer, field, layerMesh[layer]) db.writeLayerData() # Move to the next layer
def __init__(self, filepath='.'): self.filepath = filepath self.time = 0.0 self.surfaceColorMode = 0 # Local range self.subSurfaceColorMode = 0 # Local range # Surface View self.viewSurface = simple.CreateRenderView(True) self.viewSurface.EnableRenderOnInteraction = 0 self.viewSurface.OrientationAxesVisibility = 0 self.viewSurface.Background = [0.9, 0.9, 0.9] self.viewSurface.InteractionMode = '2D' self.viewSurface.CameraParallelProjection = 1 # SubSurface view self.viewSubSurface = simple.CreateRenderView(True) self.viewSubSurface.EnableRenderOnInteraction = 0 self.viewSubSurface.OrientationAxesVisibility = 0 self.viewSubSurface.Background = [0.9, 0.9, 0.9] self.viewSubSurface.InteractionMode = '2D' self.viewSubSurface.CameraParallelProjection = 1 # Read dataset self.reader = simple.ParFlowReader(FileName=filepath, DeflectTerrain=1) self.readerSurface = simple.OutputPort(self.reader, 1) self.readerSubSurface = simple.OutputPort(self.reader, 0) # Water table depth self.waterTableDepth = simple.WaterTableDepth( Subsurface=self.readerSubSurface, Surface=self.readerSurface) self.cellCenter = simple.CellCenters(Input=self.waterTableDepth) self.wtdVectCalc = simple.Calculator(Input=self.cellCenter) self.wtdVectCalc.ResultArrayName = 'wtdVect' self.wtdVectCalc.Function = 'iHat + jHat + kHat * water table depth' self.waterTableDepthGlyph = simple.Glyph( Input=self.wtdVectCalc, GlyphType='Cylinder', ScaleFactor=500, GlyphMode='All Points', GlyphTransform='Transform2', ScaleArray=['POINTS', 'wtdVect'], VectorScaleMode='Scale by Components', ) self.waterTableDepthGlyph.GlyphTransform.Rotate = [90.0, 0.0, 0.0] self.waterTableDepthGlyph.GlyphType.Resolution = 12 self.waterTableDepthGlyph.GlyphType.Radius = 0.25 self.waterTableRepresentation = simple.Show(self.waterTableDepthGlyph, self.viewSubSurface) self.waterTableRepresentation.Visibility = 0 # Water balance self.waterBalance = simple.WaterBalance( Subsurface=self.readerSubSurface, Surface=self.readerSurface) self.waterBalanceOverTime = simple.PlotGlobalVariablesOverTime( Input=self.waterBalance) # Surface representation self.surfaceRepresentation = simple.Show(self.readerSurface, self.viewSurface) self.surfaceRepresentation.SetScalarBarVisibility( self.viewSurface, True) # SubSurface representation + slice extract self.reader.UpdatePipeline() self.voi = self.reader.GetClientSideObject().GetOutputDataObject( 0).GetExtent() self.extractSubset = simple.ExtractSubset(Input=self.readerSubSurface) self.subSurfaceRepresentation = simple.Show(self.extractSubset, self.viewSubSurface) self.subSurfaceRepresentation.Representation = 'Surface' # Reset camera + center of rotation simple.Render(self.viewSurface) simple.ResetCamera(self.viewSurface) self.viewSurface.CenterOfRotation = self.viewSurface.CameraFocalPoint simple.Render(self.viewSubSurface) simple.ResetCamera(self.viewSubSurface) self.viewSubSurface.CenterOfRotation = self.viewSubSurface.CameraFocalPoint # Time management self.animationScene = simple.GetAnimationScene() self.animationScene.UpdateAnimationUsingDataTimeSteps()