예제 #1
0
def cellContainsPoint(inputs, locations):
    array = vtkDoubleArray()
    array.SetNumberOfComponents(3)
    array.SetNumberOfTuples(len(locations))
    for i in range(len(locations)):
        array.SetTuple(i, locations[i])
    node = vtkSelectionNode()
    node.SetFieldType(vtkSelectionNode.CELL)
    node.SetContentType(vtkSelectionNode.LOCATIONS)
    node.SetSelectionList(array)

    from paraview.vtk.vtkFiltersExtraction import vtkLocationSelector
    selector = vtkLocationSelector()
    selector.Initialize(node, "vtkInsidedness")

    inputDO = inputs[0].VTKObject
    outputDO = inputDO.NewInstance()
    outputDO.CopyStructure(inputDO)

    output = dsa.WrapDataObject(outputDO)
    if outputDO.IsA('vtkCompositeDataSet'):
        it = inputDO.NewIterator()
        it.InitTraversal()
        while not it.IsDoneWithTraversal():
            outputDO.SetDataSet(it, inputDO.GetDataSet(it).NewInstance())
            it.GoToNextItem()
    selector.ComputeSelectedElements(inputDO, outputDO)

    return output.CellData.GetArray('vtkInsidedness')
예제 #2
0
파일: Data.py 프로젝트: LeeRuns/PyFoam
def setSampleData(tbl,lineName,dirName="sets"):
    """Read sample data and put it into a vtkTable

    Use in 'Programmable Filter'. Set output type to 'vtkTable'.
    To get (for instance) the data on line 'lineCenter' from the sampled data in
    the directory sets (it will automatically use the current time) in the
    source code write
from PyFoam.Paraview.Data import setSampleData
setSampleData(self.GetOutput(),"lineCenter",dirName="sets")
    """
    actualDir=checkDir(dirName)
    data=SamplePlot(args=[case().name,
                          "--directory="+actualDir,
                          "--time="+str(vTime()),
                          "--line="+lineName,
                          "--fuzzy-time",
                          "--numpy"]).data

    nExp=re.compile(lineName+"_t=[^ ]+ (.+)")

    for n in data.dtype.names:
        m=nExp.match(n)
        vals=data[n]
        if m:
            n=m.group(1)
        col=vtk.vtkDoubleArray()
        col.SetName(n)
        for v in vals:
            col.InsertNextValue(v)
        tbl.AddColumn(col)

    return tbl
예제 #3
0
def setSampleData(tbl, lineName, dirName="sets"):
    """Read sample data and put it into a vtkTable

    Use in 'Programmable Filter'. Set output type to 'vtkTable'.
    To get (for instance) the data on line 'lineCenter' from the sampled data in
    the directory sets (it will automatically use the current time) in the
    source code write
from PyFoam.Paraview.Data import setSampleData
setSampleData(self.GetOutput(),"lineCenter",dirName="sets")
    """
    actualDir = checkDir(dirName)
    data = SamplePlot(args=[
        case().name, "--directory=" + actualDir, "--time=" +
        str(vTime()), "--line=" + lineName, "--fuzzy-time", "--numpy"
    ]).data

    nExp = re.compile(lineName + "_t=[^ ]+ (.+)")

    for n in data.dtype.names:
        m = nExp.match(n)
        vals = data[n]
        if m:
            n = m.group(1)
        col = vtk.vtkDoubleArray()
        col.SetName(n)
        for v in vals:
            col.InsertNextValue(v)
        tbl.AddColumn(col)

    return tbl
예제 #4
0
def pointIsNear(locations, distance, inputs):
    array = vtk.vtkDoubleArray()
    array.SetNumberOfComponents(3)
    array.SetNumberOfTuples(len(locations))
    for i in range(len(locations)):
        array.SetTuple(i, locations[i])
    node = vtk.vtkSelectionNode()
    node.SetFieldType(vtk.vtkSelectionNode.POINT)
    node.SetContentType(vtk.vtkSelectionNode.LOCATIONS)
    node.GetProperties().Set(vtk.vtkSelectionNode.EPSILON(), distance)
    node.SetSelectionList(array)

    selection = vtk.vtkSelection()
    selection.AddNode(node)
    from vtk.vtkFiltersExtraction import vtkExtractSelectedLocations
    pointsNear = vtkExtractSelectedLocations()
    pointsNear.SetInputData(0, inputs[0].VTKObject)
    pointsNear.SetInputData(1, selection)
    pointsNear.Update()

    extractedPoints = pointsNear.GetOutput()
    numPoints = inputs[0].GetNumberOfPoints()
    result = np.zeros((numPoints, ), dtype=np.int8)

    extracted = dsa.WrapDataObject(extractedPoints)
    pointIds = extracted.PointData.GetArray('vtkOriginalPointIds')
    result[pointIds] = 1

    import vtk.util.numpy_support as np_s
    vtkarray = np_s.numpy_to_vtk(result, deep=True)
    return dsa.vtkDataArrayToVTKArray(vtkarray)
