def __init__(self, *args, **kwargs):
        super(Demo, self).__init__(*args, **kwargs)

        self.setWindowTitle("Demo")
        self.resize(1024, 768)

        # Creates and sets the layout for the main window
        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        # Create and add the ParaView widget
        self.pvwidget = pvpy.PVWidget()
        self.pvwidget.setWindowFlags(Qt.Widget)
        self.layout.addWidget(self.pvwidget)

        # Add UI stuff
        self.layout.addWidget(QLabel("<h2>Awesome UI here</h2>"))
        button = QPushButton("Load demo data")
        self.layout.addWidget(button)
        self.layout.addWidget(QPushButton("Dummy button 2"))

        # Load data on clicking the demo data button
        button.clicked.connect(self.loadDemoData)

        # Create an orthographic slice viewer
        pv.RemoveViewsAndLayouts()
        self.view = pv.CreateView('OrthographicSliceView')
    def createRenderView(self,
                         view_size=[1024, 1024]):
        """Create a new 'Render View'
        """

        renderView = pv.CreateView('RenderView')
        if view_size:
            renderView.ViewSize = view_size
        renderView.InteractionMode = '2D'
        renderView.AxesGrid = 'GridAxes3DActor'
        renderView.OrientationAxesVisibility = 0
        renderView.CenterOfRotation = [1.5, 1.5, 0.0]
        renderView.StereoType = 0
        renderView.CameraPosition = [1.5, 1.5, 10000.0]
        renderView.CameraFocalPoint = [1.5, 1.5, 0.0]
        renderView.CameraParallelScale = 2.1213203435596424
        renderView.CameraParallelProjection = 1
        renderView.Background = [1.0, 1.0, 1.0]
        renderView.OSPRayMaterialLibrary = self.material_library

        # init the 'GridAxes3DActor' selected for 'AxesGrid'
        renderView.AxesGrid.XTitleFontFile = ''
        renderView.AxesGrid.YTitleFontFile = ''
        renderView.AxesGrid.ZTitleFontFile = ''
        renderView.AxesGrid.XLabelFontFile = ''
        renderView.AxesGrid.YLabelFontFile = ''
        renderView.AxesGrid.ZLabelFontFile = ''

        return renderView
Exemple #3
0
    def __init__(self,
                 location,
                 sceneConfig,
                 cameraInfo,
                 metadata={},
                 sections={}):
        DataSetBuilder.__init__(self, location, cameraInfo, metadata, sections)

        self.view = simple.CreateView('RenderView')
        self.view.ViewSize = sceneConfig['size']
        self.view.CenterAxesVisibility = 0
        self.view.OrientationAxesVisibility = 0
        self.view.UpdatePropertyInformation()

        # Initialize camera
        for key, value in sceneConfig['camera'].iteritems():
            self.view.GetProperty(key).SetData(value)

        # Create a representation for all scene sources
        self.config = sceneConfig
        self.representations = []
        for data in self.config['scene']:
            rep = simple.Show(data['source'], self.view)
            self.representations.append(rep)

        # Add directory path
        self.dataHandler.registerData(name='directory',
                                      rootFile=True,
                                      fileName='file.txt',
                                      categories=['trash'])
    def addView(self, sourceProxy):
        view = simple.CreateView('RenderView')
        view.EnableRenderOnInteraction = 0
        view.Background = [0, 0, 0]

        simple.Show(sourceProxy, view)

        return view.GetGlobalIDAsString()
Exemple #5
0
def create_render_view(label, xdim, ydim):
    render_view = pvs.CreateView('RenderView')
    pvs.RenameView(label, render_view)
    render_view.OrientationAxesVisibility = 0
    render_view.CameraPosition = [xdim / 2, ydim / 2, 10000]
    render_view.CameraFocalPoint = [xdim / 2, ydim / 2, 2.5]
    render_view.AxesGrid.Visibility = 1
    #print(dir(render_view))
    return render_view
Exemple #6
0
    def __init__(self, isWriter=True, removePNG=True):
        self.view = simple.CreateView('RenderView')
        self.view.Background = [0.0, 0.0, 0.0]
        self.view.CenterAxesVisibility = 0
        self.view.OrientationAxesVisibility = 0

        self.reader = vtkPNGReader()
        self.cleanAfterMe = removePNG

        self.canWrite = isWriter
