def execute(self, doc): """tells ParaView to color the object we've been assigned using the color definition we've been given that corresponds to the value we've been assigned to watch in the doc.descriptor""" if self.parameter not in doc.descriptor: return if self.rep is None: return o = doc.descriptor[self.parameter] spec = self.colorlist.getColor(o) if spec['type'] == 'rgb': self.rep.DiffuseColor = spec['content'] self.rep.ColorArrayName = None if self.imageExplorer: self.imageExplorer.setDrawMode('color') if spec['type'] == 'lut': aname = spec['name'] aname = aname[0:aname.rfind("_")] simple.ColorBy(self.rep, (spec['field'], aname, spec['comp'])) if self.imageExplorer: self.imageExplorer.setDrawMode('color') if spec['type'] == 'depth': if self.imageExplorer: self.imageExplorer.setDrawMode('depth') if spec['type'] == 'luminance': if self.imageExplorer: self.imageExplorer.setDrawMode('luminance') if spec['type'] == 'value': if self.imageExplorer: self.imageExplorer.setDrawMode("value", field=spec['field'], name=spec['arrayname'], component=spec['component'], range=spec['range'])
def writeLightArray(self, path, source): rep = simple.Show(source, self.view) rep.Representation = 'Surface' rep.DiffuseColor = [1, 1, 1] simple.ColorBy(rep, ('POINTS', None)) # Grab data tmpFileName = path + '__.png' self.view.LockBounds = 1 simple.SaveScreenshot(tmpFileName, self.view) self.view.LockBounds = 0 if self.canWrite: # Convert data self.reader.SetFileName(tmpFileName) self.reader.Update() rgbArray = self.reader.GetOutput().GetPointData().GetArray(0) arraySize = rgbArray.GetNumberOfTuples() rawArray = vtkUnsignedCharArray() rawArray.SetNumberOfTuples(arraySize) for idx in range(arraySize): light = rgbArray.GetTuple3(idx)[0] rawArray.SetTuple1(idx, light) with open(path, 'wb') as f: f.write(buffer(rawArray)) # Delete temporary file if self.cleanAfterMe: os.remove(tmpFileName) simple.Hide(source, self.view)
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 modifyImage(): if (toggle): print("drawing.....") # set scalar coloring simple.ColorBy(contour1Display, ('POINTS', 'pressure')) # rescale color and/or opacity maps used to include current data range contour1Display.RescaleTransferFunctionToDataRange(True, False) else: print("changing back......") # 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) self.toggle = not self.toggle
def show(self, key_array="x_velocity", source=None, rescale=False): """Show the rendered output on the screen.""" Input = source if source else self.nek5000 display = pv.Show(Input, self.renderView1) pv.ColorBy(display, ("POINTS", key_array)) if rescale: display.RescaleTransferFunctionToDataRange(True, False) display.SetScalarBarVisibility(source, True) # ... lot of parameters are possible here pv.SetActiveSource(source) try: LUT = pv.GetColorTransferFunction(key_array) PWF = pv.GetOpacityTransferFunction(key_array) except AttributeError: pass return display
def updateEventCb(self, obj, event): name = self._getSourceToExtractName(obj) if not self.source: self.source = simple.FindSource(name) simple.SetActiveSource(self.source) if self.source and not self.rep: self.outline = simple.Outline(self.source) self.rep = simple.Show(self.source) self.outline.UpdatePipeline() self.outlineRep = simple.Show(self.outline) # TODO: this is for the demo # TODO: what would be the best way to change sources and representations from the client ? # create a protocol for liveInsituLink.GetInsituProxyManager() ? # or setActiveSource endpoint ? # or is there a better way ? info = self.source.GetPointDataInformation() if info.GetNumberOfArrays() > 0: arrName = info.GetArray(0).Name self.rep.ColorArrayName = ['POINTS', arrName] simple.ColorBy(self.rep, arrName) # Point gaussian props = simple.GetDisplayProperties(self.source) props.SetRepresentationType('Point Gaussian') props.GaussianRadius = 0.01
def colorBy(self, representation, field): view = self.viewSubSurface if representation == self.subSurfaceRepresentation else self.viewSurface representation.SetScalarBarVisibility(view, False) simple.ColorBy(representation, ['CELLS', field]) applyColorMap(representation) representation.SetScalarBarVisibility(view, True) lut = simple.GetColorTransferFunction(field) colorBar = simple.GetScalarBar(lut, view) colorBar.Enabled = 1 colorBar.Selectable = 0 colorBar.AutoOrient = 0 colorBar.AutomaticLabelFormat = 1 colorBar.AddRangeLabels = 0 colorBar.ScalarBarLength = 0.9 colorBar.LabelColor = [0, 0, 0] colorBar.Position = [0.8, 0.05] colorBar.LockPosition = 1 colorBar.Repositionable = 1 colorBar.Resizable = 1 colorBar.TitleColor = [0, 0, 0]
def main(): import paraview.simple as para version_major = para.servermanager.vtkSMProxyManager.GetVersionMajor() source = para.GetActiveSource() renderView1 = para.GetRenderView() atoms = para.Glyph( Input=source, GlyphType='Sphere', Scalars='radii', ScaleMode='scalar', ) para.RenameSource('Atoms', atoms) atomsDisplay = para.Show(atoms, renderView1) if version_major <= 4: atoms.SetScaleFactor = 0.8 atomicnumbers_PVLookupTable = para.GetLookupTableForArray( 'atomic numbers', 1) atomsDisplay.ColorArrayName = ('POINT_DATA', 'atomic numbers') atomsDisplay.LookupTable = atomicnumbers_PVLookupTable else: atoms.ScaleFactor = 0.8 para.ColorBy(atomsDisplay, 'atomic numbers') atomsDisplay.SetScalarBarVisibility(renderView1, True) para.Render()
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()
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
# create a calculator to compute distance calculator1 = simple.Calculator(Input=source) calculator1.ResultArrayName = 'Distance' calculator1.Function = 'mag(coords)' # create another calculator to compute inverse distance calculator2 = simple.Calculator(Input=calculator1) calculator2.ResultArrayName = 'Inverse Distance' calculator2.Function = '%s-Distance' % str(NUM_POINTS - 1) # Get the representation rep = simple.Show(calculator2) # Set up coloring by one array rep.Representation = 'Point Gaussian' simple.ColorBy(rep, ('POINTS', 'Ordinal')) vtkSMPVRepresentationProxy.RescaleTransferFunctionToDataRange( rep.SMProxy, 'Ordinal', 0, False) # Set up sizing by another array scaleTransferFunction = simple.CreatePiecewiseFunction( Points=[0.0, 0.05, 0.5, 0.0, NUM_POINTS - 1, 0.15, 0.5, 0.0]) rep.ScaleTransferFunction = scaleTransferFunction rep.SetScaleArray = 'Distance' rep.ScaleByArray = 1 rep.GaussianRadius = 1 # And finally, set up opacity by a third array opacityTransferFunction = simple.CreatePiecewiseFunction( Points=[0.0, 0.2, 0.5, 0.0, NUM_POINTS - 1, 1.0, 0.5, 0.0]) rep.OpacityTransferFunction = opacityTransferFunction
"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', magnification=1, quality=100, view=lineChartView2)
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 render_frames( scene, frames_dir=None, frame_window=None, render_missing_frames=False, save_state_to_file=None, no_render=False, show_preview=False, show_progress=False, job_id=None, ): # Validate scene if scene["View"]["ViewSize"][0] % 16 != 0: logger.warning( "The view width should be a multiple of 16 to be compatible with" " QuickTime.") if scene["View"]["ViewSize"][1] % 2 != 0: logger.warning( "The view height should be even to be compatible with QuickTime.") render_start_time = time.time() # Setup layout layout = pv.CreateLayout("Layout") # Setup view if "Background" in scene["View"]: bg_config = scene["View"]["Background"] del scene["View"]["Background"] if isinstance(bg_config, list): if isinstance(bg_config[0], list): assert len(bg_config) == 2, ( "When 'Background' is a list of colors, it must have 2" " entries.") bg_config = dict( BackgroundColorMode="Gradient", Background=parse_as.color(bg_config[0]), Background2=parse_as.color(bg_config[1]), ) else: bg_config = dict( BackgroundColorMode="Single Color", Background=parse_as.color(bg_config), ) bg_config["UseColorPaletteForBackground"] = 0 scene["View"].update(bg_config) bg_config = None else: bg_config = None view = pv.CreateRenderView(**scene["View"]) pv.AssignViewToLayout(view=view, layout=layout, hint=0) # Set spherical background texture if bg_config is not None: bg_config["BackgroundColorMode"] = "Texture" skybox_datasource = bg_config["Datasource"] del bg_config["Datasource"] background_texture = pvserver.rendering.ImageTexture( FileName=parse_as.path(scene["Datasources"][skybox_datasource])) background_sphere = pv.Sphere(Radius=bg_config["Radius"], ThetaResolution=100, PhiResolution=100) background_texture_map = pv.TextureMaptoSphere(Input=background_sphere) pv.Show( background_texture_map, view, Texture=background_texture, BackfaceRepresentation="Cull Frontface", Ambient=1.0, ) # Load the waveform data file waveform_h5file, waveform_subfile = parse_as.file_and_subfile( scene["Datasources"]["Waveform"]) waveform_data = WaveformDataReader(FileName=waveform_h5file, Subfile=waveform_subfile) pv.UpdatePipeline() # Generate volume data from the waveform. Also sets the available time range. # TODO: Pull KeepEveryNthTimestep out of datasource waveform_to_volume_configs = scene["WaveformToVolume"] if isinstance(waveform_to_volume_configs, dict): waveform_to_volume_configs = [{ "Object": waveform_to_volume_configs, }] if "VolumeRepresentation" in scene: waveform_to_volume_configs[0]["VolumeRepresentation"] = scene[ "VolumeRepresentation"] waveform_to_volume_objects = [] for waveform_to_volume_config in waveform_to_volume_configs: volume_data = WaveformToVolume( WaveformData=waveform_data, SwshCacheDirectory=parse_as.path( scene["Datasources"]["SwshCache"]), **waveform_to_volume_config["Object"], ) if "Modes" in waveform_to_volume_config["Object"]: volume_data.Modes = waveform_to_volume_config["Object"]["Modes"] if "Polarizations" in waveform_to_volume_config["Object"]: volume_data.Polarizations = waveform_to_volume_config["Object"][ "Polarizations"] waveform_to_volume_objects.append(volume_data) # Compute timing and frames information time_range_in_M = ( volume_data.TimestepValues[0], volume_data.TimestepValues[-1], ) logger.debug(f"Full available data time range: {time_range_in_M} (in M)") if "FreezeTime" in scene["Animation"]: frozen_time = scene["Animation"]["FreezeTime"] logger.info(f"Freezing time at {frozen_time}.") view.ViewTime = frozen_time animation = None else: if "Crop" in scene["Animation"]: time_range_in_M = scene["Animation"]["Crop"] logger.debug(f"Cropping time range to {time_range_in_M} (in M).") animation_speed = scene["Animation"]["Speed"] frame_rate = scene["Animation"]["FrameRate"] num_frames = animate.num_frames( max_animation_length=time_range_in_M[1] - time_range_in_M[0], animation_speed=animation_speed, frame_rate=frame_rate, ) animation_length_in_seconds = num_frames / frame_rate animation_length_in_M = animation_length_in_seconds * animation_speed time_per_frame_in_M = animation_length_in_M / num_frames logger.info(f"Rendering {animation_length_in_seconds:.2f}s movie with" f" {num_frames} frames ({frame_rate} FPS or" f" {animation_speed:.2e} M/s or" f" {time_per_frame_in_M:.2e} M/frame)...") if frame_window is not None: animation_window_num_frames = frame_window[1] - frame_window[0] animation_window_time_range = ( time_range_in_M[0] + frame_window[0] * time_per_frame_in_M, time_range_in_M[0] + (frame_window[1] - 1) * time_per_frame_in_M, ) logger.info( f"Restricting rendering to {animation_window_num_frames} frames" f" (numbers {frame_window[0]} to {frame_window[1] - 1}).") else: animation_window_num_frames = num_frames animation_window_time_range = time_range_in_M frame_window = (0, num_frames) # Setup animation so that sources can retrieve the `UPDATE_TIME_STEP` animation = pv.GetAnimationScene() # animation.UpdateAnimationUsingDataTimeSteps() # Since the data can be evaluated at arbitrary times we define the time steps # here by setting the number of frames within the full range animation.PlayMode = "Sequence" animation.StartTime = animation_window_time_range[0] animation.EndTime = animation_window_time_range[1] animation.NumberOfFrames = animation_window_num_frames logger.debug( f"Animating from scene time {animation.StartTime} to" f" {animation.EndTime} in {animation.NumberOfFrames} frames.") def scene_time_from_real(real_time): return (real_time / animation_length_in_seconds * animation_length_in_M) # For some reason the keyframe time for animations is expected to be within # (0, 1) so we need to transform back and forth from this "normalized" time def scene_time_from_normalized(normalized_time): return animation.StartTime + normalized_time * ( animation.EndTime - animation.StartTime) def normalized_time_from_scene(scene_time): return (scene_time - animation.StartTime) / (animation.EndTime - animation.StartTime) # Setup progress measuring already here so volume data computing for # initial frame is measured if show_progress and not no_render: logging.getLogger().handlers = [TqdmLoggingHandler()] animation_window_frame_range = tqdm.trange( animation_window_num_frames, desc="Rendering", unit="frame", miniters=1, position=job_id, ) else: animation_window_frame_range = range(animation_window_num_frames) # Set the initial time step animation.GoToFirst() # Display the volume data. This will trigger computing the volume data at the # current time step. for volume_data, waveform_to_volume_config in zip( waveform_to_volume_objects, waveform_to_volume_configs): vol_repr = (waveform_to_volume_config["VolumeRepresentation"] if "VolumeRepresentation" in waveform_to_volume_config else {}) volume_color_by = config_color.extract_color_by(vol_repr) if (vol_repr["VolumeRenderingMode"] == "GPU Based" and len(volume_color_by) > 2): logger.warning( "The 'GPU Based' volume renderer doesn't support multiple" " components.") volume = pv.Show(volume_data, view, **vol_repr) pv.ColorBy(volume, value=volume_color_by) if "Slices" in scene: for slice_config in scene["Slices"]: slice_obj_config = slice_config.get("Object", {}) slice = pv.Slice(Input=volume_data) slice.SliceType = "Plane" slice.SliceOffsetValues = [0.0] slice.SliceType.Origin = slice_obj_config.get( "Origin", [0.0, 0.0, -0.3]) slice.SliceType.Normal = slice_obj_config.get( "Normal", [0.0, 0.0, 1.0]) slice_rep = pv.Show(slice, view, **slice_config.get("Representation", {})) pv.ColorBy(slice_rep, value=volume_color_by) # Display the time if "TimeAnnotation" in scene: time_annotation = pv.AnnotateTimeFilter(volume_data, **scene["TimeAnnotation"]) pv.Show(time_annotation, view, **scene["TimeAnnotationRepresentation"]) # Add spheres if "Spheres" in scene: for sphere_config in scene["Spheres"]: sphere = pv.Sphere(**sphere_config["Object"]) pv.Show(sphere, view, **sphere_config["Representation"]) # Add trajectories and objects that follow them if "Trajectories" in scene: for trajectory_config in scene["Trajectories"]: trajectory_name = trajectory_config["Name"] radial_scale = (trajectory_config["RadialScale"] if "RadialScale" in trajectory_config else 1.0) # Load the trajectory data traj_data_reader = TrajectoryDataReader( RadialScale=radial_scale, **scene["Datasources"]["Trajectories"][trajectory_name], ) # Make sure the data is loaded so we can retrieve timesteps. # TODO: This should be fixed in `TrajectoryDataReader` by # communicating time range info down the pipeline, but we had issues # with that (see also `WaveformDataReader`). traj_data_reader.UpdatePipeline() if "Objects" in trajectory_config: with animate.restore_animation_state(animation): follow_traj = FollowTrajectory( TrajectoryData=traj_data_reader) for traj_obj_config in trajectory_config["Objects"]: for traj_obj_key in traj_obj_config: if traj_obj_key in [ "Representation", "Visibility", "TimeShift", "Glyph", ]: continue traj_obj_type = getattr(pv, traj_obj_key) traj_obj_glyph = traj_obj_type( **traj_obj_config[traj_obj_key]) follow_traj.UpdatePipeline() traj_obj = pv.Glyph(Input=follow_traj, GlyphType=traj_obj_glyph) # Can't set this in the constructor for some reason traj_obj.ScaleFactor = 1.0 for glyph_property in (traj_obj_config["Glyph"] if "Glyph" in traj_obj_config else []): setattr( traj_obj, glyph_property, traj_obj_config["Glyph"][glyph_property], ) traj_obj.UpdatePipeline() if "TimeShift" in traj_obj_config: traj_obj = animate.apply_time_shift( traj_obj, traj_obj_config["TimeShift"]) pv.Show(traj_obj, view, **traj_obj_config["Representation"]) if "Visibility" in traj_obj_config: animate.apply_visibility( traj_obj, traj_obj_config["Visibility"], normalized_time_from_scene, scene_time_from_real, ) if "Tail" in trajectory_config: with animate.restore_animation_state(animation): traj_tail = TrajectoryTail(TrajectoryData=traj_data_reader) if "TimeShift" in trajectory_config: traj_tail = animate.apply_time_shift( traj_tail, trajectory_config["TimeShift"]) tail_config = trajectory_config["Tail"] traj_color_by = config_color.extract_color_by(tail_config) if "Visibility" in tail_config: tail_visibility_config = tail_config["Visibility"] del tail_config["Visibility"] else: tail_visibility_config = None tail_rep = pv.Show(traj_tail, view, **tail_config) pv.ColorBy(tail_rep, value=traj_color_by) if tail_visibility_config is not None: animate.apply_visibility( traj_tail, tail_visibility_config, normalized_time_from_scene=normalized_time_from_scene, scene_time_from_real=scene_time_from_real, ) if "Move" in trajectory_config: move_config = trajectory_config["Move"] logger.debug( f"Animating '{move_config['guiName']}' along trajectory.") with h5py.File(trajectory_file, "r") as traj_data_file: trajectory_data = np.array( traj_data_file[trajectory_subfile]) if radial_scale != 1.0: trajectory_data[:, 1:] *= radial_scale logger.debug(f"Trajectory data shape: {trajectory_data.shape}") animate.follow_path( gui_name=move_config["guiName"], trajectory_data=trajectory_data, num_keyframes=move_config["NumKeyframes"], scene_time_range=time_range_in_M, normalized_time_from_scene=normalized_time_from_scene, ) # Add non-spherical horizon shapes (instead of spherical objects following # trajectories) if "Horizons" in scene: for horizon_config in scene["Horizons"]: with animate.restore_animation_state(animation): horizon = pv.PVDReader(FileName=scene["Datasources"] ["Horizons"][horizon_config["Name"]]) if horizon_config.get("InterpolateTime", False): horizon = pv.TemporalInterpolator( Input=horizon, DiscreteTimeStepInterval=0) if "TimeShift" in horizon_config: horizon = animate.apply_time_shift(horizon, horizon_config["TimeShift"], animation) # Try to make horizon surfaces smooth. At low angular resoluton # they still show artifacts, so perhaps more can be done. horizon = pv.ExtractSurface(Input=horizon) horizon = pv.GenerateSurfaceNormals(Input=horizon) horizon_rep_config = horizon_config.get("Representation", {}) if "Representation" not in horizon_rep_config: horizon_rep_config["Representation"] = "Surface" if "AmbientColor" not in horizon_rep_config: horizon_rep_config["AmbientColor"] = [0.0, 0.0, 0.0] if "DiffuseColor" not in horizon_rep_config: horizon_rep_config["DiffuseColor"] = [0.0, 0.0, 0.0] if "Specular" not in horizon_rep_config: horizon_rep_config["Specular"] = 0.2 if "SpecularPower" not in horizon_rep_config: horizon_rep_config["SpecularPower"] = 10 if "SpecularColor" not in horizon_rep_config: horizon_rep_config["SpecularColor"] = [1.0, 1.0, 1.0] if "ColorBy" in horizon_rep_config: horizon_color_by = config_color.extract_color_by( horizon_rep_config) else: horizon_color_by = None horizon_rep = pv.Show(horizon, view, **horizon_rep_config) if horizon_color_by is not None: pv.ColorBy(horizon_rep, value=horizon_color_by) # Animate visibility if "Visibility" in horizon_config: animate.apply_visibility( horizon, horizon_config["Visibility"], normalized_time_from_scene=normalized_time_from_scene, scene_time_from_real=scene_time_from_real, ) if "Contours" in horizon_config: for contour_config in horizon_config["Contours"]: contour = pv.Contour(Input=horizon, **contour_config["Object"]) contour_rep = pv.Show(contour, view, **contour_config["Representation"]) pv.ColorBy(contour_rep, None) if "Visibility" in horizon_config: animate.apply_visibility( contour, horizon_config["Visibility"], normalized_time_from_scene= normalized_time_from_scene, scene_time_from_real=scene_time_from_real, ) # Configure transfer functions if "TransferFunctions" in scene: for tf_config in scene["TransferFunctions"]: colored_field = tf_config["Field"] transfer_fctn = pv.GetColorTransferFunction(colored_field) opacity_fctn = pv.GetOpacityTransferFunction(colored_field) tf.configure_transfer_function(transfer_fctn, opacity_fctn, tf_config["TransferFunction"]) # Save state file before configuring camera keyframes. # TODO: Make camera keyframes work with statefile if save_state_to_file is not None: pv.SaveState(save_state_to_file + ".pvsm") # Camera shots # TODO: Make this work with freezing time while the camera is swinging if animation is None: for i, shot in enumerate(scene["CameraShots"]): if (i == len(scene["CameraShots"]) - 1 or (shot["Time"] if "Time" in shot else 0.0) >= view.ViewTime): camera_motion.apply(shot) break else: camera_motion.apply_swings( scene["CameraShots"], scene_time_range=time_range_in_M, scene_time_from_real=scene_time_from_real, normalized_time_from_scene=normalized_time_from_scene, ) # Report time if animation is not None: report_time_cue = pv.PythonAnimationCue() report_time_cue.Script = """ def start_cue(self): pass def tick(self): import paraview.simple as pv import logging logger = logging.getLogger('Animation') scene_time = pv.GetActiveView().ViewTime logger.info(f"Scene time: {scene_time}") def end_cue(self): pass """ animation.Cues.append(report_time_cue) if show_preview and animation is not None: animation.PlayMode = "Real Time" animation.Duration = 10 animation.Play() animation.PlayMode = "Sequence" if no_render: logger.info("No rendering requested. Total time:" f" {time.time() - render_start_time:.2f}s") return if frames_dir is None: raise RuntimeError("Trying to render but `frames_dir` is not set.") if os.path.exists(frames_dir): logger.warning( f"Output directory '{frames_dir}' exists, files may be overwritten." ) else: os.makedirs(frames_dir) if animation is None: pv.Render() pv.SaveScreenshot(os.path.join(frames_dir, "frame.png")) else: # Iterate over frames manually to support filling in missing frames. # If `pv.SaveAnimation` would support that, here's how it could be # invoked: # pv.SaveAnimation( # os.path.join(frames_dir, 'frame.png'), # view, # animation, # FrameWindow=frame_window, # SuffixFormat='.%06d') # Note that `FrameWindow` appears to be buggy, so we set up the # `animation` according to the `frame_window` above so the frame files # are numberd correctly. for animation_window_frame_i in animation_window_frame_range: frame_i = frame_window[0] + animation_window_frame_i frame_file = os.path.join(frames_dir, f"frame.{frame_i:06d}.png") if render_missing_frames and os.path.exists(frame_file): continue logger.debug(f"Rendering frame {frame_i}...") animation.AnimationTime = ( animation.StartTime + time_per_frame_in_M * animation_window_frame_i) pv.Render() pv.SaveScreenshot(frame_file) logger.info(f"Rendered frame {frame_i}.") logger.info( f"Rendering done. Total time: {time.time() - render_start_time:.2f}s")
def writeArray(self, path, source, name, component=0): rep = simple.Show(source, self.view) rep.Representation = 'Surface' rep.DiffuseColor = [1, 1, 1] dataRange = [0.0, 1.0] fieldToColorBy = ['POINTS', name] self.view.ArrayNameToDraw = name self.view.ArrayComponentToDraw = component pdi = source.GetPointDataInformation() cdi = source.GetCellDataInformation() if pdi.GetArray(name): self.view.DrawCells = 0 dataRange = pdi.GetArray(name).GetRange(component) fieldToColorBy[0] = 'POINTS' elif cdi.GetArray(name): self.view.DrawCells = 1 dataRange = cdi.GetArray(name).GetRange(component) fieldToColorBy[0] = 'CELLS' else: print("No array with that name", name) return realRange = dataRange if dataRange[0] == dataRange[1]: dataRange = [dataRange[0] - 0.1, dataRange[1] + 0.1] simple.ColorBy(rep, fieldToColorBy) # Grab data tmpFileName = path + '__.png' self.view.ScalarRange = dataRange self.view.LockBounds = 1 self.view.StartCaptureValues() simple.SaveScreenshot(tmpFileName, self.view) self.view.StopCaptureValues() self.view.LockBounds = 0 if self.canWrite: # Convert data self.reader.SetFileName(tmpFileName) self.reader.Update() rgbArray = self.reader.GetOutput().GetPointData().GetArray(0) arraySize = rgbArray.GetNumberOfTuples() rawArray = vtkFloatArray() rawArray.SetNumberOfTuples(arraySize) minValue = 10000.0 maxValue = -100000.0 delta = (dataRange[1] - dataRange[0]) / 16777215.0 # 2^24 - 1 => 16,777,215 for idx in range(arraySize): rgb = rgbArray.GetTuple3(idx) if rgb[0] != 0 or rgb[1] != 0 or rgb[2] != 0: value = dataRange[0] + delta * float( rgb[0] * 65536 + rgb[1] * 256 + rgb[2] - 1) rawArray.SetTuple1(idx, value) minValue = min(value, minValue) maxValue = max(value, maxValue) else: rawArray.SetTuple1(idx, float('NaN')) # print ('Array bounds', minValue, maxValue, 'compare to', dataRange) with open(path, 'wb') as f: f.write(buffer(rawArray)) # Delete temporary file if self.cleanAfterMe: os.remove(tmpFileName) # Remove representation from view simple.Hide(source, self.view) return realRange
from paraview import simple import tonic from tonic.paraview.dataset_builder import * dataset_destination_path = '/Users/seb/Desktop/mpi-sphere' sphere = simple.Sphere() rep = simple.Show() simple.ColorBy(rep, ('POINTS', 'vtkProcessId')) view = simple.Render() view.ResetCamera() rep.RescaleTransferFunctionToDataRange(True) phi = range(0, 360, 10) theta = range(-60, 61, 10) dh = ImageDataSetBuilder(dataset_destination_path, 'image/jpg', { 'type': 'spherical', 'phi': phi, 'theta': theta }) dh.start(view) dh.writeImages() dh.stop()
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')
# init the 'PiecewiseFunction' selected for 'OpacityTransferFunction' ablnek5000Display.OpacityTransferFunction.Points = [ -0.18865761160850525, 0.0, 0.5, 0.0, 0.12637193500995636, 1.0, 0.5, 0.0 ] # reset view to fit data renderView1.ResetCamera() # get the material library materialLibrary1 = pv.GetMaterialLibrary() # update the view to ensure updated data information renderView1.Update() # set scalar coloring pv.ColorBy(ablnek5000Display, ('POINTS', 'x_velocity')) # rescale color and/or opacity maps used to include current data range ablnek5000Display.RescaleTransferFunctionToDataRange(True, False) # show color bar/color legend ablnek5000Display.SetScalarBarVisibility(renderView1, True) # get color transfer function/color map for 'x_velocity' x_velocityLUT = pv.GetColorTransferFunction('x_velocity') # get opacity transfer function/opacity map for 'x_velocity' x_velocityPWF = pv.GetOpacityTransferFunction('x_velocity') # set scalar coloring pv.ColorBy(ablnek5000Display, ('POINTS', 'y_velocity'))
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()")
print(" The max exact solution is =",max_sol_exacte ) print("The max numerical solution is =",my_ResultField.getNormEuclidean().max()) assert erreur_max/max_sol_exacte <1. #Postprocessing : #================ # Save 3D picture PV_routines.Save_PV_data_to_picture_file("FiniteElementsOnTorus"+'_0.vtu',"Numerical result field",'NODES',"FiniteElementsOnTorus") resolution=100 VTK_routines.Clip_VTK_data_to_VTK("FiniteElementsOnTorus"+'_0.vtu',"Clip_VTK_data_to_VTK_"+ "FiniteElementsOnTorus"+'_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_"+"FiniteElementsOnTorus"+'_0.vtu',"Numerical result field",'NODES',"Clip_VTK_data_to_VTK_"+"FiniteElementsOnTorus") # Plot over slice circle finiteElementsOnTorus_0vtu = pvs.XMLUnstructuredGridReader(FileName=["FiniteElementsOnTorus"+'_0.vtu']) slice1 = pvs.Slice(Input=finiteElementsOnTorus_0vtu) slice1.SliceType.Normal = [0.5, 0.5, 0.5] renderView1 = pvs.GetActiveViewOrCreate('RenderView') finiteElementsOnTorus_0vtuDisplay = pvs.Show(finiteElementsOnTorus_0vtu, renderView1) pvs.ColorBy(finiteElementsOnTorus_0vtuDisplay, ('POINTS', 'Numerical result field')) slice1Display = pvs.Show(slice1, renderView1) pvs.SaveScreenshot("./FiniteElementsOnTorus"+"_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 = ['Numerical result field (1)'] pvs.SaveScreenshot("./FiniteElementsOnTorus"+"_PlotOnSortedLine_"+'.png', magnification=1, quality=100, view=lineChartView2) pvs.Delete(lineChartView2)
ablnek5000Display.ScaleTransferFunction.Points = [0.0010371223324909806, 0.0, 0.5, 0.0, 1.412827968597412, 1.0, 0.5, 0.0] # init the 'PiecewiseFunction' selected for 'OpacityTransferFunction' ablnek5000Display.OpacityTransferFunction.Points = [0.0010371223324909806, 0.0, 0.5, 0.0, 1.412827968597412, 1.0, 0.5, 0.0] # reset view to fit data renderView1.ResetCamera() # get the material library materialLibrary1 = pv.GetMaterialLibrary() # update the view to ensure updated data information renderView1.Update() # set scalar coloring pv.ColorBy(ablnek5000Display, ('POINTS', 'velocity_mag')) # rescale color and/or opacity maps used to include current data range ablnek5000Display.RescaleTransferFunctionToDataRange(True, False) # show color bar/color legend ablnek5000Display.SetScalarBarVisibility(renderView1, True) # get color transfer function/color map for 'velocity_mag' velocity_magLUT = pv.GetColorTransferFunction('velocity_mag') velocity_magLUT.RGBPoints = [0.0010371223324909806, 0.231373, 0.298039, 0.752941, 0.7069325454649515, 0.865003, 0.865003, 0.865003, 1.412827968597412, 0.705882, 0.0156863, 0.14902] velocity_magLUT.ScalarRangeInitialized = 1.0 # get opacity transfer function/opacity map for 'velocity_mag' velocity_magPWF = pv.GetOpacityTransferFunction('velocity_mag') velocity_magPWF.Points = [0.0010371223324909806, 0.0, 0.5, 0.0, 1.412827968597412, 1.0, 0.5, 0.0]