Esempio n. 1
0
def xyplot(points, title='', c='b', corner=1, lines=False):
    """
    Return a vtkActor that is a plot of 2D points in x and y.

    Use corner to assign its position:
        1=topleft, 
        2=topright, 
        3=bottomleft, 
        4=bottomright.
    """
    c = vc.getColor(c)  # allow different codings
    array_x = vtk.vtkFloatArray()
    array_y = vtk.vtkFloatArray()
    array_x.SetNumberOfTuples(len(points))
    array_y.SetNumberOfTuples(len(points))
    for i, p in enumerate(points):
        array_x.InsertValue(i, p[0])
        array_y.InsertValue(i, p[1])
    field = vtk.vtkFieldData()
    field.AddArray(array_x)
    field.AddArray(array_y)
    data = vtk.vtkDataObject()
    data.SetFieldData(field)
    plot = vtk.vtkXYPlotActor()
    plot.AddDataObjectInput(data)
    plot.SetDataObjectXComponent(0, 0)
    plot.SetDataObjectYComponent(0, 1)
    plot.SetXValuesToValue()
    plot.SetXTitle(title)
    plot.SetYTitle('')
    plot.ExchangeAxesOff()
    plot.PlotPointsOn()
    if not lines: plot.PlotLinesOff()
    plot.GetProperty().SetPointSize(5)
    plot.GetProperty().SetLineWidth(2)
    plot.SetNumberOfXLabels(3)  #not working
    plot.GetProperty().SetColor(0, 0, 0)
    plot.GetProperty().SetOpacity(0.7)
    plot.SetPlotColor(0, c[0], c[1], c[2])
    tprop = plot.GetAxisLabelTextProperty()
    tprop.SetColor(0, 0, 0)
    tprop.SetOpacity(0.7)
    tprop.SetFontFamily(0)
    tprop.BoldOff()
    tprop.ItalicOff()
    tprop.ShadowOff()
    tprop.SetFontSize(3)  #not working
    plot.SetAxisTitleTextProperty(tprop)
    plot.SetAxisLabelTextProperty(tprop)
    plot.SetTitleTextProperty(tprop)
    if corner == 1: plot.GetPositionCoordinate().SetValue(.0, .8, 0)
    if corner == 2: plot.GetPositionCoordinate().SetValue(.7, .8, 0)
    if corner == 3: plot.GetPositionCoordinate().SetValue(.0, .0, 0)
    if corner == 4: plot.GetPositionCoordinate().SetValue(.7, .0, 0)
    plot.GetPosition2Coordinate().SetValue(.3, .2, 0)
    return plot
Esempio n. 2
0
def GetActor():
    data1 = vtk.vtkFieldData()
    array1 = vtk.vtkIntArray()
    array1.SetNumberOfComponents(1)
    array1.InsertNextValue(1)
    data1.AddArray(array1)
    sphere = vtk.vtkSphereSource()
    mapper = vtk.vtkPolyDataMapper()
    actor = vtk.vtkActor()
    mapper.SetInput(sphere.GetOutput())
    sphere.GetOutput().SetFieldData(data1)
    actor.SetMapper(mapper)
    return actor
Esempio n. 3
0
def set_field(obj, name, value):
    """
    Adds to an obj an field array name with 1 element value.
    """
    field_data = obj.GetFieldData()
    if not field_data:
        newfd = vtk.vtkFieldData()
        obj.SetFieldData(newfd)
        field_data = newfd
    string_array = vtk.vtkStringArray()
    string_array.SetNumberOfTuples(1)
    string_array.SetValue(0, value)
    string_array.SetName(name)
    field_data.AddArray(string_array)
Esempio n. 4
0
def plot(values):

    # convert data from python list of tuples => vtkFieldData
    xCoords = vtk.vtkFloatArray()
    yCoords = vtk.vtkFloatArray()
    xCoords.SetNumberOfTuples(len(values))
    yCoords.SetNumberOfTuples(len(values))

    for i, v in enumerate(values):
        xCoords.SetTuple1(i, v[0])
        yCoords.SetTuple1(i, v[1])

    curve = vtk.vtkFieldData()
    curve.AddArray(xCoords)
    curve.AddArray(yCoords)

    # create vtkDataObject
    plot = vtk.vtkDataObject()
    plot.SetFieldData(curve)

    # build a vtkXYPlotActor
    xyplot = vtk.vtkXYPlotActor()
    xyplot.AddDataObjectInput(plot)
    #xyplot.SetDataObjectPlotModeToRows()
    xyplot.SetDataObjectXComponent(0, 0)
    xyplot.SetDataObjectYComponent(0, 1)
    xyplot.GetPositionCoordinate().SetValue(0, 0.0, 0)
    xyplot.GetPosition2Coordinate().SetValue(1, 1, 0)
    xyplot.PlotPointsOn()
    xyplot.PlotLinesOn()
    xyplot.GetProperty().SetPointSize(5)
    #xyplot.SetXRange(0, 100)
    #xyplot.SetYRange(0, 20)
    xyplot.SetPlotColor(0, 1, 1, 0)

    # setup renderer / window / interactor
    ren = vtk.vtkRenderer()
    ren.SetBackground(0.1, 0.2, 0.4)
    ren.AddActor2D(xyplot)

    renWin = vtk.vtkRenderWindow()
    renWin.SetSize(1000, 800)
    renWin.AddRenderer(ren)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    renWin.Render()
    iren.Start()
Esempio n. 5
0
 def testMethods(self):
     """Test overloaded methods"""
     # single-argument method vtkTransform::SetMatrix()
     t = vtk.vtkTransform()
     m = vtk.vtkMatrix4x4()
     m.SetElement(0, 0, 2)
     t.SetMatrix(m)
     self.assertEqual(t.GetMatrix().GetElement(0, 0), 2)
     t.SetMatrix([0,1,0,0, 1,0,0,0, 0,0,-1,0, 0,0,0,1])
     self.assertEqual(t.GetMatrix().GetElement(0, 0), 0)
     # mixed number of arguments
     fd = vtk.vtkFieldData()
     fa = vtk.vtkFloatArray()
     fa.SetName("Real")
     ia = vtk.vtkIntArray()
     ia.SetName("Integer")
     fd.AddArray(fa)
     fd.AddArray(ia)
     a = fd.GetArray("Real")
     self.assertEqual(id(a), id(fa))
     i = vtk.mutable(0)
     a = fd.GetArray("Integer", i)
     self.assertEqual(id(a), id(ia))
     self.assertEqual(i, 1)
Esempio n. 6
0
 def testMethods(self):
     """Test overloaded methods"""
     # single-argument method vtkTransform::SetMatrix()
     t = vtk.vtkTransform()
     m = vtk.vtkMatrix4x4()
     m.SetElement(0, 0, 2)
     t.SetMatrix(m)
     self.assertEqual(t.GetMatrix().GetElement(0, 0), 2)
     t.SetMatrix([0, 1, 0, 0, 1, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1])
     self.assertEqual(t.GetMatrix().GetElement(0, 0), 0)
     # mixed number of arguments
     fd = vtk.vtkFieldData()
     fa = vtk.vtkFloatArray()
     fa.SetName("Real")
     ia = vtk.vtkIntArray()
     ia.SetName("Integer")
     fd.AddArray(fa)
     fd.AddArray(ia)
     a = fd.GetArray("Real")
     self.assertEqual(id(a), id(fa))
     i = vtk.mutable(0)
     a = fd.GetArray("Integer", i)
     self.assertEqual(id(a), id(ia))
     self.assertEqual(i, 1)