예제 #5
0
def cellContainsPoint(inputs, locations):
    array = vtkDoubleArray()
    array.SetNumberOfComponents(3)
    array.SetNumberOfTuples(len(locations))
    for i in range(len(locations)):
        array.SetTuple(i, locations[i])
    node = vtkSelectionNode()
    node.SetFieldType(vtkSelectionNode.CELL)
    node.SetContentType(vtkSelectionNode.LOCATIONS)
    node.SetSelectionList(array)

    selection = vtkSelection()
    selection.AddNode(node)
    from vtkmodules.vtkFiltersExtraction import vtkExtractSelectedLocations
    cellsNear = vtkExtractSelectedLocations()
    cellsNear.SetInputData(0, inputs[0].VTKObject)
    cellsNear.SetInputData(1, selection)
    cellsNear.Update()

    extractedCells = cellsNear.GetOutput()
    numCells = inputs[0].GetNumberOfCells()
    result = np.zeros((numCells,), dtype = np.int8)

    extracted = dsa.WrapDataObject(extractedCells)
    cellIds = extracted.CellData.GetArray('vtkOriginalCellIds')

    if isinstance(cellIds, dsa.VTKCompositeDataArray):
        for a in cellIds.GetArrays():
            result[a] = 1
    else:
         result[cellIds] = 1

    import vtkmodules.util.numpy_support as np_s
    vtkarray = np_s.numpy_to_vtk(result, deep=True)
    return dsa.vtkDataArrayToVTKArray(vtkarray)
예제 #6
0
def pointIsNear(locations, distance, inputs):
    array = vtkDoubleArray()
    array.SetNumberOfComponents(3)
    array.SetNumberOfTuples(len(locations))
    for i in range(len(locations)):
        array.SetTuple(i, locations[i])
    node = vtkSelectionNode()
    node.SetFieldType(vtkSelectionNode.POINT)
    node.SetContentType(vtkSelectionNode.LOCATIONS)
    node.GetProperties().Set(vtkSelectionNode.EPSILON(), distance)
    node.SetSelectionList(array)

    from paraview.vtk.vtkFiltersExtraction import vtkLocationSelector
    selector = vtkLocationSelector()
    selector.Initialize(node, "vtkInsidedness")

    inputDO = inputs[0].VTKObject
    outputDO = inputDO.NewInstance()
    outputDO.CopyStructure(inputDO)

    output = dsa.WrapDataObject(outputDO)
    if outputDO.IsA('vtkCompositeDataSet'):
        it = inputDO.NewIterator()
        it.InitTraversal()
        while not it.IsDoneWithTraversal():
            outputDO.SetDataSet(it, inputDO.GetDataSet(it).NewInstance())
            it.GoToNextItem()
    selector.ComputeSelectedElements(inputDO, outputDO)

    return output.PointData.GetArray('vtkInsidedness')
예제 #7
0
def setTimelineData(tbl, dirName, fields=[], positions=[], time=0):
    """Read timeline data and put it into a vtkTable

    Use in 'Programmable Filter'. Set output type to 'vtkTable'.
    To get (for instance) the fields p and U on position 'min' from the timeline data in
    the directory swakExpression_foo in the
    source code write
from PyFoam.Paraview.Data import setTimelineData
setTimelineData(self.GetOutput(),"volumeMinMax_pressureExtreme",positions=["minimum"],fields=["p","magU"])
    """
    actualDir = checkDir(dirName)
    data = TimelinePlot(args=[
        case().name, "--directory=" + actualDir, "--time=" +
        str(time), "--basic-mode=lines", "--numpy"
    ] + ["--field=%s" % f
         for f in fields] + ["--position=%s" % p for p in positions]).data

    for i, n in enumerate(data.dtype.names):
        vals = data[n]
        col = vtk.vtkDoubleArray()
        col.SetName(n)
        for v in vals:
            col.InsertNextValue(v)
        tbl.AddColumn(col)

    return tbl
예제 #8
0
def pointIsNear(locations, distance, inputs):
    array = vtkDoubleArray()
    array.SetNumberOfComponents(3)
    array.SetNumberOfTuples(len(locations))
    for i in range(len(locations)):
        array.SetTuple(i, locations[i])
    node = vtkSelectionNode()
    node.SetFieldType(vtkSelectionNode.POINT)
    node.SetContentType(vtkSelectionNode.LOCATIONS)
    node.GetProperties().Set(vtkSelectionNode.EPSILON(), distance)
    node.SetSelectionList(array)

    from paraview.vtk.vtkFiltersExtraction import vtkLocationSelector
    selector = vtkLocationSelector()
    selector.SetInsidednessArrayName("vtkInsidedness")
    selector.Initialize(node)

    inputDO = inputs[0].VTKObject
    outputDO = inputDO.NewInstance()
    outputDO.CopyStructure(inputDO)

    output = dsa.WrapDataObject(outputDO)
    if outputDO.IsA('vtkCompositeDataSet'):
        it = inputDO.NewIterator()
        it.InitTraversal()
        while not it.IsDoneWithTraversal():
            outputDO.SetDataSet(it, inputDO.GetDataSet(it).NewInstance())
            it.GoToNextItem()
    selector.Execute(inputDO, outputDO)

    return output.PointData.GetArray('vtkInsidedness')