Exemple #7
0
    def __init__(self, divvyProtocol, colorManager):
        super(ScatterPlotProtocol, self).__init__()
        self.divvyProtocol = divvyProtocol
        self.colorManager = colorManager
        self.dataTable = None
        self.dataMesh = None
        self.meshRepresentation = None
        self.arrays = {}
        self.renderView = simple.CreateView('RenderView')
        self.renderView.InteractionMode = '3D'
        self.renderView.SMProxy.GetRenderWindow().SetMultiSamples(0)
        self.renderView.EnableRenderOnInteraction = 0

        self.representationMap = self.createCustomShaderMap()

        self.trivProducer = None

        self._lutImages = None
        self._colorMapName = ''

        self.scaleTransferFunction = simple.CreatePiecewiseFunction(
            Points=[0.0, 0.3, 0.5, 0.0, 1.0, 0.05, 0.5, 0.0])
        self.opacityTransferFunction = simple.CreatePiecewiseFunction(
            Points=[0.0, 0.3, 0.5, 0.0, 1.0, 0.05, 0.5, 0.0])
        self.userSelScalePoints = [0.0, 0.3, 0.5, 0.0, 1.0, 0.05, 0.5, 0.0]
        self.userSelOpacityPoints = [0.0, 0.3, 0.5, 0.0, 1.0, 0.05, 0.5, 0.0]
        self.userSelPointSizeRange = [1, 3]

        module_path = os.path.abspath(__file__)
        pathToLuts = os.path.join(os.path.dirname(module_path),
                                  'ColorMaps.json')
        self.lutMap = readColorMaps(pathToLuts)
        self._selectionLutInitialized = False

        presets = servermanager.vtkSMTransferFunctionPresets()
        importSuccess = presets.ImportPresets(pathToLuts)

        print('Presets were%simported successfully' %
              (' ' if importSuccess else ' NOT '))

        self.activeSelectionInformation = {
            "activeAnnotation": {
                "selection": {
                    "type": "empty"
                },
                "score": []
            },
            "activeScores": []
        }

        self.initializeUserSelectionPreset()
Exemple #8
0
    class Pipeline:

      # Create data source "input" (provides simulation fields)
      simData = coprocessor.CreateProducer( datadescription, "input" )

      # Write VTK output if requested
      if writeVtkOutput:
        fullWriter = pvs.XMLHierarchicalBoxDataWriter(Input=simData, DataMode="Appended",
                                                      CompressorType="ZLib")
        # Set freq=1 to ensure that output is written whenever the pipeline runs
        coprocessor.RegisterWriter(fullWriter, filename='bg_out_%t.vth', freq=1)

      # Create a new render view to generate images
      renderView = pvs.CreateView('RenderView')
      renderView.ViewSize = [1500, 768]
      renderView.InteractionMode = '2D'
      renderView.AxesGrid = 'GridAxes3DActor'
      renderView.CenterOfRotation = [2.8, 1.7, 0.0]
      renderView.StereoType = 0
      renderView.CameraPosition = [2.8, 1.7, 10000.0]
      renderView.CameraFocalPoint = [2.8, 1.7, 0.0]
      renderView.CameraParallelScale = 3.386
      renderView.Background = [0.32, 0.34, 0.43]
      renderView.ViewTime = datadescription.GetTime()

      # Show simulation time with 1 digit after decimal point
      annotateTime = pvs.AnnotateTime()
      annotateTime.Format = 'time: %.1f'
      timeDisplay = pvs.Show(annotateTime, renderView)

      # Register the view with coprocessor and provide it with information such as
      # the filename to use. Set freq=1 to ensure that images are rendered whenever
      # the pipeline runs
      coprocessor.RegisterView(renderView, filename='bg_out_%t.png', freq=1,
                               fittoscreen=1, magnification=1, width=1500, height=768,
                               cinema={})

      # Create colour transfer function for field
      LUT = pvs.GetColorTransferFunction(fieldName)
      LUT.RGBPoints = [9.355e-05, 0.231, 0.298, 0.753, 0.0674, 0.865, 0.865, 0.865, 0.135, 0.706, 0.0157, 0.149]
      LUT.ScalarRangeInitialized = 1.0

      # Render data field and colour by field value using lookup table
      fieldDisplay = pvs.Show(simData, renderView)
      fieldDisplay.Representation = 'Surface'
      fieldDisplay.ColorArrayName = ['CELLS', fieldName]
      fieldDisplay.LookupTable = LUT
Exemple #9
0
def create_chart_view(ylabel, log_scale=False, left_max_range=1000):
    chart_view = pvs.CreateView('XYChartView')
    pvs.RenameView(ylabel, chart_view)
    chart_view.LeftAxisTitle = ylabel
    chart_view.LeftAxisTitleFontSize = 12
    chart_view.LeftAxisGridColor = [0.7, 0.7, 0.7]
    chart_view.BottomAxisTitle = 'Time step'
    chart_view.BottomAxisTitleFontSize = 12
    chart_view.BottomAxisGridColor = [0.7, 0.7, 0.7]
    chart_view.BottomAxisUseCustomRange = 0
    #print(dir(chart_view))
    chart_view.LegendLocation = 'TopLeft'
    if log_scale:
        chart_view.LeftAxisLogScale = 1
        chart_view.LeftAxisUseCustomRange = 1
        chart_view.LeftAxisRangeMinimum = 1.0
        chart_view.LeftAxisRangeMaximum = left_max_range
    return chart_view
    def __init__(self, divvyProtocol, colorManager):
        super(ScatterPlotProtocol, self).__init__()
        self.divvyProtocol = divvyProtocol
        self.colorManager = colorManager
        self.dataTable = None
        self.arrays = {}
        self.renderView = simple.CreateView('RenderView')
        self.renderView.InteractionMode = '3D'

        self._lutImages = None
        self._colorMapName = ''
        module_path = os.path.abspath(__file__)
        pathToLuts = os.path.join(os.path.dirname(module_path),
                                  'ColorMaps.json')
        self.lutMap = readColorMaps(pathToLuts)
        self._selectionLutInitialized = False

        presets = servermanager.vtkSMTransferFunctionPresets()
        importSuccess = presets.ImportPresets(pathToLuts)

        print('Presets were%simported successfully' %
              (' ' if importSuccess else ' NOT '))