Esempio n. 7
0
    def Execute(self):

        if (self.InputDirectoryName == None):
            self.PrintError('Error: no directory.')

        if (self.Pattern == None):
            self.PrintError('Error: no pattern.')

        if (self.FirstTimeStep == None):
            self.PrintError('Error: no first timestep.')

        if (self.LastTimeStep == None):
            self.PrintError('Error: no last timestep.')

        if (self.VelocityComponentsArrayNames == None):
            self.PrintError('Error: no VelocityComponentsArrayNames.')

        for root, dirs, files in os.walk(self.InputDirectoryName):
            if root == self.InputDirectoryName:
                fileList = [x for x in files if not (x.startswith('.'))]

        timeIndexList = list(range(self.FirstTimeStep,self.LastTimeStep+1,self.IntervalTimeStep))
        reader = vmtkmeshreader.vmtkMeshReader()
        #if self.VelocityVector or self.WsrVector:
        if self.WsrVector:
            vectorFromComponents = vmtkmeshvectorfromcomponents.vmtkMeshVectorFromComponents()

        u_name = self.VelocityComponentsArrayNames.split(' ')[0]
        v_name = self.VelocityComponentsArrayNames.split(' ')[1]
        w_name = self.VelocityComponentsArrayNames.split(' ')[2]

        if self.Wsr:
            taux_name = self.WsrComponentsArrayNames.split(' ')[0]
            tauy_name = self.WsrComponentsArrayNames.split(' ')[1]
            tauz_name = self.WsrComponentsArrayNames.split(' ')[2]

        field = vtk.vtkFieldData()
        field.AllocateArrays(1)
        timesteps = vtk.vtkIntArray()
        timesteps.SetNumberOfComponents(1)
        timesteps.SetName("timesteps")
        i = 0
        for step in timeIndexList:
            if (self.Pattern%step).replace(' ','0') in fileList:
                timesteps.InsertTuple1(i, step)
                i+=1

                fileName = (self.Pattern%step).replace(' ','0')
                timeIndex = step
                reader.InputFileName = os.path.abspath(os.path.join(self.InputDirectoryName,fileName))
                reader.Execute()
                mesh = reader.Mesh

                if step == self.FirstTimeStep:
                    mesh.CopyStructure(mesh)
                    self.Mesh = mesh

                if self.Pressure:
                    p = mesh.GetPointData().GetArray(self.PressureArrayName)
                    p.SetName(self.PressureArrayName+str(step))
                    self.Mesh.GetPointData().AddArray(p)

                if self.Wsr:
                    taux = mesh.GetPointData().GetArray(taux_name)
                    taux.SetName(taux_name+str(step))
                    self.Mesh.GetPointData().AddArray(taux)

                    tauy = mesh.GetPointData().GetArray(tauy_name)
                    tauy.SetName(tauy_name+str(step))
                    self.Mesh.GetPointData().AddArray(tauy)

                    tauz = mesh.GetPointData().GetArray(tauz_name)
                    tauz.SetName(tauz_name+str(step))
                    self.Mesh.GetPointData().AddArray(tauz)


                if self.VelocityVector:

                  j = 0

                  u_component = vtk.vtkDoubleArray()
                  u_component.SetNumberOfComponents(1)

                  v_component = vtk.vtkDoubleArray()
                  v_component.SetNumberOfComponents(1)

                  w_component = vtk.vtkDoubleArray()
                  w_component.SetNumberOfComponents(1)


                  while j < mesh.GetPointData().GetArray(self.VelocityVectorArrayName).GetNumberOfTuples():

                    u_val = mesh.GetPointData().GetArray(self.VelocityVectorArrayName).GetComponent(j,0)
                    v_val = mesh.GetPointData().GetArray(self.VelocityVectorArrayName).GetComponent(j,1)
                    w_val = mesh.GetPointData().GetArray(self.VelocityVectorArrayName).GetComponent(j,2)

                    u_component.InsertTuple1(j, u_val)
                    v_component.InsertTuple1(j, v_val)
                    w_component.InsertTuple1(j, w_val)

                    j+=1

                  u_component.SetName(u_name+"_"+str(step))
                  self.Mesh.GetPointData().AddArray(u_component)

                  v_component.SetName(v_name+"_"+str(step))
                  self.Mesh.GetPointData().AddArray(v_component)

                  w_component.SetName(w_name+"_"+str(step))
                  self.Mesh.GetPointData().AddArray(w_component)

                else:

                  u = mesh.GetPointData().GetArray(u_name)
                  u.SetName(u_name+"_"+str(step))
                  self.Mesh.GetPointData().AddArray(u)

                  v = mesh.GetPointData().GetArray(v_name)
                  v.SetName(v_name+"_"+str(step))
                  self.Mesh.GetPointData().AddArray(v)

                  w = mesh.GetPointData().GetArray(w_name)
                  w.SetName(w_name+"_"+str(step))
                  self.Mesh.GetPointData().AddArray(w)

                if self.WsrVector:
                    vectorFromComponents.Mesh = self.Mesh
                    vectorFromComponents.VectorArrayName = "Wsr_"+str(step)
                    vectorFromComponents.ComponentsArrayNames = [taux.GetName(),tauy.GetName(),tauz.GetName()]
                    vectorFromComponents.RemoveComponentArrays = True
                    vectorFromComponents.Execute()

        field.AddArray(timesteps)
        self.Mesh.SetFieldData(field)
Esempio n. 8
0
# create points
pts = vtk.vtkPoints()
npts = d.shape[0]
vrt = vtk.vtkCellArray()
for i in xrange(0, npts):
    id = pts.InsertNextPoint(d[i])
    vrt.InsertNextCell(1)
    vrt.InsertCellPoint(id)

pd = vtk.vtkPolyData()
pd.SetPoints(pts)
pd.SetVerts(vrt)

# add data
field = vtk.vtkFieldData()
field.AllocateArrays(1)
arr = vtk.vtkFloatArray()
arr.SetNumberOfComponents(1)
arr.SetName('dummy')
k = 0
for i in xrange(0, npts):
    arr.InsertTuple1(k, energy)
    k = k + 1
field.AddArray(arr)
pd.SetFieldData(field)

# write to disk
ofile = 'data_vhd_%d.vtp' % (energy * 10)
wrt = vtk.vtkXMLPolyDataWriter()
wrt.SetFileName(ofile)
Esempio n. 9
0
        def parseFile():
            f = open(VTK_DATA_ROOT + "/Data/financial.txt", "r")

            line = f.readline().split()
            # From the size calculate the number of lines.
            numPts = int(line[1])
            numLines = (numPts - 1) / 8 + 1

            # create the data object
            field = vtk.vtkFieldData()
            field.AllocateArrays(4)

            # read TIME_LATE - dependent variable
            while True:
                line = f.readline().split()
                if len(line) > 0:
                    break;
            timeLate = vtk.vtkFloatArray()
            timeLate.SetName(line[0])
            for i in range(0, numLines):
                line = f.readline().split()
                for j in line:
                    timeLate.InsertNextValue(float(j))
            field.AddArray(timeLate)

            # MONTHLY_PAYMENT - independent variable
            while True:
                line = f.readline().split()
                if len(line) > 0:
                    break;
            monthlyPayment = vtk.vtkFloatArray()
            monthlyPayment.SetName(line[0])
            for i in range(0, numLines):
                line = f.readline().split()
                for j in line:
                    monthlyPayment.InsertNextValue(float(j))
            field.AddArray(monthlyPayment)

            # UNPAID_PRINCIPLE - skip
            while True:
                line = f.readline().split()
                if len(line) > 0:
                    break;
            for i in range(0, numLines):
                line = f.readline()

            # LOAN_AMOUNT - skip
            while True:
                line = f.readline().split()
                if len(line) > 0:
                    break;
            for i in range(0, numLines):
                line = f.readline()

            # INTEREST_RATE - independent variable
            while True:
                line = f.readline().split()
                if len(line) > 0:
                    break;
            interestRate = vtk.vtkFloatArray()
            interestRate.SetName(line[0])
            for i in range(0, numLines):
                line = f.readline().split()
                for j in line:
                    interestRate.InsertNextValue(float(j))
            field.AddArray(interestRate)

            # MONTHLY_INCOME - independent variable
            while True:
                line = f.readline().split()
                if len(line) > 0:
                    break;
            monthlyIncome = vtk.vtkFloatArray()
            monthlyIncome.SetName(line[0])
            for i in range(0, numLines):
                line = f.readline().split()
                for j in line:
                    monthlyIncome.InsertNextValue(float(j))
            field.AddArray(monthlyIncome)

            dos.GetOutput().SetFieldData(field)