예제 #9
0
파일: Data.py 프로젝트: LeeRuns/PyFoam
def setTimelineData(tbl,dirName,fields=[],positions=[],time=0):
    """Read timeline data and put it into a vtkTable

    Use in 'Programmable Filter'. Set output type to 'vtkTable'.
    To get (for instance) the fields p and U on position 'min' from the timeline data in
    the directory swakExpression_foo in the
    source code write
from PyFoam.Paraview.Data import setTimelineData
setTimelineData(self.GetOutput(),"volumeMinMax_pressureExtreme",positions=["minimum"],fields=["p","magU"])
    """
    actualDir=checkDir(dirName)
    data=TimelinePlot(args=[case().name,
                          "--directory="+actualDir,
                          "--time="+str(time),
                          "--basic-mode=lines",
                          "--numpy"]+
                      ["--field=%s" % f for f in fields]+
                      ["--position=%s" % p for p in positions]).data


    for i,n in enumerate(data.dtype.names):
        vals=data[n]
        col=vtk.vtkDoubleArray()
        col.SetName(n)
        for v in vals:
            col.InsertNextValue(v)
        tbl.AddColumn(col)

    return tbl
예제 #10
0
def cellContainsPoint(inputs, locations):
    array = vtk.vtkDoubleArray()
    array.SetNumberOfComponents(3)
    array.SetNumberOfTuples(len(locations))
    for i in range(len(locations)):
        array.SetTuple(i, locations[i])
    node = vtk.vtkSelectionNode()
    node.SetFieldType(vtk.vtkSelectionNode.CELL)
    node.SetContentType(vtk.vtkSelectionNode.LOCATIONS)
    node.SetSelectionList(array)

    selection = vtk.vtkSelection()
    selection.AddNode(node)
    from vtk.vtkFiltersExtraction import vtkExtractSelectedLocations
    cellsNear = vtkExtractSelectedLocations()
    cellsNear.SetInputData(0, inputs[0].VTKObject)
    cellsNear.SetInputData(1, selection)
    cellsNear.Update()

    extractedCells = cellsNear.GetOutput()
    numCells = inputs[0].GetNumberOfCells()
    result = np.zeros((numCells, ), dtype=np.int8)

    extracted = dsa.WrapDataObject(extractedCells)
    cellIds = extracted.CellData.GetArray('vtkOriginalCellIds')

    if isinstance(cellIds, dsa.VTKCompositeDataArray):
        for a in cellIds.GetArrays():
            result[a] = 1
    else:
        result[cellIds] = 1

    import vtk.util.numpy_support as np_s
    vtkarray = np_s.numpy_to_vtk(result, deep=True)
    return dsa.vtkDataArrayToVTKArray(vtkarray)
def Values2VTKArray(values,n,name):
    ncomps=len(values)/n
    array=vtk.vtkDoubleArray()
    array.SetNumberOfComponents(ncomps)
    array.SetNumberOfTuples(n)
        for i in range(n):
            a = []
            for j in range(ncomps):
                a.append(values[i+j*n])
            array.SetTupleValue(i, a)
def Values2VTKArray(values,n,name):
    ncomps=len(values)/n
    array=vtk.vtkDoubleArray()
    array.SetNumberOfComponents(ncomps)
    array.SetNumberOfTuples(n)
        for i in range(n):
            a = []
            for j in range(ncomps):
                a.append(values[i+j*n])
            array.SetTypedTuple(i, a)
def Values2VTKArray(values, n, name):
    ncomps = len(values) / n
    array = vtk.vtkDoubleArray()
    array.SetNumberOfComponents(ncomps)
    array.SetNumberOfTuples(n)
    i = 0
    for x in values:
        array.SetValue(i, x)
        i += 1
    array.SetName(name)
    return array
def Values2VTKArray(values,n,name):
    ncomps=len(values)/n
    array=vtk.vtkDoubleArray()
    array.SetNumberOfComponents(ncomps)
    array.SetNumberOfTuples(n)
    i=0
    for x in values:
        array.SetValue(i,x)
        i+=1
    array.SetName(name)
    return array
예제 #15
0
    def RequestData(self, request, inInfoVec, outInfoVec):
        from paraview import vtk
        import time
        startTime = time.time()
        pdi = vtk.vtkUnstructuredGrid.GetData(inInfoVec[0], 0)
        pdo = vtk.vtkUnstructuredGrid.GetData(outInfoVec, 0)
        pdo.ShallowCopy(pdi)

        # Assign MaterialIDs
        numcells = pdi.GetNumberOfCells()
        celldata = pdi.GetCellData()
        cellmid = celldata.GetArray("MaterialIDs")
        matIdsRange = cellmid.GetRange()
        numlines = int(matIdsRange[1]) + 1

        # Load data
        firstline = True
        FileName = os.path.normcase(self._csv_file)
        f = open(FileName)
        # Read header
        if firstline:
            firstline = False
            header = f.readline().split(";")

        # How many materialparameter
        numparam = int(len(header))

        # Restore data as List in List
        datalist = []
        for line in f:
            data = line.split(";")
            datalist.append(data)

        # Assign properties to CellData
        for j in range(1, numparam):  # skip first column (MID)
            dataArray = vtk.vtkDoubleArray()
            dataArray.SetNumberOfComponents(1)
            dataArray.SetName(header[j])
            for i in range(numlines):
                for k in range(numcells):
                    t = int(cellmid.GetTuple1(k))
                    dataArray.InsertNextValue(float(datalist[t][j]))
            pdo.GetCellData().AddArray(dataArray)

        print('Material parameters were assigned. It took %8.2f seconds.' %
              (time.time() - startTime))
        return 1
