예제 #1
0
def deleteDownstream(input=None):
    """Delete downstream filters for a given input. If no input provided, all
    filters on the pipeline will be deleted.

    Args:
        input (str): The name of the object on the pipeline to preserve. 

    """
    import paraview.simple as pvs
    if input is None:
        # The below snippet deletes all Filters on the pipeline
        #- i.e. deletes anything that has an input
        #- preserves readers and sources
        for f in pvs.GetSources().values():
            if f.GetProperty("Input") is not None:
                pvs.Delete(f)
    else:
        # Be able to specify upstream source
        src = pvs.FindSource(input)
        #print('src: ', src)
        # Delete ALL things downstream of input
        for f in pvs.GetSources().values():
            #print('f: ', f)
            #print('f.Input: ', f.GetProperty("Input"))
            if f.GetPropertyValue("Input") is src:
                #print('Deleting: ', f)
                pvs.Delete(f)
    # Done
    return None
예제 #2
0
def extractParaviewLineData(caseDir, varList, coords, calcDict, csvOutputVar,
                            time):
    try:
        reader = ps.OpenFOAMReader(FileName=caseDir + '/case.foam')
    except:
        ps.Connect()
        reader = ps.OpenFOAMReader(FileName=caseDir + '/case.foam')

    try:
        reader.CellArrays = varList
    except:
        print("Variables {} were not found in results. Exiting ...".format(
            varList))

    reader.MeshRegions = ['internalMesh']

    if (time in reader.TimestepValues):
        reader.SMProxy.UpdatePipeline(time)
        reader.UpdatePipelineInformation()
        #view = ps.CreateRenderView()
        #view.ViewTime = time
    else:
        print("Time-directory {} does not exist. Exiting ...".format(time))
        sys.exit(1)

    if (calcDict):
        calc = ps.Calculator(reader)
        calc.Function = calcDict["Function"]
        calc.ResultArrayName = calcDict["ResultArrayName"]

    plotLine = ps.PlotOverLine(Source="High Resolution Line Source")
    plotLine.Source.Resolution = 450
    plotLine.Source.Point1 = coords[0]  # [0.0, 0.0008, 0.0]
    plotLine.Source.Point2 = coords[1]  # [0.59, 0.0008, 0.0]

    filePath = caseDir + "/tmp.csv"
    writer = ps.CreateWriter(filePath, plotLine)
    writer.WriteAllTimeSteps = False
    writer.UseScientificNotation = 1
    #print("Writing file tmp.csv ... ")
    writer.UpdatePipeline()
    #print("Done!")
    ps.Delete(reader)
    ps.Delete(calc)  #; ps.Delete(writer)
    ps.Delete(plotLine)
    reader = None
    del reader
    calc = None
    del calc
    plotLine = None
    del plotLine
    del writer

    if (np.mod((100. * time), 1) == 0):
        print("Disconnecting ... ")
        ps.Disconnect()  # Clear memory occasionally.

    data = extractFromCSV("tmp.csv", csvOutputVar)
    return data
예제 #3
0
    def loadDatasets(self, datafiles):
        # initially, we'll only support loading 1 dataset.
        for item in _DataProber.PipelineObjects:
            simple.Delete(item["Probe"])
            simple.Delete(item["ReaderRepresentation"])
            simple.Delete(item["Reader"])
        _DataProber.PipelineObjects = []

        for path in datafiles:
            self.loadData(path)
        bounds = self.update3DWidget()
        self.resetCameraWithBounds(bounds)
        return True
예제 #4
0
def calc_surf_to_vol(filename, arr_name, sample_rate):
    import paraview.simple as ps
    import numpy as np
    import paraview as pv
    from vtk.util.numpy_support import vtk_to_numpy

    # have paraview open the vtk data file
    reader = ps.OpenDataFile(filename)
    sys_data = pv.servermanager.Fetch(reader)
    nx, ny, nz = sys_data.GetDimensions()
    dx, dy, dz = sys_data.GetSpacing()

    # downsample the data (makes for a smoother contour surface)
    ds = ps.ExtractSubset()
    ds.SampleRateI = sample_rate
    ds.SampleRateJ = sample_rate
    ds.SampleRateK = sample_rate
    ds.VOI[1] = nx - 1
    ds.VOI[3] = ny - 1
    ds.VOI[4] = 1  # leave off bottom layer for CHBDThinFilm
    ds.VOI[5] = nz - 2  # leave off top layer for CHBDThinFilm
    ds.IncludeBoundary = 1
    ds.UpdatePipeline()

    # have paraview apply a contour surface at a concentration value of cont_val
    contour = ps.Contour()
    cont_val = 0.5  # this might change depending on order parameter
    contour.ContourBy = ['POINTS',
                         arr_name]  # Viz is the name of the vtk array
    contour.Isosurfaces = [cont_val]
    contour.SetPropertyWithName('ComputeNormals', 0)
    contour.UpdatePipeline()

    # integrate the surface area and curvature
    summed_curv = ps.IntegrateVariables()
    summed_curv_data = pv.servermanager.Fetch(summed_curv)
    surf_area = summed_curv_data.GetCellData().GetArray(0).GetValue(0)

    # calculate the surface area to volume ratio
    volume = nx * dx * ny * dy * nz * dz
    surf_to_vol = surf_area / volume

    # delete paraview sources and filters
    ps.Delete(reader)
    ps.Delete(ds)
    ps.Delete(contour)
    ps.Delete(summed_curv)
    del (sys_data)
    del (summed_curv_data)

    return surf_to_vol, surf_area, volume
