Example #1
0
    def _getDataRangeGeneral(self, src, nm, getRangeFunc):
        import vtk.numpy_interface.dataset_adapter as dsa
        import numpy as np

        def getRange(fld, whichComponent=-1):
            if isinstance(fld, (dsa.VTKArray, )):
                data = [fld]
            elif isinstance(fld, (dsa.VTKCompositeDataArray, )):
                data = [
                    f for f in fld.Arrays if isinstance(f, (dsa.VTKArray, ))
                ]
                if len(data) == 0:
                    return None
            elif isinstance(fld, (dsa.VTKNoneArray, )):
                return None
            else:
                self.error("Unimplemented GetRange for", type(fld),
                           "when scaling", nm)

            cmpt = 0
            if len(data[0].shape) == 1:
                cmpt = 1
            elif len(data[0].shape) == 2:
                cmpt = data[0].shape[1]
                if whichComponent < 0:
                    data = [np.sqrt((a**2).sum(axis=1)) for a in data]
                elif whichComponent < cmpt:
                    data = [a[:, whichComponent] for a in data]
                else:
                    self.error("Asked for component", whichComponent,
                               "but only 0 to ", cmpt - 1, "available")
            else:
                self.error("Unsupported shape", data[0].shape, "for", nm)

            return getRangeFunc(data)

        from paraview.simple import servermanager as sv
        wrapped = dsa.WrapDataObject(sv.Fetch(src))

        try:
            rng = getRange(wrapped.CellData[nm])
            if rng is None:
                rng = getRange(wrapped.PointData[nm])
            if rng is None:
                rng = getRange(wrapped.FieldData[nm])
        except AttributeError:
            try:
                rng = getRange(wrapped.PointData[nm])
                if rng is None:
                    rng = getRange(wrapped.FieldData[nm])
            except AttributeError:
                try:
                    rng = getRange(wrapped.FieldData[nm])
                except AttributeError:
                    rng = None
        return rng
Example #2
0
    def GetCellScalarField(self, scalar_field_name):
        """get scalar field for cells"""
        PTOCELL = PointDatatoCellData(Input=self.f_data_in)

        CELLDATA = servermanager.Fetch(PTOCELL)
        NOFCELLS = CELLDATA.GetNumberOfCells()
        CDATA = CELLDATA.GetCellData()

        Sfield = []
        for i in range(NOFCELLS):
            Sfield.append(CDATA.GetArray(scalar_field_name).GetValue(i))
        return Sfield
Example #3
0
    def GetArea(self):
        """get cell area field"""
        CELLSIZE = CellSize(Input=self.f_data_in)

        CELLDATA = servermanager.Fetch(CELLSIZE)
        NOFCELLS = CELLDATA.GetNumberOfCells()
        CDATA = CELLDATA.GetCellData()

        AREA = []
        for i in range(NOFCELLS):
            AREA.append(CDATA.GetArray('Area').GetValue(i))
        return AREA
Example #4
0
    def GetLength(self):
        """get cell length field for 2d meshes"""
        CELLSIZE = CellSize(Input=self.f_data_in)

        CELLDATA = servermanager.Fetch(CELLSIZE)
        NOFCELLS = CELLDATA.GetNumberOfCells()
        CDATA = CELLDATA.GetCellData()

        LENGTH = []
        for i in range(NOFCELLS):
            LENGTH.append(CDATA.GetArray('Length').GetValue(i))
        return LENGTH
Example #5
0
    def GetCellPoints(self):
        """get point coordinates in cell vortices order"""
        POINTDATA = servermanager.Fetch(self.f_data_in)
        NOFPOINTS = POINTDATA.GetNumberOfPoints()

        Pointi = []
        Points = []
        for i in range(NOFPOINTS):
            Pointi = [
                POINTDATA.GetPoint(i)[0],
                POINTDATA.GetPoint(i)[1],
                POINTDATA.GetPoint(i)[2]
            ]
            Points.append(Pointi)
        return Points