예제 #16
0
def setPlotData(tbl, solverName, plotName):
    """Read plot data and put it into a vtkTable

    Use in 'Programmable Filter'. Set output type to 'vtkTable'.
    To get (for instance) the plot data generated by solver 'compressibleInterFoam'
    (if run with pyFoamRunner.py) under the name 'linear' write
from PyFoam.Paraview.Data import setPlotData
setPlotData(self.GetOutput(),"compressibleInterFoam","linear")
    """
    actualFile = path.join("PyFoamRunner." + solverName + ".analyzed",
                           "pickledPlots")
    data = RedoPlot(
        args=[actualFile, "--pickle-file", "--numpy"]).plotNumpy[plotName]

    for n in data.dtype.names:
        vals = data[n]
        col = vtk.vtkDoubleArray()
        col.SetName(n)
        for v in vals:
            col.InsertNextValue(v)
        tbl.AddColumn(col)

    return tbl
예제 #17
0
파일: Data.py 프로젝트: LeeRuns/PyFoam
def setPlotData(tbl,solverName,plotName):
    """Read plot data and put it into a vtkTable

    Use in 'Programmable Filter'. Set output type to 'vtkTable'.
    To get (for instance) the plot data generated by solver 'compressibleInterFoam'
    (if run with pyFoamRunner.py) under the name 'linear' write
from PyFoam.Paraview.Data import setPlotData
setPlotData(self.GetOutput(),"compressibleInterFoam","linear")
    """
    actualFile=path.join("PyFoamRunner."+solverName+".analyzed","pickledPlots")
    data=RedoPlot(args=[actualFile,
                        "--pickle-file",
                        "--numpy"]).plotNumpy[plotName]

    for n in data.dtype.names:
        vals=data[n]
        col=vtk.vtkDoubleArray()
        col.SetName(n)
        for v in vals:
            col.InsertNextValue(v)
        tbl.AddColumn(col)

    return tbl
예제 #18
0
def pointIsNear(locations, distance, inputs):
    array = vtkDoubleArray()
    array.SetNumberOfComponents(3)
    array.SetNumberOfTuples(len(locations))
    for i in range(len(locations)):
        array.SetTuple(i, locations[i])
    node = vtkSelectionNode()
    node.SetFieldType(vtkSelectionNode.POINT)
    node.SetContentType(vtkSelectionNode.LOCATIONS)
    node.GetProperties().Set(vtkSelectionNode.EPSILON(), distance)
    node.SetSelectionList(array)

    selection = vtkSelection()
    selection.AddNode(node)
    from vtkmodules.vtkFiltersExtraction import vtkExtractSelectedLocations
    pointsNear = vtkExtractSelectedLocations()
    pointsNear.SetInputData(0, inputs[0].VTKObject)
    pointsNear.SetInputData(1, selection)
    pointsNear.Update()

    extractedPoints = pointsNear.GetOutput()
    numPoints = inputs[0].GetNumberOfPoints()
    result = np.zeros((numPoints,), dtype = np.int8)

    extracted = dsa.WrapDataObject(extractedPoints)
    pointIds = extracted.PointData.GetArray('vtkOriginalPointIds')

    if isinstance(pointIds, dsa.VTKCompositeDataArray):
        for a in pointIds.GetArrays():
            result[a] = 1
    else:
         result[pointIds] = 1

    import vtkmodules.util.numpy_support as np_s
    vtkarray = np_s.numpy_to_vtk(result, deep=True)
    return dsa.vtkDataArrayToVTKArray(vtkarray)
예제 #19
0
    def RescaleDataRange(self, view, time):
        """DataRange can change across time, sometime we want to rescale the
           color map to match to the closer actual data range."""
        reps = view.Representations
        for rep in reps:
            if not hasattr(rep, 'Visibility') or \
                not rep.Visibility or \
                not hasattr(rep, 'MapScalars') or \
                not rep.MapScalars or \
                not rep.LookupTable:
                # rep is either not visibile or not mapping scalars using a LUT.
                continue

            input = rep.Input
            input.UpdatePipeline(time)  #make sure range is up-to-date
            lut = rep.LookupTable
            if rep.ColorAttributeType == 'POINT_DATA':
                datainformation = input.GetPointDataInformation()
            elif rep.ColorAttributeType == 'CELL_DATA':
                datainformation = input.GetCellDataInformation()
            else:
                print 'something strange with color attribute type', rep.ColorAttributeType

            if datainformation.GetArray(rep.ColorArrayName) == None:
                # there is no array on this process. it's possible
                # that this process has no points or cells
                continue

            if lut.VectorMode != 'Magnitude' or \
               datainformation.GetArray(rep.ColorArrayName).GetNumberOfComponents() == 1:
                datarange = datainformation.GetArray(
                    rep.ColorArrayName).GetRange(lut.VectorComponent)
            else:
                datarange = [0, 0]
                for i in range(
                        datainformation.GetArray(
                            rep.ColorArrayName).GetNumberOfComponents()):
                    for j in range(2):
                        datarange[j] += datainformation.GetArray(
                            rep.ColorArrayName).GetRange(
                                i)[j] * datainformation.GetArray(
                                    rep.ColorArrayName).GetRange(i)[j]
                datarange[0] = math.sqrt(datarange[0])
                datarange[1] = math.sqrt(datarange[1])

            import vtkParallelCorePython
            import paraview.vtk as vtk
            import paraview.servermanager
            pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
            globalController = pm.GetGlobalController()
            localarray = vtk.vtkDoubleArray()
            localarray.SetNumberOfTuples(2)
            localarray.SetValue(
                0, -datarange[0]
            )  # negate so that MPI_MAX gets min instead of doing a MPI_MIN and MPI_MAX
            localarray.SetValue(1, datarange[1])
            globalarray = vtk.vtkDoubleArray()
            globalarray.SetNumberOfTuples(2)
            globalController.AllReduce(localarray, globalarray, 0)
            globaldatarange = [
                -globalarray.GetValue(0),
                globalarray.GetValue(1)
            ]
            rgbpoints = lut.RGBPoints.GetData()
            numpts = len(rgbpoints) / 4
            if globaldatarange[0] != rgbpoints[0] or globaldatarange[
                    1] != rgbpoints[(numpts - 1) * 4]:
                # rescale all of the points
                oldrange = rgbpoints[(numpts - 1) * 4] - rgbpoints[0]
                newrange = globaldatarange[1] - globaldatarange[0]
                # only readjust if the new range isn't zero.
                if newrange != 0:
                    newrgbpoints = list(rgbpoints)
                    # if the old range isn't 0 then we use that ranges distribution
                    if oldrange != 0:
                        for v in range(numpts - 1):
                            newrgbpoints[v * 4] = globaldatarange[0] + (
                                rgbpoints[v * 4] -
                                rgbpoints[0]) * newrange / oldrange

                        # avoid numerical round-off, at least with the last point
                        newrgbpoints[(numpts - 1) * 4] = globaldatarange[1]
                    else:  # the old range is 0 so the best we can do is to space the new points evenly
                        for v in range(numpts + 1):
                            newrgbpoints[v * 4] = globaldatarange[
                                0] + v * newrange / (1.0 * numpts)

                    lut.RGBPoints.SetData(newrgbpoints)