예제 #5
0
파일: datasource.py 프로젝트: sipv/pvtools
    def probe(self, variable, point):
        """Return the value of a variable at a given point.

        Args:
            variable (str): Name of the variable.
                Probing a vector return its magnitude.
                Components of the vector are available by adding a suffix
                ' X', ' Y' or ' Z' to the vector name.
                Physical coordinates are available under the name 'X', 'Y' or 'Z'.
            point (tuple): x, y and z coordinates.

        Returns:
            float: Queried value or None.
                None is returned if the variable does not exist or the point is not
                defined at the given point.
        """

        pvs.SetActiveSource(self.reader)
        prob_loc = pvs.ProbeLocation(ProbeType="Fixed Radius Point Source")
        prob_loc.ProbeType.Center = point
        array = _get_variable_array(prob_loc, variable)

        pvs.Delete(prob_loc)

        if array is None or len(array) == 0:
            return None
        elif len(array) != 1:
            raise Exception("Unexpected length of the array.")
        else:
            return array[0]
예제 #6
0
    def destroy(self):
        if self.source is not None:
            paraview.Delete(self.source)

        if self.display is not None:
            paraview.Delete(self.display)

        if self.view is not None:
            paraview.Delete(self.view)

        del self.source
        del self.display
        del self.view

        self.source = None
        self.display = None
        self.view = None
예제 #7
0
def deleteFilters(input=None):
    import paraview.simple as pvs
    """if input is not None:
        src = pvs.FindSource(dataNm)"""
    #TODO: be able to specify upstream source
    for f in pvs.GetSources().values():
        if f.GetProperty("Input") is not None:
            pvs.Delete(f)
    return None
예제 #8
0
def fitPlane():
    src = smp.GetActiveSource()

    selection = GetSelectionSource(src)

    if not selection:
        return

    extracter = smp.ExtractSelection()
    extracter.Selection = selection
    extracter.Input = src
    smp.Show(extracter)

    try:
        pd = extracter.GetClientSideObject().GetOutput()

        origin = range(3)
        normal = range(3)
        mind, maxd, stddev = vtk.mutable(0), vtk.mutable(0), vtk.mutable(0)

        channelMean = range(32)
        channelStdDev = range(32)
        channelNpts = range(32)

        vvmod.vtkPlaneFitter.PlaneFit(pd, origin, normal, mind, maxd, stddev, channelMean, channelStdDev, channelNpts)
        rows = [['overall', origin, normal, 0.0, stddev, stddev, pd.GetNumberOfPoints()]]
        rows = rows + [['%d' % i, origin, normal,
                        channelMean[i], channelStdDev[i],
                        math.sqrt(channelMean[i]**2 + channelStdDev[i]**2),
                        channelNpts[i]]
                       for i in range(32)]

        def rowconverter(x):
            try:
                return '\t'.join(['%.4f' % d for d in x])
            except TypeError:
                try:
                    x = x.get()
                except AttributeError:
                    pass
                if type(x) == float:
                    return '%.4f' % x
                elif type(x) in (int, long):
                    return '%d' % x
                else:
                    return x

        print '\t'.join(['channel','originx','originy','originz','normalx','normaly','normalz',
                         'mean','stddev','RMS','npts'])
        for r in rows:
            if r[-1] == 0:
                r[-4:-1] = ['nan', 'nan', 'nan']
            print '\t'.join([rowconverter(x) for x in r])
    finally:
        smp.Delete(extracter)
        smp.SetActiveSource(src)
예제 #9
0
    def remove(self):
        """
		Reset ParaView and Vizard stuff to default.
		"""
        self.origin_node.remove()
        for filter in reversed(self._filters):
            pv.Delete(filter)
        pv.servermanager.ProxyManager().UnRegisterProxies()
        pv.Disconnect()
        pv.Connect()
def deleteAllTemporalTransformsAxes():
    namesToDelete = [
        getCalculatorName("RX"),
        getCalculatorName("RY"),
        getCalculatorName("RZ")
    ]
    sToDelete = []
    for s in smp.GetSources():
        if s[0] in namesToDelete:
            smp.Delete(smp.GetSources()[s])
    smp.Render()