Esempio n. 10
0
    # here adapted from the C++ of a vtk-users mailing list reply by Sander
    # Niemeijer)
    _xData = vtk.vtkDataArray.CreateDataArray(vtk.VTK_FLOAT)
    _xData.SetNumberOfTuples(len(x))

    _yData = vtk.vtkDataArray.CreateDataArray(vtk.VTK_FLOAT)
    _yData.SetNumberOfTuples(len(y))

    # put the data into the data arrays
    for i in range(len(x)):
        _xData.SetTuple1(i,x[i])
        _yData.SetTuple1(i,y[i])

    # create a field data object 
    # (I think this is as a containter to hold the data arrays)
    _fieldData = vtk.vtkFieldData()
    _fieldData.AllocateArrays(2)
    _fieldData.AddArray(_xData)
    _fieldData.AddArray(_yData)

    # now put the field data object into a data object so that can add it as
    # input to the xyPlotActor
    _dataObject = vtk.vtkDataObject()
    _dataObject.SetFieldData(_fieldData)

    # set up the actor
    _plot = vtk.vtkXYPlotActor()
    _plot.AddDataObjectInput(_dataObject)

    # set the title and stuff
    _plot.SetTitle("Example 2D plot")
Esempio n. 11
0
_yData2 = vtk.vtkDataArray.CreateDataArray(vtk.VTK_FLOAT)
_yData2.SetNumberOfTuples(len(y2))

_yData3 = vtk.vtkDataArray.CreateDataArray(vtk.VTK_FLOAT)
_yData3.SetNumberOfTuples(len(y3))

# put the data into the data arrays
for i in range(len(x)):
    _xData.SetTuple1(i,x[i])
    _yData1.SetTuple1(i,y1[i])
    _yData2.SetTuple1(i,y2[i])
    _yData3.SetTuple1(i,y3[i])

# create a field data object 
# (I think this is as a containter to hold the data arrays)
_fieldData1 = vtk.vtkFieldData()
_fieldData1.AllocateArrays(2)
_fieldData1.AddArray(_xData)
_fieldData1.AddArray(_yData1)

_fieldData2 = vtk.vtkFieldData()
_fieldData2.AllocateArrays(2)
_fieldData2.AddArray(_xData)
_fieldData2.AddArray(_yData2)

_fieldData3 = vtk.vtkFieldData()
_fieldData3.AllocateArrays(2)
_fieldData3.AddArray(_xData)
_fieldData3.AddArray(_yData3)

# now put the field data object into a data object so that can add it as
Esempio n. 12
0
        def parseFile():
            f = open(VTK_DATA_ROOT + "/Data/financial.txt", "r")

            line = f.readline().split()
            # From the size calculate the number of lines.
            numPts = int(line[1])
            numLines = (numPts - 1) / 8 + 1

            # create the data object
            field = vtk.vtkFieldData()
            field.AllocateArrays(4)

            # read TIME_LATE - dependent variable
            while True:
                line = f.readline().split()
                if len(line) > 0:
                    break
            timeLate = vtk.vtkFloatArray()
            timeLate.SetName(line[0])
            for i in range(0, numLines):
                line = f.readline().split()
                for j in line:
                    timeLate.InsertNextValue(float(j))
            field.AddArray(timeLate)

            # MONTHLY_PAYMENT - independent variable
            while True:
                line = f.readline().split()
                if len(line) > 0:
                    break
            monthlyPayment = vtk.vtkFloatArray()
            monthlyPayment.SetName(line[0])
            for i in range(0, numLines):
                line = f.readline().split()
                for j in line:
                    monthlyPayment.InsertNextValue(float(j))
            field.AddArray(monthlyPayment)

            # UNPAID_PRINCIPLE - skip
            while True:
                line = f.readline().split()
                if len(line) > 0:
                    break
            for i in range(0, numLines):
                line = f.readline()

            # LOAN_AMOUNT - skip
            while True:
                line = f.readline().split()
                if len(line) > 0:
                    break
            for i in range(0, numLines):
                line = f.readline()

            # INTEREST_RATE - independent variable
            while True:
                line = f.readline().split()
                if len(line) > 0:
                    break
            interestRate = vtk.vtkFloatArray()
            interestRate.SetName(line[0])
            for i in range(0, numLines):
                line = f.readline().split()
                for j in line:
                    interestRate.InsertNextValue(float(j))
            field.AddArray(interestRate)

            # MONTHLY_INCOME - independent variable
            while True:
                line = f.readline().split()
                if len(line) > 0:
                    break
            monthlyIncome = vtk.vtkFloatArray()
            monthlyIncome.SetName(line[0])
            for i in range(0, numLines):
                line = f.readline().split()
                for j in line:
                    monthlyIncome.InsertNextValue(float(j))
            field.AddArray(monthlyIncome)

            dos.GetOutput().SetFieldData(field)