# 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)
pvs.Delete(lineChartView2)

print("Integral of the numerical solution", my_ResultField.integral(0))
print(
    "Numerical solution of Poisson equation on a sphere using finite elements done"
)
        class Pipeline:

            # Define source of pipeline
            grid = coprocessor.CreateProducer(datadescription, "input")

            if (write_full_output == True):
                fullWriter = pvs.XMLPUnstructuredGridWriter(
                    Input=grid, DataMode="Appended", CompressorType="ZLib")
                coprocessor.RegisterWriter(fullWriter,
                                           filename='full_output_%t.pvtu',
                                           freq=1)

            # Create a spherical slice
            slice = pvs.Slice(Input=grid)
            slice.SliceType = 'Sphere'
            slice.Triangulatetheslice = 0
            slice.SliceOffsetValues = [0.0]
            slice.SliceType.Radius = sphere_radius

            # Generate ghost cells - needed by CellDatatoPointData filter
            ghosts = pvs.GhostCellsGenerator(Input=grid)
            ghosts.BuildIfRequired = 0
            ghosts.MinimumNumberOfGhostLevels = 1

            # Convert cell data to point data, which is required for good contour results
            # Request "piece invariance" to ensure consistent values at
            # partition boundaries.
            #
            # CAUTION: THIS FILTER AVERAGES DATA FROM ALL CELLS SURROUNDING A POINT,
            #          WHICH REDUCES ACCURACY
            cell2point = pvs.CellDatatoPointData(Input=ghosts)

            # Create contours
            # Note that the "tube" filter can be used to highlight contours if needed.
            contours = pvs.Contour(Input=cell2point)
            contours.Isosurfaces = contour_values
            contours.ContourBy = ['POINTS', 'rho']
            contours.PointMergeMethod = 'Uniform Binning'

            # Create writers for slice and contour data and register them with the pipeline
            # Note that slice and contours generate separate datasets, so they need to be
            # written to separate files.
            sliceWriter = pvs.XMLPPolyDataWriter(Input=slice,
                                                 DataMode="Appended",
                                                 CompressorType="ZLib")
            coprocessor.RegisterWriter(sliceWriter,
                                       filename='spherical_slice_%t.pvtp',
                                       freq=1)

            # Create a new render view
            renderView = pvs.CreateView('RenderView')
            renderView.ViewSize = [1500, 768]
            renderView.AxesGrid = 'GridAxes3DActor'
            renderView.StereoType = 0
            renderView.CameraPosition = [0.0, 1.0, 0.3]
            renderView.CameraViewUp = [0.0, 0.0, 1.0]
            renderView.CameraParallelScale = 1.0
            renderView.Background = [0.32, 0.34, 0.43]
            renderView.ViewTime = datadescription.GetTime()

            # Register the view with coprocessor
            # and provide it with information such as the filename to use,
            # how frequently to write the images, etc.
            coprocessor.RegisterView(renderView,
                                     filename='contours_%t.png',
                                     freq=1,
                                     fittoscreen=1,
                                     magnification=1,
                                     width=1500,
                                     height=768,
                                     cinema={})

            # Create colour transfer function for field
            LUT = pvs.GetColorTransferFunction('rho')
            LUT.RGBPoints = [
                dataRange[0], 0.23, 0.30, 0.75, 0.5 * sum(dataRange), 0.87,
                0.87, 0.87, dataRange[1], 0.71, 0.016, 0.15
            ]
            LUT.ScalarRangeInitialized = 1.0

            # Show surface and colour by field value (which is cell data) using lookup table
            sphereDisplay = pvs.Show(slice, renderView)
            sphereDisplay.Representation = 'Surface'
            sphereDisplay.ColorArrayName = ['CELLS', 'rho']
            sphereDisplay.LookupTable = LUT

            # Show coastlines
            contourDisplay = pvs.Show(contours, renderView)
            contourDisplay.Representation = 'Surface'
            contourDisplay.ColorArrayName = [None, '']
            contourDisplay.OSPRayScaleArray = 'theta '
            contourDisplay.OSPRayScaleFunction = 'PiecewiseFunction'
            contourDisplay.SelectOrientationVectors = 'None'
            contourDisplay.ScaleFactor = 1193042.2418936265
            contourDisplay.SelectScaleArray = 'None'
            contourDisplay.GlyphType = 'Arrow'
            contourDisplay.GlyphTableIndexArray = 'None'
            contourDisplay.DataAxesGrid = 'GridAxesRepresentation'
            contourDisplay.PolarAxes = 'PolarAxesRepresentation'
            contourDisplay.GaussianRadius = 596521.1209468133
            contourDisplay.SetScaleArray = ['POINTS', 'theta ']
            contourDisplay.ScaleTransferFunction = 'PiecewiseFunction'
            contourDisplay.OpacityArray = ['POINTS', 'theta ']
            contourDisplay.OpacityTransferFunction = 'PiecewiseFunction'
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
Exemple #14
0
        class Pipeline:

            # Define source of pipeline
            grid = coprocessor.CreateProducer(datadescription, "input")

            if (write_full_output == True):
                fullWriter = pvs.XMLPUnstructuredGridWriter(
                    Input=grid, DataMode="Appended", CompressorType="ZLib")
                coprocessor.RegisterWriter(fullWriter,
                                           filename='full_output_%t.pvtu',
                                           freq=1)

            # Create a spherical slice
            slice = pvs.Slice(Input=grid)
            slice.SliceType = 'Sphere'
            slice.Triangulatetheslice = 0
            slice.SliceOffsetValues = [0.0]
            slice.SliceType.Radius = sphere_radius

            # Create writer for this data and register it with the pipeline
            sliceWriter = pvs.XMLPPolyDataWriter(Input=slice,
                                                 DataMode="Appended",
                                                 CompressorType="ZLib")
            coprocessor.RegisterWriter(sliceWriter,
                                       filename='spherical_slice_%t.pvtp',
                                       freq=1)

            # Create a new render view
            renderView = pvs.CreateView('RenderView')
            renderView.ViewSize = [1500, 768]
            renderView.AxesGrid = 'GridAxes3DActor'
            renderView.StereoType = 0
            renderView.CameraPosition = [-5, -2, 4]
            renderView.CameraViewUp = [0.5, 0.3, 0.8]
            renderView.CameraParallelScale = 1.7
            renderView.Background = [0.32, 0.34, 0.43]
            renderView.ViewTime = datadescription.GetTime()

            # Register the view with coprocessor
            # and provide it with information such as the filename to use,
            # how frequently to write the images, etc.
            coprocessor.RegisterView(renderView,
                                     filename='spherical_slice_%t.png',
                                     freq=1,
                                     fittoscreen=1,
                                     magnification=1,
                                     width=1500,
                                     height=768,
                                     cinema={})

            # Create colour transfer function for field
            LUT = pvs.GetColorTransferFunction(fieldname)
            LUT.RGBPoints = [
                dataRange[0], 0.23, 0.30, 0.75, 0.5 * sum(dataRange), 0.87,
                0.87, 0.87, dataRange[1], 0.71, 0.016, 0.15
            ]
            LUT.ScalarRangeInitialized = 1.0

            # Show surface and colour by field value (which is cell data) using lookup table
            sphereDisplay = pvs.Show(slice, renderView)
            sphereDisplay.Representation = 'Surface'
            sphereDisplay.ColorArrayName = ['CELLS', fieldname]
            sphereDisplay.LookupTable = LUT