def RequestData():
    # R.0.2018.080
    import sys
    import numpy as np
    import os
    import paraview.simple as simple
    sys.path.insert(0, r'EMC_SRC_PATH')
    import IrisEMC_Paraview_Lib as lib

    views = simple.GetViews(viewtype="SpreadSheetView")
    if len(views) > 0:
        simple.Delete(views[0])
    else:
        view = simple.GetActiveView()
        layout = simple.GetLayout(view)

    pdo = self.GetOutput()  # vtkTable

    if Coordinate_Type == 0:
        lon = X_or_Longitude
        lat = Y_or_Latitude
        depth = Z_or_Depth
        x, y, z = lib.llz2xyz(lat, lon, depth)
    else:
        x = X_or_Longitude
        y = Y_or_Latitude
        z = Z_or_Depth
        lat, lon, depth = lib.xyz2llz(x, y, z)

    # store metadata
    fieldData = pdo.GetFieldData()
    fieldData.AllocateArrays(3)  # number of fields

    fieldData = pdo.GetFieldData()
    data = vtk.vtkFloatArray()
    data.SetName('Longitude, Latitude, Depth')
    data.InsertNextValue(lon)
    data.InsertNextValue(lat)
    data.InsertNextValue(depth)
    fieldData.AddArray(data)

    data = vtk.vtkFloatArray()
    data.SetName('X, Y, Z')
    data.InsertNextValue(x)
    data.InsertNextValue(y)
    data.InsertNextValue(z)
    fieldData.AddArray(data)

    pdo.SetFieldData(fieldData)
예제 #12
0
 def openFile(self, files):
     id = ""
     if _FileOpener.reader:
         try:
             simple.Delete(_FileOpener.reader)
         except:
             _FileOpener.reader = None
     try:
         _FileOpener.reader = simple.OpenDataFile(files)
         simple.Show()
         simple.Render()
         simple.ResetCamera()
         id = _FileOpener.reader.GetGlobalIDAsString()
     except:
         _FileOpener.reader = None
     return id
예제 #13
0
    def showSphere(self, params):
        if self.sphere is not None:
            simple.Delete(self.sphere)

        maxDim = max(self.bounds[1] - self.bounds[0],
                     self.bounds[3] - self.bounds[2],
                     self.bounds[5] - self.bounds[4])

        self.sphere = simple.Sphere()
        self.sphere.Radius = maxDim / 100.0
        self.sphere.Center = params['point']
        rep = simple.Show()
        rep.Representation = 'Surface'
        rep.DiffuseColor = params['color']

        simple.SetActiveSource(self.srcObj)
예제 #14
0
    def extractSubgrid(self, bounds):
        if (self.subgrid is not None):
            simple.Delete(self.subgrid)
        simple.SetActiveSource(self.srcObj)
        self.subgrid = simple.ExtractSubset()
        self.subgrid.VOI = bounds
        simple.SetActiveSource(self.subgrid)

        self.rep = simple.Show()
        self.rep.ScalarOpacityFunction = self.sof
        self.rep.ColorArrayName = self.colorArrayName
        self.rep.Representation = 'Volume'
        self.rep.SelectionPointFieldDataArrayName = self.colorArrayName
        self.rep.LookupTable = self.lookupTable

        simple.Hide(self.srcObj)
        simple.SetActiveSource(self.subgrid)
        simple.Render()
예제 #15
0
    def _sliceSurfaces(self, slice):
        if self.meshSlice is not None:
            simple.Delete(self.meshSlice)
            self.meshSlice = None

        for surface in self.surfaces:
            rep = simple.Show(surface)

            if self.sliceMode == 'XY Plane':
                origin = [
                    0.0, 0.0,
                    math.cos(math.radians(rep.Orientation[2])) * slice
                ]
                normal = [0.0, 0.0, 1.0]
            elif self.sliceMode == 'XZ Plane':
                origin = [
                    0.0,
                    math.cos(math.radians(rep.Orientation[1])) * slice, 0.0
                ]
                normal = [0.0, 1.0, 0.0]
            else:
                origin = [
                    math.cos(math.radians(rep.Orientation[0])) * slice, 0.0,
                    0.0
                ]
                normal = [1.0, 0.0, 0.0]

            simple.Hide(surface)
            self.meshSlice = simple.Slice(Input=surface, SliceType='Plane')
            simple.SetActiveSource(self.srcObj)

            self.meshSlice.SliceOffsetValues = [0.0]
            self.meshSlice.SliceType = 'Plane'
            self.meshSlice.SliceType.Origin = origin
            self.meshSlice.SliceType.Normal = normal
            meshDataRep = simple.Show(self.meshSlice)

            meshDataRep.Representation = 'Points'
            meshDataRep.LineWidth = self.CONTOUR_LINE_WIDTH
            meshDataRep.PointSize = self.CONTOUR_LINE_WIDTH
            meshDataRep.AmbientColor = rep.DiffuseColor
            meshDataRep.Orientation = rep.Orientation

        simple.SetActiveSource(self.srcObj)