Esempio n. 13
0
def write_to_vtu(bvp, filename, time_steps=None, remove_old=False):

    # requires vtk support:
    import vtk

    if remove_old:
        import os
        os.system('rm ' + filename + '*.vtk')
    #
    # write

    #fid = open(filename+'.vtk','w')
    #
    # mesh info to vtk objects:
    #XY = reslt['mesh']['nodal_coord']
    #bvp.nodes
    #EL = reslt['mesh']['connectivity']

    #DIM = reslt['mesh']['dimension']

    # if no time stamp, or list of time stamps, do the last
    time_format = bvp.time_format
    if time_steps is None:
        try:
            time_steps = bvp.time_steps
        except:
            print("No time step information in BVP dictionary \n\t>> EXITING")
            return

    #

    #
    # add points:
    points = vtk.vtkPoints()
    for pi, px in bvp.nodes.items():
        points.InsertPoint(pi, tuple(px))

    # number of points:
    nnodes = list(bvp.nodes.keys()).__len__()
    #
    # add cells:
    cellArray = vtk.vtkCellArray()
    cellTypes = []

    new_el_nrs = {}
    el_i = 0
    for old_el in bvp.elements.keys():
        new_el_nrs[old_el] = el_i
        el_i += 1

        if bvp._el_type[old_el] in ['cpe4', 'cpe4r', 'cps4', 'cps4r']:
            cell = vtk.vtkQuad()
            cellTypes += [vtk.VTK_QUAD]
            for i in range(4):
                cell.GetPointIds().SetId(i, bvp.elements[old_el][i])

        elif bvp._el_type[old_el] in ['cpe8', 'cpe8r', 'cps8', 'cps48']:
            cell = vtk.vtkQuadraticQuad()
            cellTypes += [vtk.VTK_QUADRATIC_QUAD]
            for i in range(8):
                cell.GetPointIds().SetId(i, bvp.elements[old_el][i])

        cellArray.InsertNextCell(cell)

    #for x,y in XY:
    #points.InsertNextPoint(x,y,0)

    #if DIM == 2:
    ## create VTK point array:
    #points = vtk.vtkPoints()
    #for x,y in XY:
    #points.InsertNextPoint(x,y,0)

    ## create VTK cell array:
    #cellArray = vtk.vtkCellArray()
    #cellTypes = []
    #for elnr,ndlst in enumerate(EL):
    ## only 2d so number of nodes dictate element type:
    ## 2 = line segment # VTK_LINE (cell type = 3)
    #if ndlst.size == 2:
    #cell = vtk.vtkLine()
    #cellTypes += [vtk.VTK_LINE]
    ## 3 = triangle # VTK_TRIANGLE (cell type = 5)
    #if ndlst.size == 3:
    #cell = vtk.vtkTriangle()
    #cellTypes += [vtk.VTK_TRIANGLE]
    ## 4 = quad # VTK_QUAD (cell type = 9)
    #if ndlst.size == 4:
    #cell = vtk.vtkQuad()
    #cellTypes += [vtk.VTK_QUAD]
    ## 6 = quadratic triangle # VTK_QUADRATIC_TRIANGLE (cell type = 22)
    #if ndlst.size == 6:
    #cell = vtk.vtkQuadraticTriangle()
    #cellTypes += [vtk.VTK_QUADRATIC_TRIANGLE]
    ## 8 = quadratic quad # VTK_QUADRATIC_QUAD (cell type = 23)
    #if ndlst.size == 8:
    #cell = vtk.vtkQuadraticQuad()
    #cellTypes += [vtk.VTK_QUADRATIC_QUAD]
    ## 9 = bi-quadratic quad # VTK_BIQUADRATIC_QUAD (cell type = 28)
    #if ndlst.size == 9:
    #cell = vtk.vtkBiQuadraticQuad()
    #cellTypes += [vtk.VTK_QUADRATIC_QUAD]

    #for i,v in enumerate(ndlst):
    #cell.GetPointIds().SetId(i,v)
    ##
    #cellArray.InsertNextCell(cell)

    #

    #grid0 = vtk.vtkUnstructuredGrid()
    #grid0.SetPoints(points)
    #grid0.SetCells(cellTypes,cellArray)

    grid = vtk.vtkUnstructuredGrid()
    grid.SetPoints(points)
    grid.SetCells(cellTypes, cellArray)

    #vtuWriter = vtk.vtkXMLPUnstructuredGridWriter()
    #vtuWriter = vtk.vtkXMLUnstructuredGridWriter()

    #vtuWriter.SetInputDataObject(grid)
    #vtuWriter.SetFileName(filename+'.vtu')
    #vtuWriter.SetNumberOfTimeSteps(time_steps.__len__())
    #vtuWriter.SetDataModeToAscii()
    #vtuWriter.SetCompressorTypeToNone()

    #vtuWriter.Start()

    nr_of_files = time_steps.__len__()

    file_suffix = ''

    if nr_of_files > 1:
        # first find the time scale factor:
        time_sf = 1
        inctsf = any(np.array(time_steps) * 10**time_sf % 1)
        while inctsf:
            times2 = np.array(time_steps) * 10**time_sf // 1
            if np.unique(times2).size == nr_of_files:
                inctsf = False
            else:
                time_sf += 1
                inctsf = any(np.array(time_steps) * 10**time_sf % 1)

        file_suffix0 = '%' + '0%i' % (time_sf + 1) + 'i'

    for tt in time_steps:

        timef = time_format % tt

        #grid = grid0.NewInstance()
        # element values:

        if timef in bvp.ISVs.keys():

            print('**** Writing output for time stamp <<%s>>' % timef)

            # add time to vtk file:
            TA = vtk.vtkDoubleArray()
            TA.SetName('TIME')
            TA.SetNumberOfComponents(1)
            TA.InsertNextTuple1(tt)
            FD = vtk.vtkFieldData()
            FD.AddArray(TA)
            grid.SetFieldData(FD)
            grid.Modified()

            El_vals = bvp.ISVs[timef]

            # element averaging of each possible element ISV:

            #isvnames = ['temp_el','temp_rate','strain','stress']
            isvnames = [
                'strain', 'stress', 'cauchy', 'temp_rate', 'plastic strain',
                'equivalent plastic'
            ]

            isv4comp = ['strain', 'stress', 'cauchy', 'plastic strain']

            for isn in isvnames:

                do_isn = False

                Iavg = vtk.vtkFloatArray()
                Iavg.SetName('EA_' + isn)

                # also nodal Averaged:
                #nd_avg_name = 'NA_'+isn
                nd_avg_name = isn

                ND_I = bvp.NodeVals[timef][nd_avg_name] = {}
                ND_W = bvp.NodeVals[timef]['NA_weights'] = {}

                #number of components:
                ncomp = 1
                #if (isn == 'strain')|(isn=='stress'):
                if isn in isv4comp:
                    ncomp = 4
                    Imises = vtk.vtkFloatArray()
                    Imises.SetName('EA_' + isn + '_vM')

                # loop over elements
                for el_id in El_vals.keys():

                    ind = new_el_nrs[el_id]
                    gp_vals = El_vals[el_id]
                    #
                    el_avg = [0] * 4

                    if isn in gp_vals[1].keys():

                        # if any of the elements have a particular ISV = output that ISV (others are 0)
                        do_isn = True

                        isvR = {}
                        for gp in gp_vals.keys():
                            isvR[gp] = gp_vals[gp][isn]

                        # element connectivity and coordinates:
                        el_connect = bvp.elements[el_id]
                        #X = [bvp.nodes[nd_Id][0] for nd_Id in el_connect]
                        #Y = [bvp.nodes[nd_Id][1] for nd_Id in el_connect]
                        #XY   = np.c_[X, Y];

                        if list(gp_vals.keys()).__len__(
                        ) == 4:  # 2x2 gauss (weighting = 1 per integration point)
                            el_avg = np.average(
                                [gp_vals[i][isn] for i in range(1, 5)],
                                0).flatten()

                            #
                            NDvals = FE_shapefn.Extrapolate_2x2(
                                isvR, el_connect.__len__())
                            for nd_nr in range(el_connect.__len__()):
                                nd_Id = el_connect[nd_nr]
                                try:
                                    ND_I[nd_Id] += NDvals[nd_nr]
                                    ND_W[nd_Id] += 1
                                except:
                                    ND_I[nd_Id] = NDvals[nd_nr]
                                    ND_W[nd_Id] = 1

                    # Add the ISV to the float array
                    if ncomp == 4:
                        Iavg.SetNumberOfComponents(4)  # 11, 22, 33, 12
                        Iavg.InsertTuple4(ind, el_avg[0], el_avg[1], el_avg[2],
                                          el_avg[3])

                        mises_val = np.sqrt(
                            ((el_avg[0] - el_avg[1])**2 +
                             (el_avg[1] - el_avg[2])**2 +
                             (el_avg[2] - el_avg[0])**2 + 6 * el_avg[3]**2) /
                            2)

                        Imises.InsertTuple1(ind, mises_val)

                    else:
                        Iavg.InsertTuple1(ind, el_avg[0])

                if do_isn:

                    grid.GetCellData().SetActiveScalars('EA_' + isn)
                    grid.GetCellData().SetScalars(Iavg)
                    if ncomp == 4:
                        grid.GetCellData().SetActiveScalars('EA_' + isn +
                                                            '_vM')
                        grid.GetCellData().SetScalars(Imises)

                    # rescale the nodal averaged ISVs:
                    for nd_Id in ND_I.keys():
                        ND_I[nd_Id] /= ND_W[nd_Id]

                else:
                    del (
                        ND_I
                    )  # the specific internal state variable is unavailable
                #
                #

        if timef in bvp.NodeVals.keys():

            Nd_vals = bvp.NodeVals[timef]

            if 'temperature' in Nd_vals.keys():
                # temeparature is a scalar value:
                scalars = vtk.vtkFloatArray()
                scalars.SetName('Temperature')
                for ind in bvp.nodes.keys():
                    val = 0.
                    if ind in Nd_vals['temperature'].keys():
                        val = Nd_vals['temperature'][ind]

                #for ind,val in Nd_vals['temp_nd'].items():
                    scalars.InsertTuple1(ind, val)

                grid.GetPointData().SetActiveScalars('Temperature')
                grid.GetPointData().SetScalars(scalars)

            if 'displacement' in Nd_vals.keys():

                vector = vtk.vtkFloatArray()
                vector.SetNumberOfComponents(3)
                vector.SetName('Displacement')
                for ind in bvp.nodes.keys():
                    val = [0., 0., 0.]  # displacement field
                    if ind in Nd_vals['displacement'].keys():
                        val = Nd_vals['displacement'][ind] + [0.]

                #for ind,val in Nd_vals['temp_nd'].items():
                    vector.InsertTuple3(ind, val[0], val[1], val[2])

                grid.GetPointData().SetActiveVectors('Displacement')
                grid.GetPointData().SetVectors(vector)

            if 'strain' in Nd_vals.keys():

                scalars = vtk.vtkFloatArray()
                scalars.SetNumberOfComponents(6)
                scalars.SetName('Strain')
                for ind in bvp.nodes.keys():
                    val = [0.] * 4
                    if ind in Nd_vals['strain'].keys():
                        val = list(np.array(
                            Nd_vals['strain'][ind]).flatten()) + [0.] * 4

                #for ind,val in Nd_vals['temp_nd'].items():
                    scalars.InsertTuple6(ind, val[0], val[1], val[2], val[3],
                                         0., 0.)
                    #scalars.InsertTuple4(ind,val[0],val[1],val[2],val[3])

                grid.GetPointData().SetActiveScalars('Strain')
                grid.GetPointData().SetScalars(scalars)

            if 'plastic strain' in Nd_vals.keys():

                #print("DOING PLASTIC")
                #print(Nd_vals.keys())
                #print(Nd_vals['plastic strain'])

                scalars = vtk.vtkFloatArray()
                scalars.SetNumberOfComponents(6)
                scalars.SetName('Plastic Strain')
                for ind in bvp.nodes.keys():
                    val = [0.] * 4
                    if ind in Nd_vals['plastic strain'].keys():
                        val = list(
                            np.array(Nd_vals['plastic strain']
                                     [ind]).flatten()) + [0.] * 4

                #for ind,val in Nd_vals['temp_nd'].items():
                    scalars.InsertTuple6(ind, val[0], val[1], val[2], val[3],
                                         0., 0.)
                    #scalars.InsertTuple4(ind,val[0],val[1],val[2],val[3])

                grid.GetPointData().SetActiveScalars('Plastic Strain')
                grid.GetPointData().SetScalars(scalars)

            if 'equivalent plastic' in Nd_vals.keys():

                grid.GetPointData().SetActiveScalars('PEEQ')
                scalars = vtk.vtkFloatArray()
                scalars.SetName('PEEQ')
                for ind in bvp.nodes.keys():
                    val = 0.
                    if ind in Nd_vals['equivalent plastic'].keys():
                        val = Nd_vals['equivalent plastic'][ind]

                #for ind,val in Nd_vals['temp_nd'].items():
                    scalars.InsertTuple1(ind, val)

                grid.GetPointData().SetScalars(scalars)

            if 'stress' in Nd_vals.keys():

                scalars = vtk.vtkFloatArray()
                scalars.SetNumberOfComponents(6)
                scalars.SetName('Stress')

                ssVM = vtk.vtkFloatArray()
                ssVM.SetName('von Mises Stress')

                for ind in bvp.nodes.keys():
                    val = [0.] * 4
                    if ind in Nd_vals['stress'].keys():
                        val = list(np.array(Nd_vals['stress'][ind]).flatten())

                    scalars.InsertTuple6(ind, val[0], val[1], val[2], val[3],
                                         0., 0.)

                    mises_val = np.sqrt(
                        ((val[0] - val[1])**2 + (val[1] - val[2])**2 +
                         (val[2] - val[0])**2 + 6 * val[3]**2) / 2)

                    ssVM.InsertTuple1(ind, mises_val)

                grid.GetPointData().SetActiveScalars('Stress')
                grid.GetPointData().SetScalars(scalars)
                grid.GetPointData().SetActiveScalars('von Mises Stress')
                grid.GetPointData().SetScalars(ssVM)

        grid.Modified()

        if nr_of_files > 1:
            file_suffix = file_suffix0 % (int(round(tt * 10**time_sf)))

        vtkWriter = vtk.vtkUnstructuredGridWriter()
        vtkWriter.SetInputData(grid)
        vtkWriter.SetFileTypeToASCII()
        #vtkWriter.SetFileName(filename+'_'+timef+'.vtk')
        vtkWriter.SetFileName(filename + file_suffix + '.vtk')
        vtkWriter.Write()

        #vtuWriter.WriteNextTime(tt)

    #vtuWriter.Stop()

    # return
    return  #vtuWriter,grid