예제 #20
0
def RescaleDataRange(datadescription, cp_views, timestep):
    import math
    for view in cp_views:
        if timestep % view.cpFrequency == 0 or datadescription.GetForceOutput() == True:
            reps = view.Representations
            for rep in reps:
                if hasattr(rep, 'Visibility') and rep.Visibility == 1 and hasattr(rep, 'MapScalars') and rep.MapScalars != '':
                    input = rep.Input
                    input.UpdatePipeline() #make sure range is up-to-date
                    lut = rep.LookupTable
                    if lut == None:
                        continue
                    if rep.ColorAttributeType == 'POINT_DATA':
                        datainformation = input.GetPointDataInformation()
                    elif rep.ColorAttributeType == 'CELL_DATA':
                        datainformation = input.GetCellDataInformation()
                    else:
                        print 'something strange with color attribute type', rep.ColorAttributeType

                    if datainformation.GetArray(rep.ColorArrayName) == None:
                        # there is no array on this process. it's possible
                        # that this process has no points or cells
                        continue

                    if lut.VectorMode != 'Magnitude' or \
                       datainformation.GetArray(rep.ColorArrayName).GetNumberOfComponents() == 1:
                        datarange = datainformation.GetArray(rep.ColorArrayName).GetRange(lut.VectorComponent)
                    else:
                        datarange = [0,0]
                        for i in range(datainformation.GetArray(rep.ColorArrayName).GetNumberOfComponents()):
                            for j in range(2):
                                datarange[j] += datainformation.GetArray(rep.ColorArrayName).GetRange(i)[j]*datainformation.GetArray(rep.ColorArrayName).GetRange(i)[j]
                        datarange[0] = math.sqrt(datarange[0])
                        datarange[1] = math.sqrt(datarange[1])


                    import vtkParallelCorePython
                    import paraview.vtk as vtk
                    pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
                    globalController = pm.GetGlobalController()
                    localarray = vtk.vtkDoubleArray()
                    localarray.SetNumberOfTuples(2)
                    localarray.SetValue(0, -datarange[0]) # negate so that MPI_MAX gets min instead of doing a MPI_MIN and MPI_MAX
                    localarray.SetValue(1, datarange[1])
                    globalarray = vtk.vtkDoubleArray()
                    globalarray.SetNumberOfTuples(2)
                    globalController.AllReduce(localarray, globalarray, 0)
                    globaldatarange = [-globalarray.GetValue(0), globalarray.GetValue(1)]
                    rgbpoints = lut.RGBPoints.GetData()
                    numpts = len(rgbpoints)/4
                    if globaldatarange[0] != rgbpoints[0] or globaldatarange[1] != rgbpoints[(numpts-1)*4]:
                        # rescale all of the points
                        oldrange = rgbpoints[(numpts-1)*4] - rgbpoints[0]
                        newrange = globaldatarange[1] - globaldatarange[0]
                        # only readjust if the new range isn't zero.
                        if newrange != 0:
                           newrgbpoints = list(rgbpoints)
                           # if the old range isn't 0 then we use that ranges distribution
                           if oldrange != 0:
                              for v in range(numpts-1):
                                 newrgbpoints[v*4] = globaldatarange[0]+(rgbpoints[v*4] - rgbpoints[0])*newrange/oldrange

                              # avoid numerical round-off, at least with the last point
                              newrgbpoints[(numpts-1)*4] = rgbpoints[(numpts-1)*4]
                           else: # the old range is 0 so the best we can do is to space the new points evenly
                              for v in range(numpts+1):
                                 newrgbpoints[v*4] = globaldatarange[0]+v*newrange/(1.0*numpts)

                           lut.RGBPoints.SetData(newrgbpoints)