Exemple #15
0
 def create_view(self):
     "Inicialização da visualização."
     self.objects_['render'] = pv.CreateView('RenderView')
Exemple #16
0
        class Pipeline:

            # Define source of pipeline
            grid = coprocessor.CreateProducer(datadescription, "input")

            if (write_full_output == True):
                fullWriter = pvs.XMLPUnstructuredGridWriter(
                    Input=grid, DataMode="Appended", CompressorType="ZLib")
                coprocessor.RegisterWriter(fullWriter,
                                           filename='full_output_%t.pvtu',
                                           freq=1)

            # Horizontal slice at the bottom
            slice = pvs.Slice(Input=grid)
            slice.SliceType = 'Plane'
            slice.SliceOffsetValues = [0.0]
            slice.SliceType.Origin = [0.0, 0.0, 101.94]
            slice.SliceType.Normal = [0.0, 0.0, 1.0]
            slice.Triangulatetheslice = False

            # Set up spherical projection filter - we need to bridge into the
            # VTK universe and use a VTK transform filter; the ParaView transform filter
            # does not support geo transforms

            # Source projection - simulation data is provided in lon lat rad coordinates
            latlonproj = vtk.vtkGeoProjection()
            latlonproj.SetName('lonlat')
            latlonproj.SetCentralMeridian(0)

            # Target projection - use Mollweide here
            targetproj = vtk.vtkGeoProjection()
            targetproj.SetName('moll')
            targetproj.SetCentralMeridian(0)

            # Set up vtkGeoTransform object that defines the transformation
            transform = vtk.vtkGeoTransform()
            transform.SetSourceProjection(latlonproj)
            transform.SetDestinationProjection(targetproj)

            # Set up VTK transform filter object
            tffilter = vtk.vtkTransformFilter()
            tffilter.SetTransform(transform)
            tffilter.SetInputConnection(
                slice.GetClientSideObject().GetOutputPort(0))

            # Return to ParaView universe by using a simple PassThrough filter to receive
            # output of the VTK transform filter
            passthrough = pvs.PassThrough()
            passthrough.GetClientSideObject().SetInputConnection(
                tffilter.GetOutputPort())

            # Create a new render view
            renderView = pvs.CreateView('RenderView')
            renderView.ViewSize = [1500, 768]
            renderView.AxesGrid = 'GridAxes3DActor'
            renderView.StereoType = 0
            renderView.CameraPosition = [0, 0, 4]
            renderView.CameraParallelScale = 1.7
            renderView.Background = [0.32, 0.34, 0.43]
            renderView.ViewTime = datadescription.GetTime()

            # Register the view with coprocessor
            # and provide it with information such as the filename to use,
            # how frequently to write the images, etc.
            coprocessor.RegisterView(renderView,
                                     filename='spherical_slice_%t.png',
                                     freq=1,
                                     fittoscreen=1,
                                     magnification=1,
                                     width=1500,
                                     height=768,
                                     cinema={})

            # Create colour transfer function for field
            LUT = pvs.GetColorTransferFunction(fieldname)
            LUT.RGBPoints = [
                dataRange[0], 0.23, 0.30, 0.75, 0.5 * sum(dataRange), 0.87,
                0.87, 0.87, dataRange[1], 0.71, 0.016, 0.15
            ]
            LUT.ScalarRangeInitialized = 1.0

            # Show surface and colour by field value (which is cell data) using lookup table
            sphereDisplay = pvs.Show(passthrough, renderView)
            sphereDisplay.Representation = 'Surface'
            sphereDisplay.ColorArrayName = ['CELLS', fieldname]
            sphereDisplay.LookupTable = LUT