Esempio n. 14
0
def cornerPlot(points, pos=1, s=0.2, title="", c="b", bg="k", lines=True):
    """
    Return a ``vtkXYPlotActor`` that is a plot of `x` versus `y`,
    where `points` is a list of `(x,y)` points.

    :param int pos: assign position:

        - 1, topleft,
        - 2, topright,
        - 3, bottomleft,
        - 4, bottomright.
    """
    if len(points) == 2:  # passing [allx, ally]
        #points = list(zip(points[0], points[1]))
        points = np.stack((points[0], points[1]), axis=1)

    c = colors.getColor(c)  # allow different codings
    array_x = vtk.vtkFloatArray()
    array_y = vtk.vtkFloatArray()
    array_x.SetNumberOfTuples(len(points))
    array_y.SetNumberOfTuples(len(points))
    for i, p in enumerate(points):
        array_x.InsertValue(i, p[0])
        array_y.InsertValue(i, p[1])
    field = vtk.vtkFieldData()
    field.AddArray(array_x)
    field.AddArray(array_y)
    data = vtk.vtkDataObject()
    data.SetFieldData(field)

    plot = vtk.vtkXYPlotActor()
    plot.AddDataObjectInput(data)
    plot.SetDataObjectXComponent(0, 0)
    plot.SetDataObjectYComponent(0, 1)
    plot.SetXValuesToValue()
    plot.SetAdjustXLabels(0)
    plot.SetAdjustYLabels(0)
    plot.SetNumberOfXLabels(3)

    plot.GetProperty().SetPointSize(5)
    plot.GetProperty().SetLineWidth(2)
    plot.GetProperty().SetColor(colors.getColor(bg))
    plot.SetPlotColor(0, c[0], c[1], c[2])

    plot.SetXTitle(title)
    plot.SetYTitle("")
    plot.ExchangeAxesOff()
    plot.PlotPointsOn()
    if not lines:
        plot.PlotLinesOff()
    if pos == 1:
        plot.GetPositionCoordinate().SetValue(0.0, 0.8, 0)
    elif pos == 2:
        plot.GetPositionCoordinate().SetValue(0.76, 0.8, 0)
    elif pos == 3:
        plot.GetPositionCoordinate().SetValue(0.0, 0.0, 0)
    elif pos == 4:
        plot.GetPositionCoordinate().SetValue(0.76, 0.0, 0)
    else:
        plot.GetPositionCoordinate().SetValue(pos[0], pos[1], 0)
    plot.GetPosition2Coordinate().SetValue(s, s, 0)
    return plot
Esempio n. 15
0
File: banana.py Progetto: 0004c/VTK
    pt = sphereData.GetPoint(i)
    x = pt[0]
    y = pt[1]
    z = pt[2]
    zn = z + 0.5
    zn1 = 1.0 - zn
    if (zn > 1.0):
        zn = 1.0
    if (zn1 < 0.0):
        zn1 = 0.0
    tfarray.SetComponent(i, 0, zn1)
    tfarray.SetComponent(i, 1, zn)
    i += 1

# create field data to hold the array, and bind it to the sphere
fd = vtk.vtkFieldData()
tfarray.SetName("weights")
sphereData.GetPointData().AddArray(tfarray)

# use an ordinary transform to stretch the shape
stretch = vtk.vtkTransform()
stretch.Scale(1, 1, 3.2)

stretchFilter = vtk.vtkTransformFilter()
stretchFilter.SetInputData(sphereData)
stretchFilter.SetTransform(stretch)

# now, for the weighted transform stuff
weightedTrans = vtk.vtkWeightedTransformFilter()