예제 #16
0
def getTargetLutImages(presetNames, numSamples):
    colorArray = vtk.vtkUnsignedCharArray()
    colorArray.SetNumberOfComponents(3)
    colorArray.SetNumberOfTuples(numSamples)

    pxm = simple.servermanager.ProxyManager()
    lutProxy = pxm.NewProxy('lookup_tables', 'PVLookupTable')
    lut = lutProxy.GetClientSideObject()
    dataRange = lut.GetRange()
    delta = (dataRange[1] - dataRange[0]) / float(numSamples)

    # Add the color array to an image data
    imgData = vtk.vtkImageData()
    imgData.SetDimensions(numSamples, 1, 1)
    imgData.GetPointData().SetScalars(colorArray)

    # Use the vtk data encoder to base-64 encode the image as png, using no compression
    encoder = vtk.vtkDataEncoder()

    # Result container
    result = {}

    # Loop over all presets
    for name in presetNames:
        lutProxy.ApplyPreset(name, True)
        rgb = [0, 0, 0]
        for i in range(numSamples):
            lut.GetColor(dataRange[0] + float(i) * delta, rgb)
            r = int(round(rgb[0] * 255))
            g = int(round(rgb[1] * 255))
            b = int(round(rgb[2] * 255))
            colorArray.SetTuple3(i, r, g, b)

        result[name] = encoder.EncodeAsBase64Png(imgData, 0)

    simple.Delete(lutProxy)

    return result
예제 #17
0
def fitPlane():
    src = smp.GetActiveSource()
    if not src:
        return

    selection = GetSelectionSource(src)

    if not selection:
        return

    extracter = smp.ExtractSelection()
    extracter.Selection = selection
    extracter.Input = src
    smp.Show(extracter)

    try:
        pd = extracter.GetClientSideObject().GetOutput()

        if pd.IsTypeOf("vtkMultiBlockDataSet"):
            appendFilter = vtk.vtkAppendFilter()
            for i in range(pd.GetNumberOfBlocks()):
                appendFilter.AddInputData(pd.GetBlock(i))
            appendFilter.Update()
            pd = appendFilter.GetOutput()

        max_laser_id = pd.GetPointData().GetArray("laser_id").GetRange()[1]
        nchannels = 2**vtk.vtkMath.CeilLog2(int(max_laser_id))

        origin = range(3)
        normal = range(3)
        mind, maxd, stddev = vtk.mutable(0), vtk.mutable(0), vtk.mutable(0)

        channelMean = range(nchannels)
        channelStdDev = range(nchannels)
        channelNpts = range(nchannels)

        vvmod.vtkPlaneFitter.PlaneFit(pd, origin, normal, mind, maxd, stddev,
                                      channelMean, channelStdDev, channelNpts,
                                      nchannels)
        rows = [[
            'overall', origin, normal, 0.0, stddev, stddev,
            pd.GetNumberOfPoints()
        ]]
        rows = rows + [[
            '%d' % i, origin, normal, channelMean[i], channelStdDev[i],
            math.sqrt(channelMean[i]**2 + channelStdDev[i]**2), channelNpts[i]
        ] for i in range(nchannels)]

        def rowconverter(x):
            try:
                return '\t'.join(['%.4f' % d for d in x])
            except TypeError:
                try:
                    x = x.get()
                except AttributeError:
                    pass
                if type(x) == float:
                    return '%.4f' % x
                elif type(x) in (int, long):
                    return '%d' % x
                else:
                    return x

        print '\t'.join([
            'channel', 'originx', 'originy', 'originz', 'normalx', 'normaly',
            'normalz', 'mean', 'stddev', 'RMS', 'npts'
        ])
        for r in rows:
            if r[-1] == 0:
                r[-4:-1] = ['nan', 'nan', 'nan']
            print '\t'.join([rowconverter(x) for x in r])
    finally:
        smp.Delete(extracter)
        smp.SetActiveSource(src)
예제 #18
0
    print('the last argument should be a number')
    numsteps = 10

#imageData2 = vtk.vtkImageData()

for step in range(numsteps):
    print("Timestep %d" % step)
    # assume simulation time starts at 0
    time = step / float(numsteps)

    # create the input to the coprocessing library.  normally
    # this will come from the adaptor
    wavelet = pvsimple.Wavelet()
    wholeExtent = wavelet.WholeExtent
    # put in some variation in the point data that changes with time
    wavelet.Maximum = 255 + 200 * math.sin(step * math.pi / 100)
    wavelet.UpdatePipeline()
    imageData = pvsimple.servermanager.Fetch(wavelet)

    # note that we delete wavelet now since.  if not, it will
    # get deleted automatically in the coprocessing script
    pvsimple.Delete(wavelet)
    wavelet = None

    # "perform" coprocessing.  results are outputted only if
    # the passed in script says we should at time/step
    coProcess(imageData, time, step, sys.argv[1], wholeExtent)
    imageData = None
    import time
    time.sleep(1)
예제 #19
0
 def deleteSource(self, proxy_id):
     self.pipeline.removeNode(proxy_id)
     proxy = helper.idToProxy(proxy_id)
     simple.Delete(proxy)
     simple.Render()
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
예제 #21
0
            wavelet = pvsimple.Wavelet()
            wavelet.Maximum = 300+50*math.sin(step * 2 * 3.1415927 / 10)
            wavelet.YMag = yMag
            wavelet.ZMag = zMag

            contour = pvsimple.Contour(guiName="Contour",
                                       Isosurfaces=[230.0],
                                       ContourBy=['RTData'],
                                       PointMergeMethod="Uniform Binning" )


            fileName = currentDir + "/wavelet_{:0d}_{:0d}_{:0d}.vtp".format (
                yMag, zMag, step)
            writer = pvsimple.XMLPolyDataWriter(Input = contour,
                                                FileName=fileName)
            writer.UpdatePipeline()

            pvsimple.Show()
            pvsimple.Render()
            pvsimple.Delete(wavelet)
            pvsimple.Delete(contour)
            pvsimple.Delete(writer)
            wavelet = None
            contour = None
            writer = None
            fTime.write(fileName)
            fTime.write("\n")
        fTime.close()