예제 #21
0
    def RescaleDataRange(self, view, time):
        """DataRange can change across time, sometime we want to rescale the
           color map to match to the closer actual data range."""
        reps = view.Representations
        for rep in reps:
            if not hasattr(rep, 'Visibility') or \
                not rep.Visibility or \
                not hasattr(rep, 'MapScalars') or \
                not rep.MapScalars or \
                not rep.LookupTable:
                # rep is either not visible or not mapping scalars using a LUT.
                continue;

            input = rep.Input
            input.UpdatePipeline(time) #make sure range is up-to-date
            lut = rep.LookupTable

            colorArrayInfo = rep.GetArrayInformationForColorArray()
            if not colorArrayInfo:
                import sys
                datarange = [sys.float_info.max, -sys.float_info.max]
            else:
                if lut.VectorMode != 'Magnitude' or \
                   colorArrayInfo.GetNumberOfComponents() == 1:
                    datarange = colorArrayInfo.GetComponentRange(lut.VectorComponent)
                else:
                    # -1 corresponds to the magnitude.
                    datarange = colorArrayInfo.GetComponentRange(-1)

            from paraview.vtk import vtkDoubleArray
            import paraview.servermanager
            pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
            globalController = pm.GetGlobalController()
            localarray = vtkDoubleArray()
            localarray.SetNumberOfTuples(2)
            localarray.SetValue(0, -datarange[0]) # negate so that MPI_MAX gets min instead of doing a MPI_MIN and MPI_MAX
            localarray.SetValue(1, datarange[1])
            globalarray = vtkDoubleArray()
            globalarray.SetNumberOfTuples(2)
            globalController.AllReduce(localarray, globalarray, 0)
            globaldatarange = [-globalarray.GetValue(0), globalarray.GetValue(1)]
            rgbpoints = lut.RGBPoints.GetData()
            numpts = len(rgbpoints)//4
            if globaldatarange[0] != rgbpoints[0] or globaldatarange[1] != rgbpoints[(numpts-1)*4]:
                # rescale all of the points
                oldrange = rgbpoints[(numpts-1)*4] - rgbpoints[0]
                newrange = globaldatarange[1] - globaldatarange[0]
                # only readjust if the new range isn't zero.
                if newrange != 0:
                   newrgbpoints = list(rgbpoints)
                   # if the old range isn't 0 then we use that ranges distribution
                   if oldrange != 0:
                      for v in range(numpts-1):
                         newrgbpoints[v*4] = globaldatarange[0]+(rgbpoints[v*4] - rgbpoints[0])*newrange/oldrange

                      # avoid numerical round-off, at least with the last point
                      newrgbpoints[(numpts-1)*4] = globaldatarange[1]
                   else: # the old range is 0 so the best we can do is to space the new points evenly
                      for v in range(numpts+1):
                         newrgbpoints[v*4] = globaldatarange[0]+v*newrange/(1.0*numpts)

                   lut.RGBPoints.SetData(newrgbpoints)
예제 #22
0
           j_d=j_d+(1-alpha.GetValue(i))*U.GetComponent(i,0)*A.GetValue(i)
       a_d=a_d/Atotal
       j_a=j_a/Atotal
       j_d=j_d/Atotal
       time.append(k/5)
       a_d_time.append(a_d)
       j_a_time.append(j_a)
       if a_d==0:
           v_d_time.append(0)
       else:
           v_d_time.append(j_d/a_d)
       print('Location at '+str(l)+' and time is '+str(k/5))
#
    T=vtk.vtkTable()
    
    t=vtk.vtkDoubleArray()
    t.SetName("Time [s]")
    for i in time:
        t.InsertNextValue(i)
    T.AddColumn(t)
    
    alpha=vtk.vtkDoubleArray()
    alpha.SetName("Alpha_d")
    for i in a_d_time:
        alpha.InsertNextValue(i)
    T.AddColumn(alpha)
    
    v_j=vtk.vtkDoubleArray()
    v_j.SetName("V_j [m/s]")
    for i in j_a_time:
        v_j.InsertNextValue(i)
예제 #23
0
    else:
        ctype = 0
        numCellPoints = 0
        print("Failed to identify element type")

    return ctype, numCellPoints


# function ends here

ctype, numCellPoints = findCellType(celltype)
#print ctype, numCellPoints

for cell in range(numCells):
    celltype = words[pos2 + cell * (numCellPoints + 3) + 2]
    pos_this_cell = pos2 + cell * (numCellPoints + 3) + 3
    ctype, numCellPoints = findCellType(celltype)
    pointIds = vtk.vtkIdList()
    for pointId in range(numCellPoints):
        pointIds.InsertId(pointId, int(words[pos_this_cell + pointId]))
    output.InsertNextCell(ctype, pointIds)