# create two transforms to interpolate between
Esempio n. 16
0
_yData6 = vtk.vtkDataArray.CreateDataArray(vtk.VTK_FLOAT)
_yData6.SetNumberOfTuples(len(y6))

# put the data into the data arrays
for i in range(len(x)):
    _xData.SetTuple1(i,x[i])
    _yData1.SetTuple1(i,y1[i])
    _yData2.SetTuple1(i,y2[i])
    _yData3.SetTuple1(i,y3[i])
    _yData4.SetTuple1(i,y4[i])
    _yData5.SetTuple1(i,y5[i])
    _yData6.SetTuple1(i,y6[i])

# create a field data object 
# (I think this is as a containter to hold the data arrays)
_fieldData1 = vtk.vtkFieldData()
_fieldData1.AllocateArrays(2)
_fieldData1.AddArray(_xData)
_fieldData1.AddArray(_yData1)

_fieldData2 = vtk.vtkFieldData()
_fieldData2.AllocateArrays(2)
_fieldData2.AddArray(_xData)
_fieldData2.AddArray(_yData2)

_fieldData3 = vtk.vtkFieldData()
_fieldData3.AllocateArrays(2)
_fieldData3.AddArray(_xData)
_fieldData3.AddArray(_yData3)

_fieldData4 = vtk.vtkFieldData()
Esempio n. 17
0
    sys.exit(1)
(in_file, out_file) = args

f = open(in_file + ".dat", 'r')
#output = vtk.vtkPolyData()
output = vtk.vtkStructuredPoints()

nodes = []
nodes_array = vtk.vtkIntArray()
nodes_array.SetName("nodes")
node_x = []
node_y = []
node_z = []
counter = 0
point = vtk.vtkPoints()
field_data = vtk.vtkFieldData()

for line in f:
    if not line.split():
        continue

    tuple = ()
    tuple = line.split()

    nodes_array.InsertNextValue(counter)
    nodes.append(tuple[0])
    node_x.append(tuple[1])
    node_y.append(tuple[2])
    node_z.append(tuple[3])
    field_data.AddArray(nodes_array)
    counter += 1
Esempio n. 18
0
    def __init__(self, dataDir = 'data/', fileName = 'var.dat', streamFile = 'stream.vtk', interpolation = 'weighted', integration = 'RK6', hMin = 2e-3, hMax = 2e4, lMax = 500, tol = 1e-2, iterMax = 1e3, xx = np.array([0,0,0])):
        """
        Creates, and returns the traced streamline.
        
        call signature:
        
          streamInit(datadir = 'data/', fileName = 'save.dat, interpolation = 'weighted', integration = 'simple', hMin = 2e-3, hMax = 2e4, lMax = 500, tol = 1e-2, iterMax = 1e3, xx = np.array([0,0,0]))
        
        Trace magnetic streamlines.
        
        Keyword arguments:
        
         *dataDir*:
            Data directory.
            
         *fileName*:
            Name of the file with the field information.
            
         *interpolation*:
            Interpolation of the vector field.
            'mean': takes the mean of the adjacent grid point.
            'weighted': weights the adjacent grid points according to their distance.
       
         *integration*:
            Integration method.
            'simple': low order method.
            'RK6': Runge-Kutta 6th order.
       
         *hMin*:
            Minimum step length for and underflow to occur.
        
         *hMax*:
            Parameter for the initial step length.
        
         *lMax*:
            Maximum length of the streamline. Integration will stop if l >= lMax.
        
         *tol*:
            Tolerance for each integration step. Reduces the step length if error >= tol.
         
         *iterMax*:
            Maximum number of iterations.     
         
         *xx*:
            Initial seeds.
        """
        
        # read the data
        var = pc.read_var(datadir = dataDir, varfile = fileName, magic = 'bb', quiet = True, trimall = True)
        grid = pc.read_grid(datadir = dataDir, quiet = True)
        
        vv = var.bb
        
        p = pClass()
        p.dx = var.dx; p.dy = var.dy; p.dz = var.dz        
        p.Ox = var.x[0]; p.Oy = var.y[0]; p.Oz = var.z[0]
        p.Lx = grid.Lx; p.Ly = grid.Ly; p.Lz = grid.Lz
        p.nx = var.bb.shape[1]; p.ny = var.bb.shape[2]; p.nz = var.bb.shape[3]

        ss = []
        for i in range(xx.shape[1]):
            s = streamSingle(vv, p, interpolation = 'weighted', integration = 'simple', hMin = hMin, hMax = hMax, lMax = lMax, tol = tol, iterMax = iterMax, xx = xx[:,i])
            ss.append(s)
        slMax = 0
        for i in range(xx.shape[1]):
            if (slMax < ss[i].sl):
                slMax = ss[i].sl
        self.tracers = np.zeros((xx.shape[1], slMax, 3)) + np.nan
        self.sl = np.zeros(xx.shape[1], dtype = 'int32')
        self.l = np.zeros(xx.shape[1])
        for i in range(xx.shape[1]):
            self.tracers[i,:ss[i].sl,:] = ss[i].tracers
            self.sl[i] = ss[i].sl
            self.l[i] = ss[i].l
        self.p = s.p
        self.nt = xx.shape[1]
        
        # save into vtk file
        if (streamFile != []):
            writer = vtk.vtkPolyDataWriter()
            writer.SetFileName(dataDir + '/' + streamFile)
            polyData = vtk.vtkPolyData()
            fieldData = vtk.vtkFieldData()
            # field containing length of stream lines for later decomposition
            field = VN.numpy_to_vtk(self.l)
            field.SetName('l')
            fieldData.AddArray(field)
            field = VN.numpy_to_vtk(self.sl.astype(np.int32))
            field.SetName('sl')
            fieldData.AddArray(field)
            # streamline parameters
            tmp = range(10)            
            tmp[0] = np.array([hMin], dtype = 'float32'); field = VN.numpy_to_vtk(tmp[0]); field.SetName('hMin'); fieldData.AddArray(field)
            tmp[1] = np.array([hMax], dtype = 'float32'); field = VN.numpy_to_vtk(tmp[1]); field.SetName('hMax'); fieldData.AddArray(field)
            tmp[2] = np.array([lMax], dtype = 'float32'); field = VN.numpy_to_vtk(tmp[2]); field.SetName('lMax'); fieldData.AddArray(field)
            tmp[3] = np.array([tol], dtype = 'float32'); field = VN.numpy_to_vtk(tmp[3]); field.SetName('tol'); fieldData.AddArray(field)
            tmp[4] = np.array([iterMax], dtype = 'int32'); field = VN.numpy_to_vtk(tmp[4]); field.SetName('iterMax'); fieldData.AddArray(field)
            tmp[5] = np.array([self.nt], dtype = 'int32'); field = VN.numpy_to_vtk(tmp[5]); field.SetName('nt'); fieldData.AddArray(field)
            # fields containing simulation parameters stored in paramFile
            dic = dir(p)
            params = range(len(dic))
            i = 0
            for attr in dic:
                if( attr[0] != '_'):
                    params[i] = getattr(p, attr)
                    params[i] = np.array([params[i]], dtype = type(params[i]))
                    field = VN.numpy_to_vtk(params[i])
                    field.SetName(attr)
                    fieldData.AddArray(field)
                    i += 1
            # all streamlines as continuous array of points
            points = vtk.vtkPoints()
            for i in range(xx.shape[1]):
                for sl in range(self.sl[i]):
                    points.InsertNextPoint(self.tracers[i,sl,:])
            polyData.SetPoints(points)
            polyData.SetFieldData(fieldData)
            writer.SetInput(polyData)
            writer.SetFileTypeToBinary()
            writer.Write()
Esempio n. 19
0
 def __init__(self):
     self.maFieldData = vtk.vtkFieldData()