fEnsemble.close()
예제 #22
0
def cleanup():
    global DTMPythonFilter
    smp.Delete(DTMPythonFilter)
def RequestData():
    # R.0.2018.080
    import sys
    import numpy as np
    import os
    import paraview.simple as simple
    sys.path.insert(0, "EMC_SRC_PATH")
    import IrisEMC_Paraview_Lib as lib

    views = simple.GetViews(viewtype="SpreadSheetView")
    if len(views) > 0:
        simple.Delete(views[0])
    else:
        view = simple.GetActiveView()
        layout = simple.GetLayout(view)
        locationId = layout.SplitViewVertical(view=view, fraction=0.7)

    pdo = self.GetOutput()  # vtkTable

    if Coordinate_Type == 0:
        lon = X_or_Longitude
        lat = Y_or_Latitude
        depth = Z_or_Depth
        x, y, z = lib.llz2xyz(lat, lon, depth)
    else:
        x = X_or_Longitude
        y = Y_or_Latitude
        z = Z_or_Depth
        lat, lon, depth = lib.xyz2llz(x, y, z)

    # VTK arrays for columns
    #name = vtk.vtkStringArray()
    #name.SetNumberOfComponents(1)
    #name.SetNumberOfTuples(6)
    #name.SetName("Component Name")
    #name.InsertNextValue("X")
    #name.InsertNextValue("Y")
    #name.InsertNextValue("Z")
    #name.InsertNextValue("Latitude")
    #name.InsertNextValue("Longitude")
    #name.InsertNextValue("Depth")
    #pdo.Array(name)

    # store metadata
    fieldData = pdo.GetFieldData()
    fieldData.AllocateArrays(3)  # number of fields

    fieldData = pdo.GetFieldData()
    data = vtk.vtkFloatArray()
    data.SetName('Longitude, Latitude, Depth')
    data.InsertNextValue(lon)
    data.InsertNextValue(lat)
    data.InsertNextValue(depth)
    fieldData.AddArray(data)

    data = vtk.vtkFloatArray()
    data.SetName('X, Y, Z')
    data.InsertNextValue(x)
    data.InsertNextValue(y)
    data.InsertNextValue(z)
    fieldData.AddArray(data)

    pdo.SetFieldData(fieldData)
예제 #24
0
    def clear(self):
        version = self.version
        rv = self.rv
        simple = self.simple

        print 'Clear the pipeline.'

        # Reset time so that color range is detected correctly on build().
        rv.ViewTime = 0
        rv.StillRender()

        def name(proxy):
            # Return name of proxy.
            return (type(proxy)).__name__

        def cmp_tubes_filters_glyphs_blocks(x,y):
            # Using this function to sort the proxies will assure they are 
            # removed in the right order.
            if name(x) in ['GenerateTubes', 'TubeFilter', 'Tube']:
                return -1
            elif name(y) in ['GenerateTubes', 'TubeFilter', 'Tube']:
                return 1
            if name(x) == 'ProgrammableFilter':
                return -1
            elif name(y) == 'ProgrammableFilter':
                return 1
            elif name(x) == 'Glyph' or name(x)[:11] == 'TensorGlyph':
                return -1
            elif name(y) == 'Glyph' or name(y)[:11] == 'TensorGlyph':
                return 1
            if name(x) == 'ExtractBlock':
                return -1
            elif name(y) == 'ExtractBlock':
                return 1
            return cmp(x,y)

        # Remove lookup tables first.
        pxm = servermanager.ProxyManager()
        for proxy in pxm.GetProxiesInGroup('lookup_tables').itervalues():
            servermanager.UnRegister(proxy)

        if version == 4:
            # Then remove the source proxies.
            for proxy in sorted(pxm.GetProxiesInGroup('sources').itervalues(),
                                cmp_tubes_filters_glyphs_blocks):
                if name(proxy) == 'TensorGlyphWithCustomSource':
                    # Do nothing.
                    # Setting Source or Input gives: 
                    # 'QAbstractItemModel::endRemoveRows:
                    # Invalid index ( 2 , 0 ) in model 
                    # pqPipelineModel(0x26340b0)'
                    # http://www.paraview.org/Bug/view.php?id=9312
                    pass
                else:
                    # Avoid error:
                    # 'Connection sink not found in the pipeline model'.
                    if hasattr(proxy, "Source"):
                        proxy.Source = None
                    if hasattr(proxy, "Input"):
                        proxy.Input = None

                servermanager.UnRegister(proxy)

            # Finally remove the representations.
            for proxy in pxm.GetProxiesInGroup('representations').itervalues():
                servermanager.UnRegister(proxy)

            rv.Representations = []

        else:
            for proxy in sorted(simple.GetSources().itervalues(), 
                                cmp_tubes_filters_glyphs_blocks):
                # Avoid error:
                # 'Connection sink not found in the pipeline model'.
                if hasattr(proxy, "Input"):
                    proxy.Input = None
                if hasattr(proxy, "GlyphType"):
                    proxy.GlyphType = None

                simple.Delete(proxy)

        rv.ResetCamera()
        rv.StillRender()