# For Material properties of cell
numberOfComponents = 1  # For .msh material property by default it is 1
dataArray = vtk.vtkDoubleArray()
output.GetCellData().AddArray(dataArray)
dataArray.SetNumberOfComponents(numberOfComponents)
dataArray.SetName('matgroup')
for cell in range(numCells):
    matgroup = words[pos2 + cell * (numCellPoints + 3) + 1]
    dataArray.InsertNextValue(float(matgroup))
    valid_tuples = []
    for idx, val in idx_vals_tuples:
        if idx < 0 or idx >= nPoints:
            print 'Skipping invalid tuples (%d, %lf)' % (idx, val)
            continue

        valid_tuples.append((idx, val))

    if len(valid_tuples) == 0:
        continue

    vtkPropIdx = vtk.vtkIdTypeArray()
    vtkPropIdx.SetName("PropIdx" + arrayName)
    vtkPropIdx.SetNumberOfValues(len(valid_tuples))

    vtkPropVals = vtk.vtkDoubleArray()
    vtkPropVals.SetName("PropVals" + arrayName)
    vtkPropVals.SetNumberOfValues(len(valid_tuples))

    # Record changes
    for i, (idx, val) in enumerate(valid_tuples):
        vtkPropIdx.SetValue(i, idx)
        vtkPropVals.SetValue(i, val)

    # Set new array
    pdo.GetFieldData().AddArray(vtkPropIdx)
    pdo.GetFieldData().AddArray(vtkPropVals)

################################
# Use vtkStructuredGrid
# has all the right things but extents and bounds and cells seem to get confused and hence
# nothing gets plotted
import numpy
from paraview import vtk
import os
pts = vtk.vtkPoints()
newArray = vtk.vtkDoubleArray()
# this is how far I've got before...
newArray.SetName("testdata")
newArray.SetNumberOfComponents(1)

# stuff our numbers into pdo.GetPointData().GetArray(0).InsertNextValue(float) one by one,
# followed by pts.InsertNextPoint(x,y,z), so need to get xyz as well
xmin, xmax, Nx, ymin, ymax, Ny, zmin, zmax, Nz = -1, 1, 10, -1, 2, 20, -1, 3, 30
loci = numpy.mgrid[xmin:xmax:1j * Nx, ymin:ymax:1j * Ny,
                   zmin:zmax:1j * Nz].reshape(3, -1)
values = numpy.random.random(loci[0].shape)
exts = [0, Nx - 1, 0, Ny - 1, 0, Nz - 1]
pdo.SetExtent(exts)
for ind in range(loci[0].shape[0]):
    newArray.InsertNextValue(values[ind])
    # pts.InsertNextPoint(loci[0,ind],loci[1,ind],loci[2,ind])
pdo = self.GetOutput()
pdo.GetPointData().AddArray(newArray)
# pdo.SetPoints(pts)
# pdo.SetActiveAttribute()

# try to add this
executive = self.GetExecutive()
outInfo = executive.GetOutputInformation(0)
예제 #26
0
import os

filepath="C:\\Users\\jiabin\\Documents\\MATLAB\\python_script\\datafile.txt"
filename=os.path.normcase(filepath)

pts=vtk.vtkPoints()
f=open(filename)
pdo=self.GetOutput()

firstline=True
for line in f:
  if firstline:
    firstline=False
    for pos,word in enumerate(line.split(",")):
      if pos > 2:
        newArray = vtk.vtkDoubleArray()
        newArray.SetName(word)
        newArray.SetNumberOfComponents(1)
        pdo.GetPointData().AddArray(newArray)
  else:
    for pos,word in enumerate(line.split(",")):
      print word
      if pos == 0:
        x = float(word)
      if pos == 1:
        y = float(word)
      if pos == 2:
        z = float(word)
      if pos > 2:
        array = pdo.GetPointData().GetArray(pos-3)
        array.InsertNextValue(float(word))
예제 #27
0
    def RescaleDataRange(self, view, time):
        """DataRange can change across time, sometime we want to rescale the
           color map to match to the closer actual data range."""
        reps = view.Representations
        for rep in reps:
            if not hasattr(rep, 'Visibility') or \
                not rep.Visibility or \
                not hasattr(rep, 'MapScalars') or \
                not rep.MapScalars or \
                not rep.LookupTable:
                # rep is either not visibile or not mapping scalars using a LUT.
                continue;

            input = rep.Input
            input.UpdatePipeline(time) #make sure range is up-to-date
            lut = rep.LookupTable
            if rep.ColorAttributeType == 'POINT_DATA' or rep.ColorAttributeType == "POINTS":
                datainformation = input.GetPointDataInformation()
            elif rep.ColorAttributeType == 'CELL_DATA' or rep.ColorAttributeType == "CELLS":
                datainformation = input.GetCellDataInformation()
            else:
                print 'something strange with color attribute type', rep.ColorAttributeType

            if datainformation.GetArray(rep.ColorArrayName) == None:
                # there is no array on this process. it's possible
                # that this process has no points or cells
                continue

            if lut.VectorMode != 'Magnitude' or \
               datainformation.GetArray(rep.ColorArrayName).GetNumberOfComponents() == 1:
                datarange = datainformation.GetArray(rep.ColorArrayName).GetRange(lut.VectorComponent)
            else:
                # -1 corresponds to the magnitude.
                datarange = datainformation.GetArray(rep.ColorArrayName).GetRange(-1)

            import vtkParallelCorePython
            import paraview.vtk as vtk
            import paraview.servermanager
            pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
            globalController = pm.GetGlobalController()
            localarray = vtk.vtkDoubleArray()
            localarray.SetNumberOfTuples(2)
            localarray.SetValue(0, -datarange[0]) # negate so that MPI_MAX gets min instead of doing a MPI_MIN and MPI_MAX
            localarray.SetValue(1, datarange[1])
            globalarray = vtk.vtkDoubleArray()
            globalarray.SetNumberOfTuples(2)
            globalController.AllReduce(localarray, globalarray, 0)
            globaldatarange = [-globalarray.GetValue(0), globalarray.GetValue(1)]
            rgbpoints = lut.RGBPoints.GetData()
            numpts = len(rgbpoints)/4
            if globaldatarange[0] != rgbpoints[0] or globaldatarange[1] != rgbpoints[(numpts-1)*4]:
                # rescale all of the points
                oldrange = rgbpoints[(numpts-1)*4] - rgbpoints[0]
                newrange = globaldatarange[1] - globaldatarange[0]
                # only readjust if the new range isn't zero.
                if newrange != 0:
                   newrgbpoints = list(rgbpoints)
                   # if the old range isn't 0 then we use that ranges distribution
                   if oldrange != 0:
                      for v in range(numpts-1):
                         newrgbpoints[v*4] = globaldatarange[0]+(rgbpoints[v*4] - rgbpoints[0])*newrange/oldrange

                      # avoid numerical round-off, at least with the last point
                      newrgbpoints[(numpts-1)*4] = globaldatarange[1]
                   else: # the old range is 0 so the best we can do is to space the new points evenly
                      for v in range(numpts+1):
                         newrgbpoints[v*4] = globaldatarange[0]+v*newrange/(1.0*numpts)

                   lut.RGBPoints.SetData(newrgbpoints)