Esempio n. 20
0
        array2.SetNumberOfComponents(1)
        array2.InsertNextValue(44)
        data1.AddArray(array1)
        data1.AddArray(array2)
        sphere = vtk.vtkSphereSource()
        mapper = vtk.vtkPolyDataMapper()
        actor = vtk.vtkActor()
        mapper.SetInput(sphere.GetOutput())
        sphere.GetOutput().SetFieldData(data1)
        actor.SetMapper(mapper)
        return actor



if __name__ == '__main__':
    data1 = vtk.vtkFieldData()
    array1 = vtk.vtkIntArray()
    array1.SetNumberOfComponents(1)
    array1.InsertNextValue(1)
    array2 = vtk.vtkIntArray()
    array2.SetNumberOfComponents(1)
    array2.InsertNextValue(44)
    data1.AddArray(array1)
    data1.AddArray(array2)
    sphere = vtk.vtkSphereSource()
    mapper = vtk.vtkPolyDataMapper()
    actor = MyActor()
    mapper.SetInput(sphere.GetOutput())
    mapper.SetScalarModeToUseCellData()
    actor.SetMapper(mapper)
    actor.FieldData = data1
Esempio n. 21
0
def save_vtk_stru_point(path, vtk_dict, verbose=True):
    """
    A routine to save a structured point vtk file given by a dictionary.

    Parameters
    ----------
    path : string
        Path for the file to be saved to.
    vtk_dict : dict
        Dictionary containing information of a structured point vtk file.
        The following keywords are allowed:

        * ``"dimensions"``: (int, int, int)
        * ``"origin"``: (float, float, float)
        * ``"spacing"``: (float, float, float)
        * ``"header"``: string
        * ``"field_data"``: dict of {"name": array}
        * ``"point_data"``: dict of {"name": array}
        * ``"cell_data"``: dict of {"name": array}

    verbose : bool, optional
        Print information of the writing process. Default: True

    Notes
    -----
    All data is assumed to be scalar.
    """
    from numpy import ascontiguousarray as ascont
    from vtk import (
        vtkStructuredPoints,
        vtkStructuredPointsWriter,
        vtkFieldData,
    )
    from vtk.util.numpy_support import numpy_to_vtk as np2vtk

    out = vtkStructuredPoints()
    if verbose:
        print("Set 'dimensions', 'origin', 'spacing'")
    out.SetDimensions(vtk_dict["dimensions"])
    out.SetOrigin(vtk_dict["origin"])
    out.SetSpacing(vtk_dict["spacing"])

    if vtk_dict["field_data"]:
        if verbose:
            print("Set 'field_data'")
        data = vtkFieldData()
        for sgl_data in vtk_dict["field_data"]:
            if verbose:
                print("  Set '" + sgl_data + "'")
            arr = np2vtk(
                ascont(vtk_dict["field_data"][sgl_data].reshape(-1,
                                                                order="F")))
            arr.SetName(sgl_data)
            data.AddArray(arr)
        out.SetFieldData(data)

    if vtk_dict["point_data"]:
        if verbose:
            print("Set 'point_data'")
        data = out.GetPointData()
        for sgl_data in vtk_dict["point_data"]:
            if verbose:
                print("  Set '" + sgl_data + "'")
            arr = np2vtk(
                ascont(vtk_dict["point_data"][sgl_data].reshape(-1,
                                                                order="F")))
            arr.SetName(sgl_data)
            data.AddArray(arr)

    if vtk_dict["cell_data"]:
        if verbose:
            print("Set 'cell_data'")
        data = out.GetCellData()
        for sgl_data in vtk_dict["cell_data"]:
            if verbose:
                print("  Set '" + sgl_data + "'")
            arr = np2vtk(
                ascont(vtk_dict["cell_data"][sgl_data].reshape(-1, order="F")))
            arr.SetName(sgl_data)
            data.AddArray(arr)

    writer = vtkStructuredPointsWriter()
    writer.SetFileName(path)
    writer.SetInputData(out)
    if "header" in vtk_dict:
        writer.SetHeader(vtk_dict["header"])
    writer.Write()
Esempio n. 22
0
    def Execute(self):

        if (self.InputDirectoryName == None):
            self.PrintError('Error: no directory.')

        if (self.Pattern == None):
            self.PrintError('Error: no pattern.')

        if (self.FirstTimeStep == None):
            self.PrintError('Error: no first timestep.')

        if (self.LastTimeStep == None):
            self.PrintError('Error: no last timestep.')

        if (self.VelocityComponentsArrayNames == None):
            self.PrintError('Error: no VelocityComponentsArrayNames.')

        for root, dirs, files in os.walk(self.InputDirectoryName):
            if root == self.InputDirectoryName:
                fileList = [x for x in files if not (x.startswith('.'))]

        timeIndexList = range(self.FirstTimeStep,self.LastTimeStep+1,self.IntervalTimeStep)
        reader = vmtkmeshreader.vmtkMeshReader()
        #if self.VelocityVector or self.WsrVector:
        if self.WsrVector:
            vectorFromComponents = vmtkmeshvectorfromcomponents.vmtkMeshVectorFromComponents()

        u_name = self.VelocityComponentsArrayNames.split(' ')[0]
        v_name = self.VelocityComponentsArrayNames.split(' ')[1]
        w_name = self.VelocityComponentsArrayNames.split(' ')[2]

        if self.Wsr:
        	taux_name = self.WsrComponentsArrayNames.split(' ')[0]
        	tauy_name = self.WsrComponentsArrayNames.split(' ')[1]
        	tauz_name = self.WsrComponentsArrayNames.split(' ')[2]

        field = vtk.vtkFieldData()
        field.AllocateArrays(1)
        timesteps = vtk.vtkIntArray()
        timesteps.SetNumberOfComponents(1)
        timesteps.SetName("timesteps")
        i = 0
        for step in timeIndexList:
            if (self.Pattern%step).replace(' ','0') in fileList:
                timesteps.InsertTuple1(i, step)
                i+=1

                fileName = (self.Pattern%step).replace(' ','0')
                timeIndex = step
                reader.InputFileName = os.path.abspath(os.path.join(self.InputDirectoryName,fileName))
                reader.Execute()
                mesh = reader.Mesh

                if step == self.FirstTimeStep:
                    mesh.CopyStructure(mesh)
                    self.Mesh = mesh

                if self.Pressure:
                    p = mesh.GetPointData().GetArray(self.PressureArrayName)
                    p.SetName(self.PressureArrayName+str(step))
                    self.Mesh.GetPointData().AddArray(p)

                if self.Wsr:
                	taux = mesh.GetPointData().GetArray(taux_name)
                	taux.SetName(taux_name+str(step))
                	self.Mesh.GetPointData().AddArray(taux)

                	tauy = mesh.GetPointData().GetArray(tauy_name)
                	tauy.SetName(tauy_name+str(step))
                	self.Mesh.GetPointData().AddArray(tauy)

                	tauz = mesh.GetPointData().GetArray(tauz_name)
                	tauz.SetName(tauz_name+str(step))
                	self.Mesh.GetPointData().AddArray(tauz)


                if self.VelocityVector:

                  j = 0

                  u_component = vtk.vtkDoubleArray()
                  u_component.SetNumberOfComponents(1)

                  v_component = vtk.vtkDoubleArray()
                  v_component.SetNumberOfComponents(1)

                  w_component = vtk.vtkDoubleArray()
                  w_component.SetNumberOfComponents(1)


                  while j < mesh.GetPointData().GetArray(self.VelocityVectorArrayName).GetNumberOfTuples():

                    u_val = mesh.GetPointData().GetArray(self.VelocityVectorArrayName).GetComponent(j,0)
                    v_val = mesh.GetPointData().GetArray(self.VelocityVectorArrayName).GetComponent(j,1)
                    w_val = mesh.GetPointData().GetArray(self.VelocityVectorArrayName).GetComponent(j,2)

                    u_component.InsertTuple1(j, u_val)
                    v_component.InsertTuple1(j, v_val)
                    w_component.InsertTuple1(j, w_val)

                    j+=1

                  u_component.SetName(u_name+"_"+str(step))
                  self.Mesh.GetPointData().AddArray(u_component)

                  v_component.SetName(v_name+"_"+str(step))
                  self.Mesh.GetPointData().AddArray(v_component)

                  w_component.SetName(w_name+"_"+str(step))
                  self.Mesh.GetPointData().AddArray(w_component)

                else:

                  u = mesh.GetPointData().GetArray(u_name)
                  u.SetName(u_name+"_"+str(step))
                  self.Mesh.GetPointData().AddArray(u)

                  v = mesh.GetPointData().GetArray(v_name)
                  v.SetName(v_name+"_"+str(step))
                  self.Mesh.GetPointData().AddArray(v)

                  w = mesh.GetPointData().GetArray(w_name)
                  w.SetName(w_name+"_"+str(step))
                  self.Mesh.GetPointData().AddArray(w)

                if self.WsrVector:
                    vectorFromComponents.Mesh = self.Mesh
                    vectorFromComponents.VectorArrayName = "Wsr_"+str(step)
                    vectorFromComponents.ComponentsArrayNames = [taux.GetName(),tauy.GetName(),tauz.GetName()]
                    vectorFromComponents.RemoveComponentArrays = True
                    vectorFromComponents.Execute()

        field.AddArray(timesteps)
        self.Mesh.SetFieldData(field)