Example #6
0
    def GetCellCenters(self):
        """get cell center coordinates"""
        CELLCENTER = CellCenters(Input=self.f_data_in)

        POINTDATA = servermanager.Fetch(CELLCENTER)
        NOFPOINTS = POINTDATA.GetNumberOfPoints()

        CellCenteri = []
        CellCenter = []
        for i in range(NOFPOINTS):
            CellCenteri = [
                POINTDATA.GetPoint(i)[0],
                POINTDATA.GetPoint(i)[1],
                POINTDATA.GetPoint(i)[2]
            ]
            CellCenter.append(CellCenteri)
        return CellCenter
Example #7
0
    def GetCellVectorField(self, vector_field_name):
        """get vector field for cells"""
        PTOCELL = PointDatatoCellData(Input=self.f_data_in)

        CELLDATA = servermanager.Fetch(PTOCELL)
        NOFCELLS = CELLDATA.GetNumberOfCells()
        CDATA = CELLDATA.GetCellData()

        Vfieldi = []
        Vfield = []
        for i in range(NOFCELLS):
            Vfieldi = [
                CDATA.GetArray(vector_field_name).GetTuple(i)[0],
                CDATA.GetArray(vector_field_name).GetTuple(i)[1],
                CDATA.GetArray(vector_field_name).GetTuple(i)[2]
            ]
            Vfield.append(Vfieldi)
        return Vfield
Example #8
0
    def Get2dNormal(self):
        """get unit normal field for 2d surfaces"""
        FACENORMALFIELD = GenerateSurfaceNormals(Input=self.f_data_in)
        FACENORMALFIELD.ComputeCellNormals = 1

        CELLDATA = servermanager.Fetch(FACENORMALFIELD)
        NOFCELLS = CELLDATA.GetNumberOfCells()
        CDATA = CELLDATA.GetCellData()

        Normali = []
        Normal = []
        for i in range(NOFCELLS):
            Normali = [
                CDATA.GetArray('Normals').GetTuple(i)[0],
                CDATA.GetArray('Normals').GetTuple(i)[1],
                CDATA.GetArray('Normals').GetTuple(i)[2]
            ]
            Normal.append(Normali)
        return Normal