예제 #28
0
    def RescaleDataRange(self, view, time):
        """DataRange can change across time, sometime we want to rescale the
           color map to match to the closer actual data range."""
        reps = view.Representations
        for rep in reps:
            if not hasattr(rep, 'Visibility') or \
                not rep.Visibility or \
                not hasattr(rep, 'MapScalars') or \
                not rep.MapScalars or \
                not rep.LookupTable:
                # rep is either not visible or not mapping scalars using a LUT.
                continue

            input = rep.Input
            input.UpdatePipeline(time)  #make sure range is up-to-date
            lut = rep.LookupTable

            colorArrayInfo = rep.GetArrayInformationForColorArray()
            if not colorArrayInfo:
                import sys
                datarange = [sys.float_info.max, -sys.float_info.max]
            else:
                if lut.VectorMode != 'Magnitude' or \
                   colorArrayInfo.GetNumberOfComponents() == 1:
                    datarange = colorArrayInfo.GetComponentRange(
                        lut.VectorComponent)
                else:
                    # -1 corresponds to the magnitude.
                    datarange = colorArrayInfo.GetComponentRange(-1)

            from paraview.vtk import vtkDoubleArray
            import paraview.servermanager
            pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
            globalController = pm.GetGlobalController()
            localarray = vtkDoubleArray()
            localarray.SetNumberOfTuples(2)
            localarray.SetValue(
                0, -datarange[0]
            )  # negate so that MPI_MAX gets min instead of doing a MPI_MIN and MPI_MAX
            localarray.SetValue(1, datarange[1])
            globalarray = vtkDoubleArray()
            globalarray.SetNumberOfTuples(2)
            globalController.AllReduce(localarray, globalarray, 0)
            globaldatarange = [
                -globalarray.GetValue(0),
                globalarray.GetValue(1)
            ]
            rgbpoints = lut.RGBPoints.GetData()
            numpts = len(rgbpoints) // 4
            if globaldatarange[0] != rgbpoints[0] or globaldatarange[
                    1] != rgbpoints[(numpts - 1) * 4]:
                # rescale all of the points
                oldrange = rgbpoints[(numpts - 1) * 4] - rgbpoints[0]
                newrange = globaldatarange[1] - globaldatarange[0]
                # only readjust if the new range isn't zero.
                if newrange != 0:
                    newrgbpoints = list(rgbpoints)
                    # if the old range isn't 0 then we use that ranges distribution
                    if oldrange != 0:
                        for v in range(numpts - 1):
                            newrgbpoints[v * 4] = globaldatarange[0] + (
                                rgbpoints[v * 4] -
                                rgbpoints[0]) * newrange / oldrange

                        # avoid numerical round-off, at least with the last point
                        newrgbpoints[(numpts - 1) * 4] = globaldatarange[1]
                    else:  # the old range is 0 so the best we can do is to space the new points evenly
                        for v in range(numpts + 1):
                            newrgbpoints[v * 4] = globaldatarange[
                                0] + v * newrange / (1.0 * numpts)

                    lut.RGBPoints.SetData(newrgbpoints)
import os

filepath="/home/jiabin/python/datafile.txt"
filename=os.path.normcase(filepath)

pts=vtk.vtkPoints()
f=open(filename)
pdo=self.GetOutput()

firstline=True
for line in f:
  if firstline:
    firstline=False
    for pos,word in enumerate(line.split(",")):
      if pos > 2:
        newArray = vtk.vtkDoubleArray()
        newArray.SetName(word)
        newArray.SetNumberOfComponents(1)
        pdo.GetPointData().AddArray(newArray)
  else:
    for pos,word in enumerate(line.split(",")):
      print word
      if pos == 0:
        x = float(word)
      if pos == 1:
        y = float(word)
      if pos == 2:
        z = float(word)
      if pos > 2:
        array = pdo.GetPointData().GetArray(pos-3)
        array.InsertNextValue(float(word))