def RequestData():
    # R.0.2018.080
    import sys
    sys.path.insert(0, "EMC_SRC_PATH")
    from datetime import datetime
    import numpy as np
    from vtk.numpy_interface import dataset_adapter as dsa
    from vtk.util import numpy_support
    import IrisEMC_Paraview_Lib as lib
    import paraview.simple as simple

    views = simple.GetViews(viewtype="SpreadSheetView")
    if len(views) > 0:
       simple.Delete(views[0])
    else:
       view = simple.GetActiveView()
       layout = simple.GetLayout(view)
       locationId = layout.SplitViewVertical(view=view ,fraction=0.7)

    myId    = simple.GetActiveSource().Input.GetGlobalIDAsString()
    proxies = simple.GetSources()
    proxyList = []
    for key in proxies:
       listElt = {}
       listElt['name'] = key[0]
       listElt['id'] = key[1]
       proxy = proxies[key]
       parentId = '0'
       if hasattr(proxy, 'Input'):
           parentId = proxy.Input.GetGlobalIDAsString()
       listElt['parent'] = parentId
       proxyList.append(listElt)


    pdi = self.GetInput() # VTK PolyData Type
    np = pdi.GetNumberOfPoints()
    depthMin = 9999999999999.0
    depthMax = -9999999999999.0
    latitude  = {}
    longitude = {}

    pdo = self.GetOutput() # VTK Table Type
    polyData  = vtk.vtkPolyData()
    dataPoints = vtk.vtkPoints()

    if len(Label.strip()) <= 0:
         pid = simple.GetActiveSource().Input.GetGlobalIDAsString()
         proxies = simple.GetSources()
         for key in proxies:
             if key[1] == pid:
                 Label = " ".join(["Coordinates View:",key[0]])
                 break
    for i in range(np):
        point = pdi.GetPoints().GetPoint(i)
        (lat,lon,depth) = lib.xyz2llz(point[0],point[1],point[2])
        dataPoints.InsertNextPoint((lat,lon,depth))
        key = "%0.1f"%(depth)
        if depthMin >= float(key):
           depthMin = float(key)
           depthMinKey = key
        if depthMax <= float(key):
           depthMax = float(key)
           depthMaxKey = key
        if key not in latitude.keys():
            latitude[key] =[]
            longitude[key] = []
        latitude[key].append(float("%0.1f"%(lat)))
        longitude[key].append(float("%0.1f"%(lon)))

    # store boundary metadata

    fieldData = polyData.GetFieldData()
    fieldData.AllocateArrays(3) # number of fields

    depthData = vtk.vtkStringArray()
    depthData.SetName('Depth\n(km)')

    data = vtk.vtkStringArray()
    data.SetName('Corners (lat,lon)\n(degrees)')

    depthKeys = [depthMinKey,depthMaxKey]
    if depthMinKey == depthMaxKey:
        depthKeys = [depthMinKey]
    for i in range(len(depthKeys)):
       depthKey = depthKeys[i]
       borderLat = []
       borderLon = []
       oldMin = 999999999.0
       oldMax = -99999999.0
       lonList = list(set(sorted(longitude[depthKey])))
       for j in range(len(lonList)):
          lon = lonList[j]
          minVal = 999999999.0
          maxVal = -99999999.0
          for i in range(len(longitude[depthKey])):
             if longitude[depthKey][i] == lon:
                if latitude[depthKey][i] > maxVal:
                  maxVal = latitude[depthKey][i]
                if latitude[depthKey][i] < minVal:
                  minVal = latitude[depthKey][i]
          if oldMin != minVal or j==len(lonList)-1:
             if abs(oldMin) < 9999.0:
                borderLat.append(oldMin)
                borderLon.append(lon)
             borderLat.append(minVal)
             borderLon.append(lon)
             oldMin = minVal
          if oldMax != maxVal or j==len(lonList)-1:
             if abs(oldMax) < 9999.0:
                borderLat.append(oldMax)
                borderLon.append(lon)
             borderLat.append(maxVal)
             borderLon.append(lon)
             oldMax = maxVal
       borderList = zip(borderLat, borderLon)
       borderList.sort()
       borderList = list(set(borderList))
       min1 = borderList[0][0]
       max1 = borderList[0][0]
       for i in range(len(borderList)):
          if borderList[i][0] < min1:
             min1 = borderList[i][0]
          if borderList[i][0] > max1:
             max1 = borderList[i][0]
       minList = []
       maxList = []
       for i in range(len(borderList)):
          if borderList[i][0] ==  min1:
             minList.append(borderList[i][1])
          if borderList[i][0] ==  max1:
             maxList.append(borderList[i][1])
       depthData.InsertNextValue(depthKey)
       data.InsertNextValue("%0.1f, %0.1f"%(min1,min(minList)))
       if min(minList) != max(minList):
          depthData.InsertNextValue(" ")
          data.InsertNextValue("%0.1f, %0.1f"%(min1,max(minList)))
       depthData.InsertNextValue(" ")
       data.InsertNextValue("%0.1f, %0.1f"%(max1,max(maxList)))
       if min(maxList) != max(maxList):
         depthData.InsertNextValue(" ")
         data.InsertNextValue("%0.1f, %0.1f"%(max1,min(maxList)))
    fieldData.AddArray(data)
    fieldData.AddArray(depthData)

    if len(Label.strip()) > 0:
        simple.RenameSource(Label)

    pdo.SetFieldData(fieldData)