Example #9
0
def plotOverLine(gds, desc, step, output_dir):
    import math
    from paraview.simple import CreateXYPlotView, SetActiveView
    from paraview.simple import SetActiveView, GetActiveSource, servermanager
    from paraview.simple import PlotOverLine, Calculator, GetDisplayProperties

    logger = logging.getLogger('gcm.pv_render.plotOverLine')

    title = desc.xpathEval('title/text()')
    if len(title) == 1:
        title = title[0].getContent()
    else:
        title = None
    output = desc.prop('output')

    logger.debug('Processing plotOverLine section')
    logger.debug('Title: ' + str(title))
    logger.debug('Output file name pattern: ' + output)

    quantities = [
        x.getContent() for x in desc.xpathEval('quantities/quantity/text()')
    ]

    logger.debug('List of quantities to draw: ' + str(quantities))

    line_from = [float(x) for x in desc.prop('from').split(';')]
    line_to = [float(x) for x in desc.prop('to').split(';')]

    logger.debug('Line: %s -> %s' % (str(line_from), str(line_to)))

    view = CreateXYPlotView()
    view.ViewSize = [1000, 1000]
    view.ChartTitle = title
    SetActiveView(view)

    leftAxis = desc.xpathEval('axes/left')
    if len(leftAxis) == 1:
        leftAxis = [
            float(leftAxis[0].prop('from')),
            float(leftAxis[0].prop('to'))
        ]
        logger.debug('Using custom Y axis range: ' + str(leftAxis))
    else:
        logger.debug('Using auto Y axis range')
        leftAxis = None

    if not leftAxis is None:
        if USE_API_4_2:
            view.LeftAxisRangeMinimum = leftAxis[0]
            view.LeftAxisRangeMaximum = leftAxis[1]
            view.LeftAxisUseCustomRange = True
        else:
            view.LeftAxisRange = leftAxis
            view.AxisUseCustomRange = [1, 0, 0, 0]

    bottomAxis = desc.xpathEval('axes/bottom')
    if len(bottomAxis) == 1:
        bottomAxis = [
            float(bottomAxis[0].prop('from')),
            float(bottomAxis[0].prop('to'))
        ]
        logger.debug('Using custom labels for X axis: ' + str(bottomAxis))
    else:
        logger.debug('Using default X axis labels')
        bottomAxis = None

    if bottomAxis:
        logger.debug('Creating custom calculator to draw proper X axis labels')
        calc = Calculator(gds)
        calc.ResultArrayName = 'xindex'
        calc.Function = '%(index_from)f+%(len)f*sqrt((coordsX-(%(from_x)f))^2 + (coordsY-(%(from_y)f))^2 + (coordsZ-(%(from_z)f))^2)/%(line_len)f' % {
            'index_from':
            bottomAxis[0],
            'len':
            bottomAxis[1] - bottomAxis[0],
            'from_x':
            line_from[0],
            'from_y':
            line_from[1],
            'from_z':
            line_from[2],
            'line_len':
            math.sqrt((line_from[0] - line_to[0])**2 +
                      (line_from[1] - line_to[1])**2 +
                      (line_from[2] - line_to[2])**2)
        }

        src = calc
    else:
        src = gds

    logger.debug('Creating POL object')
    pol = PlotOverLine(src)
    pol.Source.Point1 = line_from
    pol.Source.Point2 = line_to

    active_src = GetActiveSource()
    filter = servermanager.Fetch(active_src)
    pd = filter.GetPointData()

    if USE_API_4_2:
        _sv = quantities
    else:
        logger.debug('Filing default series visibility list (hide all)')

        sv = {
            'Points (0)': '0',
            'Points (1)': '0',
            'Points (2)': '0',
            'Points (Magnitude)': '0',
            'vtkOriginalIndices': '0',
        }

        for i in range(pd.GetNumberOfArrays()):
            arr = pd.GetArray(i)
            sz = arr.GetNumberOfComponents()
            name = arr.GetName()
            if sz == 1:
                sv[name] = '0'
            else:
                for j in range(sz):
                    sv[name + ' (' + str(j) + ')'] = '0'
                sv[name + ' (Magnitude)'] = '0'

        for q in quantities:
            logger.debug('Showing plot for ' + q)
            sv[q] = '1'

        _sv = []
        for v in sv:
            _sv.append(v)
        _sv.append(sv[v])

    logger.debug('Setting display properties for POL object')
    dp = GetDisplayProperties(pol)
    dp.SeriesVisibility = _sv

    if not bottomAxis is None:
        dp.UseIndexForXAxis = 0
        dp.XArrayName = 'xindex'

    render(step, output, output_dir)
Example #10
0
    if args["verbosity"] == 1:
        print(f"Processing file ({counter}/{len(args['files'])}): {curFile}")
    counter += 1

    # load pvd file
    pvdFile = PVDReader(FileName=curFile)

    # Extract Point and Probe at a location
    selectionSource = IDSelectionSource(ContainingCells=0,
                                        InsideOut=False,
                                        FieldType="POINT",
                                        IDs=0)
    ExtractSelection = ExtractSelection(Selection=selectionSource,
                                        Input=pvdFile)
    ExtractSelection.UpdatePipeline()
    selectionData = servermanager.Fetch(ExtractSelection)

    probeLocation = ProbeLocation()
    probeLocation.Input = pvdFile
    pointSource = probeLocation.ProbeType
    pointSource.Center.SetData(args["point"])
    probeLocation.UpdatePipeline()

    # Parse the extracted source and plot over time
    selectionSourceprobeLocationation = IDSelectionSource(ContainingCells=0,
                                                          InsideOut=False,
                                                          FieldType="POINT",
                                                          IDs=[0, 0])
    plotSelectionOverTime = PlotSelectionOverTime(
        OnlyReportSelectionStatistics=False)
    plotSelectionOverTime.Selection = selectionSourceprobeLocationation