Exemple #17
0
        class Pipeline:

            # Read topographic data
            topo = pvs.XMLPolyDataReader(FileName="ETOPO_10min_Ice.vtp")

            # Scale data to just under radius of the sphere
            toposcaled = pvs.Calculator(Input=topo)
            toposcaled.CoordinateResults = 1
            toposcaled.Function = '%i*coords' % (sphere_radius * 0.99)

            # Define source of pipeline
            grid = coprocessor.CreateProducer(datadescription, "input")

            ghosts = pvs.GhostCellsGenerator(Input=grid)
            ghosts.BuildIfRequired = 0
            ghosts.MinimumNumberOfGhostLevels = 1

            # Create a spherical slice
            slice = pvs.Slice(Input=ghosts)
            slice.SliceType = 'Sphere'
            slice.Triangulatetheslice = 0
            slice.SliceOffsetValues = [0.0]
            slice.SliceType.Radius = sphere_radius

            # Convert cell data to point data, which is required for good contour results
            #
            # CAUTION: THIS FILTER AVERAGES DATA FROM ALL CELLS SURROUNDING A POINT,
            #          WHICH REDUCES ACCURACY
            cell2point = pvs.CellDatatoPointData(Input=slice)
            cell2point.PassCellData = 0
            cell2point.PieceInvariant = 0

            # Create contours
            # Note that the "tube" filter can be used to highlight contours if needed.
            contours = pvs.Contour(Input=cell2point)
            contours.Isosurfaces = contour_values
            contours.ContourBy = ['POINTS', 'rho']
            contours.PointMergeMethod = 'Uniform Binning'

            # Create a new render view
            renderView = pvs.CreateView('RenderView')
            renderView.ViewSize = [1500, 768]
            renderView.AxesGrid = 'GridAxes3DActor'
            renderView.StereoType = 0
            renderView.CameraPosition = [0.0, 1.0, 0.3]
            renderView.CameraViewUp = [0.0, 0.0, 1.0]
            renderView.CameraParallelScale = 1.0
            renderView.Background = [0.32, 0.34, 0.43]
            renderView.ViewTime = datadescription.GetTime()

            # Register the view with coprocessor
            # and provide it with information such as the filename to use,
            # how frequently to write the images, etc.
            coprocessor.RegisterView(renderView,
                                     filename='topo_contours_%t.png',
                                     freq=1,
                                     fittoscreen=1,
                                     magnification=1,
                                     width=800,
                                     height=800,
                                     cinema={})

            # Create colour transfer function for field
            LUT = pvs.GetColorTransferFunction('altitude')
            # Use Wikipedia LUT as provided on http://www.earthmodels.org/data-and-tools/color-tables
            LUT.RGBPoints = [
                -11000, 0.141176470588235, 0.149019607843137,
                0.686274509803922, -5499.999, 0.219607843137255,
                0.227450980392157, 0.764705882352941, -5500, 0.219607843137255,
                0.227450980392157, 0.764705882352941, -2999.999,
                0.274509803921569, 0.282352941176471, 0.83921568627451, -3000,
                0.274509803921569, 0.282352941176471, 0.83921568627451,
                -1999.999, 0.317647058823529, 0.4, 0.850980392156863, -2000,
                0.317647058823529, 0.4, 0.850980392156863, -749.999,
                0.392156862745098, 0.505882352941176, 0.874509803921569, -750,
                0.392156862745098, 0.505882352941176, 0.874509803921569,
                -69.999, 0.513725490196078, 0.631372549019608,
                0.901960784313726, -70, 0.513725490196078, 0.631372549019608,
                0.901960784313726, -19.999, 0.643137254901961,
                0.752941176470588, 0.941176470588235, -20, 0.643137254901961,
                0.752941176470588, 0.941176470588235, 0.001, 0.666666666666667,
                0.784313725490196, 1, 0, 0, 0.380392156862745,
                0.27843137254902, 50.001, 0.0627450980392157, 0.47843137254902,
                0.184313725490196, 50, 0.0627450980392157, 0.47843137254902,
                0.184313725490196, 500.001, 0.909803921568627,
                0.843137254901961, 0.490196078431373, 500, 0.909803921568627,
                0.843137254901961, 0.490196078431373, 1200.001,
                0.631372549019608, 0.262745098039216, 0, 1200,
                0.631372549019608, 0.262745098039216, 0, 1700.001,
                0.509803921568627, 0.117647058823529, 0.117647058823529, 1700,
                0.509803921568627, 0.117647058823529, 0.117647058823529,
                2800.001, 0.431372549019608, 0.431372549019608,
                0.431372549019608, 2800, 0.431372549019608, 0.431372549019608,
                0.431372549019608, 4000.001, 1, 1, 1, 4000, 1, 1, 1, 6000.001,
                1, 1, 1
            ]

            LUT.ScalarRangeInitialized = 1.0

            # Show topo data
            sphereDisplay = pvs.Show(toposcaled, renderView)
            sphereDisplay.Representation = 'Surface'
            sphereDisplay.ColorArrayName = ['POINTS', 'altitude']
            sphereDisplay.LookupTable = LUT
            sphereDisplay.Opacity = 1.0

            # Show surface and colour by field value (which is cell data) using lookup table
            sphereDisplay = pvs.Show(contours, renderView)
            sphereDisplay.Representation = 'Surface'
            sphereDisplay.Opacity = 1.0
        class Pipeline:

            grid = coprocessor.CreateProducer(datadescription, 'input')

            # Normalise radius - simplifies creating glyphs
            normalise = pvs.Calculator(Input=grid)
            normalise.CoordinateResults = 1
            normalise.Function = 'coords/%i' % sphere_radius

            # Visualise velocity field using arrows
            glyph = pvs.Glyph(Input=normalise, GlyphType='Arrow')
            glyph.Scalars = ['POINTS', 'None']
            glyph.Vectors = ['CELLS', 'u']
            glyph.ScaleFactor = 0.2
            glyph.GlyphTransform = 'Transform2'
            glyph.GlyphType.TipResolution = 12
            glyph.GlyphType.TipRadius = 0.05
            glyph.GlyphType.ShaftRadius = 0.015

            # Create a new 'Render View'
            renderView = pvs.CreateView('RenderView')
            renderView.ViewSize = [1500, 768]
            renderView.AxesGrid = 'GridAxes3DActor'
            renderView.StereoType = 0
            renderView.CameraPosition = [-5, -2, 4]
            renderView.CameraViewUp = [0.5, 0.3, 0.8]
            renderView.CameraParallelScale = 1.7
            renderView.Background = [0.32, 0.34, 0.43]

            # Register the view with coprocessor
            # and provide it with information such as the filename to use,
            # how frequently to write the images, etc.
            coprocessor.RegisterView(renderView,
                                     filename='velocity_field_%t.png',
                                     freq=1,
                                     fittoscreen=1,
                                     magnification=1,
                                     width=800,
                                     height=800,
                                     cinema={})
            renderView.ViewTime = datadescription.GetTime()

            # Create colour transfer function for velocity field
            uLUT = pvs.GetColorTransferFunction('u')
            uLUT.RGBPoints = [
                1.7, 0.23, 0.30, 0.75, 20.9, 0.87, 0.87, 0.87, 40.0, 0.71,
                0.016, 0.15
            ]
            uLUT.ScalarRangeInitialized = 1.0

            # Show velocity field magnitude
            velocitymagDisplay = pvs.Show(normalise, renderView)
            velocitymagDisplay.Representation = 'Surface'
            velocitymagDisplay.ColorArrayName = ['CELLS', 'u']
            velocitymagDisplay.LookupTable = uLUT

            # Show colour legend
            uLUTColorBar = pvs.GetScalarBar(uLUT, renderView)
            uLUTColorBar.Title = 'u'
            uLUTColorBar.ComponentTitle = 'Magnitude'
            velocitymagDisplay.SetScalarBarVisibility(renderView, True)

            # Show velocity field glyphs
            glyphDisplay = pvs.Show(glyph, renderView)
            glyphDisplay.Representation = 'Surface'
            glyphDisplay.ColorArrayName = [None, '']
        class Pipeline:

            grid = coprocessor.CreateProducer(datadescription, 'input')

            # Simulation domain outline
            outline = pvs.Outline(Input=grid)

            # Horizontal slice at the bottom
            slice = pvs.Slice(Input=grid)
            slice.SliceType = 'Plane'
            slice.SliceOffsetValues = [0.0]
            slice.SliceType.Origin = [0.0, 0.0, 101.94]
            slice.SliceType.Normal = [0.0, 0.0, 1.0]
            slice.Triangulatetheslice = False

            # Glyphs for representing velocity field
            glyph = pvs.Glyph(Input=grid, GlyphType='Arrow')
            glyph.Vectors = ['CELLS', 'u']
            glyph.ScaleMode = 'vector'
            glyph.ScaleFactor = 0.01
            glyph.GlyphMode = 'Every Nth Point'
            glyph.Stride = 200

            # Create a new render view
            renderView = pvs.CreateView('RenderView')
            renderView.ViewSize = [800, 400]
            renderView.InteractionMode = '2D'
            renderView.AxesGrid = 'GridAxes3DActor'
            renderView.CenterOfRotation = [0.18, 0.0, 102]
            renderView.StereoType = 0
            renderView.CameraPosition = [-3.4, -6.8, 107]
            renderView.CameraFocalPoint = [-0.27, -0.41, 102]
            renderView.CameraViewUp = [0.057, 0.49, 0.87]
            renderView.CameraParallelScale = 1.0
            renderView.Background = [0.32, 0.34, 0.43]

            # Register the view with coprocessor
            coprocessor.RegisterView(renderView,
                                     filename='image_%t.png',
                                     freq=1,
                                     fittoscreen=0,
                                     magnification=1,
                                     width=800,
                                     height=400,
                                     cinema={})
            renderView.ViewTime = datadescription.GetTime()

            # Get color transfer function/color map for field rho
            rhoLUT = pvs.GetColorTransferFunction('rho')
            rhoLUT.RGBPoints = [
                1.17, 0.231, 0.298, 0.752, 1.33, 0.865, 0.865, 0.865, 1.49,
                0.706, 0.0157, 0.149
            ]
            rhoLUT.ScalarRangeInitialized = 1.0

            # Show slice
            sliceDisplay = pvs.Show(slice, renderView)
            sliceDisplay.Representation = 'Surface With Edges'
            sliceDisplay.ColorArrayName = ['CELLS', 'rho']
            sliceDisplay.LookupTable = rhoLUT
            sliceDisplay.ScaleFactor = 0.628
            sliceDisplay.SelectScaleArray = 'None'
            sliceDisplay.GlyphType = 'Arrow'
            sliceDisplay.GlyphTableIndexArray = 'None'
            sliceDisplay.DataAxesGrid = 'GridAxesRepresentation'
            sliceDisplay.PolarAxes = 'PolarAxesRepresentation'
            sliceDisplay.GaussianRadius = 0.314
            sliceDisplay.SetScaleArray = [None, '']
            sliceDisplay.ScaleTransferFunction = 'PiecewiseFunction'
            sliceDisplay.OpacityArray = [None, '']
            sliceDisplay.OpacityTransferFunction = 'PiecewiseFunction'

            # Show color legend
            sliceDisplay.SetScalarBarVisibility(renderView, True)

            # Show glyph
            glyphDisplay = pvs.Show(glyph, renderView)

            # Show outline
            outlineDisplay = pvs.Show(outline, renderView)

            # Get color legend/bar for rhoLUT in view renderView
            rhoLUTColorBar = pvs.GetScalarBar(rhoLUT, renderView)
            rhoLUTColorBar.WindowLocation = 'LowerRightCorner'
            rhoLUTColorBar.Title = 'rho'
            rhoLUTColorBar.ComponentTitle = ''