예제 #26
0
def get_curvatures(vtk_file, vtk_file_dir, output_file, output_file_dir,
                   arr_name, sample_rate, gauss_filter, mean_filter):
    import paraview.simple as ps
    import numpy as np
    import paraview as pv
    from vtk.util.numpy_support import vtk_to_numpy

    # have paraview open the vtk data file
    reader = ps.OpenDataFile(vtk_file_dir + vtk_file)
    sys_data = pv.servermanager.Fetch(reader)
    nx, ny, nz = sys_data.GetDimensions()
    dx, dy, dz = sys_data.GetSpacing()

    # downsample the data (makes for a smoother contour surface)
    ds = ps.ExtractSubset(reader)
    ds.SampleRateI = sample_rate
    ds.SampleRateJ = sample_rate
    ds.SampleRateK = sample_rate
    ds.VOI[1] = nx - 1
    ds.VOI[3] = ny - 1
    ds.VOI[5] = nz - 1
    ds.IncludeBoundary = 1
    ds.UpdatePipeline()

    # have paraview apply a contour surface at a concentration value of cont_val
    contour = ps.Contour(ds)
    cont_val = 0.0  # this might change depending on order parameter
    contour.ContourBy = ['POINTS',
                         arr_name]  # Viz is the name of the vtk array
    contour.Isosurfaces = [cont_val]
    contour.SetPropertyWithName('ComputeNormals', 0)
    contour.UpdatePipeline()

    # have paraview calculate the curvature (default is Gaussian)
    curvature = ps.Curvature(contour)

    # filter the curvatures
    threshold = ps.Threshold(curvature)
    threshold.Scalars = ['POINTS', 'Gauss_Curvature']
    threshold.ThresholdRange = [-gauss_filter, gauss_filter]
    threshold.AllScalars = 1
    threshold.UpdatePipeline()
    gauss_data = pv.servermanager.Fetch(threshold)
    size_gauss = gauss_data.GetPointData().GetArray(0).GetSize()

    # convert vtk array to numpy array
    gauss_curv = vtk_to_numpy(gauss_data.GetPointData().GetArray(0))

    # integrate the surface area and curvature
    summed_curv = ps.IntegrateVariables(threshold)
    summed_curv_data = pv.servermanager.Fetch(summed_curv)
    g_surf_area = summed_curv_data.GetCellData().GetArray(0).GetValue(0)

    # have paraview recalculate the mean curvature
    curvature.SetPropertyWithName('CurvatureType', 'Mean')
    curvature.UpdatePipeline()
    threshold = ps.Threshold(curvature)
    threshold.Scalars = ['POINTS', 'Mean_Curvature']
    threshold.ThresholdRange = [-mean_filter, mean_filter]
    threshold.UpdatePipeline()
    summed_curv = ps.IntegrateVariables(threshold)
    summed_curv.UpdatePipeline()
    summed_curv_data = pv.servermanager.Fetch(summed_curv)
    m_surf_area = summed_curv_data.GetCellData().GetArray(0).GetValue(0)
    mean_data = pv.servermanager.Fetch(threshold)

    # convert vtk array to numpy array
    mean_curv = vtk_to_numpy(mean_data.GetPointData().GetArray(0))

    # calculate the surface area to volume ratio
    g_surf_to_vol = g_surf_area / (nx * dx * ny * dy * nz * dz)
    m_surf_to_vol = m_surf_area / (nx * dx * ny * dy * nz * dz)

    # calculate percent of data used in threshold
    curvature_data = pv.servermanager.Fetch(curvature)
    size_curv = curvature_data.GetPointData().GetArray(0).GetSize()

    # save the numpy arrays for later manipulation
    np.savez(output_file_dir + output_file, gauss_curv, mean_curv,
             g_surf_to_vol, g_surf_area, m_surf_to_vol, m_surf_area)

    # delete paraview sources and filters
    ps.Delete(summed_curv)
    ps.Delete(contour)
    ps.Delete(ds)
    ps.Delete(reader)
    del (sys_data)
    del (summed_curv_data)

    return 0