Esempio n. 23
0
polydata = vtk.vtkPolyData()
polydata.SetPoints(points)
polydata.SetPolys(polygons)

polydata.GetCellData().SetScalars(numbers)

# write an XML file
# writer = vtk.vtkXMLPolyDataWriter()
# writer.SetFileName('sample.vtp')
# writer.SetInputData(polydata)
# writer.Write()

## ------------------- ##
# create a data field
df = vtk.vtkFieldData()
temperature = vtk.vtkStringArray()
temperature.SetName("Colors")
temperature.InsertNextValue("Red")

df.AddArray(temperature)

# add data field to polydata
polydata.SetFieldData(df)
## ------------------- ##

polydata.Modified()

# Write a vtk file
writer = vtk.vtkPolyDataWriter()
writer.SetFileName('sample.vtk')
Esempio n. 24
0
    def __init__(self,
                 dataDir='data/',
                 fileName='var.dat',
                 streamFile='stream.vtk',
                 interpolation='weighted',
                 integration='RK6',
                 hMin=2e-3,
                 hMax=2e4,
                 lMax=500,
                 tol=1e-2,
                 iterMax=1e3,
                 xx=np.array([0, 0, 0])):
        """
        Creates, and returns the traced streamline.
        
        call signature:
        
          streamInit(datadir = 'data/', fileName = 'save.dat, interpolation = 'weighted', integration = 'simple', hMin = 2e-3, hMax = 2e4, lMax = 500, tol = 1e-2, iterMax = 1e3, xx = np.array([0,0,0]))
        
        Trace magnetic streamlines.
        
        Keyword arguments:
        
         *dataDir*:
            Data directory.
            
         *fileName*:
            Name of the file with the field information.
            
         *interpolation*:
            Interpolation of the vector field.
            'mean': takes the mean of the adjacent grid point.
            'weighted': weights the adjacent grid points according to their distance.
       
         *integration*:
            Integration method.
            'simple': low order method.
            'RK6': Runge-Kutta 6th order.
       
         *hMin*:
            Minimum step length for and underflow to occur.
        
         *hMax*:
            Parameter for the initial step length.
        
         *lMax*:
            Maximum length of the streamline. Integration will stop if l >= lMax.
        
         *tol*:
            Tolerance for each integration step. Reduces the step length if error >= tol.
         
         *iterMax*:
            Maximum number of iterations.     
         
         *xx*:
            Initial seeds.
        """

        # read the data
        var = pc.read_var(datadir=dataDir,
                          varfile=fileName,
                          magic='bb',
                          quiet=True,
                          trimall=True)
        grid = pc.read_grid(datadir=dataDir, quiet=True)

        vv = var.bb

        p = pClass()
        p.dx = var.dx
        p.dy = var.dy
        p.dz = var.dz
        p.Ox = var.x[0]
        p.Oy = var.y[0]
        p.Oz = var.z[0]
        p.Lx = grid.Lx
        p.Ly = grid.Ly
        p.Lz = grid.Lz
        p.nx = var.bb.shape[1]
        p.ny = var.bb.shape[2]
        p.nz = var.bb.shape[3]

        ss = []
        for i in range(xx.shape[1]):
            s = streamSingle(vv,
                             p,
                             interpolation='weighted',
                             integration='simple',
                             hMin=hMin,
                             hMax=hMax,
                             lMax=lMax,
                             tol=tol,
                             iterMax=iterMax,
                             xx=xx[:, i])
            ss.append(s)
        slMax = 0
        for i in range(xx.shape[1]):
            if (slMax < ss[i].sl):
                slMax = ss[i].sl
        self.tracers = np.zeros((xx.shape[1], slMax, 3)) + np.nan
        self.sl = np.zeros(xx.shape[1], dtype='int32')
        self.l = np.zeros(xx.shape[1])
        for i in range(xx.shape[1]):
            self.tracers[i, :ss[i].sl, :] = ss[i].tracers
            self.sl[i] = ss[i].sl
            self.l[i] = ss[i].l
        self.p = s.p
        self.nt = xx.shape[1]

        # save into vtk file
        if (streamFile != []):
            writer = vtk.vtkPolyDataWriter()
            writer.SetFileName(dataDir + '/' + streamFile)
            polyData = vtk.vtkPolyData()
            fieldData = vtk.vtkFieldData()
            # field containing length of stream lines for later decomposition
            field = VN.numpy_to_vtk(self.l)
            field.SetName('l')
            fieldData.AddArray(field)
            field = VN.numpy_to_vtk(self.sl.astype(np.int32))
            field.SetName('sl')
            fieldData.AddArray(field)
            # streamline parameters
            tmp = range(10)
            tmp[0] = np.array([hMin], dtype='float32')
            field = VN.numpy_to_vtk(tmp[0])
            field.SetName('hMin')
            fieldData.AddArray(field)
            tmp[1] = np.array([hMax], dtype='float32')
            field = VN.numpy_to_vtk(tmp[1])
            field.SetName('hMax')
            fieldData.AddArray(field)
            tmp[2] = np.array([lMax], dtype='float32')
            field = VN.numpy_to_vtk(tmp[2])
            field.SetName('lMax')
            fieldData.AddArray(field)
            tmp[3] = np.array([tol], dtype='float32')
            field = VN.numpy_to_vtk(tmp[3])
            field.SetName('tol')
            fieldData.AddArray(field)
            tmp[4] = np.array([iterMax], dtype='int32')
            field = VN.numpy_to_vtk(tmp[4])
            field.SetName('iterMax')
            fieldData.AddArray(field)
            tmp[5] = np.array([self.nt], dtype='int32')
            field = VN.numpy_to_vtk(tmp[5])
            field.SetName('nt')
            fieldData.AddArray(field)
            # fields containing simulation parameters stored in paramFile
            dic = dir(p)
            params = range(len(dic))
            i = 0
            for attr in dic:
                if (attr[0] != '_'):
                    params[i] = getattr(p, attr)
                    params[i] = np.array([params[i]], dtype=type(params[i]))
                    field = VN.numpy_to_vtk(params[i])
                    field.SetName(attr)
                    fieldData.AddArray(field)
                    i += 1
            # all streamlines as continuous array of points
            points = vtk.vtkPoints()
            for i in range(xx.shape[1]):
                for sl in range(self.sl[i]):
                    points.InsertNextPoint(self.tracers[i, sl, :])
            polyData.SetPoints(points)
            polyData.SetFieldData(fieldData)
            writer.SetInput(polyData)
            writer.SetFileTypeToBinary()
            writer.Write()