from paraview import simple

import os
import numpy as np

# Create output directory
kernel_plot_dir = './Kernel_plots'
if not os.path.exists(kernel_plot_dir):
    os.mkdir(kernel_plot_dir)

# disable automatic camera reset on 'Show'
simple._DisableFirstRenderCameraReset()

# Reset render view, seems to change slightly in pvpython mode
renderView1 = simple.CreateView('RenderView')
renderView1.ViewSize = [960, 540]
renderView1.CameraPosition = [5103005.0, -34811145.0, 0.0]
renderView1.CameraFocalPoint = [5103005.0, 0.0, 0.0]
renderView1.CenterOfRotation = [253031.0, 0.0, -65653.0]
renderView1.CameraViewUp = [0.0, 0.0, 1.0]
renderView1.InteractionMode = '2D'
renderView1.OrientationAxesVisibility = 0
renderView1.OrientationAxesLabelColor = [0.313, 0.313, 0.313]
renderView1.StereoType = 0
renderView1.LightSwitch = 1
renderView1.LightIntensity = 0.2
renderView1.CameraParallelScale = 6520917.036707207
renderView1.Background = [1.0, 1.0, 1.0]

kerner_kernelxdmf = simple.XDMFReader(FileNames=['kerner_kernel.xdmf'])
Exemple #21
0
    pvs.LoadPlugin(pluginPath + 'libnetCDFLFRicReader.so', remote=False)