예제 #27
0
    def openFile(self, files):
        id = ""
        if _FileOpener.reader:
            try:
                simple.Delete(_FileOpener.reader)
            except:
                _FileOpener.reader = None
        try:
            #_FileOpener.reader = simple.OpenDataFile(files)
            #simple.Show()
            #simple.Render()
            #simple.ResetCamera()
            #id = _FileOpener.reader.GetGlobalIDAsString()

            m000_ = simple.GenericIOReader(FileName=files)

            m000_.xAxis = 'x'
            m000_.yAxis = 'y'
            m000_.zAxis = 'z'
            m000_.PointArrayStatus = ['vx', 'vy', 'vz', 'id', 'fof_halo_tag']

            #_FileOpener.view = simple.GetRenderView()
            DataRepresentation1 = simple.Show()
            DataRepresentation1.ScaleFactor = 12.799999237060547
            DataRepresentation1.ScalarOpacityUnitDistance = 1.7320512506334491
            DataRepresentation1.SelectionPointFieldDataArrayName = 'fof_halo_tag'
            DataRepresentation1.EdgeColor = [0.0, 0.0, 0.50000762951094835]

            _FileOpener.view.CenterOfRotation = [
                63.999996662139893, 63.999996185302734, 63.999996185302734
            ]

            Calculator1 = simple.Calculator()

            _FileOpener.view.CameraPosition = [
                63.999996662139893, 63.999996185302734, 492.29631710692331
            ]
            _FileOpener.view.CameraFocalPoint = [
                63.999996662139893, 63.999996185302734, 63.999996185302734
            ]
            _FileOpener.view.CameraClippingRange = [
                296.65336530365192, 595.04075617962826
            ]
            _FileOpener.view.CameraParallelScale = 110.85124480185661

            DataRepresentation2 = simple.Show()
            DataRepresentation2.ScaleFactor = 12.799999237060547
            DataRepresentation2.ScalarOpacityUnitDistance = 1.7320512506334491
            DataRepresentation2.SelectionPointFieldDataArrayName = 'fof_halo_tag'
            DataRepresentation2.EdgeColor = [0.0, 0.0, 0.50000762951094835]

            DataRepresentation1.Visibility = 0

            Calculator1.Function = 'iHat*vx + jHat*vy + kHat*vz'
            Calculator1.ResultArrayName = 'velocity'

            _FileOpener.view.Background2 = [0.0, 0.0, 0.16470588235294117]
            _FileOpener.view.Background = [0.0, 0.0, 0.0]
            _FileOpener.view.CenterAxesVisibility = 0

            a3_velocity_PVLookupTable = GetLookupTableForArray(
                "velocity",
                3,
                RGBPoints=[
                    22.220290592721472, 0.27843099999999998,
                    0.27843099999999998, 0.85882400000000003,
                    2772.329145661583, 0.0, 0.0, 0.36078399999999999,
                    5503.2064702754178, 0.0, 1.0, 1.0, 8272.5468557993063, 0.0,
                    0.50196099999999999, 0.0, 11003.42418041314, 1.0, 1.0, 0.0,
                    13753.533035482002, 1.0, 0.38039200000000001, 0.0,
                    16503.641890550865, 0.41960799999999998, 0.0, 0.0,
                    19253.750745619727, 0.87843099999999996,
                    0.30196099999999998, 0.30196099999999998
                ],
                VectorMode='Magnitude',
                NanColor=[1.0, 1.0, 0.0],
                ColorSpace='RGB',
                ScalarRangeInitialized=1.0)
            a3_velocity_PiecewiseFunction = CreatePiecewiseFunction(Points=[
                22.220290592721472, 0.0, 0.5, 0.0, 19253.750745619727, 1.0,
                0.5, 0.0
            ])
            ScalarBarWidgetRepresentation1 = CreateScalarBar(
                ComponentTitle='Magnitude',
                Title='velocity',
                Enabled=1,
                LabelFontSize=8,
                TitleFontSize=8)
            ScalarBarWidgetRepresentation1.LookupTable = a3_velocity_PVLookupTable
            _FileOpener.view.Representations.append(
                ScalarBarWidgetRepresentation1)

            DataRepresentation2.ScalarOpacityFunction = a3_velocity_PiecewiseFunction
            DataRepresentation2.ColorArrayName = ('POINT_DATA', 'velocity')
            DataRepresentation2.PointSize = 1.0
            DataRepresentation2.LookupTable = a3_velocity_PVLookupTable

            a3_velocity_PVLookupTable.ScalarOpacityFunction = a3_velocity_PiecewiseFunction

            simple.Render()

            # Fix lookup table range
            data = simple.Calculator1.GetPointDataInformation()
            (minValue, maxValue) = data.GetArray('velocity').GetRange(-1)
            rgbPoints = a3_velocity_PVLookupTable.RGBPoints
            rgbPointsMod = []
            for i in range(8):
                alpha = i / 7.0
                rgbPointsMod.append((1 - alpha) * minValue + alpha * maxValue)
                rgbPointsMod.append(rgbPoints[4 * i + 1])
                rgbPointsMod.append(rgbPoints[4 * i + 2])
                rgbPointsMod.append(rgbPoints[4 * i + 3])
            a3_velocity_PVLookupTable.RGBPoints = rgbPointsMod

            simple.Render()

            _FileOpener.reader = m000
            id = _FileOpener.reader.GetGlobalIDAsString()

        except:
            _FileOpener.reader = None
        return id
예제 #28
0
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()
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"
)

#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]):
예제 #30
0
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