def __init__(self, dataCatalogEntry): self.debug = True self.dataFile = dataCatalogEntry["fileName"] self.description = dataCatalogEntry["description"] self.renderView = simple.GetActiveViewOrCreate('RenderView') # create a new 'EnSight Reader' self.caseData = simple.EnSightReader(CaseFileName=self.dataFile) # show data in view self.caseDataDisplay = simple.Show(self.caseData, self.renderView) # Get variables and range data from the newly-opened file. self.variables = {} #***************************TBD # Set some defaults for the display properties. self.caseDataDisplay.Representation = 'Surface' # show color bar/color legend self.caseDataDisplay.SetScalarBarVisibility(self.renderView, True) # hide data in view simple.Hide(self.caseData, self.renderView) # update the view to ensure updated data information self.renderView.Update() self.tankGeometryShown = False self.tankGeometryInit = False
def clipThrough(clip, ax, bounds, num=10, delay=1.0): """ Description ----------- This macro takes a clip source and progresses its location through a set of bounds in the data scene. The macro requires that the clip already exist in the pipeline. This is especially useful if you have many clips linked together as all will move through the seen as a result of this macro. Parameters ---------- `clip` : string - The string name of the clip source to be translated. `ax` : int - This is the axis on which to translate (0 for x, 1 for y, 2 for z). - Think of this as the normal vector for the clip. `bounds` : 6-element list or tuple - These are the bounds to constrain the clip translation. `num` : int, optional - The number of discritizations in the clip translation. `delay` : float, optional - Time delay in seconds before conducting each clip translation. """ if ax is not 0 and ax is not 1 and ax is not 2: raise Exception('Axis %d undefined.' % ax) if type(bounds) is not list and type(bounds) is not tuple: # TODO: raise Exception('getting bounds from data... not implemented') c = [(bounds[1] + bounds[0]) / 2, (bounds[3] + bounds[2]) / 2, (bounds[5] + bounds[4]) / 2] # disable automatic camera reset on 'Show' pvs._DisableFirstRenderCameraReset() # find source clp = pvs.FindSource(clip) # get active view renderView = pvs.GetActiveViewOrCreate('RenderView') for k in np.linspace(bounds[ax * 2], bounds[ax * 2 + 1], num=num): if ax == 0: o = [k, c[1], c[2]] n = [1, 0, 0] elif ax == 1: o = [c[0], k, c[2]] n = [0, 1, 0] elif ax == 2: o = [c[0], c[1], k] n = [0, 0, 1] clp.ClipType.Origin = o clp.ClipType.Normal = n renderView.Update() pvs.RenderAllViews() time.sleep(delay)
def contourf_paraview(self, array): assert array in self.reader.PointArrays renderView = pvs.GetActiveViewOrCreate("RenderView") # get color transfer function/color map for 'array' LUT = pvs.GetOpacityTransferFunction(array) # get color legend/bar for LUT in view renderView LUTColorBar = pvs.GetScalarBar(LUT, renderView) return renderView, LUTColorBar
def render_vtk(vtkfilename, outputfilename, processing=None): """ It receives the name of a vtk file, it renders it and saves a png image of it. Give it a function `processing` to apply any processing to the paraview view. """ ext = ".png" reader = prvs.OpenDataFile(vtkfilename) renderView1 = prvs.GetActiveViewOrCreate('RenderView') testvtkDisplay = prvs.Show(reader, renderView1) if processing != None: processing(renderView1) prvs.WriteImage(outputfilename + (ext if ext not in outputfilename else ""))
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 drawCone(self): ################################################## # create a new Cone object self.cone1 = simple.Cone() ## In a Paraview Trace recorded session, the 'simple.' object is ## not necessary. Take your Trace output and add 'simple.' to all ## the capitalized functions and add 'self.' to the local ## variables, and try just dropping it in here. # set active source simple.SetActiveSource(self.cone1) # get active view self.renderView1 = simple.GetActiveViewOrCreate('RenderView') # show data in view self.cone1Display = simple.Show(self.cone1, self.renderView1) # trace defaults for the display properties. self.cone1Display.Representation = 'Surface' # reset view to fit data self.renderView1.ResetCamera() # Properties modified on cone1 self.cone1.Resolution = 12 # change solid color self.cone1Display.DiffuseColor = [0.666, 0.0, 1.0] # reset view to fit data self.renderView1.ResetCamera() # update the view to ensure updated data information self.renderView1.Update() # current camera placement for renderView1 self.renderView1.CameraPosition = [1.25, -3.0, -0.4] self.renderView1.CameraViewUp = [0.75, 0.2, 0.6] self.renderView1.CameraParallelScale = 0.85
def ArrowsScript(Input1, Input2, Output, CamDirVec=None, CamUpVec=None): #### disable automatic camera reset on 'Show' pvs._DisableFirstRenderCameraReset() # create a new 'XML Unstructured Grid Reader' VTU1 = pvs.XMLUnstructuredGridReader(FileName=[Input1]) VTU1.PointArrayStatus = ['Curvature'] # create a new 'XML Unstructured Grid Reader' VTU2 = pvs.XMLUnstructuredGridReader(FileName=[Input2]) VTU2.PointArrayStatus = ['Curvature'] # get active view renderView1 = pvs.GetActiveViewOrCreate('RenderView') # show data in view VTU1Display = pvs.Show(VTU1, renderView1) VTU1Display.Representation = 'Surface' VTU1Display.Diffuse = 0.85 VTU1Display.Ambient = 0.25 makeGlyph(VTU1, renderView1, scale=40.0, color=[1.0, 0.0, 0.0]) makeGlyph(VTU2, renderView1, scale=30.0, color=[0.0, 0.0, 1.0]) # Save Screenshot AdjustCameraAndSave(renderView1, Output, ImageResolution=(2048, 2048), CamDirVec=CamDirVec, CamUpVec=CamUpVec) # set active source pvs.SetActiveSource(None) pvs.SetActiveView(None) pvs.Disconnect()
def pvd_to_mp4(sim_dir, path_to_movies, movie_name='movie', representation='Surface', num_regions=0): ############################### # Validate directory and data # ############################### if not (os.path.isdir(sim_dir)): raise Exception('pvd_to_mp4: Invalid simulation directory') if not (os.path.isdir(path_to_movies)): raise Exception('pvd_to_mp4: Invalid movie directory') if representation not in ['Surface', 'Points']: raise Exception( 'pvd_to_mp4: Representation must be either Surface or Points') if num_regions not in [0, 9]: raise Exception( 'pvd_to_mp4: Currently there is only support for 9 node regions') # sim_id = os.path.basename(os.path.normpath(sim_dir)) possible_data_directories = [] for directory in os.listdir(sim_dir): if directory.startswith('results_from_time'): possible_data_directories.append(os.path.join(sim_dir, directory)) if len(possible_data_directories) == 0: raise Exception( 'pvd_to_mp4: Could not find a "results_from_time_X" directory') # The last directory alphabetically will be the one after any initial relaxation simulation data_directory = sorted(possible_data_directories)[-1] # Get the location of the pvd file pvd_file = os.path.join(data_directory, 'results.pvd') if not (os.path.isfile(pvd_file)): raise Exception('pvd_to_mp4: Could not find a pvd data file') if os.path.getsize(pvd_file) < 1024: raise Exception( 'pvd_to_mp4: pvd file exists but is < 1kb. Presumably simulation failed to finish as expected.' ) full_movie_path = os.path.join(path_to_movies, movie_name + '_' + representation + '.mp4') ################################## # Set up scene with box and data # ################################## # Get active view. This is the ParaView default view - blue background with cross hairs and orientation axes render_view = pv.GetActiveViewOrCreate('RenderView') # Change parameters to be how we want them for output render_view.ViewSize = [1600, 900] # Size of output (pixels) render_view.CenterAxesVisibility = 0 # Remove cross hairs render_view.OrientationAxesVisibility = 0 # Remove orientation axes render_view.Background = [0.5, 0.5, 0.5] # Set background colour to 50% grey # Create a unit square (a 3D Box with ZLength set to zero) unit_square = pv.Box() unit_square.ZLength = 0.0 unit_square.YLength = 9.0 / 16.0 unit_square.Center = [0.5, 0.5, 0.0] # Show the box in the current render view, and colour it black unit_square_display = pv.Show(unit_square, render_view) unit_square_display.DiffuseColor = [0.0, 0.0, 0.0] # Read the relevant pvd file from the Chaste output results_pvd = pv.PVDReader(FileName=pvd_file) # Show the data in the current render view as a surface results_pvd_display = pv.Show(results_pvd, render_view) results_pvd_display.Representation = representation if representation == 'Points' and num_regions == 9: pv.ColorBy(results_pvd_display, ('POINTS', 'Node Regions')) node_regions_lut = pv.GetColorTransferFunction('NodeRegions') # Each four digits are: data value, r, g, b (colour) node_regions_lut.RGBPoints = [ 0.0, 1.00, 0.00, 0.00, # LEFT_APICAL_REGION, red 1.0, 1.00, 0.00, 0.00, # RIGHT_APICAL_REGION, red 2.0, 1.00, 0.00, 1.00, # LEFT_PERIAPICAL_REGION, purple 3.0, 1.00, 0.00, 1.00, # RIGHT_PERIAPICAL_REGION, purple 4.0, 0.00, 0.00, 1.00, # LEFT_LATERAL_REGION, blue 5.0, 0.00, 0.00, 1.00, # RIGHT_LATERAL_REGION, blue 6.0, 1.00, 1.00, 1.00, # LEFT_BASAL_REGION, white 7.0, 1.00, 1.00, 1.00, # RIGHT_BASAL_REGION, white 8.0, 1.00, 1.00, 1.00 ] # LAMINA_REGION, white cell_regions_lut = pv.GetColorTransferFunction('CellRegions') cell_regions_lut.RGBPoints = [ -1.0, 0.0, 0.00, 0.00, # basal lamina, black 0.0, 0.00, 0.00, 1.00, # left region, blue 1.0, 1.00, 1.00, 1.00, # centre_region, white 2.0, 1.00, 0.00, 0.00 ] # right_region, red # Glyphs for cell region cell_glyphs = pv.Glyph(Input=results_pvd, GlyphType='2D Glyph') cell_glyphs.Scalars = ['CELLS', 'Cell Regions'] cell_glyphs.ScaleFactor = 0.01 cell_glyphs.GlyphMode = 'All Points' cell_glyphs.GlyphType.GlyphType = 'Diamond' cell_glyphs.GlyphType.Filled = 1 cell_glyphs.GlyphTransform.Scale = [1.0, 2.0, 1.0] cell_glyphs_display = pv.Show(cell_glyphs, render_view) cell_glyphs_display.Opacity = 0.5 # Glyphs for node region node_glyphs = pv.Glyph(Input=results_pvd, GlyphType='2D Glyph') node_glyphs.Scalars = ['POINTS', 'Node Regions'] node_glyphs.ScaleFactor = 0.002 node_glyphs.GlyphMode = 'All Points' node_glyphs.GlyphType.GlyphType = 'Circle' node_glyphs.GlyphType.Filled = 1 pv.Show(node_glyphs, render_view) ################################### # Put the camera where we want it # ################################### # This happens after all calls to Show, as Show may do some automatic camera re-setting render_view.InteractionMode = '2D' render_view.CameraPosition = [0.5, 0.5, 1.0] render_view.CameraFocalPoint = [0.5, 0.5, 0.0] # This parameter sets the 'zoom' and needs fine-tuning by the aspect ratio render_view.CameraParallelScale = 0.5 * 9.0 / 16.0 ################################## # Set up and write the animation # ################################## # Get an animation scene, which has parameters we need to change before output animation_scene = pv.GetAnimationScene() # Get a list of time step values from the pvd file. Typically this will look like [t_0, t1, t2, ..., t_end] time_step_info = results_pvd.TimestepValues num_time_steps = len(time_step_info) # Set the animation parameters animation_scene.NumberOfFrames = num_time_steps # If num frames != num time steps, some interpolation will be used animation_scene.StartTime = time_step_info[ 0] # Usually t_0, the first entry in time_step_info animation_scene.EndTime = time_step_info[ -1] # Usually t_end, the final entry in time_step_info # Write the animation as a series of uncompressed png files, with no magnification pv.WriteAnimation(sim_dir + 'results_' + representation + '.png', Magnification=1, Compression=False) # Raise exception if the png files are not generated as expected if not (os.path.isfile(sim_dir + 'results_' + representation + '.0000.png')): raise Exception('pvd_to_mp4: png sequence not exported as expected') ####################################### # Convert from png to mp4 and tidy up # ####################################### # Ubuntu 14.04 (trusty) came bundled with avconv instead of ffmpeg, but they're nearly the same software # so we don't have to change the command other than the name of the video converter to use if platform.linux_distribution()[2] == 'trusty': video_converter = 'avconv' else: video_converter = 'ffmpeg' # Set how long you want the video to be (in seconds), and set the frame rate accordingly video_duration = 15.0 frame_rate = str(num_time_steps / video_duration) # Send the system command to run avconv/ffmpeg. Parameters: # -v 0 Suppress console output so as not to clutter the terminal # -r frame_rate Set the frame rate calculated above # -f image2 Set the convert format (image sequence to video) # -i dir/results.%04d.png Input expected as dir/results.####.png, the output from WriteAnimation above # -c:v h264 Video codec to use is h264 # -crf 0 Set video quality: 0 best, 51 worst (https://trac.ffmpeg.org/wiki/Encode/H.264) # -y dir/movie.mp4 Output directory and name os.system(video_converter + ' -v 0 -r ' + frame_rate + ' -f image2 -i ' + sim_dir + 'results_' + representation + '.%04d.png -c:v h264 -crf 0 -y ' + full_movie_path) # Raise exception if the mp4 file is not generated as expected if not (os.path.isfile(full_movie_path)): raise Exception('pvd_to_mp4: mp4 not generated as expected') # Raise exception if the mp4 file file is created but is smaller than 1kb - ffmpeg sometimes # generates an empty file even if an error occurs if os.path.getsize(full_movie_path) < 1024: raise Exception('pvd_to_mp4: mp4 not generated as expected') # Clean up the png files created by WriteAnimation os.system('rm ' + sim_dir + '*.png')
def solve(filename,resolution,meshType, testColor): start = time.time() test_desc["Mesh_type"]=meshType test_desc["Test_color"]=testColor #Chargement du maillage triangulaire de la sphère #======================================================================================= my_mesh = cdmath.Mesh(filename+".med") if(not my_mesh.isTriangular()) : raise ValueError("Wrong cell types : mesh is not made of triangles") if(my_mesh.getMeshDimension()!=2) : raise ValueError("Wrong mesh dimension : expected a surface of dimension 2") if(my_mesh.getSpaceDimension()!=3) : raise ValueError("Wrong space dimension : expected a space of dimension 3") nbNodes = my_mesh.getNumberOfNodes() nbCells = my_mesh.getNumberOfCells() test_desc["Space_dimension"]=my_mesh.getSpaceDimension() test_desc["Mesh_dimension"]=my_mesh.getMeshDimension() test_desc["Mesh_number_of_elements"]=my_mesh.getNumberOfNodes() test_desc["Mesh_cell_type"]=my_mesh.getElementTypes() print("Mesh building/loading done") print("nb of nodes=", nbNodes) print("nb of cells=", nbCells) #Discrétisation du second membre et détermination des noeuds intérieurs #====================================================================== my_RHSfield = cdmath.Field("RHS_field", cdmath.NODES, my_mesh, 1) maxNbNeighbours = 0#This is to determine the number of non zero coefficients in the sparse finite element rigidity matrix #parcours des noeuds pour discrétisation du second membre et extraction du nb max voisins d'un noeud for i in range(nbNodes): Ni=my_mesh.getNode(i) x = Ni.x() y = Ni.y() z = Ni.z() my_RHSfield[i]=12*y*(3*x*x-y*y)/pow(x*x+y*y+z*z,3/2)#vecteur propre du laplacien sur la sphère if my_mesh.isBorderNode(i): # Détection des noeuds frontière raise ValueError("Mesh should not contain borders") else: maxNbNeighbours = max(1+Ni.getNumberOfCells(),maxNbNeighbours) test_desc["Mesh_max_number_of_neighbours"]=maxNbNeighbours print("Right hand side discretisation done") print("Max nb of neighbours=", maxNbNeighbours) print("Integral of the RHS", my_RHSfield.integral(0)) # Construction de la matrice de rigidité et du vecteur second membre du système linéaire #======================================================================================= Rigidite=cdmath.SparseMatrixPetsc(nbNodes,nbNodes,maxNbNeighbours)# warning : third argument is number of non zero coefficients per line RHS=cdmath.Vector(nbNodes) # Vecteurs gradient de la fonction de forme associée à chaque noeud d'un triangle GradShapeFunc0=cdmath.Vector(3) GradShapeFunc1=cdmath.Vector(3) GradShapeFunc2=cdmath.Vector(3) normalFace0=cdmath.Vector(3) normalFace1=cdmath.Vector(3) #On parcourt les triangles du domaine for i in range(nbCells): Ci=my_mesh.getCell(i) #Contribution à la matrice de rigidité nodeId0=Ci.getNodeId(0) nodeId1=Ci.getNodeId(1) nodeId2=Ci.getNodeId(2) N0=my_mesh.getNode(nodeId0) N1=my_mesh.getNode(nodeId1) N2=my_mesh.getNode(nodeId2) #Build normal to cell Ci normalFace0[0]=Ci.getNormalVector(0,0) normalFace0[1]=Ci.getNormalVector(0,1) normalFace0[2]=Ci.getNormalVector(0,2) normalFace1[0]=Ci.getNormalVector(1,0) normalFace1[1]=Ci.getNormalVector(1,1) normalFace1[2]=Ci.getNormalVector(1,2) normalCell = normalFace0.crossProduct(normalFace1) test = normalFace0.tensProduct(normalFace1) normalCell = normalCell/normalCell.norm() cellMat=cdmath.Matrix(4) cellMat[0,0]=N0.x() cellMat[0,1]=N0.y() cellMat[0,2]=N0.z() cellMat[1,0]=N1.x() cellMat[1,1]=N1.y() cellMat[1,2]=N1.z() cellMat[2,0]=N2.x() cellMat[2,1]=N2.y() cellMat[2,2]=N2.z() cellMat[3,0]=normalCell[0] cellMat[3,1]=normalCell[1] cellMat[3,2]=normalCell[2] cellMat[0,3]=1 cellMat[1,3]=1 cellMat[2,3]=1 cellMat[3,3]=0 #Formule des gradients voir EF P1 -> calcul déterminants GradShapeFunc0[0]= cellMat.partMatrix(0,0).determinant()/2 GradShapeFunc0[1]=-cellMat.partMatrix(0,1).determinant()/2 GradShapeFunc0[2]= cellMat.partMatrix(0,2).determinant()/2 GradShapeFunc1[0]=-cellMat.partMatrix(1,0).determinant()/2 GradShapeFunc1[1]= cellMat.partMatrix(1,1).determinant()/2 GradShapeFunc1[2]=-cellMat.partMatrix(1,2).determinant()/2 GradShapeFunc2[0]= cellMat.partMatrix(2,0).determinant()/2 GradShapeFunc2[1]=-cellMat.partMatrix(2,1).determinant()/2 GradShapeFunc2[2]= cellMat.partMatrix(2,2).determinant()/2 #Création d'un tableau (numéro du noeud, gradient de la fonction de forme GradShapeFuncs={nodeId0 : GradShapeFunc0} GradShapeFuncs[nodeId1]=GradShapeFunc1 GradShapeFuncs[nodeId2]=GradShapeFunc2 # Remplissage de la matrice de rigidité et du second membre for j in [nodeId0,nodeId1,nodeId2] : #Ajout de la contribution de la cellule triangulaire i au second membre du noeud j RHS[j]=Ci.getMeasure()/3*my_RHSfield[j]+RHS[j] # intégrale dans le triangle du produit f x fonction de base #Contribution de la cellule triangulaire i à la ligne j du système linéaire for k in [nodeId0,nodeId1,nodeId2] : Rigidite.addValue(j,k,GradShapeFuncs[j]*GradShapeFuncs[k]/Ci.getMeasure()) print("Linear system matrix building done") # Résolution du système linéaire #================================= LS=cdmath.LinearSolver(Rigidite,RHS,100,1.E-2,"CG","ILU")#Remplacer CG par CHOLESKY pour solveur direct LS.isSingular()#En raison de l'absence de bord LS.setComputeConditionNumber() SolSyst=LS.solve() print "Preconditioner used : ", LS.getNameOfPc() print "Number of iterations used : ", LS.getNumberOfIter() print "Final residual : ", LS.getResidu() print("Linear system solved") test_desc["Linear_solver_algorithm"]=LS.getNameOfMethod() test_desc["Linear_solver_preconditioner"]=LS.getNameOfPc() test_desc["Linear_solver_precision"]=LS.getTolerance() test_desc["Linear_solver_maximum_iterations"]=LS.getNumberMaxOfIter() test_desc["Linear_system_max_actual_iterations_number"]=LS.getNumberOfIter() test_desc["Linear_system_max_actual_error"]=LS.getResidu() test_desc["Linear_system_max_actual_condition number"]=LS.getConditionNumber() # Création du champ résultat #=========================== my_ResultField = cdmath.Field("ResultField", cdmath.NODES, my_mesh, 1) for j in range(nbNodes): my_ResultField[j]=SolSyst[j];#remplissage des valeurs pour les noeuds intérieurs #sauvegarde sur le disque dur du résultat dans un fichier paraview my_ResultField.writeVTK("FiniteElementsOnSpherePoisson_"+meshType+str(nbNodes)) end = time.time() print("Integral of the numerical solution", my_ResultField.integral(0)) print("Numerical solution of poisson equation on a sphere using finite elements done") #Calcul de l'erreur commise par rapport à la solution exacte #=========================================================== #The following formulas use the fact that the exact solution is equal the right hand side divided by 12 max_abs_sol_exacte=0 erreur_abs=0 max_sol_num=0 min_sol_num=0 for i in range(nbNodes) : if max_abs_sol_exacte < abs(my_RHSfield[i]) : max_abs_sol_exacte = abs(my_RHSfield[i]) if erreur_abs < abs(my_RHSfield[i]/12 - my_ResultField[i]) : erreur_abs = abs(my_RHSfield[i]/12 - my_ResultField[i]) if max_sol_num < my_ResultField[i] : max_sol_num = my_ResultField[i] if min_sol_num > my_ResultField[i] : min_sol_num = my_ResultField[i] max_abs_sol_exacte = max_abs_sol_exacte/12 print("Absolute error = max(| exact solution - numerical solution |) = ",erreur_abs ) print("Relative error = max(| exact solution - numerical solution |)/max(| exact solution |) = ",erreur_abs/max_abs_sol_exacte) print ("Maximum numerical solution = ", max_sol_num, " Minimum numerical solution = ", min_sol_num) test_desc["Computational_time_taken_by_run"]=end-start test_desc["Absolute_error"]=erreur_abs test_desc["Relative_error"]=erreur_abs/max_abs_sol_exacte #Postprocessing : #================ # save 3D picture PV_routines.Save_PV_data_to_picture_file("FiniteElementsOnSpherePoisson_"+meshType+str(nbNodes)+'_0.vtu',"ResultField",'NODES',"FiniteElementsOnSpherePoisson_"+meshType+str(nbNodes)) # save 3D clip VTK_routines.Clip_VTK_data_to_VTK("FiniteElementsOnSpherePoisson_"+meshType+str(nbNodes)+'_0.vtu',"Clip_VTK_data_to_VTK_"+ "FiniteElementsOnSpherePoisson_"+meshType+str(nbNodes)+'_0.vtu',[0.25,0.25,0.25], [-0.5,-0.5,-0.5],resolution ) PV_routines.Save_PV_data_to_picture_file("Clip_VTK_data_to_VTK_"+"FiniteElementsOnSpherePoisson_"+meshType+str(nbNodes)+'_0.vtu',"ResultField",'NODES',"Clip_VTK_data_to_VTK_"+"FiniteElementsOnSpherePoisson_"+meshType+str(nbNodes)) # save plot around circumference finiteElementsOnSphere_0vtu = pvs.XMLUnstructuredGridReader(FileName=["FiniteElementsOnSpherePoisson_"+meshType+str(nbNodes)+'_0.vtu']) slice1 = pvs.Slice(Input=finiteElementsOnSphere_0vtu) slice1.SliceType.Normal = [0.5, 0.5, 0.5] renderView1 = pvs.GetActiveViewOrCreate('RenderView') finiteElementsOnSphere_0vtuDisplay = pvs.Show(finiteElementsOnSphere_0vtu, renderView1) pvs.ColorBy(finiteElementsOnSphere_0vtuDisplay, ('POINTS', 'ResultField')) slice1Display = pvs.Show(slice1, renderView1) pvs.SaveScreenshot("./FiniteElementsOnSpherePoisson"+"_Slice_"+meshType+str(nbNodes)+'.png', magnification=1, quality=100, view=renderView1) plotOnSortedLines1 = pvs.PlotOnSortedLines(Input=slice1) pvs.SaveData('./FiniteElementsOnSpherePoisson_PlotOnSortedLines'+meshType+str(nbNodes)+'.csv', proxy=plotOnSortedLines1) lineChartView2 = pvs.CreateView('XYChartView') plotOnSortedLines1Display = pvs.Show(plotOnSortedLines1, lineChartView2) plotOnSortedLines1Display.UseIndexForXAxis = 0 plotOnSortedLines1Display.XArrayName = 'arc_length' plotOnSortedLines1Display.SeriesVisibility = ['ResultField (1)'] pvs.SaveScreenshot("./FiniteElementsOnSpherePoisson"+"_PlotOnSortedLine_"+meshType+str(nbNodes)+'.png', magnification=1, quality=100, view=lineChartView2) pvs.Delete(lineChartView2) with open('test_Poisson'+str(my_mesh.getMeshDimension())+'D_EF_'+meshType+str(nbCells)+ "Cells.json", 'w') as outfile: json.dump(test_desc, outfile) return erreur_abs/max_abs_sol_exacte, nbNodes, min_sol_num, max_sol_num, end - start
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()
"FiniteElementsOnSphere") resolution = 100 VTK_routines.Clip_VTK_data_to_VTK( "FiniteElementsOnSphere" + '_0.vtu', "Clip_VTK_data_to_VTK_" + "FiniteElementsOnSphere" + '_0.vtu', [0.25, 0.25, 0.25], [-0.5, -0.5, -0.5], resolution) PV_routines.Save_PV_data_to_picture_file( "Clip_VTK_data_to_VTK_" + "FiniteElementsOnSphere" + '_0.vtu', "ResultField", 'NODES', "Clip_VTK_data_to_VTK_" + "FiniteElementsOnSphere") # Plot over slice circle finiteElementsOnSphere_0vtu = pvs.XMLUnstructuredGridReader( FileName=["FiniteElementsOnSphere" + '_0.vtu']) slice1 = pvs.Slice(Input=finiteElementsOnSphere_0vtu) slice1.SliceType.Normal = [0.5, 0.5, 0.5] renderView1 = pvs.GetActiveViewOrCreate('RenderView') finiteElementsOnSphere_0vtuDisplay = pvs.Show(finiteElementsOnSphere_0vtu, renderView1) pvs.ColorBy(finiteElementsOnSphere_0vtuDisplay, ('POINTS', 'ResultField')) slice1Display = pvs.Show(slice1, renderView1) pvs.SaveScreenshot("./FiniteElementsOnSphere" + "_Slice" + '.png', magnification=1, quality=100, view=renderView1) plotOnSortedLines1 = pvs.PlotOnSortedLines(Input=slice1) lineChartView2 = pvs.CreateView('XYChartView') plotOnSortedLines1Display = pvs.Show(plotOnSortedLines1, lineChartView2) plotOnSortedLines1Display.UseIndexForXAxis = 0 plotOnSortedLines1Display.XArrayName = 'arc_length' plotOnSortedLines1Display.SeriesVisibility = ['ResultField (1)'] pvs.SaveScreenshot("./FiniteElementsOnSphere" + "_PlotOnSortedLine_" + '.png',
def renderView1(self): """Get active view.""" return pv.GetActiveViewOrCreate("RenderView")
def batchVis(c1File,particleFile,step,saveAs): """Renders a bijel top down view in paraview and saves a screenshot.""" import paraview.simple as pv # visualize a vtk file c1 = pv.LegacyVTKReader(FileNames=c1File) p = pv.LegacyVTKReader(FileNames=particleFile) renderView1 = pv.GetActiveViewOrCreate('RenderView') renderView1.ViewSize = [1298, 860] renderView1.Background = [1.0, 1.0, 1.0] renderView1.InteractionMode = '2D' pDisplay = pv.Show(p, renderView1) c1Display = pv.Show(c1, renderView1) # create particle glyphs glyph = pv.Glyph(Input=p,GlyphType="Sphere") glyph.ScaleFactor = 1.0 glyph.GlyphMode = 'All Points' glyph.GlyphType.Radius = 1.0 glyph.GlyphType.ThetaResolution = 20 glyph.GlyphType.PhiResolution = 20 glyph.Scalars = ['POINTS','radius'] glyph.Vectors = ['POINTS','None'] glyph.ScaleMode = 'scalar' # show data in view glyphDisplay = pv.Show(glyph, renderView1) pv.ColorBy(glyphDisplay, None) pv.SetActiveSource(c1) pv.ColorBy(c1Display, ('POINTS', 'c1')) c1Display.RescaleTransferFunctionToDataRange(True) c1Display.SetRepresentationType('Volume') # make box outline # box = pv.Box() # box.XLength = 128.0 # box.YLength = 128.0 # box.ZLength = 64.0 # box.Center = [64.0, 64.0, 32.0] # boxDisplay = pv.Show(box, renderView1) # boxDisplay.SetRepresentationType('Outline') # boxDisplay.AmbientColor = [0.0, 0.0, 0.0] # set coloring of c1 c1LUT = pv.GetColorTransferFunction('c1') c1LUT.RGBPoints = [0.006000000052154064, 0.231373, 0.298039, 0.752941, 0.5120000033639371, 0.865003, 0.865003, 0.865003, 1.0180000066757202, 0.705882, 0.0156863, 0.14902] c1LUT.ColorSpace = 'Diverging' c1LUT.BelowRangeColor = [0.0, 0.0, 0.0] c1LUT.AboveRangeColor = [1.0, 1.0, 1.0] c1LUT.NanColor = [1.0, 1.0, 0.0] c1LUT.Discretize = 1 c1LUT.NumberOfTableValues = 256 c1LUT.ScalarRangeInitialized = 1.0 c1LUT.AllowDuplicateScalars = 1 c1PWF = pv.GetOpacityTransferFunction('c1') c1PWF.Points = [0.0, 0.05, 0.5, 0.0, 0.3, 0.05, 0.5, 0.0, 0.4, 0.5, 0.5, 0.0, 0.6, 0.5, 0.5, 0.0, 0.7, 0.05, 0.5, 0.0, 1., 0.05, 0.5, 0.0] # annotate time step in rendering # text = pv.Text # text.Text = 'Step '+str(step) # textDisplay = pv.Show(text,renderView1) # textDisplay.Color = [0.0, 0.0, 0.0] # textDisplay.WindowLocation = 'UpperCenter' # reset view to fit data renderView1.ResetCamera() # pv.Render() # save screen shot viewLayout1 = pv.GetLayout() print(saveAs) pv.SaveScreenshot(saveAs, layout=viewLayout1, magnification=1, quality=100) # clean up # pv.Delete(box) pv.Delete(glyph) pv.Delete(p) pv.Delete(c1) del c1 del p del glyph
def Save_PV_data_to_picture_file(inputFileName, field_name, node_or_cell,outputFileName ): pvs._DisableFirstRenderCameraReset() #pvs.HideAll(view=None)#Not available in paraview 5.1.2 view = pvs.GetActiveView() sources = pvs.GetSources().values() for aSource in sources: pvs.Hide(aSource, view) # create a new 'XML Unstructured Grid Reader' reader = pvs.XMLUnstructuredGridReader(FileName=[inputFileName]) if node_or_cell== 'CELLS': reader.CellArrayStatus = [field_name] elif node_or_cell== 'NODES': reader.PointArrayStatus = [field_name] else: raise ValueError("unknown type : should be CELLS or NODES") # get active view renderView1 = pvs.GetActiveViewOrCreate('RenderView') # uncomment following to set a specific view size # renderView1.ViewSize = [1057, 499] # show data in view display = pvs.Show(reader, renderView1); # trace defaults for the display properties. display.ColorArrayName = [None, ''] display.GlyphType = 'Arrow' display.ScalarOpacityUnitDistance = 0.02234159571242408 # reset view to fit data renderView1.ResetCamera() # set scalar coloring if node_or_cell== 'CELLS': pvs.ColorBy(display, ('CELLS', field_name)) elif node_or_cell== 'NODES': pvs.ColorBy(display, ('POINTS', field_name)) else: raise ValueError("unknown type : should be CELLS or NODES") # rescale color and/or opacity maps used to include current data range display.RescaleTransferFunctionToDataRange(True) # show color bar/color legend display.SetScalarBarVisibility(renderView1, True) pvs.SaveScreenshot(outputFileName+".png", magnification=1, quality=100, view=renderView1) display.SetScalarBarVisibility(renderView1, False) if field_name=='Velocity' : #pvs.HideAll(view=None)#Not available in paraview 5.1.2 view = pvs.GetActiveView() sources = pvs.GetSources().values() for aSource in sources: pvs.Hide(aSource, view) # create a new 'Stream Tracer' streamTracer1 = pvs.StreamTracer(Input=reader, SeedType='Point Source') streamTracer1.Vectors = ['CELLS', 'Velocity'] # init the 'Point Source' selected for 'SeedType' streamTracer1.SeedType.Center = [0.5, 0.5, 0.0] streamTracer1.SeedType.Radius = 0.0 # Properties modified on streamTracer1 streamTracer1.SeedType = 'High Resolution Line Source' # Properties modified on streamTracer1.SeedType streamTracer1.SeedType.Point1 = [0.0, 0.0, 0.0] streamTracer1.SeedType.Point2 = [1.0, 1.0, 0.0] streamTracer1.SeedType.Resolution = 20# Pb : claims attribute Resolution does not exist # show data in view streamTracer1Display = pvs.Show(streamTracer1, renderView1) # create a new 'Stream Tracer' streamTracer2 = pvs.StreamTracer(Input=reader, SeedType='Point Source') streamTracer2.Vectors = ['CELLS', 'Velocity'] # init the 'Point Source' selected for 'SeedType' streamTracer2.SeedType.Center = [0.5, 0.5, 0.0] streamTracer2.SeedType.Radius = 0.0 # Properties modified on streamTracer2 streamTracer2.SeedType = 'High Resolution Line Source' # Properties modified on streamTracer2.SeedType streamTracer2.SeedType.Point1 = [0.0, 1.0, 0.0] streamTracer2.SeedType.Point2 = [1.0, 0.0, 0.0] streamTracer2.SeedType.Resolution = 25# Pb : claims attribute Resolution does not exist # show data in view streamTracer2Display = pvs.Show(streamTracer2, renderView1) pvs.SaveScreenshot(outputFileName+"_streamlines.png", magnification=1, quality=100, view=renderView1) pvs.Delete()
sys.exit(ERR_BAD_NAME) sys.path.append(interface_folder) import cgt_objects config = None config_file = PurePath(args.interface_folder) / "visualization_config.json" with open(config_file) as f: config = json.load(f) assert config is not None #### disable automatic camera reset on 'Show' ps._DisableFirstRenderCameraReset() # get active view view = ps.GetActiveViewOrCreate("RenderView") view.CameraParallelProjection = True # view.ViewSize = [960, 720] input_files = cgt_objects.InputFiles(PurePath(args.input_folder)) visuals = cgt_objects.Visuals(view, config, input_files) # pseudocode # determine load strategy # try .data # fail? try extension # fail? go to next object # try load object # fail? go to next object # determine vis strategy # use combination of .data and .type
def initialize(self): # Bring used components self.registerVtkWebProtocol(pv_protocols.ParaViewWebMouseHandler()) self.registerVtkWebProtocol(pv_protocols.ParaViewWebViewPort()) self.registerVtkWebProtocol( pv_protocols.ParaViewWebViewPortImageDelivery()) self.registerVtkWebProtocol(amsProtocol()) self.updateSecret(_DemoServer.authKey) # Disable interactor-based render calls simple.GetRenderView().EnableRenderOnInteraction = 0 simple.GetRenderView().Background = [0, 0, 0] #cone = simple.Cone() #simple.Show(cone) # create a new 'EnSight Reader' #### disable automatic camera reset on 'Show' #paraview.simple._DisableFirstRenderCameraReset() # create a new 'EnSight Reader' matvizmofTFF90L91lpm100rpmcase = simple.EnSightReader( CaseFileName= '/Users/tomfool/tech/18/amgen/ams-102-AgileViz/EnSight/mat-viz-mofTFF-90L-9.1lpm-100rpm/mat-viz-mofTFF-90L-9.1lpm-100rpm.case' ) matvizmofTFF90L91lpm100rpmcase.PointArrays = [ 'pressure', 'pressure_coefficient', 'dynamic_pressure', 'absolute_pressure', 'total_pressure', 'rel_total_pressure', 'density', 'density_all', 'velocity_magnitude', 'x_velocity', 'y_velocity', 'z_velocity', 'axial_velocity', 'radial_velocity', 'tangential_velocity', 'rel_velocity_magnitude', 'relative_x_velocity', 'relative_y_velocity', 'relative_z_velocity', 'rel_tangential_velocity', 'mesh_x_velocity', 'mesh_y_velocity', 'mesh_z_velocity', 'velocity_angle', 'relative_velocity_angle', 'vorticity_mag', 'helicity', 'x_vorticity', 'y_vorticity', 'z_vorticity', 'cell_reynolds_number', 'turb_kinetic_energy', 'turb_intensity', 'turb_diss_rate', 'production_of_k', 'viscosity_turb', 'viscosity_eff', 'viscosity_ratio', 'y_star', 'y_plus', 'uds_0_scalar', 'uds_0_diff_scalar', 'viscosity_lam', 'wall_shear', 'x_wall_shear', 'y_wall_shear', 'z_wall_shear', 'skin_friction_coef', 'cell_partition_active', 'cell_partition_stored', 'cell_id', 'cell_element_type', 'cell_type', 'cell_zone', 'partition_neighbors', 'cell_weight', 'x_coordinate', 'y_coordinate', 'z_coordinate', 'axial_coordinate', 'angular_coordinate', 'abs_angular_coordinate', 'radial_coordinate', 'face_area_magnitude', 'x_face_area', 'y_face_area', 'z_face_area', 'cell_volume', 'orthogonal_quality', 'cell_equiangle_skew', 'cell_equivolume_skew', 'face_handedness', 'mark_poor_elememts', 'interface_overlap_fraction', 'cell_wall_distance', 'adaption_function', 'adaption_curvature', 'adaption_space_gradient', 'adaption_iso_value', 'boundary_cell_dist', 'boundary_normal_dist', 'cell_volume_change', 'cell_surface_area', 'cell_warp', 'cell_children', 'cell_refine_level', 'mass_imbalance', 'strain_rate_mag', 'dx_velocity_dx', 'dy_velocity_dx', 'dz_velocity_dx', 'dx_velocity_dy', 'dy_velocity_dy', 'dz_velocity_dy', 'dx_velocity_dz', 'dy_velocity_dz', 'dz_velocity_dz', 'dp_dx', 'dp_dy', 'dp_dz', 'velocity' ] # get active view renderView1 = simple.GetActiveViewOrCreate('RenderView') # uncomment following to set a specific view size # renderView1.ViewSize = [1638, 1076] # show data in view matvizmofTFF90L91lpm100rpmcaseDisplay = simple.Show( matvizmofTFF90L91lpm100rpmcase, renderView1) # get color transfer function/color map for 'pressure' pressureLUT = simple.GetColorTransferFunction('pressure') # get opacity transfer function/opacity map for 'pressure' pressurePWF = simple.GetOpacityTransferFunction('pressure') # trace defaults for the display properties. matvizmofTFF90L91lpm100rpmcaseDisplay.Representation = 'Surface' matvizmofTFF90L91lpm100rpmcaseDisplay.ColorArrayName = [ 'POINTS', 'pressure' ] matvizmofTFF90L91lpm100rpmcaseDisplay.LookupTable = pressureLUT matvizmofTFF90L91lpm100rpmcaseDisplay.OSPRayScaleArray = 'pressure' matvizmofTFF90L91lpm100rpmcaseDisplay.OSPRayScaleFunction = 'PiecewiseFunction' matvizmofTFF90L91lpm100rpmcaseDisplay.SelectOrientationVectors = 'velocity' matvizmofTFF90L91lpm100rpmcaseDisplay.ScaleFactor = 0.07445502169430256 matvizmofTFF90L91lpm100rpmcaseDisplay.SelectScaleArray = 'pressure' matvizmofTFF90L91lpm100rpmcaseDisplay.GlyphType = 'Arrow' matvizmofTFF90L91lpm100rpmcaseDisplay.GlyphTableIndexArray = 'pressure' matvizmofTFF90L91lpm100rpmcaseDisplay.GaussianRadius = 0.03722751084715128 matvizmofTFF90L91lpm100rpmcaseDisplay.SetScaleArray = [ 'POINTS', 'pressure' ] matvizmofTFF90L91lpm100rpmcaseDisplay.ScaleTransferFunction = 'PiecewiseFunction' matvizmofTFF90L91lpm100rpmcaseDisplay.OpacityArray = [ 'POINTS', 'pressure' ] matvizmofTFF90L91lpm100rpmcaseDisplay.OpacityTransferFunction = 'PiecewiseFunction' matvizmofTFF90L91lpm100rpmcaseDisplay.DataAxesGrid = 'GridAxesRepresentation' matvizmofTFF90L91lpm100rpmcaseDisplay.SelectionCellLabelFontFile = '' matvizmofTFF90L91lpm100rpmcaseDisplay.SelectionPointLabelFontFile = '' matvizmofTFF90L91lpm100rpmcaseDisplay.PolarAxes = 'PolarAxesRepresentation' matvizmofTFF90L91lpm100rpmcaseDisplay.ScalarOpacityFunction = pressurePWF matvizmofTFF90L91lpm100rpmcaseDisplay.ScalarOpacityUnitDistance = 0.007476863260594431 # init the 'PiecewiseFunction' selected for 'ScaleTransferFunction' matvizmofTFF90L91lpm100rpmcaseDisplay.ScaleTransferFunction.Points = [ -152.6022491455078, 0.0, 0.5, 0.0, 144.73870849609375, 1.0, 0.5, 0.0 ] # init the 'PiecewiseFunction' selected for 'OpacityTransferFunction' matvizmofTFF90L91lpm100rpmcaseDisplay.OpacityTransferFunction.Points = [ -152.6022491455078, 0.0, 0.5, 0.0, 144.73870849609375, 1.0, 0.5, 0.0 ] # init the 'GridAxesRepresentation' selected for 'DataAxesGrid' matvizmofTFF90L91lpm100rpmcaseDisplay.DataAxesGrid.XTitleFontFile = '' matvizmofTFF90L91lpm100rpmcaseDisplay.DataAxesGrid.YTitleFontFile = '' matvizmofTFF90L91lpm100rpmcaseDisplay.DataAxesGrid.ZTitleFontFile = '' matvizmofTFF90L91lpm100rpmcaseDisplay.DataAxesGrid.XLabelFontFile = '' matvizmofTFF90L91lpm100rpmcaseDisplay.DataAxesGrid.YLabelFontFile = '' matvizmofTFF90L91lpm100rpmcaseDisplay.DataAxesGrid.ZLabelFontFile = '' # init the 'PolarAxesRepresentation' selected for 'PolarAxes' matvizmofTFF90L91lpm100rpmcaseDisplay.PolarAxes.PolarAxisTitleFontFile = '' matvizmofTFF90L91lpm100rpmcaseDisplay.PolarAxes.PolarAxisLabelFontFile = '' matvizmofTFF90L91lpm100rpmcaseDisplay.PolarAxes.LastRadialAxisTextFontFile = '' matvizmofTFF90L91lpm100rpmcaseDisplay.PolarAxes.SecondaryRadialAxesTextFontFile = '' # reset view to fit data renderView1.ResetCamera() # show color bar/color legend matvizmofTFF90L91lpm100rpmcaseDisplay.SetScalarBarVisibility( renderView1, True) # update the view to ensure updated data information renderView1.Update() # hide data in view simple.Hide(matvizmofTFF90L91lpm100rpmcase, renderView1) # create a new 'Contour' contour1 = simple.Contour(Input=matvizmofTFF90L91lpm100rpmcase) contour1.ContourBy = ['POINTS', 'pressure'] contour1.Isosurfaces = [-3.9317703247070312] contour1.PointMergeMethod = 'Uniform Binning' # Properties modified on contour1 contour1.ContourBy = ['POINTS', 'uds_0_scalar'] contour1.Isosurfaces = [480.0, 570.0] # show data in view contour1Display = simple.Show(contour1, renderView1) # trace defaults for the display properties. contour1Display.Representation = 'Surface' contour1Display.ColorArrayName = ['POINTS', 'pressure'] contour1Display.LookupTable = pressureLUT contour1Display.OSPRayScaleArray = 'Normals' contour1Display.OSPRayScaleFunction = 'PiecewiseFunction' contour1Display.SelectOrientationVectors = 'velocity' contour1Display.ScaleFactor = 0.07228952534496784 contour1Display.SelectScaleArray = 'None' contour1Display.GlyphType = 'Arrow' contour1Display.GlyphTableIndexArray = 'None' contour1Display.GaussianRadius = 0.03614476267248392 contour1Display.SetScaleArray = ['POINTS', 'Normals'] contour1Display.ScaleTransferFunction = 'PiecewiseFunction' contour1Display.OpacityArray = ['POINTS', 'Normals'] contour1Display.OpacityTransferFunction = 'PiecewiseFunction' contour1Display.DataAxesGrid = 'GridAxesRepresentation' contour1Display.SelectionCellLabelFontFile = '' contour1Display.SelectionPointLabelFontFile = '' contour1Display.PolarAxes = 'PolarAxesRepresentation' # init the 'PiecewiseFunction' selected for 'ScaleTransferFunction' contour1Display.ScaleTransferFunction.Points = [ -0.9995924830436707, 0.0, 0.5, 0.0, 0.9998393058776855, 1.0, 0.5, 0.0 ] # init the 'PiecewiseFunction' selected for 'OpacityTransferFunction' contour1Display.OpacityTransferFunction.Points = [ -0.9995924830436707, 0.0, 0.5, 0.0, 0.9998393058776855, 1.0, 0.5, 0.0 ] # init the 'GridAxesRepresentation' selected for 'DataAxesGrid' contour1Display.DataAxesGrid.XTitleFontFile = '' contour1Display.DataAxesGrid.YTitleFontFile = '' contour1Display.DataAxesGrid.ZTitleFontFile = '' contour1Display.DataAxesGrid.XLabelFontFile = '' contour1Display.DataAxesGrid.YLabelFontFile = '' contour1Display.DataAxesGrid.ZLabelFontFile = '' # init the 'PolarAxesRepresentation' selected for 'PolarAxes' contour1Display.PolarAxes.PolarAxisTitleFontFile = '' contour1Display.PolarAxes.PolarAxisLabelFontFile = '' contour1Display.PolarAxes.LastRadialAxisTextFontFile = '' contour1Display.PolarAxes.SecondaryRadialAxesTextFontFile = '' # reset view to fit data renderView1.ResetCamera() # hide data in view simple.Hide(matvizmofTFF90L91lpm100rpmcase, renderView1) # show color bar/color legend contour1Display.SetScalarBarVisibility(renderView1, True) # update the view to ensure updated data information renderView1.Update() # set scalar coloring simple.ColorBy(contour1Display, ('POINTS', 'velocity_magnitude')) # rescale color and/or opacity maps used to include current data range contour1Display.RescaleTransferFunctionToDataRange(True, False) # show color bar/color legend contour1Display.SetScalarBarVisibility(renderView1, True) # get color transfer function/color map for 'velocity_magnitude' velocity_magnitudeLUT = simple.GetColorTransferFunction( 'velocity_magnitude') #### saving camera placements for all active views # current camera placement for renderView1 renderView1.CameraPosition = [ 1.3051878628081257, -1.32358496378265, -0.017141331493847792 ] renderView1.CameraFocalPoint = [ -0.052487090229988105, 0.03264869749546056, -0.3026974257081747 ] renderView1.CameraViewUp = [ -0.5051031518286454, -0.33848038039346323, 0.7939155106820026 ] renderView1.CameraParallelScale = 0.5021485229089222 #### uncomment the following to render all views # RenderAllViews() # alternatively, if you want to write images, you can use SaveScreenshot(...). ### OLD FOLLOWS simple.Render() # Update interaction mode pxm = simple.servermanager.ProxyManager() interactionProxy = pxm.GetProxy('settings', 'RenderViewInteractionSettings') print(dir(interactionProxy)) interactionProxy.Camera3DManipulators = [ 'Rotate', 'Pan', 'Zoom', 'Pan', 'Roll', 'Pan', 'Zoom', 'Rotate', 'Zoom' ] print("done with initialize()")
def StreamlinesScript(Input1, Input2, Output, N1=None, N2=None, Offset1=0.0, Offset2=0.0, CamDirVec=None, CamUpVec=None, Origin=None): ''' Creates an image with the streamlines from two VTUs. Inputs: Input1 - VTU with first direction of curvatures Input2 - VTU with second direction of curvatures N1 - List of normal of slice for VTU1 N2 - List of normal of slice for VTU2 Offset1 - Value of offset for slice of VTU1 Offset2 - Value of offset for slice of VTU2 CamDirVec - Vector for camera direction CamUpVec - Vector for camera up direction Origin - Vector with the position for the origin''' #### disable automatic camera reset on 'Show' pvs._DisableFirstRenderCameraReset() # create a new 'XML Unstructured Grid Reader' VTU1 = pvs.XMLUnstructuredGridReader(FileName=[Input1]) VTU1.PointArrayStatus = ['Curvature'] ## Fix data for Slices if N1 is None: N1 = [0.9, 0.4, 0.2] if N2 is None: # N2 = np.cross(N1,[0,0,1]) N2 = [-0.8, 0.5, 0.16] if Origin is None: Origin = paraview.servermanager.Fetch( pvs.IntegrateVariables(Input=VTU1)).GetPoint(0) # create a new 'XML Unstructured Grid Reader' VTU2 = pvs.XMLUnstructuredGridReader(FileName=[Input2]) VTU2.PointArrayStatus = ['Curvature'] # get active view renderView1 = pvs.GetActiveViewOrCreate('RenderView') # show data in view VTU1Display = pvs.Show(VTU1, renderView1) VTU1Display.Representation = 'Surface' VTU1Display.Diffuse = 0.85 VTU1Display.Ambient = 0.25 # show data in view VTU2Display = pvs.Show(VTU2, renderView1) VTU2Display.Representation = 'Surface' VTU2Display.Diffuse = 0.85 VTU2Display.Ambient = 0.25 # create a new 'Slice' slice1 = pvs.Slice(Input=VTU1) slice1.SliceType.Origin = Origin slice1.SliceType.Normal = N1 slice1.SliceType.Offset = 0.0 slice1.SliceOffsetValues = [Offset1] # create a new 'Slice' slice2 = pvs.Slice(Input=VTU2) slice2.SliceType.Origin = Origin slice2.SliceType.Normal = N2 slice2.SliceType.Offset = 0.0 slice2.SliceOffsetValues = [Offset2] # make stremlines makestream(VTU1, slice1, renderView1, [1.0, 0.0, 0.0]) makestream(VTU2, slice2, renderView1, [0.0, 0.0, 1.0]) # Save Screenshot AdjustCameraAndSave(renderView1, Output, ImageResolution=(2048, 2048), CamDirVec=CamDirVec, CamUpVec=CamUpVec) # set active source pvs.SetActiveSource(None) pvs.SetActiveView(None) pvs.Disconnect()
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