# Create a new data source with the LFRic output data, load the pressure field,
# and use Cartesian coordinates rather than lon-lat-rad
filePath = ''
data = pvs.NetCDFLFRicReader(FileName=filePath + 'lfric_output.nc')
data.CellArrayStatus = ['pressure']
data.UseCartesiancoordinates = 1

# Add a clip filter to the pipeline and set plane orientation
clip = pvs.Clip(Input=data)
clip.ClipType = 'Plane'
clip.ClipType.Normal = [0.0, 0.0, 1.0]

# Set up a new render view for displaying the grid and data
renderView = pvs.CreateView('RenderView')
renderView.ViewSize = [1600, 800]
renderView.CameraPosition = [-43.0, 39.0, 32.0]
renderView.CameraViewUp = [0.76, 0.44, 0.49]

# Define a colour look-up table using (data value, r, g, b) tuples
# Use value range from first timestep
lut = pvs.GetColorTransferFunction('pressure')
valueRange = data.CellData['pressure'].GetRange()
lut.RGBPoints = [
    valueRange[0], 0.23, 0.30, 0.75, valueRange[1], 0.71, 0.02, 0.15
]

# Show clip filter in the render view, render grid surfaces,
# and colour surfaces using the pressure field and our LUT
clipDisplay = pvs.Show(clip, renderView)
Exemple #22
0
        class Pipeline:

            # Create data source "input" (provides simulation fields)
            simData = coprocessor.CreateProducer(datadescription, "input")

            # Write VTK output if requested
            if writeVtkOutput:
                fullWriter = pvs.XMLHierarchicalBoxDataWriter(
                    Input=simData, DataMode="Appended", CompressorType="ZLib")
                # Set freq=1 to ensure that output is written whenever the pipeline runs
                coprocessor.RegisterWriter(fullWriter,
                                           filename='bg_out_%t.vth',
                                           freq=1)

            # Create a new render view to generate images
            renderView = pvs.CreateView('RenderView')
            renderView.ViewSize = [1500, 768]
            renderView.InteractionMode = '2D'
            renderView.AxesGrid = 'GridAxes3DActor'
            renderView.CenterOfRotation = [2.8, 1.7, 0.0]
            renderView.StereoType = 0
            renderView.CameraPosition = [2.8, 1.7, 10000.0]
            renderView.CameraFocalPoint = [2.8, 1.7, 0.0]
            renderView.CameraParallelScale = 3.386
            renderView.Background = [0.32, 0.34, 0.43]
            renderView.ViewTime = datadescription.GetTime()

            # Show simulation time with 1 digit after decimal point
            annotateTime = pvs.AnnotateTime()
            annotateTime.Format = 'time: %.1f'
            timeDisplay = pvs.Show(annotateTime, renderView)

            # Combine uu and vv components into velocity vector field
            calculatorVelField = pvs.Calculator(Input=simData)
            calculatorVelField.AttributeType = 'Cell Data'
            calculatorVelField.ResultArrayName = 'velocity'
            calculatorVelField.Function = 'uu*iHat+vv*jHat'

            # Compute velocity field magnitudes
            calculatorVelMag = pvs.Calculator(Input=calculatorVelField)
            calculatorVelMag.AttributeType = 'Cell Data'
            calculatorVelMag.ResultArrayName = 'mag'
            calculatorVelMag.Function = 'mag(velocity)'

            # Remove cells with vanishing velocity magnitude
            velMagThreshold = pvs.Threshold(calculatorVelMag)
            velMagThreshold.Scalars = ['CELLS', 'mag']
            velMagThreshold.ThresholdRange = [1.0e-6, 1.0e30]

            # Visualise remaining velocity vector field using arrows with fixed length
            # and skipping cells to avoid crowding
            glyphs = pvs.Glyph(Input=velMagThreshold, GlyphType='Arrow')
            glyphs.Vectors = ['CELLS', 'velocity']
            glyphs.ScaleFactor = 0.2
            glyphs.GlyphMode = 'Every Nth Point'
            glyphs.Stride = 100
            glyphs.GlyphTransform = 'Transform2'

            # Register the view with coprocessor and provide it with information such as
            # the filename to use. Set freq=1 to ensure that images are rendered whenever
            # the pipeline runs
            coprocessor.RegisterView(renderView,
                                     filename='bg_out_%t.png',
                                     freq=1,
                                     fittoscreen=0,
                                     magnification=1,
                                     width=1500,
                                     height=768,
                                     cinema={})

            # Create colour transfer function for field
            LUT = pvs.GetColorTransferFunction('hh')
            LUT.RGBPoints = [
                9.355e-05, 0.231, 0.298, 0.753, 0.0674, 0.865, 0.865, 0.865,
                0.135, 0.706, 0.0157, 0.149
            ]
            LUT.ScalarRangeInitialized = 1.0

            # Render data field and colour by field value using lookup table
            fieldDisplay = pvs.Show(simData, renderView)
            fieldDisplay.Representation = 'Surface'
            fieldDisplay.ColorArrayName = ['CELLS', 'hh']
            fieldDisplay.LookupTable = LUT

            # Add velocity field visualisation
            velfieldDisplay = pvs.Show(glyphs, renderView)